Delete safely deletes a Kubernetes resource with ownership validation It ensures only the owner can delete the resource and handles garbage collection properly
(ctx context.Context, c clientWithRecorder, owner O, expected T)
| 57 | // Delete safely deletes a Kubernetes resource with ownership validation |
| 58 | // It ensures only the owner can delete the resource and handles garbage collection properly |
| 59 | func Delete[O client.Object, T client.Object](ctx context.Context, c clientWithRecorder, owner O, expected T) error { |
| 60 | typeLogLine := logLineForObject(expected) |
| 61 | hasOwner := !reflect.ValueOf(owner).IsNil() |
| 62 | |
| 63 | existing := expected.DeepCopyObject().(T) |
| 64 | if err := c.Get(ctx, client.ObjectKeyFromObject(expected), existing); err != nil { |
| 65 | if apierrors.IsNotFound(err) || meta.IsNoMatchError(err) { |
| 66 | return nil |
| 67 | } |
| 68 | return fmt.Errorf("failed to get %s %s/%s: %w", typeLogLine, expected.GetNamespace(), expected.GetName(), err) |
| 69 | } |
| 70 | |
| 71 | if !existing.GetDeletionTimestamp().IsZero() { |
| 72 | return nil |
| 73 | } |
| 74 | |
| 75 | // Use namespace presence as a proxy for "is namespaced" to avoid the extra |
| 76 | // Scheme/RESTMapper lookups that apiutil.IsObjectNamespaced requires. |
| 77 | // Cluster-scoped resources (e.g. ClusterRoleBinding) always have an empty namespace. |
| 78 | if hasOwner && existing.GetNamespace() != "" { |
| 79 | if !metav1.IsControlledBy(existing, owner) { |
| 80 | return fmt.Errorf("cannot delete %s %s/%s: not owned by %s %s/%s", |
| 81 | typeLogLine, existing.GetNamespace(), existing.GetName(), |
| 82 | logLineForObject(owner), owner.GetNamespace(), owner.GetName()) |
| 83 | } |
| 84 | if !owner.GetDeletionTimestamp().IsZero() { |
| 85 | return nil // GC will handle |
| 86 | } |
| 87 | } |
| 88 | |
| 89 | if err := c.Delete(ctx, existing); err != nil { |
| 90 | if apierrors.IsNotFound(err) || meta.IsNoMatchError(err) { |
| 91 | return nil // already deleted |
| 92 | } |
| 93 | return fmt.Errorf("failed to delete %s %s/%s: %w", typeLogLine, expected.GetNamespace(), expected.GetName(), err) |
| 94 | } |
| 95 | |
| 96 | if hasOwner { |
| 97 | c.Eventf(owner, corev1.EventTypeNormal, "Deleted", "Deleted %s %s/%s", typeLogLine, expected.GetNamespace(), expected.GetName()) |
| 98 | } |
| 99 | return nil |
| 100 | } |
| 101 | |
| 102 | // Reconcile ensures a resource exists and matches the expected state |
| 103 | // It creates the resource if it doesn't exist, or updates it if it differs from expected state |