gc_controller.go 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133
  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/kubernetes/pkg/api"
  19. "k8s.io/kubernetes/pkg/client/cache"
  20. clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset"
  21. "k8s.io/kubernetes/pkg/controller"
  22. "k8s.io/kubernetes/pkg/controller/framework"
  23. "k8s.io/kubernetes/pkg/fields"
  24. "k8s.io/kubernetes/pkg/labels"
  25. "k8s.io/kubernetes/pkg/runtime"
  26. "k8s.io/kubernetes/pkg/util/metrics"
  27. utilruntime "k8s.io/kubernetes/pkg/util/runtime"
  28. "k8s.io/kubernetes/pkg/util/wait"
  29. "k8s.io/kubernetes/pkg/watch"
  30. "github.com/golang/glog"
  31. )
  32. const (
  33. gcCheckPeriod = 20 * time.Second
  34. )
  35. type PodGCController struct {
  36. kubeClient clientset.Interface
  37. podStore cache.StoreToPodLister
  38. podStoreSyncer *framework.Controller
  39. deletePod func(namespace, name string) error
  40. threshold int
  41. }
  42. func New(kubeClient clientset.Interface, resyncPeriod controller.ResyncPeriodFunc, threshold int) *PodGCController {
  43. if kubeClient != nil && kubeClient.Core().GetRESTClient().GetRateLimiter() != nil {
  44. metrics.RegisterMetricAndTrackRateLimiterUsage("gc_controller", kubeClient.Core().GetRESTClient().GetRateLimiter())
  45. }
  46. gcc := &PodGCController{
  47. kubeClient: kubeClient,
  48. threshold: threshold,
  49. deletePod: func(namespace, name string) error {
  50. return kubeClient.Core().Pods(namespace).Delete(name, api.NewDeleteOptions(0))
  51. },
  52. }
  53. terminatedSelector := fields.ParseSelectorOrDie("status.phase!=" + string(api.PodPending) + ",status.phase!=" + string(api.PodRunning) + ",status.phase!=" + string(api.PodUnknown))
  54. gcc.podStore.Indexer, gcc.podStoreSyncer = framework.NewIndexerInformer(
  55. &cache.ListWatch{
  56. ListFunc: func(options api.ListOptions) (runtime.Object, error) {
  57. options.FieldSelector = terminatedSelector
  58. return gcc.kubeClient.Core().Pods(api.NamespaceAll).List(options)
  59. },
  60. WatchFunc: func(options api.ListOptions) (watch.Interface, error) {
  61. options.FieldSelector = terminatedSelector
  62. return gcc.kubeClient.Core().Pods(api.NamespaceAll).Watch(options)
  63. },
  64. },
  65. &api.Pod{},
  66. resyncPeriod(),
  67. framework.ResourceEventHandlerFuncs{},
  68. // We don't need to build a index for podStore here actually, but build one for consistency.
  69. // It will ensure that if people start making use of the podStore in more specific ways,
  70. // they'll get the benefits they expect. It will also reserve the name for future refactorings.
  71. cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc},
  72. )
  73. return gcc
  74. }
  75. func (gcc *PodGCController) Run(stop <-chan struct{}) {
  76. go gcc.podStoreSyncer.Run(stop)
  77. go wait.Until(gcc.gc, gcCheckPeriod, stop)
  78. <-stop
  79. }
  80. func (gcc *PodGCController) gc() {
  81. terminatedPods, _ := gcc.podStore.List(labels.Everything())
  82. terminatedPodCount := len(terminatedPods)
  83. sort.Sort(byCreationTimestamp(terminatedPods))
  84. deleteCount := terminatedPodCount - gcc.threshold
  85. if deleteCount > terminatedPodCount {
  86. deleteCount = terminatedPodCount
  87. }
  88. if deleteCount > 0 {
  89. glog.Infof("garbage collecting %v pods", deleteCount)
  90. }
  91. var wait sync.WaitGroup
  92. for i := 0; i < deleteCount; i++ {
  93. wait.Add(1)
  94. go func(namespace string, name string) {
  95. defer wait.Done()
  96. if err := gcc.deletePod(namespace, name); err != nil {
  97. // ignore not founds
  98. defer utilruntime.HandleError(err)
  99. }
  100. }(terminatedPods[i].Namespace, terminatedPods[i].Name)
  101. }
  102. wait.Wait()
  103. }
  104. // byCreationTimestamp sorts a list by creation timestamp, using their names as a tie breaker.
  105. type byCreationTimestamp []*api.Pod
  106. func (o byCreationTimestamp) Len() int { return len(o) }
  107. func (o byCreationTimestamp) Swap(i, j int) { o[i], o[j] = o[j], o[i] }
  108. func (o byCreationTimestamp) Less(i, j int) bool {
  109. if o[i].CreationTimestamp.Equal(o[j].CreationTimestamp) {
  110. return o[i].Name < o[j].Name
  111. }
  112. return o[i].CreationTimestamp.Before(o[j].CreationTimestamp)
  113. }