resource_usage_test.go 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  1. // +build linux
  2. /*
  3. Copyright 2015 The Kubernetes Authors.
  4. Licensed under the Apache License, Version 2.0 (the "License");
  5. you may not use this file except in compliance with the License.
  6. You may obtain a copy of the License at
  7. http://www.apache.org/licenses/LICENSE-2.0
  8. Unless required by applicable law or agreed to in writing, software
  9. distributed under the License is distributed on an "AS IS" BASIS,
  10. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11. See the License for the specific language governing permissions and
  12. limitations under the License.
  13. */
  14. package e2enode
  15. import (
  16. "fmt"
  17. "strings"
  18. "time"
  19. clientset "k8s.io/client-go/kubernetes"
  20. kubeletstatsv1alpha1 "k8s.io/kubernetes/pkg/kubelet/apis/stats/v1alpha1"
  21. "k8s.io/kubernetes/test/e2e/framework"
  22. e2ekubelet "k8s.io/kubernetes/test/e2e/framework/kubelet"
  23. e2eperf "k8s.io/kubernetes/test/e2e/framework/perf"
  24. imageutils "k8s.io/kubernetes/test/utils/image"
  25. "github.com/onsi/ginkgo"
  26. )
  27. var _ = SIGDescribe("Resource-usage [Serial] [Slow]", func() {
  28. const (
  29. // Interval to poll /stats/container on a node
  30. containerStatsPollingPeriod = 10 * time.Second
  31. )
  32. var (
  33. rc *ResourceCollector
  34. om *e2ekubelet.RuntimeOperationMonitor
  35. )
  36. f := framework.NewDefaultFramework("resource-usage")
  37. ginkgo.BeforeEach(func() {
  38. om = e2ekubelet.NewRuntimeOperationMonitor(f.ClientSet)
  39. // The test collects resource usage from a standalone Cadvisor pod.
  40. // The Cadvsior of Kubelet has a housekeeping interval of 10s, which is too long to
  41. // show the resource usage spikes. But changing its interval increases the overhead
  42. // of kubelet. Hence we use a Cadvisor pod.
  43. f.PodClient().CreateSync(getCadvisorPod())
  44. rc = NewResourceCollector(containerStatsPollingPeriod)
  45. })
  46. ginkgo.AfterEach(func() {
  47. result := om.GetLatestRuntimeOperationErrorRate()
  48. framework.Logf("runtime operation error metrics:\n%s", e2ekubelet.FormatRuntimeOperationErrorRate(result))
  49. })
  50. // This test measures and verifies the steady resource usage of node is within limit
  51. // It collects data from a standalone Cadvisor with housekeeping interval 1s.
  52. // It verifies CPU percentiles and the lastest memory usage.
  53. ginkgo.Context("regular resource usage tracking", func() {
  54. rTests := []resourceTest{
  55. {
  56. podsNr: 10,
  57. cpuLimits: e2ekubelet.ContainersCPUSummary{
  58. kubeletstatsv1alpha1.SystemContainerKubelet: {0.50: 0.30, 0.95: 0.35},
  59. kubeletstatsv1alpha1.SystemContainerRuntime: {0.50: 0.30, 0.95: 0.40},
  60. },
  61. memLimits: e2ekubelet.ResourceUsagePerContainer{
  62. kubeletstatsv1alpha1.SystemContainerKubelet: &e2ekubelet.ContainerResourceUsage{MemoryRSSInBytes: 200 * 1024 * 1024},
  63. kubeletstatsv1alpha1.SystemContainerRuntime: &e2ekubelet.ContainerResourceUsage{MemoryRSSInBytes: 400 * 1024 * 1024},
  64. },
  65. },
  66. }
  67. for _, testArg := range rTests {
  68. itArg := testArg
  69. desc := fmt.Sprintf("resource tracking for %d pods per node", itArg.podsNr)
  70. ginkgo.It(desc, func() {
  71. testInfo := getTestNodeInfo(f, itArg.getTestName(), desc)
  72. runResourceUsageTest(f, rc, itArg)
  73. // Log and verify resource usage
  74. logAndVerifyResource(f, rc, itArg.cpuLimits, itArg.memLimits, testInfo, true)
  75. })
  76. }
  77. })
  78. ginkgo.Context("regular resource usage tracking", func() {
  79. rTests := []resourceTest{
  80. {
  81. podsNr: 0,
  82. },
  83. {
  84. podsNr: 10,
  85. },
  86. {
  87. podsNr: 35,
  88. },
  89. {
  90. podsNr: 105,
  91. },
  92. }
  93. for _, testArg := range rTests {
  94. itArg := testArg
  95. desc := fmt.Sprintf("resource tracking for %d pods per node [Benchmark]", itArg.podsNr)
  96. ginkgo.It(desc, func() {
  97. testInfo := getTestNodeInfo(f, itArg.getTestName(), desc)
  98. runResourceUsageTest(f, rc, itArg)
  99. // Log and verify resource usage
  100. logAndVerifyResource(f, rc, itArg.cpuLimits, itArg.memLimits, testInfo, false)
  101. })
  102. }
  103. })
  104. })
  105. type resourceTest struct {
  106. podsNr int
  107. cpuLimits e2ekubelet.ContainersCPUSummary
  108. memLimits e2ekubelet.ResourceUsagePerContainer
  109. }
  110. func (rt *resourceTest) getTestName() string {
  111. return fmt.Sprintf("resource_%d", rt.podsNr)
  112. }
  113. // runResourceUsageTest runs the resource usage test
  114. func runResourceUsageTest(f *framework.Framework, rc *ResourceCollector, testArg resourceTest) {
  115. const (
  116. // The monitoring time for one test
  117. monitoringTime = 10 * time.Minute
  118. // The periodic reporting period
  119. reportingPeriod = 5 * time.Minute
  120. // sleep for an interval here to measure steady data
  121. sleepAfterCreatePods = 10 * time.Second
  122. )
  123. pods := newTestPods(testArg.podsNr, true, imageutils.GetPauseImageName(), "test_pod")
  124. rc.Start()
  125. // Explicitly delete pods to prevent namespace controller cleanning up timeout
  126. defer deletePodsSync(f, append(pods, getCadvisorPod()))
  127. defer rc.Stop()
  128. ginkgo.By("Creating a batch of Pods")
  129. f.PodClient().CreateBatch(pods)
  130. // wait for a while to let the node be steady
  131. time.Sleep(sleepAfterCreatePods)
  132. // Log once and flush the stats.
  133. rc.LogLatest()
  134. rc.Reset()
  135. ginkgo.By("Start monitoring resource usage")
  136. // Periodically dump the cpu summary until the deadline is met.
  137. // Note that without calling e2ekubelet.ResourceMonitor.Reset(), the stats
  138. // would occupy increasingly more memory. This should be fine
  139. // for the current test duration, but we should reclaim the
  140. // entries if we plan to monitor longer (e.g., 8 hours).
  141. deadline := time.Now().Add(monitoringTime)
  142. for time.Now().Before(deadline) {
  143. timeLeft := deadline.Sub(time.Now())
  144. framework.Logf("Still running...%v left", timeLeft)
  145. if timeLeft < reportingPeriod {
  146. time.Sleep(timeLeft)
  147. } else {
  148. time.Sleep(reportingPeriod)
  149. }
  150. logPods(f.ClientSet)
  151. }
  152. ginkgo.By("Reporting overall resource usage")
  153. logPods(f.ClientSet)
  154. }
  155. // logAndVerifyResource prints the resource usage as perf data and verifies whether resource usage satisfies the limit.
  156. func logAndVerifyResource(f *framework.Framework, rc *ResourceCollector, cpuLimits e2ekubelet.ContainersCPUSummary,
  157. memLimits e2ekubelet.ResourceUsagePerContainer, testInfo map[string]string, isVerify bool) {
  158. nodeName := framework.TestContext.NodeName
  159. // Obtain memory PerfData
  160. usagePerContainer, err := rc.GetLatest()
  161. framework.ExpectNoError(err)
  162. framework.Logf("%s", formatResourceUsageStats(usagePerContainer))
  163. usagePerNode := make(e2ekubelet.ResourceUsagePerNode)
  164. usagePerNode[nodeName] = usagePerContainer
  165. // Obtain CPU PerfData
  166. cpuSummary := rc.GetCPUSummary()
  167. framework.Logf("%s", formatCPUSummary(cpuSummary))
  168. cpuSummaryPerNode := make(e2ekubelet.NodesCPUSummary)
  169. cpuSummaryPerNode[nodeName] = cpuSummary
  170. // Print resource usage
  171. logPerfData(e2eperf.ResourceUsageToPerfDataWithLabels(usagePerNode, testInfo), "memory")
  172. logPerfData(e2eperf.CPUUsageToPerfDataWithLabels(cpuSummaryPerNode, testInfo), "cpu")
  173. // Verify resource usage
  174. if isVerify {
  175. verifyMemoryLimits(f.ClientSet, memLimits, usagePerNode)
  176. verifyCPULimits(cpuLimits, cpuSummaryPerNode)
  177. }
  178. }
  179. func verifyMemoryLimits(c clientset.Interface, expected e2ekubelet.ResourceUsagePerContainer, actual e2ekubelet.ResourceUsagePerNode) {
  180. if expected == nil {
  181. return
  182. }
  183. var errList []string
  184. for nodeName, nodeSummary := range actual {
  185. var nodeErrs []string
  186. for cName, expectedResult := range expected {
  187. container, ok := nodeSummary[cName]
  188. if !ok {
  189. nodeErrs = append(nodeErrs, fmt.Sprintf("container %q: missing", cName))
  190. continue
  191. }
  192. expectedValue := expectedResult.MemoryRSSInBytes
  193. actualValue := container.MemoryRSSInBytes
  194. if expectedValue != 0 && actualValue > expectedValue {
  195. nodeErrs = append(nodeErrs, fmt.Sprintf("container %q: expected RSS memory (MB) < %d; got %d",
  196. cName, expectedValue, actualValue))
  197. }
  198. }
  199. if len(nodeErrs) > 0 {
  200. errList = append(errList, fmt.Sprintf("node %v:\n %s", nodeName, strings.Join(nodeErrs, ", ")))
  201. heapStats, err := e2ekubelet.GetKubeletHeapStats(c, nodeName)
  202. if err != nil {
  203. framework.Logf("Unable to get heap stats from %q", nodeName)
  204. } else {
  205. framework.Logf("Heap stats on %q\n:%v", nodeName, heapStats)
  206. }
  207. }
  208. }
  209. if len(errList) > 0 {
  210. framework.Failf("Memory usage exceeding limits:\n %s", strings.Join(errList, "\n"))
  211. }
  212. }
  213. func verifyCPULimits(expected e2ekubelet.ContainersCPUSummary, actual e2ekubelet.NodesCPUSummary) {
  214. if expected == nil {
  215. return
  216. }
  217. var errList []string
  218. for nodeName, perNodeSummary := range actual {
  219. var nodeErrs []string
  220. for cName, expectedResult := range expected {
  221. perContainerSummary, ok := perNodeSummary[cName]
  222. if !ok {
  223. nodeErrs = append(nodeErrs, fmt.Sprintf("container %q: missing", cName))
  224. continue
  225. }
  226. for p, expectedValue := range expectedResult {
  227. actualValue, ok := perContainerSummary[p]
  228. if !ok {
  229. nodeErrs = append(nodeErrs, fmt.Sprintf("container %q: missing percentile %v", cName, p))
  230. continue
  231. }
  232. if actualValue > expectedValue {
  233. nodeErrs = append(nodeErrs, fmt.Sprintf("container %q: expected %.0fth%% usage < %.3f; got %.3f",
  234. cName, p*100, expectedValue, actualValue))
  235. }
  236. }
  237. }
  238. if len(nodeErrs) > 0 {
  239. errList = append(errList, fmt.Sprintf("node %v:\n %s", nodeName, strings.Join(nodeErrs, ", ")))
  240. }
  241. }
  242. if len(errList) > 0 {
  243. framework.Failf("CPU usage exceeding limits:\n %s", strings.Join(errList, "\n"))
  244. }
  245. }
  246. func logPods(c clientset.Interface) {
  247. nodeName := framework.TestContext.NodeName
  248. podList, err := e2ekubelet.GetKubeletRunningPods(c, nodeName)
  249. if err != nil {
  250. framework.Logf("Unable to retrieve kubelet pods for node %v", nodeName)
  251. }
  252. framework.Logf("%d pods are running on node %v", len(podList.Items), nodeName)
  253. }