diff --git a/controllers/kustomization_gc.go b/controllers/kustomization_gc.go index 7cbfd9a8..d6781aee 100644 --- a/controllers/kustomization_gc.go +++ b/controllers/kustomization_gc.go @@ -71,11 +71,17 @@ func (kgc *KustomizeGarbageCollector) Prune(timeout time.Duration, name string, if err == nil { for _, item := range ulist.Items { id := fmt.Sprintf("%s/%s/%s", item.GetKind(), item.GetNamespace(), item.GetName()) + if kgc.shouldSkip(item) { kgc.log.V(1).Info(fmt.Sprintf("gc is disabled for '%s'", id)) continue } + if kgc.hasBlockOwnerDeletion(item) { + kgc.log.V(1).Info(fmt.Sprintf("gc is disabled for '%s' due to 'ownerReference.blockOwnerDeletion=true'", id)) + continue + } + if kgc.isStale(item) && item.GetDeletionTimestamp().IsZero() { err = kgc.Delete(ctx, &item) if err != nil { @@ -113,6 +119,11 @@ func (kgc *KustomizeGarbageCollector) Prune(timeout time.Duration, name string, continue } + if kgc.hasBlockOwnerDeletion(item) { + kgc.log.V(1).Info(fmt.Sprintf("gc is disabled for '%s' due to 'ownerReference.blockOwnerDeletion=true'", id)) + continue + } + if kgc.isStale(item) && item.GetDeletionTimestamp().IsZero() { err = kgc.Delete(ctx, &item) if err != nil { @@ -142,13 +153,25 @@ func (kgc *KustomizeGarbageCollector) isStale(obj unstructured.Unstructured) boo itemAnnotationChecksum := obj.GetAnnotations()[fmt.Sprintf("%s/checksum", kustomizev1.GroupVersion.Group)] switch kgc.newChecksum { + // when the Kustomization is deleted the new checksum is set to string empty making all objects stale case "": return true + // skip GC if the new checksum matches the object checksum case itemAnnotationChecksum: return false - default: - return true } + + // skip GC if the checksum annotation is missing from the object + return itemAnnotationChecksum != "" +} + +func (kgc *KustomizeGarbageCollector) hasBlockOwnerDeletion(obj unstructured.Unstructured) bool { + for _, ownerReference := range obj.GetOwnerReferences() { + if bod := ownerReference.BlockOwnerDeletion; bod != nil && *bod == true { + return true + } + } + return false } func (kgc *KustomizeGarbageCollector) shouldSkip(obj unstructured.Unstructured) bool { diff --git a/docs/spec/v1beta1/kustomization.md b/docs/spec/v1beta1/kustomization.md index 5bc675db..e8d5d289 100644 --- a/docs/spec/v1beta1/kustomization.md +++ b/docs/spec/v1beta1/kustomization.md @@ -390,6 +390,9 @@ labeling or annotating them with: kustomize.toolkit.fluxcd.io/prune: disabled ``` +Note that Kubernetes objects generated by other controllers that have `ownerReference.blockOwnerDeletion=true` +are skipped from garbage collection. + ## Health assessment A Kustomization can contain a series of health checks used to determine the