node_problem_detector.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  1. /*
  2. Copyright 2019 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 node
  14. import (
  15. "context"
  16. "fmt"
  17. "net"
  18. "sort"
  19. "strconv"
  20. "strings"
  21. "time"
  22. v1 "k8s.io/api/core/v1"
  23. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  24. "k8s.io/apimachinery/pkg/fields"
  25. "k8s.io/kubernetes/test/e2e/framework"
  26. e2ekubelet "k8s.io/kubernetes/test/e2e/framework/kubelet"
  27. e2enode "k8s.io/kubernetes/test/e2e/framework/node"
  28. e2eskipper "k8s.io/kubernetes/test/e2e/framework/skipper"
  29. e2essh "k8s.io/kubernetes/test/e2e/framework/ssh"
  30. testutils "k8s.io/kubernetes/test/utils"
  31. "github.com/onsi/ginkgo"
  32. "github.com/onsi/gomega"
  33. )
  34. // This test checks if node-problem-detector (NPD) runs fine without error on
  35. // the nodes in the cluster. NPD's functionality is tested in e2e_node tests.
  36. var _ = SIGDescribe("NodeProblemDetector [DisabledForLargeClusters]", func() {
  37. const (
  38. pollInterval = 1 * time.Second
  39. pollTimeout = 1 * time.Minute
  40. )
  41. f := framework.NewDefaultFramework("node-problem-detector")
  42. ginkgo.BeforeEach(func() {
  43. e2eskipper.SkipUnlessSSHKeyPresent()
  44. e2eskipper.SkipUnlessProviderIs(framework.ProvidersWithSSH...)
  45. e2eskipper.SkipUnlessProviderIs("gce", "gke")
  46. e2eskipper.SkipUnlessNodeOSDistroIs("gci", "ubuntu")
  47. e2enode.WaitForTotalHealthy(f.ClientSet, time.Minute)
  48. })
  49. ginkgo.It("should run without error", func() {
  50. e2eskipper.SkipUnlessSSHKeyPresent()
  51. ginkgo.By("Getting all nodes and their SSH-able IP addresses")
  52. nodes, err := e2enode.GetReadySchedulableNodes(f.ClientSet)
  53. framework.ExpectNoError(err)
  54. hosts := []string{}
  55. for _, node := range nodes.Items {
  56. for _, addr := range node.Status.Addresses {
  57. if addr.Type == v1.NodeExternalIP {
  58. hosts = append(hosts, net.JoinHostPort(addr.Address, "22"))
  59. break
  60. }
  61. }
  62. }
  63. framework.ExpectEqual(len(hosts), len(nodes.Items))
  64. isStandaloneMode := make(map[string]bool)
  65. cpuUsageStats := make(map[string][]float64)
  66. uptimeStats := make(map[string][]float64)
  67. rssStats := make(map[string][]float64)
  68. workingSetStats := make(map[string][]float64)
  69. for _, host := range hosts {
  70. cpuUsageStats[host] = []float64{}
  71. uptimeStats[host] = []float64{}
  72. rssStats[host] = []float64{}
  73. workingSetStats[host] = []float64{}
  74. cmd := "systemctl status node-problem-detector.service"
  75. result, err := e2essh.SSH(cmd, host, framework.TestContext.Provider)
  76. isStandaloneMode[host] = (err == nil && result.Code == 0)
  77. ginkgo.By(fmt.Sprintf("Check node %q has node-problem-detector process", host))
  78. // Using brackets "[n]" is a trick to prevent grep command itself from
  79. // showing up, because string text "[n]ode-problem-detector" does not
  80. // match regular expression "[n]ode-problem-detector".
  81. psCmd := "ps aux | grep [n]ode-problem-detector"
  82. result, err = e2essh.SSH(psCmd, host, framework.TestContext.Provider)
  83. framework.ExpectNoError(err)
  84. framework.ExpectEqual(result.Code, 0)
  85. gomega.Expect(result.Stdout).To(gomega.ContainSubstring("node-problem-detector"))
  86. ginkgo.By(fmt.Sprintf("Check node-problem-detector is running fine on node %q", host))
  87. journalctlCmd := "sudo journalctl -u node-problem-detector"
  88. result, err = e2essh.SSH(journalctlCmd, host, framework.TestContext.Provider)
  89. framework.ExpectNoError(err)
  90. framework.ExpectEqual(result.Code, 0)
  91. gomega.Expect(result.Stdout).NotTo(gomega.ContainSubstring("node-problem-detector.service: Failed"))
  92. if isStandaloneMode[host] {
  93. cpuUsage, uptime := getCPUStat(f, host)
  94. cpuUsageStats[host] = append(cpuUsageStats[host], cpuUsage)
  95. uptimeStats[host] = append(uptimeStats[host], uptime)
  96. }
  97. ginkgo.By(fmt.Sprintf("Inject log to trigger AUFSUmountHung on node %q", host))
  98. log := "INFO: task umount.aufs:21568 blocked for more than 120 seconds."
  99. injectLogCmd := "sudo sh -c \"echo 'kernel: " + log + "' >> /dev/kmsg\""
  100. _, err = e2essh.SSH(injectLogCmd, host, framework.TestContext.Provider)
  101. framework.ExpectNoError(err)
  102. framework.ExpectEqual(result.Code, 0)
  103. }
  104. ginkgo.By("Check node-problem-detector can post conditions and events to API server")
  105. for _, node := range nodes.Items {
  106. ginkgo.By(fmt.Sprintf("Check node-problem-detector posted KernelDeadlock condition on node %q", node.Name))
  107. gomega.Eventually(func() error {
  108. return verifyNodeCondition(f, "KernelDeadlock", v1.ConditionTrue, "AUFSUmountHung", node.Name)
  109. }, pollTimeout, pollInterval).Should(gomega.Succeed())
  110. ginkgo.By(fmt.Sprintf("Check node-problem-detector posted AUFSUmountHung event on node %q", node.Name))
  111. eventListOptions := metav1.ListOptions{FieldSelector: fields.Set{"involvedObject.kind": "Node"}.AsSelector().String()}
  112. gomega.Eventually(func() error {
  113. return verifyEvents(f, eventListOptions, 1, "AUFSUmountHung", node.Name)
  114. }, pollTimeout, pollInterval).Should(gomega.Succeed())
  115. // Node problem detector reports kubelet start events automatically starting from NPD v0.7.0+.
  116. // Since Kubelet may be restarted for a few times after node is booted. We just check the event
  117. // is detected, but do not check how many times Kubelet is started.
  118. ginkgo.By(fmt.Sprintf("Check node-problem-detector posted KubeletStart event on node %q", node.Name))
  119. gomega.Eventually(func() error {
  120. return verifyEventExists(f, eventListOptions, "KubeletStart", node.Name)
  121. }, pollTimeout, pollInterval).Should(gomega.Succeed())
  122. }
  123. ginkgo.By("Gather node-problem-detector cpu and memory stats")
  124. numIterations := 60
  125. for i := 1; i <= numIterations; i++ {
  126. for j, host := range hosts {
  127. if isStandaloneMode[host] {
  128. rss, workingSet := getMemoryStat(f, host)
  129. rssStats[host] = append(rssStats[host], rss)
  130. workingSetStats[host] = append(workingSetStats[host], workingSet)
  131. if i == numIterations {
  132. cpuUsage, uptime := getCPUStat(f, host)
  133. cpuUsageStats[host] = append(cpuUsageStats[host], cpuUsage)
  134. uptimeStats[host] = append(uptimeStats[host], uptime)
  135. }
  136. } else {
  137. cpuUsage, rss, workingSet := getNpdPodStat(f, nodes.Items[j].Name)
  138. cpuUsageStats[host] = append(cpuUsageStats[host], cpuUsage)
  139. rssStats[host] = append(rssStats[host], rss)
  140. workingSetStats[host] = append(workingSetStats[host], workingSet)
  141. }
  142. }
  143. time.Sleep(time.Second)
  144. }
  145. cpuStatsMsg := "CPU (core):"
  146. rssStatsMsg := "RSS (MB):"
  147. workingSetStatsMsg := "WorkingSet (MB):"
  148. for i, host := range hosts {
  149. if isStandaloneMode[host] {
  150. // When in standalone mode, NPD is running as systemd service. We
  151. // calculate its cpu usage from cgroup cpuacct value differences.
  152. cpuUsage := cpuUsageStats[host][1] - cpuUsageStats[host][0]
  153. totaltime := uptimeStats[host][1] - uptimeStats[host][0]
  154. cpuStatsMsg += fmt.Sprintf(" %s[%.3f];", nodes.Items[i].Name, cpuUsage/totaltime)
  155. } else {
  156. sort.Float64s(cpuUsageStats[host])
  157. cpuStatsMsg += fmt.Sprintf(" %s[%.3f|%.3f|%.3f];", nodes.Items[i].Name,
  158. cpuUsageStats[host][0], cpuUsageStats[host][len(cpuUsageStats[host])/2], cpuUsageStats[host][len(cpuUsageStats[host])-1])
  159. }
  160. sort.Float64s(rssStats[host])
  161. rssStatsMsg += fmt.Sprintf(" %s[%.1f|%.1f|%.1f];", nodes.Items[i].Name,
  162. rssStats[host][0], rssStats[host][len(rssStats[host])/2], rssStats[host][len(rssStats[host])-1])
  163. sort.Float64s(workingSetStats[host])
  164. workingSetStatsMsg += fmt.Sprintf(" %s[%.1f|%.1f|%.1f];", nodes.Items[i].Name,
  165. workingSetStats[host][0], workingSetStats[host][len(workingSetStats[host])/2], workingSetStats[host][len(workingSetStats[host])-1])
  166. }
  167. framework.Logf("Node-Problem-Detector CPU and Memory Stats:\n\t%s\n\t%s\n\t%s", cpuStatsMsg, rssStatsMsg, workingSetStatsMsg)
  168. })
  169. })
  170. func verifyEvents(f *framework.Framework, options metav1.ListOptions, num int, reason, nodeName string) error {
  171. events, err := f.ClientSet.CoreV1().Events(metav1.NamespaceDefault).List(context.TODO(), options)
  172. if err != nil {
  173. return err
  174. }
  175. count := 0
  176. for _, event := range events.Items {
  177. if event.Reason != reason || event.Source.Host != nodeName {
  178. continue
  179. }
  180. count += int(event.Count)
  181. }
  182. if count != num {
  183. return fmt.Errorf("expect event number %d, got %d: %v", num, count, events.Items)
  184. }
  185. return nil
  186. }
  187. func verifyEventExists(f *framework.Framework, options metav1.ListOptions, reason, nodeName string) error {
  188. events, err := f.ClientSet.CoreV1().Events(metav1.NamespaceDefault).List(context.TODO(), options)
  189. if err != nil {
  190. return err
  191. }
  192. for _, event := range events.Items {
  193. if event.Reason == reason && event.Source.Host == nodeName && event.Count > 0 {
  194. return nil
  195. }
  196. }
  197. return fmt.Errorf("Event %s does not exist: %v", reason, events.Items)
  198. }
  199. func verifyNodeCondition(f *framework.Framework, condition v1.NodeConditionType, status v1.ConditionStatus, reason, nodeName string) error {
  200. node, err := f.ClientSet.CoreV1().Nodes().Get(context.TODO(), nodeName, metav1.GetOptions{})
  201. if err != nil {
  202. return err
  203. }
  204. _, c := testutils.GetNodeCondition(&node.Status, condition)
  205. if c == nil {
  206. return fmt.Errorf("node condition %q not found", condition)
  207. }
  208. if c.Status != status || c.Reason != reason {
  209. return fmt.Errorf("unexpected node condition %q: %+v", condition, c)
  210. }
  211. return nil
  212. }
  213. func getMemoryStat(f *framework.Framework, host string) (rss, workingSet float64) {
  214. memCmd := "cat /sys/fs/cgroup/memory/system.slice/node-problem-detector.service/memory.usage_in_bytes && cat /sys/fs/cgroup/memory/system.slice/node-problem-detector.service/memory.stat"
  215. result, err := e2essh.SSH(memCmd, host, framework.TestContext.Provider)
  216. framework.ExpectNoError(err)
  217. framework.ExpectEqual(result.Code, 0)
  218. lines := strings.Split(result.Stdout, "\n")
  219. memoryUsage, err := strconv.ParseFloat(lines[0], 64)
  220. framework.ExpectNoError(err)
  221. var totalInactiveFile float64
  222. for _, line := range lines[1:] {
  223. tokens := strings.Split(line, " ")
  224. if tokens[0] == "total_rss" {
  225. rss, err = strconv.ParseFloat(tokens[1], 64)
  226. framework.ExpectNoError(err)
  227. }
  228. if tokens[0] == "total_inactive_file" {
  229. totalInactiveFile, err = strconv.ParseFloat(tokens[1], 64)
  230. framework.ExpectNoError(err)
  231. }
  232. }
  233. workingSet = memoryUsage
  234. if workingSet < totalInactiveFile {
  235. workingSet = 0
  236. } else {
  237. workingSet -= totalInactiveFile
  238. }
  239. // Convert to MB
  240. rss = rss / 1024 / 1024
  241. workingSet = workingSet / 1024 / 1024
  242. return
  243. }
  244. func getCPUStat(f *framework.Framework, host string) (usage, uptime float64) {
  245. cpuCmd := "cat /sys/fs/cgroup/cpu/system.slice/node-problem-detector.service/cpuacct.usage && cat /proc/uptime | awk '{print $1}'"
  246. result, err := e2essh.SSH(cpuCmd, host, framework.TestContext.Provider)
  247. framework.ExpectNoError(err)
  248. framework.ExpectEqual(result.Code, 0)
  249. lines := strings.Split(result.Stdout, "\n")
  250. usage, err = strconv.ParseFloat(lines[0], 64)
  251. framework.ExpectNoError(err, "Cannot parse float for usage")
  252. uptime, err = strconv.ParseFloat(lines[1], 64)
  253. framework.ExpectNoError(err, "Cannot parse float for uptime")
  254. // Convert from nanoseconds to seconds
  255. usage *= 1e-9
  256. return
  257. }
  258. func getNpdPodStat(f *framework.Framework, nodeName string) (cpuUsage, rss, workingSet float64) {
  259. summary, err := e2ekubelet.GetStatsSummary(f.ClientSet, nodeName)
  260. framework.ExpectNoError(err)
  261. hasNpdPod := false
  262. for _, pod := range summary.Pods {
  263. if !strings.HasPrefix(pod.PodRef.Name, "npd") {
  264. continue
  265. }
  266. cpuUsage = float64(*pod.CPU.UsageNanoCores) * 1e-9
  267. rss = float64(*pod.Memory.RSSBytes) / 1024 / 1024
  268. workingSet = float64(*pod.Memory.WorkingSetBytes) / 1024 / 1024
  269. hasNpdPod = true
  270. break
  271. }
  272. framework.ExpectEqual(hasNpdPod, true)
  273. return
  274. }