Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 30 additions & 1 deletion docs/spec/v1beta1/artifactgenerators.md
Original file line number Diff line number Diff line change
Expand Up @@ -748,6 +748,12 @@ namespace is kept in the inventory and the deletion is retried on the next
reconciliation, keeping the ArtifactGenerator in the terminating state when
it is being deleted.

Namespaces that carry the `source.extensions.fluxcd.io/generator` label of
another ArtifactGenerator are not pruned. When an ArtifactGenerator is recreated,
its namespaces carry the label of the previous one until they are applied again.
Existing namespaces with the `IfNotPresent` apply policy are never relabeled, so
they must be deleted manually, or have the label removed before pruning.

Deleting an ArtifactGenerator that manages namespaces or cross-namespace
artifacts requires the authorizing ServiceAccount. If it is no longer
available, the controller cannot prune the managed objects: it logs them, leaves
Expand Down Expand Up @@ -1003,7 +1009,11 @@ with one of the following reasons:

- `type: Ready`
- `status: "False"`
- `reason: BuildFailed | SourceFetchFailed | ReconciliationFailed`
- `reason: BuildFailed | SourceFetchFailed | ReconciliationFailed | DependencyNotReady`

The `DependencyNotReady` reason is set when another ArtifactGenerator is
reconciling one of the same ExternalArtifacts. The reconciliation is retried at
the interval set with the `--requeue-dependency` controller flag.

Transient errors (e.g. network issues) will cause the controller to
retry the reconciliation after a backoff period, while terminal errors
Expand All @@ -1028,6 +1038,25 @@ the `.status.inventory` field. The inventory is used by the controller to keep
track of the generated ExternalArtifacts and the managed namespaces, and to
perform garbage collection of the ones that are no longer targeted.

ExternalArtifacts that were taken over by another ArtifactGenerator are removed
from the inventory of the previous owner without being deleted.

When several ArtifactGenerators declare the same ExternalArtifact, the last one
to reconcile takes it over. To move an ExternalArtifact to another
ArtifactGenerator without it being deleted:

1. Annotate the current owner with
`source.extensions.fluxcd.io/reconcile: disabled`, so that it doesn't take
the ExternalArtifact back.
2. Add the artifact to the new owner and wait for it to become ready. A warning
event with the `OwnershipConflict` reason is expected.
3. While the previous owner is still disabled, remove the artifact from its
`.spec.artifacts`. If the artifact is generated from a `.spec.pathPattern`,
remove its directory from the source instead, and wait for the source to
be updated.
4. Remove the annotation from the previous owner, and request a reconciliation
with the `reconcile.fluxcd.io/requestedAt` annotation.

Each entry has a `kind`:

- Generated artifacts have `kind: ExternalArtifact`, along with the `name`,
Expand Down
5 changes: 1 addition & 4 deletions internal/builder/dirhash_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,6 @@ import (
. "github.com/onsi/gomega"

gotkmeta "github.com/fluxcd/pkg/apis/meta"
gotkstorage "github.com/fluxcd/pkg/artifact/storage"
sourcev1 "github.com/fluxcd/source-controller/api/v1"

swapi "github.com/fluxcd/source-watcher/api/v2/v1beta1"
)
Expand Down Expand Up @@ -213,8 +211,7 @@ func TestBuild_GarbageCollection(t *testing.T) {
}

// GC should delete artifacts older than retention
storagePath := gotkstorage.ArtifactPath(sourcev1.ExternalArtifactKind, "gc", spec.Name, "*")
deleted, err := testStorage.GarbageCollect(ctx, gotkmeta.Artifact{Path: storagePath}, 2*time.Second)
deleted, err := testStorage.GarbageCollect(ctx, *artifact3, 2*time.Second)
g.Expect(err).ToNot(HaveOccurred())
g.Expect(deleted).ToNot(BeEmpty())
g.Expect(testStorage.ArtifactExist(*artifact1)).To(BeFalse())
Expand Down
30 changes: 28 additions & 2 deletions internal/controller/artifactgenerator_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,8 @@ type ArtifactGeneratorReconciler struct {
DefaultServiceAccount string
DisallowedFieldManagers []string
ArtifactServerTLSConfig *tls.Config

artifactLocks artifactLocker
}

// +kubebuilder:rbac:groups=source.extensions.fluxcd.io,resources=artifactgenerators,verbs=get;list;watch;create;update;patchStatus;delete
Expand Down Expand Up @@ -269,6 +271,24 @@ func (r *ArtifactGeneratorReconciler) reconcile(ctx context.Context,
return ctrl.Result{RequeueAfter: obj.GetRequeueAfter()}, nil
}

// Prevent other ArtifactGenerators from building, publishing or removing
// the same ExternalArtifacts until this reconciliation is complete. The
// inventory is included as orphaned ExternalArtifacts may be pruned. The
// path pattern outputs are locked after the sources are fetched.
lease := r.artifactLocks.newLease()
defer lease.release()
lockKeys := inventoryLockKeys(obj)
if obj.Spec.PathPattern == "" {
reqs, err := buildArtifactRequests(obj, nil)
if err != nil {
return ctrl.Result{}, err
}
lockKeys = append(lockKeys, outputLockKeys(obj, reqs)...)
}
if key, ok := lease.tryAcquire(lockKeys...); !ok {
return r.requeueBusy(ctx, obj, key), nil
}

// Mark the object as reconciling and remove any previous error conditions.
gotkconditions.MarkReconciling(obj,
gotkmeta.ProgressingReason,
Expand Down Expand Up @@ -319,6 +339,11 @@ func (r *ArtifactGeneratorReconciler) reconcile(ctx context.Context,
return ctrl.Result{}, err
}

// Lock the ExternalArtifacts expanded from the path pattern.
if key, ok := lease.tryAcquire(outputLockKeys(obj, reqs)...); !ok {
return r.requeueBusy(ctx, obj, key), nil
}

// Build all artifacts first. This stages the files, stores the artifacts
// and extracts the exported inputs, but does not create the
// ExternalArtifact objects yet: namespaces must exist before the
Expand Down Expand Up @@ -520,9 +545,10 @@ func (r *ArtifactGeneratorReconciler) reconcile(ctx context.Context,
}
}

// Garbage collect old artifacts in storage according to the retention policy.
// Garbage collect old artifacts in storage according to the retention policy,
// the path must point to the current artifact to exclude it from collection.
for _, eaRef := range eaRefs {
storagePath := gotkstroage.ArtifactPath(sourcev1.ExternalArtifactKind, eaRef.Namespace, eaRef.Name, "*")
storagePath := gotkstroage.ArtifactPath(sourcev1.ExternalArtifactKind, eaRef.Namespace, eaRef.Name, eaRef.Filename)
delFiles, err := r.Storage.GarbageCollect(ctx, gotkmeta.Artifact{Path: storagePath}, 5*time.Minute)
if err != nil {
log.Error(err, "failed to garbage collect artifacts", "path", storagePath)
Expand Down
27 changes: 8 additions & 19 deletions internal/controller/artifactgenerator_externalfinalizer.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,9 @@ import (
"strings"

corev1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/types"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"

swapi "github.com/fluxcd/source-watcher/api/v2/v1beta1"
)
Expand Down Expand Up @@ -116,40 +114,31 @@ func parseExternalFinalizerRef(value string) (externalFinalizerRef, error) {
return ref, nil
}

// namespaceExternallyFinalized returns the managed Namespace and true when it
// namespaceExternallyFinalized returns true when the managed Namespace
// delegates its finalization to an external object. This is the case when the
// namespace carries a valid externalFinalizer annotation.
//
// The referenced object is not looked up: the annotation is trusted as written,
// which keeps the controller RBAC narrow and avoids caching arbitrary kinds. A
// malformed annotation value is reported to the caller, which surfaces it to
// controller-runtime for a retry.
func (r *ArtifactGeneratorReconciler) namespaceExternallyFinalized(ctx context.Context,
name string) (*corev1.Namespace, bool, error) {
func namespaceExternallyFinalized(ctx context.Context, ns *corev1.Namespace) (bool, error) {
log := ctrl.LoggerFrom(ctx)

ns := &corev1.Namespace{}
if err := r.reader().Get(ctx, client.ObjectKey{Name: name}, ns); err != nil {
if apierrors.IsNotFound(err) {
return nil, false, nil
}
return nil, false, fmt.Errorf("failed to get Namespace for external finalizer check: %w", err)
}

value, ok := ns.Annotations[swapi.ExternalFinalizerAnnotation]
if !ok || value == "" {
log.Info("No external finalizer claimed the namespace, proceeding with cleanup", "namespace", name)
return ns, false, nil
log.Info("No external finalizer claimed the namespace, proceeding with cleanup", "namespace", ns.Name)
return false, nil
}

if _, err := parseExternalFinalizerRef(value); err != nil {
return nil, false, fmt.Errorf("invalid %q annotation on namespace %q: %w",
swapi.ExternalFinalizerAnnotation, name, err)
return false, fmt.Errorf("invalid %q annotation on namespace %q: %w",
swapi.ExternalFinalizerAnnotation, ns.Name, err)
}

log.Info("Namespace finalization is delegated to an external object",
"namespace", name, "externalFinalizer", value)
return ns, true, nil
"namespace", ns.Name, "externalFinalizer", value)
return true, nil
}

// validateNamespaceMetadataExternalFinalizer rejects the reserved
Expand Down
24 changes: 6 additions & 18 deletions internal/controller/artifactgenerator_externalfinalizer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@ import (
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/util/rand"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/client/fake"
"sigs.k8s.io/controller-runtime/pkg/reconcile"

gotkmeta "github.com/fluxcd/pkg/apis/meta"
Expand Down Expand Up @@ -100,14 +99,9 @@ func TestNamespaceExternallyFinalized(t *testing.T) {
ctx := context.Background()

ns := &corev1.Namespace{Name: "tenant"}
kubeClient := fake.NewClientBuilder().WithScheme(NewTestScheme()).WithObjects(ns).Build()
r := &ArtifactGeneratorReconciler{
Client: kubeClient,
Recorder: testEnv.GetEventRecorder(controllerName),
}

// Without the annotation the controller remains accountable.
_, finalized, err := r.namespaceExternallyFinalized(ctx, "tenant")
finalized, err := namespaceExternallyFinalized(ctx, ns)
g.Expect(err).ToNot(HaveOccurred())
g.Expect(finalized).To(BeFalse())

Expand All @@ -116,30 +110,22 @@ func TestNamespaceExternallyFinalized(t *testing.T) {
ns.Annotations = map[string]string{
swapi.ExternalFinalizerAnnotation: "core/v1/ConfigMap/flux-system/missing/uid-1",
}
g.Expect(kubeClient.Update(ctx, ns)).To(Succeed())
_, finalized, err = r.namespaceExternallyFinalized(ctx, "tenant")
finalized, err = namespaceExternallyFinalized(ctx, ns)
g.Expect(err).ToNot(HaveOccurred())
g.Expect(finalized).To(BeTrue())

// A cluster-scoped reference is also accepted.
ns.Annotations[swapi.ExternalFinalizerAnnotation] = "fluxcd.controlplane.io/v1/ResourceSet/tenants/uid-2"
g.Expect(kubeClient.Update(ctx, ns)).To(Succeed())
_, finalized, err = r.namespaceExternallyFinalized(ctx, "tenant")
finalized, err = namespaceExternallyFinalized(ctx, ns)
g.Expect(err).ToNot(HaveOccurred())
g.Expect(finalized).To(BeTrue())

// A malformed value is propagated to the caller.
ns.Annotations[swapi.ExternalFinalizerAnnotation] = "self"
g.Expect(kubeClient.Update(ctx, ns)).To(Succeed())
_, finalized, err = r.namespaceExternallyFinalized(ctx, "tenant")
finalized, err = namespaceExternallyFinalized(ctx, ns)
g.Expect(err).To(HaveOccurred())
g.Expect(err.Error()).To(ContainSubstring(swapi.ExternalFinalizerAnnotation))
g.Expect(finalized).To(BeFalse())

// A missing namespace is treated as already gone.
_, finalized, err = r.namespaceExternallyFinalized(ctx, "does-not-exist")
g.Expect(err).ToNot(HaveOccurred())
g.Expect(finalized).To(BeFalse())
}

func TestArtifactGeneratorReconciler_ManagedNamespacesExternalFinalizer(t *testing.T) {
Expand Down Expand Up @@ -208,6 +194,7 @@ func TestArtifactGeneratorReconciler_ManagedNamespacesExternalFinalizer(t *testi
g.Expect(err).ToNot(HaveOccurred())
g.Expect(apierrors.IsNotFound(testClient.Get(ctx, objKey, &swapi.ArtifactGenerator{}))).To(BeTrue())
g.Expect(testClient.Get(ctx, client.ObjectKey{Name: tgtName}, ns)).To(Succeed())
g.Expect(ns.DeletionTimestamp).To(BeNil())
}

func TestArtifactGeneratorReconciler_ManagedNamespacesExternalFinalizerMalformed(t *testing.T) {
Expand Down Expand Up @@ -270,6 +257,7 @@ func TestArtifactGeneratorReconciler_ManagedNamespacesExternalFinalizerMalformed
g.Expect(err).To(HaveOccurred())
g.Expect(testClient.Get(ctx, objKey, &swapi.ArtifactGenerator{})).To(Succeed())
g.Expect(testClient.Get(ctx, client.ObjectKey{Name: tgtName}, ns)).To(Succeed())
g.Expect(ns.DeletionTimestamp).To(BeNil())
}

func TestArtifactGeneratorReconciler_ManagedNamespacesExternalFinalizerDesiredState(t *testing.T) {
Expand Down
Loading