resource_usage_test.go 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  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 e2e_node
  15. import (
  16. "fmt"
  17. "strings"
  18. "time"
  19. client "k8s.io/kubernetes/pkg/client/unversioned"
  20. "k8s.io/kubernetes/pkg/kubelet/api/v1alpha1/stats"
  21. "k8s.io/kubernetes/test/e2e/framework"
  22. . "github.com/onsi/ginkgo"
  23. . "github.com/onsi/gomega"
  24. )
  25. var _ = framework.KubeDescribe("Resource-usage [Serial] [Slow]", func() {
  26. const (
  27. // Interval to poll /stats/container on a node
  28. containerStatsPollingPeriod = 10 * time.Second
  29. )
  30. var (
  31. ns string
  32. rc *ResourceCollector
  33. om *framework.RuntimeOperationMonitor
  34. )
  35. f := framework.NewDefaultFramework("resource-usage")
  36. BeforeEach(func() {
  37. ns = f.Namespace.Name
  38. om = framework.NewRuntimeOperationMonitor(f.Client)
  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. AfterEach(func() {
  47. result := om.GetLatestRuntimeOperationErrorRate()
  48. framework.Logf("runtime operation error metrics:\n%s", framework.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. Context("regular resource usage tracking", func() {
  54. rTests := []resourceTest{
  55. {
  56. podsNr: 10,
  57. cpuLimits: framework.ContainersCPUSummary{
  58. stats.SystemContainerKubelet: {0.50: 0.30, 0.95: 0.35},
  59. stats.SystemContainerRuntime: {0.50: 0.30, 0.95: 0.40},
  60. },
  61. memLimits: framework.ResourceUsagePerContainer{
  62. stats.SystemContainerKubelet: &framework.ContainerResourceUsage{MemoryRSSInBytes: 100 * 1024 * 1024},
  63. stats.SystemContainerRuntime: &framework.ContainerResourceUsage{MemoryRSSInBytes: 400 * 1024 * 1024},
  64. },
  65. },
  66. }
  67. for _, testArg := range rTests {
  68. itArg := testArg
  69. It(fmt.Sprintf("resource tracking for %d pods per node", itArg.podsNr), func() {
  70. runResourceUsageTest(f, rc, itArg)
  71. // Log and verify resource usage
  72. logAndVerifyResource(f, rc, itArg.cpuLimits, itArg.memLimits, itArg.getTestName(), true)
  73. })
  74. }
  75. })
  76. Context("regular resource usage tracking", func() {
  77. rTests := []resourceTest{
  78. {
  79. podsNr: 10,
  80. },
  81. {
  82. podsNr: 35,
  83. },
  84. {
  85. podsNr: 105,
  86. },
  87. }
  88. for _, testArg := range rTests {
  89. itArg := testArg
  90. It(fmt.Sprintf("resource tracking for %d pods per node [Benchmark]", itArg.podsNr), func() {
  91. runResourceUsageTest(f, rc, itArg)
  92. // Log and verify resource usage
  93. logAndVerifyResource(f, rc, itArg.cpuLimits, itArg.memLimits, itArg.getTestName(), true)
  94. })
  95. }
  96. })
  97. })
  98. type resourceTest struct {
  99. podsNr int
  100. cpuLimits framework.ContainersCPUSummary
  101. memLimits framework.ResourceUsagePerContainer
  102. }
  103. func (rt *resourceTest) getTestName() string {
  104. return fmt.Sprintf("resource_%d", rt.podsNr)
  105. }
  106. // runResourceUsageTest runs the resource usage test
  107. func runResourceUsageTest(f *framework.Framework, rc *ResourceCollector, testArg resourceTest) {
  108. const (
  109. // The monitoring time for one test
  110. monitoringTime = 10 * time.Minute
  111. // The periodic reporting period
  112. reportingPeriod = 5 * time.Minute
  113. // sleep for an interval here to measure steady data
  114. sleepAfterCreatePods = 10 * time.Second
  115. )
  116. pods := newTestPods(testArg.podsNr, ImageRegistry[pauseImage], "test_pod")
  117. rc.Start()
  118. // Explicitly delete pods to prevent namespace controller cleanning up timeout
  119. defer deletePodsSync(f, append(pods, getCadvisorPod()))
  120. defer rc.Stop()
  121. By("Creating a batch of Pods")
  122. f.PodClient().CreateBatch(pods)
  123. // wait for a while to let the node be steady
  124. time.Sleep(sleepAfterCreatePods)
  125. // Log once and flush the stats.
  126. rc.LogLatest()
  127. rc.Reset()
  128. By("Start monitoring resource usage")
  129. // Periodically dump the cpu summary until the deadline is met.
  130. // Note that without calling framework.ResourceMonitor.Reset(), the stats
  131. // would occupy increasingly more memory. This should be fine
  132. // for the current test duration, but we should reclaim the
  133. // entries if we plan to monitor longer (e.g., 8 hours).
  134. deadline := time.Now().Add(monitoringTime)
  135. for time.Now().Before(deadline) {
  136. timeLeft := deadline.Sub(time.Now())
  137. framework.Logf("Still running...%v left", timeLeft)
  138. if timeLeft < reportingPeriod {
  139. time.Sleep(timeLeft)
  140. } else {
  141. time.Sleep(reportingPeriod)
  142. }
  143. logPods(f.Client)
  144. }
  145. By("Reporting overall resource usage")
  146. logPods(f.Client)
  147. }
  148. // logAndVerifyResource prints the resource usage as perf data and verifies whether resource usage satisfies the limit.
  149. func logAndVerifyResource(f *framework.Framework, rc *ResourceCollector, cpuLimits framework.ContainersCPUSummary,
  150. memLimits framework.ResourceUsagePerContainer, testName string, isVerify bool) {
  151. nodeName := framework.TestContext.NodeName
  152. // Obtain memory PerfData
  153. usagePerContainer, err := rc.GetLatest()
  154. Expect(err).NotTo(HaveOccurred())
  155. framework.Logf("%s", formatResourceUsageStats(usagePerContainer))
  156. usagePerNode := make(framework.ResourceUsagePerNode)
  157. usagePerNode[nodeName] = usagePerContainer
  158. // Obtain CPU PerfData
  159. cpuSummary := rc.GetCPUSummary()
  160. framework.Logf("%s", formatCPUSummary(cpuSummary))
  161. cpuSummaryPerNode := make(framework.NodesCPUSummary)
  162. cpuSummaryPerNode[nodeName] = cpuSummary
  163. // Print resource usage
  164. framework.PrintPerfData(framework.ResourceUsageToPerfDataWithLabels(usagePerNode,
  165. map[string]string{"test": testName, "node": nodeName}))
  166. framework.PrintPerfData(framework.CPUUsageToPerfDataWithLabels(cpuSummaryPerNode,
  167. map[string]string{"test": testName, "node": nodeName}))
  168. // Verify resource usage
  169. if isVerify {
  170. verifyMemoryLimits(f.Client, memLimits, usagePerNode)
  171. verifyCPULimits(cpuLimits, cpuSummaryPerNode)
  172. }
  173. }
  174. func verifyMemoryLimits(c *client.Client, expected framework.ResourceUsagePerContainer, actual framework.ResourceUsagePerNode) {
  175. if expected == nil {
  176. return
  177. }
  178. var errList []string
  179. for nodeName, nodeSummary := range actual {
  180. var nodeErrs []string
  181. for cName, expectedResult := range expected {
  182. container, ok := nodeSummary[cName]
  183. if !ok {
  184. nodeErrs = append(nodeErrs, fmt.Sprintf("container %q: missing", cName))
  185. continue
  186. }
  187. expectedValue := expectedResult.MemoryRSSInBytes
  188. actualValue := container.MemoryRSSInBytes
  189. if expectedValue != 0 && actualValue > expectedValue {
  190. nodeErrs = append(nodeErrs, fmt.Sprintf("container %q: expected RSS memory (MB) < %d; got %d",
  191. cName, expectedValue, actualValue))
  192. }
  193. }
  194. if len(nodeErrs) > 0 {
  195. errList = append(errList, fmt.Sprintf("node %v:\n %s", nodeName, strings.Join(nodeErrs, ", ")))
  196. heapStats, err := framework.GetKubeletHeapStats(c, nodeName)
  197. if err != nil {
  198. framework.Logf("Unable to get heap stats from %q", nodeName)
  199. } else {
  200. framework.Logf("Heap stats on %q\n:%v", nodeName, heapStats)
  201. }
  202. }
  203. }
  204. if len(errList) > 0 {
  205. framework.Failf("Memory usage exceeding limits:\n %s", strings.Join(errList, "\n"))
  206. }
  207. }
  208. func verifyCPULimits(expected framework.ContainersCPUSummary, actual framework.NodesCPUSummary) {
  209. if expected == nil {
  210. return
  211. }
  212. var errList []string
  213. for nodeName, perNodeSummary := range actual {
  214. var nodeErrs []string
  215. for cName, expectedResult := range expected {
  216. perContainerSummary, ok := perNodeSummary[cName]
  217. if !ok {
  218. nodeErrs = append(nodeErrs, fmt.Sprintf("container %q: missing", cName))
  219. continue
  220. }
  221. for p, expectedValue := range expectedResult {
  222. actualValue, ok := perContainerSummary[p]
  223. if !ok {
  224. nodeErrs = append(nodeErrs, fmt.Sprintf("container %q: missing percentile %v", cName, p))
  225. continue
  226. }
  227. if actualValue > expectedValue {
  228. nodeErrs = append(nodeErrs, fmt.Sprintf("container %q: expected %.0fth%% usage < %.3f; got %.3f",
  229. cName, p*100, expectedValue, actualValue))
  230. }
  231. }
  232. }
  233. if len(nodeErrs) > 0 {
  234. errList = append(errList, fmt.Sprintf("node %v:\n %s", nodeName, strings.Join(nodeErrs, ", ")))
  235. }
  236. }
  237. if len(errList) > 0 {
  238. framework.Failf("CPU usage exceeding limits:\n %s", strings.Join(errList, "\n"))
  239. }
  240. }
  241. func logPods(c *client.Client) {
  242. nodeName := framework.TestContext.NodeName
  243. podList, err := framework.GetKubeletRunningPods(c, nodeName)
  244. if err != nil {
  245. framework.Logf("Unable to retrieve kubelet pods for node %v", nodeName)
  246. }
  247. framework.Logf("%d pods are running on node %v", len(podList.Items), nodeName)
  248. }