reboot.go 13 KB

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