gc_controller.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  1. /*
  2. Copyright 2015 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 podgc
  14. import (
  15. "sort"
  16. "sync"
  17. "time"
  18. "k8s.io/api/core/v1"
  19. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  20. "k8s.io/apimachinery/pkg/labels"
  21. utilruntime "k8s.io/apimachinery/pkg/util/runtime"
  22. "k8s.io/apimachinery/pkg/util/sets"
  23. "k8s.io/apimachinery/pkg/util/wait"
  24. coreinformers "k8s.io/client-go/informers/core/v1"
  25. clientset "k8s.io/client-go/kubernetes"
  26. corelisters "k8s.io/client-go/listers/core/v1"
  27. "k8s.io/client-go/tools/cache"
  28. "k8s.io/kubernetes/pkg/controller"
  29. "k8s.io/kubernetes/pkg/util/metrics"
  30. "k8s.io/klog"
  31. )
  32. const (
  33. gcCheckPeriod = 20 * time.Second
  34. )
  35. type PodGCController struct {
  36. kubeClient clientset.Interface
  37. podLister corelisters.PodLister
  38. podListerSynced cache.InformerSynced
  39. deletePod func(namespace, name string) error
  40. terminatedPodThreshold int
  41. }
  42. func NewPodGC(kubeClient clientset.Interface, podInformer coreinformers.PodInformer, terminatedPodThreshold int) *PodGCController {
  43. if kubeClient != nil && kubeClient.CoreV1().RESTClient().GetRateLimiter() != nil {
  44. metrics.RegisterMetricAndTrackRateLimiterUsage("gc_controller", kubeClient.CoreV1().RESTClient().GetRateLimiter())
  45. }
  46. gcc := &PodGCController{
  47. kubeClient: kubeClient,
  48. terminatedPodThreshold: terminatedPodThreshold,
  49. deletePod: func(namespace, name string) error {
  50. klog.Infof("PodGC is force deleting Pod: %v/%v", namespace, name)
  51. return kubeClient.CoreV1().Pods(namespace).Delete(name, metav1.NewDeleteOptions(0))
  52. },
  53. }
  54. gcc.podLister = podInformer.Lister()
  55. gcc.podListerSynced = podInformer.Informer().HasSynced
  56. return gcc
  57. }
  58. func (gcc *PodGCController) Run(stop <-chan struct{}) {
  59. defer utilruntime.HandleCrash()
  60. klog.Infof("Starting GC controller")
  61. defer klog.Infof("Shutting down GC controller")
  62. if !controller.WaitForCacheSync("GC", stop, gcc.podListerSynced) {
  63. return
  64. }
  65. go wait.Until(gcc.gc, gcCheckPeriod, stop)
  66. <-stop
  67. }
  68. func (gcc *PodGCController) gc() {
  69. pods, err := gcc.podLister.List(labels.Everything())
  70. if err != nil {
  71. klog.Errorf("Error while listing all Pods: %v", err)
  72. return
  73. }
  74. if gcc.terminatedPodThreshold > 0 {
  75. gcc.gcTerminated(pods)
  76. }
  77. gcc.gcOrphaned(pods)
  78. gcc.gcUnscheduledTerminating(pods)
  79. }
  80. func isPodTerminated(pod *v1.Pod) bool {
  81. if phase := pod.Status.Phase; phase != v1.PodPending && phase != v1.PodRunning && phase != v1.PodUnknown {
  82. return true
  83. }
  84. return false
  85. }
  86. func (gcc *PodGCController) gcTerminated(pods []*v1.Pod) {
  87. terminatedPods := []*v1.Pod{}
  88. for _, pod := range pods {
  89. if isPodTerminated(pod) {
  90. terminatedPods = append(terminatedPods, pod)
  91. }
  92. }
  93. terminatedPodCount := len(terminatedPods)
  94. sort.Sort(byCreationTimestamp(terminatedPods))
  95. deleteCount := terminatedPodCount - gcc.terminatedPodThreshold
  96. if deleteCount > terminatedPodCount {
  97. deleteCount = terminatedPodCount
  98. }
  99. if deleteCount > 0 {
  100. klog.Infof("garbage collecting %v pods", deleteCount)
  101. }
  102. var wait sync.WaitGroup
  103. for i := 0; i < deleteCount; i++ {
  104. wait.Add(1)
  105. go func(namespace string, name string) {
  106. defer wait.Done()
  107. if err := gcc.deletePod(namespace, name); err != nil {
  108. // ignore not founds
  109. defer utilruntime.HandleError(err)
  110. }
  111. }(terminatedPods[i].Namespace, terminatedPods[i].Name)
  112. }
  113. wait.Wait()
  114. }
  115. // gcOrphaned deletes pods that are bound to nodes that don't exist.
  116. func (gcc *PodGCController) gcOrphaned(pods []*v1.Pod) {
  117. klog.V(4).Infof("GC'ing orphaned")
  118. // We want to get list of Nodes from the etcd, to make sure that it's as fresh as possible.
  119. nodes, err := gcc.kubeClient.CoreV1().Nodes().List(metav1.ListOptions{})
  120. if err != nil {
  121. return
  122. }
  123. nodeNames := sets.NewString()
  124. for i := range nodes.Items {
  125. nodeNames.Insert(nodes.Items[i].Name)
  126. }
  127. for _, pod := range pods {
  128. if pod.Spec.NodeName == "" {
  129. continue
  130. }
  131. if nodeNames.Has(pod.Spec.NodeName) {
  132. continue
  133. }
  134. klog.V(2).Infof("Found orphaned Pod %v/%v assigned to the Node %v. Deleting.", pod.Namespace, pod.Name, pod.Spec.NodeName)
  135. if err := gcc.deletePod(pod.Namespace, pod.Name); err != nil {
  136. utilruntime.HandleError(err)
  137. } else {
  138. klog.V(0).Infof("Forced deletion of orphaned Pod %v/%v succeeded", pod.Namespace, pod.Name)
  139. }
  140. }
  141. }
  142. // gcUnscheduledTerminating deletes pods that are terminating and haven't been scheduled to a particular node.
  143. func (gcc *PodGCController) gcUnscheduledTerminating(pods []*v1.Pod) {
  144. klog.V(4).Infof("GC'ing unscheduled pods which are terminating.")
  145. for _, pod := range pods {
  146. if pod.DeletionTimestamp == nil || len(pod.Spec.NodeName) > 0 {
  147. continue
  148. }
  149. klog.V(2).Infof("Found unscheduled terminating Pod %v/%v not assigned to any Node. Deleting.", pod.Namespace, pod.Name)
  150. if err := gcc.deletePod(pod.Namespace, pod.Name); err != nil {
  151. utilruntime.HandleError(err)
  152. } else {
  153. klog.V(0).Infof("Forced deletion of unscheduled terminating Pod %v/%v succeeded", pod.Namespace, pod.Name)
  154. }
  155. }
  156. }
  157. // byCreationTimestamp sorts a list by creation timestamp, using their names as a tie breaker.
  158. type byCreationTimestamp []*v1.Pod
  159. func (o byCreationTimestamp) Len() int { return len(o) }
  160. func (o byCreationTimestamp) Swap(i, j int) { o[i], o[j] = o[j], o[i] }
  161. func (o byCreationTimestamp) Less(i, j int) bool {
  162. if o[i].CreationTimestamp.Equal(&o[j].CreationTimestamp) {
  163. return o[i].Name < o[j].Name
  164. }
  165. return o[i].CreationTimestamp.Before(&o[j].CreationTimestamp)
  166. }