From abc31ef17fdb29673426b687f1e2c91c45088051 Mon Sep 17 00:00:00 2001 From: Timofei Larkin Date: Tue, 25 Aug 2026 19:03:23 +0300 Subject: [PATCH 0001/1280] fix(etcd-operator): gate VMServiceScrape on VictoriaMetrics operator CRD The etcd-operator HelmRelease rendered a VMServiceScrape unconditionally, so it failed to install with "no matches for kind VMServiceScrape" on any cluster without the VictoriaMetrics operator CRDs. Wrap it in the same Capabilities.APIVersions gate linstor's podscrape.yaml uses, leaving the metrics Service unconditional. Assisted-By: Claude Signed-off-by: Timofei Larkin --- .../etcd-operator/templates/metrics.yaml | 2 + .../etcd-operator/tests/metrics_test.yaml | 40 +++++++++++++++++++ 2 files changed, 42 insertions(+) create mode 100644 packages/system/etcd-operator/tests/metrics_test.yaml diff --git a/packages/system/etcd-operator/templates/metrics.yaml b/packages/system/etcd-operator/templates/metrics.yaml index ff6afa4bf..1c57f5a7a 100644 --- a/packages/system/etcd-operator/templates/metrics.yaml +++ b/packages/system/etcd-operator/templates/metrics.yaml @@ -15,6 +15,7 @@ spec: targetPort: metrics protocol: TCP --- +{{- if .Capabilities.APIVersions.Has "operator.victoriametrics.com/v1beta1" }} apiVersion: operator.victoriametrics.com/v1beta1 kind: VMServiceScrape metadata: @@ -27,3 +28,4 @@ spec: endpoints: - port: metrics scheme: http +{{- end }} diff --git a/packages/system/etcd-operator/tests/metrics_test.yaml b/packages/system/etcd-operator/tests/metrics_test.yaml new file mode 100644 index 000000000..b9996f873 --- /dev/null +++ b/packages/system/etcd-operator/tests/metrics_test.yaml @@ -0,0 +1,40 @@ +suite: metrics — Service is unconditional, VMServiceScrape is gated on the vmoperator CRD + +templates: + - templates/metrics.yaml + +release: + name: etcd-operator + namespace: cozy-etcd-operator + +capabilities: + apiVersions: [] + +tests: + - it: the metrics Service renders even when the VictoriaMetrics operator CRDs are absent + asserts: + - hasDocuments: + count: 1 + - containsDocument: + apiVersion: v1 + kind: Service + name: etcd-operator-metrics + any: true + + - it: the VMServiceScrape renders alongside the Service when the VictoriaMetrics operator CRD is present + capabilities: + apiVersions: + - operator.victoriametrics.com/v1beta1 + asserts: + - hasDocuments: + count: 2 + - containsDocument: + apiVersion: v1 + kind: Service + name: etcd-operator-metrics + any: true + - containsDocument: + apiVersion: operator.victoriametrics.com/v1beta1 + kind: VMServiceScrape + name: etcd-operator + any: true From 42a27567cee2bd013ba04331b43fb48199c4b148 Mon Sep 17 00:00:00 2001 From: Alexey Artamonov Date: Tue, 15 Sep 2026 23:34:52 +0300 Subject: [PATCH 0002/1280] fix(fluxcd): keep Helm uninstall working during flux-plunger recovery flux-plunger recovers a "has no deployed releases" HelmRelease by briefly suspending it, deleting the stale storage Secret and unsuspending. helm-controller v1.5.x skips the uninstall and drops its finalizer when it handles a delete on a suspended HelmRelease, and it wakes on the same delete event flux-plunger does, so a delete inside that window orphaned the release's DataVolume, PVCs, RBAC and storage Secret. Lifting the suspension on the delete event cannot win that race reliably. Hold the release with a flux-plunger finalizer while it is suspended. The finalizer is applied together with the suspension in one server-side apply. On a delete flux-plunger lifts its suspension and keeps the finalizer, helm-controller reconciles the unsuspended generation and runs the uninstall, and flux-plunger removes the finalizer once helm-controller's own is gone and that generation is observed. This holds whichever controller handles the delete first. A completed recovery lifts the suspension and the finalizer together, and a terminating release never begins recovery. Decide ownership of a suspension by which field manager owns spec.suspend in metadata.managedFields rather than by an annotation. The apiserver transfers the field away the moment an operator, cozyhr resume or a backup controller writes a different value to it, so a later suspension is never misread as flux-plunger's, and one set through the shared flux-client-side-apply manager (platform migrations, the tenant delete hook, a manual kubectl apply) is never claimed. A release deleted under another manager's suspension is left to that manager's decision. Acquire applies without forcing first and, on a conflict, re-fetches and forces only if spec.suspend is still false: a backup controller owns the field at false through a dynamic-client Update, which a non-forced apply can never take, while true is an active suspension to leave alone. Every apply is preconditioned on the resourceVersion and uid of the read that decided on it. Without the resourceVersion, the unforced apply of true over a foreign true is accepted as shared ownership, a window the optimistic-locked merge patch this replaces had closed, and lifting the suspension and the finalizer from a release read as live would delete it without an uninstall if helm-controller had meanwhile handled a delete. Without the uid, an apply to a release that has gone would create an empty one. The apply carries only spec.suspend and the finalizer, so it cannot leak the required spec.interval. Read the release, every re-check and the storage Secret list from the apiserver rather than the informer cache. A lagging cache would let the processed-version guard delete the revision below the one just reclaimed, and the ClusterRole grants secrets get and list but not the watch an informer needs. Emit a Warning when flux-plunger holds a suspension it failed to clear, and Normal events when it leaves an external suspension alone or defers a recovery. An external suspension on a release flux-plunger has recovered before is a Warning instead: it is most likely one an earlier flux-plunger left under the shared manager, which nothing lifts unless an operator does. A release deleted under another manager's suspension is a Normal event when that was a migration's choice, and a Warning when the release carries flux-plunger's processed-version annotation, since then the skipped uninstall is an accident. Keep a single writer with leader election. A second process able to act under the same field manager could clear a suspension the first is still recovering, and no rollout strategy prevents one: the next pod starts as soon as the old one is terminating, and an eviction or a node drain replaces a pod the same way. The old pod keeps its Lease, unreleased, through its stop and drain, and the Lease outlasts both, so the next pod acts only after the old one is done; the price is that a new pod waits for the Lease to run out. The strategy sets maxSurge 0 with maxUnavailable 1 and stays RollingUpdate because existing installs carry the apiserver-defaulted rollingUpdate block and helm-controller applies server-side, where type Recreate over it is rejected on upgrade. Give the finalizer a way out when flux-plunger itself goes. Once the manager has stopped, within a bounded time, and with it every reconcile, flux-plunger drains its finalizers under a deadline that, with the stop, fits inside the pod's termination grace period. A stop that overran its bound is drained too and still reported, and only a pod that led drains. The drain writes its events straight to the apiserver, since the manager's recorder stops with the manager. A recovery in progress is aborted, the suspension and the finalizer lifted together for the next flux-plunger to start again, and a release being deleted has the suspension lifted and keeps the finalizer until helm-controller has run the uninstall. A release helm-controller does not handle in time keeps it. The waiting lives in the controller, where the envtest suites hold it against a real apiserver's generations and finalizers, rather than in a shell script against a model of them. A pre-delete hook on the chart is the backstop for what the drain could not finish, so uninstalling the component never leaves a release that tenant teardown waits on forever. It stops flux-plunger, waits out its grace period, then lifts any remaining suspension and finalizer without waiting again, naming each release it lets go of before helm-controller uninstalled it. It lifts a suspension only where flux-plunger alone holds it, with a JSON patch preconditioned on the resourceVersion and uid it read: kubectl apply --server-side on a release last written by a client-side apply moves that apply's fields to the applying manager and strips every one the body leaves out. The Job's deadline sits under the 300s helm-controller gives a pre-delete hook by default. A Deployment that cannot be stopped or a listing that never succeeds ends the hook before any finalizer is touched, and a finalizer it cannot remove ends it after the sweep; either way it exits non-zero: a failed pre-delete hook leaves the release untouched and helm-controller retries the uninstall, hook included, from a state it can still converge from, where exiting 0 would remove the component and strand the finalizer. A flux-plunger pod still present after its grace period, typically one stuck Terminating on a NotReady node, is only reported, since failing on it would fail every retry until the node returns; because it may still be setting finalizers, they are listed again after the sweep and any found fails the hook. The Job runs once, since helm-controller's retry is the one that starts afresh, and is kept after success so that its report stays readable; helm.sh/hook-output-log-policy would make helm-controller call a nil output writer (fluxcd/helm-controller#1562). A delete still held after ten minutes raises a Warning, and the held state is re-checked on a timer instead of only on helm-controller's next status write. The chart README documents the finalizer and how to clear it. Run the envtest suites on every pull request through a new make target that fetches a kube-apiserver and etcd with a pinned setup-envtest and takes the HelmRelease CRD from the in-tree Flux manifests: the unit tests drive a fake client, and everything the finalizer rests on (apply preconditions, the finalizer set-merge, real managedFields) only holds against a real apiserver. CI caches those binaries, and the target uses them without asking the release index, so a pull request does not depend on their sources being reachable; the control plane gets a longer start timeout because it starts beside the other test goals. Assisted-by: LLM Signed-off-by: Alexey Artamonov --- .github/workflows/pull-requests.yaml | 13 +- Makefile | 25 +- cmd/flux-plunger/main.go | 29 +- hack/bats-runner-contract.bats | 2 +- hack/downstream-trigger-map.bats | 2 +- hack/flux-plunger-fence-hook_test.bats | 728 ++++++ hack/unit-test-parallelism.bats | 2 +- internal/controller/fluxplunger/drain.go | 239 ++ .../fluxplunger/drain_envtest_test.go | 323 +++ .../controller/fluxplunger/flux_plunger.go | 710 +++++- .../fluxplunger/flux_plunger_test.go | 2081 +++++++++++++++++ .../fluxplunger/hook_contract_test.go | 111 + .../controller/fluxplunger/shutdown_test.go | 265 +++ .../fluxplunger/ssa_ownership_envtest_test.go | 722 ++++++ packages/system/flux-plunger/Makefile | 4 + packages/system/flux-plunger/README.md | 31 + .../flux-plunger/templates/deployment.yaml | 31 + .../system/flux-plunger/templates/rbac.yaml | 32 + .../templates/uninstall-fence-cleanup.yaml | 391 ++++ .../flux-plunger/tests/deployment_test.yaml | 58 + .../system/flux-plunger/tests/rbac_test.yaml | 21 + .../tests/uninstall-fence-cleanup_test.yaml | 132 ++ packages/system/flux-plunger/values.yaml | 22 + 23 files changed, 5844 insertions(+), 130 deletions(-) create mode 100644 hack/flux-plunger-fence-hook_test.bats create mode 100644 internal/controller/fluxplunger/drain.go create mode 100644 internal/controller/fluxplunger/drain_envtest_test.go create mode 100644 internal/controller/fluxplunger/flux_plunger_test.go create mode 100644 internal/controller/fluxplunger/hook_contract_test.go create mode 100644 internal/controller/fluxplunger/shutdown_test.go create mode 100644 internal/controller/fluxplunger/ssa_ownership_envtest_test.go create mode 100644 packages/system/flux-plunger/README.md create mode 100644 packages/system/flux-plunger/templates/uninstall-fence-cleanup.yaml create mode 100644 packages/system/flux-plunger/tests/deployment_test.yaml create mode 100644 packages/system/flux-plunger/tests/rbac_test.yaml create mode 100644 packages/system/flux-plunger/tests/uninstall-fence-cleanup_test.yaml diff --git a/.github/workflows/pull-requests.yaml b/.github/workflows/pull-requests.yaml index 97f7cdfe9..b8b06fedf 100644 --- a/.github/workflows/pull-requests.yaml +++ b/.github/workflows/pull-requests.yaml @@ -353,6 +353,17 @@ jobs: sudo "$bats_source/install.sh" /usr/local fi bats --version | grep -qx "Bats $BATS_VERSION" + # setup-envtest and the kube-apiserver and etcd it fetches, so a pull + # request downloads them only when the versions pinned in the Makefile + # change, and an outage at their sources cannot fail unrelated changes. + # The envtest target runs the controller suites a fake client cannot + # stand in for. + - name: Cache envtest binaries + if: needs.plan.outputs.code == 'true' + uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: _out/envtest + key: envtest-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('Makefile') }} # -k is required, not cosmetic: unit-tests and test-controllers are two # independent goals on the same command line, and without -k make stops # handing out new work the moment any unit-tests prerequisite fails — @@ -361,7 +372,7 @@ jobs: # goals keep running; the job still fails overall on any red target. - name: Run unit and controller tests if: needs.plan.outputs.code == 'true' - run: make unit-tests test-controllers -j4 -k --output-sync=target + run: make unit-tests test-controllers test-controllers-envtest -j4 -k --output-sync=target - name: Run Bats unit tests for docs-only changes if: needs.plan.outputs.code == 'false' run: make bats-unit-tests diff --git a/Makefile b/Makefile index 412568384..99de4c38e 100644 --- a/Makefile +++ b/Makefile @@ -1,4 +1,4 @@ -.PHONY: manifests assets prepare-env prepare-env-container unit-tests helm-unit-tests bats-unit-tests bats-unit-files-check bats-posix-compat-tests print-bats-unit-files print-bats-posix-compat-files print-bats-jobs rd-presets-check migrations-target-check test test-controllers test-backport-audit preflight +.PHONY: manifests assets prepare-env prepare-env-container unit-tests helm-unit-tests bats-unit-tests bats-unit-files-check bats-posix-compat-tests print-bats-unit-files print-bats-posix-compat-files print-bats-jobs rd-presets-check migrations-target-check test test-controllers test-controllers-envtest test-backport-audit preflight include hack/common-envs.mk @@ -163,6 +163,29 @@ go-module-tests: test-controllers: go test ./internal/... -count=1 +# Controller suites that need a real apiserver (build tag `envtest`): server-side +# apply ownership, apply preconditions and finalizer handling, which a fake client +# does not implement. setup-envtest fetches the kube-apiserver and etcd release +# pinned by ENVTEST_K8S_VERSION into _out/envtest; the HelmRelease CRD comes from +# the in-tree Flux manifests (envtest skips their non-CRD objects). CI runs it +# next to test-controllers. Only the packages listed below are compiled, so a +# package that gains an envtest suite has to be added here. +# +# setup-envtest itself is built into _out/envtest too, and binaries already there +# are used without asking the release index, so a warm _out/envtest (CI caches +# it) needs no network at all. +ENVTEST_K8S_VERSION ?= 1.35.0 +SETUP_ENVTEST_VERSION ?= v0.0.0-20260305142021-f9589b9f2b9d +ENVTEST_DIR = $(CURDIR)/_out/envtest +SETUP_ENVTEST = $(ENVTEST_DIR)/bin/setup-envtest-$(SETUP_ENVTEST_VERSION) +$(SETUP_ENVTEST): + GOBIN=$(ENVTEST_DIR)/bin go install sigs.k8s.io/controller-runtime/tools/setup-envtest@$(SETUP_ENVTEST_VERSION) + mv $(ENVTEST_DIR)/bin/setup-envtest $@ +test-controllers-envtest: $(SETUP_ENVTEST) + KUBEBUILDER_ASSETS="$$($(SETUP_ENVTEST) use $(ENVTEST_K8S_VERSION) --installed-only --bin-dir $(ENVTEST_DIR) --print path 2>/dev/null || $(SETUP_ENVTEST) use $(ENVTEST_K8S_VERSION) --bin-dir $(ENVTEST_DIR) --print path)" \ + HELMRELEASE_CRD_DIR=$(CURDIR)/internal/fluxinstall/manifests \ + go test -tags envtest -run '^TestEnvtest' ./internal/controller/fluxplunger/... -count=1 + # Black-box golden test for cmd/check-readiness. Builds the binary and runs it # against a mock kubectl (fixtures under test/check-readiness/testdata), # diffing stdout/stderr/exit against golden files. Regenerate goldens with: diff --git a/cmd/flux-plunger/main.go b/cmd/flux-plunger/main.go index 13fe88cd3..a45ef71f3 100644 --- a/cmd/flux-plunger/main.go +++ b/cmd/flux-plunger/main.go @@ -20,6 +20,7 @@ import ( "crypto/tls" "flag" "os" + "time" // Import all Kubernetes client auth plugins (e.g. Azure, GCP, OIDC, etc.) // to ensure that exec-entrypoint and run can make use of them. @@ -56,6 +57,7 @@ func main() { var probeAddr string var secureMetrics bool var enableHTTP2 bool + var shutdownDrainTimeout time.Duration var tlsOpts []func(*tls.Config) flag.StringVar(&metricsAddr, "metrics-bind-address", "0", "The address the metrics endpoint binds to. "+ @@ -68,6 +70,9 @@ func main() { "If set, the metrics endpoint is served securely via HTTPS. Use --metrics-secure=false to use HTTP instead.") flag.BoolVar(&enableHTTP2, "enable-http2", false, "If set, HTTP/2 will be enabled for the metrics server") + flag.DurationVar(&shutdownDrainTimeout, fluxplunger.ShutdownDrainTimeoutFlag, 75*time.Second, + "How long to spend giving up the uninstall fences flux-plunger holds before it exits. "+ + "Keep it inside the pod's termination grace period.") opts := zap.Options{ Development: false, @@ -102,31 +107,25 @@ func main() { TLSOpts: tlsOpts, } - mgr, err := ctrl.NewManager(ctrl.GetConfigOrDie(), ctrl.Options{ + mgrOpts := ctrl.Options{ Scheme: scheme, Metrics: metricsServerOptions, HealthProbeBindAddress: probeAddr, LeaderElection: enableLeaderElection, LeaderElectionID: "flux-plunger.cozystack.io", - // LeaderElectionReleaseOnCancel defines if the leader should step down voluntarily - // when the Manager ends. This requires the binary to immediately end when the - // Manager is stopped, otherwise, this setting is unsafe. Setting this significantly - // speeds up voluntary leader transitions as the new leader don't have to wait - // LeaseDuration time first. - // - // In the default scaffold provided, the program ends immediately after - // the manager stops, so would be fine to enable this option. However, - // if you are doing or is intended to do any operation such as perform cleanups - // after the manager stops then its usage might be unsafe. - // LeaderElectionReleaseOnCancel: true, - }) + } + // The Lease is held, not released, through the drain after the manager stops. + fluxplunger.ApplyShutdownTimings(&mgrOpts, shutdownDrainTimeout) + mgr, err := ctrl.NewManager(ctrl.GetConfigOrDie(), mgrOpts) if err != nil { setupLog.Error(err, "unable to create manager") os.Exit(1) } if err = (&fluxplunger.FluxPlunger{ - Client: mgr.GetClient(), + Client: mgr.GetClient(), + APIReader: mgr.GetAPIReader(), + Recorder: mgr.GetEventRecorderFor("flux-plunger"), }).SetupWithManager(mgr); err != nil { setupLog.Error(err, "unable to create controller", "controller", "FluxPlunger") os.Exit(1) @@ -144,7 +143,7 @@ func main() { } setupLog.Info("starting manager") - if err := mgr.Start(ctrl.SetupSignalHandler()); err != nil { + if err := fluxplunger.RunManager(ctrl.SetupSignalHandler(), mgr, shutdownDrainTimeout); err != nil { setupLog.Error(err, "problem running manager") os.Exit(1) } diff --git a/hack/bats-runner-contract.bats b/hack/bats-runner-contract.bats index 22426edb2..a50ed0ba5 100644 --- a/hack/bats-runner-contract.bats +++ b/hack/bats-runner-contract.bats @@ -75,7 +75,7 @@ brc_write_parallel_stub() { code_command=$(yq -r '.jobs.checks.steps[] | select(.name == "Run unit and controller tests") | .run' "$BRC_WORKFLOW") docs_command=$(yq -r '.jobs.checks.steps[] | select(.name == "Run Bats unit tests for docs-only changes") | .run' "$BRC_WORKFLOW") [ -z "$lint_skip" ] - [ "$code_command" = 'make unit-tests test-controllers -j4 -k --output-sync=target' ] + [ "$code_command" = 'make unit-tests test-controllers test-controllers-envtest -j4 -k --output-sync=target' ] [ "$docs_command" = 'make bats-unit-tests' ] } diff --git a/hack/downstream-trigger-map.bats b/hack/downstream-trigger-map.bats index b26996755..c5ebf6af3 100644 --- a/hack/downstream-trigger-map.bats +++ b/hack/downstream-trigger-map.bats @@ -119,7 +119,7 @@ map_section() { [ "$code_if" = "needs.plan.outputs.code == 'true'" ] [ "$docs_if" = "needs.plan.outputs.code == 'false'" ] [ "$docs_run" = 'make bats-unit-tests' ] - [ "$code_run" = 'make unit-tests test-controllers -j4 -k --output-sync=target' ] + [ "$code_run" = 'make unit-tests test-controllers test-controllers-envtest -j4 -k --output-sync=target' ] } @test "the trigger map and the PR-template checklist list the same repositories" { diff --git a/hack/flux-plunger-fence-hook_test.bats b/hack/flux-plunger-fence-hook_test.bats new file mode 100644 index 000000000..14cd7f835 --- /dev/null +++ b/hack/flux-plunger-fence-hook_test.bats @@ -0,0 +1,728 @@ +#!/usr/bin/env bats +# Behavioural test for flux-plunger's pre-delete hook +# (packages/system/flux-plunger/templates/uninstall-fence-cleanup.yaml), the +# backstop that releases what flux-plunger's own shutdown drain could not. +# +# The script is extracted from the rendered chart and RUN against a fake kubectl +# that keeps each HelmRelease's finalizers, suspension owner, resourceVersion, +# generation and observed generation in files, and a fake clock. The fake answers +# the hook's templates only when they ask the right question (the exact fence +# literal, the f:suspend field of flux-plunger's Apply entry, the exact +# "helm-controller has not handled it" predicate), lists a release once per fence +# entry as the real template does unless the template collapses them, bumps a +# release's generation when its suspension is lifted as the apiserver does, lifts +# a suspension only as a JSON patch preconditioned on the resourceVersion and uid +# it read and never one another manager also holds, refuses kubectl apply, and +# applies a finalizer removal only when it is the guarded test-then-remove at an +# index that holds the fence. The helm-unittest +# suites in packages/system/flux-plunger/tests match the manifest text instead. +# +# CI runs this file under Bats through `make bats-unit-tests`. It also remains +# compatible with the legacy `hack/cozytest.sh` translator, so each @test builds +# its own fixture and removes it at the end of the body instead of using +# setup()/teardown(). No EXIT trap: docs/agents/e2e-testing.md bans them in +# hack/*.bats. +# +# Run with: bats hack/flux-plunger-fence-hook_test.bats + +load test_helper + +CHART=packages/system/flux-plunger +JOB=flux-plunger-uninstall-fence-cleanup +FENCE=flux-plunger.cozystack.io/uninstall-fence +HELMFIN=finalizers.fluxcd.io + +# render_hook [helm args] +# Extract the hook Job's shell script and activeDeadlineSeconds, the script's pod +# wait, retry window, selector and Deployment name, and the Deployment's grace +# period, name and pod labels, and the hook Role's resourceNames. The non-empty +# checks are early `return 1`s: hack/cozytest.sh rewrites every line matching ^}$ +# into `return 0` plus `}`, helpers included. +render_hook() { + out=$1 + shift + helm template flux-plunger "$CHART" --namespace cozy-fluxcd "$@" > "$out.all" + yq eval "select(.kind == \"Job\" and .metadata.name == \"$JOB\") | .spec.template.spec.containers[0].command[2]" "$out.all" > "$out" + [ -s "$out" ] || return 1 + DEADLINE=$(yq eval "select(.kind == \"Job\" and .metadata.name == \"$JOB\") | .spec.activeDeadlineSeconds" "$out.all") + GRACE=$(yq eval 'select(.kind == "Deployment") | .spec.template.spec.terminationGracePeriodSeconds' "$out.all") + DEPLOY_NAME=$(yq eval 'select(.kind == "Deployment") | .metadata.name' "$out.all") + ROLE_DEPLOY=$(yq eval "select(.kind == \"Role\" and .metadata.name == \"$JOB\") | .rules[0].resourceNames[0]" "$out.all") + POD_LABELS=$(yq eval 'select(.kind == "Deployment") | .spec.template.metadata.labels | to_entries | map(.key + "=" + .value) | join(",")' "$out.all") + POD_WAIT=$(sed -n 's/^ *pod_wait=\([0-9][0-9]*\)$/\1/p' "$out") + WINDOW=$(sed -n 's/.*retry_until=\$(( \$(date +%s) + \([0-9][0-9]*\) )).*/\1/p' "$out") + SCRIPT_DEPLOY=$(sed -n 's/^ *deploy=\([a-z0-9-]*\)$/\1/p' "$out") + POD_SELECTOR=$(sed -n 's/.*--selector \([^ ]*\).*/\1/p' "$out" | sort -u) + for v in "$DEADLINE" "$GRACE" "$DEPLOY_NAME" "$ROLE_DEPLOY" "$POD_LABELS" "$POD_WAIT" "$WINDOW" "$SCRIPT_DEPLOY" "$POD_SELECTOR"; do + [ -n "$v" ] || return 1 + done +} + +# add_release ... +# One HelmRelease, its finalizers in order, one per line, at generation 1 and +# observed, resourceVersion 1, suspended. +add_release() { + st=$1 ns=$2 name=$3 + shift 3 + : > "$st/$ns@$name.fin" + for f in "$@"; do + echo "$f" >> "$st/$ns@$name.fin" + done + echo 1 > "$st/$ns@$name.gen" + echo 1 > "$st/$ns@$name.obs" + echo 1 > "$st/$ns@$name.rv" + touch "$st/$ns@$name.suspended" +} + +# fences_left : how many fence entries remain across all releases. +fences_left() { + cat "$1"/*.fin 2>/dev/null | grep --count --line-regexp "$FENCE" +} + +# write_fakes +# A fake kubectl, sleep and date sharing one simulated clock in $CLOCK (seconds +# since the hook started): sleep advances it, date +%s reads it. kubectl logs +# every call to $KLOG and works on the release state in $STATE: +# * @.fin finalizers, in order; +# * @.gen/.obs metadata.generation and status.observedGeneration; +# lifting a suspension bumps the generation; +# * @.rv resourceVersion, bumped by every write; +# * @.suspended spec.suspend is true; +# * @.deleting the release is being deleted; +# * @.owned flux-plunger's Apply entry owns spec.suspend, +# holding what a correct ownership template prints; +# * @.coowned another manager also owns spec.suspend at true; +# flux-plunger's own path leaves such a suspension; +# * @.applyonly flux-plunger has an Apply entry that does not own +# spec.suspend; +# * @.updateowned flux-plunger owns spec.suspend through an Update +# entry, as an earlier flux-plunger's merge patch left +# it; the controller does not take that one as its own; +# * @.vanish the release is deleted the first time it is read +# after the listing; reading it then is NotFound +# unless --ignore-not-found is given; +# * @.readd something puts the fence back after every removal, +# as a flux-plunger still running would; +# * @.latefence the release gains the fence right after the first +# listing, as one a running flux-plunger fences would; +# * deploy.absent the flux-plunger Deployment does not exist; +# * pods.stuck flux-plunger's pod never goes: the wait runs to its +# --timeout on the clock (a negative one, as kubectl +# reads it, for a week) and fails, and the pod lists; +# * scale.slow seconds a successful scale-down takes; +# * .fail a count of calls to fail first, for the Deployment +# read (deploy), the scale-down (scale), the pod wait +# for a reason other than pods (wait), the listing +# (list), a listing after the first (relist), the +# pod listing (pods), a release's ownership read +# (@.ownedread), unsuspend +# (@.apply), unsuspend racing another +# write (@.applyconflict) or finalizer patch +# (@.patch); +# * list.partial.fail a count of listings that print what they have, then +# fail, as kubectl does on a partial error. +# Releases whose suspension was lifted are appended to $STATE/unsuspended. +# No line below is a bare column-0 closing brace, so cozytest.sh leaves it intact. +write_fakes() { + cat > "$1/kubectl" <<'KEOF' +#!/bin/sh +echo "$*" >> "$KLOG" +FENCE=flux-plunger.cozystack.io/uninstall-fence +HELMFIN=finalizers.fluxcd.io +# The one predicate that tells a release helm-controller has not yet handled in +# its unsuspended form: being deleted, no longer held by its finalizer, and its +# latest generation not yet observed. +UNHANDLED='{{if .metadata.deletionTimestamp}}{{$held := false}}{{range .metadata.finalizers}}{{if eq . "finalizers.fluxcd.io"}}{{$held = true}}{{end}}{{end}}{{if and (not $held) (ne (printf "%v" .status.observedGeneration) (printf "%v" .metadata.generation))}}' +# In the hook's pod kubectl finds the API server only through the in-cluster +# config, which client-go stops falling back to once a client override such as +# --request-timeout is set: the call then goes to localhost:8080 and fails. +case " $* " in + *" --request-timeout"*|*" --server="*|*" --server "*|*" --token"*) + echo "The connection to the server localhost:8080 was refused" >&2 + exit 1 ;; +esac +take_fail() { + [ -s "$1.fail" ] || return 1 + n=$(cat "$1.fail") + [ "$n" -gt 0 ] || return 1 + echo $((n - 1)) > "$1.fail" + return 0 + } +bump_rv() { + echo $(( $(cat "$1.rv") + 1 )) > "$1.rv" + } +ns="" name="" payload="" tmpl="" type="" fm="" all=no kind="" verb="" ignore=no timeout="" for="" ssa=no file="" +while [ $# -gt 0 ]; do + case "$1" in + --namespace) ns=$2; shift ;; + --all-namespaces) all=yes ;; + --output) tmpl=$2; shift ;; + --type) type=$2; shift ;; + --patch) payload=$2; shift ;; + --field-manager) fm=$2; shift ;; + --filename) file=$2; shift ;; + --selector) shift ;; + --ignore-not-found) ignore=yes ;; + --server-side) ssa=yes ;; + --timeout=*) timeout=${1#--timeout=}; timeout=${timeout%s} ;; + --for=*) for=${1#--for=} ;; + --*) ;; + get|patch|scale|wait|apply) [ -n "$verb" ] || verb=$1 ;; + helmreleases.helm.toolkit.fluxcd.io) kind=hr ;; + deployment) kind=deployment ;; + pod) kind=pod ;; + *) if [ -n "$kind" ] && [ -z "$name" ]; then name=$1; fi ;; + esac + shift +done +case "$verb" in + scale) + if take_fail "$STATE/scale"; then echo "fake: the scale-down was rejected" >&2; exit 1; fi + if [ -s "$STATE/scale.slow" ]; then echo $(( $(cat "$CLOCK") + $(cat "$STATE/scale.slow") )) > "$CLOCK"; fi + echo "deployment.apps/$name scaled" + exit 0 ;; + wait) + if [ "$for" != delete ]; then echo "fake: waiting on '$for', not on the pods being gone" >&2; exit 64; fi + if take_fail "$STATE/wait"; then echo "error: watch closed before the condition was met" >&2; exit 1; fi + if [ -e "$STATE/pods.stuck" ]; then + now=$(cat "$CLOCK") + # kubectl wait: zero checks once, a negative timeout waits for a week. + [ "$timeout" -ge 0 ] || timeout=604800 + echo $((now + timeout)) > "$CLOCK" + echo "error: timed out waiting for the condition on pods/flux-plunger-0" >&2 + exit 1 + fi + exit 0 ;; +esac +if [ "$kind" = pod ] && [ "$verb" = get ]; then + if take_fail "$STATE/pods"; then echo "fake: the pod listing timed out" >&2; exit 1; fi + [ -e "$STATE/pods.stuck" ] && echo "pod/flux-plunger-0" + exit 0 +fi +if [ "$kind" = deployment ] && [ "$verb" = get ]; then + if take_fail "$STATE/deploy"; then echo "fake: the Deployment read timed out" >&2; exit 1; fi + [ -e "$STATE/deploy.absent" ] || echo "deployment.apps/$name" + exit 0 +fi +if [ "$verb" = apply ]; then + # kubectl apply --server-side migrates every field kubectl-client-side-apply + # owns to the applying manager and then re-applies, so a minimal manifest strips + # those fields from a release created with a client-side kubectl apply. + echo "fake: kubectl apply takes over and strips client-side-apply fields" >&2 + exit 64 +fi +rel="$STATE/$ns@$name" +if [ "$verb" = get ] && [ -z "$name" ]; then + if take_fail "$STATE/list"; then echo "fake: the listing was throttled" >&2; exit 1; fi + if [ -e "$STATE/listed" ] && take_fail "$STATE/relist"; then echo "fake: the second listing was throttled" >&2; exit 1; fi + partial=no + if take_fail "$STATE/list.partial"; then partial=yes; fi + case "$tmpl" in *"eq . \"$FENCE\""*) ;; *) exit 0 ;; esac + for f in "$STATE"/*@*.fin; do + [ -e "$f" ] || continue + r=$(basename "$f" .fin) + rns=${r%@*} + if [ "$all" = yes ] || [ "$rns" = "$ns" ]; then + case "$tmpl" in + *'{{if $fenced}}'*) grep -q -x "$FENCE" "$f" && printf '%s/%s\n' "$rns" "${r#*@}" ;; + *) grep -x "$FENCE" "$f" | while read -r _; do printf '%s/%s\n' "$rns" "${r#*@}"; done ;; + esac + fi + done + for l in "$STATE"/*@*.latefence; do + [ -e "$l" ] || continue + echo "$FENCE" >> "${l%.latefence}.fin" + rm -f "$l" + done + if [ "$partial" = yes ]; then echo "fake: an error occurred partway through the listing" >&2; exit 1; fi + touch "$STATE/listed" + exit 0 +fi +if [ "$verb" = get ]; then + if [ -e "$rel.vanish" ]; then + rm -f "$rel.vanish" "$rel.fin" + fi + if [ ! -e "$rel.fin" ]; then + [ "$ignore" = yes ] && exit 0 + echo "Error from server (NotFound): helmreleases.helm.toolkit.fluxcd.io \"$name\" not found" >&2 + exit 1 + fi + case "$tmpl" in + *managedFields*) + if take_fail "$rel.ownedread"; then + echo "Error executing template: an error blob on stdout" + exit 1 + fi + case "$tmpl" in *'.metadata.resourceVersion}} {{.metadata.uid}}'*) printf '%s uid-%s ' "$(cat "$rel.rv")" "$name" ;; esac + case "$tmpl" in *'{{if .spec.suspend}}'*) [ -e "$rel.suspended" ] || exit 0 ;; esac + case "$tmpl" in *'eq .manager "flux-plunger"'*) ;; *) exit 0 ;; esac + [ -e "$rel.owned" ] && cat "$rel.owned" + case "$tmpl" in *'(eq .operation "Apply")'*) ;; *) [ -e "$rel.updateowned" ] && echo yes ;; esac + case "$tmpl" in *'"f:suspend"'*) ;; *) [ -e "$rel.applyonly" ] && echo yes ;; esac + # Another manager's entry also owning spec.suspend. + case "$tmpl" in *'ne .manager "flux-plunger"'*) [ -e "$rel.coowned" ] && echo other ;; esac + exit 0 ;; + *deletionTimestamp*) + case "$tmpl" in *"$UNHANDLED"*) ;; *) exit 0 ;; esac + [ -e "$rel.deleting" ] || exit 0 + grep -q -x "$HELMFIN" "$rel.fin" && exit 0 + [ "$(cat "$rel.gen")" = "$(cat "$rel.obs")" ] && exit 0 + printf 'unhandled' + exit 0 ;; + *'range $i, $f'*) + case "$tmpl" in + *"eq \$f \"$FENCE\""*) grep -n -x "$FENCE" "$rel.fin" | cut -d: -f1 | awk '{ printf "%d ", $1 - 1 }' ;; + esac + exit 0 ;; + esac +fi +if [ "$verb" = patch ]; then + [ -e "$rel.fin" ] || { echo "fake: $ns/$name not found" >&2; exit 1; } + case "$type" in + json) + case "$payload" in + *'"path":"/spec/suspend"'*) + if take_fail "$rel.apply"; then echo "fake: the unsuspend was rejected" >&2; exit 1; fi + if take_fail "$rel.applyconflict"; then bump_rv "$rel"; fi + if [ "$fm" != flux-plunger ]; then echo "fake: unsuspend not written as flux-plunger" >&2; exit 64; fi + want="[{\"op\":\"test\",\"path\":\"/metadata/resourceVersion\",\"value\":\"$(cat "$rel.rv")\"},{\"op\":\"test\",\"path\":\"/metadata/uid\",\"value\":\"uid-$name\"},{\"op\":\"replace\",\"path\":\"/spec/suspend\",\"value\":false}]" + if [ "$payload" != "$want" ]; then echo "fake: testing value /metadata/resourceVersion failed or not a preconditioned unsuspend: $payload" >&2; exit 1; fi + if [ -e "$rel.coowned" ]; then echo "fake: cleared a suspension another manager also holds" >&2; exit 64; fi + rm -f "$rel.owned" "$rel.applyonly" "$rel.suspended" + echo $(( $(cat "$rel.gen") + 1 )) > "$rel.gen" + echo "$ns/$name" >> "$STATE/unsuspended" + bump_rv "$rel" + exit 0 ;; + esac + if take_fail "$rel.patch"; then echo "fake: the patch was rejected" >&2; exit 1; fi + i=$(printf '%s' "$payload" | sed -n 's#^\[{"op":"test","path":"/metadata/finalizers/\([0-9][0-9]*\)","value":"flux-plunger\.cozystack\.io/uninstall-fence"},{"op":"remove","path":"/metadata/finalizers/\1"}\]$#\1#p') + [ -n "$i" ] || { echo "fake: not a guarded fence removal: $payload" >&2; exit 1; } + [ "$(sed -n "$((i + 1))p" "$rel.fin")" = "$FENCE" ] || { echo "fake: testing value /metadata/finalizers/$i failed" >&2; exit 1; } + sed -i.bak "$((i + 1))d" "$rel.fin" + [ -e "$rel.readd" ] && echo "$FENCE" >> "$rel.fin" + bump_rv "$rel" + now=$(cat "$CLOCK") + echo $((now + 1)) > "$CLOCK" + exit 0 ;; + esac + echo "fake: a $type patch; spec.suspend is lifted only by the guarded JSON patch" >&2 + exit 64 +fi +echo "fake kubectl: unexpected call" >&2 +exit 64 +KEOF + cat > "$1/sleep" <<'SEOF' +#!/bin/sh +now=$(cat "$CLOCK") +echo $((now + $1)) > "$CLOCK" +SEOF + cat > "$1/date" <<'DEOF' +#!/bin/sh +cat "$CLOCK" +DEOF + chmod 0755 "$1/kubectl" "$1/sleep" "$1/date" +} + +# prepare : fakes, script, empty state, clock at zero. +prepare() { + write_fakes "$1" + render_hook "$1/hook.sh" || return 1 + mkdir "$1/state" + export KLOG="$1/calls" CLOCK="$1/clock" STATE="$1/state" NAMESPACE=cozy-fluxcd + echo 0 > "$CLOCK" + : > "$KLOG" +} + +# run_hook : run the script, its output in /out, its status in $status. +run_hook() { + status=0 + PATH="$1:$PATH" sh "$1/hook.sh" > "$1/out" 2>&1 || status=$? + cat "$1/out" + echo "status=$status elapsed=$(cat "$CLOCK")s" +} + +@test "the hook waits for flux-plunger's own drain, fits under helm's bound, and stops the Deployment the chart deploys" { + tmp=$(mktemp -d) + prepare "$tmp" + echo "deadline=${DEADLINE}s grace=${GRACE}s pod-wait=${POD_WAIT}s window=${WINDOW}s deploy=$SCRIPT_DEPLOY/$DEPLOY_NAME/$ROLE_DEPLOY selector=$POD_SELECTOR labels=$POD_LABELS" + # helm-controller runs the pre-delete hook under the release's uninstall + # timeout, 300s by default, and the operator sets none; that clock starts + # when the hook is created, so the Job's own deadline has to end first. + [ "$DEADLINE" -lt 300 ] + # Retries stop a minute before the Job is killed, the pod wait covers the + # pod's grace period, and fits inside the retry window. + [ $((DEADLINE - WINDOW)) -ge 60 ] + [ "$POD_WAIT" -gt "$GRACE" ] + [ "$POD_WAIT" -lt "$WINDOW" ] + # The wait must find flux-plunger's pod: kubectl wait --for=delete succeeds at + # once on a selector that matches nothing. + [ "$POD_SELECTOR" = "$POD_LABELS" ] + # A name the chart does not deploy reads as a Deployment already gone. + [ "$SCRIPT_DEPLOY" = "$DEPLOY_NAME" ] + [ "$ROLE_DEPLOY" = "$DEPLOY_NAME" ] + rm -rf "$tmp" +} + +@test "at the largest grace period the chart accepts the hook still fits under helm's bound" { + tmp=$(mktemp -d) + render_hook "$tmp/hook.sh" --set shutdownGracePeriodSeconds=140 + echo "deadline=$DEADLINE pod-wait=$POD_WAIT window=$WINDOW" + [ "$DEADLINE" -lt 300 ] + [ $((DEADLINE - WINDOW)) -ge 60 ] + [ "$POD_WAIT" -gt 140 ] + [ "$POD_WAIT" -lt "$WINDOW" ] + rm -rf "$tmp" +} + +@test "the hook lifts only a suspension flux-plunger alone holds and removes only the fence, at the index it holds" { + tmp=$(mktemp -d) + prepare "$tmp" + add_release "$STATE" tenant-a app-a example.com/keep "$FENCE" "$HELMFIN" + echo yes > "$STATE/tenant-a@app-a.owned" + add_release "$STATE" tenant-b app-b "$FENCE" + # Two managedFields entries would print the ownership mark twice. + add_release "$STATE" tenant-c app-c example.com/one example.com/two "$FENCE" + echo yesyes > "$STATE/tenant-c@app-c.owned" + # Someone else removes this fence between the listing and the hook's next read. + add_release "$STATE" tenant-d app-d "$FENCE" example.com/keep + touch "$STATE/tenant-d@app-d.vanish" + # flux-plunger applied to this release, but its entry does not own spec.suspend. + add_release "$STATE" tenant-e app-e "$FENCE" + touch "$STATE/tenant-e@app-e.applyonly" + # A successful read that prints something other than the ownership mark. + add_release "$STATE" tenant-f app-f "$FENCE" + echo unrelated > "$STATE/tenant-f@app-f.owned" + # The apiserver accepts a finalizer listed twice; both copies go, and the + # release is counted once. + add_release "$STATE" tenant-g app-g "$FENCE" example.com/keep "$FENCE" + # Another manager also holds spec.suspend at true: its suspension stands, as + # the controller's relinquish leaves it. + add_release "$STATE" tenant-h app-h "$FENCE" + echo yes > "$STATE/tenant-h@app-h.owned" + touch "$STATE/tenant-h@app-h.coowned" + # flux-plunger owns spec.suspend at false, as after its own unsuspend: there is + # nothing to lift, and no write. + add_release "$STATE" tenant-i app-i "$FENCE" + echo yes > "$STATE/tenant-i@app-i.owned" + rm "$STATE/tenant-i@app-i.suspended" + # A suspension an earlier flux-plunger left through a merge patch is not one + # the controller takes as its own, so the hook leaves it too. + add_release "$STATE" tenant-j app-j "$FENCE" + touch "$STATE/tenant-j@app-j.updateowned" + + run_hook "$tmp" + + echo "unsuspended=$(tr '\n' ' ' < "$STATE/unsuspended" 2>/dev/null)" + [ "$status" -eq 0 ] + [ "$(fences_left "$STATE")" -eq 0 ] + [ "$(sort "$STATE/unsuspended" | tr '\n' ' ')" = "tenant-a/app-a tenant-c/app-c " ] + [ -e "$STATE/tenant-h@app-h.suspended" ] + [ -e "$STATE/tenant-j@app-j.suspended" ] + [ "$(tr '\n' ' ' < "$STATE/tenant-a@app-a.fin")" = "example.com/keep $HELMFIN " ] + [ "$(tr '\n' ' ' < "$STATE/tenant-c@app-c.fin")" = "example.com/one example.com/two " ] + [ "$(tr '\n' ' ' < "$STATE/tenant-g@app-g.fin")" = "example.com/keep " ] + grep -q -x 'released 10 of 10 fenced HelmReleases, 0 without an uninstall' "$tmp/out" + # Nothing the fake refused, and the pod wait asked the question it answers. + if grep -q -e '^fake:' -e 'the wait for flux-plunger pods to go failed' "$tmp/out"; then + echo "FAIL: the hook made a call the fake refused" + false + fi + rm -rf "$tmp" +} + +@test "a release deleted before helm-controller handled it is released, and named as deleted without an uninstall" { + tmp=$(mktemp -d) + prepare "$tmp" + # helm-controller dropped its finalizer on the suspended delete; the fence is + # all that holds it, and flux-plunger's drain did not get it through. Lifting + # the suspension bumps the generation, which helm-controller has not observed. + add_release "$STATE" tenant-a app-a "$FENCE" + touch "$STATE/tenant-a@app-a.deleting" + echo yes > "$STATE/tenant-a@app-a.owned" + # Being deleted, but helm-controller's finalizer still holds it: helm-controller + # will run the uninstall once the fence is gone. + add_release "$STATE" tenant-b app-b "$HELMFIN" "$FENCE" + touch "$STATE/tenant-b@app-b.deleting" + echo yes > "$STATE/tenant-b@app-b.owned" + # Being deleted, helm-controller has handled its current generation. + add_release "$STATE" tenant-c app-c "$FENCE" + touch "$STATE/tenant-c@app-c.deleting" + # Its uninstall completes mid-sweep, and the release is gone when read. + add_release "$STATE" tenant-d app-d "$FENCE" + touch "$STATE/tenant-d@app-d.vanish" + + run_hook "$tmp" + + [ "$status" -eq 0 ] + [ "$(fences_left "$STATE")" -eq 0 ] + grep -q -x "released $FENCE from tenant-a/app-a without an uninstall: helm-controller had not handled it" "$tmp/out" + grep -q -x "released $FENCE from tenant-b/app-b" "$tmp/out" + grep -q -x "released $FENCE from tenant-c/app-c" "$tmp/out" + grep -q -x "released $FENCE from tenant-d/app-d" "$tmp/out" + grep -q -x 'released 4 of 4 fenced HelmReleases, 1 without an uninstall' "$tmp/out" + rm -rf "$tmp" +} + +@test "transient API failures are retried, and a failed attempt's output is not taken as an answer" { + tmp=$(mktemp -d) + prepare "$tmp" + echo 2 > "$STATE/deploy.fail" + echo 2 > "$STATE/scale.fail" + echo 2 > "$STATE/list.fail" + # Two listings that print what they have and then fail: their output must + # not be added to the one that succeeds. + echo 2 > "$STATE/list.partial.fail" + add_release "$STATE" tenant-a app-a "$FENCE" + echo 2 > "$STATE/tenant-a@app-a.patch.fail" + # Not flux-plunger's suspension; a failed ownership read prints an error blob + # to stdout first. + add_release "$STATE" tenant-b app-b "$FENCE" + echo 2 > "$STATE/tenant-b@app-b.ownedread.fail" + add_release "$STATE" tenant-d app-d "$FENCE" + echo yes > "$STATE/tenant-d@app-d.owned" + echo 2 > "$STATE/tenant-d@app-d.apply.fail" + # A write lands between the ownership read and the unsuspend: the patch is + # rejected on its resourceVersion, and the decision is read again. + add_release "$STATE" tenant-e app-e "$FENCE" + echo yes > "$STATE/tenant-e@app-e.owned" + echo 1 > "$STATE/tenant-e@app-e.applyconflict.fail" + + run_hook "$tmp" + + [ "$status" -eq 0 ] + [ "$(fences_left "$STATE")" -eq 0 ] + [ "$(sort "$STATE/unsuspended" | tr '\n' ' ')" = "tenant-d/app-d tenant-e/app-e " ] + [ "$(grep --count "released $FENCE from" "$tmp/out")" -eq 4 ] + grep -q -x 'released 4 of 4 fenced HelmReleases, 0 without an uninstall' "$tmp/out" + rm -rf "$tmp" +} + +@test "a release that cannot be read, unsuspended or unfenced fails the hook, keeps its fence and is named" { + tmp=$(mktemp -d) + prepare "$tmp" + add_release "$STATE" tenant-a app-a "$FENCE" + echo 9999 > "$STATE/tenant-a@app-a.patch.fail" + add_release "$STATE" tenant-b app-b "$FENCE" + echo 9999 > "$STATE/tenant-b@app-b.ownedread.fail" + # Its suspension is flux-plunger's and cannot be lifted: without the fence a + # deleted release that is still suspended is removed without an uninstall. + add_release "$STATE" tenant-c app-c "$FENCE" + echo yes > "$STATE/tenant-c@app-c.owned" + echo 9999 > "$STATE/tenant-c@app-c.apply.fail" + add_release "$STATE" tenant-d app-d "$FENCE" + + run_hook "$tmp" + + [ "$status" -ne 0 ] + grep -q '^NOT released tenant-a/app-a' "$tmp/out" + grep -q '^NOT released tenant-b/app-b' "$tmp/out" + grep -q '^NOT released tenant-c/app-c' "$tmp/out" + if grep -q "released $FENCE from tenant-[abc]/" "$tmp/out"; then + echo "FAIL: a release left fenced was reported released" + false + fi + grep -q -x 'released 1 of 4 fenced HelmReleases, 0 without an uninstall' "$tmp/out" + [ "$(fences_left "$STATE")" -eq 3 ] + [ -e "$STATE/tenant-c@app-c.owned" ] + [ "$(cat "$CLOCK")" -lt "$DEADLINE" ] + rm -rf "$tmp" +} + +@test "a fence that keeps coming back fails the hook inside its deadline" { + tmp=$(mktemp -d) + prepare "$tmp" + add_release "$STATE" tenant-a app-a "$FENCE" + touch "$STATE/tenant-a@app-a.readd" + + run_hook "$tmp" + + [ "$status" -ne 0 ] + grep -q '^NOT released tenant-a/app-a' "$tmp/out" + [ "$(cat "$CLOCK")" -lt "$DEADLINE" ] + rm -rf "$tmp" +} + +@test "a listing that never succeeds fails the hook instead of reading as no fences" { + tmp=$(mktemp -d) + prepare "$tmp" + echo 9999 > "$STATE/list.fail" + add_release "$STATE" tenant-a app-a "$FENCE" + + run_hook "$tmp" + + [ "$status" -ne 0 ] + grep -q 'could not list' "$tmp/out" + [ "$(fences_left "$STATE")" -eq 1 ] + [ "$(cat "$CLOCK")" -lt "$DEADLINE" ] + rm -rf "$tmp" +} + +@test "a Deployment that cannot be read or scaled down fails the hook before any fence is touched" { + for knob in deploy scale; do + tmp=$(mktemp -d) + prepare "$tmp" + # flux-plunger may still be running and would fence behind a sweep, and a + # sweep that ran anyway would leave the retried uninstall nothing to + # converge on. + echo 9999 > "$STATE/$knob.fail" + add_release "$STATE" tenant-a app-a "$FENCE" + echo yes > "$STATE/tenant-a@app-a.owned" + + run_hook "$tmp" + + [ "$status" -ne 0 ] + grep -q 'no fence was touched' "$tmp/out" + [ "$(fences_left "$STATE")" -eq 1 ] + [ -e "$STATE/tenant-a@app-a.owned" ] + if grep -q 'helmreleases' "$KLOG"; then + echo "FAIL: the sweep ran with flux-plunger possibly still running" + false + fi + [ "$(cat "$CLOCK")" -lt "$DEADLINE" ] + rm -rf "$tmp" + done +} + +@test "a flux-plunger Deployment that is already gone has nothing to stop, and says so" { + tmp=$(mktemp -d) + prepare "$tmp" + touch "$STATE/deploy.absent" + echo 9999 > "$STATE/scale.fail" + add_release "$STATE" tenant-a app-a "$FENCE" + + run_hook "$tmp" + + [ "$status" -eq 0 ] + grep -q 'no flux-plunger Deployment in cozy-fluxcd; nothing to stop' "$tmp/out" + [ "$(fences_left "$STATE")" -eq 0 ] + if grep -q ' scale ' "$KLOG"; then + echo "FAIL: scaled a Deployment that is not there" + false + fi + rm -rf "$tmp" +} + +@test "a flux-plunger pod that does not go is named, and the sweep goes on" { + tmp=$(mktemp -d) + prepare "$tmp" + # A pod stuck Terminating on a NotReady node stays until the node returns or + # someone force-deletes it; failing on it would fail every retried uninstall. + touch "$STATE/pods.stuck" + add_release "$STATE" tenant-a app-a "$FENCE" + echo 2 > "$STATE/tenant-a@app-a.patch.fail" + + run_hook "$tmp" + + [ "$status" -eq 0 ] + grep -q 'pods are still running, sweeping anyway: pod/flux-plunger-0' "$tmp/out" + [ "$(fences_left "$STATE")" -eq 0 ] + grep -q -x 'released 1 of 1 fenced HelmReleases, 0 without an uninstall' "$tmp/out" + [ "$(cat "$CLOCK")" -lt "$DEADLINE" ] + rm -rf "$tmp" +} + +@test "a release the still-running flux-plunger fences after the listing fails the hook and is named" { + tmp=$(mktemp -d) + prepare "$tmp" + # The stuck pod's container is alive: it never got SIGTERM, still holds the + # Lease, and fences one more release once the listing has returned. With the + # chart gone nothing would ever remove that fence. + touch "$STATE/pods.stuck" + add_release "$STATE" tenant-a app-a "$FENCE" + add_release "$STATE" tenant-z app-z example.com/keep + touch "$STATE/tenant-z@app-z.latefence" + + run_hook "$tmp" + + [ "$status" -ne 0 ] + grep -q '^NOT released tenant-z/app-z: fenced after the sweep' "$tmp/out" + [ "$(fences_left "$STATE")" -eq 1 ] + rm -rf "$tmp" +} + +@test "a pod wait that fails for another reason is told apart from a pod that stays" { + tmp=$(mktemp -d) + prepare "$tmp" + echo 1 > "$STATE/wait.fail" + add_release "$STATE" tenant-a app-a "$FENCE" + + run_hook "$tmp" + + [ "$status" -eq 0 ] + grep -q 'the wait for flux-plunger pods to go failed, but none is left' "$tmp/out" + [ "$(fences_left "$STATE")" -eq 0 ] + # With the pods gone, nothing can have fenced behind the sweep. + [ "$(grep --count 'helmreleases.helm.toolkit.fluxcd.io --all-namespaces' "$KLOG")" -eq 1 ] + rm -rf "$tmp" +} + +@test "a pod wait after a slow scale-down is cut to what is left of the retry window" { + tmp=$(mktemp -d) + prepare "$tmp" + # The scale-down is retried for most of the window, and the pod never goes: + # the wait must not run past the window, or the Job is killed before the + # sweep and its report. + echo 80 > "$STATE/scale.fail" + touch "$STATE/pods.stuck" + add_release "$STATE" tenant-a app-a "$FENCE" + + run_hook "$tmp" + + [ "$status" -eq 0 ] + grep -q -x 'released 1 of 1 fenced HelmReleases, 0 without an uninstall' "$tmp/out" + [ "$(cat "$CLOCK")" -lt "$DEADLINE" ] + rm -rf "$tmp" +} + +@test "a pod listing that cannot be read after a failed wait is treated as a pod still running" { + tmp=$(mktemp -d) + prepare "$tmp" + echo 1 > "$STATE/wait.fail" + echo 9999 > "$STATE/pods.fail" + add_release "$STATE" tenant-a app-a "$FENCE" + add_release "$STATE" tenant-z app-z example.com/keep + touch "$STATE/tenant-z@app-z.latefence" + + run_hook "$tmp" + + [ "$status" -ne 0 ] + grep -q 'could not tell whether flux-plunger pods are still running; sweeping anyway' "$tmp/out" + grep -q '^NOT released tenant-z/app-z: fenced after the sweep' "$tmp/out" + [ "$(cat "$CLOCK")" -lt "$DEADLINE" ] + rm -rf "$tmp" +} + +@test "a listing after the sweep that never succeeds fails the hook" { + tmp=$(mktemp -d) + prepare "$tmp" + # The pod is still there, so whether it fenced anything behind the sweep is + # unknown until a listing answers. + touch "$STATE/pods.stuck" + echo 9999 > "$STATE/relist.fail" + add_release "$STATE" tenant-a app-a "$FENCE" + + run_hook "$tmp" + + [ "$status" -ne 0 ] + grep -q 'could not list fenced HelmReleases again after the sweep' "$tmp/out" + [ "$(fences_left "$STATE")" -eq 0 ] + [ "$(cat "$CLOCK")" -lt "$DEADLINE" ] + rm -rf "$tmp" +} + +@test "a scale-down that returns after the retry window still bounds the pod wait" { + tmp=$(mktemp -d) + prepare "$tmp" + # What is left of the window is then negative, which kubectl wait reads as a + # week: the Job would be killed before the sweep and its report. + echo $((WINDOW + 5)) > "$STATE/scale.slow" + touch "$STATE/pods.stuck" + add_release "$STATE" tenant-a app-a "$FENCE" + + run_hook "$tmp" + + [ "$status" -eq 0 ] + grep -q -x 'released 1 of 1 fenced HelmReleases, 0 without an uninstall' "$tmp/out" + [ "$(cat "$CLOCK")" -lt "$DEADLINE" ] + rm -rf "$tmp" +} diff --git a/hack/unit-test-parallelism.bats b/hack/unit-test-parallelism.bats index c7cdf0d52..532dbf4f2 100644 --- a/hack/unit-test-parallelism.bats +++ b/hack/unit-test-parallelism.bats @@ -25,7 +25,7 @@ load test_helper @test "PR workflow schedules unit and controller targets with four Make jobs and -k" { # -k is what lets test-controllers start when a unit-tests prerequisite # fails first; without it a red Bats file hides the Go controller suite. - grep -qF 'run: make unit-tests test-controllers -j4 -k --output-sync=target' \ + grep -qF 'run: make unit-tests test-controllers test-controllers-envtest -j4 -k --output-sync=target' \ .github/workflows/pull-requests.yaml || { echo "PR checks do not use the bounded four-slot make invocation" >&2 exit 1 diff --git a/internal/controller/fluxplunger/drain.go b/internal/controller/fluxplunger/drain.go new file mode 100644 index 000000000..53eb93e5f --- /dev/null +++ b/internal/controller/fluxplunger/drain.go @@ -0,0 +1,239 @@ +// SPDX-License-Identifier: Apache-2.0 + +package fluxplunger + +import ( + "context" + "errors" + "fmt" + "time" + + helmv2 "github.com/fluxcd/helm-controller/api/v2" + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + ctrl "sigs.k8s.io/controller-runtime" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/client/apiutil" + "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil" + "sigs.k8s.io/controller-runtime/pkg/log" +) + +const ( + // drainPollInterval is how often a drain re-reads the releases it still holds. + drainPollInterval = time.Second + // ShutdownDrainTimeoutFlag names the flag that bounds the drain; the chart + // passes it, derived from the pod's termination grace period. + ShutdownDrainTimeoutFlag = "shutdown-drain-timeout" +) + +// DrainFences gives up every fence flux-plunger holds, for a flux-plunger that is +// stopping. A live release has its recovery aborted, the suspension and the fence +// lifted together, which leaves it as recovery found it for the next flux-plunger +// to pick up. A release being deleted goes through reconcileTerminating until the +// fence is gone: flux-plunger's suspension is lifted, the fence is kept until +// helm-controller has handled the unsuspended generation, and only then lifted. +// When ctx ends first, the fences still held are left in place and counted: the +// next flux-plunger carries on with them, and when flux-plunger is being removed +// the chart's pre-delete hook releases them. Reads go to the apiserver, since the +// informer cache has stopped with the manager by now. +func (r *FluxPlunger) DrainFences(ctx context.Context) (int, error) { + logger := log.FromContext(ctx) + var reader client.Reader = r.Client + if r.APIReader != nil { + reader = r.APIReader + } + // held is what the last listing that succeeded found; -1 until one has. + held := -1 + for { + list := &helmv2.HelmReleaseList{} + if err := reader.List(ctx, list); err != nil { + // A failed listing is retried like any other step: on the uninstall + // path ending here would leave the pre-delete hook to let go of a + // release the drain could still have carried through its uninstall. + logger.Info("Could not list HelmReleases yet, retrying", "error", err.Error()) + select { + case <-ctx.Done(): + return held, ctx.Err() + case <-time.After(drainPollInterval): + } + continue + } + held = 0 + for i := range list.Items { + hr := &list.Items[i] + if !controllerutil.ContainsFinalizer(hr, fenceFinalizer) { + continue + } + held++ + var err error + if hr.DeletionTimestamp.IsZero() { + // The relinquishing apply drops every field flux-plunger's manager owns, + // so a suspension of its own goes with the fence, and one it does not own + // is left alone. + err = r.releaseFence(ctx, hr) + } else { + _, err = r.reconcileTerminating(ctx, hr) + } + if err != nil { + logger.Info("Could not give up a fence yet, retrying", "helmrelease", client.ObjectKeyFromObject(hr).String(), "error", err.Error()) + } + } + if held == 0 { + return 0, nil + } + select { + case <-ctx.Done(): + return held, ctx.Err() + case <-time.After(drainPollInterval): + } + } +} + +const ( + // managerStopTimeout bounds how long the manager may take to stop its + // controllers before the drain starts. + managerStopTimeout = 10 * time.Second + // killMargin is left between the end of the drain and the kubelet's SIGKILL. + // The chart's --shutdown-drain-timeout is the grace period less this and + // managerStopTimeout, which TestDeploymentTemplate_SubtractsTheStopAndTheMarginTheBinaryUses + // holds. + killMargin = 15 * time.Second + // leaseRetryPeriod is how often the leader renews its Lease. + leaseRetryPeriod = 5 * time.Second + // leaseRenewDeadline is how long a leader whose renewals fail goes on acting + // before it gives up; it is part of what the Lease has to outlast. + leaseRenewDeadline = 15 * time.Second + // leaseMargin is added on top of everything a stop can take. + leaseMargin = 20 * time.Second +) + +// ApplyShutdownTimings sizes the leader Lease so the next flux-plunger cannot +// lead while this one drains. A rollout or an eviction starts the next pod while +// the old one is still terminating, whatever the Deployment strategy, so it is +// the Lease, not the rollout, that keeps a single writer. The Lease is not given +// up on stop, and it outlasts its last renewal, the renew deadline, the +// manager's bounded stop and the drain; the price is that a new pod waits for it +// to run out before it leads. +func ApplyShutdownTimings(opts *ctrl.Options, drain time.Duration) { + stop := managerStopTimeout + renew := leaseRenewDeadline + lease := leaseRetryPeriod + renew + stop + drain + leaseMargin + retry := leaseRetryPeriod + opts.GracefulShutdownTimeout = &stop + opts.LeaseDuration = &lease + opts.RenewDeadline = &renew + opts.RetryPeriod = &retry + opts.LeaderElectionReleaseOnCancel = false +} + +// drainingManager is the part of a ctrl.Manager RunManager uses. +type drainingManager interface { + Start(context.Context) error + GetClient() client.Client + GetAPIReader() client.Reader + Elected() <-chan struct{} +} + +// RunManager runs the manager, then drains flux-plunger's fences. The drain +// reads through the manager's API reader: once the manager has stopped, its +// informer cache is frozen and would show fences already gone. Only a +// flux-plunger that led drains: one that never did stops while the leader goes +// on, and the fences are the leader's. Without leader election Elected is closed +// from the start. +func RunManager(ctx context.Context, mgr drainingManager, drain time.Duration) error { + drainer := &FluxPlunger{ + Client: mgr.GetClient(), + APIReader: mgr.GetAPIReader(), + Recorder: apiEventRecorder{c: mgr.GetClient()}, + } + return RunThenDrain(ctx, mgr.Start, func(dctx context.Context) (int, error) { + select { + case <-mgr.Elected(): + return drainer.DrainFences(dctx) + default: + log.FromContext(dctx).Info("Never became leader; leaving the fences to the leader") + return 0, nil + } + }, drain) +} + +// RunThenDrain runs the manager until it stops, then drains under a deadline of +// its own: the context run was given is cancelled by the stop signal, so the drain +// cannot be bounded by it. A manager that failed is not drained: a lost Lease +// means another flux-plunger leads now. A stop that overran the manager's grace +// period is drained anyway, since a reconcile slow to notice its cancelled +// context must not cost the fences their drain, and is still reported. A drain +// that leaves fences behind is logged rather than turned into a failed exit, +// since the next flux-plunger or the pre-delete hook takes them over. +func RunThenDrain(ctx context.Context, run func(context.Context) error, drain func(context.Context) (int, error), timeout time.Duration) error { + runErr := run(ctx) + if runErr != nil && !errors.Is(runErr, context.DeadlineExceeded) { + return runErr + } + dctx, cancel := context.WithTimeout(context.Background(), timeout) + defer cancel() + logger := log.FromContext(ctx) + if left, err := drain(dctx); err != nil { + logger.Info("Stopped with uninstall fences still held; the next flux-plunger or the chart's pre-delete hook releases them", "held", left, "error", err.Error()) + } else { + logger.Info("Released every uninstall fence before stopping") + } + return runErr +} + +// apiEventRecorder writes each Event straight to the apiserver. The drain cannot +// use the manager's recorder: the manager stops its recorder provider before +// Start returns, after which that recorder delivers nothing. +type apiEventRecorder struct { + c client.Client +} + +func (r apiEventRecorder) Event(obj runtime.Object, eventtype, reason, message string) { + r.write(obj, eventtype, reason, message) +} + +func (r apiEventRecorder) Eventf(obj runtime.Object, eventtype, reason, messageFmt string, args ...interface{}) { + r.write(obj, eventtype, reason, fmt.Sprintf(messageFmt, args...)) +} + +func (r apiEventRecorder) AnnotatedEventf(obj runtime.Object, _ map[string]string, eventtype, reason, messageFmt string, args ...interface{}) { + r.write(obj, eventtype, reason, fmt.Sprintf(messageFmt, args...)) +} + +func (r apiEventRecorder) write(obj runtime.Object, eventtype, reason, message string) { + logger := log.Log.WithName("drain-events") + o, ok := obj.(client.Object) + if !ok { + logger.Info("Cannot record an event for this object", "type", fmt.Sprintf("%T", obj), "reason", reason) + return + } + gvk, err := apiutil.GVKForObject(o, r.c.Scheme()) + if err != nil { + logger.Info("Cannot record an event", "reason", reason, "error", err.Error()) + return + } + now := metav1.Now() + ev := &corev1.Event{ + ObjectMeta: metav1.ObjectMeta{GenerateName: o.GetName() + ".", Namespace: o.GetNamespace()}, + InvolvedObject: corev1.ObjectReference{ + APIVersion: gvk.GroupVersion().String(), + Kind: gvk.Kind, + Namespace: o.GetNamespace(), + Name: o.GetName(), + UID: o.GetUID(), + }, + Reason: reason, + Message: message, + Type: eventtype, + Source: corev1.EventSource{Component: suspendFieldManager}, + FirstTimestamp: now, + LastTimestamp: now, + Count: 1, + } + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + if err := r.c.Create(ctx, ev); err != nil { + logger.Info("Could not record an event", "reason", reason, "error", err.Error()) + } +} diff --git a/internal/controller/fluxplunger/drain_envtest_test.go b/internal/controller/fluxplunger/drain_envtest_test.go new file mode 100644 index 000000000..7a0f6b5d1 --- /dev/null +++ b/internal/controller/fluxplunger/drain_envtest_test.go @@ -0,0 +1,323 @@ +// SPDX-License-Identifier: Apache-2.0 +//go:build envtest + +package fluxplunger + +import ( + "context" + "os" + "testing" + "time" + + helmv2 "github.com/fluxcd/helm-controller/api/v2" + corev1 "k8s.io/api/core/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/types" + clientgoscheme "k8s.io/client-go/kubernetes/scheme" + ctrl "sigs.k8s.io/controller-runtime" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil" + metricsserver "sigs.k8s.io/controller-runtime/pkg/metrics/server" +) + +// fenceAndSuspend gives a release flux-plunger's recovery state: its own +// suspension and the fence, applied together as a recovery does. +func fenceAndSuspend(t *testing.T, ctx context.Context, cl client.Client, key types.NamespacedName) { + t.Helper() + hr := &helmv2.HelmRelease{} + if err := cl.Get(ctx, key, hr); err != nil { + t.Fatalf("get: %v", err) + } + r := &FluxPlunger{Client: cl, APIReader: cl} + if acquired, err := r.suspendHelmRelease(ctx, hr); err != nil || !acquired { + t.Fatalf("acquire: acquired=%v err=%v", acquired, err) + } +} + +func TestEnvtest_DrainAbortsTheRecoveryOfALiveRelease(t *testing.T) { + ctx, cl, newRelease, stop := startFenceEnv(t) + defer stop() + key := newRelease(testName + "-drain-live") + fenceAndSuspend(t, ctx, cl, key) + + r := &FluxPlunger{Client: cl, APIReader: cl} + dctx, cancel := context.WithTimeout(ctx, 10*time.Second) + defer cancel() + left, err := r.DrainFences(dctx) + if err != nil || left != 0 { + t.Fatalf("drain: left=%d err=%v", left, err) + } + + hr := &helmv2.HelmRelease{} + if err := cl.Get(ctx, key, hr); err != nil { + t.Fatalf("get: %v", err) + } + if hr.Spec.Suspend || ownsSuspensionManagedFields(hr) { + t.Fatalf("drain must lift flux-plunger's suspension: suspend=%v owned=%v", hr.Spec.Suspend, ownsSuspensionManagedFields(hr)) + } + if controllerutil.ContainsFinalizer(hr, fenceFinalizer) { + t.Fatalf("drain must lift the fence with the suspension, finalizers %v", hr.Finalizers) + } + if !controllerutil.ContainsFinalizer(hr, helmv2.HelmReleaseFinalizer) { + t.Fatalf("drain must leave helm-controller's finalizer, finalizers %v", hr.Finalizers) + } +} + +// A live release left with the fence alone (a recovery interrupted between its +// steps) is released at once, not held until the drain's deadline. +func TestEnvtest_DrainReleasesALiveFenceWithoutASuspensionAtOnce(t *testing.T) { + ctx, cl, newRelease, stop := startFenceEnv(t) + defer stop() + key := newRelease(testName + "-drain-fence-only") + hr := &helmv2.HelmRelease{} + if err := cl.Get(ctx, key, hr); err != nil { + t.Fatalf("get: %v", err) + } + r := &FluxPlunger{Client: cl, APIReader: cl} + if err := r.applyRecoveryState(ctx, hr, nil, true, false); err != nil { + t.Fatalf("fence: %v", err) + } + + dctx, cancel := context.WithTimeout(ctx, 20*time.Second) + defer cancel() + start := time.Now() + if left, err := r.DrainFences(dctx); err != nil || left != 0 { + t.Fatalf("drain: left=%d err=%v", left, err) + } + if took := time.Since(start); took > 5*time.Second { + t.Fatalf("a live fence must go at once, the drain took %v", took) + } + if err := cl.Get(ctx, key, hr); err != nil { + t.Fatalf("get: %v", err) + } + if controllerutil.ContainsFinalizer(hr, fenceFinalizer) { + t.Fatalf("the fence must go, finalizers %v", hr.Finalizers) + } +} + +func TestEnvtest_DrainLeavesAnotherManagersSuspensionAlone(t *testing.T) { + ctx, cl, newRelease, stop := startFenceEnv(t) + defer stop() + key := newRelease(testName + "-drain-foreign") + hr := &helmv2.HelmRelease{} + if err := cl.Get(ctx, key, hr); err != nil { + t.Fatalf("get: %v", err) + } + r := &FluxPlunger{Client: cl, APIReader: cl} + if err := r.applyRecoveryState(ctx, hr, nil, true, false); err != nil { + t.Fatalf("fence: %v", err) + } + if err := cl.Get(ctx, key, hr); err != nil { + t.Fatalf("get: %v", err) + } + hr.Spec.Suspend = true + if err := cl.Update(ctx, hr, client.FieldOwner(fmOper)); err != nil { + t.Fatalf("operator suspend: %v", err) + } + + dctx, cancel := context.WithTimeout(ctx, 10*time.Second) + defer cancel() + if left, err := r.DrainFences(dctx); err != nil || left != 0 { + t.Fatalf("drain: left=%d err=%v", left, err) + } + if err := cl.Get(ctx, key, hr); err != nil { + t.Fatalf("get: %v", err) + } + if controllerutil.ContainsFinalizer(hr, fenceFinalizer) { + t.Fatalf("the fence must go, finalizers %v", hr.Finalizers) + } + if !hr.Spec.Suspend { + t.Fatal("an operator's suspension must survive the drain") + } +} + +// A rollout or an eviction starts the next flux-plunger while the old one is +// still terminating, so two of them overlap whatever the Deployment strategy. The +// old one must still be the only writer while it drains: it keeps the leader +// Lease, which it does not give up, and the next one becomes leader only once +// the Lease has run out, after the drain. +func TestEnvtest_TheNextFluxPlungerLeadsOnlyAfterTheDrain(t *testing.T) { + crdDir := os.Getenv("HELMRELEASE_CRD_DIR") + if crdDir == "" { + t.Skip("set HELMRELEASE_CRD_DIR to the dir with the HelmRelease CRD") + } + env := newEnvtestEnvironment(crdDir) + cfg, err := env.Start() + if err != nil { + t.Fatalf("start envtest: %v", err) + } + defer func() { _ = env.Stop() }() + cl, err := client.New(cfg, client.Options{Scheme: clientgoscheme.Scheme}) + if err != nil { + t.Fatalf("client: %v", err) + } + if err := cl.Create(context.Background(), &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: testNS}}); err != nil { + t.Fatalf("create ns: %v", err) + } + + // Longer than the Lease retry period, so a Lease given up on stop would be + // taken by the next manager while the drain still runs. + const drainFor = 3 * leaseRetryPeriod + newManager := func() ctrl.Manager { + opts := ctrl.Options{ + Scheme: clientgoscheme.Scheme, + Metrics: metricsserver.Options{BindAddress: "0"}, + HealthProbeBindAddress: "0", + LeaderElection: true, + LeaderElectionID: "flux-plunger.cozystack.io", + LeaderElectionNamespace: testNS, + } + ApplyShutdownTimings(&opts, drainFor) + m, err := ctrl.NewManager(cfg, opts) + if err != nil { + t.Fatalf("manager: %v", err) + } + return m + } + + old := newManager() + oldCtx, stopOld := context.WithCancel(context.Background()) + var drainEnded time.Time + oldDone := make(chan error, 1) + go func() { + oldDone <- RunThenDrain(oldCtx, old.Start, func(ctx context.Context) (int, error) { + time.Sleep(drainFor) + drainEnded = time.Now() + return 0, nil + }, drainFor) + }() + select { + case <-old.Elected(): + case <-time.After(30 * time.Second): + t.Fatal("the first flux-plunger never became leader") + } + + next := newManager() + nextCtx, stopNext := context.WithCancel(context.Background()) + defer stopNext() + go func() { _ = next.Start(nextCtx) }() + + stopOld() + if err := <-oldDone; err != nil { + t.Fatalf("a clean stop must drain, not fail: %v", err) + } + if drainEnded.IsZero() { + t.Fatal("the stopping flux-plunger did not drain") + } + select { + case <-next.Elected(): + t.Fatal("the next flux-plunger became leader while the old one was still draining") + default: + } + + select { + case <-next.Elected(): + if !time.Now().After(drainEnded) { + t.Fatal("the next flux-plunger led before the drain ended") + } + case <-time.After(2 * time.Minute): + t.Fatal("the next flux-plunger never became leader once the Lease ran out") + } +} + +// A delete that helm-controller handled while flux-plunger held the suspension +// (no uninstall, its finalizer dropped) leaves the fence as the only thing +// keeping the release. Draining must lift the suspension and keep the fence +// until helm-controller has handled the unsuspended generation, so the uninstall +// runs before the release goes. +func TestEnvtest_DrainCarriesADeleteThroughTheUninstall(t *testing.T) { + ctx, cl, newRelease, stop := startFenceEnv(t) + defer stop() + key := newRelease(testName + "-drain-delete") + fenceAndSuspend(t, ctx, cl, key) + hr := &helmv2.HelmRelease{} + if err := cl.Get(ctx, key, hr); err != nil { + t.Fatalf("get: %v", err) + } + if err := cl.Delete(ctx, hr); err != nil { + t.Fatalf("delete: %v", err) + } + if simulateHelmControllerDelete(t, ctx, cl, key) { + t.Fatal("helm-controller must skip the uninstall of a suspended release") + } + + r := &FluxPlunger{Client: cl, APIReader: cl} + dctx, cancel := context.WithTimeout(ctx, 20*time.Second) + defer cancel() + type result struct { + left int + err error + } + done := make(chan result, 1) + go func() { + left, err := r.DrainFences(dctx) + done <- result{left, err} + }() + + // helm-controller reconciles again once the suspension is lifted. Until it + // has, the fence must keep the release, through any number of drain passes. + deadline := time.Now().Add(10 * time.Second) + for { + if err := cl.Get(ctx, key, hr); err != nil { + t.Fatalf("the fence must keep the release until helm-controller has handled it, got %v", err) + } + if !hr.Spec.Suspend { + break + } + if time.Now().After(deadline) { + t.Fatal("drain did not lift flux-plunger's suspension") + } + time.Sleep(100 * time.Millisecond) + } + time.Sleep(3 * drainPollInterval) + if err := cl.Get(ctx, key, hr); err != nil { + t.Fatalf("the fence must hold while helm-controller has not observed the unsuspended generation, got %v", err) + } + if !simulateHelmControllerDelete(t, ctx, cl, key) { + t.Fatal("with the suspension lifted, helm-controller must run the uninstall") + } + + res := <-done + if res.err != nil || res.left != 0 { + t.Fatalf("drain: left=%d err=%v", res.left, res.err) + } + if err := cl.Get(ctx, key, hr); !apierrors.IsNotFound(err) { + t.Fatalf("after the uninstall the drain must lift the fence so the release is deleted, got %v", err) + } +} + +// A helm-controller that never handles the unsuspended release must not make the +// drain drop the fence: the next flux-plunger, or the chart's pre-delete hook when +// flux-plunger is being removed, takes it from there. +func TestEnvtest_DrainKeepsTheFenceWhenHelmControllerNeverAnswers(t *testing.T) { + ctx, cl, newRelease, stop := startFenceEnv(t) + defer stop() + key := newRelease(testName + "-drain-stalled") + fenceAndSuspend(t, ctx, cl, key) + hr := &helmv2.HelmRelease{} + if err := cl.Get(ctx, key, hr); err != nil { + t.Fatalf("get: %v", err) + } + if err := cl.Delete(ctx, hr); err != nil { + t.Fatalf("delete: %v", err) + } + simulateHelmControllerDelete(t, ctx, cl, key) + + r := &FluxPlunger{Client: cl, APIReader: cl} + dctx, cancel := context.WithTimeout(ctx, 3*time.Second) + defer cancel() + left, err := r.DrainFences(dctx) + if err == nil || left != 1 { + t.Fatalf("a drain cut short must report the fence it left: left=%d err=%v", left, err) + } + if err := cl.Get(ctx, key, hr); err != nil { + t.Fatalf("the fence must keep the release, got %v", err) + } + if hr.Spec.Suspend { + t.Fatal("the drain must still have lifted flux-plunger's suspension") + } + if !controllerutil.ContainsFinalizer(hr, fenceFinalizer) { + t.Fatalf("the fence must stay, finalizers %v", hr.Finalizers) + } +} diff --git a/internal/controller/fluxplunger/flux_plunger.go b/internal/controller/fluxplunger/flux_plunger.go index 44886a2cb..fc57b405c 100644 --- a/internal/controller/fluxplunger/flux_plunger.go +++ b/internal/controller/fluxplunger/flux_plunger.go @@ -2,17 +2,24 @@ package fluxplunger import ( "context" + "encoding/json" + "errors" "fmt" "sort" "strconv" "strings" + "time" helmv2 "github.com/fluxcd/helm-controller/api/v2" corev1 "k8s.io/api/core/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/types" + "k8s.io/client-go/tools/record" ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil" "sigs.k8s.io/controller-runtime/pkg/log" "sigs.k8s.io/controller-runtime/pkg/predicate" ) @@ -20,74 +27,197 @@ import ( const ( annotationLastProcessedVersion = "flux-plunger.cozystack.io/last-processed-version" errorMessageNoDeployedReleases = "has no deployed releases" - fieldManager = "flux-client-side-apply" + // fieldManager owns the client-side patch of the processed-version annotation. + fieldManager = "flux-client-side-apply" + // suspendFieldManager is the server-side-apply field manager flux-plunger uses + // to own spec.suspend. Ownership of a suspension is decided by whether this + // manager owns the field in metadata.managedFields, not by an annotation: the + // apiserver transfers the field away the moment another writer changes + // spec.suspend (a resume, then a re-suspend), so a later operator suspension is + // never misread as flux-plunger's, while an unrelated re-apply of other fields + // leaves the ownership untouched (no self-disown). A write of the value the field + // already holds does not transfer it. + suspendFieldManager = "flux-plunger" + // fenceFinalizer holds a HelmRelease while flux-plunger's recovery has it + // suspended. On a delete, helm-controller v1.5.x drops its own finalizer without + // running the Helm uninstall if the release is suspended, and it wakes on the same + // event flux-plunger does, so lifting the suspension first cannot be guaranteed. + // This finalizer keeps the object until flux-plunger has lifted the suspension + // and helm-controller has reconciled the unsuspended release, which runs the + // uninstall. It is applied in the same server-side apply as the suspension and + // removed with it once a recovery completes; on a delete it outlives the + // suspension and is removed only once helm-controller has handled the + // unsuspended release (uninstallReached). + fenceFinalizer = "flux-plunger.cozystack.io/uninstall-fence" + + // fenceRecheckInterval is how often a delete held by the fence is re-checked + // without waiting for an event, so a stalled helm-controller is noticed. + fenceRecheckInterval = time.Minute + // fenceHeldWarnAfter is how long a delete may be held by the fence, waiting for + // helm-controller to handle the unsuspended release, before it is raised as a + // Warning: an uninstall normally lands within seconds. + fenceHeldWarnAfter = 10 * time.Minute ) // FluxPlunger watches HelmRelease resources and fixes "has no deployed releases" errors type FluxPlunger struct { client.Client + + // APIReader reads directly from the apiserver, bypassing the informer cache. + // The re-fetch guards below (already-suspended, terminating) must not read the + // cache: it lags a write or delete the apiserver has already accepted, which + // would defeat the pre-delete termination re-check whose whole purpose is to + // catch a just-arrived delete. Production wires mgr.GetAPIReader(); when nil + // (tests), refetch falls back to the cached client. + APIReader client.Reader + + // Recorder emits Events so an operator can see a release flux-plunger declined + // to act on (an externally-owned suspension) rather than reading it out of the + // log. Production wires mgr.GetEventRecorderFor; nil is tolerated (tests). + Recorder record.EventRecorder + + // owns overrides the suspension-ownership check. Production leaves it nil and + // uses ownsSuspensionManagedFields (the managedFields-based check, which the + // controller-runtime fake client cannot represent). Tests in this package + // inject a stand-in so the branch, ordering and requeue behaviour can be + // exercised on the fake client, while the managedFields check itself is pinned + // by a unit test on hand-crafted managedFields and by the envtest suite. + owns func(*helmv2.HelmRelease) bool + + // now overrides the clock for tests; production leaves it nil. + now func() time.Time +} + +func (r *FluxPlunger) clock() time.Time { + if r.now != nil { + return r.now() + } + return time.Now() +} + +// recordEvent emits an Event when a Recorder is wired. The message is static so +// the recorder's event correlator folds repeats into a single counted Event rather +// than a flood. +func (r *FluxPlunger) recordEvent(hr *helmv2.HelmRelease, eventType, reason, message string) { + if r.Recorder != nil { + r.Recorder.Event(hr, eventType, reason, message) + } +} + +// recordUnsuspendFailed raises a Warning when flux-plunger holds a suspension and +// could not clear it: the state in which a delete makes helm-controller skip the +// uninstall and orphan the release, which an operator can see in +// `kubectl describe helmrelease` and must be able to alert on. A conflict is not +// such a failure: the apply is preconditioned on what was read, so any write in +// between (helm-controller's status update included) rejects it, and the requeue +// retries it against the new state. Nor is a stop cancelling the reconcile: the +// drain that follows lifts the suspension. +func (r *FluxPlunger) recordUnsuspendFailed(hr *helmv2.HelmRelease, err error) { + if apierrors.IsConflict(err) || errors.Is(err, context.Canceled) { + return + } + r.recordEvent(hr, corev1.EventTypeWarning, "UnsuspendFailed", + "Could not clear a suspension flux-plunger set; retrying. While it stays suspended, deleting the release skips the Helm uninstall and orphans its resources") +} + +// uninstallReached reports whether helm-controller has handled a terminating +// release in its current, unsuspended form: its finalizer is gone and it has +// observed the latest generation, which lifting the suspension bumped. Checking the +// finalizer alone is not enough, because helm-controller drops it without an +// uninstall while the release is still suspended. +func uninstallReached(hr *helmv2.HelmRelease) bool { + return !controllerutil.ContainsFinalizer(hr, helmv2.HelmReleaseFinalizer) && + hr.Status.ObservedGeneration == hr.Generation +} + +// ownsSuspension reports whether flux-plunger owns the current suspension, through +// the injected check in tests or the managedFields check in production. +func (r *FluxPlunger) ownsSuspension(hr *helmv2.HelmRelease) bool { + if r.owns != nil { + return r.owns(hr) + } + return ownsSuspensionManagedFields(hr) +} + +// refetch reads the freshest state of a HelmRelease. It uses the uncached +// APIReader when wired (production) so an already-suspended or termination +// re-check sees a write or delete the apiserver has just accepted; it falls back +// to the cached client only when no APIReader is set (tests). +func (r *FluxPlunger) refetch(ctx context.Context, key types.NamespacedName, hr *helmv2.HelmRelease) error { + if r.APIReader != nil { + return r.APIReader.Get(ctx, key, hr) + } + return r.Get(ctx, key, hr) } // +kubebuilder:rbac:groups=helm.toolkit.fluxcd.io,resources=helmreleases,verbs=get;list;watch;update;patch // +kubebuilder:rbac:groups="",resources=secrets,verbs=get;list;delete +// +kubebuilder:rbac:groups="",resources=events,verbs=create;patch // Reconcile handles HelmRelease resources with "has no deployed releases" error func (r *FluxPlunger) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { logger := log.FromContext(ctx) - // Get the HelmRelease + // Read the HelmRelease from the apiserver, not the informer cache: the + // already-processed guard below compares its processed-version annotation with a + // Secret list that is itself read from the apiserver, and a cache that has not yet + // seen the annotation written by the previous recovery would fail that guard and + // delete the next revision down. hr := &helmv2.HelmRelease{} - if err := r.Get(ctx, req.NamespacedName, hr); err != nil { + if err := r.refetch(ctx, req.NamespacedName, hr); err != nil { return ctrl.Result{}, client.IgnoreNotFound(err) } + if !hr.DeletionTimestamp.IsZero() { + return r.reconcileTerminating(ctx, hr) + } + // Check if HelmRelease is suspended if hr.Spec.Suspend { - logger.Info("HelmRelease is suspended, checking if we need to unsuspend") + // Ownership is decided by which field manager owns spec.suspend (see + // ownsSuspension). A suspension we own but see in a fresh reconcile means + // recovery crashed mid-flight rather than another instance running now: only + // the holder of the leader Lease reconciles, a stopping instance keeps that + // Lease through its drain (ApplyShutdownTimings), and controller-runtime + // serialises reconciles per key within the one process, so there is no + // concurrent owner to race. Releasing it un-sticks the release and lets + // error-recovery start over. A suspension flux-plunger does not own belongs to + // an operator or another controller and must be left untouched. + if !r.ownsSuspension(hr) { + logger.Info("HelmRelease is suspended by external process, skipping") + // On a release flux-plunger recovered before, the suspension is most + // likely one an earlier flux-plunger left mid-recovery under the shared + // flux-client-side-apply manager, which no one will lift unless told. + if _, recovered := hr.Annotations[annotationLastProcessedVersion]; recovered { + r.recordEvent(hr, corev1.EventTypeWarning, "SuspensionNotOwned", + "Left a suspension flux-plunger does not own untouched on a release it has recovered before; if an earlier flux-plunger left it, resume the release (see the flux-plunger chart README)") + } else { + r.recordEvent(hr, corev1.EventTypeNormal, "SuspensionNotOwned", + "Left an externally-owned suspension untouched; flux-plunger only clears suspensions it set") + } + // Our fence only guards a suspension flux-plunger holds; with the + // suspension taken over, do not keep the release from being deleted. + return ctrl.Result{}, r.releaseFence(ctx, hr) + } - // Get the list of Helm release secrets - secrets, err := r.listHelmReleaseSecrets(ctx, hr.Namespace, hr.Name) - if err != nil { - logger.Error(err, "Failed to list Helm release secrets") + logger.Info("Removing suspension owned by flux-plunger") + if err := r.unsuspendHelmRelease(ctx, hr); err != nil { + // Requeue with backoff so a stuck owned suspension is not left until the + // next informer resync, symmetric with the deletion and recovery paths. + logger.Info("Could not unsuspend HelmRelease, requeuing", "error", err.Error()) + r.recordUnsuspendFailed(hr, err) return ctrl.Result{}, err } - - // If no secrets, treat latest version as 0 - latestVersion := 0 - if len(secrets) > 0 { - latestSecret := getLatestSecret(secrets) - latestVersion = extractVersionNumber(latestSecret.Name) - } else { - logger.Info("No Helm release secrets found while suspended, treating as version 0") - } - - // Check if version is previous to just processed (latestVersion+1 == processedVersion) - // This is the ONLY condition when we unsuspend - shouldUnsuspend := false - if hr.Annotations != nil { - if processedVersionStr, exists := hr.Annotations[annotationLastProcessedVersion]; exists { - processedVersion, err := strconv.Atoi(processedVersionStr) - if err == nil && latestVersion+1 == processedVersion { - shouldUnsuspend = true - } - } - } - - if shouldUnsuspend { - // Unsuspend the HelmRelease - logger.Info("Secret was already deleted in previous run, removing suspend", "latest", latestVersion, "processed", latestVersion+1) - if err := r.unsuspendHelmRelease(ctx, hr); err != nil { - logger.Info("Could not unsuspend HelmRelease, will retry on next reconcile", "error", err.Error()) - return ctrl.Result{}, nil - } - return ctrl.Result{}, nil - } - - // If not previous to processed, skip all actions - logger.Info("HelmRelease is suspended by external process, skipping", "latest", latestVersion) return ctrl.Result{}, nil } + // A fence without a suspension is left when another writer (an operator, + // `cozyhr resume`) set spec.suspend=false and so took the field from + // flux-plunger; it guards nothing any more. + if controllerutil.ContainsFinalizer(hr, fenceFinalizer) { + return ctrl.Result{}, r.releaseFence(ctx, hr) + } + // Check if HelmRelease has the specific error if !hasNoDeployedReleasesError(hr) { logger.V(1).Info("HelmRelease does not have 'has no deployed releases' error, skipping") @@ -132,10 +262,94 @@ func (r *FluxPlunger) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Res // Suspend the HelmRelease logger.Info("Suspending HelmRelease") - if err := r.suspendHelmRelease(ctx, hr); err != nil { - // Optimistic lock conflicts are normal - FluxCD also updates HelmRelease - // Don't return error, just log and let controller-runtime requeue on next update - logger.Info("Could not suspend HelmRelease, will retry on next reconcile", "error", err.Error()) + acquired, err := r.suspendHelmRelease(ctx, hr) + if err != nil { + // Requeue with backoff on any error, symmetric with every step below. + // suspendHelmRelease reports every conflict, on either apply, as not acquired + // (handled below), so an error reaching here is a non-conflict failure (an + // admission webhook rejecting the apply, or an API error) that produces no + // follow-up event. Swallowing it would strand a stuck release until the next + // informer resync. + logger.Info("Could not suspend HelmRelease, requeuing", "error", err.Error()) + return ctrl.Result{}, err + } + if !acquired { + // The release was suspended by someone else, started terminating, or was + // written again between our read and our write, so flux-plunger does not own + // it. Do not delete its storage Secret; the write that got in between is an + // update event, and the next reconcile handles the release as it now is. + logger.Info("HelmRelease was not acquired for recovery, deferring to next reconcile") + r.recordEvent(hr, corev1.EventTypeNormal, "RecoveryDeferred", + "Deferred recovery: spec.suspend was taken by another manager or the release began terminating between read and write; will retry on the next reconcile") + return ctrl.Result{}, nil + } + + // From here flux-plunger owns the suspension (acquired above). Guarantee it is + // released before returning from any path below: a step that fails must never + // leave the HelmRelease suspended, because a delete arriving on a suspended + // release makes helm-controller skip the uninstall and orphan the release's + // resources. The unsuspend is idempotent, so the happy path running it + // explicitly and this deferred fallback are safe together. + completed := false + defer func() { + if completed { + return + } + if err := r.unsuspendHelmRelease(ctx, hr); err != nil { + logger.Info("Could not clear suspension after failed recovery step, will retry on next reconcile", "error", err.Error()) + r.recordUnsuspendFailed(hr, err) + } + }() + + // Record the version we are about to reclaim BEFORE deleting its storage + // Secret. The "already processed" guard above keys on this annotation, so + // writing it first means a failed write can never authorise deleting the NEXT + // revision on the following requeue: on failure we return here, the deferred + // unsuspend clears the suspension, and the retry re-deletes the SAME revision + // (idempotent) instead of walking down the release history one Secret per + // requeue until none is left, which would itself orphan the release. That covers + // a failed write or delete only: the guard compares revision numbers, so it cannot + // tell them from a revision Helm re-creates under the same number after the + // delete, and such a revision is reclaimed again. Requeue with backoff on failure, + // symmetric with every other step. + logger.Info("Updating annotation with processed version", "version", latestVersion) + if err := r.updateProcessedVersionAnnotation(ctx, hr, latestVersion); err != nil { + logger.Info("Could not update annotation, requeuing", "error", err.Error()) + return ctrl.Result{}, err + } + + // A delete can land between acquiring the suspension and here. Deleting the + // storage Secret of a terminating release removes the only revision + // helm-controller could uninstall; it then treats the release as already gone, + // drops its finalizer, and orphans the resources — the exact failure this + // recovery exists to prevent, reached by a narrower race than the suspended one. + // The top-of-Reconcile check and suspendHelmRelease's re-fetch only see a delete + // visible earlier, so re-check immediately before the delete. On termination, + // leave the Secret intact and return: the deferred unsuspend clears our + // suspension so helm-controller runs the uninstall against the intact revision. + // This narrows the window to the Get-then-Delete gap but cannot fully close it — + // there is no HelmRelease+Secret transaction — so a delete landing in that gap is + // an accepted residual, the tightest a two-object check-then-act allows. + terminating, err := r.releaseIsTerminating(ctx, hr) + if err != nil { + logger.Info("Could not re-check deletion before deleting the storage Secret, requeuing", "error", err.Error()) + return ctrl.Result{}, err + } + if terminating { + // Clear our suspension explicitly and requeue on failure. Leaving it to the + // log-only deferred fallback would let a failed unsuspend strand an owned + // suspension on a terminating release with nothing retrying it — the exact + // state that makes helm-controller skip the uninstall and orphan the + // resources. The Secret is left intact so the uninstall has a revision. + logger.Info("HelmRelease started terminating during recovery, clearing suspension so helm-controller can uninstall") + if err := r.unsuspendHelmRelease(ctx, hr); err != nil { + logger.Info("Could not clear suspension on terminating release, requeuing", "error", err.Error()) + r.recordUnsuspendFailed(hr, err) + // The returned error requeues and retries; skip the redundant deferred attempt. + completed = true + return ctrl.Result{}, err + } + completed = true return ctrl.Result{}, nil } @@ -146,22 +360,141 @@ func (r *FluxPlunger) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Res return ctrl.Result{}, err } - // Update annotation with processed version - logger.Info("Updating annotation with processed version", "version", latestVersion) - if err := r.updateProcessedVersionAnnotation(ctx, hr, latestVersion); err != nil { - logger.Info("Could not update annotation, will retry on next reconcile", "error", err.Error()) - return ctrl.Result{}, nil - } - - // Unsuspend the HelmRelease + // Unsuspend the HelmRelease. Force a backoff requeue on failure, symmetric with + // the deletion path: a persistently failing unsuspend (e.g. an admission webhook + // rejecting the patch) would otherwise leave the release suspended-by-plunger + // until the informer's periodic resync, far longer than necessary. logger.Info("Unsuspending HelmRelease") if err := r.unsuspendHelmRelease(ctx, hr); err != nil { - logger.Info("Could not unsuspend HelmRelease, will retry on next reconcile", "error", err.Error()) + logger.Info("Could not unsuspend HelmRelease, requeuing", "error", err.Error()) + r.recordUnsuspendFailed(hr, err) + // The returned error requeues and retries; skip the redundant deferred attempt. + completed = true + return ctrl.Result{}, err + } + + completed = true + logger.Info("Successfully processed HelmRelease", "version", latestVersion) + return ctrl.Result{}, nil +} + +// reconcileTerminating makes a delete of a release flux-plunger is recovering reach +// the Helm uninstall. helm-controller v1.5.x skips the uninstall and drops its +// finalizer for a suspended HelmRelease +// (https://github.com/fluxcd/helm-controller/blob/v1.5.0/internal/controller/helmrelease_controller.go#L447-L475), +// and it handles the delete on the same event flux-plunger does. The fence +// finalizer keeps the object whichever handles it first; flux-plunger lifts its own +// suspension, which bumps the generation and makes helm-controller reconcile the +// unsuspended release and uninstall it, and only then lifts the fence. A terminating +// release never begins recovery. +func (r *FluxPlunger) reconcileTerminating(ctx context.Context, hr *helmv2.HelmRelease) (ctrl.Result, error) { + logger := log.FromContext(ctx) + + if hr.Spec.Suspend && r.ownsSuspension(hr) { + logger.Info("HelmRelease is being deleted while suspended by flux-plunger, clearing suspension so uninstall can proceed") + if err := r.unsuspendHelmRelease(ctx, hr); err != nil { + logger.Info("Could not clear suspension on deleted HelmRelease, requeuing", "error", err.Error()) + r.recordUnsuspendFailed(hr, err) + return ctrl.Result{}, err + } + // helm-controller's reconcile of the new generation updates the status, + // which wakes this controller again to lift the fence. return ctrl.Result{}, nil } - logger.Info("Successfully processed HelmRelease", "version", latestVersion) - return ctrl.Result{}, nil + if hr.Spec.Suspend { + // Another manager's suspension: helm-controller skips the uninstall for it + // and leaves the release's resources in place, which a migration that + // suspends then deletes relies on. That is not flux-plunger's decision to + // override, and not a release its fence should hold. A release that + // carries flux-plunger's processed-version annotation was recovered before, + // so the suspension that skips its uninstall was not a migration's choice (an + // operator's hand, or one an earlier flux-plunger release left behind): that + // is the orphaning this controller exists to prevent, and a Warning. + logger.Info("HelmRelease is being deleted while suspended by another manager; helm-controller skips the uninstall") + if _, recovered := hr.Annotations[annotationLastProcessedVersion]; recovered { + r.recordEvent(hr, corev1.EventTypeWarning, "TerminatingWhileSuspended", + "HelmRelease is being deleted while suspended by another manager; helm-controller skips the Helm uninstall for a suspended release, so its resources are left behind") + } else { + r.recordEvent(hr, corev1.EventTypeNormal, "TerminatingWhileSuspended", + "HelmRelease is being deleted while suspended by another manager; helm-controller skips the Helm uninstall for a suspended release and leaves its resources in place") + } + return ctrl.Result{}, r.releaseFence(ctx, hr) + } + + if !controllerutil.ContainsFinalizer(hr, fenceFinalizer) { + return ctrl.Result{}, nil + } + if uninstallReached(hr) { + logger.Info("helm-controller has handled the unsuspended release, lifting the uninstall fence") + return ctrl.Result{}, r.releaseFence(ctx, hr) + } + // Still waiting for helm-controller to handle the unsuspended release. Re-check + // on a timer rather than only on its next status write, which never comes if it + // is not running, and say so once the delete has been held past the deadline. + if held := r.clock().Sub(hr.DeletionTimestamp.Time); held >= fenceHeldWarnAfter { + logger.Info("HelmRelease delete is still held by the uninstall fence, waiting for helm-controller", "held", held.String()) + r.recordEvent(hr, corev1.EventTypeWarning, "UninstallFenceHeld", + "HelmRelease delete is held by flux-plunger's uninstall fence until helm-controller handles the unsuspended release; check that helm-controller is running and reconciling it") + } + return ctrl.Result{RequeueAfter: fenceRecheckInterval}, nil +} + +// releaseFence removes flux-plunger's fence finalizer by relinquishing it. Callers +// hold no suspension of their own at this point: the relinquishing apply drops +// every field flux-plunger's manager owns. +func (r *FluxPlunger) releaseFence(ctx context.Context, hr *helmv2.HelmRelease) error { + if !controllerutil.ContainsFinalizer(hr, fenceFinalizer) { + return nil + } + return r.applyRecoveryState(ctx, hr, nil, false, false) +} + +// ownsSuspensionManagedFields reports whether flux-plunger owns the spec.suspend +// field via its server-side-apply field manager, recorded by the apiserver in +// metadata.managedFields. This is the sole ownership signal, and it is exact in +// the ways a bare annotation marker was not: +// +// - An operator (or `cozyhr resume`, or the backup controller) that resumes and +// later re-suspends the release writes spec.suspend under its own manager, so +// the apiserver transfers the field away from flux-plunger and this returns +// false — the later suspension is never misread as ours and cleared out from +// under them, the one boundary this controller must never cross. +// - An unrelated re-apply of other spec fields (the routine reconcile of the +// cozystack operator or helm-controller) leaves spec.suspend's owner untouched, +// so flux-plunger keeps ownership of a suspension it is mid-recovery on — no +// self-disown, unlike keying ownership on metadata.generation. +func ownsSuspensionManagedFields(hr *helmv2.HelmRelease) bool { + for _, e := range hr.ManagedFields { + if e.Manager == suspendFieldManager && + e.Operation == metav1.ManagedFieldsOperationApply && + fieldsManageSuspend(e.FieldsV1) { + return true + } + } + return false +} + +// fieldsManageSuspend reports whether a managed-fields set includes spec.suspend, +// encoded by the apiserver as {"f:spec":{"f:suspend":{}}}. +func fieldsManageSuspend(fs *metav1.FieldsV1) bool { + if fs == nil || len(fs.Raw) == 0 { + return false + } + var top map[string]json.RawMessage + if err := json.Unmarshal(fs.Raw, &top); err != nil { + return false + } + specRaw, ok := top["f:spec"] + if !ok { + return false + } + var spec map[string]json.RawMessage + if err := json.Unmarshal(specRaw, &spec); err != nil { + return false + } + _, ok = spec["f:suspend"] + return ok } // hasNoDeployedReleasesError checks if the HelmRelease has the specific error @@ -176,7 +509,21 @@ func hasNoDeployedReleasesError(hr *helmv2.HelmRelease) bool { return false } -// listHelmReleaseSecrets lists all Helm release secrets for a specific release +// listHelmReleaseSecrets lists all Helm release secrets for a specific release. +// +// It reads through the uncached APIReader (when wired). This is not only a race +// guard but a correctness fix: the controller's cached client (mgr.GetClient()) +// would serve this List from an informer, and the ClusterRole grants secrets only +// get/list, NOT watch, which an informer needs to stay synced — so a cached List +// cannot reliably reflect the cluster (stale at best, unsynced at worst, with a +// steady stream of watch-forbidden errors). Reading directly from the apiserver via +// the APIReader needs only get/list and sidesteps the informer entirely. +// getLatestSecret over the result also chooses which storage Secret is deleted and +// which version the processed annotation records, and this List runs before the +// release is suspended, exactly when helm-controller may still be creating a +// revision Secret — the same race the other re-reads guard against — so the direct +// read is doubly warranted. flux-plunger deliberately does NOT cache Secrets (no +// watch RBAC, and it would mean watching every Secret in the cluster). func (r *FluxPlunger) listHelmReleaseSecrets(ctx context.Context, namespace, releaseName string) ([]corev1.Secret, error) { secretList := &corev1.SecretList{} listOpts := []client.ListOption{ @@ -187,7 +534,11 @@ func (r *FluxPlunger) listHelmReleaseSecrets(ctx context.Context, namespace, rel }, } - if err := r.List(ctx, secretList, listOpts...); err != nil { + lister := client.Reader(r.Client) + if r.APIReader != nil { + lister = r.APIReader + } + if err := lister.List(ctx, secretList, listOpts...); err != nil { return nil, fmt.Errorf("failed to list secrets: %w", err) } @@ -240,44 +591,177 @@ func extractVersionNumber(secretName string) int { return num } -// suspendHelmRelease sets suspend to true on the HelmRelease -func (r *FluxPlunger) suspendHelmRelease(ctx context.Context, hr *helmv2.HelmRelease) error { - // Re-fetch the HelmRelease to get the latest state - key := types.NamespacedName{Namespace: hr.Namespace, Name: hr.Name} - latestHR := &helmv2.HelmRelease{} - if err := r.Get(ctx, key, latestHR); err != nil { - return fmt.Errorf("failed to get latest HelmRelease: %w", err) +// applyRecoveryState server-side-applies the fields flux-plunger's field manager +// owns during a recovery: spec.suspend and the fence finalizer, and nothing else. +// Whatever the body leaves out is relinquished. value == nil omits spec.suspend +// (when flux-plunger is its sole manager the field reverts to the unsuspended +// default); value != nil sets it to *value. fence declares the fence finalizer; +// metadata.finalizers is a set, so this adds or drops only flux-plunger's entry and +// leaves helm-controller's alone. force appends client.ForceOwnership. +// +// The apply body is an unstructured object carrying just metadata and these +// fields, NOT a typed HelmReleaseSpec: marshaling a typed spec would also emit +// spec.interval ("0s", it is a required field without omitempty), and applying +// that over a release whose interval another manager owns conflicts on +// spec.interval and never suspends, while forcing would reset the release's +// reconcile interval. +func (r *FluxPlunger) applyRecoveryState(ctx context.Context, hr *helmv2.HelmRelease, value *bool, fence, force bool) error { + apply := &unstructured.Unstructured{} + apply.SetGroupVersionKind(helmv2.GroupVersion.WithKind("HelmRelease")) + apply.SetNamespace(hr.Namespace) + apply.SetName(hr.Name) + // Precondition every apply on the object the caller read, so a write or delete + // that lands after that read is rejected with a conflict and the decision is + // taken again on the new state. The resourceVersion covers a change: unforced, + // the apiserver would otherwise accept true over a foreign true as shared + // ownership; forced, take the field over; and a relinquish decided on a live + // release would remove the fence after helm-controller had already dropped its + // finalizer on a delete, deleting the release without an uninstall. The uid + // covers a release that is gone: server-side apply creates what does not exist, + // and only a uid mismatch stops it resurrecting an empty HelmRelease. + apply.SetResourceVersion(hr.ResourceVersion) + apply.SetUID(hr.UID) + if fence { + apply.SetFinalizers([]string{fenceFinalizer}) } - - // If already suspended, nothing to do - if latestHR.Spec.Suspend { - return nil + if value != nil { + if err := unstructured.SetNestedField(apply.Object, *value, "spec", "suspend"); err != nil { + return err + } } - - patch := client.MergeFromWithOptions(latestHR.DeepCopy(), client.MergeFromWithOptimisticLock{}) - latestHR.Spec.Suspend = true - - return r.Patch(ctx, latestHR, patch, client.FieldOwner(fieldManager)) + opts := []client.PatchOption{client.FieldOwner(suspendFieldManager)} + if force { + opts = append(opts, client.ForceOwnership) + } + return r.Patch(ctx, apply, client.Apply, opts...) } -// unsuspendHelmRelease sets suspend to false on the HelmRelease -func (r *FluxPlunger) unsuspendHelmRelease(ctx context.Context, hr *helmv2.HelmRelease) error { +// suspendHelmRelease takes ownership of a fresh suspension via server-side apply. +// It reports whether it acquired one: false means the release was already +// suspended by someone else, or it started terminating after the top-of-Reconcile +// check, so the caller must not proceed as if it owns it. +// +// Both applies set the fence finalizer together with the suspension, so there is +// no moment at which flux-plunger holds a suspension a delete could slip past, and +// both are preconditioned on the resourceVersion of the read that decided on them +// (see applyRecoveryState), so any write landing after that read makes the apply +// fail with a conflict rather than be absorbed. +// +// The apply is attempted WITHOUT force first. A fresh, unowned spec.suspend applies +// cleanly and flux-plunger owns it. A conflict means the release changed since the +// read, or another manager already owns the field: this repo's backup controllers +// set spec.suspend via a dynamic-client Update (setCNPGRestoreHRSuspended / +// setEtcdRestoreHRSuspended / velero's suspendHelmRelease), and earlier flux-plunger +// releases owned it via a merge Patch, so a non-forced apply would 409 forever and +// flux-plunger could never recover such a release. On conflict we re-fetch and force +// ONLY if spec.suspend is still false: a manager owning the field at false is stale +// ownership safe to take over, while a value of true is an ACTIVE suspension (an +// operator's, or a backup mid-restore) that flux-plunger must never clear. A +// conflict on the forced retry means yet another write landed after the re-read, +// the same race as a foreign suspension seen on the re-read, so it is reported the +// same way: not acquired, no error. +func (r *FluxPlunger) suspendHelmRelease(ctx context.Context, hr *helmv2.HelmRelease) (bool, error) { // Re-fetch the HelmRelease to get the latest state key := types.NamespacedName{Namespace: hr.Namespace, Name: hr.Name} latestHR := &helmv2.HelmRelease{} - if err := r.Get(ctx, key, latestHR); err != nil { + if err := r.refetch(ctx, key, latestHR); err != nil { + return false, fmt.Errorf("failed to get latest HelmRelease: %w", err) + } + + // Never suspend a terminating release. A delete can arrive between the + // top-of-Reconcile deletion check and this re-fetch, and suspending a release + // helm-controller is about to uninstall is exactly what makes it skip the + // uninstall and orphan the release's resources. + if !latestHR.DeletionTimestamp.IsZero() { + return false, nil + } + + // If already suspended, do not take ownership of a suspension we did not set. + if latestHR.Spec.Suspend { + return false, nil + } + + suspendTrue := true + err := r.applyRecoveryState(ctx, latestHR, &suspendTrue, true, false) + if err == nil { + return true, nil + } + if !apierrors.IsConflict(err) { + return false, err + } + + // Conflict: another manager owns spec.suspend. Re-read its value and force only + // if it is still unsuspended (stale ownership); leave an active suspension alone. + // Decode into a FRESH object: client-go's Get unmarshals into the receiver without + // zeroing it, so a field absent from the second response (spec.suspend is + // omitempty) would otherwise retain the first read's value. + rechecked := &helmv2.HelmRelease{} + if err := r.refetch(ctx, key, rechecked); err != nil { + return false, fmt.Errorf("failed to re-fetch HelmRelease after suspend conflict: %w", err) + } + if !rechecked.DeletionTimestamp.IsZero() { + return false, nil + } + if rechecked.Spec.Suspend { + return false, nil + } + if err := r.applyRecoveryState(ctx, rechecked, &suspendTrue, true, true); err != nil { + if apierrors.IsConflict(err) { + return false, nil + } + return false, err + } + return true, nil +} + +// releaseIsTerminating re-fetches the HelmRelease and reports whether it has begun +// terminating. Recovery calls this immediately before deleting the storage Secret +// so a delete that landed after the earlier checks cannot make it remove the only +// revision helm-controller could uninstall. A release that is already gone counts +// as terminating. +func (r *FluxPlunger) releaseIsTerminating(ctx context.Context, hr *helmv2.HelmRelease) (bool, error) { + key := types.NamespacedName{Namespace: hr.Namespace, Name: hr.Name} + latestHR := &helmv2.HelmRelease{} + if err := r.refetch(ctx, key, latestHR); err != nil { + if apierrors.IsNotFound(err) { + return true, nil + } + return false, fmt.Errorf("failed to get latest HelmRelease: %w", err) + } + return !latestHR.DeletionTimestamp.IsZero(), nil +} + +// unsuspendHelmRelease clears a suspension flux-plunger owns by relinquishing the +// spec.suspend field: a server-side apply that no longer declares it, which reverts +// the field to unsuspended (flux-plunger being its only manager) and drops +// flux-plunger's ownership. On a live release the fence goes with it. On a +// terminating one the fence stays: helm-controller may already have dropped its +// finalizer without an uninstall, and the fence is what keeps the object until it +// reconciles the unsuspended release (reconcileTerminating lifts it then). A +// release that is already gone has nothing left to clear. +// +// Callers already gate on ownership; the re-fetched ownership check here is +// defense-in-depth against a future caller that forgets to, so an operator's +// suspension, for which the apiserver has already transferred the field away from +// flux-plunger, is never cleared by accident. +func (r *FluxPlunger) unsuspendHelmRelease(ctx context.Context, hr *helmv2.HelmRelease) error { + key := types.NamespacedName{Namespace: hr.Namespace, Name: hr.Name} + latestHR := &helmv2.HelmRelease{} + if err := r.refetch(ctx, key, latestHR); err != nil { + if apierrors.IsNotFound(err) { + return nil + } return fmt.Errorf("failed to get latest HelmRelease: %w", err) } - // If already unsuspended, nothing to do - if !latestHR.Spec.Suspend { + // Nothing to do if flux-plunger does not own the suspension: either it is + // already unsuspended, or the field belongs to another manager now. + if !r.ownsSuspension(latestHR) { return nil } - patch := client.MergeFromWithOptions(latestHR.DeepCopy(), client.MergeFromWithOptimisticLock{}) - latestHR.Spec.Suspend = false - - return r.Patch(ctx, latestHR, patch, client.FieldOwner(fieldManager)) + keepFence := !latestHR.DeletionTimestamp.IsZero() && controllerutil.ContainsFinalizer(latestHR, fenceFinalizer) + return r.applyRecoveryState(ctx, latestHR, nil, keepFence, false) } // updateProcessedVersionAnnotation updates the annotation with the processed version @@ -285,7 +769,7 @@ func (r *FluxPlunger) updateProcessedVersionAnnotation(ctx context.Context, hr * // Re-fetch the HelmRelease to get the latest state key := types.NamespacedName{Namespace: hr.Namespace, Name: hr.Name} latestHR := &helmv2.HelmRelease{} - if err := r.Get(ctx, key, latestHR); err != nil { + if err := r.refetch(ctx, key, latestHR); err != nil { return fmt.Errorf("failed to get latest HelmRelease: %w", err) } @@ -299,35 +783,41 @@ func (r *FluxPlunger) updateProcessedVersionAnnotation(ctx context.Context, hr * return r.Patch(ctx, latestHR, patch, client.FieldOwner(fieldManager)) } +// watchPredicate selects the HelmReleases flux-plunger reconciles: those carrying +// the specific error, a suspension flux-plunger owns (crash recovery, and a delete +// arriving mid-recovery, both need to wake a reconcile), flux-plunger's fence, or +// any suspended release that is being deleted. Kept a named method so a test can +// pin it. +func (r *FluxPlunger) watchPredicate(obj client.Object) bool { + hr, ok := obj.(*helmv2.HelmRelease) + if !ok { + return false + } + if hasNoDeployedReleasesError(hr) { + return true + } + if hr.Spec.Suspend && r.ownsSuspension(hr) { + return true + } + // The fence is lifted in response to helm-controller's status update after the + // uninstall, which carries neither the error nor a flux-plunger suspension. + if controllerutil.ContainsFinalizer(hr, fenceFinalizer) { + return true + } + // A suspended release being deleted skips the Helm uninstall even when the + // suspension is someone else's and the release is healthy: Reconcile has to see it + // to record TerminatingWhileSuspended. + if hr.Spec.Suspend && !hr.DeletionTimestamp.IsZero() { + return true + } + return false +} + // SetupWithManager sets up the controller with the Manager func (r *FluxPlunger) SetupWithManager(mgr ctrl.Manager) error { - // Watch HelmReleases that either: - // 1. Have the specific error, OR - // 2. Are suspended with our annotation (to handle crash recovery) - pred := predicate.NewPredicateFuncs(func(obj client.Object) bool { - hr, ok := obj.(*helmv2.HelmRelease) - if !ok { - return false - } - - // Always process if has error - if hasNoDeployedReleasesError(hr) { - return true - } - - // Also process suspended HelmReleases with our annotation (crash recovery) - if hr.Spec.Suspend && hr.Annotations != nil { - if _, exists := hr.Annotations[annotationLastProcessedVersion]; exists { - return true - } - } - - return false - }) - return ctrl.NewControllerManagedBy(mgr). Named("fluxplunger"). For(&helmv2.HelmRelease{}). - WithEventFilter(pred). + WithEventFilter(predicate.NewPredicateFuncs(r.watchPredicate)). Complete(r) } diff --git a/internal/controller/fluxplunger/flux_plunger_test.go b/internal/controller/fluxplunger/flux_plunger_test.go new file mode 100644 index 000000000..91dbba869 --- /dev/null +++ b/internal/controller/fluxplunger/flux_plunger_test.go @@ -0,0 +1,2081 @@ +// SPDX-License-Identifier: Apache-2.0 +// Copyright 2026 The Cozystack Authors. + +package fluxplunger + +import ( + "context" + "errors" + "strings" + "testing" + "time" + + helmv2 "github.com/fluxcd/helm-controller/api/v2" + corev1 "k8s.io/api/core/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/runtime/schema" + "k8s.io/apimachinery/pkg/types" + clientgoscheme "k8s.io/client-go/kubernetes/scheme" + "k8s.io/client-go/tools/record" + ctrl "sigs.k8s.io/controller-runtime" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/client/fake" + "sigs.k8s.io/controller-runtime/pkg/client/interceptor" + "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil" +) + +const ( + testNS = "tenant-root" + testName = "vm-disk-0" + // helm-controller's finalizer; present on every reconciled HelmRelease and + // required by the fake client for any object carrying a deletionTimestamp. + helmFinalizer = "finalizers.fluxcd.io" +) + +func testScheme(t *testing.T) *runtime.Scheme { + t.Helper() + s := runtime.NewScheme() + if err := clientgoscheme.AddToScheme(s); err != nil { + t.Fatalf("add client-go scheme: %v", err) + } + if err := helmv2.AddToScheme(s); err != nil { + t.Fatalf("add helm scheme: %v", err) + } + return s +} + +// The controller-runtime fake client does not persist metadata.managedFields, so +// the production ownership check (ownsSuspensionManagedFields, verified by +// TestOwnsSuspensionManagedFields and the envtest suite) cannot be exercised +// through it. Behavioural tests inject FluxPlunger.owns with testOwns, a stand-in +// that reads a plain annotation the fake client DOES persist, and ssaModelApply +// maintains that annotation with the same dynamics the apiserver gives +// managedFields: set on flux-plunger's suspend apply, dropped on its relinquish. +const testOwnedKey = "test.fluxplunger.cozystack.io/owned" + +func testOwns(hr *helmv2.HelmRelease) bool { + return hr.Annotations[testOwnedKey] == "true" +} + +// ownedFixture marks a HelmRelease as suspended and owned by flux-plunger. +func ownedFixture(hr *helmv2.HelmRelease) *helmv2.HelmRelease { + hr.Spec.Suspend = true + if hr.Annotations == nil { + hr.Annotations = map[string]string{} + } + hr.Annotations[testOwnedKey] = "true" + return hr +} + +// newPlunger builds the reconciler with the injected test ownership check. +func newPlunger(c client.Client) *FluxPlunger { + return &FluxPlunger{Client: c, owns: testOwns} +} + +// suspendManagedFields builds a managedFields entry for the pure-unit test of the +// real ownership check. +func suspendManagedFields(manager string, op metav1.ManagedFieldsOperationType) []metav1.ManagedFieldsEntry { + return []metav1.ManagedFieldsEntry{{ + Manager: manager, + Operation: op, + APIVersion: helmv2.GroupVersion.String(), + FieldsType: "FieldsV1", + FieldsV1: &metav1.FieldsV1{Raw: []byte(`{"f:spec":{"f:suspend":{}}}`)}, + }} +} + +// noDeployedReleasesHR builds a HelmRelease stuck with the "has no deployed +// releases" error that flux-plunger is meant to recover. +func noDeployedReleasesHR() *helmv2.HelmRelease { + return &helmv2.HelmRelease{ + ObjectMeta: metav1.ObjectMeta{ + Namespace: testNS, + Name: testName, + Finalizers: []string{helmFinalizer}, + }, + Status: helmv2.HelmReleaseStatus{ + Conditions: []metav1.Condition{{ + Type: "Ready", + Status: metav1.ConditionFalse, + Reason: "InstallFailed", + Message: "Helm install failed: " + errorMessageNoDeployedReleases, + }}, + }, + } +} + +func helmReleaseSecret(version string) *corev1.Secret { + return &corev1.Secret{ + ObjectMeta: metav1.ObjectMeta{ + Namespace: testNS, + Name: "sh.helm.release.v1." + testName + "." + version, + Labels: map[string]string{ + "name": testName, + "owner": "helm", + }, + }, + Type: "helm.sh/release.v1", + } +} + +func getHR(t *testing.T, c client.Client) *helmv2.HelmRelease { + t.Helper() + hr := &helmv2.HelmRelease{} + if err := c.Get(context.Background(), types.NamespacedName{Namespace: testNS, Name: testName}, hr); err != nil { + t.Fatalf("get HelmRelease: %v", err) + } + return hr +} + +// expectWarning drains the recorded events and fails unless one is a Warning with +// the given reason. +func expectWarning(t *testing.T, rec *record.FakeRecorder, reason string) { + t.Helper() + var seen []string + for { + select { + case e := <-rec.Events: + if strings.HasPrefix(e, corev1.EventTypeWarning+" "+reason+" ") { + return + } + seen = append(seen, e) + default: + t.Fatalf("expected a Warning %s event, got %q", reason, seen) + } + } +} + +func reconcile(t *testing.T, r *FluxPlunger) { + t.Helper() + _, _ = r.Reconcile(context.Background(), ctrl.Request{ + NamespacedName: types.NamespacedName{Namespace: testNS, Name: testName}, + }) +} + +// ssaModelApply models, on the fake client, what a real apiserver does with a +// flux-plunger server-side apply of spec.suspend, recorded via the test ownership +// annotation instead of managedFields (which the fake client drops): apply +// suspend=true and set the owned annotation; on the relinquish apply (suspend +// omitted), revert suspend to false and drop the annotation. This is exactly the +// dynamics the build-tagged envtest suite (ssa_ownership_envtest_test.go) proves +// against a real apiserver: an apply of true takes ownership, and a sole-owner +// relinquish reverts to false and drops the owner. Any other patch passes through +// unchanged. +// +// LIMITATION: this models NET STATE only. It treats every flux-plunger apply that +// carries suspend=false OR omits the field as "clear the suspension", so it cannot +// distinguish a relinquish (omit) from a forced set-false — on a real apiserver a +// relinquish leaves a value another manager owns unchanged, while a forced apply +// moves it. A test that depends on that distinction must assert the request SHAPE +// via plungerApplyDetail (present/value/force), not the resulting object; a test +// that checks only the object state is blind to it and can pass against broken code. +func ssaModelApply(ctx context.Context, cl client.WithWatch, obj client.Object, patch client.Patch, opts ...client.PatchOption) error { + po := &client.PatchOptions{} + po.ApplyOptions(opts) + suspend, isPlunger := plungerApplySuspend(obj, patch, po) + if !isPlunger { + return cl.Patch(ctx, obj, patch, opts...) + } + // Model the net effect with a plain Get+Update rather than the real SSA apply: + // the fake client's Apply strips unmanaged fields (it would drop a finalizer off + // a deleting object and garbage-collect it), which is a fake-client artefact, not + // apiserver behaviour. Get+Update preserves finalizers and status while applying + // exactly the suspend/ownership transition. + cur := &helmv2.HelmRelease{} + if err := cl.Get(ctx, client.ObjectKeyFromObject(obj), cur); err != nil { + return err + } + if cur.Annotations == nil { + cur.Annotations = map[string]string{} + } + switch { + case suspend: + cur.Spec.Suspend = true + cur.Annotations[testOwnedKey] = "true" + case cur.Annotations[testOwnedKey] == "true": + // Relinquishing a suspension flux-plunger owns reverts it; one another + // manager owns keeps its value. + cur.Spec.Suspend = false + delete(cur.Annotations, testOwnedKey) + } + // The fence finalizer follows the body, and, like the apiserver, a new + // finalizer cannot be added to an object that is being deleted. + wantFence := false + for _, f := range obj.GetFinalizers() { + if f == fenceFinalizer { + wantFence = true + } + } + hasFence := controllerutil.ContainsFinalizer(cur, fenceFinalizer) + if wantFence && !hasFence { + if !cur.DeletionTimestamp.IsZero() { + return apierrors.NewForbidden(schema.GroupResource{Group: "helm.toolkit.fluxcd.io", Resource: "helmreleases"}, + cur.Name, errors.New("no new finalizers can be added if the object is being deleted")) + } + controllerutil.AddFinalizer(cur, fenceFinalizer) + } + if !wantFence && hasFence { + controllerutil.RemoveFinalizer(cur, fenceFinalizer) + } + return cl.Update(ctx, cur) +} + +// plungerApplyDetail reports the shape of a flux-plunger spec.suspend apply so a +// test can tell whether it forces ownership: acquire attempts an unforced apply +// (present, value true, force false) first and forces (force true) only over a +// field re-read as false. plungerApplySuspend does not expose the force flag; this +// does. +func plungerApplyDetail(obj client.Object, patch client.Patch, opts []client.PatchOption) (present, value, force, ok bool) { + po := &client.PatchOptions{} + po.ApplyOptions(opts) + u, isU := obj.(*unstructured.Unstructured) + if !isU || patch.Type() != types.ApplyPatchType || po.FieldManager != suspendFieldManager { + return false, false, false, false + } + val, found, _ := unstructured.NestedBool(u.Object, "spec", "suspend") + return found, val, po.Force != nil && *po.Force, true +} + +// plungerApplySuspend reports whether a patch is flux-plunger's server-side apply +// of spec.suspend (the production applySuspend sends an unstructured body carrying +// only spec.suspend) and, if so, the applied value (false when the field is +// omitted — the relinquish). The failure-injection tests use it to fail exactly +// the suspend or the unsuspend step. +func plungerApplySuspend(obj client.Object, patch client.Patch, po *client.PatchOptions) (suspend bool, ok bool) { + u, isU := obj.(*unstructured.Unstructured) + if !isU || patch.Type() != types.ApplyPatchType || po.FieldManager != suspendFieldManager { + return false, false + } + val, found, _ := unstructured.NestedBool(u.Object, "spec", "suspend") + return found && val, true +} + +// isPlungerApply is the boolean form used where the test only cares about a +// specific applied value. +func isPlungerApply(obj client.Object, patch client.Patch, opts []client.PatchOption, suspend bool) bool { + po := &client.PatchOptions{} + po.ApplyOptions(opts) + got, ok := plungerApplySuspend(obj, patch, po) + return ok && got == suspend +} + +// TestOwnsSuspensionManagedFields pins the production ownership predicate directly +// on hand-crafted managedFields: only flux-plunger's own Apply of spec.suspend +// counts, not an operator Update of the same field, nor an apply that manages +// other fields. This is the check the behavioural tests inject a stand-in for. +func TestOwnsSuspensionManagedFields(t *testing.T) { + cases := []struct { + name string + mf []metav1.ManagedFieldsEntry + want bool + }{ + {"plunger apply owns", suspendManagedFields(suspendFieldManager, metav1.ManagedFieldsOperationApply), true}, + // Isolates the operation conjunct: same manager as the owning case but an + // Update, which only the Operation==Apply term rejects. + {"plunger update does not count", suspendManagedFields(suspendFieldManager, metav1.ManagedFieldsOperationUpdate), false}, + {"operator update does not count", suspendManagedFields("kubectl", metav1.ManagedFieldsOperationUpdate), false}, + {"another manager apply does not count", suspendManagedFields("helm-controller", metav1.ManagedFieldsOperationApply), false}, + // fieldManager (flux-client-side-apply) is a SHARED client-side manager: the + // earlier flux-plunger releases, platform migrations and the tenant delete hook all + // set spec.suspend under it, so it does NOT identify flux-plunger — its + // ownership must never be read as flux-plunger's. + {"shared client-side manager does not count", suspendManagedFields(fieldManager, metav1.ManagedFieldsOperationUpdate), false}, + {"no managed fields", nil, false}, + {"plunger apply of other fields", []metav1.ManagedFieldsEntry{{ + Manager: suspendFieldManager, Operation: metav1.ManagedFieldsOperationApply, + FieldsType: "FieldsV1", FieldsV1: &metav1.FieldsV1{Raw: []byte(`{"f:spec":{"f:chart":{}}}`)}, + }}, false}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + hr := &helmv2.HelmRelease{ObjectMeta: metav1.ObjectMeta{ManagedFields: tc.mf}} + if got := ownsSuspensionManagedFields(hr); got != tc.want { + t.Fatalf("ownsSuspensionManagedFields=%v want %v", got, tc.want) + } + }) + } +} + +// The normal recovery of a stuck release must delete the latest storage Secret, +// record the processed version and leave the HelmRelease unsuspended and no +// longer owned by flux-plunger. +func TestReconcile_HappyPathRecovery(t *testing.T) { + hr := noDeployedReleasesHR() + secret := helmReleaseSecret("v3") + + c := fake.NewClientBuilder().WithScheme(testScheme(t)).WithObjects(hr, secret). + WithInterceptorFuncs(interceptor.Funcs{Patch: ssaModelApply}).Build() + r := newPlunger(c) + + reconcile(t, r) + + got := getHR(t, c) + if got.Spec.Suspend { + t.Fatalf("recovery must end unsuspended, got suspend=true") + } + if testOwns(got) { + t.Fatalf("recovery must relinquish ownership of the suspension") + } + if got.Annotations[annotationLastProcessedVersion] != "3" { + t.Fatalf("recovery must record the processed version, got %q", got.Annotations[annotationLastProcessedVersion]) + } + if err := c.Get(context.Background(), types.NamespacedName{Namespace: testNS, Name: secret.Name}, &corev1.Secret{}); !apierrors.IsNotFound(err) { + t.Fatalf("recovery must delete the latest Helm storage Secret, got err=%v", err) + } +} + +// If the release is suspended by someone else between flux-plunger's initial +// read and its own suspend write, recovery must abort without deleting the +// storage Secret: flux-plunger does not own that suspension. +func TestReconcile_AbortsWhenSuspendedConcurrently(t *testing.T) { + hr := noDeployedReleasesHR() + secret := helmReleaseSecret("v1") + + hrGets := 0 + c := fake.NewClientBuilder().WithScheme(testScheme(t)). + WithObjects(hr, secret). + WithInterceptorFuncs(interceptor.Funcs{ + Get: func(ctx context.Context, cl client.WithWatch, key client.ObjectKey, obj client.Object, opts ...client.GetOption) error { + if err := cl.Get(ctx, key, obj, opts...); err != nil { + return err + } + // The first Get is the top-of-reconcile read (must see suspend=false + // so recovery starts). The second Get is suspendHelmRelease's re-fetch: + // simulate an external actor having suspended it meanwhile (no plunger + // ownership). + if h, ok := obj.(*helmv2.HelmRelease); ok { + hrGets++ + if hrGets == 2 { + h.Spec.Suspend = true + } + } + return nil + }, + Patch: ssaModelApply, + }).Build() + r := newPlunger(c) + + reconcile(t, r) + + if err := c.Get(context.Background(), types.NamespacedName{Namespace: testNS, Name: secret.Name}, &corev1.Secret{}); apierrors.IsNotFound(err) { + t.Fatalf("recovery must not delete the storage Secret when it did not acquire the suspension") + } +} + +// If the release starts terminating after recovery already acquired the +// suspension (the delete lands at the pre-delete re-check), recovery must leave +// the storage Secret intact and clear its own suspension so helm-controller can +// uninstall the release cleanly. +func TestReconcile_TerminatingDuringRecoveryKeepsSecretAndClearsSuspension(t *testing.T) { + hr := noDeployedReleasesHR() + secret := helmReleaseSecret("v1") + + hrGets := 0 + c := fake.NewClientBuilder().WithScheme(testScheme(t)). + WithObjects(hr, secret). + WithInterceptorFuncs(interceptor.Funcs{ + Get: func(ctx context.Context, cl client.WithWatch, key client.ObjectKey, obj client.Object, opts ...client.GetOption) error { + if err := cl.Get(ctx, key, obj, opts...); err != nil { + return err + } + // Gets 1-3 are the top read, suspendHelmRelease's re-fetch and the + // annotation re-fetch (all must see a live release so recovery starts and + // acquires). The 4th Get is releaseIsTerminating's pre-delete re-check: + // simulate the delete having landed by then. + if h, ok := obj.(*helmv2.HelmRelease); ok { + hrGets++ + if hrGets >= 4 { + now := metav1.Now() + h.DeletionTimestamp = &now + h.Finalizers = []string{helmFinalizer} + } + } + return nil + }, + Patch: ssaModelApply, + }).Build() + r := newPlunger(c) + + reconcile(t, r) + + if err := c.Get(context.Background(), types.NamespacedName{Namespace: testNS, Name: secret.Name}, &corev1.Secret{}); apierrors.IsNotFound(err) { + t.Fatalf("terminating recovery must leave the storage Secret for helm-controller to uninstall") + } + got := getHR(t, c) + if got.Spec.Suspend { + t.Fatalf("terminating recovery must clear the suspension so helm-controller can uninstall, got suspend=true") + } +} + +// If the release starts terminating during recovery and clearing the suspension +// then fails, recovery must requeue with an error rather than return success: +// leaving an owned suspension on a terminating release is what makes +// helm-controller skip the uninstall and orphan the resources. +func TestReconcile_TerminatingDuringRecoveryRequeuesOnUnsuspendFailure(t *testing.T) { + hr := noDeployedReleasesHR() + secret := helmReleaseSecret("v1") + + hrGets := 0 + unsuspendApplies := 0 + c := fake.NewClientBuilder().WithScheme(testScheme(t)). + WithObjects(hr, secret). + WithInterceptorFuncs(interceptor.Funcs{ + Get: func(ctx context.Context, cl client.WithWatch, key client.ObjectKey, obj client.Object, opts ...client.GetOption) error { + if err := cl.Get(ctx, key, obj, opts...); err != nil { + return err + } + if h, ok := obj.(*helmv2.HelmRelease); ok { + hrGets++ + if hrGets >= 4 { + now := metav1.Now() + h.DeletionTimestamp = &now + h.Finalizers = []string{helmFinalizer} + } + } + return nil + }, + Patch: func(ctx context.Context, cl client.WithWatch, obj client.Object, patch client.Patch, opts ...client.PatchOption) error { + if isPlungerApply(obj, patch, opts, false) { + unsuspendApplies++ + return errors.New("simulated unsuspend apply failure") + } + return ssaModelApply(ctx, cl, obj, patch, opts...) + }, + }).Build() + rec := record.NewFakeRecorder(8) + r := newPlunger(c) + r.Recorder = rec + + _, err := r.Reconcile(context.Background(), ctrl.Request{NamespacedName: types.NamespacedName{Namespace: testNS, Name: testName}}) + if err == nil { + t.Fatalf("a failed unsuspend on a terminating release must requeue with an error, got nil") + } + // The returned error requeues the retry, so the deferred fallback must not make a + // second, redundant attempt (symmetric with the final-unsuspend path). + if unsuspendApplies != 1 { + t.Fatalf("want exactly 1 unsuspend attempt on the terminating path, got %d", unsuspendApplies) + } + expectWarning(t, rec, "UnsuspendFailed") +} + +// If a delete arrives between the top-of-Reconcile deletion check and the +// re-fetch inside suspendHelmRelease, recovery must abort without suspending the +// now-terminating release or deleting its storage Secret. +func TestReconcile_AbortsWhenDeletedConcurrently(t *testing.T) { + hr := noDeployedReleasesHR() + secret := helmReleaseSecret("v1") + + hrGets := 0 + c := fake.NewClientBuilder().WithScheme(testScheme(t)). + WithObjects(hr, secret). + WithInterceptorFuncs(interceptor.Funcs{ + Get: func(ctx context.Context, cl client.WithWatch, key client.ObjectKey, obj client.Object, opts ...client.GetOption) error { + if err := cl.Get(ctx, key, obj, opts...); err != nil { + return err + } + if h, ok := obj.(*helmv2.HelmRelease); ok { + hrGets++ + if hrGets == 2 { + now := metav1.Now() + h.DeletionTimestamp = &now + h.Finalizers = []string{helmFinalizer} + } + } + return nil + }, + Patch: ssaModelApply, + }).Build() + r := newPlunger(c) + + reconcile(t, r) + + got := getHR(t, c) + if got.Spec.Suspend { + t.Fatalf("recovery must not suspend a release that started terminating, got suspend=true") + } + if err := c.Get(context.Background(), types.NamespacedName{Namespace: testNS, Name: secret.Name}, &corev1.Secret{}); apierrors.IsNotFound(err) { + t.Fatalf("recovery must not delete the storage Secret of a release that started terminating") + } +} + +// A HelmRelease deleted while flux-plunger owns its suspension must have that +// suspension cleared, otherwise helm-controller v1.5.x skips the uninstall. +func TestReconcile_DeletionClearsPlungerSuspension(t *testing.T) { + hr := noDeployedReleasesHR() + ownedFixture(hr) + now := metav1.Now() + hr.DeletionTimestamp = &now + + c := fake.NewClientBuilder().WithScheme(testScheme(t)).WithObjects(hr). + WithInterceptorFuncs(interceptor.Funcs{Patch: ssaModelApply}).Build() + r := newPlunger(c) + + reconcile(t, r) + + got := getHR(t, c) + if got.Spec.Suspend { + t.Fatalf("suspension must be cleared on a deleted HelmRelease so uninstall can proceed, got suspend=true") + } +} + +// flux-plunger must never begin recovery (suspend) on a HelmRelease that is +// already terminating. +func TestReconcile_DoesNotSuspendTerminatingHelmRelease(t *testing.T) { + hr := noDeployedReleasesHR() + now := metav1.Now() + hr.DeletionTimestamp = &now + + secret := helmReleaseSecret("v1") + c := fake.NewClientBuilder().WithScheme(testScheme(t)).WithObjects(hr, secret). + WithInterceptorFuncs(interceptor.Funcs{Patch: ssaModelApply}).Build() + r := newPlunger(c) + + reconcile(t, r) + + got := getHR(t, c) + if got.Spec.Suspend { + t.Fatalf("flux-plunger must not suspend a terminating HelmRelease, got suspend=true") + } + if err := c.Get(context.Background(), types.NamespacedName{Namespace: testNS, Name: secret.Name}, &corev1.Secret{}); err != nil { + t.Fatalf("flux-plunger must not touch the Helm storage Secret of a terminating release: %v", err) + } +} + +// A recovery step that fails after flux-plunger has suspended the release must +// not leave it suspended, or a later delete would skip the uninstall. +func TestReconcile_FailedStepDoesNotLeaveSuspended(t *testing.T) { + hr := noDeployedReleasesHR() + secret := helmReleaseSecret("v1") + + c := fake.NewClientBuilder().WithScheme(testScheme(t)). + WithObjects(hr, secret). + WithInterceptorFuncs(interceptor.Funcs{ + Patch: ssaModelApply, + Delete: func(ctx context.Context, cl client.WithWatch, obj client.Object, opts ...client.DeleteOption) error { + if _, ok := obj.(*corev1.Secret); ok { + return errors.New("simulated secret delete failure") + } + return cl.Delete(ctx, obj, opts...) + }, + }).Build() + r := newPlunger(c) + + reconcile(t, r) + + got := getHR(t, c) + if got.Spec.Suspend { + t.Fatalf("a failed recovery step must clear the suspension flux-plunger owns, got suspend=true") + } +} + +// When a recovery step fails and the deferred unsuspend fails as well, flux-plunger +// is left holding a suspension it cannot clear: the state in which a delete orphans +// the release. That must surface as a Warning, not only a log line. +func TestReconcile_DeferredUnsuspendFailureEmitsWarning(t *testing.T) { + hr := noDeployedReleasesHR() + secret := helmReleaseSecret("v1") + + c := fake.NewClientBuilder().WithScheme(testScheme(t)). + WithObjects(hr, secret). + WithInterceptorFuncs(interceptor.Funcs{ + Patch: func(ctx context.Context, cl client.WithWatch, obj client.Object, patch client.Patch, opts ...client.PatchOption) error { + if isPlungerApply(obj, patch, opts, false) { + return errors.New("simulated unsuspend apply failure") + } + return ssaModelApply(ctx, cl, obj, patch, opts...) + }, + Delete: func(ctx context.Context, cl client.WithWatch, obj client.Object, opts ...client.DeleteOption) error { + if _, ok := obj.(*corev1.Secret); ok { + return errors.New("simulated secret delete failure") + } + return cl.Delete(ctx, obj, opts...) + }, + }).Build() + rec := record.NewFakeRecorder(8) + r := newPlunger(c) + r.Recorder = rec + + reconcile(t, r) + + expectWarning(t, rec, "UnsuspendFailed") +} + +// A suspension flux-plunger owns but never recorded progress for (recovery +// crashed right after suspending) must be released on a later reconcile. +func TestReconcile_ReleasesOwnedSuspensionWithoutProgress(t *testing.T) { + hr := noDeployedReleasesHR() + ownedFixture(hr) + + c := fake.NewClientBuilder().WithScheme(testScheme(t)).WithObjects(hr). + WithInterceptorFuncs(interceptor.Funcs{Patch: ssaModelApply}).Build() + r := newPlunger(c) + + reconcile(t, r) + + got := getHR(t, c) + if got.Spec.Suspend { + t.Fatalf("a suspension flux-plunger owns with no recorded progress must be released, got suspend=true") + } +} + +// A suspension flux-plunger does not own must be left untouched even when a stale +// processed-version annotation happens to match the latest revision: the +// annotation is never an ownership signal, only the managedFields owner is. +func TestReconcile_LeavesExternalSuspensionWithStaleProcessedVersion(t *testing.T) { + hr := noDeployedReleasesHR() + hr.Spec.Suspend = true // suspended by an operator: not flux-plunger-owned + hr.Annotations = map[string]string{annotationLastProcessedVersion: "5"} + secret := helmReleaseSecret("v4") + + c := fake.NewClientBuilder().WithScheme(testScheme(t)).WithObjects(hr, secret). + WithInterceptorFuncs(interceptor.Funcs{Patch: ssaModelApply}).Build() + r := newPlunger(c) + + reconcile(t, r) + + got := getHR(t, c) + if !got.Spec.Suspend { + t.Fatalf("a stale processed-version match must not be treated as ownership; operator suspension was cleared") + } +} + +// Recovery must delete the LATEST (highest-version) storage Secret and record its +// version, even when several historical revision Secrets are present. +func TestReconcile_DeletesLatestOfMultipleSecrets(t *testing.T) { + hr := noDeployedReleasesHR() + oldest := helmReleaseSecret("v1") + middle := helmReleaseSecret("v2") + latest := helmReleaseSecret("v5") + + c := fake.NewClientBuilder().WithScheme(testScheme(t)).WithObjects(hr, oldest, middle, latest). + WithInterceptorFuncs(interceptor.Funcs{Patch: ssaModelApply}).Build() + r := newPlunger(c) + + reconcile(t, r) + + if err := c.Get(context.Background(), types.NamespacedName{Namespace: testNS, Name: latest.Name}, &corev1.Secret{}); !apierrors.IsNotFound(err) { + t.Fatalf("recovery must delete the latest storage Secret (v5), err=%v", err) + } + for _, s := range []*corev1.Secret{oldest, middle} { + if err := c.Get(context.Background(), types.NamespacedName{Namespace: testNS, Name: s.Name}, &corev1.Secret{}); err != nil { + t.Fatalf("recovery must not delete a non-latest Secret (%s): %v", s.Name, err) + } + } + got := getHR(t, c) + if got.Annotations[annotationLastProcessedVersion] != "5" { + t.Fatalf("recovery must record the latest processed version 5, got %q", got.Annotations[annotationLastProcessedVersion]) + } +} + +// A HelmRelease that does not carry the "has no deployed releases" error must be +// left entirely alone. +func TestReconcile_SkipsReleaseWithoutTargetError(t *testing.T) { + hr := noDeployedReleasesHR() + hr.Status.Conditions[0].Message = "Helm upgrade failed: some unrelated error" + secret := helmReleaseSecret("v1") + + c := fake.NewClientBuilder().WithScheme(testScheme(t)).WithObjects(hr, secret). + WithInterceptorFuncs(interceptor.Funcs{Patch: ssaModelApply}).Build() + r := newPlunger(c) + + reconcile(t, r) + + got := getHR(t, c) + if got.Spec.Suspend { + t.Fatalf("a release without the target error must not be suspended") + } + if err := c.Get(context.Background(), types.NamespacedName{Namespace: testNS, Name: secret.Name}, &corev1.Secret{}); apierrors.IsNotFound(err) { + t.Fatalf("a release without the target error must not have its storage Secret deleted") + } +} + +// A HelmRelease with the target error but no Helm storage Secrets must be skipped +// cleanly (pins the empty-list guard, without which getLatestSecret would panic). +func TestReconcile_SkipsWhenNoStorageSecrets(t *testing.T) { + hr := noDeployedReleasesHR() + + c := fake.NewClientBuilder().WithScheme(testScheme(t)).WithObjects(hr). + WithInterceptorFuncs(interceptor.Funcs{Patch: ssaModelApply}).Build() + r := newPlunger(c) + + reconcile(t, r) // must not panic + + got := getHR(t, c) + if got.Spec.Suspend { + t.Fatalf("a release with no storage Secrets must not be suspended") + } +} + +// The "already processed" skip-guard: once a pass reclaimed a revision and +// recorded the processed version, the next reconcile (latestVersion+1 == +// processedVersion) must NOT suspend or delete another Secret. +func TestReconcile_SkipsWhenAlreadyProcessed(t *testing.T) { + hr := noDeployedReleasesHR() + hr.Annotations = map[string]string{annotationLastProcessedVersion: "5"} + secret := helmReleaseSecret("v4") // 4+1 == 5 (already processed) + + c := fake.NewClientBuilder().WithScheme(testScheme(t)).WithObjects(hr, secret). + WithInterceptorFuncs(interceptor.Funcs{Patch: ssaModelApply}).Build() + r := newPlunger(c) + + reconcile(t, r) + + got := getHR(t, c) + if got.Spec.Suspend { + t.Fatalf("an already-processed release must not be suspended again, got suspend=true") + } + if err := c.Get(context.Background(), types.NamespacedName{Namespace: testNS, Name: secret.Name}, &corev1.Secret{}); apierrors.IsNotFound(err) { + t.Fatalf("an already-processed release must not have another storage Secret deleted") + } +} + +// The converse of the skip-guard: a recorded version NOT exactly one above the +// latest surviving revision means recovery must proceed (pins the off-by-one). +func TestReconcile_ProcessesWhenProcessedVersionDoesNotMatch(t *testing.T) { + hr := noDeployedReleasesHR() + hr.Annotations = map[string]string{annotationLastProcessedVersion: "5"} + secret := helmReleaseSecret("v5") // 5+1 == 6 != 5, so NOT already processed + + c := fake.NewClientBuilder().WithScheme(testScheme(t)).WithObjects(hr, secret). + WithInterceptorFuncs(interceptor.Funcs{Patch: ssaModelApply}).Build() + r := newPlunger(c) + + reconcile(t, r) + + if err := c.Get(context.Background(), types.NamespacedName{Namespace: testNS, Name: secret.Name}, &corev1.Secret{}); !apierrors.IsNotFound(err) { + t.Fatalf("a non-matching processed version must not skip recovery; the latest Secret should have been deleted, err=%v", err) + } + got := getHR(t, c) + if got.Annotations[annotationLastProcessedVersion] != "5" { + t.Fatalf("recovery must record the processed version 5, got %q", got.Annotations[annotationLastProcessedVersion]) + } +} + +// Deleting a release an operator suspended (flux-plunger does not own it) must +// leave the suspension in place: the single most safety-relevant boundary, +// enforced by the caller gate and the ownership check inside unsuspendHelmRelease. +func TestReconcile_LeavesExternalSuspensionOnDeletion(t *testing.T) { + hr := noDeployedReleasesHR() + hr.Spec.Suspend = true // operator-owned: not flux-plunger + now := metav1.Now() + hr.DeletionTimestamp = &now + + c := fake.NewClientBuilder().WithScheme(testScheme(t)).WithObjects(hr). + WithInterceptorFuncs(interceptor.Funcs{Patch: ssaModelApply}).Build() + r := newPlunger(c) + + reconcile(t, r) + + got := getHR(t, c) + if !got.Spec.Suspend { + t.Fatalf("flux-plunger must not clear an operator's suspension on deletion, got suspend=false") + } +} + +// Releasing a stuck owned suspension (crash-recovery branch) must requeue on +// failure, uniform with the other unsuspend call sites. +func TestReconcile_SuspendedBranchRequeuesOnUnsuspendFailure(t *testing.T) { + hr := noDeployedReleasesHR() + ownedFixture(hr) + + c := fake.NewClientBuilder().WithScheme(testScheme(t)). + WithObjects(hr). + WithInterceptorFuncs(interceptor.Funcs{ + Patch: func(ctx context.Context, cl client.WithWatch, obj client.Object, patch client.Patch, opts ...client.PatchOption) error { + if isPlungerApply(obj, patch, opts, false) { + return errors.New("simulated unsuspend apply failure") + } + return ssaModelApply(ctx, cl, obj, patch, opts...) + }, + }).Build() + rec := record.NewFakeRecorder(8) + r := newPlunger(c) + r.Recorder = rec + + _, err := r.Reconcile(context.Background(), ctrl.Request{NamespacedName: types.NamespacedName{Namespace: testNS, Name: testName}}) + if err == nil { + t.Fatalf("a failed unsuspend in the crash-recovery branch must requeue with an error, got nil") + } + expectWarning(t, rec, "UnsuspendFailed") +} + +// A failing processed-version annotation write must requeue with an error. +func TestReconcile_RecoveryRequeuesOnAnnotationFailure(t *testing.T) { + hr := noDeployedReleasesHR() + secret := helmReleaseSecret("v1") + + c := fake.NewClientBuilder().WithScheme(testScheme(t)). + WithObjects(hr, secret). + WithInterceptorFuncs(interceptor.Funcs{ + Patch: func(ctx context.Context, cl client.WithWatch, obj client.Object, patch client.Patch, opts ...client.PatchOption) error { + // Fail only the annotation patch (a merge patch carrying the + // processed-version annotation), not the suspend/unsuspend applies. + if h, ok := obj.(*helmv2.HelmRelease); ok && patch.Type() != types.ApplyPatchType && h.Annotations[annotationLastProcessedVersion] != "" { + return errors.New("simulated annotation patch failure") + } + return ssaModelApply(ctx, cl, obj, patch, opts...) + }, + }).Build() + r := newPlunger(c) + + _, err := r.Reconcile(context.Background(), ctrl.Request{NamespacedName: types.NamespacedName{Namespace: testNS, Name: testName}}) + if err == nil { + t.Fatalf("a failed processed-version annotation write must requeue with an error, got nil") + } +} + +// A failing final unsuspend on the recovery path must requeue with an error. +func TestReconcile_RecoveryRequeuesOnUnsuspendFailure(t *testing.T) { + hr := noDeployedReleasesHR() + secret := helmReleaseSecret("v1") + + c := fake.NewClientBuilder().WithScheme(testScheme(t)). + WithObjects(hr, secret). + WithInterceptorFuncs(interceptor.Funcs{ + Patch: func(ctx context.Context, cl client.WithWatch, obj client.Object, patch client.Patch, opts ...client.PatchOption) error { + if isPlungerApply(obj, patch, opts, false) { + return errors.New("simulated unsuspend apply failure") + } + return ssaModelApply(ctx, cl, obj, patch, opts...) + }, + }).Build() + rec := record.NewFakeRecorder(8) + r := newPlunger(c) + r.Recorder = rec + + _, err := r.Reconcile(context.Background(), ctrl.Request{NamespacedName: types.NamespacedName{Namespace: testNS, Name: testName}}) + if err == nil { + t.Fatalf("a failed final unsuspend on the recovery path must requeue with an error, got nil") + } + expectWarning(t, rec, "UnsuspendFailed") +} + +// On a terminating release owned by flux-plunger, a failed unsuspend must requeue. +func TestReconcile_DeletionRequeuesOnUnsuspendFailure(t *testing.T) { + hr := noDeployedReleasesHR() + ownedFixture(hr) + now := metav1.Now() + hr.DeletionTimestamp = &now + + c := fake.NewClientBuilder().WithScheme(testScheme(t)). + WithObjects(hr). + WithInterceptorFuncs(interceptor.Funcs{ + Patch: func(ctx context.Context, cl client.WithWatch, obj client.Object, patch client.Patch, opts ...client.PatchOption) error { + if isPlungerApply(obj, patch, opts, false) { + return errors.New("simulated unsuspend apply failure") + } + return ssaModelApply(ctx, cl, obj, patch, opts...) + }, + }).Build() + rec := record.NewFakeRecorder(8) + r := newPlunger(c) + r.Recorder = rec + + _, err := r.Reconcile(context.Background(), ctrl.Request{NamespacedName: types.NamespacedName{Namespace: testNS, Name: testName}}) + if err == nil { + t.Fatalf("a failed unsuspend on a terminating release must requeue with an error, got nil") + } + expectWarning(t, rec, "UnsuspendFailed") +} + +// A suspension flux-plunger does not own must be left untouched — including one an +// operator owns via a client-side Update of spec.suspend (managedFields shows the +// operator, not flux-plunger). This is the misattribution boundary, closed by the +// apiserver transferring the field away from flux-plunger (proven end to end in +// the envtest suite, V2/V3). +func TestReconcile_LeavesExternalSuspensionUntouched(t *testing.T) { + hr := noDeployedReleasesHR() + hr.Spec.Suspend = true // operator-owned: no test ownership marker + + c := fake.NewClientBuilder().WithScheme(testScheme(t)).WithObjects(hr). + WithInterceptorFuncs(interceptor.Funcs{Patch: ssaModelApply}).Build() + r := newPlunger(c) + + reconcile(t, r) + + got := getHR(t, c) + if !got.Spec.Suspend { + t.Fatalf("flux-plunger must not clear a suspension it does not own, got suspend=false") + } +} + +// A delete that lands after flux-plunger acquires the suspension but before it +// deletes the storage Secret must abort the delete and clear the suspension. +func TestReconcile_AbortsWhenDeletedBeforeSecretDelete(t *testing.T) { + hr := noDeployedReleasesHR() + secret := helmReleaseSecret("v1") + + c := fake.NewClientBuilder().WithScheme(testScheme(t)). + WithObjects(hr, secret). + WithInterceptorFuncs(interceptor.Funcs{ + Get: func(ctx context.Context, cl client.WithWatch, key client.ObjectKey, obj client.Object, opts ...client.GetOption) error { + if err := cl.Get(ctx, key, obj, opts...); err != nil { + return err + } + // Inject a delete once the processed-version annotation this recovery + // just wrote is visible: that is the releaseIsTerminating re-fetch, right + // before the storage Secret delete. + if h, ok := obj.(*helmv2.HelmRelease); ok && + h.Annotations[annotationLastProcessedVersion] != "" && h.DeletionTimestamp == nil { + now := metav1.Now() + h.DeletionTimestamp = &now + h.Finalizers = []string{helmFinalizer} + } + return nil + }, + Patch: ssaModelApply, + }).Build() + r := newPlunger(c) + + reconcile(t, r) + + if err := c.Get(context.Background(), types.NamespacedName{Namespace: testNS, Name: secret.Name}, &corev1.Secret{}); apierrors.IsNotFound(err) { + t.Fatalf("recovery must not delete the storage Secret of a release that started terminating before the delete") + } + got := getHR(t, c) + if got.Spec.Suspend { + t.Fatalf("the suspension flux-plunger acquired must be cleared once the release starts terminating, got suspend=true") + } +} + +// The processed-version annotation is recorded BEFORE the storage Secret is +// deleted, so a failed annotation write must leave the Secret intact. +func TestReconcile_AnnotationFailureLeavesSecretIntact(t *testing.T) { + hr := noDeployedReleasesHR() + secret := helmReleaseSecret("v1") + + c := fake.NewClientBuilder().WithScheme(testScheme(t)). + WithObjects(hr, secret). + WithInterceptorFuncs(interceptor.Funcs{ + Patch: func(ctx context.Context, cl client.WithWatch, obj client.Object, patch client.Patch, opts ...client.PatchOption) error { + if h, ok := obj.(*helmv2.HelmRelease); ok && patch.Type() != types.ApplyPatchType && h.Annotations[annotationLastProcessedVersion] != "" { + return errors.New("simulated annotation patch failure") + } + return ssaModelApply(ctx, cl, obj, patch, opts...) + }, + }).Build() + r := newPlunger(c) + + _, err := r.Reconcile(context.Background(), ctrl.Request{NamespacedName: types.NamespacedName{Namespace: testNS, Name: testName}}) + if err == nil { + t.Fatalf("a failed processed-version write must requeue with an error, got nil") + } + if getErr := c.Get(context.Background(), types.NamespacedName{Namespace: testNS, Name: secret.Name}, &corev1.Secret{}); apierrors.IsNotFound(getErr) { + t.Fatalf("a failed annotation write must not delete the storage Secret (annotation is recorded before the delete)") + } +} + +// unsuspendHelmRelease's own ownership re-check (defense-in-depth for a future +// caller that forgets the caller-side gate): with suspend=true and no flux-plunger +// ownership, a direct call sends no apply at all and leaves the suspension. The +// apply count is what pins the guard; a relinquish could not clear another +// manager's value anyway, so the resulting object alone would not. +func TestUnsuspendHelmRelease_LeavesUnownedSuspension(t *testing.T) { + hr := noDeployedReleasesHR() + hr.Spec.Suspend = true // operator-owned: no flux-plunger managedFields + + applies := 0 + c := fake.NewClientBuilder().WithScheme(testScheme(t)).WithObjects(hr). + WithInterceptorFuncs(interceptor.Funcs{ + Patch: func(ctx context.Context, cl client.WithWatch, obj client.Object, patch client.Patch, opts ...client.PatchOption) error { + if _, _, _, ok := plungerApplyDetail(obj, patch, opts); ok { + applies++ + } + return ssaModelApply(ctx, cl, obj, patch, opts...) + }, + }).Build() + r := newPlunger(c) + + if err := r.unsuspendHelmRelease(context.Background(), hr); err != nil { + t.Fatalf("unsuspendHelmRelease must not error on an unowned suspension: %v", err) + } + + if applies != 0 { + t.Fatalf("unsuspendHelmRelease must not apply on a suspension flux-plunger does not own, sent %d", applies) + } + if got := getHR(t, c); !got.Spec.Suspend { + t.Fatalf("unsuspendHelmRelease must not clear a suspension flux-plunger does not own (callee-side guard)") + } +} + +// The watch predicate must wake a reconcile for the error state and for a +// flux-plunger-owned suspension, and must NOT wake for an operator-owned +// suspension or an unrelated release. This pins both terms of the predicate, +// which nothing exercised before (SetupWithManager was never called in a test). +func TestWatchPredicate(t *testing.T) { + r := &FluxPlunger{owns: testOwns} + withError := noDeployedReleasesHR() + ownedSuspended := ownedFixture(noDeployedReleasesHR()) + ownedSuspended.Status.Conditions = nil // no error, only an owned suspension + externalSuspended := noDeployedReleasesHR() + externalSuspended.Status.Conditions = nil + externalSuspended.Spec.Suspend = true // suspended, not owned + quiet := noDeployedReleasesHR() + quiet.Status.Conditions = nil // no error, not suspended + // Owned marker but NOT suspended and no error: isolates the hr.Spec.Suspend + // conjunct. Dropping it from the predicate would wake on ownsSuspension alone and + // this case would (wrongly) match; with it, a release that is not suspended never + // matches on the suspension arm. + ownedNotSuspended := noDeployedReleasesHR() + ownedNotSuspended.Status.Conditions = nil + ownedNotSuspended.Annotations = map[string]string{testOwnedKey: "true"} + // A healthy release an operator or a migration suspended, now being deleted: + // neither the error arm nor the owned arm matches, yet this is the orphan state the + // TerminatingWhileSuspended Warning exists for, so it must wake a reconcile. + now := metav1.Now() + terminatingExternal := noDeployedReleasesHR() + terminatingExternal.Status.Conditions = nil + terminatingExternal.Spec.Suspend = true + terminatingExternal.DeletionTimestamp = &now + terminatingUnsuspended := noDeployedReleasesHR() + terminatingUnsuspended.Status.Conditions = nil + terminatingUnsuspended.DeletionTimestamp = &now + // Only the fence: the status write helm-controller makes after the uninstall + // carries no other signal, and it is what lets flux-plunger lift the fence. + fencedOnly := fencedFixture(noDeployedReleasesHR()) + fencedOnly.Status.Conditions = nil + + cases := []struct { + name string + obj client.Object + want bool + }{ + {"has target error", withError, true}, + {"owned suspension, no error", ownedSuspended, true}, + {"external suspension is ignored", externalSuspended, false}, + {"no error and not suspended", quiet, false}, + {"owned marker but not suspended", ownedNotSuspended, false}, + {"terminating under an external suspension", terminatingExternal, true}, + {"terminating and not suspended", terminatingUnsuspended, false}, + {"fenced by flux-plunger", fencedOnly, true}, + {"non-HelmRelease object", &corev1.Secret{}, false}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + if got := r.watchPredicate(tc.obj); got != tc.want { + t.Fatalf("watchPredicate=%v want %v", got, tc.want) + } + }) + } +} + +// On the final-unsuspend-failure path recovery sets completed=true before +// returning the error, so the deferred fallback does NOT run a second, redundant +// unsuspend (the requeue covers the retry). Pin that: exactly one unsuspend apply +// is attempted. Removing the completed=true makes the deferred fallback fire and +// this count become 2. +func TestReconcile_FinalUnsuspendFailureDoesNotRetryDeferred(t *testing.T) { + hr := noDeployedReleasesHR() + secret := helmReleaseSecret("v1") + + unsuspendApplies := 0 + c := fake.NewClientBuilder().WithScheme(testScheme(t)). + WithObjects(hr, secret). + WithInterceptorFuncs(interceptor.Funcs{ + Patch: func(ctx context.Context, cl client.WithWatch, obj client.Object, patch client.Patch, opts ...client.PatchOption) error { + if isPlungerApply(obj, patch, opts, false) { + unsuspendApplies++ + return errors.New("simulated unsuspend apply failure") + } + return ssaModelApply(ctx, cl, obj, patch, opts...) + }, + }).Build() + r := newPlunger(c) + + _, _ = r.Reconcile(context.Background(), ctrl.Request{NamespacedName: types.NamespacedName{Namespace: testNS, Name: testName}}) + if unsuspendApplies != 1 { + t.Fatalf("a failed final unsuspend must not trigger the deferred retry; want 1 unsuspend attempt, got %d", unsuspendApplies) + } +} + +// The pre-delete termination re-check must read the uncached APIReader, not the +// informer cache: the cache can lag a delete the apiserver already accepted, and a +// termination check that misses that delete would delete the storage Secret of a +// terminating release and orphan it. Here the cached client sees a live release +// while the APIReader sees the delete; releaseIsTerminating must report terminating. +func TestReleaseIsTerminating_ReadsAPIReaderNotCache(t *testing.T) { + cached := noDeployedReleasesHR() // cache: not terminating + fresh := noDeployedReleasesHR() + now := metav1.Now() + fresh.DeletionTimestamp = &now // apiserver: delete already accepted + fresh.Finalizers = []string{helmFinalizer} + + cachedClient := fake.NewClientBuilder().WithScheme(testScheme(t)).WithObjects(cached).Build() + apiReader := fake.NewClientBuilder().WithScheme(testScheme(t)).WithObjects(fresh).Build() + r := &FluxPlunger{Client: cachedClient, APIReader: apiReader, owns: testOwns} + + terminating, err := r.releaseIsTerminating(context.Background(), cached) + if err != nil { + t.Fatalf("releaseIsTerminating: %v", err) + } + if !terminating { + t.Fatalf("releaseIsTerminating must read the uncached APIReader (delete already accepted), not the stale cache") + } +} + +// The already-processed guard compares the processed-version annotation against the +// latest storage Secret, and the Secret list is read from the apiserver. If the +// annotation came from a lagging cache instead, a reconcile right after a finished +// recovery would see the fresh "latest" (the revision below the one just deleted) +// but the old annotation, fail the guard, and delete that revision too — walking the +// release history down one Secret per reconcile. Here the cache has no annotation +// while the apiserver records processed=5 over the surviving v4: recovery must not +// start, so no suspend apply may be sent. +func TestReconcile_ProcessedGuardReadsAPIReaderNotCache(t *testing.T) { + cached := noDeployedReleasesHR() // cache: annotation write not yet observed + fresh := noDeployedReleasesHR() + fresh.Annotations = map[string]string{annotationLastProcessedVersion: "5"} + secret := helmReleaseSecret("v4") + + applies := 0 + cachedClient := fake.NewClientBuilder().WithScheme(testScheme(t)).WithObjects(cached, secret). + WithInterceptorFuncs(interceptor.Funcs{ + Patch: func(ctx context.Context, cl client.WithWatch, obj client.Object, patch client.Patch, opts ...client.PatchOption) error { + if isPlungerApply(obj, patch, opts, true) { + applies++ + } + return ssaModelApply(ctx, cl, obj, patch, opts...) + }, + }).Build() + apiReader := fake.NewClientBuilder().WithScheme(testScheme(t)).WithObjects(fresh, secret).Build() + r := &FluxPlunger{Client: cachedClient, APIReader: apiReader, owns: testOwns} + + reconcile(t, r) + + if applies != 0 { + t.Fatalf("the processed guard must read the apiserver: v4 is already processed (annotation 5), yet %d suspend apply was sent", applies) + } +} + +// The storage-Secret List chooses which revision is deleted and which version the +// processed annotation records, so it must read the uncached APIReader like every +// other race-sensitive read: a cache lagging a just-created revision Secret would +// pick a stale "latest" and delete the wrong revision. Here the cache is empty while +// the APIReader sees the Secret; listHelmReleaseSecrets must return it. +func TestListHelmReleaseSecrets_ReadsAPIReaderNotCache(t *testing.T) { + secret := helmReleaseSecret("v1") + cachedClient := fake.NewClientBuilder().WithScheme(testScheme(t)).Build() // cache: no secret + apiReader := fake.NewClientBuilder().WithScheme(testScheme(t)).WithObjects(secret).Build() + r := &FluxPlunger{Client: cachedClient, APIReader: apiReader, owns: testOwns} + + got, err := r.listHelmReleaseSecrets(context.Background(), testNS, testName) + if err != nil { + t.Fatalf("listHelmReleaseSecrets: %v", err) + } + if len(got) != 1 { + t.Fatalf("listHelmReleaseSecrets must read the uncached APIReader (cache is empty); got %d secrets want 1", len(got)) + } +} + +// When flux-plunger declines to touch an externally-owned suspension it must emit +// an Event, so an operator can see and alert on it instead of grepping logs. +func TestReconcile_EmitsEventOnExternalSuspension(t *testing.T) { + hr := noDeployedReleasesHR() + hr.Spec.Suspend = true // suspended by an operator: not flux-plunger-owned + + c := fake.NewClientBuilder().WithScheme(testScheme(t)).WithObjects(hr). + WithInterceptorFuncs(interceptor.Funcs{Patch: ssaModelApply}).Build() + rec := record.NewFakeRecorder(8) + r := &FluxPlunger{Client: c, owns: testOwns, Recorder: rec} + + reconcile(t, r) + + select { + case e := <-rec.Events: + if !strings.Contains(e, "SuspensionNotOwned") { + t.Fatalf("expected a SuspensionNotOwned event, got %q", e) + } + default: + t.Fatalf("declining an externally-owned suspension must emit an Event, got none") + } +} + +// A suspension flux-plunger does not own on a release flux-plunger has recovered +// before is most likely one an earlier flux-plunger left mid-recovery under the +// shared field manager: it stays suspended for good unless someone acts, so it +// is a Warning, while one on a release flux-plunger never touched stays Normal. +func TestReconcile_ExternalSuspensionOnARecoveredReleaseWarns(t *testing.T) { + for _, tc := range []struct { + name string + recovered bool + want string + }{ + {"recovered before", true, corev1.EventTypeWarning}, + {"never recovered", false, corev1.EventTypeNormal}, + } { + t.Run(tc.name, func(t *testing.T) { + hr := noDeployedReleasesHR() + hr.Spec.Suspend = true + if tc.recovered { + hr.Annotations = map[string]string{annotationLastProcessedVersion: "3"} + } + c := fake.NewClientBuilder().WithScheme(testScheme(t)).WithObjects(hr). + WithInterceptorFuncs(interceptor.Funcs{Patch: ssaModelApply}).Build() + rec := record.NewFakeRecorder(8) + r := &FluxPlunger{Client: c, owns: testOwns, Recorder: rec} + + reconcile(t, r) + + select { + case e := <-rec.Events: + if !strings.HasPrefix(e, tc.want+" SuspensionNotOwned") { + t.Fatalf("want a %s SuspensionNotOwned event, got %q", tc.want, e) + } + default: + t.Fatal("no event") + } + }) + } +} + +// A non-conflict error while acquiring the suspension must requeue with an error. +func TestReconcile_SuspendFailureRequeuesOnNonConflictError(t *testing.T) { + hr := noDeployedReleasesHR() + secret := helmReleaseSecret("v1") + + c := fake.NewClientBuilder().WithScheme(testScheme(t)). + WithObjects(hr, secret). + WithInterceptorFuncs(interceptor.Funcs{ + Patch: func(ctx context.Context, cl client.WithWatch, obj client.Object, patch client.Patch, opts ...client.PatchOption) error { + if isPlungerApply(obj, patch, opts, true) { + return errors.New("simulated transient suspend failure") + } + return ssaModelApply(ctx, cl, obj, patch, opts...) + }, + }).Build() + r := newPlunger(c) + + _, err := r.Reconcile(context.Background(), ctrl.Request{NamespacedName: types.NamespacedName{Namespace: testNS, Name: testName}}) + if err == nil { + t.Fatalf("a non-conflict suspend failure must requeue with an error, got nil") + } +} + +// A conflict on the forced retry as well means another manager wrote the release +// again after the re-read: the same race as a foreign suspension caught on the +// unforced attempt, so it gets the same treatment: recovery is deferred with a +// RecoveryDeferred Event and no error, instead of a rate-limited backoff whose +// choice depends only on which of the two applies the write collided with. That +// write is itself an update event, so the next reconcile follows. Nothing is +// acquired, so the storage Secret stays intact. +func TestReconcile_ForcedAcquireConflictDefers(t *testing.T) { + hr := noDeployedReleasesHR() + secret := helmReleaseSecret("v1") + + c := fake.NewClientBuilder().WithScheme(testScheme(t)). + WithObjects(hr, secret). + WithInterceptorFuncs(interceptor.Funcs{ + Patch: func(ctx context.Context, cl client.WithWatch, obj client.Object, patch client.Patch, opts ...client.PatchOption) error { + // Conflict on every acquire apply, forced included: a foreign write lands + // before each attempt. + if isPlungerApply(obj, patch, opts, true) { + return apierrors.NewConflict( + schema.GroupResource{Group: "helm.toolkit.fluxcd.io", Resource: "helmreleases"}, + testName, errors.New("the object has been modified")) + } + return ssaModelApply(ctx, cl, obj, patch, opts...) + }, + }).Build() + rec := record.NewFakeRecorder(8) + r := &FluxPlunger{Client: c, owns: testOwns, Recorder: rec} + + _, err := r.Reconcile(context.Background(), ctrl.Request{NamespacedName: types.NamespacedName{Namespace: testNS, Name: testName}}) + if err != nil { + t.Fatalf("a conflict on the forced acquire must defer recovery, not requeue with an error: %v", err) + } + select { + case e := <-rec.Events: + if !strings.Contains(e, "RecoveryDeferred") { + t.Fatalf("expected a RecoveryDeferred event, got %q", e) + } + default: + t.Fatalf("a conflict on the forced acquire must emit RecoveryDeferred, got no event") + } + if getErr := c.Get(context.Background(), types.NamespacedName{Namespace: testNS, Name: secret.Name}, &corev1.Secret{}); apierrors.IsNotFound(getErr) { + t.Fatalf("a conflicted suspend acquires nothing, so it must not delete the storage Secret") + } +} + +// A non-conflict failure of the forced acquire (an admission webhook rejecting it, +// or an API error) produces no follow-up event, so it must requeue with an error +// rather than be treated as a deferral. +func TestReconcile_ForcedAcquireNonConflictErrorRequeues(t *testing.T) { + hr := noDeployedReleasesHR() + secret := helmReleaseSecret("v1") + + conflicted := false + c := fake.NewClientBuilder().WithScheme(testScheme(t)).WithObjects(hr, secret). + WithInterceptorFuncs(interceptor.Funcs{ + Patch: func(ctx context.Context, cl client.WithWatch, obj client.Object, patch client.Patch, opts ...client.PatchOption) error { + present, value, force, ok := plungerApplyDetail(obj, patch, opts) + if ok && present && value && !force && !conflicted { + conflicted = true + return apierrors.NewConflict( + schema.GroupResource{Group: "helm.toolkit.fluxcd.io", Resource: "helmreleases"}, + testName, errors.New("stale ownership at false")) + } + if ok && present && value && force { + return apierrors.NewForbidden( + schema.GroupResource{Group: "helm.toolkit.fluxcd.io", Resource: "helmreleases"}, + testName, errors.New("admission webhook denied the request")) + } + return ssaModelApply(ctx, cl, obj, patch, opts...) + }, + }).Build() + r := newPlunger(c) + + _, err := r.Reconcile(context.Background(), ctrl.Request{NamespacedName: types.NamespacedName{Namespace: testNS, Name: testName}}) + if err == nil { + t.Fatalf("a non-conflict failure of the forced acquire must requeue with an error, got nil") + } +} + +// Acquire re-fetches on conflict and forces ONLY over a field still read as false. +// Here the conflicting write suspended the release (an operator, or a backup +// mid-restore): the re-fetch sees suspend=true, so acquire must abort WITHOUT a +// forced apply and must not delete the storage Secret. +func TestReconcile_AcquireDoesNotForceActiveForeignSuspension(t *testing.T) { + hr := noDeployedReleasesHR() + secret := helmReleaseSecret("v1") + + var sawForce bool + c := fake.NewClientBuilder().WithScheme(testScheme(t)).WithObjects(hr, secret). + WithInterceptorFuncs(interceptor.Funcs{ + Patch: func(ctx context.Context, cl client.WithWatch, obj client.Object, patch client.Patch, opts ...client.PatchOption) error { + present, value, force, ok := plungerApplyDetail(obj, patch, opts) + if ok && present && value && force { + sawForce = true + } + // The unforced acquire loses the race: a foreign manager suspends the + // release, then our apply conflicts. Model both: write suspend=true to the + // store so the post-conflict re-fetch sees it, then return the conflict. + if ok && present && value && !force { + cur := &helmv2.HelmRelease{} + if err := cl.Get(ctx, client.ObjectKeyFromObject(obj), cur); err != nil { + return err + } + cur.Spec.Suspend = true + if err := cl.Update(ctx, cur); err != nil { + return err + } + return apierrors.NewConflict( + schema.GroupResource{Group: "helm.toolkit.fluxcd.io", Resource: "helmreleases"}, + testName, errors.New("foreign suspend won the race")) + } + return ssaModelApply(ctx, cl, obj, patch, opts...) + }, + }).Build() + r := newPlunger(c) + + reconcile(t, r) + + if sawForce { + t.Fatalf("acquire must not force over a suspension it re-read as active (true)") + } + if getErr := c.Get(context.Background(), types.NamespacedName{Namespace: testNS, Name: secret.Name}, &corev1.Secret{}); apierrors.IsNotFound(getErr) { + t.Fatalf("an aborted acquire must not delete the storage Secret") + } +} + +// The complementary case: the conflict came from a manager owning spec.suspend at +// FALSE (a backup controller that resumed, or an earlier flux-plunger release). The re-fetch +// sees suspend=false, so acquire forces over the stale ownership and recovery +// proceeds — the storage Secret is deleted. +func TestReconcile_AcquireForcesStaleForeignSuspension(t *testing.T) { + hr := noDeployedReleasesHR() + secret := helmReleaseSecret("v1") + + var sawForce bool + conflicted := false + c := fake.NewClientBuilder().WithScheme(testScheme(t)).WithObjects(hr, secret). + WithInterceptorFuncs(interceptor.Funcs{ + Patch: func(ctx context.Context, cl client.WithWatch, obj client.Object, patch client.Patch, opts ...client.PatchOption) error { + present, value, force, ok := plungerApplyDetail(obj, patch, opts) + // The unforced acquire conflicts once (foreign manager owns the field at + // false); the value is left false, so the re-fetch reads false. + if ok && present && value && !force && !conflicted { + conflicted = true + return apierrors.NewConflict( + schema.GroupResource{Group: "helm.toolkit.fluxcd.io", Resource: "helmreleases"}, + testName, errors.New("stale ownership at false")) + } + if ok && present && value && force { + sawForce = true + } + return ssaModelApply(ctx, cl, obj, patch, opts...) + }, + }).Build() + r := newPlunger(c) + + reconcile(t, r) + + if !sawForce { + t.Fatalf("acquire must force over stale ownership re-read as false; no forced apply seen") + } + if getErr := c.Get(context.Background(), types.NamespacedName{Namespace: testNS, Name: secret.Name}, &corev1.Secret{}); !apierrors.IsNotFound(getErr) { + t.Fatalf("after forcing acquisition recovery must delete the storage Secret") + } +} + +// Both acquire applies, the unforced first attempt and the forced retry, must carry +// the resourceVersion of the read that decided spec.suspend was false, so the +// apiserver rejects either with a conflict if another manager wrote the release in +// between. Without it the unforced apply of true over a foreign true is accepted as +// shared ownership and flux-plunger proceeds as if it had acquired a suspension a +// restore is holding. Pin that each is preconditioned on the stored resourceVersion. +func TestReconcile_AcquireAppliesCarryResourceVersion(t *testing.T) { + hr := noDeployedReleasesHR() + secret := helmReleaseSecret("v1") + + conflicted := false + var sawUnforced, sawForce bool + c := fake.NewClientBuilder().WithScheme(testScheme(t)).WithObjects(hr, secret). + WithInterceptorFuncs(interceptor.Funcs{ + Patch: func(ctx context.Context, cl client.WithWatch, obj client.Object, patch client.Patch, opts ...client.PatchOption) error { + present, value, force, ok := plungerApplyDetail(obj, patch, opts) + if ok && present && value { + cur := &helmv2.HelmRelease{} + if err := cl.Get(ctx, client.ObjectKeyFromObject(obj), cur); err != nil { + return err + } + if got := obj.GetResourceVersion(); got == "" || got != cur.ResourceVersion { + t.Fatalf("acquire apply (force=%v) must be preconditioned on the read resourceVersion %q, got %q", force, cur.ResourceVersion, got) + } + if !controllerutil.ContainsFinalizer(obj, fenceFinalizer) { + t.Fatalf("acquire apply (force=%v) must carry the fence finalizer, got %v", force, obj.GetFinalizers()) + } + } + if ok && present && value && !force && !conflicted { + sawUnforced = true + conflicted = true + return apierrors.NewConflict( + schema.GroupResource{Group: "helm.toolkit.fluxcd.io", Resource: "helmreleases"}, + testName, errors.New("stale ownership at false")) + } + if ok && present && value && force { + sawForce = true + } + return ssaModelApply(ctx, cl, obj, patch, opts...) + }, + }).Build() + r := newPlunger(c) + + reconcile(t, r) + + if !sawUnforced || !sawForce { + t.Fatalf("expected an unforced then a forced acquire; unforced=%v forced=%v", sawUnforced, sawForce) + } +} + +// A delete that lands while the unforced acquire is conflicting must stop the +// forced retry: suspending a terminating release is what makes helm-controller skip +// the uninstall. The re-read after the conflict sees the deletionTimestamp, so no +// forced apply may be sent and the storage Secret stays intact. +func TestReconcile_AcquireAbortsWhenTerminatingAfterConflict(t *testing.T) { + hr := noDeployedReleasesHR() + secret := helmReleaseSecret("v1") + + var sawForce bool + c := fake.NewClientBuilder().WithScheme(testScheme(t)).WithObjects(hr, secret). + WithInterceptorFuncs(interceptor.Funcs{ + Patch: func(ctx context.Context, cl client.WithWatch, obj client.Object, patch client.Patch, opts ...client.PatchOption) error { + present, value, force, ok := plungerApplyDetail(obj, patch, opts) + if ok && present && value && force { + sawForce = true + } + if ok && present && value && !force { + // The release is deleted (it keeps helm-controller's finalizer, so it + // becomes terminating) and the unforced acquire conflicts. + cur := &helmv2.HelmRelease{} + if err := cl.Get(ctx, client.ObjectKeyFromObject(obj), cur); err != nil { + return err + } + if err := cl.Delete(ctx, cur); err != nil { + return err + } + return apierrors.NewConflict( + schema.GroupResource{Group: "helm.toolkit.fluxcd.io", Resource: "helmreleases"}, + testName, errors.New("stale ownership at false")) + } + return ssaModelApply(ctx, cl, obj, patch, opts...) + }, + }).Build() + r := newPlunger(c) + + reconcile(t, r) + + if sawForce { + t.Fatalf("acquire must not force a suspension onto a release that began terminating during the conflict") + } + if getErr := c.Get(context.Background(), types.NamespacedName{Namespace: testNS, Name: secret.Name}, &corev1.Secret{}); apierrors.IsNotFound(getErr) { + t.Fatalf("an aborted acquire must not delete the storage Secret") + } +} + +// A release terminating while suspended by a manager flux-plunger does NOT own is +// the orphan state itself; flux-plunger cannot clear it but must surface it with a +// Warning Event, not only a log line, so an operator can intervene. +func TestReconcile_EmitsEventOnTerminatingExternalSuspension(t *testing.T) { + hr := noDeployedReleasesHR() + hr.Spec.Suspend = true // suspended by an external manager: not flux-plunger-owned + now := metav1.Now() + hr.DeletionTimestamp = &now + + c := fake.NewClientBuilder().WithScheme(testScheme(t)).WithObjects(hr). + WithInterceptorFuncs(interceptor.Funcs{Patch: ssaModelApply}).Build() + rec := record.NewFakeRecorder(8) + r := &FluxPlunger{Client: c, owns: testOwns, Recorder: rec} + + reconcile(t, r) + + select { + case e := <-rec.Events: + if !strings.Contains(e, "TerminatingWhileSuspended") { + t.Fatalf("expected a TerminatingWhileSuspended event, got %q", e) + } + default: + t.Fatalf("a terminating release under an external suspension must emit an Event, got none") + } +} + +// When recovery is deferred because the suspension was taken by another manager +// between read and write, flux-plunger must emit an Event, symmetric with the +// externally-owned-suspension branch, not only log. +func TestReconcile_EmitsEventOnDeferredRecovery(t *testing.T) { + hr := noDeployedReleasesHR() + secret := helmReleaseSecret("v1") + + c := fake.NewClientBuilder().WithScheme(testScheme(t)).WithObjects(hr, secret). + WithInterceptorFuncs(interceptor.Funcs{ + Patch: func(ctx context.Context, cl client.WithWatch, obj client.Object, patch client.Patch, opts ...client.PatchOption) error { + // The unforced acquire loses the race to a foreign suspension. + if present, value, force, ok := plungerApplyDetail(obj, patch, opts); ok && present && value && !force { + cur := &helmv2.HelmRelease{} + if err := cl.Get(ctx, client.ObjectKeyFromObject(obj), cur); err != nil { + return err + } + cur.Spec.Suspend = true + if err := cl.Update(ctx, cur); err != nil { + return err + } + return apierrors.NewConflict( + schema.GroupResource{Group: "helm.toolkit.fluxcd.io", Resource: "helmreleases"}, + testName, errors.New("foreign suspend won the race")) + } + return ssaModelApply(ctx, cl, obj, patch, opts...) + }, + }).Build() + rec := record.NewFakeRecorder(8) + r := &FluxPlunger{Client: c, owns: testOwns, Recorder: rec} + + reconcile(t, r) + + select { + case e := <-rec.Events: + if !strings.Contains(e, "RecoveryDeferred") { + t.Fatalf("expected a RecoveryDeferred event, got %q", e) + } + default: + t.Fatalf("a deferred recovery must emit an Event, got none") + } +} + +// fencedFixture marks a HelmRelease as held by flux-plunger's fence finalizer. +func fencedFixture(hr *helmv2.HelmRelease) *helmv2.HelmRelease { + controllerutil.AddFinalizer(hr, fenceFinalizer) + return hr +} + +// terminatingFixture marks a HelmRelease as deleted; the fake client keeps it only +// while a finalizer remains. +func terminatingFixture(hr *helmv2.HelmRelease) *helmv2.HelmRelease { + now := metav1.Now() + hr.DeletionTimestamp = &now + return hr +} + +// hrExists reports whether the test HelmRelease is still stored. +func hrExists(t *testing.T, c client.Client) (*helmv2.HelmRelease, bool) { + t.Helper() + hr := &helmv2.HelmRelease{} + err := c.Get(context.Background(), types.NamespacedName{Namespace: testNS, Name: testName}, hr) + if apierrors.IsNotFound(err) { + return nil, false + } + if err != nil { + t.Fatalf("get HelmRelease: %v", err) + } + return hr, true +} + +// The acquire must set the fence in the same apply as the suspension, on both +// attempts, so there is no moment at which flux-plunger holds a suspension a delete +// could slip past. A completed recovery lifts both together. +func TestReconcile_AcquireSetsFenceWithSuspension(t *testing.T) { + hr := noDeployedReleasesHR() + secret := helmReleaseSecret("v1") + + acquires := 0 + c := fake.NewClientBuilder().WithScheme(testScheme(t)).WithObjects(hr, secret). + WithInterceptorFuncs(interceptor.Funcs{ + Patch: func(ctx context.Context, cl client.WithWatch, obj client.Object, patch client.Patch, opts ...client.PatchOption) error { + if present, value, _, ok := plungerApplyDetail(obj, patch, opts); ok && present && value { + acquires++ + if !controllerutil.ContainsFinalizer(obj, fenceFinalizer) { + t.Fatalf("the acquire apply must carry the fence finalizer, got finalizers %v", obj.GetFinalizers()) + } + } + return ssaModelApply(ctx, cl, obj, patch, opts...) + }, + }).Build() + r := newPlunger(c) + + reconcile(t, r) + + if acquires == 0 { + t.Fatalf("expected an acquire apply") + } + got, ok := hrExists(t, c) + if !ok { + t.Fatalf("a completed recovery must leave the release in place") + } + if got.Spec.Suspend || controllerutil.ContainsFinalizer(got, fenceFinalizer) { + t.Fatalf("a completed recovery must lift both the suspension and the fence; suspend=%v finalizers=%v", got.Spec.Suspend, got.Finalizers) + } +} + +// A delete on a release flux-plunger holds suspended must lift the suspension but +// keep the fence: helm-controller may already have dropped its own finalizer +// without an uninstall, and the fence is what keeps the object until it reconciles +// the unsuspended release. +func TestReconcile_TerminatingOwnedSuspensionKeepsFence(t *testing.T) { + hr := terminatingFixture(fencedFixture(ownedFixture(noDeployedReleasesHR()))) + // The state observed on a live helm-controller v1.5.0 right after it handled the + // delete of the suspended release: its finalizer is gone and it has observed the + // current generation, yet nothing was uninstalled. The fence must not be lifted + // on that; only the suspension is. + hr.Finalizers = []string{fenceFinalizer} + hr.Generation = 3 + hr.Status.ObservedGeneration = 3 + + c := fake.NewClientBuilder().WithScheme(testScheme(t)).WithObjects(hr). + WithInterceptorFuncs(interceptor.Funcs{Patch: ssaModelApply}).Build() + r := newPlunger(c) + + reconcile(t, r) + + got, ok := hrExists(t, c) + if !ok { + t.Fatalf("the fence must keep a terminating release until the uninstall runs") + } + if got.Spec.Suspend { + t.Fatalf("the suspension must be lifted so helm-controller uninstalls") + } + if !controllerutil.ContainsFinalizer(got, fenceFinalizer) { + t.Fatalf("the fence must stay until helm-controller has handled the unsuspended release") + } +} + +// uninstallReached is the condition for lifting the fence: helm-controller's +// finalizer gone AND the latest generation observed. Each conjunct on its own is +// not enough: the finalizer is also dropped, without an uninstall, while the +// release is suspended. +func TestUninstallReached(t *testing.T) { + mk := func(helmFinalizer bool, gen, observed int64) *helmv2.HelmRelease { + hr := noDeployedReleasesHR() + hr.Finalizers = nil + if helmFinalizer { + hr.Finalizers = []string{helmv2.HelmReleaseFinalizer} + } + hr.Generation = gen + hr.Status.ObservedGeneration = observed + return hr + } + cases := []struct { + name string + hr *helmv2.HelmRelease + want bool + }{ + {"finalizer gone and generation observed", mk(false, 4, 4), true}, + {"finalizer gone, unsuspended generation not yet observed", mk(false, 4, 3), false}, + {"generation observed, finalizer still held", mk(true, 4, 4), false}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + if got := uninstallReached(tc.hr); got != tc.want { + t.Fatalf("uninstallReached=%v want %v", got, tc.want) + } + }) + } +} + +// Once helm-controller has handled the unsuspended release the fence is lifted and +// the release goes; until then it stays. +func TestReconcile_LiftsFenceOnlyOnceUninstallReached(t *testing.T) { + cases := []struct { + name string + observed int64 + wantGone bool + }{ + {"uninstall reached", 4, true}, + {"unsuspended generation not yet observed", 3, false}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + hr := terminatingFixture(noDeployedReleasesHR()) + hr.Finalizers = []string{fenceFinalizer} + hr.Generation = 4 + hr.Status.ObservedGeneration = tc.observed + + c := fake.NewClientBuilder().WithScheme(testScheme(t)).WithObjects(hr). + WithInterceptorFuncs(interceptor.Funcs{Patch: ssaModelApply}).Build() + r := newPlunger(c) + + reconcile(t, r) + + if _, exists := hrExists(t, c); exists == tc.wantGone { + t.Fatalf("release exists=%v, want gone=%v", exists, tc.wantGone) + } + }) + } +} + +// A release being deleted under another manager's suspension is that manager's +// decision (a migration suspends then deletes to leave the resources in place): +// flux-plunger must not keep the object with its fence, must leave the suspension +// alone, and records it. +func TestReconcile_TerminatingForeignSuspensionReleasesFence(t *testing.T) { + hr := terminatingFixture(fencedFixture(noDeployedReleasesHR())) + hr.Spec.Suspend = true // not flux-plunger's + + c := fake.NewClientBuilder().WithScheme(testScheme(t)).WithObjects(hr). + WithInterceptorFuncs(interceptor.Funcs{Patch: ssaModelApply}).Build() + rec := record.NewFakeRecorder(8) + r := &FluxPlunger{Client: c, owns: testOwns, Recorder: rec} + + reconcile(t, r) + + got, ok := hrExists(t, c) + if !ok { + t.Fatalf("helm-controller's finalizer still holds the release in this fixture") + } + if controllerutil.ContainsFinalizer(got, fenceFinalizer) { + t.Fatalf("the fence must not hold a release under another manager's suspension") + } + if !got.Spec.Suspend { + t.Fatalf("another manager's suspension must be left alone") + } + select { + case e := <-rec.Events: + if !strings.HasPrefix(e, corev1.EventTypeNormal+" TerminatingWhileSuspended ") { + t.Fatalf("expected a Normal TerminatingWhileSuspended event, got %q", e) + } + default: + t.Fatalf("expected a TerminatingWhileSuspended event, got none") + } +} + +// A fenced, terminating, unsuspended release that helm-controller has not handled +// yet is held by flux-plunger's fence. That hold must not be silent: the reconcile +// requeues itself so it is re-checked without waiting for an event, and once the +// delete has been held past the deadline it raises a Warning an operator can find +// before a `kubectl delete` that never returns. +func TestReconcile_HeldFenceRequeuesAndWarnsPastTheDeadline(t *testing.T) { + deletedAt := time.Date(2026, 9, 25, 10, 0, 0, 0, time.UTC) + cases := []struct { + name string + since time.Duration + wantWarn bool + }{ + {"within the deadline", time.Minute, false}, + {"past the deadline", fenceHeldWarnAfter + time.Minute, true}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + hr := noDeployedReleasesHR() + hr.Finalizers = []string{fenceFinalizer} + hr.DeletionTimestamp = &metav1.Time{Time: deletedAt} + hr.Generation = 4 + hr.Status.ObservedGeneration = 3 // the unsuspended generation not yet handled + + c := fake.NewClientBuilder().WithScheme(testScheme(t)).WithObjects(hr). + WithInterceptorFuncs(interceptor.Funcs{Patch: ssaModelApply}).Build() + rec := record.NewFakeRecorder(8) + r := &FluxPlunger{Client: c, owns: testOwns, Recorder: rec, + now: func() time.Time { return deletedAt.Add(tc.since) }} + + res, err := r.Reconcile(context.Background(), ctrl.Request{NamespacedName: types.NamespacedName{Namespace: testNS, Name: testName}}) + if err != nil { + t.Fatalf("reconcile: %v", err) + } + if res.RequeueAfter <= 0 { + t.Fatalf("a held fence must requeue itself, got %+v", res) + } + warned := false + for drained := false; !drained; { + select { + case e := <-rec.Events: + if strings.HasPrefix(e, corev1.EventTypeWarning+" UninstallFenceHeld ") { + warned = true + } + default: + drained = true + } + } + if warned != tc.wantWarn { + t.Fatalf("UninstallFenceHeld Warning=%v, want %v", warned, tc.wantWarn) + } + if _, ok := hrExists(t, c); !ok { + t.Fatalf("the fence must keep holding the release; warning is not lifting it") + } + }) + } +} + +// The same terminating-under-a-foreign-suspension state is two different things. +// A migration that suspends then deletes chose to keep the resources, so it is +// Normal. A release flux-plunger has recovered before (it carries the +// processed-version annotation: an operator suspended it by hand and deleted it, +// or an earlier flux-plunger release left it suspended) is losing its uninstall by +// accident, the failure this controller exists to prevent, so it is a Warning. +func TestReconcile_TerminatingForeignSuspensionWarnsOnlyForAPreviouslyRecoveredRelease(t *testing.T) { + cases := []struct { + name string + annotated bool + wantType string + }{ + {"never recovered by flux-plunger (migration)", false, corev1.EventTypeNormal}, + {"recovered by flux-plunger before", true, corev1.EventTypeWarning}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + hr := terminatingFixture(noDeployedReleasesHR()) + hr.Spec.Suspend = true // not flux-plunger's + if tc.annotated { + hr.Annotations = map[string]string{annotationLastProcessedVersion: "3"} + } + + c := fake.NewClientBuilder().WithScheme(testScheme(t)).WithObjects(hr). + WithInterceptorFuncs(interceptor.Funcs{Patch: ssaModelApply}).Build() + rec := record.NewFakeRecorder(8) + r := &FluxPlunger{Client: c, owns: testOwns, Recorder: rec} + + reconcile(t, r) + + select { + case e := <-rec.Events: + if !strings.HasPrefix(e, tc.wantType+" TerminatingWhileSuspended ") { + t.Fatalf("expected a %s TerminatingWhileSuspended event, got %q", tc.wantType, e) + } + default: + t.Fatalf("expected a TerminatingWhileSuspended event, got none") + } + }) + } +} + +// A fence left without a suspension on a live release (another writer set +// spec.suspend=false and took the field), or a fence whose suspension another +// manager took over, guards nothing and must be lifted, without starting a recovery. +func TestReconcile_ReleasesUnguardingFence(t *testing.T) { + cases := []struct { + name string + suspend bool + }{ + {"fence without a suspension", false}, + {"fence under another manager's suspension", true}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + hr := fencedFixture(noDeployedReleasesHR()) + hr.Spec.Suspend = tc.suspend + secret := helmReleaseSecret("v1") + + c := fake.NewClientBuilder().WithScheme(testScheme(t)).WithObjects(hr, secret). + WithInterceptorFuncs(interceptor.Funcs{Patch: ssaModelApply}).Build() + r := newPlunger(c) + + reconcile(t, r) + + got, _ := hrExists(t, c) + if controllerutil.ContainsFinalizer(got, fenceFinalizer) { + t.Fatalf("a fence that guards nothing must be lifted") + } + if got.Spec.Suspend != tc.suspend { + t.Fatalf("lifting the fence must not change spec.suspend; got %v want %v", got.Spec.Suspend, tc.suspend) + } + if getErr := c.Get(context.Background(), types.NamespacedName{Namespace: testNS, Name: secret.Name}, &corev1.Secret{}); apierrors.IsNotFound(getErr) { + t.Fatalf("lifting a stale fence must not also run a recovery") + } + }) + } +} + +// Every apply flux-plunger sends, the relinquish included, must carry the uid and +// resourceVersion of the object it was decided on: the resourceVersion so a write in +// between is rejected rather than absorbed, the uid so an apply to a release that +// has gone cannot create an empty one. +func TestReconcile_EveryApplyCarriesPreconditions(t *testing.T) { + hr := noDeployedReleasesHR() + hr.UID = "release-uid" + secret := helmReleaseSecret("v1") + + applies := 0 + c := fake.NewClientBuilder().WithScheme(testScheme(t)).WithObjects(hr, secret). + WithInterceptorFuncs(interceptor.Funcs{ + Patch: func(ctx context.Context, cl client.WithWatch, obj client.Object, patch client.Patch, opts ...client.PatchOption) error { + if _, _, _, ok := plungerApplyDetail(obj, patch, opts); ok { + applies++ + cur := &helmv2.HelmRelease{} + if err := cl.Get(ctx, client.ObjectKeyFromObject(obj), cur); err != nil { + return err + } + if obj.GetUID() != "release-uid" { + t.Fatalf("apply must carry the release uid, got %q", obj.GetUID()) + } + if obj.GetResourceVersion() == "" || obj.GetResourceVersion() != cur.ResourceVersion { + t.Fatalf("apply must carry the read resourceVersion %q, got %q", cur.ResourceVersion, obj.GetResourceVersion()) + } + } + return ssaModelApply(ctx, cl, obj, patch, opts...) + }, + }).Build() + r := newPlunger(c) + + reconcile(t, r) + + if applies < 2 { + t.Fatalf("expected the acquire and the relinquish applies, got %d", applies) + } +} + +// Every flux-plunger apply is preconditioned on the object it was decided on, so a +// routine write in between (helm-controller updating the status) makes the final +// unsuspend conflict. That is retried through the requeue, not a failure to clear +// the suspension: it must requeue, but must not raise the UnsuspendFailed Warning. +func TestReconcile_UnsuspendConflictRequeuesWithoutWarning(t *testing.T) { + hr := noDeployedReleasesHR() + secret := helmReleaseSecret("v1") + + c := fake.NewClientBuilder().WithScheme(testScheme(t)).WithObjects(hr, secret). + WithInterceptorFuncs(interceptor.Funcs{ + Patch: func(ctx context.Context, cl client.WithWatch, obj client.Object, patch client.Patch, opts ...client.PatchOption) error { + if isPlungerApply(obj, patch, opts, false) { + return apierrors.NewConflict( + schema.GroupResource{Group: "helm.toolkit.fluxcd.io", Resource: "helmreleases"}, + testName, errors.New("the object has been modified")) + } + return ssaModelApply(ctx, cl, obj, patch, opts...) + }, + }).Build() + rec := record.NewFakeRecorder(8) + r := newPlunger(c) + r.Recorder = rec + + _, err := r.Reconcile(context.Background(), ctrl.Request{NamespacedName: types.NamespacedName{Namespace: testNS, Name: testName}}) + if err == nil { + t.Fatalf("a conflicted unsuspend must requeue with an error") + } + for drained := false; !drained; { + select { + case e := <-rec.Events: + if strings.Contains(e, "UnsuspendFailed") { + t.Fatalf("a conflicted unsuspend is retried, not a failure to clear; got %q", e) + } + default: + drained = true + } + } +} + +// A release that is gone by the pre-delete termination re-check counts as +// terminating: its storage Secret must be left alone and the reconcile must not +// requeue with an error for an object no reconcile will follow. +func TestReconcile_ReleaseGoneBeforeSecretDeleteKeepsSecret(t *testing.T) { + hr := noDeployedReleasesHR() + secret := helmReleaseSecret("v1") + + c := fake.NewClientBuilder().WithScheme(testScheme(t)).WithObjects(hr, secret). + WithInterceptorFuncs(interceptor.Funcs{ + Patch: func(ctx context.Context, cl client.WithWatch, obj client.Object, patch client.Patch, opts ...client.PatchOption) error { + if err := ssaModelApply(ctx, cl, obj, patch, opts...); err != nil { + return err + } + // Right after the processed-version annotation is written, the release + // is removed outright. + if h, ok := obj.(*helmv2.HelmRelease); ok && patch.Type() != types.ApplyPatchType && h.Annotations[annotationLastProcessedVersion] != "" { + gone := &helmv2.HelmRelease{} + if err := cl.Get(ctx, client.ObjectKeyFromObject(obj), gone); err != nil { + return err + } + gone.Finalizers = nil + if err := cl.Update(ctx, gone); err != nil { + return err + } + return client.IgnoreNotFound(cl.Delete(ctx, gone)) + } + return nil + }, + }).Build() + r := newPlunger(c) + + _, err := r.Reconcile(context.Background(), ctrl.Request{NamespacedName: types.NamespacedName{Namespace: testNS, Name: testName}}) + if err != nil { + t.Fatalf("a release gone before the Secret delete must not requeue with an error: %v", err) + } + if getErr := c.Get(context.Background(), types.NamespacedName{Namespace: testNS, Name: secret.Name}, &corev1.Secret{}); apierrors.IsNotFound(getErr) { + t.Fatalf("a release gone before the Secret delete must keep its storage Secret") + } +} + +// A release that disappears in the middle of a recovery has nothing left to clear: +// the unsuspend must not report a failure it will "retry", since no reconcile will +// follow for an object that is gone. +func TestReconcile_ReleaseGoneMidRecoveryIsNotAnUnsuspendFailure(t *testing.T) { + hr := noDeployedReleasesHR() + secret := helmReleaseSecret("v1") + + c := fake.NewClientBuilder().WithScheme(testScheme(t)).WithObjects(hr, secret). + WithInterceptorFuncs(interceptor.Funcs{ + Patch: ssaModelApply, + Delete: func(ctx context.Context, cl client.WithWatch, obj client.Object, opts ...client.DeleteOption) error { + if err := cl.Delete(ctx, obj, opts...); err != nil { + return err + } + if _, ok := obj.(*corev1.Secret); ok { + // The release is removed outright right after its storage Secret. + gone := &helmv2.HelmRelease{} + if err := cl.Get(ctx, types.NamespacedName{Namespace: testNS, Name: testName}, gone); err != nil { + return err + } + gone.Finalizers = nil + if err := cl.Update(ctx, gone); err != nil { + return err + } + return client.IgnoreNotFound(cl.Delete(ctx, gone)) + } + return nil + }, + }).Build() + rec := record.NewFakeRecorder(8) + r := newPlunger(c) + r.Recorder = rec + + _, err := r.Reconcile(context.Background(), ctrl.Request{NamespacedName: types.NamespacedName{Namespace: testNS, Name: testName}}) + if err != nil { + t.Fatalf("a release gone mid-recovery must not requeue with an error: %v", err) + } + for drained := false; !drained; { + select { + case e := <-rec.Events: + if strings.Contains(e, "UnsuspendFailed") { + t.Fatalf("a release gone mid-recovery is not an unsuspend failure, got %q", e) + } + default: + drained = true + } + } +} diff --git a/internal/controller/fluxplunger/hook_contract_test.go b/internal/controller/fluxplunger/hook_contract_test.go new file mode 100644 index 000000000..1c9b0559f --- /dev/null +++ b/internal/controller/fluxplunger/hook_contract_test.go @@ -0,0 +1,111 @@ +package fluxplunger + +import ( + "os" + "regexp" + "strconv" + "strings" + "testing" + "time" +) + +// The chart's pre-delete hook restates two of this package's names in shell and +// go-template, where nothing ties them to the Go constants: the field manager +// whose Apply entry owns a suspension, and the fence finalizer. A rename on +// either side alone would leave the hook removing fences while keeping +// suspensions, or looking for a fence nobody sets. These tests guard the +// spellings only; what the hook's predicates mean is held by +// hack/flux-plunger-fence-hook_test.bats. +const ( + hookTemplate = "../../../packages/system/flux-plunger/templates/uninstall-fence-cleanup.yaml" + deploymentTemplate = "../../../packages/system/flux-plunger/templates/deployment.yaml" +) + +// The binary must run the manager through RunManager, so the drain runs on stop, +// and size the Lease with ApplyShutdownTimings, so the next flux-plunger cannot +// lead during it; dropping either from main.go leaves every other test green. +func TestMain_RunsTheDrainUnderTheLease(t *testing.T) { + raw, err := os.ReadFile("../../../cmd/flux-plunger/main.go") + if err != nil { + t.Fatalf("read main.go: %v", err) + } + for _, want := range []string{"fluxplunger.RunManager(", "fluxplunger.ApplyShutdownTimings(", "mgr.GetAPIReader()"} { + if !strings.Contains(string(raw), want) { + t.Errorf("main.go does not call %q", want) + } + } + if strings.Contains(string(raw), "mgr.Start(") { + t.Error("main.go starts the manager directly, skipping the drain") + } +} + +// The chart must turn leader election on: without it nothing keeps the next +// flux-plunger from writing while the old one drains. +func TestDeploymentTemplate_EnablesLeaderElection(t *testing.T) { + raw, err := os.ReadFile(deploymentTemplate) + if err != nil { + t.Fatalf("read %s: %v", deploymentTemplate, err) + } + if !strings.Contains(string(raw), "- --leader-elect\n") && !strings.Contains(string(raw), "- --leader-elect=true") { + t.Error("deployment does not pass --leader-elect") + } +} + +// The chart sizes the drain as the grace period less what the manager's stop and +// the margin before SIGKILL take; both live here, so the subtraction must match. +func TestDeploymentTemplate_SubtractsTheStopAndTheMarginTheBinaryUses(t *testing.T) { + raw, err := os.ReadFile(deploymentTemplate) + if err != nil { + t.Fatalf("read %s: %v", deploymentTemplate, err) + } + m := regexp.MustCompile(`--` + ShutdownDrainTimeoutFlag + `=\{\{ sub \.Values\.shutdownGracePeriodSeconds (\d+) \}\}s`).FindStringSubmatch(string(raw)) + if m == nil { + t.Fatal("deployment does not derive the drain timeout from shutdownGracePeriodSeconds") + } + want := int((managerStopTimeout + killMargin) / time.Second) + if m[1] != strconv.Itoa(want) { + t.Fatalf("deployment subtracts %s, the binary needs %d (manager stop %v + margin %v)", m[1], want, managerStopTimeout, killMargin) + } +} + +// The chart passes the drain deadline as a flag; a name the binary does not +// define makes flux-plunger exit on start. +func TestDeploymentTemplate_PassesTheDrainFlagTheBinaryDefines(t *testing.T) { + raw, err := os.ReadFile(deploymentTemplate) + if err != nil { + t.Fatalf("read %s: %v", deploymentTemplate, err) + } + if want := "- --" + ShutdownDrainTimeoutFlag + "="; !strings.Contains(string(raw), want) { + t.Errorf("deployment does not pass %q", want) + } +} + +func TestHookTemplate_UsesTheControllersNames(t *testing.T) { + raw, err := os.ReadFile(hookTemplate) + if err != nil { + t.Fatalf("read %s: %v", hookTemplate, err) + } + hook := string(raw) + + for _, want := range []string{ + `(eq .manager "` + suspendFieldManager + `") (eq .operation "Apply")`, + `--field-manager ` + suspendFieldManager, + `fence=` + fenceFinalizer, + } { + if !strings.Contains(hook, want) { + t.Errorf("hook does not contain %q", want) + } + } + + // Every flux-plunger finalizer literal in the templates is the controller's + // fence, whole: matched by the domain, so a misspelt name is caught too. + literals := regexp.MustCompile(`"[^"\s]*cozystack\.io/[^"\s]*"`).FindAllString(hook, -1) + if len(literals) == 0 { + t.Fatal("hook names no fence finalizer in a template") + } + for _, l := range literals { + if l != `"`+fenceFinalizer+`"` { + t.Errorf("hook template names fence %s, controller sets %q", l, fenceFinalizer) + } + } +} diff --git a/internal/controller/fluxplunger/shutdown_test.go b/internal/controller/fluxplunger/shutdown_test.go new file mode 100644 index 000000000..9ed044892 --- /dev/null +++ b/internal/controller/fluxplunger/shutdown_test.go @@ -0,0 +1,265 @@ +// SPDX-License-Identifier: Apache-2.0 + +package fluxplunger + +import ( + "context" + "errors" + "fmt" + "testing" + "time" + + helmv2 "github.com/fluxcd/helm-controller/api/v2" + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/client-go/tools/record" + ctrl "sigs.k8s.io/controller-runtime" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/client/fake" + "sigs.k8s.io/controller-runtime/pkg/client/interceptor" + "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil" +) + +// countingReader counts List calls and fails the first failLists of them. +type countingReader struct { + client.Reader + lists, failLists int +} + +func (r *countingReader) List(ctx context.Context, list client.ObjectList, opts ...client.ListOption) error { + r.lists++ + if r.lists <= r.failLists { + return errors.New("etcdserver: leader changed") + } + return r.Reader.List(ctx, list, opts...) +} + +type stubManager struct { + client client.Client + reader client.Reader + elected chan struct{} +} + +func (m stubManager) Start(context.Context) error { return nil } +func (m stubManager) GetClient() client.Client { return m.client } +func (m stubManager) GetAPIReader() client.Reader { return m.reader } +func (m stubManager) Elected() <-chan struct{} { return m.elected } + +// electedChan is the Elected channel of a manager that became leader. +func electedChan() chan struct{} { + c := make(chan struct{}) + close(c) + return c +} + +// A flux-plunger that never became leader stops while the leader goes on; its +// drain would write next to the leader. +func TestRunManager_DoesNotDrainWithoutHavingLed(t *testing.T) { + c := fake.NewClientBuilder().WithScheme(testScheme(t)).WithObjects(fencedLiveRelease()). + WithInterceptorFuncs(interceptor.Funcs{Patch: ssaModelApply}).Build() + reader := &countingReader{Reader: c} + if err := RunManager(context.Background(), stubManager{client: c, reader: reader, elected: make(chan struct{})}, 10*time.Second); err != nil { + t.Fatalf("RunManager: %v", err) + } + if reader.lists != 0 { + t.Fatal("a flux-plunger that never led must not drain") + } + hr := &helmv2.HelmRelease{} + if err := c.Get(context.Background(), client.ObjectKeyFromObject(fencedLiveRelease()), hr); err != nil { + t.Fatalf("get: %v", err) + } + if !controllerutil.ContainsFinalizer(hr, fenceFinalizer) { + t.Fatal("the leader's fence must be left to the leader") + } +} + +func fencedLiveRelease() *helmv2.HelmRelease { + return &helmv2.HelmRelease{ObjectMeta: metav1.ObjectMeta{ + Namespace: testNS, Name: testName, Finalizers: []string{fenceFinalizer}, + }} +} + +// After the manager stops its informer cache is frozen, so the drain must read +// through the manager's API reader; a drain reading the cache would act on +// fences already gone. +func TestRunManager_DrainsThroughTheManagersAPIReader(t *testing.T) { + c := fake.NewClientBuilder().WithScheme(testScheme(t)).WithObjects(fencedLiveRelease()). + WithInterceptorFuncs(interceptor.Funcs{Patch: ssaModelApply}).Build() + reader := &countingReader{Reader: c} + if err := RunManager(context.Background(), stubManager{client: c, reader: reader, elected: electedChan()}, 10*time.Second); err != nil { + t.Fatalf("RunManager: %v", err) + } + if reader.lists == 0 { + t.Fatal("the drain did not read through the API reader") + } + hr := &helmv2.HelmRelease{} + if err := c.Get(context.Background(), client.ObjectKeyFromObject(fencedLiveRelease()), hr); err != nil { + t.Fatalf("get: %v", err) + } + if controllerutil.ContainsFinalizer(hr, fenceFinalizer) { + t.Fatalf("the drain must release the fence, finalizers %v", hr.Finalizers) + } +} + +func TestDrainFences_RetriesAFailedListing(t *testing.T) { + c := fake.NewClientBuilder().WithScheme(testScheme(t)).WithObjects(fencedLiveRelease()). + WithInterceptorFuncs(interceptor.Funcs{Patch: ssaModelApply}).Build() + reader := &countingReader{Reader: c, failLists: 2} + r := &FluxPlunger{Client: c, APIReader: reader} + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + left, err := r.DrainFences(ctx) + if err != nil || left != 0 { + t.Fatalf("a listing that fails and then succeeds must not end the drain: left=%d err=%v lists=%d", left, err, reader.lists) + } + if reader.lists < 3 { + t.Fatalf("want the listing retried, lists=%d", reader.lists) + } +} + +func TestRunThenDrain_DrainsAfterTheManagerStopsWithItsOwnDeadline(t *testing.T) { + stopped, drained := false, false + signal, cancel := context.WithCancel(context.Background()) + run := func(ctx context.Context) error { + cancel() // the stop signal + <-ctx.Done() + stopped = true + return nil + } + drain := func(ctx context.Context) (int, error) { + drained = true + if !stopped { + t.Error("drain ran before the manager stopped") + } + // The signal context is cancelled by now; the drain must get time of its own. + if err := ctx.Err(); err != nil { + t.Errorf("drain context was already done: %v", err) + } + dl, ok := ctx.Deadline() + if !ok || time.Until(dl) > time.Minute || time.Until(dl) < 50*time.Second { + t.Errorf("drain deadline %v, want about a minute from now", dl) + } + return 0, nil + } + + if err := RunThenDrain(signal, run, drain, time.Minute); err != nil { + t.Fatalf("RunThenDrain: %v", err) + } + if !drained { + t.Fatal("drain did not run") + } +} + +// The next flux-plunger may become leader only once the old one has stopped its +// manager and finished draining, counted from the old one's last Lease renewal. +func TestApplyShutdownTimings_TheLeaseOutlastsTheStopAndTheDrain(t *testing.T) { + for _, drain := range []time.Duration{2 * time.Second, 60 * time.Second, 110 * time.Second} { + opts := ctrl.Options{} + ApplyShutdownTimings(&opts, drain) + if opts.LeaderElectionReleaseOnCancel { + t.Fatalf("drain %v: a Lease released on stop lets the next flux-plunger lead during the drain", drain) + } + if opts.GracefulShutdownTimeout == nil || opts.LeaseDuration == nil || opts.RenewDeadline == nil || opts.RetryPeriod == nil { + t.Fatalf("drain %v: timings left unset: %+v", drain, opts) + } + stop, lease, renew, retry := *opts.GracefulShutdownTimeout, *opts.LeaseDuration, *opts.RenewDeadline, *opts.RetryPeriod + if stop <= 0 { + t.Fatalf("drain %v: the manager's stop must be bounded, got %v", drain, stop) + } + // A leader whose renewals fail keeps acting until RenewDeadline has + // passed since its last renewal, so that counts too. + if lease <= retry+renew+stop+drain { + t.Fatalf("drain %v: lease %v does not outlast a renewal %v ago, a renew deadline of %v, a stop of %v and the drain", drain, lease, retry, renew, stop) + } + if !(renew < lease && time.Duration(float64(retry)*1.2) < renew) { + t.Fatalf("drain %v: client-go needs lease > renew > 1.2 * retry, got %v %v %v", drain, lease, renew, retry) + } + } +} + +// controller-runtime reports a stop that overran GracefulShutdownTimeout as an +// error from Start. A reconcile slow to notice its cancelled context must not +// cost the drain the fence exists for; the exit stays non-zero. +func TestRunThenDrain_DrainsAfterAStopThatOverranItsGracePeriod(t *testing.T) { + stopErr := fmt.Errorf("failed waiting for all runnables to end within grace period of 10s: %w", context.DeadlineExceeded) + drained := false + err := RunThenDrain(context.Background(), + func(context.Context) error { return stopErr }, + func(context.Context) (int, error) { drained = true; return 0, nil }, + time.Minute) + if !drained { + t.Fatal("a stop that overran its grace period must still drain") + } + if !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("the overrun must still be reported, got %v", err) + } +} + +// The drain's Events cannot go through the manager's recorder, which is stopped +// before Start returns; they are written directly. +func TestRunManager_DrainEventsReachTheAPI(t *testing.T) { + now := metav1.Now() + hr := fencedLiveRelease() + hr.Spec.Suspend = true + hr.DeletionTimestamp = &now + hr.Finalizers = append(hr.Finalizers, "example.com/keep") + c := fake.NewClientBuilder().WithScheme(testScheme(t)).WithObjects(hr). + WithInterceptorFuncs(interceptor.Funcs{Patch: ssaModelApply}).Build() + if err := RunManager(context.Background(), stubManager{client: c, reader: c, elected: electedChan()}, 5*time.Second); err != nil { + t.Fatalf("RunManager: %v", err) + } + events := &corev1.EventList{} + if err := c.List(context.Background(), events); err != nil { + t.Fatalf("list events: %v", err) + } + for _, e := range events.Items { + if e.Reason == "TerminatingWhileSuspended" && e.InvolvedObject.Name == hr.Name && e.InvolvedObject.Namespace == hr.Namespace { + return + } + } + t.Fatalf("the drain's event did not reach the API: %+v", events.Items) +} + +func TestRunThenDrain_DoesNotDrainWhenTheManagerFails(t *testing.T) { + boom := errors.New("boom") + drained := false + err := RunThenDrain(context.Background(), + func(context.Context) error { return boom }, + func(context.Context) (int, error) { drained = true; return 0, nil }, + time.Minute) + if !errors.Is(err, boom) { + t.Fatalf("want the manager's error, got %v", err) + } + if drained { + t.Fatal("a manager that failed must not be followed by a drain") + } +} + +func TestRunThenDrain_AnIncompleteDrainIsNotAFailure(t *testing.T) { + err := RunThenDrain(context.Background(), + func(context.Context) error { return nil }, + func(context.Context) (int, error) { return 2, context.DeadlineExceeded }, + time.Minute) + if err != nil { + t.Fatalf("fences left for the next flux-plunger or the pre-delete hook are not an error: %v", err) + } +} + +// A stop cancels every reconcile, so an unsuspend cut short by it is not the +// failure the Warning reports: the drain lifts that suspension next. +func TestRecordUnsuspendFailed_IgnoresACancelledStop(t *testing.T) { + rec := record.NewFakeRecorder(4) + r := &FluxPlunger{Recorder: rec} + r.recordUnsuspendFailed(fencedLiveRelease(), fmt.Errorf("apply: %w", context.Canceled)) + select { + case e := <-rec.Events: + t.Fatalf("a cancelled stop must not raise %q", e) + default: + } + r.recordUnsuspendFailed(fencedLiveRelease(), errors.New("forbidden")) + select { + case <-rec.Events: + default: + t.Fatal("a real failure must still raise the Warning") + } +} diff --git a/internal/controller/fluxplunger/ssa_ownership_envtest_test.go b/internal/controller/fluxplunger/ssa_ownership_envtest_test.go new file mode 100644 index 000000000..0d39c5df9 --- /dev/null +++ b/internal/controller/fluxplunger/ssa_ownership_envtest_test.go @@ -0,0 +1,722 @@ +// SPDX-License-Identifier: Apache-2.0 +//go:build envtest + +// Source of truth for what the suspension fix relies on from a REAL apiserver +// (envtest), where the controller-runtime fake client cannot stand in: it does not +// track metadata.managedFields, and it does not enforce resourceVersion or uid +// preconditions on server-side apply. It drives the PRODUCTION code against a +// realistic release, one an operator owns with a non-zero spec.interval. +// +// Ownership: acquire without conflict and without touching spec.interval, the +// operator transfer (misattribution boundary), no self-disown, relinquish, never +// claiming a suspension set under the shared client-side field manager +// (migrations, delete hook), and never acquiring an actively foreign-owned +// suspension; ownsSuspensionManagedFields is asserted directly against +// apiserver-produced managedFields. +// +// Uninstall fence (issue #4060): a delete landing during recovery reaches the Helm +// uninstall whichever of helm-controller and flux-plunger handles it first, with +// helm-controller v1.5.0's delete handling reproduced step for step; a delete +// racing the unsuspend of a live release is survived; and no apply resurrects a +// release that has gone. +// +// Built only under the `envtest` tag; `make test-controllers-envtest` fetches the +// apiserver and runs it, and CI runs that target on every pull request. +package fluxplunger + +import ( + "context" + "os" + "testing" + "time" + + helmv2 "github.com/fluxcd/helm-controller/api/v2" + corev1 "k8s.io/api/core/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/apimachinery/pkg/runtime/schema" + "k8s.io/apimachinery/pkg/types" + "k8s.io/client-go/dynamic" + clientgoscheme "k8s.io/client-go/kubernetes/scheme" + ctrl "sigs.k8s.io/controller-runtime" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/envtest" +) + +const ( + fmHelm = "cozystack-operator" + fmOper = "kubectl-patch" +) + +// envtestStartTimeout replaces envtest's 20s default: CI runs these suites beside +// three other make goals on a four-CPU runner, where kube-apiserver can take +// longer than that to come up. +const envtestStartTimeout = 2 * time.Minute + +func newEnvtestEnvironment(crdDir string) *envtest.Environment { + return &envtest.Environment{ + CRDDirectoryPaths: []string{crdDir}, + ErrorIfCRDPathMissing: true, + ControlPlaneStartTimeout: envtestStartTimeout, + } +} + +func TestEnvtest_EnvironmentToleratesASlowControlPlaneStart(t *testing.T) { + if got := newEnvtestEnvironment("crds").ControlPlaneStartTimeout; got < time.Minute { + t.Fatalf("ControlPlaneStartTimeout = %v, want at least a minute", got) + } +} + +func TestEnvtest_SuspendOwnership(t *testing.T) { + crdDir := os.Getenv("HELMRELEASE_CRD_DIR") + if crdDir == "" { + t.Skip("set HELMRELEASE_CRD_DIR to the dir with the HelmRelease CRD") + } + env := newEnvtestEnvironment(crdDir) + cfg, err := env.Start() + if err != nil { + t.Fatalf("start envtest: %v", err) + } + defer func() { _ = env.Stop() }() + + if err := helmv2.AddToScheme(clientgoscheme.Scheme); err != nil { + t.Fatalf("add helm scheme: %v", err) + } + cl, err := client.New(cfg, client.Options{Scheme: clientgoscheme.Scheme}) + if err != nil { + t.Fatalf("client: %v", err) + } + ctx := context.Background() + r := &FluxPlunger{Client: cl} + key := types.NamespacedName{Namespace: testNS, Name: testName} + get := func() *helmv2.HelmRelease { + h := &helmv2.HelmRelease{} + if err := cl.Get(ctx, key, h); err != nil { + t.Fatalf("get: %v", err) + } + return h + } + + ns := &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: testNS}} + if err := cl.Create(ctx, ns); err != nil { + t.Fatalf("create ns: %v", err) + } + + // The operator establishes a realistic release via a full-object apply that owns + // a NON-ZERO spec.interval and does NOT set spec.suspend. This is the shape a + // typed-struct suspend apply conflicts with (it would emit spec.interval "0s"). + const operatorInterval = 5 * time.Minute + base := &helmv2.HelmRelease{ + TypeMeta: metav1.TypeMeta{APIVersion: helmv2.GroupVersion.String(), Kind: "HelmRelease"}, + ObjectMeta: metav1.ObjectMeta{Namespace: testNS, Name: testName}, + Spec: helmv2.HelmReleaseSpec{ + Interval: metav1.Duration{Duration: operatorInterval}, + Chart: &helmv2.HelmChartTemplate{Spec: helmv2.HelmChartTemplateSpec{Chart: "x", SourceRef: helmv2.CrossNamespaceObjectReference{Kind: "HelmRepository", Name: "r"}}}, + }, + } + if err := cl.Patch(ctx, base, client.Apply, client.FieldOwner(fmHelm)); err != nil { + t.Fatalf("operator base apply: %v", err) + } + + // Acquire: production suspendHelmRelease must acquire WITHOUT conflicting on + // spec.interval, and must leave the operator's interval untouched. + acquired, err := r.suspendHelmRelease(ctx, get()) + if err != nil { + t.Fatalf("acquire: suspendHelmRelease errored (interval conflict regression?): %v", err) + } + if !acquired { + t.Fatalf("acquire: suspendHelmRelease did not acquire the suspension") + } + h := get() + if !h.Spec.Suspend || !ownsSuspensionManagedFields(h) { + t.Fatalf("acquire: expected suspend=true owned by flux-plunger; suspend=%v owns=%v", h.Spec.Suspend, ownsSuspensionManagedFields(h)) + } + if h.Spec.Interval.Duration != operatorInterval { + t.Fatalf("acquire: suspend must not touch the operator's spec.interval; got %v want %v", h.Spec.Interval.Duration, operatorInterval) + } + t.Log("acquire: acquired suspend without conflict, operator interval preserved") + + // Unrelated re-apply: operator re-applies the whole object (unrelated fields), NOT touching + // suspend. flux-plunger must retain ownership (no self-disown). + base2 := &helmv2.HelmRelease{ + TypeMeta: metav1.TypeMeta{APIVersion: helmv2.GroupVersion.String(), Kind: "HelmRelease"}, + ObjectMeta: metav1.ObjectMeta{Namespace: testNS, Name: testName}, + Spec: helmv2.HelmReleaseSpec{ + Interval: metav1.Duration{Duration: operatorInterval}, + Chart: &helmv2.HelmChartTemplate{Spec: helmv2.HelmChartTemplateSpec{Chart: "x2", SourceRef: helmv2.CrossNamespaceObjectReference{Kind: "HelmRepository", Name: "r"}}}, + }, + } + if err := cl.Patch(ctx, base2, client.Apply, client.FieldOwner(fmHelm)); err != nil { + t.Fatalf("unrelated re-apply: operator re-apply: %v", err) + } + if h = get(); !h.Spec.Suspend || !ownsSuspensionManagedFields(h) { + t.Fatalf("unrelated re-apply (self-disown): after unrelated operator re-apply suspend=%v owns=%v", h.Spec.Suspend, ownsSuspensionManagedFields(h)) + } + t.Log("unrelated re-apply: unrelated operator re-apply did NOT disown flux-plunger's suspend") + + // Operator transfer: operator resumes then re-suspends via client-side patches. The field + // transfers to the operator, so flux-plunger no longer owns it. + for _, want := range []bool{false, true} { + cur := get() + patch := client.MergeFrom(cur.DeepCopy()) + cur.Spec.Suspend = want + if err := cl.Patch(ctx, cur, patch, client.FieldOwner(fmOper)); err != nil { + t.Fatalf("operator set suspend=%v: %v", want, err) + } + } + if h = get(); ownsSuspensionManagedFields(h) { + t.Fatalf("operator transfer (misattribution): flux-plunger still owns an operator-set suspension") + } + t.Log("operator transfer: after operator resume+resuspend, flux-plunger does NOT own the suspension") + + // unsuspendHelmRelease must now be a no-op (not owned): the operator's + // suspension must survive. + if err := r.unsuspendHelmRelease(ctx, get()); err != nil { + t.Fatalf("unsuspend on unowned suspension errored: %v", err) + } + if h = get(); !h.Spec.Suspend { + t.Fatalf("boundary FAIL: flux-plunger cleared an operator's suspension") + } + + // Relinquish: reset to a flux-plunger-owned suspension (operator resumes so the field is + // free), acquire, then unsuspendHelmRelease must relinquish → suspend=false, + // interval untouched, ownership dropped. + cur := get() + patch := client.MergeFrom(cur.DeepCopy()) + cur.Spec.Suspend = false + if err := cl.Patch(ctx, cur, patch, client.FieldOwner(fmOper)); err != nil { + t.Fatalf("relinquish: operator resume: %v", err) + } + if acquired, err := r.suspendHelmRelease(ctx, get()); err != nil || !acquired { + t.Fatalf("relinquish: re-acquire: acquired=%v err=%v", acquired, err) + } + if err := r.unsuspendHelmRelease(ctx, get()); err != nil { + t.Fatalf("relinquish: unsuspend: %v", err) + } + h = get() + if h.Spec.Suspend { + t.Fatalf("relinquish: unsuspend did not clear the suspension") + } + if ownsSuspensionManagedFields(h) { + t.Fatalf("relinquish: flux-plunger still owns suspend after unsuspend") + } + if h.Spec.Interval.Duration != operatorInterval { + t.Fatalf("relinquish: unsuspend must not touch the operator's spec.interval; got %v", h.Spec.Interval.Duration) + } + t.Log("relinquish: unsuspend relinquished ownership, reverted suspend to false, interval preserved") + + // Shared manager: a suspension set under the SHARED client-side field manager + // (flux-client-side-apply) must NOT be read as flux-plunger's, and + // unsuspendHelmRelease must leave it untouched. That manager is used by the + // platform migrations (cozy-proxy, cert-manager) and the tenant delete hook — and + // historically by earlier flux-plunger releases, which is exactly why the field + // manager cannot identify flux-plunger. Recognising it would let flux-plunger + // clear a migration's suspension (unsuspending cozy-proxy deletes + // cozystack-operator), so the boundary is pinned here on a real apiserver. + curShared := get() + sharedPatch := client.MergeFrom(curShared.DeepCopy()) + curShared.Spec.Suspend = true + if err := cl.Patch(ctx, curShared, sharedPatch, client.FieldOwner(fieldManager)); err != nil { + t.Fatalf("shared manager: shared-manager suspend: %v", err) + } + if h = get(); ownsSuspensionManagedFields(h) { + t.Fatalf("shared manager (misattribution risk): a suspension under the shared client-side manager must NOT be read as flux-plunger's") + } + if err := r.unsuspendHelmRelease(ctx, get()); err != nil { + t.Fatalf("shared manager: unsuspend: %v", err) + } + if h = get(); !h.Spec.Suspend { + t.Fatalf("shared manager (misattribution): flux-plunger cleared a suspension set under the shared client-side manager") + } + t.Log("shared manager: a shared-client-side-manager suspension is left untouched") + + // Active foreign suspension: an operator actively owns suspend=TRUE. suspendHelmRelease must NOT acquire + // or force it away — an active foreign suspension is never taken. The early + // already-suspended guard covers the common case; the re-fetch-after-conflict + // guard covers the race the fake-client tests pin. + curActive := get() + activePatch := client.MergeFrom(curActive.DeepCopy()) + curActive.Spec.Suspend = true + if err := cl.Patch(ctx, curActive, activePatch, client.FieldOwner(fmOper)); err != nil { + t.Fatalf("active foreign suspension: operator suspend: %v", err) + } + acquired, err = r.suspendHelmRelease(ctx, get()) + if err != nil { + t.Fatalf("active foreign suspension: suspend: %v", err) + } + if acquired { + t.Fatalf("active foreign suspension: acquired an actively foreign-suspended release") + } + if h = get(); !h.Spec.Suspend { + t.Fatalf("active foreign suspension: cleared an active foreign suspension") + } + if ownsSuspensionManagedFields(h) { + t.Fatalf("active foreign suspension: took ownership of an active foreign suspension") + } + t.Log("active foreign suspension: did not acquire or clear an actively foreign-owned suspension") +} + +// TestEnvtest_AcquiresOverBackupOwnedSuspend pins acquiring a +// suspension a backup controller left owned. A backup/restore controller in this repo sets +// spec.suspend via a dynamic-client Update, taking ownership of the field. A +// non-forced apply of spec.suspend then 409s forever; production suspendHelmRelease +// re-fetches after the conflict, sees the field still false, and forces on acquire, +// which must succeed without touching the operator's interval. Reverting the +// conditional force in suspendHelmRelease turns this RED with a .spec.suspend +// conflict. +func TestEnvtest_AcquiresOverBackupOwnedSuspend(t *testing.T) { + crdDir := os.Getenv("HELMRELEASE_CRD_DIR") + if crdDir == "" { + t.Skip("set HELMRELEASE_CRD_DIR to the dir with the HelmRelease CRD") + } + env := newEnvtestEnvironment(crdDir) + cfg, err := env.Start() + if err != nil { + t.Fatalf("start envtest: %v", err) + } + defer func() { _ = env.Stop() }() + + if err := helmv2.AddToScheme(clientgoscheme.Scheme); err != nil { + t.Fatalf("add helm scheme: %v", err) + } + cl, err := client.New(cfg, client.Options{Scheme: clientgoscheme.Scheme}) + if err != nil { + t.Fatalf("client: %v", err) + } + dyn, err := dynamic.NewForConfig(cfg) + if err != nil { + t.Fatalf("dynamic client: %v", err) + } + gvr := schema.GroupVersionResource{Group: "helm.toolkit.fluxcd.io", Version: "v2", Resource: "helmreleases"} + ctx := context.Background() + r := &FluxPlunger{Client: cl} + key := types.NamespacedName{Namespace: testNS, Name: testName} + if err := cl.Create(ctx, &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: testNS}}); err != nil { + t.Fatalf("create ns: %v", err) + } + + const operatorInterval = 5 * time.Minute + base := &helmv2.HelmRelease{ + TypeMeta: metav1.TypeMeta{APIVersion: helmv2.GroupVersion.String(), Kind: "HelmRelease"}, + ObjectMeta: metav1.ObjectMeta{Namespace: testNS, Name: testName}, + Spec: helmv2.HelmReleaseSpec{ + Interval: metav1.Duration{Duration: operatorInterval}, + Chart: &helmv2.HelmChartTemplate{Spec: helmv2.HelmChartTemplateSpec{Chart: "x", SourceRef: helmv2.CrossNamespaceObjectReference{Kind: "HelmRepository", Name: "r"}}}, + }, + } + if err := cl.Patch(ctx, base, client.Apply, client.FieldOwner("cozystack-operator")); err != nil { + t.Fatalf("operator base apply: %v", err) + } + + // A backup/restore controller suspends then resumes via a dynamic-client Update, + // leaving spec.suspend=false but OWNED by it (operation=Update). This is the + // state that 409s a non-forced apply. + for _, v := range []bool{true, false} { + u, err := dyn.Resource(gvr).Namespace(testNS).Get(ctx, testName, metav1.GetOptions{}) + if err != nil { + t.Fatalf("backup get: %v", err) + } + _ = unstructured.SetNestedField(u.Object, v, "spec", "suspend") + if _, err := dyn.Resource(gvr).Namespace(testNS).Update(ctx, u, metav1.UpdateOptions{}); err != nil { + t.Fatalf("backup Update suspend=%v: %v", v, err) + } + } + + cur := &helmv2.HelmRelease{} + if err := cl.Get(ctx, key, cur); err != nil { + t.Fatalf("get: %v", err) + } + acquired, err := r.suspendHelmRelease(ctx, cur) + if err != nil { + t.Fatalf("backup-owned acquire: suspendHelmRelease could not acquire a backup-controller-owned spec.suspend (force missing?): %v", err) + } + if !acquired { + t.Fatalf("backup-owned acquire: suspendHelmRelease did not acquire") + } + got := &helmv2.HelmRelease{} + _ = cl.Get(ctx, key, got) + if !got.Spec.Suspend || !ownsSuspensionManagedFields(got) { + t.Fatalf("backup-owned acquire: expected suspend=true owned by flux-plunger; suspend=%v owns=%v", got.Spec.Suspend, ownsSuspensionManagedFields(got)) + } + if got.Spec.Interval.Duration != operatorInterval { + t.Fatalf("backup-owned acquire: acquire must not touch the operator's interval; got %v", got.Spec.Interval.Duration) + } + t.Log("backup-owned acquire: force-on-acquire took spec.suspend from a dynamic-Update owner, interval preserved") + + // Concurrent write: the backup controller holds the field at false and then + // suspends the release for real in the gap after one of acquire's reads. Both + // applies are preconditioned on the resourceVersion of the read that decided on + // them, so neither the unforced first attempt (which would otherwise record + // flux-plunger as a co-owner of the backup's true) nor the forced retry may take + // the suspension: acquire reports not acquired, without an error, and the + // backup's suspension keeps its owner. + setBackupSuspend := func(v bool) { + u, err := dyn.Resource(gvr).Namespace(testNS).Get(ctx, testName, metav1.GetOptions{}) + if err != nil { + t.Fatalf("concurrent write: backup get: %v", err) + } + _ = unstructured.SetNestedField(u.Object, v, "spec", "suspend") + if _, err := dyn.Resource(gvr).Namespace(testNS).Update(ctx, u, metav1.UpdateOptions{}); err != nil { + t.Fatalf("concurrent write: backup Update suspend=%v: %v", v, err) + } + } + for _, tc := range []struct { + name string + after int // the backup writes right after this Get of acquire + }{ + {"before the unforced apply", 1}, + {"before the forced apply", 2}, + } { + setBackupSuspend(false) + racing := &FluxPlunger{Client: cl, APIReader: &writeAfterNthGet{Reader: cl, n: tc.after, write: func() { setBackupSuspend(true) }}} + start := &helmv2.HelmRelease{} + if err := cl.Get(ctx, key, start); err != nil { + t.Fatalf("concurrent write %s: get: %v", tc.name, err) + } + acquired, err := racing.suspendHelmRelease(ctx, start) + if err != nil || acquired { + t.Fatalf("concurrent write %s: acquire must report not acquired without an error; acquired=%v err=%v", tc.name, acquired, err) + } + after := &helmv2.HelmRelease{} + _ = cl.Get(ctx, key, after) + if !after.Spec.Suspend || ownsSuspensionManagedFields(after) { + t.Fatalf("concurrent write %s: the backup's suspension must survive unowned by flux-plunger; suspend=%v owns=%v", tc.name, after.Spec.Suspend, ownsSuspensionManagedFields(after)) + } + t.Logf("concurrent write %s: acquire declined, backup's suspension kept", tc.name) + } +} + +// writeAfterNthGet runs write right after its n-th Get returns, standing in for +// another controller writing the object in the gap between a read and the apply +// decided on it. +type writeAfterNthGet struct { + client.Reader + n, calls int + write func() +} + +func (w *writeAfterNthGet) Get(ctx context.Context, key client.ObjectKey, obj client.Object, opts ...client.GetOption) error { + err := w.Reader.Get(ctx, key, obj, opts...) + w.calls++ + if w.calls == w.n { + w.write() + } + return err +} + +// simulateHelmControllerDelete stands in for helm-controller v1.5.0's +// reconcileDelete (internal/controller/helmrelease_controller.go, the +// deletionTimestamp branch): on a terminating HelmRelease it runs the Helm +// uninstall only when spec.suspend is false, then removes its own finalizer either +// way and records the observed generation. It reports whether it uninstalled. It is +// the behaviour issue #4060 is about: a delete handled while the release is +// suspended drops the finalizer without an uninstall. +func simulateHelmControllerDelete(t *testing.T, ctx context.Context, cl client.Client, key types.NamespacedName) (uninstalled bool) { + t.Helper() + hr := &helmv2.HelmRelease{} + if err := cl.Get(ctx, key, hr); err != nil { + t.Fatalf("helm-controller: get: %v", err) + } + if hr.DeletionTimestamp.IsZero() { + t.Fatalf("helm-controller: release is not terminating") + } + uninstalled = !hr.Spec.Suspend + hr.Status.ObservedGeneration = hr.Generation + if err := cl.Status().Update(ctx, hr); err != nil { + t.Fatalf("helm-controller: status update: %v", err) + } + if err := cl.Get(ctx, key, hr); err != nil { + t.Fatalf("helm-controller: re-get: %v", err) + } + var kept []string + for _, f := range hr.Finalizers { + if f != helmv2.HelmReleaseFinalizer { + kept = append(kept, f) + } + } + if len(kept) != len(hr.Finalizers) { + hr.Finalizers = kept + if err := cl.Update(ctx, hr); err != nil { + t.Fatalf("helm-controller: remove finalizer: %v", err) + } + } + return uninstalled +} + +// TestEnvtest_DeleteDuringRecoveryReachesUninstall is the regression for issue +// #4060 itself: a delete arriving while flux-plunger holds its recovery suspension +// must still reach the Helm uninstall. helm-controller and flux-plunger wake on the +// same delete event, so both orders are pinned: helm-controller handling it first +// (it sees the suspension, skips the uninstall and drops its finalizer; only +// flux-plunger's fence finalizer keeps the object alive until the suspension is +// lifted and the uninstall runs), and flux-plunger handling it first. +func TestEnvtest_DeleteDuringRecoveryReachesUninstall(t *testing.T) { + crdDir := os.Getenv("HELMRELEASE_CRD_DIR") + if crdDir == "" { + t.Skip("set HELMRELEASE_CRD_DIR to the dir with the HelmRelease CRD") + } + env := newEnvtestEnvironment(crdDir) + cfg, err := env.Start() + if err != nil { + t.Fatalf("start envtest: %v", err) + } + defer func() { _ = env.Stop() }() + if err := helmv2.AddToScheme(clientgoscheme.Scheme); err != nil { + t.Fatalf("add helm scheme: %v", err) + } + cl, err := client.New(cfg, client.Options{Scheme: clientgoscheme.Scheme}) + if err != nil { + t.Fatalf("client: %v", err) + } + ctx := context.Background() + if err := cl.Create(ctx, &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: testNS}}); err != nil { + t.Fatalf("create ns: %v", err) + } + + for _, tc := range []struct { + name string + helmFirst bool + }{ + {"helm-controller handles the delete first", true}, + {"flux-plunger handles the delete first", false}, + } { + t.Run(tc.name, func(t *testing.T) { + name := testName + map[bool]string{true: "-hc", false: "-fp"}[tc.helmFirst] + key := types.NamespacedName{Namespace: testNS, Name: name} + base := &helmv2.HelmRelease{ + TypeMeta: metav1.TypeMeta{APIVersion: helmv2.GroupVersion.String(), Kind: "HelmRelease"}, + ObjectMeta: metav1.ObjectMeta{Namespace: testNS, Name: name}, + Spec: helmv2.HelmReleaseSpec{ + Interval: metav1.Duration{Duration: 5 * time.Minute}, + Chart: &helmv2.HelmChartTemplate{Spec: helmv2.HelmChartTemplateSpec{Chart: "x", SourceRef: helmv2.CrossNamespaceObjectReference{Kind: "HelmRepository", Name: "r"}}}, + }, + } + if err := cl.Patch(ctx, base, client.Apply, client.FieldOwner(fmHelm)); err != nil { + t.Fatalf("operator base apply: %v", err) + } + hr := &helmv2.HelmRelease{} + if err := cl.Get(ctx, key, hr); err != nil { + t.Fatalf("get: %v", err) + } + hr.Finalizers = append(hr.Finalizers, helmv2.HelmReleaseFinalizer) + if err := cl.Update(ctx, hr); err != nil { + t.Fatalf("add helm-controller finalizer: %v", err) + } + + r := &FluxPlunger{Client: cl, APIReader: cl} + req := ctrl.Request{NamespacedName: key} + if err := cl.Get(ctx, key, hr); err != nil { + t.Fatalf("get: %v", err) + } + if acquired, err := r.suspendHelmRelease(ctx, hr); err != nil || !acquired { + t.Fatalf("acquire: acquired=%v err=%v", acquired, err) + } + + // The delete lands inside the recovery window. + if err := cl.Get(ctx, key, hr); err != nil { + t.Fatalf("get: %v", err) + } + if err := cl.Delete(ctx, hr); err != nil { + t.Fatalf("delete: %v", err) + } + + uninstalled := false + if tc.helmFirst { + uninstalled = simulateHelmControllerDelete(t, ctx, cl, key) || uninstalled + if err := cl.Get(ctx, key, &helmv2.HelmRelease{}); err != nil { + t.Fatalf("the release must survive helm-controller dropping its finalizer while suspended (fence), got %v", err) + } + } + if _, err := r.Reconcile(ctx, req); err != nil { + t.Fatalf("flux-plunger reconcile of the terminating release: %v", err) + } + // Lifting the suspension is itself an update event, so flux-plunger can + // reconcile again before helm-controller has seen the new generation. When + // helm-controller handled the delete first its finalizer is already gone; + // only the observed generation still lagging tells flux-plunger the + // uninstall has not run, so the fence must hold through this pass. + if _, err := r.Reconcile(ctx, req); err != nil { + t.Fatalf("flux-plunger reconcile racing ahead of helm-controller: %v", err) + } + if err := cl.Get(ctx, key, &helmv2.HelmRelease{}); err != nil { + t.Fatalf("the fence must hold until helm-controller has observed the unsuspended generation, got %v", err) + } + if !tc.helmFirst { + uninstalled = simulateHelmControllerDelete(t, ctx, cl, key) || uninstalled + } else { + // With the suspension lifted, helm-controller reconciles again and now + // runs the uninstall. + uninstalled = simulateHelmControllerDelete(t, ctx, cl, key) || uninstalled + } + if !uninstalled { + t.Fatalf("a delete arriving during recovery must reach the Helm uninstall") + } + // With the uninstall done, flux-plunger lifts its fence and the release is + // gone. + if _, err := r.Reconcile(ctx, req); err != nil { + t.Fatalf("flux-plunger reconcile after the uninstall: %v", err) + } + if err := cl.Get(ctx, key, &helmv2.HelmRelease{}); !apierrors.IsNotFound(err) { + t.Fatalf("after the uninstall flux-plunger must lift its fence so the release is deleted, got %v", err) + } + t.Logf("%s: delete during recovery reached the uninstall, release gone", tc.name) + }) + } +} + +// startFenceEnv starts envtest and returns a client plus a helper that creates a +// release under helm-controller's finalizer, as helm-controller leaves every release +// it manages. +func startFenceEnv(t *testing.T) (context.Context, client.Client, func(name string) types.NamespacedName, func()) { + t.Helper() + crdDir := os.Getenv("HELMRELEASE_CRD_DIR") + if crdDir == "" { + t.Skip("set HELMRELEASE_CRD_DIR to the dir with the HelmRelease CRD") + } + env := newEnvtestEnvironment(crdDir) + cfg, err := env.Start() + if err != nil { + t.Fatalf("start envtest: %v", err) + } + if err := helmv2.AddToScheme(clientgoscheme.Scheme); err != nil { + t.Fatalf("add helm scheme: %v", err) + } + cl, err := client.New(cfg, client.Options{Scheme: clientgoscheme.Scheme}) + if err != nil { + t.Fatalf("client: %v", err) + } + ctx := context.Background() + if err := cl.Create(ctx, &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: testNS}}); err != nil { + t.Fatalf("create ns: %v", err) + } + newRelease := func(name string) types.NamespacedName { + key := types.NamespacedName{Namespace: testNS, Name: name} + base := &helmv2.HelmRelease{ + TypeMeta: metav1.TypeMeta{APIVersion: helmv2.GroupVersion.String(), Kind: "HelmRelease"}, + ObjectMeta: metav1.ObjectMeta{Namespace: testNS, Name: name}, + Spec: helmv2.HelmReleaseSpec{ + Interval: metav1.Duration{Duration: 5 * time.Minute}, + Chart: &helmv2.HelmChartTemplate{Spec: helmv2.HelmChartTemplateSpec{Chart: "x", SourceRef: helmv2.CrossNamespaceObjectReference{Kind: "HelmRepository", Name: "r"}}}, + }, + } + if err := cl.Patch(ctx, base, client.Apply, client.FieldOwner(fmHelm)); err != nil { + t.Fatalf("operator base apply: %v", err) + } + hr := &helmv2.HelmRelease{} + if err := cl.Get(ctx, key, hr); err != nil { + t.Fatalf("get: %v", err) + } + hr.Finalizers = append(hr.Finalizers, helmv2.HelmReleaseFinalizer) + if err := cl.Update(ctx, hr); err != nil { + t.Fatalf("add helm-controller finalizer: %v", err) + } + return key + } + return ctx, cl, newRelease, func() { _ = env.Stop() } +} + +// TestEnvtest_DeleteRacingUnsuspendOfLiveReleaseKeepsFence pins the window between +// unsuspendHelmRelease's read of a still-live release and its apply, which lifts the +// suspension and the fence together. A delete landing there that helm-controller +// handles first (suspended, so no uninstall and its finalizer dropped) would leave +// the fence as the last finalizer, and an unpreconditioned apply removing it would +// delete the release without an uninstall. The apply must fail instead, and the +// next reconcile must carry the delete through to the uninstall. +func TestEnvtest_DeleteRacingUnsuspendOfLiveReleaseKeepsFence(t *testing.T) { + ctx, cl, newRelease, stop := startFenceEnv(t) + defer stop() + key := newRelease(testName + "-live") + + start := &helmv2.HelmRelease{} + if err := cl.Get(ctx, key, start); err != nil { + t.Fatalf("get: %v", err) + } + if acquired, err := (&FluxPlunger{Client: cl, APIReader: cl}).suspendHelmRelease(ctx, start); err != nil || !acquired { + t.Fatalf("acquire: acquired=%v err=%v", acquired, err) + } + + // The delete lands right after unsuspendHelmRelease reads the live release, and + // helm-controller handles it while the release is still suspended. + uninstalled := false + racing := &FluxPlunger{Client: cl, APIReader: &writeAfterNthGet{Reader: cl, n: 1, write: func() { + hr := &helmv2.HelmRelease{} + if err := cl.Get(ctx, key, hr); err != nil { + t.Fatalf("race: get: %v", err) + } + if err := cl.Delete(ctx, hr); err != nil { + t.Fatalf("race: delete: %v", err) + } + uninstalled = simulateHelmControllerDelete(t, ctx, cl, key) || uninstalled + }}} + _ = racing.unsuspendHelmRelease(ctx, start) + + if err := cl.Get(ctx, key, &helmv2.HelmRelease{}); err != nil { + t.Fatalf("the release must survive a delete racing the live unsuspend (fence), got %v", err) + } + + r := &FluxPlunger{Client: cl, APIReader: cl} + req := ctrl.Request{NamespacedName: key} + if _, err := r.Reconcile(ctx, req); err != nil { + t.Fatalf("reconcile of the terminating release: %v", err) + } + uninstalled = simulateHelmControllerDelete(t, ctx, cl, key) || uninstalled + if !uninstalled { + t.Fatalf("the delete must reach the Helm uninstall") + } + if _, err := r.Reconcile(ctx, req); err != nil { + t.Fatalf("reconcile after the uninstall: %v", err) + } + if err := cl.Get(ctx, key, &helmv2.HelmRelease{}); !apierrors.IsNotFound(err) { + t.Fatalf("after the uninstall the fence must be lifted and the release gone, got %v", err) + } +} + +// TestEnvtest_ApplyNeverRecreatesAVanishedRelease pins that flux-plunger's apply +// cannot resurrect a release. Server-side apply creates what does not exist, so an +// apply decided on a read of a release that has since gone (its fence removed by +// hand, then deleted) would otherwise create an empty HelmRelease carrying the fence. +func TestEnvtest_ApplyNeverRecreatesAVanishedRelease(t *testing.T) { + ctx, cl, newRelease, stop := startFenceEnv(t) + defer stop() + key := newRelease(testName + "-ghost") + + start := &helmv2.HelmRelease{} + if err := cl.Get(ctx, key, start); err != nil { + t.Fatalf("get: %v", err) + } + r := &FluxPlunger{Client: cl, APIReader: cl} + if acquired, err := r.suspendHelmRelease(ctx, start); err != nil || !acquired { + t.Fatalf("acquire: acquired=%v err=%v", acquired, err) + } + stale := &helmv2.HelmRelease{} + if err := cl.Get(ctx, key, stale); err != nil { + t.Fatalf("get: %v", err) + } + + // The release goes for good: its finalizers are cleared by hand and it is deleted. + gone := stale.DeepCopy() + gone.Finalizers = nil + if err := cl.Update(ctx, gone); err != nil { + t.Fatalf("clear finalizers: %v", err) + } + if err := cl.Delete(ctx, gone); err != nil { + t.Fatalf("delete: %v", err) + } + if err := cl.Get(ctx, key, &helmv2.HelmRelease{}); !apierrors.IsNotFound(err) { + t.Fatalf("setup: release must be gone, got %v", err) + } + + for _, apply := range []struct { + name string + run func() error + }{ + {"relinquish", func() error { return r.applyRecoveryState(ctx, stale, nil, false, false) }}, + {"keep the fence", func() error { return r.applyRecoveryState(ctx, stale, nil, true, false) }}, + } { + _ = apply.run() + if err := cl.Get(ctx, key, &helmv2.HelmRelease{}); !apierrors.IsNotFound(err) { + t.Fatalf("%s apply on a vanished release must not recreate it, got %v", apply.name, err) + } + } +} diff --git a/packages/system/flux-plunger/Makefile b/packages/system/flux-plunger/Makefile index d88b840bd..1ed805bc7 100644 --- a/packages/system/flux-plunger/Makefile +++ b/packages/system/flux-plunger/Makefile @@ -4,6 +4,10 @@ export NAMESPACE=cozy-fluxcd include ../../../hack/common-envs.mk include ../../../hack/package.mk +.PHONY: test +test: + helm unittest . + image: docker buildx build -f images/flux-plunger/Dockerfile ../../../ \ $(call image-tags,flux-plunger,v$(COZYSTACK_VERSION)) \ diff --git a/packages/system/flux-plunger/README.md b/packages/system/flux-plunger/README.md new file mode 100644 index 000000000..93361f568 --- /dev/null +++ b/packages/system/flux-plunger/README.md @@ -0,0 +1,31 @@ +# flux-plunger + +Recovers a HelmRelease stuck with `has no deployed releases`: it suspends the release, deletes the stale Helm storage Secret, records the processed revision in the `flux-plunger.cozystack.io/last-processed-version` annotation, and unsuspends. + +## The uninstall fence + +While a release is suspended for recovery it also carries the finalizer `flux-plunger.cozystack.io/uninstall-fence`. helm-controller skips the Helm uninstall of a suspended HelmRelease that is deleted, so without the fence a delete arriving during recovery would leave the release's resources behind. With it, flux-plunger lifts its suspension, helm-controller runs the uninstall, and flux-plunger then removes the fence. A delete held this way for more than ten minutes raises an `UninstallFenceHeld` Warning on the HelmRelease. + +When flux-plunger stops it gives up the fences it holds itself, within its termination grace period (`shutdownGracePeriodSeconds`, 90 by default, accepted between 40 and 140): its manager is given 10 seconds to stop, and the drain 25 seconds less than the grace period. The next flux-plunger starts while the old one is still terminating, on a rollout as on an eviction or a node drain, so a single writer is kept by leader election: the old pod holds its Lease through the drain without giving it up, and the Lease outlasts the drain, so a new pod waits for it to run out, a little under two minutes at the default, before it acts. A recovery in progress is aborted: the suspension and the fence go together, and the next flux-plunger starts the recovery again. A release being deleted has flux-plunger's suspension lifted and keeps the fence until helm-controller has run its uninstall, which the drain waits for; one helm-controller has not handled when the grace period runs out keeps its fence. Uninstalling this chart then releases whatever is left: a pre-delete hook stops flux-plunger, waits out its grace period, and lifts any remaining suspension and fence without waiting again. It lifts a suspension only where flux-plunger is the sole manager holding it, which is the outcome flux-plunger's own relinquish has, so a suspension another manager also holds stays; it does so with a patch of `spec.suspend` alone rather than a `kubectl apply`, which on a release last written by a client-side apply would take over and strip the fields that apply set. A release it unfences that was being deleted, that helm-controller's own finalizer no longer held and whose latest generation helm-controller had not observed, is deleted without an uninstall and is named as such. The Job's 240-second deadline sits under the 300 seconds helm-controller allows a pre-delete hook by default. A Deployment that cannot be read or scaled down (flux-plunger would keep running and could fence behind the sweep) ends the hook before any fence is touched, a listing that never succeeds ends it before any fence is touched too, and a fence the hook cannot remove ends it after the sweep; either way the hook exits non-zero, which fails the uninstall and makes helm-controller retry it, hook included. A flux-plunger Deployment that is already gone has nothing to stop, and a flux-plunger pod that is still there after its grace period, typically one stuck `Terminating` on a `NotReady` node, is named and the sweep goes on, since failing on it would fail every retry until the node returns or the pod is force-deleted; because such a pod may still be fencing, the fences are listed again after the sweep, and any found fails the hook. Its report, `released N of M fenced HelmReleases, K without an uninstall` and a line per release, stays readable for ten minutes after the Job finishes, success included: `kubectl logs --namespace cozy-fluxcd job/flux-plunger-uninstall-fence-cleanup`. + +If flux-plunger is merely stopped (scaled to zero) rather than uninstalled, or killed without a graceful stop, a fenced release that is deleted and that helm-controller has not uninstalled stays `Terminating` until flux-plunger runs again. To release one by hand, after confirming its uninstall has run or is not wanted, remove the finalizer at the position `INDEX` it has in `metadata.finalizers`; the `test` operation makes the patch fail rather than remove another finalizer if the list has changed: + +```bash +kubectl patch helmrelease NAME --namespace NAMESPACE --type json --patch '[{"op":"test","path":"/metadata/finalizers/INDEX","value":"flux-plunger.cozystack.io/uninstall-fence"},{"op":"remove","path":"/metadata/finalizers/INDEX"}]' +``` + +Fenced releases can be listed with: + +```bash +kubectl get helmreleases.helm.toolkit.fluxcd.io --all-namespaces --output go-template='{{range .items}}{{$ns := .metadata.namespace}}{{$name := .metadata.name}}{{range .metadata.finalizers}}{{if eq . "flux-plunger.cozystack.io/uninstall-fence"}}{{$ns}}/{{$name}}{{"\n"}}{{end}}{{end}}{{end}}' +``` + +## Suspensions left by an earlier flux-plunger + +Earlier flux-plunger releases set `spec.suspend` through the shared `flux-client-side-apply` manager, so a suspension one of them left behind cannot be told apart from a migration's or an operator's and is treated as external: it is not cleared automatically. Such a leftover exists only if the old pod stopped in the middle of a recovery, and flux-plunger raises a `SuspensionNotOwned` Warning on it. To list candidates, suspended releases carrying the flux-plunger annotation whose `spec.suspend` is not owned by flux-plunger's apply: + +```bash +kubectl get helmreleases.helm.toolkit.fluxcd.io --all-namespaces --output json | jq --raw-output '.items[] | select(.spec.suspend == true) | select(.metadata.annotations["flux-plunger.cozystack.io/last-processed-version"] != null) | select([.metadata.managedFields[]? | select(.manager == "flux-plunger" and .operation == "Apply" and .fieldsV1["f:spec"]["f:suspend"] != null)] | length == 0) | "\(.metadata.namespace)/\(.metadata.name)"' +``` + +Clearing one is an operator action: confirm nothing else (a migration, a restore) is holding it, then resume it with `flux resume helmrelease NAME --namespace NAMESPACE`. diff --git a/packages/system/flux-plunger/templates/deployment.yaml b/packages/system/flux-plunger/templates/deployment.yaml index 7ce6bb13c..fd856d251 100644 --- a/packages/system/flux-plunger/templates/deployment.yaml +++ b/packages/system/flux-plunger/templates/deployment.yaml @@ -6,7 +6,34 @@ metadata: app.kubernetes.io/name: flux-plunger app.kubernetes.io/instance: {{ .Release.Name }} spec: + {{- /* + flux-plunger treats a suspension its own field manager owns, seen in a fresh + reconcile, as its own interrupted run, so exactly one process may act on a + HelmRelease at a time. No rollout strategy gives that: the next pod starts as + soon as the old one is terminating, and an eviction or a node drain replaces a + pod the same way, while the old one stops its manager and drains its fences + (cmd/flux-plunger/main.go). What keeps a single writer is the leader Lease + (--leader-elect), which the old pod holds through the drain and which outlasts + it, so the next pod waits for it before it acts. maxSurge 0 only keeps a rollout + from starting the next pod before the old one is told to stop. This stays + RollingUpdate rather than Recreate because existing installs carry the + apiserver-defaulted rollingUpdate block (the chart shipped without a strategy), + and helm-controller applies server-side, where type Recreate over that block is + rejected on upgrade. + */}} + {{- $grace := int .Values.shutdownGracePeriodSeconds }} + {{- if ne (toString .Values.shutdownGracePeriodSeconds) (toString $grace) }} + {{- fail "shutdownGracePeriodSeconds must be a whole number of seconds: terminationGracePeriodSeconds takes an integer" }} + {{- end }} + {{- if or (lt $grace 40) (gt $grace 140) }} + {{- fail "shutdownGracePeriodSeconds must be between 40 and 140: below, the drain gets no time after the manager's 10s stop; above, the pre-delete hook cannot wait the pod out inside its deadline" }} + {{- end }} replicas: 1 + strategy: + type: RollingUpdate + rollingUpdate: + maxSurge: 0 + maxUnavailable: 1 selector: matchLabels: app.kubernetes.io/name: flux-plunger @@ -18,6 +45,7 @@ spec: app.kubernetes.io/instance: {{ .Release.Name }} spec: serviceAccountName: flux-plunger + terminationGracePeriodSeconds: {{ .Values.shutdownGracePeriodSeconds }} containers: - name: flux-plunger image: "{{ .Values.image }}" @@ -29,6 +57,9 @@ spec: {{- end }} - --metrics-bind-address=:8080 - --metrics-secure=false + - --leader-elect + # The manager's stop takes up to 10s; the rest leaves 15s before SIGKILL. + - --shutdown-drain-timeout={{ sub .Values.shutdownGracePeriodSeconds 25 }}s ports: - name: metrics containerPort: 8080 diff --git a/packages/system/flux-plunger/templates/rbac.yaml b/packages/system/flux-plunger/templates/rbac.yaml index 97d4eac7e..9f47ac21c 100644 --- a/packages/system/flux-plunger/templates/rbac.yaml +++ b/packages/system/flux-plunger/templates/rbac.yaml @@ -22,6 +22,13 @@ rules: - get - list - delete +- apiGroups: + - "" + resources: + - events + verbs: + - create + - patch --- apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRoleBinding @@ -35,3 +42,28 @@ subjects: - kind: ServiceAccount name: flux-plunger namespace: {{ .Release.Namespace }} +--- +# The leader Lease (--leader-elect) lives in the release namespace. +apiVersion: rbac.authorization.k8s.io/v1 +kind: Role +metadata: + name: flux-plunger-leader-election + namespace: {{ .Release.Namespace }} +rules: +- apiGroups: ["coordination.k8s.io"] + resources: ["leases"] + verbs: ["get", "list", "watch", "create", "update", "patch"] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: RoleBinding +metadata: + name: flux-plunger-leader-election + namespace: {{ .Release.Namespace }} +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: Role + name: flux-plunger-leader-election +subjects: +- kind: ServiceAccount + name: flux-plunger + namespace: {{ .Release.Namespace }} diff --git a/packages/system/flux-plunger/templates/uninstall-fence-cleanup.yaml b/packages/system/flux-plunger/templates/uninstall-fence-cleanup.yaml new file mode 100644 index 000000000..669d0f804 --- /dev/null +++ b/packages/system/flux-plunger/templates/uninstall-fence-cleanup.yaml @@ -0,0 +1,391 @@ +{{- /* + flux-plunger sets a finalizer, flux-plunger.cozystack.io/uninstall-fence, on a + HelmRelease it is recovering, and only flux-plunger removes it. When it stops it + gives them all up itself (DrainFences): it lifts its suspensions and, within its + termination grace period, waits for helm-controller to uninstall each release + being deleted before lifting that fence. This hook is the backstop for what the + drain could not finish, so that removing the chart never leaves a release that + tenant teardown waits on forever: it stops flux-plunger, waits out the drain, + then lifts any suspension and fence that remain, without waiting again. + + Two bounds apply. helm-controller runs a pre-delete hook under the release's + uninstall timeout, 300s by default (the operator sets none), counted from when + helm creates the hook; the Job's activeDeadlineSeconds is counted from the Job's + start, so it has to end first, with room for the pod to be scheduled and pulled. + The pod wait covers flux-plunger's grace period, and the sweep has the rest. + + A scale-down or a listing that never succeeds ends the hook before any fence is + touched, and a fence that cannot be removed ends it once the sweep is done. + Either way it exits non-zero: the failed hook fails the uninstall before helm + records anything, and helm-controller retries it, running this hook again from a + state it can still converge from; exiting 0 would let the chart go and leave the + fence with nothing to remove it. A pod still there after its grace period is + named and the sweep goes on; since that pod may still be fencing, the fences are + listed again after the sweep, and any found fails the hook the same way. +*/ -}} +{{- $img := printf "%s:%s" .Values.kubectlImage.repository .Values.kubectlImage.tag }} +{{- with .Values.kubectlImage.digest }}{{- $img = printf "%s@%s" $img . }}{{- end }} +{{- $deadline := 240 }} +{{- $podWait := add .Values.shutdownGracePeriodSeconds 10 }} +{{- $retryWindow := sub $deadline 60 }} +apiVersion: v1 +kind: ServiceAccount +metadata: + name: flux-plunger-uninstall-fence-cleanup + namespace: {{ .Release.Namespace }} + annotations: + helm.sh/hook: pre-delete + helm.sh/hook-weight: "-10" + helm.sh/hook-delete-policy: hook-succeeded,hook-failed,before-hook-creation +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRole +metadata: + name: flux-plunger-uninstall-fence-cleanup + annotations: + helm.sh/hook: pre-delete + helm.sh/hook-weight: "-10" + helm.sh/hook-delete-policy: hook-succeeded,hook-failed,before-hook-creation +rules: + - apiGroups: ["helm.toolkit.fluxcd.io"] + resources: ["helmreleases"] + verbs: ["get", "list", "patch"] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRoleBinding +metadata: + name: flux-plunger-uninstall-fence-cleanup + annotations: + helm.sh/hook: pre-delete + helm.sh/hook-weight: "-10" + helm.sh/hook-delete-policy: hook-succeeded,hook-failed,before-hook-creation +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: ClusterRole + name: flux-plunger-uninstall-fence-cleanup +subjects: + - kind: ServiceAccount + name: flux-plunger-uninstall-fence-cleanup + namespace: {{ .Release.Namespace }} +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: Role +metadata: + name: flux-plunger-uninstall-fence-cleanup + namespace: {{ .Release.Namespace }} + annotations: + helm.sh/hook: pre-delete + helm.sh/hook-weight: "-10" + helm.sh/hook-delete-policy: hook-succeeded,hook-failed,before-hook-creation +rules: + # kubectl scale reads the Deployment, then patches its scale subresource. + - apiGroups: ["apps"] + resources: ["deployments"] + resourceNames: ["flux-plunger"] + verbs: ["get"] + - apiGroups: ["apps"] + resources: ["deployments/scale"] + resourceNames: ["flux-plunger"] + verbs: ["patch"] + - apiGroups: [""] + resources: ["pods"] + verbs: ["get", "list", "watch"] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: RoleBinding +metadata: + name: flux-plunger-uninstall-fence-cleanup + namespace: {{ .Release.Namespace }} + annotations: + helm.sh/hook: pre-delete + helm.sh/hook-weight: "-10" + helm.sh/hook-delete-policy: hook-succeeded,hook-failed,before-hook-creation +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: Role + name: flux-plunger-uninstall-fence-cleanup +subjects: + - kind: ServiceAccount + name: flux-plunger-uninstall-fence-cleanup + namespace: {{ .Release.Namespace }} +--- +apiVersion: batch/v1 +kind: Job +metadata: + name: flux-plunger-uninstall-fence-cleanup + namespace: {{ .Release.Namespace }} + annotations: + helm.sh/hook: pre-delete + helm.sh/hook-weight: "0" + # No hook-succeeded: a succeeded Job would go with its pod and the report + # in its log. helm.sh/hook-output-log-policy cannot stand in for that, since + # helm-controller calls a nil output writer for it + # (https://github.com/fluxcd/helm-controller/issues/1562). + helm.sh/hook-delete-policy: before-hook-creation +spec: + # Under helm's own bound for the hook; see the header. + activeDeadlineSeconds: {{ $deadline }} + # One run fills the deadline; helm-controller retries the whole uninstall, + # with a fresh budget, instead of a second pod racing it out. + backoffLimit: 0 + # The finished Job, and the report in its pod's log, outlive the chart this long. + ttlSecondsAfterFinished: 600 + template: + spec: + serviceAccountName: flux-plunger-uninstall-fence-cleanup + restartPolicy: Never + securityContext: + runAsNonRoot: true + runAsUser: 65532 + seccompProfile: + type: RuntimeDefault + # kubectl keeps its discovery cache under $HOME; under a read-only root + # filesystem the emptyDir is the one place it can write it. + volumes: + - name: kube-cache + emptyDir: {} + containers: + - name: cleanup + image: {{ $img }} + imagePullPolicy: {{ .Values.kubectlImage.pullPolicy }} + # Same small fixed footprint as the other hooks that run this image, + # so the pod is scheduled promptly inside the deadline. + resources: + requests: + cpu: 10m + memory: 32Mi + limits: + cpu: 100m + memory: 64Mi + securityContext: + allowPrivilegeEscalation: false + readOnlyRootFilesystem: true + capabilities: + drop: ["ALL"] + env: + - name: NAMESPACE + value: {{ .Release.Namespace }} + - name: HOME + value: /tmp + volumeMounts: + - name: kube-cache + mountPath: /tmp + command: + - sh + - -c + - | + set -u + fence=flux-plunger.cozystack.io/uninstall-fence + deploy=flux-plunger + hr=helmreleases.helm.toolkit.fluxcd.io + # HR_SCOPE narrows the sweep so the script can be exercised against + # one namespace; the hook itself always covers the cluster. + scope="${HR_SCOPE:---all-namespaces}" + # The pod is given its grace period, and a little more, to drain. + pod_wait={{ $podWait }} + # Retries stop here, a minute short of activeDeadlineSeconds, which + # counts from the Job's start, so the report is still written when + # scheduling and the image pull took part of it. The pod wait is cut + # to what is left of this window too. + retry_until=$(( $(date +%s) + {{ $retryWindow }} )) + # Each fenced release once, however many copies of the fence it + # carries: the apiserver accepts a finalizer listed twice. + listing='{{`{{range .items}}{{$fenced := false}}{{range .metadata.finalizers}}{{if eq . "flux-plunger.cozystack.io/uninstall-fence"}}{{$fenced = true}}{{end}}{{end}}{{if $fenced}}{{.metadata.namespace}}/{{.metadata.name}}{{"\n"}}{{end}}{{end}}`}}' + + # No per-call --request-timeout: any client override makes kubectl + # skip the in-cluster config and dial localhost:8080. A wedged call + # is bounded by activeDeadlineSeconds instead, and a Job killed by + # it fails the uninstall, which helm-controller then retries. + + # retry ...: run until it succeeds or the retry window closes, + # at least once. Only the successful attempt's output is printed: + # kubectl prints what it has before it fails, and that must not be + # read as part of the answer. Each failure's stderr stays in the log. + retry() { + while :; do + if out=$("$@"); then + printf '%s\n' "$out" + return 0 + fi + [ "$(date +%s)" -lt "$retry_until" ] || return 1 + sleep 2 + done + } + + # lift_suspension : lift the spec.suspend flux-plunger's + # apply owns, with the same outcome as the controller's relinquish: a + # suspension another manager also holds is left standing. Not with + # kubectl apply --server-side: on a release created by a client-side + # kubectl apply it hands every field that apply set to flux-plunger + # and then strips them. The patch is preconditioned on the + # resourceVersion and uid of the read that decided on it, and a write + # landing in between makes it read again. Returns 2 when the release + # cannot be read, 1 when the suspension cannot be lifted. + lift_suspension() { + ls_ns=$1 + ls_name=$2 + while :; do + if ! read_out=$(retry kubectl --namespace "$ls_ns" get "$hr" "$ls_name" --ignore-not-found --output go-template='{{`{{.metadata.resourceVersion}} {{.metadata.uid}} {{if .spec.suspend}}{{range .metadata.managedFields}}{{$owns := false}}{{range $k, $v := .fieldsV1}}{{if eq $k "f:spec"}}{{range $k2, $v2 := $v}}{{if eq $k2 "f:suspend"}}{{$owns = true}}{{end}}{{end}}{{end}}{{end}}{{if $owns}}{{if and (eq .manager "flux-plunger") (eq .operation "Apply")}} yes{{end}}{{if ne .manager "flux-plunger"}} other{{end}}{{end}}{{end}}{{end}}`}}'); then + return 2 + fi + # shellcheck disable=SC2086 # split into resourceVersion, uid, marks + set -- $read_out + [ "$#" -ge 2 ] || return 0 + ls_rv=$1 + ls_uid=$2 + shift 2 + case "$*" in + *other*) return 0 ;; + *yes*) ;; + *) return 0 ;; + esac + if kubectl --namespace "$ls_ns" patch "$hr" "$ls_name" --type json --field-manager flux-plunger \ + --patch "[{\"op\":\"test\",\"path\":\"/metadata/resourceVersion\",\"value\":\"$ls_rv\"},{\"op\":\"test\",\"path\":\"/metadata/uid\",\"value\":\"$ls_uid\"},{\"op\":\"replace\",\"path\":\"/spec/suspend\",\"value\":false}]"; then + return 0 + fi + [ "$(date +%s)" -lt "$retry_until" ] || return 1 + sleep 2 + done + } + + # release_fence : remove the fence at the index it holds + # now, and again if the apiserver, which accepts a finalizer listed + # twice, has it twice. A failed patch is retried with a fresh read, + # because helm-controller keeps adding and dropping its own finalizer + # ahead of the fence while this runs. A release or fence already + # gone counts as released; one whose fence keeps coming back, as + # under a flux-plunger still running, gives up after a few copies. + release_fence() { + removed=0 + while :; do + if idx=$(kubectl --namespace "$1" get "$hr" "$2" --ignore-not-found --output go-template='{{`{{range $i, $f := .metadata.finalizers}}{{if eq $f "flux-plunger.cozystack.io/uninstall-fence"}}{{$i}} {{end}}{{end}}`}}'); then + idx=${idx%% *} + [ -n "$idx" ] || return 0 + [ "$removed" -lt 8 ] || return 1 + case "$idx" in + *[!0-9]*) echo "unexpected finalizer index '$idx' on $1/$2" >&2 ;; + *) + if kubectl --namespace "$1" patch "$hr" "$2" --type json \ + --patch "[{\"op\":\"test\",\"path\":\"/metadata/finalizers/$idx\",\"value\":\"$fence\"},{\"op\":\"remove\",\"path\":\"/metadata/finalizers/$idx\"}]"; then + removed=$((removed + 1)) + continue + fi ;; + esac + fi + [ "$(date +%s)" -lt "$retry_until" ] || return 1 + sleep 2 + done + } + + # flux-plunger gives up its fences itself when it stops: it lifts its + # suspensions and waits, within its grace period, for helm-controller + # to uninstall each release being deleted. So stop it and wait for + # the pod to go before sweeping. A scale-down that fails exits before + # any fence is touched, since a flux-plunger still running could set a + # fence behind the sweep and the retried uninstall should start from + # the same state; a Deployment already gone has nothing to stop. + if ! present=$(retry kubectl --namespace "$NAMESPACE" get deployment "$deploy" --ignore-not-found --output name); then + echo "could not read the $deploy Deployment; no fence was touched" >&2 + exit 1 + fi + if [ -z "$present" ]; then + echo "no $deploy Deployment in $NAMESPACE; nothing to stop" + elif ! retry kubectl --namespace "$NAMESPACE" scale deployment "$deploy" --replicas=0; then + echo "could not scale $deploy down; no fence was touched" >&2 + exit 1 + fi + # A pod still there after its grace period is named, not failed on: + # the usual one is stuck Terminating on a NotReady node until the node + # returns or the pod is force-deleted, and failing would fail every + # retried uninstall. A wait that failed for another reason is told + # apart by listing the pods. + wait_for=$(( retry_until - $(date +%s) )) + [ "$wait_for" -le "$pod_wait" ] || wait_for=$pod_wait + [ "$wait_for" -ge 1 ] || wait_for=1 + pods_gone=yes + if ! kubectl --namespace "$NAMESPACE" wait --for=delete pod \ + --selector app.kubernetes.io/name=flux-plunger,app.kubernetes.io/instance={{ .Release.Name }} \ + --timeout="${wait_for}s"; then + if ! left_pods=$(retry kubectl --namespace "$NAMESPACE" get pod \ + --selector app.kubernetes.io/name=flux-plunger,app.kubernetes.io/instance={{ .Release.Name }} \ + --output name); then + echo "could not tell whether $deploy pods are still running; sweeping anyway" >&2 + pods_gone=no + elif [ -n "$left_pods" ]; then + # shellcheck disable=SC2086 # one line for the names + echo "$deploy pods are still running, sweeping anyway:" $left_pods >&2 + pods_gone=no + else + echo "the wait for $deploy pods to go failed, but none is left" >&2 + fi + fi + + # An unanswered listing is not an empty one. + # shellcheck disable=SC2086 # scope is one or two words on purpose + if ! fenced=$(retry kubectl get "$hr" $scope --output "go-template=$listing"); then + echo "could not list fenced HelmReleases; no fence was released" >&2 + exit 1 + fi + + # What is left is what the drain could not finish: flux-plunger did + # not stop gracefully, or helm-controller did not uninstall a release + # being deleted within the grace period. Each loses flux-plunger's + # suspension and the fence without waiting any longer. One being + # deleted that helm-controller's own finalizer no longer holds, and + # whose latest generation it has not observed, is then deleted + # without an uninstall, and is named as such. + total=0 + released=0 + unhandled=0 + for ref in $fenced; do + total=$((total + 1)) + hns=${ref%%/*} + name=${ref#*/} + lift_suspension "$hns" "$name" + case $? in + 2) + echo "NOT released $ref: it could not be read" >&2 + continue ;; + 1) + # Without the fence a deleted release that is still + # suspended is removed without an uninstall. + echo "NOT released $ref: flux-plunger's suspension could not be lifted" >&2 + continue ;; + esac + state=$(kubectl --namespace "$hns" get "$hr" "$name" --ignore-not-found --output go-template='{{`{{if .metadata.deletionTimestamp}}{{$held := false}}{{range .metadata.finalizers}}{{if eq . "finalizers.fluxcd.io"}}{{$held = true}}{{end}}{{end}}{{if and (not $held) (ne (printf "%v" .status.observedGeneration) (printf "%v" .metadata.generation))}}unhandled{{end}}{{end}}`}}') || state=unknown + if ! release_fence "$hns" "$name"; then + echo "NOT released $ref: the fence could not be removed" >&2 + continue + fi + released=$((released + 1)) + case "$state" in + unhandled) + unhandled=$((unhandled + 1)) + echo "released $fence from $ref without an uninstall: helm-controller had not handled it" ;; + unknown) + echo "released $fence from $ref; whether helm-controller had handled it could not be read" ;; + *) + echo "released $fence from $ref" ;; + esac + done + + echo "released $released of $total fenced HelmReleases, $unhandled without an uninstall" + # A flux-plunger still running could have fenced a release after the + # listing, and with the chart gone nothing would remove that fence. + if [ "$pods_gone" = no ]; then + # shellcheck disable=SC2086 # scope is one or two words on purpose + if ! again=$(retry kubectl get "$hr" $scope --output "go-template=$listing"); then + echo "could not list fenced HelmReleases again after the sweep" >&2 + exit 1 + fi + if [ -n "$again" ]; then + for ref in $again; do + echo "NOT released $ref: fenced after the sweep; a flux-plunger is still running" >&2 + done + exit 1 + fi + fi + if [ "$released" -eq "$total" ]; then + exit 0 + fi + exit 1 diff --git a/packages/system/flux-plunger/tests/deployment_test.yaml b/packages/system/flux-plunger/tests/deployment_test.yaml new file mode 100644 index 000000000..a351bef20 --- /dev/null +++ b/packages/system/flux-plunger/tests/deployment_test.yaml @@ -0,0 +1,58 @@ +suite: flux-plunger Deployment +# On SIGTERM flux-plunger stops its manager (up to 10s) and then gives up the +# uninstall fences it holds (DrainFences). The kubelet kills it once +# terminationGracePeriodSeconds is spent, so stop and drain together have to end +# inside that grace period. The next flux-plunger starts while this one is still +# terminating, so it is leader election that keeps a single writer meanwhile. +release: + name: flux-plunger + namespace: cozy-fluxcd +templates: + - templates/deployment.yaml +tests: + - it: gives the shutdown drain a deadline inside the termination grace period + asserts: + - equal: + path: spec.template.spec.terminationGracePeriodSeconds + value: 90 + - contains: + path: spec.template.spec.containers[0].args + content: --shutdown-drain-timeout=65s + + - it: derives both from one value + set: + shutdownGracePeriodSeconds: 120 + asserts: + - equal: + path: spec.template.spec.terminationGracePeriodSeconds + value: 120 + - contains: + path: spec.template.spec.containers[0].args + content: --shutdown-drain-timeout=95s + + - it: runs under leader election, the one thing that keeps the next pod from writing during the drain + asserts: + - contains: + path: spec.template.spec.containers[0].args + content: --leader-elect + + - it: refuses a grace period that leaves the drain no time + set: + shutdownGracePeriodSeconds: 39 + asserts: + - failedTemplate: + errorPattern: shutdownGracePeriodSeconds must be between 40 and 140 + + - it: refuses a grace period that is not a whole number of seconds + set: + shutdownGracePeriodSeconds: 90.7 + asserts: + - failedTemplate: + errorPattern: shutdownGracePeriodSeconds must be a whole number of seconds + + - it: refuses a grace period the pre-delete hook cannot wait out inside its deadline + set: + shutdownGracePeriodSeconds: 141 + asserts: + - failedTemplate: + errorPattern: shutdownGracePeriodSeconds must be between 40 and 140 diff --git a/packages/system/flux-plunger/tests/rbac_test.yaml b/packages/system/flux-plunger/tests/rbac_test.yaml new file mode 100644 index 000000000..aa00815c2 --- /dev/null +++ b/packages/system/flux-plunger/tests/rbac_test.yaml @@ -0,0 +1,21 @@ +suite: flux-plunger RBAC +release: + name: flux-plunger + namespace: cozy-fluxcd +templates: + - templates/rbac.yaml +tests: + - it: may hold the leader Lease the Deployment's leader election uses, in its own namespace only + documentSelector: + path: kind + value: Role + asserts: + - equal: + path: metadata.namespace + value: cozy-fluxcd + - equal: + path: rules + value: + - apiGroups: ["coordination.k8s.io"] + resources: ["leases"] + verbs: ["get", "list", "watch", "create", "update", "patch"] diff --git a/packages/system/flux-plunger/tests/uninstall-fence-cleanup_test.yaml b/packages/system/flux-plunger/tests/uninstall-fence-cleanup_test.yaml new file mode 100644 index 000000000..1502174f2 --- /dev/null +++ b/packages/system/flux-plunger/tests/uninstall-fence-cleanup_test.yaml @@ -0,0 +1,132 @@ +suite: flux-plunger pre-delete uninstall-fence cleanup +# flux-plunger holds a finalizer (flux-plunger.cozystack.io/uninstall-fence) on a +# HelmRelease it is recovering. Nothing else in the tree knows that finalizer, so +# uninstalling this chart must release it, or a release deleted meanwhile stays +# Terminating forever. +release: + name: flux-plunger + namespace: cozy-fluxcd +templates: + - templates/uninstall-fence-cleanup.yaml +tests: + - it: runs before the release is deleted, bounded, and cleans itself up afterwards + documentSelector: + path: kind + value: Job + asserts: + - equal: + path: metadata.annotations["helm.sh/hook"] + value: pre-delete + # Kept after it finishes, success included, so its report can be read + # until ttlSecondsAfterFinished; the next run replaces it. + - equal: + path: metadata.annotations["helm.sh/hook-delete-policy"] + value: before-hook-creation + - equal: + path: spec.ttlSecondsAfterFinished + value: 600 + # helm-controller never sets Helm's hook output writer, and a hook with + # this annotation makes it call the nil func + # (https://github.com/fluxcd/helm-controller/issues/1562). + - notExists: + path: metadata.annotations["helm.sh/hook-output-log-policy"] + # Under helm-controller's default 300s uninstall timeout, which bounds the + # hook; hack/flux-plunger-fence-hook_test.bats holds the relation. + - equal: + path: spec.activeDeadlineSeconds + value: 240 + # One run fills the deadline, so a second pod would end the Job + # DeadlineExceeded and lose the first one's report; helm-controller + # retries the whole uninstall, with a fresh budget, instead. + - equal: + path: spec.backoffLimit + value: 0 + # Same pull policy and fixed footprint as the other hooks that run this + # image, so the pod is scheduled and started promptly inside the deadline. + - equal: + path: spec.template.spec.containers[0].imagePullPolicy + value: IfNotPresent + - equal: + path: spec.template.spec.containers[0].resources + value: + requests: + cpu: 10m + memory: 32Mi + limits: + cpu: 100m + memory: 64Mi + - equal: + path: spec.template.spec.serviceAccountName + value: flux-plunger-uninstall-fence-cleanup + # Digest-pinned so an upstream retag does not change what runs. + - equal: + path: spec.template.spec.containers[0].image + value: docker.io/clastix/kubectl:v1.32@sha256:b9ef7d8dbe65bcc81a46c09b8dc7543103055021c4f43287bf59e92a8f4fe05c + + - it: strips the fence by name and stops flux-plunger first + documentSelector: + path: kind + value: Job + asserts: + - matchRegex: + path: spec.template.spec.containers[0].command[2] + pattern: 'fence=flux-plunger\.cozystack\.io/uninstall-fence' + - matchRegex: + path: spec.template.spec.containers[0].command[2] + pattern: 'scale deployment "\$deploy" --replicas=0' + - equal: + path: spec.template.spec.containers[0].env[0].name + value: NAMESPACE + - equal: + path: spec.template.spec.containers[0].env[0].value + value: cozy-fluxcd + + - it: may read and patch HelmReleases cluster-wide, and nothing more there + documentSelector: + path: kind + value: ClusterRole + asserts: + - equal: + path: rules + value: + - apiGroups: ["helm.toolkit.fluxcd.io"] + resources: ["helmreleases"] + verbs: ["get", "list", "patch"] + + - it: may scale down only its own Deployment and watch its pods go + documentSelector: + path: kind + value: Role + asserts: + - equal: + path: metadata.namespace + value: cozy-fluxcd + - equal: + path: rules + value: + - apiGroups: ["apps"] + resources: ["deployments"] + resourceNames: ["flux-plunger"] + verbs: ["get"] + - apiGroups: ["apps"] + resources: ["deployments/scale"] + resourceNames: ["flux-plunger"] + verbs: ["patch"] + - apiGroups: [""] + resources: ["pods"] + verbs: ["get", "list", "watch"] + + - it: runs under the restricted pod security standard + documentSelector: + path: kind + value: Job + asserts: + - equal: + path: spec.template.spec.securityContext.runAsNonRoot + value: true + - equal: + path: spec.template.spec.containers[0].securityContext.allowPrivilegeEscalation + value: false + - equal: + path: spec.template.spec.containers[0].securityContext.readOnlyRootFilesystem + value: true diff --git a/packages/system/flux-plunger/values.yaml b/packages/system/flux-plunger/values.yaml index 1da126104..69e9f1465 100644 --- a/packages/system/flux-plunger/values.yaml +++ b/packages/system/flux-plunger/values.yaml @@ -1 +1,23 @@ image: "ghcr.io/cozystack/cozystack/flux-plunger:latest@sha256:6a6ec938973e6583c5e1573f7d25beddc1852a6699a089116b2407e29a564a72" + +# How long flux-plunger is given to stop, between 40 and 140. On SIGTERM it stops +# its manager (up to 10 seconds), then gives up the uninstall fences it holds, +# waiting for helm-controller to uninstall a release being deleted, under a +# deadline 25 seconds shorter than this. Its leader Lease outlasts both, so the +# next flux-plunger waits a little under two minutes at the default before it +# acts. The pre-delete hook waits for the pod a little longer than this before it +# releases what is left. +shutdownGracePeriodSeconds: 90 + +# Image for the pre-delete uninstall-fence cleanup hook Job (see +# templates/uninstall-fence-cleanup.yaml). Only needs a kubectl binary. The tag +# is digest-pinned so an upstream retag does not change what runs across the +# fleet; refresh by resolving the current manifest-list digest +# (`docker manifest inspect docker.io/clastix/kubectl:v1.32`) and updating +# `digest` below. Same image the etcd-operator and postgres-operator hooks pin. +# renovate: datasource=docker depName=docker.io/clastix/kubectl +kubectlImage: + repository: docker.io/clastix/kubectl + tag: v1.32 + digest: sha256:b9ef7d8dbe65bcc81a46c09b8dc7543103055021c4f43287bf59e92a8f4fe05c + pullPolicy: IfNotPresent From 730592f3235bb582c36157b891017e3dd4abe91e Mon Sep 17 00:00:00 2001 From: Andrey Kolkov Date: Wed, 26 Aug 2026 17:48:56 +0400 Subject: [PATCH 0003/1280] feat(mongodb): support the system-bucket backup flow (useSystemBucket) MongoDB was the only cozy-default app with no useSystemBucket flow: its backup storage was always static on the app CR (bucket/endpoint/creds from backup.* values + a chart-emitted -s3-creds Secret), so a tenant could not back up to the platform system bucket out of the box the way postgres/clickhouse/etc. do. PBM takes bucket/endpointUrl/region/prefix as static CR fields (not secret refs) and the platform bucket name/endpoint are only known at BackupJob time, so - unlike ClickHouse's runtime env secretKeyRef - the chart cannot render them. The fix mirrors the CNPG driver: the chart adds a useSystemBucket flag that keeps spec.backup.enabled (so the pbm agents run) but omits the static storages/tasks/pitr and the creds Secret; the cozy-default MongoDB strategy carries the coordinates (endpointUrl already scheme'd by the endpoint helper, credentialsSecret cozy-backups-creds); and the psmdb driver SSA-injects spec.backup.storages[s3-storage] onto the live PerconaServerMongoDB at BackupJob time under its own field manager with ForceOwnership, so a Flux re-render never reverts it. Injection is gated on the storage being absent, so a legacy app that ships its own static storage is left untouched. The backup snapshot falls back to the strategy coordinates when the operator status echo is empty, so the restore path rebuilds backupSource (credentialsSecret cozy-backups-creds is projected into the restore namespace before dispatch). RBAC grows patch/update on perconaservermongodbs for the injection. A bootstrap.enabled + useSystemBucket render guard mirrors postgres. Signed-off-by: Andrey Kolkov Assisted-By: LLM --- api/apps/v1alpha1/mongodb/types.go | 3 + .../strategy/v1alpha1/mongodb_types.go | 39 +++++++++ .../v1alpha1/zz_generated.deepcopy.go | 25 ++++++ .../psmdbstrategy_controller.go | 81 +++++++++++++++++++ .../psmdbstrategy_controller_test.go | 41 ++++++++++ packages/apps/mongodb/README.md | 23 +++--- .../apps/mongodb/templates/backup-secret.yaml | 12 ++- packages/apps/mongodb/templates/mongodb.yaml | 12 ++- packages/apps/mongodb/templates/restore.yaml | 3 + .../mongodb/tests/backup-secret_test.yaml | 19 ++++- packages/apps/mongodb/tests/mongodb_test.yaml | 52 ++++++++++++ packages/apps/mongodb/values.schema.json | 5 ++ packages/apps/mongodb/values.yaml | 2 + ...trategy.backups.cozystack.io_mongodbs.yaml | 39 +++++++++ .../templates/rbac.yaml | 4 +- .../templates/strategy-mongodb-default.yaml | 63 ++++++++++----- .../system/mongodb-rd/cozyrds/mongodb.yaml | 4 +- 17 files changed, 385 insertions(+), 42 deletions(-) diff --git a/api/apps/v1alpha1/mongodb/types.go b/api/apps/v1alpha1/mongodb/types.go index 45efe8868..98b27e1f3 100644 --- a/api/apps/v1alpha1/mongodb/types.go +++ b/api/apps/v1alpha1/mongodb/types.go @@ -84,6 +84,9 @@ type Backup struct { // Cron schedule for automated backups. // +kubebuilder:default:="0 2 * * *" Schedule string `json:"schedule,omitempty"` + // Opt-in: when true the chart skips the -s3-creds Secret AND leaves spec.backup.storages unset; the cozy-default MongoDB BackupClass driver SSA-injects the S3 storage (bucket/endpoint/prefix/credentials from the platform system bucket) onto the live PerconaServerMongoDB at first BackupJob time. Tenants do not supply s3AccessKey/s3SecretKey/destinationPath/endpointURL; backups scope to / under the system bucket. + // +kubebuilder:default:=false + UseSystemBucket bool `json:"useSystemBucket,omitempty"` } type Bootstrap struct { diff --git a/api/backups/strategy/v1alpha1/mongodb_types.go b/api/backups/strategy/v1alpha1/mongodb_types.go index 2f4772891..0aca1bf75 100644 --- a/api/backups/strategy/v1alpha1/mongodb_types.go +++ b/api/backups/strategy/v1alpha1/mongodb_types.go @@ -100,6 +100,45 @@ type MongoDBTemplate struct { // Left unset the operator picks its default. // +optional CompressionLevel *int `json:"compressionLevel,omitempty"` + + // S3 carries the system-bucket storage coordinates the driver SSA-patches + // onto the source PerconaServerMongoDB's spec.backup.storages[StorageName] + // on the useSystemBucket flow. PBM takes these as static CR fields (not + // secret refs), and the platform bucket name / endpoint are only known at + // BackupJob time, so the cozy-default strategy carries them (endpointUrl + // already scheme'd by the endpoint helper) and the driver injects them. Nil + // means the legacy flow: rely on the storage the app chart rendered + // statically, and patch nothing. + // +optional + S3 *MongoDBStorageS3 `json:"s3,omitempty"` +} + +// MongoDBStorageS3 mirrors the psmdb spec.backup.storages[].s3 block the +// driver injects. String fields support templating (e.g. Prefix uses +// {{ .Application.metadata.namespace }}/{{ .Application.metadata.name }}). +type MongoDBStorageS3 struct { + // Bucket is the S3 bucket name (the COSI-assigned system bucket). + // +optional + Bucket string `json:"bucket,omitempty"` + // EndpointURL is the full S3 endpoint URL including scheme. + // +optional + EndpointURL string `json:"endpointUrl,omitempty"` + // Region is the S3 region. + // +optional + Region string `json:"region,omitempty"` + // Prefix scopes this release's backups under the bucket. + // +optional + Prefix string `json:"prefix,omitempty"` + // CredentialsSecret names the Secret carrying AWS_ACCESS_KEY_ID / + // AWS_SECRET_ACCESS_KEY. Defaults to cozy-backups-creds when empty. + // +optional + CredentialsSecret string `json:"credentialsSecret,omitempty"` + // ForcePathStyle selects path-style S3 addressing. + // +optional + ForcePathStyle *bool `json:"forcePathStyle,omitempty"` + // InsecureSkipTLSVerify disables S3 endpoint certificate verification. + // +optional + InsecureSkipTLSVerify bool `json:"insecureSkipTLSVerify,omitempty"` } // MongoDBStatus reports observed state for the strategy CR. Driver controllers diff --git a/api/backups/strategy/v1alpha1/zz_generated.deepcopy.go b/api/backups/strategy/v1alpha1/zz_generated.deepcopy.go index 6241b2fc2..3ad54f0fe 100644 --- a/api/backups/strategy/v1alpha1/zz_generated.deepcopy.go +++ b/api/backups/strategy/v1alpha1/zz_generated.deepcopy.go @@ -1151,6 +1151,26 @@ func (in *MongoDBStatus) DeepCopy() *MongoDBStatus { return out } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *MongoDBStorageS3) DeepCopyInto(out *MongoDBStorageS3) { + *out = *in + if in.ForcePathStyle != nil { + in, out := &in.ForcePathStyle, &out.ForcePathStyle + *out = new(bool) + **out = **in + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MongoDBStorageS3. +func (in *MongoDBStorageS3) DeepCopy() *MongoDBStorageS3 { + if in == nil { + return nil + } + out := new(MongoDBStorageS3) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *MongoDBTemplate) DeepCopyInto(out *MongoDBTemplate) { *out = *in @@ -1159,6 +1179,11 @@ func (in *MongoDBTemplate) DeepCopyInto(out *MongoDBTemplate) { *out = new(int) **out = **in } + if in.S3 != nil { + in, out := &in.S3, &out.S3 + *out = new(MongoDBStorageS3) + (*in).DeepCopyInto(*out) + } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MongoDBTemplate. diff --git a/internal/backupcontroller/psmdbstrategy_controller.go b/internal/backupcontroller/psmdbstrategy_controller.go index 9735a6785..c60cdcf7e 100644 --- a/internal/backupcontroller/psmdbstrategy_controller.go +++ b/internal/backupcontroller/psmdbstrategy_controller.go @@ -48,6 +48,12 @@ const ( // storage; when it leaves StorageName empty the driver falls back to this. psmdbDefaultStorageName = "s3-storage" + // psmdbFieldManager is the server-side-apply field owner for the driver's + // storage injection on the useSystemBucket flow. A dedicated manager (with + // ForceOwnership) keeps the injected spec.backup.storages entry from being + // reverted by the app's Helm/Flux field manager on re-render. + psmdbFieldManager = "cozystack-psmdb-backup-driver" + // Driver-metadata keys persisted on Cozystack Backup artifacts. The // restore path reads Destination (+ the S3 snapshot) to drive the operator // Restore CR's backupSource, so a restore-to-differently-named instance @@ -220,6 +226,23 @@ func (r *BackupJobReconciler) reconcileMongoDB(ctx context.Context, j *backupsv1 } return ctrl.Result{}, err } + // System-bucket flow: the app chart leaves spec.backup.storages unset (it + // cannot know the platform bucket/endpoint at render time), so SSA-inject + // the storage from the strategy's coordinates before the precondition looks + // for it. Owned by a dedicated field manager with ForceOwnership so a Flux + // re-render of the app never reverts it (mirrors the CNPG driver's + // spec.plugins patch). Gated on the storage being ABSENT: rendered.S3==nil + // (a custom strategy) or a legacy app that already ships its own static + // s3-storage is left untouched, so this never clobbers a manual bucket. + _, hasStorage := cluster.Spec.Backup.Storages[storageName] + if rendered.S3 != nil && !hasStorage { + if err := r.applyMongoDBSystemStorage(ctx, j.Namespace, psmdbName, storageName, rendered.S3); err != nil { + return r.markBackupJobFailed(ctx, j, fmt.Sprintf("failed to inject system-bucket storage onto psmdb.percona.com/PerconaServerMongoDB %s/%s: %v", j.Namespace, psmdbName, err)) + } + if err := r.Get(ctx, types.NamespacedName{Namespace: j.Namespace, Name: psmdbName}, cluster); err != nil { + return ctrl.Result{}, err + } + } if msg := psmdbBackupPrecondition(cluster, storageName); msg != "" { if psmdbBackupDeadlineExceeded(j.Status.StartedAt) { return r.markBackupJobFailed(ctx, j, fmt.Sprintf( @@ -373,6 +396,45 @@ func psmdbStorageS3CredentialsSecret(raw runtime.RawExtension) string { return st.S3.CredentialsSecret } +// applyMongoDBSystemStorage SSA-injects the system-bucket S3 storage onto the +// live PerconaServerMongoDB's spec.backup.storages[storageName]. On the +// useSystemBucket flow the app chart omits the storage (it cannot know the +// platform bucket/endpoint at render time), so the driver owns this subtree +// via a dedicated field manager + ForceOwnership - the app's Helm/Flux manager +// never sets it, so re-renders leave the injected storage intact (mirrors the +// CNPG driver's spec.plugins patch). CredentialsSecret defaults to +// cozy-backups-creds, which the BackupJob reconciler projects into the +// namespace before dispatch. +func (r *BackupJobReconciler) applyMongoDBSystemStorage(ctx context.Context, namespace, psmdbName, storageName string, s3 *strategyv1alpha1.MongoDBStorageS3) error { + cred := s3.CredentialsSecret + if cred == "" { + cred = "cozy-backups-creds" + } + s3Cfg := map[string]interface{}{ + "bucket": s3.Bucket, + "endpointUrl": s3.EndpointURL, + "region": s3.Region, + "prefix": s3.Prefix, + "credentialsSecret": cred, + "insecureSkipTLSVerify": s3.InsecureSkipTLSVerify, + } + if s3.ForcePathStyle != nil { + s3Cfg["forcePathStyle"] = *s3.ForcePathStyle + } + entry, err := json.Marshal(map[string]interface{}{"type": "s3", "s3": s3Cfg}) + if err != nil { + return err + } + patch := &psmdbtypes.PerconaServerMongoDB{ + TypeMeta: metav1.TypeMeta{APIVersion: psmdbtypes.GroupVersion.String(), Kind: "PerconaServerMongoDB"}, + ObjectMeta: metav1.ObjectMeta{Namespace: namespace, Name: psmdbName}, + } + patch.Spec.Backup.Storages = map[string]runtime.RawExtension{ + storageName: {Raw: entry}, + } + return r.Patch(ctx, patch, client.Apply, client.FieldOwner(psmdbFieldManager), client.ForceOwnership) +} + // psmdbBackupDeadlineExceeded reports whether enough wall-clock time elapsed // since the BackupJob started that we should give up on a stuck operator // backup. Returns false when StartedAt is nil so the first reconcile does not @@ -908,6 +970,25 @@ func marshalMongoDBBackupSnapshot(mdbBackup *psmdbtypes.PerconaServerMongoDBBack S3: mdbBackup.Status.S3.DeepCopy(), Parameters: parameters, } + // On the useSystemBucket flow the driver injected the storage, so fall back + // to those coordinates when the operator's status echo is empty - the + // restore path rebuilds backupSource from this snapshot and needs the + // endpoint + credentialsSecret (cozy-backups-creds) to be present. + if snap.S3 == nil && rendered.S3 != nil { + cred := rendered.S3.CredentialsSecret + if cred == "" { + cred = "cozy-backups-creds" + } + snap.S3 = &psmdbtypes.BackupStorageS3{ + Bucket: rendered.S3.Bucket, + CredentialsSecret: cred, + EndpointURL: rendered.S3.EndpointURL, + Prefix: rendered.S3.Prefix, + Region: rendered.S3.Region, + ForcePathStyle: rendered.S3.ForcePathStyle, + InsecureSkipTLSVerify: rendered.S3.InsecureSkipTLSVerify, + } + } raw, err := json.Marshal(snap) if err != nil { return nil, err diff --git a/internal/backupcontroller/psmdbstrategy_controller_test.go b/internal/backupcontroller/psmdbstrategy_controller_test.go index 32098ceda..897868d03 100644 --- a/internal/backupcontroller/psmdbstrategy_controller_test.go +++ b/internal/backupcontroller/psmdbstrategy_controller_test.go @@ -482,6 +482,47 @@ func TestMarshalUnmarshalMongoDBBackupSnapshot_RoundTrip(t *testing.T) { } } +// TestMarshalMongoDBBackupSnapshot_SystemBucketFallback guards the +// useSystemBucket restore path: when the operator Backup status carries no S3 +// echo, the snapshot must fall back to the strategy's injected coordinates +// (rendered.S3) so restore can rebuild backupSource - with credentialsSecret +// defaulting to cozy-backups-creds. +func TestMarshalMongoDBBackupSnapshot_SystemBucketFallback(t *testing.T) { + mdbBackup := &psmdbtypes.PerconaServerMongoDBBackup{ + Status: psmdbtypes.PerconaServerMongoDBBackupStatus{ + Destination: "s3://cozybkt/tenant-root/mongodb-src/2026-08-26T00:00:00Z", + // S3 intentionally nil: operator did not echo storage config. + }, + } + rendered := &strategyv1alpha1.MongoDBTemplate{ + Type: "logical", + S3: &strategyv1alpha1.MongoDBStorageS3{ + Bucket: "cozybkt", + EndpointURL: "https://s3.example.org", + Prefix: "tenant-root/mongodb-src", + Region: "us-east-1", + // CredentialsSecret intentionally empty -> defaults below. + }, + } + raw, err := marshalMongoDBBackupSnapshot(mdbBackup, rendered, "s3-storage", nil) + if err != nil { + t.Fatalf("marshal: %v", err) + } + snap, err := unmarshalMongoDBBackupSnapshot(raw) + if err != nil { + t.Fatalf("unmarshal: %v", err) + } + if snap.S3 == nil { + t.Fatal("snapshot S3 must be populated from rendered.S3 when the operator echo is empty") + } + if snap.S3.CredentialsSecret != "cozy-backups-creds" { + t.Errorf("credentialsSecret must default to cozy-backups-creds; got %q", snap.S3.CredentialsSecret) + } + if snap.S3.EndpointURL != "https://s3.example.org" || snap.S3.Bucket != "cozybkt" { + t.Errorf("snapshot S3 coords mismatch: %#v", snap.S3) + } +} + func TestUnmarshalMongoDBBackupSnapshot_Empty(t *testing.T) { snap, err := unmarshalMongoDBBackupSnapshot(nil) if err != nil || snap != nil { diff --git a/packages/apps/mongodb/README.md b/packages/apps/mongodb/README.md index 6f4206d47..81b96dc9a 100644 --- a/packages/apps/mongodb/README.md +++ b/packages/apps/mongodb/README.md @@ -247,17 +247,18 @@ Releases with `external: false`, and sharded releases in any configuration, are ### Backup parameters -| Name | Description | Type | Value | -| ------------------------------ | ----------------------------------------------------------------------------------- | -------- | ----------------------------------- | -| `backup` | Backup configuration. | `object` | `{}` | -| `backup.enabled` | Enable regular backups. | `bool` | `false` | -| `backup.schedule` | Cron schedule for automated backups. | `string` | `0 2 * * *` | -| `backup.retentionPolicy` | Retention policy (e.g. "30d"). | `string` | `30d` | -| `backup.destinationPath` | Destination path for backups (e.g. s3://bucket/path/). | `string` | `s3://bucket/path/to/folder/` | -| `backup.endpointURL` | S3 endpoint URL for uploads. | `string` | `http://minio-gateway-service:9000` | -| `backup.insecureSkipTLSVerify` | Skip TLS verification for the S3 endpoint (self-signed, e.g. in-cluster seaweedfs). | `bool` | `false` | -| `backup.s3AccessKey` | Access key for S3 authentication. | `string` | `""` | -| `backup.s3SecretKey` | Secret key for S3 authentication. | `string` | `""` | +| Name | Description | Type | Value | +| ------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------- | ----------------------------------- | +| `backup` | Backup configuration. | `object` | `{}` | +| `backup.enabled` | Enable regular backups. | `bool` | `false` | +| `backup.useSystemBucket` | Opt-in: when true the chart skips the -s3-creds Secret AND leaves spec.backup.storages unset; the cozy-default MongoDB BackupClass driver SSA-injects the S3 storage (bucket/endpoint/prefix/credentials from the platform system bucket) onto the live PerconaServerMongoDB at first BackupJob time. Tenants do not supply s3AccessKey/s3SecretKey/destinationPath/endpointURL; backups scope to / under the system bucket. | `bool` | `false` | +| `backup.schedule` | Cron schedule for automated backups. | `string` | `0 2 * * *` | +| `backup.retentionPolicy` | Retention policy (e.g. "30d"). | `string` | `30d` | +| `backup.destinationPath` | Destination path for backups (e.g. s3://bucket/path/). | `string` | `s3://bucket/path/to/folder/` | +| `backup.endpointURL` | S3 endpoint URL for uploads. | `string` | `http://minio-gateway-service:9000` | +| `backup.insecureSkipTLSVerify` | Skip TLS verification for the S3 endpoint (self-signed, e.g. in-cluster seaweedfs). | `bool` | `false` | +| `backup.s3AccessKey` | Access key for S3 authentication. | `string` | `""` | +| `backup.s3SecretKey` | Secret key for S3 authentication. | `string` | `""` | ### Bootstrap (recovery) parameters diff --git a/packages/apps/mongodb/templates/backup-secret.yaml b/packages/apps/mongodb/templates/backup-secret.yaml index f7b2ba01b..e3bb3950c 100644 --- a/packages/apps/mongodb/templates/backup-secret.yaml +++ b/packages/apps/mongodb/templates/backup-secret.yaml @@ -1,4 +1,10 @@ -{{- if or .Values.backup.enabled .Values.bootstrap.enabled }} +{{- /* + On the useSystemBucket flow the driver injects a storage that references the + platform-projected cozy-backups-creds, so this chart-emitted Secret is skipped + and tenants do not supply inline keys. Only the legacy flow (own S3, inline + keys) materialises it. +*/}} +{{- if and (or .Values.backup.enabled .Values.bootstrap.enabled) (not .Values.backup.useSystemBucket) }} --- apiVersion: v1 kind: Secret @@ -6,6 +12,6 @@ metadata: name: {{ .Release.Name }}-s3-creds type: Opaque stringData: - AWS_ACCESS_KEY_ID: {{ required "backup.s3AccessKey is required when backup or bootstrap is enabled" .Values.backup.s3AccessKey | quote }} - AWS_SECRET_ACCESS_KEY: {{ required "backup.s3SecretKey is required when backup or bootstrap is enabled" .Values.backup.s3SecretKey | quote }} + AWS_ACCESS_KEY_ID: {{ required "backup.s3AccessKey is required when backup or bootstrap is enabled without useSystemBucket" .Values.backup.s3AccessKey | quote }} + AWS_SECRET_ACCESS_KEY: {{ required "backup.s3SecretKey is required when backup or bootstrap is enabled without useSystemBucket" .Values.backup.s3SecretKey | quote }} {{- end }} diff --git a/packages/apps/mongodb/templates/mongodb.yaml b/packages/apps/mongodb/templates/mongodb.yaml index 7aa2623fb..66e497a41 100644 --- a/packages/apps/mongodb/templates/mongodb.yaml +++ b/packages/apps/mongodb/templates/mongodb.yaml @@ -220,7 +220,17 @@ spec: backup: enabled: {{ .Values.backup.enabled | default false }} image: percona/percona-backup-mongodb:2.11.0 - {{- if .Values.backup.enabled }} + {{- /* + useSystemBucket: keep enabled (so the pbm agents run) but omit the static + storage/tasks/pitr. The chart cannot know the platform bucket/endpoint at + render time, so the cozy-default BackupClass driver SSA-injects + spec.backup.storages["s3-storage"] under its own field manager at + BackupJob time; Helm never owns that subtree, so a Flux re-render leaves + the injected storage intact (same split the postgres useSystemBucket flow + uses for spec.plugins). Scheduling is driven by a BackupClass Plan, not + the chart's tasks; PITR on the system bucket is not wired here yet. + */}} + {{- if and .Values.backup.enabled (not .Values.backup.useSystemBucket) }} storages: s3-storage: type: s3 diff --git a/packages/apps/mongodb/templates/restore.yaml b/packages/apps/mongodb/templates/restore.yaml index 57dffe2c6..a12d0e0c1 100644 --- a/packages/apps/mongodb/templates/restore.yaml +++ b/packages/apps/mongodb/templates/restore.yaml @@ -1,4 +1,7 @@ {{- if .Values.bootstrap.enabled }} +{{- if .Values.backup.useSystemBucket }} +{{- fail "mongodb: bootstrap.enabled=true is incompatible with backup.useSystemBucket=true. Restore from the system bucket with a backups.cozystack.io/RestoreJob against the cozy-default BackupClass; see docs/operations/backup-classes.md." }} +{{- end }} {{- if not .Values.bootstrap.backupName }} {{- fail "bootstrap.backupName is required when bootstrap.enabled is true" }} {{- end }} diff --git a/packages/apps/mongodb/tests/backup-secret_test.yaml b/packages/apps/mongodb/tests/backup-secret_test.yaml index f3eca410e..803789720 100644 --- a/packages/apps/mongodb/tests/backup-secret_test.yaml +++ b/packages/apps/mongodb/tests/backup-secret_test.yaml @@ -18,6 +18,21 @@ tests: - hasDocuments: count: 0 + # useSystemBucket: the driver injects a storage referencing the projected + # cozy-backups-creds, so the chart skips -s3-creds and needs no + # inline keys (no required-fail). + - it: skips the s3-creds secret on useSystemBucket + release: + name: test-mongodb + namespace: tenant-test + set: + backup: + enabled: true + useSystemBucket: true + asserts: + - hasDocuments: + count: 0 + # Rendered when backup enabled - it: renders when backup enabled release: @@ -95,7 +110,7 @@ tests: s3SecretKey: "secretkey" asserts: - failedTemplate: - errorMessage: "backup.s3AccessKey is required when backup or bootstrap is enabled" + errorMessage: "backup.s3AccessKey is required when backup or bootstrap is enabled without useSystemBucket" # Fails without s3SecretKey - it: fails when s3SecretKey missing @@ -109,4 +124,4 @@ tests: s3SecretKey: "" asserts: - failedTemplate: - errorMessage: "backup.s3SecretKey is required when backup or bootstrap is enabled" + errorMessage: "backup.s3SecretKey is required when backup or bootstrap is enabled without useSystemBucket" diff --git a/packages/apps/mongodb/tests/mongodb_test.yaml b/packages/apps/mongodb/tests/mongodb_test.yaml index 04eded23b..192551fae 100644 --- a/packages/apps/mongodb/tests/mongodb_test.yaml +++ b/packages/apps/mongodb/tests/mongodb_test.yaml @@ -38,6 +38,58 @@ tests: value: my-mongodb documentIndex: 0 + ######################### + # Backup storage gating # + ######################### + + # Legacy flow: the chart renders the static s3-storage from backup.* values. + - it: renders static s3-storage on the legacy backup flow + release: + name: test-mongodb + namespace: tenant-test + set: + _cluster: + cluster-domain: cozy.local + backup: + enabled: true + useSystemBucket: false + destinationPath: s3://my-bucket/mongodb-src/ + endpointURL: https://s3.example.org + asserts: + - equal: + path: spec.backup.enabled + value: true + documentIndex: 0 + - equal: + path: spec.backup.storages.s3-storage.s3.credentialsSecret + value: test-mongodb-s3-creds + documentIndex: 0 + + # useSystemBucket: enabled stays true (pbm agents run) but the chart omits + # spec.backup.storages entirely - the cozy-default BackupClass driver + # SSA-injects it at BackupJob time, so Helm must not own that subtree. + - it: omits spec.backup.storages on useSystemBucket + release: + name: test-mongodb + namespace: tenant-test + set: + _cluster: + cluster-domain: cozy.local + backup: + enabled: true + useSystemBucket: true + asserts: + - equal: + path: spec.backup.enabled + value: true + documentIndex: 0 + - notExists: + path: spec.backup.storages + documentIndex: 0 + - notExists: + path: spec.backup.tasks + documentIndex: 0 + ################## # Finalizers # ################## diff --git a/packages/apps/mongodb/values.schema.json b/packages/apps/mongodb/values.schema.json index 8a6afa343..1744abfd5 100644 --- a/packages/apps/mongodb/values.schema.json +++ b/packages/apps/mongodb/values.schema.json @@ -311,6 +311,11 @@ "description": "Cron schedule for automated backups.", "type": "string", "default": "0 2 * * *" + }, + "useSystemBucket": { + "description": "Opt-in: when true the chart skips the \u003crelease\u003e-s3-creds Secret AND leaves spec.backup.storages unset; the cozy-default MongoDB BackupClass driver SSA-injects the S3 storage (bucket/endpoint/prefix/credentials from the platform system bucket) onto the live PerconaServerMongoDB at first BackupJob time. Tenants do not supply s3AccessKey/s3SecretKey/destinationPath/endpointURL; backups scope to \u003cnamespace\u003e/\u003crelease\u003e under the system bucket.", + "type": "boolean", + "default": false } } }, diff --git a/packages/apps/mongodb/values.yaml b/packages/apps/mongodb/values.yaml index 1b6193a1c..3ccd36737 100644 --- a/packages/apps/mongodb/values.yaml +++ b/packages/apps/mongodb/values.yaml @@ -155,6 +155,7 @@ databases: {} ## @typedef {struct} Backup - Backup configuration. ## @field {bool} enabled - Enable regular backups. +## @field {bool} [useSystemBucket] - Opt-in: when true the chart skips the -s3-creds Secret AND leaves spec.backup.storages unset; the cozy-default MongoDB BackupClass driver SSA-injects the S3 storage (bucket/endpoint/prefix/credentials from the platform system bucket) onto the live PerconaServerMongoDB at first BackupJob time. Tenants do not supply s3AccessKey/s3SecretKey/destinationPath/endpointURL; backups scope to / under the system bucket. ## @field {string} [schedule] - Cron schedule for automated backups. ## @field {string} [retentionPolicy] - Retention policy (e.g. "30d"). ## @field {string} [destinationPath] - Destination path for backups (e.g. s3://bucket/path/). @@ -166,6 +167,7 @@ databases: {} ## @param {Backup} backup - Backup configuration. backup: enabled: false + useSystemBucket: false schedule: "0 2 * * *" retentionPolicy: 30d destinationPath: "s3://bucket/path/to/folder/" diff --git a/packages/system/backupstrategy-controller/definitions/strategy.backups.cozystack.io_mongodbs.yaml b/packages/system/backupstrategy-controller/definitions/strategy.backups.cozystack.io_mongodbs.yaml index 7feaaa5f3..ca5ed92b6 100644 --- a/packages/system/backupstrategy-controller/definitions/strategy.backups.cozystack.io_mongodbs.yaml +++ b/packages/system/backupstrategy-controller/definitions/strategy.backups.cozystack.io_mongodbs.yaml @@ -76,6 +76,45 @@ spec: "s2", "snappy", "lz4", "pgzip", "none"). Defaults to the operator-side default when empty. Templating is supported. type: string + s3: + description: |- + S3 carries the system-bucket storage coordinates the driver SSA-patches + onto the source PerconaServerMongoDB's spec.backup.storages[StorageName] + on the useSystemBucket flow. PBM takes these as static CR fields (not + secret refs), and the platform bucket name / endpoint are only known at + BackupJob time, so the cozy-default strategy carries them (endpointUrl + already scheme'd by the endpoint helper) and the driver injects them. Nil + means the legacy flow: rely on the storage the app chart rendered + statically, and patch nothing. + properties: + bucket: + description: Bucket is the S3 bucket name (the COSI-assigned + system bucket). + type: string + credentialsSecret: + description: |- + CredentialsSecret names the Secret carrying AWS_ACCESS_KEY_ID / + AWS_SECRET_ACCESS_KEY. Defaults to cozy-backups-creds when empty. + type: string + endpointUrl: + description: EndpointURL is the full S3 endpoint URL including + scheme. + type: string + forcePathStyle: + description: ForcePathStyle selects path-style S3 addressing. + type: boolean + insecureSkipTLSVerify: + description: InsecureSkipTLSVerify disables S3 endpoint certificate + verification. + type: boolean + prefix: + description: Prefix scopes this release's backups under the + bucket. + type: string + region: + description: Region is the S3 region. + type: string + type: object storageName: description: |- StorageName names a storage entry declared in the source cluster's diff --git a/packages/system/backupstrategy-controller/templates/rbac.yaml b/packages/system/backupstrategy-controller/templates/rbac.yaml index bdd0f89ea..a3973e89c 100644 --- a/packages/system/backupstrategy-controller/templates/rbac.yaml +++ b/packages/system/backupstrategy-controller/templates/rbac.yaml @@ -163,7 +163,9 @@ rules: # cleanup) by tenants / explicit teardown flows, never by this controller. - apiGroups: ["psmdb.percona.com"] resources: ["perconaservermongodbs"] - verbs: ["get", "list", "watch"] + # patch/update: the useSystemBucket flow SSA-injects spec.backup.storages + # onto the live PerconaServerMongoDB at BackupJob time. + verbs: ["get", "list", "watch", "patch", "update"] - apiGroups: ["psmdb.percona.com"] resources: ["perconaservermongodbbackups", "perconaservermongodbrestores"] verbs: ["get", "list", "watch", "create"] diff --git a/packages/system/backupstrategy-controller/templates/strategy-mongodb-default.yaml b/packages/system/backupstrategy-controller/templates/strategy-mongodb-default.yaml index 0c74a822c..f9b77a35b 100644 --- a/packages/system/backupstrategy-controller/templates/strategy-mongodb-default.yaml +++ b/packages/system/backupstrategy-controller/templates/strategy-mongodb-default.yaml @@ -1,22 +1,27 @@ {{/* - cozy-default MongoDB strategy. Unlike the MariaDB / CNPG / Altinity - defaults, this Strategy carries NO bucket coordinates or credentials: the - Percona psmdb operator resolves the on-demand backup's storageName against - the source PerconaServerMongoDB CR's spec.backup.storages, so the S3 target - lives on the MongoDB application (declared by the chart as "s3-storage" when - backup.enabled=true), not here. + cozy-default MongoDB strategy. The Percona psmdb operator resolves the + on-demand backup's storageName against the source PerconaServerMongoDB CR's + spec.backup.storages. On the legacy flow that storage lives on the MongoDB + application (declared by the chart as "s3-storage" when backup.enabled=true, + with the tenant's own bucket/creds). On the useSystemBucket flow the app + chart cannot know the platform bucket/endpoint at render time, so this + Strategy carries the coordinates (the s3 block below) and the driver + SSA-injects them into the app's spec.backup.storages["s3-storage"] on every + BackupJob. Injection is keyed off the app's backup.useSystemBucket flag, not + off the live cluster's storage set: a legacy app leaves the flag false and is + never touched, so its own static "s3-storage" stays intact. - It is gated all the same, and NOT because it needs a bucket value. This chart - ships its own strategy.backups.cozystack.io CRDs as ordinary templates - (templates/crds.yaml globs definitions/*.yaml), and Helm resolves every - document in a release manifest through the cluster's RESTMapper in Build() - BEFORE it applies any of them. An ungated Strategy CR therefore has no - mapping while its CRD is still absent, Build() fails with "no matches for - kind", and the release applies ZERO objects — including the CRDs that would - have made the mapping resolve. Nothing recovers from that: every retry - renders the same manifest, so the failure is permanent rather than a race, - and Helm's kind sorter cannot help because it orders the apply, not the - Build. + It is gated on $bucketName — which the s3 block below now renders — and on + $crdEstablished for install ordering. This chart ships its own + strategy.backups.cozystack.io CRDs as ordinary templates (templates/crds.yaml + globs definitions/*.yaml), and Helm resolves every document in a release + manifest through the cluster's RESTMapper in Build() BEFORE it applies any of + them. An ungated Strategy CR therefore has no mapping while its CRD is still + absent, Build() fails with "no matches for kind", and the release applies + ZERO objects — including the CRDs that would have made the mapping resolve. + Nothing recovers from that: every retry renders the same manifest, so the + failure is permanent rather than a race, and Helm's kind sorter cannot help + because it orders the apply, not the Build. So this Strategy must be absent from any render whose cluster cannot yet map it, and there are TWO such renders, not one. @@ -24,8 +29,7 @@ A fresh install is the first. $bucketName is empty until the COSI BucketClaim status is reconciled (see templates/_helpers.tpl), which is exactly the window where the CRDs are being applied; by the time DefaultObjectsGate forces a - second revision the CRDs exist and the mapping resolves. The seven sibling - strategies get that for free by needing the bucket name. + second revision the CRDs exist and the mapping resolves. Adding this kind to an ALREADY-INSTALLED chart is the second, and the bucket gate is no help there: the bucket name resolved releases ago, so the first @@ -38,9 +42,10 @@ afterwards. Precondition (surfaced by the driver as a clear Ready=False, not a silent - hang): the MongoDB application must be deployed with backup.enabled=true so - the percona-backup-mongodb agents run and the "s3-storage" entry exists. See - docs/operations/backup-classes.md. + hang): the MongoDB application must have backup.enabled=true so the + percona-backup-mongodb agents run. On the legacy flow the "s3-storage" entry + must also already exist on the app; on the useSystemBucket flow the driver + injects it at BackupJob time. See docs/operations/backup-classes.md. */}} {{- $bucketName := include "backupstrategy-controller.bucketName" . -}} {{- $crdEstablished := include "backupstrategy-controller.crdEstablished" (dict "root" . "crd" "mongodbs.strategy.backups.cozystack.io") -}} @@ -54,4 +59,18 @@ spec: storageName: s3-storage type: logical compressionType: gzip + # System-bucket coordinates the driver SSA-injects onto the source + # PerconaServerMongoDB's spec.backup.storages[s3-storage] when the app ran + # with backup.useSystemBucket=true (the chart then omits the static + # storage). A legacy app leaves the flag false and is never injected, so it + # keeps its own static s3-storage. endpointUrl carries the scheme from the + # endpoint helper so PBM's aws-sdk client gets a valid URL; credentials come + # from the projected cozy-backups-creds. + s3: + bucket: {{ $bucketName | quote }} + endpointUrl: {{ include "backupstrategy-controller.endpoint" . | quote }} + prefix: {{ printf "{{ .Application.metadata.namespace }}/{{ .Application.metadata.name }}" | quote }} + region: {{ .Values.backupStorage.region | quote }} + credentialsSecret: cozy-backups-creds + forcePathStyle: {{ .Values.backupStorage.forcePathStyle }} {{- end -}} diff --git a/packages/system/mongodb-rd/cozyrds/mongodb.yaml b/packages/system/mongodb-rd/cozyrds/mongodb.yaml index ae43704cf..1cad05929 100644 --- a/packages/system/mongodb-rd/cozyrds/mongodb.yaml +++ b/packages/system/mongodb-rd/cozyrds/mongodb.yaml @@ -8,7 +8,7 @@ spec: singular: mongodb plural: mongodbs openAPISchema: |- - {"title":"Chart Values","type":"object","properties":{"replicas":{"description":"Number of MongoDB replicas in replica set.","type":"integer","default":3},"resources":{"description":"Explicit CPU and memory configuration for each MongoDB replica. When omitted, the preset defined in `resourcesPreset` is applied.","type":"object","default":{},"properties":{"cpu":{"description":"CPU available to each replica.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"memory":{"description":"Memory (RAM) available to each replica.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true}}},"resourcesPreset":{"description":"Default sizing preset used when `resources` is omitted.","type":"string","default":"t1.small","enum":["t1.nano","t1.micro","t1.small","t1.medium","t1.large","t1.xlarge","t1.2xlarge","t1.4xlarge","c1.nano","c1.micro","c1.small","c1.medium","c1.large","c1.xlarge","c1.2xlarge","c1.4xlarge","s1.nano","s1.micro","s1.small","s1.medium","s1.large","s1.xlarge","s1.2xlarge","s1.4xlarge","u1.nano","u1.micro","u1.small","u1.medium","u1.large","u1.xlarge","u1.2xlarge","u1.4xlarge","m1.nano","m1.micro","m1.small","m1.medium","m1.large","m1.xlarge","m1.2xlarge","m1.4xlarge","nano","micro","small","medium","large","xlarge","2xlarge"]},"size":{"description":"Persistent Volume Claim size available for application data.","default":"10Gi","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"storageClass":{"description":"StorageClass used to store the data.","type":"string","default":"","x-kubernetes-validations":[{"rule":"self == oldSelf","message":"storageClass is immutable"}],"x-cozystack-options":{"source":"storageclass"}},"external":{"description":"Enable external access from outside the cluster.","type":"boolean","default":false},"version":{"description":"MongoDB major version to deploy.","type":"string","default":"v8","enum":["v8","v7","v6"]},"sharding":{"description":"Enable sharded cluster mode. When disabled, deploys a replica set.","type":"boolean","default":false},"shardingConfig":{"description":"Configuration for sharded cluster mode.","type":"object","default":{},"required":["configServerSize","configServers","mongos"],"properties":{"configServerSize":{"description":"PVC size for config servers.","default":"3Gi","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"configServers":{"description":"Number of config server replicas.","type":"integer","default":3},"mongos":{"description":"Number of mongos router replicas.","type":"integer","default":2},"shards":{"description":"List of shard configurations.","type":"array","default":[{"name":"rs0","replicas":3,"size":"10Gi"}],"items":{"type":"object","required":["name","replicas","size"],"properties":{"name":{"description":"Shard name.","type":"string"},"replicas":{"description":"Number of replicas in this shard.","type":"integer"},"size":{"description":"PVC size for this shard.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true}}}}}},"users":{"description":"Users configuration map.","type":"object","default":{},"additionalProperties":{"type":"object","properties":{"password":{"description":"Password for the user (auto-generated if omitted).","type":"string"}}}},"databases":{"description":"Databases configuration map.","type":"object","default":{},"additionalProperties":{"type":"object","properties":{"roles":{"description":"Roles assigned to users.","type":"object","properties":{"admin":{"description":"List of users with admin privileges (readWrite + dbAdmin).","type":"array","items":{"type":"string"}},"readonly":{"description":"List of users with read-only privileges.","type":"array","items":{"type":"string"}}}}}}},"backup":{"description":"Backup configuration.","type":"object","default":{},"required":["enabled"],"properties":{"destinationPath":{"description":"Destination path for backups (e.g. s3://bucket/path/).","type":"string","default":"s3://bucket/path/to/folder/"},"enabled":{"description":"Enable regular backups.","type":"boolean","default":false},"endpointURL":{"description":"S3 endpoint URL for uploads.","type":"string","default":"http://minio-gateway-service:9000"},"insecureSkipTLSVerify":{"description":"Skip TLS verification for the S3 endpoint (self-signed, e.g. in-cluster seaweedfs).","type":"boolean","default":false},"retentionPolicy":{"description":"Retention policy (e.g. \"30d\").","type":"string","default":"30d"},"s3AccessKey":{"description":"Access key for S3 authentication.","type":"string","default":""},"s3SecretKey":{"description":"Secret key for S3 authentication.","type":"string","default":""},"schedule":{"description":"Cron schedule for automated backups.","type":"string","default":"0 2 * * *"}}},"bootstrap":{"description":"Bootstrap configuration.","type":"object","default":{},"required":["backupName","enabled"],"properties":{"backupName":{"description":"Name of backup to restore from.","type":"string","default":""},"enabled":{"description":"Whether to restore from a backup.","type":"boolean","default":false},"recoveryTime":{"description":"Timestamp for point-in-time recovery; empty means latest.","type":"string","default":""}}}}} + {"title":"Chart Values","type":"object","properties":{"replicas":{"description":"Number of MongoDB replicas in replica set.","type":"integer","default":3},"resources":{"description":"Explicit CPU and memory configuration for each MongoDB replica. When omitted, the preset defined in `resourcesPreset` is applied.","type":"object","default":{},"properties":{"cpu":{"description":"CPU available to each replica.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"memory":{"description":"Memory (RAM) available to each replica.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true}}},"resourcesPreset":{"description":"Default sizing preset used when `resources` is omitted.","type":"string","default":"t1.small","enum":["t1.nano","t1.micro","t1.small","t1.medium","t1.large","t1.xlarge","t1.2xlarge","t1.4xlarge","c1.nano","c1.micro","c1.small","c1.medium","c1.large","c1.xlarge","c1.2xlarge","c1.4xlarge","s1.nano","s1.micro","s1.small","s1.medium","s1.large","s1.xlarge","s1.2xlarge","s1.4xlarge","u1.nano","u1.micro","u1.small","u1.medium","u1.large","u1.xlarge","u1.2xlarge","u1.4xlarge","m1.nano","m1.micro","m1.small","m1.medium","m1.large","m1.xlarge","m1.2xlarge","m1.4xlarge","nano","micro","small","medium","large","xlarge","2xlarge"]},"size":{"description":"Persistent Volume Claim size available for application data.","default":"10Gi","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"storageClass":{"description":"StorageClass used to store the data.","type":"string","default":"","x-kubernetes-validations":[{"rule":"self == oldSelf","message":"storageClass is immutable"}],"x-cozystack-options":{"source":"storageclass"}},"external":{"description":"Enable external access from outside the cluster.","type":"boolean","default":false},"version":{"description":"MongoDB major version to deploy.","type":"string","default":"v8","enum":["v8","v7","v6"]},"sharding":{"description":"Enable sharded cluster mode. When disabled, deploys a replica set.","type":"boolean","default":false},"shardingConfig":{"description":"Configuration for sharded cluster mode.","type":"object","default":{},"required":["configServerSize","configServers","mongos"],"properties":{"configServerSize":{"description":"PVC size for config servers.","default":"3Gi","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"configServers":{"description":"Number of config server replicas.","type":"integer","default":3},"mongos":{"description":"Number of mongos router replicas.","type":"integer","default":2},"shards":{"description":"List of shard configurations.","type":"array","default":[{"name":"rs0","replicas":3,"size":"10Gi"}],"items":{"type":"object","required":["name","replicas","size"],"properties":{"name":{"description":"Shard name.","type":"string"},"replicas":{"description":"Number of replicas in this shard.","type":"integer"},"size":{"description":"PVC size for this shard.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true}}}}}},"users":{"description":"Users configuration map.","type":"object","default":{},"additionalProperties":{"type":"object","properties":{"password":{"description":"Password for the user (auto-generated if omitted).","type":"string"}}}},"databases":{"description":"Databases configuration map.","type":"object","default":{},"additionalProperties":{"type":"object","properties":{"roles":{"description":"Roles assigned to users.","type":"object","properties":{"admin":{"description":"List of users with admin privileges (readWrite + dbAdmin).","type":"array","items":{"type":"string"}},"readonly":{"description":"List of users with read-only privileges.","type":"array","items":{"type":"string"}}}}}}},"backup":{"description":"Backup configuration.","type":"object","default":{},"required":["enabled"],"properties":{"destinationPath":{"description":"Destination path for backups (e.g. s3://bucket/path/).","type":"string","default":"s3://bucket/path/to/folder/"},"enabled":{"description":"Enable regular backups.","type":"boolean","default":false},"endpointURL":{"description":"S3 endpoint URL for uploads.","type":"string","default":"http://minio-gateway-service:9000"},"insecureSkipTLSVerify":{"description":"Skip TLS verification for the S3 endpoint (self-signed, e.g. in-cluster seaweedfs).","type":"boolean","default":false},"retentionPolicy":{"description":"Retention policy (e.g. \"30d\").","type":"string","default":"30d"},"s3AccessKey":{"description":"Access key for S3 authentication.","type":"string","default":""},"s3SecretKey":{"description":"Secret key for S3 authentication.","type":"string","default":""},"schedule":{"description":"Cron schedule for automated backups.","type":"string","default":"0 2 * * *"},"useSystemBucket":{"description":"Opt-in: when true the chart skips the -s3-creds Secret AND leaves spec.backup.storages unset; the cozy-default MongoDB BackupClass driver SSA-injects the S3 storage (bucket/endpoint/prefix/credentials from the platform system bucket) onto the live PerconaServerMongoDB at first BackupJob time. Tenants do not supply s3AccessKey/s3SecretKey/destinationPath/endpointURL; backups scope to / under the system bucket.","type":"boolean","default":false}}},"bootstrap":{"description":"Bootstrap configuration.","type":"object","default":{},"required":["backupName","enabled"],"properties":{"backupName":{"description":"Name of backup to restore from.","type":"string","default":""},"enabled":{"description":"Whether to restore from a backup.","type":"boolean","default":false},"recoveryTime":{"description":"Timestamp for point-in-time recovery; empty means latest.","type":"string","default":""}}}}} release: prefix: mongodb- labels: @@ -25,7 +25,7 @@ spec: tags: - database icon: PHN2ZyB3aWR0aD0iMTQ0IiBoZWlnaHQ9IjE0NCIgdmlld0JveD0iMCAwIDE0NCAxNDQiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxyZWN0IHdpZHRoPSIxNDQiIGhlaWdodD0iMTQ0IiByeD0iMjQiIGZpbGw9InVybCgjcGFpbnQwX3JhZGlhbF8zMzBfNDg5ODEpIi8+CjxwYXRoIGQ9Ik05NS4xMzg3IDYxLjQwMjhDODkuNjI3NiAzNy4yMjc1IDc2LjYwMzIgMjkuMjc4NSA3NS4yMDA3IDI2LjI0MTZDNzMuNjY3IDI0LjA5OSA3Mi4xMTI5IDIwLjI4NzkgNzIuMTEyOSAyMC4yODc5QzcyLjA4NzMgMjAuMjIzNiA3Mi4wNDY0IDIwLjExMDEgNzEuOTk4NyAyMEM3MS44NDAyIDIyLjE0MjYgNzEuNzU4NCAyMi45NjkyIDY5LjcyMDMgMjUuMTMwNUM2Ni41NjQzIDI3LjU4MzEgNTAuMzcyIDQxLjA4NzYgNDkuMDU0NyA2OC41NTRDNDcuODI2MSA5NC4xNzA4IDY3LjY3MiAxMDkuNDM1IDcwLjM1NiAxMTEuMzgxTDcwLjY2MSAxMTEuNTk2VjExMS41NzhDNzAuNjc4IDExMS43MDcgNzEuNTEzIDExNy42NzUgNzIuMDk5MyAxMjRINzQuMjAyMUM3NC42OTU1IDExOS41MjkgNzUuNDM1MSAxMTUuMDg5IDc2LjQxNzUgMTEwLjY5OUw3Ni41ODc5IDExMC41ODlDNzcuNzg4NCAxMDkuNzMzIDc4LjkzMzEgMTA4LjgwMiA4MC4wMTQ4IDEwNy44MDJMODAuMTM3NSAxMDcuNjkyQzg1Ljg0MjggMTAyLjQ1MyA5Ni4wOTk4IDkwLjMzNjEgOTUuOTk5MyA3MS4wMTY4Qzk1Ljk3OCA2Ny43OTQxIDk1LjY5MDIgNjQuNTc4NiA5NS4xMzg3IDYxLjQwMjhaTTcxLjg3NiA5Ni45MTgxQzcxLjg3NiA5Ni45MTgxIDcxLjg3NiA2MC45ODk2IDczLjA2ODkgNjAuOTk2M0M3My45OTkzIDYwLjk5NjMgNzUuMjA0MSAxMDcuMzQgNzUuMjA0MSAxMDcuMzRDNzMuNTQ3NyAxMDcuMTQyIDcxLjg3NiA5OS43MTI4IDcxLjg3NiA5Ni45MTgxWiIgZmlsbD0id2hpdGUiLz4KPGRlZnM+CjxyYWRpYWxHcmFkaWVudCBpZD0icGFpbnQwX3JhZGlhbF8zMzBfNDg5ODEiIGN4PSIwIiBjeT0iMCIgcj0iMSIgZ3JhZGllbnRVbml0cz0idXNlclNwYWNlT25Vc2UiIGdyYWRpZW50VHJhbnNmb3JtPSJ0cmFuc2xhdGUoMS4zMjI5OGUtMDUgLTcuNTAwMDEpIHJvdGF0ZSg0NC43MTc4KSBzY2FsZSgyMTUuMzE3IDMxMi40NTUpIj4KPHN0b3Agc3RvcC1jb2xvcj0iIzI1RkY4MCIvPgo8c3RvcCBvZmZzZXQ9IjEiIHN0b3AtY29sb3I9IiMxM0FBNTIiLz4KPC9yYWRpYWxHcmFkaWVudD4KPC9kZWZzPgo8L3N2Zz4K - keysOrder: [["apiVersion"], ["appVersion"], ["kind"], ["metadata"], ["metadata", "name"], ["spec", "replicas"], ["spec", "resources"], ["spec", "resourcesPreset"], ["spec", "size"], ["spec", "storageClass"], ["spec", "external"], ["spec", "version"], ["spec", "sharding"], ["spec", "shardingConfig"], ["spec", "shardingConfig", "configServers"], ["spec", "shardingConfig", "configServerSize"], ["spec", "shardingConfig", "mongos"], ["spec", "shardingConfig", "shards"], ["spec", "users"], ["spec", "databases"], ["spec", "backup"], ["spec", "backup", "enabled"], ["spec", "backup", "schedule"], ["spec", "backup", "retentionPolicy"], ["spec", "backup", "destinationPath"], ["spec", "backup", "endpointURL"], ["spec", "backup", "insecureSkipTLSVerify"], ["spec", "backup", "s3AccessKey"], ["spec", "backup", "s3SecretKey"], ["spec", "bootstrap"], ["spec", "bootstrap", "enabled"], ["spec", "bootstrap", "recoveryTime"], ["spec", "bootstrap", "backupName"]] + keysOrder: [["apiVersion"], ["appVersion"], ["kind"], ["metadata"], ["metadata", "name"], ["spec", "replicas"], ["spec", "resources"], ["spec", "resourcesPreset"], ["spec", "size"], ["spec", "storageClass"], ["spec", "external"], ["spec", "version"], ["spec", "sharding"], ["spec", "shardingConfig"], ["spec", "shardingConfig", "configServers"], ["spec", "shardingConfig", "configServerSize"], ["spec", "shardingConfig", "mongos"], ["spec", "shardingConfig", "shards"], ["spec", "users"], ["spec", "databases"], ["spec", "backup"], ["spec", "backup", "enabled"], ["spec", "backup", "useSystemBucket"], ["spec", "backup", "schedule"], ["spec", "backup", "retentionPolicy"], ["spec", "backup", "destinationPath"], ["spec", "backup", "endpointURL"], ["spec", "backup", "insecureSkipTLSVerify"], ["spec", "backup", "s3AccessKey"], ["spec", "backup", "s3SecretKey"], ["spec", "bootstrap"], ["spec", "bootstrap", "enabled"], ["spec", "bootstrap", "recoveryTime"], ["spec", "bootstrap", "backupName"]] secrets: # Evaluated before include, so this is a structural backstop rather than a # restatement: the include selector below matches by label with no name From c036efaa5aae9a428cdfa09c63a69e5cedeefc96 Mon Sep 17 00:00:00 2001 From: Andrey Kolkov Date: Wed, 26 Aug 2026 19:13:31 +0400 Subject: [PATCH 0004/1280] test(mongodb): cover system-bucket storage injection gate and builder Extract the two untested contracts from applyMongoDBSystemStorage into pure functions and unit-test both, mirroring the CNPG driver's buildBarmanObjectStore split: - shouldInjectMongoDBSystemStorage decides whether the driver injects the system-bucket storage; the tests pin both branches, including the one that leaves a legacy app's manual bucket untouched. - buildMongoDBSystemStorageEntry builds the {type:s3,s3:{...}} entry, defaulting credentialsSecret and omitting forcePathStyle when nil. Also add a helm-unittest for the restore.yaml guard rejecting bootstrap.enabled together with backup.useSystemBucket. Signed-off-by: Andrey Kolkov Assisted-By: LLM --- .../psmdbstrategy_controller.go | 50 ++++++-- .../psmdbstrategy_controller_test.go | 121 ++++++++++++++++++ packages/apps/mongodb/tests/restore_test.yaml | 14 ++ 3 files changed, 172 insertions(+), 13 deletions(-) diff --git a/internal/backupcontroller/psmdbstrategy_controller.go b/internal/backupcontroller/psmdbstrategy_controller.go index c60cdcf7e..07eafc7d3 100644 --- a/internal/backupcontroller/psmdbstrategy_controller.go +++ b/internal/backupcontroller/psmdbstrategy_controller.go @@ -234,8 +234,7 @@ func (r *BackupJobReconciler) reconcileMongoDB(ctx context.Context, j *backupsv1 // spec.plugins patch). Gated on the storage being ABSENT: rendered.S3==nil // (a custom strategy) or a legacy app that already ships its own static // s3-storage is left untouched, so this never clobbers a manual bucket. - _, hasStorage := cluster.Spec.Backup.Storages[storageName] - if rendered.S3 != nil && !hasStorage { + if shouldInjectMongoDBSystemStorage(cluster, storageName, rendered) { if err := r.applyMongoDBSystemStorage(ctx, j.Namespace, psmdbName, storageName, rendered.S3); err != nil { return r.markBackupJobFailed(ctx, j, fmt.Sprintf("failed to inject system-bucket storage onto psmdb.percona.com/PerconaServerMongoDB %s/%s: %v", j.Namespace, psmdbName, err)) } @@ -396,16 +395,28 @@ func psmdbStorageS3CredentialsSecret(raw runtime.RawExtension) string { return st.S3.CredentialsSecret } -// applyMongoDBSystemStorage SSA-injects the system-bucket S3 storage onto the -// live PerconaServerMongoDB's spec.backup.storages[storageName]. On the -// useSystemBucket flow the app chart omits the storage (it cannot know the -// platform bucket/endpoint at render time), so the driver owns this subtree -// via a dedicated field manager + ForceOwnership - the app's Helm/Flux manager -// never sets it, so re-renders leave the injected storage intact (mirrors the -// CNPG driver's spec.plugins patch). CredentialsSecret defaults to -// cozy-backups-creds, which the BackupJob reconciler projects into the -// namespace before dispatch. -func (r *BackupJobReconciler) applyMongoDBSystemStorage(ctx context.Context, namespace, psmdbName, storageName string, s3 *strategyv1alpha1.MongoDBStorageS3) error { +// shouldInjectMongoDBSystemStorage reports whether the driver must SSA-inject +// the system-bucket storage onto the live cluster: only when the strategy +// carries S3 coordinates (the useSystemBucket flow) AND the cluster does not +// already declare the named storage. The absence gate is the load-bearing +// guarantee that a legacy app shipping its own static storage — or a custom +// strategy with no S3 coordinates — is left untouched, so injection never +// clobbers a manually configured bucket. +func shouldInjectMongoDBSystemStorage(cluster *psmdbtypes.PerconaServerMongoDB, storageName string, rendered *strategyv1alpha1.MongoDBTemplate) bool { + if rendered.S3 == nil { + return false + } + _, hasStorage := cluster.Spec.Backup.Storages[storageName] + return !hasStorage +} + +// buildMongoDBSystemStorageEntry constructs the psmdb spec.backup.storages +// entry the driver injects on the useSystemBucket flow. Factored out of the +// SSA path so the defaulting (empty credentialsSecret → cozy-backups-creds), +// the forcePathStyle omit-when-nil (a nil pointer must not surface as a +// forcePathStyle:false the app never chose), and the {"type":"s3","s3":{…}} +// shape are exercised without a live apiserver. +func buildMongoDBSystemStorageEntry(s3 *strategyv1alpha1.MongoDBStorageS3) map[string]interface{} { cred := s3.CredentialsSecret if cred == "" { cred = "cozy-backups-creds" @@ -421,7 +432,20 @@ func (r *BackupJobReconciler) applyMongoDBSystemStorage(ctx context.Context, nam if s3.ForcePathStyle != nil { s3Cfg["forcePathStyle"] = *s3.ForcePathStyle } - entry, err := json.Marshal(map[string]interface{}{"type": "s3", "s3": s3Cfg}) + return map[string]interface{}{"type": "s3", "s3": s3Cfg} +} + +// applyMongoDBSystemStorage SSA-injects the system-bucket S3 storage onto the +// live PerconaServerMongoDB's spec.backup.storages[storageName]. On the +// useSystemBucket flow the app chart omits the storage (it cannot know the +// platform bucket/endpoint at render time), so the driver owns this subtree +// via a dedicated field manager + ForceOwnership - the app's Helm/Flux manager +// never sets it, so re-renders leave the injected storage intact (mirrors the +// CNPG driver's spec.plugins patch). CredentialsSecret defaults to +// cozy-backups-creds, which the BackupJob reconciler projects into the +// namespace before dispatch. +func (r *BackupJobReconciler) applyMongoDBSystemStorage(ctx context.Context, namespace, psmdbName, storageName string, s3 *strategyv1alpha1.MongoDBStorageS3) error { + entry, err := json.Marshal(buildMongoDBSystemStorageEntry(s3)) if err != nil { return err } diff --git a/internal/backupcontroller/psmdbstrategy_controller_test.go b/internal/backupcontroller/psmdbstrategy_controller_test.go index 897868d03..74f8bff3c 100644 --- a/internal/backupcontroller/psmdbstrategy_controller_test.go +++ b/internal/backupcontroller/psmdbstrategy_controller_test.go @@ -749,6 +749,127 @@ func TestCreateMongoDBBackupArtifact_ArtifactShape(t *testing.T) { }) } +// --------------------------------------------------------------------------- +// System-bucket storage injection +// --------------------------------------------------------------------------- + +// TestShouldInjectMongoDBSystemStorage pins both branches of the injection +// gate: inject only when the strategy carries S3 coordinates AND the cluster +// does not already declare the named storage. The skip-when-present branch is +// the guarantee that a legacy app's manually configured storage is never +// clobbered. +func TestShouldInjectMongoDBSystemStorage(t *testing.T) { + s3 := &strategyv1alpha1.MongoDBStorageS3{Bucket: "b", EndpointURL: "https://s3"} + withStorage := func(names ...string) *psmdbtypes.PerconaServerMongoDB { + c := &psmdbtypes.PerconaServerMongoDB{} + if len(names) > 0 { + c.Spec.Backup.Storages = map[string]runtime.RawExtension{} + for _, n := range names { + c.Spec.Backup.Storages[n] = runtime.RawExtension{Raw: []byte(`{"type":"s3"}`)} + } + } + return c + } + cases := []struct { + name string + cluster *psmdbtypes.PerconaServerMongoDB + rendered *strategyv1alpha1.MongoDBTemplate + want bool + }{ + { + name: "useSystemBucket flow, storage absent: inject", + cluster: withStorage(), + rendered: &strategyv1alpha1.MongoDBTemplate{StorageName: "s3-storage", S3: s3}, + want: true, + }, + { + name: "storage already declared: skip (never clobber a manual bucket)", + cluster: withStorage("s3-storage"), + rendered: &strategyv1alpha1.MongoDBTemplate{StorageName: "s3-storage", S3: s3}, + want: false, + }, + { + name: "custom strategy without S3 coordinates: skip", + cluster: withStorage(), + rendered: &strategyv1alpha1.MongoDBTemplate{StorageName: "s3-storage"}, + want: false, + }, + { + name: "S3 set but a different storage is declared: inject (named one is absent)", + cluster: withStorage("other-storage"), + rendered: &strategyv1alpha1.MongoDBTemplate{StorageName: "s3-storage", S3: s3}, + want: true, + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + storageName := psmdbStorageNameOrDefault(tc.rendered.StorageName) + if got := shouldInjectMongoDBSystemStorage(tc.cluster, storageName, tc.rendered); got != tc.want { + t.Fatalf("shouldInjectMongoDBSystemStorage = %v, want %v", got, tc.want) + } + }) + } +} + +// TestBuildMongoDBSystemStorageEntry pins the injected storage-entry shape: the +// {"type":"s3","s3":{…}} envelope, the empty-credentialsSecret default, and the +// forcePathStyle omit-when-nil (a nil pointer must not surface as +// forcePathStyle:false the app never chose). +func TestBuildMongoDBSystemStorageEntry(t *testing.T) { + t.Run("defaults credentialsSecret and omits forcePathStyle when nil", func(t *testing.T) { + entry := buildMongoDBSystemStorageEntry(&strategyv1alpha1.MongoDBStorageS3{ + Bucket: "sys-bucket", + EndpointURL: "https://s3.example", + Region: "us-east-1", + Prefix: "mongodb-src", + }) + if entry["type"] != "s3" { + t.Fatalf("type = %v, want s3", entry["type"]) + } + s3, ok := entry["s3"].(map[string]interface{}) + if !ok { + t.Fatalf("s3 block is not a map: %#v", entry["s3"]) + } + if s3["credentialsSecret"] != "cozy-backups-creds" { + t.Errorf("credentialsSecret = %v, want cozy-backups-creds", s3["credentialsSecret"]) + } + if _, present := s3["forcePathStyle"]; present { + t.Errorf("forcePathStyle must be omitted when the pointer is nil; got %v", s3["forcePathStyle"]) + } + for k, want := range map[string]interface{}{ + "bucket": "sys-bucket", + "endpointUrl": "https://s3.example", + "region": "us-east-1", + "prefix": "mongodb-src", + "insecureSkipTLSVerify": false, + } { + if s3[k] != want { + t.Errorf("s3[%q] = %v, want %v", k, s3[k], want) + } + } + }) + + t.Run("honours explicit credentialsSecret and forcePathStyle", func(t *testing.T) { + fps := true + entry := buildMongoDBSystemStorageEntry(&strategyv1alpha1.MongoDBStorageS3{ + Bucket: "b", + CredentialsSecret: "custom-creds", + ForcePathStyle: &fps, + InsecureSkipTLSVerify: true, + }) + s3 := entry["s3"].(map[string]interface{}) + if s3["credentialsSecret"] != "custom-creds" { + t.Errorf("credentialsSecret = %v, want custom-creds", s3["credentialsSecret"]) + } + if s3["forcePathStyle"] != true { + t.Errorf("forcePathStyle = %v, want true", s3["forcePathStyle"]) + } + if s3["insecureSkipTLSVerify"] != true { + t.Errorf("insecureSkipTLSVerify = %v, want true", s3["insecureSkipTLSVerify"]) + } + }) +} + // --------------------------------------------------------------------------- // Test helpers // --------------------------------------------------------------------------- diff --git a/packages/apps/mongodb/tests/restore_test.yaml b/packages/apps/mongodb/tests/restore_test.yaml index e591587b9..9146c05fb 100644 --- a/packages/apps/mongodb/tests/restore_test.yaml +++ b/packages/apps/mongodb/tests/restore_test.yaml @@ -59,6 +59,20 @@ tests: - failedTemplate: errorMessage: "bootstrap.backupName is required when bootstrap.enabled is true" + - it: fails when bootstrap and useSystemBucket are both enabled + release: + name: test-mongodb + namespace: tenant-test + set: + bootstrap: + enabled: true + backupName: "my-backup" + backup: + useSystemBucket: true + asserts: + - failedTemplate: + errorMessage: "mongodb: bootstrap.enabled=true is incompatible with backup.useSystemBucket=true. Restore from the system bucket with a backups.cozystack.io/RestoreJob against the cozy-default BackupClass; see docs/operations/backup-classes.md." + - it: fails when destinationPath is missing release: name: test-mongodb From 4ea48886852592ad120a34650b9db94e599cfe83 Mon Sep 17 00:00:00 2001 From: Andrey Kolkov Date: Thu, 10 Sep 2026 22:11:06 +0400 Subject: [PATCH 0005/1280] fix(mongodb): key system-bucket injection off the app flag, not live storage The MongoDB backup driver decided what to inject and what to record from the live cluster's storage set rather than from the app's opt-in flag. That had three consequences. The snapshot fallback fired for legacy apps too. Its gate was `snap.S3 == nil && rendered.S3 != nil`, but the coordinates moved onto the shared cozy-default strategy, so rendered.S3 is now non-nil for every MongoDB app. A legacy backup written to the tenant's own bucket got its snapshot rewritten to the platform bucket, sending restore to the wrong place. Gate the fallback on the app's backup.useSystemBucket flag instead, threaded through createMongoDBBackupArtifact, and pin the legacy case. The injected storage never caught up with the strategy. Injection was gated on the named storage being absent, so it ran once per cluster and froze the coordinates at the first backup; a later endpoint/region change or bucket re-provision was a silent no-op, and Helm could not repair it because the useSystemBucket chart renders no storages. Key injection off the app flag and re-apply on every BackupJob (the prefix is deterministic, so this never splits the archive the way CNPG's serverName would). Add UseSystemBucket to mongodbapp.MongoDBSpec so a legacy app is protected by the flag, not by whatever happens to be on the cluster. The docs said the opposite of what the driver does. backup-classes.md claimed "the MongoDB driver cannot inject its S3 target per-backup"; correct it and add an opt-in-to-the-system-bucket section that names which values stop being read and that scheduled backups + PITR must move to a Plan. Fix the endpoint table row, the tuning reference, the RBAC comment that said the driver never patches, the strategy header/inline comments, and the example comment. Also assert notExists on spec.backup.pitr in the helm test, and lift the duplicated cozy-backups-creds default into a const. Signed-off-by: Andrey Kolkov Assisted-By: LLM --- docs/operations/backup-classes.md | 31 ++++- examples/backups/mongodb/05-mongodb-src.yaml | 7 +- internal/backupcontroller/mongodbapp/types.go | 27 +++-- .../psmdbstrategy_controller.go | 61 ++++++---- .../psmdbstrategy_controller_test.go | 106 ++++++++++-------- packages/apps/mongodb/tests/mongodb_test.yaml | 3 + .../templates/rbac.yaml | 9 +- 7 files changed, 157 insertions(+), 87 deletions(-) diff --git a/docs/operations/backup-classes.md b/docs/operations/backup-classes.md index f1859cb20..9b3f87e01 100644 --- a/docs/operations/backup-classes.md +++ b/docs/operations/backup-classes.md @@ -38,7 +38,7 @@ Different operators expect different endpoint shapes; the strategy templates ren | CNPG (Postgres) | `barmanObjectStore.endpointURL` | full URL (scheme preserved) | | Etcd | `destination.s3.endpoint` | full URL (scheme preserved) | | MariaDB | `storage.s3.endpoint` | bare host:port (scheme stripped); `tls.enabled` derived from the scheme | -| MongoDB | n/a — storage lives on the app (`backup.endpointURL`) | full URL (scheme preserved), configured on the MongoDB application, not the strategy | +| MongoDB | `s3.endpointUrl` | full URL (scheme preserved); on the default flow the app's `backup.endpointURL`, on `useSystemBucket` the strategy coordinate injected by the driver | | FoundationDB | `blobStoreConfiguration.accountName` + `urlParameters.secure_connection` | bare host:port + derived secure flag | | Velero | `BackupStorageLocation.spec.config.s3Url` | full URL (scheme preserved) | | ClickHouse sidecar | `S3_ENDPOINT` env | bare host:port (from projected Secret) | @@ -73,9 +73,13 @@ When `useSystemBucket: true`: `s3Region`, `s3Bucket`, `endpoint`, `s3AccessKey`, `s3SecretKey`, and `s3CredentialsSecret` are ignored in this mode. -## MongoDB: the application owns the backup storage +## MongoDB: backup storage -Unlike CNPG / MariaDB / Altinity, the MongoDB driver cannot inject its S3 target per-backup: the Percona psmdb operator only runs the percona-backup-mongodb (pbm) agents and services `PerconaServerMongoDBBackup` CRs when the `PerconaServerMongoDB` cluster has `spec.backup.enabled: true` and a storage declared, and a `PerconaServerMongoDBBackup` references that storage only by name. So the MongoDB application must **opt into backups** and point at the bucket in its own chart values: +MongoDB supports two storage flows. By default the S3 target lives on the app CR and the tenant supplies its own credentials; alternatively the tenant opts into the platform system bucket and the driver injects the storage onto the live cluster at backup time. + +### Default: the application owns the backup storage + +The Percona psmdb operator only runs the percona-backup-mongodb (pbm) agents and services `PerconaServerMongoDBBackup` CRs when the `PerconaServerMongoDB` cluster has `spec.backup.enabled: true` and a storage declared, and a `PerconaServerMongoDBBackup` references that storage only by name. On the default flow the MongoDB application **opts into backups** and points at the bucket in its own chart values: ```yaml apiVersion: apps.cozystack.io/v1alpha1 @@ -98,6 +102,25 @@ For a to-copy restore the operator reads the dump from the **source** backup's b A full, scripted example (write a marker document, back up, restore to a copy, assert the round-trip while the source stays untouched) is in [`examples/backups/mongodb/`](../../examples/backups/mongodb/) — driven by `run-all.sh`. +### Opt-in to the system bucket + +Unlike ClickHouse's sidecar, PBM takes the bucket/endpoint/prefix as static fields on the `PerconaServerMongoDB` CR, and the platform bucket name is only known at BackupJob time — so the chart cannot render them. Instead the `cozy-default-mongodb` driver injects the storage onto the live cluster. To back up to the platform bucket without supplying S3 credentials, set: + +```yaml +backup: + enabled: true + useSystemBucket: true +``` + +When `useSystemBucket: true`: + +- The chart-emitted `-s3-creds` Secret is no longer rendered, and the chart leaves `spec.backup.storages`, `spec.backup.tasks` and `spec.backup.pitr` unset on the `PerconaServerMongoDB`. +- On every BackupJob the driver SSA-injects the `s3-storage` entry from the strategy coordinates (bucket/endpoint from the platform system bucket, `credentialsSecret: cozy-backups-creds`, prefix `/`) under its own field manager, so a Flux re-render never reverts it and a later change to the coordinates is picked up on the next backup rather than frozen at the first. + +`destinationPath`, `endpointURL`, `insecureSkipTLSVerify`, `s3AccessKey` and `s3SecretKey` are ignored in this mode. + +Because the chart drops `spec.backup.tasks` and `spec.backup.pitr`, the psmdb operator's own scheduled backups and oplog PITR do **not** run on this flow — `backup.schedule` and `backup.retentionPolicy` stay in the schema for the default flow but have no effect here, and the `recoveryTime` PITR restores described below are not available. Migrate scheduled backups to a `backups.cozystack.io/Plan` against `cozy-default` instead. **Flipping this flag on a running app** removes the storage, tasks and pitr the app had, so a release that was taking scheduled backups + PITR before the flip stops until a `Plan` takes over. + ### Point-in-time recovery (MongoDB) psmdb records an oplog stream between logical backups. A MongoDB `RestoreJob` recovers to a timestamp via `spec.options.recoveryTime` — the same option name and RFC3339 format the Postgres/CNPG driver uses, so the two are uniform: @@ -265,7 +288,7 @@ The defaults aim at a reasonable middle (30-day retention, gzip compression wher - **CNPG strategy**: `barmanObjectStore.retentionPolicy`, `data.compression`, `wal.compression`. - **MariaDB strategy**: `compression`, `maxRetention`, `databases[]`. -- **MongoDB strategy**: `storageName` (which `spec.backup.storages` entry on the psmdb cluster to use), `type` (`logical`), `compressionType` / `compressionLevel`. The S3 target itself is tuned via `backup.*` values on the MongoDB release (see [MongoDB: the application owns the backup storage](#mongodb-the-application-owns-the-backup-storage)). +- **MongoDB strategy**: `storageName` (which `spec.backup.storages` entry on the psmdb cluster to use), `type` (`logical`), `compressionType` / `compressionLevel`, and — for the `useSystemBucket` flow — the `s3` coordinates the driver injects. On the default flow the S3 target is tuned via `backup.*` values on the MongoDB release instead (see [MongoDB: backup storage](#mongodb-backup-storage)). - **Altinity strategy**: tune the `clickhouse-backup` sidecar via `backup.*` values on the ClickHouse release; the strategy Pod is a thin HTTP client. When the S3 endpoint's certificate is signed by a private CA rather than a publicly-trusted one — SeaweedFS's in-cluster `:8333` being the case in point — point `backup.endpointCA` at a Secret holding that CA bundle; the chart mounts it into the sidecar and adds it to the trust store via `SSL_CERT_DIR`, which supplements the system CA set rather than replacing it. - **FoundationDB strategy**: `snapshotPeriodSeconds`, `agentCount`, `urlParameters[]`. - **Rabbitmq strategy**: `artifactURITemplate` (the `///definitions.json` object-key layout) and the pod `template` (image, resources). The backup is a definitions export over the management API — vhosts, users, permissions, queues, exchanges, bindings, policies, parameters — so message payloads are out of scope and there is no point-in-time recovery; a full message-data backup is a Velero volume snapshot instead. **Restore is a merge, not a reset**: importing definitions (`POST /api/definitions`) creates or updates what the export contains and never deletes, so anything created after the backup survives the restore and the broker is not returned to its exact backup-time state. A to-copy restore imports the source's users (with password hashes) into the target, so those source credentials become valid logins there. Unlike the operator-backed strategies (whose engine owns archive retention), the Rabbitmq driver owns its object outright and deletes it from the bucket when its `Backup` is deleted — via a one-shot Job the Backup's removal waits on — so a retention-pruned `Plan` does not normally accumulate objects. The delete is **best-effort**: when it cannot run from here the Backup is released without deleting the object (with a `Warning` Event naming what was left behind), so the Backup — and any namespace being torn down — never wedges. The named give-up conditions are: the namespace is terminating (`CREATE` is forbidden there), the strategy CR or the projected credentials are unavailable, the rendered Job name is invalid, or the skip annotation below is set. Otherwise a genuinely failing delete (object storage unreachable) keeps the `Backup` in `Terminating` (a visible signal to act on) and retries. To release such a stuck `Backup`, annotate it `backups.cozystack.io/skip-artifact-cleanup: "true"` — cleanup then skips the delete and lets the `Backup` go, leaving the object in the bucket to be reclaimed manually or by a bucket lifecycle policy (`kubectl annotate backup -n backups.cozystack.io/skip-artifact-cleanup=true`). diff --git a/examples/backups/mongodb/05-mongodb-src.yaml b/examples/backups/mongodb/05-mongodb-src.yaml index 8159fa800..d828d44bc 100644 --- a/examples/backups/mongodb/05-mongodb-src.yaml +++ b/examples/backups/mongodb/05-mongodb-src.yaml @@ -4,8 +4,11 @@ # when the cluster has the percona-backup-mongodb agents running and a storage # declared — that is what `backup.enabled: true` wires up. The cozystack # backup-strategy driver names that storage ("s3-storage", the one the chart -# declares) via the cozy-default-mongodb Strategy; it does NOT inject storage -# into the cluster, so unlike MariaDB the application must opt into backups. +# declares) via the cozy-default-mongodb Strategy. This example uses the default +# flow, where the application owns the storage and the driver does not inject it +# — so, unlike MariaDB, the application must opt into backups. (Set +# backup.useSystemBucket: true instead to have the driver inject the platform +# system-bucket storage; see docs/operations/backup-classes.md.) # # The bucket coordinates (destinationPath / endpointURL / s3AccessKey / # s3SecretKey) point the storage at the Bucket provisioned in 00-bucket.yaml. diff --git a/internal/backupcontroller/mongodbapp/types.go b/internal/backupcontroller/mongodbapp/types.go index 729bcf4ab..e00cacb27 100644 --- a/internal/backupcontroller/mongodbapp/types.go +++ b/internal/backupcontroller/mongodbapp/types.go @@ -54,13 +54,20 @@ type MongoDBList struct { Items []MongoDB `json:"items"` } -// MongoDBSpec is intentionally empty: the driver does not currently read or -// patch any apps.cozystack.io/MongoDB spec field. It reads the downstream -// psmdb.percona.com/PerconaServerMongoDB CR (rendered by the chart's -// HelmRelease) for existence + backup-enabled gating, and drives -// PerconaServerMongoDBBackup / PerconaServerMongoDBRestore CRs; it never -// mutates the app CR. -// -// Reserved for future fields the driver might need to read. Add fields here -// only when the driver genuinely needs them. -type MongoDBSpec struct{} +// MongoDBSpec mirrors only the apps.cozystack.io/MongoDB spec fields the driver +// reads. It drives the downstream psmdb.percona.com CRs directly, so it keeps +// no other spec state here. +type MongoDBSpec struct { + Backup MongoDBBackupSpec `json:"backup,omitempty"` +} + +// MongoDBBackupSpec carries the backup fields the driver reads off the app CR. +// UseSystemBucket is the tenant's opt-in to the platform system bucket: on that +// flow the chart leaves spec.backup.storages unset and the driver injects the +// storage from the strategy coordinates at BackupJob time. The driver keys its +// injection and its snapshot fallback off this flag, not off whatever storage +// happens to be on the live cluster, so a legacy app that ships its own static +// storage (UseSystemBucket=false) is never touched. +type MongoDBBackupSpec struct { + UseSystemBucket bool `json:"useSystemBucket,omitempty"` +} diff --git a/internal/backupcontroller/psmdbstrategy_controller.go b/internal/backupcontroller/psmdbstrategy_controller.go index 07eafc7d3..11de59cff 100644 --- a/internal/backupcontroller/psmdbstrategy_controller.go +++ b/internal/backupcontroller/psmdbstrategy_controller.go @@ -48,6 +48,12 @@ const ( // storage; when it leaves StorageName empty the driver falls back to this. psmdbDefaultStorageName = "s3-storage" + // psmdbDefaultCredentialsSecret is the Secret the useSystemBucket flow + // authenticates against: the BackupJob reconciler projects it into the + // namespace before dispatch. Both the storage injection and the snapshot + // fallback default to it when the strategy names none. + psmdbDefaultCredentialsSecret = "cozy-backups-creds" + // psmdbFieldManager is the server-side-apply field owner for the driver's // storage injection on the useSystemBucket flow. A dedicated manager (with // ForceOwnership) keeps the injected spec.backup.storages entry from being @@ -199,6 +205,8 @@ func (r *BackupJobReconciler) reconcileMongoDB(ctx context.Context, j *backupsv1 return ctrl.Result{}, err } + useSystemBucket := app.Spec.Backup.UseSystemBucket + rendered, err := renderMongoDBTemplate(strategy.Spec.Template, app, resolved.Parameters) if err != nil { return r.markBackupJobFailed(ctx, j, fmt.Sprintf("failed to template MongoDB strategy: %v", err)) @@ -231,10 +239,15 @@ func (r *BackupJobReconciler) reconcileMongoDB(ctx context.Context, j *backupsv1 // the storage from the strategy's coordinates before the precondition looks // for it. Owned by a dedicated field manager with ForceOwnership so a Flux // re-render of the app never reverts it (mirrors the CNPG driver's - // spec.plugins patch). Gated on the storage being ABSENT: rendered.S3==nil - // (a custom strategy) or a legacy app that already ships its own static - // s3-storage is left untouched, so this never clobbers a manual bucket. - if shouldInjectMongoDBSystemStorage(cluster, storageName, rendered) { + // spec.plugins patch). Keyed off the app's useSystemBucket flag, not off + // whatever storage is on the live cluster: when the flag is set the apply + // runs on every BackupJob so a later change to the strategy coordinates + // (endpoint, region, bucket re-provision) catches up rather than being + // frozen at the first backup; when it is unset the driver never touches the + // cluster, so a legacy app that ships its own static storage is left alone. + // The path prefix is deterministic (/), so re-applying the + // whole entry never splits the archive the way CNPG's serverName would. + if shouldInjectMongoDBSystemStorage(useSystemBucket, rendered) { if err := r.applyMongoDBSystemStorage(ctx, j.Namespace, psmdbName, storageName, rendered.S3); err != nil { return r.markBackupJobFailed(ctx, j, fmt.Sprintf("failed to inject system-bucket storage onto psmdb.percona.com/PerconaServerMongoDB %s/%s: %v", j.Namespace, psmdbName, err)) } @@ -271,7 +284,7 @@ func (r *BackupJobReconciler) reconcileMongoDB(ctx context.Context, j *backupsv1 if j.Status.BackupRef != nil { return ctrl.Result{}, nil } - artifact, err := r.createMongoDBBackupArtifact(ctx, j, resolved, mdbBackup, rendered, storageName) + artifact, err := r.createMongoDBBackupArtifact(ctx, j, resolved, mdbBackup, rendered, storageName, useSystemBucket) if err != nil { return r.markBackupJobFailed(ctx, j, fmt.Sprintf("failed to create Backup artifact: %v", err)) } @@ -396,18 +409,15 @@ func psmdbStorageS3CredentialsSecret(raw runtime.RawExtension) string { } // shouldInjectMongoDBSystemStorage reports whether the driver must SSA-inject -// the system-bucket storage onto the live cluster: only when the strategy -// carries S3 coordinates (the useSystemBucket flow) AND the cluster does not -// already declare the named storage. The absence gate is the load-bearing -// guarantee that a legacy app shipping its own static storage — or a custom -// strategy with no S3 coordinates — is left untouched, so injection never -// clobbers a manually configured bucket. -func shouldInjectMongoDBSystemStorage(cluster *psmdbtypes.PerconaServerMongoDB, storageName string, rendered *strategyv1alpha1.MongoDBTemplate) bool { - if rendered.S3 == nil { - return false - } - _, hasStorage := cluster.Spec.Backup.Storages[storageName] - return !hasStorage +// the system-bucket storage onto the live cluster: only when the app opted in +// via backup.useSystemBucket AND the strategy actually carries S3 coordinates +// to inject. Keying off the app flag (not the live cluster's storage set) is +// the load-bearing guarantee: a legacy app leaves the flag false and is never +// touched, so injection never clobbers a manually configured bucket; a +// useSystemBucket app is injected on every BackupJob, so a later change to the +// strategy coordinates catches up instead of being frozen at the first backup. +func shouldInjectMongoDBSystemStorage(useSystemBucket bool, rendered *strategyv1alpha1.MongoDBTemplate) bool { + return useSystemBucket && rendered.S3 != nil } // buildMongoDBSystemStorageEntry constructs the psmdb spec.backup.storages @@ -419,7 +429,7 @@ func shouldInjectMongoDBSystemStorage(cluster *psmdbtypes.PerconaServerMongoDB, func buildMongoDBSystemStorageEntry(s3 *strategyv1alpha1.MongoDBStorageS3) map[string]interface{} { cred := s3.CredentialsSecret if cred == "" { - cred = "cozy-backups-creds" + cred = psmdbDefaultCredentialsSecret } s3Cfg := map[string]interface{}{ "bucket": s3.Bucket, @@ -551,6 +561,7 @@ func (r *BackupJobReconciler) createMongoDBBackupArtifact( mdbBackup *psmdbtypes.PerconaServerMongoDBBackup, rendered *strategyv1alpha1.MongoDBTemplate, storageName string, + useSystemBucket bool, ) (*backupsv1alpha1.Backup, error) { takenAt := metav1.Now() if mdbBackup.Status.Completed != nil && !mdbBackup.Status.Completed.IsZero() { @@ -565,7 +576,7 @@ func (r *BackupJobReconciler) createMongoDBBackupArtifact( driverMD[psmdbDestinationKey] = mdbBackup.Status.Destination } - underlyingResources, err := marshalMongoDBBackupSnapshot(mdbBackup, rendered, storageName, resolved.Parameters) + underlyingResources, err := marshalMongoDBBackupSnapshot(mdbBackup, rendered, storageName, resolved.Parameters, useSystemBucket) if err != nil { return nil, fmt.Errorf("encode source snapshot for Backup.status.underlyingResources: %w", err) } @@ -984,7 +995,7 @@ type mongodbBackupSnapshot struct { Parameters map[string]string `json:"parameters,omitempty"` } -func marshalMongoDBBackupSnapshot(mdbBackup *psmdbtypes.PerconaServerMongoDBBackup, rendered *strategyv1alpha1.MongoDBTemplate, storageName string, parameters map[string]string) (*runtime.RawExtension, error) { +func marshalMongoDBBackupSnapshot(mdbBackup *psmdbtypes.PerconaServerMongoDBBackup, rendered *strategyv1alpha1.MongoDBTemplate, storageName string, parameters map[string]string, useSystemBucket bool) (*runtime.RawExtension, error) { snap := mongodbBackupSnapshot{ Kind: psmdbBackupSnapshotKind, APIVersion: psmdbBackupSnapshotAPIVersion, @@ -997,11 +1008,15 @@ func marshalMongoDBBackupSnapshot(mdbBackup *psmdbtypes.PerconaServerMongoDBBack // On the useSystemBucket flow the driver injected the storage, so fall back // to those coordinates when the operator's status echo is empty - the // restore path rebuilds backupSource from this snapshot and needs the - // endpoint + credentialsSecret (cozy-backups-creds) to be present. - if snap.S3 == nil && rendered.S3 != nil { + // endpoint + credentialsSecret (cozy-backups-creds) to be present. Gated on + // the app's flag, not on rendered.S3 alone: the coordinates now live on the + // shared cozy-default strategy, so rendered.S3 is non-nil for a legacy app + // too, and recording the platform bucket for an archive written to the + // tenant's own bucket would send restore to the wrong place. + if useSystemBucket && snap.S3 == nil && rendered.S3 != nil { cred := rendered.S3.CredentialsSecret if cred == "" { - cred = "cozy-backups-creds" + cred = psmdbDefaultCredentialsSecret } snap.S3 = &psmdbtypes.BackupStorageS3{ Bucket: rendered.S3.Bucket, diff --git a/internal/backupcontroller/psmdbstrategy_controller_test.go b/internal/backupcontroller/psmdbstrategy_controller_test.go index 74f8bff3c..e836c856c 100644 --- a/internal/backupcontroller/psmdbstrategy_controller_test.go +++ b/internal/backupcontroller/psmdbstrategy_controller_test.go @@ -457,7 +457,7 @@ func TestMarshalUnmarshalMongoDBBackupSnapshot_RoundTrip(t *testing.T) { }, } rendered := &strategyv1alpha1.MongoDBTemplate{Type: "logical"} - raw, err := marshalMongoDBBackupSnapshot(mdbBackup, rendered, "s3-storage", map[string]string{"k": "v"}) + raw, err := marshalMongoDBBackupSnapshot(mdbBackup, rendered, "s3-storage", map[string]string{"k": "v"}, false) if err != nil { t.Fatalf("marshal: %v", err) } @@ -504,7 +504,7 @@ func TestMarshalMongoDBBackupSnapshot_SystemBucketFallback(t *testing.T) { // CredentialsSecret intentionally empty -> defaults below. }, } - raw, err := marshalMongoDBBackupSnapshot(mdbBackup, rendered, "s3-storage", nil) + raw, err := marshalMongoDBBackupSnapshot(mdbBackup, rendered, "s3-storage", nil, true) if err != nil { t.Fatalf("marshal: %v", err) } @@ -523,6 +523,42 @@ func TestMarshalMongoDBBackupSnapshot_SystemBucketFallback(t *testing.T) { } } +// TestMarshalMongoDBBackupSnapshot_LegacyNoFallback pins the other half of the +// gate: a legacy app (useSystemBucket=false) whose operator echoed no S3 must +// leave the snapshot S3 nil even though the shared cozy-default strategy now +// carries platform coordinates. Recording the platform bucket for an archive +// the tenant wrote to its own bucket would send restore to the wrong place. +func TestMarshalMongoDBBackupSnapshot_LegacyNoFallback(t *testing.T) { + mdbBackup := &psmdbtypes.PerconaServerMongoDBBackup{ + Status: psmdbtypes.PerconaServerMongoDBBackupStatus{ + Destination: "s3://tenant-own-bucket/mongodb-src/2026-08-26T00:00:00Z", + // S3 nil: operator echoed nothing, as on a legacy app whose storage + // lives on the app CR. + }, + } + rendered := &strategyv1alpha1.MongoDBTemplate{ + Type: "logical", + S3: &strategyv1alpha1.MongoDBStorageS3{ + Bucket: "cozy-backups-PLATFORM", + EndpointURL: "https://platform-s3.example", + }, + } + raw, err := marshalMongoDBBackupSnapshot(mdbBackup, rendered, "s3-storage", nil, false) + if err != nil { + t.Fatalf("marshal: %v", err) + } + snap, err := unmarshalMongoDBBackupSnapshot(raw) + if err != nil { + t.Fatalf("unmarshal: %v", err) + } + if snap.S3 != nil { + t.Fatalf("legacy snapshot must not adopt the platform coordinates; got %#v", snap.S3) + } + if snap.Destination != "s3://tenant-own-bucket/mongodb-src/2026-08-26T00:00:00Z" { + t.Errorf("legacy destination must be preserved; got %q", snap.Destination) + } +} + func TestUnmarshalMongoDBBackupSnapshot_Empty(t *testing.T) { snap, err := unmarshalMongoDBBackupSnapshot(nil) if err != nil || snap != nil { @@ -574,7 +610,7 @@ func TestResolveMongoDBBackupSource_SnapshotFallback(t *testing.T) { S3: &psmdbtypes.BackupStorageS3{Bucket: "bkt", ForcePathStyle: &fps}, }, } - raw, err := marshalMongoDBBackupSnapshot(snapBackup, &strategyv1alpha1.MongoDBTemplate{Type: "logical"}, "s3-storage", nil) + raw, err := marshalMongoDBBackupSnapshot(snapBackup, &strategyv1alpha1.MongoDBTemplate{Type: "logical"}, "s3-storage", nil, false) if err != nil { t.Fatalf("marshal snapshot: %v", err) } @@ -688,7 +724,7 @@ func TestCreateMongoDBBackupArtifact_ArtifactShape(t *testing.T) { }, } - artefact, err := r.createMongoDBBackupArtifact(context.Background(), job, resolved, mdbBackup, rendered, "s3-storage") + artefact, err := r.createMongoDBBackupArtifact(context.Background(), job, resolved, mdbBackup, rendered, "s3-storage", false) if err != nil { t.Fatalf("createMongoDBBackupArtifact: %v", err) } @@ -736,7 +772,7 @@ func TestCreateMongoDBBackupArtifact_ArtifactShape(t *testing.T) { Status: psmdbtypes.PerconaServerMongoDBBackupStatus{State: psmdbtypes.StateReady}, } - artefact, err := r.createMongoDBBackupArtifact(context.Background(), job, resolved, mdbBackup, rendered, "s3-storage") + artefact, err := r.createMongoDBBackupArtifact(context.Background(), job, resolved, mdbBackup, rendered, "s3-storage", false) if err != nil { t.Fatalf("createMongoDBBackupArtifact: %v", err) } @@ -753,58 +789,40 @@ func TestCreateMongoDBBackupArtifact_ArtifactShape(t *testing.T) { // System-bucket storage injection // --------------------------------------------------------------------------- -// TestShouldInjectMongoDBSystemStorage pins both branches of the injection -// gate: inject only when the strategy carries S3 coordinates AND the cluster -// does not already declare the named storage. The skip-when-present branch is -// the guarantee that a legacy app's manually configured storage is never -// clobbered. +// TestShouldInjectMongoDBSystemStorage pins the injection gate: inject only when +// the app opted into the system bucket AND the strategy carries S3 coordinates. +// The flag-false branch is the guarantee that a legacy app is never touched, +// regardless of what storage happens to be on the live cluster. func TestShouldInjectMongoDBSystemStorage(t *testing.T) { s3 := &strategyv1alpha1.MongoDBStorageS3{Bucket: "b", EndpointURL: "https://s3"} - withStorage := func(names ...string) *psmdbtypes.PerconaServerMongoDB { - c := &psmdbtypes.PerconaServerMongoDB{} - if len(names) > 0 { - c.Spec.Backup.Storages = map[string]runtime.RawExtension{} - for _, n := range names { - c.Spec.Backup.Storages[n] = runtime.RawExtension{Raw: []byte(`{"type":"s3"}`)} - } - } - return c - } cases := []struct { - name string - cluster *psmdbtypes.PerconaServerMongoDB - rendered *strategyv1alpha1.MongoDBTemplate - want bool + name string + useSystemBucket bool + rendered *strategyv1alpha1.MongoDBTemplate + want bool }{ { - name: "useSystemBucket flow, storage absent: inject", - cluster: withStorage(), - rendered: &strategyv1alpha1.MongoDBTemplate{StorageName: "s3-storage", S3: s3}, - want: true, + name: "useSystemBucket flow with strategy coordinates: inject", + useSystemBucket: true, + rendered: &strategyv1alpha1.MongoDBTemplate{StorageName: "s3-storage", S3: s3}, + want: true, }, { - name: "storage already declared: skip (never clobber a manual bucket)", - cluster: withStorage("s3-storage"), - rendered: &strategyv1alpha1.MongoDBTemplate{StorageName: "s3-storage", S3: s3}, - want: false, + name: "legacy app (flag off): skip even when the shared strategy carries coordinates", + useSystemBucket: false, + rendered: &strategyv1alpha1.MongoDBTemplate{StorageName: "s3-storage", S3: s3}, + want: false, }, { - name: "custom strategy without S3 coordinates: skip", - cluster: withStorage(), - rendered: &strategyv1alpha1.MongoDBTemplate{StorageName: "s3-storage"}, - want: false, - }, - { - name: "S3 set but a different storage is declared: inject (named one is absent)", - cluster: withStorage("other-storage"), - rendered: &strategyv1alpha1.MongoDBTemplate{StorageName: "s3-storage", S3: s3}, - want: true, + name: "useSystemBucket flag but strategy carries no coordinates: skip (nothing to inject)", + useSystemBucket: true, + rendered: &strategyv1alpha1.MongoDBTemplate{StorageName: "s3-storage"}, + want: false, }, } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { - storageName := psmdbStorageNameOrDefault(tc.rendered.StorageName) - if got := shouldInjectMongoDBSystemStorage(tc.cluster, storageName, tc.rendered); got != tc.want { + if got := shouldInjectMongoDBSystemStorage(tc.useSystemBucket, tc.rendered); got != tc.want { t.Fatalf("shouldInjectMongoDBSystemStorage = %v, want %v", got, tc.want) } }) diff --git a/packages/apps/mongodb/tests/mongodb_test.yaml b/packages/apps/mongodb/tests/mongodb_test.yaml index 192551fae..1eb60275a 100644 --- a/packages/apps/mongodb/tests/mongodb_test.yaml +++ b/packages/apps/mongodb/tests/mongodb_test.yaml @@ -89,6 +89,9 @@ tests: - notExists: path: spec.backup.tasks documentIndex: 0 + - notExists: + path: spec.backup.pitr + documentIndex: 0 ################## # Finalizers # diff --git a/packages/system/backupstrategy-controller/templates/rbac.yaml b/packages/system/backupstrategy-controller/templates/rbac.yaml index a3973e89c..2b80beec1 100644 --- a/packages/system/backupstrategy-controller/templates/rbac.yaml +++ b/packages/system/backupstrategy-controller/templates/rbac.yaml @@ -157,10 +157,11 @@ rules: # MongoDB strategy: read the operator-side PerconaServerMongoDB CR to gate on # "backups enabled + storage declared" preconditions, create one-shot # PerconaServerMongoDBBackup CRs on the BackupJob path, and create -# PerconaServerMongoDBRestore CRs on the RestoreJob path. As with MariaDB the -# driver only ever Creates/Lists/Gets these objects — it never patches or -# deletes them; their lifecycle is owned by the psmdb operator and (for -# cleanup) by tenants / explicit teardown flows, never by this controller. +# PerconaServerMongoDBRestore CRs on the RestoreJob path. The Backup/Restore CRs +# are only ever Created/Listed/Gotten — their lifecycle is owned by the psmdb +# operator and (for cleanup) by tenants / explicit teardown flows. The cluster +# CR is patched only on the useSystemBucket flow (storage injection, below); it +# is never deleted. - apiGroups: ["psmdb.percona.com"] resources: ["perconaservermongodbs"] # patch/update: the useSystemBucket flow SSA-injects spec.backup.storages From 9545bee233d88e59699827d3b6b9a74d69c9f2ac Mon Sep 17 00:00:00 2001 From: Andrey Kolkov Date: Fri, 11 Sep 2026 16:13:02 +0400 Subject: [PATCH 0006/1280] fix(mongodb): correct system-bucket prose, pin strategy rendering, make restore credential swap flow-aware MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Several comments and the useSystemBucket field description had drifted from what the code does. The strategy header still said the $bucketName gate was "not because it needs the value" and that the sibling strategies needed the bucket name while this one only asked for ordering, but the strategy now renders bucket: {{ $bucketName }} for the injected coordinates, so it needs the value; the precondition comment claimed the s3-storage entry exists on backup.enabled=true, which is only the legacy flow. The rendering-test comment carried the same "needs no bucket coordinates" claim. The useSystemBucket field description said injection happens "at first BackupJob time" (it now runs on every BackupJob) and that backups scope to / (the prefix templates the application name, not the release), and it ran ~700 chars of implementation detail into the CRD that backup-classes.md already carries; trimmed and corrected, then regenerated schema/README/types/cozyrds. Same slip fixed in the driver comment and the docs. Nothing asserted the new strategy rendering. Added the MongoDB row to the endpoint-form suite (s3.endpointUrl, scheme preserved both ways) and field assertions to the rendering suite — bucket, endpointUrl, region, credentialsSecret, forcePathStyle, and prefix, which must reach the CR as a literal go-template string so the driver can template it per-application; a stray brace would empty it with every doc-count test still green. The restore credential swap broke across flows. It replaced the source credentialsSecret with whatever the target declared, comparing no buckets, so a system-bucket backup restored into a legacy target kept the platform bucket against the tenant's own -s3-creds, and a legacy backup restored into a system-bucket target got cozy-backups-creds against the tenant bucket - both AccessDenied. Skip the swap when the source already names the platform-projected cozy-backups-creds (it outlives the source app, nothing to repair), and only adopt a target credential whose storage is on the same bucket as the archive. psmdbStorageS3 now reads .s3.bucket alongside .s3.credentialsSecret; TestPsmdbTargetCredentialsSecret covers the match, the cross-bucket refusal, and the empty-bucket no-op. Also drop the post-apply re-Get: the typed SSA Patch decodes the server's merged object back into the passed struct, so the precondition reads the injected storage from it instead of a follow-up Get that hit the informer cache and briefly reported Ready=False on the happy path. Signed-off-by: Andrey Kolkov Assisted-By: LLM --- api/apps/v1alpha1/mongodb/types.go | 2 +- docs/operations/backup-classes.md | 2 +- .../psmdbstrategy_controller.go | 132 +++++++++++------- .../psmdbstrategy_controller_test.go | 75 ++++++---- packages/apps/mongodb/README.md | 24 ++-- packages/apps/mongodb/values.schema.json | 2 +- packages/apps/mongodb/values.yaml | 2 +- .../tests/endpoint_form_test.yaml | 9 ++ .../tests/rendering_test.yaml | 38 +++-- .../system/mongodb-rd/cozyrds/mongodb.yaml | 2 +- 10 files changed, 183 insertions(+), 105 deletions(-) diff --git a/api/apps/v1alpha1/mongodb/types.go b/api/apps/v1alpha1/mongodb/types.go index 98b27e1f3..6741ea9b2 100644 --- a/api/apps/v1alpha1/mongodb/types.go +++ b/api/apps/v1alpha1/mongodb/types.go @@ -84,7 +84,7 @@ type Backup struct { // Cron schedule for automated backups. // +kubebuilder:default:="0 2 * * *" Schedule string `json:"schedule,omitempty"` - // Opt-in: when true the chart skips the -s3-creds Secret AND leaves spec.backup.storages unset; the cozy-default MongoDB BackupClass driver SSA-injects the S3 storage (bucket/endpoint/prefix/credentials from the platform system bucket) onto the live PerconaServerMongoDB at first BackupJob time. Tenants do not supply s3AccessKey/s3SecretKey/destinationPath/endpointURL; backups scope to / under the system bucket. + // Opt-in: back up to the platform system bucket without supplying S3 credentials. The cozy-default MongoDB BackupClass injects the storage at BackupJob time; tenants do not set s3AccessKey/s3SecretKey/destinationPath/endpointURL, and backups scope to /. See docs/operations/backup-classes.md. // +kubebuilder:default:=false UseSystemBucket bool `json:"useSystemBucket,omitempty"` } diff --git a/docs/operations/backup-classes.md b/docs/operations/backup-classes.md index 9b3f87e01..2c90ce387 100644 --- a/docs/operations/backup-classes.md +++ b/docs/operations/backup-classes.md @@ -115,7 +115,7 @@ backup: When `useSystemBucket: true`: - The chart-emitted `-s3-creds` Secret is no longer rendered, and the chart leaves `spec.backup.storages`, `spec.backup.tasks` and `spec.backup.pitr` unset on the `PerconaServerMongoDB`. -- On every BackupJob the driver SSA-injects the `s3-storage` entry from the strategy coordinates (bucket/endpoint from the platform system bucket, `credentialsSecret: cozy-backups-creds`, prefix `/`) under its own field manager, so a Flux re-render never reverts it and a later change to the coordinates is picked up on the next backup rather than frozen at the first. +- On every BackupJob the driver SSA-injects the `s3-storage` entry from the strategy coordinates (bucket/endpoint from the platform system bucket, `credentialsSecret: cozy-backups-creds`, prefix `/`) under its own field manager, so a Flux re-render never reverts it and a later change to the coordinates is picked up on the next backup rather than frozen at the first. `destinationPath`, `endpointURL`, `insecureSkipTLSVerify`, `s3AccessKey` and `s3SecretKey` are ignored in this mode. diff --git a/internal/backupcontroller/psmdbstrategy_controller.go b/internal/backupcontroller/psmdbstrategy_controller.go index 11de59cff..f7a5f61b7 100644 --- a/internal/backupcontroller/psmdbstrategy_controller.go +++ b/internal/backupcontroller/psmdbstrategy_controller.go @@ -245,15 +245,15 @@ func (r *BackupJobReconciler) reconcileMongoDB(ctx context.Context, j *backupsv1 // (endpoint, region, bucket re-provision) catches up rather than being // frozen at the first backup; when it is unset the driver never touches the // cluster, so a legacy app that ships its own static storage is left alone. - // The path prefix is deterministic (/), so re-applying the - // whole entry never splits the archive the way CNPG's serverName would. + // The path prefix is deterministic (/), so + // re-applying the whole entry never splits the archive the way CNPG's + // serverName would. if shouldInjectMongoDBSystemStorage(useSystemBucket, rendered) { - if err := r.applyMongoDBSystemStorage(ctx, j.Namespace, psmdbName, storageName, rendered.S3); err != nil { + injected, err := r.applyMongoDBSystemStorage(ctx, j.Namespace, psmdbName, storageName, rendered.S3) + if err != nil { return r.markBackupJobFailed(ctx, j, fmt.Sprintf("failed to inject system-bucket storage onto psmdb.percona.com/PerconaServerMongoDB %s/%s: %v", j.Namespace, psmdbName, err)) } - if err := r.Get(ctx, types.NamespacedName{Namespace: j.Namespace, Name: psmdbName}, cluster); err != nil { - return ctrl.Result{}, err - } + cluster = injected } if msg := psmdbBackupPrecondition(cluster, storageName); msg != "" { if psmdbBackupDeadlineExceeded(j.Status.StartedAt) { @@ -360,52 +360,65 @@ func psmdbBackupPrecondition(cluster *psmdbtypes.PerconaServerMongoDB, storageNa return "" } -// psmdbTargetCredentialsSecret returns the s3 credentialsSecret name the target -// cluster declares for its backup storage, so a restore authenticates with the -// TARGET's own credentials rather than the (possibly deleted) source's. It -// prefers the storage whose name the source backup used, then the chart's -// default storage, then — only when the cluster declares exactly one storage — -// that sole storage. Returns "" when nothing is resolvable, in which case the -// caller keeps the source reference. spec.backup.storages is decoded on demand -// from runtime.RawExtension (the partial type keeps only the key set for the -// precondition gate), so no upstream storage shape is mirrored here. -func psmdbTargetCredentialsSecret(cluster *psmdbtypes.PerconaServerMongoDB, preferredStorage string) string { +// psmdbTargetCredentialsSecret returns the s3 credentialsSecret the target +// cluster declares for a storage on the SAME bucket (wantBucket) as the source +// archive, so a restore authenticates with the TARGET's own credentials rather +// than the (possibly deleted) source's — but only when the target actually has +// access to that bucket. Requiring the bucket to match keeps a legacy→legacy +// restore on a shared bucket working while refusing to hand a cross-flow restore +// a credential for the wrong bucket (a system-bucket target's cozy-backups-creds +// against a legacy tenant bucket, or vice versa). It prefers the storage the +// source backup named, then the chart default, then — only when the cluster +// declares exactly one storage — that sole storage. Returns "" when nothing on +// wantBucket is resolvable (including when wantBucket is empty), in which case +// the caller keeps the source reference. spec.backup.storages is decoded on +// demand from runtime.RawExtension, so no upstream storage shape is mirrored. +func psmdbTargetCredentialsSecret(cluster *psmdbtypes.PerconaServerMongoDB, preferredStorage, wantBucket string) string { storages := cluster.Spec.Backup.Storages - if len(storages) == 0 { + if len(storages) == 0 || wantBucket == "" { + return "" + } + credOnWantBucket := func(raw runtime.RawExtension) string { + bucket, cred := psmdbStorageS3(raw) + if cred != "" && bucket == wantBucket { + return cred + } return "" } if preferredStorage != "" { - if cred := psmdbStorageS3CredentialsSecret(storages[preferredStorage]); cred != "" { + if cred := credOnWantBucket(storages[preferredStorage]); cred != "" { return cred } } - if cred := psmdbStorageS3CredentialsSecret(storages[psmdbDefaultStorageName]); cred != "" { + if cred := credOnWantBucket(storages[psmdbDefaultStorageName]); cred != "" { return cred } if len(storages) == 1 { for _, raw := range storages { - return psmdbStorageS3CredentialsSecret(raw) + return credOnWantBucket(raw) } } return "" } -// psmdbStorageS3CredentialsSecret extracts .s3.credentialsSecret from one -// psmdb spec.backup.storages entry. Returns "" for an empty/non-object entry, -// a non-s3 storage, or an entry that names no secret. -func psmdbStorageS3CredentialsSecret(raw runtime.RawExtension) string { +// psmdbStorageS3 extracts .s3.bucket and .s3.credentialsSecret from one psmdb +// spec.backup.storages entry. Returns ("","") for an empty/non-object entry or +// a non-s3 storage. The bucket lets the restore path refuse to hand a restore a +// credential for a storage on a different bucket than the archive. +func psmdbStorageS3(raw runtime.RawExtension) (bucket, credentialsSecret string) { if len(raw.Raw) == 0 { - return "" + return "", "" } var st struct { S3 struct { + Bucket string `json:"bucket"` CredentialsSecret string `json:"credentialsSecret"` } `json:"s3"` } if err := json.Unmarshal(raw.Raw, &st); err != nil { - return "" + return "", "" } - return st.S3.CredentialsSecret + return st.S3.Bucket, st.S3.CredentialsSecret } // shouldInjectMongoDBSystemStorage reports whether the driver must SSA-inject @@ -446,18 +459,22 @@ func buildMongoDBSystemStorageEntry(s3 *strategyv1alpha1.MongoDBStorageS3) map[s } // applyMongoDBSystemStorage SSA-injects the system-bucket S3 storage onto the -// live PerconaServerMongoDB's spec.backup.storages[storageName]. On the -// useSystemBucket flow the app chart omits the storage (it cannot know the -// platform bucket/endpoint at render time), so the driver owns this subtree -// via a dedicated field manager + ForceOwnership - the app's Helm/Flux manager -// never sets it, so re-renders leave the injected storage intact (mirrors the -// CNPG driver's spec.plugins patch). CredentialsSecret defaults to -// cozy-backups-creds, which the BackupJob reconciler projects into the -// namespace before dispatch. -func (r *BackupJobReconciler) applyMongoDBSystemStorage(ctx context.Context, namespace, psmdbName, storageName string, s3 *strategyv1alpha1.MongoDBStorageS3) error { +// live PerconaServerMongoDB's spec.backup.storages[storageName] and returns the +// server's post-apply view of the cluster. On the useSystemBucket flow the app +// chart omits the storage (it cannot know the platform bucket/endpoint at render +// time), so the driver owns this subtree via a dedicated field manager + +// ForceOwnership - the app's Helm/Flux manager never sets it, so re-renders +// leave the injected storage intact (mirrors the CNPG driver's spec.plugins +// patch). CredentialsSecret defaults to cozy-backups-creds, which the BackupJob +// reconciler projects into the namespace before dispatch. The typed Patch +// decodes the apiserver's response (the full merged object, storage included) +// back into the patch object, so the caller reads the injected storage straight +// from the return value instead of a follow-up Get, which would hit the +// informer cache and see the pre-patch cluster. +func (r *BackupJobReconciler) applyMongoDBSystemStorage(ctx context.Context, namespace, psmdbName, storageName string, s3 *strategyv1alpha1.MongoDBStorageS3) (*psmdbtypes.PerconaServerMongoDB, error) { entry, err := json.Marshal(buildMongoDBSystemStorageEntry(s3)) if err != nil { - return err + return nil, err } patch := &psmdbtypes.PerconaServerMongoDB{ TypeMeta: metav1.TypeMeta{APIVersion: psmdbtypes.GroupVersion.String(), Kind: "PerconaServerMongoDB"}, @@ -466,7 +483,10 @@ func (r *BackupJobReconciler) applyMongoDBSystemStorage(ctx context.Context, nam patch.Spec.Backup.Storages = map[string]runtime.RawExtension{ storageName: {Raw: entry}, } - return r.Patch(ctx, patch, client.Apply, client.FieldOwner(psmdbFieldManager), client.ForceOwnership) + if err := r.Patch(ctx, patch, client.Apply, client.FieldOwner(psmdbFieldManager), client.ForceOwnership); err != nil { + return nil, err + } + return patch, nil } // psmdbBackupDeadlineExceeded reports whether enough wall-clock time elapsed @@ -752,21 +772,27 @@ func (r *RestoreJobReconciler) reconcileMongoDBRestore(ctx context.Context, rest fmt.Sprintf("waiting for target psmdb.percona.com/PerconaServerMongoDB %s/%s to enable backups", target.Namespace, targetPSMDBName)) } - // Re-point the restore at the TARGET cluster's own S3 credentials. The - // backupSource carries the SOURCE cluster's credentialsSecret (read back from - // the source backup status / snapshot), which names the source release's - // -s3-creds Secret. That Secret is deleted together with the source app — - // exactly the disaster-recovery case backups exist for — so a restore into a - // fresh, differently-named target must not depend on it. The restore replays - // into the target, whose own -s3-creds Secret is guaranteed present - // (backup.enabled was gated just above) and grants access to the backup's - // bucket. The backupSource's bucket/prefix/endpoint still come from the - // source (that is where the archive lives); only the credential reference is - // swapped. Falls back to the source reference when the target declares no - // discoverable s3 credentials (in-place restore into the still-present source - // resolves to the same Secret, so this is a no-op there). - if source.S3 != nil { - if cred := psmdbTargetCredentialsSecret(targetCluster, source.StorageName); cred != "" && cred != source.S3.CredentialsSecret { + // Re-point the restore at the TARGET cluster's own S3 credentials. On the + // legacy flow the backupSource carries the SOURCE release's -s3-creds Secret, + // which is deleted together with the source app — exactly the disaster- + // recovery case backups exist for — so a restore into a fresh, differently- + // named target must not depend on it. Two guards keep the swap correct across + // flows: + // - Skip it when the source already names the platform-projected + // cozy-backups-creds (the useSystemBucket flow): that Secret is projected + // into the restore namespace and outlives the source app, so there is + // nothing to repair, and repointing it at a legacy target's own creds + // would send a platform-bucket restore at the wrong credentials. + // - Only adopt a target credential whose storage is on the SAME bucket as + // the archive (source.S3.Bucket). The backupSource's bucket/prefix/ + // endpoint always stay the source's (that is where the archive lives); + // swapping in a credential for a different bucket (a system-bucket + // target's cozy-backups-creds against a legacy tenant bucket) would fail + // the restore with AccessDenied. When no same-bucket target credential is + // discoverable the source reference is kept (in-place restore into the + // still-present source resolves to the same Secret, so this is a no-op). + if source.S3 != nil && source.S3.CredentialsSecret != psmdbDefaultCredentialsSecret { + if cred := psmdbTargetCredentialsSecret(targetCluster, source.StorageName, source.S3.Bucket); cred != "" && cred != source.S3.CredentialsSecret { logger.Debug("re-pointing MongoDB restore credentials at target cluster storage", "restorejob", restoreJob.Name, "from", source.S3.CredentialsSecret, "to", cred) source.S3.CredentialsSecret = cred diff --git a/internal/backupcontroller/psmdbstrategy_controller_test.go b/internal/backupcontroller/psmdbstrategy_controller_test.go index e836c856c..c4217aa03 100644 --- a/internal/backupcontroller/psmdbstrategy_controller_test.go +++ b/internal/backupcontroller/psmdbstrategy_controller_test.go @@ -125,8 +125,8 @@ func TestPsmdbBackupPrecondition(t *testing.T) { // deleted together with the source app. The selector prefers the source's // storage name, then the chart default, then a sole storage. func TestPsmdbTargetCredentialsSecret(t *testing.T) { - s3Storage := func(secret string) runtime.RawExtension { - return runtime.RawExtension{Raw: []byte(fmt.Sprintf(`{"type":"s3","s3":{"credentialsSecret":%q}}`, secret))} + s3Storage := func(bucket, secret string) runtime.RawExtension { + return runtime.RawExtension{Raw: []byte(fmt.Sprintf(`{"type":"s3","s3":{"bucket":%q,"credentialsSecret":%q}}`, bucket, secret))} } clusterWith := func(storages map[string]runtime.RawExtension) *psmdbtypes.PerconaServerMongoDB { return &psmdbtypes.PerconaServerMongoDB{ @@ -136,47 +136,68 @@ func TestPsmdbTargetCredentialsSecret(t *testing.T) { } } cases := []struct { - name string - storages map[string]runtime.RawExtension - preferred string - want string + name string + storages map[string]runtime.RawExtension + preferred string + wantBucket string + want string }{ { - name: "preferred storage wins", - storages: map[string]runtime.RawExtension{"s3-storage": s3Storage("target-creds"), "other": s3Storage("other-creds")}, - preferred: "s3-storage", - want: "target-creds", + name: "preferred storage on the source bucket wins", + storages: map[string]runtime.RawExtension{"s3-storage": s3Storage("shared", "target-creds"), "other": s3Storage("shared", "other-creds")}, + preferred: "s3-storage", + wantBucket: "shared", + want: "target-creds", }, { - name: "falls back to chart default when preferred absent", - storages: map[string]runtime.RawExtension{"s3-storage": s3Storage("target-creds")}, - preferred: "nonexistent", - want: "target-creds", + name: "falls back to chart default when preferred absent", + storages: map[string]runtime.RawExtension{"s3-storage": s3Storage("shared", "target-creds")}, + preferred: "nonexistent", + wantBucket: "shared", + want: "target-creds", }, { - name: "sole non-default storage is used", - storages: map[string]runtime.RawExtension{"custom": s3Storage("custom-creds")}, - want: "custom-creds", + name: "sole non-default storage on the source bucket is used", + storages: map[string]runtime.RawExtension{"custom": s3Storage("shared", "custom-creds")}, + wantBucket: "shared", + want: "custom-creds", }, { - name: "ambiguous (multiple, none default, no preferred) yields empty", - storages: map[string]runtime.RawExtension{"a": s3Storage("a-creds"), "b": s3Storage("b-creds")}, - want: "", + name: "different bucket is NOT adopted (cross-flow guard)", + storages: map[string]runtime.RawExtension{"s3-storage": s3Storage("platform-bucket", "cozy-backups-creds")}, + preferred: "s3-storage", + wantBucket: "tenant-bucket", + want: "", }, { - name: "no storages yields empty", - storages: nil, - want: "", + name: "empty wantBucket yields empty (unknown source bucket, no swap)", + storages: map[string]runtime.RawExtension{"s3-storage": s3Storage("shared", "target-creds")}, + preferred: "s3-storage", + wantBucket: "", + want: "", }, { - name: "non-s3 storage yields empty", - storages: map[string]runtime.RawExtension{"s3-storage": {Raw: []byte(`{"type":"azure","azure":{"container":"c"}}`)}}, - want: "", + name: "ambiguous (multiple, none default, no preferred) yields empty", + storages: map[string]runtime.RawExtension{"a": s3Storage("shared", "a-creds"), "b": s3Storage("shared", "b-creds")}, + wantBucket: "shared", + want: "", + }, + { + name: "no storages yields empty", + storages: nil, + wantBucket: "shared", + want: "", + }, + { + name: "non-s3 storage yields empty", + storages: map[string]runtime.RawExtension{"s3-storage": {Raw: []byte(`{"type":"azure","azure":{"container":"c"}}`)}}, + wantBucket: "shared", + want: "", }, } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { - if got := psmdbTargetCredentialsSecret(clusterWith(tc.storages), tc.preferred); got != tc.want { + if got := psmdbTargetCredentialsSecret(clusterWith(tc.storages), tc.preferred, tc.wantBucket); got != tc.want { t.Errorf("psmdbTargetCredentialsSecret: got %q want %q", got, tc.want) } }) diff --git a/packages/apps/mongodb/README.md b/packages/apps/mongodb/README.md index 81b96dc9a..8e7a147c9 100644 --- a/packages/apps/mongodb/README.md +++ b/packages/apps/mongodb/README.md @@ -247,18 +247,18 @@ Releases with `external: false`, and sharded releases in any configuration, are ### Backup parameters -| Name | Description | Type | Value | -| ------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------- | ----------------------------------- | -| `backup` | Backup configuration. | `object` | `{}` | -| `backup.enabled` | Enable regular backups. | `bool` | `false` | -| `backup.useSystemBucket` | Opt-in: when true the chart skips the -s3-creds Secret AND leaves spec.backup.storages unset; the cozy-default MongoDB BackupClass driver SSA-injects the S3 storage (bucket/endpoint/prefix/credentials from the platform system bucket) onto the live PerconaServerMongoDB at first BackupJob time. Tenants do not supply s3AccessKey/s3SecretKey/destinationPath/endpointURL; backups scope to / under the system bucket. | `bool` | `false` | -| `backup.schedule` | Cron schedule for automated backups. | `string` | `0 2 * * *` | -| `backup.retentionPolicy` | Retention policy (e.g. "30d"). | `string` | `30d` | -| `backup.destinationPath` | Destination path for backups (e.g. s3://bucket/path/). | `string` | `s3://bucket/path/to/folder/` | -| `backup.endpointURL` | S3 endpoint URL for uploads. | `string` | `http://minio-gateway-service:9000` | -| `backup.insecureSkipTLSVerify` | Skip TLS verification for the S3 endpoint (self-signed, e.g. in-cluster seaweedfs). | `bool` | `false` | -| `backup.s3AccessKey` | Access key for S3 authentication. | `string` | `""` | -| `backup.s3SecretKey` | Secret key for S3 authentication. | `string` | `""` | +| Name | Description | Type | Value | +| ------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------- | ----------------------------------- | +| `backup` | Backup configuration. | `object` | `{}` | +| `backup.enabled` | Enable regular backups. | `bool` | `false` | +| `backup.useSystemBucket` | Opt-in: back up to the platform system bucket without supplying S3 credentials. The cozy-default MongoDB BackupClass injects the storage at BackupJob time; tenants do not set s3AccessKey/s3SecretKey/destinationPath/endpointURL, and backups scope to /. See docs/operations/backup-classes.md. | `bool` | `false` | +| `backup.schedule` | Cron schedule for automated backups. | `string` | `0 2 * * *` | +| `backup.retentionPolicy` | Retention policy (e.g. "30d"). | `string` | `30d` | +| `backup.destinationPath` | Destination path for backups (e.g. s3://bucket/path/). | `string` | `s3://bucket/path/to/folder/` | +| `backup.endpointURL` | S3 endpoint URL for uploads. | `string` | `http://minio-gateway-service:9000` | +| `backup.insecureSkipTLSVerify` | Skip TLS verification for the S3 endpoint (self-signed, e.g. in-cluster seaweedfs). | `bool` | `false` | +| `backup.s3AccessKey` | Access key for S3 authentication. | `string` | `""` | +| `backup.s3SecretKey` | Secret key for S3 authentication. | `string` | `""` | ### Bootstrap (recovery) parameters diff --git a/packages/apps/mongodb/values.schema.json b/packages/apps/mongodb/values.schema.json index 1744abfd5..60abc75c2 100644 --- a/packages/apps/mongodb/values.schema.json +++ b/packages/apps/mongodb/values.schema.json @@ -313,7 +313,7 @@ "default": "0 2 * * *" }, "useSystemBucket": { - "description": "Opt-in: when true the chart skips the \u003crelease\u003e-s3-creds Secret AND leaves spec.backup.storages unset; the cozy-default MongoDB BackupClass driver SSA-injects the S3 storage (bucket/endpoint/prefix/credentials from the platform system bucket) onto the live PerconaServerMongoDB at first BackupJob time. Tenants do not supply s3AccessKey/s3SecretKey/destinationPath/endpointURL; backups scope to \u003cnamespace\u003e/\u003crelease\u003e under the system bucket.", + "description": "Opt-in: back up to the platform system bucket without supplying S3 credentials. The cozy-default MongoDB BackupClass injects the storage at BackupJob time; tenants do not set s3AccessKey/s3SecretKey/destinationPath/endpointURL, and backups scope to \u003cnamespace\u003e/\u003capplication\u003e. See docs/operations/backup-classes.md.", "type": "boolean", "default": false } diff --git a/packages/apps/mongodb/values.yaml b/packages/apps/mongodb/values.yaml index 3ccd36737..541b19fe4 100644 --- a/packages/apps/mongodb/values.yaml +++ b/packages/apps/mongodb/values.yaml @@ -155,7 +155,7 @@ databases: {} ## @typedef {struct} Backup - Backup configuration. ## @field {bool} enabled - Enable regular backups. -## @field {bool} [useSystemBucket] - Opt-in: when true the chart skips the -s3-creds Secret AND leaves spec.backup.storages unset; the cozy-default MongoDB BackupClass driver SSA-injects the S3 storage (bucket/endpoint/prefix/credentials from the platform system bucket) onto the live PerconaServerMongoDB at first BackupJob time. Tenants do not supply s3AccessKey/s3SecretKey/destinationPath/endpointURL; backups scope to / under the system bucket. +## @field {bool} [useSystemBucket] - Opt-in: back up to the platform system bucket without supplying S3 credentials. The cozy-default MongoDB BackupClass injects the storage at BackupJob time; tenants do not set s3AccessKey/s3SecretKey/destinationPath/endpointURL, and backups scope to /. See docs/operations/backup-classes.md. ## @field {string} [schedule] - Cron schedule for automated backups. ## @field {string} [retentionPolicy] - Retention policy (e.g. "30d"). ## @field {string} [destinationPath] - Destination path for backups (e.g. s3://bucket/path/). diff --git a/packages/system/backupstrategy-controller/tests/endpoint_form_test.yaml b/packages/system/backupstrategy-controller/tests/endpoint_form_test.yaml index 0c569ec2c..58821f3f3 100644 --- a/packages/system/backupstrategy-controller/tests/endpoint_form_test.yaml +++ b/packages/system/backupstrategy-controller/tests/endpoint_form_test.yaml @@ -19,6 +19,7 @@ templates: - templates/strategy-cnpg-default.yaml - templates/strategy-mariadb-default.yaml - templates/strategy-foundationdb-default.yaml + - templates/strategy-mongodb-default.yaml - templates/velero-bsl.yaml release: @@ -62,6 +63,10 @@ tests: path: spec.template.blobStoreConfiguration.urlParameters content: secure_connection=1 template: templates/strategy-foundationdb-default.yaml + - equal: + path: spec.template.s3.endpointUrl + value: https://s3.example.com:8333 + template: templates/strategy-mongodb-default.yaml - it: "http endpoint: MariaDB TLS off, FDB secure_connection=0, Etcd keeps scheme" set: @@ -79,6 +84,10 @@ tests: path: spec.template.blobStoreConfiguration.urlParameters content: secure_connection=0 template: templates/strategy-foundationdb-default.yaml + - equal: + path: spec.template.s3.endpointUrl + value: http://s3.example.com:8333 + template: templates/strategy-mongodb-default.yaml - it: "external S3 (provisionBucket:false): endpoint is used verbatim (no derivation)" set: diff --git a/packages/system/backupstrategy-controller/tests/rendering_test.yaml b/packages/system/backupstrategy-controller/tests/rendering_test.yaml index 4ef71df70..afd7aafbc 100644 --- a/packages/system/backupstrategy-controller/tests/rendering_test.yaml +++ b/packages/system/backupstrategy-controller/tests/rendering_test.yaml @@ -54,14 +54,13 @@ tests: count: 0 template: templates/strategy-altinity-default.yaml # MongoDB is gated like every sibling, and this count is the assertion - # that keeps the chart installable. Its Strategy needs no bucket - # coordinates (the S3 target lives on the MongoDB application's - # spec.backup, the driver only names the storage), so the gate is there - # purely for ordering: this chart ships its own CRDs as templates, Helm - # resolves the whole manifest through the RESTMapper before applying any - # of it, and one ungated Strategy CR makes the first install apply zero - # objects with "no matches for kind" and never recover. A count of 1 here - # is that bug, green, which is how it shipped once already. + # that keeps the chart installable. Its Strategy carries the system-bucket + # coordinates ($bucketName), so it needs the gate for the same reason the + # others do: this chart ships its own CRDs as templates, Helm resolves the + # whole manifest through the RESTMapper before applying any of it, and one + # ungated Strategy CR makes the first install apply zero objects with "no + # matches for kind" and never recover. A count of 1 here is that bug, + # green, which is how it shipped once already. - hasDocuments: count: 0 template: templates/strategy-mongodb-default.yaml @@ -163,6 +162,29 @@ tests: - hasDocuments: count: 1 template: templates/strategy-mongodb-default.yaml + - equal: + path: spec.template.s3.bucket + value: test-bucket + template: templates/strategy-mongodb-default.yaml + - equal: + path: spec.template.s3.credentialsSecret + value: cozy-backups-creds + template: templates/strategy-mongodb-default.yaml + - equal: + path: spec.template.s3.region + value: us-east-1 + template: templates/strategy-mongodb-default.yaml + - equal: + path: spec.template.s3.forcePathStyle + value: true + template: templates/strategy-mongodb-default.yaml + # prefix must reach the CR as a literal go-template string: Helm must NOT + # evaluate it, so the driver templates it per-application at BackupJob time. + # A stray brace would empty it with every doc-count assertion still green. + - equal: + path: spec.template.s3.prefix + value: "{{ .Application.metadata.namespace }}/{{ .Application.metadata.name }}" + template: templates/strategy-mongodb-default.yaml - hasDocuments: count: 1 template: templates/strategy-rabbitmq-default.yaml diff --git a/packages/system/mongodb-rd/cozyrds/mongodb.yaml b/packages/system/mongodb-rd/cozyrds/mongodb.yaml index 1cad05929..78745bd7b 100644 --- a/packages/system/mongodb-rd/cozyrds/mongodb.yaml +++ b/packages/system/mongodb-rd/cozyrds/mongodb.yaml @@ -8,7 +8,7 @@ spec: singular: mongodb plural: mongodbs openAPISchema: |- - {"title":"Chart Values","type":"object","properties":{"replicas":{"description":"Number of MongoDB replicas in replica set.","type":"integer","default":3},"resources":{"description":"Explicit CPU and memory configuration for each MongoDB replica. When omitted, the preset defined in `resourcesPreset` is applied.","type":"object","default":{},"properties":{"cpu":{"description":"CPU available to each replica.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"memory":{"description":"Memory (RAM) available to each replica.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true}}},"resourcesPreset":{"description":"Default sizing preset used when `resources` is omitted.","type":"string","default":"t1.small","enum":["t1.nano","t1.micro","t1.small","t1.medium","t1.large","t1.xlarge","t1.2xlarge","t1.4xlarge","c1.nano","c1.micro","c1.small","c1.medium","c1.large","c1.xlarge","c1.2xlarge","c1.4xlarge","s1.nano","s1.micro","s1.small","s1.medium","s1.large","s1.xlarge","s1.2xlarge","s1.4xlarge","u1.nano","u1.micro","u1.small","u1.medium","u1.large","u1.xlarge","u1.2xlarge","u1.4xlarge","m1.nano","m1.micro","m1.small","m1.medium","m1.large","m1.xlarge","m1.2xlarge","m1.4xlarge","nano","micro","small","medium","large","xlarge","2xlarge"]},"size":{"description":"Persistent Volume Claim size available for application data.","default":"10Gi","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"storageClass":{"description":"StorageClass used to store the data.","type":"string","default":"","x-kubernetes-validations":[{"rule":"self == oldSelf","message":"storageClass is immutable"}],"x-cozystack-options":{"source":"storageclass"}},"external":{"description":"Enable external access from outside the cluster.","type":"boolean","default":false},"version":{"description":"MongoDB major version to deploy.","type":"string","default":"v8","enum":["v8","v7","v6"]},"sharding":{"description":"Enable sharded cluster mode. When disabled, deploys a replica set.","type":"boolean","default":false},"shardingConfig":{"description":"Configuration for sharded cluster mode.","type":"object","default":{},"required":["configServerSize","configServers","mongos"],"properties":{"configServerSize":{"description":"PVC size for config servers.","default":"3Gi","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"configServers":{"description":"Number of config server replicas.","type":"integer","default":3},"mongos":{"description":"Number of mongos router replicas.","type":"integer","default":2},"shards":{"description":"List of shard configurations.","type":"array","default":[{"name":"rs0","replicas":3,"size":"10Gi"}],"items":{"type":"object","required":["name","replicas","size"],"properties":{"name":{"description":"Shard name.","type":"string"},"replicas":{"description":"Number of replicas in this shard.","type":"integer"},"size":{"description":"PVC size for this shard.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true}}}}}},"users":{"description":"Users configuration map.","type":"object","default":{},"additionalProperties":{"type":"object","properties":{"password":{"description":"Password for the user (auto-generated if omitted).","type":"string"}}}},"databases":{"description":"Databases configuration map.","type":"object","default":{},"additionalProperties":{"type":"object","properties":{"roles":{"description":"Roles assigned to users.","type":"object","properties":{"admin":{"description":"List of users with admin privileges (readWrite + dbAdmin).","type":"array","items":{"type":"string"}},"readonly":{"description":"List of users with read-only privileges.","type":"array","items":{"type":"string"}}}}}}},"backup":{"description":"Backup configuration.","type":"object","default":{},"required":["enabled"],"properties":{"destinationPath":{"description":"Destination path for backups (e.g. s3://bucket/path/).","type":"string","default":"s3://bucket/path/to/folder/"},"enabled":{"description":"Enable regular backups.","type":"boolean","default":false},"endpointURL":{"description":"S3 endpoint URL for uploads.","type":"string","default":"http://minio-gateway-service:9000"},"insecureSkipTLSVerify":{"description":"Skip TLS verification for the S3 endpoint (self-signed, e.g. in-cluster seaweedfs).","type":"boolean","default":false},"retentionPolicy":{"description":"Retention policy (e.g. \"30d\").","type":"string","default":"30d"},"s3AccessKey":{"description":"Access key for S3 authentication.","type":"string","default":""},"s3SecretKey":{"description":"Secret key for S3 authentication.","type":"string","default":""},"schedule":{"description":"Cron schedule for automated backups.","type":"string","default":"0 2 * * *"},"useSystemBucket":{"description":"Opt-in: when true the chart skips the -s3-creds Secret AND leaves spec.backup.storages unset; the cozy-default MongoDB BackupClass driver SSA-injects the S3 storage (bucket/endpoint/prefix/credentials from the platform system bucket) onto the live PerconaServerMongoDB at first BackupJob time. Tenants do not supply s3AccessKey/s3SecretKey/destinationPath/endpointURL; backups scope to / under the system bucket.","type":"boolean","default":false}}},"bootstrap":{"description":"Bootstrap configuration.","type":"object","default":{},"required":["backupName","enabled"],"properties":{"backupName":{"description":"Name of backup to restore from.","type":"string","default":""},"enabled":{"description":"Whether to restore from a backup.","type":"boolean","default":false},"recoveryTime":{"description":"Timestamp for point-in-time recovery; empty means latest.","type":"string","default":""}}}}} + {"title":"Chart Values","type":"object","properties":{"replicas":{"description":"Number of MongoDB replicas in replica set.","type":"integer","default":3},"resources":{"description":"Explicit CPU and memory configuration for each MongoDB replica. When omitted, the preset defined in `resourcesPreset` is applied.","type":"object","default":{},"properties":{"cpu":{"description":"CPU available to each replica.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"memory":{"description":"Memory (RAM) available to each replica.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true}}},"resourcesPreset":{"description":"Default sizing preset used when `resources` is omitted.","type":"string","default":"t1.small","enum":["t1.nano","t1.micro","t1.small","t1.medium","t1.large","t1.xlarge","t1.2xlarge","t1.4xlarge","c1.nano","c1.micro","c1.small","c1.medium","c1.large","c1.xlarge","c1.2xlarge","c1.4xlarge","s1.nano","s1.micro","s1.small","s1.medium","s1.large","s1.xlarge","s1.2xlarge","s1.4xlarge","u1.nano","u1.micro","u1.small","u1.medium","u1.large","u1.xlarge","u1.2xlarge","u1.4xlarge","m1.nano","m1.micro","m1.small","m1.medium","m1.large","m1.xlarge","m1.2xlarge","m1.4xlarge","nano","micro","small","medium","large","xlarge","2xlarge"]},"size":{"description":"Persistent Volume Claim size available for application data.","default":"10Gi","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"storageClass":{"description":"StorageClass used to store the data.","type":"string","default":"","x-kubernetes-validations":[{"rule":"self == oldSelf","message":"storageClass is immutable"}],"x-cozystack-options":{"source":"storageclass"}},"external":{"description":"Enable external access from outside the cluster.","type":"boolean","default":false},"version":{"description":"MongoDB major version to deploy.","type":"string","default":"v8","enum":["v8","v7","v6"]},"sharding":{"description":"Enable sharded cluster mode. When disabled, deploys a replica set.","type":"boolean","default":false},"shardingConfig":{"description":"Configuration for sharded cluster mode.","type":"object","default":{},"required":["configServerSize","configServers","mongos"],"properties":{"configServerSize":{"description":"PVC size for config servers.","default":"3Gi","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"configServers":{"description":"Number of config server replicas.","type":"integer","default":3},"mongos":{"description":"Number of mongos router replicas.","type":"integer","default":2},"shards":{"description":"List of shard configurations.","type":"array","default":[{"name":"rs0","replicas":3,"size":"10Gi"}],"items":{"type":"object","required":["name","replicas","size"],"properties":{"name":{"description":"Shard name.","type":"string"},"replicas":{"description":"Number of replicas in this shard.","type":"integer"},"size":{"description":"PVC size for this shard.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true}}}}}},"users":{"description":"Users configuration map.","type":"object","default":{},"additionalProperties":{"type":"object","properties":{"password":{"description":"Password for the user (auto-generated if omitted).","type":"string"}}}},"databases":{"description":"Databases configuration map.","type":"object","default":{},"additionalProperties":{"type":"object","properties":{"roles":{"description":"Roles assigned to users.","type":"object","properties":{"admin":{"description":"List of users with admin privileges (readWrite + dbAdmin).","type":"array","items":{"type":"string"}},"readonly":{"description":"List of users with read-only privileges.","type":"array","items":{"type":"string"}}}}}}},"backup":{"description":"Backup configuration.","type":"object","default":{},"required":["enabled"],"properties":{"destinationPath":{"description":"Destination path for backups (e.g. s3://bucket/path/).","type":"string","default":"s3://bucket/path/to/folder/"},"enabled":{"description":"Enable regular backups.","type":"boolean","default":false},"endpointURL":{"description":"S3 endpoint URL for uploads.","type":"string","default":"http://minio-gateway-service:9000"},"insecureSkipTLSVerify":{"description":"Skip TLS verification for the S3 endpoint (self-signed, e.g. in-cluster seaweedfs).","type":"boolean","default":false},"retentionPolicy":{"description":"Retention policy (e.g. \"30d\").","type":"string","default":"30d"},"s3AccessKey":{"description":"Access key for S3 authentication.","type":"string","default":""},"s3SecretKey":{"description":"Secret key for S3 authentication.","type":"string","default":""},"schedule":{"description":"Cron schedule for automated backups.","type":"string","default":"0 2 * * *"},"useSystemBucket":{"description":"Opt-in: back up to the platform system bucket without supplying S3 credentials. The cozy-default MongoDB BackupClass injects the storage at BackupJob time; tenants do not set s3AccessKey/s3SecretKey/destinationPath/endpointURL, and backups scope to /. See docs/operations/backup-classes.md.","type":"boolean","default":false}}},"bootstrap":{"description":"Bootstrap configuration.","type":"object","default":{},"required":["backupName","enabled"],"properties":{"backupName":{"description":"Name of backup to restore from.","type":"string","default":""},"enabled":{"description":"Whether to restore from a backup.","type":"boolean","default":false},"recoveryTime":{"description":"Timestamp for point-in-time recovery; empty means latest.","type":"string","default":""}}}}} release: prefix: mongodb- labels: From 47fe7c963045ab1a51d8518f2b9ecfdbb9ae4ca5 Mon Sep 17 00:00:00 2001 From: Andrey Kolkov Date: Sat, 12 Sep 2026 11:25:25 +0400 Subject: [PATCH 0007/1280] test(mongodb): pin the restore credential swap and document the opt-out The restore-time decision to re-point a backup's credentialsSecret at the target cluster lived inline in reconcileMongoDBRestore with no test, so the same-bucket guard that keeps a cross-flow restore from authenticating against the wrong bucket could be dropped unnoticed. Extract it into mongodbRestoreCredentialsSecret and cover all four {legacy,system}x{legacy,system} combinations; neutralising the bucket match now reddens the suite. The projected-secret skip is kept as well: a target storage sharing the platform bucket but naming a different secret is better restored with the platform-projected cozy-backups-creds than with that secret. Document the reverse toggle: flipping useSystemBucket true->false leaves the driver-injected s3-storage on the live PerconaServerMongoDB under the driver's field manager, which the chart does not own and never prunes. It is inert once backups are disabled; the operator must delete it by hand to return the release to the legacy flow. Signed-off-by: Andrey Kolkov Assisted-By: LLM --- docs/operations/backup-classes.md | 2 + .../psmdbstrategy_controller.go | 65 ++++++++++++------ .../psmdbstrategy_controller_test.go | 66 +++++++++++++++++++ 3 files changed, 112 insertions(+), 21 deletions(-) diff --git a/docs/operations/backup-classes.md b/docs/operations/backup-classes.md index 2c90ce387..c781ff6f0 100644 --- a/docs/operations/backup-classes.md +++ b/docs/operations/backup-classes.md @@ -121,6 +121,8 @@ When `useSystemBucket: true`: Because the chart drops `spec.backup.tasks` and `spec.backup.pitr`, the psmdb operator's own scheduled backups and oplog PITR do **not** run on this flow — `backup.schedule` and `backup.retentionPolicy` stay in the schema for the default flow but have no effect here, and the `recoveryTime` PITR restores described below are not available. Migrate scheduled backups to a `backups.cozystack.io/Plan` against `cozy-default` instead. **Flipping this flag on a running app** removes the storage, tasks and pitr the app had, so a release that was taking scheduled backups + PITR before the flip stops until a `Plan` takes over. +**Opting back out** (`useSystemBucket` true→false) is not automatic in reverse: the driver stops injecting, but the `s3-storage` entry it already applied stays on the live `PerconaServerMongoDB` under the driver's own field manager (`cozystack-psmdb-backup-driver`) — the chart does not own it and so never prunes it. It is inert once `backup.enabled=false`; to fully return a release to the legacy flow, delete that storage entry from the `PerconaServerMongoDB` by hand before re-declaring the tenant's own `backup.*` S3 values. + ### Point-in-time recovery (MongoDB) psmdb records an oplog stream between logical backups. A MongoDB `RestoreJob` recovers to a timestamp via `spec.options.recoveryTime` — the same option name and RFC3339 format the Postgres/CNPG driver uses, so the two are uniform: diff --git a/internal/backupcontroller/psmdbstrategy_controller.go b/internal/backupcontroller/psmdbstrategy_controller.go index f7a5f61b7..c61a94113 100644 --- a/internal/backupcontroller/psmdbstrategy_controller.go +++ b/internal/backupcontroller/psmdbstrategy_controller.go @@ -401,6 +401,39 @@ func psmdbTargetCredentialsSecret(cluster *psmdbtypes.PerconaServerMongoDB, pref return "" } +// mongodbRestoreCredentialsSecret picks the s3 credentialsSecret a restore into +// targetCluster should authenticate with. It returns the source's own reference +// unless a safe swap applies, so the caller can compare and re-point only when +// the value actually changes. Two guards make the swap correct across the legacy +// and useSystemBucket flows: +// - When the source already names the platform-projected cozy-backups-creds +// (useSystemBucket), keep it: that Secret is projected into the restore +// namespace and outlives the source app, so there is nothing to repair, and +// repointing it at a legacy target's own creds would send a platform-bucket +// restore at the wrong credentials. +// - Otherwise adopt a target credential only when its storage is on the SAME +// bucket as the archive (source.S3.Bucket): the backupSource's bucket stays +// the source's, so a credential for a different bucket (a system-bucket +// target's cozy-backups-creds against a legacy tenant bucket) would fail the +// restore with AccessDenied. When no same-bucket target credential is +// discoverable the source reference is kept (in-place restore into the +// still-present source resolves to the same Secret, so this is a no-op). +// +// Returns "" only when the source carries no s3 reference at all. +func mongodbRestoreCredentialsSecret(source *psmdbtypes.BackupSource, targetCluster *psmdbtypes.PerconaServerMongoDB) string { + if source == nil || source.S3 == nil { + return "" + } + current := source.S3.CredentialsSecret + if current == psmdbDefaultCredentialsSecret { + return current + } + if cred := psmdbTargetCredentialsSecret(targetCluster, source.StorageName, source.S3.Bucket); cred != "" { + return cred + } + return current +} + // psmdbStorageS3 extracts .s3.bucket and .s3.credentialsSecret from one psmdb // spec.backup.storages entry. Returns ("","") for an empty/non-object entry or // a non-s3 storage. The bucket lets the restore path refuse to hand a restore a @@ -772,27 +805,17 @@ func (r *RestoreJobReconciler) reconcileMongoDBRestore(ctx context.Context, rest fmt.Sprintf("waiting for target psmdb.percona.com/PerconaServerMongoDB %s/%s to enable backups", target.Namespace, targetPSMDBName)) } - // Re-point the restore at the TARGET cluster's own S3 credentials. On the - // legacy flow the backupSource carries the SOURCE release's -s3-creds Secret, - // which is deleted together with the source app — exactly the disaster- - // recovery case backups exist for — so a restore into a fresh, differently- - // named target must not depend on it. Two guards keep the swap correct across - // flows: - // - Skip it when the source already names the platform-projected - // cozy-backups-creds (the useSystemBucket flow): that Secret is projected - // into the restore namespace and outlives the source app, so there is - // nothing to repair, and repointing it at a legacy target's own creds - // would send a platform-bucket restore at the wrong credentials. - // - Only adopt a target credential whose storage is on the SAME bucket as - // the archive (source.S3.Bucket). The backupSource's bucket/prefix/ - // endpoint always stay the source's (that is where the archive lives); - // swapping in a credential for a different bucket (a system-bucket - // target's cozy-backups-creds against a legacy tenant bucket) would fail - // the restore with AccessDenied. When no same-bucket target credential is - // discoverable the source reference is kept (in-place restore into the - // still-present source resolves to the same Secret, so this is a no-op). - if source.S3 != nil && source.S3.CredentialsSecret != psmdbDefaultCredentialsSecret { - if cred := psmdbTargetCredentialsSecret(targetCluster, source.StorageName, source.S3.Bucket); cred != "" && cred != source.S3.CredentialsSecret { + // Re-point the restore at the TARGET cluster's own S3 credentials when a safe + // swap applies. On the legacy flow the backupSource carries the SOURCE + // release's -s3-creds Secret, which is deleted together with the source app — + // exactly the disaster-recovery case backups exist for — so a restore into a + // fresh, differently-named target must not depend on it. mongodbRestoreCreden- + // tialsSecret encodes the cross-flow guards (skip when the source already + // names the projected cozy-backups-creds; adopt a target credential only on + // the same bucket as the archive); it is unit-tested across the four flow + // combinations. + if source.S3 != nil { + if cred := mongodbRestoreCredentialsSecret(source, targetCluster); cred != "" && cred != source.S3.CredentialsSecret { logger.Debug("re-pointing MongoDB restore credentials at target cluster storage", "restorejob", restoreJob.Name, "from", source.S3.CredentialsSecret, "to", cred) source.S3.CredentialsSecret = cred diff --git a/internal/backupcontroller/psmdbstrategy_controller_test.go b/internal/backupcontroller/psmdbstrategy_controller_test.go index c4217aa03..93e7c7075 100644 --- a/internal/backupcontroller/psmdbstrategy_controller_test.go +++ b/internal/backupcontroller/psmdbstrategy_controller_test.go @@ -204,6 +204,72 @@ func TestPsmdbTargetCredentialsSecret(t *testing.T) { } } +// TestMongoDBRestoreCredentialsSecret pins the restore credential-swap decision +// across the four {legacy,system}×{legacy,system} flow combinations, so neither +// cross-flow guard can be dropped unnoticed: the projected-secret skip (a system +// source keeps cozy-backups-creds rather than adopting a legacy target's own +// Secret) and the same-bucket match (a legacy source is not handed a credential +// for a bucket its archive does not live in). +func TestMongoDBRestoreCredentialsSecret(t *testing.T) { + s3Storage := func(bucket, secret string) runtime.RawExtension { + return runtime.RawExtension{Raw: []byte(fmt.Sprintf(`{"type":"s3","s3":{"bucket":%q,"credentialsSecret":%q}}`, bucket, secret))} + } + target := func(storages map[string]runtime.RawExtension) *psmdbtypes.PerconaServerMongoDB { + return &psmdbtypes.PerconaServerMongoDB{ + Spec: psmdbtypes.PerconaServerMongoDBSpec{ + Backup: psmdbtypes.PerconaServerMongoDBBackupConfig{Storages: storages}, + }, + } + } + src := func(bucket, cred string) *psmdbtypes.BackupSource { + return &psmdbtypes.BackupSource{StorageName: "s3-storage", S3: &psmdbtypes.BackupStorageS3{Bucket: bucket, CredentialsSecret: cred}} + } + cases := []struct { + name string + source *psmdbtypes.BackupSource + target *psmdbtypes.PerconaServerMongoDB + want string + }{ + { + name: "legacy source -> legacy target on the same bucket: swap to target creds (DR after source delete)", + source: src("tenant-bucket", "src-s3-creds"), + target: target(map[string]runtime.RawExtension{"s3-storage": s3Storage("tenant-bucket", "target-s3-creds")}), + want: "target-s3-creds", + }, + { + name: "legacy source -> legacy target on a different bucket: keep source creds (no cross-bucket swap)", + source: src("tenant-bucket", "src-s3-creds"), + target: target(map[string]runtime.RawExtension{"s3-storage": s3Storage("other-bucket", "target-s3-creds")}), + want: "src-s3-creds", + }, + { + name: "system source -> legacy target: keep projected cozy-backups-creds (outlives source, reads the platform bucket)", + source: src("cozy-backups-PLATFORM", "cozy-backups-creds"), + target: target(map[string]runtime.RawExtension{"s3-storage": s3Storage("tenant-bucket", "target-s3-creds")}), + want: "cozy-backups-creds", + }, + { + name: "legacy source -> system-bucket target: keep source creds (target storage is on the platform bucket, not the archive's)", + source: src("tenant-bucket", "src-s3-creds"), + target: target(map[string]runtime.RawExtension{"s3-storage": s3Storage("cozy-backups-PLATFORM", "cozy-backups-creds")}), + want: "src-s3-creds", + }, + { + name: "no s3 source: empty (caller keeps the source reference)", + source: &psmdbtypes.BackupSource{StorageName: "s3-storage"}, + target: target(map[string]runtime.RawExtension{"s3-storage": s3Storage("tenant-bucket", "target-s3-creds")}), + want: "", + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + if got := mongodbRestoreCredentialsSecret(tc.source, tc.target); got != tc.want { + t.Errorf("mongodbRestoreCredentialsSecret: got %q want %q", got, tc.want) + } + }) + } +} + // --------------------------------------------------------------------------- // Backup-side ensure idempotency + CR shape // --------------------------------------------------------------------------- From 1d05dafb2edcd0dd401d9322e3ba4f5b2a28cc8a Mon Sep 17 00:00:00 2001 From: Andrey Kolkov Date: Mon, 14 Sep 2026 18:06:51 +0400 Subject: [PATCH 0008/1280] fix(mongodb): own and prune the system-bucket archive, and heal the restore read path MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two correctness gaps on the useSystemBucket flow. Retention. Gating spec.backup.tasks out of the chart also dropped the keep that psmdb task retention used, and an on-demand PerconaServerMongoDBBackup is not covered by task retention, so nothing pruned the shared cozy-backups bucket — a retention-swept Plan grew it unboundedly for every tenant at once. Own the archive the way the Redis/Rabbitmq drivers own theirs: stamp the operator's percona.com/delete-backup finalizer onto the backups minted on this flow, and on Cozystack Backup deletion delete that operator CR and wait for the finalizer to free the object before releasing. A legacy backup (tenant's own bucket) keeps the pre-existing hands-off no-op. Adds the delete verb on perconaservermongodbbackups and a skip-artifact-cleanup escape hatch for a wedged operator, matching the sibling drivers. Also drops the unused update verb from the psmdb cluster RBAC (server-side apply is a patch, not an update). Restore. resolveMongoDBBackupSource returned early off the live operator Backup CR whenever it reported a destination, copying status.s3 as-is. On this flow the operator can echo a destination with status.s3 empty (the storage was injected, not declared), and the target has no declared storage to resolve from either, so the restore stranded with no coordinates. Backfill a missing live S3 block from the snapshot the BackupJob recorded. Also correct the precondition godoc: the pbm agents start on spec.backup.enabled alone; the declared storage is required by the backup CR's resolution, not by the agents. Assisted-By: LLM Signed-off-by: Andrey Kolkov --- docs/operations/backup-classes.md | 2 + .../backupcontroller/backup_controller.go | 20 +- .../psmdbstrategy_controller.go | 130 +++++++- .../psmdbstrategy_controller_test.go | 298 +++++++++++++++++- .../templates/rbac.yaml | 26 +- 5 files changed, 441 insertions(+), 35 deletions(-) diff --git a/docs/operations/backup-classes.md b/docs/operations/backup-classes.md index c781ff6f0..732482cbb 100644 --- a/docs/operations/backup-classes.md +++ b/docs/operations/backup-classes.md @@ -121,6 +121,8 @@ When `useSystemBucket: true`: Because the chart drops `spec.backup.tasks` and `spec.backup.pitr`, the psmdb operator's own scheduled backups and oplog PITR do **not** run on this flow — `backup.schedule` and `backup.retentionPolicy` stay in the schema for the default flow but have no effect here, and the `recoveryTime` PITR restores described below are not available. Migrate scheduled backups to a `backups.cozystack.io/Plan` against `cozy-default` instead. **Flipping this flag on a running app** removes the storage, tasks and pitr the app had, so a release that was taking scheduled backups + PITR before the flip stops until a `Plan` takes over. +Dropping `spec.backup.tasks` also drops the psmdb `keep` retention it carried, so on this flow **the driver owns the archive** the way the Rabbitmq/Redis drivers own theirs (an on-demand `PerconaServerMongoDBBackup` is not covered by psmdb task retention). The driver stamps the operator's `percona.com/delete-backup` finalizer onto each backup it mints here, and deleting a Cozystack `Backup` (a retention-pruned `Plan`, or a manual delete) deletes that `PerconaServerMongoDBBackup` CR — whose finalizer removes the pbm object from the shared bucket before the `Backup` is released, so a Plan does not accumulate objects in `cozy-backups`. A legacy backup writes to the tenant's own bucket and keeps the pre-existing hands-off contract (its lifecycle stays the tenant's / operator's; nothing is deleted on `Backup` removal). If the operator is down or storage is unreachable the `Backup` stays `Terminating` (a visible signal); annotate it `backups.cozystack.io/skip-artifact-cleanup: "true"` to release it and leave the object for a bucket lifecycle policy to reclaim. + **Opting back out** (`useSystemBucket` true→false) is not automatic in reverse: the driver stops injecting, but the `s3-storage` entry it already applied stays on the live `PerconaServerMongoDB` under the driver's own field manager (`cozystack-psmdb-backup-driver`) — the chart does not own it and so never prunes it. It is inert once `backup.enabled=false`; to fully return a release to the legacy flow, delete that storage entry from the `PerconaServerMongoDB` by hand before re-declaring the tenant's own `backup.*` S3 values. ### Point-in-time recovery (MongoDB) diff --git a/internal/backupcontroller/backup_controller.go b/internal/backupcontroller/backup_controller.go index 75d8dd581..1a8ec0b40 100644 --- a/internal/backupcontroller/backup_controller.go +++ b/internal/backupcontroller/backup_controller.go @@ -138,17 +138,15 @@ func (r *BackupReconciler) cleanupOnDelete(ctx context.Context, backup *backupsv // Mirrors the Altinity branch's "we do not own S3" stance. return ctrl.Result{}, nil case strategyv1alpha1.MongoDBStrategyKind: - // Cozystack Backup deletion does NOT delete the operator-side - // psmdb.percona.com/PerconaServerMongoDBBackup CR or the backing S3 - // archive. Lifecycle of that CR is owned by the psmdb operator's - // retention and by tenants / explicit teardown flows; the - // controller's RBAC has no delete verb on - // psmdb.percona.com/perconaservermongodbbackups for that reason. Same - // "we do not own the archive" contract as Altinity / MariaDB / FDB — - // the explicit branch guards the seam against a future driver refactor - // that might incidentally stamp velero.io/backup-name onto MongoDB - // driverMetadata via a shared helper. - return ctrl.Result{}, nil + // Split by flow (see cleanupMongoDBBackup). A legacy backup writes to the + // tenant's own bucket and its lifecycle stays the tenant's / psmdb + // operator's — that branch is a no-op, the same "we do not own the + // archive" contract as Altinity / MariaDB / FDB. A useSystemBucket backup + // lands in the shared cozy-backups bucket with no psmdb task retention to + // prune it, so the driver OWNS it: this deletes the operator + // PerconaServerMongoDBBackup CR and waits for its delete-backup finalizer + // to free the object before the Backup is removed (like Redis / Rabbitmq). + return r.cleanupMongoDBBackup(ctx, backup) case strategyv1alpha1.FoundationDBStrategyKind: // Cozystack Backup deletion does NOT delete the operator-side // foundationdb.org/FoundationDBBackup CR. That CR drives a diff --git a/internal/backupcontroller/psmdbstrategy_controller.go b/internal/backupcontroller/psmdbstrategy_controller.go index c61a94113..e6f4831be 100644 --- a/internal/backupcontroller/psmdbstrategy_controller.go +++ b/internal/backupcontroller/psmdbstrategy_controller.go @@ -68,6 +68,29 @@ const ( psmdbBackupNamespaceKey = "psmdb.percona.com/backup-namespace" psmdbDestinationKey = "psmdb.percona.com/destination" + // psmdbUseSystemBucketKey records, on the Cozystack Backup, that the archive + // lives in the shared platform bucket (the useSystemBucket flow). The cleanup + // path keys off it: only system-bucket archives are the driver's to prune, so + // a legacy backup (tenant's own bucket, tenant-owned lifecycle) stays a no-op + // on deletion exactly as before. + psmdbUseSystemBucketKey = "backups.cozystack.io/use-system-bucket" + + // psmdbDeleteBackupFinalizer is the psmdb-operator finalizer that removes the + // pbm archive from object storage when its PerconaServerMongoDBBackup CR is + // deleted. The driver stamps it onto the CRs it mints on the useSystemBucket + // flow so that pruning a Cozystack Backup (Plan retention or manual delete) + // also frees the object it wrote to the shared bucket. Without it a + // retention-pruned Plan would grow cozy-backups unboundedly for every tenant + // at once, since the system-bucket flow ships no psmdb task retention (the + // chart's tasks[].keep is gated out) to prune it. + psmdbDeleteBackupFinalizer = "percona.com/delete-backup" + + // psmdbSkipArtifactCleanupAnnotation, on a Cozystack Backup, releases it from + // Terminating without waiting for the operator to prune the archive — an + // escape hatch for a wedged delete (operator down, storage unreachable). The + // object is then left in the bucket. Mirrors the Redis/Rabbitmq drivers. + psmdbSkipArtifactCleanupAnnotation = "backups.cozystack.io/skip-artifact-cleanup" + // Polling cadence for the operator Backup/Restore lifecycle. psmdbPollInterval = 5 * time.Second @@ -264,7 +287,7 @@ func (r *BackupJobReconciler) reconcileMongoDB(ctx context.Context, j *backupsv1 return r.requeueMongoDBBackupWaiting(ctx, j, "PerconaServerMongoDBBackupsDisabled", msg) } - mdbBackup, err := r.ensureMongoDBBackup(ctx, j, psmdbName, storageName, rendered) + mdbBackup, err := r.ensureMongoDBBackup(ctx, j, psmdbName, storageName, rendered, useSystemBucket) if err != nil { return r.markBackupJobFailed(ctx, j, fmt.Sprintf("failed to ensure psmdb.percona.com/PerconaServerMongoDBBackup: %v", err)) } @@ -347,9 +370,12 @@ func (r *BackupJobReconciler) requeueMongoDBBackupWaiting(ctx context.Context, j } // psmdbBackupPrecondition reports why a cluster is not ready to service an -// on-demand backup, or "" when it is. The operator only runs pbm agents (and -// therefore only completes PerconaServerMongoDBBackup CRs) when backups are -// enabled and the named storage is declared. +// on-demand backup, or "" when it is. Two independent conditions must hold, for +// two different reasons: the operator runs the pbm agents only when +// spec.backup.enabled=true, and a PerconaServerMongoDBBackup that names a +// storage absent from spec.backup.storages fails resolution rather than +// running. (Agent startup itself is gated on Enabled alone; the storage is +// required by the backup CR, not by the agents.) func psmdbBackupPrecondition(cluster *psmdbtypes.PerconaServerMongoDB, storageName string) string { if !cluster.Spec.Backup.Enabled { return "spec.backup.enabled is false; on-demand backups need the percona-backup-mongodb agents running" @@ -536,7 +562,7 @@ func psmdbBackupDeadlineExceeded(startedAt *metav1.Time) bool { // ensureMongoDBBackup creates a one-shot PerconaServerMongoDBBackup CR labelled // with the BackupJob, or returns the existing one if a previous reconcile // already created it. Idempotency relies on the OwningJob labels. -func (r *BackupJobReconciler) ensureMongoDBBackup(ctx context.Context, j *backupsv1alpha1.BackupJob, clusterName, storageName string, rendered *strategyv1alpha1.MongoDBTemplate) (*psmdbtypes.PerconaServerMongoDBBackup, error) { +func (r *BackupJobReconciler) ensureMongoDBBackup(ctx context.Context, j *backupsv1alpha1.BackupJob, clusterName, storageName string, rendered *strategyv1alpha1.MongoDBTemplate, useSystemBucket bool) (*psmdbtypes.PerconaServerMongoDBBackup, error) { existing, err := r.findMongoDBBackupForJob(ctx, j) if err != nil { return nil, err @@ -565,6 +591,14 @@ func (r *BackupJobReconciler) ensureMongoDBBackup(ctx context.Context, j *backup lvl := *rendered.CompressionLevel obj.Spec.CompressionLevel = &lvl } + if useSystemBucket { + // Own the archive's lifecycle on the shared bucket: the operator's + // delete-backup finalizer prunes the pbm object from storage when this CR + // is deleted, which is how the cleanup path (Plan retention) reclaims + // cozy-backups. A legacy backup writes to the tenant's own bucket and its + // lifecycle stays the tenant's, so it is left unfinalized. + obj.Finalizers = append(obj.Finalizers, psmdbDeleteBackupFinalizer) + } if err := r.Create(ctx, obj); err != nil { return nil, err @@ -628,6 +662,11 @@ func (r *BackupJobReconciler) createMongoDBBackupArtifact( if mdbBackup.Status.Destination != "" { driverMD[psmdbDestinationKey] = mdbBackup.Status.Destination } + if useSystemBucket { + // The cleanup path prunes only system-bucket archives (the shared bucket + // the driver owns); record the flow so a legacy backup stays hands-off. + driverMD[psmdbUseSystemBucketKey] = "true" + } underlyingResources, err := marshalMongoDBBackupSnapshot(mdbBackup, rendered, storageName, resolved.Parameters, useSystemBucket) if err != nil { @@ -671,6 +710,59 @@ func (r *BackupJobReconciler) createMongoDBBackupArtifact( return backup, nil } +// cleanupMongoDBBackup prunes the pbm archive a system-bucket Backup wrote to +// the shared cozy-backups bucket when that Backup is deleted (Plan retention or +// manual). It deletes the operator PerconaServerMongoDBBackup CR and waits for +// the operator's delete-backup finalizer (stamped at creation by +// ensureMongoDBBackup) to remove the object from storage before releasing the +// Cozystack Backup, so no object is orphaned — the same "own the artifact, wait +// for the delete" contract the Redis/Rabbitmq branches use. A legacy backup +// (its own tenant bucket, no system-bucket marker) is left untouched, matching +// the pre-existing no-op contract for the operator-backed drivers. +func (r *BackupReconciler) cleanupMongoDBBackup(ctx context.Context, backup *backupsv1alpha1.Backup) (ctrl.Result, error) { + logger := getLogger(ctx) + + if backup.Spec.DriverMetadata[psmdbUseSystemBucketKey] != "true" { + // Legacy flow: the archive is in the tenant's own bucket and its + // lifecycle is the tenant's / psmdb operator's, not the platform's. + return ctrl.Result{}, nil + } + + sourceBackupName := backup.Spec.DriverMetadata[psmdbBackupNameKey] + if sourceBackupName == "" { + // Nothing recorded to delete (Backup written before the name was tracked). + return ctrl.Result{}, nil + } + + live := &psmdbtypes.PerconaServerMongoDBBackup{} + err := r.Get(ctx, types.NamespacedName{Namespace: backup.Namespace, Name: sourceBackupName}, live) + if apierrors.IsNotFound(err) { + // The operator CR is gone, which — with the delete-backup finalizer set + // at creation — means the archive was pruned with it. Release. + return ctrl.Result{}, nil + } + if err != nil { + return ctrl.Result{}, err + } + + if backup.Annotations[psmdbSkipArtifactCleanupAnnotation] == "true" { + logger.Debug("skipping MongoDB artifact cleanup per annotation; object left in bucket", + "backup", backup.Name, "annotation", psmdbSkipArtifactCleanupAnnotation) + return ctrl.Result{}, nil + } + + if live.DeletionTimestamp.IsZero() { + if derr := r.Delete(ctx, live); derr != nil && !apierrors.IsNotFound(derr) { + return ctrl.Result{}, derr + } + } + // Requeue until the operator finalizer has removed the CR (and the archive + // with it). + logger.Debug("waiting for psmdb operator to prune system-bucket archive", + "backup", backup.Name, "sourceBackup", sourceBackupName) + return ctrl.Result{RequeueAfter: psmdbPollInterval}, nil +} + // --------------------------------------------------------------------------- // RestoreJob path // --------------------------------------------------------------------------- @@ -895,6 +987,16 @@ var errTransientRestoreSource = errors.New("transient backup-source resolution e // nothing to restore from. A transient read error on the live Backup CR is // wrapped in errTransientRestoreSource so the caller can requeue instead. func (r *RestoreJobReconciler) resolveMongoDBBackupSource(ctx context.Context, backup *backupsv1alpha1.Backup) (*psmdbtypes.BackupSource, error) { + // Snapshot persisted at backup time. Decoded up front so the live path can + // backfill an S3 block the operator status omits: on the useSystemBucket + // flow the driver injected the storage rather than the chart declaring it, + // and the operator can report status.destination while leaving status.s3 + // empty. Without the S3 block the restore has no endpoint/credentialsSecret, + // and a system-bucket target has no declared storage to resolve from either + // (injection runs only on the BackupJob path), so a live CR that echoes a + // destination but no s3 would otherwise strand the restore. + snap, snapErr := unmarshalMongoDBBackupSnapshot(backup.Status.UnderlyingResources) + // Live operator Backup CR (same namespace as the Cozystack Backup). sourceBackupName := backup.Spec.DriverMetadata[psmdbBackupNameKey] if sourceBackupName != "" { @@ -902,22 +1004,28 @@ func (r *RestoreJobReconciler) resolveMongoDBBackupSource(ctx context.Context, b err := r.Get(ctx, types.NamespacedName{Namespace: backup.Namespace, Name: sourceBackupName}, live) if err == nil { if live.Status.Destination != "" { - return &psmdbtypes.BackupSource{ + src := &psmdbtypes.BackupSource{ Type: psmdbBackupTypeOrDefault(live.Status.Type), Destination: live.Status.Destination, StorageName: live.Status.StorageName, S3: live.Status.S3.DeepCopy(), - }, nil + } + if src.S3 == nil && snap != nil { + src.S3 = snap.S3.DeepCopy() + if src.StorageName == "" { + src.StorageName = snap.StorageName + } + } + return src, nil } } else if !apierrors.IsNotFound(err) { return nil, fmt.Errorf("%w: get source PerconaServerMongoDBBackup %s/%s: %v", errTransientRestoreSource, backup.Namespace, sourceBackupName, err) } } - // Snapshot fallback. - snap, err := unmarshalMongoDBBackupSnapshot(backup.Status.UnderlyingResources) - if err != nil { - return nil, fmt.Errorf("decode Backup snapshot: %v", err) + // Snapshot fallback (operator CR reaped or never reported a destination). + if snapErr != nil { + return nil, fmt.Errorf("decode Backup snapshot: %v", snapErr) } destination := backup.Spec.DriverMetadata[psmdbDestinationKey] if snap != nil && snap.Destination != "" { diff --git a/internal/backupcontroller/psmdbstrategy_controller_test.go b/internal/backupcontroller/psmdbstrategy_controller_test.go index 93e7c7075..bd1ed8f2b 100644 --- a/internal/backupcontroller/psmdbstrategy_controller_test.go +++ b/internal/backupcontroller/psmdbstrategy_controller_test.go @@ -11,6 +11,7 @@ import ( apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/types" "k8s.io/client-go/kubernetes/scheme" "k8s.io/client-go/tools/record" "sigs.k8s.io/controller-runtime/pkg/client" @@ -254,6 +255,18 @@ func TestMongoDBRestoreCredentialsSecret(t *testing.T) { target: target(map[string]runtime.RawExtension{"s3-storage": s3Storage("cozy-backups-PLATFORM", "cozy-backups-creds")}), want: "src-s3-creds", }, + { + // Reaches the projected-secret early return specifically: the target + // declares a storage on the SAME bucket as the archive under a + // different credentialsSecret, so without the "already cozy-backups- + // creds" short-circuit the same-bucket swap would re-point the restore + // at the operator-managed secret. Keeping the projected secret is + // correct — it outlives the source app and reads the platform bucket. + name: "system source -> target with same-bucket storage under other creds: keep projected cozy-backups-creds", + source: src("cozy-backups-PLATFORM", "cozy-backups-creds"), + target: target(map[string]runtime.RawExtension{"s3-storage": s3Storage("cozy-backups-PLATFORM", "operator-managed-creds")}), + want: "cozy-backups-creds", + }, { name: "no s3 source: empty (caller keeps the source reference)", source: &psmdbtypes.BackupSource{StorageName: "s3-storage"}, @@ -284,11 +297,11 @@ func TestEnsureMongoDBBackup_IdempotentByLabel(t *testing.T) { rendered := newRenderedMongoDBTemplate() cluster := mongodbNameForApp("mongodb-src") - first, err := r.ensureMongoDBBackup(context.Background(), job, cluster, "s3-storage", rendered) + first, err := r.ensureMongoDBBackup(context.Background(), job, cluster, "s3-storage", rendered, false) if err != nil { t.Fatalf("first ensureMongoDBBackup: %v", err) } - second, err := r.ensureMongoDBBackup(context.Background(), job, cluster, "s3-storage", rendered) + second, err := r.ensureMongoDBBackup(context.Background(), job, cluster, "s3-storage", rendered, false) if err != nil { t.Fatalf("second ensureMongoDBBackup: %v", err) } @@ -323,6 +336,37 @@ func TestEnsureMongoDBBackup_IdempotentByLabel(t *testing.T) { if got.Labels[backupsv1alpha1.OwningJobNameLabel] != "bj-1" { t.Errorf("OwningJobName label missing or wrong: %v", got.Labels) } + // Legacy flow: the archive is the tenant's, so the driver must NOT stamp the + // delete-backup finalizer that would prune it on CR deletion. + for _, f := range got.Finalizers { + if f == psmdbDeleteBackupFinalizer { + t.Errorf("legacy backup must not carry %q finalizer; got %v", psmdbDeleteBackupFinalizer, got.Finalizers) + } + } +} + +func TestEnsureMongoDBBackup_SystemBucketStampsDeleteFinalizer(t *testing.T) { + c := newMongoDBStrategyTestClient(t) + r := &BackupJobReconciler{Client: c, Scheme: c.Scheme()} + job := newMongoDBBackupJob("bj-sb", "tenant") + if err := c.Create(context.Background(), job); err != nil { + t.Fatalf("seed BackupJob: %v", err) + } + got, err := r.ensureMongoDBBackup(context.Background(), job, "mongodb-app", "s3-storage", newRenderedMongoDBTemplate(), true) + if err != nil { + t.Fatalf("ensureMongoDBBackup: %v", err) + } + found := false + for _, f := range got.Finalizers { + if f == psmdbDeleteBackupFinalizer { + found = true + } + } + if !found { + // Without it, deleting the Backup on Plan retention would orphan the + // object in the shared cozy-backups bucket forever. + t.Errorf("system-bucket backup must carry %q finalizer so its archive is pruned on delete; got %v", psmdbDeleteBackupFinalizer, got.Finalizers) + } } // --------------------------------------------------------------------------- @@ -1022,3 +1066,253 @@ func newRenderedMongoDBTemplate() *strategyv1alpha1.MongoDBTemplate { CompressionType: "gzip", } } + +// --------------------------------------------------------------------------- +// Strategy rendering +// --------------------------------------------------------------------------- + +// The strategy prefix reaches the CR as a literal Go template +// ("/") and renderMongoDBTemplate is what turns it into a per-tenant +// path at BackupJob time. That resolution is the only thing keeping two tenants' +// dumps apart inside one shared bucket, so pin it: an unrendered prefix would +// collide every tenant under the same path. Mirrors the CNPG/FoundationDB +// sibling render tests. +func TestRenderMongoDBTemplate_TemplatingApplicationName(t *testing.T) { + tmpl := strategyv1alpha1.MongoDBTemplate{ + StorageName: "s3-storage", + Type: "logical", + S3: &strategyv1alpha1.MongoDBStorageS3{ + Bucket: "cozy-backups", + EndpointURL: "https://s3.example", + Prefix: "{{ .Application.metadata.namespace }}/{{ .Application.metadata.name }}", + CredentialsSecret: "cozy-backups-creds", + }, + } + app := &mongodbapp.MongoDB{ObjectMeta: metav1.ObjectMeta{Namespace: "tenant-x", Name: "mongo-y"}} + + got, err := renderMongoDBTemplate(tmpl, app, nil) + if err != nil { + t.Fatalf("renderMongoDBTemplate: %v", err) + } + if got.S3 == nil { + t.Fatalf("rendered S3 is nil") + } + if got.S3.Prefix != "tenant-x/mongo-y" { + t.Errorf("prefix not templated per application: got %q want tenant-x/mongo-y", got.S3.Prefix) + } + // The non-templated coordinates must pass through untouched. + if got.S3.Bucket != "cozy-backups" || got.S3.CredentialsSecret != "cozy-backups-creds" { + t.Errorf("static coordinates altered: %#v", got.S3) + } +} + +// --------------------------------------------------------------------------- +// System-bucket storage injection (BackupJob path) +// --------------------------------------------------------------------------- + +// The injection is what makes the useSystemBucket flow work: the app chart omits +// the storage, so reconcileMongoDB SSA-injects it and must read the precondition +// off the post-apply cluster (cluster = injected), not the pre-apply one it +// Got. This pins that within a single reconcile: with a live cluster that has +// backups enabled but no storage declared, the reconcile must inject, pass the +// precondition, and create the operator Backup CR. Drop the reassignment and the +// precondition reads the pre-apply cluster, fails, and no Backup is created. +func TestReconcileMongoDB_InjectsSystemStorageBeforePrecondition(t *testing.T) { + apps := mongodbapp.GroupName + strategyGroup := strategyv1alpha1.GroupVersion.Group + now := metav1.Now() + + job := &backupsv1alpha1.BackupJob{ + ObjectMeta: metav1.ObjectMeta{Namespace: "tenant", Name: "bj-inj"}, + Spec: backupsv1alpha1.BackupJobSpec{ + ApplicationRef: corev1.TypedLocalObjectReference{Kind: "MongoDB", Name: "app1", APIGroup: &apps}, + }, + Status: backupsv1alpha1.BackupJobStatus{StartedAt: &now}, + } + strategy := &strategyv1alpha1.MongoDB{ + ObjectMeta: metav1.ObjectMeta{Name: "cozy-default-mongodb"}, + Spec: strategyv1alpha1.MongoDBSpec{Template: strategyv1alpha1.MongoDBTemplate{ + StorageName: "s3-storage", + Type: "logical", + S3: &strategyv1alpha1.MongoDBStorageS3{ + Bucket: "cozy-backups", + EndpointURL: "https://s3.example", + Prefix: "{{ .Application.metadata.namespace }}/{{ .Application.metadata.name }}", + CredentialsSecret: "cozy-backups-creds", + }, + }}, + } + app := &mongodbapp.MongoDB{ + ObjectMeta: metav1.ObjectMeta{Namespace: "tenant", Name: "app1"}, + Spec: mongodbapp.MongoDBSpec{Backup: mongodbapp.MongoDBBackupSpec{UseSystemBucket: true}}, + } + // Live cluster: backups enabled (agents run) but storage NOT declared — the + // exact state the chart leaves on the useSystemBucket flow. + cluster := &psmdbtypes.PerconaServerMongoDB{ + ObjectMeta: metav1.ObjectMeta{Namespace: "tenant", Name: "mongodb-app1"}, + Spec: psmdbtypes.PerconaServerMongoDBSpec{Backup: psmdbtypes.PerconaServerMongoDBBackupConfig{Enabled: true}}, + } + + c := newMongoDBStrategyTestClient(t, job, strategy, app, cluster) + r := &BackupJobReconciler{Client: c, Scheme: c.Scheme()} + + resolved := &ResolvedBackupConfig{ + StrategyRef: corev1.TypedLocalObjectReference{APIGroup: &strategyGroup, Kind: strategyv1alpha1.MongoDBStrategyKind, Name: "cozy-default-mongodb"}, + Parameters: map[string]string{}, + } + + res, err := r.reconcileMongoDB(context.Background(), job.DeepCopy(), resolved) + if err != nil { + t.Fatalf("reconcileMongoDB: %v", err) + } + if res.RequeueAfter == 0 { + t.Fatalf("expected a poll requeue while the operator Backup runs, got %+v", res) + } + + // The precondition passed only because it read the injected cluster: an + // operator Backup CR now exists. + list := &psmdbtypes.PerconaServerMongoDBBackupList{} + if err := c.List(context.Background(), list, client.InNamespace("tenant")); err != nil { + t.Fatalf("list operator backups: %v", err) + } + if len(list.Items) != 1 { + t.Fatalf("expected the injection to let the precondition pass and create 1 operator Backup, got %d", len(list.Items)) + } + + // The storage was actually persisted onto the live cluster. + got := &psmdbtypes.PerconaServerMongoDB{} + if err := c.Get(context.Background(), types.NamespacedName{Namespace: "tenant", Name: "mongodb-app1"}, got); err != nil { + t.Fatalf("get cluster: %v", err) + } + if _, ok := got.Spec.Backup.Storages["s3-storage"]; !ok { + t.Errorf("expected injected s3-storage on the cluster, got %#v", got.Spec.Backup.Storages) + } +} + +// resolveMongoDBBackupSource must fill an S3 block the live operator status +// omits from the snapshot: on the useSystemBucket flow the operator can report +// status.destination with status.s3 empty (the storage was injected, not +// declared), and without the coordinates the restore has nothing to authenticate +// or address the archive with. Neither prior test covers a live CR whose +// destination is set but whose S3 is nil. +func TestResolveMongoDBBackupSource_LiveMissingS3BackfillsFromSnapshot(t *testing.T) { + liveBackup := &psmdbtypes.PerconaServerMongoDBBackup{ + ObjectMeta: metav1.ObjectMeta{Namespace: "tenant", Name: "op-backup"}, + Status: psmdbtypes.PerconaServerMongoDBBackupStatus{ + State: psmdbtypes.StateReady, + Type: "logical", + Destination: "s3://cozy-backups/tenant/app1/2026", + // S3 intentionally nil: the operator echoed a destination only. + }, + } + snapBackup := &psmdbtypes.PerconaServerMongoDBBackup{ + Status: psmdbtypes.PerconaServerMongoDBBackupStatus{ + Destination: "s3://cozy-backups/tenant/app1/2026", + S3: &psmdbtypes.BackupStorageS3{Bucket: "cozy-backups", CredentialsSecret: "cozy-backups-creds", EndpointURL: "https://s3.example"}, + }, + } + raw, err := marshalMongoDBBackupSnapshot(snapBackup, &strategyv1alpha1.MongoDBTemplate{Type: "logical"}, "s3-storage", nil, false) + if err != nil { + t.Fatalf("marshal snapshot: %v", err) + } + cozyBackup := &backupsv1alpha1.Backup{ + ObjectMeta: metav1.ObjectMeta{Namespace: "tenant", Name: "cozy-bk"}, + Spec: backupsv1alpha1.BackupSpec{ + DriverMetadata: map[string]string{psmdbBackupNameKey: "op-backup"}, + }, + Status: backupsv1alpha1.BackupStatus{UnderlyingResources: raw}, + } + c := newMongoDBStrategyTestClient(t, liveBackup) + r := &RestoreJobReconciler{Client: c, Recorder: record.NewFakeRecorder(10)} + src, err := r.resolveMongoDBBackupSource(context.Background(), cozyBackup) + if err != nil { + t.Fatalf("resolveMongoDBBackupSource: %v", err) + } + if src.Destination != "s3://cozy-backups/tenant/app1/2026" { + t.Errorf("expected live destination, got %q", src.Destination) + } + if src.S3 == nil { + t.Fatalf("expected S3 backfilled from snapshot, got nil (restore would have no coordinates)") + } + if src.S3.CredentialsSecret != "cozy-backups-creds" || src.S3.Bucket != "cozy-backups" { + t.Errorf("expected snapshot S3 coordinates, got %#v", src.S3) + } +} + +// --------------------------------------------------------------------------- +// System-bucket archive cleanup (retention) +// --------------------------------------------------------------------------- + +func TestCleanupMongoDBBackup(t *testing.T) { + newBackup := func(md map[string]string, ann map[string]string) *backupsv1alpha1.Backup { + return &backupsv1alpha1.Backup{ + ObjectMeta: metav1.ObjectMeta{Namespace: "tenant", Name: "cozy-bk", Annotations: ann}, + Spec: backupsv1alpha1.BackupSpec{DriverMetadata: md}, + } + } + opBackup := func() *psmdbtypes.PerconaServerMongoDBBackup { + return &psmdbtypes.PerconaServerMongoDBBackup{ + ObjectMeta: metav1.ObjectMeta{Namespace: "tenant", Name: "op-bk", Finalizers: []string{psmdbDeleteBackupFinalizer}}, + } + } + + t.Run("legacy backup is a no-op (tenant owns the archive)", func(t *testing.T) { + c := newMongoDBStrategyTestClient(t, opBackup()) + r := &BackupReconciler{Client: c} + res, err := r.cleanupMongoDBBackup(context.Background(), newBackup(map[string]string{psmdbBackupNameKey: "op-bk"}, nil)) + if err != nil || res.RequeueAfter != 0 { + t.Fatalf("legacy cleanup must be a no-op, got res=%+v err=%v", res, err) + } + // The operator CR must be untouched (no delete issued). + got := &psmdbtypes.PerconaServerMongoDBBackup{} + if err := c.Get(context.Background(), types.NamespacedName{Namespace: "tenant", Name: "op-bk"}, got); err != nil { + t.Fatalf("operator CR should be untouched: %v", err) + } + if !got.DeletionTimestamp.IsZero() { + t.Errorf("legacy cleanup must not delete the operator CR") + } + }) + + t.Run("system-bucket backup deletes the operator CR and waits", func(t *testing.T) { + c := newMongoDBStrategyTestClient(t, opBackup()) + r := &BackupReconciler{Client: c} + md := map[string]string{psmdbBackupNameKey: "op-bk", psmdbUseSystemBucketKey: "true"} + res, err := r.cleanupMongoDBBackup(context.Background(), newBackup(md, nil)) + if err != nil { + t.Fatalf("cleanupMongoDBBackup: %v", err) + } + if res.RequeueAfter == 0 { + t.Fatalf("expected a requeue while the operator prunes the archive, got %+v", res) + } + // The delete-backup finalizer holds the CR Terminating until the operator + // prunes the object; the driver must keep waiting, not release early. + got := &psmdbtypes.PerconaServerMongoDBBackup{} + if err := c.Get(context.Background(), types.NamespacedName{Namespace: "tenant", Name: "op-bk"}, got); err != nil { + t.Fatalf("operator CR should still exist under its finalizer: %v", err) + } + if got.DeletionTimestamp.IsZero() { + t.Errorf("expected the operator CR to be marked for deletion") + } + }) + + t.Run("operator CR already gone releases (finalizer pruned the archive)", func(t *testing.T) { + c := newMongoDBStrategyTestClient(t) + r := &BackupReconciler{Client: c} + md := map[string]string{psmdbBackupNameKey: "op-bk", psmdbUseSystemBucketKey: "true"} + res, err := r.cleanupMongoDBBackup(context.Background(), newBackup(md, nil)) + if err != nil || res.RequeueAfter != 0 { + t.Fatalf("a reaped operator CR must release, got res=%+v err=%v", res, err) + } + }) + + t.Run("skip annotation releases without waiting", func(t *testing.T) { + c := newMongoDBStrategyTestClient(t, opBackup()) + r := &BackupReconciler{Client: c} + md := map[string]string{psmdbBackupNameKey: "op-bk", psmdbUseSystemBucketKey: "true"} + ann := map[string]string{psmdbSkipArtifactCleanupAnnotation: "true"} + res, err := r.cleanupMongoDBBackup(context.Background(), newBackup(md, ann)) + if err != nil || res.RequeueAfter != 0 { + t.Fatalf("skip annotation must release, got res=%+v err=%v", res, err) + } + }) +} diff --git a/packages/system/backupstrategy-controller/templates/rbac.yaml b/packages/system/backupstrategy-controller/templates/rbac.yaml index 2b80beec1..8c2afbadb 100644 --- a/packages/system/backupstrategy-controller/templates/rbac.yaml +++ b/packages/system/backupstrategy-controller/templates/rbac.yaml @@ -155,20 +155,24 @@ rules: resources: ["backups", "restores"] verbs: ["get", "list", "watch", "create"] # MongoDB strategy: read the operator-side PerconaServerMongoDB CR to gate on -# "backups enabled + storage declared" preconditions, create one-shot -# PerconaServerMongoDBBackup CRs on the BackupJob path, and create -# PerconaServerMongoDBRestore CRs on the RestoreJob path. The Backup/Restore CRs -# are only ever Created/Listed/Gotten — their lifecycle is owned by the psmdb -# operator and (for cleanup) by tenants / explicit teardown flows. The cluster -# CR is patched only on the useSystemBucket flow (storage injection, below); it -# is never deleted. +# the backup preconditions, create one-shot PerconaServerMongoDBBackup CRs on the +# BackupJob path, and create PerconaServerMongoDBRestore CRs on the RestoreJob +# path. The cluster CR is patched only on the useSystemBucket flow (storage +# injection, below); it is never deleted. - apiGroups: ["psmdb.percona.com"] resources: ["perconaservermongodbs"] - # patch/update: the useSystemBucket flow SSA-injects spec.backup.storages - # onto the live PerconaServerMongoDB at BackupJob time. - verbs: ["get", "list", "watch", "patch", "update"] + # patch: the useSystemBucket flow SSA-injects spec.backup.storages onto the + # live PerconaServerMongoDB at BackupJob time (server-side apply is a PATCH). + verbs: ["get", "list", "watch", "patch"] - apiGroups: ["psmdb.percona.com"] - resources: ["perconaservermongodbbackups", "perconaservermongodbrestores"] + resources: ["perconaservermongodbbackups"] + # delete: on the useSystemBucket flow the driver owns the shared-bucket archive + # and prunes it on Cozystack Backup deletion by deleting this CR, whose + # delete-backup finalizer frees the object (see cleanupMongoDBBackup). A legacy + # backup lives in the tenant's own bucket and is never deleted here. + verbs: ["get", "list", "watch", "create", "delete"] +- apiGroups: ["psmdb.percona.com"] + resources: ["perconaservermongodbrestores"] verbs: ["get", "list", "watch", "create"] # FoundationDB strategy: read the operator-side FoundationDBCluster CR to # surface "not yet rendered" preconditions, create per-BackupJob From f27a02f1b686ccab316c2deac31dbcf69a4655a9 Mon Sep 17 00:00:00 2001 From: Andrey Kolkov Date: Mon, 14 Sep 2026 18:07:04 +0400 Subject: [PATCH 0009/1280] docs(mongodb): correct the inlined-storage story and surface the TLS knob MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The strategy godoc still said the storage config is NOT inlined and the strategy only names the storage — which controller-gen copies verbatim into the CRD, so kubectl explain served the new s3 field and its own denial from one object. Rewrite it (and the StorageName field doc) to describe both flows, and regenerate the CRD. Render insecureSkipTLSVerify on the default MongoDB strategy: the field is plumbed end to end into the driver-injected storage entry and backed by a platform knob, but the template set only forcePathStyle, pinning it to false so a self-signed external S3 that Redis backups honour would fail MongoDB x509 verification. Pin it in the rendering test alongside the other s3 coordinates. Fix the useSystemBucket field description: angle brackets rendered as empty HTML tags in the README table and the dashboard schema, so wrap the path in backticks (as the postgres field already does) and note that schedule, retentionPolicy and PITR are ignored on this flow. Regenerate the chart schema, README and mongodb-rd. Assisted-By: LLM Signed-off-by: Andrey Kolkov --- api/apps/v1alpha1/mongodb/types.go | 2 +- .../strategy/v1alpha1/mongodb_types.go | 21 +++++++++------- packages/apps/mongodb/README.md | 24 +++++++++---------- packages/apps/mongodb/values.schema.json | 2 +- packages/apps/mongodb/values.yaml | 2 +- ...trategy.backups.cozystack.io_mongodbs.yaml | 21 +++++++++------- .../templates/strategy-mongodb-default.yaml | 1 + .../tests/rendering_test.yaml | 7 ++++++ .../system/mongodb-rd/cozyrds/mongodb.yaml | 2 +- 9 files changed, 50 insertions(+), 32 deletions(-) diff --git a/api/apps/v1alpha1/mongodb/types.go b/api/apps/v1alpha1/mongodb/types.go index 6741ea9b2..7c0f6f33f 100644 --- a/api/apps/v1alpha1/mongodb/types.go +++ b/api/apps/v1alpha1/mongodb/types.go @@ -84,7 +84,7 @@ type Backup struct { // Cron schedule for automated backups. // +kubebuilder:default:="0 2 * * *" Schedule string `json:"schedule,omitempty"` - // Opt-in: back up to the platform system bucket without supplying S3 credentials. The cozy-default MongoDB BackupClass injects the storage at BackupJob time; tenants do not set s3AccessKey/s3SecretKey/destinationPath/endpointURL, and backups scope to /. See docs/operations/backup-classes.md. + // Opt-in: back up to the platform system bucket without supplying S3 credentials. The cozy-default MongoDB BackupClass injects the storage at BackupJob time; tenants do not set s3AccessKey/s3SecretKey/destinationPath/endpointURL, and backups scope to `/`. Scheduling and retention move to the BackupClass Plan, so `schedule`, `retentionPolicy` and PITR are ignored while this is on. See docs/operations/backup-classes.md. // +kubebuilder:default:=false UseSystemBucket bool `json:"useSystemBucket,omitempty"` } diff --git a/api/backups/strategy/v1alpha1/mongodb_types.go b/api/backups/strategy/v1alpha1/mongodb_types.go index 0aca1bf75..abefdabe7 100644 --- a/api/backups/strategy/v1alpha1/mongodb_types.go +++ b/api/backups/strategy/v1alpha1/mongodb_types.go @@ -37,11 +37,14 @@ const ( // carrying the S3 destination read back from the source backup, so the same // artifact restores in-place or into a differently-named instance. // -// Unlike the MariaDB strategy, the storage config is NOT inlined here: psmdb -// resolves spec.storageName against the source cluster's spec.backup.storages, -// so the S3/credentials live on the PerconaServerMongoDB CR (the mongodb chart -// declares them when backup.enabled=true) and the strategy only names the -// storage to use. +// The strategy always names the storage (spec.template.storageName) psmdb +// resolves against the source cluster's spec.backup.storages. On the legacy +// flow the S3/credentials for that storage live on the PerconaServerMongoDB CR +// (the mongodb chart declares them when backup.enabled=true and +// useSystemBucket=false). On the useSystemBucket flow the chart cannot know the +// platform bucket at render time, so the strategy also carries the storage's S3 +// coordinates (spec.template.s3) and the driver SSA-injects them onto the +// cluster at BackupJob time. type MongoDB struct { metav1.TypeMeta `json:",inline"` metav1.ObjectMeta `json:"metadata,omitempty"` @@ -75,9 +78,11 @@ type MongoDBSpec struct { // MongoDBTemplate describes the templated PerconaServerMongoDBBackup shape the // driver renders per BackupJob. type MongoDBTemplate struct { - // StorageName names a storage entry declared in the source cluster's - // spec.backup.storages. The mongodb chart declares "s3-storage" when - // backup.enabled=true; leave empty to use that default. Templating is + // StorageName names a storage entry in the source cluster's + // spec.backup.storages. On the legacy flow the mongodb chart declares + // "s3-storage" when backup.enabled=true and useSystemBucket=false; on the + // useSystemBucket flow the driver injects an entry under this same name from + // the S3 coordinates below. Leave empty to use "s3-storage". Templating is // supported. // +optional StorageName string `json:"storageName,omitempty"` diff --git a/packages/apps/mongodb/README.md b/packages/apps/mongodb/README.md index 8e7a147c9..af033c2b8 100644 --- a/packages/apps/mongodb/README.md +++ b/packages/apps/mongodb/README.md @@ -247,18 +247,18 @@ Releases with `external: false`, and sharded releases in any configuration, are ### Backup parameters -| Name | Description | Type | Value | -| ------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------- | ----------------------------------- | -| `backup` | Backup configuration. | `object` | `{}` | -| `backup.enabled` | Enable regular backups. | `bool` | `false` | -| `backup.useSystemBucket` | Opt-in: back up to the platform system bucket without supplying S3 credentials. The cozy-default MongoDB BackupClass injects the storage at BackupJob time; tenants do not set s3AccessKey/s3SecretKey/destinationPath/endpointURL, and backups scope to /. See docs/operations/backup-classes.md. | `bool` | `false` | -| `backup.schedule` | Cron schedule for automated backups. | `string` | `0 2 * * *` | -| `backup.retentionPolicy` | Retention policy (e.g. "30d"). | `string` | `30d` | -| `backup.destinationPath` | Destination path for backups (e.g. s3://bucket/path/). | `string` | `s3://bucket/path/to/folder/` | -| `backup.endpointURL` | S3 endpoint URL for uploads. | `string` | `http://minio-gateway-service:9000` | -| `backup.insecureSkipTLSVerify` | Skip TLS verification for the S3 endpoint (self-signed, e.g. in-cluster seaweedfs). | `bool` | `false` | -| `backup.s3AccessKey` | Access key for S3 authentication. | `string` | `""` | -| `backup.s3SecretKey` | Secret key for S3 authentication. | `string` | `""` | +| Name | Description | Type | Value | +| ------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------- | ----------------------------------- | +| `backup` | Backup configuration. | `object` | `{}` | +| `backup.enabled` | Enable regular backups. | `bool` | `false` | +| `backup.useSystemBucket` | Opt-in: back up to the platform system bucket without supplying S3 credentials. The cozy-default MongoDB BackupClass injects the storage at BackupJob time; tenants do not set s3AccessKey/s3SecretKey/destinationPath/endpointURL, and backups scope to `/`. Scheduling and retention move to the BackupClass Plan, so `schedule`, `retentionPolicy` and PITR are ignored while this is on. See docs/operations/backup-classes.md. | `bool` | `false` | +| `backup.schedule` | Cron schedule for automated backups. | `string` | `0 2 * * *` | +| `backup.retentionPolicy` | Retention policy (e.g. "30d"). | `string` | `30d` | +| `backup.destinationPath` | Destination path for backups (e.g. s3://bucket/path/). | `string` | `s3://bucket/path/to/folder/` | +| `backup.endpointURL` | S3 endpoint URL for uploads. | `string` | `http://minio-gateway-service:9000` | +| `backup.insecureSkipTLSVerify` | Skip TLS verification for the S3 endpoint (self-signed, e.g. in-cluster seaweedfs). | `bool` | `false` | +| `backup.s3AccessKey` | Access key for S3 authentication. | `string` | `""` | +| `backup.s3SecretKey` | Secret key for S3 authentication. | `string` | `""` | ### Bootstrap (recovery) parameters diff --git a/packages/apps/mongodb/values.schema.json b/packages/apps/mongodb/values.schema.json index 60abc75c2..a6fdd3f46 100644 --- a/packages/apps/mongodb/values.schema.json +++ b/packages/apps/mongodb/values.schema.json @@ -313,7 +313,7 @@ "default": "0 2 * * *" }, "useSystemBucket": { - "description": "Opt-in: back up to the platform system bucket without supplying S3 credentials. The cozy-default MongoDB BackupClass injects the storage at BackupJob time; tenants do not set s3AccessKey/s3SecretKey/destinationPath/endpointURL, and backups scope to \u003cnamespace\u003e/\u003capplication\u003e. See docs/operations/backup-classes.md.", + "description": "Opt-in: back up to the platform system bucket without supplying S3 credentials. The cozy-default MongoDB BackupClass injects the storage at BackupJob time; tenants do not set s3AccessKey/s3SecretKey/destinationPath/endpointURL, and backups scope to `\u003cnamespace\u003e/\u003capplication\u003e`. Scheduling and retention move to the BackupClass Plan, so `schedule`, `retentionPolicy` and PITR are ignored while this is on. See docs/operations/backup-classes.md.", "type": "boolean", "default": false } diff --git a/packages/apps/mongodb/values.yaml b/packages/apps/mongodb/values.yaml index 541b19fe4..660332029 100644 --- a/packages/apps/mongodb/values.yaml +++ b/packages/apps/mongodb/values.yaml @@ -155,7 +155,7 @@ databases: {} ## @typedef {struct} Backup - Backup configuration. ## @field {bool} enabled - Enable regular backups. -## @field {bool} [useSystemBucket] - Opt-in: back up to the platform system bucket without supplying S3 credentials. The cozy-default MongoDB BackupClass injects the storage at BackupJob time; tenants do not set s3AccessKey/s3SecretKey/destinationPath/endpointURL, and backups scope to /. See docs/operations/backup-classes.md. +## @field {bool} [useSystemBucket] - Opt-in: back up to the platform system bucket without supplying S3 credentials. The cozy-default MongoDB BackupClass injects the storage at BackupJob time; tenants do not set s3AccessKey/s3SecretKey/destinationPath/endpointURL, and backups scope to `/`. Scheduling and retention move to the BackupClass Plan, so `schedule`, `retentionPolicy` and PITR are ignored while this is on. See docs/operations/backup-classes.md. ## @field {string} [schedule] - Cron schedule for automated backups. ## @field {string} [retentionPolicy] - Retention policy (e.g. "30d"). ## @field {string} [destinationPath] - Destination path for backups (e.g. s3://bucket/path/). diff --git a/packages/system/backupstrategy-controller/definitions/strategy.backups.cozystack.io_mongodbs.yaml b/packages/system/backupstrategy-controller/definitions/strategy.backups.cozystack.io_mongodbs.yaml index ca5ed92b6..4a26604af 100644 --- a/packages/system/backupstrategy-controller/definitions/strategy.backups.cozystack.io_mongodbs.yaml +++ b/packages/system/backupstrategy-controller/definitions/strategy.backups.cozystack.io_mongodbs.yaml @@ -27,11 +27,14 @@ spec: carrying the S3 destination read back from the source backup, so the same artifact restores in-place or into a differently-named instance. - Unlike the MariaDB strategy, the storage config is NOT inlined here: psmdb - resolves spec.storageName against the source cluster's spec.backup.storages, - so the S3/credentials live on the PerconaServerMongoDB CR (the mongodb chart - declares them when backup.enabled=true) and the strategy only names the - storage to use. + The strategy always names the storage (spec.template.storageName) psmdb + resolves against the source cluster's spec.backup.storages. On the legacy + flow the S3/credentials for that storage live on the PerconaServerMongoDB CR + (the mongodb chart declares them when backup.enabled=true and + useSystemBucket=false). On the useSystemBucket flow the chart cannot know the + platform bucket at render time, so the strategy also carries the storage's S3 + coordinates (spec.template.s3) and the driver SSA-injects them onto the + cluster at BackupJob time. properties: apiVersion: description: |- @@ -117,9 +120,11 @@ spec: type: object storageName: description: |- - StorageName names a storage entry declared in the source cluster's - spec.backup.storages. The mongodb chart declares "s3-storage" when - backup.enabled=true; leave empty to use that default. Templating is + StorageName names a storage entry in the source cluster's + spec.backup.storages. On the legacy flow the mongodb chart declares + "s3-storage" when backup.enabled=true and useSystemBucket=false; on the + useSystemBucket flow the driver injects an entry under this same name from + the S3 coordinates below. Leave empty to use "s3-storage". Templating is supported. type: string type: diff --git a/packages/system/backupstrategy-controller/templates/strategy-mongodb-default.yaml b/packages/system/backupstrategy-controller/templates/strategy-mongodb-default.yaml index f9b77a35b..5e71b25d2 100644 --- a/packages/system/backupstrategy-controller/templates/strategy-mongodb-default.yaml +++ b/packages/system/backupstrategy-controller/templates/strategy-mongodb-default.yaml @@ -73,4 +73,5 @@ spec: region: {{ .Values.backupStorage.region | quote }} credentialsSecret: cozy-backups-creds forcePathStyle: {{ .Values.backupStorage.forcePathStyle }} + insecureSkipTLSVerify: {{ .Values.backupStorage.insecureSkipTLSVerify }} {{- end -}} diff --git a/packages/system/backupstrategy-controller/tests/rendering_test.yaml b/packages/system/backupstrategy-controller/tests/rendering_test.yaml index afd7aafbc..695f82792 100644 --- a/packages/system/backupstrategy-controller/tests/rendering_test.yaml +++ b/packages/system/backupstrategy-controller/tests/rendering_test.yaml @@ -178,6 +178,13 @@ tests: path: spec.template.s3.forcePathStyle value: true template: templates/strategy-mongodb-default.yaml + # insecureSkipTLSVerify is plumbed end-to-end (strategy -> driver-injected + # storage entry); the template must render it from the platform knob, not + # leave it unset (which pins the injected entry to false regardless). + - equal: + path: spec.template.s3.insecureSkipTLSVerify + value: false + template: templates/strategy-mongodb-default.yaml # prefix must reach the CR as a literal go-template string: Helm must NOT # evaluate it, so the driver templates it per-application at BackupJob time. # A stray brace would empty it with every doc-count assertion still green. diff --git a/packages/system/mongodb-rd/cozyrds/mongodb.yaml b/packages/system/mongodb-rd/cozyrds/mongodb.yaml index 78745bd7b..1e8b69f48 100644 --- a/packages/system/mongodb-rd/cozyrds/mongodb.yaml +++ b/packages/system/mongodb-rd/cozyrds/mongodb.yaml @@ -8,7 +8,7 @@ spec: singular: mongodb plural: mongodbs openAPISchema: |- - {"title":"Chart Values","type":"object","properties":{"replicas":{"description":"Number of MongoDB replicas in replica set.","type":"integer","default":3},"resources":{"description":"Explicit CPU and memory configuration for each MongoDB replica. When omitted, the preset defined in `resourcesPreset` is applied.","type":"object","default":{},"properties":{"cpu":{"description":"CPU available to each replica.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"memory":{"description":"Memory (RAM) available to each replica.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true}}},"resourcesPreset":{"description":"Default sizing preset used when `resources` is omitted.","type":"string","default":"t1.small","enum":["t1.nano","t1.micro","t1.small","t1.medium","t1.large","t1.xlarge","t1.2xlarge","t1.4xlarge","c1.nano","c1.micro","c1.small","c1.medium","c1.large","c1.xlarge","c1.2xlarge","c1.4xlarge","s1.nano","s1.micro","s1.small","s1.medium","s1.large","s1.xlarge","s1.2xlarge","s1.4xlarge","u1.nano","u1.micro","u1.small","u1.medium","u1.large","u1.xlarge","u1.2xlarge","u1.4xlarge","m1.nano","m1.micro","m1.small","m1.medium","m1.large","m1.xlarge","m1.2xlarge","m1.4xlarge","nano","micro","small","medium","large","xlarge","2xlarge"]},"size":{"description":"Persistent Volume Claim size available for application data.","default":"10Gi","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"storageClass":{"description":"StorageClass used to store the data.","type":"string","default":"","x-kubernetes-validations":[{"rule":"self == oldSelf","message":"storageClass is immutable"}],"x-cozystack-options":{"source":"storageclass"}},"external":{"description":"Enable external access from outside the cluster.","type":"boolean","default":false},"version":{"description":"MongoDB major version to deploy.","type":"string","default":"v8","enum":["v8","v7","v6"]},"sharding":{"description":"Enable sharded cluster mode. When disabled, deploys a replica set.","type":"boolean","default":false},"shardingConfig":{"description":"Configuration for sharded cluster mode.","type":"object","default":{},"required":["configServerSize","configServers","mongos"],"properties":{"configServerSize":{"description":"PVC size for config servers.","default":"3Gi","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"configServers":{"description":"Number of config server replicas.","type":"integer","default":3},"mongos":{"description":"Number of mongos router replicas.","type":"integer","default":2},"shards":{"description":"List of shard configurations.","type":"array","default":[{"name":"rs0","replicas":3,"size":"10Gi"}],"items":{"type":"object","required":["name","replicas","size"],"properties":{"name":{"description":"Shard name.","type":"string"},"replicas":{"description":"Number of replicas in this shard.","type":"integer"},"size":{"description":"PVC size for this shard.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true}}}}}},"users":{"description":"Users configuration map.","type":"object","default":{},"additionalProperties":{"type":"object","properties":{"password":{"description":"Password for the user (auto-generated if omitted).","type":"string"}}}},"databases":{"description":"Databases configuration map.","type":"object","default":{},"additionalProperties":{"type":"object","properties":{"roles":{"description":"Roles assigned to users.","type":"object","properties":{"admin":{"description":"List of users with admin privileges (readWrite + dbAdmin).","type":"array","items":{"type":"string"}},"readonly":{"description":"List of users with read-only privileges.","type":"array","items":{"type":"string"}}}}}}},"backup":{"description":"Backup configuration.","type":"object","default":{},"required":["enabled"],"properties":{"destinationPath":{"description":"Destination path for backups (e.g. s3://bucket/path/).","type":"string","default":"s3://bucket/path/to/folder/"},"enabled":{"description":"Enable regular backups.","type":"boolean","default":false},"endpointURL":{"description":"S3 endpoint URL for uploads.","type":"string","default":"http://minio-gateway-service:9000"},"insecureSkipTLSVerify":{"description":"Skip TLS verification for the S3 endpoint (self-signed, e.g. in-cluster seaweedfs).","type":"boolean","default":false},"retentionPolicy":{"description":"Retention policy (e.g. \"30d\").","type":"string","default":"30d"},"s3AccessKey":{"description":"Access key for S3 authentication.","type":"string","default":""},"s3SecretKey":{"description":"Secret key for S3 authentication.","type":"string","default":""},"schedule":{"description":"Cron schedule for automated backups.","type":"string","default":"0 2 * * *"},"useSystemBucket":{"description":"Opt-in: back up to the platform system bucket without supplying S3 credentials. The cozy-default MongoDB BackupClass injects the storage at BackupJob time; tenants do not set s3AccessKey/s3SecretKey/destinationPath/endpointURL, and backups scope to /. See docs/operations/backup-classes.md.","type":"boolean","default":false}}},"bootstrap":{"description":"Bootstrap configuration.","type":"object","default":{},"required":["backupName","enabled"],"properties":{"backupName":{"description":"Name of backup to restore from.","type":"string","default":""},"enabled":{"description":"Whether to restore from a backup.","type":"boolean","default":false},"recoveryTime":{"description":"Timestamp for point-in-time recovery; empty means latest.","type":"string","default":""}}}}} + {"title":"Chart Values","type":"object","properties":{"replicas":{"description":"Number of MongoDB replicas in replica set.","type":"integer","default":3},"resources":{"description":"Explicit CPU and memory configuration for each MongoDB replica. When omitted, the preset defined in `resourcesPreset` is applied.","type":"object","default":{},"properties":{"cpu":{"description":"CPU available to each replica.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"memory":{"description":"Memory (RAM) available to each replica.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true}}},"resourcesPreset":{"description":"Default sizing preset used when `resources` is omitted.","type":"string","default":"t1.small","enum":["t1.nano","t1.micro","t1.small","t1.medium","t1.large","t1.xlarge","t1.2xlarge","t1.4xlarge","c1.nano","c1.micro","c1.small","c1.medium","c1.large","c1.xlarge","c1.2xlarge","c1.4xlarge","s1.nano","s1.micro","s1.small","s1.medium","s1.large","s1.xlarge","s1.2xlarge","s1.4xlarge","u1.nano","u1.micro","u1.small","u1.medium","u1.large","u1.xlarge","u1.2xlarge","u1.4xlarge","m1.nano","m1.micro","m1.small","m1.medium","m1.large","m1.xlarge","m1.2xlarge","m1.4xlarge","nano","micro","small","medium","large","xlarge","2xlarge"]},"size":{"description":"Persistent Volume Claim size available for application data.","default":"10Gi","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"storageClass":{"description":"StorageClass used to store the data.","type":"string","default":"","x-kubernetes-validations":[{"rule":"self == oldSelf","message":"storageClass is immutable"}],"x-cozystack-options":{"source":"storageclass"}},"external":{"description":"Enable external access from outside the cluster.","type":"boolean","default":false},"version":{"description":"MongoDB major version to deploy.","type":"string","default":"v8","enum":["v8","v7","v6"]},"sharding":{"description":"Enable sharded cluster mode. When disabled, deploys a replica set.","type":"boolean","default":false},"shardingConfig":{"description":"Configuration for sharded cluster mode.","type":"object","default":{},"required":["configServerSize","configServers","mongos"],"properties":{"configServerSize":{"description":"PVC size for config servers.","default":"3Gi","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"configServers":{"description":"Number of config server replicas.","type":"integer","default":3},"mongos":{"description":"Number of mongos router replicas.","type":"integer","default":2},"shards":{"description":"List of shard configurations.","type":"array","default":[{"name":"rs0","replicas":3,"size":"10Gi"}],"items":{"type":"object","required":["name","replicas","size"],"properties":{"name":{"description":"Shard name.","type":"string"},"replicas":{"description":"Number of replicas in this shard.","type":"integer"},"size":{"description":"PVC size for this shard.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true}}}}}},"users":{"description":"Users configuration map.","type":"object","default":{},"additionalProperties":{"type":"object","properties":{"password":{"description":"Password for the user (auto-generated if omitted).","type":"string"}}}},"databases":{"description":"Databases configuration map.","type":"object","default":{},"additionalProperties":{"type":"object","properties":{"roles":{"description":"Roles assigned to users.","type":"object","properties":{"admin":{"description":"List of users with admin privileges (readWrite + dbAdmin).","type":"array","items":{"type":"string"}},"readonly":{"description":"List of users with read-only privileges.","type":"array","items":{"type":"string"}}}}}}},"backup":{"description":"Backup configuration.","type":"object","default":{},"required":["enabled"],"properties":{"destinationPath":{"description":"Destination path for backups (e.g. s3://bucket/path/).","type":"string","default":"s3://bucket/path/to/folder/"},"enabled":{"description":"Enable regular backups.","type":"boolean","default":false},"endpointURL":{"description":"S3 endpoint URL for uploads.","type":"string","default":"http://minio-gateway-service:9000"},"insecureSkipTLSVerify":{"description":"Skip TLS verification for the S3 endpoint (self-signed, e.g. in-cluster seaweedfs).","type":"boolean","default":false},"retentionPolicy":{"description":"Retention policy (e.g. \"30d\").","type":"string","default":"30d"},"s3AccessKey":{"description":"Access key for S3 authentication.","type":"string","default":""},"s3SecretKey":{"description":"Secret key for S3 authentication.","type":"string","default":""},"schedule":{"description":"Cron schedule for automated backups.","type":"string","default":"0 2 * * *"},"useSystemBucket":{"description":"Opt-in: back up to the platform system bucket without supplying S3 credentials. The cozy-default MongoDB BackupClass injects the storage at BackupJob time; tenants do not set s3AccessKey/s3SecretKey/destinationPath/endpointURL, and backups scope to `/`. Scheduling and retention move to the BackupClass Plan, so `schedule`, `retentionPolicy` and PITR are ignored while this is on. See docs/operations/backup-classes.md.","type":"boolean","default":false}}},"bootstrap":{"description":"Bootstrap configuration.","type":"object","default":{},"required":["backupName","enabled"],"properties":{"backupName":{"description":"Name of backup to restore from.","type":"string","default":""},"enabled":{"description":"Whether to restore from a backup.","type":"boolean","default":false},"recoveryTime":{"description":"Timestamp for point-in-time recovery; empty means latest.","type":"string","default":""}}}}} release: prefix: mongodb- labels: From 542f42ef67c2a12e2afb2650ba34c1563af2ef71 Mon Sep 17 00:00:00 2001 From: Andrey Kolkov Date: Tue, 15 Sep 2026 11:47:21 +0400 Subject: [PATCH 0010/1280] fix(mongodb): make the system-bucket cleanup teardown-safe and single-source its ownership MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Four issues in the system-bucket cleanup path. Teardown wedge. The cleanup requeued forever waiting for the operator to prune, and the escape-hatch annotation released the Cozystack Backup without touching the delete-backup finalizer the driver stamps on the operator CR. So a namespace teardown, where the operator's delete-backup step cannot run (it execs against a pbm agent that is going away), left the operator CR — and the namespace — stuck in Terminating with no way out but hand-patching finalizers. Cleanup now detects a terminating namespace (as Redis/Rabbitmq do) and, on that or the annotation, strips its own finalizer and releases, leaving the object for a bucket lifecycle policy. Needs patch on perconaservermongodbbackups for the finalizer strip. Ownership was read from two places written at different times: the finalizer (stamped when the operator CR is created) and a driverMetadata flag (written when the artifact is created, a later reconcile). If the app's useSystemBucket flag flipped between them they disagreed. Read ownership from the finalizer on the one CR named in driverMetadata (the one the driver minted): resolving it by name, never by scan, keeps the operator's own cron-* task-minted backups (which do carry percona.com/delete-backup at v1.22.0) out of scope, so the finalizer on that named CR is an unambiguous single marker. Drops the driverMetadata flag. Injection error was terminal. A transient server-side apply — an apiserver hiccup, or a conflict while the operator writes the same cluster — failed the BackupJob outright. Requeue with backoff instead, bounded by the existing deadline, matching the cluster/app read errors alongside it. Injection ran before the enabled check, mutating a cluster that can never back up. Gate it on backup.enabled so a disabled cluster is left untouched. Also: reframe the restore S3 backfill as the defensive guard it is (the pinned operator always echoes status.s3, so the live path normally carries coordinates), and correct the psmdbtypes doc that still claimed the driver never patches the operator CRs. Assisted-By: LLM Signed-off-by: Andrey Kolkov --- docs/operations/backup-classes.md | 2 +- .../psmdbstrategy_controller.go | 136 +++++++---- .../psmdbstrategy_controller_test.go | 214 +++++++++++++++--- internal/backupcontroller/psmdbtypes/types.go | 10 +- .../templates/rbac.yaml | 5 +- 5 files changed, 284 insertions(+), 83 deletions(-) diff --git a/docs/operations/backup-classes.md b/docs/operations/backup-classes.md index 732482cbb..0a288cd53 100644 --- a/docs/operations/backup-classes.md +++ b/docs/operations/backup-classes.md @@ -121,7 +121,7 @@ When `useSystemBucket: true`: Because the chart drops `spec.backup.tasks` and `spec.backup.pitr`, the psmdb operator's own scheduled backups and oplog PITR do **not** run on this flow — `backup.schedule` and `backup.retentionPolicy` stay in the schema for the default flow but have no effect here, and the `recoveryTime` PITR restores described below are not available. Migrate scheduled backups to a `backups.cozystack.io/Plan` against `cozy-default` instead. **Flipping this flag on a running app** removes the storage, tasks and pitr the app had, so a release that was taking scheduled backups + PITR before the flip stops until a `Plan` takes over. -Dropping `spec.backup.tasks` also drops the psmdb `keep` retention it carried, so on this flow **the driver owns the archive** the way the Rabbitmq/Redis drivers own theirs (an on-demand `PerconaServerMongoDBBackup` is not covered by psmdb task retention). The driver stamps the operator's `percona.com/delete-backup` finalizer onto each backup it mints here, and deleting a Cozystack `Backup` (a retention-pruned `Plan`, or a manual delete) deletes that `PerconaServerMongoDBBackup` CR — whose finalizer removes the pbm object from the shared bucket before the `Backup` is released, so a Plan does not accumulate objects in `cozy-backups`. A legacy backup writes to the tenant's own bucket and keeps the pre-existing hands-off contract (its lifecycle stays the tenant's / operator's; nothing is deleted on `Backup` removal). If the operator is down or storage is unreachable the `Backup` stays `Terminating` (a visible signal); annotate it `backups.cozystack.io/skip-artifact-cleanup: "true"` to release it and leave the object for a bucket lifecycle policy to reclaim. +Dropping `spec.backup.tasks` also drops the psmdb `keep` retention it carried, so on this flow **the driver owns the archive** the way the Rabbitmq/Redis drivers own theirs (an on-demand `PerconaServerMongoDBBackup` is not covered by psmdb task retention). The driver stamps the operator's `percona.com/delete-backup` finalizer onto each backup it mints here, and deleting a Cozystack `Backup` (a retention-pruned `Plan`, or a manual delete) deletes that `PerconaServerMongoDBBackup` CR — whose finalizer removes the pbm object from the shared bucket before the `Backup` is released, so a Plan does not accumulate objects in `cozy-backups`. A legacy backup writes to the tenant's own bucket and keeps the pre-existing hands-off contract (its lifecycle stays the tenant's / operator's; nothing is deleted on `Backup` removal). Note this prunes only when a `Backup` is deleted: unlike CNPG and MariaDB, which prune engine-side on their own schedule, MongoDB has no engine-side scheduled trim on this flow, so keeping `cozy-backups` bounded depends on a `Plan`'s retention actually deleting old `Backup` objects (scheduled retention at the `Plan` level is tracked as future work). When cleanup cannot complete — the namespace is terminating (the operator's delete-backup step cannot run there) or the operator is down — the driver strips its own finalizer and releases the `Backup` rather than pinning the namespace in `Terminating`, leaving the object for a bucket lifecycle policy to reclaim. Force that release early by annotating the `Backup` `backups.cozystack.io/skip-artifact-cleanup: "true"`. **Opting back out** (`useSystemBucket` true→false) is not automatic in reverse: the driver stops injecting, but the `s3-storage` entry it already applied stays on the live `PerconaServerMongoDB` under the driver's own field manager (`cozystack-psmdb-backup-driver`) — the chart does not own it and so never prunes it. It is inert once `backup.enabled=false`; to fully return a release to the legacy flow, delete that storage entry from the `PerconaServerMongoDB` by hand before re-declaring the tenant's own `backup.*` S3 values. diff --git a/internal/backupcontroller/psmdbstrategy_controller.go b/internal/backupcontroller/psmdbstrategy_controller.go index e6f4831be..60067e724 100644 --- a/internal/backupcontroller/psmdbstrategy_controller.go +++ b/internal/backupcontroller/psmdbstrategy_controller.go @@ -18,6 +18,7 @@ import ( "k8s.io/apimachinery/pkg/types" ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil" strategyv1alpha1 "github.com/cozystack/cozystack/api/backups/strategy/v1alpha1" backupsv1alpha1 "github.com/cozystack/cozystack/api/backups/v1alpha1" @@ -68,13 +69,6 @@ const ( psmdbBackupNamespaceKey = "psmdb.percona.com/backup-namespace" psmdbDestinationKey = "psmdb.percona.com/destination" - // psmdbUseSystemBucketKey records, on the Cozystack Backup, that the archive - // lives in the shared platform bucket (the useSystemBucket flow). The cleanup - // path keys off it: only system-bucket archives are the driver's to prune, so - // a legacy backup (tenant's own bucket, tenant-owned lifecycle) stays a no-op - // on deletion exactly as before. - psmdbUseSystemBucketKey = "backups.cozystack.io/use-system-bucket" - // psmdbDeleteBackupFinalizer is the psmdb-operator finalizer that removes the // pbm archive from object storage when its PerconaServerMongoDBBackup CR is // deleted. The driver stamps it onto the CRs it mints on the useSystemBucket @@ -270,11 +264,23 @@ func (r *BackupJobReconciler) reconcileMongoDB(ctx context.Context, j *backupsv1 // cluster, so a legacy app that ships its own static storage is left alone. // The path prefix is deterministic (/), so // re-applying the whole entry never splits the archive the way CNPG's - // serverName would. - if shouldInjectMongoDBSystemStorage(useSystemBucket, rendered) { + // serverName would. Gated additionally on backups being enabled: a cluster + // that can never service a backup should not be mutated just to fail the + // precondition below on the enabled check anyway. + if cluster.Spec.Backup.Enabled && shouldInjectMongoDBSystemStorage(useSystemBucket, rendered) { injected, err := r.applyMongoDBSystemStorage(ctx, j.Namespace, psmdbName, storageName, rendered.S3) if err != nil { - return r.markBackupJobFailed(ctx, j, fmt.Sprintf("failed to inject system-bucket storage onto psmdb.percona.com/PerconaServerMongoDB %s/%s: %v", j.Namespace, psmdbName, err)) + // A server-side apply can fail transiently — an apiserver hiccup, or a + // conflict while the psmdb operator writes the same cluster — so requeue + // with backoff rather than failing the BackupJob outright. The deadline + // still turns a permanently-failing apply terminal, matching how the + // cluster/app read errors above are handled. + if psmdbBackupDeadlineExceeded(j.Status.StartedAt) { + return r.markBackupJobFailed(ctx, j, fmt.Sprintf( + "failed to inject system-bucket storage onto psmdb.percona.com/PerconaServerMongoDB %s/%s within %s: %v", + j.Namespace, psmdbName, psmdbDefaultBackupDeadline, err)) + } + return ctrl.Result{}, err } cluster = injected } @@ -596,8 +602,11 @@ func (r *BackupJobReconciler) ensureMongoDBBackup(ctx context.Context, j *backup // delete-backup finalizer prunes the pbm object from storage when this CR // is deleted, which is how the cleanup path (Plan retention) reclaims // cozy-backups. A legacy backup writes to the tenant's own bucket and its - // lifecycle stays the tenant's, so it is left unfinalized. - obj.Finalizers = append(obj.Finalizers, psmdbDeleteBackupFinalizer) + // lifecycle stays the tenant's, so it is left unfinalized. This finalizer + // is also the sole ownership marker cleanup reads back: the psmdb operator + // never adds it on its own (verified against v1.22.0 checkFinalizers), so + // its presence unambiguously means "the driver owns this archive". + controllerutil.AddFinalizer(obj, psmdbDeleteBackupFinalizer) } if err := r.Create(ctx, obj); err != nil { @@ -662,11 +671,6 @@ func (r *BackupJobReconciler) createMongoDBBackupArtifact( if mdbBackup.Status.Destination != "" { driverMD[psmdbDestinationKey] = mdbBackup.Status.Destination } - if useSystemBucket { - // The cleanup path prunes only system-bucket archives (the shared bucket - // the driver owns); record the flow so a legacy backup stays hands-off. - driverMD[psmdbUseSystemBucketKey] = "true" - } underlyingResources, err := marshalMongoDBBackupSnapshot(mdbBackup, rendered, storageName, resolved.Parameters, useSystemBucket) if err != nil { @@ -712,22 +716,24 @@ func (r *BackupJobReconciler) createMongoDBBackupArtifact( // cleanupMongoDBBackup prunes the pbm archive a system-bucket Backup wrote to // the shared cozy-backups bucket when that Backup is deleted (Plan retention or -// manual). It deletes the operator PerconaServerMongoDBBackup CR and waits for -// the operator's delete-backup finalizer (stamped at creation by -// ensureMongoDBBackup) to remove the object from storage before releasing the -// Cozystack Backup, so no object is orphaned — the same "own the artifact, wait -// for the delete" contract the Redis/Rabbitmq branches use. A legacy backup -// (its own tenant bucket, no system-bucket marker) is left untouched, matching -// the pre-existing no-op contract for the operator-backed drivers. +// manual). Ownership is read from the operator CR's delete-backup finalizer, +// which ensureMongoDBBackup stamps only on the useSystemBucket flow and the +// psmdb operator never adds on its own — so its presence is the single, +// unambiguous "the driver owns this archive" marker (no separate driverMetadata +// flag that could disagree with the finalizer if the app's useSystemBucket flag +// flipped mid-backup). When the driver owns it, this deletes the operator CR and +// waits for the finalizer to remove the object before releasing the Cozystack +// Backup, so nothing is orphaned — the "own the artifact, wait for the delete" +// contract the Redis/Rabbitmq branches use. A legacy backup (no such finalizer) +// is left untouched, the pre-existing no-op contract for the operator-backed +// drivers. +// +// The wait is bounded by give-up conditions, so a wedged operator never pins a +// tenant namespace in Terminating: when the namespace is going away (the psmdb +// delete-backup exec cannot run there) or the escape-hatch annotation is set, +// the driver strips its own finalizer and releases, leaving the object for a +// bucket lifecycle policy to reclaim. func (r *BackupReconciler) cleanupMongoDBBackup(ctx context.Context, backup *backupsv1alpha1.Backup) (ctrl.Result, error) { - logger := getLogger(ctx) - - if backup.Spec.DriverMetadata[psmdbUseSystemBucketKey] != "true" { - // Legacy flow: the archive is in the tenant's own bucket and its - // lifecycle is the tenant's / psmdb operator's, not the platform's. - return ctrl.Result{}, nil - } - sourceBackupName := backup.Spec.DriverMetadata[psmdbBackupNameKey] if sourceBackupName == "" { // Nothing recorded to delete (Backup written before the name was tracked). @@ -737,20 +743,31 @@ func (r *BackupReconciler) cleanupMongoDBBackup(ctx context.Context, backup *bac live := &psmdbtypes.PerconaServerMongoDBBackup{} err := r.Get(ctx, types.NamespacedName{Namespace: backup.Namespace, Name: sourceBackupName}, live) if apierrors.IsNotFound(err) { - // The operator CR is gone, which — with the delete-backup finalizer set - // at creation — means the archive was pruned with it. Release. + // The operator CR is gone: a driver-owned archive was pruned with it (the + // finalizer ran), and a legacy CR that is gone was nothing of ours. Release. return ctrl.Result{}, nil } if err != nil { return ctrl.Result{}, err } - if backup.Annotations[psmdbSkipArtifactCleanupAnnotation] == "true" { - logger.Debug("skipping MongoDB artifact cleanup per annotation; object left in bucket", - "backup", backup.Name, "annotation", psmdbSkipArtifactCleanupAnnotation) + if !controllerutil.ContainsFinalizer(live, psmdbDeleteBackupFinalizer) { + // Legacy backup: the driver never stamped the prune finalizer, so the + // archive is the tenant's (its own bucket) and its lifecycle is not ours. return ctrl.Result{}, nil } + terminating, nsErr := r.namespaceTerminating(ctx, backup.Namespace) + if nsErr != nil { + return ctrl.Result{}, nsErr + } + if terminating { + return r.releaseMongoDBCleanup(ctx, backup, live, "namespace is terminating") + } + if backup.Annotations[psmdbSkipArtifactCleanupAnnotation] == "true" { + return r.releaseMongoDBCleanup(ctx, backup, live, "skip-artifact-cleanup annotation set") + } + if live.DeletionTimestamp.IsZero() { if derr := r.Delete(ctx, live); derr != nil && !apierrors.IsNotFound(derr) { return ctrl.Result{}, derr @@ -758,11 +775,39 @@ func (r *BackupReconciler) cleanupMongoDBBackup(ctx context.Context, backup *bac } // Requeue until the operator finalizer has removed the CR (and the archive // with it). - logger.Debug("waiting for psmdb operator to prune system-bucket archive", + getLogger(ctx).Debug("waiting for psmdb operator to prune system-bucket archive", "backup", backup.Name, "sourceBackup", sourceBackupName) return ctrl.Result{RequeueAfter: psmdbPollInterval}, nil } +// releaseMongoDBCleanup gives up pruning the archive and lets the Cozystack +// Backup (and any enclosing namespace) finish deleting: it strips the driver's +// delete-backup finalizer from the operator CR so the CR no longer blocks +// teardown, best-effort deletes that CR, and records a Warning naming the object +// left in the bucket. Mirrors the Redis/Rabbitmq release path — the prune is +// best-effort, not guaranteed. +func (r *BackupReconciler) releaseMongoDBCleanup(ctx context.Context, backup *backupsv1alpha1.Backup, live *psmdbtypes.PerconaServerMongoDBBackup, reason string) (ctrl.Result, error) { + if controllerutil.ContainsFinalizer(live, psmdbDeleteBackupFinalizer) { + base := live.DeepCopy() + controllerutil.RemoveFinalizer(live, psmdbDeleteBackupFinalizer) + if err := r.Patch(ctx, live, client.MergeFrom(base)); err != nil && !apierrors.IsNotFound(err) { + return ctrl.Result{}, err + } + } + if live.DeletionTimestamp.IsZero() { + if derr := r.Delete(ctx, live); derr != nil && !apierrors.IsNotFound(derr) { + return ctrl.Result{}, derr + } + } + getLogger(ctx).Info("releasing MongoDB Backup without pruning its object", + "backup", backup.Name, "sourceBackup", live.Name, "reason", reason) + if r.Recorder != nil { + r.Recorder.Eventf(backup, corev1.EventTypeWarning, "ArtifactNotDeleted", + "left MongoDB archive in the bucket: %s", reason) + } + return ctrl.Result{}, nil +} + // --------------------------------------------------------------------------- // RestoreJob path // --------------------------------------------------------------------------- @@ -988,13 +1033,14 @@ var errTransientRestoreSource = errors.New("transient backup-source resolution e // wrapped in errTransientRestoreSource so the caller can requeue instead. func (r *RestoreJobReconciler) resolveMongoDBBackupSource(ctx context.Context, backup *backupsv1alpha1.Backup) (*psmdbtypes.BackupSource, error) { // Snapshot persisted at backup time. Decoded up front so the live path can - // backfill an S3 block the operator status omits: on the useSystemBucket - // flow the driver injected the storage rather than the chart declaring it, - // and the operator can report status.destination while leaving status.s3 - // empty. Without the S3 block the restore has no endpoint/credentialsSecret, - // and a system-bucket target has no declared storage to resolve from either - // (injection runs only on the BackupJob path), so a live CR that echoes a - // destination but no s3 would otherwise strand the restore. + // backfill an S3 block the operator status omits. The pinned psmdb operator + // (v1.22.0) always echoes status.s3 once a backup reaches a destination + // (reconcilePBMConfig resolves the storage), so on that operator the live + // path already carries coordinates and this backfill is a defensive guard — + // an operator that reported a bare destination would otherwise strand a + // system-bucket restore, whose target has no chart-declared storage to + // resolve from (injection runs only on the BackupJob path). It keeps the + // snapshot the single fallback source, matching the reaped-CR path below. snap, snapErr := unmarshalMongoDBBackupSnapshot(backup.Status.UnderlyingResources) // Live operator Backup CR (same namespace as the Cozystack Backup). diff --git a/internal/backupcontroller/psmdbstrategy_controller_test.go b/internal/backupcontroller/psmdbstrategy_controller_test.go index bd1ed8f2b..5e7a0f5f5 100644 --- a/internal/backupcontroller/psmdbstrategy_controller_test.go +++ b/internal/backupcontroller/psmdbstrategy_controller_test.go @@ -11,12 +11,14 @@ import ( apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/types" "k8s.io/client-go/kubernetes/scheme" "k8s.io/client-go/tools/record" "sigs.k8s.io/controller-runtime/pkg/client" clientfake "sigs.k8s.io/controller-runtime/pkg/client/fake" "sigs.k8s.io/controller-runtime/pkg/client/interceptor" + "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil" strategyv1alpha1 "github.com/cozystack/cozystack/api/backups/strategy/v1alpha1" backupsv1alpha1 "github.com/cozystack/cozystack/api/backups/v1alpha1" @@ -1189,6 +1191,120 @@ func TestReconcileMongoDB_InjectsSystemStorageBeforePrecondition(t *testing.T) { } } +// mongodbInjectFixture builds the four objects reconcileMongoDB needs to reach +// the injection point on the useSystemBucket flow, parameterised on the live +// cluster's backup.enabled. +func mongodbInjectFixture(enabled bool) (*backupsv1alpha1.BackupJob, *strategyv1alpha1.MongoDB, *mongodbapp.MongoDB, *psmdbtypes.PerconaServerMongoDB, *ResolvedBackupConfig) { + apps := mongodbapp.GroupName + strategyGroup := strategyv1alpha1.GroupVersion.Group + now := metav1.Now() + job := &backupsv1alpha1.BackupJob{ + ObjectMeta: metav1.ObjectMeta{Namespace: "tenant", Name: "bj-inj"}, + Spec: backupsv1alpha1.BackupJobSpec{ + ApplicationRef: corev1.TypedLocalObjectReference{Kind: "MongoDB", Name: "app1", APIGroup: &apps}, + }, + Status: backupsv1alpha1.BackupJobStatus{StartedAt: &now}, + } + strategy := &strategyv1alpha1.MongoDB{ + ObjectMeta: metav1.ObjectMeta{Name: "cozy-default-mongodb"}, + Spec: strategyv1alpha1.MongoDBSpec{Template: strategyv1alpha1.MongoDBTemplate{ + StorageName: "s3-storage", + Type: "logical", + S3: &strategyv1alpha1.MongoDBStorageS3{ + Bucket: "cozy-backups", EndpointURL: "https://s3.example", + Prefix: "{{ .Application.metadata.namespace }}/{{ .Application.metadata.name }}", CredentialsSecret: "cozy-backups-creds", + }, + }}, + } + app := &mongodbapp.MongoDB{ + ObjectMeta: metav1.ObjectMeta{Namespace: "tenant", Name: "app1"}, + Spec: mongodbapp.MongoDBSpec{Backup: mongodbapp.MongoDBBackupSpec{UseSystemBucket: true}}, + } + cluster := &psmdbtypes.PerconaServerMongoDB{ + ObjectMeta: metav1.ObjectMeta{Namespace: "tenant", Name: "mongodb-app1"}, + Spec: psmdbtypes.PerconaServerMongoDBSpec{Backup: psmdbtypes.PerconaServerMongoDBBackupConfig{Enabled: enabled}}, + } + resolved := &ResolvedBackupConfig{ + StrategyRef: corev1.TypedLocalObjectReference{APIGroup: &strategyGroup, Kind: strategyv1alpha1.MongoDBStrategyKind, Name: "cozy-default-mongodb"}, + Parameters: map[string]string{}, + } + return job, strategy, app, cluster, resolved +} + +// A cluster that can never service a backup (backup.enabled=false) must not be +// mutated: injection is gated on Enabled so the disabled cluster fails the +// precondition on the enabled check without the driver having written storage +// onto it. +func TestReconcileMongoDB_DisabledClusterNotMutated(t *testing.T) { + job, strategy, app, cluster, resolved := mongodbInjectFixture(false) + c := newMongoDBStrategyTestClient(t, job, strategy, app, cluster) + r := &BackupJobReconciler{Client: c, Scheme: c.Scheme()} + + res, err := r.reconcileMongoDB(context.Background(), job.DeepCopy(), resolved) + if err != nil { + t.Fatalf("reconcileMongoDB: %v", err) + } + if res.RequeueAfter == 0 { + t.Fatalf("expected a waiting requeue for a disabled cluster, got %+v", res) + } + got := &psmdbtypes.PerconaServerMongoDB{} + if err := c.Get(context.Background(), types.NamespacedName{Namespace: "tenant", Name: "mongodb-app1"}, got); err != nil { + t.Fatalf("get cluster: %v", err) + } + if len(got.Spec.Backup.Storages) != 0 { + t.Errorf("disabled cluster must not be injected, got storages %#v", got.Spec.Backup.Storages) + } + list := &psmdbtypes.PerconaServerMongoDBBackupList{} + if err := c.List(context.Background(), list, client.InNamespace("tenant")); err != nil { + t.Fatalf("list: %v", err) + } + if len(list.Items) != 0 { + t.Errorf("no operator Backup should be created for a disabled cluster, got %d", len(list.Items)) + } +} + +// A server-side apply that fails transiently (apiserver hiccup, operator +// conflict) must requeue with backoff, not fail the BackupJob terminally. Before +// the fix the injection error went straight to markBackupJobFailed, so one +// transient apply killed the backup. +func TestReconcileMongoDB_InjectApplyErrorRequeues(t *testing.T) { + job, strategy, app, cluster, resolved := mongodbInjectFixture(true) + + s := runtime.NewScheme() + _ = scheme.AddToScheme(s) + _ = backupsv1alpha1.AddToScheme(s) + _ = strategyv1alpha1.AddToScheme(s) + _ = psmdbtypes.AddToScheme(s) + _ = mongodbapp.AddToScheme(s) + c := clientfake.NewClientBuilder(). + WithScheme(s). + WithObjects(job, strategy, app, cluster). + WithStatusSubresource(&backupsv1alpha1.BackupJob{}). + WithInterceptorFuncs(interceptor.Funcs{ + Patch: func(ctx context.Context, cl client.WithWatch, obj client.Object, patch client.Patch, opts ...client.PatchOption) error { + if _, ok := obj.(*psmdbtypes.PerconaServerMongoDB); ok { + return apierrors.NewConflict(schema.GroupResource{Group: "psmdb.percona.com", Resource: "perconaservermongodbs"}, obj.GetName(), errors.New("racing the operator")) + } + return cl.Patch(ctx, obj, patch, opts...) + }, + }). + Build() + r := &BackupJobReconciler{Client: c, Scheme: c.Scheme()} + + _, err := r.reconcileMongoDB(context.Background(), job.DeepCopy(), resolved) + if err == nil { + t.Fatal("expected a transient error so the caller requeues, got nil") + } + // The BackupJob must NOT be marked Failed by a transient apply error. + persisted := &backupsv1alpha1.BackupJob{} + if err := c.Get(context.Background(), types.NamespacedName{Namespace: "tenant", Name: "bj-inj"}, persisted); err != nil { + t.Fatalf("get job: %v", err) + } + if persisted.Status.Phase == backupsv1alpha1.BackupJobPhaseFailed { + t.Errorf("a transient inject error must not fail the BackupJob terminally") + } +} + // resolveMongoDBBackupSource must fill an S3 block the live operator status // omits from the snapshot: on the useSystemBucket flow the operator can report // status.destination with status.s3 empty (the storage was injected, not @@ -1244,75 +1360,107 @@ func TestResolveMongoDBBackupSource_LiveMissingS3BackfillsFromSnapshot(t *testin // --------------------------------------------------------------------------- func TestCleanupMongoDBBackup(t *testing.T) { - newBackup := func(md map[string]string, ann map[string]string) *backupsv1alpha1.Backup { + md := map[string]string{psmdbBackupNameKey: "op-bk"} + newBackup := func(ann map[string]string) *backupsv1alpha1.Backup { return &backupsv1alpha1.Backup{ ObjectMeta: metav1.ObjectMeta{Namespace: "tenant", Name: "cozy-bk", Annotations: ann}, Spec: backupsv1alpha1.BackupSpec{DriverMetadata: md}, } } - opBackup := func() *psmdbtypes.PerconaServerMongoDBBackup { - return &psmdbtypes.PerconaServerMongoDBBackup{ - ObjectMeta: metav1.ObjectMeta{Namespace: "tenant", Name: "op-bk", Finalizers: []string{psmdbDeleteBackupFinalizer}}, + // The delete-backup finalizer is the ownership marker: present = the driver + // owns the shared-bucket archive; absent = legacy (tenant bucket). + opBackup := func(finalized bool) *psmdbtypes.PerconaServerMongoDBBackup { + b := &psmdbtypes.PerconaServerMongoDBBackup{ + ObjectMeta: metav1.ObjectMeta{Namespace: "tenant", Name: "op-bk"}, } + if finalized { + b.Finalizers = []string{psmdbDeleteBackupFinalizer} + } + return b + } + liveNamespace := &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: "tenant"}} + getOp := func(t *testing.T, c client.Client) *psmdbtypes.PerconaServerMongoDBBackup { + got := &psmdbtypes.PerconaServerMongoDBBackup{} + if err := c.Get(context.Background(), types.NamespacedName{Namespace: "tenant", Name: "op-bk"}, got); err != nil { + t.Fatalf("get operator CR: %v", err) + } + return got } - t.Run("legacy backup is a no-op (tenant owns the archive)", func(t *testing.T) { - c := newMongoDBStrategyTestClient(t, opBackup()) + t.Run("legacy backup (no finalizer) is a no-op", func(t *testing.T) { + c := newMongoDBStrategyTestClient(t, opBackup(false), liveNamespace) r := &BackupReconciler{Client: c} - res, err := r.cleanupMongoDBBackup(context.Background(), newBackup(map[string]string{psmdbBackupNameKey: "op-bk"}, nil)) + res, err := r.cleanupMongoDBBackup(context.Background(), newBackup(nil)) if err != nil || res.RequeueAfter != 0 { t.Fatalf("legacy cleanup must be a no-op, got res=%+v err=%v", res, err) } - // The operator CR must be untouched (no delete issued). - got := &psmdbtypes.PerconaServerMongoDBBackup{} - if err := c.Get(context.Background(), types.NamespacedName{Namespace: "tenant", Name: "op-bk"}, got); err != nil { - t.Fatalf("operator CR should be untouched: %v", err) - } - if !got.DeletionTimestamp.IsZero() { + if !getOp(t, c).DeletionTimestamp.IsZero() { t.Errorf("legacy cleanup must not delete the operator CR") } }) - t.Run("system-bucket backup deletes the operator CR and waits", func(t *testing.T) { - c := newMongoDBStrategyTestClient(t, opBackup()) + t.Run("owned archive deletes the operator CR and waits", func(t *testing.T) { + c := newMongoDBStrategyTestClient(t, opBackup(true), liveNamespace) r := &BackupReconciler{Client: c} - md := map[string]string{psmdbBackupNameKey: "op-bk", psmdbUseSystemBucketKey: "true"} - res, err := r.cleanupMongoDBBackup(context.Background(), newBackup(md, nil)) + res, err := r.cleanupMongoDBBackup(context.Background(), newBackup(nil)) if err != nil { t.Fatalf("cleanupMongoDBBackup: %v", err) } if res.RequeueAfter == 0 { t.Fatalf("expected a requeue while the operator prunes the archive, got %+v", res) } - // The delete-backup finalizer holds the CR Terminating until the operator - // prunes the object; the driver must keep waiting, not release early. - got := &psmdbtypes.PerconaServerMongoDBBackup{} - if err := c.Get(context.Background(), types.NamespacedName{Namespace: "tenant", Name: "op-bk"}, got); err != nil { - t.Fatalf("operator CR should still exist under its finalizer: %v", err) - } + // The finalizer holds the CR Terminating until the operator prunes; the + // driver keeps its finalizer and waits, it does not strip it here. + got := getOp(t, c) if got.DeletionTimestamp.IsZero() { t.Errorf("expected the operator CR to be marked for deletion") } + if !controllerutil.ContainsFinalizer(got, psmdbDeleteBackupFinalizer) { + t.Errorf("driver must keep the finalizer while waiting, so the operator can prune") + } }) - t.Run("operator CR already gone releases (finalizer pruned the archive)", func(t *testing.T) { - c := newMongoDBStrategyTestClient(t) + t.Run("operator CR already gone releases", func(t *testing.T) { + c := newMongoDBStrategyTestClient(t, liveNamespace) r := &BackupReconciler{Client: c} - md := map[string]string{psmdbBackupNameKey: "op-bk", psmdbUseSystemBucketKey: "true"} - res, err := r.cleanupMongoDBBackup(context.Background(), newBackup(md, nil)) + res, err := r.cleanupMongoDBBackup(context.Background(), newBackup(nil)) if err != nil || res.RequeueAfter != 0 { t.Fatalf("a reaped operator CR must release, got res=%+v err=%v", res, err) } }) - t.Run("skip annotation releases without waiting", func(t *testing.T) { - c := newMongoDBStrategyTestClient(t, opBackup()) - r := &BackupReconciler{Client: c} - md := map[string]string{psmdbBackupNameKey: "op-bk", psmdbUseSystemBucketKey: "true"} - ann := map[string]string{psmdbSkipArtifactCleanupAnnotation: "true"} - res, err := r.cleanupMongoDBBackup(context.Background(), newBackup(md, ann)) + t.Run("skip annotation strips the finalizer and releases", func(t *testing.T) { + c := newMongoDBStrategyTestClient(t, opBackup(true), liveNamespace) + r := &BackupReconciler{Client: c, Recorder: record.NewFakeRecorder(10)} + res, err := r.cleanupMongoDBBackup(context.Background(), newBackup(map[string]string{psmdbSkipArtifactCleanupAnnotation: "true"})) if err != nil || res.RequeueAfter != 0 { t.Fatalf("skip annotation must release, got res=%+v err=%v", res, err) } + // Releasing strips our finalizer so the CR can be reaped (in the fake + // client, with no finalizer left, the best-effort delete removes it): the + // escape hatch actually unwedges. Tolerate either "gone" or "present + // without our finalizer". + got := &psmdbtypes.PerconaServerMongoDBBackup{} + err = c.Get(context.Background(), types.NamespacedName{Namespace: "tenant", Name: "op-bk"}, got) + if err == nil && controllerutil.ContainsFinalizer(got, psmdbDeleteBackupFinalizer) { + t.Errorf("release must strip the delete-backup finalizer; still present: %v", got.Finalizers) + } + }) + + t.Run("terminating namespace strips the finalizer and releases (no wedge)", func(t *testing.T) { + // No namespace object seeded → namespaceTerminating reports true, the + // teardown case. The driver must not requeue forever waiting on an + // operator that can no longer prune; it strips its finalizer and releases. + c := newMongoDBStrategyTestClient(t, opBackup(true)) + r := &BackupReconciler{Client: c, Recorder: record.NewFakeRecorder(10)} + res, err := r.cleanupMongoDBBackup(context.Background(), newBackup(nil)) + if err != nil || res.RequeueAfter != 0 { + t.Fatalf("teardown must release, not wedge; got res=%+v err=%v", res, err) + } + got := &psmdbtypes.PerconaServerMongoDBBackup{} + err = c.Get(context.Background(), types.NamespacedName{Namespace: "tenant", Name: "op-bk"}, got) + if err == nil && controllerutil.ContainsFinalizer(got, psmdbDeleteBackupFinalizer) { + t.Errorf("teardown must strip the finalizer so the namespace can finish; still present: %v", got.Finalizers) + } }) } diff --git a/internal/backupcontroller/psmdbtypes/types.go b/internal/backupcontroller/psmdbtypes/types.go index 573c3276a..d86bbdc5b 100644 --- a/internal/backupcontroller/psmdbtypes/types.go +++ b/internal/backupcontroller/psmdbtypes/types.go @@ -8,9 +8,13 @@ // // The driver reads PerconaServerMongoDB for an existence/backup-enabled gate, // creates PerconaServerMongoDBBackup CRs on the BackupJob path, and creates -// PerconaServerMongoDBRestore CRs on the RestoreJob path. It never patches the -// operator CRs, so the partial specs below only carry the fields the driver -// writes; unknown fields are preserved by the server on any merge patch. +// PerconaServerMongoDBRestore CRs on the RestoreJob path. On the useSystemBucket +// flow it also server-side-applies spec.backup.storages onto the live +// PerconaServerMongoDB (storage injection) and strips its own delete-backup +// finalizer from a PerconaServerMongoDBBackup on teardown. These partial specs +// carry only the fields the driver reads or writes; unknown fields are preserved +// by the server on any apply/merge patch, so injecting one subtree never drops +// the storage the operator resolved from the rest of the object. // // +groupName=psmdb.percona.com // +versionName=v1 diff --git a/packages/system/backupstrategy-controller/templates/rbac.yaml b/packages/system/backupstrategy-controller/templates/rbac.yaml index 8c2afbadb..aa032cad5 100644 --- a/packages/system/backupstrategy-controller/templates/rbac.yaml +++ b/packages/system/backupstrategy-controller/templates/rbac.yaml @@ -170,7 +170,10 @@ rules: # and prunes it on Cozystack Backup deletion by deleting this CR, whose # delete-backup finalizer frees the object (see cleanupMongoDBBackup). A legacy # backup lives in the tenant's own bucket and is never deleted here. - verbs: ["get", "list", "watch", "create", "delete"] + # patch: strip the driver's own delete-backup finalizer to release a wedged + # cleanup (namespace terminating, or the skip-artifact-cleanup annotation) so a + # stuck operator never pins a tenant namespace in Terminating. + verbs: ["get", "list", "watch", "create", "delete", "patch"] - apiGroups: ["psmdb.percona.com"] resources: ["perconaservermongodbrestores"] verbs: ["get", "list", "watch", "create"] From d58322e2537581eebb88abd6797f772d5b5586f8 Mon Sep 17 00:00:00 2001 From: Andrey Kolkov Date: Tue, 15 Sep 2026 14:56:34 +0400 Subject: [PATCH 0011/1280] fix(mongodb): let the system-bucket cleanup escape hatch survive an unreadable operator CR MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The two give-up paths sat behind the operator-CR Get, so a Get that hard-fails the way a removed CRD (NoKindMatchError) or a revoked verb (Forbidden) does returned the error and never reached the release — leaving a Backup that keeps its cleanup finalizer and requeues forever, exactly in the situation someone sets the escape-hatch annotation to get out of. Read the skip annotation before any apiserver call (as the Redis cleanup does) so it always releases, and classify NoMatchError alongside NotFound (as the Job/Redis cleanups do) so a missing CRD reads as "gone". releaseMongoDBCleanup now takes the CR name and treats every apiserver step as best-effort, so the release is never blocked by the same unreachable CR. Also correct the docs, which promised an automatic release when "the operator is down": only a terminating namespace or the annotation release. A down operator in a live namespace keeps the Backup in Terminating as a visible signal, which is what the code does. Assisted-By: LLM Signed-off-by: Andrey Kolkov --- docs/operations/backup-classes.md | 2 +- .../psmdbstrategy_controller.go | 68 +++++++++++-------- .../psmdbstrategy_controller_test.go | 44 ++++++++++++ 3 files changed, 86 insertions(+), 28 deletions(-) diff --git a/docs/operations/backup-classes.md b/docs/operations/backup-classes.md index 0a288cd53..0b3b31bb6 100644 --- a/docs/operations/backup-classes.md +++ b/docs/operations/backup-classes.md @@ -121,7 +121,7 @@ When `useSystemBucket: true`: Because the chart drops `spec.backup.tasks` and `spec.backup.pitr`, the psmdb operator's own scheduled backups and oplog PITR do **not** run on this flow — `backup.schedule` and `backup.retentionPolicy` stay in the schema for the default flow but have no effect here, and the `recoveryTime` PITR restores described below are not available. Migrate scheduled backups to a `backups.cozystack.io/Plan` against `cozy-default` instead. **Flipping this flag on a running app** removes the storage, tasks and pitr the app had, so a release that was taking scheduled backups + PITR before the flip stops until a `Plan` takes over. -Dropping `spec.backup.tasks` also drops the psmdb `keep` retention it carried, so on this flow **the driver owns the archive** the way the Rabbitmq/Redis drivers own theirs (an on-demand `PerconaServerMongoDBBackup` is not covered by psmdb task retention). The driver stamps the operator's `percona.com/delete-backup` finalizer onto each backup it mints here, and deleting a Cozystack `Backup` (a retention-pruned `Plan`, or a manual delete) deletes that `PerconaServerMongoDBBackup` CR — whose finalizer removes the pbm object from the shared bucket before the `Backup` is released, so a Plan does not accumulate objects in `cozy-backups`. A legacy backup writes to the tenant's own bucket and keeps the pre-existing hands-off contract (its lifecycle stays the tenant's / operator's; nothing is deleted on `Backup` removal). Note this prunes only when a `Backup` is deleted: unlike CNPG and MariaDB, which prune engine-side on their own schedule, MongoDB has no engine-side scheduled trim on this flow, so keeping `cozy-backups` bounded depends on a `Plan`'s retention actually deleting old `Backup` objects (scheduled retention at the `Plan` level is tracked as future work). When cleanup cannot complete — the namespace is terminating (the operator's delete-backup step cannot run there) or the operator is down — the driver strips its own finalizer and releases the `Backup` rather than pinning the namespace in `Terminating`, leaving the object for a bucket lifecycle policy to reclaim. Force that release early by annotating the `Backup` `backups.cozystack.io/skip-artifact-cleanup: "true"`. +Dropping `spec.backup.tasks` also drops the psmdb `keep` retention it carried, so on this flow **the driver owns the archive** the way the Rabbitmq/Redis drivers own theirs (an on-demand `PerconaServerMongoDBBackup` is not covered by psmdb task retention). The driver stamps the operator's `percona.com/delete-backup` finalizer onto each backup it mints here, and deleting a Cozystack `Backup` (a retention-pruned `Plan`, or a manual delete) deletes that `PerconaServerMongoDBBackup` CR — whose finalizer removes the pbm object from the shared bucket before the `Backup` is released, so a Plan does not accumulate objects in `cozy-backups`. A legacy backup writes to the tenant's own bucket and keeps the pre-existing hands-off contract (its lifecycle stays the tenant's / operator's; nothing is deleted on `Backup` removal). Note this prunes only when a `Backup` is deleted: unlike CNPG and MariaDB, which prune engine-side on their own schedule, MongoDB has no engine-side scheduled trim on this flow, so keeping `cozy-backups` bounded depends on a `Plan`'s retention actually deleting old `Backup` objects (scheduled retention at the `Plan` level is tracked as future work). Two cases release the `Backup` without waiting for the object to be pruned, so a wedged prune never pins a namespace in `Terminating`: a terminating namespace (where the operator's delete-backup step cannot run) and the `backups.cozystack.io/skip-artifact-cleanup: "true"` annotation. In both the driver strips its own finalizer and leaves the object for a bucket lifecycle policy to reclaim. A down operator or unreachable storage in a live namespace is NOT released automatically — the `Backup` stays `Terminating` as a visible signal until the operator recovers or you set that annotation to force the release. **Opting back out** (`useSystemBucket` true→false) is not automatic in reverse: the driver stops injecting, but the `s3-storage` entry it already applied stays on the live `PerconaServerMongoDB` under the driver's own field manager (`cozystack-psmdb-backup-driver`) — the chart does not own it and so never prunes it. It is inert once `backup.enabled=false`; to fully return a release to the legacy flow, delete that storage entry from the `PerconaServerMongoDB` by hand before re-declaring the tenant's own `backup.*` S3 values. diff --git a/internal/backupcontroller/psmdbstrategy_controller.go b/internal/backupcontroller/psmdbstrategy_controller.go index 60067e724..5cb894049 100644 --- a/internal/backupcontroller/psmdbstrategy_controller.go +++ b/internal/backupcontroller/psmdbstrategy_controller.go @@ -729,10 +729,13 @@ func (r *BackupJobReconciler) createMongoDBBackupArtifact( // drivers. // // The wait is bounded by give-up conditions, so a wedged operator never pins a -// tenant namespace in Terminating: when the namespace is going away (the psmdb -// delete-backup exec cannot run there) or the escape-hatch annotation is set, -// the driver strips its own finalizer and releases, leaving the object for a -// bucket lifecycle policy to reclaim. +// tenant namespace in Terminating: the escape-hatch annotation (honoured before +// any apiserver read, so it still frees a Backup whose operator CR has become +// unreadable) and a going-away namespace (the psmdb delete-backup exec cannot +// run there) each make the driver strip its own finalizer and release, leaving +// the object for a bucket lifecycle policy to reclaim. A down operator in a live +// namespace is NOT auto-released: the Backup stays Terminating as a visible +// signal until an operator recovers or the annotation is set. func (r *BackupReconciler) cleanupMongoDBBackup(ctx context.Context, backup *backupsv1alpha1.Backup) (ctrl.Result, error) { sourceBackupName := backup.Spec.DriverMetadata[psmdbBackupNameKey] if sourceBackupName == "" { @@ -740,11 +743,23 @@ func (r *BackupReconciler) cleanupMongoDBBackup(ctx context.Context, backup *bac return ctrl.Result{}, nil } + // Escape hatch first, before any apiserver read: the Backup must be releasable + // even when the operator CR cannot be read at all — its CRD removed, or the + // verb revoked — which is exactly the situation someone sets it in. Mirrors + // the Redis cleanup, which reads its skip annotation before it touches the + // apiserver. + if backup.Annotations[psmdbSkipArtifactCleanupAnnotation] == "true" { + return r.releaseMongoDBCleanup(ctx, backup, sourceBackupName, "skip-artifact-cleanup annotation set") + } + live := &psmdbtypes.PerconaServerMongoDBBackup{} err := r.Get(ctx, types.NamespacedName{Namespace: backup.Namespace, Name: sourceBackupName}, live) - if apierrors.IsNotFound(err) { - // The operator CR is gone: a driver-owned archive was pruned with it (the - // finalizer ran), and a legacy CR that is gone was nothing of ours. Release. + if apierrors.IsNotFound(err) || apimeta.IsNoMatchError(err) { + // The operator CR is gone (a driver-owned archive was pruned with it, and + // a legacy CR that is gone was nothing of ours), or its CRD is no longer + // served (nothing to strip when the kind itself is unmapped). Release. + // Classifying NoMatchError alongside NotFound matches the Job/Redis + // cleanups. return ctrl.Result{}, nil } if err != nil { @@ -762,10 +777,7 @@ func (r *BackupReconciler) cleanupMongoDBBackup(ctx context.Context, backup *bac return ctrl.Result{}, nsErr } if terminating { - return r.releaseMongoDBCleanup(ctx, backup, live, "namespace is terminating") - } - if backup.Annotations[psmdbSkipArtifactCleanupAnnotation] == "true" { - return r.releaseMongoDBCleanup(ctx, backup, live, "skip-artifact-cleanup annotation set") + return r.releaseMongoDBCleanup(ctx, backup, sourceBackupName, "namespace is terminating") } if live.DeletionTimestamp.IsZero() { @@ -781,26 +793,28 @@ func (r *BackupReconciler) cleanupMongoDBBackup(ctx context.Context, backup *bac } // releaseMongoDBCleanup gives up pruning the archive and lets the Cozystack -// Backup (and any enclosing namespace) finish deleting: it strips the driver's -// delete-backup finalizer from the operator CR so the CR no longer blocks -// teardown, best-effort deletes that CR, and records a Warning naming the object -// left in the bucket. Mirrors the Redis/Rabbitmq release path — the prune is -// best-effort, not guaranteed. -func (r *BackupReconciler) releaseMongoDBCleanup(ctx context.Context, backup *backupsv1alpha1.Backup, live *psmdbtypes.PerconaServerMongoDBBackup, reason string) (ctrl.Result, error) { - if controllerutil.ContainsFinalizer(live, psmdbDeleteBackupFinalizer) { - base := live.DeepCopy() - controllerutil.RemoveFinalizer(live, psmdbDeleteBackupFinalizer) - if err := r.Patch(ctx, live, client.MergeFrom(base)); err != nil && !apierrors.IsNotFound(err) { - return ctrl.Result{}, err +// Backup (and any enclosing namespace) finish deleting: best-effort, it strips +// the driver's delete-backup finalizer from the operator CR so the CR no longer +// blocks teardown and deletes that CR, then records a Warning naming the object +// left in the bucket. Every apiserver step is best-effort — a failed read or +// write is swallowed — because the caller reaches here precisely to let a wedged +// Backup go, and must never be blocked by the same unreachable CR. Takes the CR +// name rather than a fetched object so it works on the annotation path, which +// runs before any read. Mirrors the Redis/Rabbitmq release path. +func (r *BackupReconciler) releaseMongoDBCleanup(ctx context.Context, backup *backupsv1alpha1.Backup, sourceBackupName, reason string) (ctrl.Result, error) { + live := &psmdbtypes.PerconaServerMongoDBBackup{} + if err := r.Get(ctx, types.NamespacedName{Namespace: backup.Namespace, Name: sourceBackupName}, live); err == nil { + if controllerutil.ContainsFinalizer(live, psmdbDeleteBackupFinalizer) { + base := live.DeepCopy() + controllerutil.RemoveFinalizer(live, psmdbDeleteBackupFinalizer) + _ = r.Patch(ctx, live, client.MergeFrom(base)) } - } - if live.DeletionTimestamp.IsZero() { - if derr := r.Delete(ctx, live); derr != nil && !apierrors.IsNotFound(derr) { - return ctrl.Result{}, derr + if live.DeletionTimestamp.IsZero() { + _ = r.Delete(ctx, live) } } getLogger(ctx).Info("releasing MongoDB Backup without pruning its object", - "backup", backup.Name, "sourceBackup", live.Name, "reason", reason) + "backup", backup.Name, "sourceBackup", sourceBackupName, "reason", reason) if r.Recorder != nil { r.Recorder.Eventf(backup, corev1.EventTypeWarning, "ArtifactNotDeleted", "left MongoDB archive in the bucket: %s", reason) diff --git a/internal/backupcontroller/psmdbstrategy_controller_test.go b/internal/backupcontroller/psmdbstrategy_controller_test.go index 5e7a0f5f5..c53afea3b 100644 --- a/internal/backupcontroller/psmdbstrategy_controller_test.go +++ b/internal/backupcontroller/psmdbstrategy_controller_test.go @@ -9,6 +9,7 @@ import ( corev1 "k8s.io/api/core/v1" apierrors "k8s.io/apimachinery/pkg/api/errors" + apimeta "k8s.io/apimachinery/pkg/api/meta" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" @@ -1463,4 +1464,47 @@ func TestCleanupMongoDBBackup(t *testing.T) { t.Errorf("teardown must strip the finalizer so the namespace can finish; still present: %v", got.Finalizers) } }) + + // A client whose Get on the operator CR hard-fails the way a missing CRD or a + // revoked verb does — NoKindMatchError / an arbitrary error — models the case + // the escape hatch exists for. The annotation must free the Backup without + // depending on that read, and a bare NoMatchError must be treated as "gone". + failingGetClient := func(getErr error) client.Client { + s := runtime.NewScheme() + _ = scheme.AddToScheme(s) + _ = backupsv1alpha1.AddToScheme(s) + _ = psmdbtypes.AddToScheme(s) + return clientfake.NewClientBuilder(). + WithScheme(s). + WithInterceptorFuncs(interceptor.Funcs{ + Get: func(ctx context.Context, cl client.WithWatch, key client.ObjectKey, obj client.Object, opts ...client.GetOption) error { + if _, ok := obj.(*psmdbtypes.PerconaServerMongoDBBackup); ok { + return getErr + } + return cl.Get(ctx, key, obj, opts...) + }, + }). + Build() + } + noMatch := &apimeta.NoKindMatchError{GroupKind: schema.GroupKind{Group: "psmdb.percona.com", Kind: "PerconaServerMongoDBBackup"}} + + t.Run("skip annotation releases even when the operator CR is unreadable", func(t *testing.T) { + // The verb is revoked (Forbidden): the escape hatch runs before the Get, so + // it must still release rather than propagate the read error and wedge. + c := failingGetClient(apierrors.NewForbidden(schema.GroupResource{Group: "psmdb.percona.com", Resource: "perconaservermongodbbackups"}, "op-bk", errors.New("rbac revoked"))) + r := &BackupReconciler{Client: c, Recorder: record.NewFakeRecorder(10)} + res, err := r.cleanupMongoDBBackup(context.Background(), newBackup(map[string]string{psmdbSkipArtifactCleanupAnnotation: "true"})) + if err != nil || res.RequeueAfter != 0 { + t.Fatalf("annotation must release despite an unreadable operator CR, got res=%+v err=%v", res, err) + } + }) + + t.Run("a missing CRD (NoMatchError) releases instead of wedging", func(t *testing.T) { + c := failingGetClient(noMatch) + r := &BackupReconciler{Client: c} + res, err := r.cleanupMongoDBBackup(context.Background(), newBackup(nil)) + if err != nil || res.RequeueAfter != 0 { + t.Fatalf("NoMatchError must be treated as gone and release, got res=%+v err=%v", res, err) + } + }) } From cc51e040ae1677c3e643ad06d50bc6c5e5cce1b8 Mon Sep 17 00:00:00 2001 From: Andrey Kolkov Date: Tue, 15 Sep 2026 17:49:45 +0400 Subject: [PATCH 0012/1280] fix(mongodb): keep the cleanup escape hatch off legacy operator CRs, and surface a stuck finalizer MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The skip-artifact-cleanup annotation reaches releaseMongoDBCleanup before the ownership check, and the operator-CR delete sat outside the finalizer gate, so a legacy backup (no delete-backup finalizer) lost its PerconaServerMongoDBBackup record when a tenant set the annotation to release a stuck Backup or applied it across a namespace during teardown. That record is what a psmdb restore-by-name resolves against, and both the RBAC comment and the docs promise it is never touched. Gate every write in the release on the finalizer being present: an unowned (legacy) CR or one that cannot be read at all is left intact, and the Cozystack Backup still releases. Surface a failed finalizer strip. The release must proceed even against an unreachable CR, but the swallowed patch error left the operator CR holding percona.com/delete-backup — pinning its namespace in Terminating, the outcome the branch exists to prevent — while the Event reported the success case. Emit a FinalizerNotStripped Warning naming the object so an operator can find it. Mark the sibling backup fields (schedule, retentionPolicy, destinationPath, endpointURL, insecureSkipTLSVerify, s3AccessKey, s3SecretKey) as ignored under useSystemBucket, so a tenant editing one instead of the flag itself is not misled by a description that describes only the legacy flow; regenerate the schema, README and mongodb-rd. Pair the insecureSkipTLSVerify rendering assertion with a case that flips the platform knob on, so the two together discriminate the rendered value from a hardcoded default. Assisted-By: LLM Signed-off-by: Andrey Kolkov --- api/apps/v1alpha1/mongodb/types.go | 14 ++--- .../psmdbstrategy_controller.go | 59 +++++++++++++------ .../psmdbstrategy_controller_test.go | 54 +++++++++++++++++ packages/apps/mongodb/README.md | 14 ++--- packages/apps/mongodb/values.schema.json | 14 ++--- packages/apps/mongodb/values.yaml | 14 ++--- .../tests/rendering_test.yaml | 20 ++++++- .../system/mongodb-rd/cozyrds/mongodb.yaml | 2 +- 8 files changed, 141 insertions(+), 50 deletions(-) diff --git a/api/apps/v1alpha1/mongodb/types.go b/api/apps/v1alpha1/mongodb/types.go index 7c0f6f33f..89ebef1f7 100644 --- a/api/apps/v1alpha1/mongodb/types.go +++ b/api/apps/v1alpha1/mongodb/types.go @@ -60,28 +60,28 @@ type ConfigSpec struct { } type Backup struct { - // Destination path for backups (e.g. s3://bucket/path/). + // Destination path for backups (e.g. s3://bucket/path/). Ignored when useSystemBucket is true (the driver injects the platform bucket). // +kubebuilder:default:="s3://bucket/path/to/folder/" DestinationPath string `json:"destinationPath,omitempty"` // Enable regular backups. // +kubebuilder:default:=false Enabled bool `json:"enabled"` - // S3 endpoint URL for uploads. + // S3 endpoint URL for uploads. Ignored when useSystemBucket is true (the strategy supplies the platform endpoint). // +kubebuilder:default:="http://minio-gateway-service:9000" EndpointURL string `json:"endpointURL,omitempty"` - // Skip TLS verification for the S3 endpoint (self-signed, e.g. in-cluster seaweedfs). + // Skip TLS verification for the S3 endpoint (self-signed, e.g. in-cluster seaweedfs). Ignored when useSystemBucket is true (the platform backupStorage knob applies instead). // +kubebuilder:default:=false InsecureSkipTLSVerify bool `json:"insecureSkipTLSVerify,omitempty"` - // Retention policy (e.g. "30d"). + // Retention policy (e.g. "30d"). Ignored when useSystemBucket is true (no engine-side retention on that flow). // +kubebuilder:default:="30d" RetentionPolicy string `json:"retentionPolicy,omitempty"` - // Access key for S3 authentication. + // Access key for S3 authentication. Ignored when useSystemBucket is true (credentials come from the projected cozy-backups-creds). // +kubebuilder:default:="" S3AccessKey string `json:"s3AccessKey,omitempty"` - // Secret key for S3 authentication. + // Secret key for S3 authentication. Ignored when useSystemBucket is true (credentials come from the projected cozy-backups-creds). // +kubebuilder:default:="" S3SecretKey string `json:"s3SecretKey,omitempty"` - // Cron schedule for automated backups. + // Cron schedule for automated backups. Ignored when useSystemBucket is true (scheduling moves to the BackupClass Plan). // +kubebuilder:default:="0 2 * * *" Schedule string `json:"schedule,omitempty"` // Opt-in: back up to the platform system bucket without supplying S3 credentials. The cozy-default MongoDB BackupClass injects the storage at BackupJob time; tenants do not set s3AccessKey/s3SecretKey/destinationPath/endpointURL, and backups scope to `/`. Scheduling and retention move to the BackupClass Plan, so `schedule`, `retentionPolicy` and PITR are ignored while this is on. See docs/operations/backup-classes.md. diff --git a/internal/backupcontroller/psmdbstrategy_controller.go b/internal/backupcontroller/psmdbstrategy_controller.go index 5cb894049..cd17e61f0 100644 --- a/internal/backupcontroller/psmdbstrategy_controller.go +++ b/internal/backupcontroller/psmdbstrategy_controller.go @@ -792,28 +792,49 @@ func (r *BackupReconciler) cleanupMongoDBBackup(ctx context.Context, backup *bac return ctrl.Result{RequeueAfter: psmdbPollInterval}, nil } -// releaseMongoDBCleanup gives up pruning the archive and lets the Cozystack -// Backup (and any enclosing namespace) finish deleting: best-effort, it strips -// the driver's delete-backup finalizer from the operator CR so the CR no longer -// blocks teardown and deletes that CR, then records a Warning naming the object -// left in the bucket. Every apiserver step is best-effort — a failed read or -// write is swallowed — because the caller reaches here precisely to let a wedged -// Backup go, and must never be blocked by the same unreachable CR. Takes the CR -// name rather than a fetched object so it works on the annotation path, which -// runs before any read. Mirrors the Redis/Rabbitmq release path. +// releaseMongoDBCleanup lets the Cozystack Backup (and any enclosing namespace) +// finish deleting when the archive cannot be pruned in place. It only ever +// touches an operator CR the driver OWNS — one carrying the delete-backup +// finalizer: it strips that finalizer so the CR no longer blocks teardown and +// deletes it. A legacy CR (no finalizer) or one that cannot be read at all is +// left entirely intact, so the never-deleted contract for legacy backups holds +// even though the annotation reaches this path before the ownership check, and +// an unreadable CR still releases. The finalizer strip is best-effort — the +// release must proceed even against an unreachable CR — but a failed strip is +// surfaced (log + Event), because the CR then keeps the finalizer and can hold +// its namespace in Terminating, and the operator needs to know which one. Takes +// the CR name so it works on the annotation path, which runs before any read. func (r *BackupReconciler) releaseMongoDBCleanup(ctx context.Context, backup *backupsv1alpha1.Backup, sourceBackupName, reason string) (ctrl.Result, error) { + logger := getLogger(ctx) live := &psmdbtypes.PerconaServerMongoDBBackup{} - if err := r.Get(ctx, types.NamespacedName{Namespace: backup.Namespace, Name: sourceBackupName}, live); err == nil { - if controllerutil.ContainsFinalizer(live, psmdbDeleteBackupFinalizer) { - base := live.DeepCopy() - controllerutil.RemoveFinalizer(live, psmdbDeleteBackupFinalizer) - _ = r.Patch(ctx, live, client.MergeFrom(base)) - } - if live.DeletionTimestamp.IsZero() { - _ = r.Delete(ctx, live) - } + err := r.Get(ctx, types.NamespacedName{Namespace: backup.Namespace, Name: sourceBackupName}, live) + if err != nil || !controllerutil.ContainsFinalizer(live, psmdbDeleteBackupFinalizer) { + // Legacy backup (no delete-backup finalizer) or an unreadable CR: nothing + // of the driver's to strip or delete. Leave the operator CR untouched and + // release the Cozystack Backup. + logger.Debug("releasing MongoDB Backup; no driver-owned archive to prune", + "backup", backup.Name, "sourceBackup", sourceBackupName, "reason", reason) + return ctrl.Result{}, nil } - getLogger(ctx).Info("releasing MongoDB Backup without pruning its object", + + base := live.DeepCopy() + controllerutil.RemoveFinalizer(live, psmdbDeleteBackupFinalizer) + if perr := r.Patch(ctx, live, client.MergeFrom(base)); perr != nil { + // The release still proceeds (an unreachable CR must not wedge the + // Backup), but the CR keeps the finalizer and can pin its namespace in + // Terminating — surface which object so an operator can find it. + logger.Info("released MongoDB Backup but could not strip the delete-backup finalizer; the operator CR may hold its namespace in Terminating", + "backup", backup.Name, "sourceBackup", sourceBackupName, "reason", reason, "error", perr) + if r.Recorder != nil { + r.Recorder.Eventf(backup, corev1.EventTypeWarning, "FinalizerNotStripped", + "released Backup but could not strip the delete-backup finalizer from PerconaServerMongoDBBackup %s (%v); it may keep the namespace in Terminating", sourceBackupName, perr) + } + return ctrl.Result{}, nil + } + if live.DeletionTimestamp.IsZero() { + _ = r.Delete(ctx, live) + } + logger.Info("releasing MongoDB Backup, leaving its shared-bucket object for a lifecycle policy", "backup", backup.Name, "sourceBackup", sourceBackupName, "reason", reason) if r.Recorder != nil { r.Recorder.Eventf(backup, corev1.EventTypeWarning, "ArtifactNotDeleted", diff --git a/internal/backupcontroller/psmdbstrategy_controller_test.go b/internal/backupcontroller/psmdbstrategy_controller_test.go index c53afea3b..203177650 100644 --- a/internal/backupcontroller/psmdbstrategy_controller_test.go +++ b/internal/backupcontroller/psmdbstrategy_controller_test.go @@ -5,6 +5,7 @@ import ( "context" "errors" "fmt" + "strings" "testing" corev1 "k8s.io/api/core/v1" @@ -1507,4 +1508,57 @@ func TestCleanupMongoDBBackup(t *testing.T) { t.Fatalf("NoMatchError must be treated as gone and release, got res=%+v err=%v", res, err) } }) + + // The annotation reaches releaseMongoDBCleanup before the ownership check, so + // the release must itself refuse to touch a CR the driver does not own — the + // legacy operator-side backup record is what a psmdb restore-by-name resolves + // against, and the RBAC comment and docs both promise it is never deleted. + t.Run("legacy backup with the skip annotation keeps its operator CR", func(t *testing.T) { + c := newMongoDBStrategyTestClient(t, opBackup(false), liveNamespace) + r := &BackupReconciler{Client: c, Recorder: record.NewFakeRecorder(10)} + res, err := r.cleanupMongoDBBackup(context.Background(), newBackup(map[string]string{psmdbSkipArtifactCleanupAnnotation: "true"})) + if err != nil || res.RequeueAfter != 0 { + t.Fatalf("legacy + annotation must release, got res=%+v err=%v", res, err) + } + got := getOp(t, c) + if !got.DeletionTimestamp.IsZero() { + t.Errorf("the escape hatch must not delete a legacy (unowned) operator CR") + } + }) + + // When the finalizer strip fails, the CR keeps percona.com/delete-backup and + // can pin its namespace in Terminating; the release still proceeds, but it + // must say which object is stuck rather than emit the success-case Event. + t.Run("a failed finalizer strip surfaces the stuck object", func(t *testing.T) { + s := runtime.NewScheme() + _ = scheme.AddToScheme(s) + _ = backupsv1alpha1.AddToScheme(s) + _ = psmdbtypes.AddToScheme(s) + c := clientfake.NewClientBuilder(). + WithScheme(s). + WithObjects(opBackup(true)). + WithInterceptorFuncs(interceptor.Funcs{ + Patch: func(ctx context.Context, cl client.WithWatch, obj client.Object, patch client.Patch, opts ...client.PatchOption) error { + if _, ok := obj.(*psmdbtypes.PerconaServerMongoDBBackup); ok { + return apierrors.NewServiceUnavailable("apiserver down") + } + return cl.Patch(ctx, obj, patch, opts...) + }, + }). + Build() + rec := record.NewFakeRecorder(10) + r := &BackupReconciler{Client: c, Recorder: rec} + res, err := r.cleanupMongoDBBackup(context.Background(), newBackup(map[string]string{psmdbSkipArtifactCleanupAnnotation: "true"})) + if err != nil || res.RequeueAfter != 0 { + t.Fatalf("release must proceed even when the strip fails, got res=%+v err=%v", res, err) + } + select { + case ev := <-rec.Events: + if !strings.Contains(ev, "FinalizerNotStripped") || !strings.Contains(ev, "op-bk") { + t.Errorf("expected a FinalizerNotStripped event naming the object, got %q", ev) + } + default: + t.Errorf("expected an event surfacing the stuck finalizer, got none") + } + }) } diff --git a/packages/apps/mongodb/README.md b/packages/apps/mongodb/README.md index af033c2b8..e779a7353 100644 --- a/packages/apps/mongodb/README.md +++ b/packages/apps/mongodb/README.md @@ -252,13 +252,13 @@ Releases with `external: false`, and sharded releases in any configuration, are | `backup` | Backup configuration. | `object` | `{}` | | `backup.enabled` | Enable regular backups. | `bool` | `false` | | `backup.useSystemBucket` | Opt-in: back up to the platform system bucket without supplying S3 credentials. The cozy-default MongoDB BackupClass injects the storage at BackupJob time; tenants do not set s3AccessKey/s3SecretKey/destinationPath/endpointURL, and backups scope to `/`. Scheduling and retention move to the BackupClass Plan, so `schedule`, `retentionPolicy` and PITR are ignored while this is on. See docs/operations/backup-classes.md. | `bool` | `false` | -| `backup.schedule` | Cron schedule for automated backups. | `string` | `0 2 * * *` | -| `backup.retentionPolicy` | Retention policy (e.g. "30d"). | `string` | `30d` | -| `backup.destinationPath` | Destination path for backups (e.g. s3://bucket/path/). | `string` | `s3://bucket/path/to/folder/` | -| `backup.endpointURL` | S3 endpoint URL for uploads. | `string` | `http://minio-gateway-service:9000` | -| `backup.insecureSkipTLSVerify` | Skip TLS verification for the S3 endpoint (self-signed, e.g. in-cluster seaweedfs). | `bool` | `false` | -| `backup.s3AccessKey` | Access key for S3 authentication. | `string` | `""` | -| `backup.s3SecretKey` | Secret key for S3 authentication. | `string` | `""` | +| `backup.schedule` | Cron schedule for automated backups. Ignored when useSystemBucket is true (scheduling moves to the BackupClass Plan). | `string` | `0 2 * * *` | +| `backup.retentionPolicy` | Retention policy (e.g. "30d"). Ignored when useSystemBucket is true (no engine-side retention on that flow). | `string` | `30d` | +| `backup.destinationPath` | Destination path for backups (e.g. s3://bucket/path/). Ignored when useSystemBucket is true (the driver injects the platform bucket). | `string` | `s3://bucket/path/to/folder/` | +| `backup.endpointURL` | S3 endpoint URL for uploads. Ignored when useSystemBucket is true (the strategy supplies the platform endpoint). | `string` | `http://minio-gateway-service:9000` | +| `backup.insecureSkipTLSVerify` | Skip TLS verification for the S3 endpoint (self-signed, e.g. in-cluster seaweedfs). Ignored when useSystemBucket is true (the platform backupStorage knob applies instead). | `bool` | `false` | +| `backup.s3AccessKey` | Access key for S3 authentication. Ignored when useSystemBucket is true (credentials come from the projected cozy-backups-creds). | `string` | `""` | +| `backup.s3SecretKey` | Secret key for S3 authentication. Ignored when useSystemBucket is true (credentials come from the projected cozy-backups-creds). | `string` | `""` | ### Bootstrap (recovery) parameters diff --git a/packages/apps/mongodb/values.schema.json b/packages/apps/mongodb/values.schema.json index a6fdd3f46..5680ea65c 100644 --- a/packages/apps/mongodb/values.schema.json +++ b/packages/apps/mongodb/values.schema.json @@ -273,7 +273,7 @@ ], "properties": { "destinationPath": { - "description": "Destination path for backups (e.g. s3://bucket/path/).", + "description": "Destination path for backups (e.g. s3://bucket/path/). Ignored when useSystemBucket is true (the driver injects the platform bucket).", "type": "string", "default": "s3://bucket/path/to/folder/" }, @@ -283,32 +283,32 @@ "default": false }, "endpointURL": { - "description": "S3 endpoint URL for uploads.", + "description": "S3 endpoint URL for uploads. Ignored when useSystemBucket is true (the strategy supplies the platform endpoint).", "type": "string", "default": "http://minio-gateway-service:9000" }, "insecureSkipTLSVerify": { - "description": "Skip TLS verification for the S3 endpoint (self-signed, e.g. in-cluster seaweedfs).", + "description": "Skip TLS verification for the S3 endpoint (self-signed, e.g. in-cluster seaweedfs). Ignored when useSystemBucket is true (the platform backupStorage knob applies instead).", "type": "boolean", "default": false }, "retentionPolicy": { - "description": "Retention policy (e.g. \"30d\").", + "description": "Retention policy (e.g. \"30d\"). Ignored when useSystemBucket is true (no engine-side retention on that flow).", "type": "string", "default": "30d" }, "s3AccessKey": { - "description": "Access key for S3 authentication.", + "description": "Access key for S3 authentication. Ignored when useSystemBucket is true (credentials come from the projected cozy-backups-creds).", "type": "string", "default": "" }, "s3SecretKey": { - "description": "Secret key for S3 authentication.", + "description": "Secret key for S3 authentication. Ignored when useSystemBucket is true (credentials come from the projected cozy-backups-creds).", "type": "string", "default": "" }, "schedule": { - "description": "Cron schedule for automated backups.", + "description": "Cron schedule for automated backups. Ignored when useSystemBucket is true (scheduling moves to the BackupClass Plan).", "type": "string", "default": "0 2 * * *" }, diff --git a/packages/apps/mongodb/values.yaml b/packages/apps/mongodb/values.yaml index 660332029..10dd250e3 100644 --- a/packages/apps/mongodb/values.yaml +++ b/packages/apps/mongodb/values.yaml @@ -156,13 +156,13 @@ databases: {} ## @typedef {struct} Backup - Backup configuration. ## @field {bool} enabled - Enable regular backups. ## @field {bool} [useSystemBucket] - Opt-in: back up to the platform system bucket without supplying S3 credentials. The cozy-default MongoDB BackupClass injects the storage at BackupJob time; tenants do not set s3AccessKey/s3SecretKey/destinationPath/endpointURL, and backups scope to `/`. Scheduling and retention move to the BackupClass Plan, so `schedule`, `retentionPolicy` and PITR are ignored while this is on. See docs/operations/backup-classes.md. -## @field {string} [schedule] - Cron schedule for automated backups. -## @field {string} [retentionPolicy] - Retention policy (e.g. "30d"). -## @field {string} [destinationPath] - Destination path for backups (e.g. s3://bucket/path/). -## @field {string} [endpointURL] - S3 endpoint URL for uploads. -## @field {bool} [insecureSkipTLSVerify] - Skip TLS verification for the S3 endpoint (self-signed, e.g. in-cluster seaweedfs). -## @field {string} [s3AccessKey] - Access key for S3 authentication. -## @field {string} [s3SecretKey] - Secret key for S3 authentication. +## @field {string} [schedule] - Cron schedule for automated backups. Ignored when useSystemBucket is true (scheduling moves to the BackupClass Plan). +## @field {string} [retentionPolicy] - Retention policy (e.g. "30d"). Ignored when useSystemBucket is true (no engine-side retention on that flow). +## @field {string} [destinationPath] - Destination path for backups (e.g. s3://bucket/path/). Ignored when useSystemBucket is true (the driver injects the platform bucket). +## @field {string} [endpointURL] - S3 endpoint URL for uploads. Ignored when useSystemBucket is true (the strategy supplies the platform endpoint). +## @field {bool} [insecureSkipTLSVerify] - Skip TLS verification for the S3 endpoint (self-signed, e.g. in-cluster seaweedfs). Ignored when useSystemBucket is true (the platform backupStorage knob applies instead). +## @field {string} [s3AccessKey] - Access key for S3 authentication. Ignored when useSystemBucket is true (credentials come from the projected cozy-backups-creds). +## @field {string} [s3SecretKey] - Secret key for S3 authentication. Ignored when useSystemBucket is true (credentials come from the projected cozy-backups-creds). ## @param {Backup} backup - Backup configuration. backup: diff --git a/packages/system/backupstrategy-controller/tests/rendering_test.yaml b/packages/system/backupstrategy-controller/tests/rendering_test.yaml index 695f82792..5bb5cc1d7 100644 --- a/packages/system/backupstrategy-controller/tests/rendering_test.yaml +++ b/packages/system/backupstrategy-controller/tests/rendering_test.yaml @@ -179,8 +179,10 @@ tests: value: true template: templates/strategy-mongodb-default.yaml # insecureSkipTLSVerify is plumbed end-to-end (strategy -> driver-injected - # storage entry); the template must render it from the platform knob, not - # leave it unset (which pins the injected entry to false regardless). + # storage entry). This case pins the default (knob off -> false); the + # "renders insecureSkipTLSVerify from the platform knob" case below flips + # the knob on, so the pair discriminates the rendered value from a + # hardcoded literal (either would redden one of the two). - equal: path: spec.template.s3.insecureSkipTLSVerify value: false @@ -240,6 +242,20 @@ tests: value: "true" template: templates/velero-bsl.yaml + - it: "the MongoDB strategy renders insecureSkipTLSVerify from the platform knob" + # Pairs with the default (false) assertion above: with the knob flipped on, + # the injected storage entry must carry true. A template that hardcoded either + # literal would redden one of the two cases, so together they prove the value + # tracks backupStorage.insecureSkipTLSVerify rather than a constant. + set: + backupStorage.bucketNameOverride: test-bucket + backupStorage.insecureSkipTLSVerify: true + asserts: + - equal: + path: spec.template.s3.insecureSkipTLSVerify + value: true + template: templates/strategy-mongodb-default.yaml + - it: "external S3 (provisionBucket=false): Strategy CRs render against the configured bucketName, no Bucket CR is created" set: backupStorage.provisionBucket: false diff --git a/packages/system/mongodb-rd/cozyrds/mongodb.yaml b/packages/system/mongodb-rd/cozyrds/mongodb.yaml index 1e8b69f48..0b0ee8863 100644 --- a/packages/system/mongodb-rd/cozyrds/mongodb.yaml +++ b/packages/system/mongodb-rd/cozyrds/mongodb.yaml @@ -8,7 +8,7 @@ spec: singular: mongodb plural: mongodbs openAPISchema: |- - {"title":"Chart Values","type":"object","properties":{"replicas":{"description":"Number of MongoDB replicas in replica set.","type":"integer","default":3},"resources":{"description":"Explicit CPU and memory configuration for each MongoDB replica. When omitted, the preset defined in `resourcesPreset` is applied.","type":"object","default":{},"properties":{"cpu":{"description":"CPU available to each replica.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"memory":{"description":"Memory (RAM) available to each replica.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true}}},"resourcesPreset":{"description":"Default sizing preset used when `resources` is omitted.","type":"string","default":"t1.small","enum":["t1.nano","t1.micro","t1.small","t1.medium","t1.large","t1.xlarge","t1.2xlarge","t1.4xlarge","c1.nano","c1.micro","c1.small","c1.medium","c1.large","c1.xlarge","c1.2xlarge","c1.4xlarge","s1.nano","s1.micro","s1.small","s1.medium","s1.large","s1.xlarge","s1.2xlarge","s1.4xlarge","u1.nano","u1.micro","u1.small","u1.medium","u1.large","u1.xlarge","u1.2xlarge","u1.4xlarge","m1.nano","m1.micro","m1.small","m1.medium","m1.large","m1.xlarge","m1.2xlarge","m1.4xlarge","nano","micro","small","medium","large","xlarge","2xlarge"]},"size":{"description":"Persistent Volume Claim size available for application data.","default":"10Gi","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"storageClass":{"description":"StorageClass used to store the data.","type":"string","default":"","x-kubernetes-validations":[{"rule":"self == oldSelf","message":"storageClass is immutable"}],"x-cozystack-options":{"source":"storageclass"}},"external":{"description":"Enable external access from outside the cluster.","type":"boolean","default":false},"version":{"description":"MongoDB major version to deploy.","type":"string","default":"v8","enum":["v8","v7","v6"]},"sharding":{"description":"Enable sharded cluster mode. When disabled, deploys a replica set.","type":"boolean","default":false},"shardingConfig":{"description":"Configuration for sharded cluster mode.","type":"object","default":{},"required":["configServerSize","configServers","mongos"],"properties":{"configServerSize":{"description":"PVC size for config servers.","default":"3Gi","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"configServers":{"description":"Number of config server replicas.","type":"integer","default":3},"mongos":{"description":"Number of mongos router replicas.","type":"integer","default":2},"shards":{"description":"List of shard configurations.","type":"array","default":[{"name":"rs0","replicas":3,"size":"10Gi"}],"items":{"type":"object","required":["name","replicas","size"],"properties":{"name":{"description":"Shard name.","type":"string"},"replicas":{"description":"Number of replicas in this shard.","type":"integer"},"size":{"description":"PVC size for this shard.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true}}}}}},"users":{"description":"Users configuration map.","type":"object","default":{},"additionalProperties":{"type":"object","properties":{"password":{"description":"Password for the user (auto-generated if omitted).","type":"string"}}}},"databases":{"description":"Databases configuration map.","type":"object","default":{},"additionalProperties":{"type":"object","properties":{"roles":{"description":"Roles assigned to users.","type":"object","properties":{"admin":{"description":"List of users with admin privileges (readWrite + dbAdmin).","type":"array","items":{"type":"string"}},"readonly":{"description":"List of users with read-only privileges.","type":"array","items":{"type":"string"}}}}}}},"backup":{"description":"Backup configuration.","type":"object","default":{},"required":["enabled"],"properties":{"destinationPath":{"description":"Destination path for backups (e.g. s3://bucket/path/).","type":"string","default":"s3://bucket/path/to/folder/"},"enabled":{"description":"Enable regular backups.","type":"boolean","default":false},"endpointURL":{"description":"S3 endpoint URL for uploads.","type":"string","default":"http://minio-gateway-service:9000"},"insecureSkipTLSVerify":{"description":"Skip TLS verification for the S3 endpoint (self-signed, e.g. in-cluster seaweedfs).","type":"boolean","default":false},"retentionPolicy":{"description":"Retention policy (e.g. \"30d\").","type":"string","default":"30d"},"s3AccessKey":{"description":"Access key for S3 authentication.","type":"string","default":""},"s3SecretKey":{"description":"Secret key for S3 authentication.","type":"string","default":""},"schedule":{"description":"Cron schedule for automated backups.","type":"string","default":"0 2 * * *"},"useSystemBucket":{"description":"Opt-in: back up to the platform system bucket without supplying S3 credentials. The cozy-default MongoDB BackupClass injects the storage at BackupJob time; tenants do not set s3AccessKey/s3SecretKey/destinationPath/endpointURL, and backups scope to `/`. Scheduling and retention move to the BackupClass Plan, so `schedule`, `retentionPolicy` and PITR are ignored while this is on. See docs/operations/backup-classes.md.","type":"boolean","default":false}}},"bootstrap":{"description":"Bootstrap configuration.","type":"object","default":{},"required":["backupName","enabled"],"properties":{"backupName":{"description":"Name of backup to restore from.","type":"string","default":""},"enabled":{"description":"Whether to restore from a backup.","type":"boolean","default":false},"recoveryTime":{"description":"Timestamp for point-in-time recovery; empty means latest.","type":"string","default":""}}}}} + {"title":"Chart Values","type":"object","properties":{"replicas":{"description":"Number of MongoDB replicas in replica set.","type":"integer","default":3},"resources":{"description":"Explicit CPU and memory configuration for each MongoDB replica. When omitted, the preset defined in `resourcesPreset` is applied.","type":"object","default":{},"properties":{"cpu":{"description":"CPU available to each replica.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"memory":{"description":"Memory (RAM) available to each replica.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true}}},"resourcesPreset":{"description":"Default sizing preset used when `resources` is omitted.","type":"string","default":"t1.small","enum":["t1.nano","t1.micro","t1.small","t1.medium","t1.large","t1.xlarge","t1.2xlarge","t1.4xlarge","c1.nano","c1.micro","c1.small","c1.medium","c1.large","c1.xlarge","c1.2xlarge","c1.4xlarge","s1.nano","s1.micro","s1.small","s1.medium","s1.large","s1.xlarge","s1.2xlarge","s1.4xlarge","u1.nano","u1.micro","u1.small","u1.medium","u1.large","u1.xlarge","u1.2xlarge","u1.4xlarge","m1.nano","m1.micro","m1.small","m1.medium","m1.large","m1.xlarge","m1.2xlarge","m1.4xlarge","nano","micro","small","medium","large","xlarge","2xlarge"]},"size":{"description":"Persistent Volume Claim size available for application data.","default":"10Gi","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"storageClass":{"description":"StorageClass used to store the data.","type":"string","default":"","x-kubernetes-validations":[{"rule":"self == oldSelf","message":"storageClass is immutable"}],"x-cozystack-options":{"source":"storageclass"}},"external":{"description":"Enable external access from outside the cluster.","type":"boolean","default":false},"version":{"description":"MongoDB major version to deploy.","type":"string","default":"v8","enum":["v8","v7","v6"]},"sharding":{"description":"Enable sharded cluster mode. When disabled, deploys a replica set.","type":"boolean","default":false},"shardingConfig":{"description":"Configuration for sharded cluster mode.","type":"object","default":{},"required":["configServerSize","configServers","mongos"],"properties":{"configServerSize":{"description":"PVC size for config servers.","default":"3Gi","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"configServers":{"description":"Number of config server replicas.","type":"integer","default":3},"mongos":{"description":"Number of mongos router replicas.","type":"integer","default":2},"shards":{"description":"List of shard configurations.","type":"array","default":[{"name":"rs0","replicas":3,"size":"10Gi"}],"items":{"type":"object","required":["name","replicas","size"],"properties":{"name":{"description":"Shard name.","type":"string"},"replicas":{"description":"Number of replicas in this shard.","type":"integer"},"size":{"description":"PVC size for this shard.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true}}}}}},"users":{"description":"Users configuration map.","type":"object","default":{},"additionalProperties":{"type":"object","properties":{"password":{"description":"Password for the user (auto-generated if omitted).","type":"string"}}}},"databases":{"description":"Databases configuration map.","type":"object","default":{},"additionalProperties":{"type":"object","properties":{"roles":{"description":"Roles assigned to users.","type":"object","properties":{"admin":{"description":"List of users with admin privileges (readWrite + dbAdmin).","type":"array","items":{"type":"string"}},"readonly":{"description":"List of users with read-only privileges.","type":"array","items":{"type":"string"}}}}}}},"backup":{"description":"Backup configuration.","type":"object","default":{},"required":["enabled"],"properties":{"destinationPath":{"description":"Destination path for backups (e.g. s3://bucket/path/). Ignored when useSystemBucket is true (the driver injects the platform bucket).","type":"string","default":"s3://bucket/path/to/folder/"},"enabled":{"description":"Enable regular backups.","type":"boolean","default":false},"endpointURL":{"description":"S3 endpoint URL for uploads. Ignored when useSystemBucket is true (the strategy supplies the platform endpoint).","type":"string","default":"http://minio-gateway-service:9000"},"insecureSkipTLSVerify":{"description":"Skip TLS verification for the S3 endpoint (self-signed, e.g. in-cluster seaweedfs). Ignored when useSystemBucket is true (the platform backupStorage knob applies instead).","type":"boolean","default":false},"retentionPolicy":{"description":"Retention policy (e.g. \"30d\"). Ignored when useSystemBucket is true (no engine-side retention on that flow).","type":"string","default":"30d"},"s3AccessKey":{"description":"Access key for S3 authentication. Ignored when useSystemBucket is true (credentials come from the projected cozy-backups-creds).","type":"string","default":""},"s3SecretKey":{"description":"Secret key for S3 authentication. Ignored when useSystemBucket is true (credentials come from the projected cozy-backups-creds).","type":"string","default":""},"schedule":{"description":"Cron schedule for automated backups. Ignored when useSystemBucket is true (scheduling moves to the BackupClass Plan).","type":"string","default":"0 2 * * *"},"useSystemBucket":{"description":"Opt-in: back up to the platform system bucket without supplying S3 credentials. The cozy-default MongoDB BackupClass injects the storage at BackupJob time; tenants do not set s3AccessKey/s3SecretKey/destinationPath/endpointURL, and backups scope to `/`. Scheduling and retention move to the BackupClass Plan, so `schedule`, `retentionPolicy` and PITR are ignored while this is on. See docs/operations/backup-classes.md.","type":"boolean","default":false}}},"bootstrap":{"description":"Bootstrap configuration.","type":"object","default":{},"required":["backupName","enabled"],"properties":{"backupName":{"description":"Name of backup to restore from.","type":"string","default":""},"enabled":{"description":"Whether to restore from a backup.","type":"boolean","default":false},"recoveryTime":{"description":"Timestamp for point-in-time recovery; empty means latest.","type":"string","default":""}}}}} release: prefix: mongodb- labels: From f8554d289d531d33e0ff86e94d53d62c1e069f1f Mon Sep 17 00:00:00 2001 From: Andrey Kolkov Date: Wed, 16 Sep 2026 11:46:50 +0400 Subject: [PATCH 0013/1280] fix(mongodb): stop the system-bucket flow stranding archives, and reject an inert retentionPolicy MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two ways the shared cozy-backups bucket could accumulate objects nothing prunes. A dump that outran the 30-minute deadline was declared failed while pbm kept writing. The BackupJob's terminal-phase guard then never runs the branch that mints the Cozystack Backup, so the archive lands with no Backup object to represent it and no retention can reach it (the operator CR carries no ownerRef either). Leave a running dump to finish — a real dataset routinely outruns 30m, and a broken one still terminates through the operator's error/rejected state. The deadline keeps bounding the case it was written for: the operator never starts the backup (state stays "", requested or waiting), where nothing has been written and failing strands nothing. retentionPolicy is inert on this flow (the chart's tasks[].keep is gated out and no Plan-level retention exists yet), so a value a tenant set expecting it to work would grow the bucket silently. Reject a retentionPolicy changed from the chart default when useSystemBucket is on, rather than ignore it; the default still renders so an untouched install is unaffected. Also on the cleanup path: hand the terminating-namespace release the operator CR the caller already read and confirmed owned, so the finalizer strip is not gated on a second Get whose transient failure would silently drop it and leave the CR finalized in a namespace being torn down. Correct the ownership comments — the delete-backup finalizer is not one the operator never sets (it finalizes task-minted backups on the legacy flow); what keeps it unambiguous is that cleanup only ever resolves the one CR named in driverMetadata. Add the missing isolation test that a legacy app's own s3-storage is never overwritten by the injection call site, and move the strategy's storage comment into a Go-template comment so it no longer ships into every rendered Strategy CR. Assisted-By: LLM Signed-off-by: Andrey Kolkov --- .../psmdbstrategy_controller.go | 97 +++++++++---- .../psmdbstrategy_controller_test.go | 137 ++++++++++++++++++ packages/apps/mongodb/templates/mongodb.yaml | 12 ++ packages/apps/mongodb/tests/mongodb_test.yaml | 37 +++++ .../templates/strategy-mongodb-default.yaml | 16 +- 5 files changed, 263 insertions(+), 36 deletions(-) diff --git a/internal/backupcontroller/psmdbstrategy_controller.go b/internal/backupcontroller/psmdbstrategy_controller.go index cd17e61f0..6f3804968 100644 --- a/internal/backupcontroller/psmdbstrategy_controller.go +++ b/internal/backupcontroller/psmdbstrategy_controller.go @@ -343,16 +343,17 @@ func (r *BackupJobReconciler) reconcileMongoDB(ctx context.Context, j *backupsv1 return r.markBackupJobFailed(ctx, j, message) default: - // Still in progress ("", requested, running, waiting). Apply a - // wall-clock deadline so a permanently-stuck backup eventually fails - // the BackupJob instead of pinning it Running forever. - if psmdbBackupDeadlineExceeded(j.Status.StartedAt) { + // Still in progress ("", requested, running, waiting). A wall-clock + // deadline fails a backup the operator never starts (so it cannot pin the + // BackupJob Running forever), but a running dump is left to finish rather + // than stranding its archive — see psmdbBackupTimedOut. + if psmdbBackupTimedOut(state, j.Status.StartedAt) { detail := "no state observed" if state != "" { detail = fmt.Sprintf("state=%s", state) } return r.markBackupJobFailed(ctx, j, fmt.Sprintf( - "psmdb.percona.com PerconaServerMongoDBBackup did not complete within %s (%s)", psmdbDefaultBackupDeadline, detail)) + "psmdb.percona.com PerconaServerMongoDBBackup did not start within %s (%s)", psmdbDefaultBackupDeadline, detail)) } return ctrl.Result{RequeueAfter: psmdbPollInterval}, nil } @@ -565,6 +566,25 @@ func psmdbBackupDeadlineExceeded(startedAt *metav1.Time) bool { return time.Since(startedAt.Time) > psmdbDefaultBackupDeadline } +// psmdbBackupTimedOut reports whether an in-progress operator backup should be +// failed on the wall-clock deadline. A dump the operator is actively writing +// (state=running) is never timed out: pbm keeps streaming into the shared bucket +// after the driver gives up, and the BackupJob's terminal-phase guard means the +// artifact-creating branch never runs again — so failing a running dump would +// strand an archive that no Backup object represents and no retention can reach +// (the operator CR carries no ownerRef either). A real dataset routinely outruns +// 30m, and a genuinely broken dump terminates through the operator's own +// error/rejected state, so a running backup is left to finish. The deadline +// still bounds the case it was written for — the operator never starts the +// backup (state stays "", requested or waiting), where nothing has been written +// and failing strands nothing. +func psmdbBackupTimedOut(state string, startedAt *metav1.Time) bool { + if state == psmdbtypes.StateRunning { + return false + } + return psmdbBackupDeadlineExceeded(startedAt) +} + // ensureMongoDBBackup creates a one-shot PerconaServerMongoDBBackup CR labelled // with the BackupJob, or returns the existing one if a previous reconcile // already created it. Idempotency relies on the OwningJob labels. @@ -601,11 +621,14 @@ func (r *BackupJobReconciler) ensureMongoDBBackup(ctx context.Context, j *backup // Own the archive's lifecycle on the shared bucket: the operator's // delete-backup finalizer prunes the pbm object from storage when this CR // is deleted, which is how the cleanup path (Plan retention) reclaims - // cozy-backups. A legacy backup writes to the tenant's own bucket and its - // lifecycle stays the tenant's, so it is left unfinalized. This finalizer - // is also the sole ownership marker cleanup reads back: the psmdb operator - // never adds it on its own (verified against v1.22.0 checkFinalizers), so - // its presence unambiguously means "the driver owns this archive". + // cozy-backups. A legacy backup writes to the tenant's own bucket and is + // left unfinalized, so cleanup reads it as unowned. That finalizer check + // is only ever run against the one CR this function minted — cleanup + // resolves it by the backup-name recorded in driverMetadata, never by + // label or by scanning the namespace — so a task-minted CR that the + // operator itself finalizes on the legacy flow (spec.backup.tasks with a + // delete-from-storage retention) is never in scope and never mistaken for + // ours. controllerutil.AddFinalizer(obj, psmdbDeleteBackupFinalizer) } @@ -716,11 +739,13 @@ func (r *BackupJobReconciler) createMongoDBBackupArtifact( // cleanupMongoDBBackup prunes the pbm archive a system-bucket Backup wrote to // the shared cozy-backups bucket when that Backup is deleted (Plan retention or -// manual). Ownership is read from the operator CR's delete-backup finalizer, -// which ensureMongoDBBackup stamps only on the useSystemBucket flow and the -// psmdb operator never adds on its own — so its presence is the single, -// unambiguous "the driver owns this archive" marker (no separate driverMetadata -// flag that could disagree with the finalizer if the app's useSystemBucket flag +// manual). Ownership is read from the delete-backup finalizer on the ONE +// operator CR named in driverMetadata (the one ensureMongoDBBackup minted for +// this Backup) — resolved by name, never by label or scan, so a task-minted CR +// the operator finalizes on the legacy flow is out of scope. ensureMongoDBBackup +// stamps that finalizer only on the useSystemBucket flow, so its presence on the +// named CR is the "the driver owns this archive" marker (and there is no separate +// driverMetadata flag that could disagree if the app's useSystemBucket flag // flipped mid-backup). When the driver owns it, this deletes the operator CR and // waits for the finalizer to remove the object before releasing the Cozystack // Backup, so nothing is orphaned — the "own the artifact, wait for the delete" @@ -749,7 +774,9 @@ func (r *BackupReconciler) cleanupMongoDBBackup(ctx context.Context, backup *bac // the Redis cleanup, which reads its skip annotation before it touches the // apiserver. if backup.Annotations[psmdbSkipArtifactCleanupAnnotation] == "true" { - return r.releaseMongoDBCleanup(ctx, backup, sourceBackupName, "skip-artifact-cleanup annotation set") + // No object in hand (this runs before any read); releaseMongoDBCleanup + // does the best-effort fetch. + return r.releaseMongoDBCleanup(ctx, backup, sourceBackupName, nil, "skip-artifact-cleanup annotation set") } live := &psmdbtypes.PerconaServerMongoDBBackup{} @@ -777,7 +804,11 @@ func (r *BackupReconciler) cleanupMongoDBBackup(ctx context.Context, backup *bac return ctrl.Result{}, nsErr } if terminating { - return r.releaseMongoDBCleanup(ctx, backup, sourceBackupName, "namespace is terminating") + // Hand down the object already read and confirmed owned above, so the + // release strips its finalizer without a second Get that a transient + // throttle/Forbidden could fold into "nothing of ours" — leaving the CR + // finalized in a namespace being torn down, the exact wedge this prevents. + return r.releaseMongoDBCleanup(ctx, backup, sourceBackupName, live, "namespace is terminating") } if live.DeletionTimestamp.IsZero() { @@ -802,19 +833,27 @@ func (r *BackupReconciler) cleanupMongoDBBackup(ctx context.Context, backup *bac // an unreadable CR still releases. The finalizer strip is best-effort — the // release must proceed even against an unreachable CR — but a failed strip is // surfaced (log + Event), because the CR then keeps the finalizer and can hold -// its namespace in Terminating, and the operator needs to know which one. Takes -// the CR name so it works on the annotation path, which runs before any read. -func (r *BackupReconciler) releaseMongoDBCleanup(ctx context.Context, backup *backupsv1alpha1.Backup, sourceBackupName, reason string) (ctrl.Result, error) { +// its namespace in Terminating, and the operator needs to know which one. +// +// `live` is the object the caller already read and confirmed owned; the +// terminating path passes it so the strip is not gated on a second Get whose +// transient failure would silently drop it. The annotation path passes nil (it +// runs before any read), and this does the best-effort fetch itself — an +// unreadable or unowned CR is then left intact and the Backup still releases. +func (r *BackupReconciler) releaseMongoDBCleanup(ctx context.Context, backup *backupsv1alpha1.Backup, sourceBackupName string, live *psmdbtypes.PerconaServerMongoDBBackup, reason string) (ctrl.Result, error) { logger := getLogger(ctx) - live := &psmdbtypes.PerconaServerMongoDBBackup{} - err := r.Get(ctx, types.NamespacedName{Namespace: backup.Namespace, Name: sourceBackupName}, live) - if err != nil || !controllerutil.ContainsFinalizer(live, psmdbDeleteBackupFinalizer) { - // Legacy backup (no delete-backup finalizer) or an unreadable CR: nothing - // of the driver's to strip or delete. Leave the operator CR untouched and - // release the Cozystack Backup. - logger.Debug("releasing MongoDB Backup; no driver-owned archive to prune", - "backup", backup.Name, "sourceBackup", sourceBackupName, "reason", reason) - return ctrl.Result{}, nil + if live == nil { + fetched := &psmdbtypes.PerconaServerMongoDBBackup{} + if err := r.Get(ctx, types.NamespacedName{Namespace: backup.Namespace, Name: sourceBackupName}, fetched); err != nil || + !controllerutil.ContainsFinalizer(fetched, psmdbDeleteBackupFinalizer) { + // Legacy backup (no delete-backup finalizer) or an unreadable CR: + // nothing of the driver's to strip or delete. Leave the operator CR + // untouched and release the Cozystack Backup. + logger.Debug("releasing MongoDB Backup; no driver-owned archive to prune", + "backup", backup.Name, "sourceBackup", sourceBackupName, "reason", reason) + return ctrl.Result{}, nil + } + live = fetched } base := live.DeepCopy() diff --git a/internal/backupcontroller/psmdbstrategy_controller_test.go b/internal/backupcontroller/psmdbstrategy_controller_test.go index 203177650..34773f5ee 100644 --- a/internal/backupcontroller/psmdbstrategy_controller_test.go +++ b/internal/backupcontroller/psmdbstrategy_controller_test.go @@ -7,6 +7,7 @@ import ( "fmt" "strings" "testing" + "time" corev1 "k8s.io/api/core/v1" apierrors "k8s.io/apimachinery/pkg/api/errors" @@ -1562,3 +1563,139 @@ func TestCleanupMongoDBBackup(t *testing.T) { } }) } + +// A dump the operator is actively writing (state=running) must never be failed +// on the wall-clock deadline: pbm keeps streaming into the shared bucket after +// the driver gives up, so failing it strands an archive no Backup object +// represents. Only a backup the operator never started trips the deadline. +func TestPsmdbBackupTimedOut(t *testing.T) { + past := &metav1.Time{Time: time.Now().Add(-2 * psmdbDefaultBackupDeadline)} + recent := &metav1.Time{Time: time.Now()} + cases := []struct { + state string + started *metav1.Time + want bool + }{ + {psmdbtypes.StateRunning, past, false}, // progressing: keep polling, never strand the archive + {psmdbtypes.StateWaiting, past, true}, // never started: safe to fail, nothing written + {psmdbtypes.StateRequested, past, true}, // + {"", past, true}, // operator never observed it + {psmdbtypes.StateRunning, recent, false}, // running, deadline not reached + {psmdbtypes.StateWaiting, recent, false}, // not yet past the deadline + {psmdbtypes.StateRunning, nil, false}, // no StartedAt + } + for _, tc := range cases { + if got := psmdbBackupTimedOut(tc.state, tc.started); got != tc.want { + t.Errorf("psmdbBackupTimedOut(state=%q, past=%v): got %v want %v", tc.state, tc.started == past, got, tc.want) + } + } +} + +// The SSA-patch call site is the one place that could force-overwrite a running +// legacy tenant's own s3-storage entry. On the legacy flow (useSystemBucket +// false) the driver must never touch the cluster, even when the cluster is +// otherwise ready to back up — the injection is gated on the app flag, not on +// the live storage set. +func TestReconcileMongoDB_LegacyClusterNotPatched(t *testing.T) { + apps := mongodbapp.GroupName + strategyGroup := strategyv1alpha1.GroupVersion.Group + now := metav1.Now() + + job := &backupsv1alpha1.BackupJob{ + ObjectMeta: metav1.ObjectMeta{Namespace: "tenant", Name: "bj-legacy"}, + Spec: backupsv1alpha1.BackupJobSpec{ + ApplicationRef: corev1.TypedLocalObjectReference{Kind: "MongoDB", Name: "app1", APIGroup: &apps}, + }, + Status: backupsv1alpha1.BackupJobStatus{StartedAt: &now}, + } + // Strategy still carries S3 coordinates (they live on the shared default), so + // the guard cannot lean on rendered.S3 being nil — only the app flag. + strategy := &strategyv1alpha1.MongoDB{ + ObjectMeta: metav1.ObjectMeta{Name: "cozy-default-mongodb"}, + Spec: strategyv1alpha1.MongoDBSpec{Template: strategyv1alpha1.MongoDBTemplate{ + StorageName: "s3-storage", + Type: "logical", + S3: &strategyv1alpha1.MongoDBStorageS3{Bucket: "cozy-backups", EndpointURL: "https://s3.example", CredentialsSecret: "cozy-backups-creds"}, + }}, + } + app := &mongodbapp.MongoDB{ + ObjectMeta: metav1.ObjectMeta{Namespace: "tenant", Name: "app1"}, + Spec: mongodbapp.MongoDBSpec{Backup: mongodbapp.MongoDBBackupSpec{UseSystemBucket: false}}, + } + // Legacy cluster with backups enabled AND its own tenant-bucket storage. + ownStorage := runtime.RawExtension{Raw: []byte(`{"type":"s3","s3":{"bucket":"tenant-own","credentialsSecret":"mongodb-app1-s3-creds"}}`)} + cluster := &psmdbtypes.PerconaServerMongoDB{ + ObjectMeta: metav1.ObjectMeta{Namespace: "tenant", Name: "mongodb-app1"}, + Spec: psmdbtypes.PerconaServerMongoDBSpec{Backup: psmdbtypes.PerconaServerMongoDBBackupConfig{ + Enabled: true, + Storages: map[string]runtime.RawExtension{"s3-storage": ownStorage}, + }}, + } + + c := newMongoDBStrategyTestClient(t, job, strategy, app, cluster) + r := &BackupJobReconciler{Client: c, Scheme: c.Scheme()} + resolved := &ResolvedBackupConfig{ + StrategyRef: corev1.TypedLocalObjectReference{APIGroup: &strategyGroup, Kind: strategyv1alpha1.MongoDBStrategyKind, Name: "cozy-default-mongodb"}, + Parameters: map[string]string{}, + } + + if _, err := r.reconcileMongoDB(context.Background(), job.DeepCopy(), resolved); err != nil { + t.Fatalf("reconcileMongoDB: %v", err) + } + + got := &psmdbtypes.PerconaServerMongoDB{} + if err := c.Get(context.Background(), types.NamespacedName{Namespace: "tenant", Name: "mongodb-app1"}, got); err != nil { + t.Fatalf("get cluster: %v", err) + } + bucket, _ := psmdbStorageS3(got.Spec.Backup.Storages["s3-storage"]) + if bucket != "tenant-own" { + t.Errorf("legacy tenant's own s3-storage was overwritten: bucket=%q, want tenant-own", bucket) + } +} + +// releaseMongoDBCleanup must strip the finalizer off the object the caller +// already read and confirmed owned, without a second Get whose transient +// failure would silently drop the strip and wedge a terminating namespace. +func TestReleaseMongoDBCleanup_UsesPassedObjectNotReRead(t *testing.T) { + owned := &psmdbtypes.PerconaServerMongoDBBackup{ + ObjectMeta: metav1.ObjectMeta{Namespace: "tenant", Name: "op-bk", Finalizers: []string{psmdbDeleteBackupFinalizer}}, + } + s := runtime.NewScheme() + _ = scheme.AddToScheme(s) + _ = backupsv1alpha1.AddToScheme(s) + _ = psmdbtypes.AddToScheme(s) + c := clientfake.NewClientBuilder(). + WithScheme(s). + WithObjects(owned.DeepCopy()). + WithInterceptorFuncs(interceptor.Funcs{ + Get: func(ctx context.Context, cl client.WithWatch, key client.ObjectKey, obj client.Object, opts ...client.GetOption) error { + if _, ok := obj.(*psmdbtypes.PerconaServerMongoDBBackup); ok { + return apierrors.NewServiceUnavailable("read throttled") + } + return cl.Get(ctx, key, obj, opts...) + }, + }). + Build() + rec := record.NewFakeRecorder(10) + r := &BackupReconciler{Client: c, Recorder: rec} + backup := &backupsv1alpha1.Backup{ + ObjectMeta: metav1.ObjectMeta{Namespace: "tenant", Name: "cozy-bk"}, + Spec: backupsv1alpha1.BackupSpec{DriverMetadata: map[string]string{psmdbBackupNameKey: "op-bk"}}, + } + + res, err := r.releaseMongoDBCleanup(context.Background(), backup, "op-bk", owned.DeepCopy(), "namespace is terminating") + if err != nil || res.RequeueAfter != 0 { + t.Fatalf("release must proceed, got res=%+v err=%v", res, err) + } + // The owned-strip path fires ArtifactNotDeleted; if the code had re-read the + // CR (Get throttled), it would have taken the quiet "nothing of ours" path + // with no event — so the event proves the passed object was used. + select { + case ev := <-rec.Events: + if !strings.Contains(ev, "ArtifactNotDeleted") { + t.Errorf("expected the owned-release event proving the passed object was used, got %q", ev) + } + default: + t.Errorf("expected an ArtifactNotDeleted event (passed object used, strip ran), got none") + } +} diff --git a/packages/apps/mongodb/templates/mongodb.yaml b/packages/apps/mongodb/templates/mongodb.yaml index 66e497a41..2173fdd52 100644 --- a/packages/apps/mongodb/templates/mongodb.yaml +++ b/packages/apps/mongodb/templates/mongodb.yaml @@ -217,6 +217,18 @@ spec: {{- end }} {{- end }} + {{- /* + useSystemBucket cannot honour backup.retentionPolicy: the tasks[].keep block + below (the chart's only retention) is gated out on this flow, and no + Plan-level retention exists yet, so a retentionPolicy set here would silently + grow the shared cozy-backups bucket. Reject a value the tenant changed from + the chart default rather than ignore it — an untouched useSystemBucket install + keeps rendering. $defaultRetentionPolicy MUST track the values.yaml default. + */}} + {{- $defaultRetentionPolicy := "30d" }} + {{- if and .Values.backup.useSystemBucket .Values.backup.retentionPolicy (ne .Values.backup.retentionPolicy $defaultRetentionPolicy) }} + {{- fail (printf "backup.retentionPolicy=%q cannot be honoured when backup.useSystemBucket=true: the platform flow has no engine-side retention and Plan-level retention is not yet available (see docs/operations/backup-classes.md). Remove backup.retentionPolicy, or drive scheduled backups and retention through a backups.cozystack.io/Plan." .Values.backup.retentionPolicy) }} + {{- end }} backup: enabled: {{ .Values.backup.enabled | default false }} image: percona/percona-backup-mongodb:2.11.0 diff --git a/packages/apps/mongodb/tests/mongodb_test.yaml b/packages/apps/mongodb/tests/mongodb_test.yaml index 1eb60275a..308e19a9c 100644 --- a/packages/apps/mongodb/tests/mongodb_test.yaml +++ b/packages/apps/mongodb/tests/mongodb_test.yaml @@ -93,6 +93,43 @@ tests: path: spec.backup.pitr documentIndex: 0 + - it: rejects a non-default retentionPolicy on useSystemBucket + # The platform flow cannot honour retentionPolicy (no engine-side trim, no + # Plan retention yet), so a value the tenant changed from the default is a + # hard error rather than a silent no-op that grows the shared bucket. + release: + name: test-mongodb + namespace: tenant-test + set: + _cluster: + cluster-domain: cozy.local + backup: + enabled: true + useSystemBucket: true + retentionPolicy: 7d + asserts: + - failedTemplate: + errorMessage: 'backup.retentionPolicy="7d" cannot be honoured when backup.useSystemBucket=true: the platform flow has no engine-side retention and Plan-level retention is not yet available (see docs/operations/backup-classes.md). Remove backup.retentionPolicy, or drive scheduled backups and retention through a backups.cozystack.io/Plan.' + + - it: allows the default retentionPolicy on useSystemBucket + # The untouched default must still render, so the guard only fires on a + # tenant-changed value (this pins the discriminator, not just the reject). + release: + name: test-mongodb + namespace: tenant-test + set: + _cluster: + cluster-domain: cozy.local + backup: + enabled: true + useSystemBucket: true + retentionPolicy: 30d + asserts: + - equal: + path: spec.backup.enabled + value: true + documentIndex: 0 + ################## # Finalizers # ################## diff --git a/packages/system/backupstrategy-controller/templates/strategy-mongodb-default.yaml b/packages/system/backupstrategy-controller/templates/strategy-mongodb-default.yaml index 5e71b25d2..3bf8ff407 100644 --- a/packages/system/backupstrategy-controller/templates/strategy-mongodb-default.yaml +++ b/packages/system/backupstrategy-controller/templates/strategy-mongodb-default.yaml @@ -59,13 +59,15 @@ spec: storageName: s3-storage type: logical compressionType: gzip - # System-bucket coordinates the driver SSA-injects onto the source - # PerconaServerMongoDB's spec.backup.storages[s3-storage] when the app ran - # with backup.useSystemBucket=true (the chart then omits the static - # storage). A legacy app leaves the flag false and is never injected, so it - # keeps its own static s3-storage. endpointUrl carries the scheme from the - # endpoint helper so PBM's aws-sdk client gets a valid URL; credentials come - # from the projected cozy-backups-creds. + {{- /* + System-bucket coordinates the driver SSA-injects onto the source + PerconaServerMongoDB's spec.backup.storages[s3-storage] when the app ran + with backup.useSystemBucket=true (the chart then omits the static storage). + A legacy app leaves the flag false and is never injected, so it keeps its + own static s3-storage. endpointUrl carries the scheme from the endpoint + helper so PBM's aws-sdk client gets a valid URL; credentials come from the + projected cozy-backups-creds. See docs/operations/backup-classes.md. + */}} s3: bucket: {{ $bucketName | quote }} endpointUrl: {{ include "backupstrategy-controller.endpoint" . | quote }} From a89321fa8ce8315461b27d771a45c3b0aaed9abd Mon Sep 17 00:00:00 2001 From: Andrey Kolkov Date: Wed, 16 Sep 2026 14:48:11 +0400 Subject: [PATCH 0014/1280] fix(mongodb): keep retentionPolicy a genuine no-op, and cancel a timed-out backup so it cannot orphan an archive MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Every prose surface (the useSystemBucket field, the retentionPolicy field, and backup-classes.md) tells a tenant that schedule and retentionPolicy are ignored on this flow, and cozyvalues-gen copies that into the schema, README and the dashboard. A render-time reject of a non-default retentionPolicy contradicted all of them: a tenant who followed the documented opt-in with a retentionPolicy still set got a failed render and a HelmRelease that stopped converging, pointed at the very doc that says the field does nothing. Drop the reject so retentionPolicy is inert exactly as documented, handled the same way as schedule (gated out, no error). The absence of retention on this flow is real but belongs to a follow-up, so the docs now point at the BackupRetentionPolicy design (#4192) and the teardown-GC issue (#3966), and recommend an S3 lifecycle policy until they land. Cancel a timed-out operator backup instead of only failing the BackupJob. The deadline fires for a backup the operator has not begun streaming; but `waiting` is the state pbm reports for a backup queued behind another, and the operator starts it once the slot frees — after the BackupJob is Failed and never reconciled again, writing an archive into the shared bucket that no Backup object represents. The deadline branch now deletes the operator CR before failing, which prevents that late run entirely: at v1.22.0 the operator returns for a CR with a deletion timestamp before it dispatches to pbm, so nothing is written. The delete is best-effort so it never blocks the failure. Assisted-By: LLM Signed-off-by: Andrey Kolkov --- docs/operations/backup-classes.md | 2 +- .../psmdbstrategy_controller.go | 24 ++++++++-- .../psmdbstrategy_controller_test.go | 48 +++++++++++++++++++ packages/apps/mongodb/templates/mongodb.yaml | 12 ----- packages/apps/mongodb/tests/mongodb_test.yaml | 29 ++++------- 5 files changed, 78 insertions(+), 37 deletions(-) diff --git a/docs/operations/backup-classes.md b/docs/operations/backup-classes.md index 0b3b31bb6..6d11482dc 100644 --- a/docs/operations/backup-classes.md +++ b/docs/operations/backup-classes.md @@ -121,7 +121,7 @@ When `useSystemBucket: true`: Because the chart drops `spec.backup.tasks` and `spec.backup.pitr`, the psmdb operator's own scheduled backups and oplog PITR do **not** run on this flow — `backup.schedule` and `backup.retentionPolicy` stay in the schema for the default flow but have no effect here, and the `recoveryTime` PITR restores described below are not available. Migrate scheduled backups to a `backups.cozystack.io/Plan` against `cozy-default` instead. **Flipping this flag on a running app** removes the storage, tasks and pitr the app had, so a release that was taking scheduled backups + PITR before the flip stops until a `Plan` takes over. -Dropping `spec.backup.tasks` also drops the psmdb `keep` retention it carried, so on this flow **the driver owns the archive** the way the Rabbitmq/Redis drivers own theirs (an on-demand `PerconaServerMongoDBBackup` is not covered by psmdb task retention). The driver stamps the operator's `percona.com/delete-backup` finalizer onto each backup it mints here, and deleting a Cozystack `Backup` (a retention-pruned `Plan`, or a manual delete) deletes that `PerconaServerMongoDBBackup` CR — whose finalizer removes the pbm object from the shared bucket before the `Backup` is released, so a Plan does not accumulate objects in `cozy-backups`. A legacy backup writes to the tenant's own bucket and keeps the pre-existing hands-off contract (its lifecycle stays the tenant's / operator's; nothing is deleted on `Backup` removal). Note this prunes only when a `Backup` is deleted: unlike CNPG and MariaDB, which prune engine-side on their own schedule, MongoDB has no engine-side scheduled trim on this flow, so keeping `cozy-backups` bounded depends on a `Plan`'s retention actually deleting old `Backup` objects (scheduled retention at the `Plan` level is tracked as future work). Two cases release the `Backup` without waiting for the object to be pruned, so a wedged prune never pins a namespace in `Terminating`: a terminating namespace (where the operator's delete-backup step cannot run) and the `backups.cozystack.io/skip-artifact-cleanup: "true"` annotation. In both the driver strips its own finalizer and leaves the object for a bucket lifecycle policy to reclaim. A down operator or unreachable storage in a live namespace is NOT released automatically — the `Backup` stays `Terminating` as a visible signal until the operator recovers or you set that annotation to force the release. +Dropping `spec.backup.tasks` also drops the psmdb `keep` retention it carried, so on this flow **the driver owns the archive** the way the Rabbitmq/Redis drivers own theirs (an on-demand `PerconaServerMongoDBBackup` is not covered by psmdb task retention). The driver stamps the operator's `percona.com/delete-backup` finalizer onto each backup it mints here, and deleting a Cozystack `Backup` (a retention-pruned `Plan`, or a manual delete) deletes that `PerconaServerMongoDBBackup` CR — whose finalizer removes the pbm object from the shared bucket before the `Backup` is released, so a Plan does not accumulate objects in `cozy-backups`. A legacy backup writes to the tenant's own bucket and keeps the pre-existing hands-off contract (its lifecycle stays the tenant's / operator's; nothing is deleted on `Backup` removal). Note this prunes only when a `Backup` is deleted: unlike CNPG and MariaDB, which prune engine-side on their own schedule, MongoDB has no engine-side scheduled trim on this flow, so keeping `cozy-backups` bounded depends on a `Plan`'s retention actually deleting old `Backup` objects. **A `Plan` has no retention field yet** (`PlanSpec` carries only `applicationRef`, `backupClassName` and `schedule`), so today a nightly `useSystemBucket` Plan grows the shared bucket unbounded — `schedule` and `retentionPolicy` on the app are inert here (see [MongoDB: opt-in to the system bucket](#mongodb-backup-storage)), and platform-level retention is tracked in the [`BackupRetentionPolicy` design (#4192)](https://github.com/cozystack/cozystack/pull/4192). Teardown GC of orphaned `Backup`s / S3 data is [#3966](https://github.com/cozystack/cozystack/issues/3966). Until those land, bound `cozy-backups` with an S3 lifecycle policy on the object store. Two cases release the `Backup` without waiting for the object to be pruned, so a wedged prune never pins a namespace in `Terminating`: a terminating namespace (where the operator's delete-backup step cannot run) and the `backups.cozystack.io/skip-artifact-cleanup: "true"` annotation. In both the driver strips its own finalizer and leaves the object for a bucket lifecycle policy to reclaim. A down operator or unreachable storage in a live namespace is NOT released automatically — the `Backup` stays `Terminating` as a visible signal until the operator recovers or you set that annotation to force the release. **Opting back out** (`useSystemBucket` true→false) is not automatic in reverse: the driver stops injecting, but the `s3-storage` entry it already applied stays on the live `PerconaServerMongoDB` under the driver's own field manager (`cozystack-psmdb-backup-driver`) — the chart does not own it and so never prunes it. It is inert once `backup.enabled=false`; to fully return a release to the legacy flow, delete that storage entry from the `PerconaServerMongoDB` by hand before re-declaring the tenant's own `backup.*` S3 values. diff --git a/internal/backupcontroller/psmdbstrategy_controller.go b/internal/backupcontroller/psmdbstrategy_controller.go index 6f3804968..9d89cd19d 100644 --- a/internal/backupcontroller/psmdbstrategy_controller.go +++ b/internal/backupcontroller/psmdbstrategy_controller.go @@ -348,6 +348,22 @@ func (r *BackupJobReconciler) reconcileMongoDB(ctx context.Context, j *backupsv1 // BackupJob Running forever), but a running dump is left to finish rather // than stranding its archive — see psmdbBackupTimedOut. if psmdbBackupTimedOut(state, j.Status.StartedAt) { + // Cancel the operator CR before failing. A `waiting` backup is queued + // behind another and the operator starts it once the slot frees — which + // would be after this BackupJob is Failed and never reconciled again, + // writing an archive into the shared bucket that no Backup object + // represents. Deleting the CR now prevents that late run; on the + // useSystemBucket flow its delete-backup finalizer also takes anything + // partially written. Best-effort: a delete failure must not stop the + // job from failing (a leftover CR is the pre-existing behaviour, not a + // regression). The terminal Phase=Failed makes reconcileMongoDB return + // early next time, so ensureMongoDBBackup never re-creates it. + if mdbBackup.DeletionTimestamp.IsZero() { + if derr := r.Delete(ctx, mdbBackup); derr != nil && !apierrors.IsNotFound(derr) { + getLogger(ctx).Debug("could not cancel the timed-out operator backup before failing", + "backupjob", j.Name, "sourceBackup", mdbBackup.Name, "error", derr) + } + } detail := "no state observed" if state != "" { detail = fmt.Sprintf("state=%s", state) @@ -575,9 +591,11 @@ func psmdbBackupDeadlineExceeded(startedAt *metav1.Time) bool { // (the operator CR carries no ownerRef either). A real dataset routinely outruns // 30m, and a genuinely broken dump terminates through the operator's own // error/rejected state, so a running backup is left to finish. The deadline -// still bounds the case it was written for — the operator never starts the -// backup (state stays "", requested or waiting), where nothing has been written -// and failing strands nothing. +// still bounds the case it was written for — the operator has not started the +// backup (state stays "", requested or waiting), where nothing has been written. +// A `waiting` backup (queued behind another) could still be started later, so +// the caller cancels the operator CR when this trips, rather than leaving it to +// run into the shared bucket after the BackupJob is already Failed. func psmdbBackupTimedOut(state string, startedAt *metav1.Time) bool { if state == psmdbtypes.StateRunning { return false diff --git a/internal/backupcontroller/psmdbstrategy_controller_test.go b/internal/backupcontroller/psmdbstrategy_controller_test.go index 34773f5ee..3d823e0de 100644 --- a/internal/backupcontroller/psmdbstrategy_controller_test.go +++ b/internal/backupcontroller/psmdbstrategy_controller_test.go @@ -1234,6 +1234,54 @@ func mongodbInjectFixture(enabled bool) (*backupsv1alpha1.BackupJob, *strategyv1 return job, strategy, app, cluster, resolved } +// When a backup the operator never started (state=waiting, queued behind +// another) trips the deadline, the driver must cancel the operator CR before +// failing the BackupJob — otherwise the operator starts it later and writes an +// archive into the shared bucket that no Backup object represents. +func TestReconcileMongoDB_TimedOutBackupIsCancelled(t *testing.T) { + job, strategy, app, cluster, resolved := mongodbInjectFixture(true) + // The BackupJob started well past the deadline. + old := &metav1.Time{Time: time.Now().Add(-2 * psmdbDefaultBackupDeadline)} + job.Status.StartedAt = old + // An operator backup already exists for this job, queued (state=waiting), with + // the delete-backup finalizer the useSystemBucket flow stamps. + opBackup := &psmdbtypes.PerconaServerMongoDBBackup{ + ObjectMeta: metav1.ObjectMeta{ + Namespace: "tenant", + Name: "op-waiting", + Finalizers: []string{psmdbDeleteBackupFinalizer}, + Labels: map[string]string{ + backupsv1alpha1.OwningJobNameLabel: job.Name, + backupsv1alpha1.OwningJobNamespaceLabel: job.Namespace, + }, + }, + Status: psmdbtypes.PerconaServerMongoDBBackupStatus{State: psmdbtypes.StateWaiting}, + } + + c := newMongoDBStrategyTestClient(t, job, strategy, app, cluster, opBackup) + r := &BackupJobReconciler{Client: c, Scheme: c.Scheme()} + + if _, err := r.reconcileMongoDB(context.Background(), job.DeepCopy(), resolved); err != nil { + t.Fatalf("reconcileMongoDB: %v", err) + } + + // The operator CR must be cancelled (deleted): with the finalizer it stays + // Terminating, so assert a DeletionTimestamp; without the fix it is untouched. + got := &psmdbtypes.PerconaServerMongoDBBackup{} + err := c.Get(context.Background(), types.NamespacedName{Namespace: "tenant", Name: "op-waiting"}, got) + if err == nil && got.DeletionTimestamp.IsZero() { + t.Errorf("timed-out operator backup must be cancelled (deleted) so it cannot run later; it was left untouched") + } + // And the BackupJob is failed. + persisted := &backupsv1alpha1.BackupJob{} + if err := c.Get(context.Background(), types.NamespacedName{Namespace: "tenant", Name: job.Name}, persisted); err != nil { + t.Fatalf("get job: %v", err) + } + if persisted.Status.Phase != backupsv1alpha1.BackupJobPhaseFailed { + t.Errorf("expected the BackupJob to be Failed, got phase=%q", persisted.Status.Phase) + } +} + // A cluster that can never service a backup (backup.enabled=false) must not be // mutated: injection is gated on Enabled so the disabled cluster fails the // precondition on the enabled check without the driver having written storage diff --git a/packages/apps/mongodb/templates/mongodb.yaml b/packages/apps/mongodb/templates/mongodb.yaml index 2173fdd52..66e497a41 100644 --- a/packages/apps/mongodb/templates/mongodb.yaml +++ b/packages/apps/mongodb/templates/mongodb.yaml @@ -217,18 +217,6 @@ spec: {{- end }} {{- end }} - {{- /* - useSystemBucket cannot honour backup.retentionPolicy: the tasks[].keep block - below (the chart's only retention) is gated out on this flow, and no - Plan-level retention exists yet, so a retentionPolicy set here would silently - grow the shared cozy-backups bucket. Reject a value the tenant changed from - the chart default rather than ignore it — an untouched useSystemBucket install - keeps rendering. $defaultRetentionPolicy MUST track the values.yaml default. - */}} - {{- $defaultRetentionPolicy := "30d" }} - {{- if and .Values.backup.useSystemBucket .Values.backup.retentionPolicy (ne .Values.backup.retentionPolicy $defaultRetentionPolicy) }} - {{- fail (printf "backup.retentionPolicy=%q cannot be honoured when backup.useSystemBucket=true: the platform flow has no engine-side retention and Plan-level retention is not yet available (see docs/operations/backup-classes.md). Remove backup.retentionPolicy, or drive scheduled backups and retention through a backups.cozystack.io/Plan." .Values.backup.retentionPolicy) }} - {{- end }} backup: enabled: {{ .Values.backup.enabled | default false }} image: percona/percona-backup-mongodb:2.11.0 diff --git a/packages/apps/mongodb/tests/mongodb_test.yaml b/packages/apps/mongodb/tests/mongodb_test.yaml index 308e19a9c..a7ac07c47 100644 --- a/packages/apps/mongodb/tests/mongodb_test.yaml +++ b/packages/apps/mongodb/tests/mongodb_test.yaml @@ -93,10 +93,10 @@ tests: path: spec.backup.pitr documentIndex: 0 - - it: rejects a non-default retentionPolicy on useSystemBucket - # The platform flow cannot honour retentionPolicy (no engine-side trim, no - # Plan retention yet), so a value the tenant changed from the default is a - # hard error rather than a silent no-op that grows the shared bucket. + - it: ignores retentionPolicy and schedule on useSystemBucket (renders, no tasks) + # On this flow retentionPolicy and schedule are inert (documented as ignored), + # handled the same way: a custom value renders cleanly without emitting the + # tasks block, never a hard render error. release: name: test-mongodb namespace: tenant-test @@ -107,28 +107,15 @@ tests: enabled: true useSystemBucket: true retentionPolicy: 7d - asserts: - - failedTemplate: - errorMessage: 'backup.retentionPolicy="7d" cannot be honoured when backup.useSystemBucket=true: the platform flow has no engine-side retention and Plan-level retention is not yet available (see docs/operations/backup-classes.md). Remove backup.retentionPolicy, or drive scheduled backups and retention through a backups.cozystack.io/Plan.' - - - it: allows the default retentionPolicy on useSystemBucket - # The untouched default must still render, so the guard only fires on a - # tenant-changed value (this pins the discriminator, not just the reject). - release: - name: test-mongodb - namespace: tenant-test - set: - _cluster: - cluster-domain: cozy.local - backup: - enabled: true - useSystemBucket: true - retentionPolicy: 30d + schedule: "0 5 * * *" asserts: - equal: path: spec.backup.enabled value: true documentIndex: 0 + - notExists: + path: spec.backup.tasks + documentIndex: 0 ################## # Finalizers # From e653a4fa5d3eadb05abe8936d23a43af7bd7d22b Mon Sep 17 00:00:00 2001 From: Andrey Kolkov Date: Wed, 16 Sep 2026 17:38:04 +0400 Subject: [PATCH 0015/1280] fix(mongodb): correct the finalizer-prune claims, pin the pre-read release CR, and fix the retention field text MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The delete-backup finalizer prunes storage only for a `ready` backup at v1.22.0; a timed-out backup never reaches `ready`, so the deadline-cancel comment no longer claims the finalizer "takes anything partially written" — nothing is written until the backup runs, which the cancel prevents. The psmdbBackupTimedOut godoc no longer says the operator "has not started" the backup, which is wrong for `requested` (the operator sets it as it dispatches); it now describes the not-yet-running states it actually gates. The pre-read CR handed to releaseMongoDBCleanup on the terminating path had no test that failed when the argument was dropped, because the existing cases either call the function directly or let the second Get succeed. Added a cleanupMongoDBBackup case whose operator-CR Get fails after the first: the release must strip from the passed object, not re-read, or the teardown wedges. The useSystemBucket field said "retention move[s] to the Plan", but a Plan has no retention field; corrected to "scheduling moves to a Plan; this flow has no retention yet" and regenerated the schema, README and mongodb-rd. Softened the "never pins a namespace in Terminating" wording in the cleanup godoc and RBAC comment: the driver only bounds its own finalizer, the operator's release-lock finalizer can still hold the CR while the operator is down. Assisted-By: LLM Signed-off-by: Andrey Kolkov --- api/apps/v1alpha1/mongodb/types.go | 2 +- .../psmdbstrategy_controller.go | 43 +++++++++++------- .../psmdbstrategy_controller_test.go | 44 +++++++++++++++++++ packages/apps/mongodb/README.md | 24 +++++----- packages/apps/mongodb/values.schema.json | 2 +- packages/apps/mongodb/values.yaml | 2 +- .../templates/rbac.yaml | 5 ++- .../system/mongodb-rd/cozyrds/mongodb.yaml | 2 +- 8 files changed, 89 insertions(+), 35 deletions(-) diff --git a/api/apps/v1alpha1/mongodb/types.go b/api/apps/v1alpha1/mongodb/types.go index 89ebef1f7..f0c943b14 100644 --- a/api/apps/v1alpha1/mongodb/types.go +++ b/api/apps/v1alpha1/mongodb/types.go @@ -84,7 +84,7 @@ type Backup struct { // Cron schedule for automated backups. Ignored when useSystemBucket is true (scheduling moves to the BackupClass Plan). // +kubebuilder:default:="0 2 * * *" Schedule string `json:"schedule,omitempty"` - // Opt-in: back up to the platform system bucket without supplying S3 credentials. The cozy-default MongoDB BackupClass injects the storage at BackupJob time; tenants do not set s3AccessKey/s3SecretKey/destinationPath/endpointURL, and backups scope to `/`. Scheduling and retention move to the BackupClass Plan, so `schedule`, `retentionPolicy` and PITR are ignored while this is on. See docs/operations/backup-classes.md. + // Opt-in: back up to the platform system bucket without supplying S3 credentials. The cozy-default MongoDB BackupClass injects the storage at BackupJob time; tenants do not set s3AccessKey/s3SecretKey/destinationPath/endpointURL, and backups scope to `/`. Scheduling moves to a BackupClass Plan; `schedule`, `retentionPolicy` and PITR are ignored while this is on, and this flow has no retention yet (see docs/operations/backup-classes.md). // +kubebuilder:default:=false UseSystemBucket bool `json:"useSystemBucket,omitempty"` } diff --git a/internal/backupcontroller/psmdbstrategy_controller.go b/internal/backupcontroller/psmdbstrategy_controller.go index 9d89cd19d..baa88a465 100644 --- a/internal/backupcontroller/psmdbstrategy_controller.go +++ b/internal/backupcontroller/psmdbstrategy_controller.go @@ -352,10 +352,14 @@ func (r *BackupJobReconciler) reconcileMongoDB(ctx context.Context, j *backupsv1 // behind another and the operator starts it once the slot frees — which // would be after this BackupJob is Failed and never reconciled again, // writing an archive into the shared bucket that no Backup object - // represents. Deleting the CR now prevents that late run; on the - // useSystemBucket flow its delete-backup finalizer also takes anything - // partially written. Best-effort: a delete failure must not stop the - // job from failing (a leftover CR is the pre-existing behaviour, not a + // represents. Deleting the CR before the operator sends the backup + // command prevents that late run: at v1.22.0 the operator returns for a + // CR with a deletion timestamp before it reaches the code that calls + // Start. (It does not clean up a partial object — the delete-backup + // finalizer prunes storage only for a `ready` backup — but nothing is + // partially written until the backup actually runs, which the cancel + // prevents.) Best-effort: a delete failure must not stop the job from + // failing (a leftover CR is the pre-existing behaviour, not a // regression). The terminal Phase=Failed makes reconcileMongoDB return // early next time, so ensureMongoDBBackup never re-creates it. if mdbBackup.DeletionTimestamp.IsZero() { @@ -591,11 +595,12 @@ func psmdbBackupDeadlineExceeded(startedAt *metav1.Time) bool { // (the operator CR carries no ownerRef either). A real dataset routinely outruns // 30m, and a genuinely broken dump terminates through the operator's own // error/rejected state, so a running backup is left to finish. The deadline -// still bounds the case it was written for — the operator has not started the -// backup (state stays "", requested or waiting), where nothing has been written. -// A `waiting` backup (queued behind another) could still be started later, so -// the caller cancels the operator CR when this trips, rather than leaving it to -// run into the shared bucket after the BackupJob is already Failed. +// still bounds the not-yet-`running` states ("", requested, waiting): a backup +// the operator has not begun streaming. Those can still be advanced later — a +// `waiting` backup runs when the slot frees, and `requested` is set as the +// operator dispatches — so the caller cancels the operator CR when this trips, +// rather than leaving it to run into the shared bucket after the BackupJob is +// already Failed. func psmdbBackupTimedOut(state string, startedAt *metav1.Time) bool { if state == psmdbtypes.StateRunning { return false @@ -771,14 +776,18 @@ func (r *BackupJobReconciler) createMongoDBBackupArtifact( // is left untouched, the pre-existing no-op contract for the operator-backed // drivers. // -// The wait is bounded by give-up conditions, so a wedged operator never pins a -// tenant namespace in Terminating: the escape-hatch annotation (honoured before -// any apiserver read, so it still frees a Backup whose operator CR has become -// unreadable) and a going-away namespace (the psmdb delete-backup exec cannot -// run there) each make the driver strip its own finalizer and release, leaving -// the object for a bucket lifecycle policy to reclaim. A down operator in a live -// namespace is NOT auto-released: the Backup stays Terminating as a visible -// signal until an operator recovers or the annotation is set. +// The wait has give-up conditions so a wedged operator does not, on its own, +// keep this driver holding the Backup in Terminating: the escape-hatch +// annotation (honoured before any apiserver read, so it still frees a Backup +// whose operator CR has become unreadable) and a going-away namespace (the psmdb +// delete-backup exec cannot run there) each make the driver strip its own +// finalizer and release, leaving the object for a bucket lifecycle policy. This +// bounds only what the driver contributes: a Get that fails with something other +// than NotFound/NoMatchError still requeues (below), and the psmdb operator's own +// release-lock finalizer keeps the CR Terminating while the operator is down, +// whatever the driver strips. A down operator in a live namespace is likewise +// not auto-released: the Backup stays Terminating as a visible signal until an +// operator recovers or the annotation is set. func (r *BackupReconciler) cleanupMongoDBBackup(ctx context.Context, backup *backupsv1alpha1.Backup) (ctrl.Result, error) { sourceBackupName := backup.Spec.DriverMetadata[psmdbBackupNameKey] if sourceBackupName == "" { diff --git a/internal/backupcontroller/psmdbstrategy_controller_test.go b/internal/backupcontroller/psmdbstrategy_controller_test.go index 3d823e0de..ba9893a02 100644 --- a/internal/backupcontroller/psmdbstrategy_controller_test.go +++ b/internal/backupcontroller/psmdbstrategy_controller_test.go @@ -1515,6 +1515,50 @@ func TestCleanupMongoDBBackup(t *testing.T) { } }) + t.Run("terminating release uses the pre-read CR, not a second Get", func(t *testing.T) { + // The terminating path hands the CR it already read and confirmed owned to + // releaseMongoDBCleanup, so the strip is not gated on a second Get. Fail + // every operator-CR Get after the first: cleanup's initial read succeeds + // and confirms ownership, and the release must strip from the passed object + // without re-reading. If the call site instead passed nil, the release + // would re-Get (fail here) and skip the strip — no ArtifactNotDeleted Event. + getN := 0 + s := runtime.NewScheme() + _ = scheme.AddToScheme(s) + _ = backupsv1alpha1.AddToScheme(s) + _ = psmdbtypes.AddToScheme(s) + c := clientfake.NewClientBuilder(). + WithScheme(s). + WithObjects(opBackup(true)). + WithInterceptorFuncs(interceptor.Funcs{ + Get: func(ctx context.Context, cl client.WithWatch, key client.ObjectKey, obj client.Object, opts ...client.GetOption) error { + if _, ok := obj.(*psmdbtypes.PerconaServerMongoDBBackup); ok { + getN++ + if getN > 1 { + return apierrors.NewServiceUnavailable("read throttled after first") + } + } + return cl.Get(ctx, key, obj, opts...) + }, + }). + Build() + rec := record.NewFakeRecorder(10) + r := &BackupReconciler{Client: c, Recorder: rec} + // No Namespace object → namespaceTerminating reports true (teardown path). + res, err := r.cleanupMongoDBBackup(context.Background(), newBackup(nil)) + if err != nil || res.RequeueAfter != 0 { + t.Fatalf("teardown must release, got res=%+v err=%v", res, err) + } + select { + case ev := <-rec.Events: + if !strings.Contains(ev, "ArtifactNotDeleted") { + t.Errorf("expected the owned-release event proving the pre-read CR was used, got %q", ev) + } + default: + t.Errorf("expected an ArtifactNotDeleted event (pre-read CR used, strip ran), got none") + } + }) + // A client whose Get on the operator CR hard-fails the way a missing CRD or a // revoked verb does — NoKindMatchError / an arbitrary error — models the case // the escape hatch exists for. The annotation must free the Backup without diff --git a/packages/apps/mongodb/README.md b/packages/apps/mongodb/README.md index e779a7353..49cbdf49b 100644 --- a/packages/apps/mongodb/README.md +++ b/packages/apps/mongodb/README.md @@ -247,18 +247,18 @@ Releases with `external: false`, and sharded releases in any configuration, are ### Backup parameters -| Name | Description | Type | Value | -| ------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------- | ----------------------------------- | -| `backup` | Backup configuration. | `object` | `{}` | -| `backup.enabled` | Enable regular backups. | `bool` | `false` | -| `backup.useSystemBucket` | Opt-in: back up to the platform system bucket without supplying S3 credentials. The cozy-default MongoDB BackupClass injects the storage at BackupJob time; tenants do not set s3AccessKey/s3SecretKey/destinationPath/endpointURL, and backups scope to `/`. Scheduling and retention move to the BackupClass Plan, so `schedule`, `retentionPolicy` and PITR are ignored while this is on. See docs/operations/backup-classes.md. | `bool` | `false` | -| `backup.schedule` | Cron schedule for automated backups. Ignored when useSystemBucket is true (scheduling moves to the BackupClass Plan). | `string` | `0 2 * * *` | -| `backup.retentionPolicy` | Retention policy (e.g. "30d"). Ignored when useSystemBucket is true (no engine-side retention on that flow). | `string` | `30d` | -| `backup.destinationPath` | Destination path for backups (e.g. s3://bucket/path/). Ignored when useSystemBucket is true (the driver injects the platform bucket). | `string` | `s3://bucket/path/to/folder/` | -| `backup.endpointURL` | S3 endpoint URL for uploads. Ignored when useSystemBucket is true (the strategy supplies the platform endpoint). | `string` | `http://minio-gateway-service:9000` | -| `backup.insecureSkipTLSVerify` | Skip TLS verification for the S3 endpoint (self-signed, e.g. in-cluster seaweedfs). Ignored when useSystemBucket is true (the platform backupStorage knob applies instead). | `bool` | `false` | -| `backup.s3AccessKey` | Access key for S3 authentication. Ignored when useSystemBucket is true (credentials come from the projected cozy-backups-creds). | `string` | `""` | -| `backup.s3SecretKey` | Secret key for S3 authentication. Ignored when useSystemBucket is true (credentials come from the projected cozy-backups-creds). | `string` | `""` | +| Name | Description | Type | Value | +| ------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------- | ----------------------------------- | +| `backup` | Backup configuration. | `object` | `{}` | +| `backup.enabled` | Enable regular backups. | `bool` | `false` | +| `backup.useSystemBucket` | Opt-in: back up to the platform system bucket without supplying S3 credentials. The cozy-default MongoDB BackupClass injects the storage at BackupJob time; tenants do not set s3AccessKey/s3SecretKey/destinationPath/endpointURL, and backups scope to `/`. Scheduling moves to a BackupClass Plan; `schedule`, `retentionPolicy` and PITR are ignored while this is on, and this flow has no retention yet (see docs/operations/backup-classes.md). | `bool` | `false` | +| `backup.schedule` | Cron schedule for automated backups. Ignored when useSystemBucket is true (scheduling moves to the BackupClass Plan). | `string` | `0 2 * * *` | +| `backup.retentionPolicy` | Retention policy (e.g. "30d"). Ignored when useSystemBucket is true (no engine-side retention on that flow). | `string` | `30d` | +| `backup.destinationPath` | Destination path for backups (e.g. s3://bucket/path/). Ignored when useSystemBucket is true (the driver injects the platform bucket). | `string` | `s3://bucket/path/to/folder/` | +| `backup.endpointURL` | S3 endpoint URL for uploads. Ignored when useSystemBucket is true (the strategy supplies the platform endpoint). | `string` | `http://minio-gateway-service:9000` | +| `backup.insecureSkipTLSVerify` | Skip TLS verification for the S3 endpoint (self-signed, e.g. in-cluster seaweedfs). Ignored when useSystemBucket is true (the platform backupStorage knob applies instead). | `bool` | `false` | +| `backup.s3AccessKey` | Access key for S3 authentication. Ignored when useSystemBucket is true (credentials come from the projected cozy-backups-creds). | `string` | `""` | +| `backup.s3SecretKey` | Secret key for S3 authentication. Ignored when useSystemBucket is true (credentials come from the projected cozy-backups-creds). | `string` | `""` | ### Bootstrap (recovery) parameters diff --git a/packages/apps/mongodb/values.schema.json b/packages/apps/mongodb/values.schema.json index 5680ea65c..90bafad64 100644 --- a/packages/apps/mongodb/values.schema.json +++ b/packages/apps/mongodb/values.schema.json @@ -313,7 +313,7 @@ "default": "0 2 * * *" }, "useSystemBucket": { - "description": "Opt-in: back up to the platform system bucket without supplying S3 credentials. The cozy-default MongoDB BackupClass injects the storage at BackupJob time; tenants do not set s3AccessKey/s3SecretKey/destinationPath/endpointURL, and backups scope to `\u003cnamespace\u003e/\u003capplication\u003e`. Scheduling and retention move to the BackupClass Plan, so `schedule`, `retentionPolicy` and PITR are ignored while this is on. See docs/operations/backup-classes.md.", + "description": "Opt-in: back up to the platform system bucket without supplying S3 credentials. The cozy-default MongoDB BackupClass injects the storage at BackupJob time; tenants do not set s3AccessKey/s3SecretKey/destinationPath/endpointURL, and backups scope to `\u003cnamespace\u003e/\u003capplication\u003e`. Scheduling moves to a BackupClass Plan; `schedule`, `retentionPolicy` and PITR are ignored while this is on, and this flow has no retention yet (see docs/operations/backup-classes.md).", "type": "boolean", "default": false } diff --git a/packages/apps/mongodb/values.yaml b/packages/apps/mongodb/values.yaml index 10dd250e3..78012bdbc 100644 --- a/packages/apps/mongodb/values.yaml +++ b/packages/apps/mongodb/values.yaml @@ -155,7 +155,7 @@ databases: {} ## @typedef {struct} Backup - Backup configuration. ## @field {bool} enabled - Enable regular backups. -## @field {bool} [useSystemBucket] - Opt-in: back up to the platform system bucket without supplying S3 credentials. The cozy-default MongoDB BackupClass injects the storage at BackupJob time; tenants do not set s3AccessKey/s3SecretKey/destinationPath/endpointURL, and backups scope to `/`. Scheduling and retention move to the BackupClass Plan, so `schedule`, `retentionPolicy` and PITR are ignored while this is on. See docs/operations/backup-classes.md. +## @field {bool} [useSystemBucket] - Opt-in: back up to the platform system bucket without supplying S3 credentials. The cozy-default MongoDB BackupClass injects the storage at BackupJob time; tenants do not set s3AccessKey/s3SecretKey/destinationPath/endpointURL, and backups scope to `/`. Scheduling moves to a BackupClass Plan; `schedule`, `retentionPolicy` and PITR are ignored while this is on, and this flow has no retention yet (see docs/operations/backup-classes.md). ## @field {string} [schedule] - Cron schedule for automated backups. Ignored when useSystemBucket is true (scheduling moves to the BackupClass Plan). ## @field {string} [retentionPolicy] - Retention policy (e.g. "30d"). Ignored when useSystemBucket is true (no engine-side retention on that flow). ## @field {string} [destinationPath] - Destination path for backups (e.g. s3://bucket/path/). Ignored when useSystemBucket is true (the driver injects the platform bucket). diff --git a/packages/system/backupstrategy-controller/templates/rbac.yaml b/packages/system/backupstrategy-controller/templates/rbac.yaml index aa032cad5..3d70dca61 100644 --- a/packages/system/backupstrategy-controller/templates/rbac.yaml +++ b/packages/system/backupstrategy-controller/templates/rbac.yaml @@ -171,8 +171,9 @@ rules: # delete-backup finalizer frees the object (see cleanupMongoDBBackup). A legacy # backup lives in the tenant's own bucket and is never deleted here. # patch: strip the driver's own delete-backup finalizer to release a wedged - # cleanup (namespace terminating, or the skip-artifact-cleanup annotation) so a - # stuck operator never pins a tenant namespace in Terminating. + # cleanup (namespace terminating, or the skip-artifact-cleanup annotation) so + # the driver's finalizer is not what holds a tenant namespace in Terminating + # (the operator's own release-lock finalizer can still hold it if it is down). verbs: ["get", "list", "watch", "create", "delete", "patch"] - apiGroups: ["psmdb.percona.com"] resources: ["perconaservermongodbrestores"] diff --git a/packages/system/mongodb-rd/cozyrds/mongodb.yaml b/packages/system/mongodb-rd/cozyrds/mongodb.yaml index 0b0ee8863..24961dfe9 100644 --- a/packages/system/mongodb-rd/cozyrds/mongodb.yaml +++ b/packages/system/mongodb-rd/cozyrds/mongodb.yaml @@ -8,7 +8,7 @@ spec: singular: mongodb plural: mongodbs openAPISchema: |- - {"title":"Chart Values","type":"object","properties":{"replicas":{"description":"Number of MongoDB replicas in replica set.","type":"integer","default":3},"resources":{"description":"Explicit CPU and memory configuration for each MongoDB replica. When omitted, the preset defined in `resourcesPreset` is applied.","type":"object","default":{},"properties":{"cpu":{"description":"CPU available to each replica.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"memory":{"description":"Memory (RAM) available to each replica.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true}}},"resourcesPreset":{"description":"Default sizing preset used when `resources` is omitted.","type":"string","default":"t1.small","enum":["t1.nano","t1.micro","t1.small","t1.medium","t1.large","t1.xlarge","t1.2xlarge","t1.4xlarge","c1.nano","c1.micro","c1.small","c1.medium","c1.large","c1.xlarge","c1.2xlarge","c1.4xlarge","s1.nano","s1.micro","s1.small","s1.medium","s1.large","s1.xlarge","s1.2xlarge","s1.4xlarge","u1.nano","u1.micro","u1.small","u1.medium","u1.large","u1.xlarge","u1.2xlarge","u1.4xlarge","m1.nano","m1.micro","m1.small","m1.medium","m1.large","m1.xlarge","m1.2xlarge","m1.4xlarge","nano","micro","small","medium","large","xlarge","2xlarge"]},"size":{"description":"Persistent Volume Claim size available for application data.","default":"10Gi","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"storageClass":{"description":"StorageClass used to store the data.","type":"string","default":"","x-kubernetes-validations":[{"rule":"self == oldSelf","message":"storageClass is immutable"}],"x-cozystack-options":{"source":"storageclass"}},"external":{"description":"Enable external access from outside the cluster.","type":"boolean","default":false},"version":{"description":"MongoDB major version to deploy.","type":"string","default":"v8","enum":["v8","v7","v6"]},"sharding":{"description":"Enable sharded cluster mode. When disabled, deploys a replica set.","type":"boolean","default":false},"shardingConfig":{"description":"Configuration for sharded cluster mode.","type":"object","default":{},"required":["configServerSize","configServers","mongos"],"properties":{"configServerSize":{"description":"PVC size for config servers.","default":"3Gi","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"configServers":{"description":"Number of config server replicas.","type":"integer","default":3},"mongos":{"description":"Number of mongos router replicas.","type":"integer","default":2},"shards":{"description":"List of shard configurations.","type":"array","default":[{"name":"rs0","replicas":3,"size":"10Gi"}],"items":{"type":"object","required":["name","replicas","size"],"properties":{"name":{"description":"Shard name.","type":"string"},"replicas":{"description":"Number of replicas in this shard.","type":"integer"},"size":{"description":"PVC size for this shard.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true}}}}}},"users":{"description":"Users configuration map.","type":"object","default":{},"additionalProperties":{"type":"object","properties":{"password":{"description":"Password for the user (auto-generated if omitted).","type":"string"}}}},"databases":{"description":"Databases configuration map.","type":"object","default":{},"additionalProperties":{"type":"object","properties":{"roles":{"description":"Roles assigned to users.","type":"object","properties":{"admin":{"description":"List of users with admin privileges (readWrite + dbAdmin).","type":"array","items":{"type":"string"}},"readonly":{"description":"List of users with read-only privileges.","type":"array","items":{"type":"string"}}}}}}},"backup":{"description":"Backup configuration.","type":"object","default":{},"required":["enabled"],"properties":{"destinationPath":{"description":"Destination path for backups (e.g. s3://bucket/path/). Ignored when useSystemBucket is true (the driver injects the platform bucket).","type":"string","default":"s3://bucket/path/to/folder/"},"enabled":{"description":"Enable regular backups.","type":"boolean","default":false},"endpointURL":{"description":"S3 endpoint URL for uploads. Ignored when useSystemBucket is true (the strategy supplies the platform endpoint).","type":"string","default":"http://minio-gateway-service:9000"},"insecureSkipTLSVerify":{"description":"Skip TLS verification for the S3 endpoint (self-signed, e.g. in-cluster seaweedfs). Ignored when useSystemBucket is true (the platform backupStorage knob applies instead).","type":"boolean","default":false},"retentionPolicy":{"description":"Retention policy (e.g. \"30d\"). Ignored when useSystemBucket is true (no engine-side retention on that flow).","type":"string","default":"30d"},"s3AccessKey":{"description":"Access key for S3 authentication. Ignored when useSystemBucket is true (credentials come from the projected cozy-backups-creds).","type":"string","default":""},"s3SecretKey":{"description":"Secret key for S3 authentication. Ignored when useSystemBucket is true (credentials come from the projected cozy-backups-creds).","type":"string","default":""},"schedule":{"description":"Cron schedule for automated backups. Ignored when useSystemBucket is true (scheduling moves to the BackupClass Plan).","type":"string","default":"0 2 * * *"},"useSystemBucket":{"description":"Opt-in: back up to the platform system bucket without supplying S3 credentials. The cozy-default MongoDB BackupClass injects the storage at BackupJob time; tenants do not set s3AccessKey/s3SecretKey/destinationPath/endpointURL, and backups scope to `/`. Scheduling and retention move to the BackupClass Plan, so `schedule`, `retentionPolicy` and PITR are ignored while this is on. See docs/operations/backup-classes.md.","type":"boolean","default":false}}},"bootstrap":{"description":"Bootstrap configuration.","type":"object","default":{},"required":["backupName","enabled"],"properties":{"backupName":{"description":"Name of backup to restore from.","type":"string","default":""},"enabled":{"description":"Whether to restore from a backup.","type":"boolean","default":false},"recoveryTime":{"description":"Timestamp for point-in-time recovery; empty means latest.","type":"string","default":""}}}}} + {"title":"Chart Values","type":"object","properties":{"replicas":{"description":"Number of MongoDB replicas in replica set.","type":"integer","default":3},"resources":{"description":"Explicit CPU and memory configuration for each MongoDB replica. When omitted, the preset defined in `resourcesPreset` is applied.","type":"object","default":{},"properties":{"cpu":{"description":"CPU available to each replica.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"memory":{"description":"Memory (RAM) available to each replica.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true}}},"resourcesPreset":{"description":"Default sizing preset used when `resources` is omitted.","type":"string","default":"t1.small","enum":["t1.nano","t1.micro","t1.small","t1.medium","t1.large","t1.xlarge","t1.2xlarge","t1.4xlarge","c1.nano","c1.micro","c1.small","c1.medium","c1.large","c1.xlarge","c1.2xlarge","c1.4xlarge","s1.nano","s1.micro","s1.small","s1.medium","s1.large","s1.xlarge","s1.2xlarge","s1.4xlarge","u1.nano","u1.micro","u1.small","u1.medium","u1.large","u1.xlarge","u1.2xlarge","u1.4xlarge","m1.nano","m1.micro","m1.small","m1.medium","m1.large","m1.xlarge","m1.2xlarge","m1.4xlarge","nano","micro","small","medium","large","xlarge","2xlarge"]},"size":{"description":"Persistent Volume Claim size available for application data.","default":"10Gi","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"storageClass":{"description":"StorageClass used to store the data.","type":"string","default":"","x-kubernetes-validations":[{"rule":"self == oldSelf","message":"storageClass is immutable"}],"x-cozystack-options":{"source":"storageclass"}},"external":{"description":"Enable external access from outside the cluster.","type":"boolean","default":false},"version":{"description":"MongoDB major version to deploy.","type":"string","default":"v8","enum":["v8","v7","v6"]},"sharding":{"description":"Enable sharded cluster mode. When disabled, deploys a replica set.","type":"boolean","default":false},"shardingConfig":{"description":"Configuration for sharded cluster mode.","type":"object","default":{},"required":["configServerSize","configServers","mongos"],"properties":{"configServerSize":{"description":"PVC size for config servers.","default":"3Gi","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"configServers":{"description":"Number of config server replicas.","type":"integer","default":3},"mongos":{"description":"Number of mongos router replicas.","type":"integer","default":2},"shards":{"description":"List of shard configurations.","type":"array","default":[{"name":"rs0","replicas":3,"size":"10Gi"}],"items":{"type":"object","required":["name","replicas","size"],"properties":{"name":{"description":"Shard name.","type":"string"},"replicas":{"description":"Number of replicas in this shard.","type":"integer"},"size":{"description":"PVC size for this shard.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true}}}}}},"users":{"description":"Users configuration map.","type":"object","default":{},"additionalProperties":{"type":"object","properties":{"password":{"description":"Password for the user (auto-generated if omitted).","type":"string"}}}},"databases":{"description":"Databases configuration map.","type":"object","default":{},"additionalProperties":{"type":"object","properties":{"roles":{"description":"Roles assigned to users.","type":"object","properties":{"admin":{"description":"List of users with admin privileges (readWrite + dbAdmin).","type":"array","items":{"type":"string"}},"readonly":{"description":"List of users with read-only privileges.","type":"array","items":{"type":"string"}}}}}}},"backup":{"description":"Backup configuration.","type":"object","default":{},"required":["enabled"],"properties":{"destinationPath":{"description":"Destination path for backups (e.g. s3://bucket/path/). Ignored when useSystemBucket is true (the driver injects the platform bucket).","type":"string","default":"s3://bucket/path/to/folder/"},"enabled":{"description":"Enable regular backups.","type":"boolean","default":false},"endpointURL":{"description":"S3 endpoint URL for uploads. Ignored when useSystemBucket is true (the strategy supplies the platform endpoint).","type":"string","default":"http://minio-gateway-service:9000"},"insecureSkipTLSVerify":{"description":"Skip TLS verification for the S3 endpoint (self-signed, e.g. in-cluster seaweedfs). Ignored when useSystemBucket is true (the platform backupStorage knob applies instead).","type":"boolean","default":false},"retentionPolicy":{"description":"Retention policy (e.g. \"30d\"). Ignored when useSystemBucket is true (no engine-side retention on that flow).","type":"string","default":"30d"},"s3AccessKey":{"description":"Access key for S3 authentication. Ignored when useSystemBucket is true (credentials come from the projected cozy-backups-creds).","type":"string","default":""},"s3SecretKey":{"description":"Secret key for S3 authentication. Ignored when useSystemBucket is true (credentials come from the projected cozy-backups-creds).","type":"string","default":""},"schedule":{"description":"Cron schedule for automated backups. Ignored when useSystemBucket is true (scheduling moves to the BackupClass Plan).","type":"string","default":"0 2 * * *"},"useSystemBucket":{"description":"Opt-in: back up to the platform system bucket without supplying S3 credentials. The cozy-default MongoDB BackupClass injects the storage at BackupJob time; tenants do not set s3AccessKey/s3SecretKey/destinationPath/endpointURL, and backups scope to `/`. Scheduling moves to a BackupClass Plan; `schedule`, `retentionPolicy` and PITR are ignored while this is on, and this flow has no retention yet (see docs/operations/backup-classes.md).","type":"boolean","default":false}}},"bootstrap":{"description":"Bootstrap configuration.","type":"object","default":{},"required":["backupName","enabled"],"properties":{"backupName":{"description":"Name of backup to restore from.","type":"string","default":""},"enabled":{"description":"Whether to restore from a backup.","type":"boolean","default":false},"recoveryTime":{"description":"Timestamp for point-in-time recovery; empty means latest.","type":"string","default":""}}}}} release: prefix: mongodb- labels: From d091c9951c20c0c3cad8f76af4a93096a51fe425 Mon Sep 17 00:00:00 2001 From: Andrey Kolkov Date: Thu, 17 Sep 2026 09:58:19 +0400 Subject: [PATCH 0016/1280] fix(mongodb): requeue after a fresh storage injection so the operator's cache can observe it MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The first BackupJob of a useSystemBucket app SSA-injected the storage and minted the operator PerconaServerMongoDBBackup in one reconcile. The psmdb operator resolves spec.backup.storages from a cached cluster read when it services that CR, and a cache that has not yet observed the apply takes the not-found branch and latches the CR at State=error — which the operator never re-drives (it returns for a terminal-state CR and watches only the Backup CR and Pods) and the driver reads as a terminal failure. Only the first job per app is exposed; later ones re-apply an already-declared storage. When the pre-apply cluster did not already declare the storage, requeue after the apply instead of minting in the same pass. The next reconcile finds the storage in this driver's own cache (a good proxy that the operator's has caught up too) and only then mints the CR — one 5s poll per app, well inside the deadline. A fake client has no informer lag, so this is pinned by asserting the first pass requeues and mints nothing rather than by reproducing the timing. Also correct the RBAC delete-grant comment: the 30m timeout branch cancels a not-yet-started operator CR on either flow, not just the useSystemBucket cleanup, so a Failed BackupJob never leaves a CR the operator would run later. And pin the wantBucket=="" restore-credential short-circuit with a no-bucket source case. Assisted-By: LLM Signed-off-by: Andrey Kolkov --- .../psmdbstrategy_controller.go | 16 ++++ .../psmdbstrategy_controller_test.go | 77 ++++++++++++++++--- .../templates/rbac.yaml | 11 ++- 3 files changed, 91 insertions(+), 13 deletions(-) diff --git a/internal/backupcontroller/psmdbstrategy_controller.go b/internal/backupcontroller/psmdbstrategy_controller.go index baa88a465..04735e39e 100644 --- a/internal/backupcontroller/psmdbstrategy_controller.go +++ b/internal/backupcontroller/psmdbstrategy_controller.go @@ -268,6 +268,7 @@ func (r *BackupJobReconciler) reconcileMongoDB(ctx context.Context, j *backupsv1 // that can never service a backup should not be mutated just to fail the // precondition below on the enabled check anyway. if cluster.Spec.Backup.Enabled && shouldInjectMongoDBSystemStorage(useSystemBucket, rendered) { + _, storageDeclared := cluster.Spec.Backup.Storages[storageName] injected, err := r.applyMongoDBSystemStorage(ctx, j.Namespace, psmdbName, storageName, rendered.S3) if err != nil { // A server-side apply can fail transiently — an apiserver hiccup, or a @@ -283,6 +284,21 @@ func (r *BackupJobReconciler) reconcileMongoDB(ctx context.Context, j *backupsv1 return ctrl.Result{}, err } cluster = injected + if !storageDeclared { + // First injection for this app: the storage is now applied, but the + // psmdb operator resolves spec.backup.storages from a CACHED cluster + // read when it services the PerconaServerMongoDBBackup, and its cache + // may not have observed the apply yet. A miss there latches the CR at + // State=error with nothing to re-drive it (the operator returns for a + // terminal-state CR and watches only the Backup CR and Pods), and the + // driver reads that as a terminal failure. So requeue instead of + // minting the CR in the same pass: on the next reconcile this driver's + // own cache reflects the storage (storageDeclared is true), which is a + // good proxy that the operator's does too, and only then do we mint. + // One 5s poll per app, well inside the deadline; later BackupJobs find + // the storage already declared and skip straight through. + return ctrl.Result{RequeueAfter: psmdbPollInterval}, nil + } } if msg := psmdbBackupPrecondition(cluster, storageName); msg != "" { if psmdbBackupDeadlineExceeded(j.Status.StartedAt) { diff --git a/internal/backupcontroller/psmdbstrategy_controller_test.go b/internal/backupcontroller/psmdbstrategy_controller_test.go index ba9893a02..b2825a8b6 100644 --- a/internal/backupcontroller/psmdbstrategy_controller_test.go +++ b/internal/backupcontroller/psmdbstrategy_controller_test.go @@ -278,6 +278,16 @@ func TestMongoDBRestoreCredentialsSecret(t *testing.T) { target: target(map[string]runtime.RawExtension{"s3-storage": s3Storage("tenant-bucket", "target-s3-creds")}), want: "", }, + { + // Source archive with no bucket recorded (wantBucket==""): the swap + // must be refused even against a lone target storage that also has an + // empty bucket, keeping the source reference. Pins the wantBucket=="" + // short-circuit — without it that sole storage would be adopted. + name: "no-bucket source: keep source creds against an empty-bucket target storage", + source: src("", "src-s3-creds"), + target: target(map[string]runtime.RawExtension{"only": s3Storage("", "empty-bucket-creds")}), + want: "src-s3-creds", + }, } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { @@ -1166,25 +1176,23 @@ func TestReconcileMongoDB_InjectsSystemStorageBeforePrecondition(t *testing.T) { Parameters: map[string]string{}, } + // First pass: the storage is freshly injected, so the driver requeues rather + // than minting the Backup CR in the same reconcile (see the injection-race + // note in reconcileMongoDB). The apply is persisted onto the live cluster. res, err := r.reconcileMongoDB(context.Background(), job.DeepCopy(), resolved) if err != nil { - t.Fatalf("reconcileMongoDB: %v", err) + t.Fatalf("reconcileMongoDB pass 1: %v", err) } if res.RequeueAfter == 0 { - t.Fatalf("expected a poll requeue while the operator Backup runs, got %+v", res) + t.Fatalf("expected a requeue after the first injection, got %+v", res) } - - // The precondition passed only because it read the injected cluster: an - // operator Backup CR now exists. list := &psmdbtypes.PerconaServerMongoDBBackupList{} if err := c.List(context.Background(), list, client.InNamespace("tenant")); err != nil { t.Fatalf("list operator backups: %v", err) } - if len(list.Items) != 1 { - t.Fatalf("expected the injection to let the precondition pass and create 1 operator Backup, got %d", len(list.Items)) + if len(list.Items) != 0 { + t.Fatalf("no operator Backup should be minted before the requeue, got %d", len(list.Items)) } - - // The storage was actually persisted onto the live cluster. got := &psmdbtypes.PerconaServerMongoDB{} if err := c.Get(context.Background(), types.NamespacedName{Namespace: "tenant", Name: "mongodb-app1"}, got); err != nil { t.Fatalf("get cluster: %v", err) @@ -1192,6 +1200,23 @@ func TestReconcileMongoDB_InjectsSystemStorageBeforePrecondition(t *testing.T) { if _, ok := got.Spec.Backup.Storages["s3-storage"]; !ok { t.Errorf("expected injected s3-storage on the cluster, got %#v", got.Spec.Backup.Storages) } + + // Second pass: the cluster already declares the storage (the operator cache + // has had a poll to observe it), so the precondition passes off the injected + // storage and the operator Backup CR is minted. + res, err = r.reconcileMongoDB(context.Background(), job.DeepCopy(), resolved) + if err != nil { + t.Fatalf("reconcileMongoDB pass 2: %v", err) + } + if res.RequeueAfter == 0 { + t.Fatalf("expected a poll requeue while the operator Backup runs, got %+v", res) + } + if err := c.List(context.Background(), list, client.InNamespace("tenant")); err != nil { + t.Fatalf("list operator backups: %v", err) + } + if len(list.Items) != 1 { + t.Fatalf("expected the injected storage to let the precondition pass and create 1 operator Backup, got %d", len(list.Items)) + } } // mongodbInjectFixture builds the four objects reconcileMongoDB needs to reach @@ -1234,6 +1259,34 @@ func mongodbInjectFixture(enabled bool) (*backupsv1alpha1.BackupJob, *strategyv1 return job, strategy, app, cluster, resolved } +// The first BackupJob of a useSystemBucket app injects the storage; the psmdb +// operator resolves it from a cached cluster read when it services the Backup +// CR, so minting the CR in the same pass races that cache and can latch it at +// State=error. The driver must requeue after a fresh injection instead of +// minting, giving the cache a poll to observe the storage. +func TestReconcileMongoDB_FirstInjectionRequeuesBeforeMinting(t *testing.T) { + // Fixture seeds a cluster with backups enabled and NO storage declared. + job, strategy, app, cluster, resolved := mongodbInjectFixture(true) + c := newMongoDBStrategyTestClient(t, job, strategy, app, cluster) + r := &BackupJobReconciler{Client: c, Scheme: c.Scheme()} + + res, err := r.reconcileMongoDB(context.Background(), job.DeepCopy(), resolved) + if err != nil { + t.Fatalf("reconcileMongoDB: %v", err) + } + if res.RequeueAfter == 0 { + t.Fatalf("expected a requeue after the first injection, got %+v", res) + } + // No operator Backup CR minted yet — that waits for the next pass. + list := &psmdbtypes.PerconaServerMongoDBBackupList{} + if err := c.List(context.Background(), list, client.InNamespace("tenant")); err != nil { + t.Fatalf("list: %v", err) + } + if len(list.Items) != 0 { + t.Errorf("no operator Backup should be created in the same pass as a fresh injection, got %d", len(list.Items)) + } +} + // When a backup the operator never started (state=waiting, queued behind // another) trips the deadline, the driver must cancel the operator CR before // failing the BackupJob — otherwise the operator starts it later and writes an @@ -1257,6 +1310,12 @@ func TestReconcileMongoDB_TimedOutBackupIsCancelled(t *testing.T) { }, Status: psmdbtypes.PerconaServerMongoDBBackupStatus{State: psmdbtypes.StateWaiting}, } + // The storage is already declared (injected on the pass that minted the + // backup 30m ago), so this reconcile re-applies it without the first-injection + // requeue and reaches the timeout branch. + cluster.Spec.Backup.Storages = map[string]runtime.RawExtension{ + "s3-storage": {Raw: []byte(`{"type":"s3","s3":{"bucket":"cozy-backups"}}`)}, + } c := newMongoDBStrategyTestClient(t, job, strategy, app, cluster, opBackup) r := &BackupJobReconciler{Client: c, Scheme: c.Scheme()} diff --git a/packages/system/backupstrategy-controller/templates/rbac.yaml b/packages/system/backupstrategy-controller/templates/rbac.yaml index 3d70dca61..f6486e3dc 100644 --- a/packages/system/backupstrategy-controller/templates/rbac.yaml +++ b/packages/system/backupstrategy-controller/templates/rbac.yaml @@ -166,10 +166,13 @@ rules: verbs: ["get", "list", "watch", "patch"] - apiGroups: ["psmdb.percona.com"] resources: ["perconaservermongodbbackups"] - # delete: on the useSystemBucket flow the driver owns the shared-bucket archive - # and prunes it on Cozystack Backup deletion by deleting this CR, whose - # delete-backup finalizer frees the object (see cleanupMongoDBBackup). A legacy - # backup lives in the tenant's own bucket and is never deleted here. + # delete: two paths. On the useSystemBucket flow cleanupMongoDBBackup prunes the + # shared-bucket archive on Cozystack Backup deletion by deleting this CR, whose + # delete-backup finalizer frees the object (a legacy backup carries no such + # finalizer, so its own-bucket archive is left). Independently, the BackupJob's + # 30m timeout cancels a not-yet-started operator CR on either flow, so a Failed + # job never leaves a CR the operator would run later (see the deadline branch in + # reconcileMongoDB). # patch: strip the driver's own delete-backup finalizer to release a wedged # cleanup (namespace terminating, or the skip-artifact-cleanup annotation) so # the driver's finalizer is not what holds a tenant namespace in Terminating From 0aaf5e1e050e582189a53e21693156ffe090831e Mon Sep 17 00:00:00 2001 From: Andrey Kolkov Date: Thu, 17 Sep 2026 10:23:46 +0400 Subject: [PATCH 0017/1280] docs(mongodb): condense the psmdb-backups RBAC comment so it does not ship into the ClusterRole The delete/patch grant justification had grown to an 11-line `#` block, which (unlike a `{{/* */}}` comment) renders verbatim into every cluster's ClusterRole and drifts out of date as the code moves. Condense it to a short pointer at reconcileMongoDB / cleanupMongoDBBackup and the docs, where the detail is versioned; keep only enough to explain the non-obvious grant. Assisted-By: LLM Signed-off-by: Andrey Kolkov --- .../templates/rbac.yaml | 16 +++++----------- 1 file changed, 5 insertions(+), 11 deletions(-) diff --git a/packages/system/backupstrategy-controller/templates/rbac.yaml b/packages/system/backupstrategy-controller/templates/rbac.yaml index f6486e3dc..a20a0052e 100644 --- a/packages/system/backupstrategy-controller/templates/rbac.yaml +++ b/packages/system/backupstrategy-controller/templates/rbac.yaml @@ -166,17 +166,11 @@ rules: verbs: ["get", "list", "watch", "patch"] - apiGroups: ["psmdb.percona.com"] resources: ["perconaservermongodbbackups"] - # delete: two paths. On the useSystemBucket flow cleanupMongoDBBackup prunes the - # shared-bucket archive on Cozystack Backup deletion by deleting this CR, whose - # delete-backup finalizer frees the object (a legacy backup carries no such - # finalizer, so its own-bucket archive is left). Independently, the BackupJob's - # 30m timeout cancels a not-yet-started operator CR on either flow, so a Failed - # job never leaves a CR the operator would run later (see the deadline branch in - # reconcileMongoDB). - # patch: strip the driver's own delete-backup finalizer to release a wedged - # cleanup (namespace terminating, or the skip-artifact-cleanup annotation) so - # the driver's finalizer is not what holds a tenant namespace in Terminating - # (the operator's own release-lock finalizer can still hold it if it is down). + # delete: prune a useSystemBucket archive by deleting its CR (the delete-backup + # finalizer frees the object), and cancel a not-yet-started CR at the BackupJob + # timeout on either flow. patch: strip the driver's own delete-backup finalizer + # to release a wedged cleanup. See reconcileMongoDB / cleanupMongoDBBackup and + # docs/operations/backup-classes.md. verbs: ["get", "list", "watch", "create", "delete", "patch"] - apiGroups: ["psmdb.percona.com"] resources: ["perconaservermongodbrestores"] From 2293c0c07374540cff8b9ea9ba4d9ed636d04674 Mon Sep 17 00:00:00 2001 From: Andrey Kolkov Date: Thu, 17 Sep 2026 16:26:20 +0400 Subject: [PATCH 0018/1280] fix(mongodb): bound and surface the useSystemBucket backup race-recovery waits The useSystemBucket driver injects storage onto the live cluster at BackupJob time and works around the psmdb operator resolving that storage from a cache that has not yet observed the apply. Several of those waits were unbounded or silent, and a PITR restore of a system-bucket backup reached the operator despite no oplog ever being captured on that flow: - the first-injection requeue now fails terminally once the backup deadline passes, instead of polling a cluster whose cache never reflects the storage - a state=error the operator raises because it has not yet seen the injected storage is retried (delete the CR, requeue) within the deadline rather than failing the BackupJob on the driver's own race - a backup wedged in state=running past the stall window surfaces Ready=False and a Warning once its status stops transitioning, so it no longer parks later BackupJobs in silence, and is never cancelled (that would strand the partial archive pbm keeps writing to the shared bucket) - the timeout-cancel path re-reads the CR live before deleting, so a waiting CR whose live state just turned running at the boundary is not deleted mid-dump - a failed delete-backup finalizer strip now emits a Warning naming the stuck object instead of the success-case event - a recoveryTime restore over a system-bucket backup fails with a named error rather than handing the operator a point-in-time target it cannot serve Assisted-By: LLM Signed-off-by: Andrey Kolkov --- .../psmdbstrategy_controller.go | 209 +++++++++++--- .../psmdbstrategy_controller_test.go | 269 +++++++++++++++++- 2 files changed, 437 insertions(+), 41 deletions(-) diff --git a/internal/backupcontroller/psmdbstrategy_controller.go b/internal/backupcontroller/psmdbstrategy_controller.go index 04735e39e..102e70d0c 100644 --- a/internal/backupcontroller/psmdbstrategy_controller.go +++ b/internal/backupcontroller/psmdbstrategy_controller.go @@ -14,7 +14,9 @@ import ( apierrors "k8s.io/apimachinery/pkg/api/errors" apimeta "k8s.io/apimachinery/pkg/api/meta" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/types" ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/client" @@ -94,6 +96,14 @@ const ( // Plan-controller queue. Mirrors the MariaDB/CNPG deadline. psmdbDefaultBackupDeadline = 30 * time.Minute + // psmdbBackupStallWindow is how long an operator backup may sit in + // state=running without its status.lastTransition advancing before the driver + // treats it as stalled and surfaces it (Ready=False + a Warning). A streaming + // dump keeps transitioning well inside this; the window is generous so a slow + // but progressing dump is never mistaken for a stall. A stalled dump is + // surfaced, not killed — cancelling it would strand a partial archive. + psmdbBackupStallWindow = 30 * time.Minute + // Default deadline on a RestoreJob waiting for the operator Restore to // terminate. Tenants override via spec.options.restoreTimeoutSeconds. psmdbDefaultRestoreDeadline = 30 * time.Minute @@ -112,6 +122,14 @@ const ( // existing API surface. Mirrors the MariaDB driver. var psmdbBackupSnapshotAPIVersion = backupsv1alpha1.GroupVersion.String() +// psmdbBackupGVR addresses PerconaServerMongoDBBackup through the dynamic client +// for an uncached, live status read (see psmdbBackupLiveState). +var psmdbBackupGVR = schema.GroupVersionResource{ + Group: psmdbtypes.GroupVersion.Group, + Version: psmdbtypes.GroupVersion.Version, + Resource: "perconaservermongodbbackups", +} + // mongodbNameForApp returns the psmdb.percona.com/PerconaServerMongoDB CR name // for a cozystack MongoDB application instance. func mongodbNameForApp(appName string) string { @@ -295,9 +313,18 @@ func (r *BackupJobReconciler) reconcileMongoDB(ctx context.Context, j *backupsv1 // minting the CR in the same pass: on the next reconcile this driver's // own cache reflects the storage (storageDeclared is true), which is a // good proxy that the operator's does too, and only then do we mint. - // One 5s poll per app, well inside the deadline; later BackupJobs find - // the storage already declared and skip straight through. - return ctrl.Result{RequeueAfter: psmdbPollInterval}, nil + // Later BackupJobs find the storage already declared and skip through. + // + // Bounded and observable like the other waits: consult the deadline so + // a cluster whose cache never reflects the storage cannot poll forever, + // and write Ready=False so the wait is named in kubectl describe. + if psmdbBackupDeadlineExceeded(j.Status.StartedAt) { + return r.markBackupJobFailed(ctx, j, fmt.Sprintf( + "psmdb.percona.com/PerconaServerMongoDB %s/%s did not reflect the injected storage %q within %s", + j.Namespace, psmdbName, storageName, psmdbDefaultBackupDeadline)) + } + return r.requeueMongoDBBackupWaiting(ctx, j, "PerconaServerMongoDBStorageInjected", + fmt.Sprintf("injected storage %q; waiting for the cluster to reflect it before starting the backup", storageName)) } } if msg := psmdbBackupPrecondition(cluster, storageName); msg != "" { @@ -349,49 +376,87 @@ func (r *BackupJobReconciler) reconcileMongoDB(ctx context.Context, j *backupsv1 return ctrl.Result{}, nil case state == psmdbtypes.StateError || state == psmdbtypes.StateRejected: + message := mdbBackup.Status.Error + // The residual half of the injection race: on the useSystemBucket flow the + // operator can latch state=error because it resolved the injected storage + // from a cluster cache that had not yet observed the apply. That is the + // driver's own race, not the tenant's failure, so retry it (bounded by the + // deadline) — delete the errored CR so a fresh one resolves against a + // caught-up cache — rather than failing the BackupJob terminally. + if useSystemBucket && psmdbErrorIsUnresolvedStorage(message, storageName) && !psmdbBackupDeadlineExceeded(j.Status.StartedAt) { + if mdbBackup.DeletionTimestamp.IsZero() { + if derr := r.Delete(ctx, mdbBackup); derr != nil && !apierrors.IsNotFound(derr) { + return ctrl.Result{}, derr + } + } + return r.requeueMongoDBBackupWaiting(ctx, j, "PerconaServerMongoDBStorageRace", + fmt.Sprintf("operator has not observed the injected storage %q yet; retrying the backup", storageName)) + } // Terminal failure. The operator sets state=error/rejected once the pbm // backup fails or is refused, so fail the BackupJob immediately rather // than waiting for the driver-side deadline. - message := mdbBackup.Status.Error if message == "" { message = fmt.Sprintf("psmdb.percona.com PerconaServerMongoDBBackup reported state=%s", state) } return r.markBackupJobFailed(ctx, j, message) default: - // Still in progress ("", requested, running, waiting). A wall-clock - // deadline fails a backup the operator never starts (so it cannot pin the - // BackupJob Running forever), but a running dump is left to finish rather - // than stranding its archive — see psmdbBackupTimedOut. - if psmdbBackupTimedOut(state, j.Status.StartedAt) { - // Cancel the operator CR before failing. A `waiting` backup is queued - // behind another and the operator starts it once the slot frees — which - // would be after this BackupJob is Failed and never reconciled again, - // writing an archive into the shared bucket that no Backup object - // represents. Deleting the CR before the operator sends the backup - // command prevents that late run: at v1.22.0 the operator returns for a - // CR with a deletion timestamp before it reaches the code that calls - // Start. (It does not clean up a partial object — the delete-backup - // finalizer prunes storage only for a `ready` backup — but nothing is - // partially written until the backup actually runs, which the cancel - // prevents.) Best-effort: a delete failure must not stop the job from - // failing (a leftover CR is the pre-existing behaviour, not a - // regression). The terminal Phase=Failed makes reconcileMongoDB return - // early next time, so ensureMongoDBBackup never re-creates it. - if mdbBackup.DeletionTimestamp.IsZero() { - if derr := r.Delete(ctx, mdbBackup); derr != nil && !apierrors.IsNotFound(derr) { - getLogger(ctx).Debug("could not cancel the timed-out operator backup before failing", - "backupjob", j.Name, "sourceBackup", mdbBackup.Name, "error", derr) + // Still in progress ("", requested, running, waiting). + if state == psmdbtypes.StateRunning { + // A dump that is streaming is never killed — failing it would strand a + // partial archive on the shared bucket. But `running` is also where a CR + // freezes when nothing progresses (a cluster gone unhealthy mid-dump, an + // unrecognised pbm status): a progressing dump keeps bumping its + // status.lastTransition, a stalled one leaves it stale. A stalled backup + // holds the operator's backup lease and parks every later BackupJob for + // the app behind it, so past the stall window it must not pin things in + // silence — surface it (Ready=False + a Warning) without cancelling and + // stranding whatever pbm has written. + if psmdbBackupRunningStalled(mdbBackup, j.Status.StartedAt) { + if r.Recorder != nil { + r.Recorder.Eventf(j, corev1.EventTypeWarning, "BackupStalled", + "psmdb.percona.com/PerconaServerMongoDBBackup %s is stuck in state=running with no status transition for over %s; left running to avoid stranding a partial archive — investigate the operator/cluster", + mdbBackup.Name, psmdbBackupStallWindow) } + return r.requeueMongoDBBackupWaiting(ctx, j, "PerconaServerMongoDBBackupStalled", + fmt.Sprintf("backup stuck in state=running with no status transition for over %s; left running to avoid stranding a partial archive", psmdbBackupStallWindow)) } - detail := "no state observed" - if state != "" { - detail = fmt.Sprintf("state=%s", state) - } - return r.markBackupJobFailed(ctx, j, fmt.Sprintf( - "psmdb.percona.com PerconaServerMongoDBBackup did not start within %s (%s)", psmdbDefaultBackupDeadline, detail)) + return ctrl.Result{RequeueAfter: psmdbPollInterval}, nil } - return ctrl.Result{RequeueAfter: psmdbPollInterval}, nil + // Not-yet-started states ("", requested, waiting). A wall-clock deadline + // fails a backup the operator never starts, so it cannot pin the BackupJob + // Running forever. + if !psmdbBackupTimedOut(state, j.Status.StartedAt) { + return ctrl.Result{RequeueAfter: psmdbPollInterval}, nil + } + // The deadline hit for a not-yet-started backup. mdbBackup came from the + // cache, so re-read the CR live before cancelling: a `waiting` CR whose + // live state has just turned running at the deadline boundary must not be + // deleted mid-dump, stranding the partial the running branch avoids. If it + // started, defer to the running branch on the next reconcile. + if r.psmdbBackupLiveState(ctx, mdbBackup.Namespace, mdbBackup.Name) == psmdbtypes.StateRunning { + return ctrl.Result{RequeueAfter: psmdbPollInterval}, nil + } + // Cancel the operator CR before failing. On the observed (and re-read) + // not-started state nothing is written, and at v1.22.0 the operator returns + // for a CR with a deletion timestamp before it dispatches to pbm, so the + // delete prevents a late run into the shared bucket that no Backup object + // would represent. Best-effort: a delete failure must not stop the job from + // failing (a leftover CR is the pre-existing behaviour, not a regression). + // The terminal Phase=Failed makes reconcileMongoDB return early next time, + // so ensureMongoDBBackup never re-creates it. + if mdbBackup.DeletionTimestamp.IsZero() { + if derr := r.Delete(ctx, mdbBackup); derr != nil && !apierrors.IsNotFound(derr) { + getLogger(ctx).Debug("could not cancel the timed-out operator backup before failing", + "backupjob", j.Name, "sourceBackup", mdbBackup.Name, "error", derr) + } + } + detail := "no state observed" + if state != "" { + detail = fmt.Sprintf("state=%s", state) + } + return r.markBackupJobFailed(ctx, j, fmt.Sprintf( + "psmdb.percona.com PerconaServerMongoDBBackup did not start within %s (%s)", psmdbDefaultBackupDeadline, detail)) } } @@ -624,6 +689,49 @@ func psmdbBackupTimedOut(state string, startedAt *metav1.Time) bool { return psmdbBackupDeadlineExceeded(startedAt) } +// psmdbBackupRunningStalled reports whether an operator backup left in +// state=running has stopped making progress. The operator copies pbm's +// last-transition timestamp into status.lastTransition, which advances while a +// dump streams and freezes when nothing progresses (a cluster gone unhealthy +// mid-dump, or a pbm status the operator maps to running but never updates). A +// stale lastTransition past the stall window is the signal; when it is unset the +// operator has not written progress at all, so the BackupJob's own deadline +// stands in. A stalled running backup is surfaced, never cancelled — cancelling +// would strand whatever pbm has already written. +func psmdbBackupRunningStalled(b *psmdbtypes.PerconaServerMongoDBBackup, startedAt *metav1.Time) bool { + if lt := b.Status.LastTransition; lt != nil { + return time.Since(lt.Time) > psmdbBackupStallWindow + } + return psmdbBackupDeadlineExceeded(startedAt) +} + +// psmdbErrorIsUnresolvedStorage reports whether a PerconaServerMongoDBBackup +// error is the operator failing to resolve the named storage — the message the +// v1.22.0 backup reconciler sets ("unable to get storage ''") when it +// reads a cluster cache that has not yet observed the driver's storage +// injection. That is the residual half of the injection race, retryable rather +// than a tenant failure. +func psmdbErrorIsUnresolvedStorage(errMsg, storageName string) bool { + return strings.Contains(errMsg, "unable to get storage") && strings.Contains(errMsg, storageName) +} + +// psmdbBackupLiveState reads the operator backup CR straight from the apiserver +// (bypassing the informer cache) and returns its status.state, or "" when the CR +// cannot be read. The timeout-cancel path uses it to avoid deleting a CR whose +// cached state still reads not-started at the deadline boundary while its live +// state has just turned running. +func (r *BackupJobReconciler) psmdbBackupLiveState(ctx context.Context, namespace, name string) string { + if r.Interface == nil { + return "" + } + u, err := r.Interface.Resource(psmdbBackupGVR).Namespace(namespace).Get(ctx, name, metav1.GetOptions{}) + if err != nil { + return "" + } + state, _, _ := unstructured.NestedString(u.Object, "status", "state") + return state +} + // ensureMongoDBBackup creates a one-shot PerconaServerMongoDBBackup CR labelled // with the BackupJob, or returns the existing one if a previous reconcile // already created it. Idempotency relies on the OwningJob labels. @@ -887,11 +995,24 @@ func (r *BackupReconciler) releaseMongoDBCleanup(ctx context.Context, backup *ba logger := getLogger(ctx) if live == nil { fetched := &psmdbtypes.PerconaServerMongoDBBackup{} - if err := r.Get(ctx, types.NamespacedName{Namespace: backup.Namespace, Name: sourceBackupName}, fetched); err != nil || - !controllerutil.ContainsFinalizer(fetched, psmdbDeleteBackupFinalizer) { - // Legacy backup (no delete-backup finalizer) or an unreadable CR: - // nothing of the driver's to strip or delete. Leave the operator CR - // untouched and release the Cozystack Backup. + err := r.Get(ctx, types.NamespacedName{Namespace: backup.Namespace, Name: sourceBackupName}, fetched) + switch { + case err != nil: + // The CR could not be read (its CRD removed, the verb revoked, a + // throttle). It may still carry the driver's delete-backup finalizer, so + // the annotation releases the Backup regardless — but this is the same + // class of leftover as a failed strip below, so surface which object may + // be left finalized rather than a Debug line nobody sees. + logger.Info("releasing MongoDB Backup; could not read the operator CR to strip its finalizer", + "backup", backup.Name, "sourceBackup", sourceBackupName, "reason", reason, "error", err) + if r.Recorder != nil { + r.Recorder.Eventf(backup, corev1.EventTypeWarning, "FinalizerNotStripped", + "released Backup but could not read PerconaServerMongoDBBackup %s to strip its delete-backup finalizer (%v); if it carries the finalizer it may hold its namespace in Terminating", sourceBackupName, err) + } + return ctrl.Result{}, nil + case !controllerutil.ContainsFinalizer(fetched, psmdbDeleteBackupFinalizer): + // Legacy backup (no delete-backup finalizer): genuinely not the + // driver's, so leave the operator CR untouched and release quietly. logger.Debug("releasing MongoDB Backup; no driver-owned archive to prune", "backup", backup.Name, "sourceBackup", sourceBackupName, "reason", reason) return ctrl.Result{}, nil @@ -1029,6 +1150,16 @@ func (r *RestoreJobReconciler) reconcileMongoDBRestore(ctx context.Context, rest return r.markRestoreJobFailed(ctx, restoreJob, err.Error()) } + // Point-in-time recovery needs an oplog stream, which the useSystemBucket flow + // never captures — the chart leaves spec.backup.pitr unset there (see + // backup-classes.md). Refuse a recoveryTime restore of a system-bucket backup + // with a named error rather than hand the operator a PITR target it cannot + // serve; the source's projected cozy-backups-creds identifies the flow. + if pitr != nil && source.S3 != nil && source.S3.CredentialsSecret == psmdbDefaultCredentialsSecret { + return r.markRestoreJobFailed(ctx, restoreJob, + "restoreJob.spec.options.recoveryTime is set, but point-in-time recovery is not available for a backup taken on the useSystemBucket flow (no oplog is captured there); omit recoveryTime to restore the backup as taken. See docs/operations/backup-classes.md.") + } + // The operator Restore replays into a live cluster, so the target // PerconaServerMongoDB must exist (and, for the pbm agents to run the // restore, have backups enabled). Mirror the backup path's transient diff --git a/internal/backupcontroller/psmdbstrategy_controller_test.go b/internal/backupcontroller/psmdbstrategy_controller_test.go index b2825a8b6..5cf1c2b0d 100644 --- a/internal/backupcontroller/psmdbstrategy_controller_test.go +++ b/internal/backupcontroller/psmdbstrategy_controller_test.go @@ -1203,8 +1203,13 @@ func TestReconcileMongoDB_InjectsSystemStorageBeforePrecondition(t *testing.T) { // Second pass: the cluster already declares the storage (the operator cache // has had a poll to observe it), so the precondition passes off the injected - // storage and the operator Backup CR is minted. - res, err = r.reconcileMongoDB(context.Background(), job.DeepCopy(), resolved) + // storage and the operator Backup CR is minted. Re-fetch the BackupJob first — + // pass 1 wrote its Ready=False condition, so a stale copy would conflict. + fresh := &backupsv1alpha1.BackupJob{} + if err := c.Get(context.Background(), types.NamespacedName{Namespace: "tenant", Name: "bj-inj"}, fresh); err != nil { + t.Fatalf("re-get job: %v", err) + } + res, err = r.reconcileMongoDB(context.Background(), fresh, resolved) if err != nil { t.Fatalf("reconcileMongoDB pass 2: %v", err) } @@ -1850,3 +1855,263 @@ func TestReleaseMongoDBCleanup_UsesPassedObjectNotReRead(t *testing.T) { t.Errorf("expected an ArtifactNotDeleted event (passed object used, strip ran), got none") } } + +// state=running is the driver's one never-cancel state, so the only signal that +// a run is wedged rather than streaming is its status.lastTransition going +// stale. Pin both readings: a transition older than the stall window is stalled, +// a fresh one is progressing. The nil-lastTransition fallback leans on the +// wall-clock deadline (an operator that never wrote a transition at all). +func TestPsmdbBackupRunningStalled(t *testing.T) { + pastDeadline := &metav1.Time{Time: time.Now().Add(-2 * psmdbDefaultBackupDeadline)} + recentStart := &metav1.Time{Time: time.Now()} + staleLT := &metav1.Time{Time: time.Now().Add(-2 * psmdbBackupStallWindow)} + freshLT := &metav1.Time{Time: time.Now()} + + cases := []struct { + name string + lt *metav1.Time + started *metav1.Time + want bool + }{ + {"stale transition is stalled", staleLT, recentStart, true}, + {"fresh transition is progressing", freshLT, pastDeadline, false}, + {"no transition, past deadline is stalled", nil, pastDeadline, true}, + {"no transition, recent start is progressing", nil, recentStart, false}, + } + for _, tc := range cases { + b := &psmdbtypes.PerconaServerMongoDBBackup{ + Status: psmdbtypes.PerconaServerMongoDBBackupStatus{State: psmdbtypes.StateRunning, LastTransition: tc.lt}, + } + if got := psmdbBackupRunningStalled(b, tc.started); got != tc.want { + t.Errorf("%s: got %v want %v", tc.name, got, tc.want) + } + } +} + +// The storage-race retry hinges on recognising the operator's own +// unable-to-get-storage error and only that: a different error, or the right +// error naming a different storage, must not be swallowed as retryable. +func TestPsmdbErrorIsUnresolvedStorage(t *testing.T) { + cases := []struct { + msg, storage string + want bool + }{ + {`unable to get storage "s3-storage": not found`, "s3-storage", true}, + {`unable to get storage "other": not found`, "s3-storage", false}, + {"connection refused", "s3-storage", false}, + {"", "s3-storage", false}, + } + for _, tc := range cases { + if got := psmdbErrorIsUnresolvedStorage(tc.msg, tc.storage); got != tc.want { + t.Errorf("psmdbErrorIsUnresolvedStorage(%q, %q): got %v want %v", tc.msg, tc.storage, got, tc.want) + } + } +} + +// The first-injection requeue waits for the cluster cache to reflect the applied +// storage, but that wait is deadline-bounded: a cluster whose cache never +// reflects it must fail terminally, not requeue forever. Pin the bound — a fresh +// injection past the deadline fails the BackupJob without minting a Backup CR. +func TestReconcileMongoDB_FirstInjectionDeadlineFails(t *testing.T) { + job, strategy, app, cluster, resolved := mongodbInjectFixture(true) + // No storage declared (fresh injection) and started well past the deadline. + job.Status.StartedAt = &metav1.Time{Time: time.Now().Add(-2 * psmdbDefaultBackupDeadline)} + + c := newMongoDBStrategyTestClient(t, job, strategy, app, cluster) + r := &BackupJobReconciler{Client: c, Scheme: c.Scheme()} + + if _, err := r.reconcileMongoDB(context.Background(), job.DeepCopy(), resolved); err != nil { + t.Fatalf("reconcileMongoDB: %v", err) + } + + persisted := &backupsv1alpha1.BackupJob{} + if err := c.Get(context.Background(), types.NamespacedName{Namespace: "tenant", Name: job.Name}, persisted); err != nil { + t.Fatalf("get job: %v", err) + } + if persisted.Status.Phase != backupsv1alpha1.BackupJobPhaseFailed { + t.Fatalf("expected the BackupJob to be Failed past the injection deadline, got phase=%q", persisted.Status.Phase) + } + cond := apimeta.FindStatusCondition(persisted.Status.Conditions, "Ready") + if cond == nil || !strings.Contains(cond.Message, "did not reflect the injected storage") { + t.Errorf("expected a Ready condition naming the unreflected storage, got %+v", cond) + } + list := &psmdbtypes.PerconaServerMongoDBBackupList{} + if err := c.List(context.Background(), list, client.InNamespace("tenant")); err != nil { + t.Fatalf("list: %v", err) + } + if len(list.Items) != 0 { + t.Errorf("no operator Backup should be minted on the deadline failure, got %d", len(list.Items)) + } +} + +// The residual injection race: the operator can latch the Backup CR at +// state=error because it resolved storage from a cache that had not observed the +// apply. Within the deadline the driver must delete that CR and requeue (a fresh +// one resolves against a caught-up cache), not fail the BackupJob — that error +// is the driver's own race, not the tenant's failure. +func TestReconcileMongoDB_StorageRaceErrorRetried(t *testing.T) { + job, strategy, app, cluster, resolved := mongodbInjectFixture(true) + job.Status.StartedAt = &metav1.Time{Time: time.Now()} // within deadline + // Storage already declared so the reconcile skips the first-injection requeue + // and reaches the state switch. + cluster.Spec.Backup.Storages = map[string]runtime.RawExtension{ + "s3-storage": {Raw: []byte(`{"type":"s3","s3":{"bucket":"cozy-backups"}}`)}, + } + errored := &psmdbtypes.PerconaServerMongoDBBackup{ + ObjectMeta: metav1.ObjectMeta{ + Namespace: "tenant", + Name: "op-errored", + Finalizers: []string{psmdbDeleteBackupFinalizer}, + Labels: map[string]string{ + backupsv1alpha1.OwningJobNameLabel: job.Name, + backupsv1alpha1.OwningJobNamespaceLabel: job.Namespace, + }, + }, + Status: psmdbtypes.PerconaServerMongoDBBackupStatus{ + State: psmdbtypes.StateError, + Error: `unable to get storage "s3-storage": not found`, + }, + } + + c := newMongoDBStrategyTestClient(t, job, strategy, app, cluster, errored) + r := &BackupJobReconciler{Client: c, Scheme: c.Scheme()} + + res, err := r.reconcileMongoDB(context.Background(), job.DeepCopy(), resolved) + if err != nil { + t.Fatalf("reconcileMongoDB: %v", err) + } + if res.RequeueAfter == 0 { + t.Fatalf("expected a retry requeue on the storage-race error, got %+v", res) + } + // The errored CR is deleted (Terminating with its finalizer) so a fresh one + // resolves against a caught-up cache. + got := &psmdbtypes.PerconaServerMongoDBBackup{} + gerr := c.Get(context.Background(), types.NamespacedName{Namespace: "tenant", Name: "op-errored"}, got) + if gerr == nil && got.DeletionTimestamp.IsZero() { + t.Errorf("the storage-race errored CR must be deleted before retrying; it was left untouched") + } + // The BackupJob is NOT failed. + persisted := &backupsv1alpha1.BackupJob{} + if err := c.Get(context.Background(), types.NamespacedName{Namespace: "tenant", Name: job.Name}, persisted); err != nil { + t.Fatalf("get job: %v", err) + } + if persisted.Status.Phase == backupsv1alpha1.BackupJobPhaseFailed { + t.Errorf("the storage-race error must be retried, not fail the BackupJob") + } +} + +// A backup wedged in state=running holds the operator's lease and parks every +// later BackupJob behind it, so past the stall window the driver must surface it +// (Ready=False + a Warning) — but never cancel it, which would strand whatever +// pbm has already written to the shared bucket. A run still transitioning stays +// silent. +func TestReconcileMongoDB_RunningStalledSurfaced(t *testing.T) { + newRunning := func(lt *metav1.Time) (*BackupJobReconciler, client.Client, *record.FakeRecorder, *ResolvedBackupConfig, *backupsv1alpha1.BackupJob) { + job, strategy, app, cluster, resolved := mongodbInjectFixture(true) + job.Status.StartedAt = &metav1.Time{Time: time.Now().Add(-2 * psmdbDefaultBackupDeadline)} + cluster.Spec.Backup.Storages = map[string]runtime.RawExtension{ + "s3-storage": {Raw: []byte(`{"type":"s3","s3":{"bucket":"cozy-backups"}}`)}, + } + running := &psmdbtypes.PerconaServerMongoDBBackup{ + ObjectMeta: metav1.ObjectMeta{ + Namespace: "tenant", + Name: "op-running", + Finalizers: []string{psmdbDeleteBackupFinalizer}, + Labels: map[string]string{ + backupsv1alpha1.OwningJobNameLabel: job.Name, + backupsv1alpha1.OwningJobNamespaceLabel: job.Namespace, + }, + }, + Status: psmdbtypes.PerconaServerMongoDBBackupStatus{State: psmdbtypes.StateRunning, LastTransition: lt}, + } + c := newMongoDBStrategyTestClient(t, job, strategy, app, cluster, running) + rec := record.NewFakeRecorder(10) + return &BackupJobReconciler{Client: c, Scheme: c.Scheme(), Recorder: rec}, c, rec, resolved, job + } + + t.Run("stalled run is surfaced but not cancelled", func(t *testing.T) { + r, c, rec, resolved, job := newRunning(&metav1.Time{Time: time.Now().Add(-2 * psmdbBackupStallWindow)}) + res, err := r.reconcileMongoDB(context.Background(), job.DeepCopy(), resolved) + if err != nil { + t.Fatalf("reconcileMongoDB: %v", err) + } + if res.RequeueAfter == 0 { + t.Fatalf("expected a requeue for a stalled run, got %+v", res) + } + select { + case ev := <-rec.Events: + if !strings.Contains(ev, "BackupStalled") { + t.Errorf("expected a BackupStalled event, got %q", ev) + } + default: + t.Errorf("expected a BackupStalled Warning, got none") + } + got := &psmdbtypes.PerconaServerMongoDBBackup{} + if err := c.Get(context.Background(), types.NamespacedName{Namespace: "tenant", Name: "op-running"}, got); err != nil { + t.Fatalf("get running backup: %v", err) + } + if !got.DeletionTimestamp.IsZero() { + t.Errorf("a stalled running backup must never be cancelled (partial archive), it was deleted") + } + }) + + t.Run("progressing run stays silent", func(t *testing.T) { + r, _, rec, resolved, job := newRunning(&metav1.Time{Time: time.Now()}) + if _, err := r.reconcileMongoDB(context.Background(), job.DeepCopy(), resolved); err != nil { + t.Fatalf("reconcileMongoDB: %v", err) + } + select { + case ev := <-rec.Events: + t.Errorf("a progressing run must not emit a stall event, got %q", ev) + default: + } + }) +} + +// PITR needs an oplog stream the useSystemBucket flow never captures, so a +// recoveryTime restore of a system-bucket backup (its source carries the +// projected cozy-backups-creds) must fail with a named error rather than hand +// the operator a target it cannot serve. The refusal fires before the target +// cluster read, so no target need exist. +func TestReconcileMongoDBRestore_RefusesPITROnSystemBucketBackup(t *testing.T) { + apps := mongodbapp.GroupName + snap := &psmdbtypes.PerconaServerMongoDBBackup{ + Status: psmdbtypes.PerconaServerMongoDBBackupStatus{ + Destination: "s3://cozy-backups/tenant/app1/2026", + S3: &psmdbtypes.BackupStorageS3{Bucket: "cozy-backups", CredentialsSecret: psmdbDefaultCredentialsSecret}, + }, + } + raw, err := marshalMongoDBBackupSnapshot(snap, &strategyv1alpha1.MongoDBTemplate{Type: "logical"}, "s3-storage", nil, true) + if err != nil { + t.Fatalf("marshal snapshot: %v", err) + } + backup := &backupsv1alpha1.Backup{ + ObjectMeta: metav1.ObjectMeta{Namespace: "tenant", Name: "src-backup"}, + Spec: backupsv1alpha1.BackupSpec{ + ApplicationRef: corev1.TypedLocalObjectReference{Kind: "MongoDB", Name: "app1", APIGroup: &apps}, + }, + Status: backupsv1alpha1.BackupStatus{UnderlyingResources: raw}, + } + restoreJob := newMongoDBRestoreJob("rj-pitr", "tenant") + restoreJob.Status.StartedAt = &metav1.Time{Time: time.Now()} + restoreJob.Status.Phase = backupsv1alpha1.RestoreJobPhaseRunning + restoreJob.Spec.Options = &runtime.RawExtension{Raw: []byte(`{"recoveryTime":"2026-08-05T12:34:56Z"}`)} + + c := newMongoDBStrategyTestClient(t, backup, restoreJob) + r := &RestoreJobReconciler{Client: c, Scheme: c.Scheme(), Recorder: record.NewFakeRecorder(10)} + + if _, err := r.reconcileMongoDBRestore(context.Background(), restoreJob.DeepCopy(), backup); err != nil { + t.Fatalf("reconcileMongoDBRestore: %v", err) + } + persisted := &backupsv1alpha1.RestoreJob{} + if err := c.Get(context.Background(), types.NamespacedName{Namespace: "tenant", Name: "rj-pitr"}, persisted); err != nil { + t.Fatalf("get restore job: %v", err) + } + if persisted.Status.Phase != backupsv1alpha1.RestoreJobPhaseFailed { + t.Fatalf("expected the RestoreJob to fail on a PITR request over a system-bucket backup, got phase=%q", persisted.Status.Phase) + } + cond := apimeta.FindStatusCondition(persisted.Status.Conditions, "Ready") + if cond == nil || !strings.Contains(cond.Message, "point-in-time recovery is not available") { + t.Errorf("expected a Ready condition explaining PITR is unavailable, got %+v", cond) + } +} From 69f80dbdc2b6c6750abef387800dd9c8028e9c67 Mon Sep 17 00:00:00 2001 From: Andrey Kolkov Date: Fri, 18 Sep 2026 11:11:13 +0400 Subject: [PATCH 0019/1280] fix(mongodb): drop the false-positive stall detector and harden the cancel The pinned psmdb operator persists a backup's status only when the state string or error changes, so status.lastTransition freezes at the instant a dump enters running and never advances while it streams. A stall detector keyed on that field fires on every dump that outruns its window and raises the same signal a genuine wedge would, so it cannot be acted on either way. Drop it: a running dump is polled quietly and never cancelled, since this CR carries no field a driver-side timer can use to tell a slow dump from a wedged one. The deadline cancel re-read the live state but could not tell "could not read" from "not started": the helper returned "" for a nil client, a throttle, a 403 and a real absence alike, and a live ready or error state also fell through, so an unanswerable read or a just-completed CR was deleted, taking a finished archive with it via the delete-backup finalizer. The helper now returns an error, and the cancel deletes only on a positive not-started answer, deferring on anything else. The restore's point-in-time refusal keyed on the resolved credentialsSecret name, which a BackupClass can set to any Secret; record the useSystemBucket flag on the backup snapshot and key the refusal on that instead. The storage-race retry deleted the errored CR, but the lookup kept returning it while it lingered Terminating, so a fresh CR was never minted; skip a CR carrying a deletion timestamp in the lookup. Assisted-by: LLM Signed-off-by: Andrey Kolkov --- .../psmdbstrategy_controller.go | 158 +++---- .../psmdbstrategy_controller_test.go | 396 ++++++++++++------ 2 files changed, 362 insertions(+), 192 deletions(-) diff --git a/internal/backupcontroller/psmdbstrategy_controller.go b/internal/backupcontroller/psmdbstrategy_controller.go index 102e70d0c..eda0a2444 100644 --- a/internal/backupcontroller/psmdbstrategy_controller.go +++ b/internal/backupcontroller/psmdbstrategy_controller.go @@ -96,14 +96,6 @@ const ( // Plan-controller queue. Mirrors the MariaDB/CNPG deadline. psmdbDefaultBackupDeadline = 30 * time.Minute - // psmdbBackupStallWindow is how long an operator backup may sit in - // state=running without its status.lastTransition advancing before the driver - // treats it as stalled and surfaces it (Ready=False + a Warning). A streaming - // dump keeps transitioning well inside this; the window is generous so a slow - // but progressing dump is never mistaken for a stall. A stalled dump is - // surfaced, not killed — cancelling it would strand a partial archive. - psmdbBackupStallWindow = 30 * time.Minute - // Default deadline on a RestoreJob waiting for the operator Restore to // terminate. Tenants override via spec.options.restoreTimeoutSeconds. psmdbDefaultRestoreDeadline = 30 * time.Minute @@ -404,23 +396,15 @@ func (r *BackupJobReconciler) reconcileMongoDB(ctx context.Context, j *backupsv1 // Still in progress ("", requested, running, waiting). if state == psmdbtypes.StateRunning { // A dump that is streaming is never killed — failing it would strand a - // partial archive on the shared bucket. But `running` is also where a CR - // freezes when nothing progresses (a cluster gone unhealthy mid-dump, an - // unrecognised pbm status): a progressing dump keeps bumping its - // status.lastTransition, a stalled one leaves it stale. A stalled backup - // holds the operator's backup lease and parks every later BackupJob for - // the app behind it, so past the stall window it must not pin things in - // silence — surface it (Ready=False + a Warning) without cancelling and - // stranding whatever pbm has written. - if psmdbBackupRunningStalled(mdbBackup, j.Status.StartedAt) { - if r.Recorder != nil { - r.Recorder.Eventf(j, corev1.EventTypeWarning, "BackupStalled", - "psmdb.percona.com/PerconaServerMongoDBBackup %s is stuck in state=running with no status transition for over %s; left running to avoid stranding a partial archive — investigate the operator/cluster", - mdbBackup.Name, psmdbBackupStallWindow) - } - return r.requeueMongoDBBackupWaiting(ctx, j, "PerconaServerMongoDBBackupStalled", - fmt.Sprintf("backup stuck in state=running with no status transition for over %s; left running to avoid stranding a partial archive", psmdbBackupStallWindow)) - } + // partial archive on the shared bucket, and this CR carries no signal to + // separate a slow dump from a wedged one: the pinned operator persists + // status only when the state string or error changes, so every pbm phase + // under `running` collapses to one write and status.lastTransition freezes + // at the instant the dump entered `running` (a real dataset routinely + // outruns any wall-clock window). So keep polling quietly and let the + // operator move the CR to ready/error; a genuinely wedged dump is an + // operator/cluster problem surfaced there, not something a driver-side + // timer can tell apart here. return ctrl.Result{RequeueAfter: psmdbPollInterval}, nil } // Not-yet-started states ("", requested, waiting). A wall-clock deadline @@ -430,21 +414,35 @@ func (r *BackupJobReconciler) reconcileMongoDB(ctx context.Context, j *backupsv1 return ctrl.Result{RequeueAfter: psmdbPollInterval}, nil } // The deadline hit for a not-yet-started backup. mdbBackup came from the - // cache, so re-read the CR live before cancelling: a `waiting` CR whose - // live state has just turned running at the deadline boundary must not be - // deleted mid-dump, stranding the partial the running branch avoids. If it - // started, defer to the running branch on the next reconcile. - if r.psmdbBackupLiveState(ctx, mdbBackup.Namespace, mdbBackup.Name) == psmdbtypes.StateRunning { + // cache, so re-read the CR live before cancelling: the cancel deletes a CR + // this flow finalizes with delete-backup, and the operator prunes storage on + // that finalizer once the CR is ready, so deleting anything that has already + // moved off not-started risks taking a running dump's partial or a completed + // archive with it. Require a positive not-started answer to cancel: a read + // error ("" is indistinguishable, so it returns an error) or any live state + // other than the not-started set must defer, not delete. + liveState, lerr := r.psmdbBackupLiveState(ctx, mdbBackup.Namespace, mdbBackup.Name) + if lerr != nil { + getLogger(ctx).Debug("could not re-read live backup state before cancelling; deferring rather than deleting blind", + "backupjob", j.Name, "sourceBackup", mdbBackup.Name, "error", lerr) return ctrl.Result{RequeueAfter: psmdbPollInterval}, nil } - // Cancel the operator CR before failing. On the observed (and re-read) - // not-started state nothing is written, and at v1.22.0 the operator returns - // for a CR with a deletion timestamp before it dispatches to pbm, so the - // delete prevents a late run into the shared bucket that no Backup object - // would represent. Best-effort: a delete failure must not stop the job from - // failing (a leftover CR is the pre-existing behaviour, not a regression). - // The terminal Phase=Failed makes reconcileMongoDB return early next time, - // so ensureMongoDBBackup never re-creates it. + switch liveState { + case "", psmdbtypes.StateRequested, psmdbtypes.StateWaiting: + // Positively not-started: nothing is written yet, safe to cancel below. + default: + // running/ready/error/rejected — the CR moved on; let the state switch + // handle it on the next reconcile instead of deleting it here. + return ctrl.Result{RequeueAfter: psmdbPollInterval}, nil + } + // Cancel the operator CR before failing. On the re-read not-started state + // nothing is written, and at v1.22.0 the operator returns for a CR with a + // deletion timestamp before it dispatches to pbm, so the delete prevents a + // late run into the shared bucket that no Backup object would represent. + // Best-effort: a delete failure must not stop the job from failing (a + // leftover CR is the pre-existing behaviour, not a regression). The terminal + // Phase=Failed makes reconcileMongoDB return early next time, so + // ensureMongoDBBackup never re-creates it. if mdbBackup.DeletionTimestamp.IsZero() { if derr := r.Delete(ctx, mdbBackup); derr != nil && !apierrors.IsNotFound(derr) { getLogger(ctx).Debug("could not cancel the timed-out operator backup before failing", @@ -689,22 +687,6 @@ func psmdbBackupTimedOut(state string, startedAt *metav1.Time) bool { return psmdbBackupDeadlineExceeded(startedAt) } -// psmdbBackupRunningStalled reports whether an operator backup left in -// state=running has stopped making progress. The operator copies pbm's -// last-transition timestamp into status.lastTransition, which advances while a -// dump streams and freezes when nothing progresses (a cluster gone unhealthy -// mid-dump, or a pbm status the operator maps to running but never updates). A -// stale lastTransition past the stall window is the signal; when it is unset the -// operator has not written progress at all, so the BackupJob's own deadline -// stands in. A stalled running backup is surfaced, never cancelled — cancelling -// would strand whatever pbm has already written. -func psmdbBackupRunningStalled(b *psmdbtypes.PerconaServerMongoDBBackup, startedAt *metav1.Time) bool { - if lt := b.Status.LastTransition; lt != nil { - return time.Since(lt.Time) > psmdbBackupStallWindow - } - return psmdbBackupDeadlineExceeded(startedAt) -} - // psmdbErrorIsUnresolvedStorage reports whether a PerconaServerMongoDBBackup // error is the operator failing to resolve the named storage — the message the // v1.22.0 backup reconciler sets ("unable to get storage ''") when it @@ -716,20 +698,22 @@ func psmdbErrorIsUnresolvedStorage(errMsg, storageName string) bool { } // psmdbBackupLiveState reads the operator backup CR straight from the apiserver -// (bypassing the informer cache) and returns its status.state, or "" when the CR -// cannot be read. The timeout-cancel path uses it to avoid deleting a CR whose -// cached state still reads not-started at the deadline boundary while its live -// state has just turned running. -func (r *BackupJobReconciler) psmdbBackupLiveState(ctx context.Context, namespace, name string) string { +// (bypassing the informer cache) and returns its status.state. It returns an +// error whenever the live state could not be established — the dynamic client is +// unset, the read failed (throttle, 403, removed CRD), or the object is gone — +// so the caller can tell "could not read" apart from a genuine empty state and +// never treat an unanswerable read as a not-started answer. A successful read of +// a CR that carries no status.state yet returns ("", nil). +func (r *BackupJobReconciler) psmdbBackupLiveState(ctx context.Context, namespace, name string) (string, error) { if r.Interface == nil { - return "" + return "", fmt.Errorf("dynamic client not configured") } u, err := r.Interface.Resource(psmdbBackupGVR).Namespace(namespace).Get(ctx, name, metav1.GetOptions{}) if err != nil { - return "" + return "", err } state, _, _ := unstructured.NestedString(u.Object, "status", "state") - return state + return state, nil } // ensureMongoDBBackup creates a one-shot PerconaServerMongoDBBackup CR labelled @@ -801,18 +785,30 @@ func (r *BackupJobReconciler) findMongoDBBackupForJob(ctx context.Context, j *ba ); err != nil { return nil, err } - if len(list.Items) == 0 { + // Skip CRs already being deleted. The storage-race retry deletes an errored + // CR so a fresh one resolves against a caught-up cache, but the release-lock + // finalizer keeps it briefly Terminating; treating that lingering CR as the + // current one would re-observe the same error and requeue without ever + // re-minting. The mint uses GenerateName, so a new CR never collides with the + // Terminating one. + live := make([]*psmdbtypes.PerconaServerMongoDBBackup, 0, len(list.Items)) + for i := range list.Items { + if list.Items[i].DeletionTimestamp.IsZero() { + live = append(live, &list.Items[i]) + } + } + if len(live) == 0 { return nil, nil } - if len(list.Items) > 1 { - names := make([]string, 0, len(list.Items)) - for i := range list.Items { - names = append(names, list.Items[i].Name) + if len(live) > 1 { + names := make([]string, 0, len(live)) + for _, b := range live { + names = append(names, b.Name) } getLogger(ctx).Debug("multiple PerconaServerMongoDBBackup CRs match BackupJob OwningJob labels; reusing first", "backupjob", j.Name, "namespace", j.Namespace, "matches", names, "picked", names[0]) } - return &list.Items[0], nil + return live[0], nil } // createMongoDBBackupArtifact materialises a Cozystack Backup resource carrying @@ -1154,10 +1150,16 @@ func (r *RestoreJobReconciler) reconcileMongoDBRestore(ctx context.Context, rest // never captures — the chart leaves spec.backup.pitr unset there (see // backup-classes.md). Refuse a recoveryTime restore of a system-bucket backup // with a named error rather than hand the operator a PITR target it cannot - // serve; the source's projected cozy-backups-creds identifies the flow. - if pitr != nil && source.S3 != nil && source.S3.CredentialsSecret == psmdbDefaultCredentialsSecret { - return r.markRestoreJobFailed(ctx, restoreJob, - "restoreJob.spec.options.recoveryTime is set, but point-in-time recovery is not available for a backup taken on the useSystemBucket flow (no oplog is captured there); omit recoveryTime to restore the backup as taken. See docs/operations/backup-classes.md.") + // serve. Identify the flow from the flag recorded on the snapshot at backup + // time, not from the resolved credentialsSecret: a BackupClass may name any + // Secret, so the Secret name is only a proxy, while the snapshot flag is what + // the backup actually ran on. + if pitr != nil { + snap, _ := unmarshalMongoDBBackupSnapshot(backup.Status.UnderlyingResources) + if snap != nil && snap.UseSystemBucket { + return r.markRestoreJobFailed(ctx, restoreJob, + "restoreJob.spec.options.recoveryTime is set, but point-in-time recovery is not available for a backup taken on the useSystemBucket flow (no oplog is captured there); omit recoveryTime to restore the backup as taken. See docs/operations/backup-classes.md.") + } } // The operator Restore replays into a live cluster, so the target @@ -1444,6 +1446,11 @@ type mongodbBackupSnapshot struct { StorageName string `json:"storageName,omitempty"` S3 *psmdbtypes.BackupStorageS3 `json:"s3,omitempty"` Parameters map[string]string `json:"parameters,omitempty"` + // UseSystemBucket records the flow the backup was taken on, so the restore + // path can identify a system-bucket backup directly rather than inferring it + // from the resolved credentialsSecret name (which a BackupClass may set to + // anything). Point-in-time recovery is refused on this flow. + UseSystemBucket bool `json:"useSystemBucket,omitempty"` } func marshalMongoDBBackupSnapshot(mdbBackup *psmdbtypes.PerconaServerMongoDBBackup, rendered *strategyv1alpha1.MongoDBTemplate, storageName string, parameters map[string]string, useSystemBucket bool) (*runtime.RawExtension, error) { @@ -1452,9 +1459,10 @@ func marshalMongoDBBackupSnapshot(mdbBackup *psmdbtypes.PerconaServerMongoDBBack APIVersion: psmdbBackupSnapshotAPIVersion, Destination: mdbBackup.Status.Destination, Type: psmdbBackupTypeOrDefault(rendered.Type), - StorageName: storageName, - S3: mdbBackup.Status.S3.DeepCopy(), - Parameters: parameters, + StorageName: storageName, + S3: mdbBackup.Status.S3.DeepCopy(), + Parameters: parameters, + UseSystemBucket: useSystemBucket, } // On the useSystemBucket flow the driver injected the storage, so fall back // to those coordinates when the operator's status echo is empty - the diff --git a/internal/backupcontroller/psmdbstrategy_controller_test.go b/internal/backupcontroller/psmdbstrategy_controller_test.go index 5cf1c2b0d..89e6a2fcb 100644 --- a/internal/backupcontroller/psmdbstrategy_controller_test.go +++ b/internal/backupcontroller/psmdbstrategy_controller_test.go @@ -13,9 +13,11 @@ import ( apierrors "k8s.io/apimachinery/pkg/api/errors" apimeta "k8s.io/apimachinery/pkg/api/meta" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/types" + dynamicfake "k8s.io/client-go/dynamic/fake" "k8s.io/client-go/kubernetes/scheme" "k8s.io/client-go/tools/record" "sigs.k8s.io/controller-runtime/pkg/client" @@ -1290,59 +1292,15 @@ func TestReconcileMongoDB_FirstInjectionRequeuesBeforeMinting(t *testing.T) { if len(list.Items) != 0 { t.Errorf("no operator Backup should be created in the same pass as a fresh injection, got %d", len(list.Items)) } -} - -// When a backup the operator never started (state=waiting, queued behind -// another) trips the deadline, the driver must cancel the operator CR before -// failing the BackupJob — otherwise the operator starts it later and writes an -// archive into the shared bucket that no Backup object represents. -func TestReconcileMongoDB_TimedOutBackupIsCancelled(t *testing.T) { - job, strategy, app, cluster, resolved := mongodbInjectFixture(true) - // The BackupJob started well past the deadline. - old := &metav1.Time{Time: time.Now().Add(-2 * psmdbDefaultBackupDeadline)} - job.Status.StartedAt = old - // An operator backup already exists for this job, queued (state=waiting), with - // the delete-backup finalizer the useSystemBucket flow stamps. - opBackup := &psmdbtypes.PerconaServerMongoDBBackup{ - ObjectMeta: metav1.ObjectMeta{ - Namespace: "tenant", - Name: "op-waiting", - Finalizers: []string{psmdbDeleteBackupFinalizer}, - Labels: map[string]string{ - backupsv1alpha1.OwningJobNameLabel: job.Name, - backupsv1alpha1.OwningJobNamespaceLabel: job.Namespace, - }, - }, - Status: psmdbtypes.PerconaServerMongoDBBackupStatus{State: psmdbtypes.StateWaiting}, - } - // The storage is already declared (injected on the pass that minted the - // backup 30m ago), so this reconcile re-applies it without the first-injection - // requeue and reaches the timeout branch. - cluster.Spec.Backup.Storages = map[string]runtime.RawExtension{ - "s3-storage": {Raw: []byte(`{"type":"s3","s3":{"bucket":"cozy-backups"}}`)}, - } - - c := newMongoDBStrategyTestClient(t, job, strategy, app, cluster, opBackup) - r := &BackupJobReconciler{Client: c, Scheme: c.Scheme()} - - if _, err := r.reconcileMongoDB(context.Background(), job.DeepCopy(), resolved); err != nil { - t.Fatalf("reconcileMongoDB: %v", err) - } - - // The operator CR must be cancelled (deleted): with the finalizer it stays - // Terminating, so assert a DeletionTimestamp; without the fix it is untouched. - got := &psmdbtypes.PerconaServerMongoDBBackup{} - err := c.Get(context.Background(), types.NamespacedName{Namespace: "tenant", Name: "op-waiting"}, got) - if err == nil && got.DeletionTimestamp.IsZero() { - t.Errorf("timed-out operator backup must be cancelled (deleted) so it cannot run later; it was left untouched") - } - // And the BackupJob is failed. + // The wait is named on the BackupJob, not silent: a Ready=False condition with + // the injection reason so the pause is visible in kubectl describe. persisted := &backupsv1alpha1.BackupJob{} if err := c.Get(context.Background(), types.NamespacedName{Namespace: "tenant", Name: job.Name}, persisted); err != nil { t.Fatalf("get job: %v", err) } - if persisted.Status.Phase != backupsv1alpha1.BackupJobPhaseFailed { - t.Errorf("expected the BackupJob to be Failed, got phase=%q", persisted.Status.Phase) + cond := apimeta.FindStatusCondition(persisted.Status.Conditions, "Ready") + if cond == nil || cond.Status != metav1.ConditionFalse || cond.Reason != "PerconaServerMongoDBStorageInjected" { + t.Errorf("expected Ready=False with reason PerconaServerMongoDBStorageInjected, got %+v", cond) } } @@ -1650,11 +1608,22 @@ func TestCleanupMongoDBBackup(t *testing.T) { // The verb is revoked (Forbidden): the escape hatch runs before the Get, so // it must still release rather than propagate the read error and wedge. c := failingGetClient(apierrors.NewForbidden(schema.GroupResource{Group: "psmdb.percona.com", Resource: "perconaservermongodbbackups"}, "op-bk", errors.New("rbac revoked"))) - r := &BackupReconciler{Client: c, Recorder: record.NewFakeRecorder(10)} + rec := record.NewFakeRecorder(10) + r := &BackupReconciler{Client: c, Recorder: rec} res, err := r.cleanupMongoDBBackup(context.Background(), newBackup(map[string]string{psmdbSkipArtifactCleanupAnnotation: "true"})) if err != nil || res.RequeueAfter != 0 { t.Fatalf("annotation must release despite an unreadable operator CR, got res=%+v err=%v", res, err) } + // A CR that could not be read may still carry the finalizer, so the release + // surfaces which object may be left stuck rather than a Debug line nobody sees. + select { + case ev := <-rec.Events: + if !strings.Contains(ev, "FinalizerNotStripped") || !strings.Contains(ev, "op-bk") { + t.Errorf("expected a FinalizerNotStripped event naming the unreadable CR, got %q", ev) + } + default: + t.Errorf("expected a FinalizerNotStripped Warning for the unreadable CR, got none") + } }) t.Run("a missing CRD (NoMatchError) releases instead of wedging", func(t *testing.T) { @@ -1856,35 +1825,58 @@ func TestReleaseMongoDBCleanup_UsesPassedObjectNotReRead(t *testing.T) { } } -// state=running is the driver's one never-cancel state, so the only signal that -// a run is wedged rather than streaming is its status.lastTransition going -// stale. Pin both readings: a transition older than the stall window is stalled, -// a fresh one is progressing. The nil-lastTransition fallback leans on the -// wall-clock deadline (an operator that never wrote a transition at all). -func TestPsmdbBackupRunningStalled(t *testing.T) { - pastDeadline := &metav1.Time{Time: time.Now().Add(-2 * psmdbDefaultBackupDeadline)} - recentStart := &metav1.Time{Time: time.Now()} - staleLT := &metav1.Time{Time: time.Now().Add(-2 * psmdbBackupStallWindow)} - freshLT := &metav1.Time{Time: time.Now()} - - cases := []struct { - name string - lt *metav1.Time - started *metav1.Time - want bool - }{ - {"stale transition is stalled", staleLT, recentStart, true}, - {"fresh transition is progressing", freshLT, pastDeadline, false}, - {"no transition, past deadline is stalled", nil, pastDeadline, true}, - {"no transition, recent start is progressing", nil, recentStart, false}, +// A streaming dump is never cancelled: the pinned operator persists status only +// on a state/error change, so status.lastTransition freezes at the instant the +// dump entered running and a real dataset routinely outruns any wall-clock +// window. The driver must keep polling a running CR quietly even long past the +// deadline — never fail the BackupJob, never delete the CR (which would strand +// the partial archive on the shared bucket). +func TestReconcileMongoDB_RunningNeverCancelled(t *testing.T) { + job, strategy, app, cluster, resolved := mongodbInjectFixture(true) + // Running far longer than the deadline. + job.Status.StartedAt = &metav1.Time{Time: time.Now().Add(-4 * psmdbDefaultBackupDeadline)} + cluster.Spec.Backup.Storages = map[string]runtime.RawExtension{ + "s3-storage": {Raw: []byte(`{"type":"s3","s3":{"bucket":"cozy-backups"}}`)}, } - for _, tc := range cases { - b := &psmdbtypes.PerconaServerMongoDBBackup{ - Status: psmdbtypes.PerconaServerMongoDBBackupStatus{State: psmdbtypes.StateRunning, LastTransition: tc.lt}, - } - if got := psmdbBackupRunningStalled(b, tc.started); got != tc.want { - t.Errorf("%s: got %v want %v", tc.name, got, tc.want) - } + running := &psmdbtypes.PerconaServerMongoDBBackup{ + ObjectMeta: metav1.ObjectMeta{ + Namespace: "tenant", + Name: "op-running", + Finalizers: []string{psmdbDeleteBackupFinalizer}, + Labels: map[string]string{ + backupsv1alpha1.OwningJobNameLabel: job.Name, + backupsv1alpha1.OwningJobNamespaceLabel: job.Namespace, + }, + }, + // lastTransition frozen at the start, as the pinned operator leaves it. + Status: psmdbtypes.PerconaServerMongoDBBackupStatus{ + State: psmdbtypes.StateRunning, + LastTransition: &metav1.Time{Time: time.Now().Add(-4 * psmdbDefaultBackupDeadline)}, + }, + } + c := newMongoDBStrategyTestClient(t, job, strategy, app, cluster, running) + r := &BackupJobReconciler{Client: c, Scheme: c.Scheme(), Recorder: record.NewFakeRecorder(10)} + + res, err := r.reconcileMongoDB(context.Background(), job.DeepCopy(), resolved) + if err != nil { + t.Fatalf("reconcileMongoDB: %v", err) + } + if res.RequeueAfter == 0 { + t.Fatalf("expected a poll requeue for a running backup, got %+v", res) + } + got := &psmdbtypes.PerconaServerMongoDBBackup{} + if err := c.Get(context.Background(), types.NamespacedName{Namespace: "tenant", Name: "op-running"}, got); err != nil { + t.Fatalf("get running backup: %v", err) + } + if !got.DeletionTimestamp.IsZero() { + t.Errorf("a running backup must never be cancelled, even past the deadline; it was deleted") + } + persisted := &backupsv1alpha1.BackupJob{} + if err := c.Get(context.Background(), types.NamespacedName{Namespace: "tenant", Name: job.Name}, persisted); err != nil { + t.Fatalf("get job: %v", err) + } + if persisted.Status.Phase == backupsv1alpha1.BackupJobPhaseFailed { + t.Errorf("a running backup must not fail the BackupJob on the deadline, got phase=Failed") } } @@ -2000,79 +1992,199 @@ func TestReconcileMongoDB_StorageRaceErrorRetried(t *testing.T) { } } -// A backup wedged in state=running holds the operator's lease and parks every -// later BackupJob behind it, so past the stall window the driver must surface it -// (Ready=False + a Warning) — but never cancel it, which would strand whatever -// pbm has already written to the shared bucket. A run still transitioning stays -// silent. -func TestReconcileMongoDB_RunningStalledSurfaced(t *testing.T) { - newRunning := func(lt *metav1.Time) (*BackupJobReconciler, client.Client, *record.FakeRecorder, *ResolvedBackupConfig, *backupsv1alpha1.BackupJob) { +// The retry deletes the errored CR, but its release-lock finalizer keeps it +// briefly Terminating. The lookup must skip a Terminating CR so a fresh one is +// minted (against a caught-up cache) rather than re-observing the same error on +// the lingering object and requeuing forever. +func TestReconcileMongoDB_StorageRaceReMintsPastLingeringCR(t *testing.T) { + job, strategy, app, cluster, resolved := mongodbInjectFixture(true) + job.Status.StartedAt = &metav1.Time{Time: time.Now()} // within deadline + cluster.Spec.Backup.Storages = map[string]runtime.RawExtension{ + "s3-storage": {Raw: []byte(`{"type":"s3","s3":{"bucket":"cozy-backups"}}`)}, + } + // An errored CR from a previous retry, still carrying the finalizer. + lingering := &psmdbtypes.PerconaServerMongoDBBackup{ + ObjectMeta: metav1.ObjectMeta{ + Namespace: "tenant", + Name: "op-lingering", + Finalizers: []string{psmdbDeleteBackupFinalizer}, + Labels: map[string]string{ + backupsv1alpha1.OwningJobNameLabel: job.Name, + backupsv1alpha1.OwningJobNamespaceLabel: job.Namespace, + }, + }, + Status: psmdbtypes.PerconaServerMongoDBBackupStatus{State: psmdbtypes.StateError, Error: `unable to get storage "s3-storage": not found`}, + } + c := newMongoDBStrategyTestClient(t, job, strategy, app, cluster, lingering) + // Delete it so the finalizer holds it Terminating (DeletionTimestamp set). + if err := c.Delete(context.Background(), lingering); err != nil { + t.Fatalf("delete to make it Terminating: %v", err) + } + r := &BackupJobReconciler{Client: c, Scheme: c.Scheme(), Recorder: record.NewFakeRecorder(10)} + + if _, err := r.reconcileMongoDB(context.Background(), job.DeepCopy(), resolved); err != nil { + t.Fatalf("reconcileMongoDB: %v", err) + } + + // A fresh, non-Terminating CR must exist — the retry re-minted past the + // lingering one instead of re-observing it. + list := &psmdbtypes.PerconaServerMongoDBBackupList{} + if err := c.List(context.Background(), list, client.InNamespace("tenant")); err != nil { + t.Fatalf("list: %v", err) + } + fresh := 0 + for i := range list.Items { + if list.Items[i].DeletionTimestamp.IsZero() { + fresh++ + } + } + if fresh == 0 { + t.Errorf("expected a fresh operator Backup minted past the Terminating CR, got none (lookup did not skip the lingering CR)") + } +} + +// psmdbBackupUnstructured builds a live PerconaServerMongoDBBackup for the fake +// dynamic client, carrying status.state (omitted when empty). +func psmdbBackupUnstructured(namespace, name, state string) *unstructured.Unstructured { + u := &unstructured.Unstructured{} + u.SetGroupVersionKind(schema.GroupVersionKind{ + Group: psmdbBackupGVR.Group, + Version: psmdbBackupGVR.Version, + Kind: "PerconaServerMongoDBBackup", + }) + u.SetNamespace(namespace) + u.SetName(name) + if state != "" { + _ = unstructured.SetNestedField(u.Object, state, "status", "state") + } + return u +} + +// newPsmdbBackupDynamicClient is the dynamic (uncached) client the cancel path +// re-reads live state through. Modelled on altinitystrategy_controller_test.go. +func newPsmdbBackupDynamicClient(objs ...*unstructured.Unstructured) *dynamicfake.FakeDynamicClient { + rtObjs := make([]runtime.Object, 0, len(objs)) + for _, o := range objs { + rtObjs = append(rtObjs, o) + } + return dynamicfake.NewSimpleDynamicClientWithCustomListKinds( + runtime.NewScheme(), + map[schema.GroupVersionResource]string{psmdbBackupGVR: "PerconaServerMongoDBBackupList"}, + rtObjs..., + ) +} + +// The deadline cancel re-reads the CR live and must delete it only on a positive +// not-started answer: a live state that has moved to running or ready, or a read +// that cannot be answered at all, must defer instead of deleting a CR whose +// delete-backup finalizer would take a running partial or a completed archive +// with it. The cached mdbBackup reads not-started (waiting) past the deadline in +// every case; only the live answer differs. +func TestReconcileMongoDB_TimedOutCancelUsesLiveState(t *testing.T) { + setup := func(t *testing.T, live *dynamicfake.FakeDynamicClient) (*BackupJobReconciler, client.Client, *ResolvedBackupConfig, *backupsv1alpha1.BackupJob) { job, strategy, app, cluster, resolved := mongodbInjectFixture(true) job.Status.StartedAt = &metav1.Time{Time: time.Now().Add(-2 * psmdbDefaultBackupDeadline)} cluster.Spec.Backup.Storages = map[string]runtime.RawExtension{ "s3-storage": {Raw: []byte(`{"type":"s3","s3":{"bucket":"cozy-backups"}}`)}, } - running := &psmdbtypes.PerconaServerMongoDBBackup{ + // Cached CR reads a not-started state (waiting) past the deadline. + cached := &psmdbtypes.PerconaServerMongoDBBackup{ ObjectMeta: metav1.ObjectMeta{ Namespace: "tenant", - Name: "op-running", + Name: "op-waiting", Finalizers: []string{psmdbDeleteBackupFinalizer}, Labels: map[string]string{ backupsv1alpha1.OwningJobNameLabel: job.Name, backupsv1alpha1.OwningJobNamespaceLabel: job.Namespace, }, }, - Status: psmdbtypes.PerconaServerMongoDBBackupStatus{State: psmdbtypes.StateRunning, LastTransition: lt}, + Status: psmdbtypes.PerconaServerMongoDBBackupStatus{State: psmdbtypes.StateWaiting}, } - c := newMongoDBStrategyTestClient(t, job, strategy, app, cluster, running) - rec := record.NewFakeRecorder(10) - return &BackupJobReconciler{Client: c, Scheme: c.Scheme(), Recorder: rec}, c, rec, resolved, job + c := newMongoDBStrategyTestClient(t, job, strategy, app, cluster, cached) + return &BackupJobReconciler{Client: c, Interface: live, Scheme: c.Scheme(), Recorder: record.NewFakeRecorder(10)}, c, resolved, job + } + deleted := func(t *testing.T, c client.Client) bool { + got := &psmdbtypes.PerconaServerMongoDBBackup{} + err := c.Get(context.Background(), types.NamespacedName{Namespace: "tenant", Name: "op-waiting"}, got) + return err == nil && !got.DeletionTimestamp.IsZero() + } + failed := func(t *testing.T, c client.Client, name string) bool { + p := &backupsv1alpha1.BackupJob{} + if err := c.Get(context.Background(), types.NamespacedName{Namespace: "tenant", Name: name}, p); err != nil { + t.Fatalf("get job: %v", err) + } + return p.Status.Phase == backupsv1alpha1.BackupJobPhaseFailed } - t.Run("stalled run is surfaced but not cancelled", func(t *testing.T) { - r, c, rec, resolved, job := newRunning(&metav1.Time{Time: time.Now().Add(-2 * psmdbBackupStallWindow)}) + t.Run("live still not-started → cancel and fail", func(t *testing.T) { + live := newPsmdbBackupDynamicClient(psmdbBackupUnstructured("tenant", "op-waiting", psmdbtypes.StateWaiting)) + r, c, resolved, job := setup(t, live) + if _, err := r.reconcileMongoDB(context.Background(), job.DeepCopy(), resolved); err != nil { + t.Fatalf("reconcileMongoDB: %v", err) + } + if !deleted(t, c) { + t.Errorf("a positively not-started backup past the deadline must be cancelled") + } + if !failed(t, c, job.Name) { + t.Errorf("the BackupJob must be Failed after cancelling a timed-out not-started backup") + } + }) + + t.Run("live turned running → defer, never cancel", func(t *testing.T) { + live := newPsmdbBackupDynamicClient(psmdbBackupUnstructured("tenant", "op-waiting", psmdbtypes.StateRunning)) + r, c, resolved, job := setup(t, live) res, err := r.reconcileMongoDB(context.Background(), job.DeepCopy(), resolved) if err != nil { t.Fatalf("reconcileMongoDB: %v", err) } if res.RequeueAfter == 0 { - t.Fatalf("expected a requeue for a stalled run, got %+v", res) + t.Fatalf("a live running state must requeue, got %+v", res) } - select { - case ev := <-rec.Events: - if !strings.Contains(ev, "BackupStalled") { - t.Errorf("expected a BackupStalled event, got %q", ev) - } - default: - t.Errorf("expected a BackupStalled Warning, got none") + if deleted(t, c) { + t.Errorf("a CR whose live state turned running must not be cancelled (partial archive)") } - got := &psmdbtypes.PerconaServerMongoDBBackup{} - if err := c.Get(context.Background(), types.NamespacedName{Namespace: "tenant", Name: "op-running"}, got); err != nil { - t.Fatalf("get running backup: %v", err) - } - if !got.DeletionTimestamp.IsZero() { - t.Errorf("a stalled running backup must never be cancelled (partial archive), it was deleted") + if failed(t, c, job.Name) { + t.Errorf("the BackupJob must not fail while the live backup is running") } }) - t.Run("progressing run stays silent", func(t *testing.T) { - r, _, rec, resolved, job := newRunning(&metav1.Time{Time: time.Now()}) + t.Run("live completed ready → defer, archive protected", func(t *testing.T) { + live := newPsmdbBackupDynamicClient(psmdbBackupUnstructured("tenant", "op-waiting", psmdbtypes.StateReady)) + r, c, resolved, job := setup(t, live) if _, err := r.reconcileMongoDB(context.Background(), job.DeepCopy(), resolved); err != nil { t.Fatalf("reconcileMongoDB: %v", err) } - select { - case ev := <-rec.Events: - t.Errorf("a progressing run must not emit a stall event, got %q", ev) - default: + if deleted(t, c) { + t.Errorf("a just-completed (ready) CR must not be deleted — its delete-backup finalizer would prune the archive") + } + }) + + t.Run("live read cannot be answered → defer, never cancel", func(t *testing.T) { + // Empty dynamic store: the live Get returns NotFound (an error), which must + // not be read as a not-started answer. + live := newPsmdbBackupDynamicClient() + r, c, resolved, job := setup(t, live) + res, err := r.reconcileMongoDB(context.Background(), job.DeepCopy(), resolved) + if err != nil { + t.Fatalf("reconcileMongoDB: %v", err) + } + if res.RequeueAfter == 0 { + t.Fatalf("an unanswerable live read must requeue, got %+v", res) + } + if deleted(t, c) { + t.Errorf("an unanswerable live read must defer, not delete blind") + } + if failed(t, c, job.Name) { + t.Errorf("an unanswerable live read must not fail the BackupJob") } }) } // PITR needs an oplog stream the useSystemBucket flow never captures, so a -// recoveryTime restore of a system-bucket backup (its source carries the -// projected cozy-backups-creds) must fail with a named error rather than hand -// the operator a target it cannot serve. The refusal fires before the target -// cluster read, so no target need exist. +// recoveryTime restore of a backup taken on that flow (recorded by the snapshot +// flag, not inferred from a Secret name) must fail with a named error rather +// than hand the operator a target it cannot serve. The refusal fires before the +// target cluster read, so no target need exist. func TestReconcileMongoDBRestore_RefusesPITROnSystemBucketBackup(t *testing.T) { apps := mongodbapp.GroupName snap := &psmdbtypes.PerconaServerMongoDBBackup{ @@ -2115,3 +2227,53 @@ func TestReconcileMongoDBRestore_RefusesPITROnSystemBucketBackup(t *testing.T) { t.Errorf("expected a Ready condition explaining PITR is unavailable, got %+v", cond) } } + +// The refusal keys on the snapshot flow flag, not on the credentialsSecret name: +// a legacy (non-system-bucket) backup that happens to resolve to cozy-backups-creds +// must NOT have its recoveryTime restore refused. Keeps the check honest — the +// Secret name is a proxy a BackupClass can defeat either way. +func TestReconcileMongoDBRestore_PITRAllowedForNonSystemBucketBackup(t *testing.T) { + apps := mongodbapp.GroupName + snap := &psmdbtypes.PerconaServerMongoDBBackup{ + Status: psmdbtypes.PerconaServerMongoDBBackupStatus{ + Destination: "s3://tenant-own/tenant/app1/2026", + S3: &psmdbtypes.BackupStorageS3{Bucket: "tenant-own", CredentialsSecret: psmdbDefaultCredentialsSecret}, + }, + } + // useSystemBucket=false recorded on the snapshot despite the cozy-backups-creds name. + raw, err := marshalMongoDBBackupSnapshot(snap, &strategyv1alpha1.MongoDBTemplate{Type: "logical"}, "s3-storage", nil, false) + if err != nil { + t.Fatalf("marshal snapshot: %v", err) + } + backup := &backupsv1alpha1.Backup{ + ObjectMeta: metav1.ObjectMeta{Namespace: "tenant", Name: "src-backup"}, + Spec: backupsv1alpha1.BackupSpec{ + ApplicationRef: corev1.TypedLocalObjectReference{Kind: "MongoDB", Name: "app1", APIGroup: &apps}, + }, + Status: backupsv1alpha1.BackupStatus{UnderlyingResources: raw}, + } + restoreJob := newMongoDBRestoreJob("rj-pitr-legacy", "tenant") + restoreJob.Status.StartedAt = &metav1.Time{Time: time.Now()} + restoreJob.Status.Phase = backupsv1alpha1.RestoreJobPhaseRunning + restoreJob.Spec.Options = &runtime.RawExtension{Raw: []byte(`{"recoveryTime":"2026-08-05T12:34:56Z"}`)} + + c := newMongoDBStrategyTestClient(t, backup, restoreJob) + r := &RestoreJobReconciler{Client: c, Scheme: c.Scheme(), Recorder: record.NewFakeRecorder(10)} + + // No target cluster exists, so the reconcile requeues on the target read — it + // must get past the PITR refusal to reach it. A PITR-refusal failure here would + // mean the check still keyed on the Secret name. + if _, err := r.reconcileMongoDBRestore(context.Background(), restoreJob.DeepCopy(), backup); err != nil { + t.Fatalf("reconcileMongoDBRestore: %v", err) + } + persisted := &backupsv1alpha1.RestoreJob{} + if err := c.Get(context.Background(), types.NamespacedName{Namespace: "tenant", Name: "rj-pitr-legacy"}, persisted); err != nil { + t.Fatalf("get restore job: %v", err) + } + if persisted.Status.Phase == backupsv1alpha1.RestoreJobPhaseFailed { + cond := apimeta.FindStatusCondition(persisted.Status.Conditions, "Ready") + if cond != nil && strings.Contains(cond.Message, "point-in-time recovery is not available") { + t.Errorf("PITR must not be refused for a non-system-bucket backup (keyed on Secret name, not the flow): %+v", cond) + } + } +} From 42a29e3597ea65e4ff9980cb8eee689e6c5ee6b6 Mon Sep 17 00:00:00 2001 From: Andrey Kolkov Date: Fri, 18 Sep 2026 18:07:56 +0400 Subject: [PATCH 0020/1280] fix(mongodb): keep the legacy deadline on a running dump and name the wait Exempting state=running from the wall-clock deadline was justified by the shared bucket: on the useSystemBucket flow a failed BackupJob leaves pbm streaming an archive no Backup object represents. The exemption was applied to both flows, though, so a legacy dump whose operator or node died mid-run went from failing on the deadline to polling forever with no condition and no Event. Gate the exemption on the flow: a legacy archive lands in the tenant's own bucket under psmdb task retention and the pre-existing contract failed the job while leaving the operator CR alone, so that is restored. On the system-bucket flow the wait is now named on the BackupJob (Ready=False with the start time) instead of being silent; the waiting helper writes status only when the condition changes so a dump that runs for hours does not cost a status write per poll. The point-in-time refusal read the snapshot flag with the decode error discarded, so an undecodable snapshot fell open and a recoveryTime restore of a system-bucket archive reached the operator to die on a pbm-level message. Treat a decode failure as "flow unknown" and refuse. Adopting a target credential only for a storage on the same bucket left the source's own reference in place when nothing matched, and opting an app into the system bucket prunes exactly that Secret while older Backups still name it. Check the reference resolves before the operator sees it and fail with a named reason instead of a missing-Secret error deep in the restore. Opting back out stops the injection but leaves the driver's storage on the live cluster until the chart re-renders; a BackupJob in that window passed the presence-only precondition, minted a CR without the delete-backup finalizer and wrote an object nothing owns into the platform bucket. Refuse to mint onto a storage whose bucket is the platform's while the flag reads false, bounded by the deadline like the other waits. Also realign the snapshot literal for gofmt, and fix two doc slips: the pbm agents start on backup.enabled alone (a declared storage is needed only to service a backup), and the opt-in cross-reference targeted the parent heading instead of its subsection. Assisted-by: LLM Signed-off-by: Andrey Kolkov --- docs/operations/backup-classes.md | 4 +- .../psmdbstrategy_controller.go | 133 +++++-- .../psmdbstrategy_controller_test.go | 372 +++++++++++++++--- 3 files changed, 408 insertions(+), 101 deletions(-) diff --git a/docs/operations/backup-classes.md b/docs/operations/backup-classes.md index 6d11482dc..3eeabe4f3 100644 --- a/docs/operations/backup-classes.md +++ b/docs/operations/backup-classes.md @@ -79,7 +79,7 @@ MongoDB supports two storage flows. By default the S3 target lives on the app CR ### Default: the application owns the backup storage -The Percona psmdb operator only runs the percona-backup-mongodb (pbm) agents and services `PerconaServerMongoDBBackup` CRs when the `PerconaServerMongoDB` cluster has `spec.backup.enabled: true` and a storage declared, and a `PerconaServerMongoDBBackup` references that storage only by name. On the default flow the MongoDB application **opts into backups** and points at the bucket in its own chart values: +The Percona psmdb operator runs the percona-backup-mongodb (pbm) agents whenever the `PerconaServerMongoDB` cluster has `spec.backup.enabled: true` (a declared storage is not needed for the agents to start), and services a `PerconaServerMongoDBBackup` only once the storage it references by name is declared on the cluster. On the default flow the MongoDB application **opts into backups** and points at the bucket in its own chart values: ```yaml apiVersion: apps.cozystack.io/v1alpha1 @@ -121,7 +121,7 @@ When `useSystemBucket: true`: Because the chart drops `spec.backup.tasks` and `spec.backup.pitr`, the psmdb operator's own scheduled backups and oplog PITR do **not** run on this flow — `backup.schedule` and `backup.retentionPolicy` stay in the schema for the default flow but have no effect here, and the `recoveryTime` PITR restores described below are not available. Migrate scheduled backups to a `backups.cozystack.io/Plan` against `cozy-default` instead. **Flipping this flag on a running app** removes the storage, tasks and pitr the app had, so a release that was taking scheduled backups + PITR before the flip stops until a `Plan` takes over. -Dropping `spec.backup.tasks` also drops the psmdb `keep` retention it carried, so on this flow **the driver owns the archive** the way the Rabbitmq/Redis drivers own theirs (an on-demand `PerconaServerMongoDBBackup` is not covered by psmdb task retention). The driver stamps the operator's `percona.com/delete-backup` finalizer onto each backup it mints here, and deleting a Cozystack `Backup` (a retention-pruned `Plan`, or a manual delete) deletes that `PerconaServerMongoDBBackup` CR — whose finalizer removes the pbm object from the shared bucket before the `Backup` is released, so a Plan does not accumulate objects in `cozy-backups`. A legacy backup writes to the tenant's own bucket and keeps the pre-existing hands-off contract (its lifecycle stays the tenant's / operator's; nothing is deleted on `Backup` removal). Note this prunes only when a `Backup` is deleted: unlike CNPG and MariaDB, which prune engine-side on their own schedule, MongoDB has no engine-side scheduled trim on this flow, so keeping `cozy-backups` bounded depends on a `Plan`'s retention actually deleting old `Backup` objects. **A `Plan` has no retention field yet** (`PlanSpec` carries only `applicationRef`, `backupClassName` and `schedule`), so today a nightly `useSystemBucket` Plan grows the shared bucket unbounded — `schedule` and `retentionPolicy` on the app are inert here (see [MongoDB: opt-in to the system bucket](#mongodb-backup-storage)), and platform-level retention is tracked in the [`BackupRetentionPolicy` design (#4192)](https://github.com/cozystack/cozystack/pull/4192). Teardown GC of orphaned `Backup`s / S3 data is [#3966](https://github.com/cozystack/cozystack/issues/3966). Until those land, bound `cozy-backups` with an S3 lifecycle policy on the object store. Two cases release the `Backup` without waiting for the object to be pruned, so a wedged prune never pins a namespace in `Terminating`: a terminating namespace (where the operator's delete-backup step cannot run) and the `backups.cozystack.io/skip-artifact-cleanup: "true"` annotation. In both the driver strips its own finalizer and leaves the object for a bucket lifecycle policy to reclaim. A down operator or unreachable storage in a live namespace is NOT released automatically — the `Backup` stays `Terminating` as a visible signal until the operator recovers or you set that annotation to force the release. +Dropping `spec.backup.tasks` also drops the psmdb `keep` retention it carried, so on this flow **the driver owns the archive** the way the Rabbitmq/Redis drivers own theirs (an on-demand `PerconaServerMongoDBBackup` is not covered by psmdb task retention). The driver stamps the operator's `percona.com/delete-backup` finalizer onto each backup it mints here, and deleting a Cozystack `Backup` (a retention-pruned `Plan`, or a manual delete) deletes that `PerconaServerMongoDBBackup` CR — whose finalizer removes the pbm object from the shared bucket before the `Backup` is released, so a Plan does not accumulate objects in `cozy-backups`. A legacy backup writes to the tenant's own bucket and keeps the pre-existing hands-off contract (its lifecycle stays the tenant's / operator's; nothing is deleted on `Backup` removal). Note this prunes only when a `Backup` is deleted: unlike CNPG and MariaDB, which prune engine-side on their own schedule, MongoDB has no engine-side scheduled trim on this flow, so keeping `cozy-backups` bounded depends on a `Plan`'s retention actually deleting old `Backup` objects. **A `Plan` has no retention field yet** (`PlanSpec` carries only `applicationRef`, `backupClassName` and `schedule`), so today a nightly `useSystemBucket` Plan grows the shared bucket unbounded — `schedule` and `retentionPolicy` on the app are inert here (see [Opt-in to the system bucket](#opt-in-to-the-system-bucket)), and platform-level retention is tracked in the [`BackupRetentionPolicy` design (#4192)](https://github.com/cozystack/cozystack/pull/4192). Teardown GC of orphaned `Backup`s / S3 data is [#3966](https://github.com/cozystack/cozystack/issues/3966). Until those land, bound `cozy-backups` with an S3 lifecycle policy on the object store. Two cases release the `Backup` without waiting for the object to be pruned, so a wedged prune never pins a namespace in `Terminating`: a terminating namespace (where the operator's delete-backup step cannot run) and the `backups.cozystack.io/skip-artifact-cleanup: "true"` annotation. In both the driver strips its own finalizer and leaves the object for a bucket lifecycle policy to reclaim. A down operator or unreachable storage in a live namespace is NOT released automatically — the `Backup` stays `Terminating` as a visible signal until the operator recovers or you set that annotation to force the release. **Opting back out** (`useSystemBucket` true→false) is not automatic in reverse: the driver stops injecting, but the `s3-storage` entry it already applied stays on the live `PerconaServerMongoDB` under the driver's own field manager (`cozystack-psmdb-backup-driver`) — the chart does not own it and so never prunes it. It is inert once `backup.enabled=false`; to fully return a release to the legacy flow, delete that storage entry from the `PerconaServerMongoDB` by hand before re-declaring the tenant's own `backup.*` S3 values. diff --git a/internal/backupcontroller/psmdbstrategy_controller.go b/internal/backupcontroller/psmdbstrategy_controller.go index eda0a2444..e93e12a8c 100644 --- a/internal/backupcontroller/psmdbstrategy_controller.go +++ b/internal/backupcontroller/psmdbstrategy_controller.go @@ -328,6 +328,25 @@ func (r *BackupJobReconciler) reconcileMongoDB(ctx context.Context, j *backupsv1 return r.requeueMongoDBBackupWaiting(ctx, j, "PerconaServerMongoDBBackupsDisabled", msg) } + // Opting out (useSystemBucket true→false) stops the injection but leaves the + // driver's storage entry on the live cluster until the chart re-renders. A + // BackupJob in that window passes the precondition (presence, not content), + // would mint a CR without the delete-backup finalizer, and the dump would land + // in the platform bucket as an object nothing owns or prunes. Refuse to mint + // onto a storage whose bucket is the platform's while the flag reads false; + // bounded by the deadline like the other waits. + if !useSystemBucket && rendered.S3 != nil { + if bucket, _ := psmdbStorageS3(cluster.Spec.Backup.Storages[storageName]); bucket != "" && bucket == rendered.S3.Bucket { + if psmdbBackupDeadlineExceeded(j.Status.StartedAt) { + return r.markBackupJobFailed(ctx, j, fmt.Sprintf( + "psmdb.percona.com/PerconaServerMongoDB %s/%s storage %q still points at the platform bucket %q with backup.useSystemBucket=false after %s; wait for the chart to re-render the application's own storage", + j.Namespace, psmdbName, storageName, bucket, psmdbDefaultBackupDeadline)) + } + return r.requeueMongoDBBackupWaiting(ctx, j, "PerconaServerMongoDBStorageStale", + fmt.Sprintf("storage %q still points at the platform bucket %q with backup.useSystemBucket=false; waiting for the chart to re-render the application's own storage", storageName, bucket)) + } + } + mdbBackup, err := r.ensureMongoDBBackup(ctx, j, psmdbName, storageName, rendered, useSystemBucket) if err != nil { return r.markBackupJobFailed(ctx, j, fmt.Sprintf("failed to ensure psmdb.percona.com/PerconaServerMongoDBBackup: %v", err)) @@ -395,22 +414,33 @@ func (r *BackupJobReconciler) reconcileMongoDB(ctx context.Context, j *backupsv1 default: // Still in progress ("", requested, running, waiting). if state == psmdbtypes.StateRunning { - // A dump that is streaming is never killed — failing it would strand a - // partial archive on the shared bucket, and this CR carries no signal to - // separate a slow dump from a wedged one: the pinned operator persists - // status only when the state string or error changes, so every pbm phase - // under `running` collapses to one write and status.lastTransition freezes - // at the instant the dump entered `running` (a real dataset routinely - // outruns any wall-clock window). So keep polling quietly and let the - // operator move the CR to ready/error; a genuinely wedged dump is an - // operator/cluster problem surfaced there, not something a driver-side - // timer can tell apart here. - return ctrl.Result{RequeueAfter: psmdbPollInterval}, nil + if !psmdbBackupTimedOut(state, j.Status.StartedAt, useSystemBucket) { + // The wait is long by nature (a real dataset routinely outruns any + // wall-clock window) and the CR carries nothing to tell a slow dump + // from a wedged one: the pinned operator persists status only when the + // state string or error changes, so status.lastTransition freezes at + // the instant the dump entered `running`. Name the wait on the + // BackupJob instead of judging it by a timer — Ready=False with the + // start time, so `kubectl describe backupjob` shows what it is waiting + // on — and let the operator move the CR to ready/error. + since := "an unknown start time" + if j.Status.StartedAt != nil { + since = j.Status.StartedAt.UTC().Format(time.RFC3339) + } + return r.requeueMongoDBBackupWaiting(ctx, j, "PerconaServerMongoDBBackupRunning", + fmt.Sprintf("psmdb.percona.com PerconaServerMongoDBBackup %s has been streaming since %s; a running dump is left to finish", mdbBackup.Name, since)) + } + // Legacy flow past the deadline: the archive lands in the tenant's own + // bucket under psmdb task retention, so failing the job strands nothing + // the platform owns. The operator CR is left alone, as it was before this + // driver existed — only a not-started CR is ever cancelled below. + return r.markBackupJobFailed(ctx, j, fmt.Sprintf( + "psmdb.percona.com PerconaServerMongoDBBackup did not complete within %s (state=running)", psmdbDefaultBackupDeadline)) } // Not-yet-started states ("", requested, waiting). A wall-clock deadline // fails a backup the operator never starts, so it cannot pin the BackupJob // Running forever. - if !psmdbBackupTimedOut(state, j.Status.StartedAt) { + if !psmdbBackupTimedOut(state, j.Status.StartedAt, useSystemBucket) { return ctrl.Result{RequeueAfter: psmdbPollInterval}, nil } // The deadline hit for a not-yet-started backup. mdbBackup came from the @@ -463,14 +493,19 @@ func (r *BackupJobReconciler) reconcileMongoDB(ctx context.Context, j *backupsv1 // waiting-for-precondition branches (cluster absent, backups disabled) that // share the same shape. func (r *BackupJobReconciler) requeueMongoDBBackupWaiting(ctx context.Context, j *backupsv1alpha1.BackupJob, reason, message string) (ctrl.Result, error) { - apimeta.SetStatusCondition(&j.Status.Conditions, metav1.Condition{ + // Write only when the condition actually changes: a running dump polls + // through here every few seconds for as long as it streams, and rewriting an + // identical condition each time would be a status write per poll for hours. + changed := apimeta.SetStatusCondition(&j.Status.Conditions, metav1.Condition{ Type: "Ready", Status: metav1.ConditionFalse, Reason: reason, Message: message, }) - if err := r.Status().Update(ctx, j); err != nil { - return ctrl.Result{}, err + if changed { + if err := r.Status().Update(ctx, j); err != nil { + return ctrl.Result{}, err + } } return ctrl.Result{RequeueAfter: psmdbPollInterval}, nil } @@ -666,22 +701,25 @@ func psmdbBackupDeadlineExceeded(startedAt *metav1.Time) bool { } // psmdbBackupTimedOut reports whether an in-progress operator backup should be -// failed on the wall-clock deadline. A dump the operator is actively writing -// (state=running) is never timed out: pbm keeps streaming into the shared bucket -// after the driver gives up, and the BackupJob's terminal-phase guard means the -// artifact-creating branch never runs again — so failing a running dump would -// strand an archive that no Backup object represents and no retention can reach -// (the operator CR carries no ownerRef either). A real dataset routinely outruns -// 30m, and a genuinely broken dump terminates through the operator's own -// error/rejected state, so a running backup is left to finish. The deadline -// still bounds the not-yet-`running` states ("", requested, waiting): a backup -// the operator has not begun streaming. Those can still be advanced later — a -// `waiting` backup runs when the slot frees, and `requested` is set as the -// operator dispatches — so the caller cancels the operator CR when this trips, -// rather than leaving it to run into the shared bucket after the BackupJob is -// already Failed. -func psmdbBackupTimedOut(state string, startedAt *metav1.Time) bool { - if state == psmdbtypes.StateRunning { +// failed on the wall-clock deadline. On the useSystemBucket flow a backup that +// has begun streaming (state=running) is exempt: pbm keeps writing into the +// shared bucket after the driver gives up, and the BackupJob's terminal-phase +// guard means the artifact-creating branch never runs again, so failing it +// would strand an archive that no Backup object represents and no retention +// can reach (the operator CR carries no ownerRef either). A real dataset +// routinely outruns 30m, and a genuinely broken dump terminates through the +// operator's own error/rejected state, so it is left to finish. On the legacy +// flow the deadline applies to `running` too: the archive lands in the tenant's +// own bucket under psmdb task retention, nothing the platform owns is stranded, +// and the pre-existing contract failed the job on the deadline while leaving +// the operator CR alone. The deadline bounds the not-yet-`running` states ("", +// requested, waiting) on both flows: a backup the operator has not begun +// streaming can still be advanced later — a `waiting` backup runs when the slot +// frees, and `requested` is set as the operator dispatches — so the caller +// cancels the operator CR when this trips, rather than leaving it to run into +// the shared bucket after the BackupJob is already Failed. +func psmdbBackupTimedOut(state string, startedAt *metav1.Time, useSystemBucket bool) bool { + if state == psmdbtypes.StateRunning && useSystemBucket { return false } return psmdbBackupDeadlineExceeded(startedAt) @@ -1155,7 +1193,15 @@ func (r *RestoreJobReconciler) reconcileMongoDBRestore(ctx context.Context, rest // Secret, so the Secret name is only a proxy, while the snapshot flag is what // the backup actually ran on. if pitr != nil { - snap, _ := unmarshalMongoDBBackupSnapshot(backup.Status.UnderlyingResources) + snap, serr := unmarshalMongoDBBackupSnapshot(backup.Status.UnderlyingResources) + if serr != nil { + // Flow unknown: refuse rather than fall open. resolveMongoDBBackupSource + // treats the same decode failure as fatal only on its snapshot-fallback + // path and returns from the live-CR path first, so this is the one check + // that still sees it while the operator CR is alive. + return r.markRestoreJobFailed(ctx, restoreJob, fmt.Sprintf( + "restoreJob.spec.options.recoveryTime is set, but the Backup snapshot cannot be decoded (%v), so the flow the backup was taken on is unknown; refusing point-in-time recovery rather than handing the operator a target it may not serve", serr)) + } if snap != nil && snap.UseSystemBucket { return r.markRestoreJobFailed(ctx, restoreJob, "restoreJob.spec.options.recoveryTime is set, but point-in-time recovery is not available for a backup taken on the useSystemBucket flow (no oplog is captured there); omit recoveryTime to restore the backup as taken. See docs/operations/backup-classes.md.") @@ -1207,6 +1253,21 @@ func (r *RestoreJobReconciler) reconcileMongoDBRestore(ctx context.Context, rest "restorejob", restoreJob.Name, "from", source.S3.CredentialsSecret, "to", cred) source.S3.CredentialsSecret = cred } + // The reference must resolve before the operator sees it. After an app opts + // into useSystemBucket the chart prunes the legacy -s3-creds while + // older Backups still name it, and with no same-bucket target credential to + // adopt the restore would reach the operator naming a Secret that is gone + // and die on a pbm-level message. Check here and fail with a legible one. + if source.S3.CredentialsSecret != "" { + if err := r.Get(ctx, types.NamespacedName{Namespace: target.Namespace, Name: source.S3.CredentialsSecret}, &corev1.Secret{}); err != nil { + if apierrors.IsNotFound(err) { + return r.markRestoreJobFailedReason(ctx, restoreJob, "RestoreCredentialsMissing", fmt.Sprintf( + "the backup was written to bucket %q with credentialsSecret %q, which does not exist in namespace %s (the chart prunes it when the application opts into useSystemBucket); re-create a Secret by that name holding credentials for that bucket, or restore into a target whose storage declares that bucket", + source.S3.Bucket, source.S3.CredentialsSecret, target.Namespace)) + } + return ctrl.Result{}, err + } + } } mdbRestore, err := r.ensureMongoDBRestore(ctx, restoreJob, targetPSMDBName, source, pitr) @@ -1455,10 +1516,10 @@ type mongodbBackupSnapshot struct { func marshalMongoDBBackupSnapshot(mdbBackup *psmdbtypes.PerconaServerMongoDBBackup, rendered *strategyv1alpha1.MongoDBTemplate, storageName string, parameters map[string]string, useSystemBucket bool) (*runtime.RawExtension, error) { snap := mongodbBackupSnapshot{ - Kind: psmdbBackupSnapshotKind, - APIVersion: psmdbBackupSnapshotAPIVersion, - Destination: mdbBackup.Status.Destination, - Type: psmdbBackupTypeOrDefault(rendered.Type), + Kind: psmdbBackupSnapshotKind, + APIVersion: psmdbBackupSnapshotAPIVersion, + Destination: mdbBackup.Status.Destination, + Type: psmdbBackupTypeOrDefault(rendered.Type), StorageName: storageName, S3: mdbBackup.Status.S3.DeepCopy(), Parameters: parameters, diff --git a/internal/backupcontroller/psmdbstrategy_controller_test.go b/internal/backupcontroller/psmdbstrategy_controller_test.go index 89e6a2fcb..8909ba0bf 100644 --- a/internal/backupcontroller/psmdbstrategy_controller_test.go +++ b/internal/backupcontroller/psmdbstrategy_controller_test.go @@ -1689,29 +1689,35 @@ func TestCleanupMongoDBBackup(t *testing.T) { }) } -// A dump the operator is actively writing (state=running) must never be failed -// on the wall-clock deadline: pbm keeps streaming into the shared bucket after -// the driver gives up, so failing it strands an archive no Backup object -// represents. Only a backup the operator never started trips the deadline. +// On the useSystemBucket flow a dump the operator is actively writing +// (state=running) is never failed on the wall-clock deadline: pbm keeps +// streaming into the shared bucket after the driver gives up, so failing it +// strands an archive no Backup object represents. On the legacy flow the +// archive lands in the tenant's own bucket under psmdb task retention, so the +// pre-existing deadline still applies to running. Not-started states trip the +// deadline on both flows. func TestPsmdbBackupTimedOut(t *testing.T) { past := &metav1.Time{Time: time.Now().Add(-2 * psmdbDefaultBackupDeadline)} recent := &metav1.Time{Time: time.Now()} cases := []struct { + name string state string started *metav1.Time + usb bool want bool }{ - {psmdbtypes.StateRunning, past, false}, // progressing: keep polling, never strand the archive - {psmdbtypes.StateWaiting, past, true}, // never started: safe to fail, nothing written - {psmdbtypes.StateRequested, past, true}, // - {"", past, true}, // operator never observed it - {psmdbtypes.StateRunning, recent, false}, // running, deadline not reached - {psmdbtypes.StateWaiting, recent, false}, // not yet past the deadline - {psmdbtypes.StateRunning, nil, false}, // no StartedAt + {"system-bucket running past deadline: never strand the shared archive", psmdbtypes.StateRunning, past, true, false}, + {"legacy running past deadline: the pre-existing deadline applies", psmdbtypes.StateRunning, past, false, true}, + {"waiting past deadline: nothing written, safe to fail", psmdbtypes.StateWaiting, past, true, true}, + {"requested past deadline", psmdbtypes.StateRequested, past, false, true}, + {"never observed past deadline", "", past, true, true}, + {"legacy running within deadline", psmdbtypes.StateRunning, recent, false, false}, + {"waiting within deadline", psmdbtypes.StateWaiting, recent, true, false}, + {"legacy running with no StartedAt", psmdbtypes.StateRunning, nil, false, false}, } for _, tc := range cases { - if got := psmdbBackupTimedOut(tc.state, tc.started); got != tc.want { - t.Errorf("psmdbBackupTimedOut(state=%q, past=%v): got %v want %v", tc.state, tc.started == past, got, tc.want) + if got := psmdbBackupTimedOut(tc.state, tc.started, tc.usb); got != tc.want { + t.Errorf("%s: psmdbBackupTimedOut(state=%q, useSystemBucket=%v): got %v want %v", tc.name, tc.state, tc.usb, got, tc.want) } } } @@ -1825,59 +1831,104 @@ func TestReleaseMongoDBCleanup_UsesPassedObjectNotReRead(t *testing.T) { } } -// A streaming dump is never cancelled: the pinned operator persists status only -// on a state/error change, so status.lastTransition freezes at the instant the -// dump entered running and a real dataset routinely outruns any wall-clock -// window. The driver must keep polling a running CR quietly even long past the -// deadline — never fail the BackupJob, never delete the CR (which would strand -// the partial archive on the shared bucket). -func TestReconcileMongoDB_RunningNeverCancelled(t *testing.T) { - job, strategy, app, cluster, resolved := mongodbInjectFixture(true) - // Running far longer than the deadline. - job.Status.StartedAt = &metav1.Time{Time: time.Now().Add(-4 * psmdbDefaultBackupDeadline)} - cluster.Spec.Backup.Storages = map[string]runtime.RawExtension{ - "s3-storage": {Raw: []byte(`{"type":"s3","s3":{"bucket":"cozy-backups"}}`)}, - } - running := &psmdbtypes.PerconaServerMongoDBBackup{ - ObjectMeta: metav1.ObjectMeta{ - Namespace: "tenant", - Name: "op-running", - Finalizers: []string{psmdbDeleteBackupFinalizer}, - Labels: map[string]string{ - backupsv1alpha1.OwningJobNameLabel: job.Name, - backupsv1alpha1.OwningJobNamespaceLabel: job.Namespace, +// A streaming dump on the useSystemBucket flow is neither cancelled nor failed +// on the deadline: the pinned operator persists status only on a state/error +// change, so status.lastTransition freezes at the instant the dump entered +// running, and a real dataset routinely outruns any window. The wait is named +// on the BackupJob (Ready=False with the start time) rather than silent. On the +// legacy flow the archive lands in the tenant's own bucket under psmdb task +// retention, so the pre-existing deadline still fails the job — and the operator +// CR is left alone either way. +func TestReconcileMongoDB_RunningPastDeadline(t *testing.T) { + setup := func(t *testing.T, useSystemBucket bool) (*BackupJobReconciler, client.Client, *ResolvedBackupConfig, *backupsv1alpha1.BackupJob) { + job, strategy, app, cluster, resolved := mongodbInjectFixture(true) + app.Spec.Backup.UseSystemBucket = useSystemBucket + job.Status.StartedAt = &metav1.Time{Time: time.Now().Add(-4 * psmdbDefaultBackupDeadline)} + bucket := "cozy-backups" + if !useSystemBucket { + // Legacy: the strategy carries no coordinates to inject and the cluster + // declares the tenant's own bucket. + strategy.Spec.Template.S3 = nil + bucket = "tenant-own" + } + cluster.Spec.Backup.Storages = map[string]runtime.RawExtension{ + "s3-storage": {Raw: []byte(fmt.Sprintf(`{"type":"s3","s3":{"bucket":%q}}`, bucket))}, + } + running := &psmdbtypes.PerconaServerMongoDBBackup{ + ObjectMeta: metav1.ObjectMeta{ + Namespace: "tenant", + Name: "op-running", + Labels: map[string]string{ + backupsv1alpha1.OwningJobNameLabel: job.Name, + backupsv1alpha1.OwningJobNamespaceLabel: job.Namespace, + }, }, - }, - // lastTransition frozen at the start, as the pinned operator leaves it. - Status: psmdbtypes.PerconaServerMongoDBBackupStatus{ - State: psmdbtypes.StateRunning, - LastTransition: &metav1.Time{Time: time.Now().Add(-4 * psmdbDefaultBackupDeadline)}, - }, + // lastTransition frozen at the start, as the pinned operator leaves it. + Status: psmdbtypes.PerconaServerMongoDBBackupStatus{ + State: psmdbtypes.StateRunning, + LastTransition: &metav1.Time{Time: time.Now().Add(-4 * psmdbDefaultBackupDeadline)}, + }, + } + if useSystemBucket { + running.Finalizers = []string{psmdbDeleteBackupFinalizer} + } + c := newMongoDBStrategyTestClient(t, job, strategy, app, cluster, running) + return &BackupJobReconciler{Client: c, Scheme: c.Scheme(), Recorder: record.NewFakeRecorder(10)}, c, resolved, job + } + getCR := func(t *testing.T, c client.Client) *psmdbtypes.PerconaServerMongoDBBackup { + got := &psmdbtypes.PerconaServerMongoDBBackup{} + if err := c.Get(context.Background(), types.NamespacedName{Namespace: "tenant", Name: "op-running"}, got); err != nil { + t.Fatalf("get running backup: %v", err) + } + return got + } + getJob := func(t *testing.T, c client.Client, name string) *backupsv1alpha1.BackupJob { + p := &backupsv1alpha1.BackupJob{} + if err := c.Get(context.Background(), types.NamespacedName{Namespace: "tenant", Name: name}, p); err != nil { + t.Fatalf("get job: %v", err) + } + return p } - c := newMongoDBStrategyTestClient(t, job, strategy, app, cluster, running) - r := &BackupJobReconciler{Client: c, Scheme: c.Scheme(), Recorder: record.NewFakeRecorder(10)} - res, err := r.reconcileMongoDB(context.Background(), job.DeepCopy(), resolved) - if err != nil { - t.Fatalf("reconcileMongoDB: %v", err) - } - if res.RequeueAfter == 0 { - t.Fatalf("expected a poll requeue for a running backup, got %+v", res) - } - got := &psmdbtypes.PerconaServerMongoDBBackup{} - if err := c.Get(context.Background(), types.NamespacedName{Namespace: "tenant", Name: "op-running"}, got); err != nil { - t.Fatalf("get running backup: %v", err) - } - if !got.DeletionTimestamp.IsZero() { - t.Errorf("a running backup must never be cancelled, even past the deadline; it was deleted") - } - persisted := &backupsv1alpha1.BackupJob{} - if err := c.Get(context.Background(), types.NamespacedName{Namespace: "tenant", Name: job.Name}, persisted); err != nil { - t.Fatalf("get job: %v", err) - } - if persisted.Status.Phase == backupsv1alpha1.BackupJobPhaseFailed { - t.Errorf("a running backup must not fail the BackupJob on the deadline, got phase=Failed") - } + t.Run("system bucket: left to finish, wait named on the job", func(t *testing.T) { + r, c, resolved, job := setup(t, true) + res, err := r.reconcileMongoDB(context.Background(), job.DeepCopy(), resolved) + if err != nil { + t.Fatalf("reconcileMongoDB: %v", err) + } + if res.RequeueAfter == 0 { + t.Fatalf("expected a poll requeue for a running system-bucket backup, got %+v", res) + } + if !getCR(t, c).DeletionTimestamp.IsZero() { + t.Errorf("a running system-bucket backup must never be cancelled; it was deleted") + } + p := getJob(t, c, job.Name) + if p.Status.Phase == backupsv1alpha1.BackupJobPhaseFailed { + t.Errorf("a running system-bucket backup must not fail the BackupJob on the deadline") + } + cond := apimeta.FindStatusCondition(p.Status.Conditions, "Ready") + if cond == nil || cond.Status != metav1.ConditionFalse || cond.Reason != "PerconaServerMongoDBBackupRunning" || !strings.Contains(cond.Message, "streaming since") { + t.Errorf("expected Ready=False PerconaServerMongoDBBackupRunning naming the start time, got %+v", cond) + } + }) + + t.Run("legacy: the deadline still fails the job, CR left alone", func(t *testing.T) { + r, c, resolved, job := setup(t, false) + if _, err := r.reconcileMongoDB(context.Background(), job.DeepCopy(), resolved); err != nil { + t.Fatalf("reconcileMongoDB: %v", err) + } + p := getJob(t, c, job.Name) + if p.Status.Phase != backupsv1alpha1.BackupJobPhaseFailed { + t.Fatalf("a legacy backup running past the deadline must fail the BackupJob, got phase=%q", p.Status.Phase) + } + cond := apimeta.FindStatusCondition(p.Status.Conditions, "Ready") + if cond == nil || !strings.Contains(cond.Message, "did not complete within") { + t.Errorf("expected a Ready condition naming the deadline, got %+v", cond) + } + if !getCR(t, c).DeletionTimestamp.IsZero() { + t.Errorf("the legacy operator CR must be left alone (hands-off); it was deleted") + } + }) } // The storage-race retry hinges on recognising the operator's own @@ -2277,3 +2328,198 @@ func TestReconcileMongoDBRestore_PITRAllowedForNonSystemBucketBackup(t *testing. } } } + +// A recoveryTime restore must know which flow the backup was taken on; a +// snapshot that fails to decode leaves that unknown, and the refusal must fail +// closed rather than hand the operator a point-in-time target it may not serve. +// The live operator CR is present so source resolution succeeds on the live path +// (which never consults the snapshot) — exactly the case that reaches this guard. +func TestReconcileMongoDBRestore_PITRRefusedWhenSnapshotUndecodable(t *testing.T) { + apps := mongodbapp.GroupName + live := &psmdbtypes.PerconaServerMongoDBBackup{ + ObjectMeta: metav1.ObjectMeta{Namespace: "tenant", Name: "op-backup"}, + Status: psmdbtypes.PerconaServerMongoDBBackupStatus{ + State: psmdbtypes.StateReady, + Destination: "s3://cozy-backups/tenant/app1/2026", + S3: &psmdbtypes.BackupStorageS3{Bucket: "cozy-backups", CredentialsSecret: psmdbDefaultCredentialsSecret}, + }, + } + backup := &backupsv1alpha1.Backup{ + ObjectMeta: metav1.ObjectMeta{Namespace: "tenant", Name: "src-backup"}, + Spec: backupsv1alpha1.BackupSpec{ + ApplicationRef: corev1.TypedLocalObjectReference{Kind: "MongoDB", Name: "app1", APIGroup: &apps}, + DriverMetadata: map[string]string{psmdbBackupNameKey: "op-backup"}, + }, + // Valid JSON, wrong shape: the flag field is not a bool, so the typed decode fails. + Status: backupsv1alpha1.BackupStatus{UnderlyingResources: &runtime.RawExtension{Raw: []byte(`{"kind":"MongoDBBackupSnapshot","useSystemBucket":"not-a-bool"}`)}}, + } + restoreJob := newMongoDBRestoreJob("rj-pitr-bad", "tenant") + restoreJob.Status.StartedAt = &metav1.Time{Time: time.Now()} + restoreJob.Status.Phase = backupsv1alpha1.RestoreJobPhaseRunning + restoreJob.Spec.Options = &runtime.RawExtension{Raw: []byte(`{"recoveryTime":"2026-08-05T12:34:56Z"}`)} + + c := newMongoDBStrategyTestClient(t, backup, restoreJob, live) + r := &RestoreJobReconciler{Client: c, Scheme: c.Scheme(), Recorder: record.NewFakeRecorder(10)} + + if _, err := r.reconcileMongoDBRestore(context.Background(), restoreJob.DeepCopy(), backup); err != nil { + t.Fatalf("reconcileMongoDBRestore: %v", err) + } + persisted := &backupsv1alpha1.RestoreJob{} + if err := c.Get(context.Background(), types.NamespacedName{Namespace: "tenant", Name: "rj-pitr-bad"}, persisted); err != nil { + t.Fatalf("get restore job: %v", err) + } + if persisted.Status.Phase != backupsv1alpha1.RestoreJobPhaseFailed { + t.Fatalf("a PITR request over an undecodable snapshot must fail closed, got phase=%q", persisted.Status.Phase) + } + cond := apimeta.FindStatusCondition(persisted.Status.Conditions, "Ready") + if cond == nil || !strings.Contains(cond.Message, "cannot be decoded") { + t.Errorf("expected a Ready condition naming the undecodable snapshot, got %+v", cond) + } +} + +// After an app opts into useSystemBucket the chart prunes its legacy +// -s3-creds, and its live storage moves to the platform bucket, so a +// restore of an older legacy backup finds no same-bucket credential to adopt +// and keeps the source's — now deleted — Secret. It must fail with a legible, +// named reason before the operator sees a reference to a Secret that is gone. +func TestReconcileMongoDBRestore_FailsNamedWhenCredentialsSecretMissing(t *testing.T) { + apps := mongodbapp.GroupName + snap := &psmdbtypes.PerconaServerMongoDBBackup{ + Status: psmdbtypes.PerconaServerMongoDBBackupStatus{ + Destination: "s3://tenant-own/tenant/app1/2026", + S3: &psmdbtypes.BackupStorageS3{Bucket: "tenant-own", CredentialsSecret: "mongodb-app1-s3-creds"}, + }, + } + raw, err := marshalMongoDBBackupSnapshot(snap, &strategyv1alpha1.MongoDBTemplate{Type: "logical"}, "s3-storage", nil, false) + if err != nil { + t.Fatalf("marshal snapshot: %v", err) + } + newBackup := func() *backupsv1alpha1.Backup { + return &backupsv1alpha1.Backup{ + ObjectMeta: metav1.ObjectMeta{Namespace: "tenant", Name: "src-backup"}, + Spec: backupsv1alpha1.BackupSpec{ + ApplicationRef: corev1.TypedLocalObjectReference{Kind: "MongoDB", Name: "app1", APIGroup: &apps}, + }, + Status: backupsv1alpha1.BackupStatus{UnderlyingResources: raw}, + } + } + // The same app, now on the system bucket: its only storage is on cozy-backups, + // so nothing on tenant-own is adoptable. + newTarget := func() *psmdbtypes.PerconaServerMongoDB { + return &psmdbtypes.PerconaServerMongoDB{ + ObjectMeta: metav1.ObjectMeta{Namespace: "tenant", Name: mongodbNameForApp("app1")}, + Spec: psmdbtypes.PerconaServerMongoDBSpec{Backup: psmdbtypes.PerconaServerMongoDBBackupConfig{ + Enabled: true, + Storages: map[string]runtime.RawExtension{"s3-storage": {Raw: []byte(`{"type":"s3","s3":{"bucket":"cozy-backups","credentialsSecret":"cozy-backups-creds"}}`)}}, + }}, + } + } + newRJ := func(name string) *backupsv1alpha1.RestoreJob { + rj := newMongoDBRestoreJob(name, "tenant") + rj.Status.StartedAt = &metav1.Time{Time: time.Now()} + rj.Status.Phase = backupsv1alpha1.RestoreJobPhaseRunning + return rj + } + + t.Run("missing Secret fails with a named reason", func(t *testing.T) { + backup, rj := newBackup(), newRJ("rj-nocred") + c := newMongoDBStrategyTestClient(t, backup, rj, newTarget()) + r := &RestoreJobReconciler{Client: c, Scheme: c.Scheme(), Recorder: record.NewFakeRecorder(10)} + if _, err := r.reconcileMongoDBRestore(context.Background(), rj.DeepCopy(), backup); err != nil { + t.Fatalf("reconcileMongoDBRestore: %v", err) + } + persisted := &backupsv1alpha1.RestoreJob{} + if err := c.Get(context.Background(), types.NamespacedName{Namespace: "tenant", Name: "rj-nocred"}, persisted); err != nil { + t.Fatalf("get restore job: %v", err) + } + if persisted.Status.Phase != backupsv1alpha1.RestoreJobPhaseFailed { + t.Fatalf("a restore naming a missing credentialsSecret must fail, got phase=%q", persisted.Status.Phase) + } + cond := apimeta.FindStatusCondition(persisted.Status.Conditions, "Ready") + if cond == nil || cond.Reason != "RestoreCredentialsMissing" || !strings.Contains(cond.Message, "mongodb-app1-s3-creds") { + t.Errorf("expected Ready=False RestoreCredentialsMissing naming the Secret, got %+v", cond) + } + }) + + t.Run("present Secret lets the restore proceed", func(t *testing.T) { + backup, rj := newBackup(), newRJ("rj-cred-ok") + secret := &corev1.Secret{ObjectMeta: metav1.ObjectMeta{Namespace: "tenant", Name: "mongodb-app1-s3-creds"}} + c := newMongoDBStrategyTestClient(t, backup, rj, newTarget(), secret) + r := &RestoreJobReconciler{Client: c, Scheme: c.Scheme(), Recorder: record.NewFakeRecorder(10)} + if _, err := r.reconcileMongoDBRestore(context.Background(), rj.DeepCopy(), backup); err != nil { + t.Fatalf("reconcileMongoDBRestore: %v", err) + } + persisted := &backupsv1alpha1.RestoreJob{} + if err := c.Get(context.Background(), types.NamespacedName{Namespace: "tenant", Name: "rj-cred-ok"}, persisted); err != nil { + t.Fatalf("get restore job: %v", err) + } + if cond := apimeta.FindStatusCondition(persisted.Status.Conditions, "Ready"); cond != nil && cond.Reason == "RestoreCredentialsMissing" { + t.Errorf("an existing credentialsSecret must not be reported missing: %+v", cond) + } + }) +} + +// Opting out (useSystemBucket true→false) stops the injection but leaves the +// driver's storage on the live cluster until the chart re-renders. A BackupJob +// in that window must not mint a CR — it would carry no delete-backup finalizer +// and write an object nothing owns into the platform bucket. The wait is named +// and deadline-bounded like the others. +func TestReconcileMongoDB_OptOutRefusesStalePlatformStorage(t *testing.T) { + setup := func(t *testing.T, startedAt time.Time) (*BackupJobReconciler, client.Client, *ResolvedBackupConfig, *backupsv1alpha1.BackupJob) { + job, strategy, app, cluster, resolved := mongodbInjectFixture(true) + app.Spec.Backup.UseSystemBucket = false // opted back out; the strategy still names cozy-backups + job.Status.StartedAt = &metav1.Time{Time: startedAt} + // Live cluster still carries the entry the driver injected. + cluster.Spec.Backup.Storages = map[string]runtime.RawExtension{ + "s3-storage": {Raw: []byte(`{"type":"s3","s3":{"bucket":"cozy-backups","credentialsSecret":"cozy-backups-creds"}}`)}, + } + c := newMongoDBStrategyTestClient(t, job, strategy, app, cluster) + return &BackupJobReconciler{Client: c, Scheme: c.Scheme(), Recorder: record.NewFakeRecorder(10)}, c, resolved, job + } + countCRs := func(t *testing.T, c client.Client) int { + list := &psmdbtypes.PerconaServerMongoDBBackupList{} + if err := c.List(context.Background(), list, client.InNamespace("tenant")); err != nil { + t.Fatalf("list: %v", err) + } + return len(list.Items) + } + + t.Run("within the deadline: no mint, named wait", func(t *testing.T) { + r, c, resolved, job := setup(t, time.Now()) + res, err := r.reconcileMongoDB(context.Background(), job.DeepCopy(), resolved) + if err != nil { + t.Fatalf("reconcileMongoDB: %v", err) + } + if res.RequeueAfter == 0 { + t.Fatalf("expected a waiting requeue while the platform storage lingers, got %+v", res) + } + if n := countCRs(t, c); n != 0 { + t.Errorf("no operator Backup must be minted onto the platform bucket with useSystemBucket=false, got %d", n) + } + persisted := &backupsv1alpha1.BackupJob{} + if err := c.Get(context.Background(), types.NamespacedName{Namespace: "tenant", Name: job.Name}, persisted); err != nil { + t.Fatalf("get job: %v", err) + } + cond := apimeta.FindStatusCondition(persisted.Status.Conditions, "Ready") + if cond == nil || cond.Reason != "PerconaServerMongoDBStorageStale" { + t.Errorf("expected Ready=False PerconaServerMongoDBStorageStale, got %+v", cond) + } + }) + + t.Run("past the deadline: fails, still no mint", func(t *testing.T) { + r, c, resolved, job := setup(t, time.Now().Add(-2*psmdbDefaultBackupDeadline)) + if _, err := r.reconcileMongoDB(context.Background(), job.DeepCopy(), resolved); err != nil { + t.Fatalf("reconcileMongoDB: %v", err) + } + if n := countCRs(t, c); n != 0 { + t.Errorf("no operator Backup must be minted on the deadline failure either, got %d", n) + } + persisted := &backupsv1alpha1.BackupJob{} + if err := c.Get(context.Background(), types.NamespacedName{Namespace: "tenant", Name: job.Name}, persisted); err != nil { + t.Fatalf("get job: %v", err) + } + if persisted.Status.Phase != backupsv1alpha1.BackupJobPhaseFailed { + t.Errorf("expected the BackupJob to fail once the stale storage outlives the deadline, got phase=%q", persisted.Status.Phase) + } + }) +} From 4233e907924b188ff06e142e2a040beb4de99a5e Mon Sep 17 00:00:00 2001 From: Andrey Kolkov Date: Sat, 19 Sep 2026 10:55:35 +0400 Subject: [PATCH 0021/1280] fix(mongodb): decide a backup's flow from its own CR, not the app flag MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The opt-out refusal ran before the lookup of the job's existing operator CR, so it was a per-poll gate rather than a mint-time one: flipping backup.useSystemBucket to false while a dump streamed routed every later reconcile into the refusal, failed the job at the deadline and left the CR minted under the old flag streaming into the platform bucket with a finalizer no Backup would ever resolve — the stranded archive the running exemption exists to prevent. The refusal now applies only while the job has no CR, and everything after the mint reads the flow off the CR's delete-backup finalizer, which is fixed at mint time, instead of the mutable app flag. A late dump on the legacy flow is likewise handled by its CR's flow: the deadline fails the job and leaves the operator CR, as before this driver existed. The refusal also identified the injected entry by bucket name and told the operator to wait for the chart to re-render it, which the docs say never happens. The entry is now recognised by its credentialsSecret, the one field on it the driver chose (bucket names collide with an admin's external bucket and drift when the platform bucket is re-provisioned), and the message names the manual removal the docs prescribe. At the pinned operator `requested` is set right after the command is sent to pbm, so deleting a CR in that state cannot recall it and a late dump would land with nothing to own it. Only an unobserved or queued CR is cancelled; a requested one is left as the handle to whatever pbm writes, and the job fails. The credential pre-check failed at once where every sibling precondition waits for the restore deadline, and it re-ran against a restore already replaying, so a Secret pruned mid-replay marked an in-progress restore Failed. It now waits like its neighbours and is skipped once the operator restore exists. The status-write suppression on the waiting helper is pinned by counting status updates across repeated reconciles. The legacy deadline's justification claimed psmdb task retention covers the archive; the operator prunes only its own scheduled backups, so the object is the tenant's to reclaim, and the comments say that instead. The bootstrap refusal names the value that actually clears it (bootstrap.enabled is not reset after a bootstrap restore). Assisted-by: LLM Signed-off-by: Andrey Kolkov --- docs/operations/backup-classes.md | 2 +- .../psmdbstrategy_controller.go | 177 ++++++++---- .../psmdbstrategy_controller_test.go | 258 +++++++++++++++++- packages/apps/mongodb/templates/restore.yaml | 2 +- packages/apps/mongodb/tests/restore_test.yaml | 2 +- 5 files changed, 373 insertions(+), 68 deletions(-) diff --git a/docs/operations/backup-classes.md b/docs/operations/backup-classes.md index 3eeabe4f3..9a031b6a1 100644 --- a/docs/operations/backup-classes.md +++ b/docs/operations/backup-classes.md @@ -123,7 +123,7 @@ Because the chart drops `spec.backup.tasks` and `spec.backup.pitr`, the psmdb op Dropping `spec.backup.tasks` also drops the psmdb `keep` retention it carried, so on this flow **the driver owns the archive** the way the Rabbitmq/Redis drivers own theirs (an on-demand `PerconaServerMongoDBBackup` is not covered by psmdb task retention). The driver stamps the operator's `percona.com/delete-backup` finalizer onto each backup it mints here, and deleting a Cozystack `Backup` (a retention-pruned `Plan`, or a manual delete) deletes that `PerconaServerMongoDBBackup` CR — whose finalizer removes the pbm object from the shared bucket before the `Backup` is released, so a Plan does not accumulate objects in `cozy-backups`. A legacy backup writes to the tenant's own bucket and keeps the pre-existing hands-off contract (its lifecycle stays the tenant's / operator's; nothing is deleted on `Backup` removal). Note this prunes only when a `Backup` is deleted: unlike CNPG and MariaDB, which prune engine-side on their own schedule, MongoDB has no engine-side scheduled trim on this flow, so keeping `cozy-backups` bounded depends on a `Plan`'s retention actually deleting old `Backup` objects. **A `Plan` has no retention field yet** (`PlanSpec` carries only `applicationRef`, `backupClassName` and `schedule`), so today a nightly `useSystemBucket` Plan grows the shared bucket unbounded — `schedule` and `retentionPolicy` on the app are inert here (see [Opt-in to the system bucket](#opt-in-to-the-system-bucket)), and platform-level retention is tracked in the [`BackupRetentionPolicy` design (#4192)](https://github.com/cozystack/cozystack/pull/4192). Teardown GC of orphaned `Backup`s / S3 data is [#3966](https://github.com/cozystack/cozystack/issues/3966). Until those land, bound `cozy-backups` with an S3 lifecycle policy on the object store. Two cases release the `Backup` without waiting for the object to be pruned, so a wedged prune never pins a namespace in `Terminating`: a terminating namespace (where the operator's delete-backup step cannot run) and the `backups.cozystack.io/skip-artifact-cleanup: "true"` annotation. In both the driver strips its own finalizer and leaves the object for a bucket lifecycle policy to reclaim. A down operator or unreachable storage in a live namespace is NOT released automatically — the `Backup` stays `Terminating` as a visible signal until the operator recovers or you set that annotation to force the release. -**Opting back out** (`useSystemBucket` true→false) is not automatic in reverse: the driver stops injecting, but the `s3-storage` entry it already applied stays on the live `PerconaServerMongoDB` under the driver's own field manager (`cozystack-psmdb-backup-driver`) — the chart does not own it and so never prunes it. It is inert once `backup.enabled=false`; to fully return a release to the legacy flow, delete that storage entry from the `PerconaServerMongoDB` by hand before re-declaring the tenant's own `backup.*` S3 values. +**Opting back out** (`useSystemBucket` true→false) is not automatic in reverse: the driver stops injecting, but the `s3-storage` entry it already applied stays on the live `PerconaServerMongoDB` under the driver's own field manager (`cozystack-psmdb-backup-driver`) — the chart does not own it and so never prunes it. It is inert once `backup.enabled=false`; to fully return a release to the legacy flow, delete that storage entry from the `PerconaServerMongoDB` by hand before re-declaring the tenant's own `backup.*` S3 values. Until it is removed, a new `BackupJob` on that release is refused rather than written into the platform bucket unowned: the driver recognises the injected entry by its `credentialsSecret` and holds the job at `Ready=False` (`PerconaServerMongoDBStorageStale`) naming that manual step, failing it at the backup deadline. A backup already streaming when the flag was flipped is unaffected — its flow is fixed by the finalizer on its own operator CR. ### Point-in-time recovery (MongoDB) diff --git a/internal/backupcontroller/psmdbstrategy_controller.go b/internal/backupcontroller/psmdbstrategy_controller.go index e93e12a8c..882ac4bb0 100644 --- a/internal/backupcontroller/psmdbstrategy_controller.go +++ b/internal/backupcontroller/psmdbstrategy_controller.go @@ -329,21 +329,31 @@ func (r *BackupJobReconciler) reconcileMongoDB(ctx context.Context, j *backupsv1 } // Opting out (useSystemBucket true→false) stops the injection but leaves the - // driver's storage entry on the live cluster until the chart re-renders. A - // BackupJob in that window passes the precondition (presence, not content), - // would mint a CR without the delete-backup finalizer, and the dump would land - // in the platform bucket as an object nothing owns or prunes. Refuse to mint - // onto a storage whose bucket is the platform's while the flag reads false; - // bounded by the deadline like the other waits. - if !useSystemBucket && rendered.S3 != nil { - if bucket, _ := psmdbStorageS3(cluster.Spec.Backup.Storages[storageName]); bucket != "" && bucket == rendered.S3.Bucket { + // driver's storage entry on the live cluster: the chart never owned it and + // does not prune it, so it stays until removed by hand (backup-classes.md). A + // BackupJob started in that state passes the presence-only precondition and + // would mint a CR without the delete-backup finalizer, landing the dump in + // the platform bucket as an object nothing owns or prunes. Refuse to mint. + // Two points of shape: this is a mint-time gate, so it applies only while + // the job has no CR — a CR minted while the flag was true is handled by the + // state switch below, which reads the flow off the CR's own finalizer, so a + // flag flipped mid-dump cannot fail a streaming backup here; and the injected + // entry is identified by its credentialsSecret, the one field on it the + // driver chose — bucket names collide with an admin's external bucket and + // drift when the platform bucket is re-provisioned. + existing, err := r.findMongoDBBackupForJob(ctx, j) + if err != nil { + return ctrl.Result{}, err + } + if existing == nil && !useSystemBucket && rendered.S3 != nil { + if _, cred := psmdbStorageS3(cluster.Spec.Backup.Storages[storageName]); cred != "" && cred == psmdbInjectedCredentialsSecret(rendered.S3) { if psmdbBackupDeadlineExceeded(j.Status.StartedAt) { return r.markBackupJobFailed(ctx, j, fmt.Sprintf( - "psmdb.percona.com/PerconaServerMongoDB %s/%s storage %q still points at the platform bucket %q with backup.useSystemBucket=false after %s; wait for the chart to re-render the application's own storage", - j.Namespace, psmdbName, storageName, bucket, psmdbDefaultBackupDeadline)) + "psmdb.percona.com/PerconaServerMongoDB %s/%s storage %q is still the entry injected for the system bucket (credentialsSecret %q) while backup.useSystemBucket=false, %s after the job started; delete that storage entry from the PerconaServerMongoDB by hand or set backup.useSystemBucket=true again (see docs/operations/backup-classes.md)", + j.Namespace, psmdbName, storageName, cred, psmdbDefaultBackupDeadline)) } return r.requeueMongoDBBackupWaiting(ctx, j, "PerconaServerMongoDBStorageStale", - fmt.Sprintf("storage %q still points at the platform bucket %q with backup.useSystemBucket=false; waiting for the chart to re-render the application's own storage", storageName, bucket)) + fmt.Sprintf("storage %q is still the entry injected for the system bucket (credentialsSecret %q) while backup.useSystemBucket=false; delete it from the PerconaServerMongoDB by hand or set backup.useSystemBucket=true again", storageName, cred)) } } @@ -351,6 +361,11 @@ func (r *BackupJobReconciler) reconcileMongoDB(ctx context.Context, j *backupsv1 if err != nil { return r.markBackupJobFailed(ctx, j, fmt.Sprintf("failed to ensure psmdb.percona.com/PerconaServerMongoDBBackup: %v", err)) } + // The flow a CR belongs to is fixed at mint time by its finalizer, not by the + // app flag a tenant can flip while the dump streams: a CR carrying + // delete-backup writes into the platform bucket whatever the flag reads now, + // and is handled as system-bucket for the rest of its life. + flowSystemBucket := controllerutil.ContainsFinalizer(mdbBackup, psmdbDeleteBackupFinalizer) if j.Status.Phase != backupsv1alpha1.BackupJobPhaseRunning { j.Status.Phase = backupsv1alpha1.BackupJobPhaseRunning @@ -414,7 +429,7 @@ func (r *BackupJobReconciler) reconcileMongoDB(ctx context.Context, j *backupsv1 default: // Still in progress ("", requested, running, waiting). if state == psmdbtypes.StateRunning { - if !psmdbBackupTimedOut(state, j.Status.StartedAt, useSystemBucket) { + if !psmdbBackupTimedOut(state, j.Status.StartedAt, flowSystemBucket) { // The wait is long by nature (a real dataset routinely outruns any // wall-clock window) and the CR carries nothing to tell a slow dump // from a wedged one: the pinned operator persists status only when the @@ -430,27 +445,41 @@ func (r *BackupJobReconciler) reconcileMongoDB(ctx context.Context, j *backupsv1 return r.requeueMongoDBBackupWaiting(ctx, j, "PerconaServerMongoDBBackupRunning", fmt.Sprintf("psmdb.percona.com PerconaServerMongoDBBackup %s has been streaming since %s; a running dump is left to finish", mdbBackup.Name, since)) } - // Legacy flow past the deadline: the archive lands in the tenant's own - // bucket under psmdb task retention, so failing the job strands nothing - // the platform owns. The operator CR is left alone, as it was before this - // driver existed — only a not-started CR is ever cancelled below. + // Legacy flow past the deadline: the archive is in the tenant's own bucket + // and is theirs to reclaim — no platform retention covers it (the + // operator prunes only its own scheduled backups, selected by ancestor + // label, which a driver-minted CR does not carry), so failing the job + // strands nothing the platform owns. The operator CR is left alone, as + // it was before this driver existed. return r.markBackupJobFailed(ctx, j, fmt.Sprintf( "psmdb.percona.com PerconaServerMongoDBBackup did not complete within %s (state=running)", psmdbDefaultBackupDeadline)) } // Not-yet-started states ("", requested, waiting). A wall-clock deadline // fails a backup the operator never starts, so it cannot pin the BackupJob // Running forever. - if !psmdbBackupTimedOut(state, j.Status.StartedAt, useSystemBucket) { + if !psmdbBackupTimedOut(state, j.Status.StartedAt, flowSystemBucket) { return ctrl.Result{RequeueAfter: psmdbPollInterval}, nil } - // The deadline hit for a not-yet-started backup. mdbBackup came from the - // cache, so re-read the CR live before cancelling: the cancel deletes a CR - // this flow finalizes with delete-backup, and the operator prunes storage on - // that finalizer once the CR is ready, so deleting anything that has already - // moved off not-started risks taking a running dump's partial or a completed - // archive with it. Require a positive not-started answer to cancel: a read - // error ("" is indistinguishable, so it returns an error) or any live state - // other than the not-started set must defer, not delete. + detail := "no state observed" + if state != "" { + detail = fmt.Sprintf("state=%s", state) + } + if !flowSystemBucket { + // Legacy flow: the CR and whatever it may still write are the tenant's, + // in the tenant's bucket. Fail the job and leave the CR, as before this + // driver existed; only a system-bucket CR is ever cancelled below. + return r.markBackupJobFailed(ctx, j, fmt.Sprintf( + "psmdb.percona.com PerconaServerMongoDBBackup did not start within %s (%s)", psmdbDefaultBackupDeadline, detail)) + } + // The deadline hit for a system-bucket backup that has not started. A late + // run would land in the shared bucket with no Backup object to represent + // it, so the CR is cancelled — but only on a positive answer that nothing + // has been handed to pbm yet. mdbBackup came from the cache, so re-read it + // live first: the CR carries delete-backup and the operator prunes storage + // on that finalizer once the CR is ready, so deleting anything that has + // moved on risks taking a running dump's partial or a completed archive + // with it. A read error ("" is indistinguishable, so the helper returns an + // error) defers rather than deletes blind. liveState, lerr := r.psmdbBackupLiveState(ctx, mdbBackup.Namespace, mdbBackup.Name) if lerr != nil { getLogger(ctx).Debug("could not re-read live backup state before cancelling; deferring rather than deleting blind", @@ -458,17 +487,23 @@ func (r *BackupJobReconciler) reconcileMongoDB(ctx context.Context, j *backupsv1 return ctrl.Result{RequeueAfter: psmdbPollInterval}, nil } switch liveState { - case "", psmdbtypes.StateRequested, psmdbtypes.StateWaiting: - // Positively not-started: nothing is written yet, safe to cancel below. + case "", psmdbtypes.StateWaiting: + // Not handed to pbm: "" means the operator has not observed the CR, + // waiting means it is queued behind another backup. At v1.22.0 the + // operator returns for a CR with a deletion timestamp before it + // dispatches, so the delete below prevents the late run. + case psmdbtypes.StateRequested: + // Dispatched: at v1.22.0 `requested` is set right after the command is + // sent to pbm, so pbm already holds it and deleting the CR cannot recall + // it — a late dump would then land with no CR to own it. Leave the CR + // (its finalizer stays the handle to whatever pbm writes) and fail. + return r.markBackupJobFailed(ctx, j, fmt.Sprintf( + "psmdb.percona.com PerconaServerMongoDBBackup did not start within %s (state=requested: already dispatched to pbm, so the operator backup is left in place)", psmdbDefaultBackupDeadline)) default: // running/ready/error/rejected — the CR moved on; let the state switch // handle it on the next reconcile instead of deleting it here. return ctrl.Result{RequeueAfter: psmdbPollInterval}, nil } - // Cancel the operator CR before failing. On the re-read not-started state - // nothing is written, and at v1.22.0 the operator returns for a CR with a - // deletion timestamp before it dispatches to pbm, so the delete prevents a - // late run into the shared bucket that no Backup object would represent. // Best-effort: a delete failure must not stop the job from failing (a // leftover CR is the pre-existing behaviour, not a regression). The terminal // Phase=Failed makes reconcileMongoDB return early next time, so @@ -479,10 +514,6 @@ func (r *BackupJobReconciler) reconcileMongoDB(ctx context.Context, j *backupsv1 "backupjob", j.Name, "sourceBackup", mdbBackup.Name, "error", derr) } } - detail := "no state observed" - if state != "" { - detail = fmt.Sprintf("state=%s", state) - } return r.markBackupJobFailed(ctx, j, fmt.Sprintf( "psmdb.percona.com PerconaServerMongoDBBackup did not start within %s (%s)", psmdbDefaultBackupDeadline, detail)) } @@ -621,6 +652,18 @@ func psmdbStorageS3(raw runtime.RawExtension) (bucket, credentialsSecret string) return st.S3.Bucket, st.S3.CredentialsSecret } +// psmdbInjectedCredentialsSecret is the Secret name the injected storage entry +// carries: the strategy's, or the platform-projected default when the strategy +// leaves it empty. It is the one field on the entry the driver chose (bucket and +// endpoint are whatever the platform bucket happens to be named or hosted at), +// so it is what identifies the driver's entry on a live cluster. +func psmdbInjectedCredentialsSecret(s3 *strategyv1alpha1.MongoDBStorageS3) string { + if s3.CredentialsSecret != "" { + return s3.CredentialsSecret + } + return psmdbDefaultCredentialsSecret +} + // shouldInjectMongoDBSystemStorage reports whether the driver must SSA-inject // the system-bucket storage onto the live cluster: only when the app opted in // via backup.useSystemBucket AND the strategy actually carries S3 coordinates @@ -640,10 +683,7 @@ func shouldInjectMongoDBSystemStorage(useSystemBucket bool, rendered *strategyv1 // forcePathStyle:false the app never chose), and the {"type":"s3","s3":{…}} // shape are exercised without a live apiserver. func buildMongoDBSystemStorageEntry(s3 *strategyv1alpha1.MongoDBStorageS3) map[string]interface{} { - cred := s3.CredentialsSecret - if cred == "" { - cred = psmdbDefaultCredentialsSecret - } + cred := psmdbInjectedCredentialsSecret(s3) s3Cfg := map[string]interface{}{ "bucket": s3.Bucket, "endpointUrl": s3.EndpointURL, @@ -709,10 +749,10 @@ func psmdbBackupDeadlineExceeded(startedAt *metav1.Time) bool { // can reach (the operator CR carries no ownerRef either). A real dataset // routinely outruns 30m, and a genuinely broken dump terminates through the // operator's own error/rejected state, so it is left to finish. On the legacy -// flow the deadline applies to `running` too: the archive lands in the tenant's -// own bucket under psmdb task retention, nothing the platform owns is stranded, -// and the pre-existing contract failed the job on the deadline while leaving -// the operator CR alone. The deadline bounds the not-yet-`running` states ("", +// flow the deadline applies to `running` too: the archive is in the tenant's +// own bucket and is theirs to reclaim (no platform retention covers it), so +// nothing the platform owns is stranded, and the pre-existing contract failed +// the job on the deadline while leaving the operator CR alone. The deadline bounds the not-yet-`running` states ("", // requested, waiting) on both flows: a backup the operator has not begun // streaming can still be advanced later — a `waiting` backup runs when the slot // frees, and `requested` is set as the operator dispatches — so the caller @@ -1257,16 +1297,32 @@ func (r *RestoreJobReconciler) reconcileMongoDBRestore(ctx context.Context, rest // into useSystemBucket the chart prunes the legacy -s3-creds while // older Backups still name it, and with no same-bucket target credential to // adopt the restore would reach the operator naming a Secret that is gone - // and die on a pbm-level message. Check here and fail with a legible one. + // and die on a pbm-level message. Like the other preconditions here (target + // absent, backups disabled) this waits until the restore deadline and only + // then fails — the Secret can be re-created. It is a hand-over check: once + // the operator restore exists the reference is the operator's, and a Secret + // pruned mid-replay is its error to report, not grounds to mark a restore + // still in progress Failed. if source.S3.CredentialsSecret != "" { - if err := r.Get(ctx, types.NamespacedName{Namespace: target.Namespace, Name: source.S3.CredentialsSecret}, &corev1.Secret{}); err != nil { - if apierrors.IsNotFound(err) { - return r.markRestoreJobFailedReason(ctx, restoreJob, "RestoreCredentialsMissing", fmt.Sprintf( - "the backup was written to bucket %q with credentialsSecret %q, which does not exist in namespace %s (the chart prunes it when the application opts into useSystemBucket); re-create a Secret by that name holding credentials for that bucket, or restore into a target whose storage declares that bucket", - source.S3.Bucket, source.S3.CredentialsSecret, target.Namespace)) - } + existingRestore, err := r.findMongoDBRestoreForJob(ctx, restoreJob) + if err != nil { return ctrl.Result{}, err } + if existingRestore == nil { + if err := r.Get(ctx, types.NamespacedName{Namespace: target.Namespace, Name: source.S3.CredentialsSecret}, &corev1.Secret{}); err != nil { + if !apierrors.IsNotFound(err) { + return ctrl.Result{}, err + } + msg := fmt.Sprintf( + "credentialsSecret %q for bucket %q does not exist in namespace %s (the chart prunes it when the application opts into useSystemBucket); re-create a Secret by that name holding credentials for that bucket, or restore into a target whose storage declares that bucket", + source.S3.CredentialsSecret, source.S3.Bucket, target.Namespace) + deadline := options.effectiveRestoreDeadline() + if restoreJob.Status.StartedAt != nil && time.Since(restoreJob.Status.StartedAt.Time) > deadline { + return r.markRestoreJobFailedReason(ctx, restoreJob, "RestoreCredentialsMissing", fmt.Sprintf("%s; not resolved within %s", msg, deadline)) + } + return r.requeueMongoDBRestoreWaiting(ctx, restoreJob, "RestoreCredentialsMissing", msg) + } + } } } @@ -1406,10 +1462,9 @@ func (r *RestoreJobReconciler) resolveMongoDBBackupSource(ctx context.Context, b return src, nil } -// ensureMongoDBRestore creates a PerconaServerMongoDBRestore CR labelled with -// the RestoreJob, or returns the existing one if a previous reconcile already -// created it. -func (r *RestoreJobReconciler) ensureMongoDBRestore(ctx context.Context, rj *backupsv1alpha1.RestoreJob, targetClusterName string, source *psmdbtypes.BackupSource, pitr *psmdbtypes.PITRSpec) (*psmdbtypes.PerconaServerMongoDBRestore, error) { +// findMongoDBRestoreForJob returns the PerconaServerMongoDBRestore labelled with +// the RestoreJob's OwningJob{Name,Namespace}, or (nil, nil) when none exists. +func (r *RestoreJobReconciler) findMongoDBRestoreForJob(ctx context.Context, rj *backupsv1alpha1.RestoreJob) (*psmdbtypes.PerconaServerMongoDBRestore, error) { list := &psmdbtypes.PerconaServerMongoDBRestoreList{} if err := r.List(ctx, list, client.InNamespace(rj.Namespace), @@ -1420,8 +1475,18 @@ func (r *RestoreJobReconciler) ensureMongoDBRestore(ctx context.Context, rj *bac ); err != nil { return nil, err } - if len(list.Items) > 0 { - return &list.Items[0], nil + if len(list.Items) == 0 { + return nil, nil + } + return &list.Items[0], nil +} + +// ensureMongoDBRestore creates a PerconaServerMongoDBRestore CR labelled with +// the RestoreJob, or returns the existing one if a previous reconcile already +// created it. +func (r *RestoreJobReconciler) ensureMongoDBRestore(ctx context.Context, rj *backupsv1alpha1.RestoreJob, targetClusterName string, source *psmdbtypes.BackupSource, pitr *psmdbtypes.PITRSpec) (*psmdbtypes.PerconaServerMongoDBRestore, error) { + if existing, err := r.findMongoDBRestoreForJob(ctx, rj); err != nil || existing != nil { + return existing, err } obj := &psmdbtypes.PerconaServerMongoDBRestore{ diff --git a/internal/backupcontroller/psmdbstrategy_controller_test.go b/internal/backupcontroller/psmdbstrategy_controller_test.go index 8909ba0bf..8ce197bd7 100644 --- a/internal/backupcontroller/psmdbstrategy_controller_test.go +++ b/internal/backupcontroller/psmdbstrategy_controller_test.go @@ -2229,6 +2229,56 @@ func TestReconcileMongoDB_TimedOutCancelUsesLiveState(t *testing.T) { t.Errorf("an unanswerable live read must not fail the BackupJob") } }) + + t.Run("live requested → fail but leave the CR (already dispatched to pbm)", func(t *testing.T) { + live := newPsmdbBackupDynamicClient(psmdbBackupUnstructured("tenant", "op-waiting", psmdbtypes.StateRequested)) + r, c, resolved, job := setup(t, live) + if _, err := r.reconcileMongoDB(context.Background(), job.DeepCopy(), resolved); err != nil { + t.Fatalf("reconcileMongoDB: %v", err) + } + if deleted(t, c) { + t.Errorf("a requested CR was already handed to pbm; deleting it cannot recall the command and would orphan the dump") + } + if !failed(t, c, job.Name) { + t.Errorf("the BackupJob must still fail on the deadline for a requested-but-never-run backup") + } + }) + + // The legacy flow keeps its hands-off contract: the deadline fails the job + // and the operator CR — the tenant's — is left in place, exactly as before + // this driver existed. No live read is consulted. + t.Run("legacy waiting past deadline → fail, CR left alone", func(t *testing.T) { + job, strategy, app, cluster, resolved := mongodbInjectFixture(true) + app.Spec.Backup.UseSystemBucket = false + strategy.Spec.Template.S3 = nil + job.Status.StartedAt = &metav1.Time{Time: time.Now().Add(-2 * psmdbDefaultBackupDeadline)} + cluster.Spec.Backup.Storages = map[string]runtime.RawExtension{ + "s3-storage": {Raw: []byte(`{"type":"s3","s3":{"bucket":"tenant-own","credentialsSecret":"mongodb-app1-s3-creds"}}`)}, + } + cached := &psmdbtypes.PerconaServerMongoDBBackup{ // no delete-backup finalizer: legacy + ObjectMeta: metav1.ObjectMeta{ + Namespace: "tenant", Name: "op-waiting", + Labels: map[string]string{ + backupsv1alpha1.OwningJobNameLabel: job.Name, + backupsv1alpha1.OwningJobNamespaceLabel: job.Namespace, + }, + }, + Status: psmdbtypes.PerconaServerMongoDBBackupStatus{State: psmdbtypes.StateWaiting}, + } + c := newMongoDBStrategyTestClient(t, job, strategy, app, cluster, cached) + // No dynamic client at all: the legacy path must not need a live read. + r := &BackupJobReconciler{Client: c, Scheme: c.Scheme(), Recorder: record.NewFakeRecorder(10)} + if _, err := r.reconcileMongoDB(context.Background(), job.DeepCopy(), resolved); err != nil { + t.Fatalf("reconcileMongoDB: %v", err) + } + if !failed(t, c, job.Name) { + t.Errorf("a legacy backup that never started must fail on the deadline") + } + got := &psmdbtypes.PerconaServerMongoDBBackup{} + if err := c.Get(context.Background(), types.NamespacedName{Namespace: "tenant", Name: "op-waiting"}, got); err != nil || !got.DeletionTimestamp.IsZero() { + t.Errorf("the legacy operator CR must be left alone (hands-off), err=%v", err) + } + }) } // PITR needs an oplog stream the useSystemBucket flow never captures, so a @@ -2421,23 +2471,80 @@ func TestReconcileMongoDBRestore_FailsNamedWhenCredentialsSecretMissing(t *testi return rj } - t.Run("missing Secret fails with a named reason", func(t *testing.T) { + getRJ := func(t *testing.T, c client.Client, name string) *backupsv1alpha1.RestoreJob { + p := &backupsv1alpha1.RestoreJob{} + if err := c.Get(context.Background(), types.NamespacedName{Namespace: "tenant", Name: name}, p); err != nil { + t.Fatalf("get restore job: %v", err) + } + return p + } + + // Like the sibling preconditions (target absent, backups disabled) the check + // waits until the restore deadline — the Secret can be re-created — naming + // the reason on the job, and only then fails. + t.Run("missing Secret waits with a named reason", func(t *testing.T) { backup, rj := newBackup(), newRJ("rj-nocred") c := newMongoDBStrategyTestClient(t, backup, rj, newTarget()) r := &RestoreJobReconciler{Client: c, Scheme: c.Scheme(), Recorder: record.NewFakeRecorder(10)} + res, err := r.reconcileMongoDBRestore(context.Background(), rj.DeepCopy(), backup) + if err != nil { + t.Fatalf("reconcileMongoDBRestore: %v", err) + } + if res.RequeueAfter == 0 { + t.Fatalf("a missing Secret within the deadline must requeue, got %+v", res) + } + p := getRJ(t, c, "rj-nocred") + if p.Status.Phase == backupsv1alpha1.RestoreJobPhaseFailed { + t.Errorf("must not fail before the restore deadline") + } + cond := apimeta.FindStatusCondition(p.Status.Conditions, "Ready") + if cond == nil || cond.Reason != "RestoreCredentialsMissing" || !strings.Contains(cond.Message, "mongodb-app1-s3-creds") { + t.Errorf("expected Ready=False RestoreCredentialsMissing naming the Secret, got %+v", cond) + } + }) + + t.Run("missing Secret past the deadline fails with the named reason", func(t *testing.T) { + backup, rj := newBackup(), newRJ("rj-nocred-late") + rj.Status.StartedAt = &metav1.Time{Time: time.Now().Add(-2 * psmdbDefaultRestoreDeadline)} + c := newMongoDBStrategyTestClient(t, backup, rj, newTarget()) + r := &RestoreJobReconciler{Client: c, Scheme: c.Scheme(), Recorder: record.NewFakeRecorder(10)} if _, err := r.reconcileMongoDBRestore(context.Background(), rj.DeepCopy(), backup); err != nil { t.Fatalf("reconcileMongoDBRestore: %v", err) } - persisted := &backupsv1alpha1.RestoreJob{} - if err := c.Get(context.Background(), types.NamespacedName{Namespace: "tenant", Name: "rj-nocred"}, persisted); err != nil { - t.Fatalf("get restore job: %v", err) + p := getRJ(t, c, "rj-nocred-late") + if p.Status.Phase != backupsv1alpha1.RestoreJobPhaseFailed { + t.Fatalf("expected Failed past the deadline, got phase=%q", p.Status.Phase) } - if persisted.Status.Phase != backupsv1alpha1.RestoreJobPhaseFailed { - t.Fatalf("a restore naming a missing credentialsSecret must fail, got phase=%q", persisted.Status.Phase) + if cond := apimeta.FindStatusCondition(p.Status.Conditions, "Ready"); cond == nil || cond.Reason != "RestoreCredentialsMissing" { + t.Errorf("expected RestoreCredentialsMissing, got %+v", cond) } - cond := apimeta.FindStatusCondition(persisted.Status.Conditions, "Ready") - if cond == nil || cond.Reason != "RestoreCredentialsMissing" || !strings.Contains(cond.Message, "mongodb-app1-s3-creds") { - t.Errorf("expected Ready=False RestoreCredentialsMissing naming the Secret, got %+v", cond) + }) + + // Once the operator restore exists the reference has been handed over; a + // Secret pruned mid-replay must not mark a restore still in progress Failed. + t.Run("an existing operator restore skips the check", func(t *testing.T) { + backup, rj := newBackup(), newRJ("rj-replaying") + inflight := &psmdbtypes.PerconaServerMongoDBRestore{ + ObjectMeta: metav1.ObjectMeta{ + Namespace: "tenant", Name: "rj-replaying-abc", + Labels: map[string]string{ + backupsv1alpha1.OwningJobNameLabel: rj.Name, + backupsv1alpha1.OwningJobNamespaceLabel: rj.Namespace, + }, + }, + Status: psmdbtypes.PerconaServerMongoDBRestoreStatus{State: psmdbtypes.StateRunning}, + } + c := newMongoDBStrategyTestClient(t, backup, rj, newTarget(), inflight) + r := &RestoreJobReconciler{Client: c, Scheme: c.Scheme(), Recorder: record.NewFakeRecorder(10)} + if _, err := r.reconcileMongoDBRestore(context.Background(), rj.DeepCopy(), backup); err != nil { + t.Fatalf("reconcileMongoDBRestore: %v", err) + } + p := getRJ(t, c, "rj-replaying") + if cond := apimeta.FindStatusCondition(p.Status.Conditions, "Ready"); cond != nil && cond.Reason == "RestoreCredentialsMissing" { + t.Errorf("a restore already replaying must not be reported as missing credentials: %+v", cond) + } + if p.Status.Phase == backupsv1alpha1.RestoreJobPhaseFailed { + t.Errorf("a restore already replaying must not be failed by the pre-check") } }) @@ -2522,4 +2629,137 @@ func TestReconcileMongoDB_OptOutRefusesStalePlatformStorage(t *testing.T) { t.Errorf("expected the BackupJob to fail once the stale storage outlives the deadline, got phase=%q", persisted.Status.Phase) } }) + + // A CR minted while the flag was true carries the delete-backup finalizer and + // is still streaming into the platform bucket; flipping the flag must not + // route later polls into the refusal and fail it at the deadline. + t.Run("a dump already in flight is not pre-empted by the refusal", func(t *testing.T) { + r, c, resolved, job := setup(t, time.Now().Add(-2*psmdbDefaultBackupDeadline)) + running := &psmdbtypes.PerconaServerMongoDBBackup{ + ObjectMeta: metav1.ObjectMeta{ + Namespace: "tenant", Name: "op-inflight", + Finalizers: []string{psmdbDeleteBackupFinalizer}, + Labels: map[string]string{ + backupsv1alpha1.OwningJobNameLabel: job.Name, + backupsv1alpha1.OwningJobNamespaceLabel: job.Namespace, + }, + }, + Status: psmdbtypes.PerconaServerMongoDBBackupStatus{State: psmdbtypes.StateRunning}, + } + if err := c.Create(context.Background(), running); err != nil { + t.Fatalf("seed in-flight CR: %v", err) + } + res, err := r.reconcileMongoDB(context.Background(), job.DeepCopy(), resolved) + if err != nil { + t.Fatalf("reconcileMongoDB: %v", err) + } + if res.RequeueAfter == 0 { + t.Fatalf("an in-flight system-bucket dump must keep polling, got %+v", res) + } + persisted := &backupsv1alpha1.BackupJob{} + if err := c.Get(context.Background(), types.NamespacedName{Namespace: "tenant", Name: job.Name}, persisted); err != nil { + t.Fatalf("get job: %v", err) + } + if persisted.Status.Phase == backupsv1alpha1.BackupJobPhaseFailed { + t.Errorf("the opt-out refusal must not fail a dump already streaming (flow comes from the CR's finalizer)") + } + cond := apimeta.FindStatusCondition(persisted.Status.Conditions, "Ready") + if cond == nil || cond.Reason != "PerconaServerMongoDBBackupRunning" { + t.Errorf("expected the running wait, not the stale-storage refusal, got %+v", cond) + } + got := &psmdbtypes.PerconaServerMongoDBBackup{} + if err := c.Get(context.Background(), types.NamespacedName{Namespace: "tenant", Name: "op-inflight"}, got); err != nil || !got.DeletionTimestamp.IsZero() { + t.Errorf("the in-flight CR must be left alone, err=%v deleted=%v", err, err == nil && !got.DeletionTimestamp.IsZero()) + } + }) + + // The injected entry is identified by its credentialsSecret, not by bucket + // name: a legacy tenant whose own bucket happens to carry the platform's name + // (external S3, admin-chosen name) must not be refused. + t.Run("a legacy storage on a same-named bucket with its own Secret is not refused", func(t *testing.T) { + job, strategy, app, cluster, resolved := mongodbInjectFixture(true) + app.Spec.Backup.UseSystemBucket = false + job.Status.StartedAt = &metav1.Time{Time: time.Now()} + cluster.Spec.Backup.Storages = map[string]runtime.RawExtension{ + "s3-storage": {Raw: []byte(`{"type":"s3","s3":{"bucket":"cozy-backups","credentialsSecret":"mongodb-app1-s3-creds"}}`)}, + } + c := newMongoDBStrategyTestClient(t, job, strategy, app, cluster) + r := &BackupJobReconciler{Client: c, Scheme: c.Scheme(), Recorder: record.NewFakeRecorder(10)} + if _, err := r.reconcileMongoDB(context.Background(), job.DeepCopy(), resolved); err != nil { + t.Fatalf("reconcileMongoDB: %v", err) + } + if n := countCRs(t, c); n != 1 { + t.Errorf("a legacy storage with the tenant's own Secret must mint normally, got %d CRs", n) + } + }) +} + +// A running dump polls through requeueMongoDBBackupWaiting for hours; the +// condition it writes is stable, so only the first reconcile may write status. +// Counts status updates on the BackupJob across two reconciles of the same +// fixture and requires exactly one. +func TestRequeueMongoDBBackupWaiting_WritesStatusOnlyOnChange(t *testing.T) { + job, strategy, app, cluster, resolved := mongodbInjectFixture(true) + job.Status.StartedAt = &metav1.Time{Time: time.Now().Add(-4 * psmdbDefaultBackupDeadline)} + cluster.Spec.Backup.Storages = map[string]runtime.RawExtension{ + "s3-storage": {Raw: []byte(`{"type":"s3","s3":{"bucket":"cozy-backups"}}`)}, + } + running := &psmdbtypes.PerconaServerMongoDBBackup{ + ObjectMeta: metav1.ObjectMeta{ + Namespace: "tenant", Name: "op-running", + Finalizers: []string{psmdbDeleteBackupFinalizer}, + Labels: map[string]string{ + backupsv1alpha1.OwningJobNameLabel: job.Name, + backupsv1alpha1.OwningJobNamespaceLabel: job.Namespace, + }, + }, + Status: psmdbtypes.PerconaServerMongoDBBackupStatus{State: psmdbtypes.StateRunning}, + } + sch := runtime.NewScheme() + _ = scheme.AddToScheme(sch) + _ = backupsv1alpha1.AddToScheme(sch) + _ = strategyv1alpha1.AddToScheme(sch) + _ = psmdbtypes.AddToScheme(sch) + _ = mongodbapp.AddToScheme(sch) + statusWrites := 0 + c := clientfake.NewClientBuilder(). + WithScheme(sch). + WithObjects(job, strategy, app, cluster, running). + WithStatusSubresource(&backupsv1alpha1.BackupJob{}). + WithInterceptorFuncs(interceptor.Funcs{ + SubResourceUpdate: func(ctx context.Context, cl client.Client, sub string, obj client.Object, opts ...client.SubResourceUpdateOption) error { + if _, ok := obj.(*backupsv1alpha1.BackupJob); ok && sub == "status" { + statusWrites++ + } + return cl.SubResource(sub).Update(ctx, obj, opts...) + }, + }). + Build() + r := &BackupJobReconciler{Client: c, Scheme: sch, Recorder: record.NewFakeRecorder(10)} + + for pass := 1; pass <= 2; pass++ { + fresh := &backupsv1alpha1.BackupJob{} + if err := c.Get(context.Background(), types.NamespacedName{Namespace: "tenant", Name: job.Name}, fresh); err != nil { + t.Fatalf("get job: %v", err) + } + if _, err := r.reconcileMongoDB(context.Background(), fresh, resolved); err != nil { + t.Fatalf("reconcileMongoDB pass %d: %v", pass, err) + } + } + // Pass 1 also flips Phase to Running (one write) and writes the condition; + // pass 2 must add nothing. + if statusWrites < 1 { + t.Fatalf("expected the first reconcile to write status, got %d writes", statusWrites) + } + first := statusWrites + fresh := &backupsv1alpha1.BackupJob{} + if err := c.Get(context.Background(), types.NamespacedName{Namespace: "tenant", Name: job.Name}, fresh); err != nil { + t.Fatalf("get job: %v", err) + } + if _, err := r.reconcileMongoDB(context.Background(), fresh, resolved); err != nil { + t.Fatalf("reconcileMongoDB pass 3: %v", err) + } + if statusWrites != first { + t.Errorf("an unchanged running wait must not write status again: %d writes before, %d after", first, statusWrites) + } } diff --git a/packages/apps/mongodb/templates/restore.yaml b/packages/apps/mongodb/templates/restore.yaml index a12d0e0c1..083a72091 100644 --- a/packages/apps/mongodb/templates/restore.yaml +++ b/packages/apps/mongodb/templates/restore.yaml @@ -1,6 +1,6 @@ {{- if .Values.bootstrap.enabled }} {{- if .Values.backup.useSystemBucket }} -{{- fail "mongodb: bootstrap.enabled=true is incompatible with backup.useSystemBucket=true. Restore from the system bucket with a backups.cozystack.io/RestoreJob against the cozy-default BackupClass; see docs/operations/backup-classes.md." }} +{{- fail "mongodb: bootstrap.enabled=true is incompatible with backup.useSystemBucket=true. bootstrap.enabled is not reset after a bootstrap restore completes, so set bootstrap.enabled=false before opting in; to restore from the system bucket use a backups.cozystack.io/RestoreJob against the cozy-default BackupClass instead. See docs/operations/backup-classes.md." }} {{- end }} {{- if not .Values.bootstrap.backupName }} {{- fail "bootstrap.backupName is required when bootstrap.enabled is true" }} diff --git a/packages/apps/mongodb/tests/restore_test.yaml b/packages/apps/mongodb/tests/restore_test.yaml index 9146c05fb..df07e5c80 100644 --- a/packages/apps/mongodb/tests/restore_test.yaml +++ b/packages/apps/mongodb/tests/restore_test.yaml @@ -71,7 +71,7 @@ tests: useSystemBucket: true asserts: - failedTemplate: - errorMessage: "mongodb: bootstrap.enabled=true is incompatible with backup.useSystemBucket=true. Restore from the system bucket with a backups.cozystack.io/RestoreJob against the cozy-default BackupClass; see docs/operations/backup-classes.md." + errorMessage: "mongodb: bootstrap.enabled=true is incompatible with backup.useSystemBucket=true. bootstrap.enabled is not reset after a bootstrap restore completes, so set bootstrap.enabled=false before opting in; to restore from the system bucket use a backups.cozystack.io/RestoreJob against the cozy-default BackupClass instead. See docs/operations/backup-classes.md." - it: fails when destinationPath is missing release: From 5e3b8c217b7cf7b0007fa462a8f029d5664a2106 Mon Sep 17 00:00:00 2001 From: Andrey Kolkov Date: Sun, 20 Sep 2026 10:54:30 +0400 Subject: [PATCH 0022/1280] fix(mongodb): refuse useSystemBucket without backup.enabled and pin the retry's flow MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The pbm agents run only when backup.enabled is true, so useSystemBucket with backups disabled renders a cluster that can never service a BackupJob, and the tenant learned that thirty minutes into the first job when the driver's precondition gave up. The chart already fails closed on the bootstrap clash; do the same here so the combination is a render-time error with the remedy in it. The storage-race retry keyed on the app flag while everything else in the state switch had moved to the flow recorded on the CR's own finalizer, and that flag term was the only thing keeping a legacy tenant's operator CR from being deleted and retried on the same operator error — with no test holding it. Key it on the CR's flow like its neighbours and pin the legacy side: the error is terminal and the CR survives. The retry matches the operator's own error wording, which is correct at the pinned crVersion and nothing else ties together: a bump that rewords it turns the retry off with the suite still green. Name the coupling at the pin and at the matcher so a bump re-checks it. Assisted-by: LLM Signed-off-by: Andrey Kolkov --- api/apps/v1alpha1/mongodb/types.go | 2 +- .../psmdbstrategy_controller.go | 7 +++- .../psmdbstrategy_controller_test.go | 40 +++++++++++++++++++ packages/apps/mongodb/README.md | 24 +++++------ packages/apps/mongodb/templates/mongodb.yaml | 9 +++++ packages/apps/mongodb/tests/mongodb_test.yaml | 17 ++++++++ packages/apps/mongodb/values.schema.json | 2 +- packages/apps/mongodb/values.yaml | 2 +- .../system/mongodb-rd/cozyrds/mongodb.yaml | 2 +- 9 files changed, 87 insertions(+), 18 deletions(-) diff --git a/api/apps/v1alpha1/mongodb/types.go b/api/apps/v1alpha1/mongodb/types.go index f0c943b14..7be6be036 100644 --- a/api/apps/v1alpha1/mongodb/types.go +++ b/api/apps/v1alpha1/mongodb/types.go @@ -84,7 +84,7 @@ type Backup struct { // Cron schedule for automated backups. Ignored when useSystemBucket is true (scheduling moves to the BackupClass Plan). // +kubebuilder:default:="0 2 * * *" Schedule string `json:"schedule,omitempty"` - // Opt-in: back up to the platform system bucket without supplying S3 credentials. The cozy-default MongoDB BackupClass injects the storage at BackupJob time; tenants do not set s3AccessKey/s3SecretKey/destinationPath/endpointURL, and backups scope to `/`. Scheduling moves to a BackupClass Plan; `schedule`, `retentionPolicy` and PITR are ignored while this is on, and this flow has no retention yet (see docs/operations/backup-classes.md). + // Opt-in: back up to the platform system bucket without supplying S3 credentials. The cozy-default MongoDB BackupClass injects the storage at BackupJob time; tenants do not set s3AccessKey/s3SecretKey/destinationPath/endpointURL, and backups scope to `/`. Scheduling moves to a BackupClass Plan; `schedule`, `retentionPolicy` and PITR are ignored while this is on, and this flow has no retention yet (see docs/operations/backup-classes.md). Requires `backup.enabled: true` (the pbm agents run on that flag); the chart refuses the combination with `enabled: false` at render time. // +kubebuilder:default:=false UseSystemBucket bool `json:"useSystemBucket,omitempty"` } diff --git a/internal/backupcontroller/psmdbstrategy_controller.go b/internal/backupcontroller/psmdbstrategy_controller.go index 882ac4bb0..bc370ac9c 100644 --- a/internal/backupcontroller/psmdbstrategy_controller.go +++ b/internal/backupcontroller/psmdbstrategy_controller.go @@ -409,7 +409,7 @@ func (r *BackupJobReconciler) reconcileMongoDB(ctx context.Context, j *backupsv1 // driver's own race, not the tenant's failure, so retry it (bounded by the // deadline) — delete the errored CR so a fresh one resolves against a // caught-up cache — rather than failing the BackupJob terminally. - if useSystemBucket && psmdbErrorIsUnresolvedStorage(message, storageName) && !psmdbBackupDeadlineExceeded(j.Status.StartedAt) { + if flowSystemBucket && psmdbErrorIsUnresolvedStorage(message, storageName) && !psmdbBackupDeadlineExceeded(j.Status.StartedAt) { if mdbBackup.DeletionTimestamp.IsZero() { if derr := r.Delete(ctx, mdbBackup); derr != nil && !apierrors.IsNotFound(derr) { return ctrl.Result{}, derr @@ -770,7 +770,10 @@ func psmdbBackupTimedOut(state string, startedAt *metav1.Time, useSystemBucket b // v1.22.0 backup reconciler sets ("unable to get storage ''") when it // reads a cluster cache that has not yet observed the driver's storage // injection. That is the residual half of the injection race, retryable rather -// than a tenant failure. +// than a tenant failure. The match is against upstream's wording at the +// operator version the chart pins (packages/apps/mongodb/templates/mongodb.yaml, +// spec.crVersion): a bump that rewords this error silently turns the retry +// off, so re-check pkg/controller/perconaservermongodbbackup/backup.go there. func psmdbErrorIsUnresolvedStorage(errMsg, storageName string) bool { return strings.Contains(errMsg, "unable to get storage") && strings.Contains(errMsg, storageName) } diff --git a/internal/backupcontroller/psmdbstrategy_controller_test.go b/internal/backupcontroller/psmdbstrategy_controller_test.go index 8ce197bd7..8fc9550e1 100644 --- a/internal/backupcontroller/psmdbstrategy_controller_test.go +++ b/internal/backupcontroller/psmdbstrategy_controller_test.go @@ -2043,6 +2043,46 @@ func TestReconcileMongoDB_StorageRaceErrorRetried(t *testing.T) { } } +// The storage-race retry is a system-bucket repair: it deletes the errored CR +// and re-mints. On the legacy flow the same operator error is the tenant's own +// storage problem and the CR is the tenant's — it must be left alone and the +// job failed terminally, never deleted and retried. +func TestReconcileMongoDB_StorageRaceErrorIsTerminalOnLegacy(t *testing.T) { + job, strategy, app, cluster, resolved := mongodbInjectFixture(true) + app.Spec.Backup.UseSystemBucket = false + strategy.Spec.Template.S3 = nil + job.Status.StartedAt = &metav1.Time{Time: time.Now()} + cluster.Spec.Backup.Storages = map[string]runtime.RawExtension{ + "s3-storage": {Raw: []byte(`{"type":"s3","s3":{"bucket":"tenant-own","credentialsSecret":"mongodb-app1-s3-creds"}}`)}, + } + errored := &psmdbtypes.PerconaServerMongoDBBackup{ // no delete-backup finalizer: legacy + ObjectMeta: metav1.ObjectMeta{ + Namespace: "tenant", Name: "op-legacy-errored", + Labels: map[string]string{ + backupsv1alpha1.OwningJobNameLabel: job.Name, + backupsv1alpha1.OwningJobNamespaceLabel: job.Namespace, + }, + }, + Status: psmdbtypes.PerconaServerMongoDBBackupStatus{State: psmdbtypes.StateError, Error: `unable to get storage "s3-storage": not found`}, + } + c := newMongoDBStrategyTestClient(t, job, strategy, app, cluster, errored) + r := &BackupJobReconciler{Client: c, Scheme: c.Scheme(), Recorder: record.NewFakeRecorder(10)} + if _, err := r.reconcileMongoDB(context.Background(), job.DeepCopy(), resolved); err != nil { + t.Fatalf("reconcileMongoDB: %v", err) + } + got := &psmdbtypes.PerconaServerMongoDBBackup{} + if err := c.Get(context.Background(), types.NamespacedName{Namespace: "tenant", Name: "op-legacy-errored"}, got); err != nil || !got.DeletionTimestamp.IsZero() { + t.Errorf("a legacy operator CR must never be deleted by the storage-race retry, err=%v", err) + } + persisted := &backupsv1alpha1.BackupJob{} + if err := c.Get(context.Background(), types.NamespacedName{Namespace: "tenant", Name: job.Name}, persisted); err != nil { + t.Fatalf("get job: %v", err) + } + if persisted.Status.Phase != backupsv1alpha1.BackupJobPhaseFailed { + t.Errorf("a legacy storage error is terminal, got phase=%q", persisted.Status.Phase) + } +} + // The retry deletes the errored CR, but its release-lock finalizer keeps it // briefly Terminating. The lookup must skip a Terminating CR so a fresh one is // minted (against a caught-up cache) rather than re-observing the same error on diff --git a/packages/apps/mongodb/README.md b/packages/apps/mongodb/README.md index 49cbdf49b..08ba25969 100644 --- a/packages/apps/mongodb/README.md +++ b/packages/apps/mongodb/README.md @@ -247,18 +247,18 @@ Releases with `external: false`, and sharded releases in any configuration, are ### Backup parameters -| Name | Description | Type | Value | -| ------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------- | ----------------------------------- | -| `backup` | Backup configuration. | `object` | `{}` | -| `backup.enabled` | Enable regular backups. | `bool` | `false` | -| `backup.useSystemBucket` | Opt-in: back up to the platform system bucket without supplying S3 credentials. The cozy-default MongoDB BackupClass injects the storage at BackupJob time; tenants do not set s3AccessKey/s3SecretKey/destinationPath/endpointURL, and backups scope to `/`. Scheduling moves to a BackupClass Plan; `schedule`, `retentionPolicy` and PITR are ignored while this is on, and this flow has no retention yet (see docs/operations/backup-classes.md). | `bool` | `false` | -| `backup.schedule` | Cron schedule for automated backups. Ignored when useSystemBucket is true (scheduling moves to the BackupClass Plan). | `string` | `0 2 * * *` | -| `backup.retentionPolicy` | Retention policy (e.g. "30d"). Ignored when useSystemBucket is true (no engine-side retention on that flow). | `string` | `30d` | -| `backup.destinationPath` | Destination path for backups (e.g. s3://bucket/path/). Ignored when useSystemBucket is true (the driver injects the platform bucket). | `string` | `s3://bucket/path/to/folder/` | -| `backup.endpointURL` | S3 endpoint URL for uploads. Ignored when useSystemBucket is true (the strategy supplies the platform endpoint). | `string` | `http://minio-gateway-service:9000` | -| `backup.insecureSkipTLSVerify` | Skip TLS verification for the S3 endpoint (self-signed, e.g. in-cluster seaweedfs). Ignored when useSystemBucket is true (the platform backupStorage knob applies instead). | `bool` | `false` | -| `backup.s3AccessKey` | Access key for S3 authentication. Ignored when useSystemBucket is true (credentials come from the projected cozy-backups-creds). | `string` | `""` | -| `backup.s3SecretKey` | Secret key for S3 authentication. Ignored when useSystemBucket is true (credentials come from the projected cozy-backups-creds). | `string` | `""` | +| Name | Description | Type | Value | +| ------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------- | ----------------------------------- | +| `backup` | Backup configuration. | `object` | `{}` | +| `backup.enabled` | Enable regular backups. | `bool` | `false` | +| `backup.useSystemBucket` | Opt-in: back up to the platform system bucket without supplying S3 credentials. The cozy-default MongoDB BackupClass injects the storage at BackupJob time; tenants do not set s3AccessKey/s3SecretKey/destinationPath/endpointURL, and backups scope to `/`. Scheduling moves to a BackupClass Plan; `schedule`, `retentionPolicy` and PITR are ignored while this is on, and this flow has no retention yet (see docs/operations/backup-classes.md). Requires `backup.enabled: true` (the pbm agents run on that flag); the chart refuses the combination with `enabled: false` at render time. | `bool` | `false` | +| `backup.schedule` | Cron schedule for automated backups. Ignored when useSystemBucket is true (scheduling moves to the BackupClass Plan). | `string` | `0 2 * * *` | +| `backup.retentionPolicy` | Retention policy (e.g. "30d"). Ignored when useSystemBucket is true (no engine-side retention on that flow). | `string` | `30d` | +| `backup.destinationPath` | Destination path for backups (e.g. s3://bucket/path/). Ignored when useSystemBucket is true (the driver injects the platform bucket). | `string` | `s3://bucket/path/to/folder/` | +| `backup.endpointURL` | S3 endpoint URL for uploads. Ignored when useSystemBucket is true (the strategy supplies the platform endpoint). | `string` | `http://minio-gateway-service:9000` | +| `backup.insecureSkipTLSVerify` | Skip TLS verification for the S3 endpoint (self-signed, e.g. in-cluster seaweedfs). Ignored when useSystemBucket is true (the platform backupStorage knob applies instead). | `bool` | `false` | +| `backup.s3AccessKey` | Access key for S3 authentication. Ignored when useSystemBucket is true (credentials come from the projected cozy-backups-creds). | `string` | `""` | +| `backup.s3SecretKey` | Secret key for S3 authentication. Ignored when useSystemBucket is true (credentials come from the projected cozy-backups-creds). | `string` | `""` | ### Bootstrap (recovery) parameters diff --git a/packages/apps/mongodb/templates/mongodb.yaml b/packages/apps/mongodb/templates/mongodb.yaml index 66e497a41..439bb978a 100644 --- a/packages/apps/mongodb/templates/mongodb.yaml +++ b/packages/apps/mongodb/templates/mongodb.yaml @@ -1,4 +1,7 @@ {{- $clusterDomain := (index .Values._cluster "cluster-domain") | default "cozy.local" }} +{{- if and .Values.backup.useSystemBucket (not .Values.backup.enabled) }} +{{- fail "mongodb: backup.useSystemBucket=true requires backup.enabled=true: the percona-backup-mongodb agents only run when backups are enabled, so this combination renders a cluster that can never service a BackupJob. Set backup.enabled=true (or drop useSystemBucket). See docs/operations/backup-classes.md." }} +{{- end }} {{- /* TLS IMPLEMENTATION NOTE — operator-managed cert-manager chain ============================================================= @@ -43,6 +46,12 @@ metadata: - percona.com/delete-psmdb-pods-in-order - percona.com/delete-psmdb-pvc spec: + {{- /* + The backup driver matches this operator's own error text ("unable to get + storage") to retry the storage-injection race; bumping crVersion must be + paired with re-checking that wording in internal/backupcontroller/ + psmdbstrategy_controller.go (psmdbErrorIsUnresolvedStorage). + */}} crVersion: 1.22.0 clusterServiceDNSSuffix: svc.{{ $clusterDomain }} secrets: diff --git a/packages/apps/mongodb/tests/mongodb_test.yaml b/packages/apps/mongodb/tests/mongodb_test.yaml index a7ac07c47..87df5a1cb 100644 --- a/packages/apps/mongodb/tests/mongodb_test.yaml +++ b/packages/apps/mongodb/tests/mongodb_test.yaml @@ -917,3 +917,20 @@ tests: value: mongod documentIndex: 1 + # useSystemBucket without backup.enabled renders a cluster that can never + # service a BackupJob (the pbm agents run on enabled alone), so the chart + # refuses it at render time instead of letting the tenant find out at the + # first BackupJob's deadline. + - it: refuses useSystemBucket without backup.enabled + release: + name: mongo-usb-off + namespace: tenant-test + set: + _cluster: + cluster-domain: cozy.local + backup: + enabled: false + useSystemBucket: true + asserts: + - failedTemplate: + errorMessage: "mongodb: backup.useSystemBucket=true requires backup.enabled=true: the percona-backup-mongodb agents only run when backups are enabled, so this combination renders a cluster that can never service a BackupJob. Set backup.enabled=true (or drop useSystemBucket). See docs/operations/backup-classes.md." diff --git a/packages/apps/mongodb/values.schema.json b/packages/apps/mongodb/values.schema.json index 90bafad64..20964db29 100644 --- a/packages/apps/mongodb/values.schema.json +++ b/packages/apps/mongodb/values.schema.json @@ -313,7 +313,7 @@ "default": "0 2 * * *" }, "useSystemBucket": { - "description": "Opt-in: back up to the platform system bucket without supplying S3 credentials. The cozy-default MongoDB BackupClass injects the storage at BackupJob time; tenants do not set s3AccessKey/s3SecretKey/destinationPath/endpointURL, and backups scope to `\u003cnamespace\u003e/\u003capplication\u003e`. Scheduling moves to a BackupClass Plan; `schedule`, `retentionPolicy` and PITR are ignored while this is on, and this flow has no retention yet (see docs/operations/backup-classes.md).", + "description": "Opt-in: back up to the platform system bucket without supplying S3 credentials. The cozy-default MongoDB BackupClass injects the storage at BackupJob time; tenants do not set s3AccessKey/s3SecretKey/destinationPath/endpointURL, and backups scope to `\u003cnamespace\u003e/\u003capplication\u003e`. Scheduling moves to a BackupClass Plan; `schedule`, `retentionPolicy` and PITR are ignored while this is on, and this flow has no retention yet (see docs/operations/backup-classes.md). Requires `backup.enabled: true` (the pbm agents run on that flag); the chart refuses the combination with `enabled: false` at render time.", "type": "boolean", "default": false } diff --git a/packages/apps/mongodb/values.yaml b/packages/apps/mongodb/values.yaml index 78012bdbc..6385e5b7d 100644 --- a/packages/apps/mongodb/values.yaml +++ b/packages/apps/mongodb/values.yaml @@ -155,7 +155,7 @@ databases: {} ## @typedef {struct} Backup - Backup configuration. ## @field {bool} enabled - Enable regular backups. -## @field {bool} [useSystemBucket] - Opt-in: back up to the platform system bucket without supplying S3 credentials. The cozy-default MongoDB BackupClass injects the storage at BackupJob time; tenants do not set s3AccessKey/s3SecretKey/destinationPath/endpointURL, and backups scope to `/`. Scheduling moves to a BackupClass Plan; `schedule`, `retentionPolicy` and PITR are ignored while this is on, and this flow has no retention yet (see docs/operations/backup-classes.md). +## @field {bool} [useSystemBucket] - Opt-in: back up to the platform system bucket without supplying S3 credentials. The cozy-default MongoDB BackupClass injects the storage at BackupJob time; tenants do not set s3AccessKey/s3SecretKey/destinationPath/endpointURL, and backups scope to `/`. Scheduling moves to a BackupClass Plan; `schedule`, `retentionPolicy` and PITR are ignored while this is on, and this flow has no retention yet (see docs/operations/backup-classes.md). Requires `backup.enabled: true` (the pbm agents run on that flag); the chart refuses the combination with `enabled: false` at render time. ## @field {string} [schedule] - Cron schedule for automated backups. Ignored when useSystemBucket is true (scheduling moves to the BackupClass Plan). ## @field {string} [retentionPolicy] - Retention policy (e.g. "30d"). Ignored when useSystemBucket is true (no engine-side retention on that flow). ## @field {string} [destinationPath] - Destination path for backups (e.g. s3://bucket/path/). Ignored when useSystemBucket is true (the driver injects the platform bucket). diff --git a/packages/system/mongodb-rd/cozyrds/mongodb.yaml b/packages/system/mongodb-rd/cozyrds/mongodb.yaml index 24961dfe9..17a0ce947 100644 --- a/packages/system/mongodb-rd/cozyrds/mongodb.yaml +++ b/packages/system/mongodb-rd/cozyrds/mongodb.yaml @@ -8,7 +8,7 @@ spec: singular: mongodb plural: mongodbs openAPISchema: |- - {"title":"Chart Values","type":"object","properties":{"replicas":{"description":"Number of MongoDB replicas in replica set.","type":"integer","default":3},"resources":{"description":"Explicit CPU and memory configuration for each MongoDB replica. When omitted, the preset defined in `resourcesPreset` is applied.","type":"object","default":{},"properties":{"cpu":{"description":"CPU available to each replica.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"memory":{"description":"Memory (RAM) available to each replica.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true}}},"resourcesPreset":{"description":"Default sizing preset used when `resources` is omitted.","type":"string","default":"t1.small","enum":["t1.nano","t1.micro","t1.small","t1.medium","t1.large","t1.xlarge","t1.2xlarge","t1.4xlarge","c1.nano","c1.micro","c1.small","c1.medium","c1.large","c1.xlarge","c1.2xlarge","c1.4xlarge","s1.nano","s1.micro","s1.small","s1.medium","s1.large","s1.xlarge","s1.2xlarge","s1.4xlarge","u1.nano","u1.micro","u1.small","u1.medium","u1.large","u1.xlarge","u1.2xlarge","u1.4xlarge","m1.nano","m1.micro","m1.small","m1.medium","m1.large","m1.xlarge","m1.2xlarge","m1.4xlarge","nano","micro","small","medium","large","xlarge","2xlarge"]},"size":{"description":"Persistent Volume Claim size available for application data.","default":"10Gi","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"storageClass":{"description":"StorageClass used to store the data.","type":"string","default":"","x-kubernetes-validations":[{"rule":"self == oldSelf","message":"storageClass is immutable"}],"x-cozystack-options":{"source":"storageclass"}},"external":{"description":"Enable external access from outside the cluster.","type":"boolean","default":false},"version":{"description":"MongoDB major version to deploy.","type":"string","default":"v8","enum":["v8","v7","v6"]},"sharding":{"description":"Enable sharded cluster mode. When disabled, deploys a replica set.","type":"boolean","default":false},"shardingConfig":{"description":"Configuration for sharded cluster mode.","type":"object","default":{},"required":["configServerSize","configServers","mongos"],"properties":{"configServerSize":{"description":"PVC size for config servers.","default":"3Gi","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"configServers":{"description":"Number of config server replicas.","type":"integer","default":3},"mongos":{"description":"Number of mongos router replicas.","type":"integer","default":2},"shards":{"description":"List of shard configurations.","type":"array","default":[{"name":"rs0","replicas":3,"size":"10Gi"}],"items":{"type":"object","required":["name","replicas","size"],"properties":{"name":{"description":"Shard name.","type":"string"},"replicas":{"description":"Number of replicas in this shard.","type":"integer"},"size":{"description":"PVC size for this shard.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true}}}}}},"users":{"description":"Users configuration map.","type":"object","default":{},"additionalProperties":{"type":"object","properties":{"password":{"description":"Password for the user (auto-generated if omitted).","type":"string"}}}},"databases":{"description":"Databases configuration map.","type":"object","default":{},"additionalProperties":{"type":"object","properties":{"roles":{"description":"Roles assigned to users.","type":"object","properties":{"admin":{"description":"List of users with admin privileges (readWrite + dbAdmin).","type":"array","items":{"type":"string"}},"readonly":{"description":"List of users with read-only privileges.","type":"array","items":{"type":"string"}}}}}}},"backup":{"description":"Backup configuration.","type":"object","default":{},"required":["enabled"],"properties":{"destinationPath":{"description":"Destination path for backups (e.g. s3://bucket/path/). Ignored when useSystemBucket is true (the driver injects the platform bucket).","type":"string","default":"s3://bucket/path/to/folder/"},"enabled":{"description":"Enable regular backups.","type":"boolean","default":false},"endpointURL":{"description":"S3 endpoint URL for uploads. Ignored when useSystemBucket is true (the strategy supplies the platform endpoint).","type":"string","default":"http://minio-gateway-service:9000"},"insecureSkipTLSVerify":{"description":"Skip TLS verification for the S3 endpoint (self-signed, e.g. in-cluster seaweedfs). Ignored when useSystemBucket is true (the platform backupStorage knob applies instead).","type":"boolean","default":false},"retentionPolicy":{"description":"Retention policy (e.g. \"30d\"). Ignored when useSystemBucket is true (no engine-side retention on that flow).","type":"string","default":"30d"},"s3AccessKey":{"description":"Access key for S3 authentication. Ignored when useSystemBucket is true (credentials come from the projected cozy-backups-creds).","type":"string","default":""},"s3SecretKey":{"description":"Secret key for S3 authentication. Ignored when useSystemBucket is true (credentials come from the projected cozy-backups-creds).","type":"string","default":""},"schedule":{"description":"Cron schedule for automated backups. Ignored when useSystemBucket is true (scheduling moves to the BackupClass Plan).","type":"string","default":"0 2 * * *"},"useSystemBucket":{"description":"Opt-in: back up to the platform system bucket without supplying S3 credentials. The cozy-default MongoDB BackupClass injects the storage at BackupJob time; tenants do not set s3AccessKey/s3SecretKey/destinationPath/endpointURL, and backups scope to `/`. Scheduling moves to a BackupClass Plan; `schedule`, `retentionPolicy` and PITR are ignored while this is on, and this flow has no retention yet (see docs/operations/backup-classes.md).","type":"boolean","default":false}}},"bootstrap":{"description":"Bootstrap configuration.","type":"object","default":{},"required":["backupName","enabled"],"properties":{"backupName":{"description":"Name of backup to restore from.","type":"string","default":""},"enabled":{"description":"Whether to restore from a backup.","type":"boolean","default":false},"recoveryTime":{"description":"Timestamp for point-in-time recovery; empty means latest.","type":"string","default":""}}}}} + {"title":"Chart Values","type":"object","properties":{"replicas":{"description":"Number of MongoDB replicas in replica set.","type":"integer","default":3},"resources":{"description":"Explicit CPU and memory configuration for each MongoDB replica. When omitted, the preset defined in `resourcesPreset` is applied.","type":"object","default":{},"properties":{"cpu":{"description":"CPU available to each replica.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"memory":{"description":"Memory (RAM) available to each replica.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true}}},"resourcesPreset":{"description":"Default sizing preset used when `resources` is omitted.","type":"string","default":"t1.small","enum":["t1.nano","t1.micro","t1.small","t1.medium","t1.large","t1.xlarge","t1.2xlarge","t1.4xlarge","c1.nano","c1.micro","c1.small","c1.medium","c1.large","c1.xlarge","c1.2xlarge","c1.4xlarge","s1.nano","s1.micro","s1.small","s1.medium","s1.large","s1.xlarge","s1.2xlarge","s1.4xlarge","u1.nano","u1.micro","u1.small","u1.medium","u1.large","u1.xlarge","u1.2xlarge","u1.4xlarge","m1.nano","m1.micro","m1.small","m1.medium","m1.large","m1.xlarge","m1.2xlarge","m1.4xlarge","nano","micro","small","medium","large","xlarge","2xlarge"]},"size":{"description":"Persistent Volume Claim size available for application data.","default":"10Gi","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"storageClass":{"description":"StorageClass used to store the data.","type":"string","default":"","x-kubernetes-validations":[{"rule":"self == oldSelf","message":"storageClass is immutable"}],"x-cozystack-options":{"source":"storageclass"}},"external":{"description":"Enable external access from outside the cluster.","type":"boolean","default":false},"version":{"description":"MongoDB major version to deploy.","type":"string","default":"v8","enum":["v8","v7","v6"]},"sharding":{"description":"Enable sharded cluster mode. When disabled, deploys a replica set.","type":"boolean","default":false},"shardingConfig":{"description":"Configuration for sharded cluster mode.","type":"object","default":{},"required":["configServerSize","configServers","mongos"],"properties":{"configServerSize":{"description":"PVC size for config servers.","default":"3Gi","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"configServers":{"description":"Number of config server replicas.","type":"integer","default":3},"mongos":{"description":"Number of mongos router replicas.","type":"integer","default":2},"shards":{"description":"List of shard configurations.","type":"array","default":[{"name":"rs0","replicas":3,"size":"10Gi"}],"items":{"type":"object","required":["name","replicas","size"],"properties":{"name":{"description":"Shard name.","type":"string"},"replicas":{"description":"Number of replicas in this shard.","type":"integer"},"size":{"description":"PVC size for this shard.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true}}}}}},"users":{"description":"Users configuration map.","type":"object","default":{},"additionalProperties":{"type":"object","properties":{"password":{"description":"Password for the user (auto-generated if omitted).","type":"string"}}}},"databases":{"description":"Databases configuration map.","type":"object","default":{},"additionalProperties":{"type":"object","properties":{"roles":{"description":"Roles assigned to users.","type":"object","properties":{"admin":{"description":"List of users with admin privileges (readWrite + dbAdmin).","type":"array","items":{"type":"string"}},"readonly":{"description":"List of users with read-only privileges.","type":"array","items":{"type":"string"}}}}}}},"backup":{"description":"Backup configuration.","type":"object","default":{},"required":["enabled"],"properties":{"destinationPath":{"description":"Destination path for backups (e.g. s3://bucket/path/). Ignored when useSystemBucket is true (the driver injects the platform bucket).","type":"string","default":"s3://bucket/path/to/folder/"},"enabled":{"description":"Enable regular backups.","type":"boolean","default":false},"endpointURL":{"description":"S3 endpoint URL for uploads. Ignored when useSystemBucket is true (the strategy supplies the platform endpoint).","type":"string","default":"http://minio-gateway-service:9000"},"insecureSkipTLSVerify":{"description":"Skip TLS verification for the S3 endpoint (self-signed, e.g. in-cluster seaweedfs). Ignored when useSystemBucket is true (the platform backupStorage knob applies instead).","type":"boolean","default":false},"retentionPolicy":{"description":"Retention policy (e.g. \"30d\"). Ignored when useSystemBucket is true (no engine-side retention on that flow).","type":"string","default":"30d"},"s3AccessKey":{"description":"Access key for S3 authentication. Ignored when useSystemBucket is true (credentials come from the projected cozy-backups-creds).","type":"string","default":""},"s3SecretKey":{"description":"Secret key for S3 authentication. Ignored when useSystemBucket is true (credentials come from the projected cozy-backups-creds).","type":"string","default":""},"schedule":{"description":"Cron schedule for automated backups. Ignored when useSystemBucket is true (scheduling moves to the BackupClass Plan).","type":"string","default":"0 2 * * *"},"useSystemBucket":{"description":"Opt-in: back up to the platform system bucket without supplying S3 credentials. The cozy-default MongoDB BackupClass injects the storage at BackupJob time; tenants do not set s3AccessKey/s3SecretKey/destinationPath/endpointURL, and backups scope to `/`. Scheduling moves to a BackupClass Plan; `schedule`, `retentionPolicy` and PITR are ignored while this is on, and this flow has no retention yet (see docs/operations/backup-classes.md). Requires `backup.enabled: true` (the pbm agents run on that flag); the chart refuses the combination with `enabled: false` at render time.","type":"boolean","default":false}}},"bootstrap":{"description":"Bootstrap configuration.","type":"object","default":{},"required":["backupName","enabled"],"properties":{"backupName":{"description":"Name of backup to restore from.","type":"string","default":""},"enabled":{"description":"Whether to restore from a backup.","type":"boolean","default":false},"recoveryTime":{"description":"Timestamp for point-in-time recovery; empty means latest.","type":"string","default":""}}}}} release: prefix: mongodb- labels: From f004b35fb4267fdfc55b77083605634801ecee5a Mon Sep 17 00:00:00 2001 From: Andrey Kolkov Date: Sun, 20 Sep 2026 12:06:50 +0400 Subject: [PATCH 0023/1280] fix(mongodb): record the CR's flow on the artifact and bound the two open loops Reading a backup's flow off its CR's finalizer had reached the state switch but not the artifact: the snapshot was still written from the app flag, re-read on the completing reconcile. A flag flipped to false while a system-bucket dump streamed produced a Backup whose snapshot called a cozy-backups archive legacy, so the point-in-time refusal and the S3 backfill both switched off for it. The artifact now takes the same flow the switch does, pinned by a test that flips the flag between mint and completion. Two waits had no upper bound. A live-state read that kept failing at the deadline deferred every poll behind a debug line with no condition, so an unreadable CR pinned the job Running with nothing to act on; it is now a named wait and fails after a grace, with the CR left in place rather than deleted blind. The storage-race retry minted a fresh operator CR per poll while the previous ones terminated, for the whole deadline; it now stops after a small budget and surfaces the operator's error. On useSystemBucket the chart already guarantees backup.enabled, so a strategy without s3 coordinates failed with a remedy the tenant had in place; the wait names the missing coordinates instead. The missing-credentials message no longer blames useSystemBucket on a release that never enabled it. Assisted-by: LLM Signed-off-by: Andrey Kolkov --- .../psmdbstrategy_controller.go | 83 ++++++++-- .../psmdbstrategy_controller_test.go | 156 +++++++++++++++++- 2 files changed, 223 insertions(+), 16 deletions(-) diff --git a/internal/backupcontroller/psmdbstrategy_controller.go b/internal/backupcontroller/psmdbstrategy_controller.go index bc370ac9c..c7bc46f49 100644 --- a/internal/backupcontroller/psmdbstrategy_controller.go +++ b/internal/backupcontroller/psmdbstrategy_controller.go @@ -100,6 +100,19 @@ const ( // terminate. Tenants override via spec.options.restoreTimeoutSeconds. psmdbDefaultRestoreDeadline = 30 * time.Minute + // psmdbLiveReadGrace bounds how long past the backup deadline the driver keeps + // deferring a cancel it cannot confirm: the live re-read of the operator CR + // keeps failing (throttle, revoked verb, removed CRD). After it the job fails + // and the CR is left in place rather than deleted blind. + psmdbLiveReadGrace = 30 * time.Minute + + // psmdbStorageRaceRetryBudget caps how many operator CRs the storage-race + // retry may mint for one BackupJob. Each retry deletes the errored CR and + // mints a fresh one; the race clears after a poll or two on a healthy + // operator, so a job still hitting it after this many attempts has a + // standing problem the tenant must see rather than a churn of CRs. + psmdbStorageRaceRetryBudget = 3 + // psmdbBackupSnapshotKind is the Kind stamped onto the snapshot persisted // in Backup.status.underlyingResources. It carries the S3 storage // descriptor (by reference — bucket/endpoint/credentialsSecret NAME, never @@ -320,12 +333,20 @@ func (r *BackupJobReconciler) reconcileMongoDB(ctx context.Context, j *backupsv1 } } if msg := psmdbBackupPrecondition(cluster, storageName); msg != "" { + // On useSystemBucket the chart refuses backup.enabled=false at render, so + // a missing storage there means the strategy carried no s3 coordinates to + // inject — name that, not a remedy the tenant already has in place. + reason, hint := "PerconaServerMongoDBBackupsDisabled", "set backup.enabled=true on the MongoDB application" + if useSystemBucket && rendered.S3 == nil { + reason, hint = "MongoDBStrategyHasNoS3", "the MongoDB strategy carries no s3 coordinates to inject; set spec.template.s3 on it" + msg = fmt.Sprintf("%s (%s)", msg, hint) + } if psmdbBackupDeadlineExceeded(j.Status.StartedAt) { return r.markBackupJobFailed(ctx, j, fmt.Sprintf( - "psmdb.percona.com/PerconaServerMongoDB %s/%s not ready for backups within %s: %s (set backup.enabled=true on the MongoDB application)", - j.Namespace, psmdbName, psmdbDefaultBackupDeadline, msg)) + "psmdb.percona.com/PerconaServerMongoDB %s/%s not ready for backups within %s: %s (%s)", + j.Namespace, psmdbName, psmdbDefaultBackupDeadline, msg, hint)) } - return r.requeueMongoDBBackupWaiting(ctx, j, "PerconaServerMongoDBBackupsDisabled", msg) + return r.requeueMongoDBBackupWaiting(ctx, j, reason, msg) } // Opting out (useSystemBucket true→false) stops the injection but leaves the @@ -382,7 +403,7 @@ func (r *BackupJobReconciler) reconcileMongoDB(ctx context.Context, j *backupsv1 if j.Status.BackupRef != nil { return ctrl.Result{}, nil } - artifact, err := r.createMongoDBBackupArtifact(ctx, j, resolved, mdbBackup, rendered, storageName, useSystemBucket) + artifact, err := r.createMongoDBBackupArtifact(ctx, j, resolved, mdbBackup, rendered, storageName, flowSystemBucket) if err != nil { return r.markBackupJobFailed(ctx, j, fmt.Sprintf("failed to create Backup artifact: %v", err)) } @@ -410,13 +431,23 @@ func (r *BackupJobReconciler) reconcileMongoDB(ctx context.Context, j *backupsv1 // deadline) — delete the errored CR so a fresh one resolves against a // caught-up cache — rather than failing the BackupJob terminally. if flowSystemBucket && psmdbErrorIsUnresolvedStorage(message, storageName) && !psmdbBackupDeadlineExceeded(j.Status.StartedAt) { - if mdbBackup.DeletionTimestamp.IsZero() { - if derr := r.Delete(ctx, mdbBackup); derr != nil && !apierrors.IsNotFound(derr) { - return ctrl.Result{}, derr - } + // Every retry leaves the previous CR Terminating and mints another, so + // count all of this job's CRs (not just the live one) against the budget; + // once it is spent the error is the tenant's to see, below. + minted, err := r.countMongoDBBackupsForJob(ctx, j) + if err != nil { + return ctrl.Result{}, err } - return r.requeueMongoDBBackupWaiting(ctx, j, "PerconaServerMongoDBStorageRace", - fmt.Sprintf("operator has not observed the injected storage %q yet; retrying the backup", storageName)) + if minted < psmdbStorageRaceRetryBudget { + if mdbBackup.DeletionTimestamp.IsZero() { + if derr := r.Delete(ctx, mdbBackup); derr != nil && !apierrors.IsNotFound(derr) { + return ctrl.Result{}, derr + } + } + return r.requeueMongoDBBackupWaiting(ctx, j, "PerconaServerMongoDBStorageRace", + fmt.Sprintf("operator has not observed the injected storage %q yet; retrying the backup (attempt %d of %d)", storageName, minted, psmdbStorageRaceRetryBudget)) + } + message = fmt.Sprintf("%s (the operator still could not resolve the injected storage after %d attempts)", message, psmdbStorageRaceRetryBudget) } // Terminal failure. The operator sets state=error/rejected once the pbm // backup fails or is refused, so fail the BackupJob immediately rather @@ -482,9 +513,16 @@ func (r *BackupJobReconciler) reconcileMongoDB(ctx context.Context, j *backupsv1 // error) defers rather than deletes blind. liveState, lerr := r.psmdbBackupLiveState(ctx, mdbBackup.Namespace, mdbBackup.Name) if lerr != nil { - getLogger(ctx).Debug("could not re-read live backup state before cancelling; deferring rather than deleting blind", - "backupjob", j.Name, "sourceBackup", mdbBackup.Name, "error", lerr) - return ctrl.Result{RequeueAfter: psmdbPollInterval}, nil + // Deferring is the safe default, but not forever: past the grace the + // job fails with the CR left in place (never deleted blind), so an + // unreadable CR cannot pin the job Running with nothing to act on. + if j.Status.StartedAt != nil && time.Since(j.Status.StartedAt.Time) > psmdbDefaultBackupDeadline+psmdbLiveReadGrace { + return r.markBackupJobFailed(ctx, j, fmt.Sprintf( + "psmdb.percona.com PerconaServerMongoDBBackup %s did not start within %s and its live state could not be confirmed for a further %s (%v); the operator backup is left in place", + mdbBackup.Name, psmdbDefaultBackupDeadline, psmdbLiveReadGrace, lerr)) + } + return r.requeueMongoDBBackupWaiting(ctx, j, "PerconaServerMongoDBLiveStateUnknown", + fmt.Sprintf("backup %s passed the start deadline but its live state could not be read (%v); not cancelling blind", mdbBackup.Name, lerr)) } switch liveState { case "", psmdbtypes.StateWaiting: @@ -850,6 +888,23 @@ func (r *BackupJobReconciler) ensureMongoDBBackup(ctx context.Context, j *backup return obj, nil } +// countMongoDBBackupsForJob counts every PerconaServerMongoDBBackup carrying +// the BackupJob's OwningJob labels, Terminating ones included — the retry +// budget is about how many CRs a job has minted, not how many are still live. +func (r *BackupJobReconciler) countMongoDBBackupsForJob(ctx context.Context, j *backupsv1alpha1.BackupJob) (int, error) { + list := &psmdbtypes.PerconaServerMongoDBBackupList{} + if err := r.List(ctx, list, + client.InNamespace(j.Namespace), + client.MatchingLabels{ + backupsv1alpha1.OwningJobNameLabel: j.Name, + backupsv1alpha1.OwningJobNamespaceLabel: j.Namespace, + }, + ); err != nil { + return 0, err + } + return len(list.Items), nil +} + // findMongoDBBackupForJob returns the PerconaServerMongoDBBackup labelled with // the BackupJob's OwningJob{Name,Namespace}, if any. Returns (nil, nil) when no // match is found. See the MariaDB driver's findMariaDBBackupForJob for the @@ -1317,7 +1372,7 @@ func (r *RestoreJobReconciler) reconcileMongoDBRestore(ctx context.Context, rest return ctrl.Result{}, err } msg := fmt.Sprintf( - "credentialsSecret %q for bucket %q does not exist in namespace %s (the chart prunes it when the application opts into useSystemBucket); re-create a Secret by that name holding credentials for that bucket, or restore into a target whose storage declares that bucket", + "credentialsSecret %q for bucket %q does not exist in namespace %s (a release's -s3-creds goes away with the release, or when it opts into useSystemBucket); re-create a Secret by that name holding credentials for that bucket, or restore into a target whose storage declares that bucket", source.S3.CredentialsSecret, source.S3.Bucket, target.Namespace) deadline := options.effectiveRestoreDeadline() if restoreJob.Status.StartedAt != nil && time.Since(restoreJob.Status.StartedAt.Time) > deadline { diff --git a/internal/backupcontroller/psmdbstrategy_controller_test.go b/internal/backupcontroller/psmdbstrategy_controller_test.go index 8fc9550e1..a13ee8523 100644 --- a/internal/backupcontroller/psmdbstrategy_controller_test.go +++ b/internal/backupcontroller/psmdbstrategy_controller_test.go @@ -2174,7 +2174,8 @@ func newPsmdbBackupDynamicClient(objs ...*unstructured.Unstructured) *dynamicfak func TestReconcileMongoDB_TimedOutCancelUsesLiveState(t *testing.T) { setup := func(t *testing.T, live *dynamicfake.FakeDynamicClient) (*BackupJobReconciler, client.Client, *ResolvedBackupConfig, *backupsv1alpha1.BackupJob) { job, strategy, app, cluster, resolved := mongodbInjectFixture(true) - job.Status.StartedAt = &metav1.Time{Time: time.Now().Add(-2 * psmdbDefaultBackupDeadline)} + // Past the deadline but inside the live-read grace. + job.Status.StartedAt = &metav1.Time{Time: time.Now().Add(-psmdbDefaultBackupDeadline - psmdbLiveReadGrace/2)} cluster.Spec.Backup.Storages = map[string]runtime.RawExtension{ "s3-storage": {Raw: []byte(`{"type":"s3","s3":{"bucket":"cozy-backups"}}`)}, } @@ -2266,7 +2267,31 @@ func TestReconcileMongoDB_TimedOutCancelUsesLiveState(t *testing.T) { t.Errorf("an unanswerable live read must defer, not delete blind") } if failed(t, c, job.Name) { - t.Errorf("an unanswerable live read must not fail the BackupJob") + t.Errorf("an unanswerable live read must not fail the BackupJob inside the grace") + } + p := &backupsv1alpha1.BackupJob{} + if err := c.Get(context.Background(), types.NamespacedName{Namespace: "tenant", Name: job.Name}, p); err != nil { + t.Fatalf("get job: %v", err) + } + if cond := apimeta.FindStatusCondition(p.Status.Conditions, "Ready"); cond == nil || cond.Reason != "PerconaServerMongoDBLiveStateUnknown" { + t.Errorf("the deferral must be named on the job (Ready=False PerconaServerMongoDBLiveStateUnknown), got %+v", cond) + } + }) + + // Deferring cannot be forever: once the grace past the deadline is spent the + // job fails, and the CR is still not deleted blind. + t.Run("live read still unanswerable past the grace → fail, CR left alone", func(t *testing.T) { + live := newPsmdbBackupDynamicClient() + r, c, resolved, job := setup(t, live) + job.Status.StartedAt = &metav1.Time{Time: time.Now().Add(-2*psmdbDefaultBackupDeadline - psmdbLiveReadGrace)} + if _, err := r.reconcileMongoDB(context.Background(), job.DeepCopy(), resolved); err != nil { + t.Fatalf("reconcileMongoDB: %v", err) + } + if deleted(t, c) { + t.Errorf("an unconfirmed CR must never be deleted blind, even when the job finally fails") + } + if !failed(t, c, job.Name) { + t.Errorf("an unreadable CR must not pin the BackupJob Running forever; expected Failed past the grace") } }) @@ -2803,3 +2828,130 @@ func TestRequeueMongoDBBackupWaiting_WritesStatusOnlyOnChange(t *testing.T) { t.Errorf("an unchanged running wait must not write status again: %d writes before, %d after", first, statusWrites) } } + +// The flow a backup ran on is fixed at mint time by its CR's finalizer, and the +// artifact must record that — not the app flag re-read on the completing +// reconcile. Flip the flag to false while the system-bucket dump completes: the +// snapshot must still say useSystemBucket, or the PITR refusal and the S3 +// backfill both switch off for an archive that lives in cozy-backups. +func TestReconcileMongoDB_ArtifactRecordsTheCRsFlowNotTheFlag(t *testing.T) { + job, strategy, app, cluster, resolved := mongodbInjectFixture(true) + app.Spec.Backup.UseSystemBucket = false // flipped after the mint + job.Status.StartedAt = &metav1.Time{Time: time.Now()} + cluster.Spec.Backup.Storages = map[string]runtime.RawExtension{ + "s3-storage": {Raw: []byte(`{"type":"s3","s3":{"bucket":"cozy-backups","credentialsSecret":"cozy-backups-creds"}}`)}, + } + ready := &psmdbtypes.PerconaServerMongoDBBackup{ + ObjectMeta: metav1.ObjectMeta{ + Namespace: "tenant", Name: "op-ready", + Finalizers: []string{psmdbDeleteBackupFinalizer}, // minted on the system-bucket flow + Labels: map[string]string{ + backupsv1alpha1.OwningJobNameLabel: job.Name, + backupsv1alpha1.OwningJobNamespaceLabel: job.Namespace, + }, + }, + Status: psmdbtypes.PerconaServerMongoDBBackupStatus{ + State: psmdbtypes.StateReady, + Destination: "s3://cozy-backups/tenant/app1/2026-09-20", + S3: &psmdbtypes.BackupStorageS3{Bucket: "cozy-backups", CredentialsSecret: psmdbDefaultCredentialsSecret}, + }, + } + c := newMongoDBStrategyTestClient(t, job, strategy, app, cluster, ready) + r := &BackupJobReconciler{Client: c, Scheme: c.Scheme(), Recorder: record.NewFakeRecorder(10)} + if _, err := r.reconcileMongoDB(context.Background(), job.DeepCopy(), resolved); err != nil { + t.Fatalf("reconcileMongoDB: %v", err) + } + persisted := &backupsv1alpha1.BackupJob{} + if err := c.Get(context.Background(), types.NamespacedName{Namespace: "tenant", Name: job.Name}, persisted); err != nil { + t.Fatalf("get job: %v", err) + } + if persisted.Status.BackupRef == nil { + t.Fatalf("expected a Backup artifact, got phase=%q conditions=%+v", persisted.Status.Phase, persisted.Status.Conditions) + } + artifact := &backupsv1alpha1.Backup{} + if err := c.Get(context.Background(), types.NamespacedName{Namespace: "tenant", Name: persisted.Status.BackupRef.Name}, artifact); err != nil { + t.Fatalf("get artifact: %v", err) + } + snap, err := unmarshalMongoDBBackupSnapshot(artifact.Status.UnderlyingResources) + if err != nil || snap == nil { + t.Fatalf("snapshot: %v (%+v)", err, snap) + } + if !snap.UseSystemBucket { + t.Errorf("the snapshot must record the flow the CR ran on (useSystemBucket), not the app flag re-read at completion") + } +} + +// On useSystemBucket the chart refuses backup.enabled=false, so a missing storage +// means the strategy carried nothing to inject; the wait must say that rather +// than send the tenant to a value they already have set. +func TestReconcileMongoDB_StrategyWithoutS3NamesTheCause(t *testing.T) { + job, strategy, app, cluster, resolved := mongodbInjectFixture(true) + strategy.Spec.Template.S3 = nil + job.Status.StartedAt = &metav1.Time{Time: time.Now()} + c := newMongoDBStrategyTestClient(t, job, strategy, app, cluster) + r := &BackupJobReconciler{Client: c, Scheme: c.Scheme(), Recorder: record.NewFakeRecorder(10)} + if _, err := r.reconcileMongoDB(context.Background(), job.DeepCopy(), resolved); err != nil { + t.Fatalf("reconcileMongoDB: %v", err) + } + persisted := &backupsv1alpha1.BackupJob{} + if err := c.Get(context.Background(), types.NamespacedName{Namespace: "tenant", Name: job.Name}, persisted); err != nil { + t.Fatalf("get job: %v", err) + } + cond := apimeta.FindStatusCondition(persisted.Status.Conditions, "Ready") + if cond == nil || cond.Reason != "MongoDBStrategyHasNoS3" || !strings.Contains(cond.Message, "no s3 coordinates") { + t.Errorf("expected Ready=False MongoDBStrategyHasNoS3 naming the missing coordinates, got %+v", cond) + } +} + +// The storage-race retry mints a fresh operator CR per attempt; it must stop +// after the budget instead of churning CRs every poll for the whole deadline, +// and the error then reaches the tenant. +func TestReconcileMongoDB_StorageRaceRetryBudgetExhausted(t *testing.T) { + job, strategy, app, cluster, resolved := mongodbInjectFixture(true) + job.Status.StartedAt = &metav1.Time{Time: time.Now()} + cluster.Spec.Backup.Storages = map[string]runtime.RawExtension{ + "s3-storage": {Raw: []byte(`{"type":"s3","s3":{"bucket":"cozy-backups","credentialsSecret":"cozy-backups-creds"}}`)}, + } + mk := func(name string) *psmdbtypes.PerconaServerMongoDBBackup { + return &psmdbtypes.PerconaServerMongoDBBackup{ + ObjectMeta: metav1.ObjectMeta{ + Namespace: "tenant", Name: name, Finalizers: []string{psmdbDeleteBackupFinalizer}, + Labels: map[string]string{ + backupsv1alpha1.OwningJobNameLabel: job.Name, + backupsv1alpha1.OwningJobNamespaceLabel: job.Namespace, + }, + }, + Status: psmdbtypes.PerconaServerMongoDBBackupStatus{State: psmdbtypes.StateError, Error: `unable to get storage "s3-storage": not found`}, + } + } + old1, old2, live := mk("op-try-1"), mk("op-try-2"), mk("op-try-3") + c := newMongoDBStrategyTestClient(t, job, strategy, app, cluster, old1, old2, live) + // Two earlier attempts already deleted (Terminating under the finalizer). + for _, o := range []*psmdbtypes.PerconaServerMongoDBBackup{old1, old2} { + if err := c.Delete(context.Background(), o); err != nil { + t.Fatalf("delete %s: %v", o.Name, err) + } + } + r := &BackupJobReconciler{Client: c, Scheme: c.Scheme(), Recorder: record.NewFakeRecorder(10)} + if _, err := r.reconcileMongoDB(context.Background(), job.DeepCopy(), resolved); err != nil { + t.Fatalf("reconcileMongoDB: %v", err) + } + persisted := &backupsv1alpha1.BackupJob{} + if err := c.Get(context.Background(), types.NamespacedName{Namespace: "tenant", Name: job.Name}, persisted); err != nil { + t.Fatalf("get job: %v", err) + } + if persisted.Status.Phase != backupsv1alpha1.BackupJobPhaseFailed { + t.Fatalf("with the retry budget spent the job must fail, got phase=%q", persisted.Status.Phase) + } + got := &psmdbtypes.PerconaServerMongoDBBackup{} + if err := c.Get(context.Background(), types.NamespacedName{Namespace: "tenant", Name: "op-try-3"}, got); err != nil || !got.DeletionTimestamp.IsZero() { + t.Errorf("the terminal path must not delete the live errored CR, err=%v", err) + } + list := &psmdbtypes.PerconaServerMongoDBBackupList{} + if err := c.List(context.Background(), list, client.InNamespace("tenant")); err != nil { + t.Fatalf("list: %v", err) + } + if len(list.Items) != 3 { + t.Errorf("no further CR may be minted once the budget is spent, got %d", len(list.Items)) + } +} From 8849aa13defcc707d7f7642932150a78e82b32b5 Mon Sep 17 00:00:00 2001 From: Andrey Kolkov Date: Sun, 20 Sep 2026 13:03:30 +0400 Subject: [PATCH 0024/1280] fix(mongodb): keep a completed archive reachable and a legacy Backup unblocked MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Once the operator CR is ready the archive exists, and the Backup object is the only thing that can ever reach it again. A transient failure creating that object (etcd timeout, quota, webhook) failed the job terminally with no artifact, and the terminal-phase guard stopped any retry, so the dump sat in the shared bucket with nothing to reclaim it. The failure is now retried with backoff for a window after the dump completed, and when it does give up the job names the operator CR that still holds the archive. Cleanup read the operator CR before deciding whether the Backup owned anything, so a legacy Backup — an unconditional no-op before this driver — could be held Terminating by a throttle or a revoked verb on a CR the driver never owned. The snapshot records the flow, so a legacy Backup now releases before any apiserver read; a missing or undecodable snapshot still falls through to the read. The opt-out refusal recognised the lingering injected entry only by the strategy's current credentialsSecret and only while the strategy still carried s3, so a platform change to the strategy after a tenant opted out let a legacy CR be minted onto the platform bucket. The platform default Secret name is now recognised as well, independent of the strategy's current block. Assisted-by: LLM Signed-off-by: Andrey Kolkov --- .../psmdbstrategy_controller.go | 55 +++++- .../psmdbstrategy_controller_test.go | 158 ++++++++++++++++++ 2 files changed, 210 insertions(+), 3 deletions(-) diff --git a/internal/backupcontroller/psmdbstrategy_controller.go b/internal/backupcontroller/psmdbstrategy_controller.go index c7bc46f49..ad47844d3 100644 --- a/internal/backupcontroller/psmdbstrategy_controller.go +++ b/internal/backupcontroller/psmdbstrategy_controller.go @@ -366,8 +366,8 @@ func (r *BackupJobReconciler) reconcileMongoDB(ctx context.Context, j *backupsv1 if err != nil { return ctrl.Result{}, err } - if existing == nil && !useSystemBucket && rendered.S3 != nil { - if _, cred := psmdbStorageS3(cluster.Spec.Backup.Storages[storageName]); cred != "" && cred == psmdbInjectedCredentialsSecret(rendered.S3) { + if existing == nil && !useSystemBucket { + if _, cred := psmdbStorageS3(cluster.Spec.Backup.Storages[storageName]); cred != "" && psmdbCredentialsSecretIsInjected(cred, rendered) { if psmdbBackupDeadlineExceeded(j.Status.StartedAt) { return r.markBackupJobFailed(ctx, j, fmt.Sprintf( "psmdb.percona.com/PerconaServerMongoDB %s/%s storage %q is still the entry injected for the system bucket (credentialsSecret %q) while backup.useSystemBucket=false, %s after the job started; delete that storage entry from the PerconaServerMongoDB by hand or set backup.useSystemBucket=true again (see docs/operations/backup-classes.md)", @@ -405,7 +405,21 @@ func (r *BackupJobReconciler) reconcileMongoDB(ctx context.Context, j *backupsv1 } artifact, err := r.createMongoDBBackupArtifact(ctx, j, resolved, mdbBackup, rendered, storageName, flowSystemBucket) if err != nil { - return r.markBackupJobFailed(ctx, j, fmt.Sprintf("failed to create Backup artifact: %v", err)) + // The archive is already written; the Backup object is the only thing + // that can ever reach it again. A transient Create failure (etcd + // timeout, quota, webhook hiccup) must not turn that into a terminal + // Failed with no artifact, so retry with backoff for a window after + // the dump completed — the SSA-apply error above gets the same + // treatment — and only then give up, naming the CR that still holds + // the archive so it can be reclaimed by hand. + if !psmdbArtifactWindowExceeded(mdbBackup, j.Status.StartedAt) { + return ctrl.Result{}, err + } + if r.Recorder != nil && flowSystemBucket { + r.Recorder.Eventf(j, corev1.EventTypeWarning, "BackupArtifactNotCreated", + "the dump completed but no Backup object could be created (%v); the archive is reachable only through PerconaServerMongoDBBackup %s, which is left in place", err, mdbBackup.Name) + } + return r.markBackupJobFailed(ctx, j, fmt.Sprintf("failed to create Backup artifact for %s after retrying for %s: %v", mdbBackup.Name, psmdbLiveReadGrace, err)) } now := metav1.Now() j.Status.BackupRef = &corev1.LocalObjectReference{Name: artifact.Name} @@ -702,6 +716,19 @@ func psmdbInjectedCredentialsSecret(s3 *strategyv1alpha1.MongoDBStorageS3) strin return psmdbDefaultCredentialsSecret } +// psmdbCredentialsSecretIsInjected reports whether a live storage entry's +// credentialsSecret is one the driver would have written: the strategy's +// current name, or the platform default. Checking the default as well keeps a +// lingering injected entry recognisable after the strategy drops or renames +// its s3 block — otherwise the opt-out refusal would stop seeing the entry it +// exists to refuse, and a legacy CR would be minted onto the platform bucket. +func psmdbCredentialsSecretIsInjected(cred string, rendered *strategyv1alpha1.MongoDBTemplate) bool { + if cred == psmdbDefaultCredentialsSecret { + return true + } + return rendered.S3 != nil && cred == psmdbInjectedCredentialsSecret(rendered.S3) +} + // shouldInjectMongoDBSystemStorage reports whether the driver must SSA-inject // the system-bucket storage onto the live cluster: only when the app opted in // via backup.useSystemBucket AND the strategy actually carries S3 coordinates @@ -803,6 +830,17 @@ func psmdbBackupTimedOut(state string, startedAt *metav1.Time, useSystemBucket b return psmdbBackupDeadlineExceeded(startedAt) } +// psmdbArtifactWindowExceeded bounds how long the driver keeps retrying to +// materialise the Backup object for a completed dump: psmdbLiveReadGrace after +// the operator marked the CR complete, or after the backup deadline when the +// operator did not record a completion time. +func psmdbArtifactWindowExceeded(b *psmdbtypes.PerconaServerMongoDBBackup, startedAt *metav1.Time) bool { + if b.Status.Completed != nil { + return time.Since(b.Status.Completed.Time) > psmdbLiveReadGrace + } + return startedAt != nil && time.Since(startedAt.Time) > psmdbDefaultBackupDeadline+psmdbLiveReadGrace +} + // psmdbErrorIsUnresolvedStorage reports whether a PerconaServerMongoDBBackup // error is the operator failing to resolve the named storage — the message the // v1.22.0 backup reconciler sets ("unable to get storage ''") when it @@ -1062,6 +1100,17 @@ func (r *BackupReconciler) cleanupMongoDBBackup(ctx context.Context, backup *bac return r.releaseMongoDBCleanup(ctx, backup, sourceBackupName, nil, "skip-artifact-cleanup annotation set") } + // A legacy Backup owns nothing on the shared bucket, and before this driver + // its cleanup was an unconditional no-op that no apiserver error could hold + // up. The snapshot records the flow, so decide from it first: when it is our + // kind and says legacy, release without reading the operator CR at all, so a + // throttle or a revoked verb on a CR the driver does not own cannot pin the + // Backup (or a namespace being torn down) in Terminating. A missing or + // undecodable snapshot falls through to the read below, never the other way. + if snap, serr := unmarshalMongoDBBackupSnapshot(backup.Status.UnderlyingResources); serr == nil && snap != nil && snap.Kind == psmdbBackupSnapshotKind && !snap.UseSystemBucket { + return ctrl.Result{}, nil + } + live := &psmdbtypes.PerconaServerMongoDBBackup{} err := r.Get(ctx, types.NamespacedName{Namespace: backup.Namespace, Name: sourceBackupName}, live) if apierrors.IsNotFound(err) || apimeta.IsNoMatchError(err) { diff --git a/internal/backupcontroller/psmdbstrategy_controller_test.go b/internal/backupcontroller/psmdbstrategy_controller_test.go index a13ee8523..c288a6a5f 100644 --- a/internal/backupcontroller/psmdbstrategy_controller_test.go +++ b/internal/backupcontroller/psmdbstrategy_controller_test.go @@ -2955,3 +2955,161 @@ func TestReconcileMongoDB_StorageRaceRetryBudgetExhausted(t *testing.T) { t.Errorf("no further CR may be minted once the budget is spent, got %d", len(list.Items)) } } + +// The archive exists once the operator CR is ready; the Backup object is the +// only thing that can ever reach it. A transient Create failure must retry (the +// job stays Running) rather than fail terminally with no artifact, and when the +// window is spent the failure names the CR that still holds the archive. +func TestReconcileMongoDB_ArtifactCreateFailureRetriesThenNamesTheCR(t *testing.T) { + build := func(t *testing.T, completed time.Time) (*BackupJobReconciler, client.Client, *record.FakeRecorder, *ResolvedBackupConfig, *backupsv1alpha1.BackupJob) { + job, strategy, app, cluster, resolved := mongodbInjectFixture(true) + job.Status.StartedAt = &metav1.Time{Time: time.Now().Add(-10 * time.Minute)} + cluster.Spec.Backup.Storages = map[string]runtime.RawExtension{ + "s3-storage": {Raw: []byte(`{"type":"s3","s3":{"bucket":"cozy-backups","credentialsSecret":"cozy-backups-creds"}}`)}, + } + ready := &psmdbtypes.PerconaServerMongoDBBackup{ + ObjectMeta: metav1.ObjectMeta{ + Namespace: "tenant", Name: "op-ready", Finalizers: []string{psmdbDeleteBackupFinalizer}, + Labels: map[string]string{ + backupsv1alpha1.OwningJobNameLabel: job.Name, + backupsv1alpha1.OwningJobNamespaceLabel: job.Namespace, + }, + }, + Status: psmdbtypes.PerconaServerMongoDBBackupStatus{ + State: psmdbtypes.StateReady, Completed: &metav1.Time{Time: completed}, + Destination: "s3://cozy-backups/tenant/app1/2026-09-20", + S3: &psmdbtypes.BackupStorageS3{Bucket: "cozy-backups", CredentialsSecret: psmdbDefaultCredentialsSecret}, + }, + } + sch := runtime.NewScheme() + _ = scheme.AddToScheme(sch) + _ = backupsv1alpha1.AddToScheme(sch) + _ = strategyv1alpha1.AddToScheme(sch) + _ = psmdbtypes.AddToScheme(sch) + _ = mongodbapp.AddToScheme(sch) + c := clientfake.NewClientBuilder().WithScheme(sch).WithObjects(job, strategy, app, cluster, ready). + WithStatusSubresource(&backupsv1alpha1.BackupJob{}, &backupsv1alpha1.Backup{}). + WithInterceptorFuncs(interceptor.Funcs{ + Create: func(ctx context.Context, cl client.WithWatch, obj client.Object, opts ...client.CreateOption) error { + if _, ok := obj.(*backupsv1alpha1.Backup); ok { + return apierrors.NewServiceUnavailable("etcd timeout") + } + return cl.Create(ctx, obj, opts...) + }, + }).Build() + rec := record.NewFakeRecorder(10) + return &BackupJobReconciler{Client: c, Scheme: sch, Recorder: rec}, c, rec, resolved, job + } + getJob := func(t *testing.T, c client.Client, name string) *backupsv1alpha1.BackupJob { + p := &backupsv1alpha1.BackupJob{} + if err := c.Get(context.Background(), types.NamespacedName{Namespace: "tenant", Name: name}, p); err != nil { + t.Fatalf("get job: %v", err) + } + return p + } + + t.Run("inside the window: retried, not failed", func(t *testing.T) { + r, c, _, resolved, job := build(t, time.Now()) + if _, err := r.reconcileMongoDB(context.Background(), job.DeepCopy(), resolved); err == nil { + t.Fatalf("a transient artifact Create failure must be returned for backoff, got nil") + } + if p := getJob(t, c, job.Name); p.Status.Phase == backupsv1alpha1.BackupJobPhaseFailed { + t.Errorf("a transient artifact Create failure must not fail the job while the window is open") + } + }) + + t.Run("window spent: fails and names the CR holding the archive", func(t *testing.T) { + r, c, rec, resolved, job := build(t, time.Now().Add(-2*psmdbLiveReadGrace)) + if _, err := r.reconcileMongoDB(context.Background(), job.DeepCopy(), resolved); err != nil { + t.Fatalf("reconcileMongoDB: %v", err) + } + p := getJob(t, c, job.Name) + if p.Status.Phase != backupsv1alpha1.BackupJobPhaseFailed { + t.Fatalf("expected Failed once the artifact window is spent, got phase=%q", p.Status.Phase) + } + if cond := apimeta.FindStatusCondition(p.Status.Conditions, "Ready"); cond == nil || !strings.Contains(cond.Message, "op-ready") { + t.Errorf("the terminal message must name the CR that still holds the archive, got %+v", cond) + } + select { + case ev := <-rec.Events: + if !strings.Contains(ev, "BackupArtifactNotCreated") || !strings.Contains(ev, "op-ready") { + t.Errorf("expected a BackupArtifactNotCreated Warning naming the CR, got %q", ev) + } + default: + t.Errorf("expected a Warning naming the orphaned archive's CR, got none") + } + }) +} + +// A legacy Backup owns nothing on the shared bucket; before this driver its +// cleanup was an unconditional no-op. With the flow recorded on the snapshot, +// cleanup must release a legacy Backup without any apiserver read, so a throttle +// or revoked verb on a CR the driver does not own cannot hold it Terminating. +func TestCleanupMongoDBBackup_LegacySnapshotSkipsTheRead(t *testing.T) { + legacySnap := &psmdbtypes.PerconaServerMongoDBBackup{Status: psmdbtypes.PerconaServerMongoDBBackupStatus{ + Destination: "s3://tenant-own/x", S3: &psmdbtypes.BackupStorageS3{Bucket: "tenant-own", CredentialsSecret: "mongodb-app1-s3-creds"}, + }} + raw, err := marshalMongoDBBackupSnapshot(legacySnap, &strategyv1alpha1.MongoDBTemplate{Type: "logical"}, "s3-storage", nil, false) + if err != nil { + t.Fatalf("marshal: %v", err) + } + s := runtime.NewScheme() + _ = scheme.AddToScheme(s) + _ = backupsv1alpha1.AddToScheme(s) + _ = psmdbtypes.AddToScheme(s) + reads := 0 + c := clientfake.NewClientBuilder().WithScheme(s).WithInterceptorFuncs(interceptor.Funcs{ + Get: func(ctx context.Context, cl client.WithWatch, key client.ObjectKey, obj client.Object, opts ...client.GetOption) error { + if _, ok := obj.(*psmdbtypes.PerconaServerMongoDBBackup); ok { + reads++ + return apierrors.NewTooManyRequests("apiserver throttled", 1) + } + return cl.Get(ctx, key, obj, opts...) + }, + }).Build() + r := &BackupReconciler{Client: c, Recorder: record.NewFakeRecorder(10)} + backup := &backupsv1alpha1.Backup{ + ObjectMeta: metav1.ObjectMeta{Namespace: "tenant", Name: "legacy-bk"}, + Spec: backupsv1alpha1.BackupSpec{DriverMetadata: map[string]string{psmdbBackupNameKey: "op-legacy"}}, + Status: backupsv1alpha1.BackupStatus{UnderlyingResources: raw}, + } + res, err := r.cleanupMongoDBBackup(context.Background(), backup) + if err != nil || res.RequeueAfter != 0 { + t.Fatalf("a legacy Backup must release without depending on the operator CR read, got res=%+v err=%v", res, err) + } + if reads != 0 { + t.Errorf("a legacy Backup must not read the operator CR at all, got %d reads", reads) + } +} + +// After a tenant opts out, the platform may drop or rename the strategy's s3 +// block; the lingering injected entry still carries the platform default Secret +// and must still be refused, or a legacy CR is minted onto the platform bucket. +func TestReconcileMongoDB_OptOutRefusalSurvivesStrategyWithoutS3(t *testing.T) { + job, strategy, app, cluster, resolved := mongodbInjectFixture(true) + app.Spec.Backup.UseSystemBucket = false + strategy.Spec.Template.S3 = nil // platform dropped the coordinates after the opt-out + job.Status.StartedAt = &metav1.Time{Time: time.Now()} + cluster.Spec.Backup.Storages = map[string]runtime.RawExtension{ + "s3-storage": {Raw: []byte(`{"type":"s3","s3":{"bucket":"cozy-backups","credentialsSecret":"cozy-backups-creds"}}`)}, + } + c := newMongoDBStrategyTestClient(t, job, strategy, app, cluster) + r := &BackupJobReconciler{Client: c, Scheme: c.Scheme(), Recorder: record.NewFakeRecorder(10)} + if _, err := r.reconcileMongoDB(context.Background(), job.DeepCopy(), resolved); err != nil { + t.Fatalf("reconcileMongoDB: %v", err) + } + list := &psmdbtypes.PerconaServerMongoDBBackupList{} + if err := c.List(context.Background(), list, client.InNamespace("tenant")); err != nil { + t.Fatalf("list: %v", err) + } + if len(list.Items) != 0 { + t.Errorf("the lingering injected entry must still be refused when the strategy carries no s3, got %d CRs minted", len(list.Items)) + } + persisted := &backupsv1alpha1.BackupJob{} + if err := c.Get(context.Background(), types.NamespacedName{Namespace: "tenant", Name: job.Name}, persisted); err != nil { + t.Fatalf("get job: %v", err) + } + if cond := apimeta.FindStatusCondition(persisted.Status.Conditions, "Ready"); cond == nil || cond.Reason != "PerconaServerMongoDBStorageStale" { + t.Errorf("expected Ready=False PerconaServerMongoDBStorageStale, got %+v", cond) + } +} From 5e3ffbe634d86fa1fb7773d19bc2049663d1596f Mon Sep 17 00:00:00 2001 From: Aleksei Sviridkin Date: Wed, 16 Sep 2026 17:43:26 +0300 Subject: [PATCH 0025/1280] feat(harbor): restrict the portal and API to listed source ranges Harbor serves its web portal and management API on the same host as the registry endpoints, and a tenant had no way to limit who reaches the portal and API without also cutting off image pulls. managementWhitelist restricts every path except /v2 and /service/token, which move to a second Ingress on the same host, so docker login, pull and push keep working from any address. The field is a list of ranges rather than a free-form annotation map: the shared ingress-nginx accepts snippet annotations, so arbitrary annotations from a tenant-writable spec would reach its nginx configuration. Gateway API publishing has no equivalent, so a non-empty list fails the render there instead of being silently dropped. Assisted-by: LLM Signed-off-by: Aleksei Sviridkin --- api/apps/v1alpha1/harbor/types.go | 3 + .../v1alpha1/harbor/zz_generated.deepcopy.go | 5 + packages/apps/harbor/README.md | 9 +- .../templates/dashboard-resourcemap.yaml | 1 + packages/apps/harbor/templates/httproute.yaml | 3 + packages/apps/harbor/templates/ingress.yaml | 52 ++++- .../ingress_management_whitelist_test.yaml | 192 ++++++++++++++++++ packages/apps/harbor/values.schema.json | 8 + packages/apps/harbor/values.yaml | 3 + packages/system/harbor-rd/cozyrds/harbor.yaml | 5 +- 10 files changed, 270 insertions(+), 11 deletions(-) create mode 100644 packages/apps/harbor/tests/ingress_management_whitelist_test.yaml diff --git a/api/apps/v1alpha1/harbor/types.go b/api/apps/v1alpha1/harbor/types.go index 99b89dbc1..2a7af004d 100644 --- a/api/apps/v1alpha1/harbor/types.go +++ b/api/apps/v1alpha1/harbor/types.go @@ -20,6 +20,9 @@ type ConfigSpec struct { // Hostname for external access to Harbor (defaults to 'harbor' subdomain for the tenant host). // +kubebuilder:default:="" Host string `json:"host,omitempty"` + // IP addresses or CIDR ranges allowed to reach the Harbor web portal and API. Only `/v2/` and `/service/token` stay open to any address, which is what `docker login`, image pulls and pushes use; every other path on the Harbor host is restricted. Empty allows every address. Requires Ingress publishing; rejected when the tenant publishes through Gateway API. + // +kubebuilder:default:={} + ManagementWhitelist []string `json:"managementWhitelist,omitempty"` // StorageClass used to store the data. // +kubebuilder:default:="" // +kubebuilder:validation:XValidation:rule="self == oldSelf",message="storageClass is immutable" diff --git a/api/apps/v1alpha1/harbor/zz_generated.deepcopy.go b/api/apps/v1alpha1/harbor/zz_generated.deepcopy.go index 3e7338ad9..8ff615ac2 100644 --- a/api/apps/v1alpha1/harbor/zz_generated.deepcopy.go +++ b/api/apps/v1alpha1/harbor/zz_generated.deepcopy.go @@ -53,6 +53,11 @@ func (in *Config) DeepCopyObject() runtime.Object { // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *ConfigSpec) DeepCopyInto(out *ConfigSpec) { *out = *in + if in.ManagementWhitelist != nil { + in, out := &in.ManagementWhitelist, &out.ManagementWhitelist + *out = make([]string, len(*in)) + copy(*out, *in) + } in.Core.DeepCopyInto(&out.Core) in.Registry.DeepCopyInto(&out.Registry) in.Jobservice.DeepCopyInto(&out.Jobservice) diff --git a/packages/apps/harbor/README.md b/packages/apps/harbor/README.md index cfa40e7f6..640cabd39 100644 --- a/packages/apps/harbor/README.md +++ b/packages/apps/harbor/README.md @@ -20,10 +20,11 @@ Without object storage in the tenant chain, Harbor cannot provision its registry ### Common parameters -| Name | Description | Type | Value | -| -------------- | -------------------------------------------------------------------------------------------- | -------- | ----- | -| `host` | Hostname for external access to Harbor (defaults to 'harbor' subdomain for the tenant host). | `string` | `""` | -| `storageClass` | StorageClass used to store the data. | `string` | `""` | +| Name | Description | Type | Value | +| --------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------- | ----- | +| `host` | Hostname for external access to Harbor (defaults to 'harbor' subdomain for the tenant host). | `string` | `""` | +| `managementWhitelist` | IP addresses or CIDR ranges allowed to reach the Harbor web portal and API. Only `/v2/` and `/service/token` stay open to any address, which is what `docker login`, image pulls and pushes use; every other path on the Harbor host is restricted. Empty allows every address. Requires Ingress publishing; rejected when the tenant publishes through Gateway API. | `[]string` | `[]` | +| `storageClass` | StorageClass used to store the data. | `string` | `""` | ### Component configuration diff --git a/packages/apps/harbor/templates/dashboard-resourcemap.yaml b/packages/apps/harbor/templates/dashboard-resourcemap.yaml index f8d91a612..89416d9e6 100644 --- a/packages/apps/harbor/templates/dashboard-resourcemap.yaml +++ b/packages/apps/harbor/templates/dashboard-resourcemap.yaml @@ -23,6 +23,7 @@ rules: - ingresses resourceNames: - {{ .Release.Name }}-ingress + - {{ .Release.Name }}-registry-ingress verbs: ["get", "list", "watch"] - apiGroups: - cozystack.io diff --git a/packages/apps/harbor/templates/httproute.yaml b/packages/apps/harbor/templates/httproute.yaml index 335d224d8..373d7b35f 100644 --- a/packages/apps/harbor/templates/httproute.yaml +++ b/packages/apps/harbor/templates/httproute.yaml @@ -2,6 +2,9 @@ {{- $host := .Values._namespace.host }} {{- $harborHost := .Values.host | default (printf "%s.%s" .Release.Name $host) }} {{- if $gateway }} +{{- if .Values.managementWhitelist }} +{{- fail "managementWhitelist is enforced by ingress-nginx and has no effect on an HTTPRoute; clear it or publish this tenant through Ingress" }} +{{- end }} apiVersion: gateway.networking.k8s.io/v1 kind: HTTPRoute metadata: diff --git a/packages/apps/harbor/templates/ingress.yaml b/packages/apps/harbor/templates/ingress.yaml index f416b729a..023daf121 100644 --- a/packages/apps/harbor/templates/ingress.yaml +++ b/packages/apps/harbor/templates/ingress.yaml @@ -1,3 +1,10 @@ +{{- define "harbor.ingress.proxyAnnotations" -}} +nginx.ingress.kubernetes.io/proxy-body-size: "0" +nginx.ingress.kubernetes.io/proxy-read-timeout: "900" +nginx.ingress.kubernetes.io/proxy-send-timeout: "900" +nginx.ingress.kubernetes.io/ssl-redirect: "true" +nginx.ingress.kubernetes.io/backend-protocol: "HTTP" +{{- end }} {{- $ingress := .Values._namespace.ingress }} {{- $gateway := .Values._namespace.gateway | default "" }} {{- $host := .Values._namespace.host }} @@ -12,11 +19,10 @@ kind: Ingress metadata: name: {{ .Release.Name }}-ingress annotations: - nginx.ingress.kubernetes.io/proxy-body-size: "0" - nginx.ingress.kubernetes.io/proxy-read-timeout: "900" - nginx.ingress.kubernetes.io/proxy-send-timeout: "900" - nginx.ingress.kubernetes.io/ssl-redirect: "true" - nginx.ingress.kubernetes.io/backend-protocol: "HTTP" + {{- include "harbor.ingress.proxyAnnotations" . | nindent 4 }} + {{- with .Values.managementWhitelist }} + nginx.ingress.kubernetes.io/whitelist-source-range: {{ join "," . | quote }} + {{- end }} {{- /* Operator wildcard mode: nginx serves the default SSL cert, so skip per-host ACME. */}} {{- if not $wildcardSecret }} {{- if eq $solver "http01" }} @@ -46,4 +52,40 @@ spec: name: {{ .Release.Name }} port: number: 80 +{{- /* whitelist-source-range is scoped to the locations of the Ingress that + carries it, so the registry API and its token endpoint stay open on a + second Ingress for the same host. /service/notifications is left behind + the whitelist: it only takes internal job callbacks. The certificate is + shared without the cert-manager annotations, otherwise ingress-shim + sees two owners for one Certificate. */}} +{{- if .Values.managementWhitelist }} +--- +apiVersion: networking.k8s.io/v1 +kind: Ingress +metadata: + name: {{ .Release.Name }}-registry-ingress + annotations: + {{- include "harbor.ingress.proxyAnnotations" . | nindent 4 }} +spec: + ingressClassName: {{ $ingress }} + tls: + - hosts: + - {{ $harborHost | quote }} + {{- if not $wildcardSecret }} + secretName: {{ .Release.Name }}-ingress-tls + {{- end }} + rules: + - host: {{ $harborHost | quote }} + http: + paths: + {{- range list "/v2" "/service/token" }} + - path: {{ . }} + pathType: Prefix + backend: + service: + name: {{ $.Release.Name }} + port: + number: 80 + {{- end }} +{{- end }} {{- end }} diff --git a/packages/apps/harbor/tests/ingress_management_whitelist_test.yaml b/packages/apps/harbor/tests/ingress_management_whitelist_test.yaml new file mode 100644 index 000000000..2923cb2ab --- /dev/null +++ b/packages/apps/harbor/tests/ingress_management_whitelist_test.yaml @@ -0,0 +1,192 @@ +suite: harbor managementWhitelist restricts everything but the registry paths +templates: + - templates/ingress.yaml + - templates/httproute.yaml + - templates/dashboard-resourcemap.yaml + +release: + name: harbor + namespace: tenant-root + +set: + _namespace: + host: example.org + ingress: tenant-root + gateway: "" + _cluster: + issuer-name: letsencrypt-prod + solver: http01 + +tests: + - it: renders the single Ingress unchanged when the list is empty + template: templates/ingress.yaml + asserts: + - hasDocuments: + count: 1 + - equal: + path: metadata + value: + name: harbor-ingress + annotations: + nginx.ingress.kubernetes.io/proxy-body-size: "0" + nginx.ingress.kubernetes.io/proxy-read-timeout: "900" + nginx.ingress.kubernetes.io/proxy-send-timeout: "900" + nginx.ingress.kubernetes.io/ssl-redirect: "true" + nginx.ingress.kubernetes.io/backend-protocol: "HTTP" + acme.cert-manager.io/http01-ingress-ingressclassname: tenant-root + cert-manager.io/cluster-issuer: letsencrypt-prod + - equal: + path: spec + value: + ingressClassName: tenant-root + tls: + - hosts: + - harbor.example.org + secretName: harbor-ingress-tls + rules: + - host: harbor.example.org + http: + paths: + - path: / + pathType: Prefix + backend: + service: + name: harbor + port: + number: 80 + + - it: splits into a management and a registry Ingress when the list is set + template: templates/ingress.yaml + set: + managementWhitelist: + - 192.0.2.0/24 + asserts: + - hasDocuments: + count: 2 + + - it: restricts the management Ingress to the listed ranges + template: templates/ingress.yaml + documentSelector: + path: metadata.name + value: harbor-ingress + set: + managementWhitelist: + - 192.0.2.0/24 + - 198.51.100.7/32 + asserts: + - equal: + path: metadata.annotations["nginx.ingress.kubernetes.io/whitelist-source-range"] + value: 192.0.2.0/24,198.51.100.7/32 + - equal: + path: metadata.annotations["cert-manager.io/cluster-issuer"] + value: letsencrypt-prod + - equal: + path: spec.rules[0].http.paths + value: + - path: / + pathType: Prefix + backend: + service: + name: harbor + port: + number: 80 + + - it: serves the registry API and token endpoint from an unrestricted Ingress on the same host and certificate + template: templates/ingress.yaml + documentSelector: + path: metadata.name + value: harbor-registry-ingress + set: + managementWhitelist: + - 192.0.2.0/24 + asserts: + - equal: + path: metadata.annotations + value: + nginx.ingress.kubernetes.io/proxy-body-size: "0" + nginx.ingress.kubernetes.io/proxy-read-timeout: "900" + nginx.ingress.kubernetes.io/proxy-send-timeout: "900" + nginx.ingress.kubernetes.io/ssl-redirect: "true" + nginx.ingress.kubernetes.io/backend-protocol: "HTTP" + - equal: + path: spec + value: + ingressClassName: tenant-root + tls: + - hosts: + - harbor.example.org + secretName: harbor-ingress-tls + rules: + - host: harbor.example.org + http: + paths: + - path: /v2 + pathType: Prefix + backend: + service: + name: harbor + port: + number: 80 + - path: /service/token + pathType: Prefix + backend: + service: + name: harbor + port: + number: 80 + + - it: leaves the registry Ingress without a secretName in wildcard mode + template: templates/ingress.yaml + documentSelector: + path: metadata.name + value: harbor-registry-ingress + set: + managementWhitelist: + - 192.0.2.0/24 + _cluster: + wildcard-secret-name: wildcard-tls + asserts: + - equal: + path: spec.tls + value: + - hosts: + - harbor.example.org + + - it: refuses a whitelist in Gateway API mode instead of dropping it + template: templates/httproute.yaml + set: + managementWhitelist: + - 192.0.2.0/24 + _namespace: + gateway: tenant-root + asserts: + - failedTemplate: + errorPattern: managementWhitelist + + - it: renders the HTTPRoute in Gateway API mode without a whitelist + template: templates/httproute.yaml + set: + _namespace: + gateway: tenant-root + asserts: + - equal: + path: kind + value: HTTPRoute + + - it: lets the dashboard read both Ingress objects + template: templates/dashboard-resourcemap.yaml + documentSelector: + path: kind + value: Role + asserts: + - contains: + path: rules + content: + apiGroups: + - networking.k8s.io + resources: + - ingresses + resourceNames: + - harbor-ingress + - harbor-registry-ingress + verbs: ["get", "list", "watch"] diff --git a/packages/apps/harbor/values.schema.json b/packages/apps/harbor/values.schema.json index 2b9be8b77..c266ed895 100644 --- a/packages/apps/harbor/values.schema.json +++ b/packages/apps/harbor/values.schema.json @@ -7,6 +7,14 @@ "type": "string", "default": "" }, + "managementWhitelist": { + "description": "IP addresses or CIDR ranges allowed to reach the Harbor web portal and API. Only `/v2/` and `/service/token` stay open to any address, which is what `docker login`, image pulls and pushes use; every other path on the Harbor host is restricted. Empty allows every address. Requires Ingress publishing; rejected when the tenant publishes through Gateway API.", + "type": "array", + "default": [], + "items": { + "type": "string" + } + }, "storageClass": { "description": "StorageClass used to store the data.", "type": "string", diff --git a/packages/apps/harbor/values.yaml b/packages/apps/harbor/values.yaml index 71cff465e..4fd3ac5e7 100644 --- a/packages/apps/harbor/values.yaml +++ b/packages/apps/harbor/values.yaml @@ -5,6 +5,9 @@ ## @param {string} [host] - Hostname for external access to Harbor (defaults to 'harbor' subdomain for the tenant host). host: "" +## @param {[]string} [managementWhitelist] - IP addresses or CIDR ranges allowed to reach the Harbor web portal and API. Only `/v2/` and `/service/token` stay open to any address, which is what `docker login`, image pulls and pushes use; every other path on the Harbor host is restricted. Empty allows every address. Requires Ingress publishing; rejected when the tenant publishes through Gateway API. +managementWhitelist: [] + ## @param {string} storageClass - StorageClass used to store the data. ## @immutable ## @x-cozystack-options {source: storageclass} diff --git a/packages/system/harbor-rd/cozyrds/harbor.yaml b/packages/system/harbor-rd/cozyrds/harbor.yaml index 83cc11af0..658213908 100644 --- a/packages/system/harbor-rd/cozyrds/harbor.yaml +++ b/packages/system/harbor-rd/cozyrds/harbor.yaml @@ -8,7 +8,7 @@ spec: singular: harbor plural: harbors openAPISchema: |- - {"title":"Chart Values","type":"object","properties":{"host":{"description":"Hostname for external access to Harbor (defaults to 'harbor' subdomain for the tenant host).","type":"string","default":""},"storageClass":{"description":"StorageClass used to store the data.","type":"string","default":"","x-kubernetes-validations":[{"rule":"self == oldSelf","message":"storageClass is immutable"}],"x-cozystack-options":{"source":"storageclass"}},"core":{"description":"Core API server configuration.","type":"object","default":{},"properties":{"resources":{"description":"Explicit CPU and memory configuration. When omitted, the preset defined in `resourcesPreset` is applied.","type":"object","default":{},"properties":{"cpu":{"description":"Number of CPU cores allocated.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"memory":{"description":"Amount of memory allocated.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true}}},"resourcesPreset":{"description":"Default sizing preset used when `resources` is omitted.","type":"string","default":"t1.small","enum":["t1.nano","t1.micro","t1.small","t1.medium","t1.large","t1.xlarge","t1.2xlarge","t1.4xlarge","c1.nano","c1.micro","c1.small","c1.medium","c1.large","c1.xlarge","c1.2xlarge","c1.4xlarge","s1.nano","s1.micro","s1.small","s1.medium","s1.large","s1.xlarge","s1.2xlarge","s1.4xlarge","u1.nano","u1.micro","u1.small","u1.medium","u1.large","u1.xlarge","u1.2xlarge","u1.4xlarge","m1.nano","m1.micro","m1.small","m1.medium","m1.large","m1.xlarge","m1.2xlarge","m1.4xlarge","nano","micro","small","medium","large","xlarge","2xlarge"]}}},"registry":{"description":"Container image registry configuration.","type":"object","default":{},"properties":{"resources":{"description":"Explicit CPU and memory configuration. When omitted, the preset defined in `resourcesPreset` is applied.","type":"object","default":{},"properties":{"cpu":{"description":"Number of CPU cores allocated.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"memory":{"description":"Amount of memory allocated.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true}}},"resourcesPreset":{"description":"Default sizing preset used when `resources` is omitted.","type":"string","default":"t1.small","enum":["t1.nano","t1.micro","t1.small","t1.medium","t1.large","t1.xlarge","t1.2xlarge","t1.4xlarge","c1.nano","c1.micro","c1.small","c1.medium","c1.large","c1.xlarge","c1.2xlarge","c1.4xlarge","s1.nano","s1.micro","s1.small","s1.medium","s1.large","s1.xlarge","s1.2xlarge","s1.4xlarge","u1.nano","u1.micro","u1.small","u1.medium","u1.large","u1.xlarge","u1.2xlarge","u1.4xlarge","m1.nano","m1.micro","m1.small","m1.medium","m1.large","m1.xlarge","m1.2xlarge","m1.4xlarge","nano","micro","small","medium","large","xlarge","2xlarge"]}}},"jobservice":{"description":"Background job service configuration.","type":"object","default":{},"properties":{"resources":{"description":"Explicit CPU and memory configuration. When omitted, the preset defined in `resourcesPreset` is applied.","type":"object","default":{},"properties":{"cpu":{"description":"Number of CPU cores allocated.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"memory":{"description":"Amount of memory allocated.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true}}},"resourcesPreset":{"description":"Default sizing preset used when `resources` is omitted.","type":"string","default":"t1.nano","enum":["t1.nano","t1.micro","t1.small","t1.medium","t1.large","t1.xlarge","t1.2xlarge","t1.4xlarge","c1.nano","c1.micro","c1.small","c1.medium","c1.large","c1.xlarge","c1.2xlarge","c1.4xlarge","s1.nano","s1.micro","s1.small","s1.medium","s1.large","s1.xlarge","s1.2xlarge","s1.4xlarge","u1.nano","u1.micro","u1.small","u1.medium","u1.large","u1.xlarge","u1.2xlarge","u1.4xlarge","m1.nano","m1.micro","m1.small","m1.medium","m1.large","m1.xlarge","m1.2xlarge","m1.4xlarge","nano","micro","small","medium","large","xlarge","2xlarge"]}}},"trivy":{"description":"Trivy vulnerability scanner configuration.","type":"object","default":{},"required":["enabled","size"],"properties":{"enabled":{"description":"Enable or disable the vulnerability scanner.","type":"boolean","default":true},"resources":{"description":"Explicit CPU and memory configuration. When omitted, the preset defined in `resourcesPreset` is applied.","type":"object","default":{},"properties":{"cpu":{"description":"Number of CPU cores allocated.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"memory":{"description":"Amount of memory allocated.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true}}},"resourcesPreset":{"description":"Default sizing preset used when `resources` is omitted.","type":"string","default":"t1.nano","enum":["t1.nano","t1.micro","t1.small","t1.medium","t1.large","t1.xlarge","t1.2xlarge","t1.4xlarge","c1.nano","c1.micro","c1.small","c1.medium","c1.large","c1.xlarge","c1.2xlarge","c1.4xlarge","s1.nano","s1.micro","s1.small","s1.medium","s1.large","s1.xlarge","s1.2xlarge","s1.4xlarge","u1.nano","u1.micro","u1.small","u1.medium","u1.large","u1.xlarge","u1.2xlarge","u1.4xlarge","m1.nano","m1.micro","m1.small","m1.medium","m1.large","m1.xlarge","m1.2xlarge","m1.4xlarge","nano","micro","small","medium","large","xlarge","2xlarge"]},"size":{"description":"Persistent Volume size for vulnerability database cache.","default":"5Gi","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true}}},"database":{"description":"PostgreSQL database configuration.","type":"object","default":{},"required":["replicas","size"],"properties":{"replicas":{"description":"Number of database instances.","type":"integer","default":2},"size":{"description":"Persistent Volume size for database storage.","default":"5Gi","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true}}},"redis":{"description":"Redis cache configuration.","type":"object","default":{},"required":["replicas","size"],"properties":{"replicas":{"description":"Number of Redis replicas.","type":"integer","default":2},"size":{"description":"Persistent Volume size for cache storage.","default":"1Gi","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true}}}}} + {"title":"Chart Values","type":"object","properties":{"host":{"description":"Hostname for external access to Harbor (defaults to 'harbor' subdomain for the tenant host).","type":"string","default":""},"managementWhitelist":{"description":"IP addresses or CIDR ranges allowed to reach the Harbor web portal and API. Only `/v2/` and `/service/token` stay open to any address, which is what `docker login`, image pulls and pushes use; every other path on the Harbor host is restricted. Empty allows every address. Requires Ingress publishing; rejected when the tenant publishes through Gateway API.","type":"array","default":[],"items":{"type":"string"}},"storageClass":{"description":"StorageClass used to store the data.","type":"string","default":"","x-kubernetes-validations":[{"rule":"self == oldSelf","message":"storageClass is immutable"}],"x-cozystack-options":{"source":"storageclass"}},"core":{"description":"Core API server configuration.","type":"object","default":{},"properties":{"resources":{"description":"Explicit CPU and memory configuration. When omitted, the preset defined in `resourcesPreset` is applied.","type":"object","default":{},"properties":{"cpu":{"description":"Number of CPU cores allocated.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"memory":{"description":"Amount of memory allocated.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true}}},"resourcesPreset":{"description":"Default sizing preset used when `resources` is omitted.","type":"string","default":"t1.small","enum":["t1.nano","t1.micro","t1.small","t1.medium","t1.large","t1.xlarge","t1.2xlarge","t1.4xlarge","c1.nano","c1.micro","c1.small","c1.medium","c1.large","c1.xlarge","c1.2xlarge","c1.4xlarge","s1.nano","s1.micro","s1.small","s1.medium","s1.large","s1.xlarge","s1.2xlarge","s1.4xlarge","u1.nano","u1.micro","u1.small","u1.medium","u1.large","u1.xlarge","u1.2xlarge","u1.4xlarge","m1.nano","m1.micro","m1.small","m1.medium","m1.large","m1.xlarge","m1.2xlarge","m1.4xlarge","nano","micro","small","medium","large","xlarge","2xlarge"]}}},"registry":{"description":"Container image registry configuration.","type":"object","default":{},"properties":{"resources":{"description":"Explicit CPU and memory configuration. When omitted, the preset defined in `resourcesPreset` is applied.","type":"object","default":{},"properties":{"cpu":{"description":"Number of CPU cores allocated.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"memory":{"description":"Amount of memory allocated.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true}}},"resourcesPreset":{"description":"Default sizing preset used when `resources` is omitted.","type":"string","default":"t1.small","enum":["t1.nano","t1.micro","t1.small","t1.medium","t1.large","t1.xlarge","t1.2xlarge","t1.4xlarge","c1.nano","c1.micro","c1.small","c1.medium","c1.large","c1.xlarge","c1.2xlarge","c1.4xlarge","s1.nano","s1.micro","s1.small","s1.medium","s1.large","s1.xlarge","s1.2xlarge","s1.4xlarge","u1.nano","u1.micro","u1.small","u1.medium","u1.large","u1.xlarge","u1.2xlarge","u1.4xlarge","m1.nano","m1.micro","m1.small","m1.medium","m1.large","m1.xlarge","m1.2xlarge","m1.4xlarge","nano","micro","small","medium","large","xlarge","2xlarge"]}}},"jobservice":{"description":"Background job service configuration.","type":"object","default":{},"properties":{"resources":{"description":"Explicit CPU and memory configuration. When omitted, the preset defined in `resourcesPreset` is applied.","type":"object","default":{},"properties":{"cpu":{"description":"Number of CPU cores allocated.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"memory":{"description":"Amount of memory allocated.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true}}},"resourcesPreset":{"description":"Default sizing preset used when `resources` is omitted.","type":"string","default":"t1.nano","enum":["t1.nano","t1.micro","t1.small","t1.medium","t1.large","t1.xlarge","t1.2xlarge","t1.4xlarge","c1.nano","c1.micro","c1.small","c1.medium","c1.large","c1.xlarge","c1.2xlarge","c1.4xlarge","s1.nano","s1.micro","s1.small","s1.medium","s1.large","s1.xlarge","s1.2xlarge","s1.4xlarge","u1.nano","u1.micro","u1.small","u1.medium","u1.large","u1.xlarge","u1.2xlarge","u1.4xlarge","m1.nano","m1.micro","m1.small","m1.medium","m1.large","m1.xlarge","m1.2xlarge","m1.4xlarge","nano","micro","small","medium","large","xlarge","2xlarge"]}}},"trivy":{"description":"Trivy vulnerability scanner configuration.","type":"object","default":{},"required":["enabled","size"],"properties":{"enabled":{"description":"Enable or disable the vulnerability scanner.","type":"boolean","default":true},"resources":{"description":"Explicit CPU and memory configuration. When omitted, the preset defined in `resourcesPreset` is applied.","type":"object","default":{},"properties":{"cpu":{"description":"Number of CPU cores allocated.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"memory":{"description":"Amount of memory allocated.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true}}},"resourcesPreset":{"description":"Default sizing preset used when `resources` is omitted.","type":"string","default":"t1.nano","enum":["t1.nano","t1.micro","t1.small","t1.medium","t1.large","t1.xlarge","t1.2xlarge","t1.4xlarge","c1.nano","c1.micro","c1.small","c1.medium","c1.large","c1.xlarge","c1.2xlarge","c1.4xlarge","s1.nano","s1.micro","s1.small","s1.medium","s1.large","s1.xlarge","s1.2xlarge","s1.4xlarge","u1.nano","u1.micro","u1.small","u1.medium","u1.large","u1.xlarge","u1.2xlarge","u1.4xlarge","m1.nano","m1.micro","m1.small","m1.medium","m1.large","m1.xlarge","m1.2xlarge","m1.4xlarge","nano","micro","small","medium","large","xlarge","2xlarge"]},"size":{"description":"Persistent Volume size for vulnerability database cache.","default":"5Gi","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true}}},"database":{"description":"PostgreSQL database configuration.","type":"object","default":{},"required":["replicas","size"],"properties":{"replicas":{"description":"Number of database instances.","type":"integer","default":2},"size":{"description":"Persistent Volume size for database storage.","default":"5Gi","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true}}},"redis":{"description":"Redis cache configuration.","type":"object","default":{},"required":["replicas","size"],"properties":{"replicas":{"description":"Number of Redis replicas.","type":"integer","default":2},"size":{"description":"Persistent Volume size for cache storage.","default":"1Gi","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true}}}}} release: prefix: "harbor-" labels: @@ -27,7 +27,7 @@ spec: - registry - container icon: "PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHJvbGU9ImltZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiIHZpZXdCb3g9IjEuMDUgLTEuOTUgMzU5LjQxIDM2MS42NiI+PGRlZnM+PGxpbmVhckdyYWRpZW50IGlkPSJsaW5lYXItZ3JhZGllbnQiIHgxPSIyNjQuNzkiIHgyPSIyNjcuMjciIHkxPSI5NTIuMzkiIHkyPSI5NTIuMzkiIGdyYWRpZW50VHJhbnNmb3JtPSJtYXRyaXgoMzAuNDMgMCAwIC0zMC40MyAtNzk1NS4yMiAyOTI4NS43NSkiIGdyYWRpZW50VW5pdHM9InVzZXJTcGFjZU9uVXNlIj48c3RvcCBvZmZzZXQ9IjAiIHN0b3AtY29sb3I9IiM2MGI5MzIiLz48c3RvcCBvZmZzZXQ9Ii4yOCIgc3RvcC1jb2xvcj0iIzYwYjkzMiIvPjxzdG9wIG9mZnNldD0iMSIgc3RvcC1jb2xvcj0iIzM2N2MzNCIvPjwvbGluZWFyR3JhZGllbnQ+PGxpbmVhckdyYWRpZW50IGlkPSJsaW5lYXItZ3JhZGllbnQtMiIgeDE9IjI2My43NyIgeDI9IjI2Ni4yNiIgeTE9Ijk1NS42NSIgeTI9Ijk1NS42NSIgZ3JhZGllbnRUcmFuc2Zvcm09Im1hdHJpeCgyNy4yMSAwIDAgLTI3LjIxIC03MDczLjg1IDI2MTY5LjQxKSIgeGxpbms6aHJlZj0iI2xpbmVhci1ncmFkaWVudCIvPjxsaW5lYXJHcmFkaWVudCBpZD0ibGluZWFyLWdyYWRpZW50LTMiIHgxPSIyNjMuMjgiIHgyPSIyNjUuNzYiIHkxPSI5NTMuNzQiIHkyPSI5NTMuNzQiIGdyYWRpZW50VHJhbnNmb3JtPSJtYXRyaXgoMjUuNzUgMCAwIC0yNS43NSAtNjY3MS4xMyAyNDgxMi4yMykiIHhsaW5rOmhyZWY9IiNsaW5lYXItZ3JhZGllbnQiLz48bGluZWFyR3JhZGllbnQgaWQ9ImxpbmVhci1ncmFkaWVudC00IiB4MT0iMjYzLjc3IiB4Mj0iMjY2LjI1IiB5MT0iOTUzLjIiIHkyPSI5NTMuMiIgZ3JhZGllbnRUcmFuc2Zvcm09Im1hdHJpeCgyNy4xIDAgMCAtMjcuMSAtNzA0MC45IDI2MTAyLjQ5KSIgeGxpbms6aHJlZj0iI2xpbmVhci1ncmFkaWVudCIvPjxsaW5lYXJHcmFkaWVudCBpZD0ibGluZWFyLWdyYWRpZW50LTUiIHgxPSIyNjIuNzMiIHgyPSIyNjUuMjEiIHkxPSI5NTQuMzQiIHkyPSI5NTQuMzQiIGdyYWRpZW50VHJhbnNmb3JtPSJtYXRyaXgoMjQuNCAwIDAgLTI0LjQgLTYzMDEuMzYgMjM1MjEuOTcpIiB4bGluazpocmVmPSIjbGluZWFyLWdyYWRpZW50Ii8+PGxpbmVhckdyYWRpZW50IGlkPSJsaW5lYXItZ3JhZGllbnQtNiIgeDE9IjI3Mi4xNCIgeDI9IjI3NC42MiIgeTE9Ijk1NS4xNSIgeTI9Ijk1NS4xNSIgZ3JhZGllbnRUcmFuc2Zvcm09InNjYWxlKDY2LjA5IC02Ni4wOSkgcm90YXRlKDM2LjUyIDE1ODguMTUzIDY4LjE0OCkiIGdyYWRpZW50VW5pdHM9InVzZXJTcGFjZU9uVXNlIj48c3RvcCBvZmZzZXQ9IjAiIHN0b3AtY29sb3I9IiM0NTk2ZDgiLz48c3RvcCBvZmZzZXQ9Ii4yIiBzdG9wLWNvbG9yPSIjNDU5NmQ4Ii8+PHN0b3Agb2Zmc2V0PSIxIiBzdG9wLWNvbG9yPSIjZmZmIi8+PC9saW5lYXJHcmFkaWVudD48bGluZWFyR3JhZGllbnQgaWQ9ImxpbmVhci1ncmFkaWVudC03IiB4MT0iMjcwLjY1IiB4Mj0iMjczLjEzIiB5MT0iOTUyLjM4IiB5Mj0iOTUyLjM4IiBncmFkaWVudFRyYW5zZm9ybT0ic2NhbGUoNzcuOCAtNzcuOCkgcm90YXRlKC0xMS41NCAtNDU4Ny4yMDkgMTgwMy4zMjMpIiBncmFkaWVudFVuaXRzPSJ1c2VyU3BhY2VPblVzZSI+PHN0b3Agb2Zmc2V0PSIwIiBzdG9wLWNvbG9yPSIjNDE5NGQ3Ii8+PHN0b3Agb2Zmc2V0PSIuMiIgc3RvcC1jb2xvcj0iIzQxOTRkNyIvPjxzdG9wIG9mZnNldD0iMSIgc3RvcC1jb2xvcj0iI2ZmZiIvPjwvbGluZWFyR3JhZGllbnQ+PGxpbmVhckdyYWRpZW50IGlkPSJsaW5lYXItZ3JhZGllbnQtOCIgeDE9IjI3MC45NyIgeDI9IjI3My40NSIgeTE9Ijk1My43NSIgeTI9Ijk1My43NSIgZ3JhZGllbnRUcmFuc2Zvcm09InNjYWxlKDcxLjM1IC03MS4zNSkgcm90YXRlKDEwLjIzIDU0NzcuMzcgLTEwMjQuNjAyKSIgZ3JhZGllbnRVbml0cz0idXNlclNwYWNlT25Vc2UiPjxzdG9wIG9mZnNldD0iMCIgc3RvcC1jb2xvcj0iIzQxOTRkNyIvPjxzdG9wIG9mZnNldD0iLjMzIiBzdG9wLWNvbG9yPSIjNDQ5NmQ4Ii8+PHN0b3Agb2Zmc2V0PSIxIiBzdG9wLWNvbG9yPSIjZmZmIi8+PC9saW5lYXJHcmFkaWVudD48Y2xpcFBhdGggaWQ9ImNsaXAtcGF0aCI+PHBhdGggZD0iTTE3NC40IDMwMi41MmwtNjguNjUtMzAuMjYtMy44MyA0My4yMSA3NS41IDIzLjk4LTMuMDItMzYuOTN6IiBjbGFzcz0iY2xzLTEiLz48L2NsaXBQYXRoPjxjbGlwUGF0aCBpZD0iY2xpcC1wYXRoLTIiPjxwYXRoIGQ9Ik0xMTkuMTkgMTM1LjM4aDM4LjU1djMyLjg5aC05LjE1di0xNGExMC4xMyAxMC4xMyAwIDEgMC0yMC4yNiAwdjE0aC05LjE1em0tNy43IDcybDU3LjIgMjUuMjEtMy45NC00OC4yNGg3LjQ5di0xNi4wOGgtNS41NXYtMzIuODloNS41NXYtOS40NWwtMzAuODYtMzAuMTl2LTIuMTJhMi45MSAyLjkxIDAgMCAwLTUuODIgMHYyLjEybC0zMC44NiAzMC4xOXY5LjQ1aDUuNTZ2MzIuODloLTUuNTZ2MTYuMTJoOC44MnoiIGNsYXNzPSJjbHMtMSIvPjwvY2xpcFBhdGg+PGNsaXBQYXRoIGlkPSJjbGlwLXBhdGgtMyI+PHBhdGggZD0iTTEwOC4xNCAyNDUuMjhsNjMuODggMjguMTYtLjk2LTExLjczLTYxLjk2LTI3LjMtLjk2IDEwLjg3eiIgY2xhc3M9ImNscy0xIi8+PC9jbGlwUGF0aD48Y2xpcFBhdGggaWQ9ImNsaXAtcGF0aC00Ij48cGF0aCBkPSJNMTA2LjQ2IDI2NC4yMWw2Ny4yMyAyOS42My0uOTYtMTEuNzItNjUuMzEtMjguNzgtLjk2IDEwLjg3eiIgY2xhc3M9ImNscy0xIi8+PC9jbGlwUGF0aD48Y2xpcFBhdGggaWQ9ImNsaXAtcGF0aC01Ij48cGF0aCBkPSJNMTEwLjc3IDIxNS40OGwtLjk2IDEwLjg3IDYwLjU0IDI2LjY4LS45NS0xMS43Mi01OC42My0yNS44M3oiIGNsYXNzPSJjbHMtMSIvPjwvY2xpcFBhdGg+PGNsaXBQYXRoIGlkPSJjbGlwLXBhdGgtNiI+PHBhdGggZD0iTTMxMy4xMyA2Ny41OWExNzUuMzEgMTc1LjMxIDAgMCAwLTI5Ljc1LTI4LjEzYy0xLjU3LTEuMTctMy4xOC0yLjMtNC43OS0zLjQyTDI1NiA1OS41bC04Mi4zNCA4NS42MyAxMTMuNDEtNTguNjggMjkuMDctMTVjLTEuMDEtMS4zMS0xLjk4LTIuNjItMy4wMS0zLjg2eiIgY2xhc3M9ImNscy0xIi8+PC9jbGlwUGF0aD48Y2xpcFBhdGggaWQ9ImNsaXAtcGF0aC03Ij48cGF0aCBkPSJNMzUzLjU5IDE3Ny42MWMwLTItLjE0LTQtLjIyLTUuOTNsLTMyLjIxLTIuMzEtMTQ3LjQ3LTEwLjU4TDMxOC4zNiAyMDlsMzAuNDEgMTAuNTVjLjA5LS4zNi4xOS0uNzEuMjgtMS4wOGExNzMuNjUgMTczLjY1IDAgMCAwIDQuNTctMzkuNDd2LTEuMzd6IiBjbGFzcz0iY2xzLTEiLz48L2NsaXBQYXRoPjxjbGlwUGF0aCBpZD0iY2xpcC1wYXRoLTgiPjxwYXRoIGQ9Ik0zNDguODQgMTM4LjYxYTE3Mi41NSAxNzIuNTUgMCAwIDAtMTMuODQtMzcuN2wtMzAuOTQgOS45NEwxNzUuOTIgMTUybDE0Mi00LjgzIDMyLjUtMS4xMWMtLjUtMi40OC0uOTktNC45OC0xLjU4LTcuNDV6IiBjbGFzcz0iY2xzLTEiLz48L2NsaXBQYXRoPjxzdHlsZT4uY2xzLTF7ZmlsbDpub25lfS5jbHMtMTN7ZmlsbDojNjk2NTY2fTwvc3R5bGU+PC9kZWZzPjxnIGlkPSJnMTIiPjxwYXRoIGlkPSJwYXRoMTQiIGZpbGw9IiNmZmYiIGQ9Ik0zMC44OSAxNzlhMTQ4Ljg3IDE0OC44NyAwIDEgMSAxNDguODcgMTQ4Ljg1QTE0OC44NyAxNDguODcgMCAwIDEgMzAuODkgMTc5Ii8+PGcgaWQ9ImczMCIgY2xpcC1wYXRoPSJ1cmwoI2NsaXAtcGF0aCkiPjxnIGlkPSJnMzIiPjxwYXRoIGlkPSJwYXRoNDYiIGZpbGw9InVybCgjbGluZWFyLWdyYWRpZW50KSIgZD0iTTE3NC40IDMwMi41MmwtNjguNjUtMzAuMjUtMy44MiA0My4yIDc1LjUgMjQtMy0zNi45MyIvPjwvZz48L2c+PGcgaWQ9Imc0OCIgY2xpcC1wYXRoPSJ1cmwoI2NsaXAtcGF0aC0yKSI+PGcgaWQ9Imc1MCI+PHBhdGggaWQ9InBhdGg2NCIgZmlsbD0idXJsKCNsaW5lYXItZ3JhZGllbnQtMikiIGQ9Ik0xMTkuMTkgMTM1LjM4aDM4LjU1djMyLjg5aC05LjE1di0xNGExMC4xMyAxMC4xMyAwIDEgMC0yMC4yNiAwdjE0aC05LjE1em0tNy43IDcybDU3LjIgMjUuMjEtMy45NC00OC4yNGg3LjQ5di0xNi4wOGgtNS41NXYtMzIuODloNS41NXYtOS40NWwtMzAuODYtMzAuMTl2LTIuMTJhMi45MSAyLjkxIDAgMCAwLTUuODIgMHYyLjEybC0zMC44NiAzMC4xOXY5LjQ1aDUuNTZ2MzIuODloLTUuNTZ2MTYuMTJoOC44MmwtMiAyMyIvPjwvZz48L2c+PGcgaWQ9Imc2NiIgY2xpcC1wYXRoPSJ1cmwoI2NsaXAtcGF0aC0zKSI+PGcgaWQ9Imc2OCI+PHBhdGggaWQ9InBhdGg4MiIgZmlsbD0idXJsKCNsaW5lYXItZ3JhZGllbnQtMykiIGQ9Ik0xMDguMTMgMjQ1LjI4TDE3MiAyNzMuNDRsLTEtMTEuNzItNjItMjcuMzEtMSAxMC44NyIvPjwvZz48L2c+PGcgaWQ9Imc4NCIgY2xpcC1wYXRoPSJ1cmwoI2NsaXAtcGF0aC00KSI+PGcgaWQ9Imc4NiI+PHBhdGggaWQ9InBhdGgxMDAiIGZpbGw9InVybCgjbGluZWFyLWdyYWRpZW50LTQpIiBkPSJNMTA2LjQ2IDI2NC4yMWw2Ny4yMyAyOS42My0xLTExLjcyLTY1LjMxLTI4Ljc4LTEgMTAuODciLz48L2c+PC9nPjxnIGlkPSJnMTAyIiBjbGlwLXBhdGg9InVybCgjY2xpcC1wYXRoLTUpIj48ZyBpZD0iZzEwNCI+PHBhdGggaWQ9InBhdGgxMTgiIGZpbGw9InVybCgjbGluZWFyLWdyYWRpZW50LTUpIiBkPSJNMTEwLjc3IDIxNS40OGwtMSAxMC44OEwxNzAuMzUgMjUzbC0xLTExLjcyLTU4LjYyLTI1LjgzIi8+PC9nPjwvZz48cGF0aCBpZD0icGF0aDEyMCIgZD0iTTMwNC4wNyAxMTAuODVsMzAuOTMtOS45NGMtLjExLS4yMi0uMjEtLjQ1LS4zMi0uNjZhMTc0LjQxIDE3NC40MSAwIDAgMC0xOC41NS0yOC44M2wtMjkuMDcgMTVhMTQyLjcxIDE0Mi43MSAwIDAgMSAxNi43MyAyMy44N2MuMS4xNy4xOC4zNS4yNy41MyIgY2xhc3M9ImNscy0xMyIvPjxwYXRoIGlkPSJwYXRoMTIyIiBkPSJNMzIxLjE1IDE2OS4zN2wzMi4yMSAyLjMxYTE3Mi44NiAxNzIuODYgMCAwIDAtMy0yNS41OWwtMzIuNSAxLjExYTE0MSAxNDEgMCAwIDEgMy4yNSAyMi4xNyIgY2xhc3M9ImNscy0xMyIvPjxwYXRoIGlkPSJwYXRoMTI0IiBkPSJNMTgyIDMyMC44MWMtNzguMiAwLTE0MS44My02My42Mi0xNDEuODMtMTQxLjgyUzEwMy44MiAzNy4xNiAxODIgMzcuMTZhMTQwLjkzIDE0MC45MyAwIDAgMSA3Ni4zIDIyLjM0TDI4MC44NSAzNkExNzIuODYgMTcyLjg2IDAgMCAwIDE4MiA1LjExQzg2LjE1IDUuMTEgOC4xNSA4My4xMSA4LjE1IDE3OXM3OCAxNzMuODUgMTczLjg1IDE3My44NWM4MS45IDAgMTUwLjY5LTU3IDE2OS0xMzMuMzJMMzIwLjYyIDIwOWMtMTMuOCA2My44NC03MC42OSAxMTEuODMtMTM4LjYgMTExLjgzIiBjbGFzcz0iY2xzLTEzIi8+PGcgaWQ9ImcxMjYiIGNsaXAtcGF0aD0idXJsKCNjbGlwLXBhdGgtNikiPjxnIGlkPSJnMTI4Ij48cGF0aCBpZD0icGF0aDE0MiIgZmlsbD0idXJsKCNsaW5lYXItZ3JhZGllbnQtNikiIGQ9Ik0zMTMuMTMgNjcuNTlhMTc1LjMxIDE3NS4zMSAwIDAgMC0yOS43NS0yOC4xM2MtMS41Ny0xLjE3LTMuMTgtMi4zLTQuNzktMy40MkwyNTYgNTkuNWwtODIuMzQgODUuNjMgMTEzLjQxLTU4LjY4IDI5LjA3LTE1Yy0xLTEuMjctMi0yLjU4LTMtMy44MiIvPjwvZz48L2c+PGcgaWQ9ImcxNDQiIGNsaXAtcGF0aD0idXJsKCNjbGlwLXBhdGgtNykiPjxnIGlkPSJnMTQ2Ij48cGF0aCBpZD0icGF0aDE2MCIgZmlsbD0idXJsKCNsaW5lYXItZ3JhZGllbnQtNykiIGQ9Ik0zNTMuNTkgMTc3LjYxYzAtMi0uMTQtNC0uMjItNS45M2wtMzIuMjEtMi4zMS0xNDcuNDctMTAuNThMMzE4LjM2IDIwOWwzMC40MSAxMC41NWMuMDktLjM2LjE5LS43MS4yOC0xLjA4YTE3My42NSAxNzMuNjUgMCAwIDAgNC41Ny0zOS40N3YtMS4zNyIvPjwvZz48L2c+PGcgaWQ9ImcxNjIiIGNsaXAtcGF0aD0idXJsKCNjbGlwLXBhdGgtOCkiPjxnIGlkPSJnMTY0Ij48cGF0aCBpZD0icGF0aDE3OCIgZmlsbD0idXJsKCNsaW5lYXItZ3JhZGllbnQtOCkiIGQ9Ik0zNDguODQgMTM4LjYxYTE3Mi41NSAxNzIuNTUgMCAwIDAtMTMuODQtMzcuN2wtMzAuOTQgOS45NEwxNzUuOTIgMTUybDE0Mi00LjgzIDMyLjUtMS4xMWMtLjQ4LTIuNTEtMS01LTEuNTYtNy40OCIvPjwvZz48L2c+PC9nPjwvc3ZnPg==" - keysOrder: [["apiVersion"], ["appVersion"], ["kind"], ["metadata"], ["metadata", "name"], ["spec", "host"], ["spec", "storageClass"], ["spec", "core"], ["spec", "core", "resources"], ["spec", "core", "resourcesPreset"], ["spec", "registry"], ["spec", "registry", "resources"], ["spec", "registry", "resourcesPreset"], ["spec", "jobservice"], ["spec", "jobservice", "resources"], ["spec", "jobservice", "resourcesPreset"], ["spec", "trivy"], ["spec", "trivy", "enabled"], ["spec", "trivy", "size"], ["spec", "trivy", "resources"], ["spec", "trivy", "resourcesPreset"], ["spec", "database"], ["spec", "database", "size"], ["spec", "database", "replicas"], ["spec", "redis"], ["spec", "redis", "size"], ["spec", "redis", "replicas"]] + keysOrder: [["apiVersion"], ["appVersion"], ["kind"], ["metadata"], ["metadata", "name"], ["spec", "host"], ["spec", "managementWhitelist"], ["spec", "storageClass"], ["spec", "core"], ["spec", "core", "resources"], ["spec", "core", "resourcesPreset"], ["spec", "registry"], ["spec", "registry", "resources"], ["spec", "registry", "resourcesPreset"], ["spec", "jobservice"], ["spec", "jobservice", "resources"], ["spec", "jobservice", "resourcesPreset"], ["spec", "trivy"], ["spec", "trivy", "enabled"], ["spec", "trivy", "size"], ["spec", "trivy", "resources"], ["spec", "trivy", "resourcesPreset"], ["spec", "database"], ["spec", "database", "size"], ["spec", "database", "replicas"], ["spec", "redis"], ["spec", "redis", "size"], ["spec", "redis", "replicas"]] secrets: exclude: [] include: @@ -45,3 +45,4 @@ spec: include: - resourceNames: - "harbor-{{ .name }}-ingress" + - "harbor-{{ .name }}-registry-ingress" From 46674f80e7e1fdb8e799eac1def131f0fd48f49c Mon Sep 17 00:00:00 2001 From: Aleksei Sviridkin Date: Thu, 24 Sep 2026 15:02:12 +0300 Subject: [PATCH 0026/1280] docs(kubevirt): state the preconditions of the eviction comments The comments on evictionStrategy and workloadUpdateMethods described the new behaviour as if it applied to every VMI. The VMI mutator stamps the cluster strategy into the spec at creation, so a VMI started before LiveMigrateIfPossible keeps LiveMigrate: if it cannot migrate, its drain still blocks and the workload updater's eviction is refused until its VM restarts. The worker case pointed at the wrong mechanism too. CAPK reports a non-migratable VMI under evacuation as a terminal failure, and every kubernetes-nodes group has a MachineHealthCheck, so the Machine gets replaced. Where maxUnhealthy holds remediation back the VM restarts in place, but the failure is never cleared, so the Machine is still replaced later. Assisted-by: LLM Signed-off-by: Aleksei Sviridkin --- .../system/kubevirt/templates/kubevirt-cr.yaml | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/packages/system/kubevirt/templates/kubevirt-cr.yaml b/packages/system/kubevirt/templates/kubevirt-cr.yaml index 379b5f2cf..2e2845bf1 100644 --- a/packages/system/kubevirt/templates/kubevirt-cr.yaml +++ b/packages/system/kubevirt/templates/kubevirt-cr.yaml @@ -123,16 +123,20 @@ spec: migrations: {{- toYaml . | nindent 6 }} {{- end }} - evictionStrategy: LiveMigrateIfPossible # a VMI that cannot live-migrate is evicted instead of blocking the node drain + evictionStrategy: LiveMigrateIfPossible # a VMI that cannot live-migrate is evicted instead of blocking the drain; a VMI keeps the strategy it was created with, so a non-migratable one created before this value still blocks until its VM is restarted virtualMachineOptions: disableSerialConsoleLog: {} vmRolloutStrategy: LiveUpdate workloadUpdateStrategy: - # Evict shuts down VMs that cannot migrate on a KubeVirt upgrade, but it is - # also how such a kubernetes-nodes worker (evictionStrategy External) gets - # the new launcher without a rollout: the eviction marks the VMI for - # evacuation, CAPK drains the tenant node and deletes the VMI, and the VM - # starts it again. + # Evict shuts down VMs that cannot migrate on a KubeVirt upgrade; a VMI still + # carrying LiveMigrate from before evictionStrategy changed refuses the + # eviction and stays on the old launcher. Evict is also how a non-migratable + # kubernetes-nodes worker (evictionStrategy External) gets the new launcher: + # the eviction marks the VMI for evacuation, CAPK drains the tenant node and + # deletes the VMI, and it also marks the KubevirtMachine failed, so the node + # group's MachineHealthCheck replaces the Machine. Where maxUnhealthy holds + # remediation back, the VM starts a new VMI but the Machine stays failed and + # is replaced once remediation is allowed. workloadUpdateMethods: - LiveMigrate - Evict From fd2a6a05e4167893cb43a47a0f82a5579c54c84e Mon Sep 17 00:00:00 2001 From: Aleksei Sviridkin Date: Thu, 24 Sep 2026 15:52:35 +0300 Subject: [PATCH 0027/1280] fix(harbor): refuse managementWhitelist entries that are not addresses ingress-nginx reads an empty whitelist-source-range as no annotation and falls back to the open default, so managementWhitelist: [""] rendered a split that looked restricted while the portal and API stayed public. One unparseable entry went the other way and turned the whole portal location into a 503. The values schema generator has no item-level constraints, so each entry is checked at render time and a bad one fails the release with the offending value in the message. IPv4 is matched strictly; IPv6 by character set only, which still leaves a malformed IPv6 entry failing closed in the controller. Assisted-by: LLM Signed-off-by: Aleksei Sviridkin --- packages/apps/harbor/templates/ingress.yaml | 13 +++ .../ingress_management_whitelist_test.yaml | 81 +++++++++++++++++++ 2 files changed, 94 insertions(+) diff --git a/packages/apps/harbor/templates/ingress.yaml b/packages/apps/harbor/templates/ingress.yaml index 023daf121..7a0cbdbb1 100644 --- a/packages/apps/harbor/templates/ingress.yaml +++ b/packages/apps/harbor/templates/ingress.yaml @@ -13,6 +13,19 @@ nginx.ingress.kubernetes.io/backend-protocol: "HTTP" {{- $clusterIssuer := (index .Values._cluster "issuer-name") | default "letsencrypt-prod" }} {{- $wildcardSecret := (index .Values._cluster "wildcard-secret-name") | default "" }} {{- if not $gateway }} +{{- /* ingress-nginx reads an empty whitelist-source-range as no annotation + and serves the portal to everyone, and one unparseable entry turns the + whole location into a 503. The values schema cannot validate list + items, so the check lives here. IPv6 is matched by character set only; + a malformed IPv6 entry still fails closed in the controller. */}} +{{- $octet := "(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])" }} +{{- $ipv4 := printf "^%s(\\.%s){3}(/(3[0-2]|[12]?[0-9]))?$" $octet $octet }} +{{- $ipv6 := "^[0-9A-Fa-f.]*:[0-9A-Fa-f:.]*(/(12[0-8]|1[01][0-9]|[1-9]?[0-9]))?$" }} +{{- range .Values.managementWhitelist }} +{{- if not (or (regexMatch $ipv4 (toString .)) (regexMatch $ipv6 (toString .))) }} +{{- fail (printf "managementWhitelist entry %q is not an IP address or CIDR range" (toString .)) }} +{{- end }} +{{- end }} --- apiVersion: networking.k8s.io/v1 kind: Ingress diff --git a/packages/apps/harbor/tests/ingress_management_whitelist_test.yaml b/packages/apps/harbor/tests/ingress_management_whitelist_test.yaml index 2923cb2ab..b5d14fd7e 100644 --- a/packages/apps/harbor/tests/ingress_management_whitelist_test.yaml +++ b/packages/apps/harbor/tests/ingress_management_whitelist_test.yaml @@ -91,6 +91,87 @@ tests: port: number: 80 + - it: accepts bare addresses and ranges of both families + template: templates/ingress.yaml + documentSelector: + path: metadata.name + value: harbor-ingress + set: + managementWhitelist: + - 203.0.113.9 + - 0.0.0.0/0 + - 2001:db8::1 + - 2001:db8::/32 + - ::ffff:192.0.2.1/128 + asserts: + - equal: + path: metadata.annotations["nginx.ingress.kubernetes.io/whitelist-source-range"] + value: 203.0.113.9,0.0.0.0/0,2001:db8::1,2001:db8::/32,::ffff:192.0.2.1/128 + + - it: refuses an empty entry, which ingress-nginx would read as no restriction + template: templates/ingress.yaml + set: + managementWhitelist: + - "" + asserts: + - failedTemplate: + errorPattern: 'managementWhitelist entry "" is not an IP address or CIDR range' + + - it: refuses a whitespace-only entry + template: templates/ingress.yaml + set: + managementWhitelist: + - " " + asserts: + - failedTemplate: + errorPattern: 'managementWhitelist entry " " is not' + + - it: refuses a prefix length out of range + template: templates/ingress.yaml + set: + managementWhitelist: + - 10.0.0.0/99 + asserts: + - failedTemplate: + errorPattern: 'managementWhitelist entry "10.0.0.0/99" is not' + + - it: refuses an IPv4 octet out of range + template: templates/ingress.yaml + set: + managementWhitelist: + - 192.0.2.256 + asserts: + - failedTemplate: + errorPattern: 'managementWhitelist entry "192.0.2.256" is not' + + - it: refuses a hostname + template: templates/ingress.yaml + set: + managementWhitelist: + - not-an-ip + asserts: + - failedTemplate: + errorPattern: 'managementWhitelist entry "not-an-ip" is not' + + - it: refuses two ranges packed into one entry + template: templates/ingress.yaml + set: + managementWhitelist: + - 192.0.2.0/24,198.51.100.0/24 + asserts: + - failedTemplate: + errorPattern: 'managementWhitelist entry "192.0.2.0/24,198.51.100.0/24" is not' + + - it: refuses a bad entry mixed with good ones + template: templates/ingress.yaml + set: + managementWhitelist: + - 192.0.2.0/24 + - 2001:db8::/129 + asserts: + - failedTemplate: + errorPattern: 'managementWhitelist entry "2001:db8::/129" is not' + - it: serves the registry API and token endpoint from an unrestricted Ingress on the same host and certificate template: templates/ingress.yaml documentSelector: From 8a5cfbe1cbb3892c4b5484952f42bcf6777fa53b Mon Sep 17 00:00:00 2001 From: Aleksei Sviridkin Date: Thu, 24 Sep 2026 15:53:00 +0300 Subject: [PATCH 0028/1280] docs(harbor): say what managementWhitelist overrides and trusts A per-Ingress whitelist-source-range replaces the controller-wide default that the tenant ingress whitelist sets, so for the portal and API the Harbor list is not an intersection: an address the tenant policy excluded gets in when it is on this list. The description also promised that every other path is restricted, which holds only while the controller sees the real client address. Behind a proxy or with a header-derived client address the check runs against that instead. Assisted-by: LLM Signed-off-by: Aleksei Sviridkin --- api/apps/v1alpha1/harbor/types.go | 2 +- packages/apps/harbor/README.md | 10 +++++----- packages/apps/harbor/values.schema.json | 2 +- packages/apps/harbor/values.yaml | 2 +- packages/system/harbor-rd/cozyrds/harbor.yaml | 2 +- 5 files changed, 9 insertions(+), 9 deletions(-) diff --git a/api/apps/v1alpha1/harbor/types.go b/api/apps/v1alpha1/harbor/types.go index 2a7af004d..d5638214e 100644 --- a/api/apps/v1alpha1/harbor/types.go +++ b/api/apps/v1alpha1/harbor/types.go @@ -20,7 +20,7 @@ type ConfigSpec struct { // Hostname for external access to Harbor (defaults to 'harbor' subdomain for the tenant host). // +kubebuilder:default:="" Host string `json:"host,omitempty"` - // IP addresses or CIDR ranges allowed to reach the Harbor web portal and API. Only `/v2/` and `/service/token` stay open to any address, which is what `docker login`, image pulls and pushes use; every other path on the Harbor host is restricted. Empty allows every address. Requires Ingress publishing; rejected when the tenant publishes through Gateway API. + // IP addresses or CIDR ranges allowed to reach the Harbor web portal and API. `/v2/` and `/service/token`, which `docker login`, image pulls and pushes use, are not restricted by this list. For the portal and API it replaces the tenant ingress `whitelist` rather than narrowing it, and it is matched against the client address the ingress controller sees, which is a proxy or a forwarded header rather than the real client when something in front of the controller rewrites it. Empty allows every address. Requires Ingress publishing; rejected when the tenant publishes through Gateway API. // +kubebuilder:default:={} ManagementWhitelist []string `json:"managementWhitelist,omitempty"` // StorageClass used to store the data. diff --git a/packages/apps/harbor/README.md b/packages/apps/harbor/README.md index 640cabd39..7a036d7a0 100644 --- a/packages/apps/harbor/README.md +++ b/packages/apps/harbor/README.md @@ -20,11 +20,11 @@ Without object storage in the tenant chain, Harbor cannot provision its registry ### Common parameters -| Name | Description | Type | Value | -| --------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------- | ----- | -| `host` | Hostname for external access to Harbor (defaults to 'harbor' subdomain for the tenant host). | `string` | `""` | -| `managementWhitelist` | IP addresses or CIDR ranges allowed to reach the Harbor web portal and API. Only `/v2/` and `/service/token` stay open to any address, which is what `docker login`, image pulls and pushes use; every other path on the Harbor host is restricted. Empty allows every address. Requires Ingress publishing; rejected when the tenant publishes through Gateway API. | `[]string` | `[]` | -| `storageClass` | StorageClass used to store the data. | `string` | `""` | +| Name | Description | Type | Value | +| --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------- | ----- | +| `host` | Hostname for external access to Harbor (defaults to 'harbor' subdomain for the tenant host). | `string` | `""` | +| `managementWhitelist` | IP addresses or CIDR ranges allowed to reach the Harbor web portal and API. `/v2/` and `/service/token`, which `docker login`, image pulls and pushes use, are not restricted by this list. For the portal and API it replaces the tenant ingress `whitelist` rather than narrowing it, and it is matched against the client address the ingress controller sees, which is a proxy or a forwarded header rather than the real client when something in front of the controller rewrites it. Empty allows every address. Requires Ingress publishing; rejected when the tenant publishes through Gateway API. | `[]string` | `[]` | +| `storageClass` | StorageClass used to store the data. | `string` | `""` | ### Component configuration diff --git a/packages/apps/harbor/values.schema.json b/packages/apps/harbor/values.schema.json index c266ed895..5427370ec 100644 --- a/packages/apps/harbor/values.schema.json +++ b/packages/apps/harbor/values.schema.json @@ -8,7 +8,7 @@ "default": "" }, "managementWhitelist": { - "description": "IP addresses or CIDR ranges allowed to reach the Harbor web portal and API. Only `/v2/` and `/service/token` stay open to any address, which is what `docker login`, image pulls and pushes use; every other path on the Harbor host is restricted. Empty allows every address. Requires Ingress publishing; rejected when the tenant publishes through Gateway API.", + "description": "IP addresses or CIDR ranges allowed to reach the Harbor web portal and API. `/v2/` and `/service/token`, which `docker login`, image pulls and pushes use, are not restricted by this list. For the portal and API it replaces the tenant ingress `whitelist` rather than narrowing it, and it is matched against the client address the ingress controller sees, which is a proxy or a forwarded header rather than the real client when something in front of the controller rewrites it. Empty allows every address. Requires Ingress publishing; rejected when the tenant publishes through Gateway API.", "type": "array", "default": [], "items": { diff --git a/packages/apps/harbor/values.yaml b/packages/apps/harbor/values.yaml index 4fd3ac5e7..364871884 100644 --- a/packages/apps/harbor/values.yaml +++ b/packages/apps/harbor/values.yaml @@ -5,7 +5,7 @@ ## @param {string} [host] - Hostname for external access to Harbor (defaults to 'harbor' subdomain for the tenant host). host: "" -## @param {[]string} [managementWhitelist] - IP addresses or CIDR ranges allowed to reach the Harbor web portal and API. Only `/v2/` and `/service/token` stay open to any address, which is what `docker login`, image pulls and pushes use; every other path on the Harbor host is restricted. Empty allows every address. Requires Ingress publishing; rejected when the tenant publishes through Gateway API. +## @param {[]string} [managementWhitelist] - IP addresses or CIDR ranges allowed to reach the Harbor web portal and API. `/v2/` and `/service/token`, which `docker login`, image pulls and pushes use, are not restricted by this list. For the portal and API it replaces the tenant ingress `whitelist` rather than narrowing it, and it is matched against the client address the ingress controller sees, which is a proxy or a forwarded header rather than the real client when something in front of the controller rewrites it. Empty allows every address. Requires Ingress publishing; rejected when the tenant publishes through Gateway API. managementWhitelist: [] ## @param {string} storageClass - StorageClass used to store the data. diff --git a/packages/system/harbor-rd/cozyrds/harbor.yaml b/packages/system/harbor-rd/cozyrds/harbor.yaml index 658213908..32913a044 100644 --- a/packages/system/harbor-rd/cozyrds/harbor.yaml +++ b/packages/system/harbor-rd/cozyrds/harbor.yaml @@ -8,7 +8,7 @@ spec: singular: harbor plural: harbors openAPISchema: |- - {"title":"Chart Values","type":"object","properties":{"host":{"description":"Hostname for external access to Harbor (defaults to 'harbor' subdomain for the tenant host).","type":"string","default":""},"managementWhitelist":{"description":"IP addresses or CIDR ranges allowed to reach the Harbor web portal and API. Only `/v2/` and `/service/token` stay open to any address, which is what `docker login`, image pulls and pushes use; every other path on the Harbor host is restricted. Empty allows every address. Requires Ingress publishing; rejected when the tenant publishes through Gateway API.","type":"array","default":[],"items":{"type":"string"}},"storageClass":{"description":"StorageClass used to store the data.","type":"string","default":"","x-kubernetes-validations":[{"rule":"self == oldSelf","message":"storageClass is immutable"}],"x-cozystack-options":{"source":"storageclass"}},"core":{"description":"Core API server configuration.","type":"object","default":{},"properties":{"resources":{"description":"Explicit CPU and memory configuration. When omitted, the preset defined in `resourcesPreset` is applied.","type":"object","default":{},"properties":{"cpu":{"description":"Number of CPU cores allocated.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"memory":{"description":"Amount of memory allocated.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true}}},"resourcesPreset":{"description":"Default sizing preset used when `resources` is omitted.","type":"string","default":"t1.small","enum":["t1.nano","t1.micro","t1.small","t1.medium","t1.large","t1.xlarge","t1.2xlarge","t1.4xlarge","c1.nano","c1.micro","c1.small","c1.medium","c1.large","c1.xlarge","c1.2xlarge","c1.4xlarge","s1.nano","s1.micro","s1.small","s1.medium","s1.large","s1.xlarge","s1.2xlarge","s1.4xlarge","u1.nano","u1.micro","u1.small","u1.medium","u1.large","u1.xlarge","u1.2xlarge","u1.4xlarge","m1.nano","m1.micro","m1.small","m1.medium","m1.large","m1.xlarge","m1.2xlarge","m1.4xlarge","nano","micro","small","medium","large","xlarge","2xlarge"]}}},"registry":{"description":"Container image registry configuration.","type":"object","default":{},"properties":{"resources":{"description":"Explicit CPU and memory configuration. When omitted, the preset defined in `resourcesPreset` is applied.","type":"object","default":{},"properties":{"cpu":{"description":"Number of CPU cores allocated.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"memory":{"description":"Amount of memory allocated.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true}}},"resourcesPreset":{"description":"Default sizing preset used when `resources` is omitted.","type":"string","default":"t1.small","enum":["t1.nano","t1.micro","t1.small","t1.medium","t1.large","t1.xlarge","t1.2xlarge","t1.4xlarge","c1.nano","c1.micro","c1.small","c1.medium","c1.large","c1.xlarge","c1.2xlarge","c1.4xlarge","s1.nano","s1.micro","s1.small","s1.medium","s1.large","s1.xlarge","s1.2xlarge","s1.4xlarge","u1.nano","u1.micro","u1.small","u1.medium","u1.large","u1.xlarge","u1.2xlarge","u1.4xlarge","m1.nano","m1.micro","m1.small","m1.medium","m1.large","m1.xlarge","m1.2xlarge","m1.4xlarge","nano","micro","small","medium","large","xlarge","2xlarge"]}}},"jobservice":{"description":"Background job service configuration.","type":"object","default":{},"properties":{"resources":{"description":"Explicit CPU and memory configuration. When omitted, the preset defined in `resourcesPreset` is applied.","type":"object","default":{},"properties":{"cpu":{"description":"Number of CPU cores allocated.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"memory":{"description":"Amount of memory allocated.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true}}},"resourcesPreset":{"description":"Default sizing preset used when `resources` is omitted.","type":"string","default":"t1.nano","enum":["t1.nano","t1.micro","t1.small","t1.medium","t1.large","t1.xlarge","t1.2xlarge","t1.4xlarge","c1.nano","c1.micro","c1.small","c1.medium","c1.large","c1.xlarge","c1.2xlarge","c1.4xlarge","s1.nano","s1.micro","s1.small","s1.medium","s1.large","s1.xlarge","s1.2xlarge","s1.4xlarge","u1.nano","u1.micro","u1.small","u1.medium","u1.large","u1.xlarge","u1.2xlarge","u1.4xlarge","m1.nano","m1.micro","m1.small","m1.medium","m1.large","m1.xlarge","m1.2xlarge","m1.4xlarge","nano","micro","small","medium","large","xlarge","2xlarge"]}}},"trivy":{"description":"Trivy vulnerability scanner configuration.","type":"object","default":{},"required":["enabled","size"],"properties":{"enabled":{"description":"Enable or disable the vulnerability scanner.","type":"boolean","default":true},"resources":{"description":"Explicit CPU and memory configuration. When omitted, the preset defined in `resourcesPreset` is applied.","type":"object","default":{},"properties":{"cpu":{"description":"Number of CPU cores allocated.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"memory":{"description":"Amount of memory allocated.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true}}},"resourcesPreset":{"description":"Default sizing preset used when `resources` is omitted.","type":"string","default":"t1.nano","enum":["t1.nano","t1.micro","t1.small","t1.medium","t1.large","t1.xlarge","t1.2xlarge","t1.4xlarge","c1.nano","c1.micro","c1.small","c1.medium","c1.large","c1.xlarge","c1.2xlarge","c1.4xlarge","s1.nano","s1.micro","s1.small","s1.medium","s1.large","s1.xlarge","s1.2xlarge","s1.4xlarge","u1.nano","u1.micro","u1.small","u1.medium","u1.large","u1.xlarge","u1.2xlarge","u1.4xlarge","m1.nano","m1.micro","m1.small","m1.medium","m1.large","m1.xlarge","m1.2xlarge","m1.4xlarge","nano","micro","small","medium","large","xlarge","2xlarge"]},"size":{"description":"Persistent Volume size for vulnerability database cache.","default":"5Gi","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true}}},"database":{"description":"PostgreSQL database configuration.","type":"object","default":{},"required":["replicas","size"],"properties":{"replicas":{"description":"Number of database instances.","type":"integer","default":2},"size":{"description":"Persistent Volume size for database storage.","default":"5Gi","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true}}},"redis":{"description":"Redis cache configuration.","type":"object","default":{},"required":["replicas","size"],"properties":{"replicas":{"description":"Number of Redis replicas.","type":"integer","default":2},"size":{"description":"Persistent Volume size for cache storage.","default":"1Gi","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true}}}}} + {"title":"Chart Values","type":"object","properties":{"host":{"description":"Hostname for external access to Harbor (defaults to 'harbor' subdomain for the tenant host).","type":"string","default":""},"managementWhitelist":{"description":"IP addresses or CIDR ranges allowed to reach the Harbor web portal and API. `/v2/` and `/service/token`, which `docker login`, image pulls and pushes use, are not restricted by this list. For the portal and API it replaces the tenant ingress `whitelist` rather than narrowing it, and it is matched against the client address the ingress controller sees, which is a proxy or a forwarded header rather than the real client when something in front of the controller rewrites it. Empty allows every address. Requires Ingress publishing; rejected when the tenant publishes through Gateway API.","type":"array","default":[],"items":{"type":"string"}},"storageClass":{"description":"StorageClass used to store the data.","type":"string","default":"","x-kubernetes-validations":[{"rule":"self == oldSelf","message":"storageClass is immutable"}],"x-cozystack-options":{"source":"storageclass"}},"core":{"description":"Core API server configuration.","type":"object","default":{},"properties":{"resources":{"description":"Explicit CPU and memory configuration. When omitted, the preset defined in `resourcesPreset` is applied.","type":"object","default":{},"properties":{"cpu":{"description":"Number of CPU cores allocated.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"memory":{"description":"Amount of memory allocated.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true}}},"resourcesPreset":{"description":"Default sizing preset used when `resources` is omitted.","type":"string","default":"t1.small","enum":["t1.nano","t1.micro","t1.small","t1.medium","t1.large","t1.xlarge","t1.2xlarge","t1.4xlarge","c1.nano","c1.micro","c1.small","c1.medium","c1.large","c1.xlarge","c1.2xlarge","c1.4xlarge","s1.nano","s1.micro","s1.small","s1.medium","s1.large","s1.xlarge","s1.2xlarge","s1.4xlarge","u1.nano","u1.micro","u1.small","u1.medium","u1.large","u1.xlarge","u1.2xlarge","u1.4xlarge","m1.nano","m1.micro","m1.small","m1.medium","m1.large","m1.xlarge","m1.2xlarge","m1.4xlarge","nano","micro","small","medium","large","xlarge","2xlarge"]}}},"registry":{"description":"Container image registry configuration.","type":"object","default":{},"properties":{"resources":{"description":"Explicit CPU and memory configuration. When omitted, the preset defined in `resourcesPreset` is applied.","type":"object","default":{},"properties":{"cpu":{"description":"Number of CPU cores allocated.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"memory":{"description":"Amount of memory allocated.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true}}},"resourcesPreset":{"description":"Default sizing preset used when `resources` is omitted.","type":"string","default":"t1.small","enum":["t1.nano","t1.micro","t1.small","t1.medium","t1.large","t1.xlarge","t1.2xlarge","t1.4xlarge","c1.nano","c1.micro","c1.small","c1.medium","c1.large","c1.xlarge","c1.2xlarge","c1.4xlarge","s1.nano","s1.micro","s1.small","s1.medium","s1.large","s1.xlarge","s1.2xlarge","s1.4xlarge","u1.nano","u1.micro","u1.small","u1.medium","u1.large","u1.xlarge","u1.2xlarge","u1.4xlarge","m1.nano","m1.micro","m1.small","m1.medium","m1.large","m1.xlarge","m1.2xlarge","m1.4xlarge","nano","micro","small","medium","large","xlarge","2xlarge"]}}},"jobservice":{"description":"Background job service configuration.","type":"object","default":{},"properties":{"resources":{"description":"Explicit CPU and memory configuration. When omitted, the preset defined in `resourcesPreset` is applied.","type":"object","default":{},"properties":{"cpu":{"description":"Number of CPU cores allocated.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"memory":{"description":"Amount of memory allocated.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true}}},"resourcesPreset":{"description":"Default sizing preset used when `resources` is omitted.","type":"string","default":"t1.nano","enum":["t1.nano","t1.micro","t1.small","t1.medium","t1.large","t1.xlarge","t1.2xlarge","t1.4xlarge","c1.nano","c1.micro","c1.small","c1.medium","c1.large","c1.xlarge","c1.2xlarge","c1.4xlarge","s1.nano","s1.micro","s1.small","s1.medium","s1.large","s1.xlarge","s1.2xlarge","s1.4xlarge","u1.nano","u1.micro","u1.small","u1.medium","u1.large","u1.xlarge","u1.2xlarge","u1.4xlarge","m1.nano","m1.micro","m1.small","m1.medium","m1.large","m1.xlarge","m1.2xlarge","m1.4xlarge","nano","micro","small","medium","large","xlarge","2xlarge"]}}},"trivy":{"description":"Trivy vulnerability scanner configuration.","type":"object","default":{},"required":["enabled","size"],"properties":{"enabled":{"description":"Enable or disable the vulnerability scanner.","type":"boolean","default":true},"resources":{"description":"Explicit CPU and memory configuration. When omitted, the preset defined in `resourcesPreset` is applied.","type":"object","default":{},"properties":{"cpu":{"description":"Number of CPU cores allocated.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"memory":{"description":"Amount of memory allocated.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true}}},"resourcesPreset":{"description":"Default sizing preset used when `resources` is omitted.","type":"string","default":"t1.nano","enum":["t1.nano","t1.micro","t1.small","t1.medium","t1.large","t1.xlarge","t1.2xlarge","t1.4xlarge","c1.nano","c1.micro","c1.small","c1.medium","c1.large","c1.xlarge","c1.2xlarge","c1.4xlarge","s1.nano","s1.micro","s1.small","s1.medium","s1.large","s1.xlarge","s1.2xlarge","s1.4xlarge","u1.nano","u1.micro","u1.small","u1.medium","u1.large","u1.xlarge","u1.2xlarge","u1.4xlarge","m1.nano","m1.micro","m1.small","m1.medium","m1.large","m1.xlarge","m1.2xlarge","m1.4xlarge","nano","micro","small","medium","large","xlarge","2xlarge"]},"size":{"description":"Persistent Volume size for vulnerability database cache.","default":"5Gi","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true}}},"database":{"description":"PostgreSQL database configuration.","type":"object","default":{},"required":["replicas","size"],"properties":{"replicas":{"description":"Number of database instances.","type":"integer","default":2},"size":{"description":"Persistent Volume size for database storage.","default":"5Gi","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true}}},"redis":{"description":"Redis cache configuration.","type":"object","default":{},"required":["replicas","size"],"properties":{"replicas":{"description":"Number of Redis replicas.","type":"integer","default":2},"size":{"description":"Persistent Volume size for cache storage.","default":"1Gi","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true}}}}} release: prefix: "harbor-" labels: From 47caa2a227dca5fa810005f1dd3809a6cad0a5fd Mon Sep 17 00:00:00 2001 From: Aleksei Sviridkin Date: Thu, 24 Sep 2026 23:11:30 +0300 Subject: [PATCH 0029/1280] fix(kamaji): drop any subchart nested under the vendored kamaji chart The vendored kamaji chart declares a kamaji-etcd dependency gated on kamaji-etcd.deploy. That condition is never evaluated here: Helm's processDependencyEnabled returns before recursing when the chart it starts from declares no dependencies, and this umbrella declares none. A chart placed under charts/kamaji/charts would therefore render whatever the values say, deploying an etcd nobody asked for. Upstream does not ship that directory today, so the update recipe produces the same tree as before; removing it after extraction keeps it that way if upstream ever starts committing the packaged subchart. Assisted-by: LLM Signed-off-by: Aleksei Sviridkin --- packages/system/kamaji/Makefile | 2 ++ 1 file changed, 2 insertions(+) diff --git a/packages/system/kamaji/Makefile b/packages/system/kamaji/Makefile index 6302e11e3..811b4c84e 100644 --- a/packages/system/kamaji/Makefile +++ b/packages/system/kamaji/Makefile @@ -14,6 +14,8 @@ update: # `make update` stays reproducible. Mirrors the pattern used by # packages/system/ingress-nginx. patch --no-backup-if-mismatch -p1 < patches/1.diff + # cozy-kamaji declares no dependencies, so Helm's processDependencyEnabled never evaluates kamaji-etcd.deploy and any subchart here always renders. + rm -rf charts/kamaji/charts image: docker buildx build images/kamaji \ From dd1fbf9bbb12df1068565794037cc25b1dfd32da Mon Sep 17 00:00:00 2001 From: Aleksei Sviridkin Date: Thu, 24 Sep 2026 23:11:39 +0300 Subject: [PATCH 0030/1280] test(kamaji): fail when a nested subchart renders anything A subchart under charts/kamaji/charts deploys unconditionally through this umbrella, so the suite asserts that no template there produces a document. It is the package's first helm-unittest suite, so the Makefile gains the test target the repository sweep discovers, and the suite directory is kept out of the packaged chart. Assisted-by: LLM Signed-off-by: Aleksei Sviridkin --- packages/system/kamaji/.helmignore | 1 + packages/system/kamaji/Makefile | 3 +++ .../system/kamaji/tests/nested_subchart_test.yaml | 12 ++++++++++++ 3 files changed, 16 insertions(+) create mode 100644 packages/system/kamaji/tests/nested_subchart_test.yaml diff --git a/packages/system/kamaji/.helmignore b/packages/system/kamaji/.helmignore index cd2b36066..f143b5d6c 100644 --- a/packages/system/kamaji/.helmignore +++ b/packages/system/kamaji/.helmignore @@ -1,2 +1,3 @@ /images /hack +/tests diff --git a/packages/system/kamaji/Makefile b/packages/system/kamaji/Makefile index 811b4c84e..f286fb13f 100644 --- a/packages/system/kamaji/Makefile +++ b/packages/system/kamaji/Makefile @@ -4,6 +4,9 @@ export NAMESPACE=cozy-$(NAME) include ../../../hack/common-envs.mk include ../../../hack/package.mk +test: + helm unittest . + update: rm -rf charts tag=$$(git ls-remote --tags --sort="v:refname" https://github.com/clastix/kamaji | grep -E 'refs/tags/[0-9]+\.[0-9]+\.[0-9]+-edge$$' | awk -F/ 'END{print $$NF}') && \ diff --git a/packages/system/kamaji/tests/nested_subchart_test.yaml b/packages/system/kamaji/tests/nested_subchart_test.yaml new file mode 100644 index 000000000..29598e805 --- /dev/null +++ b/packages/system/kamaji/tests/nested_subchart_test.yaml @@ -0,0 +1,12 @@ +suite: no subchart is vendored under charts/kamaji + +# The kamaji-etcd dependency's condition is never evaluated through this +# umbrella chart, so any chart placed under charts/kamaji/charts deploys. +templates: + - "charts/kamaji/charts/*/templates/*" + +tests: + - it: renders nothing from a nested subchart + asserts: + - hasDocuments: + count: 0 From 4910bc536edbfa969d858cd61af61441496a5ea4 Mon Sep 17 00:00:00 2001 From: Aleksei Sviridkin Date: Thu, 24 Sep 2026 23:08:13 +0300 Subject: [PATCH 0031/1280] test(e2e): wait for the opensearch handoff before the first API call The first OpenSearch API call in the suite ran as soon as the data node reported Ready. At that point the operator's bootstrap pod can still be the elected cluster-manager, and until its own security configuration loads it answers a cluster-manager action such as an index create with 503. The operator deletes the pod only after it has left the committed voting configuration, so once the pod object is gone the cluster-manager is the Ready data node. The same Initialized flag that starts the handoff also releases a rolling restart that can be pending since first boot, and with one replica that restart takes the only node down. The step therefore also waits for the StatefulSet to settle on its update revision. Assisted-by: LLM Signed-off-by: Aleksei Sviridkin --- .../opensearch/chainsaw-test.yaml | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/hack/e2e-chainsaw/opensearch/chainsaw-test.yaml b/hack/e2e-chainsaw/opensearch/chainsaw-test.yaml index a4ca434cb..a70381888 100644 --- a/hack/e2e-chainsaw/opensearch/chainsaw-test.yaml +++ b/hack/e2e-chainsaw/opensearch/chainsaw-test.yaml @@ -197,6 +197,33 @@ spec: # roll below always has to get through a yellow cluster. - name: make-the-cluster-permanently-yellow try: + # The bootstrap pod stays cluster-manager after the data node is Ready, and + # answers 503 until its own security config loads; once it is gone, the + # Ready data node is the manager. The handoff takes seconds; 3m leaves room + # for several 10s retire retries, a 30s requeue and the 30s grace period. + - error: + timeout: 3m + resource: + apiVersion: v1 + kind: Pod + metadata: + name: opensearch-test-bootstrap-0 + # The same Initialized flag also releases any restart that became pending + # during first boot, and on one replica it takes the only node down. 6m: + # the health steps requeue every 10s, then the pod restarts on an image the + # node already has. + - assert: + timeout: 6m + resource: + apiVersion: apps/v1 + kind: StatefulSet + metadata: + name: opensearch-test-nodes + (status.observedGeneration == metadata.generation): true + status: + readyReplicas: 1 + updatedReplicas: 1 + (currentRevision == updateRevision): true - script: # Above the two in-pod budgets below, so one of them is what fires. timeout: 3m From cce3387f8d15769c7fd9d1bb168929e9bb79b5fd Mon Sep 17 00:00:00 2001 From: Aleksei Sviridkin Date: Fri, 25 Sep 2026 01:16:47 +0300 Subject: [PATCH 0032/1280] docs(ci): say why the overlay's ancestry tie goes to main The comment claimed a line fresh off main is the same as main, but the cozystack-packages:main artifact is built from main's tip, not from the cut commit. Once main moves past the cut, a stack on such a line gets newer images than the line's, until the stack holds a commit of the line's own. State that limit, and why the tie still goes to main: a branch forked from main before a cut ties the same way and is far more common. Assisted-by: LLM Signed-off-by: Aleksei Sviridkin --- .github/workflows/pull-requests.yaml | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/.github/workflows/pull-requests.yaml b/.github/workflows/pull-requests.yaml index 4a385ac56..4ecfe1988 100644 --- a/.github/workflows/pull-requests.yaml +++ b/.github/workflows/pull-requests.yaml @@ -642,9 +642,13 @@ jobs: # A base that is neither main nor a line (a stacked PR's feature branch) has # no artifact, and a `/` in it is not even a valid OCI tag. It reads the # artifact of whichever of main and the lines it has the fewest commits on - # top of. A tie goes to main, so a stack on a line keeps that line's - # generation only once the line has a commit of its own: a line fresh off - # main is topologically the same as main at that commit. + # top of. A tie goes to main. A line with no commit of its own yet is, in + # the graph, main at the cut commit, so a stack on it ties and reads the + # artifact built from main's tip. That artifact carries newer images than + # the line once main moves past the cut. The stack keeps reading it until + # it contains a commit of the line's own. Breaking the tie towards the + # line instead would misroute the far more common branch forked from main + # before the cut, which ties the same way. # # A missing artifact stays a no-op (packages keep their committed refs), which # also covers a line whose first build-release run has not landed yet. From 31bade054d6736b3d103ba4d51d33e015a31d335 Mon Sep 17 00:00:00 2001 From: Myasnikov Daniil Date: Tue, 1 Sep 2026 18:10:22 +0500 Subject: [PATCH 0033/1280] test(tests): add offline app chart render checks helm-unittest suites can select individual templates, leaving other templates unchecked even when the chart's tests pass. Rendering the full chart with the platform's injected values catches those failures before a cluster is needed. Assisted-By: LLM Signed-off-by: Myasnikov Daniil --- hack/check-render-matrix.bats | 112 +++++++++++++++ hack/check-render-matrix.sh | 133 ++++++++++++++++++ hack/testdata/render-fixtures/README.md | 31 ++++ hack/testdata/render-fixtures/configured.yaml | 21 +++ hack/testdata/render-fixtures/fresh.yaml | 17 +++ hack/testdata/render-fixtures/wildcard.yaml | 18 +++ 6 files changed, 332 insertions(+) create mode 100644 hack/check-render-matrix.bats create mode 100755 hack/check-render-matrix.sh create mode 100644 hack/testdata/render-fixtures/README.md create mode 100644 hack/testdata/render-fixtures/configured.yaml create mode 100644 hack/testdata/render-fixtures/fresh.yaml create mode 100644 hack/testdata/render-fixtures/wildcard.yaml diff --git a/hack/check-render-matrix.bats b/hack/check-render-matrix.bats new file mode 100644 index 000000000..613af7d12 --- /dev/null +++ b/hack/check-render-matrix.bats @@ -0,0 +1,112 @@ +#!/usr/bin/env bats + +# Contract for hack/check-render-matrix.sh. The point of these is that the check +# FAILS on a broken chart: a smoke check that cannot go red is worse than none, +# because it reports a number that looks like coverage. +# +# Written for cozytest.sh, which is not real bats: no `run`, no `$status`, no +# setup()/teardown(). Each test calls the script directly and inspects its exit +# with `if`, the way the other hack/*.bats here do. + +@test "render matrix passes on the tree as it stands" { + output=$(hack/check-render-matrix.sh) + case "$output" in + *"rendered,"*" skipped"*) ;; + *) echo "expected a summary line, got: $output" >&2; exit 1 ;; + esac +} + +@test "render matrix fails on a chart whose template is broken" { + tmp=$(mktemp -d) + mkdir -p "$tmp/broken/templates" + printf 'apiVersion: v2\nname: broken\nversion: 0.0.0\n' > "$tmp/broken/Chart.yaml" + # `required` with no value is the cheapest deterministic render failure. + printf '{{ required "deliberately broken" .Values.nope }}\n' > "$tmp/broken/templates/boom.yaml" + + if out=$(hack/check-render-matrix.sh "$tmp/broken" 2>&1); then + echo "expected a non-zero exit for a broken chart, got success: $out" >&2 + rm -rf "$tmp" + exit 1 + fi + case "$out" in + *"FAIL broken"*) ;; + *) echo "expected 'FAIL broken', got: $out" >&2; rm -rf "$tmp"; exit 1 ;; + esac + rm -rf "$tmp" +} + +# helm's own parser is what catches this, which is why the script carries no +# separate YAML pass. Pinned so that stays true: if a future helm accepted it, +# the check would silently start passing malformed manifests. +@test "render matrix fails on a template that is not valid YAML" { + tmp=$(mktemp -d) + mkdir -p "$tmp/badyaml/templates" + printf 'apiVersion: v2\nname: badyaml\nversion: 0.0.0\n' > "$tmp/badyaml/Chart.yaml" + printf 'a: b\n c: d\n' > "$tmp/badyaml/templates/boom.yaml" + + if out=$(hack/check-render-matrix.sh "$tmp/badyaml" 2>&1); then + echo "expected a non-zero exit for invalid YAML, got success: $out" >&2 + rm -rf "$tmp" + exit 1 + fi + case "$out" in + *"FAIL badyaml"*) ;; + *) echo "expected 'FAIL badyaml', got: $out" >&2; rm -rf "$tmp"; exit 1 ;; + esac + rm -rf "$tmp" +} + +# Every skipped chart has to carry a reason, so a skip cannot quietly become the +# way a chart avoids the check. +@test "every skip names a reason" { + output=$(hack/check-render-matrix.sh) + printf '%s\n' "$output" | grep '^SKIP' > /tmp/render-skips.$$ || true + while read -r line; do + [ -n "$line" ] || continue + case "$line" in + *"("*")"*) ;; + *) echo "skip without a reason: $line" >&2; rm -f /tmp/render-skips.$$; exit 1 ;; + esac + done < /tmp/render-skips.$$ + rm -f /tmp/render-skips.$$ +} + +# The sweep must cover the charts that exist rather than a number frozen when +# this was written: a chart added to packages/apps must land in the check or in +# the skip list, and the two together have to account for all of them. +@test "rendered plus skipped accounts for every app chart" { + total=$(find packages/apps -mindepth 1 -maxdepth 1 -type d | wc -l | tr -d ' ') + output=$(hack/check-render-matrix.sh) + summary=$(printf '%s\n' "$output" | grep '^check-render-matrix:') + rendered=$(printf '%s\n' "$summary" | sed 's/.*: \([0-9]*\) rendered.*/\1/') + skipped=$(printf '%s\n' "$summary" | sed 's/.*, \([0-9]*\) skipped.*/\1/') + sum=$((rendered + skipped)) + if [ "$sum" -ne "$total" ]; then + echo "sweep covered $sum charts ($rendered rendered, $skipped skipped) but packages/apps holds $total" >&2 + exit 1 + fi +} + +# A fixture that does not reproduce the platform's types tests a shape the +# platform never produces. The booleans are the trap: charts compare them with +# `eq $x "true"`, so a real YAML bool makes helm fail on incompatible types. +@test "fixtures carry the platform's string-typed values" { + for f in hack/testdata/render-fixtures/*.yaml; do + python3 -c 'import sys,yaml; d=yaml.safe_load(open(sys.argv[1])) or {}; c=d.get("_cluster") or {}; bad=[k for k,v in c.items() if isinstance(v,bool)]; sys.exit(f"{sys.argv[1]}: _cluster keys are YAML booleans, the platform injects strings: {bad}") if bad else None; sys.exit(f"{sys.argv[1]}: no _cluster map") if not c else None' "$f" + done +} + +# Each fixture is one cluster state and they must actually differ, or the sweep +# renders the same shape three times and reports triple the coverage it has. +@test "the fixtures represent different cluster states" { + count=$(find hack/testdata/render-fixtures -name '*.yaml' | wc -l | tr -d ' ') + [ "$count" -ge 2 ] + distinct=$(for f in hack/testdata/render-fixtures/*.yaml; do + grep -E '^ (oidc-enabled|solver|wildcard-issue):' "$f" | tr -d ' ' | sort | tr '\n' ',' + echo + done | sort -u | wc -l | tr -d ' ') + if [ "$distinct" -lt "$count" ]; then + echo "fixtures do not differ on the keys charts branch on ($distinct distinct of $count files)" >&2 + exit 1 + fi +} diff --git a/hack/check-render-matrix.sh b/hack/check-render-matrix.sh new file mode 100755 index 000000000..724a0deed --- /dev/null +++ b/hack/check-render-matrix.sh @@ -0,0 +1,133 @@ +#!/bin/sh +# Render every app chart and fail if one does not produce valid YAML. +# +# The gap this closes: helm-unittest covers roughly a fifth of the packages, so +# for most charts nothing outside the E2E suite ever renders them. A template +# that breaks on its own defaults is then found by a 176-minute lane, or by a +# release, rather than by a check that costs a second. +# +# What it does NOT cover, so the number is not read as more than it is. +# +# `lookup` returns nothing here. Without a cluster helm gives an empty result and +# charts carry on -- which is why this works at all -- but 46 of the 55 lookup +# call sites in packages/apps/*/templates/ sit inside a conditional on that +# result, so this renders one side of each of them and never the other. The +# unrendered side is where a whole class of real bugs has lived: the +# lookup-preserve pattern that keeps an immutable PVC storageClass across +# reconciles, and adopt-in-place migrations. Covering those needs a cluster +# holding the objects, which is a different lane. Do not read a green sweep as +# "these charts render correctly", only as "they render". +# +# Values outside `_cluster`/`_namespace` are chart defaults. Presets, replica +# counts and feature toggles are not swept; assertions about what the output +# CONTAINS belong in helm-unittest, per package, where they can be specific. +# +# Usage: hack/check-render-matrix.sh [chart-dir ...] +# defaults to packages/apps/*/ +set -eu + +# Cluster states to render each chart under. Each file reproduces the `_cluster` +# map the platform injects, taken from packages/core/platform/templates/apps.yaml +# rather than guessed -- including that every value is a STRING, because charts +# compare them with `eq $oidcEnabled "true"` and a real bool makes helm fail on +# incompatible types. hack/testdata/render-fixtures/README.md carries the detail. +# +# More than one, and that is the difference between a check and a formality: +# charts branch on these values, so a single state renders one side of each +# branch and passes a chart whose other side is broken. +FIXTURE_DIR="hack/testdata/render-fixtures" + +# Charts needing one more value of their own. Kept as a table rather than folded +# into FIXTURE so each entry names a chart-specific requirement instead of +# widening what every chart is rendered with. +# Empty today. Kept because the next chart that needs one value of its own +# should get it here rather than by widening FIXTURE for all of them. +extra_values() { + case "$1" in + *) echo "" ;; + esac +} + +# Charts that cannot be rendered without a live cluster, with the reason. A +# chart lands here only when the blocker is a lookup whose empty result the +# template turns into a hard failure -- not merely because it uses lookup, which +# most charts do and survive (helm returns an empty result and they carry on). +# +# vm-instance, kubernetes-nodes +# both resolve an instance type through a lookup of +# VirtualMachineClusterInstancetype and fail when it finds +# nothing ("specified instanceType u1.medium not found in +# cluster"). That check is the point of those templates in +# production, so the charts are skipped here rather than weakened +# for a test. Covering them needs a cluster holding the +# instancetype CRs, which is a different lane, not a fixture. +# +# Every skip costs coverage, so keep the list short and say why. +skip_reason() { + case "$1" in + vm-instance|kubernetes-nodes) echo "looks up VirtualMachineClusterInstancetype and hard-fails on an empty result" ;; + *) echo "" ;; + esac +} + +# The release name matters to more than cosmetics: tenant's own template refuses +# a name that is not `tenant-`, so a fixed name would fail it for a +# reason that has nothing to do with rendering health. +release_name() { + case "$1" in + tenant) echo "tenant-sub" ;; + *) echo "$1-render-check" ;; + esac +} + +charts="$*" +if [ -z "$charts" ]; then + charts=$(find packages/apps -mindepth 1 -maxdepth 1 -type d | sort) +fi +if [ -z "$charts" ]; then + echo "check-render-matrix: found no charts under packages/apps — refusing to report success from an empty sweep" >&2 + exit 1 +fi + +if [ -z "$(find "$FIXTURE_DIR" -name '*.yaml' 2>/dev/null)" ]; then + echo "check-render-matrix: no fixtures under $FIXTURE_DIR — every chart would render under nothing and the sweep would report success having checked no state" >&2 + exit 1 +fi + +rc=0 +rendered=0 +skipped=0 +for dir in $charts; do + name=$(basename "$dir") + + reason=$(skip_reason "$name") + if [ -n "$reason" ]; then + echo "SKIP $name ($reason)" + skipped=$((skipped + 1)) + continue + fi + + chart_failed=0 + for fixture in "$FIXTURE_DIR"/*.yaml; do + state=$(basename "$fixture" .yaml) + out=$(mktemp) + # shellcheck disable=SC2086 # extra_values is an argument list + if ! helm template "$(release_name "$name")" "$dir" -n tenant-test \ + -f "$fixture" $(extra_values "$name") >"$out" 2>"$out.err"; then + echo "FAIL $name ($state)" + grep -v 'level=INFO' "$out.err" | sed 's/^/ /' | head -12 + rc=1 + chart_failed=1 + fi + rm -f "$out" "$out.err" + done + if [ "$chart_failed" -ne 0 ]; then + continue + fi + + rendered=$((rendered + 1)) + rm -f "$out" "$out.err" +done + +echo "check-render-matrix: $rendered rendered, $skipped skipped" +exit "$rc" diff --git a/hack/testdata/render-fixtures/README.md b/hack/testdata/render-fixtures/README.md new file mode 100644 index 000000000..20ef180df --- /dev/null +++ b/hack/testdata/render-fixtures/README.md @@ -0,0 +1,31 @@ +# Render fixtures + +Values the platform injects into every app chart at install time, reproduced +here so `hack/check-render-matrix.sh` can render a chart the way it is actually +rendered in a cluster. + +The authority is `packages/core/platform/templates/apps.yaml`, which builds the +`_cluster` map into the `cozystack-values` Secret, plus +`templates/bundles/system.yaml` for `oidc-enabled`. **Every value there goes +through `| quote`, so every value here is a string** — including the booleans. +That is not cosmetic: charts compare them with `eq $oidcEnabled "true"`, and a +real bool makes helm fail with "incompatible types for comparison". A fixture +that guesses the type tests a shape the platform never produces. + +Each file is one cluster state, and a chart is rendered under all of them. The +states exist because charts branch on these values, so a single fixture renders +one side of each branch and passes a chart whose other side is broken. + +| file | state it represents | +|---|---| +| `fresh.yaml` | a new install: nothing configured, OIDC off, no certificates | +| `configured.yaml` | OIDC on, per-host ACME via http01, services exposed | +| `wildcard.yaml` | dns01 with a platform-issued wildcard certificate | + +When a chart starts reading a `_cluster` key none of these set, add it to all +three. A key absent from every fixture is a branch nothing renders, and it fails +silently by passing. To list what the charts read: + +```sh +grep -rhoE '_cluster "[a-z-]*"|_cluster\.[a-zA-Z-]*' packages/apps/*/templates/ +``` diff --git a/hack/testdata/render-fixtures/configured.yaml b/hack/testdata/render-fixtures/configured.yaml new file mode 100644 index 000000000..e6474dde5 --- /dev/null +++ b/hack/testdata/render-fixtures/configured.yaml @@ -0,0 +1,21 @@ +# OIDC on, per-host ACME through http01, services exposed. The other side of the +# branches fresh.yaml leaves off. +_cluster: + root-host: "example.org" + bundle-name: "paas-full" + solver: "http01" + issuer-name: "letsencrypt-prod" + wildcard-secret-name: "" + wildcard-issue: "false" + oidc-enabled: "true" + oidc-insecure-skip-verify: "false" + keycloak-internal-url: "https://keycloak.cozy-keycloak.svc.cluster.local" + extra-keycloak-redirect-uri-for-dashboard: "" + expose-ingress: "tenant-root" + expose-services: "tenant-root" + cluster-domain: "cluster.local" + scheduling: + nodeSelector: {} + tolerations: [] +_namespace: + host: "example.org" diff --git a/hack/testdata/render-fixtures/fresh.yaml b/hack/testdata/render-fixtures/fresh.yaml new file mode 100644 index 000000000..d844e3f61 --- /dev/null +++ b/hack/testdata/render-fixtures/fresh.yaml @@ -0,0 +1,17 @@ +# A cluster right after install: nothing configured yet. +_cluster: + root-host: "example.org" + bundle-name: "paas-full" + solver: "" + issuer-name: "" + wildcard-secret-name: "" + wildcard-issue: "false" + oidc-enabled: "false" + oidc-insecure-skip-verify: "false" + keycloak-internal-url: "" + extra-keycloak-redirect-uri-for-dashboard: "" + expose-ingress: "" + expose-services: "" + cluster-domain: "cluster.local" +_namespace: + host: "example.org" diff --git a/hack/testdata/render-fixtures/wildcard.yaml b/hack/testdata/render-fixtures/wildcard.yaml new file mode 100644 index 000000000..ca410ebac --- /dev/null +++ b/hack/testdata/render-fixtures/wildcard.yaml @@ -0,0 +1,18 @@ +# dns01 with a platform-issued wildcard certificate: the path where charts stop +# doing per-host ACME and point at a shared Secret instead. +_cluster: + root-host: "example.org" + bundle-name: "paas-full" + solver: "dns01" + issuer-name: "letsencrypt-prod" + wildcard-secret-name: "wildcard-tls" + wildcard-issue: "true" + oidc-enabled: "true" + oidc-insecure-skip-verify: "false" + keycloak-internal-url: "https://keycloak.cozy-keycloak.svc.cluster.local" + extra-keycloak-redirect-uri-for-dashboard: "" + expose-ingress: "tenant-root" + expose-services: "tenant-root" + cluster-domain: "cluster.local" +_namespace: + host: "example.org" From 5fcd99f0ada05958959d57a652dc300ac0ab8064 Mon Sep 17 00:00:00 2001 From: Myasnikov Daniil Date: Tue, 1 Sep 2026 18:24:39 +0500 Subject: [PATCH 0034/1280] test(clickhouse): cover backup API password persistence A password change during reconciliation leaves the backup sidecar and strategy Pod using different credentials, causing backup requests to fail with 401. Both first install and reuse of an existing Secret need coverage. Assisted-By: LLM Signed-off-by: Myasnikov Daniil --- hack/check-render-matrix.sh | 19 ++++-- .../backup_api_password_persistence_test.yaml | 68 +++++++++++++++++++ 2 files changed, 82 insertions(+), 5 deletions(-) create mode 100644 packages/apps/clickhouse/tests/backup_api_password_persistence_test.yaml diff --git a/hack/check-render-matrix.sh b/hack/check-render-matrix.sh index 724a0deed..70a95769d 100755 --- a/hack/check-render-matrix.sh +++ b/hack/check-render-matrix.sh @@ -11,12 +11,21 @@ # `lookup` returns nothing here. Without a cluster helm gives an empty result and # charts carry on -- which is why this works at all -- but 46 of the 55 lookup # call sites in packages/apps/*/templates/ sit inside a conditional on that -# result, so this renders one side of each of them and never the other. The -# unrendered side is where a whole class of real bugs has lived: the +# result, so this sweep renders one side of each of them and never the other. +# The unrendered side is where a whole class of real bugs has lived: the # lookup-preserve pattern that keeps an immutable PVC storageClass across -# reconciles, and adopt-in-place migrations. Covering those needs a cluster -# holding the objects, which is a different lane. Do not read a green sweep as -# "these charts render correctly", only as "they render". +# reconciles, and adopt-in-place migrations. +# +# That side is NOT out of reach, and it does not need a cluster: helm-unittest +# can fake the API a chart looks up, via `kubernetesProvider` in a test suite. +# packages/apps/clickhouse/tests/backup_api_password_persistence_test.yaml is +# the worked example -- it covers both the mint and the preserve branch of the +# backup API password, in milliseconds. So lookup branches belong there, per +# chart, where the fake can be specific about what exists; this sweep stays what +# it is, a check that every chart still renders at all. +# +# Do not read a green sweep as "these charts render correctly", only as "they +# render, under these cluster states, on the empty-lookup path". # # Values outside `_cluster`/`_namespace` are chart defaults. Presets, replica # counts and feature toggles are not swept; assertions about what the output diff --git a/packages/apps/clickhouse/tests/backup_api_password_persistence_test.yaml b/packages/apps/clickhouse/tests/backup_api_password_persistence_test.yaml new file mode 100644 index 000000000..281dedd7e --- /dev/null +++ b/packages/apps/clickhouse/tests/backup_api_password_persistence_test.yaml @@ -0,0 +1,68 @@ +suite: clickhouse-backup API password persistence across reconciles + +# The chart mints the backup API password once and then preserves it, by looking +# up its own previously-rendered Secret. Both halves matter and they are +# different code paths: +# - no existing Secret -> generate a fresh password; +# - existing Secret -> reuse it, because rotating on every re-render leaves +# a window where the sidecar and the strategy Pod +# disagree and every backup 401s. +# +# The second path is reachable here only because helm-unittest can fake the API +# the chart looks up (kubernetesProvider). Without that, `lookup` returns nothing +# outside a cluster, only the generate path renders, and the preserve path -- the +# one with the failure mode -- is covered by nothing short of a live upgrade. +# +# This is the pattern, not the exception: the same lookup-preserve shape guards +# an immutable PVC storageClass in harbor and the adopt-in-place migrations in +# seaweedfs. Anywhere a chart reads existing cluster state to decide what to +# render, this is how the other branch gets tested. + +templates: + - templates/backup-api-auth-secret.yaml + +release: + name: ch-test + namespace: tenant-test + +set: + _cluster: {} + backup: + enabled: true + +tests: + - it: "mints a password when none exists yet" + asserts: + - equal: + path: stringData.username + value: backup + - exists: + path: stringData.password + # Not asserting the value: it is random by design. Asserting its length + # would pin randAlphaNum's argument, which is not the contract. + - notEqual: + path: stringData.password + value: "" + + - it: "preserves the existing password rather than rotating it" + kubernetesProvider: + scheme: + "v1/Secret": + gvr: + version: "v1" + resource: "secrets" + namespaced: true + objects: + - kind: Secret + apiVersion: v1 + metadata: + name: ch-test-backup-api-auth + namespace: tenant-test + data: + # base64 of "backup" and "preserved-password" + username: YmFja3Vw + password: cHJlc2VydmVkLXBhc3N3b3Jk + asserts: + - equal: + path: stringData.password + value: preserved-password From 0cf2d5b34cfd59735d14c2aa6d56667238577e9a Mon Sep 17 00:00:00 2001 From: Myasnikov Daniil Date: Tue, 1 Sep 2026 18:44:43 +0500 Subject: [PATCH 0035/1280] test(tests): exercise shared-service render fixtures An empty shared-service namespace disables templates that tenants with inherited services rely on. Rendering only that state leaves those templates unchecked. Assisted-By: LLM Signed-off-by: Myasnikov Daniil --- hack/check-render-matrix.bats | 69 ++++++++++++------- hack/check-render-matrix.sh | 37 +++++++--- hack/testdata/render-fixtures/README.md | 34 ++++++--- hack/testdata/render-fixtures/configured.yaml | 9 +++ hack/testdata/render-fixtures/fresh.yaml | 8 +++ hack/testdata/render-fixtures/wildcard.yaml | 9 +++ 6 files changed, 123 insertions(+), 43 deletions(-) diff --git a/hack/check-render-matrix.bats b/hack/check-render-matrix.bats index 613af7d12..bd5bc0cb9 100644 --- a/hack/check-render-matrix.bats +++ b/hack/check-render-matrix.bats @@ -56,19 +56,30 @@ rm -rf "$tmp" } -# Every skipped chart has to carry a reason, so a skip cannot quietly become the -# way a chart avoids the check. -@test "every skip names a reason" { - output=$(hack/check-render-matrix.sh) - printf '%s\n' "$output" | grep '^SKIP' > /tmp/render-skips.$$ || true - while read -r line; do - [ -n "$line" ] || continue - case "$line" in - *"("*")"*) ;; - *) echo "skip without a reason: $line" >&2; rm -f /tmp/render-skips.$$; exit 1 ;; - esac - done < /tmp/render-skips.$$ - rm -f /tmp/render-skips.$$ +# A skip that has stopped being necessary is worse than no skip: it silently +# drops a chart from the sweep forever. This renders each skipped chart directly +# and requires it to STILL fail, so a chart that becomes renderable shows up as a +# red test rather than as permanent invisible exclusion. +# +# Replaces an earlier test that asserted every SKIP line contains parentheses. +# The only line that emits one is `echo "SKIP $name ($reason)"` guarded on a +# non-empty reason, so that assertion was unreachable by construction: it could +# not fail for the property it named. +@test "every skipped chart still genuinely fails to render" { + # mktemp, not $BATS_TMPDIR: cozytest.sh is not real bats and defines none of + # bats's variables, so under `set -u` that name aborts the suite. + skips=$(mktemp) + hack/check-render-matrix.sh | grep '^SKIP' | sed 's/^SKIP \([^ ]*\) .*/\1/' > "$skips" || true + while read -r name; do + [ -n "$name" ] || continue + if helm template "$name-render-check" "packages/apps/$name" -n tenant-test \ + -f hack/testdata/render-fixtures/fresh.yaml >/dev/null 2>&1; then + echo "chart '$name' is on the skip list but renders fine now — remove the skip" >&2 + rm -f "$skips" + exit 1 + fi + done < "$skips" + rm -f "$skips" } # The sweep must cover the charts that exist rather than a number frozen when @@ -92,21 +103,31 @@ # `eq $x "true"`, so a real YAML bool makes helm fail on incompatible types. @test "fixtures carry the platform's string-typed values" { for f in hack/testdata/render-fixtures/*.yaml; do - python3 -c 'import sys,yaml; d=yaml.safe_load(open(sys.argv[1])) or {}; c=d.get("_cluster") or {}; bad=[k for k,v in c.items() if isinstance(v,bool)]; sys.exit(f"{sys.argv[1]}: _cluster keys are YAML booleans, the platform injects strings: {bad}") if bad else None; sys.exit(f"{sys.argv[1]}: no _cluster map") if not c else None' "$f" + python3 -c 'import sys,yaml;d=yaml.safe_load(open(sys.argv[1])) or {};bad=[];[bad.append(f"{sec}.{k}") for sec in ("_cluster","_namespace") for k,v in (d.get(sec) or {}).items() if isinstance(v,(bool,int,float)) or v is None];sys.exit(f"{sys.argv[1]}: scalars must be strings, the platform quotes them: {bad}") if bad else None;sys.exit(f"{sys.argv[1]}: no _cluster map") if not (d.get("_cluster") or {}) else None' "$f" done } -# Each fixture is one cluster state and they must actually differ, or the sweep -# renders the same shape three times and reports triple the coverage it has. -@test "the fixtures represent different cluster states" { - count=$(find hack/testdata/render-fixtures -name '*.yaml' | wc -l | tr -d ' ') +# Each fixture is one cluster state, and what matters is that they produce +# DIFFERENT RENDERS -- otherwise the sweep runs helm three times over the same +# shape and reports triple the coverage it has. +# +# An earlier version compared the fixture FILES on three key names. That passed +# while the sweep was in fact rendering 19 of 21 charts identically across all +# three states, which is the exact condition it claimed to prevent. Comparing +# output is the only form of this test that can fail for the right reason. +@test "the fixtures produce different renders for at least one chart" { + count=$(find hack/testdata/render-fixtures -maxdepth 1 -name '*.yaml' | wc -l | tr -d ' ') [ "$count" -ge 2 ] - distinct=$(for f in hack/testdata/render-fixtures/*.yaml; do - grep -E '^ (oidc-enabled|solver|wildcard-issue):' "$f" | tr -d ' ' | sort | tr '\n' ',' - echo - done | sort -u | wc -l | tr -d ' ') - if [ "$distinct" -lt "$count" ]; then - echo "fixtures do not differ on the keys charts branch on ($distinct distinct of $count files)" >&2 + + # packages/apps/kubernetes is the chart that branches most on these values + # (the _namespace. flags gate ~15 manifests). If a future fixture + # change stops moving even this one, the states have collapsed. + a=$(helm template kubernetes-render-check packages/apps/kubernetes -n tenant-test \ + -f hack/testdata/render-fixtures/fresh.yaml 2>/dev/null | grep -c '^kind:') + b=$(helm template kubernetes-render-check packages/apps/kubernetes -n tenant-test \ + -f hack/testdata/render-fixtures/configured.yaml 2>/dev/null | grep -c '^kind:') + if [ "$a" = "$b" ]; then + echo "fresh and configured render the same number of documents ($a) for packages/apps/kubernetes — the fixtures no longer represent different cluster states" >&2 exit 1 fi } diff --git a/hack/check-render-matrix.sh b/hack/check-render-matrix.sh index 70a95769d..a5b62f89a 100755 --- a/hack/check-render-matrix.sh +++ b/hack/check-render-matrix.sh @@ -9,9 +9,11 @@ # What it does NOT cover, so the number is not read as more than it is. # # `lookup` returns nothing here. Without a cluster helm gives an empty result and -# charts carry on -- which is why this works at all -- but 46 of the 55 lookup -# call sites in packages/apps/*/templates/ sit inside a conditional on that -# result, so this sweep renders one side of each of them and never the other. +# charts carry on -- which is why this works at all -- but the sweep then renders +# only the empty-result side. There are 40 template lookup calls under +# packages/apps/*/templates/ (`grep -rho 'lookup "'`; a plain `grep -c 'lookup '` +# returns 55 by counting prose in comments), and 13 of them sit inside a +# conditional on the result, so those 13 branches have a side this never renders. # The unrendered side is where a whole class of real bugs has lived: the # lookup-preserve pattern that keeps an immutable PVC storageClass across # reconciles, and adopt-in-place migrations. @@ -37,9 +39,11 @@ set -eu # Cluster states to render each chart under. Each file reproduces the `_cluster` # map the platform injects, taken from packages/core/platform/templates/apps.yaml -# rather than guessed -- including that every value is a STRING, because charts -# compare them with `eq $oidcEnabled "true"` and a real bool makes helm fail on -# incompatible types. hack/testdata/render-fixtures/README.md carries the detail. +# rather than guessed. Every SCALAR there goes through `| quote`, so the booleans +# arrive as the strings "true"/"false" -- tenant compares one with +# `eq $oidcEnabled "true"` and a real bool makes helm fail on incompatible types. +# `scheduling` and `branding` are the exceptions: the platform emits those as +# maps. hack/testdata/render-fixtures/README.md carries the detail. # # More than one, and that is the difference between a check and a formality: # charts branch on these values, so a single state renders one side of each @@ -67,9 +71,18 @@ extra_values() { # VirtualMachineClusterInstancetype and fail when it finds # nothing ("specified instanceType u1.medium not found in # cluster"). That check is the point of those templates in -# production, so the charts are skipped here rather than weakened -# for a test. Covering them needs a cluster holding the -# instancetype CRs, which is a different lane, not a fixture. +# production, so the charts are skipped rather than weakened. +# +# Worth being precise, because an earlier version of this comment +# was not: for kubernetes-nodes that lookup is the THIRD blocker, +# not the first. It also needs `--set cluster=` and a +# release name starting with `kubernetes-nodes--`, and +# both of those are ordinary fixture work that extra_values() and +# release_name() below exist for. Only after supplying them does +# the chart reach the lookup. vm-instance likewise renders with +# explicit resources.* values; the lookup is what stops it on +# defaults. So "these need a cluster" is true of the last blocker +# in each, not of the charts as a whole. # # Every skip costs coverage, so keep the list short and say why. skip_reason() { @@ -98,7 +111,10 @@ if [ -z "$charts" ]; then exit 1 fi -if [ -z "$(find "$FIXTURE_DIR" -name '*.yaml' 2>/dev/null)" ]; then +# -maxdepth 1 so the guard tests exactly what the loop below globs; a recursive +# find here would pass on a fixture in a subdirectory the glob never reaches, and +# every chart would then fail on the literal `*.yaml`. +if [ -z "$(find "$FIXTURE_DIR" -maxdepth 1 -name '*.yaml' 2>/dev/null)" ]; then echo "check-render-matrix: no fixtures under $FIXTURE_DIR — every chart would render under nothing and the sweep would report success having checked no state" >&2 exit 1 fi @@ -135,7 +151,6 @@ for dir in $charts; do fi rendered=$((rendered + 1)) - rm -f "$out" "$out.err" done echo "check-render-matrix: $rendered rendered, $skipped skipped" diff --git a/hack/testdata/render-fixtures/README.md b/hack/testdata/render-fixtures/README.md index 20ef180df..524b8fc12 100644 --- a/hack/testdata/render-fixtures/README.md +++ b/hack/testdata/render-fixtures/README.md @@ -4,13 +4,24 @@ Values the platform injects into every app chart at install time, reproduced here so `hack/check-render-matrix.sh` can render a chart the way it is actually rendered in a cluster. -The authority is `packages/core/platform/templates/apps.yaml`, which builds the -`_cluster` map into the `cozystack-values` Secret, plus -`templates/bundles/system.yaml` for `oidc-enabled`. **Every value there goes -through `| quote`, so every value here is a string** — including the booleans. -That is not cosmetic: charts compare them with `eq $oidcEnabled "true"`, and a -real bool makes helm fail with "incompatible types for comparison". A fixture -that guesses the type tests a shape the platform never produces. +The authority is `packages/core/platform/templates/apps.yaml`, which builds the `_cluster` map +into the `cozystack-values` Secret, plus `templates/bundles/system.yaml` for +`oidc-enabled`. `_namespace` comes from +`packages/apps/tenant/templates/namespace.yaml`. + +**Every scalar there goes through `| quote`, so every scalar here is a string** — +including the booleans. That is not cosmetic: `tenant` compares one with +`eq $oidcEnabled "true"`, and a real bool makes helm fail with "incompatible +types for comparison". `scheduling` and `branding` are the exceptions: the +platform emits those as maps. + +`_namespace.` is not a boolean at all, which is easy to get wrong: the +value is the NAMESPACE providing that service, or an empty string when the tenant +has none (`$etcd = $tenantName` in namespace.yaml). Charts test it with a bare +`{{- if .Values._namespace.etcd }}`, so `""` is the off side and any name is the +on side. Omitting the key entirely renders the off side, which is a state the +platform does produce — but then nothing renders the on side, and in +`packages/apps/kubernetes` that is 15 manifests. Each file is one cluster state, and a chart is rendered under all of them. The states exist because charts branch on these values, so a single fixture renders @@ -27,5 +38,12 @@ three. A key absent from every fixture is a branch nothing renders, and it fails silently by passing. To list what the charts read: ```sh -grep -rhoE '_cluster "[a-z-]*"|_cluster\.[a-zA-Z-]*' packages/apps/*/templates/ +grep -rn '_cluster' packages/apps/*/templates/ ``` + +Grep for the bare word rather than a shape: the reads are written four different +ways (`.Values._cluster.foo`, `index .Values._cluster "foo"`, `dig "foo" ...`, +and `(.Values._cluster | default dict)`), so any pattern narrow enough to look +tidy misses some of them. A key absent from every fixture is a branch nothing +renders, and it fails silently by passing, so a false negative here is the +expensive kind. diff --git a/hack/testdata/render-fixtures/configured.yaml b/hack/testdata/render-fixtures/configured.yaml index e6474dde5..4b7dbd292 100644 --- a/hack/testdata/render-fixtures/configured.yaml +++ b/hack/testdata/render-fixtures/configured.yaml @@ -17,5 +17,14 @@ _cluster: scheduling: nodeSelector: {} tolerations: [] +# The value is the NAMESPACE providing the service, not a boolean: tenant's +# namespace.yaml sets `$etcd = $tenantName`. A non-empty value is the on side of +# the nine `{{- if .Values._namespace. }}` branches, and it renders 15 +# manifests in packages/apps/kubernetes that the off side does not. _namespace: + etcd: "tenant-test" + ingress: "tenant-test" + gateway: "tenant-test" + monitoring: "tenant-test" + seaweedfs: "tenant-test" host: "example.org" diff --git a/hack/testdata/render-fixtures/fresh.yaml b/hack/testdata/render-fixtures/fresh.yaml index d844e3f61..42eb12b9c 100644 --- a/hack/testdata/render-fixtures/fresh.yaml +++ b/hack/testdata/render-fixtures/fresh.yaml @@ -13,5 +13,13 @@ _cluster: expose-ingress: "" expose-services: "" cluster-domain: "cluster.local" +# Empty string means "this tenant has no such shared service"; the charts test it +# with a bare `{{- if .Values._namespace.etcd }}`, and "" is false. This is the +# off side of nine such branches. _namespace: + etcd: "" + ingress: "" + gateway: "" + monitoring: "" + seaweedfs: "" host: "example.org" diff --git a/hack/testdata/render-fixtures/wildcard.yaml b/hack/testdata/render-fixtures/wildcard.yaml index ca410ebac..4c6f22ec4 100644 --- a/hack/testdata/render-fixtures/wildcard.yaml +++ b/hack/testdata/render-fixtures/wildcard.yaml @@ -14,5 +14,14 @@ _cluster: expose-ingress: "tenant-root" expose-services: "tenant-root" cluster-domain: "cluster.local" +# The value is the NAMESPACE providing the service, not a boolean: tenant's +# namespace.yaml sets `$etcd = $tenantName`. A non-empty value is the on side of +# the nine `{{- if .Values._namespace. }}` branches, and it renders 15 +# manifests in packages/apps/kubernetes that the off side does not. _namespace: + etcd: "tenant-test" + ingress: "tenant-test" + gateway: "tenant-test" + monitoring: "tenant-test" + seaweedfs: "tenant-test" host: "example.org" From 97053d125e11ffb2e74848d547f41d85425760c1 Mon Sep 17 00:00:00 2001 From: Myasnikov Daniil Date: Thu, 10 Sep 2026 11:44:22 +0500 Subject: [PATCH 0036/1280] test(tests): verify render fixtures and lookup skip failures A fixture with unused scheduling keys can render successfully without exercising scheduling. A skip caused by an unrelated failure can also survive after its original lookup restriction is gone. These cases need checks of the rendered result and the failure reason. Assisted-By: LLM Signed-off-by: Myasnikov Daniil --- hack/check-render-matrix.bats | 250 ++++++++++-------- hack/check-render-matrix.sh | 188 +++++-------- hack/testdata/render-fixtures/README.md | 54 ++-- hack/testdata/render-fixtures/configured.yaml | 12 +- hack/testdata/render-fixtures/fresh.yaml | 6 +- .../render-fixtures/validator/Chart.yaml | 4 + .../validator/templates/check.yaml | 32 +++ hack/testdata/render-fixtures/wildcard.yaml | 11 +- 8 files changed, 266 insertions(+), 291 deletions(-) create mode 100644 hack/testdata/render-fixtures/validator/Chart.yaml create mode 100644 hack/testdata/render-fixtures/validator/templates/check.yaml diff --git a/hack/check-render-matrix.bats b/hack/check-render-matrix.bats index bd5bc0cb9..45069af4a 100644 --- a/hack/check-render-matrix.bats +++ b/hack/check-render-matrix.bats @@ -1,133 +1,161 @@ #!/usr/bin/env bats -# Contract for hack/check-render-matrix.sh. The point of these is that the check -# FAILS on a broken chart: a smoke check that cannot go red is worse than none, -# because it reports a number that looks like coverage. -# -# Written for cozytest.sh, which is not real bats: no `run`, no `$status`, no -# setup()/teardown(). Each test calls the script directly and inspects its exit -# with `if`, the way the other hack/*.bats here do. +# Shared by bats and cozytest.sh: inspect exit codes directly, without bats-only +# helpers. Scratch directories stay available if an assertion fails. -@test "render matrix passes on the tree as it stands" { - output=$(hack/check-render-matrix.sh) - case "$output" in - *"rendered,"*" skipped"*) ;; - *) echo "expected a summary line, got: $output" >&2; exit 1 ;; - esac +make_render_chart() { + mkdir -p "$1/templates" + printf 'apiVersion: v2\nname: render-test\nversion: 0.0.0\n' > "$1/Chart.yaml" + printf 'apiVersion: v1\nkind: ConfigMap\nmetadata:\n name: render-test\n' > "$1/templates/object.yaml" } -@test "render matrix fails on a chart whose template is broken" { - tmp=$(mktemp -d) - mkdir -p "$tmp/broken/templates" - printf 'apiVersion: v2\nname: broken\nversion: 0.0.0\n' > "$tmp/broken/Chart.yaml" - # `required` with no value is the cheapest deterministic render failure. - printf '{{ required "deliberately broken" .Values.nope }}\n' > "$tmp/broken/templates/boom.yaml" - - if out=$(hack/check-render-matrix.sh "$tmp/broken" 2>&1); then - echo "expected a non-zero exit for a broken chart, got success: $out" >&2 - rm -rf "$tmp" - exit 1 +expect_render_failure() { + if output=$(dash hack/check-render-matrix.sh "$@" 2>&1); then + echo "expected render failure, got: $output" >&2 + return 1 fi - case "$out" in - *"FAIL broken"*) ;; - *) echo "expected 'FAIL broken', got: $out" >&2; rm -rf "$tmp"; exit 1 ;; - esac - rm -rf "$tmp" + printf '%s\n' "$output" } -# helm's own parser is what catches this, which is why the script carries no -# separate YAML pass. Pinned so that stays true: if a future helm accepted it, -# the check would silently start passing malformed manifests. -@test "render matrix fails on a template that is not valid YAML" { - tmp=$(mktemp -d) - mkdir -p "$tmp/badyaml/templates" - printf 'apiVersion: v2\nname: badyaml\nversion: 0.0.0\n' > "$tmp/badyaml/Chart.yaml" - printf 'a: b\n c: d\n' > "$tmp/badyaml/templates/boom.yaml" - - if out=$(hack/check-render-matrix.sh "$tmp/badyaml" 2>&1); then - echo "expected a non-zero exit for invalid YAML, got success: $out" >&2 - rm -rf "$tmp" - exit 1 - fi - case "$out" in - *"FAIL badyaml"*) ;; - *) echo "expected 'FAIL badyaml', got: $out" >&2; rm -rf "$tmp"; exit 1 ;; - esac - rm -rf "$tmp" -} - -# A skip that has stopped being necessary is worse than no skip: it silently -# drops a chart from the sweep forever. This renders each skipped chart directly -# and requires it to STILL fail, so a chart that becomes renderable shows up as a -# red test rather than as permanent invisible exclusion. -# -# Replaces an earlier test that asserted every SKIP line contains parentheses. -# The only line that emits one is `echo "SKIP $name ($reason)"` guarded on a -# non-empty reason, so that assertion was unreachable by construction: it could -# not fail for the property it named. -@test "every skipped chart still genuinely fails to render" { - # mktemp, not $BATS_TMPDIR: cozytest.sh is not real bats and defines none of - # bats's variables, so under `set -u` that name aborts the suite. - skips=$(mktemp) - hack/check-render-matrix.sh | grep '^SKIP' | sed 's/^SKIP \([^ ]*\) .*/\1/' > "$skips" || true - while read -r name; do - [ -n "$name" ] || continue - if helm template "$name-render-check" "packages/apps/$name" -n tenant-test \ - -f hack/testdata/render-fixtures/fresh.yaml >/dev/null 2>&1; then - echo "chart '$name' is on the skip list but renders fine now — remove the skip" >&2 - rm -f "$skips" - exit 1 - fi - done < "$skips" - rm -f "$skips" -} - -# The sweep must cover the charts that exist rather than a number frozen when -# this was written: a chart added to packages/apps must land in the check or in -# the skip list, and the two together have to account for all of them. @test "rendered plus skipped accounts for every app chart" { total=$(find packages/apps -mindepth 1 -maxdepth 1 -type d | wc -l | tr -d ' ') - output=$(hack/check-render-matrix.sh) + output=$(dash hack/check-render-matrix.sh) summary=$(printf '%s\n' "$output" | grep '^check-render-matrix:') rendered=$(printf '%s\n' "$summary" | sed 's/.*: \([0-9]*\) rendered.*/\1/') skipped=$(printf '%s\n' "$summary" | sed 's/.*, \([0-9]*\) skipped.*/\1/') - sum=$((rendered + skipped)) - if [ "$sum" -ne "$total" ]; then - echo "sweep covered $sum charts ($rendered rendered, $skipped skipped) but packages/apps holds $total" >&2 - exit 1 - fi + [ "$rendered" -gt 0 ] + [ "$((rendered + skipped))" -eq "$total" ] } -# A fixture that does not reproduce the platform's types tests a shape the -# platform never produces. The booleans are the trap: charts compare them with -# `eq $x "true"`, so a real YAML bool makes helm fail on incompatible types. -@test "fixtures carry the platform's string-typed values" { - for f in hack/testdata/render-fixtures/*.yaml; do - python3 -c 'import sys,yaml;d=yaml.safe_load(open(sys.argv[1])) or {};bad=[];[bad.append(f"{sec}.{k}") for sec in ("_cluster","_namespace") for k,v in (d.get(sec) or {}).items() if isinstance(v,(bool,int,float)) or v is None];sys.exit(f"{sys.argv[1]}: scalars must be strings, the platform quotes them: {bad}") if bad else None;sys.exit(f"{sys.argv[1]}: no _cluster map") if not (d.get("_cluster") or {}) else None' "$f" +@test "render matrix preserves multiple chart paths containing spaces" { + tmp=$(mktemp -d) + make_render_chart "$tmp/space in parent/first" + make_render_chart "$tmp/space in parent/second" + output=$(dash hack/check-render-matrix.sh "$tmp/space in parent/first/" "$tmp/space in parent/second") + printf '%s\n' "$output" | grep -Fx 'check-render-matrix: 2 rendered, 0 skipped' + rm -rf "$tmp" +} + +@test "render matrix reports a broken chart and still checks the next chart" { + tmp=$(mktemp -d) + make_render_chart "$tmp/broken" + make_render_chart "$tmp/valid" + printf '{{ required "deliberately broken" .Values.nope }}\n' > "$tmp/broken/templates/object.yaml" + output=$(expect_render_failure "$tmp/broken" "$tmp/valid") + for fixture in hack/testdata/render-fixtures/*.yaml; do + state=$(basename "$fixture" .yaml) + printf '%s\n' "$output" | grep -Fx "FAIL broken ($state)" + done + printf '%s\n' "$output" | grep -F 'deliberately broken' + printf '%s\n' "$output" | grep -Fx 'check-render-matrix: 1 rendered, 0 skipped' + rm -rf "$tmp" +} + +@test "render matrix fails on malformed YAML" { + tmp=$(mktemp -d) + make_render_chart "$tmp/badyaml" + printf 'a: b\n c: d\n' > "$tmp/badyaml/templates/object.yaml" + output=$(expect_render_failure "$tmp/badyaml") + printf '%s\n' "$output" | grep -F 'FAIL badyaml' + printf '%s\n' "$output" | grep -F 'YAML parse error' + rm -rf "$tmp" +} + +@test "render matrix does not count a nonexistent chart as rendered" { + tmp=$(mktemp -d) + output=$(expect_render_failure "$tmp/missing") + printf '%s\n' "$output" | grep -F 'FAIL missing' + printf '%s\n' "$output" | grep -Fx 'check-render-matrix: 0 rendered, 0 skipped' + rm -rf "$tmp" +} + +@test "render matrix rejects skips that now render or fail for another reason" { + tmp=$(mktemp -d) + for name in vm-instance kubernetes-nodes; do + make_render_chart "$tmp/$name" + output=$(expect_render_failure "$tmp/$name") + printf '%s\n' "$output" | grep -F 'chart now renders; remove its skip' + printf '{{ fail "unrelated render failure" }}\n' > "$tmp/$name/templates/object.yaml" + output=$(expect_render_failure "$tmp/$name") + printf '%s\n' "$output" | grep -F 'unrelated render failure' + printf '%s\n' "$output" | grep -Fx 'check-render-matrix: 0 rendered, 0 skipped' + done + rm -rf "$tmp" +} + +@test "fixtures match the injected value types" { + for fixture in hack/testdata/render-fixtures/*.yaml; do + helm template fixture-check hack/testdata/render-fixtures/validator \ + --set-file "fixture=$fixture" done } -# Each fixture is one cluster state, and what matters is that they produce -# DIFFERENT RENDERS -- otherwise the sweep runs helm three times over the same -# shape and reports triple the coverage it has. -# -# An earlier version compared the fixture FILES on three key names. That passed -# while the sweep was in fact rendering 19 of 21 charts identically across all -# three states, which is the exact condition it claimed to prevent. Comparing -# output is the only form of this test that can fail for the right reason. -@test "the fixtures produce different renders for at least one chart" { - count=$(find hack/testdata/render-fixtures -maxdepth 1 -name '*.yaml' | wc -l | tr -d ' ') - [ "$count" -ge 2 ] +@test "fixture validation rejects wrong scalar and scheduling types" { + tmp=$(mktemp -d) + for value in true 12 null '[]' '{}'; do + printf '_cluster:\n oidc-enabled: %s\n_namespace: {host: "example.org"}\n' "$value" > "$tmp/value.yaml" + if output=$(helm template fixture-check hack/testdata/render-fixtures/validator \ + --set-file "fixture=$tmp/value.yaml" 2>&1); then + echo "accepted non-string oidc-enabled: $value" >&2 + exit 1 + fi + printf '%s\n' "$output" | grep -F '_cluster.oidc-enabled must be a string' + done + for value in true 12 null '[]' '{}'; do + printf '_cluster:\n scheduling:\n globalAppTopologySpreadConstraints: %s\n dedicatedNodesForWindowsVMs: "false"\n_namespace: {host: "example.org"}\n' "$value" > "$tmp/value.yaml" + if output=$(helm template fixture-check hack/testdata/render-fixtures/validator \ + --set-file "fixture=$tmp/value.yaml" 2>&1); then + echo "accepted non-string scheduling constraint: $value" >&2 + exit 1 + fi + printf '%s\n' "$output" | grep -F '_cluster.scheduling.globalAppTopologySpreadConstraints must be a string' + done + rm -rf "$tmp" +} - # packages/apps/kubernetes is the chart that branches most on these values - # (the _namespace. flags gate ~15 manifests). If a future fixture - # change stops moving even this one, the states have collapsed. - a=$(helm template kubernetes-render-check packages/apps/kubernetes -n tenant-test \ - -f hack/testdata/render-fixtures/fresh.yaml 2>/dev/null | grep -c '^kind:') - b=$(helm template kubernetes-render-check packages/apps/kubernetes -n tenant-test \ - -f hack/testdata/render-fixtures/configured.yaml 2>/dev/null | grep -c '^kind:') - if [ "$a" = "$b" ]; then - echo "fresh and configured render the same number of documents ($a) for packages/apps/kubernetes — the fixtures no longer represent different cluster states" >&2 +@test "configured scheduling reaches the postgres manifest" { + tmp=$(mktemp -d) + for state in fresh configured wildcard; do + helm template postgres-render-check packages/apps/postgres -n tenant-test \ + -f "hack/testdata/render-fixtures/$state.yaml" > "$tmp/$state.yaml" + done + if grep -q '^ topologySpreadConstraints:' "$tmp/fresh.yaml"; then + echo 'fresh unexpectedly enables topology spread' >&2 exit 1 fi + for state in configured wildcard; do + grep -A 7 '^ topologySpreadConstraints:' "$tmp/$state.yaml" > "$tmp/constraints" + grep -F 'maxSkew: 1' "$tmp/constraints" + grep -F 'topologyKey: topology.kubernetes.io/zone' "$tmp/constraints" + grep -F 'cnpg.io/cluster: postgres-render-check' "$tmp/constraints" + done + rm -rf "$tmp" +} + +@test "every pair of fixture states produces different deterministic manifests" { + tmp=$(mktemp -d) + count=0 + for fixture in hack/testdata/render-fixtures/*.yaml; do + state=$(basename "$fixture" .yaml) + count=$((count + 1)) + # Tenant exercises OIDC and certificate modes without random Secrets. + # Render twice so randomness cannot masquerade as state coverage. + for run in first second; do + helm template tenant-check packages/apps/tenant -n tenant-test \ + -f "$fixture" > "$tmp/$state-$run.yaml" + done + cmp "$tmp/$state-first.yaml" "$tmp/$state-second.yaml" + cp "$tmp/$state-first.yaml" "$tmp/$state.manifests" + done + [ "$count" -ge 3 ] + for a in "$tmp"/*.manifests; do + for b in "$tmp"/*.manifests; do + [ "$a" != "$b" ] || continue + if cmp -s "$a" "$b"; then + echo "fixture states produce identical manifests: $a and $b" >&2 + exit 1 + fi + done + done + rm -rf "$tmp" } diff --git a/hack/check-render-matrix.sh b/hack/check-render-matrix.sh index a5b62f89a..1e2d6d26c 100755 --- a/hack/check-render-matrix.sh +++ b/hack/check-render-matrix.sh @@ -1,156 +1,86 @@ #!/bin/sh -# Render every app chart and fail if one does not produce valid YAML. -# -# The gap this closes: helm-unittest covers roughly a fifth of the packages, so -# for most charts nothing outside the E2E suite ever renders them. A template -# that breaks on its own defaults is then found by a 176-minute lane, or by a -# release, rather than by a check that costs a second. -# -# What it does NOT cover, so the number is not read as more than it is. -# -# `lookup` returns nothing here. Without a cluster helm gives an empty result and -# charts carry on -- which is why this works at all -- but the sweep then renders -# only the empty-result side. There are 40 template lookup calls under -# packages/apps/*/templates/ (`grep -rho 'lookup "'`; a plain `grep -c 'lookup '` -# returns 55 by counting prose in comments), and 13 of them sit inside a -# conditional on the result, so those 13 branches have a side this never renders. -# The unrendered side is where a whole class of real bugs has lived: the -# lookup-preserve pattern that keeps an immutable PVC storageClass across -# reconciles, and adopt-in-place migrations. -# -# That side is NOT out of reach, and it does not need a cluster: helm-unittest -# can fake the API a chart looks up, via `kubernetesProvider` in a test suite. -# packages/apps/clickhouse/tests/backup_api_password_persistence_test.yaml is -# the worked example -- it covers both the mint and the preserve branch of the -# backup API password, in milliseconds. So lookup branches belong there, per -# chart, where the fake can be specific about what exists; this sweep stays what -# it is, a check that every chart still renders at all. -# -# Do not read a green sweep as "these charts render correctly", only as "they -# render, under these cluster states, on the empty-lookup path". -# -# Values outside `_cluster`/`_namespace` are chart defaults. Presets, replica -# counts and feature toggles are not swept; assertions about what the output -# CONTAINS belong in helm-unittest, per package, where they can be specific. -# -# Usage: hack/check-render-matrix.sh [chart-dir ...] -# defaults to packages/apps/*/ +# Render app charts on their defaults plus injected cluster/namespace values. +# helm-unittest renders only templates selected by a suite; this smoke check +# also reaches templates with no assertions. It checks rendering, not Kubernetes +# schema validity or runtime behavior. See testdata/render-fixtures/README.md. +# Usage (from the repository root): hack/check-render-matrix.sh [chart-dir ...] set -eu -# Cluster states to render each chart under. Each file reproduces the `_cluster` -# map the platform injects, taken from packages/core/platform/templates/apps.yaml -# rather than guessed. Every SCALAR there goes through `| quote`, so the booleans -# arrive as the strings "true"/"false" -- tenant compares one with -# `eq $oidcEnabled "true"` and a real bool makes helm fail on incompatible types. -# `scheduling` and `branding` are the exceptions: the platform emits those as -# maps. hack/testdata/render-fixtures/README.md carries the detail. -# -# More than one, and that is the difference between a check and a formality: -# charts branch on these values, so a single state renders one side of each -# branch and passes a chart whose other side is broken. FIXTURE_DIR="hack/testdata/render-fixtures" -# Charts needing one more value of their own. Kept as a table rather than folded -# into FIXTURE so each entry names a chart-specific requirement instead of -# widening what every chart is rendered with. -# Empty today. Kept because the next chart that needs one value of its own -# should get it here rather than by widening FIXTURE for all of them. -extra_values() { - case "$1" in - *) echo "" ;; - esac -} - -# Charts that cannot be rendered without a live cluster, with the reason. A -# chart lands here only when the blocker is a lookup whose empty result the -# template turns into a hard failure -- not merely because it uses lookup, which -# most charts do and survive (helm returns an empty result and they carry on). -# -# vm-instance, kubernetes-nodes -# both resolve an instance type through a lookup of -# VirtualMachineClusterInstancetype and fail when it finds -# nothing ("specified instanceType u1.medium not found in -# cluster"). That check is the point of those templates in -# production, so the charts are skipped rather than weakened. -# -# Worth being precise, because an earlier version of this comment -# was not: for kubernetes-nodes that lookup is the THIRD blocker, -# not the first. It also needs `--set cluster=` and a -# release name starting with `kubernetes-nodes--`, and -# both of those are ordinary fixture work that extra_values() and -# release_name() below exist for. Only after supplying them does -# the chart reach the lookup. vm-instance likewise renders with -# explicit resources.* values; the lookup is what stops it on -# defaults. So "these need a cluster" is true of the last blocker -# in each, not of the charts as a whole. -# -# Every skip costs coverage, so keep the list short and say why. +# Empty lookup results are the only accepted reason to skip a chart. Match the +# actual diagnostic, so another error cannot keep an obsolete skip alive. skip_reason() { case "$1" in - vm-instance|kubernetes-nodes) echo "looks up VirtualMachineClusterInstancetype and hard-fails on an empty result" ;; + vm-instance) echo 'Specified instanceType does not exist in the cluster: u1.medium' ;; + kubernetes-nodes) echo 'specified instanceType "u1.medium" not found in cluster' ;; *) echo "" ;; esac } -# The release name matters to more than cosmetics: tenant's own template refuses -# a name that is not `tenant-`, so a fixed name would fail it for a -# reason that has nothing to do with rendering health. -release_name() { - case "$1" in - tenant) echo "tenant-sub" ;; - *) echo "$1-render-check" ;; +render_chart() { + chart=$1 fixture=$2 + name=$(basename "$chart") + case "$name" in + tenant) set -- tenant-sub ;; + # Satisfy the parent-cluster and release-name contract before the lookup. + kubernetes-nodes) set -- kubernetes-nodes-render-check --set-string cluster=render ;; + *) set -- "$name-render-check" ;; esac + helm template "$@" "$chart" -n tenant-test -f "$fixture" } -charts="$*" -if [ -z "$charts" ]; then - charts=$(find packages/apps -mindepth 1 -maxdepth 1 -type d | sort) +if [ "$#" -eq 0 ]; then + set -- packages/apps/*/ + if [ ! -d "$1" ]; then + echo "check-render-matrix: found no charts under packages/apps" >&2 + exit 1 + fi fi -if [ -z "$charts" ]; then - echo "check-render-matrix: found no charts under packages/apps — refusing to report success from an empty sweep" >&2 + +# Check exactly the files the render loop will consume, not nested fixtures. +fixtures=0 +for fixture in "$FIXTURE_DIR"/*.yaml; do + [ -f "$fixture" ] || continue + fixtures=$((fixtures + 1)) +done +if [ "$fixtures" -eq 0 ]; then + echo "check-render-matrix: no fixtures under $FIXTURE_DIR" >&2 exit 1 fi -# -maxdepth 1 so the guard tests exactly what the loop below globs; a recursive -# find here would pass on a fixture in a subdirectory the glob never reaches, and -# every chart would then fail on the literal `*.yaml`. -if [ -z "$(find "$FIXTURE_DIR" -maxdepth 1 -name '*.yaml' 2>/dev/null)" ]; then - echo "check-render-matrix: no fixtures under $FIXTURE_DIR — every chart would render under nothing and the sweep would report success having checked no state" >&2 - exit 1 -fi - -rc=0 -rendered=0 -skipped=0 -for dir in $charts; do +errors=$(mktemp) +trap 'rm -f "$errors"' EXIT +rc=0 rendered=0 skipped=0 +for dir in "$@"; do name=$(basename "$dir") - reason=$(skip_reason "$name") + chart_failed=0 + for fixture in "$FIXTURE_DIR"/*.yaml; do + [ -f "$fixture" ] || continue + state=$(basename "$fixture" .yaml) + if render_chart "$dir" "$fixture" >/dev/null 2>"$errors"; then + if [ -z "$reason" ]; then + continue + fi + echo "FAIL $name ($state): chart now renders; remove its skip" + else + if [ -n "$reason" ] && grep -Fq "$reason" "$errors"; then + continue + fi + echo "FAIL $name ($state)" + sed -n '/^level=INFO/d; s/^/ /; p' "$errors" + fi + rc=1 + chart_failed=1 + done + [ "$chart_failed" -eq 0 ] || continue if [ -n "$reason" ]; then echo "SKIP $name ($reason)" skipped=$((skipped + 1)) - continue + else + rendered=$((rendered + 1)) fi - - chart_failed=0 - for fixture in "$FIXTURE_DIR"/*.yaml; do - state=$(basename "$fixture" .yaml) - out=$(mktemp) - # shellcheck disable=SC2086 # extra_values is an argument list - if ! helm template "$(release_name "$name")" "$dir" -n tenant-test \ - -f "$fixture" $(extra_values "$name") >"$out" 2>"$out.err"; then - echo "FAIL $name ($state)" - grep -v 'level=INFO' "$out.err" | sed 's/^/ /' | head -12 - rc=1 - chart_failed=1 - fi - rm -f "$out" "$out.err" - done - if [ "$chart_failed" -ne 0 ]; then - continue - fi - - rendered=$((rendered + 1)) done echo "check-render-matrix: $rendered rendered, $skipped skipped" diff --git a/hack/testdata/render-fixtures/README.md b/hack/testdata/render-fixtures/README.md index 524b8fc12..229a2b91c 100644 --- a/hack/testdata/render-fixtures/README.md +++ b/hack/testdata/render-fixtures/README.md @@ -1,49 +1,27 @@ # Render fixtures -Values the platform injects into every app chart at install time, reproduced -here so `hack/check-render-matrix.sh` can render a chart the way it is actually -rendered in a cluster. +`hack/check-render-matrix.sh` renders every app chart with its defaults plus these injected values. helm-unittest renders the templates selected by each suite, so a chart with passing unit tests can still have an untested template that fails to render. This sweep checks that Helm accepts the rendered YAML; it does not validate Kubernetes schemas or runtime behavior. -The authority is `packages/core/platform/templates/apps.yaml`, which builds the `_cluster` map -into the `cozystack-values` Secret, plus `templates/bundles/system.yaml` for -`oidc-enabled`. `_namespace` comes from -`packages/apps/tenant/templates/namespace.yaml`. +The source of `_cluster` is `packages/core/platform/templates/apps.yaml`; `_namespace` comes from `packages/apps/tenant/templates/namespace.yaml`. These fixtures model selected install states, not a complete copy of every platform setting. Top-level scalar values in these maps are strings, including booleans. Charts such as tenant compare `oidc-enabled` with `"true"`, so a YAML boolean has the wrong type. -**Every scalar there goes through `| quote`, so every scalar here is a string** — -including the booleans. That is not cosmetic: `tenant` compares one with -`eq $oidcEnabled "true"`, and a real bool makes helm fail with "incompatible -types for comparison". `scheduling` and `branding` are the exceptions: the -platform emits those as maps. +`scheduling` and `branding` are maps copied with `toYaml`, which preserves their nested types. The scheduling keys read by app charts have a more specific contract: `globalAppTopologySpreadConstraints` is a string containing YAML (or an empty string), and `dedicatedNodesForWindowsVMs` is compared with the string `"true"`. The configured and wildcard fixtures supply a topology constraint; fresh leaves it empty. The embedded YAML retains numeric fields such as `maxSkew`. -`_namespace.` is not a boolean at all, which is easy to get wrong: the -value is the NAMESPACE providing that service, or an empty string when the tenant -has none (`$etcd = $tenantName` in namespace.yaml). Charts test it with a bare -`{{- if .Values._namespace.etcd }}`, so `""` is the off side and any name is the -on side. Omitting the key entirely renders the off side, which is a state the -platform does produce — but then nothing renders the on side, and in -`packages/apps/kubernetes` that is 15 manifests. +`_namespace.` contains the namespace providing the shared service, or an empty string when unavailable. A non-empty value enables the service-dependent templates in the Kubernetes chart. -Each file is one cluster state, and a chart is rendered under all of them. The -states exist because charts branch on these values, so a single fixture renders -one side of each branch and passes a chart whose other side is broken. - -| file | state it represents | +| File | State | |---|---| -| `fresh.yaml` | a new install: nothing configured, OIDC off, no certificates | -| `configured.yaml` | OIDC on, per-host ACME via http01, services exposed | -| `wildcard.yaml` | dns01 with a platform-issued wildcard certificate | +| `fresh.yaml` | OIDC off, no certificates or shared services, no topology constraint | +| `configured.yaml` | OIDC on, per-host ACME via http01, shared services and topology constraint | +| `wildcard.yaml` | OIDC on, dns01 with a platform-issued wildcard certificate, shared services and topology constraint | -When a chart starts reading a `_cluster` key none of these set, add it to all -three. A key absent from every fixture is a branch nothing renders, and it fails -silently by passing. To list what the charts read: +Each chart is attempted under every fixture. `vm-instance` and `kubernetes-nodes` require a `VirtualMachineClusterInstancetype` lookup on their defaults. The sweep accepts their skip only while every fixture fails with the recorded lookup diagnostic; a successful render or a different error fails the sweep. For kubernetes-nodes it supplies a parent cluster and matching release name first. + +`lookup` returns an empty result during this check. Tests for existing objects belong in chart-specific helm-unittest suites using `kubernetesProvider`; `packages/apps/clickhouse/tests/backup_api_password_persistence_test.yaml` covers both password generation and preservation that way. Presets, replica counts and other app feature toggles are outside this sweep. + +The BATS suite checks fixture types with the small Helm chart in `validator/`, using `--set-file` so explicit nulls are not removed by Helm's values merge. It also verifies scheduling reaches the PostgreSQL manifest and compares complete tenant renders for every pair of fixture states. Tenant exercises OIDC and certificate modes without generating random Secrets; rendering each state twice verifies that the comparison is deterministic. Identical output from other charts is expected. + +When adding an injected value read by an app, update the relevant states and add an assertion for the branch it exercises. Review all read forms, including `index`, `get` and `dig`, before deciding a value is unused: ```sh -grep -rn '_cluster' packages/apps/*/templates/ +grep -rn '_cluster\|_namespace' packages/apps/*/templates/ ``` - -Grep for the bare word rather than a shape: the reads are written four different -ways (`.Values._cluster.foo`, `index .Values._cluster "foo"`, `dig "foo" ...`, -and `(.Values._cluster | default dict)`), so any pattern narrow enough to look -tidy misses some of them. A key absent from every fixture is a branch nothing -renders, and it fails silently by passing, so a false negative here is the -expensive kind. diff --git a/hack/testdata/render-fixtures/configured.yaml b/hack/testdata/render-fixtures/configured.yaml index 4b7dbd292..d5230f77b 100644 --- a/hack/testdata/render-fixtures/configured.yaml +++ b/hack/testdata/render-fixtures/configured.yaml @@ -15,12 +15,12 @@ _cluster: expose-services: "tenant-root" cluster-domain: "cluster.local" scheduling: - nodeSelector: {} - tolerations: [] -# The value is the NAMESPACE providing the service, not a boolean: tenant's -# namespace.yaml sets `$etcd = $tenantName`. A non-empty value is the on side of -# the nine `{{- if .Values._namespace. }}` branches, and it renders 15 -# manifests in packages/apps/kubernetes that the off side does not. + dedicatedNodesForWindowsVMs: "false" + globalAppTopologySpreadConstraints: | + topologySpreadConstraints: + - maxSkew: 1 + topologyKey: topology.kubernetes.io/zone + whenUnsatisfiable: ScheduleAnyway _namespace: etcd: "tenant-test" ingress: "tenant-test" diff --git a/hack/testdata/render-fixtures/fresh.yaml b/hack/testdata/render-fixtures/fresh.yaml index 42eb12b9c..f056daf5a 100644 --- a/hack/testdata/render-fixtures/fresh.yaml +++ b/hack/testdata/render-fixtures/fresh.yaml @@ -13,9 +13,9 @@ _cluster: expose-ingress: "" expose-services: "" cluster-domain: "cluster.local" -# Empty string means "this tenant has no such shared service"; the charts test it -# with a bare `{{- if .Values._namespace.etcd }}`, and "" is false. This is the -# off side of nine such branches. + scheduling: + dedicatedNodesForWindowsVMs: "false" + globalAppTopologySpreadConstraints: "" _namespace: etcd: "" ingress: "" diff --git a/hack/testdata/render-fixtures/validator/Chart.yaml b/hack/testdata/render-fixtures/validator/Chart.yaml new file mode 100644 index 000000000..f46c7cc96 --- /dev/null +++ b/hack/testdata/render-fixtures/validator/Chart.yaml @@ -0,0 +1,4 @@ +apiVersion: v2 +name: render-fixture-validator +version: 0.0.0 +type: application diff --git a/hack/testdata/render-fixtures/validator/templates/check.yaml b/hack/testdata/render-fixtures/validator/templates/check.yaml new file mode 100644 index 000000000..2648055e9 --- /dev/null +++ b/hack/testdata/render-fixtures/validator/templates/check.yaml @@ -0,0 +1,32 @@ +{{- /* Parse raw fixture YAML: merging values would silently remove null keys. */ -}} +{{- $fixture := .Values.fixture | fromYaml -}} +{{- if hasKey $fixture "Error" -}} + {{- fail (get $fixture "Error") -}} +{{- end -}} +{{- range $section := list "_cluster" "_namespace" -}} + {{- $values := get $fixture $section -}} + {{- if or (not (kindIs "map" $values)) (empty $values) -}} + {{- fail (printf "%s must be a non-empty map" $section) -}} + {{- end -}} + {{- range $key, $value := $values -}} + {{- if and (eq $section "_cluster") (has $key (list "scheduling" "branding")) -}} + {{- if not (kindIs "map" $value) -}} + {{- fail (printf "%s.%s must be a map" $section $key) -}} + {{- end -}} + {{- else if not (kindIs "string" $value) -}} + {{- fail (printf "%s.%s must be a string" $section $key) -}} + {{- end -}} + {{- end -}} +{{- end -}} +{{- $scheduling := get $fixture._cluster "scheduling" -}} +{{- if not (kindIs "map" $scheduling) -}} + {{- fail "_cluster.scheduling must be a map" -}} +{{- end -}} +{{- range $key := list "globalAppTopologySpreadConstraints" "dedicatedNodesForWindowsVMs" -}} + {{- if not (hasKey $scheduling $key) -}} + {{- fail (printf "_cluster.scheduling.%s is missing" $key) -}} + {{- end -}} + {{- if not (kindIs "string" (get $scheduling $key)) -}} + {{- fail (printf "_cluster.scheduling.%s must be a string" $key) -}} + {{- end -}} +{{- end -}} diff --git a/hack/testdata/render-fixtures/wildcard.yaml b/hack/testdata/render-fixtures/wildcard.yaml index 4c6f22ec4..f50cb647e 100644 --- a/hack/testdata/render-fixtures/wildcard.yaml +++ b/hack/testdata/render-fixtures/wildcard.yaml @@ -14,10 +14,13 @@ _cluster: expose-ingress: "tenant-root" expose-services: "tenant-root" cluster-domain: "cluster.local" -# The value is the NAMESPACE providing the service, not a boolean: tenant's -# namespace.yaml sets `$etcd = $tenantName`. A non-empty value is the on side of -# the nine `{{- if .Values._namespace. }}` branches, and it renders 15 -# manifests in packages/apps/kubernetes that the off side does not. + scheduling: + dedicatedNodesForWindowsVMs: "false" + globalAppTopologySpreadConstraints: | + topologySpreadConstraints: + - maxSkew: 1 + topologyKey: topology.kubernetes.io/zone + whenUnsatisfiable: ScheduleAnyway _namespace: etcd: "tenant-test" ingress: "tenant-test" From edd54252c3a53065e679748d977279894575bc4d Mon Sep 17 00:00:00 2001 From: Myasnikov Daniil Date: Thu, 10 Sep 2026 11:49:33 +0500 Subject: [PATCH 0037/1280] test(tests): exercise OIDC and certificate fixture branches OIDC values do not reach tenant realm-group templates unless Helm also knows the Keycloak API. Harbor's Gateway setting bypasses its Ingress certificate branches, so certificate fixtures need the ingress path. Assisted-By: LLM Signed-off-by: Myasnikov Daniil --- hack/check-render-matrix.bats | 61 ++++++++++++++++++- hack/check-render-matrix.sh | 2 +- hack/testdata/render-fixtures/README.md | 8 +-- hack/testdata/render-fixtures/configured.yaml | 2 +- hack/testdata/render-fixtures/wildcard.yaml | 4 +- 5 files changed, 67 insertions(+), 10 deletions(-) diff --git a/hack/check-render-matrix.bats b/hack/check-render-matrix.bats index 45069af4a..2e9f976d7 100644 --- a/hack/check-render-matrix.bats +++ b/hack/check-render-matrix.bats @@ -132,17 +132,74 @@ expect_render_failure() { rm -rf "$tmp" } +@test "render matrix reaches capability-gated OIDC templates" { + tmp=$(mktemp -d) + make_render_chart "$tmp/tenant" + cat > "$tmp/tenant/templates/object.yaml" <<'EOF' +{{- if and (eq (index .Values._cluster "oidc-enabled") "true") (.Capabilities.APIVersions.Has "v1.edp.epam.com/v1") }} +{{- fail "OIDC branch rendered" }} +{{- end }} +EOF + output=$(expect_render_failure "$tmp/tenant") + printf '%s\n' "$output" | grep -Fx 'FAIL tenant (configured)' + printf '%s\n' "$output" | grep -Fx 'FAIL tenant (wildcard)' + printf '%s\n' "$output" | grep -F 'OIDC branch rendered' + if printf '%s\n' "$output" | grep -Fq 'FAIL tenant (fresh)'; then + echo 'OIDC branch enabled for fresh fixture' >&2 + exit 1 + fi + rm -rf "$tmp" +} + +@test "fixture states enable OIDC groups and shared-service resources" { + tmp=$(mktemp -d) + for state in fresh configured wildcard; do + helm template tenant-check packages/apps/tenant -n tenant-test \ + --api-versions v1.edp.epam.com/v1 \ + -f "hack/testdata/render-fixtures/$state.yaml" > "$tmp/tenant.yaml" + helm template kubernetes-check packages/apps/kubernetes -n tenant-test \ + -f "hack/testdata/render-fixtures/$state.yaml" > "$tmp/kubernetes.yaml" + groups=$(awk '/^kind: KeycloakRealmGroup$/ {n++} END {print n+0}' "$tmp/tenant.yaml") + metrics=$(awk '/^ name: kubernetes-check-metrics-server$/ {n++} END {print n+0}' "$tmp/kubernetes.yaml") + case "$state" in + fresh) [ "$groups" -eq 0 ]; [ "$metrics" -eq 0 ] ;; + *) [ "$groups" -eq 4 ]; [ "$metrics" -eq 1 ] ;; + esac + done + rm -rf "$tmp" +} + +@test "certificate fixtures exercise per-host ACME and wildcard ingress" { + tmp=$(mktemp -d) + for state in configured wildcard; do + helm template harbor-check packages/apps/harbor -n tenant-test \ + -f "hack/testdata/render-fixtures/$state.yaml" \ + --show-only templates/ingress.yaml > "$tmp/$state.yaml" + grep -Fx 'kind: Ingress' "$tmp/$state.yaml" + grep -F 'harbor-check.example.org' "$tmp/$state.yaml" + done + grep -F 'acme.cert-manager.io/http01-ingress-ingressclassname: tenant-test' "$tmp/configured.yaml" + grep -F 'cert-manager.io/cluster-issuer: letsencrypt-prod' "$tmp/configured.yaml" + grep -F 'secretName: harbor-check-ingress-tls' "$tmp/configured.yaml" + grep -Fx ' tls:' "$tmp/wildcard.yaml" + if grep -Eq '^[[:space:]]+(acme.cert-manager.io/|cert-manager.io/cluster-issuer:|secretName:)' "$tmp/wildcard.yaml"; then + echo 'wildcard ingress unexpectedly requests a per-host certificate' >&2 + exit 1 + fi + rm -rf "$tmp" +} + @test "every pair of fixture states produces different deterministic manifests" { tmp=$(mktemp -d) count=0 for fixture in hack/testdata/render-fixtures/*.yaml; do state=$(basename "$fixture" .yaml) count=$((count + 1)) - # Tenant exercises OIDC and certificate modes without random Secrets. + # This compares whole states; the tests above assert specific branches. # Render twice so randomness cannot masquerade as state coverage. for run in first second; do helm template tenant-check packages/apps/tenant -n tenant-test \ - -f "$fixture" > "$tmp/$state-$run.yaml" + --api-versions v1.edp.epam.com/v1 -f "$fixture" > "$tmp/$state-$run.yaml" done cmp "$tmp/$state-first.yaml" "$tmp/$state-second.yaml" cp "$tmp/$state-first.yaml" "$tmp/$state.manifests" diff --git a/hack/check-render-matrix.sh b/hack/check-render-matrix.sh index 1e2d6d26c..faff145b9 100755 --- a/hack/check-render-matrix.sh +++ b/hack/check-render-matrix.sh @@ -22,7 +22,7 @@ render_chart() { chart=$1 fixture=$2 name=$(basename "$chart") case "$name" in - tenant) set -- tenant-sub ;; + tenant) set -- tenant-sub --api-versions v1.edp.epam.com/v1 ;; # Satisfy the parent-cluster and release-name contract before the lookup. kubernetes-nodes) set -- kubernetes-nodes-render-check --set-string cluster=render ;; *) set -- "$name-render-check" ;; diff --git a/hack/testdata/render-fixtures/README.md b/hack/testdata/render-fixtures/README.md index 229a2b91c..adfc24f2e 100644 --- a/hack/testdata/render-fixtures/README.md +++ b/hack/testdata/render-fixtures/README.md @@ -6,7 +6,7 @@ The source of `_cluster` is `packages/core/platform/templates/apps.yaml`; `_name `scheduling` and `branding` are maps copied with `toYaml`, which preserves their nested types. The scheduling keys read by app charts have a more specific contract: `globalAppTopologySpreadConstraints` is a string containing YAML (or an empty string), and `dedicatedNodesForWindowsVMs` is compared with the string `"true"`. The configured and wildcard fixtures supply a topology constraint; fresh leaves it empty. The embedded YAML retains numeric fields such as `maxSkew`. -`_namespace.` contains the namespace providing the shared service, or an empty string when unavailable. A non-empty value enables the service-dependent templates in the Kubernetes chart. +`_namespace.` contains the namespace providing the shared service, or an empty string when unavailable. A non-empty value enables the service-dependent templates in the Kubernetes chart. These states use ingress rather than Gateway API, so `gateway` stays empty: a non-empty gateway would disable Harbor Ingress and leave the certificate modes untested. | File | State | |---|---| @@ -14,14 +14,14 @@ The source of `_cluster` is `packages/core/platform/templates/apps.yaml`; `_name | `configured.yaml` | OIDC on, per-host ACME via http01, shared services and topology constraint | | `wildcard.yaml` | OIDC on, dns01 with a platform-issued wildcard certificate, shared services and topology constraint | -Each chart is attempted under every fixture. `vm-instance` and `kubernetes-nodes` require a `VirtualMachineClusterInstancetype` lookup on their defaults. The sweep accepts their skip only while every fixture fails with the recorded lookup diagnostic; a successful render or a different error fails the sweep. For kubernetes-nodes it supplies a parent cluster and matching release name first. +Each chart is attempted under every fixture. `vm-instance` and `kubernetes-nodes` require a `VirtualMachineClusterInstancetype` lookup on their defaults. The sweep accepts their skip only while every fixture fails with the recorded lookup diagnostic; a successful render or a different error fails the sweep. For kubernetes-nodes it supplies a parent cluster and matching release name first. For tenant it declares the Keycloak API with `--api-versions v1.edp.epam.com/v1`, allowing OIDC-enabled fixtures to render the realm groups. `lookup` returns an empty result during this check. Tests for existing objects belong in chart-specific helm-unittest suites using `kubernetesProvider`; `packages/apps/clickhouse/tests/backup_api_password_persistence_test.yaml` covers both password generation and preservation that way. Presets, replica counts and other app feature toggles are outside this sweep. -The BATS suite checks fixture types with the small Helm chart in `validator/`, using `--set-file` so explicit nulls are not removed by Helm's values merge. It also verifies scheduling reaches the PostgreSQL manifest and compares complete tenant renders for every pair of fixture states. Tenant exercises OIDC and certificate modes without generating random Secrets; rendering each state twice verifies that the comparison is deterministic. Identical output from other charts is expected. +The BATS suite checks fixture types with the small Helm chart in `validator/`, using `--set-file` so explicit nulls are not removed by Helm's values merge. Separate assertions check PostgreSQL topology constraints, tenant OIDC groups, the Kubernetes metrics-server HelmRelease and Harbor per-host ACME versus wildcard TLS. Pairwise comparison of complete tenant renders detects duplicate fixture states, and a second render of each state checks that randomness cannot satisfy that comparison. The branch assertions are needed because tenant also copies injected values into a Secret, so different output alone does not prove a conditional resource was rendered. When adding an injected value read by an app, update the relevant states and add an assertion for the branch it exercises. Review all read forms, including `index`, `get` and `dig`, before deciding a value is unused: ```sh -grep -rn '_cluster\|_namespace' packages/apps/*/templates/ +grep -rn -e '_cluster' -e '_namespace' packages/apps/*/templates/ ``` diff --git a/hack/testdata/render-fixtures/configured.yaml b/hack/testdata/render-fixtures/configured.yaml index d5230f77b..1417de8fc 100644 --- a/hack/testdata/render-fixtures/configured.yaml +++ b/hack/testdata/render-fixtures/configured.yaml @@ -24,7 +24,7 @@ _cluster: _namespace: etcd: "tenant-test" ingress: "tenant-test" - gateway: "tenant-test" + gateway: "" monitoring: "tenant-test" seaweedfs: "tenant-test" host: "example.org" diff --git a/hack/testdata/render-fixtures/wildcard.yaml b/hack/testdata/render-fixtures/wildcard.yaml index f50cb647e..895ec3873 100644 --- a/hack/testdata/render-fixtures/wildcard.yaml +++ b/hack/testdata/render-fixtures/wildcard.yaml @@ -1,5 +1,5 @@ # dns01 with a platform-issued wildcard certificate: the path where charts stop -# doing per-host ACME and point at a shared Secret instead. +# doing per-host ACME and use the ingress controller default certificate. _cluster: root-host: "example.org" bundle-name: "paas-full" @@ -24,7 +24,7 @@ _cluster: _namespace: etcd: "tenant-test" ingress: "tenant-test" - gateway: "tenant-test" + gateway: "" monitoring: "tenant-test" seaweedfs: "tenant-test" host: "example.org" From 5dc4489962d96190a4cb58ca902d75e090f37d5b Mon Sep 17 00:00:00 2001 From: Myasnikov Daniil Date: Fri, 25 Sep 2026 11:03:47 +0500 Subject: [PATCH 0038/1280] test(tests): cover empty render inputs and fixture rejection paths The render suite stayed green when empty fixture discovery, skip accounting or several fixture validation guards were removed. Those gaps could hide an incomplete sweep or admit fixture shapes that applications do not receive. Signed-off-by: Myasnikov Daniil Assisted-by: LLM --- hack/check-render-matrix.bats | 56 +++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) diff --git a/hack/check-render-matrix.bats b/hack/check-render-matrix.bats index 2e9f976d7..31b9a3545 100644 --- a/hack/check-render-matrix.bats +++ b/hack/check-render-matrix.bats @@ -36,6 +36,19 @@ expect_render_failure() { rm -rf "$tmp" } +@test "render matrix refuses empty discovery and ignores nested fixtures" { + tmp=$(mktemp -d) + mkdir -p "$tmp/hack/testdata/render-fixtures/validator" + cp hack/check-render-matrix.sh "$tmp/hack/" + cp hack/testdata/render-fixtures/fresh.yaml "$tmp/hack/testdata/render-fixtures/validator/nested.yaml" + output=$(cd "$tmp" && expect_render_failure) + printf '%s\n' "$output" | grep -F 'found no charts under packages/apps' + make_render_chart "$tmp/packages/apps/example" + output=$(cd "$tmp" && expect_render_failure) + printf '%s\n' "$output" | grep -F 'no fixtures under hack/testdata/render-fixtures' + rm -rf "$tmp" +} + @test "render matrix reports a broken chart and still checks the next chart" { tmp=$(mktemp -d) make_render_chart "$tmp/broken" @@ -83,6 +96,19 @@ expect_render_failure() { rm -rf "$tmp" } +@test "render matrix counts documented lookup failures as skipped" { + tmp=$(mktemp -d) + make_render_chart "$tmp/vm-instance" + make_render_chart "$tmp/kubernetes-nodes" + printf '%s\n' '{{ fail "Specified instanceType does not exist in the cluster: u1.medium" }}' > "$tmp/vm-instance/templates/object.yaml" + printf '%s\n' '{{ fail `specified instanceType "u1.medium" not found in cluster` }}' > "$tmp/kubernetes-nodes/templates/object.yaml" + output=$(dash hack/check-render-matrix.sh "$tmp/vm-instance" "$tmp/kubernetes-nodes") + printf '%s\n' "$output" | grep -F 'SKIP vm-instance (' + printf '%s\n' "$output" | grep -F 'SKIP kubernetes-nodes (' + printf '%s\n' "$output" | grep -Fx 'check-render-matrix: 0 rendered, 2 skipped' + rm -rf "$tmp" +} + @test "fixtures match the injected value types" { for fixture in hack/testdata/render-fixtures/*.yaml; do helm template fixture-check hack/testdata/render-fixtures/validator \ @@ -113,6 +139,36 @@ expect_render_failure() { rm -rf "$tmp" } +@test "fixture validation rejects malformed maps and missing scheduling keys" { + tmp=$(mktemp -d) + for variant in malformed-yaml empty-namespace branding-scalar namespace-map scheduling-scalar missing-scheduling missing-constraint missing-windows; do + cluster_extra='' + scheduling='scheduling:' + namespace='host: "example.org"' + constraint='globalAppTopologySpreadConstraints: ""' + windows='dedicatedNodesForWindowsVMs: "false"' + case "$variant" in + malformed-yaml) constraint='['; windows=''; expected='error converting YAML to JSON' ;; + empty-namespace) namespace=''; expected='_namespace must be a non-empty map' ;; + branding-scalar) cluster_extra='branding: true'; expected='_cluster.branding must be a map' ;; + namespace-map) namespace='branding: {}'; expected='_namespace.branding must be a string' ;; + scheduling-scalar) constraint='true'; windows=''; expected='_cluster.scheduling must be a map' ;; + missing-scheduling) cluster_extra='oidc-enabled: "false"'; scheduling=''; constraint=''; windows=''; expected='_cluster.scheduling must be a map' ;; + missing-constraint) constraint=''; expected='_cluster.scheduling.globalAppTopologySpreadConstraints is missing' ;; + missing-windows) windows=''; expected='_cluster.scheduling.dedicatedNodesForWindowsVMs is missing' ;; + esac + printf '_cluster:\n %s\n %s\n %s\n %s\n_namespace: {%s}\n' \ + "$cluster_extra" "$scheduling" "$constraint" "$windows" "$namespace" > "$tmp/value.yaml" + if output=$(helm template fixture-check hack/testdata/render-fixtures/validator \ + --set-file "fixture=$tmp/value.yaml" 2>&1); then + echo "accepted invalid fixture: $variant" >&2 + exit 1 + fi + printf '%s\n' "$output" | grep -F "$expected" + done + rm -rf "$tmp" +} + @test "configured scheduling reaches the postgres manifest" { tmp=$(mktemp -d) for state in fresh configured wildcard; do From 46b4b352702d13f33c42df702dd3e0747ba2d0fe Mon Sep 17 00:00:00 2001 From: IvanHunters Date: Fri, 4 Sep 2026 18:28:53 +0300 Subject: [PATCH 0039/1280] chore(seaweedfs): bump chart to 4.45 Refreshes the vendored chart from 4.31 through `make update`. All carried patches still apply; the volume-resize-hook one is rebased onto the pod template labels upstream now renders, so it appends the cozystack apiserver label instead of creating the block. Rendered names, StatefulSet selectors and volumeClaimTemplates are identical to 4.31, so running workloads keep their volumes across the upgrade. Assisted-by: LLM Signed-off-by: IvanHunters --- .../seaweedfs/charts/seaweedfs/Chart.yaml | 4 +- .../seaweedfs/charts/seaweedfs/README.md | 220 +++++++++- .../charts/seaweedfs/ci/default-values.yaml | 1 + .../charts/seaweedfs/ci/sftp-values.yaml | 5 + .../seaweedfs-grafana-dashboard.json | 285 +++++++++++++ .../templates/admin/admin-service.yaml | 14 +- .../templates/admin/admin-statefulset.yaml | 3 + .../all-in-one/all-in-one-deployment.yaml | 57 ++- .../all-in-one/all-in-one-service.yml | 44 +- .../seaweedfs/templates/cert/admin-cert.yaml | 5 + .../seaweedfs/templates/cert/client-cert.yaml | 5 + .../seaweedfs/templates/cert/filer-cert.yaml | 5 + .../seaweedfs/templates/cert/master-cert.yaml | 5 + .../seaweedfs/templates/cert/volume-cert.yaml | 5 + .../seaweedfs/templates/cert/worker-cert.yaml | 5 + .../templates/cosi/cosi-deployment.yaml | 3 + .../filer/filer-grpc-ingressroutetcp.yaml | 47 +++ .../templates/filer/filer-ingress.yaml | 89 ++++- .../templates/filer/filer-service-client.yaml | 3 - .../templates/filer/filer-service.yaml | 8 +- .../templates/filer/filer-servicemonitor.yaml | 1 + .../templates/filer/filer-statefulset.yaml | 19 + .../templates/master/master-statefulset.yaml | 6 + .../seaweedfs/templates/s3/s3-deployment.yaml | 12 + .../templates/s3/s3-lance-ingress.yaml | 61 +++ .../seaweedfs/templates/s3/s3-secret.yaml | 21 +- .../seaweedfs/templates/s3/s3-service.yaml | 29 +- .../templates/sftp/sftp-ca-secret.yaml | 40 ++ .../templates/sftp/sftp-deployment.yaml | 26 +- .../seaweedfs/templates/sftp/sftp-secret.yaml | 17 +- .../templates/sftp/sftp-service.yaml | 14 +- .../templates/sftp/sftp-ssh-secret.yaml | 35 ++ .../seaweedfs/templates/shared/_helpers.tpl | 201 +++++++++- .../templates/shared/networkpolicy.yaml | 267 +++++++++++++ .../shared/post-install-bucket-hook.yaml | 76 +++- .../templates/shared/secret-seaweedfs-db.yaml | 2 +- .../templates/shared/security-configmap.yaml | 30 +- .../templates/volume/volume-resize-hook.yaml | 70 +--- .../templates/volume/volume-statefulset.yaml | 25 +- .../templates/worker/worker-deployment.yaml | 78 ++++ .../templates/worker/worker-service.yaml | 11 +- .../worker/worker-servicemonitor.yaml | 10 +- .../seaweedfs/charts/seaweedfs/values.yaml | 375 ++++++++++++++++-- .../patches/resize-api-server-annotation.diff | 11 +- 44 files changed, 2064 insertions(+), 186 deletions(-) create mode 100644 packages/system/seaweedfs/charts/seaweedfs/ci/default-values.yaml create mode 100644 packages/system/seaweedfs/charts/seaweedfs/ci/sftp-values.yaml create mode 100644 packages/system/seaweedfs/charts/seaweedfs/templates/filer/filer-grpc-ingressroutetcp.yaml create mode 100644 packages/system/seaweedfs/charts/seaweedfs/templates/s3/s3-lance-ingress.yaml create mode 100644 packages/system/seaweedfs/charts/seaweedfs/templates/sftp/sftp-ca-secret.yaml create mode 100644 packages/system/seaweedfs/charts/seaweedfs/templates/sftp/sftp-ssh-secret.yaml create mode 100644 packages/system/seaweedfs/charts/seaweedfs/templates/shared/networkpolicy.yaml diff --git a/packages/system/seaweedfs/charts/seaweedfs/Chart.yaml b/packages/system/seaweedfs/charts/seaweedfs/Chart.yaml index 32f60787b..bfb39d484 100644 --- a/packages/system/seaweedfs/charts/seaweedfs/Chart.yaml +++ b/packages/system/seaweedfs/charts/seaweedfs/Chart.yaml @@ -1,6 +1,6 @@ apiVersion: v1 description: SeaweedFS name: seaweedfs -appVersion: "4.31" +appVersion: "4.45" # Dev note: Trigger a helm chart release by `git tag -a helm-` -version: 4.31.0 +version: 4.45.0 diff --git a/packages/system/seaweedfs/charts/seaweedfs/README.md b/packages/system/seaweedfs/charts/seaweedfs/README.md index a7d666d55..f787f8bb4 100644 --- a/packages/system/seaweedfs/charts/seaweedfs/README.md +++ b/packages/system/seaweedfs/charts/seaweedfs/README.md @@ -22,8 +22,8 @@ helm install --values=values.yaml seaweedfs seaweedfs/seaweedfs ## Info: * master/filer/volume are stateful sets with anti-affinity on the hostname, so your deployment will be spread/HA. -* chart is using memsql(mysql) as the filer backend to enable HA (multiple filer instances) and backup/HA memsql can provide. -* mysql user/password are created in a k8s secret (default: `-seaweedfs-db-secret`) and injected to the filer with ENV. +* leveldb2 is the default filer backend; a mysql-compatible database (memsql, ...) enables HA (multiple filer instances) and the backup/HA it can provide. +* with `filer.extraEnvironmentVars.WEED_MYSQL_ENABLED` set to `"true"`, mysql user/password are created in a k8s secret (default: `-seaweedfs-db-secret`) and injected to the filer with ENV. On any other store neither the secret nor the `WEED_MYSQL_*` env, plain or secret-backed, is rendered. * cert config exists and can be enabled, but not been tested, requires cert-manager to be installed. ## Prerequisites @@ -107,6 +107,120 @@ https://github.com/rancher/local-path-provisioner you can use ANY storage class you like, just update the correct storage-class for your deployment. +### Master data: hostPath vs a claim + +The master's `-mdir` holds its Raft log and snapshots, and with them the +cluster's identity (its topology UUID). `master.data.type` defaults to +`hostPath`, which does not follow a pod to another node: a master that is +rescheduled comes back with an empty data directory and a brand new cluster +UUID. With the chart's default of a single master replica there is no peer to +recover the identity from either. + +Putting the master's data on a claim avoids that: + +```yaml +master: + data: + type: "persistentVolumeClaim" + size: "1Gi" + storageClass: "" # empty uses the cluster's default StorageClass +``` + +Raft state is small, so a modest claim is enough — sizing matters far more for +volume and filer. + +The default is left at `hostPath` for backward compatibility: +`volumeClaimTemplates` is immutable on a StatefulSet, so flipping the type on a +release that already exists fails, whether the chart changes the default or you +change it yourself: + +```text +StatefulSet.apps "-seaweedfs-master" is invalid: spec: Forbidden: +updates to statefulset spec for fields other than 'replicas', ... are forbidden +``` + +New installs can set the claim from the start. To move an **existing** release +onto a claim without losing the cluster UUID, use the migration below. The +claim has to be seeded while the master is stopped: a running master rewrites +its Raft state, so copying into a live pod is silently undone by the next +restart. + +The steps below are for the chart's default of a single master +(`master.replicas: 1`). With several master replicas, repeat steps 1, 3 and 4 +for every ordinal, or migrate one at a time and let the remaining quorum +re-replicate. + +Take the names from the cluster rather than assembling them — the release +name, `nameOverride` and `fullnameOverride` all feed the chart's fullname +helper, so `-seaweedfs` is not always right: + +```bash +NS=; REL= +# scope by instance as well as component: several releases can share a namespace +STS=$(kubectl -n $NS get sts \ + -l app.kubernetes.io/instance=$REL,app.kubernetes.io/component=master \ + -o jsonpath='{.items[0].metadata.name}') +POD=$STS-0 +# a StatefulSet names its claims