reboot.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  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. 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)
  98. })
  99. ginkgo.It("each node by dropping all inbound packets for a while and ensure they function afterwards", func() {
  100. // tell the firewall to drop all inbound packets for a while
  101. // We sleep 10 seconds to give some time for ssh command to cleanly finish before starting dropping inbound packets.
  102. // We still accept packages send from localhost to prevent monit from restarting kubelet.
  103. tmpLogPath := "/tmp/drop-inbound.log"
  104. testReboot(f.ClientSet, dropPacketsScript("INPUT", tmpLogPath), catLogHook(tmpLogPath))
  105. })
  106. ginkgo.It("each node by dropping all outbound packets for a while and ensure they function afterwards", func() {
  107. // tell the firewall to drop all outbound packets for a while
  108. // We sleep 10 seconds to give some time for ssh command to cleanly finish before starting dropping outbound packets.
  109. // We still accept packages send to localhost to prevent monit from restarting kubelet.
  110. tmpLogPath := "/tmp/drop-outbound.log"
  111. testReboot(f.ClientSet, dropPacketsScript("OUTPUT", tmpLogPath), catLogHook(tmpLogPath))
  112. })
  113. })
  114. func testReboot(c clientset.Interface, rebootCmd string, hook terminationHook) {
  115. // Get all nodes, and kick off the test on each.
  116. nodelist, err := e2enode.GetReadySchedulableNodes(c)
  117. framework.ExpectNoError(err, "failed to list nodes")
  118. if hook != nil {
  119. defer func() {
  120. framework.Logf("Executing termination hook on nodes")
  121. hook(framework.TestContext.Provider, nodelist)
  122. }()
  123. }
  124. result := make([]bool, len(nodelist.Items))
  125. wg := sync.WaitGroup{}
  126. wg.Add(len(nodelist.Items))
  127. failed := false
  128. for ix := range nodelist.Items {
  129. go func(ix int) {
  130. defer wg.Done()
  131. n := nodelist.Items[ix]
  132. result[ix] = rebootNode(c, framework.TestContext.Provider, n.ObjectMeta.Name, rebootCmd)
  133. if !result[ix] {
  134. failed = true
  135. }
  136. }(ix)
  137. }
  138. // Wait for all to finish and check the final result.
  139. wg.Wait()
  140. if failed {
  141. for ix := range nodelist.Items {
  142. n := nodelist.Items[ix]
  143. if !result[ix] {
  144. framework.Logf("Node %s failed reboot test.", n.ObjectMeta.Name)
  145. }
  146. }
  147. framework.Failf("Test failed; at least one node failed to reboot in the time given.")
  148. }
  149. }
  150. func printStatusAndLogsForNotReadyPods(c clientset.Interface, ns string, podNames []string, pods []*v1.Pod) {
  151. printFn := func(id, log string, err error, previous bool) {
  152. prefix := "Retrieving log for container"
  153. if previous {
  154. prefix = "Retrieving log for the last terminated container"
  155. }
  156. if err != nil {
  157. framework.Logf("%s %s, err: %v:\n%s\n", prefix, id, err, log)
  158. } else {
  159. framework.Logf("%s %s:\n%s\n", prefix, id, log)
  160. }
  161. }
  162. podNameSet := sets.NewString(podNames...)
  163. for _, p := range pods {
  164. if p.Namespace != ns {
  165. continue
  166. }
  167. if !podNameSet.Has(p.Name) {
  168. continue
  169. }
  170. if ok, _ := testutils.PodRunningReady(p); ok {
  171. continue
  172. }
  173. framework.Logf("Status for not ready pod %s/%s: %+v", p.Namespace, p.Name, p.Status)
  174. // Print the log of the containers if pod is not running and ready.
  175. for _, container := range p.Status.ContainerStatuses {
  176. cIdentifer := fmt.Sprintf("%s/%s/%s", p.Namespace, p.Name, container.Name)
  177. log, err := e2epod.GetPodLogs(c, p.Namespace, p.Name, container.Name)
  178. printFn(cIdentifer, log, err, false)
  179. // Get log from the previous container.
  180. if container.RestartCount > 0 {
  181. printFn(cIdentifer, log, err, true)
  182. }
  183. }
  184. }
  185. }
  186. // rebootNode takes node name on provider through the following steps using c:
  187. // - ensures the node is ready
  188. // - ensures all pods on the node are running and ready
  189. // - reboots the node (by executing rebootCmd over ssh)
  190. // - ensures the node reaches some non-ready state
  191. // - ensures the node becomes ready again
  192. // - ensures all pods on the node become running and ready again
  193. //
  194. // It returns true through result only if all of the steps pass; at the first
  195. // failed step, it will return false through result and not run the rest.
  196. func rebootNode(c clientset.Interface, provider, name, rebootCmd string) bool {
  197. // Setup
  198. ns := metav1.NamespaceSystem
  199. ps, err := testutils.NewPodStore(c, ns, labels.Everything(), fields.OneTermEqualSelector(api.PodHostField, name))
  200. if err != nil {
  201. framework.Logf("Couldn't initialize pod store: %v", err)
  202. return false
  203. }
  204. defer ps.Stop()
  205. // Get the node initially.
  206. framework.Logf("Getting %s", name)
  207. node, err := c.CoreV1().Nodes().Get(context.TODO(), name, metav1.GetOptions{})
  208. if err != nil {
  209. framework.Logf("Couldn't get node %s", name)
  210. return false
  211. }
  212. // Node sanity check: ensure it is "ready".
  213. if !e2enode.WaitForNodeToBeReady(c, name, framework.NodeReadyInitialTimeout) {
  214. return false
  215. }
  216. // Get all the pods on the node that don't have liveness probe set.
  217. // Liveness probe may cause restart of a pod during node reboot, and the pod may not be running.
  218. pods := ps.List()
  219. podNames := []string{}
  220. for _, p := range pods {
  221. probe := false
  222. for _, c := range p.Spec.Containers {
  223. if c.LivenessProbe != nil {
  224. probe = true
  225. break
  226. }
  227. }
  228. if !probe {
  229. podNames = append(podNames, p.ObjectMeta.Name)
  230. }
  231. }
  232. framework.Logf("Node %s has %d assigned pods with no liveness probes: %v", name, len(podNames), podNames)
  233. // For each pod, we do a sanity check to ensure it's running / healthy
  234. // or succeeded now, as that's what we'll be checking later.
  235. if !e2epod.CheckPodsRunningReadyOrSucceeded(c, ns, podNames, framework.PodReadyBeforeTimeout) {
  236. printStatusAndLogsForNotReadyPods(c, ns, podNames, pods)
  237. return false
  238. }
  239. // Reboot the node.
  240. if err = e2essh.IssueSSHCommand(rebootCmd, provider, node); err != nil {
  241. framework.Logf("Error while issuing ssh command: %v", err)
  242. return false
  243. }
  244. // Wait for some kind of "not ready" status.
  245. if !e2enode.WaitForNodeToBeNotReady(c, name, rebootNodeNotReadyTimeout) {
  246. return false
  247. }
  248. // Wait for some kind of "ready" status.
  249. if !e2enode.WaitForNodeToBeReady(c, name, rebootNodeReadyAgainTimeout) {
  250. return false
  251. }
  252. // Ensure all of the pods that we found on this node before the reboot are
  253. // running / healthy, or succeeded.
  254. if !e2epod.CheckPodsRunningReadyOrSucceeded(c, ns, podNames, rebootPodReadyAgainTimeout) {
  255. newPods := ps.List()
  256. printStatusAndLogsForNotReadyPods(c, ns, podNames, newPods)
  257. return false
  258. }
  259. framework.Logf("Reboot successful on node %s", name)
  260. return true
  261. }
  262. type terminationHook func(provider string, nodes *v1.NodeList)
  263. func catLogHook(logPath string) terminationHook {
  264. return func(provider string, nodes *v1.NodeList) {
  265. for _, n := range nodes.Items {
  266. cmd := fmt.Sprintf("cat %v && rm %v", logPath, logPath)
  267. if _, err := e2essh.IssueSSHCommandWithResult(cmd, provider, &n); err != nil {
  268. framework.Logf("Error while issuing ssh command: %v", err)
  269. }
  270. }
  271. }
  272. }
  273. func dropPacketsScript(chainName, logPath string) string {
  274. return strings.Replace(fmt.Sprintf(`
  275. nohup sh -c '
  276. set -x
  277. sleep 10
  278. while true; do sudo iptables -I ${CHAIN} 1 -s 127.0.0.1 -j ACCEPT && break; done
  279. while true; do sudo iptables -I ${CHAIN} 2 -j DROP && break; done
  280. date
  281. sleep 120
  282. while true; do sudo iptables -D ${CHAIN} -j DROP && break; done
  283. while true; do sudo iptables -D ${CHAIN} -s 127.0.0.1 -j ACCEPT && break; done
  284. ' >%v 2>&1 &
  285. `, logPath), "${CHAIN}", chainName, -1)
  286. }