eviction_manager.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569
  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 eviction
  14. import (
  15. "fmt"
  16. "sort"
  17. "sync"
  18. "time"
  19. "k8s.io/klog"
  20. v1 "k8s.io/api/core/v1"
  21. "k8s.io/apimachinery/pkg/api/resource"
  22. "k8s.io/apimachinery/pkg/util/clock"
  23. utilfeature "k8s.io/apiserver/pkg/util/feature"
  24. "k8s.io/client-go/tools/record"
  25. apiv1resource "k8s.io/kubernetes/pkg/api/v1/resource"
  26. v1helper "k8s.io/kubernetes/pkg/apis/core/v1/helper"
  27. v1qos "k8s.io/kubernetes/pkg/apis/core/v1/helper/qos"
  28. "k8s.io/kubernetes/pkg/features"
  29. statsapi "k8s.io/kubernetes/pkg/kubelet/apis/stats/v1alpha1"
  30. evictionapi "k8s.io/kubernetes/pkg/kubelet/eviction/api"
  31. "k8s.io/kubernetes/pkg/kubelet/lifecycle"
  32. "k8s.io/kubernetes/pkg/kubelet/metrics"
  33. "k8s.io/kubernetes/pkg/kubelet/server/stats"
  34. kubelettypes "k8s.io/kubernetes/pkg/kubelet/types"
  35. "k8s.io/kubernetes/pkg/kubelet/util/format"
  36. )
  37. const (
  38. podCleanupTimeout = 30 * time.Second
  39. podCleanupPollFreq = time.Second
  40. )
  41. // managerImpl implements Manager
  42. type managerImpl struct {
  43. // used to track time
  44. clock clock.Clock
  45. // config is how the manager is configured
  46. config Config
  47. // the function to invoke to kill a pod
  48. killPodFunc KillPodFunc
  49. // the function to get the mirror pod by a given statid pod
  50. mirrorPodFunc MirrorPodFunc
  51. // the interface that knows how to do image gc
  52. imageGC ImageGC
  53. // the interface that knows how to do container gc
  54. containerGC ContainerGC
  55. // protects access to internal state
  56. sync.RWMutex
  57. // node conditions are the set of conditions present
  58. nodeConditions []v1.NodeConditionType
  59. // captures when a node condition was last observed based on a threshold being met
  60. nodeConditionsLastObservedAt nodeConditionsObservedAt
  61. // nodeRef is a reference to the node
  62. nodeRef *v1.ObjectReference
  63. // used to record events about the node
  64. recorder record.EventRecorder
  65. // used to measure usage stats on system
  66. summaryProvider stats.SummaryProvider
  67. // records when a threshold was first observed
  68. thresholdsFirstObservedAt thresholdsObservedAt
  69. // records the set of thresholds that have been met (including graceperiod) but not yet resolved
  70. thresholdsMet []evictionapi.Threshold
  71. // signalToRankFunc maps a resource to ranking function for that resource.
  72. signalToRankFunc map[evictionapi.Signal]rankFunc
  73. // signalToNodeReclaimFuncs maps a resource to an ordered list of functions that know how to reclaim that resource.
  74. signalToNodeReclaimFuncs map[evictionapi.Signal]nodeReclaimFuncs
  75. // last observations from synchronize
  76. lastObservations signalObservations
  77. // dedicatedImageFs indicates if imagefs is on a separate device from the rootfs
  78. dedicatedImageFs *bool
  79. // thresholdNotifiers is a list of memory threshold notifiers which each notify for a memory eviction threshold
  80. thresholdNotifiers []ThresholdNotifier
  81. // thresholdsLastUpdated is the last time the thresholdNotifiers were updated.
  82. thresholdsLastUpdated time.Time
  83. }
  84. // ensure it implements the required interface
  85. var _ Manager = &managerImpl{}
  86. // NewManager returns a configured Manager and an associated admission handler to enforce eviction configuration.
  87. func NewManager(
  88. summaryProvider stats.SummaryProvider,
  89. config Config,
  90. killPodFunc KillPodFunc,
  91. mirrorPodFunc MirrorPodFunc,
  92. imageGC ImageGC,
  93. containerGC ContainerGC,
  94. recorder record.EventRecorder,
  95. nodeRef *v1.ObjectReference,
  96. clock clock.Clock,
  97. ) (Manager, lifecycle.PodAdmitHandler) {
  98. manager := &managerImpl{
  99. clock: clock,
  100. killPodFunc: killPodFunc,
  101. mirrorPodFunc: mirrorPodFunc,
  102. imageGC: imageGC,
  103. containerGC: containerGC,
  104. config: config,
  105. recorder: recorder,
  106. summaryProvider: summaryProvider,
  107. nodeRef: nodeRef,
  108. nodeConditionsLastObservedAt: nodeConditionsObservedAt{},
  109. thresholdsFirstObservedAt: thresholdsObservedAt{},
  110. dedicatedImageFs: nil,
  111. thresholdNotifiers: []ThresholdNotifier{},
  112. }
  113. return manager, manager
  114. }
  115. // Admit rejects a pod if its not safe to admit for node stability.
  116. func (m *managerImpl) Admit(attrs *lifecycle.PodAdmitAttributes) lifecycle.PodAdmitResult {
  117. m.RLock()
  118. defer m.RUnlock()
  119. if len(m.nodeConditions) == 0 {
  120. return lifecycle.PodAdmitResult{Admit: true}
  121. }
  122. // Admit Critical pods even under resource pressure since they are required for system stability.
  123. // https://github.com/kubernetes/kubernetes/issues/40573 has more details.
  124. if kubelettypes.IsCriticalPod(attrs.Pod) {
  125. return lifecycle.PodAdmitResult{Admit: true}
  126. }
  127. // Conditions other than memory pressure reject all pods
  128. nodeOnlyHasMemoryPressureCondition := hasNodeCondition(m.nodeConditions, v1.NodeMemoryPressure) && len(m.nodeConditions) == 1
  129. if nodeOnlyHasMemoryPressureCondition {
  130. notBestEffort := v1.PodQOSBestEffort != v1qos.GetPodQOS(attrs.Pod)
  131. if notBestEffort {
  132. return lifecycle.PodAdmitResult{Admit: true}
  133. }
  134. // When node has memory pressure, check BestEffort Pod's toleration:
  135. // admit it if tolerates memory pressure taint, fail for other tolerations, e.g. DiskPressure.
  136. if v1helper.TolerationsTolerateTaint(attrs.Pod.Spec.Tolerations, &v1.Taint{
  137. Key: v1.TaintNodeMemoryPressure,
  138. Effect: v1.TaintEffectNoSchedule,
  139. }) {
  140. return lifecycle.PodAdmitResult{Admit: true}
  141. }
  142. }
  143. // reject pods when under memory pressure (if pod is best effort), or if under disk pressure.
  144. klog.Warningf("Failed to admit pod %s - node has conditions: %v", format.Pod(attrs.Pod), m.nodeConditions)
  145. return lifecycle.PodAdmitResult{
  146. Admit: false,
  147. Reason: Reason,
  148. Message: fmt.Sprintf(nodeConditionMessageFmt, m.nodeConditions),
  149. }
  150. }
  151. // Start starts the control loop to observe and response to low compute resources.
  152. func (m *managerImpl) Start(diskInfoProvider DiskInfoProvider, podFunc ActivePodsFunc, podCleanedUpFunc PodCleanedUpFunc, monitoringInterval time.Duration) {
  153. thresholdHandler := func(message string) {
  154. klog.Infof(message)
  155. m.synchronize(diskInfoProvider, podFunc)
  156. }
  157. if m.config.KernelMemcgNotification {
  158. for _, threshold := range m.config.Thresholds {
  159. if threshold.Signal == evictionapi.SignalMemoryAvailable || threshold.Signal == evictionapi.SignalAllocatableMemoryAvailable {
  160. notifier, err := NewMemoryThresholdNotifier(threshold, m.config.PodCgroupRoot, &CgroupNotifierFactory{}, thresholdHandler)
  161. if err != nil {
  162. klog.Warningf("eviction manager: failed to create memory threshold notifier: %v", err)
  163. } else {
  164. go notifier.Start()
  165. m.thresholdNotifiers = append(m.thresholdNotifiers, notifier)
  166. }
  167. }
  168. }
  169. }
  170. // start the eviction manager monitoring
  171. go func() {
  172. for {
  173. if evictedPods := m.synchronize(diskInfoProvider, podFunc); evictedPods != nil {
  174. klog.Infof("eviction manager: pods %s evicted, waiting for pod to be cleaned up", format.Pods(evictedPods))
  175. m.waitForPodsCleanup(podCleanedUpFunc, evictedPods)
  176. } else {
  177. time.Sleep(monitoringInterval)
  178. }
  179. }
  180. }()
  181. }
  182. // IsUnderMemoryPressure returns true if the node is under memory pressure.
  183. func (m *managerImpl) IsUnderMemoryPressure() bool {
  184. m.RLock()
  185. defer m.RUnlock()
  186. return hasNodeCondition(m.nodeConditions, v1.NodeMemoryPressure)
  187. }
  188. // IsUnderDiskPressure returns true if the node is under disk pressure.
  189. func (m *managerImpl) IsUnderDiskPressure() bool {
  190. m.RLock()
  191. defer m.RUnlock()
  192. return hasNodeCondition(m.nodeConditions, v1.NodeDiskPressure)
  193. }
  194. // IsUnderPIDPressure returns true if the node is under PID pressure.
  195. func (m *managerImpl) IsUnderPIDPressure() bool {
  196. m.RLock()
  197. defer m.RUnlock()
  198. return hasNodeCondition(m.nodeConditions, v1.NodePIDPressure)
  199. }
  200. // synchronize is the main control loop that enforces eviction thresholds.
  201. // Returns the pod that was killed, or nil if no pod was killed.
  202. func (m *managerImpl) synchronize(diskInfoProvider DiskInfoProvider, podFunc ActivePodsFunc) []*v1.Pod {
  203. // if we have nothing to do, just return
  204. thresholds := m.config.Thresholds
  205. if len(thresholds) == 0 && !utilfeature.DefaultFeatureGate.Enabled(features.LocalStorageCapacityIsolation) {
  206. return nil
  207. }
  208. klog.V(3).Infof("eviction manager: synchronize housekeeping")
  209. // build the ranking functions (if not yet known)
  210. // TODO: have a function in cadvisor that lets us know if global housekeeping has completed
  211. if m.dedicatedImageFs == nil {
  212. hasImageFs, ok := diskInfoProvider.HasDedicatedImageFs()
  213. if ok != nil {
  214. return nil
  215. }
  216. m.dedicatedImageFs = &hasImageFs
  217. m.signalToRankFunc = buildSignalToRankFunc(hasImageFs)
  218. m.signalToNodeReclaimFuncs = buildSignalToNodeReclaimFuncs(m.imageGC, m.containerGC, hasImageFs)
  219. }
  220. activePods := podFunc()
  221. updateStats := true
  222. summary, err := m.summaryProvider.Get(updateStats)
  223. if err != nil {
  224. klog.Errorf("eviction manager: failed to get summary stats: %v", err)
  225. return nil
  226. }
  227. if m.clock.Since(m.thresholdsLastUpdated) > notifierRefreshInterval {
  228. m.thresholdsLastUpdated = m.clock.Now()
  229. for _, notifier := range m.thresholdNotifiers {
  230. if err := notifier.UpdateThreshold(summary); err != nil {
  231. klog.Warningf("eviction manager: failed to update %s: %v", notifier.Description(), err)
  232. }
  233. }
  234. }
  235. // make observations and get a function to derive pod usage stats relative to those observations.
  236. observations, statsFunc := makeSignalObservations(summary)
  237. debugLogObservations("observations", observations)
  238. // determine the set of thresholds met independent of grace period
  239. thresholds = thresholdsMet(thresholds, observations, false)
  240. debugLogThresholdsWithObservation("thresholds - ignoring grace period", thresholds, observations)
  241. // determine the set of thresholds previously met that have not yet satisfied the associated min-reclaim
  242. if len(m.thresholdsMet) > 0 {
  243. thresholdsNotYetResolved := thresholdsMet(m.thresholdsMet, observations, true)
  244. thresholds = mergeThresholds(thresholds, thresholdsNotYetResolved)
  245. }
  246. debugLogThresholdsWithObservation("thresholds - reclaim not satisfied", thresholds, observations)
  247. // track when a threshold was first observed
  248. now := m.clock.Now()
  249. thresholdsFirstObservedAt := thresholdsFirstObservedAt(thresholds, m.thresholdsFirstObservedAt, now)
  250. // the set of node conditions that are triggered by currently observed thresholds
  251. nodeConditions := nodeConditions(thresholds)
  252. if len(nodeConditions) > 0 {
  253. klog.V(3).Infof("eviction manager: node conditions - observed: %v", nodeConditions)
  254. }
  255. // track when a node condition was last observed
  256. nodeConditionsLastObservedAt := nodeConditionsLastObservedAt(nodeConditions, m.nodeConditionsLastObservedAt, now)
  257. // node conditions report true if it has been observed within the transition period window
  258. nodeConditions = nodeConditionsObservedSince(nodeConditionsLastObservedAt, m.config.PressureTransitionPeriod, now)
  259. if len(nodeConditions) > 0 {
  260. klog.V(3).Infof("eviction manager: node conditions - transition period not met: %v", nodeConditions)
  261. }
  262. // determine the set of thresholds we need to drive eviction behavior (i.e. all grace periods are met)
  263. thresholds = thresholdsMetGracePeriod(thresholdsFirstObservedAt, now)
  264. debugLogThresholdsWithObservation("thresholds - grace periods satisfied", thresholds, observations)
  265. // update internal state
  266. m.Lock()
  267. m.nodeConditions = nodeConditions
  268. m.thresholdsFirstObservedAt = thresholdsFirstObservedAt
  269. m.nodeConditionsLastObservedAt = nodeConditionsLastObservedAt
  270. m.thresholdsMet = thresholds
  271. // determine the set of thresholds whose stats have been updated since the last sync
  272. thresholds = thresholdsUpdatedStats(thresholds, observations, m.lastObservations)
  273. debugLogThresholdsWithObservation("thresholds - updated stats", thresholds, observations)
  274. m.lastObservations = observations
  275. m.Unlock()
  276. // evict pods if there is a resource usage violation from local volume temporary storage
  277. // If eviction happens in localStorageEviction function, skip the rest of eviction action
  278. if utilfeature.DefaultFeatureGate.Enabled(features.LocalStorageCapacityIsolation) {
  279. if evictedPods := m.localStorageEviction(summary, activePods); len(evictedPods) > 0 {
  280. return evictedPods
  281. }
  282. }
  283. if len(thresholds) == 0 {
  284. klog.V(3).Infof("eviction manager: no resources are starved")
  285. return nil
  286. }
  287. // rank the thresholds by eviction priority
  288. sort.Sort(byEvictionPriority(thresholds))
  289. thresholdToReclaim, resourceToReclaim, foundAny := getReclaimableThreshold(thresholds)
  290. if !foundAny {
  291. return nil
  292. }
  293. klog.Warningf("eviction manager: attempting to reclaim %v", resourceToReclaim)
  294. // record an event about the resources we are now attempting to reclaim via eviction
  295. m.recorder.Eventf(m.nodeRef, v1.EventTypeWarning, "EvictionThresholdMet", "Attempting to reclaim %s", resourceToReclaim)
  296. // check if there are node-level resources we can reclaim to reduce pressure before evicting end-user pods.
  297. if m.reclaimNodeLevelResources(thresholdToReclaim.Signal, resourceToReclaim) {
  298. klog.Infof("eviction manager: able to reduce %v pressure without evicting pods.", resourceToReclaim)
  299. return nil
  300. }
  301. klog.Infof("eviction manager: must evict pod(s) to reclaim %v", resourceToReclaim)
  302. // rank the pods for eviction
  303. rank, ok := m.signalToRankFunc[thresholdToReclaim.Signal]
  304. if !ok {
  305. klog.Errorf("eviction manager: no ranking function for signal %s", thresholdToReclaim.Signal)
  306. return nil
  307. }
  308. // the only candidates viable for eviction are those pods that had anything running.
  309. if len(activePods) == 0 {
  310. klog.Errorf("eviction manager: eviction thresholds have been met, but no pods are active to evict")
  311. return nil
  312. }
  313. // rank the running pods for eviction for the specified resource
  314. rank(activePods, statsFunc)
  315. klog.Infof("eviction manager: pods ranked for eviction: %s", format.Pods(activePods))
  316. //record age of metrics for met thresholds that we are using for evictions.
  317. for _, t := range thresholds {
  318. timeObserved := observations[t.Signal].time
  319. if !timeObserved.IsZero() {
  320. metrics.EvictionStatsAge.WithLabelValues(string(t.Signal)).Observe(metrics.SinceInSeconds(timeObserved.Time))
  321. }
  322. }
  323. // we kill at most a single pod during each eviction interval
  324. for i := range activePods {
  325. pod := activePods[i]
  326. gracePeriodOverride := int64(0)
  327. if !isHardEvictionThreshold(thresholdToReclaim) {
  328. gracePeriodOverride = m.config.MaxPodGracePeriodSeconds
  329. }
  330. message, annotations := evictionMessage(resourceToReclaim, pod, statsFunc)
  331. if m.evictPod(pod, gracePeriodOverride, message, annotations) {
  332. metrics.Evictions.WithLabelValues(string(thresholdToReclaim.Signal)).Inc()
  333. return []*v1.Pod{pod}
  334. }
  335. }
  336. klog.Infof("eviction manager: unable to evict any pods from the node")
  337. return nil
  338. }
  339. func (m *managerImpl) waitForPodsCleanup(podCleanedUpFunc PodCleanedUpFunc, pods []*v1.Pod) {
  340. timeout := m.clock.NewTimer(podCleanupTimeout)
  341. defer timeout.Stop()
  342. ticker := m.clock.NewTicker(podCleanupPollFreq)
  343. defer ticker.Stop()
  344. for {
  345. select {
  346. case <-timeout.C():
  347. klog.Warningf("eviction manager: timed out waiting for pods %s to be cleaned up", format.Pods(pods))
  348. return
  349. case <-ticker.C():
  350. for i, pod := range pods {
  351. if !podCleanedUpFunc(pod) {
  352. break
  353. }
  354. if i == len(pods)-1 {
  355. klog.Infof("eviction manager: pods %s successfully cleaned up", format.Pods(pods))
  356. return
  357. }
  358. }
  359. }
  360. }
  361. }
  362. // reclaimNodeLevelResources attempts to reclaim node level resources. returns true if thresholds were satisfied and no pod eviction is required.
  363. func (m *managerImpl) reclaimNodeLevelResources(signalToReclaim evictionapi.Signal, resourceToReclaim v1.ResourceName) bool {
  364. nodeReclaimFuncs := m.signalToNodeReclaimFuncs[signalToReclaim]
  365. for _, nodeReclaimFunc := range nodeReclaimFuncs {
  366. // attempt to reclaim the pressured resource.
  367. if err := nodeReclaimFunc(); err != nil {
  368. klog.Warningf("eviction manager: unexpected error when attempting to reduce %v pressure: %v", resourceToReclaim, err)
  369. }
  370. }
  371. if len(nodeReclaimFuncs) > 0 {
  372. summary, err := m.summaryProvider.Get(true)
  373. if err != nil {
  374. klog.Errorf("eviction manager: failed to get summary stats after resource reclaim: %v", err)
  375. return false
  376. }
  377. // make observations and get a function to derive pod usage stats relative to those observations.
  378. observations, _ := makeSignalObservations(summary)
  379. debugLogObservations("observations after resource reclaim", observations)
  380. // determine the set of thresholds met independent of grace period
  381. thresholds := thresholdsMet(m.config.Thresholds, observations, false)
  382. debugLogThresholdsWithObservation("thresholds after resource reclaim - ignoring grace period", thresholds, observations)
  383. if len(thresholds) == 0 {
  384. return true
  385. }
  386. }
  387. return false
  388. }
  389. // localStorageEviction checks the EmptyDir volume usage for each pod and determine whether it exceeds the specified limit and needs
  390. // to be evicted. It also checks every container in the pod, if the container overlay usage exceeds the limit, the pod will be evicted too.
  391. func (m *managerImpl) localStorageEviction(summary *statsapi.Summary, pods []*v1.Pod) []*v1.Pod {
  392. statsFunc := cachedStatsFunc(summary.Pods)
  393. evicted := []*v1.Pod{}
  394. for _, pod := range pods {
  395. podStats, ok := statsFunc(pod)
  396. if !ok {
  397. continue
  398. }
  399. if m.emptyDirLimitEviction(podStats, pod) {
  400. evicted = append(evicted, pod)
  401. continue
  402. }
  403. if m.podEphemeralStorageLimitEviction(podStats, pod) {
  404. evicted = append(evicted, pod)
  405. continue
  406. }
  407. if m.containerEphemeralStorageLimitEviction(podStats, pod) {
  408. evicted = append(evicted, pod)
  409. }
  410. }
  411. return evicted
  412. }
  413. func (m *managerImpl) emptyDirLimitEviction(podStats statsapi.PodStats, pod *v1.Pod) bool {
  414. podVolumeUsed := make(map[string]*resource.Quantity)
  415. for _, volume := range podStats.VolumeStats {
  416. podVolumeUsed[volume.Name] = resource.NewQuantity(int64(*volume.UsedBytes), resource.BinarySI)
  417. }
  418. for i := range pod.Spec.Volumes {
  419. source := &pod.Spec.Volumes[i].VolumeSource
  420. if source.EmptyDir != nil {
  421. size := source.EmptyDir.SizeLimit
  422. used := podVolumeUsed[pod.Spec.Volumes[i].Name]
  423. if used != nil && size != nil && size.Sign() == 1 && used.Cmp(*size) > 0 {
  424. // the emptyDir usage exceeds the size limit, evict the pod
  425. return m.evictPod(pod, 0, fmt.Sprintf(emptyDirMessageFmt, pod.Spec.Volumes[i].Name, size.String()), nil)
  426. }
  427. }
  428. }
  429. return false
  430. }
  431. func (m *managerImpl) podEphemeralStorageLimitEviction(podStats statsapi.PodStats, pod *v1.Pod) bool {
  432. _, podLimits := apiv1resource.PodRequestsAndLimits(pod)
  433. _, found := podLimits[v1.ResourceEphemeralStorage]
  434. if !found {
  435. return false
  436. }
  437. podEphemeralStorageTotalUsage := &resource.Quantity{}
  438. var fsStatsSet []fsStatsType
  439. if *m.dedicatedImageFs {
  440. fsStatsSet = []fsStatsType{fsStatsLogs, fsStatsLocalVolumeSource}
  441. } else {
  442. fsStatsSet = []fsStatsType{fsStatsRoot, fsStatsLogs, fsStatsLocalVolumeSource}
  443. }
  444. podEphemeralUsage, err := podLocalEphemeralStorageUsage(podStats, pod, fsStatsSet)
  445. if err != nil {
  446. klog.Errorf("eviction manager: error getting pod disk usage %v", err)
  447. return false
  448. }
  449. podEphemeralStorageTotalUsage.Add(podEphemeralUsage[v1.ResourceEphemeralStorage])
  450. podEphemeralStorageLimit := podLimits[v1.ResourceEphemeralStorage]
  451. if podEphemeralStorageTotalUsage.Cmp(podEphemeralStorageLimit) > 0 {
  452. // the total usage of pod exceeds the total size limit of containers, evict the pod
  453. return m.evictPod(pod, 0, fmt.Sprintf(podEphemeralStorageMessageFmt, podEphemeralStorageLimit.String()), nil)
  454. }
  455. return false
  456. }
  457. func (m *managerImpl) containerEphemeralStorageLimitEviction(podStats statsapi.PodStats, pod *v1.Pod) bool {
  458. thresholdsMap := make(map[string]*resource.Quantity)
  459. for _, container := range pod.Spec.Containers {
  460. ephemeralLimit := container.Resources.Limits.StorageEphemeral()
  461. if ephemeralLimit != nil && ephemeralLimit.Value() != 0 {
  462. thresholdsMap[container.Name] = ephemeralLimit
  463. }
  464. }
  465. for _, containerStat := range podStats.Containers {
  466. containerUsed := diskUsage(containerStat.Logs)
  467. if !*m.dedicatedImageFs {
  468. containerUsed.Add(*diskUsage(containerStat.Rootfs))
  469. }
  470. if ephemeralStorageThreshold, ok := thresholdsMap[containerStat.Name]; ok {
  471. if ephemeralStorageThreshold.Cmp(*containerUsed) < 0 {
  472. return m.evictPod(pod, 0, fmt.Sprintf(containerEphemeralStorageMessageFmt, containerStat.Name, ephemeralStorageThreshold.String()), nil)
  473. }
  474. }
  475. }
  476. return false
  477. }
  478. func (m *managerImpl) evictPod(pod *v1.Pod, gracePeriodOverride int64, evictMsg string, annotations map[string]string) bool {
  479. // If the pod is marked as critical and static, and support for critical pod annotations is enabled,
  480. // do not evict such pods. Static pods are not re-admitted after evictions.
  481. // https://github.com/kubernetes/kubernetes/issues/40573 has more details.
  482. if kubelettypes.IsCriticalPod(pod) {
  483. klog.Errorf("eviction manager: cannot evict a critical pod %s", format.Pod(pod))
  484. return false
  485. }
  486. status := v1.PodStatus{
  487. Phase: v1.PodFailed,
  488. Message: evictMsg,
  489. Reason: Reason,
  490. }
  491. // record that we are evicting the pod
  492. m.recorder.AnnotatedEventf(pod, annotations, v1.EventTypeWarning, Reason, evictMsg)
  493. // this is a blocking call and should only return when the pod and its containers are killed.
  494. err := m.killPodFunc(pod, status, &gracePeriodOverride)
  495. if err != nil {
  496. klog.Errorf("eviction manager: pod %s failed to evict %v", format.Pod(pod), err)
  497. } else {
  498. klog.Infof("eviction manager: pod %s is evicted successfully", format.Pod(pod))
  499. }
  500. return true
  501. }