pvc_protection_controller.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  1. /*
  2. Copyright 2017 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 pvcprotection
  14. import (
  15. "context"
  16. "fmt"
  17. "time"
  18. v1 "k8s.io/api/core/v1"
  19. apierrors "k8s.io/apimachinery/pkg/api/errors"
  20. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  21. "k8s.io/apimachinery/pkg/labels"
  22. utilruntime "k8s.io/apimachinery/pkg/util/runtime"
  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/client-go/util/workqueue"
  29. "k8s.io/component-base/metrics/prometheus/ratelimiter"
  30. "k8s.io/klog"
  31. "k8s.io/kubernetes/pkg/controller/volume/protectionutil"
  32. "k8s.io/kubernetes/pkg/util/slice"
  33. volumeutil "k8s.io/kubernetes/pkg/volume/util"
  34. )
  35. // Controller is controller that removes PVCProtectionFinalizer
  36. // from PVCs that are used by no pods.
  37. type Controller struct {
  38. client clientset.Interface
  39. pvcLister corelisters.PersistentVolumeClaimLister
  40. pvcListerSynced cache.InformerSynced
  41. podLister corelisters.PodLister
  42. podListerSynced cache.InformerSynced
  43. queue workqueue.RateLimitingInterface
  44. // allows overriding of StorageObjectInUseProtection feature Enabled/Disabled for testing
  45. storageObjectInUseProtectionEnabled bool
  46. }
  47. // NewPVCProtectionController returns a new instance of PVCProtectionController.
  48. func NewPVCProtectionController(pvcInformer coreinformers.PersistentVolumeClaimInformer, podInformer coreinformers.PodInformer, cl clientset.Interface, storageObjectInUseProtectionFeatureEnabled bool) *Controller {
  49. e := &Controller{
  50. client: cl,
  51. queue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), "pvcprotection"),
  52. storageObjectInUseProtectionEnabled: storageObjectInUseProtectionFeatureEnabled,
  53. }
  54. if cl != nil && cl.CoreV1().RESTClient().GetRateLimiter() != nil {
  55. ratelimiter.RegisterMetricAndTrackRateLimiterUsage("persistentvolumeclaim_protection_controller", cl.CoreV1().RESTClient().GetRateLimiter())
  56. }
  57. e.pvcLister = pvcInformer.Lister()
  58. e.pvcListerSynced = pvcInformer.Informer().HasSynced
  59. pvcInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{
  60. AddFunc: e.pvcAddedUpdated,
  61. UpdateFunc: func(old, new interface{}) {
  62. e.pvcAddedUpdated(new)
  63. },
  64. })
  65. e.podLister = podInformer.Lister()
  66. e.podListerSynced = podInformer.Informer().HasSynced
  67. podInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{
  68. AddFunc: func(obj interface{}) {
  69. e.podAddedDeletedUpdated(nil, obj, false)
  70. },
  71. DeleteFunc: func(obj interface{}) {
  72. e.podAddedDeletedUpdated(nil, obj, true)
  73. },
  74. UpdateFunc: func(old, new interface{}) {
  75. e.podAddedDeletedUpdated(old, new, false)
  76. },
  77. })
  78. return e
  79. }
  80. // Run runs the controller goroutines.
  81. func (c *Controller) Run(workers int, stopCh <-chan struct{}) {
  82. defer utilruntime.HandleCrash()
  83. defer c.queue.ShutDown()
  84. klog.Infof("Starting PVC protection controller")
  85. defer klog.Infof("Shutting down PVC protection controller")
  86. if !cache.WaitForNamedCacheSync("PVC protection", stopCh, c.pvcListerSynced, c.podListerSynced) {
  87. return
  88. }
  89. for i := 0; i < workers; i++ {
  90. go wait.Until(c.runWorker, time.Second, stopCh)
  91. }
  92. <-stopCh
  93. }
  94. func (c *Controller) runWorker() {
  95. for c.processNextWorkItem() {
  96. }
  97. }
  98. // processNextWorkItem deals with one pvcKey off the queue. It returns false when it's time to quit.
  99. func (c *Controller) processNextWorkItem() bool {
  100. pvcKey, quit := c.queue.Get()
  101. if quit {
  102. return false
  103. }
  104. defer c.queue.Done(pvcKey)
  105. pvcNamespace, pvcName, err := cache.SplitMetaNamespaceKey(pvcKey.(string))
  106. if err != nil {
  107. utilruntime.HandleError(fmt.Errorf("error parsing PVC key %q: %v", pvcKey, err))
  108. return true
  109. }
  110. err = c.processPVC(pvcNamespace, pvcName)
  111. if err == nil {
  112. c.queue.Forget(pvcKey)
  113. return true
  114. }
  115. utilruntime.HandleError(fmt.Errorf("PVC %v failed with : %v", pvcKey, err))
  116. c.queue.AddRateLimited(pvcKey)
  117. return true
  118. }
  119. func (c *Controller) processPVC(pvcNamespace, pvcName string) error {
  120. klog.V(4).Infof("Processing PVC %s/%s", pvcNamespace, pvcName)
  121. startTime := time.Now()
  122. defer func() {
  123. klog.V(4).Infof("Finished processing PVC %s/%s (%v)", pvcNamespace, pvcName, time.Since(startTime))
  124. }()
  125. pvc, err := c.pvcLister.PersistentVolumeClaims(pvcNamespace).Get(pvcName)
  126. if apierrors.IsNotFound(err) {
  127. klog.V(4).Infof("PVC %s/%s not found, ignoring", pvcNamespace, pvcName)
  128. return nil
  129. }
  130. if err != nil {
  131. return err
  132. }
  133. if protectionutil.IsDeletionCandidate(pvc, volumeutil.PVCProtectionFinalizer) {
  134. // PVC should be deleted. Check if it's used and remove finalizer if
  135. // it's not.
  136. isUsed, err := c.isBeingUsed(pvc)
  137. if err != nil {
  138. return err
  139. }
  140. if !isUsed {
  141. return c.removeFinalizer(pvc)
  142. }
  143. klog.V(2).Infof("Keeping PVC %s/%s because it is still being used", pvc.Namespace, pvc.Name)
  144. }
  145. if protectionutil.NeedToAddFinalizer(pvc, volumeutil.PVCProtectionFinalizer) {
  146. // PVC is not being deleted -> it should have the finalizer. The
  147. // finalizer should be added by admission plugin, this is just to add
  148. // the finalizer to old PVCs that were created before the admission
  149. // plugin was enabled.
  150. return c.addFinalizer(pvc)
  151. }
  152. return nil
  153. }
  154. func (c *Controller) addFinalizer(pvc *v1.PersistentVolumeClaim) error {
  155. // Skip adding Finalizer in case the StorageObjectInUseProtection feature is not enabled
  156. if !c.storageObjectInUseProtectionEnabled {
  157. return nil
  158. }
  159. claimClone := pvc.DeepCopy()
  160. claimClone.ObjectMeta.Finalizers = append(claimClone.ObjectMeta.Finalizers, volumeutil.PVCProtectionFinalizer)
  161. _, err := c.client.CoreV1().PersistentVolumeClaims(claimClone.Namespace).Update(context.TODO(), claimClone, metav1.UpdateOptions{})
  162. if err != nil {
  163. klog.V(3).Infof("Error adding protection finalizer to PVC %s/%s: %v", pvc.Namespace, pvc.Name, err)
  164. return err
  165. }
  166. klog.V(3).Infof("Added protection finalizer to PVC %s/%s", pvc.Namespace, pvc.Name)
  167. return nil
  168. }
  169. func (c *Controller) removeFinalizer(pvc *v1.PersistentVolumeClaim) error {
  170. claimClone := pvc.DeepCopy()
  171. claimClone.ObjectMeta.Finalizers = slice.RemoveString(claimClone.ObjectMeta.Finalizers, volumeutil.PVCProtectionFinalizer, nil)
  172. _, err := c.client.CoreV1().PersistentVolumeClaims(claimClone.Namespace).Update(context.TODO(), claimClone, metav1.UpdateOptions{})
  173. if err != nil {
  174. klog.V(3).Infof("Error removing protection finalizer from PVC %s/%s: %v", pvc.Namespace, pvc.Name, err)
  175. return err
  176. }
  177. klog.V(3).Infof("Removed protection finalizer from PVC %s/%s", pvc.Namespace, pvc.Name)
  178. return nil
  179. }
  180. func (c *Controller) isBeingUsed(pvc *v1.PersistentVolumeClaim) (bool, error) {
  181. // Look for a Pod using pvc in the Informer's cache. If one is found the
  182. // correct decision to keep pvc is taken without doing an expensive live
  183. // list.
  184. if inUse, err := c.askInformer(pvc); err != nil {
  185. // No need to return because a live list will follow.
  186. klog.Error(err)
  187. } else if inUse {
  188. return true, nil
  189. }
  190. // Even if no Pod using pvc was found in the Informer's cache it doesn't
  191. // mean such a Pod doesn't exist: it might just not be in the cache yet. To
  192. // be 100% confident that it is safe to delete pvc make sure no Pod is using
  193. // it among those returned by a live list.
  194. return c.askAPIServer(pvc)
  195. }
  196. func (c *Controller) askInformer(pvc *v1.PersistentVolumeClaim) (bool, error) {
  197. klog.V(4).Infof("Looking for Pods using PVC %s/%s in the Informer's cache", pvc.Namespace, pvc.Name)
  198. pods, err := c.podLister.Pods(pvc.Namespace).List(labels.Everything())
  199. if err != nil {
  200. return false, fmt.Errorf("cache-based list of pods failed while processing %s/%s: %s", pvc.Namespace, pvc.Name, err.Error())
  201. }
  202. for _, pod := range pods {
  203. if podUsesPVC(pod, pvc.Name) {
  204. return true, nil
  205. }
  206. }
  207. klog.V(4).Infof("No Pod using PVC %s/%s was found in the Informer's cache", pvc.Namespace, pvc.Name)
  208. return false, nil
  209. }
  210. func (c *Controller) askAPIServer(pvc *v1.PersistentVolumeClaim) (bool, error) {
  211. klog.V(4).Infof("Looking for Pods using PVC %s/%s with a live list", pvc.Namespace, pvc.Name)
  212. podsList, err := c.client.CoreV1().Pods(pvc.Namespace).List(context.TODO(), metav1.ListOptions{})
  213. if err != nil {
  214. return false, fmt.Errorf("live list of pods failed: %s", err.Error())
  215. }
  216. for _, pod := range podsList.Items {
  217. if podUsesPVC(&pod, pvc.Name) {
  218. return true, nil
  219. }
  220. }
  221. klog.V(2).Infof("PVC %s/%s is unused", pvc.Namespace, pvc.Name)
  222. return false, nil
  223. }
  224. func podUsesPVC(pod *v1.Pod, pvc string) bool {
  225. // Check whether pvc is used by pod only if pod is scheduled, because
  226. // kubelet sees pods after they have been scheduled and it won't allow
  227. // starting a pod referencing a PVC with a non-nil deletionTimestamp.
  228. if pod.Spec.NodeName != "" {
  229. for _, volume := range pod.Spec.Volumes {
  230. if volume.PersistentVolumeClaim != nil && volume.PersistentVolumeClaim.ClaimName == pvc {
  231. klog.V(2).Infof("Pod %s/%s uses PVC %s", pod.Namespace, pod.Name, pvc)
  232. return true
  233. }
  234. }
  235. }
  236. return false
  237. }
  238. // pvcAddedUpdated reacts to pvc added/updated events
  239. func (c *Controller) pvcAddedUpdated(obj interface{}) {
  240. pvc, ok := obj.(*v1.PersistentVolumeClaim)
  241. if !ok {
  242. utilruntime.HandleError(fmt.Errorf("PVC informer returned non-PVC object: %#v", obj))
  243. return
  244. }
  245. key, err := cache.MetaNamespaceKeyFunc(pvc)
  246. if err != nil {
  247. utilruntime.HandleError(fmt.Errorf("couldn't get key for Persistent Volume Claim %#v: %v", pvc, err))
  248. return
  249. }
  250. klog.V(4).Infof("Got event on PVC %s", key)
  251. if protectionutil.NeedToAddFinalizer(pvc, volumeutil.PVCProtectionFinalizer) || protectionutil.IsDeletionCandidate(pvc, volumeutil.PVCProtectionFinalizer) {
  252. c.queue.Add(key)
  253. }
  254. }
  255. // podAddedDeletedUpdated reacts to Pod events
  256. func (c *Controller) podAddedDeletedUpdated(old, new interface{}, deleted bool) {
  257. if pod := c.parsePod(new); pod != nil {
  258. c.enqueuePVCs(pod, deleted)
  259. // An update notification might mask the deletion of a pod X and the
  260. // following creation of a pod Y with the same namespaced name as X. If
  261. // that's the case X needs to be processed as well to handle the case
  262. // where it is blocking deletion of a PVC not referenced by Y, otherwise
  263. // such PVC will never be deleted.
  264. if oldPod := c.parsePod(old); oldPod != nil && oldPod.UID != pod.UID {
  265. c.enqueuePVCs(oldPod, true)
  266. }
  267. }
  268. }
  269. func (*Controller) parsePod(obj interface{}) *v1.Pod {
  270. if obj == nil {
  271. return nil
  272. }
  273. pod, ok := obj.(*v1.Pod)
  274. if !ok {
  275. tombstone, ok := obj.(cache.DeletedFinalStateUnknown)
  276. if !ok {
  277. utilruntime.HandleError(fmt.Errorf("couldn't get object from tombstone %#v", obj))
  278. return nil
  279. }
  280. pod, ok = tombstone.Obj.(*v1.Pod)
  281. if !ok {
  282. utilruntime.HandleError(fmt.Errorf("tombstone contained object that is not a Pod %#v", obj))
  283. return nil
  284. }
  285. }
  286. return pod
  287. }
  288. func (c *Controller) enqueuePVCs(pod *v1.Pod, deleted bool) {
  289. // Filter out pods that can't help us to remove a finalizer on PVC
  290. if !deleted && !volumeutil.IsPodTerminated(pod, pod.Status) && pod.Spec.NodeName != "" {
  291. return
  292. }
  293. klog.V(4).Infof("Enqueuing PVCs for Pod %s/%s (UID=%s)", pod.Namespace, pod.Name, pod.UID)
  294. // Enqueue all PVCs that the pod uses
  295. for _, volume := range pod.Spec.Volumes {
  296. if volume.PersistentVolumeClaim != nil {
  297. c.queue.Add(pod.Namespace + "/" + volume.PersistentVolumeClaim.ClaimName)
  298. }
  299. }
  300. }