node_problem_detector.go 11 KB

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