eviction_manager.go 22 KB

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