reboot.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  1. /*
  2. Copyright 2015 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package lifecycle
  14. import (
  15. "fmt"
  16. "strings"
  17. "sync"
  18. "time"
  19. v1 "k8s.io/api/core/v1"
  20. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  21. "k8s.io/apimachinery/pkg/fields"
  22. "k8s.io/apimachinery/pkg/labels"
  23. "k8s.io/apimachinery/pkg/util/sets"
  24. clientset "k8s.io/client-go/kubernetes"
  25. api "k8s.io/kubernetes/pkg/apis/core"
  26. "k8s.io/kubernetes/test/e2e/framework"
  27. e2elog "k8s.io/kubernetes/test/e2e/framework/log"
  28. e2essh "k8s.io/kubernetes/test/e2e/framework/ssh"
  29. testutils "k8s.io/kubernetes/test/utils"
  30. "github.com/onsi/ginkgo"
  31. )
  32. const (
  33. // How long a node is allowed to go from "Ready" to "NotReady" after a
  34. // reboot is issued before the test is considered failed.
  35. rebootNodeNotReadyTimeout = 2 * time.Minute
  36. // How long a node is allowed to go from "NotReady" to "Ready" after a
  37. // reboot is issued and it is found to be "NotReady" before the test is
  38. // considered failed.
  39. rebootNodeReadyAgainTimeout = 5 * time.Minute
  40. // How long pods have to be "ready" after the reboot.
  41. rebootPodReadyAgainTimeout = 5 * time.Minute
  42. )
  43. var _ = SIGDescribe("Reboot [Disruptive] [Feature:Reboot]", func() {
  44. var f *framework.Framework
  45. ginkgo.BeforeEach(func() {
  46. // These tests requires SSH to nodes, so the provider check should be identical to there
  47. // (the limiting factor is the implementation of util.go's e2essh.GetSigner(...)).
  48. // Cluster must support node reboot
  49. framework.SkipUnlessProviderIs(framework.ProvidersWithSSH...)
  50. })
  51. ginkgo.AfterEach(func() {
  52. if ginkgo.CurrentGinkgoTestDescription().Failed {
  53. // Most of the reboot tests just make sure that addon/system pods are running, so dump
  54. // events for the kube-system namespace on failures
  55. namespaceName := metav1.NamespaceSystem
  56. ginkgo.By(fmt.Sprintf("Collecting events from namespace %q.", namespaceName))
  57. events, err := f.ClientSet.CoreV1().Events(namespaceName).List(metav1.ListOptions{})
  58. framework.ExpectNoError(err)
  59. for _, e := range events.Items {
  60. e2elog.Logf("event for %v: %v %v: %v", e.InvolvedObject.Name, e.Source, e.Reason, e.Message)
  61. }
  62. }
  63. // In GKE, our current tunneling setup has the potential to hold on to a broken tunnel (from a
  64. // rebooted/deleted node) for up to 5 minutes before all tunnels are dropped and recreated. Most tests
  65. // make use of some proxy feature to verify functionality. So, if a reboot test runs right before a test
  66. // that tries to get logs, for example, we may get unlucky and try to use a closed tunnel to a node that
  67. // was recently rebooted. There's no good way to framework.Poll for proxies being closed, so we sleep.
  68. //
  69. // TODO(cjcullen) reduce this sleep (#19314)
  70. if framework.ProviderIs("gke") {
  71. ginkgo.By("waiting 5 minutes for all dead tunnels to be dropped")
  72. time.Sleep(5 * time.Minute)
  73. }
  74. })
  75. f = framework.NewDefaultFramework("reboot")
  76. ginkgo.It("each node by ordering clean reboot and ensure they function upon restart", func() {
  77. // clean shutdown and restart
  78. // We sleep 10 seconds to give some time for ssh command to cleanly finish before the node is rebooted.
  79. testReboot(f.ClientSet, "nohup sh -c 'sleep 10 && sudo reboot' >/dev/null 2>&1 &", nil)
  80. })
  81. ginkgo.It("each node by ordering unclean reboot and ensure they function upon restart", func() {
  82. // unclean shutdown and restart
  83. // We sleep 10 seconds to give some time for ssh command to cleanly finish before the node is shutdown.
  84. testReboot(f.ClientSet, "nohup sh -c 'echo 1 | sudo tee /proc/sys/kernel/sysrq && sleep 10 && echo b | sudo tee /proc/sysrq-trigger' >/dev/null 2>&1 &", nil)
  85. })
  86. ginkgo.It("each node by triggering kernel panic and ensure they function upon restart", func() {
  87. // kernel panic
  88. // We sleep 10 seconds to give some time for ssh command to cleanly finish before kernel panic is triggered.
  89. testReboot(f.ClientSet, "nohup sh -c 'echo 1 | sudo tee /proc/sys/kernel/sysrq && sleep 10 && echo c | sudo tee /proc/sysrq-trigger' >/dev/null 2>&1 &", nil)
  90. })
  91. ginkgo.It("each node by switching off the network interface and ensure they function upon switch on", func() {
  92. // switch the network interface off for a while to simulate a network outage
  93. // We sleep 10 seconds to give some time for ssh command to cleanly finish before network is down.
  94. testReboot(f.ClientSet, "nohup sh -c 'sleep 10 && sudo ip link set eth0 down && sleep 120 && sudo ip link set eth0 up && (sudo dhclient || true)' >/dev/null 2>&1 &", nil)
  95. })
  96. ginkgo.It("each node by dropping all inbound packets for a while and ensure they function afterwards", func() {
  97. // tell the firewall to drop all inbound packets for a while
  98. // We sleep 10 seconds to give some time for ssh command to cleanly finish before starting dropping inbound packets.
  99. // We still accept packages send from localhost to prevent monit from restarting kubelet.
  100. tmpLogPath := "/tmp/drop-inbound.log"
  101. testReboot(f.ClientSet, dropPacketsScript("INPUT", tmpLogPath), catLogHook(tmpLogPath))
  102. })
  103. ginkgo.It("each node by dropping all outbound packets for a while and ensure they function afterwards", func() {
  104. // tell the firewall to drop all outbound packets for a while
  105. // We sleep 10 seconds to give some time for ssh command to cleanly finish before starting dropping outbound packets.
  106. // We still accept packages send to localhost to prevent monit from restarting kubelet.
  107. tmpLogPath := "/tmp/drop-outbound.log"
  108. testReboot(f.ClientSet, dropPacketsScript("OUTPUT", tmpLogPath), catLogHook(tmpLogPath))
  109. })
  110. })
  111. func testReboot(c clientset.Interface, rebootCmd string, hook terminationHook) {
  112. // Get all nodes, and kick off the test on each.
  113. nodelist := framework.GetReadySchedulableNodesOrDie(c)
  114. if hook != nil {
  115. defer func() {
  116. e2elog.Logf("Executing termination hook on nodes")
  117. hook(framework.TestContext.Provider, nodelist)
  118. }()
  119. }
  120. result := make([]bool, len(nodelist.Items))
  121. wg := sync.WaitGroup{}
  122. wg.Add(len(nodelist.Items))
  123. failed := false
  124. for ix := range nodelist.Items {
  125. go func(ix int) {
  126. defer wg.Done()
  127. n := nodelist.Items[ix]
  128. result[ix] = rebootNode(c, framework.TestContext.Provider, n.ObjectMeta.Name, rebootCmd)
  129. if !result[ix] {
  130. failed = true
  131. }
  132. }(ix)
  133. }
  134. // Wait for all to finish and check the final result.
  135. wg.Wait()
  136. if failed {
  137. for ix := range nodelist.Items {
  138. n := nodelist.Items[ix]
  139. if !result[ix] {
  140. e2elog.Logf("Node %s failed reboot test.", n.ObjectMeta.Name)
  141. }
  142. }
  143. framework.Failf("Test failed; at least one node failed to reboot in the time given.")
  144. }
  145. }
  146. func printStatusAndLogsForNotReadyPods(c clientset.Interface, ns string, podNames []string, pods []*v1.Pod) {
  147. printFn := func(id, log string, err error, previous bool) {
  148. prefix := "Retrieving log for container"
  149. if previous {
  150. prefix = "Retrieving log for the last terminated container"
  151. }
  152. if err != nil {
  153. e2elog.Logf("%s %s, err: %v:\n%s\n", prefix, id, err, log)
  154. } else {
  155. e2elog.Logf("%s %s:\n%s\n", prefix, id, log)
  156. }
  157. }
  158. podNameSet := sets.NewString(podNames...)
  159. for _, p := range pods {
  160. if p.Namespace != ns {
  161. continue
  162. }
  163. if !podNameSet.Has(p.Name) {
  164. continue
  165. }
  166. if ok, _ := testutils.PodRunningReady(p); ok {
  167. continue
  168. }
  169. e2elog.Logf("Status for not ready pod %s/%s: %+v", p.Namespace, p.Name, p.Status)
  170. // Print the log of the containers if pod is not running and ready.
  171. for _, container := range p.Status.ContainerStatuses {
  172. cIdentifer := fmt.Sprintf("%s/%s/%s", p.Namespace, p.Name, container.Name)
  173. log, err := framework.GetPodLogs(c, p.Namespace, p.Name, container.Name)
  174. printFn(cIdentifer, log, err, false)
  175. // Get log from the previous container.
  176. if container.RestartCount > 0 {
  177. printFn(cIdentifer, log, err, true)
  178. }
  179. }
  180. }
  181. }
  182. // rebootNode takes node name on provider through the following steps using c:
  183. // - ensures the node is ready
  184. // - ensures all pods on the node are running and ready
  185. // - reboots the node (by executing rebootCmd over ssh)
  186. // - ensures the node reaches some non-ready state
  187. // - ensures the node becomes ready again
  188. // - ensures all pods on the node become running and ready again
  189. //
  190. // It returns true through result only if all of the steps pass; at the first
  191. // failed step, it will return false through result and not run the rest.
  192. func rebootNode(c clientset.Interface, provider, name, rebootCmd string) bool {
  193. // Setup
  194. ns := metav1.NamespaceSystem
  195. ps, err := testutils.NewPodStore(c, ns, labels.Everything(), fields.OneTermEqualSelector(api.PodHostField, name))
  196. if err != nil {
  197. e2elog.Logf("Couldn't initialize pod store: %v", err)
  198. return false
  199. }
  200. defer ps.Stop()
  201. // Get the node initially.
  202. e2elog.Logf("Getting %s", name)
  203. node, err := c.CoreV1().Nodes().Get(name, metav1.GetOptions{})
  204. if err != nil {
  205. e2elog.Logf("Couldn't get node %s", name)
  206. return false
  207. }
  208. // Node sanity check: ensure it is "ready".
  209. if !framework.WaitForNodeToBeReady(c, name, framework.NodeReadyInitialTimeout) {
  210. return false
  211. }
  212. // Get all the pods on the node that don't have liveness probe set.
  213. // Liveness probe may cause restart of a pod during node reboot, and the pod may not be running.
  214. pods := ps.List()
  215. podNames := []string{}
  216. for _, p := range pods {
  217. probe := false
  218. for _, c := range p.Spec.Containers {
  219. if c.LivenessProbe != nil {
  220. probe = true
  221. break
  222. }
  223. }
  224. if !probe {
  225. podNames = append(podNames, p.ObjectMeta.Name)
  226. }
  227. }
  228. e2elog.Logf("Node %s has %d assigned pods with no liveness probes: %v", name, len(podNames), podNames)
  229. // For each pod, we do a sanity check to ensure it's running / healthy
  230. // or succeeded now, as that's what we'll be checking later.
  231. if !framework.CheckPodsRunningReadyOrSucceeded(c, ns, podNames, framework.PodReadyBeforeTimeout) {
  232. printStatusAndLogsForNotReadyPods(c, ns, podNames, pods)
  233. return false
  234. }
  235. // Reboot the node.
  236. if err = e2essh.IssueSSHCommand(rebootCmd, provider, node); err != nil {
  237. e2elog.Logf("Error while issuing ssh command: %v", err)
  238. return false
  239. }
  240. // Wait for some kind of "not ready" status.
  241. if !framework.WaitForNodeToBeNotReady(c, name, rebootNodeNotReadyTimeout) {
  242. return false
  243. }
  244. // Wait for some kind of "ready" status.
  245. if !framework.WaitForNodeToBeReady(c, name, rebootNodeReadyAgainTimeout) {
  246. return false
  247. }
  248. // Ensure all of the pods that we found on this node before the reboot are
  249. // running / healthy, or succeeded.
  250. if !framework.CheckPodsRunningReadyOrSucceeded(c, ns, podNames, rebootPodReadyAgainTimeout) {
  251. newPods := ps.List()
  252. printStatusAndLogsForNotReadyPods(c, ns, podNames, newPods)
  253. return false
  254. }
  255. e2elog.Logf("Reboot successful on node %s", name)
  256. return true
  257. }
  258. type terminationHook func(provider string, nodes *v1.NodeList)
  259. func catLogHook(logPath string) terminationHook {
  260. return func(provider string, nodes *v1.NodeList) {
  261. for _, n := range nodes.Items {
  262. cmd := fmt.Sprintf("cat %v && rm %v", logPath, logPath)
  263. if _, err := e2essh.IssueSSHCommandWithResult(cmd, provider, &n); err != nil {
  264. e2elog.Logf("Error while issuing ssh command: %v", err)
  265. }
  266. }
  267. }
  268. }
  269. func dropPacketsScript(chainName, logPath string) string {
  270. return strings.Replace(fmt.Sprintf(`
  271. nohup sh -c '
  272. set -x
  273. sleep 10
  274. while true; do sudo iptables -I ${CHAIN} 1 -s 127.0.0.1 -j ACCEPT && break; done
  275. while true; do sudo iptables -I ${CHAIN} 2 -j DROP && break; done
  276. date
  277. sleep 120
  278. while true; do sudo iptables -D ${CHAIN} -j DROP && break; done
  279. while true; do sudo iptables -D ${CHAIN} -s 127.0.0.1 -j ACCEPT && break; done
  280. ' >%v 2>&1 &
  281. `, logPath), "${CHAIN}", chainName, -1)
  282. }