eviction_test.go 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939
  1. /*
  2. Copyright 2016 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 e2enode
  14. import (
  15. "context"
  16. "fmt"
  17. "path/filepath"
  18. "strconv"
  19. "strings"
  20. "time"
  21. v1 "k8s.io/api/core/v1"
  22. schedulingv1 "k8s.io/api/scheduling/v1"
  23. apierrors "k8s.io/apimachinery/pkg/api/errors"
  24. "k8s.io/apimachinery/pkg/api/resource"
  25. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  26. "k8s.io/apimachinery/pkg/fields"
  27. kubeletconfig "k8s.io/kubernetes/pkg/kubelet/apis/config"
  28. kubeletstatsv1alpha1 "k8s.io/kubernetes/pkg/kubelet/apis/stats/v1alpha1"
  29. "k8s.io/kubernetes/pkg/kubelet/eviction"
  30. evictionapi "k8s.io/kubernetes/pkg/kubelet/eviction/api"
  31. kubeletmetrics "k8s.io/kubernetes/pkg/kubelet/metrics"
  32. kubetypes "k8s.io/kubernetes/pkg/kubelet/types"
  33. "k8s.io/kubernetes/test/e2e/framework"
  34. e2eskipper "k8s.io/kubernetes/test/e2e/framework/skipper"
  35. testutils "k8s.io/kubernetes/test/utils"
  36. imageutils "k8s.io/kubernetes/test/utils/image"
  37. "github.com/onsi/ginkgo"
  38. "github.com/onsi/gomega"
  39. )
  40. // Eviction Policy is described here:
  41. // https://github.com/kubernetes/community/blob/master/contributors/design-proposals/node/kubelet-eviction.md
  42. const (
  43. postTestConditionMonitoringPeriod = 1 * time.Minute
  44. evictionPollInterval = 2 * time.Second
  45. pressureDissapearTimeout = 1 * time.Minute
  46. // pressure conditions often surface after evictions because the kubelet only updates
  47. // node conditions periodically.
  48. // we wait this period after evictions to make sure that we wait out this delay
  49. pressureDelay = 20 * time.Second
  50. testContextFmt = "when we run containers that should cause %s"
  51. noPressure = v1.NodeConditionType("NoPressure")
  52. lotsOfDisk = 10240 // 10 Gb in Mb
  53. lotsOfFiles = 1000000000 // 1 billion
  54. resourceInodes = v1.ResourceName("inodes")
  55. noStarvedResource = v1.ResourceName("none")
  56. )
  57. // InodeEviction tests that the node responds to node disk pressure by evicting only responsible pods.
  58. // Node disk pressure is induced by consuming all inodes on the node.
  59. var _ = framework.KubeDescribe("InodeEviction [Slow] [Serial] [Disruptive][NodeFeature:Eviction]", func() {
  60. f := framework.NewDefaultFramework("inode-eviction-test")
  61. expectedNodeCondition := v1.NodeDiskPressure
  62. expectedStarvedResource := resourceInodes
  63. pressureTimeout := 15 * time.Minute
  64. inodesConsumed := uint64(200000)
  65. ginkgo.Context(fmt.Sprintf(testContextFmt, expectedNodeCondition), func() {
  66. tempSetCurrentKubeletConfig(f, func(initialConfig *kubeletconfig.KubeletConfiguration) {
  67. // Set the eviction threshold to inodesFree - inodesConsumed, so that using inodesConsumed causes an eviction.
  68. summary := eventuallyGetSummary()
  69. inodesFree := *summary.Node.Fs.InodesFree
  70. if inodesFree <= inodesConsumed {
  71. e2eskipper.Skipf("Too few inodes free on the host for the InodeEviction test to run")
  72. }
  73. initialConfig.EvictionHard = map[string]string{string(evictionapi.SignalNodeFsInodesFree): fmt.Sprintf("%d", inodesFree-inodesConsumed)}
  74. initialConfig.EvictionMinimumReclaim = map[string]string{}
  75. })
  76. runEvictionTest(f, pressureTimeout, expectedNodeCondition, expectedStarvedResource, logInodeMetrics, []podEvictSpec{
  77. {
  78. evictionPriority: 1,
  79. pod: inodeConsumingPod("container-inode-hog", lotsOfFiles, nil),
  80. },
  81. {
  82. evictionPriority: 1,
  83. pod: inodeConsumingPod("volume-inode-hog", lotsOfFiles, &v1.VolumeSource{EmptyDir: &v1.EmptyDirVolumeSource{}}),
  84. },
  85. {
  86. evictionPriority: 0,
  87. pod: innocentPod(),
  88. },
  89. })
  90. })
  91. })
  92. // ImageGCNoEviction tests that the node does not evict pods when inodes are consumed by images
  93. // Disk pressure is induced by pulling large images
  94. var _ = framework.KubeDescribe("ImageGCNoEviction [Slow] [Serial] [Disruptive][NodeFeature:Eviction]", func() {
  95. f := framework.NewDefaultFramework("image-gc-eviction-test")
  96. pressureTimeout := 10 * time.Minute
  97. expectedNodeCondition := v1.NodeDiskPressure
  98. expectedStarvedResource := resourceInodes
  99. inodesConsumed := uint64(100000)
  100. ginkgo.Context(fmt.Sprintf(testContextFmt, expectedNodeCondition), func() {
  101. tempSetCurrentKubeletConfig(f, func(initialConfig *kubeletconfig.KubeletConfiguration) {
  102. // Set the eviction threshold to inodesFree - inodesConsumed, so that using inodesConsumed causes an eviction.
  103. summary := eventuallyGetSummary()
  104. inodesFree := *summary.Node.Fs.InodesFree
  105. if inodesFree <= inodesConsumed {
  106. e2eskipper.Skipf("Too few inodes free on the host for the InodeEviction test to run")
  107. }
  108. initialConfig.EvictionHard = map[string]string{string(evictionapi.SignalNodeFsInodesFree): fmt.Sprintf("%d", inodesFree-inodesConsumed)}
  109. initialConfig.EvictionMinimumReclaim = map[string]string{}
  110. })
  111. // Consume enough inodes to induce disk pressure,
  112. // but expect that image garbage collection can reduce it enough to avoid an eviction
  113. runEvictionTest(f, pressureTimeout, expectedNodeCondition, expectedStarvedResource, logDiskMetrics, []podEvictSpec{
  114. {
  115. evictionPriority: 0,
  116. pod: inodeConsumingPod("container-inode", 110000, nil),
  117. },
  118. })
  119. })
  120. })
  121. // MemoryAllocatableEviction tests that the node responds to node memory pressure by evicting only responsible pods.
  122. // Node memory pressure is only encountered because we reserve the majority of the node's capacity via kube-reserved.
  123. var _ = framework.KubeDescribe("MemoryAllocatableEviction [Slow] [Serial] [Disruptive][NodeFeature:Eviction]", func() {
  124. f := framework.NewDefaultFramework("memory-allocatable-eviction-test")
  125. expectedNodeCondition := v1.NodeMemoryPressure
  126. expectedStarvedResource := v1.ResourceMemory
  127. pressureTimeout := 10 * time.Minute
  128. ginkgo.Context(fmt.Sprintf(testContextFmt, expectedNodeCondition), func() {
  129. tempSetCurrentKubeletConfig(f, func(initialConfig *kubeletconfig.KubeletConfiguration) {
  130. // Set large system and kube reserved values to trigger allocatable thresholds far before hard eviction thresholds.
  131. kubeReserved := getNodeCPUAndMemoryCapacity(f)[v1.ResourceMemory]
  132. // The default hard eviction threshold is 250Mb, so Allocatable = Capacity - Reserved - 250Mb
  133. // We want Allocatable = 50Mb, so set Reserved = Capacity - Allocatable - 250Mb = Capacity - 300Mb
  134. kubeReserved.Sub(resource.MustParse("300Mi"))
  135. initialConfig.KubeReserved = map[string]string{
  136. string(v1.ResourceMemory): kubeReserved.String(),
  137. }
  138. initialConfig.EnforceNodeAllocatable = []string{kubetypes.NodeAllocatableEnforcementKey}
  139. initialConfig.CgroupsPerQOS = true
  140. })
  141. runEvictionTest(f, pressureTimeout, expectedNodeCondition, expectedStarvedResource, logMemoryMetrics, []podEvictSpec{
  142. {
  143. evictionPriority: 1,
  144. pod: getMemhogPod("memory-hog-pod", "memory-hog", v1.ResourceRequirements{}),
  145. },
  146. {
  147. evictionPriority: 0,
  148. pod: innocentPod(),
  149. },
  150. })
  151. })
  152. })
  153. // LocalStorageEviction tests that the node responds to node disk pressure by evicting only responsible pods
  154. // Disk pressure is induced by running pods which consume disk space.
  155. var _ = framework.KubeDescribe("LocalStorageEviction [Slow] [Serial] [Disruptive][NodeFeature:Eviction]", func() {
  156. f := framework.NewDefaultFramework("localstorage-eviction-test")
  157. pressureTimeout := 10 * time.Minute
  158. expectedNodeCondition := v1.NodeDiskPressure
  159. expectedStarvedResource := v1.ResourceEphemeralStorage
  160. ginkgo.Context(fmt.Sprintf(testContextFmt, expectedNodeCondition), func() {
  161. tempSetCurrentKubeletConfig(f, func(initialConfig *kubeletconfig.KubeletConfiguration) {
  162. diskConsumed := resource.MustParse("200Mi")
  163. summary := eventuallyGetSummary()
  164. availableBytes := *(summary.Node.Fs.AvailableBytes)
  165. initialConfig.EvictionHard = map[string]string{string(evictionapi.SignalNodeFsAvailable): fmt.Sprintf("%d", availableBytes-uint64(diskConsumed.Value()))}
  166. initialConfig.EvictionMinimumReclaim = map[string]string{}
  167. })
  168. runEvictionTest(f, pressureTimeout, expectedNodeCondition, expectedStarvedResource, logDiskMetrics, []podEvictSpec{
  169. {
  170. evictionPriority: 1,
  171. pod: diskConsumingPod("container-disk-hog", lotsOfDisk, nil, v1.ResourceRequirements{}),
  172. },
  173. {
  174. evictionPriority: 0,
  175. pod: innocentPod(),
  176. },
  177. })
  178. })
  179. })
  180. // LocalStorageEviction tests that the node responds to node disk pressure by evicting only responsible pods
  181. // Disk pressure is induced by running pods which consume disk space, which exceed the soft eviction threshold.
  182. // Note: This test's purpose is to test Soft Evictions. Local storage was chosen since it is the least costly to run.
  183. var _ = framework.KubeDescribe("LocalStorageSoftEviction [Slow] [Serial] [Disruptive][NodeFeature:Eviction]", func() {
  184. f := framework.NewDefaultFramework("localstorage-eviction-test")
  185. pressureTimeout := 10 * time.Minute
  186. expectedNodeCondition := v1.NodeDiskPressure
  187. expectedStarvedResource := v1.ResourceEphemeralStorage
  188. ginkgo.Context(fmt.Sprintf(testContextFmt, expectedNodeCondition), func() {
  189. tempSetCurrentKubeletConfig(f, func(initialConfig *kubeletconfig.KubeletConfiguration) {
  190. diskConsumed := resource.MustParse("200Mi")
  191. summary := eventuallyGetSummary()
  192. availableBytes := *(summary.Node.Fs.AvailableBytes)
  193. if availableBytes <= uint64(diskConsumed.Value()) {
  194. e2eskipper.Skipf("Too little disk free on the host for the LocalStorageSoftEviction test to run")
  195. }
  196. initialConfig.EvictionSoft = map[string]string{string(evictionapi.SignalNodeFsAvailable): fmt.Sprintf("%d", availableBytes-uint64(diskConsumed.Value()))}
  197. initialConfig.EvictionSoftGracePeriod = map[string]string{string(evictionapi.SignalNodeFsAvailable): "1m"}
  198. // Defer to the pod default grace period
  199. initialConfig.EvictionMaxPodGracePeriod = 30
  200. initialConfig.EvictionMinimumReclaim = map[string]string{}
  201. // Ensure that pods are not evicted because of the eviction-hard threshold
  202. // setting a threshold to 0% disables; non-empty map overrides default value (necessary due to omitempty)
  203. initialConfig.EvictionHard = map[string]string{string(evictionapi.SignalMemoryAvailable): "0%"}
  204. })
  205. runEvictionTest(f, pressureTimeout, expectedNodeCondition, expectedStarvedResource, logDiskMetrics, []podEvictSpec{
  206. {
  207. evictionPriority: 1,
  208. pod: diskConsumingPod("container-disk-hog", lotsOfDisk, nil, v1.ResourceRequirements{}),
  209. },
  210. {
  211. evictionPriority: 0,
  212. pod: innocentPod(),
  213. },
  214. })
  215. })
  216. })
  217. // LocalStorageCapacityIsolationEviction tests that container and volume local storage limits are enforced through evictions
  218. var _ = framework.KubeDescribe("LocalStorageCapacityIsolationEviction [Slow] [Serial] [Disruptive] [Feature:LocalStorageCapacityIsolation][NodeFeature:Eviction]", func() {
  219. f := framework.NewDefaultFramework("localstorage-eviction-test")
  220. evictionTestTimeout := 10 * time.Minute
  221. ginkgo.Context(fmt.Sprintf(testContextFmt, "evictions due to pod local storage violations"), func() {
  222. tempSetCurrentKubeletConfig(f, func(initialConfig *kubeletconfig.KubeletConfiguration) {
  223. // setting a threshold to 0% disables; non-empty map overrides default value (necessary due to omitempty)
  224. initialConfig.EvictionHard = map[string]string{string(evictionapi.SignalMemoryAvailable): "0%"}
  225. })
  226. sizeLimit := resource.MustParse("100Mi")
  227. useOverLimit := 101 /* Mb */
  228. useUnderLimit := 99 /* Mb */
  229. containerLimit := v1.ResourceList{v1.ResourceEphemeralStorage: sizeLimit}
  230. runEvictionTest(f, evictionTestTimeout, noPressure, noStarvedResource, logDiskMetrics, []podEvictSpec{
  231. {
  232. evictionPriority: 1, // This pod should be evicted because emptyDir (default storage type) usage violation
  233. pod: diskConsumingPod("emptydir-disk-sizelimit", useOverLimit, &v1.VolumeSource{
  234. EmptyDir: &v1.EmptyDirVolumeSource{SizeLimit: &sizeLimit},
  235. }, v1.ResourceRequirements{}),
  236. },
  237. {
  238. evictionPriority: 1, // This pod should be evicted because of memory emptyDir usage violation
  239. pod: diskConsumingPod("emptydir-memory-sizelimit", useOverLimit, &v1.VolumeSource{
  240. EmptyDir: &v1.EmptyDirVolumeSource{Medium: "Memory", SizeLimit: &sizeLimit},
  241. }, v1.ResourceRequirements{}),
  242. },
  243. {
  244. evictionPriority: 1, // This pod should cross the container limit by writing to its writable layer.
  245. pod: diskConsumingPod("container-disk-limit", useOverLimit, nil, v1.ResourceRequirements{Limits: containerLimit}),
  246. },
  247. {
  248. evictionPriority: 1, // This pod should hit the container limit by writing to an emptydir
  249. pod: diskConsumingPod("container-emptydir-disk-limit", useOverLimit, &v1.VolumeSource{EmptyDir: &v1.EmptyDirVolumeSource{}},
  250. v1.ResourceRequirements{Limits: containerLimit}),
  251. },
  252. {
  253. evictionPriority: 0, // This pod should not be evicted because it uses less than its limit
  254. pod: diskConsumingPod("emptydir-disk-below-sizelimit", useUnderLimit, &v1.VolumeSource{
  255. EmptyDir: &v1.EmptyDirVolumeSource{SizeLimit: &sizeLimit},
  256. }, v1.ResourceRequirements{}),
  257. },
  258. {
  259. evictionPriority: 0, // This pod should not be evicted because it uses less than its limit
  260. pod: diskConsumingPod("container-disk-below-sizelimit", useUnderLimit, nil, v1.ResourceRequirements{Limits: containerLimit}),
  261. },
  262. })
  263. })
  264. })
  265. // PriorityMemoryEvictionOrdering tests that the node responds to node memory pressure by evicting pods.
  266. // This test tests that the guaranteed pod is never evicted, and that the lower-priority pod is evicted before
  267. // the higher priority pod.
  268. var _ = framework.KubeDescribe("PriorityMemoryEvictionOrdering [Slow] [Serial] [Disruptive][NodeFeature:Eviction]", func() {
  269. f := framework.NewDefaultFramework("priority-memory-eviction-ordering-test")
  270. expectedNodeCondition := v1.NodeMemoryPressure
  271. expectedStarvedResource := v1.ResourceMemory
  272. pressureTimeout := 10 * time.Minute
  273. highPriorityClassName := f.BaseName + "-high-priority"
  274. highPriority := int32(999999999)
  275. ginkgo.Context(fmt.Sprintf(testContextFmt, expectedNodeCondition), func() {
  276. tempSetCurrentKubeletConfig(f, func(initialConfig *kubeletconfig.KubeletConfiguration) {
  277. memoryConsumed := resource.MustParse("600Mi")
  278. summary := eventuallyGetSummary()
  279. availableBytes := *(summary.Node.Memory.AvailableBytes)
  280. if availableBytes <= uint64(memoryConsumed.Value()) {
  281. e2eskipper.Skipf("Too little memory free on the host for the PriorityMemoryEvictionOrdering test to run")
  282. }
  283. initialConfig.EvictionHard = map[string]string{string(evictionapi.SignalMemoryAvailable): fmt.Sprintf("%d", availableBytes-uint64(memoryConsumed.Value()))}
  284. initialConfig.EvictionMinimumReclaim = map[string]string{}
  285. })
  286. ginkgo.BeforeEach(func() {
  287. _, err := f.ClientSet.SchedulingV1().PriorityClasses().Create(context.TODO(), &schedulingv1.PriorityClass{ObjectMeta: metav1.ObjectMeta{Name: highPriorityClassName}, Value: highPriority}, metav1.CreateOptions{})
  288. framework.ExpectEqual(err == nil || apierrors.IsAlreadyExists(err), true)
  289. })
  290. ginkgo.AfterEach(func() {
  291. err := f.ClientSet.SchedulingV1().PriorityClasses().Delete(context.TODO(), highPriorityClassName, &metav1.DeleteOptions{})
  292. framework.ExpectNoError(err)
  293. })
  294. specs := []podEvictSpec{
  295. {
  296. evictionPriority: 2,
  297. pod: getMemhogPod("memory-hog-pod", "memory-hog", v1.ResourceRequirements{}),
  298. },
  299. {
  300. evictionPriority: 1,
  301. pod: getMemhogPod("high-priority-memory-hog-pod", "high-priority-memory-hog", v1.ResourceRequirements{}),
  302. },
  303. {
  304. evictionPriority: 0,
  305. pod: getMemhogPod("guaranteed-pod", "guaranteed-pod", v1.ResourceRequirements{
  306. Requests: v1.ResourceList{
  307. v1.ResourceMemory: resource.MustParse("300Mi"),
  308. },
  309. Limits: v1.ResourceList{
  310. v1.ResourceMemory: resource.MustParse("300Mi"),
  311. },
  312. }),
  313. },
  314. }
  315. specs[1].pod.Spec.PriorityClassName = highPriorityClassName
  316. runEvictionTest(f, pressureTimeout, expectedNodeCondition, expectedStarvedResource, logMemoryMetrics, specs)
  317. })
  318. })
  319. // PriorityLocalStorageEvictionOrdering tests that the node responds to node disk pressure by evicting pods.
  320. // This test tests that the guaranteed pod is never evicted, and that the lower-priority pod is evicted before
  321. // the higher priority pod.
  322. var _ = framework.KubeDescribe("PriorityLocalStorageEvictionOrdering [Slow] [Serial] [Disruptive][NodeFeature:Eviction]", func() {
  323. f := framework.NewDefaultFramework("priority-disk-eviction-ordering-test")
  324. expectedNodeCondition := v1.NodeDiskPressure
  325. expectedStarvedResource := v1.ResourceEphemeralStorage
  326. pressureTimeout := 10 * time.Minute
  327. highPriorityClassName := f.BaseName + "-high-priority"
  328. highPriority := int32(999999999)
  329. ginkgo.Context(fmt.Sprintf(testContextFmt, expectedNodeCondition), func() {
  330. tempSetCurrentKubeletConfig(f, func(initialConfig *kubeletconfig.KubeletConfiguration) {
  331. diskConsumed := resource.MustParse("350Mi")
  332. summary := eventuallyGetSummary()
  333. availableBytes := *(summary.Node.Fs.AvailableBytes)
  334. if availableBytes <= uint64(diskConsumed.Value()) {
  335. e2eskipper.Skipf("Too little disk free on the host for the PriorityLocalStorageEvictionOrdering test to run")
  336. }
  337. initialConfig.EvictionHard = map[string]string{string(evictionapi.SignalNodeFsAvailable): fmt.Sprintf("%d", availableBytes-uint64(diskConsumed.Value()))}
  338. initialConfig.EvictionMinimumReclaim = map[string]string{}
  339. })
  340. ginkgo.BeforeEach(func() {
  341. _, err := f.ClientSet.SchedulingV1().PriorityClasses().Create(context.TODO(), &schedulingv1.PriorityClass{ObjectMeta: metav1.ObjectMeta{Name: highPriorityClassName}, Value: highPriority}, metav1.CreateOptions{})
  342. framework.ExpectEqual(err == nil || apierrors.IsAlreadyExists(err), true)
  343. })
  344. ginkgo.AfterEach(func() {
  345. err := f.ClientSet.SchedulingV1().PriorityClasses().Delete(context.TODO(), highPriorityClassName, &metav1.DeleteOptions{})
  346. framework.ExpectNoError(err)
  347. })
  348. specs := []podEvictSpec{
  349. {
  350. evictionPriority: 2,
  351. pod: diskConsumingPod("best-effort-disk", lotsOfDisk, nil, v1.ResourceRequirements{}),
  352. },
  353. {
  354. evictionPriority: 1,
  355. pod: diskConsumingPod("high-priority-disk", lotsOfDisk, nil, v1.ResourceRequirements{}),
  356. },
  357. {
  358. evictionPriority: 0,
  359. // Only require 99% accuracy (297/300 Mb) because on some OS distributions, the file itself (excluding contents), consumes disk space.
  360. pod: diskConsumingPod("guaranteed-disk", 297 /* Mb */, nil, v1.ResourceRequirements{
  361. Requests: v1.ResourceList{
  362. v1.ResourceEphemeralStorage: resource.MustParse("300Mi"),
  363. },
  364. Limits: v1.ResourceList{
  365. v1.ResourceEphemeralStorage: resource.MustParse("300Mi"),
  366. },
  367. }),
  368. },
  369. }
  370. specs[1].pod.Spec.PriorityClassName = highPriorityClassName
  371. runEvictionTest(f, pressureTimeout, expectedNodeCondition, expectedStarvedResource, logDiskMetrics, specs)
  372. })
  373. })
  374. // PriorityPidEvictionOrdering tests that the node emits pid pressure in response to a fork bomb, and evicts pods by priority
  375. var _ = framework.KubeDescribe("PriorityPidEvictionOrdering [Slow] [Serial] [Disruptive][NodeFeature:Eviction]", func() {
  376. f := framework.NewDefaultFramework("pidpressure-eviction-test")
  377. pressureTimeout := 2 * time.Minute
  378. expectedNodeCondition := v1.NodePIDPressure
  379. expectedStarvedResource := noStarvedResource
  380. highPriorityClassName := f.BaseName + "-high-priority"
  381. highPriority := int32(999999999)
  382. ginkgo.Context(fmt.Sprintf(testContextFmt, expectedNodeCondition), func() {
  383. tempSetCurrentKubeletConfig(f, func(initialConfig *kubeletconfig.KubeletConfiguration) {
  384. pidsConsumed := int64(10000)
  385. summary := eventuallyGetSummary()
  386. availablePids := *(summary.Node.Rlimit.MaxPID) - *(summary.Node.Rlimit.NumOfRunningProcesses)
  387. initialConfig.EvictionHard = map[string]string{string(evictionapi.SignalPIDAvailable): fmt.Sprintf("%d", availablePids-pidsConsumed)}
  388. initialConfig.EvictionMinimumReclaim = map[string]string{}
  389. })
  390. ginkgo.BeforeEach(func() {
  391. _, err := f.ClientSet.SchedulingV1().PriorityClasses().Create(context.TODO(), &schedulingv1.PriorityClass{ObjectMeta: metav1.ObjectMeta{Name: highPriorityClassName}, Value: highPriority}, metav1.CreateOptions{})
  392. framework.ExpectEqual(err == nil || apierrors.IsAlreadyExists(err), true)
  393. })
  394. ginkgo.AfterEach(func() {
  395. err := f.ClientSet.SchedulingV1().PriorityClasses().Delete(context.TODO(), highPriorityClassName, &metav1.DeleteOptions{})
  396. framework.ExpectNoError(err)
  397. })
  398. specs := []podEvictSpec{
  399. {
  400. evictionPriority: 1,
  401. pod: pidConsumingPod("fork-bomb-container", 12000),
  402. },
  403. {
  404. evictionPriority: 0,
  405. pod: innocentPod(),
  406. },
  407. }
  408. specs[1].pod.Spec.PriorityClassName = highPriorityClassName
  409. runEvictionTest(f, pressureTimeout, expectedNodeCondition, expectedStarvedResource, logPidMetrics, specs)
  410. })
  411. })
  412. // Struct used by runEvictionTest that specifies the pod, and when that pod should be evicted, relative to other pods
  413. type podEvictSpec struct {
  414. // P0 should never be evicted, P1 shouldn't evict before P2, etc.
  415. // If two are ranked at P1, either is permitted to fail before the other.
  416. // The test ends when all pods other than p0 have been evicted
  417. evictionPriority int
  418. pod *v1.Pod
  419. }
  420. // runEvictionTest sets up a testing environment given the provided pods, and checks a few things:
  421. // It ensures that the desired expectedNodeCondition is actually triggered.
  422. // It ensures that evictionPriority 0 pods are not evicted
  423. // It ensures that lower evictionPriority pods are always evicted before higher evictionPriority pods (2 evicted before 1, etc.)
  424. // It ensures that all pods with non-zero evictionPriority are eventually evicted.
  425. // runEvictionTest then cleans up the testing environment by deleting provided pods, and ensures that expectedNodeCondition no longer exists
  426. func runEvictionTest(f *framework.Framework, pressureTimeout time.Duration, expectedNodeCondition v1.NodeConditionType, expectedStarvedResource v1.ResourceName, logFunc func(), testSpecs []podEvictSpec) {
  427. // Place the remainder of the test within a context so that the kubelet config is set before and after the test.
  428. ginkgo.Context("", func() {
  429. ginkgo.BeforeEach(func() {
  430. // reduce memory usage in the allocatable cgroup to ensure we do not have MemoryPressure
  431. reduceAllocatableMemoryUsage()
  432. // Nodes do not immediately report local storage capacity
  433. // Sleep so that pods requesting local storage do not fail to schedule
  434. time.Sleep(30 * time.Second)
  435. ginkgo.By("seting up pods to be used by tests")
  436. pods := []*v1.Pod{}
  437. for _, spec := range testSpecs {
  438. pods = append(pods, spec.pod)
  439. }
  440. f.PodClient().CreateBatch(pods)
  441. })
  442. ginkgo.It("should eventually evict all of the correct pods", func() {
  443. ginkgo.By(fmt.Sprintf("Waiting for node to have NodeCondition: %s", expectedNodeCondition))
  444. gomega.Eventually(func() error {
  445. logFunc()
  446. if expectedNodeCondition == noPressure || hasNodeCondition(f, expectedNodeCondition) {
  447. return nil
  448. }
  449. return fmt.Errorf("NodeCondition: %s not encountered", expectedNodeCondition)
  450. }, pressureTimeout, evictionPollInterval).Should(gomega.BeNil())
  451. ginkgo.By("Waiting for evictions to occur")
  452. gomega.Eventually(func() error {
  453. if expectedNodeCondition != noPressure {
  454. if hasNodeCondition(f, expectedNodeCondition) {
  455. framework.Logf("Node has %s", expectedNodeCondition)
  456. } else {
  457. framework.Logf("Node does NOT have %s", expectedNodeCondition)
  458. }
  459. }
  460. logKubeletLatencyMetrics(kubeletmetrics.EvictionStatsAgeKey)
  461. logFunc()
  462. return verifyEvictionOrdering(f, testSpecs)
  463. }, pressureTimeout, evictionPollInterval).Should(gomega.BeNil())
  464. // We observe pressure from the API server. The eviction manager observes pressure from the kubelet internal stats.
  465. // This means the eviction manager will observe pressure before we will, creating a delay between when the eviction manager
  466. // evicts a pod, and when we observe the pressure by querying the API server. Add a delay here to account for this delay
  467. ginkgo.By("making sure pressure from test has surfaced before continuing")
  468. time.Sleep(pressureDelay)
  469. ginkgo.By(fmt.Sprintf("Waiting for NodeCondition: %s to no longer exist on the node", expectedNodeCondition))
  470. gomega.Eventually(func() error {
  471. logFunc()
  472. logKubeletLatencyMetrics(kubeletmetrics.EvictionStatsAgeKey)
  473. if expectedNodeCondition != noPressure && hasNodeCondition(f, expectedNodeCondition) {
  474. return fmt.Errorf("Conditions havent returned to normal, node still has %s", expectedNodeCondition)
  475. }
  476. return nil
  477. }, pressureDissapearTimeout, evictionPollInterval).Should(gomega.BeNil())
  478. ginkgo.By("checking for stable, pressure-free condition without unexpected pod failures")
  479. gomega.Consistently(func() error {
  480. if expectedNodeCondition != noPressure && hasNodeCondition(f, expectedNodeCondition) {
  481. return fmt.Errorf("%s dissappeared and then reappeared", expectedNodeCondition)
  482. }
  483. logFunc()
  484. logKubeletLatencyMetrics(kubeletmetrics.EvictionStatsAgeKey)
  485. return verifyEvictionOrdering(f, testSpecs)
  486. }, postTestConditionMonitoringPeriod, evictionPollInterval).Should(gomega.BeNil())
  487. ginkgo.By("checking for correctly formatted eviction events")
  488. verifyEvictionEvents(f, testSpecs, expectedStarvedResource)
  489. })
  490. ginkgo.AfterEach(func() {
  491. prePullImagesIfNeccecary := func() {
  492. if expectedNodeCondition == v1.NodeDiskPressure && framework.TestContext.PrepullImages {
  493. // The disk eviction test may cause the prepulled images to be evicted,
  494. // prepull those images again to ensure this test not affect following tests.
  495. PrePullAllImages()
  496. }
  497. }
  498. // Run prePull using a defer to make sure it is executed even when the assertions below fails
  499. defer prePullImagesIfNeccecary()
  500. ginkgo.By("deleting pods")
  501. for _, spec := range testSpecs {
  502. ginkgo.By(fmt.Sprintf("deleting pod: %s", spec.pod.Name))
  503. f.PodClient().DeleteSync(spec.pod.Name, &metav1.DeleteOptions{}, 10*time.Minute)
  504. }
  505. // In case a test fails before verifying that NodeCondition no longer exist on the node,
  506. // we should wait for the NodeCondition to disappear
  507. ginkgo.By(fmt.Sprintf("making sure NodeCondition %s no longer exist on the node", expectedNodeCondition))
  508. gomega.Eventually(func() error {
  509. if expectedNodeCondition != noPressure && hasNodeCondition(f, expectedNodeCondition) {
  510. return fmt.Errorf("Conditions havent returned to normal, node still has %s", expectedNodeCondition)
  511. }
  512. return nil
  513. }, pressureDissapearTimeout, evictionPollInterval).Should(gomega.BeNil())
  514. reduceAllocatableMemoryUsage()
  515. ginkgo.By("making sure we have all the required images for testing")
  516. prePullImagesIfNeccecary()
  517. ginkgo.By("making sure we can start a new pod after the test")
  518. podName := "test-admit-pod"
  519. f.PodClient().CreateSync(&v1.Pod{
  520. ObjectMeta: metav1.ObjectMeta{
  521. Name: podName,
  522. },
  523. Spec: v1.PodSpec{
  524. RestartPolicy: v1.RestartPolicyNever,
  525. Containers: []v1.Container{
  526. {
  527. Image: imageutils.GetPauseImageName(),
  528. Name: podName,
  529. },
  530. },
  531. },
  532. })
  533. if ginkgo.CurrentGinkgoTestDescription().Failed {
  534. if framework.TestContext.DumpLogsOnFailure {
  535. logPodEvents(f)
  536. logNodeEvents(f)
  537. }
  538. }
  539. })
  540. })
  541. }
  542. // verifyEvictionOrdering returns an error if all non-zero priority pods have not been evicted, nil otherwise
  543. // This function panics (via Expect) if eviction ordering is violated, or if a priority-zero pod fails.
  544. func verifyEvictionOrdering(f *framework.Framework, testSpecs []podEvictSpec) error {
  545. // Gather current information
  546. updatedPodList, err := f.ClientSet.CoreV1().Pods(f.Namespace.Name).List(context.TODO(), metav1.ListOptions{})
  547. if err != nil {
  548. return err
  549. }
  550. updatedPods := updatedPodList.Items
  551. for _, p := range updatedPods {
  552. framework.Logf("fetching pod %s; phase= %v", p.Name, p.Status.Phase)
  553. }
  554. ginkgo.By("checking eviction ordering and ensuring important pods dont fail")
  555. done := true
  556. for _, priorityPodSpec := range testSpecs {
  557. var priorityPod v1.Pod
  558. for _, p := range updatedPods {
  559. if p.Name == priorityPodSpec.pod.Name {
  560. priorityPod = p
  561. }
  562. }
  563. gomega.Expect(priorityPod).NotTo(gomega.BeNil())
  564. framework.ExpectNotEqual(priorityPod.Status.Phase, v1.PodSucceeded,
  565. fmt.Sprintf("pod: %s succeeded unexpectedly", priorityPod.Name))
  566. // Check eviction ordering.
  567. // Note: it is alright for a priority 1 and priority 2 pod (for example) to fail in the same round,
  568. // but never alright for a priority 1 pod to fail while the priority 2 pod is still running
  569. for _, lowPriorityPodSpec := range testSpecs {
  570. var lowPriorityPod v1.Pod
  571. for _, p := range updatedPods {
  572. if p.Name == lowPriorityPodSpec.pod.Name {
  573. lowPriorityPod = p
  574. }
  575. }
  576. gomega.Expect(lowPriorityPod).NotTo(gomega.BeNil())
  577. if priorityPodSpec.evictionPriority < lowPriorityPodSpec.evictionPriority && lowPriorityPod.Status.Phase == v1.PodRunning {
  578. framework.ExpectNotEqual(priorityPod.Status.Phase, v1.PodFailed,
  579. fmt.Sprintf("priority %d pod: %s failed before priority %d pod: %s",
  580. priorityPodSpec.evictionPriority, priorityPodSpec.pod.Name, lowPriorityPodSpec.evictionPriority, lowPriorityPodSpec.pod.Name))
  581. }
  582. }
  583. if priorityPod.Status.Phase == v1.PodFailed {
  584. framework.ExpectEqual(priorityPod.Status.Reason, eviction.Reason, "pod %s failed; expected Status.Reason to be %s, but got %s",
  585. priorityPod.Name, eviction.Reason, priorityPod.Status.Reason)
  586. }
  587. // EvictionPriority 0 pods should not fail
  588. if priorityPodSpec.evictionPriority == 0 {
  589. framework.ExpectNotEqual(priorityPod.Status.Phase, v1.PodFailed,
  590. fmt.Sprintf("priority 0 pod: %s failed", priorityPod.Name))
  591. }
  592. // If a pod that is not evictionPriority 0 has not been evicted, we are not done
  593. if priorityPodSpec.evictionPriority != 0 && priorityPod.Status.Phase != v1.PodFailed {
  594. done = false
  595. }
  596. }
  597. if done {
  598. return nil
  599. }
  600. return fmt.Errorf("pods that should be evicted are still running")
  601. }
  602. func verifyEvictionEvents(f *framework.Framework, testSpecs []podEvictSpec, expectedStarvedResource v1.ResourceName) {
  603. for _, spec := range testSpecs {
  604. pod := spec.pod
  605. if spec.evictionPriority != 0 {
  606. selector := fields.Set{
  607. "involvedObject.kind": "Pod",
  608. "involvedObject.name": pod.Name,
  609. "involvedObject.namespace": f.Namespace.Name,
  610. "reason": eviction.Reason,
  611. }.AsSelector().String()
  612. podEvictEvents, err := f.ClientSet.CoreV1().Events(f.Namespace.Name).List(context.TODO(), metav1.ListOptions{FieldSelector: selector})
  613. gomega.Expect(err).To(gomega.BeNil(), "Unexpected error getting events during eviction test: %v", err)
  614. framework.ExpectEqual(len(podEvictEvents.Items), 1, "Expected to find 1 eviction event for pod %s, got %d", pod.Name, len(podEvictEvents.Items))
  615. event := podEvictEvents.Items[0]
  616. if expectedStarvedResource != noStarvedResource {
  617. // Check the eviction.StarvedResourceKey
  618. starved, found := event.Annotations[eviction.StarvedResourceKey]
  619. framework.ExpectEqual(found, true, "Expected to find an annotation on the eviction event for pod %s containing the starved resource %s, but it was not found",
  620. pod.Name, expectedStarvedResource)
  621. starvedResource := v1.ResourceName(starved)
  622. framework.ExpectEqual(starvedResource, expectedStarvedResource, "Expected to the starved_resource annotation on pod %s to contain %s, but got %s instead",
  623. pod.Name, expectedStarvedResource, starvedResource)
  624. // We only check these keys for memory, because ephemeral storage evictions may be due to volume usage, in which case these values are not present
  625. if expectedStarvedResource == v1.ResourceMemory {
  626. // Check the eviction.OffendingContainersKey
  627. offendersString, found := event.Annotations[eviction.OffendingContainersKey]
  628. framework.ExpectEqual(found, true, "Expected to find an annotation on the eviction event for pod %s containing the offending containers, but it was not found",
  629. pod.Name)
  630. offendingContainers := strings.Split(offendersString, ",")
  631. framework.ExpectEqual(len(offendingContainers), 1, "Expected to find the offending container's usage in the %s annotation, but no container was found",
  632. eviction.OffendingContainersKey)
  633. framework.ExpectEqual(offendingContainers[0], pod.Spec.Containers[0].Name, "Expected to find the offending container: %s's usage in the %s annotation, but found %s instead",
  634. pod.Spec.Containers[0].Name, eviction.OffendingContainersKey, offendingContainers[0])
  635. // Check the eviction.OffendingContainersUsageKey
  636. offendingUsageString, found := event.Annotations[eviction.OffendingContainersUsageKey]
  637. framework.ExpectEqual(found, true, "Expected to find an annotation on the eviction event for pod %s containing the offending containers' usage, but it was not found",
  638. pod.Name)
  639. offendingContainersUsage := strings.Split(offendingUsageString, ",")
  640. framework.ExpectEqual(len(offendingContainersUsage), 1, "Expected to find the offending container's usage in the %s annotation, but found %+v",
  641. eviction.OffendingContainersUsageKey, offendingContainersUsage)
  642. usageQuantity, err := resource.ParseQuantity(offendingContainersUsage[0])
  643. gomega.Expect(err).To(gomega.BeNil(), "Expected to be able to parse pod %s's %s annotation as a quantity, but got err: %v", pod.Name, eviction.OffendingContainersUsageKey, err)
  644. request := pod.Spec.Containers[0].Resources.Requests[starvedResource]
  645. framework.ExpectEqual(usageQuantity.Cmp(request), 1, "Expected usage of offending container: %s in pod %s to exceed its request %s",
  646. usageQuantity.String(), pod.Name, request.String())
  647. }
  648. }
  649. }
  650. }
  651. }
  652. // Returns TRUE if the node has the node condition, FALSE otherwise
  653. func hasNodeCondition(f *framework.Framework, expectedNodeCondition v1.NodeConditionType) bool {
  654. localNodeStatus := getLocalNode(f).Status
  655. _, actualNodeCondition := testutils.GetNodeCondition(&localNodeStatus, expectedNodeCondition)
  656. gomega.Expect(actualNodeCondition).NotTo(gomega.BeNil())
  657. return actualNodeCondition.Status == v1.ConditionTrue
  658. }
  659. func logInodeMetrics() {
  660. summary, err := getNodeSummary()
  661. if err != nil {
  662. framework.Logf("Error getting summary: %v", err)
  663. return
  664. }
  665. if summary.Node.Runtime != nil && summary.Node.Runtime.ImageFs != nil && summary.Node.Runtime.ImageFs.Inodes != nil && summary.Node.Runtime.ImageFs.InodesFree != nil {
  666. framework.Logf("imageFsInfo.Inodes: %d, imageFsInfo.InodesFree: %d", *summary.Node.Runtime.ImageFs.Inodes, *summary.Node.Runtime.ImageFs.InodesFree)
  667. }
  668. if summary.Node.Fs != nil && summary.Node.Fs.Inodes != nil && summary.Node.Fs.InodesFree != nil {
  669. framework.Logf("rootFsInfo.Inodes: %d, rootFsInfo.InodesFree: %d", *summary.Node.Fs.Inodes, *summary.Node.Fs.InodesFree)
  670. }
  671. for _, pod := range summary.Pods {
  672. framework.Logf("Pod: %s", pod.PodRef.Name)
  673. for _, container := range pod.Containers {
  674. if container.Rootfs != nil && container.Rootfs.InodesUsed != nil {
  675. framework.Logf("--- summary Container: %s inodeUsage: %d", container.Name, *container.Rootfs.InodesUsed)
  676. }
  677. }
  678. for _, volume := range pod.VolumeStats {
  679. if volume.FsStats.InodesUsed != nil {
  680. framework.Logf("--- summary Volume: %s inodeUsage: %d", volume.Name, *volume.FsStats.InodesUsed)
  681. }
  682. }
  683. }
  684. }
  685. func logDiskMetrics() {
  686. summary, err := getNodeSummary()
  687. if err != nil {
  688. framework.Logf("Error getting summary: %v", err)
  689. return
  690. }
  691. if summary.Node.Runtime != nil && summary.Node.Runtime.ImageFs != nil && summary.Node.Runtime.ImageFs.CapacityBytes != nil && summary.Node.Runtime.ImageFs.AvailableBytes != nil {
  692. framework.Logf("imageFsInfo.CapacityBytes: %d, imageFsInfo.AvailableBytes: %d", *summary.Node.Runtime.ImageFs.CapacityBytes, *summary.Node.Runtime.ImageFs.AvailableBytes)
  693. }
  694. if summary.Node.Fs != nil && summary.Node.Fs.CapacityBytes != nil && summary.Node.Fs.AvailableBytes != nil {
  695. framework.Logf("rootFsInfo.CapacityBytes: %d, rootFsInfo.AvailableBytes: %d", *summary.Node.Fs.CapacityBytes, *summary.Node.Fs.AvailableBytes)
  696. }
  697. for _, pod := range summary.Pods {
  698. framework.Logf("Pod: %s", pod.PodRef.Name)
  699. for _, container := range pod.Containers {
  700. if container.Rootfs != nil && container.Rootfs.UsedBytes != nil {
  701. framework.Logf("--- summary Container: %s UsedBytes: %d", container.Name, *container.Rootfs.UsedBytes)
  702. }
  703. }
  704. for _, volume := range pod.VolumeStats {
  705. if volume.FsStats.InodesUsed != nil {
  706. framework.Logf("--- summary Volume: %s UsedBytes: %d", volume.Name, *volume.FsStats.UsedBytes)
  707. }
  708. }
  709. }
  710. }
  711. func logMemoryMetrics() {
  712. summary, err := getNodeSummary()
  713. if err != nil {
  714. framework.Logf("Error getting summary: %v", err)
  715. return
  716. }
  717. if summary.Node.Memory != nil && summary.Node.Memory.WorkingSetBytes != nil && summary.Node.Memory.AvailableBytes != nil {
  718. framework.Logf("Node.Memory.WorkingSetBytes: %d, Node.Memory.AvailableBytes: %d", *summary.Node.Memory.WorkingSetBytes, *summary.Node.Memory.AvailableBytes)
  719. }
  720. for _, sysContainer := range summary.Node.SystemContainers {
  721. if sysContainer.Name == kubeletstatsv1alpha1.SystemContainerPods && sysContainer.Memory != nil && sysContainer.Memory.WorkingSetBytes != nil && sysContainer.Memory.AvailableBytes != nil {
  722. framework.Logf("Allocatable.Memory.WorkingSetBytes: %d, Allocatable.Memory.AvailableBytes: %d", *sysContainer.Memory.WorkingSetBytes, *sysContainer.Memory.AvailableBytes)
  723. }
  724. }
  725. for _, pod := range summary.Pods {
  726. framework.Logf("Pod: %s", pod.PodRef.Name)
  727. for _, container := range pod.Containers {
  728. if container.Memory != nil && container.Memory.WorkingSetBytes != nil {
  729. framework.Logf("--- summary Container: %s WorkingSetBytes: %d", container.Name, *container.Memory.WorkingSetBytes)
  730. }
  731. }
  732. }
  733. }
  734. func logPidMetrics() {
  735. summary, err := getNodeSummary()
  736. if err != nil {
  737. framework.Logf("Error getting summary: %v", err)
  738. return
  739. }
  740. if summary.Node.Rlimit != nil && summary.Node.Rlimit.MaxPID != nil && summary.Node.Rlimit.NumOfRunningProcesses != nil {
  741. framework.Logf("Node.Rlimit.MaxPID: %d, Node.Rlimit.RunningProcesses: %d", *summary.Node.Rlimit.MaxPID, *summary.Node.Rlimit.NumOfRunningProcesses)
  742. }
  743. }
  744. func eventuallyGetSummary() (s *kubeletstatsv1alpha1.Summary) {
  745. gomega.Eventually(func() error {
  746. summary, err := getNodeSummary()
  747. if err != nil {
  748. return err
  749. }
  750. if summary == nil || summary.Node.Fs == nil || summary.Node.Fs.InodesFree == nil || summary.Node.Fs.AvailableBytes == nil {
  751. return fmt.Errorf("some part of data is nil")
  752. }
  753. s = summary
  754. return nil
  755. }, time.Minute, evictionPollInterval).Should(gomega.BeNil())
  756. return
  757. }
  758. // returns a pod that does not use any resources
  759. func innocentPod() *v1.Pod {
  760. return &v1.Pod{
  761. ObjectMeta: metav1.ObjectMeta{Name: "innocent-pod"},
  762. Spec: v1.PodSpec{
  763. RestartPolicy: v1.RestartPolicyNever,
  764. Containers: []v1.Container{
  765. {
  766. Image: busyboxImage,
  767. Name: "innocent-container",
  768. Command: []string{
  769. "sh",
  770. "-c",
  771. "while true; do sleep 5; done",
  772. },
  773. },
  774. },
  775. },
  776. }
  777. }
  778. const (
  779. volumeMountPath = "/test-mnt"
  780. volumeName = "test-volume"
  781. )
  782. func inodeConsumingPod(name string, numFiles int, volumeSource *v1.VolumeSource) *v1.Pod {
  783. path := ""
  784. if volumeSource != nil {
  785. path = volumeMountPath
  786. }
  787. // Each iteration creates an empty file
  788. return podWithCommand(volumeSource, v1.ResourceRequirements{}, numFiles, name, fmt.Sprintf("touch %s${i}.txt; sleep 0.001;", filepath.Join(path, "file")))
  789. }
  790. func diskConsumingPod(name string, diskConsumedMB int, volumeSource *v1.VolumeSource, resources v1.ResourceRequirements) *v1.Pod {
  791. path := ""
  792. if volumeSource != nil {
  793. path = volumeMountPath
  794. }
  795. // Each iteration writes 1 Mb, so do diskConsumedMB iterations.
  796. return podWithCommand(volumeSource, resources, diskConsumedMB, name, fmt.Sprintf("dd if=/dev/urandom of=%s${i} bs=1048576 count=1 2>/dev/null; sleep .1;", filepath.Join(path, "file")))
  797. }
  798. func pidConsumingPod(name string, numProcesses int) *v1.Pod {
  799. // Each iteration forks once, but creates two processes
  800. return podWithCommand(nil, v1.ResourceRequirements{}, numProcesses/2, name, "(while true; do sleep 5; done)&")
  801. }
  802. // podWithCommand returns a pod with the provided volumeSource and resourceRequirements.
  803. func podWithCommand(volumeSource *v1.VolumeSource, resources v1.ResourceRequirements, iterations int, name, command string) *v1.Pod {
  804. volumeMounts := []v1.VolumeMount{}
  805. volumes := []v1.Volume{}
  806. if volumeSource != nil {
  807. volumeMounts = []v1.VolumeMount{{MountPath: volumeMountPath, Name: volumeName}}
  808. volumes = []v1.Volume{{Name: volumeName, VolumeSource: *volumeSource}}
  809. }
  810. return &v1.Pod{
  811. ObjectMeta: metav1.ObjectMeta{Name: fmt.Sprintf("%s-pod", name)},
  812. Spec: v1.PodSpec{
  813. RestartPolicy: v1.RestartPolicyNever,
  814. Containers: []v1.Container{
  815. {
  816. Image: busyboxImage,
  817. Name: fmt.Sprintf("%s-container", name),
  818. Command: []string{
  819. "sh",
  820. "-c",
  821. fmt.Sprintf("i=0; while [ $i -lt %d ]; do %s i=$(($i+1)); done; while true; do sleep 5; done", iterations, command),
  822. },
  823. Resources: resources,
  824. VolumeMounts: volumeMounts,
  825. },
  826. },
  827. Volumes: volumes,
  828. },
  829. }
  830. }
  831. func getMemhogPod(podName string, ctnName string, res v1.ResourceRequirements) *v1.Pod {
  832. env := []v1.EnvVar{
  833. {
  834. Name: "MEMORY_LIMIT",
  835. ValueFrom: &v1.EnvVarSource{
  836. ResourceFieldRef: &v1.ResourceFieldSelector{
  837. Resource: "limits.memory",
  838. },
  839. },
  840. },
  841. }
  842. // If there is a limit specified, pass 80% of it for -mem-total, otherwise use the downward API
  843. // to pass limits.memory, which will be the total memory available.
  844. // This helps prevent a guaranteed pod from triggering an OOM kill due to it's low memory limit,
  845. // which will cause the test to fail inappropriately.
  846. var memLimit string
  847. if limit, ok := res.Limits[v1.ResourceMemory]; ok {
  848. memLimit = strconv.Itoa(int(
  849. float64(limit.Value()) * 0.8))
  850. } else {
  851. memLimit = "$(MEMORY_LIMIT)"
  852. }
  853. return &v1.Pod{
  854. ObjectMeta: metav1.ObjectMeta{
  855. Name: podName,
  856. },
  857. Spec: v1.PodSpec{
  858. RestartPolicy: v1.RestartPolicyNever,
  859. Containers: []v1.Container{
  860. {
  861. Name: ctnName,
  862. Image: "k8s.gcr.io/stress:v1",
  863. ImagePullPolicy: "Always",
  864. Env: env,
  865. // 60 min timeout * 60s / tick per 10s = 360 ticks before timeout => ~11.11Mi/tick
  866. // to fill ~4Gi of memory, so initial ballpark 12Mi/tick.
  867. // We might see flakes due to timeout if the total memory on the nodes increases.
  868. Args: []string{"-mem-alloc-size", "12Mi", "-mem-alloc-sleep", "10s", "-mem-total", memLimit},
  869. Resources: res,
  870. },
  871. },
  872. },
  873. }
  874. }