From 64e5bf9b0b08d383c377a49839ff7296caebf178 Mon Sep 17 00:00:00 2001 From: "frolov.so" Date: Sat, 26 Sep 2026 12:25:32 +0300 Subject: [PATCH 01/17] docs(api): clarify health check parsing and evaluation Health expressions are parsed before helm-controller selects a wait strategy, while evaluation also applies to hooks waited through the poller when install wait is disabled. The API documentation must distinguish these paths so future ApplicationDefinitions do not rely on invalid no-op assumptions. Fixes cozystack/cozystack#4388 Assisted-by: LLM Signed-off-by: frolov.so --- api/v1alpha1/applicationdefinitions_types.go | 12 ++++++++---- packages/extra/monitoring/templates/helmrelease.yaml | 12 +++++++----- .../cozystack.io_applicationdefinitions.yaml | 12 ++++++++---- 3 files changed, 23 insertions(+), 13 deletions(-) diff --git a/api/v1alpha1/applicationdefinitions_types.go b/api/v1alpha1/applicationdefinitions_types.go index 0a6166254..98841a362 100644 --- a/api/v1alpha1/applicationdefinitions_types.go +++ b/api/v1alpha1/applicationdefinitions_types.go @@ -120,10 +120,14 @@ type ApplicationDefinitionRelease struct { // kstatus rules instead. // A CR whose CRD is not installed fails the Helm action before any wait, // whatever these expressions say. - // Upstream evaluates these only when the Helm action itself has wait - // enabled, so the release.cozystack.io/helm-install-disable-wait annotation - // makes them a silent no-op whatever waitStrategy says: the HelmRelease - // reports Ready as soon as helm applies the CR, with no error or warning. + // helm-controller parses and validates these expressions and constructs the + // status reader before choosing how to wait. Invalid configuration can + // therefore stall the HelmRelease with reason InvalidCELExpression even when + // the release.cozystack.io/helm-install-disable-wait annotation is set or the + // legacy wait strategy is selected. Once setup succeeds, only helm-controller's + // poller evaluates expressions: while a Helm action waits under the poller + // strategy, and for Helm hooks, which are still waited on when the annotation + // disables wait. The legacy strategy never evaluates them. // +optional HealthCheckExprs []kustomize.CustomHealthCheck `json:"healthCheckExprs,omitempty"` } diff --git a/packages/extra/monitoring/templates/helmrelease.yaml b/packages/extra/monitoring/templates/helmrelease.yaml index 0ffa7a630..42a67af26 100644 --- a/packages/extra/monitoring/templates/helmrelease.yaml +++ b/packages/extra/monitoring/templates/helmrelease.yaml @@ -43,11 +43,13 @@ spec: an unexpected status can never be silently read as Ready. A paused or failed log store is not ingesting, so the release must not report Ready; cozystack never sets spec.paused on these VLClusters, so `paused` is not - reachable in normal operation. Before the operator writes any updateStatus - (fresh apply) all three predicates are false, so the poller holds the - release not-ready until it becomes operational or hits `timeout:`, the - real backstop. Matching by kind covers every logsStorages entry. (CEL - evaluation is exercised live, not in helm-unittest, which cannot run it.) + reachable in normal operation. If status exists but has no updateStatus, + all three predicates evaluate to false. If the top-level status key is + absent, `has(status.updateStatus)` can instead fail during evaluation and + the status reader reports Unknown. The poller continues waiting in both + cases until the resource becomes operational or hits `timeout:`, the real + backstop. Matching by kind covers every logsStorages entry. (CEL evaluation + is exercised live, not in helm-unittest, which cannot run it.) The gate keys on a VLCluster existing, so an empty logsStorages would leave nothing to match. That configuration is rejected at render time by the diff --git a/packages/system/application-definition-crd/definition/cozystack.io_applicationdefinitions.yaml b/packages/system/application-definition-crd/definition/cozystack.io_applicationdefinitions.yaml index 9229e7601..f997f6398 100644 --- a/packages/system/application-definition-crd/definition/cozystack.io_applicationdefinitions.yaml +++ b/packages/system/application-definition-crd/definition/cozystack.io_applicationdefinitions.yaml @@ -337,10 +337,14 @@ spec: kstatus rules instead. A CR whose CRD is not installed fails the Helm action before any wait, whatever these expressions say. - Upstream evaluates these only when the Helm action itself has wait - enabled, so the release.cozystack.io/helm-install-disable-wait annotation - makes them a silent no-op whatever waitStrategy says: the HelmRelease - reports Ready as soon as helm applies the CR, with no error or warning. + helm-controller parses and validates these expressions and constructs the + status reader before choosing how to wait. Invalid configuration can + therefore stall the HelmRelease with reason InvalidCELExpression even when + the release.cozystack.io/helm-install-disable-wait annotation is set or the + legacy wait strategy is selected. Once setup succeeds, only helm-controller's + poller evaluates expressions: while a Helm action waits under the poller + strategy, and for Helm hooks, which are still waited on when the annotation + disables wait. The legacy strategy never evaluates them. items: description: CustomHealthCheck defines the health check for custom resources. From 05cdd323bbab1ed4db833d9ac467eed25fb0d512 Mon Sep 17 00:00:00 2001 From: "frolov.so" Date: Mon, 28 Sep 2026 18:46:01 +0300 Subject: [PATCH 02/17] docs(api): clarify legacy hook evaluation precedence Disabling install wait takes precedence over the selected wait strategy, so hook health expressions still run even when legacy is configured. State that exception explicitly so ApplicationDefinition authors do not assume their hook checks are bypassed. Assisted-by: LLM Signed-off-by: frolov.so --- api/v1alpha1/applicationdefinitions_types.go | 10 +++++++--- .../cozystack.io_applicationdefinitions.yaml | 10 +++++++--- 2 files changed, 14 insertions(+), 6 deletions(-) diff --git a/api/v1alpha1/applicationdefinitions_types.go b/api/v1alpha1/applicationdefinitions_types.go index 98841a362..82d5bd8de 100644 --- a/api/v1alpha1/applicationdefinitions_types.go +++ b/api/v1alpha1/applicationdefinitions_types.go @@ -120,14 +120,18 @@ type ApplicationDefinitionRelease struct { // kstatus rules instead. // A CR whose CRD is not installed fails the Helm action before any wait, // whatever these expressions say. - // helm-controller parses and validates these expressions and constructs the - // status reader before choosing how to wait. Invalid configuration can + // helm-controller parses and validates these expressions and creates a + // status reader factory before choosing how to wait. The factory constructs + // the concrete status reader when the selected wait path creates its + // resource manager. Invalid configuration can // therefore stall the HelmRelease with reason InvalidCELExpression even when // the release.cozystack.io/helm-install-disable-wait annotation is set or the // legacy wait strategy is selected. Once setup succeeds, only helm-controller's // poller evaluates expressions: while a Helm action waits under the poller // strategy, and for Helm hooks, which are still waited on when the annotation - // disables wait. The legacy strategy never evaluates them. + // disables wait. Without the annotation, the legacy strategy never evaluates + // them. With it, hooks are evaluated whatever the strategy, because disabling + // wait takes precedence. // +optional HealthCheckExprs []kustomize.CustomHealthCheck `json:"healthCheckExprs,omitempty"` } diff --git a/packages/system/application-definition-crd/definition/cozystack.io_applicationdefinitions.yaml b/packages/system/application-definition-crd/definition/cozystack.io_applicationdefinitions.yaml index f997f6398..8e208ac66 100644 --- a/packages/system/application-definition-crd/definition/cozystack.io_applicationdefinitions.yaml +++ b/packages/system/application-definition-crd/definition/cozystack.io_applicationdefinitions.yaml @@ -337,14 +337,18 @@ spec: kstatus rules instead. A CR whose CRD is not installed fails the Helm action before any wait, whatever these expressions say. - helm-controller parses and validates these expressions and constructs the - status reader before choosing how to wait. Invalid configuration can + helm-controller parses and validates these expressions and creates a + status reader factory before choosing how to wait. The factory constructs + the concrete status reader when the selected wait path creates its + resource manager. Invalid configuration can therefore stall the HelmRelease with reason InvalidCELExpression even when the release.cozystack.io/helm-install-disable-wait annotation is set or the legacy wait strategy is selected. Once setup succeeds, only helm-controller's poller evaluates expressions: while a Helm action waits under the poller strategy, and for Helm hooks, which are still waited on when the annotation - disables wait. The legacy strategy never evaluates them. + disables wait. Without the annotation, the legacy strategy never evaluates + them. With it, hooks are evaluated whatever the strategy, because disabling + wait takes precedence. items: description: CustomHealthCheck defines the health check for custom resources. From 662fcf83dee9cd8358f44a05395d48dc11eb43b8 Mon Sep 17 00:00:00 2001 From: Marian Koreniuk Date: Wed, 21 Oct 2026 15:09:55 +0200 Subject: [PATCH 03/17] feat(build): attach a provenance attestation beside the SBOM An image built with SBOM=1 says what is in it and nothing about how it was built: BUILDX_ARGS set --provenance=false for every build, from when any attestation broke the single-platform stitch. SBOM=1 now also passes --attest type=provenance,mode=min, which BuildKit writes into the same attestation manifest as the SBOM, so the index shape the stitch and the gate read since #4997 is unchanged and a signature over the index covers it. mode=min records the build times, the platform, the frontend and the BuildKit version and leaves out build arguments and secrets, which is what lets it ride every release image. A build without SBOM=1 keeps --provenance=false: the default docker driver cannot attach it, and a PR image turned into an index would buy nothing. Refs #3278 Assisted-by: LLM Signed-off-by: Marian Koreniuk --- docs/release.md | 2 +- hack/common-envs.mk | 24 ++++++++++++++++-------- hack/common-envs_test.bats | 9 +++++++-- 3 files changed, 24 insertions(+), 11 deletions(-) diff --git a/docs/release.md b/docs/release.md index c8620dbe9..2c4a54245 100644 --- a/docs/release.md +++ b/docs/release.md @@ -355,7 +355,7 @@ The script runs the same `cosign verify-blob` before it returns, so a signature ### SBOM of the container images -The container images a release pins by digest each carry an SPDX SBOM of the packages in them, which BuildKit attaches at build time as an attestation (`SBOM=1` in `tags.yaml`, scanner and flags in [`hack/common-envs.mk`](../hack/common-envs.mk)). The attestation is an entry of the image's index, so the digest the release pins names both, and promotion copies it with the image. Read it with `docker buildx imagetools inspect @ --format '{{ json .SBOM }}'`, which prints one document per platform. The attestations are not signed. A release cut before `SBOM=1` was set has none, and neither has the Talos installer image, which the imager builds and `skopeo` pushes, nor the third-party images `packages/` vendors by digest. +The container images a release pins by digest each carry an SPDX SBOM of the packages in them, which BuildKit attaches at build time as an attestation (`SBOM=1` in `tags.yaml`, scanner and flags in [`hack/common-envs.mk`](../hack/common-envs.mk)). The attestation is an entry of the image's index, so the digest the release pins names both, and promotion copies it with the image. Read it with `docker buildx imagetools inspect @ --format '{{ json .SBOM }}'`, which prints one document per platform. The same attestation manifest carries a SLSA provenance statement of the build, in BuildKit's `mode=min` (build times, platform, frontend and BuildKit version, no build arguments and no secrets), which `docker buildx imagetools inspect @ --format '{{ json .Provenance }}'` prints. The attestations are not signed. A release cut before `SBOM=1` was set has none, and neither has the Talos installer image, which the imager builds and `skopeo` pushes, nor the third-party images `packages/` vendors by digest. ## Nightly builds diff --git a/hack/common-envs.mk b/hack/common-envs.mk index 687de095d..8ede2e7d5 100644 --- a/hack/common-envs.mk +++ b/hack/common-envs.mk @@ -66,21 +66,29 @@ PLATFORM ?= $(if $(filter 1,$(LOAD)),,$(DEFAULT_PLATFORMS)) BUILDX_EXTRA_ARGS ?= COZYSTACK_VERSION = $(patsubst v%,%,$(shell git describe --tags --match 'v*')) -# SBOM=1 attaches an SPDX SBOM to every image as a BuildKit attestation. The -# pushed ref then names an index of the image and its attestation manifest, not -# the image itself, which hack/stitch-multiarch.sh and hack/verify-multiarch.sh -# both handle. Attestations need the docker-container buildx driver. The scanner -# is pinned by digest like every other build input, where --sbom=true would pull +# SBOM=1 attaches an SPDX SBOM and a SLSA provenance statement to every image +# as BuildKit attestations, in one attestation manifest per platform. The +# pushed ref then names an index of the image and that manifest, not the image +# itself, which hack/stitch-multiarch.sh and hack/verify-multiarch.sh both +# handle. Attestations need the docker-container buildx driver. The scanner is +# pinned by digest like every other build input, where --sbom=true would pull # a floating tag. Renovate bumps the version and the digest together, through # the manager in .github/renovate.json that reads the SBOM_SCANNER line below. +# +# The provenance is mode=min: build times, the build platform, the frontend +# and BuildKit version, nothing of the build arguments or secrets, so it can +# ride every release image. Without SBOM=1 provenance stays off: the default +# docker driver cannot attach it, and it would turn every PR image into an +# index for nothing that reads it. SBOM ?= 0 SBOM_SCANNER ?= docker.io/docker/buildkit-syft-scanner:1.12.0@sha256:ae4f3b554449e7e25548e7d8ccc029d17357348e30c6e3df01b92bc93654d6a9 -# A variable, because the commas would split the arguments of $(if) below. +# Variables, because the commas would split the arguments of $(if) below. SBOM_ATTEST := --attest type=sbom,generator=$(SBOM_SCANNER) +PROVENANCE_ATTEST := --attest type=provenance,mode=min -BUILDX_ARGS := --provenance=false --push=$(PUSH) --load=$(LOAD) \ +BUILDX_ARGS := --push=$(PUSH) --load=$(LOAD) \ --label org.opencontainers.image.source=https://github.com/cozystack/cozystack \ - $(if $(filter 1,$(SBOM)),$(SBOM_ATTEST)) \ + $(if $(filter 1,$(SBOM)),$(SBOM_ATTEST) $(PROVENANCE_ATTEST),--provenance=false) \ $(if $(strip $(BUILDER)),--builder=$(BUILDER)) \ $(if $(strip $(PLATFORM)),--platform=$(PLATFORM)) \ $(BUILDX_EXTRA_ARGS) diff --git a/hack/common-envs_test.bats b/hack/common-envs_test.bats index fd88ec6cd..59ad1eae6 100644 --- a/hack/common-envs_test.bats +++ b/hack/common-envs_test.bats @@ -144,15 +144,20 @@ load test_helper echo "$out" | grep -q -- '--push=0 --load=1' } -@test "SBOM=1 attaches an SPDX attestation from a scanner pinned by digest, and the default builds none" { +@test "SBOM=1 attaches an SPDX attestation from a scanner pinned by digest and a mode=min provenance, and the default builds none" { # An image built with an attestation is an index, not a plain manifest, which # the stitch and the gate have to read, so it stays off unless a build asks. - # --sbom=true would pull the scanner by a floating tag. + # --sbom=true would pull the scanner by a floating tag. Provenance rides the + # same attestation manifest; mode=max would write build arguments into it. out=$(make -n -C packages/system/cozystack-controller image IMAGE_TAG=pr-1-abc COZYSTACK_VERSION=0 BUILDER=b) if echo "$out" | grep -q -- '--attest\|--sbom'; then echo "FAIL: an attestation without SBOM=1"; false; fi + echo "$out" | grep -q -- '--provenance=false' || { echo "FAIL: provenance not switched off without SBOM=1"; false; } out=$(make -n -C packages/system/cozystack-controller image IMAGE_TAG=pr-1-abc COZYSTACK_VERSION=0 BUILDER=b SBOM=1) echo "$out" | grep -qE -- '--attest type=sbom,generator=[^ ]+@sha256:[0-9a-f]{64} ' || { echo "FAIL: no digest-pinned scanner"; false; } if echo "$out" | grep -q -- '--sbom'; then echo "FAIL: --sbom=true pulls a floating scanner tag"; false; fi + echo "$out" | grep -q -- '--attest type=provenance,mode=min' || { echo "FAIL: no mode=min provenance beside the SBOM"; false; } + if echo "$out" | grep -q -- '--provenance=false'; then echo "FAIL: --provenance=false cancels the provenance attestation"; false; fi + if echo "$out" | grep -qE -- 'provenance,mode=max|--provenance=true'; then echo "FAIL: full provenance would carry build arguments"; false; fi # The environment reaches buildx as well, which is how the release workflow sets it. out=$(SBOM=1 make -n -C packages/system/cozystack-controller image IMAGE_TAG=pr-1-abc COZYSTACK_VERSION=0 BUILDER=b) echo "$out" | grep -q -- '--attest type=sbom,' From 2527baf1156fc9d01d9fb3e2e725a92040100693 Mon Sep 17 00:00:00 2001 From: Andrey Kolkov Date: Thu, 12 Nov 2026 15:02:33 +0700 Subject: [PATCH 04/17] feat(dashboard): let a login link pick the Keycloak identity provider A link to the dashboard from an external portal, such as a billing system brokered into Keycloak as an identity provider, always lands on the realm login page first: the user has to pick that provider by hand, even though the link already knows which one they came from. Keycloak skips the page when the auth request carries kc_idp_hint, but the gatekeeper builds that request from a fixed login URL and its flags cannot pass a parameter through. The OIDC gatekeeper now runs oauth2-proxy from an alpha configuration, which allows kc_idp_hint on /oauth2/start to reach the login URL, so /oauth2/start?kc_idp_hint=&rd= goes straight to that provider. A login without the parameter is unchanged. Provider, upstream, listen address and injected headers move into a ConfigMap, because oauth2-proxy refuses them as flags alongside the alpha configuration; the values are those its --convert-config-to-alpha produces for the previous flags, and the pod restarts when they change. The client secret is mounted as a file. The tests that read the Keycloak URLs from the container args go with the flags; the rest of the gatekeeper suite now also loads the config template the deployment checksums. Assisted-By: LLM Signed-off-by: Andrey Kolkov --- .../templates/gatekeeper-config.yaml | 79 +++++++++ .../dashboard/templates/gatekeeper.yaml | 58 +++--- .../dashboard/tests/gatekeeper_test.yaml | 166 ++---------------- 3 files changed, 121 insertions(+), 182 deletions(-) create mode 100644 packages/system/dashboard/templates/gatekeeper-config.yaml diff --git a/packages/system/dashboard/templates/gatekeeper-config.yaml b/packages/system/dashboard/templates/gatekeeper-config.yaml new file mode 100644 index 000000000..19e1624e9 --- /dev/null +++ b/packages/system/dashboard/templates/gatekeeper-config.yaml @@ -0,0 +1,79 @@ +{{- $host := index .Values._cluster "root-host" }} +{{- $realm := index .Values._cluster "oidc-realm-name" | default "cozy" }} +{{- $oidcEnabled := index .Values._cluster "oidc-enabled" }} +{{- $keycloakInternalUrl := index .Values._cluster "keycloak-internal-url" | default "" }} +{{- if eq $oidcEnabled "true" }} +# oauth2-proxy alpha configuration for the OIDC gatekeeper. Provider, upstream, +# server and header injection live here because only the alpha configuration +# can pass a query parameter from /oauth2/start through to the IdP login URL. +apiVersion: v1 +kind: ConfigMap +metadata: + name: incloud-web-gatekeeper-config +data: + alpha-config.yaml: | + server: + BindAddress: 0.0.0.0:8000 + upstreamConfig: + upstreams: + - id: / + path: / + uri: http://cozy-dashboard-console.{{ .Release.Namespace }}.svc:8080 + passHostHeader: true + proxyWebSockets: true + flushInterval: 1s + timeout: 30s + injectRequestHeaders: + - name: X-Forwarded-Groups + values: [{claim: groups}] + - name: X-Forwarded-User + values: [{claim: user}] + - name: X-Forwarded-Email + values: [{claim: email}] + - name: X-Forwarded-Preferred-Username + values: [{claim: preferred_username}] + - name: X-Forwarded-Access-Token + values: [{claim: access_token}] + - name: Authorization + values: [{claim: id_token, prefix: "Bearer "}] + providers: + - id: oidc=dashboard + provider: oidc + clientID: dashboard + clientSecretFile: /etc/oauth2-proxy/client/client-secret + # No offline_access: that scope makes Keycloak issue an *offline* + # refresh token, which is decoupled from the SSO session and is NOT + # revoked by logout (end_session). Since oauth2-proxy keeps the + # refresh token in the kc-access cookie and silently refreshes it, + # a copied cookie would stay valid for the whole offline-session + # lifetime (~30d) even after the user logs out. An online refresh + # token is bound to the SSO session and is revoked on logout. + scope: openid email profile + loginURLParameters: + - name: approval_prompt + default: [force] + # A link to /oauth2/start?kc_idp_hint= sends the user straight + # to that Keycloak identity provider instead of the realm login page. + - name: kc_idp_hint + allow: + - pattern: '^[A-Za-z0-9._-]+$' + {{- if $keycloakInternalUrl }} + loginURL: https://keycloak.{{ $host }}/realms/{{ $realm }}/protocol/openid-connect/auth + redeemURL: {{ $keycloakInternalUrl }}/protocol/openid-connect/token + validateURL: {{ $keycloakInternalUrl }}/protocol/openid-connect/userinfo + backendLogoutURL: {{ $keycloakInternalUrl }}/protocol/openid-connect/logout?id_token_hint={id_token} + {{- else }} + backendLogoutURL: https://keycloak.{{ $host }}/realms/{{ $realm }}/protocol/openid-connect/logout?id_token_hint={id_token} + {{- end }} + oidcConfig: + issuerURL: https://keycloak.{{ $host }}/realms/{{ $realm }} + {{- if $keycloakInternalUrl }} + skipDiscovery: true + jwksURL: {{ $keycloakInternalUrl }}/protocol/openid-connect/certs + {{- end }} + emailClaim: email + groupsClaim: groups + userIDClaim: email + audienceClaims: [aud] + insecureSkipNonce: true +{{- end }} diff --git a/packages/system/dashboard/templates/gatekeeper.yaml b/packages/system/dashboard/templates/gatekeeper.yaml index dce5dcd84..9e231e9e8 100644 --- a/packages/system/dashboard/templates/gatekeeper.yaml +++ b/packages/system/dashboard/templates/gatekeeper.yaml @@ -21,6 +21,10 @@ spec: maxUnavailable: 25% template: metadata: + {{- if eq $oidcEnabled "true" }} + annotations: + checksum/gatekeeper-config: {{ include (print $.Template.BasePath "/gatekeeper-config.yaml") . | sha256sum }} + {{- end }} labels: app.kubernetes.io/instance: incloud-web app.kubernetes.io/name: gatekeeper @@ -51,52 +55,32 @@ spec: - name: auth-proxy image: quay.io/oauth2-proxy/oauth2-proxy:v7.12.0 imagePullPolicy: IfNotPresent + # Provider, upstream, listen address and injected headers are in + # gatekeeper-config.yaml; oauth2-proxy refuses them as flags next to + # --alpha-config. args: - - --provider=oidc - - --upstream=http://cozy-dashboard-console.{{ .Release.Namespace }}.svc:8080 - - --http-address=0.0.0.0:8000 + - --alpha-config=/etc/oauth2-proxy/config/alpha-config.yaml - --redirect-url=https://dashboard.{{ $host }}/oauth2/callback - - --oidc-issuer-url=https://keycloak.{{ $host }}/realms/{{ $realm }} - {{- if $keycloakInternalUrl }} - - --skip-oidc-discovery - - --login-url=https://keycloak.{{ $host }}/realms/{{ $realm }}/protocol/openid-connect/auth - - --redeem-url={{ $keycloakInternalUrl }}/protocol/openid-connect/token - - --oidc-jwks-url={{ $keycloakInternalUrl }}/protocol/openid-connect/certs - - --validate-url={{ $keycloakInternalUrl }}/protocol/openid-connect/userinfo - - --backend-logout-url={{ $keycloakInternalUrl }}/protocol/openid-connect/logout?id_token_hint={id_token} - {{- else }} - - --backend-logout-url=https://keycloak.{{ $host }}/realms/{{ $realm }}/protocol/openid-connect/logout?id_token_hint={id_token} - {{- end }} - --whitelist-domain=keycloak.{{ $host }} - --email-domain=* - --api-route=^/api(/|$) - --api-route=^/apis(/|$) - - --pass-access-token=true - - --pass-authorization-header=true - --cookie-refresh=3m - --cookie-name=kc-access - --cookie-secure=true - --cookie-secret=$(OAUTH2_PROXY_COOKIE_SECRET) - --skip-provider-button - # No offline_access: that scope makes Keycloak issue an *offline* - # refresh token, which is decoupled from the SSO session and is NOT - # revoked by logout (end_session). Since oauth2-proxy keeps the - # refresh token in the kc-access cookie and silently refreshes it, - # a copied cookie would stay valid for the whole offline-session - # lifetime (~30d) even after the user logs out. An online refresh - # token is bound to the SSO session and is revoked on logout. - - --scope=openid email profile {{- if eq $oidcInsecureSkipVerify "true" }} - --ssl-insecure-skip-verify=true {{- end }} + volumeMounts: + - name: gatekeeper-config + mountPath: /etc/oauth2-proxy/config + readOnly: true + - name: client-secret + mountPath: /etc/oauth2-proxy/client + readOnly: true env: - - name: OAUTH2_PROXY_CLIENT_ID - value: dashboard - - name: OAUTH2_PROXY_CLIENT_SECRET - valueFrom: - secretKeyRef: - name: dashboard-client - key: client-secret-key - name: OAUTH2_PROXY_COOKIE_SECRET valueFrom: secretKeyRef: @@ -212,8 +196,18 @@ spec: type: RuntimeDefault terminationMessagePath: /dev/termination-log terminationMessagePolicy: File - {{- if ne $oidcEnabled "true" }} volumes: + {{- if eq $oidcEnabled "true" }} + - name: gatekeeper-config + configMap: + name: incloud-web-gatekeeper-config + - name: client-secret + secret: + secretName: dashboard-client + items: + - key: client-secret-key + path: client-secret + {{- else }} # optional: the login page degrades to its unbranded default if the # ConfigMap is missing, so a start-up dependency is not worth failing on. - name: branding diff --git a/packages/system/dashboard/tests/gatekeeper_test.yaml b/packages/system/dashboard/tests/gatekeeper_test.yaml index 3b8efd7ed..e5735e9b8 100644 --- a/packages/system/dashboard/tests/gatekeeper_test.yaml +++ b/packages/system/dashboard/tests/gatekeeper_test.yaml @@ -1,6 +1,7 @@ suite: gatekeeper container and probes per OIDC mode templates: - templates/gatekeeper.yaml + - templates/gatekeeper-config.yaml release: name: dashboard @@ -19,6 +20,7 @@ release: tests: - it: oidc-enabled=false renders token-proxy with /healthz probes + template: templates/gatekeeper.yaml set: _cluster: root-host: example.org @@ -76,15 +78,25 @@ tests: # there — pin its absence so a refactor that hoists the volume out of the # non-OIDC guard is a test failure. - it: oidc-enabled=true does not mount the branding config + template: templates/gatekeeper.yaml set: _cluster: root-host: example.org oidc-enabled: "true" asserts: - - notExists: + - notContains: path: spec.template.spec.volumes - - notExists: + content: + name: branding + configMap: + name: cozy-dashboard-console-config + optional: true + - notContains: path: spec.template.spec.containers[0].volumeMounts + content: + name: branding + mountPath: /etc/cozystack/branding + readOnly: true # authentication.oidc.enabled defaults to false while keycloakInternalUrl now # defaults to the in-cluster Service, so THIS pair — OIDC off, internal URL @@ -93,6 +105,7 @@ tests: # token-proxy branch today; pin that, because a refactor which hoists the # block out would otherwise ship silently. - it: oidc-enabled=false ignores a set keycloak-internal-url + template: templates/gatekeeper.yaml set: _cluster: root-host: example.org @@ -115,6 +128,7 @@ tests: content: --oidc-jwks-url=http://keycloak-http.cozy-keycloak.svc:8080/realms/cozy/protocol/openid-connect/certs - it: oidc-enabled=true renders auth-proxy with /ping probes and no startupProbe + template: templates/gatekeeper.yaml set: _cluster: root-host: example.org @@ -137,151 +151,3 @@ tests: - equal: path: spec.template.spec.containers[0].ports[0].containerPort value: 8000 - - # keycloak-internal-url arrives on the _cluster channel from - # authentication.oidc.keycloakInternalUrl in packages/core/platform. Its - # default is the in-cluster Keycloak Service, so the value asserted below is - # what a stock cluster ships: oauth2-proxy skips OIDC discovery and talks to - # the Service for token/jwks/userinfo/logout, which keeps the dashboard - # independent of the root ingress serving keycloak. at startup. The - # browser-facing URLs (redirect, login) must stay on the external host — - # routing them to a cluster-internal address would send the user's browser to - # an unreachable URL. - - it: default in-cluster keycloak URL skips discovery and keeps browser URLs external - set: - _cluster: - root-host: example.org - oidc-enabled: "true" - keycloak-internal-url: http://keycloak-http.cozy-keycloak.svc:8080/realms/cozy - asserts: - - contains: - path: spec.template.spec.containers[0].args - content: --skip-oidc-discovery - - contains: - path: spec.template.spec.containers[0].args - content: --redeem-url=http://keycloak-http.cozy-keycloak.svc:8080/realms/cozy/protocol/openid-connect/token - - contains: - path: spec.template.spec.containers[0].args - content: --oidc-jwks-url=http://keycloak-http.cozy-keycloak.svc:8080/realms/cozy/protocol/openid-connect/certs - - contains: - path: spec.template.spec.containers[0].args - content: --validate-url=http://keycloak-http.cozy-keycloak.svc:8080/realms/cozy/protocol/openid-connect/userinfo - - contains: - path: spec.template.spec.containers[0].args - content: --backend-logout-url=http://keycloak-http.cozy-keycloak.svc:8080/realms/cozy/protocol/openid-connect/logout?id_token_hint={id_token} - - contains: - path: spec.template.spec.containers[0].args - content: --redirect-url=https://dashboard.example.org/oauth2/callback - - contains: - path: spec.template.spec.containers[0].args - content: --login-url=https://keycloak.example.org/realms/cozy/protocol/openid-connect/auth - - contains: - path: spec.template.spec.containers[0].args - content: --oidc-issuer-url=https://keycloak.example.org/realms/cozy - - - it: an explicit keycloak-internal-url override wins over the default - set: - _cluster: - root-host: example.org - oidc-enabled: "true" - keycloak-internal-url: http://keycloak.example.test:8080/realms/other - asserts: - - contains: - path: spec.template.spec.containers[0].args - content: --skip-oidc-discovery - - contains: - path: spec.template.spec.containers[0].args - content: --redeem-url=http://keycloak.example.test:8080/realms/other/protocol/openid-connect/token - - contains: - path: spec.template.spec.containers[0].args - content: --oidc-jwks-url=http://keycloak.example.test:8080/realms/other/protocol/openid-connect/certs - - contains: - path: spec.template.spec.containers[0].args - content: --validate-url=http://keycloak.example.test:8080/realms/other/protocol/openid-connect/userinfo - - notContains: - path: spec.template.spec.containers[0].args - content: --redeem-url=http://keycloak-http.cozy-keycloak.svc:8080/realms/cozy/protocol/openid-connect/token - - # The escape hatch: an operator who sets keycloakInternalUrl back to "" gets - # the historical shape — full OIDC discovery against the external issuer, no - # backend URLs pinned. It must keep working, so pin it. - # - # --skip-oidc-discovery carries the whole meaning here. All five in-cluster - # args live inside one {{- if $keycloakInternalUrl }} block in the template, - # so its absence structurally guarantees the absence of the other four; the - # notContains assertions below then pin the regression that actually threatens - # this branch — the in-cluster default leaking back in. Asserting an arg count - # instead would couple this OIDC test to every unrelated gatekeeper flag. - - it: empty keycloak-internal-url restores external OIDC discovery - set: - _cluster: - root-host: example.org - oidc-enabled: "true" - keycloak-internal-url: "" - asserts: - - notContains: - path: spec.template.spec.containers[0].args - content: --skip-oidc-discovery - - contains: - path: spec.template.spec.containers[0].args - content: --oidc-issuer-url=https://keycloak.example.org/realms/cozy - - contains: - path: spec.template.spec.containers[0].args - content: --backend-logout-url=https://keycloak.example.org/realms/cozy/protocol/openid-connect/logout?id_token_hint={id_token} - - notContains: - path: spec.template.spec.containers[0].args - content: --redeem-url=http://keycloak-http.cozy-keycloak.svc:8080/realms/cozy/protocol/openid-connect/token - - notContains: - path: spec.template.spec.containers[0].args - content: --oidc-jwks-url=http://keycloak-http.cozy-keycloak.svc:8080/realms/cozy/protocol/openid-connect/certs - - notContains: - path: spec.template.spec.containers[0].args - content: --validate-url=http://keycloak-http.cozy-keycloak.svc:8080/realms/cozy/protocol/openid-connect/userinfo - - notContains: - path: spec.template.spec.containers[0].args - content: --backend-logout-url=http://keycloak-http.cozy-keycloak.svc:8080/realms/cozy/protocol/openid-connect/logout?id_token_hint={id_token} - - # The realm segment of the browser-facing issuer/login/logout URLs is driven - # by _cluster.oidc-realm-name (authentication.oidc.realmName in the platform). - # A renamed realm must reach every one of them; a URL left on the literal - # "cozy" would send the browser to a realm the apiserver OIDC issuer no longer - # matches, silently breaking SSO. - - it: threads a custom realm name through the browser-facing OIDC URLs - set: - _cluster: - root-host: example.org - oidc-enabled: "true" - oidc-realm-name: acme - keycloak-internal-url: http://keycloak-http.cozy-keycloak.svc:8080/realms/acme - asserts: - - contains: - path: spec.template.spec.containers[0].args - content: --oidc-issuer-url=https://keycloak.example.org/realms/acme - - contains: - path: spec.template.spec.containers[0].args - content: --login-url=https://keycloak.example.org/realms/acme/protocol/openid-connect/auth - - notContains: - path: spec.template.spec.containers[0].args - content: --oidc-issuer-url=https://keycloak.example.org/realms/cozy - - # The external-discovery branch (empty internal URL) builds its own - # backend-logout-url on the browser host, so the realm segment there must - # follow oidc-realm-name too; reverting $realm in that branch alone would - # otherwise survive the suite. - - it: threads a custom realm into the external-discovery logout URL - set: - _cluster: - root-host: example.org - oidc-enabled: "true" - oidc-realm-name: acme - keycloak-internal-url: "" - asserts: - - notContains: - path: spec.template.spec.containers[0].args - content: --skip-oidc-discovery - - contains: - path: spec.template.spec.containers[0].args - content: --backend-logout-url=https://keycloak.example.org/realms/acme/protocol/openid-connect/logout?id_token_hint={id_token} - - notContains: - path: spec.template.spec.containers[0].args - content: --backend-logout-url=https://keycloak.example.org/realms/cozy/protocol/openid-connect/logout?id_token_hint={id_token} From 7b214464ee88e6ae67782cc8b114ebe4cd33660d Mon Sep 17 00:00:00 2001 From: Timofei Larkin Date: Wed, 14 Oct 2026 11:58:49 +0200 Subject: [PATCH 05/17] fix(lineage-webhook): keep an explicit tenantresource false The webhook computes the tenantresource verdict from the ApplicationDefinition selectors on first admission and copies it over whatever label the chart rendered, so a chart cannot take a Secret the definition still selects off the tenantsecrets projection. The credentials conversion in design-proposals/user-secrets-api needs exactly that during its migration window: the converted chart renders the platform-only credentials Secret with tenantresource false while the old definition still selects the name. A rendered false is now kept; a rendered true is still replaced by the computed verdict, so the object can only narrow what the definition grants, never widen it. Assisted-by: LLM Signed-off-by: Timofei Larkin --- internal/lineagecontrollerwebhook/webhook.go | 19 ++- .../webhook_tenantresource_test.go | 115 ++++++++++++++++++ 2 files changed, 128 insertions(+), 6 deletions(-) create mode 100644 internal/lineagecontrollerwebhook/webhook_tenantresource_test.go diff --git a/internal/lineagecontrollerwebhook/webhook.go b/internal/lineagecontrollerwebhook/webhook.go index ea8b0d01b..d2ef5f938 100644 --- a/internal/lineagecontrollerwebhook/webhook.go +++ b/internal/lineagecontrollerwebhook/webhook.go @@ -193,12 +193,19 @@ func (h *LineageControllerWebhook) computeLabels(ctx context.Context, obj *unstr crd := cfg.appCRDMap[appRef{gv.Group, owner.GetKind()}] resourceSelectors := h.getResourceSelectors(obj.GroupVersionKind().GroupKind(), crd) - labels[corev1alpha1.TenantResourceLabelKey] = func(b bool) string { - if b { - return corev1alpha1.TenantResourceLabelValue - } - return "false" - }(matchResourceToExcludeInclude(ctx, obj.GetName(), templateLabels, obj.GetLabels(), resourceSelectors)) + selected := matchResourceToExcludeInclude(ctx, obj.GetName(), templateLabels, obj.GetLabels(), resourceSelectors) + // The verdict can be narrowed by the object and never widened: a chart that + // renders tenantresource "false" keeps it even where the definition selects + // the name, while a chart-set "true" is replaced by the computed verdict. + // This is what lets a chart take a Secret the definition still selects off + // the tenantsecrets projection while the definition catches up. + if obj.GetLabels()[corev1alpha1.TenantResourceLabelKey] == "false" { + selected = false + } + labels[corev1alpha1.TenantResourceLabelKey] = "false" + if selected { + labels[corev1alpha1.TenantResourceLabelKey] = corev1alpha1.TenantResourceLabelValue + } return labels, nil } diff --git a/internal/lineagecontrollerwebhook/webhook_tenantresource_test.go b/internal/lineagecontrollerwebhook/webhook_tenantresource_test.go new file mode 100644 index 000000000..4fe9f6af8 --- /dev/null +++ b/internal/lineagecontrollerwebhook/webhook_tenantresource_test.go @@ -0,0 +1,115 @@ +package lineagecontrollerwebhook + +import ( + "context" + "encoding/json" + "strings" + "testing" + + cozyv1alpha1 "github.com/cozystack/cozystack/api/v1alpha1" + corev1alpha1 "github.com/cozystack/cozystack/pkg/apis/core/v1alpha1" + admissionv1 "k8s.io/api/admission/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/apimachinery/pkg/runtime" + "sigs.k8s.io/controller-runtime/pkg/webhook/admission" +) + +// The tenantresource verdict is the definition's, but an object may narrow it +// and never widen it: a rendered "false" survives a selector that matches the +// name, a rendered "true" does not survive one that does not. +func TestHandle_TenantResourceLabelNarrowsOnly(t *testing.T) { + tenantResourcePath := "/metadata/labels/" + strings.ReplaceAll(corev1alpha1.TenantResourceLabelKey, "/", "~1") + + tests := []struct { + name string + secret string + rendered string + // want is the value the label must hold once the patch is applied; + // "" means the response must not touch the label at all. + want string + }{ + { + name: "a rendered false is kept where the definition selects the name", + secret: "harbor-demo-credentials", + rendered: "false", + want: "", + }, + { + name: "a rendered true is overwritten where the definition does not select the name", + secret: "harbor-demo-other", + rendered: "true", + want: "false", + }, + { + name: "no rendered label gets the definition's verdict", + secret: "harbor-demo-credentials", + rendered: "", + want: "true", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + w := newHandleTestWebhook(t) + w.config.Store(&runtimeConfig{appCRDMap: map[appRef]*cozyv1alpha1.ApplicationDefinition{ + {"apps.cozystack.io", "Harbor"}: {Spec: cozyv1alpha1.ApplicationDefinitionSpec{ + Application: cozyv1alpha1.ApplicationDefinitionApplication{Kind: "Harbor"}, + Secrets: cozyv1alpha1.ApplicationDefinitionResources{ + Include: []*cozyv1alpha1.ApplicationDefinitionResourceSelector{ + {ResourceNames: []string{"{{ .kind }}-{{ .name }}-credentials"}}, + }, + }, + }}, + }}) + + labels := map[string]string{"helm.toolkit.fluxcd.io/name": "harbor-demo"} + if tt.rendered != "" { + labels[corev1alpha1.TenantResourceLabelKey] = tt.rendered + } + obj := &unstructured.Unstructured{} + obj.SetAPIVersion("v1") + obj.SetKind("Secret") + obj.SetNamespace("tenant-demo") + obj.SetName(tt.secret) + obj.SetLabels(labels) + raw, err := json.Marshal(obj) + if err != nil { + t.Fatalf("marshal object: %v", err) + } + + resp := w.Handle(context.Background(), admission.Request{AdmissionRequest: admissionv1.AdmissionRequest{ + Kind: metav1.GroupVersionKind{Version: "v1", Kind: "Secret"}, + Namespace: "tenant-demo", + Name: tt.secret, + Operation: admissionv1.Create, + Object: runtime.RawExtension{Raw: raw}, + }}) + if !resp.Allowed { + t.Fatalf("expected allowed response, got %+v", resp.Result) + } + + var got string + var touched bool + for _, p := range resp.Patches { + if p.Path != tenantResourcePath { + continue + } + touched = true + v, ok := p.Value.(string) + if !ok { + t.Fatalf("patch %s carries %T, want string", p.Path, p.Value) + } + got = v + } + switch { + case tt.want == "" && touched: + t.Errorf("expected the label untouched, got patch value %q", got) + case tt.want != "" && !touched: + t.Errorf("expected a patch setting the label to %q, got none", tt.want) + case tt.want != "" && got != tt.want: + t.Errorf("label patched to %q, want %q", got, tt.want) + } + }) + } +} From d687e73fd40d455868fc32fd904112b10e4cb6de Mon Sep 17 00:00:00 2001 From: Timofei Larkin Date: Mon, 26 Oct 2026 10:51:43 +0100 Subject: [PATCH 06/17] docs(lineage-webhook): cut the rationale from the verdict comment Comments carry the mechanism, not the reason the change was made; the reason is in the design doc and the PR. Assisted-by: LLM Signed-off-by: Timofei Larkin --- internal/lineagecontrollerwebhook/webhook.go | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/internal/lineagecontrollerwebhook/webhook.go b/internal/lineagecontrollerwebhook/webhook.go index d2ef5f938..a98735da3 100644 --- a/internal/lineagecontrollerwebhook/webhook.go +++ b/internal/lineagecontrollerwebhook/webhook.go @@ -194,11 +194,9 @@ func (h *LineageControllerWebhook) computeLabels(ctx context.Context, obj *unstr resourceSelectors := h.getResourceSelectors(obj.GroupVersionKind().GroupKind(), crd) selected := matchResourceToExcludeInclude(ctx, obj.GetName(), templateLabels, obj.GetLabels(), resourceSelectors) - // The verdict can be narrowed by the object and never widened: a chart that - // renders tenantresource "false" keeps it even where the definition selects - // the name, while a chart-set "true" is replaced by the computed verdict. - // This is what lets a chart take a Secret the definition still selects off - // the tenantsecrets projection while the definition catches up. + // The object may narrow the verdict and never widen it: a rendered "false" + // is kept even where the definition selects the name, a rendered "true" is + // replaced by the computed verdict. if obj.GetLabels()[corev1alpha1.TenantResourceLabelKey] == "false" { selected = false } From 730fd5ebf52aaa0e493a43904f20e1f11e134cc7 Mon Sep 17 00:00:00 2001 From: Timofei Larkin Date: Tue, 27 Oct 2026 16:14:35 +0100 Subject: [PATCH 07/17] fix(lineage-webhook): keep a rendered false only on create The cacert controller re-runs admission after a selector change by dropping managed-by-cozystack and keeping the other labels, so the UPDATE carries the "false" this webhook wrote on an earlier admission. Reading that as the chart's narrowing froze the old verdict: a projection, once revoked, could not be granted again. The chart's narrowing only matters on CREATE, since an existing Secret already carries managed-by-cozystack and skips the webhook. Assisted-by: LLM Signed-off-by: Timofei Larkin --- internal/lineagecontrollerwebhook/webhook.go | 16 ++++--- .../webhook_tenantresource_test.go | 43 ++++++++++++++++--- 2 files changed, 48 insertions(+), 11 deletions(-) diff --git a/internal/lineagecontrollerwebhook/webhook.go b/internal/lineagecontrollerwebhook/webhook.go index a98735da3..b6e996275 100644 --- a/internal/lineagecontrollerwebhook/webhook.go +++ b/internal/lineagecontrollerwebhook/webhook.go @@ -9,6 +9,7 @@ import ( "strings" "github.com/cozystack/cozystack/pkg/lineage" + admissionv1 "k8s.io/api/admission/v1" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" @@ -123,7 +124,7 @@ func (h *LineageControllerWebhook) Handle(ctx context.Context, req admission.Req logger.Error(err, "error computing lineage labels") return admission.Errored(500, fmt.Errorf("error computing lineage labels: %w", err)) } - labels, err := h.computeLabels(ctx, obj, owner) + labels, err := h.computeLabels(ctx, obj, owner, req.Operation) if err != nil { logger.Error(err, "error computing lineage labels") return admission.Errored(500, fmt.Errorf("error computing lineage labels: %w", err)) @@ -159,7 +160,7 @@ func (h *LineageControllerWebhook) getOwner(ctx context.Context, o *unstructured return obj, err } -func (h *LineageControllerWebhook) computeLabels(ctx context.Context, obj *unstructured.Unstructured, owner *unstructured.Unstructured) (map[string]string, error) { +func (h *LineageControllerWebhook) computeLabels(ctx context.Context, obj *unstructured.Unstructured, owner *unstructured.Unstructured, op admissionv1.Operation) (map[string]string, error) { if owner == nil { return nil, nil } @@ -194,10 +195,13 @@ func (h *LineageControllerWebhook) computeLabels(ctx context.Context, obj *unstr resourceSelectors := h.getResourceSelectors(obj.GroupVersionKind().GroupKind(), crd) selected := matchResourceToExcludeInclude(ctx, obj.GetName(), templateLabels, obj.GetLabels(), resourceSelectors) - // The object may narrow the verdict and never widen it: a rendered "false" - // is kept even where the definition selects the name, a rendered "true" is - // replaced by the computed verdict. - if obj.GetLabels()[corev1alpha1.TenantResourceLabelKey] == "false" { + // On CREATE the object may narrow the verdict and never widen it: a + // rendered "false" is kept even where the definition selects the name, a + // rendered "true" is replaced. Only on CREATE: a re-admission (UPDATE with + // managed-by-cozystack dropped, as the cacert controller does on a selector + // change) carries the "false" this webhook wrote earlier, and keeping it + // would block a grant. + if op == admissionv1.Create && obj.GetLabels()[corev1alpha1.TenantResourceLabelKey] == "false" { selected = false } labels[corev1alpha1.TenantResourceLabelKey] = "false" diff --git a/internal/lineagecontrollerwebhook/webhook_tenantresource_test.go b/internal/lineagecontrollerwebhook/webhook_tenantresource_test.go index 4fe9f6af8..32d218715 100644 --- a/internal/lineagecontrollerwebhook/webhook_tenantresource_test.go +++ b/internal/lineagecontrollerwebhook/webhook_tenantresource_test.go @@ -16,13 +16,15 @@ import ( ) // The tenantresource verdict is the definition's, but an object may narrow it -// and never widen it: a rendered "false" survives a selector that matches the -// name, a rendered "true" does not survive one that does not. +// on CREATE and never widen it: a rendered "false" survives a selector that +// matches the name, a rendered "true" does not survive one that does not. A +// re-admission UPDATE gets the definition's verdict whatever the label says. func TestHandle_TenantResourceLabelNarrowsOnly(t *testing.T) { tenantResourcePath := "/metadata/labels/" + strings.ReplaceAll(corev1alpha1.TenantResourceLabelKey, "/", "~1") tests := []struct { name string + op admissionv1.Operation secret string rendered string // want is the value the label must hold once the patch is applied; @@ -31,22 +33,41 @@ func TestHandle_TenantResourceLabelNarrowsOnly(t *testing.T) { }{ { name: "a rendered false is kept where the definition selects the name", + op: admissionv1.Create, secret: "harbor-demo-credentials", rendered: "false", want: "", }, { name: "a rendered true is overwritten where the definition does not select the name", + op: admissionv1.Create, secret: "harbor-demo-other", rendered: "true", want: "false", }, { name: "no rendered label gets the definition's verdict", + op: admissionv1.Create, secret: "harbor-demo-credentials", rendered: "", want: "true", }, + { + // The cacert controller's re-admission after a selector change: + // managed-by-cozystack dropped, the old verdict still on the object. + name: "a re-admission grants where the definition now selects the name", + op: admissionv1.Update, + secret: "harbor-demo-credentials", + rendered: "false", + want: "true", + }, + { + name: "a re-admission revokes where the definition no longer selects the name", + op: admissionv1.Update, + secret: "harbor-demo-other", + rendered: "true", + want: "false", + }, } for _, tt := range tests { @@ -78,13 +99,25 @@ func TestHandle_TenantResourceLabelNarrowsOnly(t *testing.T) { t.Fatalf("marshal object: %v", err) } - resp := w.Handle(context.Background(), admission.Request{AdmissionRequest: admissionv1.AdmissionRequest{ + req := admissionv1.AdmissionRequest{ Kind: metav1.GroupVersionKind{Version: "v1", Kind: "Secret"}, Namespace: "tenant-demo", Name: tt.secret, - Operation: admissionv1.Create, + Operation: tt.op, Object: runtime.RawExtension{Raw: raw}, - }}) + } + if tt.op == admissionv1.Update { + old := obj.DeepCopy() + oldLabels := old.GetLabels() + oldLabels[ManagedObjectKey] = "true" + old.SetLabels(oldLabels) + oldRaw, err := json.Marshal(old) + if err != nil { + t.Fatalf("marshal old object: %v", err) + } + req.OldObject = runtime.RawExtension{Raw: oldRaw} + } + resp := w.Handle(context.Background(), admission.Request{AdmissionRequest: req}) if !resp.Allowed { t.Fatalf("expected allowed response, got %+v", resp.Result) } From 49e98d4ec51cbfc557e0e30700da02ae9d6175f0 Mon Sep 17 00:00:00 2001 From: Andrey Kolkov Date: Thu, 12 Nov 2026 18:25:40 +0700 Subject: [PATCH 08/17] test(dashboard): check the gatekeeper login redirect in e2e The Keycloak URLs, the realm and the kc_idp_hint allow rule now live in the gatekeeper's alpha configuration, and nothing exercised them: the OIDC e2e only proved the pod starts. After the gatekeeper rolls out with OIDC enabled, the test requests /oauth2/start through a port-forward and checks the redirect: an allowed hint reaches the cozy realm's auth URL, and a value outside the allow pattern is dropped. Assisted-by: LLM Signed-off-by: Andrey Kolkov --- hack/e2e-install-cozystack.bats | 42 +++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/hack/e2e-install-cozystack.bats b/hack/e2e-install-cozystack.bats index 47315ac85..ff2b128ab 100644 --- a/hack/e2e-install-cozystack.bats +++ b/hack/e2e-install-cozystack.bats @@ -367,6 +367,48 @@ # has necessarily been re-reconciled, so Ready here means the whole upgrade # converged -- not just the one Deployment this test watched. kubectl wait hr/dashboard -n cozy-dashboard --timeout=10m --for=condition=ready + + # The login redirect oauth2-proxy builds from the alpha config: the realm path + # must reach the browser-facing auth URL, an allowed kc_idp_hint must be passed + # through to Keycloak, and a value outside the allow pattern must be dropped. + # Asserted after the port-forward is gone: on failure set -e would skip a kill + # placed after the assertion, and a trap would hide the TAP line. + pf_log=$(mktemp) + kubectl -n cozy-dashboard port-forward deploy/incloud-web-gatekeeper 18000:8000 >"$pf_log" 2>&1 & + pf_pid=$! + hinted="" + rejected="" + if timeout 30 sh -ec 'until nc -z localhost 18000; do sleep 0.2; done'; then + hinted=$(curl -sS -o /dev/null -w '%{redirect_url}' 'http://localhost:18000/oauth2/start?kc_idp_hint=e2e-idp') || true + rejected=$(curl -sS -o /dev/null -w '%{redirect_url}' 'http://localhost:18000/oauth2/start?kc_idp_hint=e2e%26prompt%3Dnone') || true + fi + kill "$pf_pid" 2>/dev/null || true + wait "$pf_pid" 2>/dev/null || true + + case "$hinted" in + https://keycloak.example.org/realms/cozy/protocol/openid-connect/auth\?*kc_idp_hint=e2e-idp*) ;; + *) + echo "=== /oauth2/start?kc_idp_hint=e2e-idp did not redirect to the cozy realm with the hint ===" + echo "Location: ${hinted:-}" + cat "$pf_log" + false + ;; + esac + case "$rejected" in + https://keycloak.example.org/realms/cozy/protocol/openid-connect/auth\?*kc_idp_hint*|https://keycloak.example.org/realms/cozy/protocol/openid-connect/auth\?*prompt=none*) + echo "=== a kc_idp_hint outside the allow pattern reached the Keycloak URL ===" + echo "Location: $rejected" + false + ;; + https://keycloak.example.org/realms/cozy/protocol/openid-connect/auth\?*) ;; + *) + echo "=== /oauth2/start with a rejected kc_idp_hint did not redirect to Keycloak ===" + echo "Location: ${rejected:-}" + cat "$pf_log" + false + ;; + esac + rm -f "$pf_log" } @test "Aggregated API rejects Tenant name with dashes" { From cbdcd4a57209d774a9d9c4413db544dfd41487e7 Mon Sep 17 00:00:00 2001 From: Andrey Kolkov Date: Fri, 13 Nov 2026 11:21:42 +0700 Subject: [PATCH 09/17] test(dashboard): run the gatekeeper login redirect against oauth2-proxy The realm and Keycloak URL branches moved into the gatekeeper's alpha configuration, and nothing checked them for a realm other than cozy or for the OIDC discovery branch: the e2e runs the default realm with the in-cluster Keycloak URL. A unit test renders the chart for another realm, starts the auth-proxy image with the rendered args and config, and checks the /oauth2/start redirect on both branches, the discovery one against a local Keycloak stub. The image is read from the render, so an oauth2-proxy bump re-checks the alpha configuration. Assisted-by: LLM Signed-off-by: Andrey Kolkov --- hack/dashboard-gatekeeper-login.bats | 162 +++++++++++++++++++++++++++ 1 file changed, 162 insertions(+) create mode 100644 hack/dashboard-gatekeeper-login.bats diff --git a/hack/dashboard-gatekeeper-login.bats b/hack/dashboard-gatekeeper-login.bats new file mode 100644 index 000000000..03a22e2f0 --- /dev/null +++ b/hack/dashboard-gatekeeper-login.bats @@ -0,0 +1,162 @@ +#!/usr/bin/env bats +# ----------------------------------------------------------------------------- +# The dashboard gatekeeper's login redirect, checked against the oauth2-proxy +# binary the chart ships rather than against the rendered config text: the +# chart is rendered for a non-default realm, the auth-proxy container runs with +# the image, args and alpha config from that render, and /oauth2/start must +# redirect to that realm with an allowed kc_idp_hint passed through. The image +# comes from the render, so bumping it re-runs these cases on the new binary. +# ----------------------------------------------------------------------------- + +load test_helper + +REPO_ROOT="$(cd "$(dirname "${BATS_TEST_FILENAME:-$0}")/.." && pwd)" +STUB_IMAGE="python:3.13-alpine@sha256:9ef1a599f863231c3d91e941389bfdc4a2d6070557243d54df1a4e57015b960e" +HOST=example.org +REALM=acme + +setup() { + strict_setup + docker info >/dev/null 2>&1 || { + echo "docker is required to run the gatekeeper image" >&2 + return 1 + } + work=$(mktemp -d) + mkdir -p "$work/config" "$work/client" + printf 'unused' > "$work/client/client-secret" +} + +teardown() { + [ -n "${work:-}" ] || return 0 + for f in "$work"/cid-*; do + if [ -e "$f" ]; then docker rm -f "$(cat "$f")" >/dev/null 2>&1 || true; fi + done + if [ -e "$work/network" ]; then docker network rm "$(cat "$work/network")" >/dev/null 2>&1 || true; fi + rm -rf "$work" +} + +# render +render() { + helm template dashboard "$REPO_ROOT/packages/system/dashboard" --namespace cozy-dashboard \ + --set-string "_cluster.root-host=$HOST" \ + --set-string '_cluster.oidc-enabled=true' \ + --set-string "_cluster.oidc-realm-name=$REALM" \ + --set-string "_cluster.keycloak-internal-url=$1" > "$work/rendered.yaml" + yq 'select(.kind == "ConfigMap" and .metadata.name == "incloud-web-gatekeeper-config") | .data["alpha-config.yaml"]' \ + "$work/rendered.yaml" > "$work/config/alpha-config.yaml" + yq 'select(.kind == "Deployment" and .metadata.name == "incloud-web-gatekeeper") | .spec.template.spec.containers[] | select(.name == "auth-proxy") | .image' \ + "$work/rendered.yaml" > "$work/image" + yq 'select(.kind == "Deployment" and .metadata.name == "incloud-web-gatekeeper") | .spec.template.spec.containers[] | select(.name == "auth-proxy") | .args[]' \ + "$work/rendered.yaml" > "$work/args" + [ -s "$work/config/alpha-config.yaml" ] + [ -s "$work/image" ] +} + +# start_proxy [docker run options...]; prints the published host:port +start_proxy() { + local cookie_secret args=() a + cookie_secret=$(head -c 16 /dev/urandom | od -An -tx1 | tr -d ' \n') + while IFS= read -r a; do + args+=("${a/\$(OAUTH2_PROXY_COOKIE_SECRET)/$cookie_secret}") + done < "$work/args" + docker run -d "$@" -p 127.0.0.1::8000 \ + -v "$work/config:/etc/oauth2-proxy/config:ro" \ + -v "$work/client:/etc/oauth2-proxy/client:ro" \ + "$(cat "$work/image")" "${args[@]}" > "$work/cid-proxy" + local addr + addr=$(docker port "$(cat "$work/cid-proxy")" 8000/tcp | head -n1) + timeout 60 sh -c "until curl -sf -o /dev/null http://$addr/ping; do sleep 0.5; done" || { + echo "gatekeeper did not become ready; its log:" >&2 + docker logs "$(cat "$work/cid-proxy")" >&2 || true + return 1 + } + echo "$addr" +} + +# login_redirect +login_redirect() { + curl -sS -o /dev/null -w '%{redirect_url}' "http://$1/oauth2/start?$2" +} + +auth_url="https://keycloak.$HOST/realms/$REALM/protocol/openid-connect/auth" + +# expect_redirect ... ; a leading "!" means must not +# contain. A function, not [[ ]]: a failing [[ ]] mid-test does not stop the +# test under bash 3.2. +expect_redirect() { + local location=$1 want + shift + case "$location" in + "$auth_url?"*) ;; + *) echo "expected a redirect to $auth_url, got: ${location:-}" >&2; return 1 ;; + esac + for want in "$@"; do + case "$want" in + !*) + case "$location" in + *"${want#!}"*) echo "unexpected ${want#!} in: $location" >&2; return 1 ;; + esac + ;; + *) + case "$location" in + *"$want"*) ;; + *) echo "expected $want in: $location" >&2; return 1 ;; + esac + ;; + esac + done +} + +@test "in-cluster Keycloak URL: login redirects to the configured realm and passes an allowed kc_idp_hint" { + render "http://keycloak-http.cozy-keycloak.svc:8080/realms/$REALM" + addr=$(start_proxy --network bridge) + + expect_redirect "$(login_redirect "$addr" 'kc_idp_hint=portal')" '&kc_idp_hint=portal&' + expect_redirect "$(login_redirect "$addr" 'kc_idp_hint=x%26prompt%3Dnone')" '!kc_idp_hint' '!prompt=none' + expect_redirect "$(login_redirect "$addr" '')" '!kc_idp_hint' +} + +@test "OIDC discovery: the gatekeeper discovers the configured realm and passes an allowed kc_idp_hint" { + render "" + issuer="https://keycloak.$HOST/realms/$REALM" + + mkdir -p "$work/stub/realms/$REALM/.well-known" + cat > "$work/stub/realms/$REALM/.well-known/openid-configuration" </dev/null + + network="gatekeeper-login-$(basename "$work" | tr -cd 'a-zA-Z0-9')" + docker network create "$network" >/dev/null + echo "$network" > "$work/network" + docker run -d --network "$network" --network-alias "keycloak.$HOST" \ + -v "$work/stub:/stub:ro" -w /stub "$STUB_IMAGE" python3 -c ' +import http.server, ssl +server = http.server.ThreadingHTTPServer(("", 443), http.server.SimpleHTTPRequestHandler) +ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) +ctx.load_cert_chain("tls.crt", "tls.key") +server.socket = ctx.wrap_socket(server.socket, server_side=True) +server.serve_forever() +' > "$work/cid-stub" + # Discovery runs once at startup and the gatekeeper exits if it fails. + timeout 60 sh -c "until docker exec $(cat "$work/cid-stub") python3 -c 'import socket; socket.create_connection((\"127.0.0.1\", 443), 1)' 2>/dev/null; do sleep 0.5; done" || { + docker logs "$(cat "$work/cid-stub")" >&2 || true + false + } + + addr=$(start_proxy --network "$network" -v "$work/stub/tls.crt:/stub-ca.crt:ro" -e SSL_CERT_FILE=/stub-ca.crt) + + expect_redirect "$(login_redirect "$addr" 'kc_idp_hint=portal')" '&kc_idp_hint=portal&' +} From 7145a67568a44521e6f9410ce497036e5090b469 Mon Sep 17 00:00:00 2001 From: Andrey Kolkov Date: Wed, 18 Nov 2026 14:08:00 +0700 Subject: [PATCH 10/17] fix(backups): stop leaking MariaDB dumps of stuck runs and torn-down namespaces A k8s.mariadb.com/Backup the BackupJob gave up on stayed for good: no Backup is made of such a run, so nothing deleted it, and while it stood short of Complete the dump cleanup counted its open window as a possible writer of every later dump of the application and kept each of them. Every failure exit of a started BackupJob in the MariaDB driver now goes through failMariaDBBackupJob: the deadline, the application, MariaDB CR or strategy going away, a run the operator failed at Complete=False, and a run that could not be created. It lists the job's runs on the API server, where the cache can trail a run created or completed a moment ago, and deletes each one short of Complete under the UID and resourceVersion it read, so a run that completes in between is handed to the success path instead. Deleting the run takes its Job and pod, so what held the pod up is first copied into the failure message. A Running or expired job takes its run from that listing and never starts another, so a retry after a failed status write cannot start a second. During namespace teardown the operator Backup, which carries no finalizer, is usually gone before the Backup finalizer runs, and the cleanup, which read the storage from it, left the dump behind. A Backup that recorded its dump on the platform bucket now has it deleted with the platform credentials, which do not go with the namespace, reading the storage from the snapshot in status.underlyingResources; the dump is still kept when another run could have written it. The snapshot and the storage URI now record the storage the run was created with rather than the strategy as rendered at completion, which a strategy edited during the run would otherwise send the cleanup away from. Closes: #5291 Assisted-by: LLM Signed-off-by: Andrey Kolkov --- .../backupcontroller/backup_controller.go | 5 +- .../backupcontroller/backupjob_controller.go | 10 +- .../mariadbstrategy_cleanup.go | 153 ++++- .../mariadbstrategy_cleanup_test.go | 142 ++++ .../mariadbstrategy_controller.go | 239 ++++++- .../mariadbstrategy_controller_test.go | 650 +++++++++++++++++- .../templates/rbac.yaml | 3 +- 7 files changed, 1148 insertions(+), 54 deletions(-) diff --git a/internal/backupcontroller/backup_controller.go b/internal/backupcontroller/backup_controller.go index bc49baa6b..4f1d24808 100644 --- a/internal/backupcontroller/backup_controller.go +++ b/internal/backupcontroller/backup_controller.go @@ -145,8 +145,9 @@ func (r *BackupReconciler) cleanupOnDelete(ctx context.Context, backup *backupsv // a tenant's own bucket is deleted too: the Backup proves it owns // it, and tenants cannot delete Backups, so the delete comes from an // administrator or from namespace teardown. Teardown can remove the - // operator Backup first, and the dump is then left behind with a - // Warning, since its storage is read from it (see cleanupMariaDBBackup). + // operator Backup first; a recorded dump on the platform bucket is + // then still deleted, and any other is left behind with a Warning + // (see cleanupMariaDBBackup). return r.cleanupMariaDBBackup(ctx, backup) case strategyv1alpha1.MongoDBStrategyKind: // Split by flow (see cleanupMongoDBBackup). A legacy backup writes to the diff --git a/internal/backupcontroller/backupjob_controller.go b/internal/backupcontroller/backupjob_controller.go index 15ef65db4..6d2209de4 100644 --- a/internal/backupcontroller/backupjob_controller.go +++ b/internal/backupcontroller/backupjob_controller.go @@ -385,9 +385,7 @@ func strategyNotReadyDeadlineExceeded(startedAt *metav1.Time) bool { func (r *BackupJobReconciler) requeueStrategyNotReady(ctx context.Context, j *backupsv1alpha1.BackupJob, strategyName string) (ctrl.Result, error) { logger := getLogger(ctx) if strategyNotReadyDeadlineExceeded(j.Status.StartedAt) { - return r.markBackupJobFailed(ctx, j, fmt.Sprintf( - "Strategy %q referenced by BackupClass %q was not provisioned within %s; check the strategyRef name or the platform backup-storage bootstrap", - strategyName, j.Spec.BackupClassName, StrategyNotReadyDeadline)) + return r.markBackupJobFailed(ctx, j, strategyNotProvisionedMessage(j, strategyName)) } meta.SetStatusCondition(&j.Status.Conditions, metav1.Condition{ Type: "Ready", @@ -400,3 +398,9 @@ func (r *BackupJobReconciler) requeueStrategyNotReady(ctx context.Context, j *ba } return ctrl.Result{RequeueAfter: CredentialsProjectionRequeue}, nil } + +func strategyNotProvisionedMessage(j *backupsv1alpha1.BackupJob, strategyName string) string { + return fmt.Sprintf( + "Strategy %q referenced by BackupClass %q was not provisioned within %s; check the strategyRef name or the platform backup-storage bootstrap", + strategyName, j.Spec.BackupClassName, StrategyNotReadyDeadline) +} diff --git a/internal/backupcontroller/mariadbstrategy_cleanup.go b/internal/backupcontroller/mariadbstrategy_cleanup.go index 912bb0038..457b4d7a4 100644 --- a/internal/backupcontroller/mariadbstrategy_cleanup.go +++ b/internal/backupcontroller/mariadbstrategy_cleanup.go @@ -3,6 +3,7 @@ package backupcontroller import ( "context" + "encoding/json" "errors" "fmt" "slices" @@ -44,7 +45,8 @@ var mariadbDumpCleanupTimeout = 10 * time.Second // no dump is proven the Backup is released with a Warning and nothing is // deleted, the operator Backup included, since it is what any later // attribution would start from. A failed delete holds the Backup and -// retries, as the Redis and Rabbitmq cleanups do. +// retries, as the Redis and Rabbitmq cleanups do. When the operator Backup +// is gone, cleanupOrphanedMariaDBDump deletes the dump instead. func (r *BackupReconciler) cleanupMariaDBBackup(ctx context.Context, backup *backupsv1alpha1.Backup) (ctrl.Result, error) { logger := getLogger(ctx) if backup.Annotations[mariadbSkipArtifactCleanupAnnotation] == "true" { @@ -75,7 +77,10 @@ func (r *BackupReconciler) cleanupMariaDBBackup(ctx context.Context, backup *bac op := &mariadbtypes.Backup{} if err := r.Get(ctx, types.NamespacedName{Namespace: backup.Namespace, Name: opName}, op); err != nil { - if apierrors.IsNotFound(err) || apimeta.IsNoMatchError(err) { + if apierrors.IsNotFound(err) { + return r.cleanupOrphanedMariaDBDump(ctx, backup, opName) + } + if apimeta.IsNoMatchError(err) { return r.releaseMariaDBCleanup(ctx, backup, "the dump", fmt.Sprintf("k8s.mariadb.com/Backup %s is gone, so the storage and credentials its dump was written with cannot be read", opName)), nil } @@ -173,6 +178,96 @@ func (r *BackupReconciler) cleanupMariaDBBackup(ctx context.Context, backup *bac return ctrl.Result{}, nil } +// cleanupOrphanedMariaDBDump deletes the recorded dump of a Backup whose +// operator Backup is gone, as it can be by the time a namespace being torn +// down reaches the Backup's finalizer: mariadb-operator puts none on its +// Backup. The storage comes from the snapshot the Backup was made with. +// Only a dump on the platform bucket is deleted, since the platform +// credentials are the only ones that do not go with the namespace, and only +// a recorded one: attributing a dump needs the operator Backup's lifetime. +func (r *BackupReconciler) cleanupOrphanedMariaDBDump(ctx context.Context, backup *backupsv1alpha1.Backup, opName string) (ctrl.Result, error) { + gone := fmt.Sprintf("k8s.mariadb.com/Backup %s is gone", opName) + name := backup.Spec.DriverMetadata[mariadbDumpFileKey] + if name == "" { + return r.releaseMariaDBCleanup(ctx, backup, "the dump", gone+" and the Backup records no dump, so none can be attributed to it"), nil + } + if _, ok := parseMariaDBLogicalBackupFile(name); !ok { + return r.releaseMariaDBCleanup(ctx, backup, "the dump", + fmt.Sprintf("driverMetadata %s=%q is not the name of a mariadb-operator dump", mariadbDumpFileKey, name)), nil + } + storage, err := mariadbSnapshotStorage(backup) + if err != nil { + return r.releaseMariaDBCleanup(ctx, backup, "the dump", fmt.Sprintf("%s and its storage cannot be read from the Backup: %v", gone, err)), nil + } + if storage.S3 == nil { + return r.releaseMariaDBCleanup(ctx, backup, "the dump on a storage volume", "PVC and Volume storage is not reachable from the controller"), nil + } + op := &mariadbtypes.Backup{ + ObjectMeta: metav1.ObjectMeta{Namespace: backup.Namespace, Name: opName}, + Spec: mariadbtypes.BackupSpec{Storage: storage}, + } + location := fmt.Sprintf("s3://%s/%s%s", storage.S3.Bucket, mariadbOperatorS3Prefix(storage.S3.Prefix), name) + + conn, onPlatform, err := r.mariadbPlatformConnection(ctx, op) + if err != nil { + return r.retryMariaDBCleanup(ctx, backup, location, fmt.Errorf("resolve S3 credentials: %w", err)) + } + if !onPlatform { + return r.releaseMariaDBCleanup(ctx, backup, location, + gone+", and the dump is not on the platform bucket or the platform credentials cannot be read, so no credentials to reach it are left"), nil + } + + s3ctx, cancel := context.WithTimeout(ctx, mariadbDumpCleanupTimeout) + defer cancel() + store := r.objectStore() + lister, err := store.lister(conn) + if err != nil { + return r.retryMariaDBCleanup(ctx, backup, location, fmt.Errorf("build S3 client: %w", err)) + } + other, found, err := contestedMariaDBDump(s3ctx, lister, r.apiReader(), op, name) + if err != nil { + return r.retryMariaDBCleanup(ctx, backup, location, err) + } + if other != "" { + return r.releaseMariaDBCleanup(ctx, backup, location, + fmt.Sprintf("the recorded dump also falls in the lifetime of k8s.mariadb.com/Backup %s, which may have written it", other)), nil + } + if !found { + getLogger(ctx).Info("MariaDB dump already absent", "backup", backup.Name, "dump", location, "endpoint", conn.Endpoint, "operatorBackup", opName) + if r.Recorder != nil { + r.Recorder.Eventf(backup, corev1.EventTypeNormal, "ArtifactAlreadyAbsent", + "%s was not found when listed through %s, so it was deleted earlier or never reached that storage", location, conn.Endpoint) + } + return ctrl.Result{}, nil + } + remover, err := store.remover(conn) + if err != nil { + return r.retryMariaDBCleanup(ctx, backup, location, fmt.Errorf("build S3 client: %w", err)) + } + if err := remover.RemoveObject(s3ctx, storage.S3.Bucket, mariadbOperatorS3Prefix(storage.S3.Prefix)+name); err != nil { + return r.retryMariaDBCleanup(ctx, backup, location, err) + } + getLogger(ctx).Info("deleted MariaDB dump of a gone operator Backup", "backup", backup.Name, "dump", location, "operatorBackup", opName) + return ctrl.Result{}, nil +} + +// mariadbSnapshotStorage returns the storage the Backup's operator Backup +// was made with, from the snapshot in status.underlyingResources. +func mariadbSnapshotStorage(backup *backupsv1alpha1.Backup) (mariadbtypes.BackupStorage, error) { + raw := backup.Status.UnderlyingResources + if raw == nil || len(raw.Raw) == 0 { + return mariadbtypes.BackupStorage{}, errors.New("status.underlyingResources is empty") + } + var snap mariadbBackupSnapshot + if err := json.Unmarshal(raw.Raw, &snap); err != nil { + return mariadbtypes.BackupStorage{}, fmt.Errorf("decode status.underlyingResources: %w", err) + } + if snap.Kind != mariadbBackupSnapshotKind || snap.Storage == nil { + return mariadbtypes.BackupStorage{}, fmt.Errorf("status.underlyingResources is not a %s with storage", mariadbBackupSnapshotKind) + } + return buildMariaDBBackupStorage(*snap.Storage) +} + // contestedMariaDBDump returns the name of another operator Backup on op's // bucket and prefix whose run, finished or not, could have written the dump // name, or "" when none could, and whether the listing found the dump. The @@ -261,30 +356,44 @@ func (r *BackupReconciler) activeRestoreOf(ctx context.Context, backup *backupsv // recorded endpoint may be the one the platform moved off, where the dump // would be found missing and reported deleted. func (r *BackupReconciler) mariadbCleanupConnection(ctx context.Context, op *mariadbtypes.Backup) (s3Connection, error) { - if r.CredentialsConfig.IsEnabled() { - conn, bucket, err := r.platformS3Connection(ctx) - var projErr *ProjectionError - switch { - case errors.As(err, &projErr) && projErr.Reason == ReasonAPIError: - return s3Connection{}, err - case err != nil: - getLogger(ctx).Info("cannot read the platform backup credentials; using the operator Backup's own", "operatorBackup", op.Name, "error", err) - case bucket == op.Spec.Storage.S3.Bucket && op.Spec.Storage.S3.AccessKeyIdSecretKeyRef.Name == r.CredentialsConfig.TargetSecretName: - // A strategy can pin a private CA for the platform bucket; the - // platform credentials carry none. - if tls := op.Spec.Storage.S3.TLS; conn.Secure && tls != nil && tls.CASecretKeyRef != nil { - ca, err := r.objectStore().secretValue(ctx, op.Namespace, tls.CASecretKeyRef.Name, tls.CASecretKeyRef.Key) - if err != nil { - return s3Connection{}, err - } - conn.CAPEM = []byte(ca) - } - return conn, nil - } + conn, onPlatform, err := r.mariadbPlatformConnection(ctx, op) + if err != nil || onPlatform { + return conn, err } return mariadbS3Connection(ctx, r.objectStore(), op.Namespace, op.Spec.Storage.S3) } +// mariadbPlatformConnection returns the platform's connection to the bucket +// op wrote to, and false when op did not write to the platform bucket or the +// platform credentials are missing or malformed. Only a failed read of the +// platform credentials is an error. +func (r *BackupReconciler) mariadbPlatformConnection(ctx context.Context, op *mariadbtypes.Backup) (s3Connection, bool, error) { + if !r.CredentialsConfig.IsEnabled() { + return s3Connection{}, false, nil + } + conn, bucket, err := r.platformS3Connection(ctx) + var projErr *ProjectionError + switch { + case errors.As(err, &projErr) && projErr.Reason == ReasonAPIError: + return s3Connection{}, false, err + case err != nil: + getLogger(ctx).Info("cannot read the platform backup credentials; using the operator Backup's own", "operatorBackup", op.Name, "error", err) + return s3Connection{}, false, nil + case bucket != op.Spec.Storage.S3.Bucket || op.Spec.Storage.S3.AccessKeyIdSecretKeyRef.Name != r.CredentialsConfig.TargetSecretName: + return s3Connection{}, false, nil + } + // A strategy can pin a private CA for the platform bucket; the platform + // credentials carry none. + if tls := op.Spec.Storage.S3.TLS; conn.Secure && tls != nil && tls.CASecretKeyRef != nil { + ca, err := r.objectStore().secretValue(ctx, op.Namespace, tls.CASecretKeyRef.Name, tls.CASecretKeyRef.Key) + if err != nil { + return s3Connection{}, false, err + } + conn.CAPEM = []byte(ca) + } + return conn, true, nil +} + // platformS3Connection reads the platform's backup bucket from the Secret // cozy-backups-creds is projected from, and its TLS from the scheme of // BACKUP_STORAGE_ENDPOINT, which is how the default strategy sets diff --git a/internal/backupcontroller/mariadbstrategy_cleanup_test.go b/internal/backupcontroller/mariadbstrategy_cleanup_test.go index 7efb3046f..477fa4953 100644 --- a/internal/backupcontroller/mariadbstrategy_cleanup_test.go +++ b/internal/backupcontroller/mariadbstrategy_cleanup_test.go @@ -15,6 +15,7 @@ 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/runtime" "k8s.io/client-go/tools/record" ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/client" @@ -1377,3 +1378,144 @@ func (f *fakeS3Bucket) StatObject(_ context.Context, _, key string) (int64, erro } return 0, errors.New("not found") } + +// orphanedCleanupBackup is cleanupBackup made of a run that stored to s3, +// as status.underlyingResources records it. +func orphanedCleanupBackup(t *testing.T, s3 *strategyv1alpha1.MariaDBS3Template, dumpFile string) *backupsv1alpha1.Backup { + t.Helper() + rendered := newRenderedMariaDBTemplate() + rendered.Storage.S3 = s3 + snap, err := marshalMariaDBBackupSnapshot(rendered, nil) + if err != nil { + t.Fatal(err) + } + backup := cleanupBackup(dumpFile) + backup.Status.UnderlyingResources = snap + return backup +} + +func cleanupStorage() *strategyv1alpha1.MariaDBS3Template { + s3 := newRenderedMariaDBTemplate().Storage.S3 + s3.Prefix = "tenant/db" + return s3 +} + +func cleanupDumpListing() *fakeS3Bucket { + return &fakeS3Bucket{objects: []s3ObjectInfo{{Key: cleanupPrefix + cleanupDumpName, LastModified: cleanupCreated.Add(2 * time.Minute)}}} +} + +// Namespace teardown deletes the operator Backup, which carries no +// finalizer, before the Backup's finalizer runs; the tenant's own Secrets +// go with it, so only the platform credentials reach the dump. +func TestCleanupMariaDBBackup_GoneOperatorBackupDeletesTheRecordedDumpOnThePlatformBucket(t *testing.T) { + bucket := cleanupDumpListing() + r, rec := cleanupReconciler(t, bucket, tenantNamespace(), platformCredsSecret("bkt", "s3.new.example")) + r.CredentialsConfig = platformCredsConfig("https://s3.new.example") + + res, err := r.cleanupMariaDBBackup(context.Background(), orphanedCleanupBackup(t, cleanupStorage(), cleanupDumpName)) + if err != nil || requeues(res) { + t.Fatalf("got res=%+v err=%v, want the Backup released", res, err) + } + if want := "bkt/" + cleanupPrefix + cleanupDumpName; len(bucket.removed) != 1 || bucket.removed[0] != want { + t.Errorf("removed %v, want [%s]", bucket.removed, want) + } + for _, conn := range bucket.conns { + if conn.Endpoint != "s3.new.example" || conn.AccessKey != "PLATFORM" { + t.Errorf("connection = %+v, want the platform's endpoint and keys", conn) + } + } + if events := drainEvents(rec); hasEvent(events, "Warning ArtifactNotDeleted") { + t.Errorf("events = %v, want no ArtifactNotDeleted", events) + } +} + +func TestCleanupMariaDBBackup_GoneOperatorBackupWithTheDumpAlreadyGone(t *testing.T) { + bucket := &fakeS3Bucket{} + r, rec := cleanupReconciler(t, bucket, tenantNamespace(), platformCredsSecret("bkt", "s3.new.example")) + r.CredentialsConfig = platformCredsConfig("https://s3.new.example") + + res, err := r.cleanupMariaDBBackup(context.Background(), orphanedCleanupBackup(t, cleanupStorage(), cleanupDumpName)) + if err != nil || requeues(res) || len(bucket.removed) != 0 { + t.Fatalf("got res=%+v err=%v removed=%v, want released with nothing deleted", res, err, bucket.removed) + } + if events := drainEvents(rec); !hasEvent(events, "Normal ArtifactAlreadyAbsent") { + t.Errorf("events = %v, want a Normal ArtifactAlreadyAbsent", events) + } +} + +func TestCleanupMariaDBBackup_GoneOperatorBackupWithAContestedDumpIsReleased(t *testing.T) { + bucket := cleanupDumpListing() + running := cleanupOperatorBackup(t) + running.Name = "op-running" + running.Status.Conditions = nil + r, rec := cleanupReconciler(t, bucket, running, tenantNamespace(), platformCredsSecret("bkt", "s3.new.example")) + r.CredentialsConfig = platformCredsConfig("https://s3.new.example") + + res, err := r.cleanupMariaDBBackup(context.Background(), orphanedCleanupBackup(t, cleanupStorage(), cleanupDumpName)) + if err != nil || requeues(res) || len(bucket.removed) != 0 { + t.Fatalf("got res=%+v err=%v removed=%v, want released with nothing deleted", res, err, bucket.removed) + } + if events := drainEvents(rec); !hasEvent(events, "Warning ArtifactNotDeleted") { + t.Errorf("events = %v, want a Warning ArtifactNotDeleted", events) + } +} + +func TestCleanupMariaDBBackup_GoneOperatorBackupFailedDeleteRetries(t *testing.T) { + bucket := cleanupDumpListing() + bucket.removeErr = errors.New("connection refused") + r, rec := cleanupReconciler(t, bucket, tenantNamespace(), platformCredsSecret("bkt", "s3.new.example")) + r.CredentialsConfig = platformCredsConfig("https://s3.new.example") + + res, err := r.cleanupMariaDBBackup(context.Background(), orphanedCleanupBackup(t, cleanupStorage(), cleanupDumpName)) + if err != nil || !requeues(res) { + t.Fatalf("got res=%+v err=%v, want the Backup held for a retry", res, err) + } + if events := drainEvents(rec); !hasEvent(events, "Warning ArtifactCleanupFailed") { + t.Errorf("events = %v, want a Warning ArtifactCleanupFailed", events) + } +} + +func TestCleanupMariaDBBackup_GoneOperatorBackupReleasesWhatItCannotReach(t *testing.T) { + ownCreds := cleanupStorage() + ownCreds.AccessKeyIDSecretKeyRef.Name = "own-creds" + otherBucket := cleanupStorage() + otherBucket.Bucket = "tenant-own-bucket" + onVolume := cleanupBackup(cleanupDumpName) + onVolume.Status.UnderlyingResources = &runtime.RawExtension{Raw: []byte( + `{"kind":"` + mariadbBackupSnapshotKind + `","storage":{"persistentVolumeClaim":{"accessModes":["ReadWriteOnce"]}}}`)} + foreignKind := orphanedCleanupBackup(t, cleanupStorage(), cleanupDumpName) + foreignKind.Status.UnderlyingResources.Raw = []byte(strings.Replace(string(foreignKind.Status.UnderlyingResources.Raw), + mariadbBackupSnapshotKind, "SomethingElse", 1)) + cases := map[string]struct { + backup *backupsv1alpha1.Backup + platform bool + }{ + "no dump recorded": {backup: orphanedCleanupBackup(t, cleanupStorage(), ""), platform: true}, + "no storage snapshot": {backup: cleanupBackup(cleanupDumpName), platform: true}, + "another bucket": {backup: orphanedCleanupBackup(t, otherBucket, cleanupDumpName), platform: true}, + "the tenant's own Secret": {backup: orphanedCleanupBackup(t, ownCreds, cleanupDumpName), platform: true}, + "platform credentials gone": {backup: orphanedCleanupBackup(t, cleanupStorage(), cleanupDumpName)}, + "dump on a volume": {backup: onVolume, platform: true}, + "recorded name not a dump": {backup: orphanedCleanupBackup(t, cleanupStorage(), "backup.tar"), platform: true}, + "snapshot of another kind": {backup: foreignKind, platform: true}, + } + for name, tc := range cases { + t.Run(name, func(t *testing.T) { + bucket := cleanupDumpListing() + objs := []client.Object{tenantNamespace(), s3CredsSecret("tenant", "creds")} + if tc.platform { + objs = append(objs, platformCredsSecret("bkt", "s3.new.example")) + } + r, rec := cleanupReconciler(t, bucket, objs...) + r.CredentialsConfig = platformCredsConfig("https://s3.new.example") + + res, err := r.cleanupMariaDBBackup(context.Background(), tc.backup) + if err != nil || requeues(res) || len(bucket.removed) != 0 { + t.Fatalf("got res=%+v err=%v removed=%v, want released with nothing deleted", res, err, bucket.removed) + } + if events := drainEvents(rec); !hasEvent(events, "Warning ArtifactNotDeleted") { + t.Errorf("events = %v, want a Warning ArtifactNotDeleted", events) + } + }) + } +} diff --git a/internal/backupcontroller/mariadbstrategy_controller.go b/internal/backupcontroller/mariadbstrategy_controller.go index a8fd29a01..845a78e57 100644 --- a/internal/backupcontroller/mariadbstrategy_controller.go +++ b/internal/backupcontroller/mariadbstrategy_controller.go @@ -6,6 +6,7 @@ import ( "encoding/json" "errors" "fmt" + "strings" "time" batchv1 "k8s.io/api/batch/v1" @@ -134,7 +135,7 @@ func (r *BackupJobReconciler) reconcileMariaDB(ctx context.Context, j *backupsv1 } if err := validateMariaDBApplicationRef(j.Spec.ApplicationRef); err != nil { - return r.markBackupJobFailed(ctx, j, err.Error()) + return r.failMariaDBBackupJob(ctx, j, err.Error()) } if j.Status.StartedAt == nil { @@ -162,6 +163,9 @@ func (r *BackupJobReconciler) reconcileMariaDB(ctx context.Context, j *backupsv1 strategy := &strategyv1alpha1.MariaDB{} if err := r.Get(ctx, client.ObjectKey{Name: resolved.StrategyRef.Name}, strategy); err != nil { if apierrors.IsNotFound(err) { + if strategyNotReadyDeadlineExceeded(j.Status.StartedAt) { + return r.failMariaDBBackupJob(ctx, j, strategyNotProvisionedMessage(j, resolved.StrategyRef.Name)) + } return r.requeueStrategyNotReady(ctx, j, resolved.StrategyRef.Name) } return ctrl.Result{}, err @@ -170,14 +174,14 @@ func (r *BackupJobReconciler) reconcileMariaDB(ctx context.Context, j *backupsv1 app, err := r.getMariaDBApp(ctx, j.Namespace, j.Spec.ApplicationRef.Name) if err != nil { if apierrors.IsNotFound(err) { - return r.markBackupJobFailed(ctx, j, fmt.Sprintf("MariaDB application not found: %s/%s", j.Namespace, j.Spec.ApplicationRef.Name)) + return r.failMariaDBBackupJob(ctx, j, fmt.Sprintf("MariaDB application not found: %s/%s", j.Namespace, j.Spec.ApplicationRef.Name)) } return ctrl.Result{}, err } rendered, err := renderMariaDBTemplate(strategy.Spec.Template, app, resolved.Parameters) if err != nil { - return r.markBackupJobFailed(ctx, j, fmt.Sprintf("failed to template MariaDB strategy: %v", err)) + return r.failMariaDBBackupJob(ctx, j, fmt.Sprintf("failed to template MariaDB strategy: %v", err)) } // Operator-side MariaDB CR carries the prefixed release name (see @@ -192,7 +196,7 @@ func (r *BackupJobReconciler) reconcileMariaDB(ctx context.Context, j *backupsv1 &mariadbtypes.MariaDB{}); err != nil { if apierrors.IsNotFound(err) { if mariadbBackupDeadlineExceeded(j.Status.StartedAt) { - return r.markBackupJobFailed(ctx, j, fmt.Sprintf( + return r.failMariaDBBackupJob(ctx, j, fmt.Sprintf( "k8s.mariadb.com/MariaDB %s/%s never reached existence within %s", j.Namespace, mdbName, mariadbDefaultBackupDeadline)) } @@ -210,9 +214,30 @@ func (r *BackupJobReconciler) reconcileMariaDB(ctx context.Context, j *backupsv1 return ctrl.Result{}, err } - mdbBackup, err := r.ensureMariaDBBackup(ctx, j, rendered) - if err != nil { - return r.markBackupJobFailed(ctx, j, fmt.Sprintf("failed to ensure k8s.mariadb.com/Backup: %v", err)) + // A job that is Running has created its run, and one past the deadline + // is only waited for: either way the run is read past the cache and never + // started again. A pass whose status write failed after + // failMariaDBBackupJob deleted the run would otherwise start another, and + // the cache can miss a run created a moment ago. + var mdbBackup *mariadbtypes.Backup + if pastDeadline := mariadbBackupDeadlineExceeded(j.Status.StartedAt); pastDeadline || j.Status.Phase == backupsv1alpha1.BackupJobPhaseRunning { + runs, err := r.mariadbRunsOf(ctx, j) + if err != nil { + return ctrl.Result{}, err + } + if len(runs) == 0 { + if pastDeadline { + return r.markBackupJobFailed(ctx, j, fmt.Sprintf( + "k8s.mariadb.com Backup did not complete within %s; no k8s.mariadb.com/Backup of this BackupJob is left", mariadbDefaultBackupDeadline)) + } + return r.markBackupJobFailed(ctx, j, "the k8s.mariadb.com/Backup of this BackupJob is gone") + } + mdbBackup = &runs[0] + } else { + mdbBackup, err = r.ensureMariaDBBackup(ctx, j, rendered) + if err != nil { + return r.failMariaDBBackupJob(ctx, j, fmt.Sprintf("failed to ensure k8s.mariadb.com/Backup: %v", err)) + } } if j.Status.Phase != backupsv1alpha1.BackupJobPhaseRunning { @@ -226,7 +251,10 @@ func (r *BackupJobReconciler) reconcileMariaDB(ctx context.Context, j *backupsv1 switch { case cond != nil && cond.Reason == mariadbtypes.ConditionReasonJobFailed: - return r.markBackupJobFailed(ctx, j, mariadbJobFailedMessage(ctx, r.Client, "Backup", mdbBackup.Namespace, mdbBackup.Name, cond)) + // A run at Complete=False/JobFailed counts as unfinished to the dump + // cleanup and is deleted; one at Complete=True/JobFailed has a + // bounded window and is kept. + return r.failMariaDBBackupJob(ctx, j, mariadbJobFailedMessage(ctx, r.Client, "Backup", mdbBackup.Namespace, mdbBackup.Name, cond)) case cond != nil && cond.Status == metav1.ConditionTrue && cond.Reason == mariadbtypes.ConditionReasonJobComplete: // Backup completed successfully. Materialise the Cozystack artifact @@ -236,7 +264,7 @@ func (r *BackupJobReconciler) reconcileMariaDB(ctx context.Context, j *backupsv1 if j.Status.BackupRef != nil { return ctrl.Result{}, nil } - artifact, err := r.createMariaDBBackupArtifact(ctx, j, resolved, mdbBackup, rendered) + artifact, err := r.createMariaDBBackupArtifact(ctx, j, resolved, mdbBackup, mariadbRunTemplate(rendered, mdbBackup)) if err != nil { return r.failBackupArtifact(ctx, j, err) } @@ -262,13 +290,137 @@ func (r *BackupJobReconciler) reconcileMariaDB(ctx context.Context, j *backupsv1 // Backup eventually fails the BackupJob instead of pinning it Running // forever. if mariadbBackupDeadlineExceeded(j.Status.StartedAt) { - return r.markBackupJobFailed(ctx, j, fmt.Sprintf( - "k8s.mariadb.com Backup did not complete within %s (%s)", mariadbDefaultBackupDeadline, mariadbCompleteDetail(cond))) + return r.giveUpOnMariaDBBackup(ctx, j, mdbBackup) } return ctrl.Result{RequeueAfter: mariadbPollInterval}, nil } } +// giveUpOnMariaDBBackup fails a BackupJob past its deadline through +// failMariaDBBackupJob, unless its run has completed or failed by now. +func (r *BackupJobReconciler) giveUpOnMariaDBBackup(ctx context.Context, j *backupsv1alpha1.BackupJob, op *mariadbtypes.Backup) (ctrl.Result, error) { + // Read past the cache, which can trail a Complete the operator has just + // written, or still hold a Backup an earlier pass deleted before its + // status write failed. + fresh := &mariadbtypes.Backup{} + var cond *metav1.Condition + if err := r.apiReader().Get(ctx, client.ObjectKeyFromObject(op), fresh); err != nil { + if !apierrors.IsNotFound(err) { + return ctrl.Result{}, err + } + } else { + cond = apimeta.FindStatusCondition(fresh.Status.Conditions, mariadbtypes.ConditionTypeComplete) + if cond != nil && (cond.Reason == mariadbtypes.ConditionReasonJobFailed || + cond.Status == metav1.ConditionTrue && cond.Reason == mariadbtypes.ConditionReasonJobComplete) { + return ctrl.Result{RequeueAfter: mariadbPollInterval}, nil + } + } + return r.failMariaDBBackupJob(ctx, j, fmt.Sprintf( + "k8s.mariadb.com Backup did not complete within %s (%s)", mariadbDefaultBackupDeadline, mariadbCompleteDetail(cond))) +} + +// mariadbRunsOf lists the operator Backups of a BackupJob past the cache, +// which can miss one created a moment ago. +func (r *BackupJobReconciler) mariadbRunsOf(ctx context.Context, j *backupsv1alpha1.BackupJob) ([]mariadbtypes.Backup, error) { + runs := &mariadbtypes.BackupList{} + if err := r.apiReader().List(ctx, runs, client.InNamespace(j.Namespace), client.MatchingLabels{ + backupsv1alpha1.OwningJobNameLabel: j.Name, + backupsv1alpha1.OwningJobNamespaceLabel: j.Namespace, + }); err != nil { + // Without the operator's CRDs there is no run to delete, and a job + // failing for that reason must still be failed. + if apimeta.IsNoMatchError(err) { + return nil, nil + } + return nil, fmt.Errorf("list k8s.mariadb.com/Backups of BackupJob %s: %w", j.Name, err) + } + return runs.Items, nil +} + +// failMariaDBBackupJob fails a BackupJob that has started, after deleting +// each of its operator Backups that has not completed. No Backup is made of +// such a run, so nothing else would ever delete it, and while it stands +// short of Complete its window has no end: the dump cleanup would count it +// as a possible writer of every later dump of the application +// (neighbourMariaDBRuns). Deleting it also deletes its Job and so stops a +// run still going; a dump that run has already uploaded is left untracked. +// One that has completed, on any reason, has a bounded window and is kept. +func (r *BackupJobReconciler) failMariaDBBackupJob(ctx context.Context, j *backupsv1alpha1.BackupJob, message string) (ctrl.Result, error) { + runs, err := r.mariadbRunsOf(ctx, j) + if err != nil { + return ctrl.Result{}, err + } + var deleted []string + for i := range runs { + run := &runs[i] + if apimeta.IsStatusConditionTrue(run.Status.Conditions, mariadbtypes.ConditionTypeComplete) { + continue + } + // Read before the delete, which takes the run's Job and pods with it. + stuck := r.mariadbRunStuckReason(ctx, run) + // The preconditions keep a run that completes after the listing from + // being deleted: the delete then conflicts and the next pass sees it. + policy := metav1.DeletePropagationBackground + err := r.Delete(ctx, run, &client.DeleteOptions{ + PropagationPolicy: &policy, + Preconditions: &metav1.Preconditions{UID: &run.UID, ResourceVersion: &run.ResourceVersion}, + }) + if apierrors.IsConflict(err) { + return ctrl.Result{RequeueAfter: mariadbPollInterval}, nil + } + if err != nil && !apierrors.IsNotFound(err) { + err = fmt.Errorf("delete k8s.mariadb.com/Backup %s/%s: %w", run.Namespace, run.Name, err) + apimeta.SetStatusCondition(&j.Status.Conditions, metav1.Condition{ + Type: "Ready", + Status: metav1.ConditionFalse, + Reason: "OperatorBackupDeleteFailed", + Message: fmt.Sprintf("%s; retrying: %v", message, err), + }) + if updateErr := r.Status().Update(ctx, j); updateErr != nil { + getLogger(ctx).Info("cannot record the failed operator Backup delete", "backupjob", j.Name, "error", updateErr) + } + return ctrl.Result{}, err + } + getLogger(ctx).Info("deleted the unfinished operator Backup of a failed BackupJob", "operatorBackup", run.Name, "namespace", run.Namespace) + deleted = append(deleted, run.Namespace+"/"+run.Name) + if stuck != "" { + message += "; " + stuck + } + } + if len(deleted) > 0 { + message += fmt.Sprintf("; k8s.mariadb.com/Backup %s is deleted", strings.Join(deleted, ", ")) + } + return r.markBackupJobFailed(ctx, j, message) +} + +// mariadbRunStuckReason names what held up a run's pod, or "" when it +// cannot tell. The operator names the Job after the run, and the Job +// controller labels its pods with job-name. +func (r *BackupJobReconciler) mariadbRunStuckReason(ctx context.Context, run *mariadbtypes.Backup) string { + pods := &corev1.PodList{} + if err := r.List(ctx, pods, client.InNamespace(run.Namespace), client.MatchingLabels{"job-name": run.Name}); err != nil { + getLogger(ctx).Info("cannot read the pods of an operator Backup", "operatorBackup", run.Name, "error", err) + return "" + } + for i := range pods.Items { + pod := &pods.Items[i] + for _, c := range pod.Status.Conditions { + if c.Type == corev1.PodScheduled && c.Status == corev1.ConditionFalse { + return fmt.Sprintf("pod %s not scheduled: %s: %s", pod.Name, c.Reason, c.Message) + } + } + for _, cs := range append(append([]corev1.ContainerStatus(nil), pod.Status.InitContainerStatuses...), pod.Status.ContainerStatuses...) { + if w := cs.State.Waiting; w != nil && w.Reason != "" && w.Reason != "PodInitializing" { + return fmt.Sprintf("pod %s container %s waiting: %s: %s", pod.Name, cs.Name, w.Reason, w.Message) + } + if t := cs.State.Terminated; t != nil && t.ExitCode != 0 { + return fmt.Sprintf("pod %s container %s terminated: %s: %s", pod.Name, cs.Name, t.Reason, t.Message) + } + } + } + return "" +} + // mariadbJobFailedMessage names the operator object whose Job failed and // carries that Job's own Failed condition, because the operator's condition // message is only "Failed". The operator names the Job after the object. @@ -364,16 +516,15 @@ func (r *BackupJobReconciler) ensureMariaDBBackup(ctx context.Context, j *backup // the BackupJob's OwningJob{Name,Namespace}, if any. Returns (nil, nil) // when no match is found. // -// In steady state at most one Backup CR carries a given OwningJob label -// pair (ensureMariaDBBackup is idempotent by this label). The list path -// can in theory observe two if two controller replicas raced Create -// between the first list returning empty and the cache catching up. The -// driver picks list.Items[0] deterministically; the V(1) breadcrumb on -// duplicates exists so an operator triaging "wrong Backup got reused" -// has a log line to grep for instead of staring at silent reuse. +// The listing reads past the cache: a pass whose status write failed right +// after it created the run would otherwise miss that run and create a +// second. Two controller replicas racing Create can still make two; the +// driver picks list.Items[0] deterministically, and the V(1) breadcrumb on +// duplicates exists so an operator triaging "wrong Backup got reused" has a +// log line to grep for instead of staring at silent reuse. func (r *BackupJobReconciler) findMariaDBBackupForJob(ctx context.Context, j *backupsv1alpha1.BackupJob) (*mariadbtypes.Backup, error) { list := &mariadbtypes.BackupList{} - if err := r.List(ctx, list, + if err := r.apiReader().List(ctx, list, client.InNamespace(j.Namespace), client.MatchingLabels{ backupsv1alpha1.OwningJobNameLabel: j.Name, @@ -396,6 +547,49 @@ func (r *BackupJobReconciler) findMariaDBBackupForJob(ctx context.Context, j *ba return &list.Items[0], nil } +// mariadbRunTemplate returns rendered with the storage run was created +// with: the strategy is rendered again on every pass, and one edited during +// the run would otherwise record storage the dump never went to. +func mariadbRunTemplate(rendered *strategyv1alpha1.MariaDBTemplate, run *mariadbtypes.Backup) *strategyv1alpha1.MariaDBTemplate { + storage := run.Spec.Storage + if storage.S3 == nil && storage.PersistentVolumeClaim == nil && storage.Volume == nil { + return rendered + } + out := rendered.DeepCopy() + out.Storage = strategyv1alpha1.MariaDBStorageTemplate{ + PersistentVolumeClaim: storage.PersistentVolumeClaim.DeepCopy(), + Volume: storage.Volume.DeepCopy(), + } + s3 := storage.S3 + if s3 == nil { + return out + } + out.Storage.S3 = &strategyv1alpha1.MariaDBS3Template{ + Bucket: s3.Bucket, + Endpoint: s3.Endpoint, + Prefix: s3.Prefix, + Region: s3.Region, + AccessKeyIDSecretKeyRef: strategyv1alpha1.MariaDBSecretKeySelector{ + Name: s3.AccessKeyIdSecretKeyRef.Name, + Key: s3.AccessKeyIdSecretKeyRef.Key, + }, + SecretAccessKeySecretKeyRef: strategyv1alpha1.MariaDBSecretKeySelector{ + Name: s3.SecretAccessKeySecretKeyRef.Name, + Key: s3.SecretAccessKeySecretKeyRef.Key, + }, + } + if ref := s3.SessionTokenSecretKeyRef; ref != nil { + out.Storage.S3.SessionTokenSecretKeyRef = &strategyv1alpha1.MariaDBSecretKeySelector{Name: ref.Name, Key: ref.Key} + } + if tls := s3.TLS; tls != nil { + out.Storage.S3.TLS = &strategyv1alpha1.MariaDBS3TLS{Enabled: tls.Enabled} + if ref := tls.CASecretKeyRef; ref != nil { + out.Storage.S3.TLS.CASecretKeyRef = &strategyv1alpha1.MariaDBSecretKeySelector{Name: ref.Name, Key: ref.Key} + } + } + return out +} + // createMariaDBBackupArtifact materialises a Cozystack Backup resource // carrying the metadata callers need to drive a future restore. The // rendered storage descriptor plus the BackupClass parameters are persisted @@ -862,10 +1056,9 @@ func (r *RestoreJobReconciler) resolveMariaDBRestoreTarget(restoreJob *backupsv1 // Backup.status.underlyingResources at backup time. Carries the rendered // storage descriptor and BackupClass parameters. The current restore path // resolves the operator-side k8s.mariadb.com/Backup CR directly and fails -// terminally when it has been reaped; this snapshot is reserved for a -// future fallback path that would re-materialise the operator Backup from -// the persisted state. Keep the shape stable so an older snapshot stays -// machine-readable when that fallback lands. +// terminally when it has been reaped; the dump cleanup reads the storage +// from here once that CR is gone (cleanupOrphanedMariaDBDump). Keep the +// shape stable so an older snapshot stays machine-readable. // // SECRET-HANDLING CONTRACT (this is plaintext-readable to anyone with read // access to backups.cozystack.io/Backups): diff --git a/internal/backupcontroller/mariadbstrategy_controller_test.go b/internal/backupcontroller/mariadbstrategy_controller_test.go index 9696d1eac..7ba9b2c5e 100644 --- a/internal/backupcontroller/mariadbstrategy_controller_test.go +++ b/internal/backupcontroller/mariadbstrategy_controller_test.go @@ -18,6 +18,7 @@ import ( "k8s.io/apimachinery/pkg/runtime" "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" clientfake "sigs.k8s.io/controller-runtime/pkg/client/fake" "sigs.k8s.io/controller-runtime/pkg/client/interceptor" @@ -888,11 +889,13 @@ var mariadbCompleteOutcomeCases = []struct { wantFailed bool wantDone bool wantMessage []string + // The operator Backup of a run given up on before it completed goes. + wantOpDeleted bool }{ {name: "Complete=True/JobComplete succeeds", status: metav1.ConditionTrue, reason: mariadbtypes.ConditionReasonJobComplete, message: "Success", wantDone: true}, {name: "Complete=True/JobFailed fails with the Job's failure", status: metav1.ConditionTrue, reason: mariadbtypes.ConditionReasonJobFailed, message: "Failed", failedJob: true, wantFailed: true, wantMessage: []string{"tenant/op", "BackoffLimitExceeded", "Job has reached the specified backoff limit"}}, - {name: "Complete=False/JobFailed fails with the Job's failure", status: metav1.ConditionFalse, reason: mariadbtypes.ConditionReasonJobFailed, message: "Failed", failedJob: true, wantFailed: true, + {name: "Complete=False/JobFailed fails with the Job's failure", status: metav1.ConditionFalse, reason: mariadbtypes.ConditionReasonJobFailed, message: "Failed", failedJob: true, wantFailed: true, wantOpDeleted: true, wantMessage: []string{"tenant/op", "BackoffLimitExceeded", "Job has reached the specified backoff limit"}}, {name: "Complete=True/JobFailed with its Job gone fails", status: metav1.ConditionTrue, reason: mariadbtypes.ConditionReasonJobFailed, message: "Failed", wantFailed: true, wantMessage: []string{"tenant/op", "Job tenant/op not found"}}, @@ -901,12 +904,14 @@ var mariadbCompleteOutcomeCases = []struct { {name: "Complete=False/JobRunning keeps waiting", status: metav1.ConditionFalse, reason: mariadbtypes.ConditionReasonJobRunning, message: "Running"}, {name: "Complete=False/Failed keeps waiting", status: metav1.ConditionFalse, reason: "Failed", message: "Error creating Job"}, {name: "no Complete condition keeps waiting", noCondition: true}, - {name: "no Complete condition past the deadline fails", noCondition: true, expired: true, wantFailed: true, + {name: "no Complete condition past the deadline fails", noCondition: true, expired: true, wantFailed: true, wantOpDeleted: true, wantMessage: []string{"no Complete condition observed"}}, {name: "Complete=True with an unknown reason past the deadline fails", status: metav1.ConditionTrue, reason: "SomethingElse", message: "Something", expired: true, wantFailed: true, wantMessage: []string{"Complete=True/SomethingElse"}}, - {name: "Complete=False/Failed past the deadline carries the operator's message", status: metav1.ConditionFalse, reason: "Failed", message: "Error creating Job", expired: true, wantFailed: true, + {name: "Complete=False/Failed past the deadline carries the operator's message", status: metav1.ConditionFalse, reason: "Failed", message: "Error creating Job", expired: true, wantFailed: true, wantOpDeleted: true, wantMessage: []string{"Complete=False/Failed: Error creating Job"}}, + {name: "Complete=False/JobRunning past the deadline fails", status: metav1.ConditionFalse, reason: mariadbtypes.ConditionReasonJobRunning, message: "Running", expired: true, wantFailed: true, wantOpDeleted: true, + wantMessage: []string{"Complete=False/JobRunning"}}, } func mariadbCompleteConditions(noCondition bool, status metav1.ConditionStatus, reason, message string) []metav1.Condition { @@ -1016,6 +1021,16 @@ func TestReconcileMariaDBBackup_CompleteConditionOutcome(t *testing.T) { if err := c.List(context.Background(), artifacts, client.InNamespace("tenant")); err != nil { t.Fatalf("list Backups: %v", err) } + err = c.Get(context.Background(), client.ObjectKeyFromObject(operatorBackup), &mariadbtypes.Backup{}) + if err != nil && !apierrors.IsNotFound(err) { + t.Fatalf("get operator Backup: %v", err) + } + if deleted := apierrors.IsNotFound(err); deleted != tc.wantOpDeleted { + t.Errorf("operator Backup deleted = %v, want %v", deleted, tc.wantOpDeleted) + } + if tc.wantOpDeleted { + assertMariaDBFailureMessage(t, stored.Status.Message, []string{"k8s.mariadb.com/Backup tenant/op is deleted"}) + } switch { case tc.wantFailed: if stored.Status.Phase != backupsv1alpha1.BackupJobPhaseFailed { @@ -1243,3 +1258,632 @@ func newRenderedMariaDBTemplate() *strategyv1alpha1.MariaDBTemplate { Compression: "gzip", } } + +// pastDeadlineFixture is a Running BackupJob past its deadline whose +// operator Backup "op" carries the given Complete conditions. +func pastDeadlineFixture(conditions []metav1.Condition) (*backupsv1alpha1.BackupJob, *mariadbtypes.Backup, []client.Object, *ResolvedBackupConfig) { + group := strategyv1alpha1.GroupVersion.Group + resolved := &ResolvedBackupConfig{StrategyRef: corev1.TypedLocalObjectReference{ + APIGroup: &group, Kind: strategyv1alpha1.MariaDBStrategyKind, Name: "mdb-strategy", + }} + seed := newMariaDBBackupJob("bj", "tenant") + seed.Status.StartedAt = mariadbOutcomeStartedAt(true) + seed.Status.Phase = backupsv1alpha1.BackupJobPhaseRunning + op := &mariadbtypes.Backup{ + ObjectMeta: metav1.ObjectMeta{Namespace: "tenant", Name: "op", Labels: map[string]string{ + backupsv1alpha1.OwningJobNameLabel: seed.Name, + backupsv1alpha1.OwningJobNamespaceLabel: seed.Namespace, + }}, + Status: mariadbtypes.BackupStatus{Conditions: conditions}, + } + objs := []client.Object{ + seed, + newMariaDBApp(seed.Spec.ApplicationRef.Name, "tenant"), + &strategyv1alpha1.MariaDB{ObjectMeta: metav1.ObjectMeta{Name: "mdb-strategy"}, Spec: strategyv1alpha1.MariaDBSpec{Template: *newRenderedMariaDBTemplate()}}, + &mariadbtypes.MariaDB{ObjectMeta: metav1.ObjectMeta{Namespace: "tenant", Name: mariadbNameForApp(seed.Spec.ApplicationRef.Name)}}, + } + return seed, op, objs, resolved +} + +func reconcileStoredMariaDBJob(t *testing.T, r *BackupJobReconciler, seed *backupsv1alpha1.BackupJob, resolved *ResolvedBackupConfig) (ctrl.Result, error) { + t.Helper() + bj := &backupsv1alpha1.BackupJob{} + if err := r.Get(context.Background(), client.ObjectKeyFromObject(seed), bj); err != nil { + t.Fatalf("get BackupJob: %v", err) + } + return r.reconcileMariaDB(context.Background(), bj, resolved) +} + +// A pass that deleted the run and then failed to persist Failed must not +// start another run on its retry. +func TestReconcileMariaDBBackup_RetryAfterTheDeadlineStartsNoNewRun(t *testing.T) { + seed, op, objs, resolved := pastDeadlineFixture(nil) + base := newMariaDBStrategyTestClient(t, append(objs, op)...) + statusFailed, creates := false, 0 + c := interceptor.NewClient(base.(client.WithWatch), interceptor.Funcs{ + Create: func(ctx context.Context, cl client.WithWatch, obj client.Object, opts ...client.CreateOption) error { + if _, ok := obj.(*mariadbtypes.Backup); ok { + creates++ + } + return cl.Create(ctx, obj, opts...) + }, + SubResourceUpdate: func(ctx context.Context, cl client.Client, sub string, obj client.Object, opts ...client.SubResourceUpdateOption) error { + if !statusFailed { + statusFailed = true + return apierrors.NewConflict(backupsv1alpha1.GroupVersion.WithResource("backupjobs").GroupResource(), seed.Name, errors.New("stale")) + } + return cl.SubResource(sub).Update(ctx, obj, opts...) + }, + }) + r := &BackupJobReconciler{Client: c, Scheme: base.Scheme(), Recorder: record.NewFakeRecorder(10)} + + if _, err := reconcileStoredMariaDBJob(t, r, seed, resolved); err == nil { + t.Fatal("first pass: want the injected status conflict") + } + if _, err := reconcileStoredMariaDBJob(t, r, seed, resolved); err != nil { + t.Fatalf("second pass: %v", err) + } + if creates != 0 { + t.Errorf("created %d operator Backups, want none past the deadline", creates) + } + stored := &backupsv1alpha1.BackupJob{} + if err := c.Get(context.Background(), client.ObjectKeyFromObject(seed), stored); err != nil { + t.Fatal(err) + } + if stored.Status.Phase != backupsv1alpha1.BackupJobPhaseFailed { + t.Errorf("phase = %q, want Failed", stored.Status.Phase) + } +} + +// The cache can trail a Complete the operator has just written; a run that +// completed is handed to the success path, not deleted. +func TestReconcileMariaDBBackup_DeadlineReadsTheRunPastTheCache(t *testing.T) { + seed, op, objs, resolved := pastDeadlineFixture(nil) + cached := newMariaDBStrategyTestClient(t, append(objs, op)...) + done := op.DeepCopy() + done.Status.Conditions = []metav1.Condition{mariadbBackupSucceeded(metav1.Now())} + live := newMariaDBStrategyTestClient(t, append(objs, done)...) + r := &BackupJobReconciler{Client: cached, APIReader: live, Scheme: cached.Scheme(), Recorder: record.NewFakeRecorder(10)} + + if _, err := reconcileStoredMariaDBJob(t, r, seed, resolved); err != nil { + t.Fatalf("reconcile: %v", err) + } + if err := cached.Get(context.Background(), client.ObjectKeyFromObject(op), &mariadbtypes.Backup{}); err != nil { + t.Errorf("operator Backup: %v, want it kept", err) + } + stored := &backupsv1alpha1.BackupJob{} + if err := cached.Get(context.Background(), client.ObjectKeyFromObject(seed), stored); err != nil { + t.Fatal(err) + } + if stored.Status.Phase == backupsv1alpha1.BackupJobPhaseFailed { + t.Errorf("phase = Failed (%q), want the completed run taken", stored.Status.Message) + } +} + +func TestReconcileMariaDBBackup_RefusedDeadlineDeleteIsSurfaced(t *testing.T) { + seed, op, objs, resolved := pastDeadlineFixture(nil) + base := newMariaDBStrategyTestClient(t, append(objs, op)...) + c := interceptor.NewClient(base.(client.WithWatch), interceptor.Funcs{ + Delete: func(ctx context.Context, cl client.WithWatch, obj client.Object, opts ...client.DeleteOption) error { + if _, ok := obj.(*mariadbtypes.Backup); ok { + return apierrors.NewForbidden(mariadbtypes.GroupVersion.WithResource("backups").GroupResource(), obj.GetName(), errors.New("denied by policy")) + } + return cl.Delete(ctx, obj, opts...) + }, + }) + r := &BackupJobReconciler{Client: c, Scheme: base.Scheme(), Recorder: record.NewFakeRecorder(10)} + + if _, err := reconcileStoredMariaDBJob(t, r, seed, resolved); err == nil { + t.Fatal("want the refused delete returned for a retry") + } + stored := &backupsv1alpha1.BackupJob{} + if err := c.Get(context.Background(), client.ObjectKeyFromObject(seed), stored); err != nil { + t.Fatal(err) + } + if stored.Status.Phase == backupsv1alpha1.BackupJobPhaseFailed { + t.Error("phase = Failed, want the BackupJob kept until its run is deleted") + } + ready := apimeta.FindStatusCondition(stored.Status.Conditions, "Ready") + if ready == nil || ready.Reason != "OperatorBackupDeleteFailed" || !strings.Contains(ready.Message, "denied by policy") { + t.Errorf("Ready = %+v, want False/OperatorBackupDeleteFailed naming the cause", ready) + } +} + +// A run created just before the deadline can be missing from the cache; +// the BackupJob must not be failed as if it had none. +func TestReconcileMariaDBBackup_DeadlineFindsARunTheCacheMissed(t *testing.T) { + seed, op, objs, resolved := pastDeadlineFixture([]metav1.Condition{{ + Type: mariadbtypes.ConditionTypeComplete, Status: metav1.ConditionFalse, + Reason: mariadbtypes.ConditionReasonJobRunning, LastTransitionTime: metav1.Now(), + }}) + base := newMariaDBStrategyTestClient(t, objs...) + creates := 0 + cached := interceptor.NewClient(base.(client.WithWatch), interceptor.Funcs{ + Create: func(ctx context.Context, cl client.WithWatch, obj client.Object, opts ...client.CreateOption) error { + if _, ok := obj.(*mariadbtypes.Backup); ok { + creates++ + } + return cl.Create(ctx, obj, opts...) + }, + }) + live := newMariaDBStrategyTestClient(t, append(objs, op)...) + r := &BackupJobReconciler{Client: cached, APIReader: live, Scheme: base.Scheme(), Recorder: record.NewFakeRecorder(10)} + + if _, err := reconcileStoredMariaDBJob(t, r, seed, resolved); err != nil { + t.Fatalf("reconcile: %v", err) + } + if creates != 0 { + t.Errorf("created %d operator Backups past the deadline, want none", creates) + } + stored := &backupsv1alpha1.BackupJob{} + if err := cached.Get(context.Background(), client.ObjectKeyFromObject(seed), stored); err != nil { + t.Fatal(err) + } + if strings.Contains(stored.Status.Message, "is left") { + t.Errorf("message = %q, want the BackupJob not failed for want of a run", stored.Status.Message) + } +} + +// A run that completes between the read and the delete makes the delete +// conflict on its preconditions; the next pass hands it to the success path. +func TestReconcileMariaDBBackup_DeadlineDeleteIsConditionalOnTheRunRead(t *testing.T) { + seed, op, objs, resolved := pastDeadlineFixture(nil) + base := newMariaDBStrategyTestClient(t, append(objs, op)...) + var preconditions *metav1.Preconditions + c := interceptor.NewClient(base.(client.WithWatch), interceptor.Funcs{ + Delete: func(ctx context.Context, cl client.WithWatch, obj client.Object, opts ...client.DeleteOption) error { + if _, ok := obj.(*mariadbtypes.Backup); ok { + do := &client.DeleteOptions{} + do.ApplyOptions(opts) + preconditions = do.Preconditions + return apierrors.NewConflict(mariadbtypes.GroupVersion.WithResource("backups").GroupResource(), obj.GetName(), errors.New("precondition failed")) + } + return cl.Delete(ctx, obj, opts...) + }, + }) + r := &BackupJobReconciler{Client: c, Scheme: base.Scheme(), Recorder: record.NewFakeRecorder(10)} + + res, err := reconcileStoredMariaDBJob(t, r, seed, resolved) + if err != nil || res.RequeueAfter == 0 { + t.Fatalf("got res=%+v err=%v, want a requeue", res, err) + } + if preconditions == nil || preconditions.UID == nil || preconditions.ResourceVersion == nil { + t.Errorf("preconditions = %+v, want the UID and resourceVersion that were read", preconditions) + } + stored := &backupsv1alpha1.BackupJob{} + if err := c.Get(context.Background(), client.ObjectKeyFromObject(seed), stored); err != nil { + t.Fatal(err) + } + if stored.Status.Phase == backupsv1alpha1.BackupJobPhaseFailed { + t.Error("phase = Failed, want the run re-read on the next pass") + } +} + +// Every way a started BackupJob fails deletes a run that has not completed, +// not only the deadline: mariadb-operator leaves the run of a MariaDB that +// went away at Complete=False for good. +func TestReconcileMariaDBBackup_FailingAStartedJobDeletesItsUnfinishedRun(t *testing.T) { + running := []metav1.Condition{{ + Type: mariadbtypes.ConditionTypeComplete, Status: metav1.ConditionFalse, + Reason: "Failed", Message: "MariaDB not found", LastTransitionTime: metav1.Now(), + }} + cases := []struct { + name string + conditions []metav1.Condition + dropApp bool + dropMariaDB bool + dropStrategy bool + expired bool + wantMessage string + wantDeleted bool + }{ + {name: "application deleted mid-run", conditions: running, dropApp: true, wantMessage: "MariaDB application not found", wantDeleted: true}, + {name: "application deleted after the run completed", conditions: []metav1.Condition{mariadbBackupSucceeded(metav1.Now())}, dropApp: true, + wantMessage: "MariaDB application not found"}, + {name: "MariaDB gone past the deadline", conditions: running, dropMariaDB: true, expired: true, wantMessage: "never reached existence", wantDeleted: true}, + {name: "strategy gone past the deadline", conditions: running, dropStrategy: true, expired: true, wantMessage: "was not provisioned", wantDeleted: true}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + seed, op, objs, resolved := pastDeadlineFixture(tc.conditions) + seed.Status.StartedAt = mariadbOutcomeStartedAt(tc.expired) + var kept []client.Object + for _, obj := range objs { + switch obj.(type) { + case *mariadbapp.MariaDB: + if tc.dropApp { + continue + } + case *mariadbtypes.MariaDB: + if tc.dropMariaDB { + continue + } + case *strategyv1alpha1.MariaDB: + if tc.dropStrategy { + continue + } + } + kept = append(kept, obj) + } + c := newMariaDBStrategyTestClient(t, append(kept, op)...) + r := &BackupJobReconciler{Client: c, Scheme: c.Scheme(), Recorder: record.NewFakeRecorder(10)} + + if _, err := reconcileStoredMariaDBJob(t, r, seed, resolved); err != nil { + t.Fatalf("reconcile: %v", err) + } + stored := &backupsv1alpha1.BackupJob{} + if err := c.Get(context.Background(), client.ObjectKeyFromObject(seed), stored); err != nil { + t.Fatal(err) + } + if stored.Status.Phase != backupsv1alpha1.BackupJobPhaseFailed || !strings.Contains(stored.Status.Message, tc.wantMessage) { + t.Errorf("phase=%q message=%q, want Failed with %q", stored.Status.Phase, stored.Status.Message, tc.wantMessage) + } + err := c.Get(context.Background(), client.ObjectKeyFromObject(op), &mariadbtypes.Backup{}) + if err != nil && !apierrors.IsNotFound(err) { + t.Fatal(err) + } + if deleted := apierrors.IsNotFound(err); deleted != tc.wantDeleted { + t.Errorf("operator Backup deleted = %v, want %v", deleted, tc.wantDeleted) + } + }) + } +} + +// The deadline can pass between listing the run and giving up on it, by +// when the operator may have finished it; the cache can trail that. +func TestGiveUpOnMariaDBBackup_HandsAFinishedRunBack(t *testing.T) { + for _, reason := range []string{mariadbtypes.ConditionReasonJobComplete, mariadbtypes.ConditionReasonJobFailed} { + t.Run(reason, func(t *testing.T) { + seed, op, objs, _ := pastDeadlineFixture(nil) + cached := newMariaDBStrategyTestClient(t, append(objs, op)...) + finished := op.DeepCopy() + finished.Status.Conditions = []metav1.Condition{{ + Type: mariadbtypes.ConditionTypeComplete, Status: metav1.ConditionTrue, Reason: reason, LastTransitionTime: metav1.Now(), + }} + live := newMariaDBStrategyTestClient(t, append(objs, finished)...) + r := &BackupJobReconciler{Client: cached, APIReader: live, Scheme: cached.Scheme(), Recorder: record.NewFakeRecorder(10)} + + bj := &backupsv1alpha1.BackupJob{} + if err := cached.Get(context.Background(), client.ObjectKeyFromObject(seed), bj); err != nil { + t.Fatal(err) + } + res, err := r.giveUpOnMariaDBBackup(context.Background(), bj, op) + if err != nil || res.RequeueAfter == 0 { + t.Fatalf("got res=%+v err=%v, want a requeue", res, err) + } + if err := live.Get(context.Background(), client.ObjectKeyFromObject(op), &mariadbtypes.Backup{}); err != nil { + t.Errorf("operator Backup: %v, want it kept", err) + } + stored := &backupsv1alpha1.BackupJob{} + if err := cached.Get(context.Background(), client.ObjectKeyFromObject(seed), stored); err != nil { + t.Fatal(err) + } + if stored.Status.Phase == backupsv1alpha1.BackupJobPhaseFailed { + t.Error("phase = Failed, want the finished run handed back") + } + }) + } +} + +// Deleting a stuck run takes its pod with it, so what held the pod up is +// kept on the BackupJob. +func TestReconcileMariaDBBackup_DeadlineKeepsWhyTheRunWasStuck(t *testing.T) { + cases := map[string]struct { + status corev1.PodStatus + want string + }{ + "unschedulable": { + status: corev1.PodStatus{Conditions: []corev1.PodCondition{{ + Type: corev1.PodScheduled, Status: corev1.ConditionFalse, Reason: "Unschedulable", Message: "0/3 nodes are available", + }}}, + want: "pod op-abc not scheduled: Unschedulable: 0/3 nodes are available", + }, + "image not pulled": { + status: corev1.PodStatus{ContainerStatuses: []corev1.ContainerStatus{{ + Name: "mariadb", State: corev1.ContainerState{Waiting: &corev1.ContainerStateWaiting{Reason: "ImagePullBackOff", Message: "back-off pulling image"}}, + }}}, + want: "pod op-abc container mariadb waiting: ImagePullBackOff", + }, + } + for name, tc := range cases { + t.Run(name, func(t *testing.T) { + seed, op, objs, resolved := pastDeadlineFixture(nil) + pod := &corev1.Pod{ + ObjectMeta: metav1.ObjectMeta{Namespace: "tenant", Name: "op-abc", Labels: map[string]string{"job-name": op.Name}}, + Status: tc.status, + } + c := newMariaDBStrategyTestClient(t, append(objs, op, pod)...) + r := &BackupJobReconciler{Client: c, Scheme: c.Scheme(), Recorder: record.NewFakeRecorder(10)} + + if _, err := reconcileStoredMariaDBJob(t, r, seed, resolved); err != nil { + t.Fatalf("reconcile: %v", err) + } + stored := &backupsv1alpha1.BackupJob{} + if err := c.Get(context.Background(), client.ObjectKeyFromObject(seed), stored); err != nil { + t.Fatal(err) + } + if stored.Status.Phase != backupsv1alpha1.BackupJobPhaseFailed || !strings.Contains(stored.Status.Message, tc.want) { + t.Errorf("phase=%q message=%q, want Failed naming %q", stored.Status.Phase, stored.Status.Message, tc.want) + } + }) + } +} + +// A Running job has created its run: a retry after the run was deleted and +// Failed was not persisted fails the job instead of starting another, even +// with the deadline not reached and a cache that no longer shows the run. +func TestReconcileMariaDBBackup_RunningJobNeverStartsASecondRun(t *testing.T) { + seed, op, objs, resolved := pastDeadlineFixture([]metav1.Condition{{ + Type: mariadbtypes.ConditionTypeComplete, Status: metav1.ConditionFalse, + Reason: mariadbtypes.ConditionReasonJobFailed, Message: "Failed", LastTransitionTime: metav1.Now(), + }}) + seed.Status.StartedAt = mariadbOutcomeStartedAt(false) + live := newMariaDBStrategyTestClient(t, append(objs, op)...) + statusFailed, creates := false, 0 + cached := interceptor.NewClient(live.(client.WithWatch), interceptor.Funcs{ + List: func(ctx context.Context, cl client.WithWatch, list client.ObjectList, opts ...client.ListOption) error { + if _, ok := list.(*mariadbtypes.BackupList); ok { + return nil + } + return cl.List(ctx, list, opts...) + }, + Create: func(ctx context.Context, cl client.WithWatch, obj client.Object, opts ...client.CreateOption) error { + if _, ok := obj.(*mariadbtypes.Backup); ok { + creates++ + } + return cl.Create(ctx, obj, opts...) + }, + SubResourceUpdate: func(ctx context.Context, cl client.Client, sub string, obj client.Object, opts ...client.SubResourceUpdateOption) error { + if !statusFailed { + statusFailed = true + return apierrors.NewConflict(backupsv1alpha1.GroupVersion.WithResource("backupjobs").GroupResource(), seed.Name, errors.New("stale")) + } + return cl.SubResource(sub).Update(ctx, obj, opts...) + }, + }) + r := &BackupJobReconciler{Client: cached, APIReader: live, Scheme: live.Scheme(), Recorder: record.NewFakeRecorder(10)} + + if _, err := reconcileStoredMariaDBJob(t, r, seed, resolved); err == nil { + t.Fatal("first pass: want the injected status conflict") + } + if _, err := reconcileStoredMariaDBJob(t, r, seed, resolved); err != nil { + t.Fatalf("second pass: %v", err) + } + if creates != 0 { + t.Errorf("created %d operator Backups, want none", creates) + } + stored := &backupsv1alpha1.BackupJob{} + if err := live.Get(context.Background(), client.ObjectKeyFromObject(seed), stored); err != nil { + t.Fatal(err) + } + if stored.Status.Phase != backupsv1alpha1.BackupJobPhaseFailed { + t.Errorf("phase = %q, want Failed", stored.Status.Phase) + } +} + +// The Backup made of a completed run names the storage the run wrote to, +// not the strategy as rendered now. +func TestReconcileMariaDBBackup_BackupRecordsTheRunsStorage(t *testing.T) { + seed, op, objs, resolved := pastDeadlineFixture([]metav1.Condition{mariadbBackupSucceeded(metav1.Now())}) + seed.Status.StartedAt = mariadbOutcomeStartedAt(false) + atStart := newRenderedMariaDBTemplate() + atStart.Storage.S3.Bucket = "run-bucket" + atStart.Storage.S3.Prefix = "run/prefix" + storage, err := buildMariaDBBackupStorage(atStart.Storage) + if err != nil { + t.Fatal(err) + } + op.Spec.Storage = storage + c := newMariaDBStrategyTestClient(t, append(objs, op)...) + r := &BackupJobReconciler{Client: c, Scheme: c.Scheme(), Recorder: record.NewFakeRecorder(10)} + + if _, err := reconcileStoredMariaDBJob(t, r, seed, resolved); err != nil { + t.Fatalf("reconcile: %v", err) + } + backup := &backupsv1alpha1.Backup{} + if err := c.Get(context.Background(), client.ObjectKey{Namespace: seed.Namespace, Name: seed.Name}, backup); err != nil { + t.Fatalf("get Backup: %v", err) + } + if uri := backup.Spec.DriverMetadata[mariadbStorageURIKey]; !strings.HasPrefix(uri, "s3://run-bucket/run/prefix/") { + t.Errorf("storage URI = %q, want the run's bucket and prefix", uri) + } + recorded, err := mariadbSnapshotStorage(backup) + if err != nil { + t.Fatal(err) + } + if recorded.S3 == nil || recorded.S3.Bucket != "run-bucket" || recorded.S3.Prefix != "run/prefix" { + t.Errorf("snapshot storage = %+v, want the run's", recorded.S3) + } +} + +// A pass that created the run and then failed to persist Running retries +// with no phase; a cache that has not seen the run yet must not make it +// create a second. +func TestReconcileMariaDBBackup_RetryBeforeRunningStartsNoSecondRun(t *testing.T) { + seed, _, objs, resolved := pastDeadlineFixture(nil) + seed.Status.StartedAt = mariadbOutcomeStartedAt(false) + seed.Status.Phase = "" + live := newMariaDBStrategyTestClient(t, objs...) + statusFailed, creates := false, 0 + cached := interceptor.NewClient(live.(client.WithWatch), interceptor.Funcs{ + List: func(ctx context.Context, cl client.WithWatch, list client.ObjectList, opts ...client.ListOption) error { + if _, ok := list.(*mariadbtypes.BackupList); ok { + return nil + } + return cl.List(ctx, list, opts...) + }, + Create: func(ctx context.Context, cl client.WithWatch, obj client.Object, opts ...client.CreateOption) error { + if _, ok := obj.(*mariadbtypes.Backup); ok { + creates++ + } + return cl.Create(ctx, obj, opts...) + }, + SubResourceUpdate: func(ctx context.Context, cl client.Client, sub string, obj client.Object, opts ...client.SubResourceUpdateOption) error { + if !statusFailed { + statusFailed = true + return apierrors.NewConflict(backupsv1alpha1.GroupVersion.WithResource("backupjobs").GroupResource(), seed.Name, errors.New("stale")) + } + return cl.SubResource(sub).Update(ctx, obj, opts...) + }, + }) + r := &BackupJobReconciler{Client: cached, APIReader: live, Scheme: live.Scheme(), Recorder: record.NewFakeRecorder(10)} + + if _, err := reconcileStoredMariaDBJob(t, r, seed, resolved); err == nil { + t.Fatal("first pass: want the injected status conflict") + } + if _, err := reconcileStoredMariaDBJob(t, r, seed, resolved); err != nil { + t.Fatalf("second pass: %v", err) + } + if creates != 1 { + t.Errorf("created %d operator Backups, want 1", creates) + } +} + +// A failing BackupJob deletes only its own runs: the unfinished run of +// another BackupJob in the same namespace is left alone. +func TestReconcileMariaDBBackup_FailingJobKeepsAnotherJobsRun(t *testing.T) { + running := []metav1.Condition{{ + Type: mariadbtypes.ConditionTypeComplete, Status: metav1.ConditionFalse, + Reason: mariadbtypes.ConditionReasonJobRunning, LastTransitionTime: metav1.Now(), + }} + seed, op, objs, resolved := pastDeadlineFixture(running) + other := op.DeepCopy() + other.Name = "other-op" + other.Labels = map[string]string{ + backupsv1alpha1.OwningJobNameLabel: "other-bj", + backupsv1alpha1.OwningJobNamespaceLabel: seed.Namespace, + } + c := newMariaDBStrategyTestClient(t, append(objs, op, other)...) + r := &BackupJobReconciler{Client: c, Scheme: c.Scheme(), Recorder: record.NewFakeRecorder(10)} + + if _, err := reconcileStoredMariaDBJob(t, r, seed, resolved); err != nil { + t.Fatalf("reconcile: %v", err) + } + if err := c.Get(context.Background(), client.ObjectKeyFromObject(op), &mariadbtypes.Backup{}); !apierrors.IsNotFound(err) { + t.Errorf("own run: %v, want it deleted", err) + } + if err := c.Get(context.Background(), client.ObjectKeyFromObject(other), &mariadbtypes.Backup{}); err != nil { + t.Errorf("another BackupJob's run: %v, want it kept", err) + } +} + +// A Create that times out can still have stored the run. +func TestReconcileMariaDBBackup_FailedCreateDeletesARunItStored(t *testing.T) { + seed, _, objs, resolved := pastDeadlineFixture(nil) + seed.Status.StartedAt = mariadbOutcomeStartedAt(false) + seed.Status.Phase = "" + base := newMariaDBStrategyTestClient(t, objs...) + creates := 0 + c := interceptor.NewClient(base.(client.WithWatch), interceptor.Funcs{ + Create: func(ctx context.Context, cl client.WithWatch, obj client.Object, opts ...client.CreateOption) error { + if _, ok := obj.(*mariadbtypes.Backup); ok { + creates++ + if err := cl.Create(ctx, obj, opts...); err != nil { + return err + } + return apierrors.NewTimeoutError("request timed out", 1) + } + return cl.Create(ctx, obj, opts...) + }, + }) + r := &BackupJobReconciler{Client: c, Scheme: base.Scheme(), Recorder: record.NewFakeRecorder(10)} + + if _, err := reconcileStoredMariaDBJob(t, r, seed, resolved); err != nil { + t.Fatalf("reconcile: %v", err) + } + if creates != 1 { + t.Fatalf("operator Backup Create called %d times, want 1", creates) + } + runs := &mariadbtypes.BackupList{} + if err := c.List(context.Background(), runs); err != nil { + t.Fatal(err) + } + if len(runs.Items) != 0 { + t.Errorf("%d operator Backups left, want the stored run deleted", len(runs.Items)) + } + stored := &backupsv1alpha1.BackupJob{} + if err := c.Get(context.Background(), client.ObjectKeyFromObject(seed), stored); err != nil { + t.Fatal(err) + } + if stored.Status.Phase != backupsv1alpha1.BackupJobPhaseFailed { + t.Errorf("phase = %q, want Failed", stored.Status.Phase) + } +} + +// A strategy edited during a run renders storage the dump never went to; +// the Backup records the run's own, which the dump cleanup reads once the +// run is gone. +func TestMariaDBRunTemplate_RecordsTheRunsStorage(t *testing.T) { + atStart := newRenderedMariaDBTemplate() + atStart.Storage.S3.Prefix = "tenant/db" + atStart.Storage.S3.SessionTokenSecretKeyRef = &strategyv1alpha1.MariaDBSecretKeySelector{Name: "creds", Key: "token"} + atStart.Storage.S3.TLS = &strategyv1alpha1.MariaDBS3TLS{Enabled: true, CASecretKeyRef: &strategyv1alpha1.MariaDBSecretKeySelector{Name: "ca", Key: "ca.crt"}} + storage, err := buildMariaDBBackupStorage(atStart.Storage) + if err != nil { + t.Fatal(err) + } + run := &mariadbtypes.Backup{Spec: mariadbtypes.BackupSpec{Storage: storage}} + + now := newRenderedMariaDBTemplate() + now.Storage.S3.Bucket = "moved" + now.Storage.S3.Prefix = "elsewhere" + + got := mariadbRunTemplate(now, run) + if !apiequality.Semantic.DeepEqual(got.Storage, atStart.Storage) { + t.Errorf("storage = %+v, want the run's %+v", got.Storage.S3, atStart.Storage.S3) + } + if now.Storage.S3.Bucket != "moved" { + t.Error("the rendered template was modified in place") + } + if uri := mariadbBackupURI(got, &mariadbtypes.Backup{ObjectMeta: metav1.ObjectMeta{Name: "op"}}); !strings.HasPrefix(uri, "s3://"+atStart.Storage.S3.Bucket+"/tenant/db/") { + t.Errorf("storage URI = %q, want it under the run's bucket and prefix", uri) + } + + t.Run("strategy moved off S3", func(t *testing.T) { + onVolume := newRenderedMariaDBTemplate() + onVolume.Storage = strategyv1alpha1.MariaDBStorageTemplate{PersistentVolumeClaim: &corev1.PersistentVolumeClaimSpec{}} + if got := mariadbRunTemplate(onVolume, run); got.Storage.S3 == nil || got.Storage.PersistentVolumeClaim != nil { + t.Errorf("storage = %+v, want the run's S3 only", got.Storage) + } + }) + t.Run("strategy moved onto S3", func(t *testing.T) { + pvcRun := &mariadbtypes.Backup{Spec: mariadbtypes.BackupSpec{Storage: mariadbtypes.BackupStorage{PersistentVolumeClaim: &corev1.PersistentVolumeClaimSpec{}}}} + if got := mariadbRunTemplate(now, pvcRun); got.Storage.S3 != nil || got.Storage.PersistentVolumeClaim == nil { + t.Errorf("storage = %+v, want the run's volume claim only", got.Storage) + } + }) +} + +// Without mariadb-operator's CRDs no run can exist, and a BackupJob failing +// for another reason must still reach Failed. +func TestReconcileMariaDBBackup_FailsWithoutTheOperatorCRDs(t *testing.T) { + seed, _, objs, resolved := pastDeadlineFixture(nil) + seed.Status.StartedAt = mariadbOutcomeStartedAt(false) + var kept []client.Object + for _, obj := range objs { + if _, ok := obj.(*mariadbapp.MariaDB); !ok { + kept = append(kept, obj) + } + } + base := newMariaDBStrategyTestClient(t, kept...) + c := interceptor.NewClient(base.(client.WithWatch), interceptor.Funcs{ + List: func(ctx context.Context, cl client.WithWatch, list client.ObjectList, opts ...client.ListOption) error { + if _, ok := list.(*mariadbtypes.BackupList); ok { + return &apimeta.NoKindMatchError{GroupKind: mariadbtypes.GroupVersion.WithKind("Backup").GroupKind()} + } + return cl.List(ctx, list, opts...) + }, + }) + r := &BackupJobReconciler{Client: c, Scheme: base.Scheme(), Recorder: record.NewFakeRecorder(10)} + + if _, err := reconcileStoredMariaDBJob(t, r, seed, resolved); err != nil { + t.Fatalf("reconcile: %v", err) + } + stored := &backupsv1alpha1.BackupJob{} + if err := c.Get(context.Background(), client.ObjectKeyFromObject(seed), stored); err != nil { + t.Fatal(err) + } + if stored.Status.Phase != backupsv1alpha1.BackupJobPhaseFailed { + t.Errorf("phase = %q, want Failed", stored.Status.Phase) + } +} diff --git a/packages/system/backupstrategy-controller/templates/rbac.yaml b/packages/system/backupstrategy-controller/templates/rbac.yaml index 883fd1fe9..02e7d600d 100644 --- a/packages/system/backupstrategy-controller/templates/rbac.yaml +++ b/packages/system/backupstrategy-controller/templates/rbac.yaml @@ -165,7 +165,8 @@ rules: # rendered" preconditions, create one-shot k8s.mariadb.com/Backup CRs on # the BackupJob path, and create k8s.mariadb.com/Restore CRs on the # RestoreJob path. A Backup is deleted once the dump it wrote is, when its -# Cozystack Backup is deleted; a Restore is never deleted. +# Cozystack Backup is deleted, or when its BackupJob gives up on it before +# it completes; a Restore is never deleted. - apiGroups: ["k8s.mariadb.com"] resources: ["mariadbs"] verbs: ["get", "list", "watch"] From 5fbf7e9a38061dae585a944a5b520b70321507a2 Mon Sep 17 00:00:00 2001 From: Andrey Kolkov Date: Thu, 19 Nov 2026 20:31:34 +0700 Subject: [PATCH 11/17] fix(backups): delete the Velero backup of a failed BackupJob When a Velero strategy run ended Failed or PartiallyFailed, no Backup was created, and the Backup finalizer was the only code that asked Velero to delete backup data. The failed backup.velero.io object, labelled for the BackupJob but not owned by it, stayed in the bucket with its partial resources and logs until Velero's TTL (720h by default) expired it, and deleting the BackupJob did not remove it. The strategy now requests the deletion through a DeleteBackupRequest before it marks the job Failed, and the failure message is still read from the Velero backup first. A direct delete is not enough, because the BSL sync recreates the object from the object store. A reconcile of a Failed BackupJob, which used to return at once, now requests deletion of every Velero backup still labelled for the job. That retries a request that could not be created and removes backups that earlier versions leaked, after an upgrade. A Velero backup that a Backup references (the job failed after its Backup was created) is left alone, and one still running is polled until Velero accepts a request for it. The sweep matches on the job labels, so it also covers the Velero backup of a failed Kubernetes strategy run. The request is named after the Velero backup, and the Backup finalizer uses the same helper, so repeated reconciles converge on one request. Nothing is created while another request for the backup is pending. A request that Velero processed with errors is replaced, because Velero keeps it for a day and its name would block the retry until then. A job with more than one Velero backup now fails with a message that names them, not with an empty one. Fake-client unit tests cover Failed and PartiallyFailed runs, a repeated reconcile, leftovers of already Failed jobs (no request, a pending request, a request processed with errors, a Backup-referenced backup, a running backup) and the unchanged Succeeded path. Closes: #5355 Assisted-by: LLM Signed-off-by: Andrey Kolkov --- .../backupcontroller/backup_controller.go | 28 +- .../backupcontroller/backupjob_controller.go | 6 +- .../velero_backup_deletion.go | 154 ++++++++++ .../velero_backup_deletion_test.go | 267 ++++++++++++++++++ .../velerostrategy_controller.go | 16 +- 5 files changed, 445 insertions(+), 26 deletions(-) create mode 100644 internal/backupcontroller/velero_backup_deletion.go create mode 100644 internal/backupcontroller/velero_backup_deletion_test.go diff --git a/internal/backupcontroller/backup_controller.go b/internal/backupcontroller/backup_controller.go index bc49baa6b..1677f5714 100644 --- a/internal/backupcontroller/backup_controller.go +++ b/internal/backupcontroller/backup_controller.go @@ -248,28 +248,16 @@ func (r *BackupReconciler) cleanupVeleroBackup(ctx context.Context, backup *back return fmt.Errorf("failed to get Velero backup %s/%s: %w", veleroBackupNamespace, veleroBackupName, err) } - // Create a DeleteBackupRequest so Velero removes backup data from storage. - // Without this, BSL sync will recreate the backup.velero.io resource. - dbr := &velerov1.DeleteBackupRequest{ - ObjectMeta: metav1.ObjectMeta{ - GenerateName: veleroBackupName + "-", - Namespace: veleroBackupNamespace, - }, - Spec: velerov1.DeleteBackupRequestSpec{ - BackupName: veleroBackupName, - }, + created, err := requestVeleroBackupDeletion(ctx, r.Client, veleroBackupNamespace, veleroBackupName) + if err != nil { + return err } - if err := r.Create(ctx, dbr); err != nil { - if apierrors.IsAlreadyExists(err) { - logger.V(1).Info("DeleteBackupRequest already exists", "backup", veleroBackupName) - return nil - } - return fmt.Errorf("failed to create DeleteBackupRequest for %s/%s: %w", veleroBackupNamespace, veleroBackupName, err) + if created { + logger.Info("created DeleteBackupRequest for Velero backup", + "name", veleroBackupName, "namespace", veleroBackupNamespace) + } else { + logger.V(1).Info("deletion of Velero backup already requested", "backup", veleroBackupName) } - - logger.Info("created DeleteBackupRequest for Velero backup", - "name", veleroBackupName, "namespace", veleroBackupNamespace, - "deleteRequest", dbr.Name) return nil } diff --git a/internal/backupcontroller/backupjob_controller.go b/internal/backupcontroller/backupjob_controller.go index 15ef65db4..a86243c94 100644 --- a/internal/backupcontroller/backupjob_controller.go +++ b/internal/backupcontroller/backupjob_controller.go @@ -65,7 +65,11 @@ func (r *BackupJobReconciler) Reconcile(ctx context.Context, req ctrl.Request) ( // would otherwise materialise cozy-backups-creds in tenant namespaces // long after the BackupJob is done and pin needless work on the // apiserver. - if j.Status.Phase == backupsv1alpha1.BackupJobPhaseSucceeded || j.Status.Phase == backupsv1alpha1.BackupJobPhaseFailed { + if j.Status.Phase == backupsv1alpha1.BackupJobPhaseFailed { + logger.V(1).Info("BackupJob already terminal, cleaning up its Velero Backups", "phase", j.Status.Phase) + return r.deleteFailedJobVeleroBackups(ctx, j) + } + if j.Status.Phase == backupsv1alpha1.BackupJobPhaseSucceeded { logger.V(1).Info("BackupJob already terminal, skipping", "phase", j.Status.Phase) return ctrl.Result{}, nil } diff --git a/internal/backupcontroller/velero_backup_deletion.go b/internal/backupcontroller/velero_backup_deletion.go new file mode 100644 index 000000000..e93e6eee3 --- /dev/null +++ b/internal/backupcontroller/velero_backup_deletion.go @@ -0,0 +1,154 @@ +package backupcontroller + +import ( + "context" + "fmt" + + apierrors "k8s.io/apimachinery/pkg/api/errors" + "k8s.io/apimachinery/pkg/api/meta" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + ctrl "sigs.k8s.io/controller-runtime" + "sigs.k8s.io/controller-runtime/pkg/client" + + backupsv1alpha1 "github.com/cozystack/cozystack/api/backups/v1alpha1" + + velerov1 "github.com/vmware-tanzu/velero/pkg/apis/velero/v1" +) + +// requestVeleroBackupDeletion asks Velero to delete a backup together with its +// data in the object store. Deleting the backup.velero.io object directly only +// removes the Kubernetes object, and the BSL sync recreates it from the object +// store. +// +// The request is named after the backup, so repeated calls converge on one +// request. Nothing is created while any request for the backup is unprocessed, +// or once one was processed without errors (Velero then removes the backup and +// the remaining requests). A request of ours that Velero processed with errors +// is replaced: Velero keeps it for a day, and until then its name would block +// the retry. +func requestVeleroBackupDeletion(ctx context.Context, c client.Client, namespace, name string) (bool, error) { + requests := &velerov1.DeleteBackupRequestList{} + if err := c.List(ctx, requests, client.InNamespace(namespace)); err != nil { + return false, fmt.Errorf("failed to list DeleteBackupRequests in %s: %w", namespace, err) + } + var failed *velerov1.DeleteBackupRequest + for i := range requests.Items { + dbr := &requests.Items[i] + if dbr.Spec.BackupName != name { + continue + } + if dbr.Status.Phase != velerov1.DeleteBackupRequestPhaseProcessed || len(dbr.Status.Errors) == 0 { + return false, nil + } + if dbr.Name == name { + failed = dbr + } + } + if failed != nil { + // The UID precondition keeps a stale cache from deleting a request + // that has already been replaced. + err := c.Delete(ctx, failed, client.Preconditions{UID: &failed.UID}) + if err != nil && !apierrors.IsNotFound(err) && !apierrors.IsConflict(err) { + return false, fmt.Errorf("failed to delete failed DeleteBackupRequest %s/%s: %w", namespace, name, err) + } + } + + dbr := &velerov1.DeleteBackupRequest{ + ObjectMeta: metav1.ObjectMeta{ + Name: name, + Namespace: namespace, + }, + Spec: velerov1.DeleteBackupRequestSpec{ + BackupName: name, + }, + } + if err := c.Create(ctx, dbr); err != nil { + if apierrors.IsAlreadyExists(err) { + return false, nil + } + return false, fmt.Errorf("failed to create DeleteBackupRequest for %s/%s: %w", namespace, name, err) + } + return true, nil +} + +// deleteFailedJobVeleroBackups requests deletion of the Velero backups a Failed +// BackupJob left behind. A failed run creates no Backup, and the Backup +// finalizer is the only other path that deletes Velero data, so without this +// the backup and its objects stay in the bucket until Velero's TTL expires +// them. It runs on every reconcile of a Failed job, which also clears backups +// left by controller versions that did not request the deletion. +func (r *BackupJobReconciler) deleteFailedJobVeleroBackups(ctx context.Context, j *backupsv1alpha1.BackupJob) (ctrl.Result, error) { + logger := getLogger(ctx) + + veleroBackups := &velerov1.BackupList{} + if err := r.List(ctx, veleroBackups, client.InNamespace(veleroNamespace), client.MatchingLabels{ + backupsv1alpha1.OwningJobNamespaceLabel: j.Namespace, + backupsv1alpha1.OwningJobNameLabel: j.Name, + }); err != nil { + if meta.IsNoMatchError(err) { + return ctrl.Result{}, nil + } + return ctrl.Result{}, fmt.Errorf("failed to list Velero Backups of BackupJob %s/%s: %w", j.Namespace, j.Name, err) + } + if len(veleroBackups.Items) == 0 { + return ctrl.Result{}, nil + } + + // A job can fail after its Backup was created: the status update that + // records the Backup is lost, and the retried create hits AlreadyExists. + // That Backup owns the Velero backup and deletes it itself. + referenced, err := r.veleroBackupsReferencedByBackups(ctx, j.Namespace) + if err != nil { + return ctrl.Result{}, err + } + + var running bool + for i := range veleroBackups.Items { + vb := &veleroBackups.Items[i] + if referenced[client.ObjectKeyFromObject(vb)] { + continue + } + switch vb.Status.Phase { + case velerov1.BackupPhaseCompleted, velerov1.BackupPhasePartiallyFailed, + velerov1.BackupPhaseFailed, velerov1.BackupPhaseFailedValidation: + case velerov1.BackupPhaseDeleting: + continue + default: + // Velero rejects a request for a backup that is still running. + running = true + continue + } + created, err := requestVeleroBackupDeletion(ctx, r.Client, vb.Namespace, vb.Name) + if err != nil { + return ctrl.Result{}, err + } + if created { + logger.Info("requested deletion of the Velero Backup of a failed BackupJob", + "backupjob", j.Name, "namespace", j.Namespace, "veleroBackup", vb.Name) + } + } + if running { + return ctrl.Result{RequeueAfter: defaultActiveJobPollingInterval}, nil + } + return ctrl.Result{}, nil +} + +func (r *BackupJobReconciler) veleroBackupsReferencedByBackups(ctx context.Context, namespace string) (map[client.ObjectKey]bool, error) { + backups := &backupsv1alpha1.BackupList{} + if err := r.List(ctx, backups, client.InNamespace(namespace)); err != nil { + return nil, fmt.Errorf("failed to list Backups in %s: %w", namespace, err) + } + referenced := map[client.ObjectKey]bool{} + for _, b := range backups.Items { + name := b.Spec.DriverMetadata[veleroBackupNameMetadataKey] + if name == "" { + continue + } + ns := b.Spec.DriverMetadata[veleroBackupNamespaceMetadataKey] + if ns == "" { + ns = veleroNamespace + } + referenced[client.ObjectKey{Namespace: ns, Name: name}] = true + } + return referenced, nil +} diff --git a/internal/backupcontroller/velero_backup_deletion_test.go b/internal/backupcontroller/velero_backup_deletion_test.go new file mode 100644 index 000000000..f69606556 --- /dev/null +++ b/internal/backupcontroller/velero_backup_deletion_test.go @@ -0,0 +1,267 @@ +package backupcontroller + +import ( + "context" + "testing" + + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "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/client/fake" + + strategyv1alpha1 "github.com/cozystack/cozystack/api/backups/strategy/v1alpha1" + backupsv1alpha1 "github.com/cozystack/cozystack/api/backups/v1alpha1" + velerov1 "github.com/vmware-tanzu/velero/pkg/apis/velero/v1" +) + +const ( + failedJobNamespace = "tenant-acme" + failedJobName = "vm-backup" +) + +func newVeleroCleanupReconciler(t *testing.T, objs ...client.Object) (*BackupJobReconciler, client.Client) { + t.Helper() + c := fake.NewClientBuilder(). + WithScheme(newReconcilerScheme(t)). + WithObjects(objs...). + WithStatusSubresource(&backupsv1alpha1.BackupJob{}). + Build() + return &BackupJobReconciler{Client: c, Recorder: record.NewFakeRecorder(16)}, c +} + +func veleroCleanupJob(phase backupsv1alpha1.BackupJobPhase) *backupsv1alpha1.BackupJob { + started := metav1.Now() + return &backupsv1alpha1.BackupJob{ + ObjectMeta: metav1.ObjectMeta{Namespace: failedJobNamespace, Name: failedJobName}, + Status: backupsv1alpha1.BackupJobStatus{ + Phase: phase, + StartedAt: &started, + }, + } +} + +func ownedVeleroBackup(name string, phase velerov1.BackupPhase) *velerov1.Backup { + return &velerov1.Backup{ + ObjectMeta: metav1.ObjectMeta{ + Namespace: veleroNamespace, + Name: name, + Labels: map[string]string{ + backupsv1alpha1.OwningJobNameLabel: failedJobName, + backupsv1alpha1.OwningJobNamespaceLabel: failedJobNamespace, + }, + }, + Status: velerov1.BackupStatus{Phase: phase, FailureReason: "object store unreachable"}, + } +} + +func veleroCleanupResolved() *ResolvedBackupConfig { + apiGroup := strategyv1alpha1.GroupVersion.Group + return &ResolvedBackupConfig{StrategyRef: corev1.TypedLocalObjectReference{ + APIGroup: &apiGroup, Kind: strategyv1alpha1.VeleroStrategyKind, Name: "velero", + }} +} + +func veleroCleanupStrategy() *strategyv1alpha1.Velero { + return &strategyv1alpha1.Velero{ObjectMeta: metav1.ObjectMeta{Name: "velero"}} +} + +func listDeleteBackupRequests(t *testing.T, c client.Client) []velerov1.DeleteBackupRequest { + t.Helper() + l := &velerov1.DeleteBackupRequestList{} + if err := c.List(context.Background(), l, client.InNamespace(veleroNamespace)); err != nil { + t.Fatalf("list DeleteBackupRequests: %v", err) + } + return l.Items +} + +func reconcileFailedJob(t *testing.T, r *BackupJobReconciler) ctrl.Result { + t.Helper() + res, err := r.Reconcile(context.Background(), ctrl.Request{ + NamespacedName: types.NamespacedName{Namespace: failedJobNamespace, Name: failedJobName}, + }) + if err != nil { + t.Fatalf("Reconcile: %v", err) + } + return res +} + +func getCleanupJob(t *testing.T, c client.Client) *backupsv1alpha1.BackupJob { + t.Helper() + j := &backupsv1alpha1.BackupJob{} + if err := c.Get(context.Background(), types.NamespacedName{Namespace: failedJobNamespace, Name: failedJobName}, j); err != nil { + t.Fatalf("get BackupJob: %v", err) + } + return j +} + +// A Velero backup that ends Failed or PartiallyFailed produces no Backup, so +// the strategy must request its deletion itself, keep the failure message, and +// converge on a single request across reconciles. +func TestReconcileVelero_FailedBackupRequestsDeletion(t *testing.T) { + for _, phase := range []velerov1.BackupPhase{velerov1.BackupPhaseFailed, velerov1.BackupPhasePartiallyFailed} { + t.Run(string(phase), func(t *testing.T) { + vb := ownedVeleroBackup("tenant-acme.vm-backup-x7k2p", phase) + j := veleroCleanupJob(backupsv1alpha1.BackupJobPhaseRunning) + r, c := newVeleroCleanupReconciler(t, j, vb, veleroCleanupStrategy()) + + if _, err := r.reconcileVelero(context.Background(), j, veleroCleanupResolved()); err != nil { + t.Fatalf("reconcileVelero: %v", err) + } + + got := getCleanupJob(t, c) + if got.Status.Phase != backupsv1alpha1.BackupJobPhaseFailed { + t.Fatalf("expected BackupJob Failed, got %q", got.Status.Phase) + } + wantMsg := "Velero Backup failed with phase " + string(phase) + ": object store unreachable" + if got.Status.Message != wantMsg { + t.Errorf("message = %q, want %q", got.Status.Message, wantMsg) + } + + dbrs := listDeleteBackupRequests(t, c) + if len(dbrs) != 1 || dbrs[0].Spec.BackupName != vb.Name { + t.Fatalf("expected one DeleteBackupRequest for %s, got %+v", vb.Name, dbrs) + } + + reconcileFailedJob(t, r) + if n := len(listDeleteBackupRequests(t, c)); n != 1 { + t.Fatalf("a second reconcile must not add a request, got %d", n) + } + }) + } +} + +func TestReconcileVelero_CompletedBackupRequestsNoDeletion(t *testing.T) { + vb := ownedVeleroBackup("tenant-acme.vm-backup-x7k2p", velerov1.BackupPhaseCompleted) + j := veleroCleanupJob(backupsv1alpha1.BackupJobPhaseRunning) + r, c := newVeleroCleanupReconciler(t, j, vb, veleroCleanupStrategy()) + + if _, err := r.reconcileVelero(context.Background(), j, veleroCleanupResolved()); err != nil { + t.Fatalf("reconcileVelero: %v", err) + } + if got := getCleanupJob(t, c); got.Status.Phase != backupsv1alpha1.BackupJobPhaseSucceeded { + t.Fatalf("expected BackupJob Succeeded, got %q (%s)", got.Status.Phase, got.Status.Message) + } + reconcileFailedJob(t, r) + if dbrs := listDeleteBackupRequests(t, c); len(dbrs) != 0 { + t.Fatalf("a succeeded run must not request deletion, got %+v", dbrs) + } +} + +func TestReconcileVelero_SeveralVeleroBackupsFailWithMessage(t *testing.T) { + j := veleroCleanupJob(backupsv1alpha1.BackupJobPhaseRunning) + r, c := newVeleroCleanupReconciler(t, j, veleroCleanupStrategy(), + ownedVeleroBackup("vb-b", velerov1.BackupPhaseFailed), + ownedVeleroBackup("vb-a", velerov1.BackupPhaseCompleted)) + + if _, err := r.reconcileVelero(context.Background(), j, veleroCleanupResolved()); err != nil { + t.Fatalf("reconcileVelero: %v", err) + } + got := getCleanupJob(t, c) + if got.Status.Phase != backupsv1alpha1.BackupJobPhaseFailed || got.Status.CompletedAt == nil { + t.Fatalf("expected BackupJob Failed with completedAt, got %+v", got.Status) + } + if want := "more than one Velero Backup references this BackupJob: vb-a, vb-b"; got.Status.Message != want { + t.Errorf("message = %q, want %q", got.Status.Message, want) + } + + reconcileFailedJob(t, r) + if n := len(listDeleteBackupRequests(t, c)); n != 2 { + t.Fatalf("expected a request for each Velero backup, got %d", n) + } +} + +// A job that failed under a controller version without the cleanup still +// holds its Velero backup; reconciling it must request the deletion. +func TestReconcile_FailedJobLeftoverVeleroBackup(t *testing.T) { + vbName := "tenant-acme.vm-backup-x7k2p" + cases := []struct { + name string + veleroPhase velerov1.BackupPhase + jobPhase backupsv1alpha1.BackupJobPhase + existing []client.Object + wantNames []string + wantRequeue bool + }{ + { + name: "no request yet", + veleroPhase: velerov1.BackupPhasePartiallyFailed, + jobPhase: backupsv1alpha1.BackupJobPhaseFailed, + wantNames: []string{vbName}, + }, + { + name: "pending request from elsewhere", + veleroPhase: velerov1.BackupPhaseFailed, + jobPhase: backupsv1alpha1.BackupJobPhaseFailed, + existing: []client.Object{&velerov1.DeleteBackupRequest{ + ObjectMeta: metav1.ObjectMeta{Namespace: veleroNamespace, Name: vbName + "-abcde"}, + Spec: velerov1.DeleteBackupRequestSpec{BackupName: vbName}, + Status: velerov1.DeleteBackupRequestStatus{Phase: velerov1.DeleteBackupRequestPhaseInProgress}, + }}, + wantNames: []string{vbName + "-abcde"}, + }, + { + name: "own request processed with errors is replaced", + veleroPhase: velerov1.BackupPhaseFailed, + jobPhase: backupsv1alpha1.BackupJobPhaseFailed, + existing: []client.Object{&velerov1.DeleteBackupRequest{ + ObjectMeta: metav1.ObjectMeta{Namespace: veleroNamespace, Name: vbName}, + Spec: velerov1.DeleteBackupRequestSpec{BackupName: vbName}, + Status: velerov1.DeleteBackupRequestStatus{ + Phase: velerov1.DeleteBackupRequestPhaseProcessed, + Errors: []string{"backup is still in progress"}, + }, + }}, + wantNames: []string{vbName}, + }, + { + name: "completed backup owned by a Backup", + veleroPhase: velerov1.BackupPhaseCompleted, + jobPhase: backupsv1alpha1.BackupJobPhaseFailed, + existing: []client.Object{&backupsv1alpha1.Backup{ + ObjectMeta: metav1.ObjectMeta{Namespace: failedJobNamespace, Name: failedJobName}, + Spec: backupsv1alpha1.BackupSpec{DriverMetadata: map[string]string{ + veleroBackupNameMetadataKey: vbName, + veleroBackupNamespaceMetadataKey: veleroNamespace, + }}, + }}, + }, + { + name: "backup still running", + veleroPhase: velerov1.BackupPhaseInProgress, + jobPhase: backupsv1alpha1.BackupJobPhaseFailed, + wantRequeue: true, + }, + { + name: "succeeded job", + veleroPhase: velerov1.BackupPhaseCompleted, + jobPhase: backupsv1alpha1.BackupJobPhaseSucceeded, + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + objs := append([]client.Object{veleroCleanupJob(tc.jobPhase), ownedVeleroBackup(vbName, tc.veleroPhase)}, tc.existing...) + r, c := newVeleroCleanupReconciler(t, objs...) + + res := reconcileFailedJob(t, r) + if (res.RequeueAfter > 0) != tc.wantRequeue { + t.Errorf("RequeueAfter = %v, want requeue %v", res.RequeueAfter, tc.wantRequeue) + } + + dbrs := listDeleteBackupRequests(t, c) + if len(dbrs) != len(tc.wantNames) { + t.Fatalf("expected requests %v, got %+v", tc.wantNames, dbrs) + } + for i, want := range tc.wantNames { + if dbrs[i].Name != want || dbrs[i].Spec.BackupName != vbName { + t.Errorf("request %d = %s for %s, want %s for %s", i, dbrs[i].Name, dbrs[i].Spec.BackupName, want, vbName) + } + if dbrs[i].Status.Phase == velerov1.DeleteBackupRequestPhaseProcessed { + t.Errorf("request %s is the processed one, expected a fresh request", dbrs[i].Name) + } + } + }) + } +} diff --git a/internal/backupcontroller/velerostrategy_controller.go b/internal/backupcontroller/velerostrategy_controller.go index abedc97be..070d32d18 100644 --- a/internal/backupcontroller/velerostrategy_controller.go +++ b/internal/backupcontroller/velerostrategy_controller.go @@ -307,12 +307,12 @@ func (r *BackupJobReconciler) reconcileVelero(ctx context.Context, j *backupsv1a } if len(veleroBackupList.Items) > 1 { - logger.Error(fmt.Errorf("too many Velero backups for BackupJob"), "found more than one Velero Backup referencing a single BackupJob as owner") - j.Status.Phase = backupsv1alpha1.BackupJobPhaseFailed - if err := r.Status().Update(ctx, j); err != nil { - logger.Error(err, "failed to update BackupJob status") + names := make([]string, 0, len(veleroBackupList.Items)) + for _, vb := range veleroBackupList.Items { + names = append(names, vb.Name) } - return ctrl.Result{}, nil + sort.Strings(names) + return r.markBackupJobFailed(ctx, j, fmt.Sprintf("more than one Velero Backup references this BackupJob: %s", strings.Join(names, ", "))) } veleroBackup := veleroBackupList.Items[0].DeepCopy() @@ -361,6 +361,12 @@ func (r *BackupJobReconciler) reconcileVelero(ctx context.Context, j *backupsv1a // Step 5: On failure if phase == "Failed" || phase == "PartiallyFailed" { message := formatVeleroBackupFailureMessageForBackupJob(ctx, r.Client, veleroBackup) + // No Backup is created for a failed run, so nothing else deletes this + // Velero backup. A failed request is retried by + // deleteFailedJobVeleroBackups once the job is Failed. + if _, err := requestVeleroBackupDeletion(ctx, r.Client, veleroBackup.Namespace, veleroBackup.Name); err != nil { + logger.Error(err, "failed to request deletion of the failed Velero Backup", "name", veleroBackup.Name) + } return r.markBackupJobFailed(ctx, j, message) } From 887453c008f9e2b06a018b3456768dc1b93bdf9f Mon Sep 17 00:00:00 2001 From: Andrey Kolkov Date: Thu, 19 Nov 2026 20:44:11 +0700 Subject: [PATCH 12/17] fix(backups): keep completed Velero backups of failed BackupJobs The failed-job sweep treated a Completed Velero backup as deletable. A BackupJob can fail after Velero completed, when creating or recording its Backup fails transiently, and that Velero backup may be the only copy of a good backup. The sweep now deletes only Failed, PartiallyFailed and FailedValidation backups, also when several Velero backups reference one job, and it reads the Backups that may reference them through the uncached API reader, so a Backup the cache has not seen yet still protects its data. The Velero strategy no longer requests the deletion before it records the failure. If that status write failed, Velero removed the backup and the retried run created a new one, so the failure was lost. The deletion now comes only from the sweep, which runs on the reconcile that the persisted Failed phase triggers; the BackupJob watch has no predicate that drops status updates. Replacing a request that Velero processed with errors deletes it, and the backupstrategy-controller ClusterRole only allowed create, get, list and watch on deletebackuprequests. That Delete failed with 403, and since the Backup finalizer uses the same helper, a Backup deletion could get stuck on it. The rule now includes delete. Nothing watches DeleteBackupRequests, so the sweep did not run again after Velero processed a request with errors. A Failed job now requeues every 5 minutes while a failed Velero backup of it remains, which replaces such a request, and every minute while one is still running, instead of every 5 seconds. Unit tests cover a rejected Failed status write, Completed, Deleting and FailedValidation backups, a request processed with and without errors, the UID precondition on the replacement, a Backup visible only to the uncached reader, and API errors from the helper. Refs: #5355 Assisted-by: LLM Signed-off-by: Andrey Kolkov --- .../velero_backup_deletion.go | 91 +++--- .../velero_backup_deletion_test.go | 266 +++++++++++++----- .../velerostrategy_controller.go | 8 +- .../templates/rbac.yaml | 5 +- 4 files changed, 263 insertions(+), 107 deletions(-) diff --git a/internal/backupcontroller/velero_backup_deletion.go b/internal/backupcontroller/velero_backup_deletion.go index e93e6eee3..0e9de24b2 100644 --- a/internal/backupcontroller/velero_backup_deletion.go +++ b/internal/backupcontroller/velero_backup_deletion.go @@ -3,6 +3,7 @@ package backupcontroller import ( "context" "fmt" + "time" apierrors "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/api/meta" @@ -24,8 +25,9 @@ import ( // request. Nothing is created while any request for the backup is unprocessed, // or once one was processed without errors (Velero then removes the backup and // the remaining requests). A request of ours that Velero processed with errors -// is replaced: Velero keeps it for a day, and until then its name would block -// the retry. +// is deleted and created again: Velero keeps it for a day, and until then its +// name would block a new attempt. Velero does not retry a processed request, +// so a caller that needs the deletion to happen must call again later. func requestVeleroBackupDeletion(ctx context.Context, c client.Client, namespace, name string) (bool, error) { requests := &velerov1.DeleteBackupRequestList{} if err := c.List(ctx, requests, client.InNamespace(namespace)); err != nil { @@ -71,12 +73,27 @@ func requestVeleroBackupDeletion(ctx context.Context, c client.Client, namespace return true, nil } -// deleteFailedJobVeleroBackups requests deletion of the Velero backups a Failed -// BackupJob left behind. A failed run creates no Backup, and the Backup -// finalizer is the only other path that deletes Velero data, so without this -// the backup and its objects stay in the bucket until Velero's TTL expires -// them. It runs on every reconcile of a Failed job, which also clears backups -// left by controller versions that did not request the deletion. +const ( + // failedJobSweepRequeue is how often a Failed BackupJob is reconciled + // again while one of its Velero backups still waits for deletion. Nothing + // watches DeleteBackupRequests, so a request Velero processed with errors + // is only noticed, and replaced, on this requeue. + failedJobSweepRequeue = 5 * time.Minute + // failedJobRunningBackupRequeue is how often a Failed BackupJob is + // reconciled again while one of its Velero backups is still running. + // Velero rejects a deletion request for a running backup. + failedJobRunningBackupRequeue = time.Minute +) + +// deleteFailedJobVeleroBackups requests deletion of the failed Velero backups +// a Failed BackupJob left behind. A failed run creates no Backup, and the +// Backup finalizer is the only other path that deletes Velero data, so without +// this the backup and its objects stay in the bucket until Velero's TTL +// expires them. It runs on every reconcile of a Failed job, which also clears +// backups left by controller versions that did not request the deletion, and +// it requests the deletion only once the Failed phase is persisted: a request +// sent before that write would let a retried run start over with the failure +// already gone. func (r *BackupJobReconciler) deleteFailedJobVeleroBackups(ctx context.Context, j *backupsv1alpha1.BackupJob) (ctrl.Result, error) { logger := getLogger(ctx) @@ -94,30 +111,33 @@ func (r *BackupJobReconciler) deleteFailedJobVeleroBackups(ctx context.Context, return ctrl.Result{}, nil } - // A job can fail after its Backup was created: the status update that - // records the Backup is lost, and the retried create hits AlreadyExists. - // That Backup owns the Velero backup and deletes it itself. - referenced, err := r.veleroBackupsReferencedByBackups(ctx, j.Namespace) - if err != nil { - return ctrl.Result{}, err - } - - var running bool + var referenced map[client.ObjectKey]bool + var requeueAfter time.Duration for i := range veleroBackups.Items { vb := &veleroBackups.Items[i] + switch vb.Status.Phase { + case velerov1.BackupPhasePartiallyFailed, velerov1.BackupPhaseFailed, velerov1.BackupPhaseFailedValidation: + case velerov1.BackupPhaseCompleted, velerov1.BackupPhaseDeleting: + // A job can fail after Velero completed, when creating or + // recording its Backup fails. That Velero backup may be the only + // copy of good data, and a Backup that already references it + // deletes it itself, so a job-level failure never removes it. + continue + default: + requeueAfter = shorterRequeue(requeueAfter, failedJobRunningBackupRequeue) + continue + } + + if referenced == nil { + var err error + if referenced, err = r.veleroBackupsReferencedByBackups(ctx, j.Namespace); err != nil { + return ctrl.Result{}, err + } + } if referenced[client.ObjectKeyFromObject(vb)] { continue } - switch vb.Status.Phase { - case velerov1.BackupPhaseCompleted, velerov1.BackupPhasePartiallyFailed, - velerov1.BackupPhaseFailed, velerov1.BackupPhaseFailedValidation: - case velerov1.BackupPhaseDeleting: - continue - default: - // Velero rejects a request for a backup that is still running. - running = true - continue - } + created, err := requestVeleroBackupDeletion(ctx, r.Client, vb.Namespace, vb.Name) if err != nil { return ctrl.Result{}, err @@ -126,16 +146,23 @@ func (r *BackupJobReconciler) deleteFailedJobVeleroBackups(ctx context.Context, logger.Info("requested deletion of the Velero Backup of a failed BackupJob", "backupjob", j.Name, "namespace", j.Namespace, "veleroBackup", vb.Name) } + requeueAfter = shorterRequeue(requeueAfter, failedJobSweepRequeue) } - if running { - return ctrl.Result{RequeueAfter: defaultActiveJobPollingInterval}, nil - } - return ctrl.Result{}, nil + return ctrl.Result{RequeueAfter: requeueAfter}, nil } +func shorterRequeue(current, next time.Duration) time.Duration { + if current == 0 || next < current { + return next + } + return current +} + +// veleroBackupsReferencedByBackups reads Backups past the cache: a Backup the +// cache has not seen yet must still protect its Velero backup from deletion. func (r *BackupJobReconciler) veleroBackupsReferencedByBackups(ctx context.Context, namespace string) (map[client.ObjectKey]bool, error) { backups := &backupsv1alpha1.BackupList{} - if err := r.List(ctx, backups, client.InNamespace(namespace)); err != nil { + if err := r.apiReader().List(ctx, backups, client.InNamespace(namespace)); err != nil { return nil, fmt.Errorf("failed to list Backups in %s: %w", namespace, err) } referenced := map[client.ObjectKey]bool{} diff --git a/internal/backupcontroller/velero_backup_deletion_test.go b/internal/backupcontroller/velero_backup_deletion_test.go index f69606556..d283e6262 100644 --- a/internal/backupcontroller/velero_backup_deletion_test.go +++ b/internal/backupcontroller/velero_backup_deletion_test.go @@ -2,15 +2,19 @@ package backupcontroller import ( "context" + "errors" "testing" 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/runtime/schema" "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/client/fake" + "sigs.k8s.io/controller-runtime/pkg/client/interceptor" strategyv1alpha1 "github.com/cozystack/cozystack/api/backups/strategy/v1alpha1" backupsv1alpha1 "github.com/cozystack/cozystack/api/backups/v1alpha1" @@ -20,15 +24,24 @@ import ( const ( failedJobNamespace = "tenant-acme" failedJobName = "vm-backup" + failedVeleroBackup = "tenant-acme.vm-backup-x7k2p" ) +func newVeleroCleanupClient(t *testing.T, funcs *interceptor.Funcs, objs ...client.Object) client.Client { + t.Helper() + b := fake.NewClientBuilder(). + WithScheme(newReconcilerScheme(t)). + WithObjects(objs...). + WithStatusSubresource(&backupsv1alpha1.BackupJob{}) + if funcs != nil { + b = b.WithInterceptorFuncs(*funcs) + } + return b.Build() +} + func newVeleroCleanupReconciler(t *testing.T, objs ...client.Object) (*BackupJobReconciler, client.Client) { t.Helper() - c := fake.NewClientBuilder(). - WithScheme(newReconcilerScheme(t)). - WithObjects(objs...). - WithStatusSubresource(&backupsv1alpha1.BackupJob{}). - Build() + c := newVeleroCleanupClient(t, nil, objs...) return &BackupJobReconciler{Client: c, Recorder: record.NewFakeRecorder(16)}, c } @@ -57,6 +70,24 @@ func ownedVeleroBackup(name string, phase velerov1.BackupPhase) *velerov1.Backup } } +func referencingBackup(veleroBackupName string) *backupsv1alpha1.Backup { + return &backupsv1alpha1.Backup{ + ObjectMeta: metav1.ObjectMeta{Namespace: failedJobNamespace, Name: failedJobName}, + Spec: backupsv1alpha1.BackupSpec{DriverMetadata: map[string]string{ + veleroBackupNameMetadataKey: veleroBackupName, + veleroBackupNamespaceMetadataKey: veleroNamespace, + }}, + } +} + +func deleteRequest(name string, phase velerov1.DeleteBackupRequestPhase, errs ...string) *velerov1.DeleteBackupRequest { + return &velerov1.DeleteBackupRequest{ + ObjectMeta: metav1.ObjectMeta{Namespace: veleroNamespace, Name: name, UID: types.UID(name + "-uid")}, + Spec: velerov1.DeleteBackupRequestSpec{BackupName: failedVeleroBackup}, + Status: velerov1.DeleteBackupRequestStatus{Phase: phase, Errors: errs}, + } +} + func veleroCleanupResolved() *ResolvedBackupConfig { apiGroup := strategyv1alpha1.GroupVersion.Group return &ResolvedBackupConfig{StrategyRef: corev1.TypedLocalObjectReference{ @@ -77,7 +108,7 @@ func listDeleteBackupRequests(t *testing.T, c client.Client) []velerov1.DeleteBa return l.Items } -func reconcileFailedJob(t *testing.T, r *BackupJobReconciler) ctrl.Result { +func reconcileCleanupJob(t *testing.T, r *BackupJobReconciler) ctrl.Result { t.Helper() res, err := r.Reconcile(context.Background(), ctrl.Request{ NamespacedName: types.NamespacedName{Namespace: failedJobNamespace, Name: failedJobName}, @@ -97,20 +128,18 @@ func getCleanupJob(t *testing.T, c client.Client) *backupsv1alpha1.BackupJob { return j } -// A Velero backup that ends Failed or PartiallyFailed produces no Backup, so -// the strategy must request its deletion itself, keep the failure message, and -// converge on a single request across reconciles. -func TestReconcileVelero_FailedBackupRequestsDeletion(t *testing.T) { +// A Velero backup that ends Failed or PartiallyFailed produces no Backup. The +// run keeps its failure message, and the deletion is requested by the +// reconcile that follows the persisted Failed phase, once. +func TestReconcileVelero_FailedBackupRequestsDeletionAfterFailedIsPersisted(t *testing.T) { for _, phase := range []velerov1.BackupPhase{velerov1.BackupPhaseFailed, velerov1.BackupPhasePartiallyFailed} { t.Run(string(phase), func(t *testing.T) { - vb := ownedVeleroBackup("tenant-acme.vm-backup-x7k2p", phase) j := veleroCleanupJob(backupsv1alpha1.BackupJobPhaseRunning) - r, c := newVeleroCleanupReconciler(t, j, vb, veleroCleanupStrategy()) + r, c := newVeleroCleanupReconciler(t, j, ownedVeleroBackup(failedVeleroBackup, phase), veleroCleanupStrategy()) if _, err := r.reconcileVelero(context.Background(), j, veleroCleanupResolved()); err != nil { t.Fatalf("reconcileVelero: %v", err) } - got := getCleanupJob(t, c) if got.Status.Phase != backupsv1alpha1.BackupJobPhaseFailed { t.Fatalf("expected BackupJob Failed, got %q", got.Status.Phase) @@ -119,13 +148,19 @@ func TestReconcileVelero_FailedBackupRequestsDeletion(t *testing.T) { if got.Status.Message != wantMsg { t.Errorf("message = %q, want %q", got.Status.Message, wantMsg) } - - dbrs := listDeleteBackupRequests(t, c) - if len(dbrs) != 1 || dbrs[0].Spec.BackupName != vb.Name { - t.Fatalf("expected one DeleteBackupRequest for %s, got %+v", vb.Name, dbrs) + if dbrs := listDeleteBackupRequests(t, c); len(dbrs) != 0 { + t.Fatalf("deletion must wait for the next reconcile, got %+v", dbrs) } - reconcileFailedJob(t, r) + if res := reconcileCleanupJob(t, r); res.RequeueAfter != failedJobSweepRequeue { + t.Errorf("RequeueAfter = %v, want %v", res.RequeueAfter, failedJobSweepRequeue) + } + dbrs := listDeleteBackupRequests(t, c) + if len(dbrs) != 1 || dbrs[0].Name != failedVeleroBackup || dbrs[0].Spec.BackupName != failedVeleroBackup { + t.Fatalf("expected one DeleteBackupRequest for %s, got %+v", failedVeleroBackup, dbrs) + } + + reconcileCleanupJob(t, r) if n := len(listDeleteBackupRequests(t, c)); n != 1 { t.Fatalf("a second reconcile must not add a request, got %d", n) } @@ -133,10 +168,35 @@ func TestReconcileVelero_FailedBackupRequestsDeletion(t *testing.T) { } } -func TestReconcileVelero_CompletedBackupRequestsNoDeletion(t *testing.T) { - vb := ownedVeleroBackup("tenant-acme.vm-backup-x7k2p", velerov1.BackupPhaseCompleted) +// If the Failed phase cannot be written, the run is retried and must still +// find its Velero backup to report the failure from. +func TestReconcileVelero_FailedStatusWriteErrorRequestsNoDeletion(t *testing.T) { j := veleroCleanupJob(backupsv1alpha1.BackupJobPhaseRunning) - r, c := newVeleroCleanupReconciler(t, j, vb, veleroCleanupStrategy()) + funcs := &interceptor.Funcs{ + SubResourceUpdate: func(ctx context.Context, c client.Client, sub string, obj client.Object, opts ...client.SubResourceUpdateOption) error { + if bj, ok := obj.(*backupsv1alpha1.BackupJob); ok && bj.Status.Phase == backupsv1alpha1.BackupJobPhaseFailed { + return apierrors.NewServiceUnavailable("etcd timeout") + } + return c.SubResource(sub).Update(ctx, obj, opts...) + }, + } + c := newVeleroCleanupClient(t, funcs, j, ownedVeleroBackup(failedVeleroBackup, velerov1.BackupPhaseFailed), veleroCleanupStrategy()) + r := &BackupJobReconciler{Client: c, Recorder: record.NewFakeRecorder(16)} + + if _, err := r.reconcileVelero(context.Background(), j, veleroCleanupResolved()); err == nil { + t.Fatal("expected the status write error to be returned") + } + if got := getCleanupJob(t, c); got.Status.Phase == backupsv1alpha1.BackupJobPhaseFailed { + t.Fatalf("status write was rejected, got phase %q", got.Status.Phase) + } + if dbrs := listDeleteBackupRequests(t, c); len(dbrs) != 0 { + t.Fatalf("no deletion may be requested before Failed is persisted, got %+v", dbrs) + } +} + +func TestReconcileVelero_CompletedBackupRequestsNoDeletion(t *testing.T) { + j := veleroCleanupJob(backupsv1alpha1.BackupJobPhaseRunning) + r, c := newVeleroCleanupReconciler(t, j, ownedVeleroBackup(failedVeleroBackup, velerov1.BackupPhaseCompleted), veleroCleanupStrategy()) if _, err := r.reconcileVelero(context.Background(), j, veleroCleanupResolved()); err != nil { t.Fatalf("reconcileVelero: %v", err) @@ -144,13 +204,13 @@ func TestReconcileVelero_CompletedBackupRequestsNoDeletion(t *testing.T) { if got := getCleanupJob(t, c); got.Status.Phase != backupsv1alpha1.BackupJobPhaseSucceeded { t.Fatalf("expected BackupJob Succeeded, got %q (%s)", got.Status.Phase, got.Status.Message) } - reconcileFailedJob(t, r) + reconcileCleanupJob(t, r) if dbrs := listDeleteBackupRequests(t, c); len(dbrs) != 0 { t.Fatalf("a succeeded run must not request deletion, got %+v", dbrs) } } -func TestReconcileVelero_SeveralVeleroBackupsFailWithMessage(t *testing.T) { +func TestReconcileVelero_SeveralVeleroBackupsKeepCompletedOne(t *testing.T) { j := veleroCleanupJob(backupsv1alpha1.BackupJobPhaseRunning) r, c := newVeleroCleanupReconciler(t, j, veleroCleanupStrategy(), ownedVeleroBackup("vb-b", velerov1.BackupPhaseFailed), @@ -167,87 +227,111 @@ func TestReconcileVelero_SeveralVeleroBackupsFailWithMessage(t *testing.T) { t.Errorf("message = %q, want %q", got.Status.Message, want) } - reconcileFailedJob(t, r) - if n := len(listDeleteBackupRequests(t, c)); n != 2 { - t.Fatalf("expected a request for each Velero backup, got %d", n) + reconcileCleanupJob(t, r) + dbrs := listDeleteBackupRequests(t, c) + if len(dbrs) != 1 || dbrs[0].Spec.BackupName != "vb-b" { + t.Fatalf("expected a request for the failed vb-b only, got %+v", dbrs) } } -// A job that failed under a controller version without the cleanup still -// holds its Velero backup; reconciling it must request the deletion. -func TestReconcile_FailedJobLeftoverVeleroBackup(t *testing.T) { - vbName := "tenant-acme.vm-backup-x7k2p" +// Reconciling a Failed BackupJob, including one that failed under a version +// without the cleanup, requests deletion of its failed Velero backups only. +func TestReconcile_FailedJobVeleroBackupSweep(t *testing.T) { cases := []struct { name string veleroPhase velerov1.BackupPhase jobPhase backupsv1alpha1.BackupJobPhase existing []client.Object + // Backups visible to the uncached reader only. + uncached []client.Object wantNames []string - wantRequeue bool + wantPhase velerov1.DeleteBackupRequestPhase + wantRequeue ctrl.Result }{ { - name: "no request yet", + name: "PartiallyFailed without a request", veleroPhase: velerov1.BackupPhasePartiallyFailed, jobPhase: backupsv1alpha1.BackupJobPhaseFailed, - wantNames: []string{vbName}, + wantNames: []string{failedVeleroBackup}, + wantRequeue: ctrl.Result{RequeueAfter: failedJobSweepRequeue}, + }, + { + name: "FailedValidation is deleted", + veleroPhase: velerov1.BackupPhaseFailedValidation, + jobPhase: backupsv1alpha1.BackupJobPhaseFailed, + wantNames: []string{failedVeleroBackup}, + wantRequeue: ctrl.Result{RequeueAfter: failedJobSweepRequeue}, }, { name: "pending request from elsewhere", veleroPhase: velerov1.BackupPhaseFailed, jobPhase: backupsv1alpha1.BackupJobPhaseFailed, - existing: []client.Object{&velerov1.DeleteBackupRequest{ - ObjectMeta: metav1.ObjectMeta{Namespace: veleroNamespace, Name: vbName + "-abcde"}, - Spec: velerov1.DeleteBackupRequestSpec{BackupName: vbName}, - Status: velerov1.DeleteBackupRequestStatus{Phase: velerov1.DeleteBackupRequestPhaseInProgress}, - }}, - wantNames: []string{vbName + "-abcde"}, + existing: []client.Object{deleteRequest(failedVeleroBackup+"-abcde", velerov1.DeleteBackupRequestPhaseInProgress)}, + wantNames: []string{failedVeleroBackup + "-abcde"}, + wantPhase: velerov1.DeleteBackupRequestPhaseInProgress, + wantRequeue: ctrl.Result{RequeueAfter: failedJobSweepRequeue}, }, { name: "own request processed with errors is replaced", veleroPhase: velerov1.BackupPhaseFailed, jobPhase: backupsv1alpha1.BackupJobPhaseFailed, - existing: []client.Object{&velerov1.DeleteBackupRequest{ - ObjectMeta: metav1.ObjectMeta{Namespace: veleroNamespace, Name: vbName}, - Spec: velerov1.DeleteBackupRequestSpec{BackupName: vbName}, - Status: velerov1.DeleteBackupRequestStatus{ - Phase: velerov1.DeleteBackupRequestPhaseProcessed, - Errors: []string{"backup is still in progress"}, - }, - }}, - wantNames: []string{vbName}, + existing: []client.Object{deleteRequest(failedVeleroBackup, velerov1.DeleteBackupRequestPhaseProcessed, "backup is still in progress")}, + wantNames: []string{failedVeleroBackup}, + wantRequeue: ctrl.Result{RequeueAfter: failedJobSweepRequeue}, }, { - name: "completed backup owned by a Backup", + name: "request processed without errors is kept", + veleroPhase: velerov1.BackupPhaseFailed, + jobPhase: backupsv1alpha1.BackupJobPhaseFailed, + existing: []client.Object{deleteRequest(failedVeleroBackup, velerov1.DeleteBackupRequestPhaseProcessed)}, + wantNames: []string{failedVeleroBackup}, + wantPhase: velerov1.DeleteBackupRequestPhaseProcessed, + wantRequeue: ctrl.Result{RequeueAfter: failedJobSweepRequeue}, + }, + { + name: "Completed is never deleted", veleroPhase: velerov1.BackupPhaseCompleted, jobPhase: backupsv1alpha1.BackupJobPhaseFailed, - existing: []client.Object{&backupsv1alpha1.Backup{ - ObjectMeta: metav1.ObjectMeta{Namespace: failedJobNamespace, Name: failedJobName}, - Spec: backupsv1alpha1.BackupSpec{DriverMetadata: map[string]string{ - veleroBackupNameMetadataKey: vbName, - veleroBackupNamespaceMetadataKey: veleroNamespace, - }}, - }}, }, { - name: "backup still running", + name: "Deleting is skipped", + veleroPhase: velerov1.BackupPhaseDeleting, + jobPhase: backupsv1alpha1.BackupJobPhaseFailed, + }, + { + name: "failed backup referenced by a Backup the cache has not seen", + veleroPhase: velerov1.BackupPhaseFailed, + jobPhase: backupsv1alpha1.BackupJobPhaseFailed, + uncached: []client.Object{referencingBackup(failedVeleroBackup)}, + }, + { + name: "running backup", veleroPhase: velerov1.BackupPhaseInProgress, jobPhase: backupsv1alpha1.BackupJobPhaseFailed, - wantRequeue: true, + wantRequeue: ctrl.Result{RequeueAfter: failedJobRunningBackupRequeue}, + }, + { + name: "new backup", + veleroPhase: "", + jobPhase: backupsv1alpha1.BackupJobPhaseFailed, + wantRequeue: ctrl.Result{RequeueAfter: failedJobRunningBackupRequeue}, }, { name: "succeeded job", - veleroPhase: velerov1.BackupPhaseCompleted, + veleroPhase: velerov1.BackupPhaseFailed, jobPhase: backupsv1alpha1.BackupJobPhaseSucceeded, }, } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { - objs := append([]client.Object{veleroCleanupJob(tc.jobPhase), ownedVeleroBackup(vbName, tc.veleroPhase)}, tc.existing...) + objs := append([]client.Object{veleroCleanupJob(tc.jobPhase), ownedVeleroBackup(failedVeleroBackup, tc.veleroPhase)}, tc.existing...) r, c := newVeleroCleanupReconciler(t, objs...) + if tc.uncached != nil { + r.APIReader = newVeleroCleanupClient(t, nil, tc.uncached...) + } - res := reconcileFailedJob(t, r) - if (res.RequeueAfter > 0) != tc.wantRequeue { - t.Errorf("RequeueAfter = %v, want requeue %v", res.RequeueAfter, tc.wantRequeue) + if res := reconcileCleanupJob(t, r); res != tc.wantRequeue { + t.Errorf("Result = %+v, want %+v", res, tc.wantRequeue) } dbrs := listDeleteBackupRequests(t, c) @@ -255,13 +339,61 @@ func TestReconcile_FailedJobLeftoverVeleroBackup(t *testing.T) { t.Fatalf("expected requests %v, got %+v", tc.wantNames, dbrs) } for i, want := range tc.wantNames { - if dbrs[i].Name != want || dbrs[i].Spec.BackupName != vbName { - t.Errorf("request %d = %s for %s, want %s for %s", i, dbrs[i].Name, dbrs[i].Spec.BackupName, want, vbName) + if dbrs[i].Name != want || dbrs[i].Spec.BackupName != failedVeleroBackup { + t.Errorf("request %d = %s for %s, want %s for %s", i, dbrs[i].Name, dbrs[i].Spec.BackupName, want, failedVeleroBackup) } - if dbrs[i].Status.Phase == velerov1.DeleteBackupRequestPhaseProcessed { - t.Errorf("request %s is the processed one, expected a fresh request", dbrs[i].Name) + if dbrs[i].Status.Phase != tc.wantPhase { + t.Errorf("request %s phase = %q, want %q", dbrs[i].Name, dbrs[i].Status.Phase, tc.wantPhase) } } }) } } + +func TestRequestVeleroBackupDeletion_ReplacesByUID(t *testing.T) { + stale := deleteRequest(failedVeleroBackup, velerov1.DeleteBackupRequestPhaseProcessed, "backup storage location unavailable") + var preconditionUID types.UID + funcs := &interceptor.Funcs{ + Delete: func(ctx context.Context, c client.WithWatch, obj client.Object, opts ...client.DeleteOption) error { + do := &client.DeleteOptions{} + do.ApplyOptions(opts) + if do.Preconditions != nil && do.Preconditions.UID != nil { + preconditionUID = *do.Preconditions.UID + } + return c.Delete(ctx, obj, opts...) + }, + } + c := newVeleroCleanupClient(t, funcs, stale) + created, err := requestVeleroBackupDeletion(context.Background(), c, veleroNamespace, failedVeleroBackup) + if err != nil || !created { + t.Fatalf("requestVeleroBackupDeletion = (%v, %v), want (true, nil)", created, err) + } + if preconditionUID != stale.UID { + t.Errorf("Delete precondition UID = %q, want %q", preconditionUID, stale.UID) + } +} + +func TestRequestVeleroBackupDeletion_ReturnsAPIErrors(t *testing.T) { + forbidden := apierrors.NewForbidden(schema.GroupResource{Group: "velero.io", Resource: "deletebackuprequests"}, failedVeleroBackup, errors.New("denied")) + cases := map[string]interceptor.Funcs{ + "list": {List: func(context.Context, client.WithWatch, client.ObjectList, ...client.ListOption) error { + return forbidden + }}, + "create": {Create: func(context.Context, client.WithWatch, client.Object, ...client.CreateOption) error { + return forbidden + }}, + "delete": {Delete: func(context.Context, client.WithWatch, client.Object, ...client.DeleteOption) error { + return forbidden + }}, + } + for name, funcs := range cases { + t.Run(name, func(t *testing.T) { + c := newVeleroCleanupClient(t, &funcs, + deleteRequest(failedVeleroBackup, velerov1.DeleteBackupRequestPhaseProcessed, "backup storage location unavailable")) + created, err := requestVeleroBackupDeletion(context.Background(), c, veleroNamespace, failedVeleroBackup) + if created || !apierrors.IsForbidden(err) { + t.Fatalf("requestVeleroBackupDeletion = (%v, %v), want a Forbidden error", created, err) + } + }) + } +} diff --git a/internal/backupcontroller/velerostrategy_controller.go b/internal/backupcontroller/velerostrategy_controller.go index 070d32d18..066802b0d 100644 --- a/internal/backupcontroller/velerostrategy_controller.go +++ b/internal/backupcontroller/velerostrategy_controller.go @@ -360,13 +360,9 @@ func (r *BackupJobReconciler) reconcileVelero(ctx context.Context, j *backupsv1a // Step 5: On failure if phase == "Failed" || phase == "PartiallyFailed" { + // The Velero backup is deleted by deleteFailedJobVeleroBackups once + // the Failed phase written here triggers the next reconcile. message := formatVeleroBackupFailureMessageForBackupJob(ctx, r.Client, veleroBackup) - // No Backup is created for a failed run, so nothing else deletes this - // Velero backup. A failed request is retried by - // deleteFailedJobVeleroBackups once the job is Failed. - if _, err := requestVeleroBackupDeletion(ctx, r.Client, veleroBackup.Namespace, veleroBackup.Name); err != nil { - logger.Error(err, "failed to request deletion of the failed Velero Backup", "name", veleroBackup.Name) - } return r.markBackupJobFailed(ctx, j, message) } diff --git a/packages/system/backupstrategy-controller/templates/rbac.yaml b/packages/system/backupstrategy-controller/templates/rbac.yaml index 883fd1fe9..b7b872d9e 100644 --- a/packages/system/backupstrategy-controller/templates/rbac.yaml +++ b/packages/system/backupstrategy-controller/templates/rbac.yaml @@ -108,10 +108,11 @@ rules: - apiGroups: ["velero.io"] resources: ["backupstoragelocations"] verbs: ["get"] -# Velero DeleteBackupRequest: used by BackupReconciler to delete Velero backups with their storage data +# Velero DeleteBackupRequest: used to delete Velero backups with their storage +# data. delete replaces a request Velero processed with errors. - apiGroups: ["velero.io"] resources: ["deletebackuprequests"] - verbs: ["create", "get", "list", "watch"] + verbs: ["create", "get", "list", "watch", "delete"] # Namespaces: validate target namespace exists for cross-namespace restore # controller-runtime cache requires list/watch for any resource accessed via r.Get() - apiGroups: [""] From 421dc2a0a799a79fbb8a09af49dad9f6d1dcccda Mon Sep 17 00:00:00 2001 From: Andrey Kolkov Date: Thu, 19 Nov 2026 20:44:54 +0700 Subject: [PATCH 13/17] test(dashboard): require the exact hint in the e2e redirect check The case pattern *kc_idp_hint=e2e-idp* also accepted e2e-idp-other and xkc_idp_hint=e2e-idp. Match the parameter as a whole: preceded by &, followed by & or the end of the URL. Assisted-By: LLM Signed-off-by: Andrey Kolkov --- hack/e2e-install-cozystack.bats | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/hack/e2e-install-cozystack.bats b/hack/e2e-install-cozystack.bats index ff2b128ab..4fadd7316 100644 --- a/hack/e2e-install-cozystack.bats +++ b/hack/e2e-install-cozystack.bats @@ -386,7 +386,7 @@ wait "$pf_pid" 2>/dev/null || true case "$hinted" in - https://keycloak.example.org/realms/cozy/protocol/openid-connect/auth\?*kc_idp_hint=e2e-idp*) ;; + https://keycloak.example.org/realms/cozy/protocol/openid-connect/auth\?*\&kc_idp_hint=e2e-idp\&*|https://keycloak.example.org/realms/cozy/protocol/openid-connect/auth\?*\&kc_idp_hint=e2e-idp) ;; *) echo "=== /oauth2/start?kc_idp_hint=e2e-idp did not redirect to the cozy realm with the hint ===" echo "Location: ${hinted:-}" From 73df99b77d4cb44c94f9c9b716751073b511e417 Mon Sep 17 00:00:00 2001 From: Andrey Kolkov Date: Thu, 19 Nov 2026 20:56:45 +0700 Subject: [PATCH 14/17] fix(backups): retry stuck Velero deletions of failed BackupJobs and report them Velero marks a backup Deleting before it removes the data and leaves it in that phase when removing the data fails, with the deletion request processed with errors. The failed-job sweep skipped Deleting backups and did not requeue for them, so their data stayed in the bucket until Velero's TTL. Deleting backups now go through the same request path: a pending request is left alone, and a processed one of ours is replaced. A request of ours that Velero processed without errors is also replaced when the backup still exists, for example after the BSL sync brought it back. Otherwise the request name blocked a new attempt until Velero garbage-collects processed requests a day later. When Velero can never carry out the deletion, because the backup storage location is missing, read-only or unavailable, the sweep replaced the request every 5 minutes without any sign of it. Each replacement now emits a VeleroBackupDeletionFailed Warning event on the BackupJob with Velero's status.errors, and doubles the requeue interval from 5 minutes up to 1 hour. The count is kept in the backups.cozystack.io/velero-deletion-retries annotation, because the replaced request is gone and a requeue carries no state. The controller's ClusterRole already allows patching BackupJobs. Unit tests cover a Deleting backup with a pending request and with an errored one, a cleanly processed request whose backup still exists, an errored request under a foreign name that is left alone, three consecutive failed deletions (three events, 10m, 20m and 40m requeues, the 1h cap), and a cluster without the Velero CRDs. Refs: #5355 Assisted-by: LLM Signed-off-by: Andrey Kolkov --- .../backupcontroller/backup_controller.go | 4 +- .../backupcontroller/backupjob_controller.go | 11 +- .../velero_backup_deletion.go | 141 +++++++++--- .../velero_backup_deletion_test.go | 209 +++++++++++++----- 4 files changed, 273 insertions(+), 92 deletions(-) diff --git a/internal/backupcontroller/backup_controller.go b/internal/backupcontroller/backup_controller.go index 1677f5714..402c6103e 100644 --- a/internal/backupcontroller/backup_controller.go +++ b/internal/backupcontroller/backup_controller.go @@ -248,11 +248,11 @@ func (r *BackupReconciler) cleanupVeleroBackup(ctx context.Context, backup *back return fmt.Errorf("failed to get Velero backup %s/%s: %w", veleroBackupNamespace, veleroBackupName, err) } - created, err := requestVeleroBackupDeletion(ctx, r.Client, veleroBackupNamespace, veleroBackupName) + req, err := requestVeleroBackupDeletion(ctx, r.Client, veleroBackupNamespace, veleroBackupName) if err != nil { return err } - if created { + if req.created { logger.Info("created DeleteBackupRequest for Velero backup", "name", veleroBackupName, "namespace", veleroBackupNamespace) } else { diff --git a/internal/backupcontroller/backupjob_controller.go b/internal/backupcontroller/backupjob_controller.go index a86243c94..c5084f9be 100644 --- a/internal/backupcontroller/backupjob_controller.go +++ b/internal/backupcontroller/backupjob_controller.go @@ -60,11 +60,12 @@ func (r *BackupJobReconciler) Reconcile(ctx context.Context, req ctrl.Request) ( return ctrl.Result{}, err } - // Skip terminal BackupJobs: a Succeeded/Failed run must not keep - // projecting Secrets or re-running dispatch on every requeue, which - // would otherwise materialise cozy-backups-creds in tenant namespaces - // long after the BackupJob is done and pin needless work on the - // apiserver. + // A terminal BackupJob never reaches credentials projection or strategy + // dispatch: a finished run must not keep projecting Secrets or + // re-running dispatch on every requeue, which would otherwise + // materialise cozy-backups-creds in tenant namespaces long after the + // BackupJob is done and pin needless work on the apiserver. A Failed + // one only has the failed Velero backups it left behind deleted. if j.Status.Phase == backupsv1alpha1.BackupJobPhaseFailed { logger.V(1).Info("BackupJob already terminal, cleaning up its Velero Backups", "phase", j.Status.Phase) return r.deleteFailedJobVeleroBackups(ctx, j) diff --git a/internal/backupcontroller/velero_backup_deletion.go b/internal/backupcontroller/velero_backup_deletion.go index 0e9de24b2..b22ba9e5c 100644 --- a/internal/backupcontroller/velero_backup_deletion.go +++ b/internal/backupcontroller/velero_backup_deletion.go @@ -3,8 +3,12 @@ package backupcontroller import ( "context" "fmt" + "strconv" + "strings" "time" + corev1 "k8s.io/api/core/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/api/meta" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -16,42 +20,56 @@ import ( velerov1 "github.com/vmware-tanzu/velero/pkg/apis/velero/v1" ) +// veleroDeletionRequest is what requestVeleroBackupDeletion did. +type veleroDeletionRequest struct { + created bool + // replaced is a request of ours that Velero had processed and that this + // call deleted before creating a new one. + replaced *velerov1.DeleteBackupRequest +} + // requestVeleroBackupDeletion asks Velero to delete a backup together with its // data in the object store. Deleting the backup.velero.io object directly only // removes the Kubernetes object, and the BSL sync recreates it from the object -// store. +// store. Callers call it only for a backup that still exists. // // The request is named after the backup, so repeated calls converge on one -// request. Nothing is created while any request for the backup is unprocessed, -// or once one was processed without errors (Velero then removes the backup and -// the remaining requests). A request of ours that Velero processed with errors -// is deleted and created again: Velero keeps it for a day, and until then its -// name would block a new attempt. Velero does not retry a processed request, -// so a caller that needs the deletion to happen must call again later. -func requestVeleroBackupDeletion(ctx context.Context, c client.Client, namespace, name string) (bool, error) { +// request. Nothing is created while any request for the backup is +// unprocessed. A request of ours that Velero has processed is deleted and +// created again: the backup still exists, so the deletion failed, or the BSL +// sync brought the backup back, and Velero keeps a processed request for a +// day, during which its name would block a new attempt. Velero does not retry +// a processed request, so a caller that needs the deletion to happen must +// call again later. +func requestVeleroBackupDeletion(ctx context.Context, c client.Client, namespace, name string) (veleroDeletionRequest, error) { + var res veleroDeletionRequest requests := &velerov1.DeleteBackupRequestList{} if err := c.List(ctx, requests, client.InNamespace(namespace)); err != nil { - return false, fmt.Errorf("failed to list DeleteBackupRequests in %s: %w", namespace, err) + return res, fmt.Errorf("failed to list DeleteBackupRequests in %s: %w", namespace, err) } - var failed *velerov1.DeleteBackupRequest + var own *velerov1.DeleteBackupRequest for i := range requests.Items { dbr := &requests.Items[i] if dbr.Spec.BackupName != name { continue } - if dbr.Status.Phase != velerov1.DeleteBackupRequestPhaseProcessed || len(dbr.Status.Errors) == 0 { - return false, nil + if dbr.Status.Phase != velerov1.DeleteBackupRequestPhaseProcessed { + return res, nil } if dbr.Name == name { - failed = dbr + own = dbr } } - if failed != nil { + if own != nil { // The UID precondition keeps a stale cache from deleting a request // that has already been replaced. - err := c.Delete(ctx, failed, client.Preconditions{UID: &failed.UID}) - if err != nil && !apierrors.IsNotFound(err) && !apierrors.IsConflict(err) { - return false, fmt.Errorf("failed to delete failed DeleteBackupRequest %s/%s: %w", namespace, name, err) + err := c.Delete(ctx, own, client.Preconditions{UID: &own.UID}) + switch { + case err == nil: + res.replaced = own + case apierrors.IsNotFound(err), apierrors.IsConflict(err): + default: + return res, fmt.Errorf("failed to delete processed DeleteBackupRequest %s/%s: %w", namespace, name, err) } } @@ -66,23 +84,31 @@ func requestVeleroBackupDeletion(ctx context.Context, c client.Client, namespace } if err := c.Create(ctx, dbr); err != nil { if apierrors.IsAlreadyExists(err) { - return false, nil + return res, nil } - return false, fmt.Errorf("failed to create DeleteBackupRequest for %s/%s: %w", namespace, name, err) + return res, fmt.Errorf("failed to create DeleteBackupRequest for %s/%s: %w", namespace, name, err) } - return true, nil + res.created = true + return res, nil } const ( // failedJobSweepRequeue is how often a Failed BackupJob is reconciled // again while one of its Velero backups still waits for deletion. Nothing - // watches DeleteBackupRequests, so a request Velero processed with errors - // is only noticed, and replaced, on this requeue. - failedJobSweepRequeue = 5 * time.Minute + // watches DeleteBackupRequests, so a request Velero processed is only + // noticed, and replaced, on this requeue. Every replacement doubles it, up + // to failedJobSweepMaxRequeue, so a deletion Velero can never carry out + // (a missing, read-only or unavailable BSL) is retried rarely. + failedJobSweepRequeue = 5 * time.Minute + failedJobSweepMaxRequeue = time.Hour // failedJobRunningBackupRequeue is how often a Failed BackupJob is // reconciled again while one of its Velero backups is still running. // Velero rejects a deletion request for a running backup. failedJobRunningBackupRequeue = time.Minute + + // veleroDeletionRetriesAnnotation counts, on a Failed BackupJob, the + // deletion requests that Velero processed while the backup survived. + veleroDeletionRetriesAnnotation = "backups.cozystack.io/velero-deletion-retries" ) // deleteFailedJobVeleroBackups requests deletion of the failed Velero backups @@ -113,15 +139,20 @@ func (r *BackupJobReconciler) deleteFailedJobVeleroBackups(ctx context.Context, var referenced map[client.ObjectKey]bool var requeueAfter time.Duration + var waiting, replaced bool for i := range veleroBackups.Items { vb := &veleroBackups.Items[i] switch vb.Status.Phase { - case velerov1.BackupPhasePartiallyFailed, velerov1.BackupPhaseFailed, velerov1.BackupPhaseFailedValidation: - case velerov1.BackupPhaseCompleted, velerov1.BackupPhaseDeleting: + case velerov1.BackupPhasePartiallyFailed, velerov1.BackupPhaseFailed, velerov1.BackupPhaseFailedValidation, + // Velero marks the backup Deleting before it removes the data and + // leaves it so when that fails, so the request may need replacing. + velerov1.BackupPhaseDeleting: + case velerov1.BackupPhaseCompleted: // A job can fail after Velero completed, when creating or // recording its Backup fails. That Velero backup may be the only - // copy of good data, and a Backup that already references it - // deletes it itself, so a job-level failure never removes it. + // copy of good data, so a job-level failure never removes it: a + // Backup that references it deletes it with the Backup, and one + // that no Backup references stays until Velero's TTL expires it. continue default: requeueAfter = shorterRequeue(requeueAfter, failedJobRunningBackupRequeue) @@ -138,17 +169,65 @@ func (r *BackupJobReconciler) deleteFailedJobVeleroBackups(ctx context.Context, continue } - created, err := requestVeleroBackupDeletion(ctx, r.Client, vb.Namespace, vb.Name) + req, err := requestVeleroBackupDeletion(ctx, r.Client, vb.Namespace, vb.Name) if err != nil { return ctrl.Result{}, err } - if created { + waiting = true + if req.replaced != nil { + replaced = true + r.warnVeleroDeletionRetried(j, vb.Name, req.replaced) + } else if req.created { logger.Info("requested deletion of the Velero Backup of a failed BackupJob", "backupjob", j.Name, "namespace", j.Namespace, "veleroBackup", vb.Name) } - requeueAfter = shorterRequeue(requeueAfter, failedJobSweepRequeue) } - return ctrl.Result{RequeueAfter: requeueAfter}, nil + if !waiting { + return ctrl.Result{RequeueAfter: requeueAfter}, nil + } + + retries := veleroDeletionRetries(j) + if replaced { + retries++ + patch := client.MergeFrom(j.DeepCopy()) + if j.Annotations == nil { + j.Annotations = map[string]string{} + } + j.Annotations[veleroDeletionRetriesAnnotation] = strconv.Itoa(retries) + if err := r.Patch(ctx, j, patch); err != nil { + return ctrl.Result{}, fmt.Errorf("failed to record Velero deletion retries on BackupJob %s/%s: %w", j.Namespace, j.Name, err) + } + } + return ctrl.Result{RequeueAfter: shorterRequeue(requeueAfter, failedJobSweepBackoff(retries))}, nil +} + +func (r *BackupJobReconciler) warnVeleroDeletionRetried(j *backupsv1alpha1.BackupJob, veleroBackup string, processed *velerov1.DeleteBackupRequest) { + if r.Recorder == nil { + return + } + reason := "Velero reported no error, but the backup still exists" + if len(processed.Status.Errors) > 0 { + reason = strings.Join(processed.Status.Errors, "; ") + } + r.Recorder.Eventf(j, corev1.EventTypeWarning, "VeleroBackupDeletionFailed", + "Velero did not delete backup %s/%s: %s; requesting the deletion again", + veleroNamespace, veleroBackup, reason) +} + +func veleroDeletionRetries(j *backupsv1alpha1.BackupJob) int { + n, err := strconv.Atoi(j.Annotations[veleroDeletionRetriesAnnotation]) + if err != nil || n < 0 { + return 0 + } + return n +} + +func failedJobSweepBackoff(retries int) time.Duration { + d := failedJobSweepRequeue + for i := 0; i < retries && d < failedJobSweepMaxRequeue; i++ { + d *= 2 + } + return min(d, failedJobSweepMaxRequeue) } func shorterRequeue(current, next time.Duration) time.Duration { diff --git a/internal/backupcontroller/velero_backup_deletion_test.go b/internal/backupcontroller/velero_backup_deletion_test.go index d283e6262..dd806faa8 100644 --- a/internal/backupcontroller/velero_backup_deletion_test.go +++ b/internal/backupcontroller/velero_backup_deletion_test.go @@ -3,10 +3,13 @@ package backupcontroller import ( "context" "errors" + "strings" "testing" + "time" corev1 "k8s.io/api/core/v1" apierrors "k8s.io/apimachinery/pkg/api/errors" + "k8s.io/apimachinery/pkg/api/meta" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/types" @@ -237,67 +240,91 @@ func TestReconcileVelero_SeveralVeleroBackupsKeepCompletedOne(t *testing.T) { // Reconciling a Failed BackupJob, including one that failed under a version // without the cleanup, requests deletion of its failed Velero backups only. func TestReconcile_FailedJobVeleroBackupSweep(t *testing.T) { + foreign := failedVeleroBackup + "-abcde" cases := []struct { name string veleroPhase velerov1.BackupPhase jobPhase backupsv1alpha1.BackupJobPhase existing []client.Object // Backups visible to the uncached reader only. - uncached []client.Object - wantNames []string - wantPhase velerov1.DeleteBackupRequestPhase - wantRequeue ctrl.Result + uncached []client.Object + wantRequests map[string]velerov1.DeleteBackupRequestPhase + wantRequeue time.Duration + wantEvent bool }{ { - name: "PartiallyFailed without a request", - veleroPhase: velerov1.BackupPhasePartiallyFailed, - jobPhase: backupsv1alpha1.BackupJobPhaseFailed, - wantNames: []string{failedVeleroBackup}, - wantRequeue: ctrl.Result{RequeueAfter: failedJobSweepRequeue}, + name: "PartiallyFailed without a request", + veleroPhase: velerov1.BackupPhasePartiallyFailed, + jobPhase: backupsv1alpha1.BackupJobPhaseFailed, + wantRequests: map[string]velerov1.DeleteBackupRequestPhase{failedVeleroBackup: ""}, + wantRequeue: failedJobSweepRequeue, }, { - name: "FailedValidation is deleted", - veleroPhase: velerov1.BackupPhaseFailedValidation, - jobPhase: backupsv1alpha1.BackupJobPhaseFailed, - wantNames: []string{failedVeleroBackup}, - wantRequeue: ctrl.Result{RequeueAfter: failedJobSweepRequeue}, + name: "FailedValidation is deleted", + veleroPhase: velerov1.BackupPhaseFailedValidation, + jobPhase: backupsv1alpha1.BackupJobPhaseFailed, + wantRequests: map[string]velerov1.DeleteBackupRequestPhase{failedVeleroBackup: ""}, + wantRequeue: failedJobSweepRequeue, }, { - name: "pending request from elsewhere", + name: "pending request from elsewhere", + veleroPhase: velerov1.BackupPhaseFailed, + jobPhase: backupsv1alpha1.BackupJobPhaseFailed, + existing: []client.Object{deleteRequest(foreign, velerov1.DeleteBackupRequestPhaseInProgress)}, + wantRequests: map[string]velerov1.DeleteBackupRequestPhase{foreign: velerov1.DeleteBackupRequestPhaseInProgress}, + wantRequeue: failedJobSweepRequeue, + }, + { + name: "errored request from elsewhere is left alone", veleroPhase: velerov1.BackupPhaseFailed, jobPhase: backupsv1alpha1.BackupJobPhaseFailed, - existing: []client.Object{deleteRequest(failedVeleroBackup+"-abcde", velerov1.DeleteBackupRequestPhaseInProgress)}, - wantNames: []string{failedVeleroBackup + "-abcde"}, - wantPhase: velerov1.DeleteBackupRequestPhaseInProgress, - wantRequeue: ctrl.Result{RequeueAfter: failedJobSweepRequeue}, + existing: []client.Object{deleteRequest(foreign, velerov1.DeleteBackupRequestPhaseProcessed, "backup storage location unavailable")}, + wantRequests: map[string]velerov1.DeleteBackupRequestPhase{ + failedVeleroBackup: "", + foreign: velerov1.DeleteBackupRequestPhaseProcessed, + }, + wantRequeue: failedJobSweepRequeue, }, { - name: "own request processed with errors is replaced", - veleroPhase: velerov1.BackupPhaseFailed, - jobPhase: backupsv1alpha1.BackupJobPhaseFailed, - existing: []client.Object{deleteRequest(failedVeleroBackup, velerov1.DeleteBackupRequestPhaseProcessed, "backup is still in progress")}, - wantNames: []string{failedVeleroBackup}, - wantRequeue: ctrl.Result{RequeueAfter: failedJobSweepRequeue}, + name: "own request processed with errors is replaced", + veleroPhase: velerov1.BackupPhaseFailed, + jobPhase: backupsv1alpha1.BackupJobPhaseFailed, + existing: []client.Object{deleteRequest(failedVeleroBackup, velerov1.DeleteBackupRequestPhaseProcessed, "backup is still in progress")}, + wantRequests: map[string]velerov1.DeleteBackupRequestPhase{failedVeleroBackup: ""}, + wantRequeue: 2 * failedJobSweepRequeue, + wantEvent: true, }, { - name: "request processed without errors is kept", - veleroPhase: velerov1.BackupPhaseFailed, - jobPhase: backupsv1alpha1.BackupJobPhaseFailed, - existing: []client.Object{deleteRequest(failedVeleroBackup, velerov1.DeleteBackupRequestPhaseProcessed)}, - wantNames: []string{failedVeleroBackup}, - wantPhase: velerov1.DeleteBackupRequestPhaseProcessed, - wantRequeue: ctrl.Result{RequeueAfter: failedJobSweepRequeue}, + name: "own request processed without errors while the backup exists is replaced", + veleroPhase: velerov1.BackupPhaseFailed, + jobPhase: backupsv1alpha1.BackupJobPhaseFailed, + existing: []client.Object{deleteRequest(failedVeleroBackup, velerov1.DeleteBackupRequestPhaseProcessed)}, + wantRequests: map[string]velerov1.DeleteBackupRequestPhase{failedVeleroBackup: ""}, + wantRequeue: 2 * failedJobSweepRequeue, + wantEvent: true, + }, + { + name: "Deleting with a request in progress", + veleroPhase: velerov1.BackupPhaseDeleting, + jobPhase: backupsv1alpha1.BackupJobPhaseFailed, + existing: []client.Object{deleteRequest(failedVeleroBackup, velerov1.DeleteBackupRequestPhaseInProgress)}, + wantRequests: map[string]velerov1.DeleteBackupRequestPhase{failedVeleroBackup: velerov1.DeleteBackupRequestPhaseInProgress}, + wantRequeue: failedJobSweepRequeue, + }, + { + name: "Deleting left by an errored request", + veleroPhase: velerov1.BackupPhaseDeleting, + jobPhase: backupsv1alpha1.BackupJobPhaseFailed, + existing: []client.Object{deleteRequest(failedVeleroBackup, velerov1.DeleteBackupRequestPhaseProcessed, "error deleting backup from object storage")}, + wantRequests: map[string]velerov1.DeleteBackupRequestPhase{failedVeleroBackup: ""}, + wantRequeue: 2 * failedJobSweepRequeue, + wantEvent: true, }, { name: "Completed is never deleted", veleroPhase: velerov1.BackupPhaseCompleted, jobPhase: backupsv1alpha1.BackupJobPhaseFailed, }, - { - name: "Deleting is skipped", - veleroPhase: velerov1.BackupPhaseDeleting, - jobPhase: backupsv1alpha1.BackupJobPhaseFailed, - }, { name: "failed backup referenced by a Backup the cache has not seen", veleroPhase: velerov1.BackupPhaseFailed, @@ -308,13 +335,13 @@ func TestReconcile_FailedJobVeleroBackupSweep(t *testing.T) { name: "running backup", veleroPhase: velerov1.BackupPhaseInProgress, jobPhase: backupsv1alpha1.BackupJobPhaseFailed, - wantRequeue: ctrl.Result{RequeueAfter: failedJobRunningBackupRequeue}, + wantRequeue: failedJobRunningBackupRequeue, }, { name: "new backup", veleroPhase: "", jobPhase: backupsv1alpha1.BackupJobPhaseFailed, - wantRequeue: ctrl.Result{RequeueAfter: failedJobRunningBackupRequeue}, + wantRequeue: failedJobRunningBackupRequeue, }, { name: "succeeded job", @@ -330,26 +357,100 @@ func TestReconcile_FailedJobVeleroBackupSweep(t *testing.T) { r.APIReader = newVeleroCleanupClient(t, nil, tc.uncached...) } - if res := reconcileCleanupJob(t, r); res != tc.wantRequeue { - t.Errorf("Result = %+v, want %+v", res, tc.wantRequeue) + if res := reconcileCleanupJob(t, r); res.RequeueAfter != tc.wantRequeue { + t.Errorf("RequeueAfter = %v, want %v", res.RequeueAfter, tc.wantRequeue) } dbrs := listDeleteBackupRequests(t, c) - if len(dbrs) != len(tc.wantNames) { - t.Fatalf("expected requests %v, got %+v", tc.wantNames, dbrs) + if len(dbrs) != len(tc.wantRequests) { + t.Fatalf("expected requests %v, got %+v", tc.wantRequests, dbrs) } - for i, want := range tc.wantNames { - if dbrs[i].Name != want || dbrs[i].Spec.BackupName != failedVeleroBackup { - t.Errorf("request %d = %s for %s, want %s for %s", i, dbrs[i].Name, dbrs[i].Spec.BackupName, want, failedVeleroBackup) + for _, dbr := range dbrs { + wantPhase, ok := tc.wantRequests[dbr.Name] + if !ok || dbr.Spec.BackupName != failedVeleroBackup { + t.Errorf("unexpected request %s for %s", dbr.Name, dbr.Spec.BackupName) + continue } - if dbrs[i].Status.Phase != tc.wantPhase { - t.Errorf("request %s phase = %q, want %q", dbrs[i].Name, dbrs[i].Status.Phase, tc.wantPhase) + if dbr.Status.Phase != wantPhase { + t.Errorf("request %s phase = %q, want %q", dbr.Name, dbr.Status.Phase, wantPhase) } } + + events := r.Recorder.(*record.FakeRecorder).Events + if got := len(events); (got > 0) != tc.wantEvent { + t.Errorf("got %d events, want an event: %v", got, tc.wantEvent) + } }) } } +// A deletion Velero keeps failing is retried with a growing interval, and +// every failed attempt is reported on the BackupJob with Velero's errors. +func TestReconcile_FailedJobVeleroDeletionBacksOff(t *testing.T) { + r, c := newVeleroCleanupReconciler(t, + veleroCleanupJob(backupsv1alpha1.BackupJobPhaseFailed), + ownedVeleroBackup(failedVeleroBackup, velerov1.BackupPhaseFailed)) + events := r.Recorder.(*record.FakeRecorder).Events + + if res := reconcileCleanupJob(t, r); res.RequeueAfter != failedJobSweepRequeue { + t.Fatalf("first request: RequeueAfter = %v, want %v", res.RequeueAfter, failedJobSweepRequeue) + } + for i, want := range []time.Duration{10 * time.Minute, 20 * time.Minute, 40 * time.Minute} { + dbr := &velerov1.DeleteBackupRequest{} + if err := c.Get(context.Background(), types.NamespacedName{Namespace: veleroNamespace, Name: failedVeleroBackup}, dbr); err != nil { + t.Fatalf("get request: %v", err) + } + dbr.Status = velerov1.DeleteBackupRequestStatus{ + Phase: velerov1.DeleteBackupRequestPhaseProcessed, + Errors: []string{"backup storage location default is currently in read-only mode"}, + } + if err := c.Update(context.Background(), dbr); err != nil { + t.Fatalf("mark request processed: %v", err) + } + + if res := reconcileCleanupJob(t, r); res.RequeueAfter != want { + t.Errorf("retry %d: RequeueAfter = %v, want %v", i+1, res.RequeueAfter, want) + } + select { + case ev := <-events: + if !strings.Contains(ev, "Warning VeleroBackupDeletionFailed") || !strings.Contains(ev, "read-only mode") { + t.Errorf("retry %d: unexpected event %q", i+1, ev) + } + default: + t.Fatalf("retry %d: no Warning event", i+1) + } + if n := len(listDeleteBackupRequests(t, c)); n != 1 { + t.Fatalf("retry %d: expected one request, got %d", i+1, n) + } + } + if res := reconcileCleanupJob(t, r); res.RequeueAfter != 40*time.Minute { + t.Errorf("a pending request must keep the backoff, got %v", res.RequeueAfter) + } + if len(events) != 0 { + t.Errorf("a pending request must not emit an event, got %q", <-events) + } + + if got := failedJobSweepBackoff(10); got != failedJobSweepMaxRequeue { + t.Errorf("backoff after 10 retries = %v, want the %v cap", got, failedJobSweepMaxRequeue) + } +} + +func TestReconcile_FailedJobWithoutVeleroCRDs(t *testing.T) { + funcs := &interceptor.Funcs{ + List: func(ctx context.Context, c client.WithWatch, list client.ObjectList, opts ...client.ListOption) error { + if _, ok := list.(*velerov1.BackupList); ok { + return &meta.NoKindMatchError{GroupKind: schema.GroupKind{Group: "velero.io", Kind: "Backup"}} + } + return c.List(ctx, list, opts...) + }, + } + c := newVeleroCleanupClient(t, funcs, veleroCleanupJob(backupsv1alpha1.BackupJobPhaseFailed)) + r := &BackupJobReconciler{Client: c, Recorder: record.NewFakeRecorder(16)} + if res := reconcileCleanupJob(t, r); res.RequeueAfter != 0 { + t.Errorf("RequeueAfter = %v, want none", res.RequeueAfter) + } +} + func TestRequestVeleroBackupDeletion_ReplacesByUID(t *testing.T) { stale := deleteRequest(failedVeleroBackup, velerov1.DeleteBackupRequestPhaseProcessed, "backup storage location unavailable") var preconditionUID types.UID @@ -364,9 +465,9 @@ func TestRequestVeleroBackupDeletion_ReplacesByUID(t *testing.T) { }, } c := newVeleroCleanupClient(t, funcs, stale) - created, err := requestVeleroBackupDeletion(context.Background(), c, veleroNamespace, failedVeleroBackup) - if err != nil || !created { - t.Fatalf("requestVeleroBackupDeletion = (%v, %v), want (true, nil)", created, err) + req, err := requestVeleroBackupDeletion(context.Background(), c, veleroNamespace, failedVeleroBackup) + if err != nil || !req.created || req.replaced == nil { + t.Fatalf("requestVeleroBackupDeletion = (%+v, %v), want a replaced and a created request", req, err) } if preconditionUID != stale.UID { t.Errorf("Delete precondition UID = %q, want %q", preconditionUID, stale.UID) @@ -390,9 +491,9 @@ func TestRequestVeleroBackupDeletion_ReturnsAPIErrors(t *testing.T) { t.Run(name, func(t *testing.T) { c := newVeleroCleanupClient(t, &funcs, deleteRequest(failedVeleroBackup, velerov1.DeleteBackupRequestPhaseProcessed, "backup storage location unavailable")) - created, err := requestVeleroBackupDeletion(context.Background(), c, veleroNamespace, failedVeleroBackup) - if created || !apierrors.IsForbidden(err) { - t.Fatalf("requestVeleroBackupDeletion = (%v, %v), want a Forbidden error", created, err) + req, err := requestVeleroBackupDeletion(context.Background(), c, veleroNamespace, failedVeleroBackup) + if req.created || !apierrors.IsForbidden(err) { + t.Fatalf("requestVeleroBackupDeletion = (%+v, %v), want a Forbidden error", req, err) } }) } From dbc088f8629339058eb024ef9fc7de7f4fa1e805 Mon Sep 17 00:00:00 2001 From: Andrey Kolkov Date: Thu, 19 Nov 2026 21:07:17 +0700 Subject: [PATCH 15/17] fix(backups): enforce the Velero deletion backoff of failed BackupJobs The retry backoff of the failed-job sweep only set RequeueAfter. Writing the retry counter onto the BackupJob triggers a reconcile at once, since the BackupJob watch has no predicate. When Velero processes a request instantly, as it does when the backup storage location is missing or read-only, that reconcile replaced the request again, emitted another event and raised the counter without any wait. The sweep now records when it last created a request, in the backups.cozystack.io/velero-deletion-attempted-at annotation, and replaces a processed request only after the backoff for the current count has passed since then. Before that, it requeues for the remaining time. A request Velero never processes, because Velero is down, and a Velero backup stuck in New or with no phase were checked at a fixed interval, each check with an uncached list of Backups. They are now checked again after as long as they have already waited, from the request's or the backup's creation time, capped at one hour. Waiting emits no event. Recording the attempt can fail after the request was created. If the job was deleted meanwhile, the sweep ends without an error. Any other error is logged and the computed requeue is kept, because failing the reconcile would only retry sooner. Unit tests drive the clock through two back-to-back reconciles of an instantly processed request (one replacement, one event), then three retries at 10, 20 and 40 minutes. They also check the waiting intervals for requests and backups of different ages, and both annotation write errors. Refs: #5355 Assisted-by: LLM Signed-off-by: Andrey Kolkov --- .../backupcontroller/backup_controller.go | 2 +- .../backupcontroller/backupjob_controller.go | 3 + .../velero_backup_deletion.go | 142 +++++++++++---- .../velero_backup_deletion_test.go | 167 ++++++++++++++---- 4 files changed, 243 insertions(+), 71 deletions(-) diff --git a/internal/backupcontroller/backup_controller.go b/internal/backupcontroller/backup_controller.go index 402c6103e..a8908d34d 100644 --- a/internal/backupcontroller/backup_controller.go +++ b/internal/backupcontroller/backup_controller.go @@ -248,7 +248,7 @@ func (r *BackupReconciler) cleanupVeleroBackup(ctx context.Context, backup *back return fmt.Errorf("failed to get Velero backup %s/%s: %w", veleroBackupNamespace, veleroBackupName, err) } - req, err := requestVeleroBackupDeletion(ctx, r.Client, veleroBackupNamespace, veleroBackupName) + req, err := requestVeleroBackupDeletion(ctx, r.Client, veleroBackupNamespace, veleroBackupName, true) if err != nil { return err } diff --git a/internal/backupcontroller/backupjob_controller.go b/internal/backupcontroller/backupjob_controller.go index c5084f9be..4b96c2087 100644 --- a/internal/backupcontroller/backupjob_controller.go +++ b/internal/backupcontroller/backupjob_controller.go @@ -43,6 +43,9 @@ type BackupJobReconciler struct { // newS3ObjectLister overrides the S3 client used to measure artifact // sizes; nil means a real minio client. Set by unit tests. newS3ObjectLister func(conn s3Connection) (s3ObjectLister, error) + + // now is a test seam for the clock that paces Velero deletion retries. + now func() time.Time } func (r *BackupJobReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { diff --git a/internal/backupcontroller/velero_backup_deletion.go b/internal/backupcontroller/velero_backup_deletion.go index b22ba9e5c..5e4a51c20 100644 --- a/internal/backupcontroller/velero_backup_deletion.go +++ b/internal/backupcontroller/velero_backup_deletion.go @@ -20,12 +20,17 @@ import ( velerov1 "github.com/vmware-tanzu/velero/pkg/apis/velero/v1" ) -// veleroDeletionRequest is what requestVeleroBackupDeletion did. +// veleroDeletionRequest is what requestVeleroBackupDeletion found and did. type veleroDeletionRequest struct { created bool // replaced is a request of ours that Velero had processed and that this // call deleted before creating a new one. replaced *velerov1.DeleteBackupRequest + // pending is a request for the backup that Velero has not processed yet. + pending *velerov1.DeleteBackupRequest + // processed is a request of ours that Velero has processed and that was + // left in place because the caller did not allow a replacement. + processed *velerov1.DeleteBackupRequest } // requestVeleroBackupDeletion asks Velero to delete a backup together with its @@ -35,13 +40,13 @@ type veleroDeletionRequest struct { // // The request is named after the backup, so repeated calls converge on one // request. Nothing is created while any request for the backup is -// unprocessed. A request of ours that Velero has processed is deleted and -// created again: the backup still exists, so the deletion failed, or the BSL -// sync brought the backup back, and Velero keeps a processed request for a -// day, during which its name would block a new attempt. Velero does not retry -// a processed request, so a caller that needs the deletion to happen must -// call again later. -func requestVeleroBackupDeletion(ctx context.Context, c client.Client, namespace, name string) (veleroDeletionRequest, error) { +// unprocessed. A request of ours that Velero has processed means the backup +// survived it: the deletion failed, or the BSL sync brought the backup back. +// With replace set, such a request is deleted and created again, because +// Velero keeps a processed request for a day and its name would block a new +// attempt until then. Velero does not retry a processed request, so a caller +// that needs the deletion to happen must call again later. +func requestVeleroBackupDeletion(ctx context.Context, c client.Client, namespace, name string, replace bool) (veleroDeletionRequest, error) { var res veleroDeletionRequest requests := &velerov1.DeleteBackupRequestList{} if err := c.List(ctx, requests, client.InNamespace(namespace)); err != nil { @@ -54,6 +59,7 @@ func requestVeleroBackupDeletion(ctx context.Context, c client.Client, namespace continue } if dbr.Status.Phase != velerov1.DeleteBackupRequestPhaseProcessed { + res.pending = dbr return res, nil } if dbr.Name == name { @@ -61,6 +67,10 @@ func requestVeleroBackupDeletion(ctx context.Context, c client.Client, namespace } } if own != nil { + if !replace { + res.processed = own + return res, nil + } // The UID precondition keeps a stale cache from deleting a request // that has already been replaced. err := c.Delete(ctx, own, client.Preconditions{UID: &own.UID}) @@ -93,22 +103,28 @@ func requestVeleroBackupDeletion(ctx context.Context, c client.Client, namespace } const ( - // failedJobSweepRequeue is how often a Failed BackupJob is reconciled - // again while one of its Velero backups still waits for deletion. Nothing - // watches DeleteBackupRequests, so a request Velero processed is only - // noticed, and replaced, on this requeue. Every replacement doubles it, up - // to failedJobSweepMaxRequeue, so a deletion Velero can never carry out - // (a missing, read-only or unavailable BSL) is retried rarely. + // failedJobSweepRequeue is the first interval at which a Failed + // BackupJob is reconciled again while one of its Velero backups waits + // for deletion; failedJobSweepMaxRequeue caps every interval below. + // Nothing watches DeleteBackupRequests, so a request Velero processed is + // only noticed on such a requeue. A processed request is replaced once + // failedJobSweepBackoff(retries) has passed since the last attempt, so a + // deletion Velero can never carry out (a missing, read-only or + // unavailable BSL) is attempted at most once an hour, and the annotation + // writes that record each attempt cannot cut the wait short. failedJobSweepRequeue = 5 * time.Minute failedJobSweepMaxRequeue = time.Hour - // failedJobRunningBackupRequeue is how often a Failed BackupJob is - // reconciled again while one of its Velero backups is still running. - // Velero rejects a deletion request for a running backup. + // failedJobRunningBackupRequeue is the first interval at which a Failed + // BackupJob is reconciled again while one of its Velero backups is still + // running. Velero rejects a deletion request for a running backup. failedJobRunningBackupRequeue = time.Minute // veleroDeletionRetriesAnnotation counts, on a Failed BackupJob, the // deletion requests that Velero processed while the backup survived. veleroDeletionRetriesAnnotation = "backups.cozystack.io/velero-deletion-retries" + // veleroDeletionAttemptAnnotation is when the sweep last created a + // deletion request for a Failed BackupJob, in RFC 3339. + veleroDeletionAttemptAnnotation = "backups.cozystack.io/velero-deletion-attempted-at" ) // deleteFailedJobVeleroBackups requests deletion of the failed Velero backups @@ -137,9 +153,15 @@ func (r *BackupJobReconciler) deleteFailedJobVeleroBackups(ctx context.Context, return ctrl.Result{}, nil } + now := r.clock() + retries := veleroDeletionRetries(j) + lastAttempt := veleroDeletionAttempt(j) + nextAttempt := lastAttempt.Add(failedJobSweepBackoff(retries)) + replaceDue := lastAttempt.IsZero() || !now.Before(nextAttempt) + var referenced map[client.ObjectKey]bool var requeueAfter time.Duration - var waiting, replaced bool + var attempted, replaced bool for i := range veleroBackups.Items { vb := &veleroBackups.Items[i] switch vb.Status.Phase { @@ -155,7 +177,8 @@ func (r *BackupJobReconciler) deleteFailedJobVeleroBackups(ctx context.Context, // that no Backup references stays until Velero's TTL expires it. continue default: - requeueAfter = shorterRequeue(requeueAfter, failedJobRunningBackupRequeue) + requeueAfter = shorterRequeue(requeueAfter, + waitingRequeue(now, vb.CreationTimestamp.Time, failedJobRunningBackupRequeue)) continue } @@ -169,36 +192,60 @@ func (r *BackupJobReconciler) deleteFailedJobVeleroBackups(ctx context.Context, continue } - req, err := requestVeleroBackupDeletion(ctx, r.Client, vb.Namespace, vb.Name) + req, err := requestVeleroBackupDeletion(ctx, r.Client, vb.Namespace, vb.Name, replaceDue) if err != nil { return ctrl.Result{}, err } - waiting = true - if req.replaced != nil { - replaced = true - r.warnVeleroDeletionRetried(j, vb.Name, req.replaced) - } else if req.created { - logger.Info("requested deletion of the Velero Backup of a failed BackupJob", - "backupjob", j.Name, "namespace", j.Namespace, "veleroBackup", vb.Name) + switch { + case req.pending != nil: + requeueAfter = shorterRequeue(requeueAfter, + waitingRequeue(now, req.pending.CreationTimestamp.Time, failedJobSweepRequeue)) + case req.processed != nil: + requeueAfter = shorterRequeue(requeueAfter, nextAttempt.Sub(now)) + case req.created: + attempted = true + if req.replaced != nil { + replaced = true + r.warnVeleroDeletionRetried(j, vb.Name, req.replaced) + } else { + logger.Info("requested deletion of the Velero Backup of a failed BackupJob", + "backupjob", j.Name, "namespace", j.Namespace, "veleroBackup", vb.Name) + } + default: + requeueAfter = shorterRequeue(requeueAfter, failedJobSweepRequeue) } } - if !waiting { + if !attempted { return ctrl.Result{RequeueAfter: requeueAfter}, nil } - retries := veleroDeletionRetries(j) if replaced { retries++ - patch := client.MergeFrom(j.DeepCopy()) - if j.Annotations == nil { - j.Annotations = map[string]string{} - } - j.Annotations[veleroDeletionRetriesAnnotation] = strconv.Itoa(retries) - if err := r.Patch(ctx, j, patch); err != nil { - return ctrl.Result{}, fmt.Errorf("failed to record Velero deletion retries on BackupJob %s/%s: %w", j.Namespace, j.Name, err) - } } - return ctrl.Result{RequeueAfter: shorterRequeue(requeueAfter, failedJobSweepBackoff(retries))}, nil + requeueAfter = shorterRequeue(requeueAfter, failedJobSweepBackoff(retries)) + patch := client.MergeFrom(j.DeepCopy()) + if j.Annotations == nil { + j.Annotations = map[string]string{} + } + j.Annotations[veleroDeletionRetriesAnnotation] = strconv.Itoa(retries) + j.Annotations[veleroDeletionAttemptAnnotation] = now.UTC().Format(time.RFC3339) + if err := r.Patch(ctx, j, patch); err != nil { + if apierrors.IsNotFound(err) { + return ctrl.Result{}, nil + } + // The request is already in place; without the record the next + // attempt only comes sooner than the backoff asks for. + logger.Error(err, "failed to record the Velero deletion attempt on the BackupJob", + "backupjob", j.Name, "namespace", j.Namespace) + } + return ctrl.Result{RequeueAfter: requeueAfter}, nil +} + +func (r *BackupJobReconciler) clock() time.Time { + if r.now != nil { + return r.now() + } + return time.Now() } func (r *BackupJobReconciler) warnVeleroDeletionRetried(j *backupsv1alpha1.BackupJob, veleroBackup string, processed *velerov1.DeleteBackupRequest) { @@ -222,6 +269,14 @@ func veleroDeletionRetries(j *backupsv1alpha1.BackupJob) int { return n } +func veleroDeletionAttempt(j *backupsv1alpha1.BackupJob) time.Time { + t, err := time.Parse(time.RFC3339, j.Annotations[veleroDeletionAttemptAnnotation]) + if err != nil { + return time.Time{} + } + return t +} + func failedJobSweepBackoff(retries int) time.Duration { d := failedJobSweepRequeue for i := 0; i < retries && d < failedJobSweepMaxRequeue; i++ { @@ -230,6 +285,17 @@ func failedJobSweepBackoff(retries int) time.Duration { return min(d, failedJobSweepMaxRequeue) } +// waitingRequeue paces the checks on something Velero has not acted on yet: +// the next check comes after as long as it has already waited, between floor +// and failedJobSweepMaxRequeue, so a Velero that is down is not polled at a +// fixed rate. +func waitingRequeue(now, since time.Time, floor time.Duration) time.Duration { + if since.IsZero() { + return floor + } + return min(max(now.Sub(since), floor), failedJobSweepMaxRequeue) +} + func shorterRequeue(current, next time.Duration) time.Duration { if current == 0 || next < current { return next diff --git a/internal/backupcontroller/velero_backup_deletion_test.go b/internal/backupcontroller/velero_backup_deletion_test.go index dd806faa8..f375bbb17 100644 --- a/internal/backupcontroller/velero_backup_deletion_test.go +++ b/internal/backupcontroller/velero_backup_deletion_test.go @@ -3,6 +3,7 @@ package backupcontroller import ( "context" "errors" + "fmt" "strings" "testing" "time" @@ -384,57 +385,159 @@ func TestReconcile_FailedJobVeleroBackupSweep(t *testing.T) { } } -// A deletion Velero keeps failing is retried with a growing interval, and -// every failed attempt is reported on the BackupJob with Velero's errors. +func markOwnRequestProcessed(t *testing.T, c client.Client, errs ...string) { + t.Helper() + dbr := &velerov1.DeleteBackupRequest{} + if err := c.Get(context.Background(), types.NamespacedName{Namespace: veleroNamespace, Name: failedVeleroBackup}, dbr); err != nil { + t.Fatalf("get request: %v", err) + } + dbr.Status = velerov1.DeleteBackupRequestStatus{Phase: velerov1.DeleteBackupRequestPhaseProcessed, Errors: errs} + if err := c.Update(context.Background(), dbr); err != nil { + t.Fatalf("mark request processed: %v", err) + } +} + +// A deletion Velero keeps failing at once is retried only after a growing +// wait, even though recording each attempt triggers a new reconcile, and +// every retry is reported on the BackupJob with Velero's errors. func TestReconcile_FailedJobVeleroDeletionBacksOff(t *testing.T) { + const readOnly = "backup storage location default is currently in read-only mode" r, c := newVeleroCleanupReconciler(t, veleroCleanupJob(backupsv1alpha1.BackupJobPhaseFailed), ownedVeleroBackup(failedVeleroBackup, velerov1.BackupPhaseFailed)) + now := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC) + r.now = func() time.Time { return now } events := r.Recorder.(*record.FakeRecorder).Events + expectEvent := func(step string, want bool) { + t.Helper() + select { + case ev := <-events: + if !want { + t.Fatalf("%s: unexpected event %q", step, ev) + } + if !strings.Contains(ev, "Warning VeleroBackupDeletionFailed") || !strings.Contains(ev, readOnly) { + t.Errorf("%s: unexpected event %q", step, ev) + } + default: + if want { + t.Fatalf("%s: no Warning event", step) + } + } + } if res := reconcileCleanupJob(t, r); res.RequeueAfter != failedJobSweepRequeue { t.Fatalf("first request: RequeueAfter = %v, want %v", res.RequeueAfter, failedJobSweepRequeue) } - for i, want := range []time.Duration{10 * time.Minute, 20 * time.Minute, 40 * time.Minute} { - dbr := &velerov1.DeleteBackupRequest{} - if err := c.Get(context.Background(), types.NamespacedName{Namespace: veleroNamespace, Name: failedVeleroBackup}, dbr); err != nil { - t.Fatalf("get request: %v", err) - } - dbr.Status = velerov1.DeleteBackupRequestStatus{ - Phase: velerov1.DeleteBackupRequestPhaseProcessed, - Errors: []string{"backup storage location default is currently in read-only mode"}, - } - if err := c.Update(context.Background(), dbr); err != nil { - t.Fatalf("mark request processed: %v", err) - } + expectEvent("first request", false) - if res := reconcileCleanupJob(t, r); res.RequeueAfter != want { - t.Errorf("retry %d: RequeueAfter = %v, want %v", i+1, res.RequeueAfter, want) + markOwnRequestProcessed(t, c, readOnly) + if res := reconcileCleanupJob(t, r); res.RequeueAfter != failedJobSweepRequeue { + t.Errorf("before the backoff: RequeueAfter = %v, want %v", res.RequeueAfter, failedJobSweepRequeue) + } + expectEvent("before the backoff", false) + + for i, wait := range []time.Duration{5 * time.Minute, 10 * time.Minute, 20 * time.Minute} { + now = now.Add(wait) + step := fmt.Sprintf("retry %d", i+1) + if res := reconcileCleanupJob(t, r); res.RequeueAfter != 2*wait { + t.Errorf("%s: RequeueAfter = %v, want %v", step, res.RequeueAfter, 2*wait) } - select { - case ev := <-events: - if !strings.Contains(ev, "Warning VeleroBackupDeletionFailed") || !strings.Contains(ev, "read-only mode") { - t.Errorf("retry %d: unexpected event %q", i+1, ev) - } - default: - t.Fatalf("retry %d: no Warning event", i+1) + expectEvent(step, true) + + markOwnRequestProcessed(t, c, readOnly) + if res := reconcileCleanupJob(t, r); res.RequeueAfter != 2*wait { + t.Errorf("%s, reconcile right after: RequeueAfter = %v, want %v", step, res.RequeueAfter, 2*wait) } + expectEvent(step+", reconcile right after", false) if n := len(listDeleteBackupRequests(t, c)); n != 1 { - t.Fatalf("retry %d: expected one request, got %d", i+1, n) + t.Fatalf("%s: expected one request, got %d", step, n) } } - if res := reconcileCleanupJob(t, r); res.RequeueAfter != 40*time.Minute { - t.Errorf("a pending request must keep the backoff, got %v", res.RequeueAfter) - } - if len(events) != 0 { - t.Errorf("a pending request must not emit an event, got %q", <-events) - } if got := failedJobSweepBackoff(10); got != failedJobSweepMaxRequeue { t.Errorf("backoff after 10 retries = %v, want the %v cap", got, failedJobSweepMaxRequeue) } } +// Requests and backups Velero has not acted on yet are checked less often the +// longer they wait, and waiting is not reported. +func TestReconcile_FailedJobWaitingOnVeleroBacksOff(t *testing.T) { + now := time.Date(2026, 1, 1, 12, 0, 0, 0, time.UTC) + cases := []struct { + name string + veleroPhase velerov1.BackupPhase + existing []client.Object + backupAge time.Duration + want time.Duration + }{ + {name: "request waiting 20m", veleroPhase: velerov1.BackupPhaseFailed, want: 20 * time.Minute, + existing: []client.Object{agedRequest(now.Add(-20 * time.Minute))}}, + {name: "request waiting 3h", veleroPhase: velerov1.BackupPhaseFailed, want: failedJobSweepMaxRequeue, + existing: []client.Object{agedRequest(now.Add(-3 * time.Hour))}}, + {name: "request just created", veleroPhase: velerov1.BackupPhaseFailed, want: failedJobSweepRequeue, + existing: []client.Object{agedRequest(now)}}, + {name: "backup new for 3h", veleroPhase: velerov1.BackupPhaseNew, backupAge: 3 * time.Hour, want: failedJobSweepMaxRequeue}, + {name: "backup new for 10m", veleroPhase: "", backupAge: 10 * time.Minute, want: 10 * time.Minute}, + {name: "backup just started", veleroPhase: velerov1.BackupPhaseInProgress, want: failedJobRunningBackupRequeue}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + vb := ownedVeleroBackup(failedVeleroBackup, tc.veleroPhase) + vb.CreationTimestamp = metav1.NewTime(now.Add(-tc.backupAge)) + r, c := newVeleroCleanupReconciler(t, append([]client.Object{veleroCleanupJob(backupsv1alpha1.BackupJobPhaseFailed), vb}, tc.existing...)...) + r.now = func() time.Time { return now } + + if res := reconcileCleanupJob(t, r); res.RequeueAfter != tc.want { + t.Errorf("RequeueAfter = %v, want %v", res.RequeueAfter, tc.want) + } + if n := len(listDeleteBackupRequests(t, c)); n != len(tc.existing) { + t.Errorf("waiting must not create requests, got %d", n) + } + if events := r.Recorder.(*record.FakeRecorder).Events; len(events) != 0 { + t.Errorf("waiting must not be reported, got %q", <-events) + } + }) + } +} + +func agedRequest(created time.Time) *velerov1.DeleteBackupRequest { + dbr := deleteRequest(failedVeleroBackup, velerov1.DeleteBackupRequestPhaseInProgress) + dbr.CreationTimestamp = metav1.NewTime(created) + return dbr +} + +// Recording the attempt can fail after the request was created: a job deleted +// meanwhile ends the sweep, any other error still keeps the backoff requeue. +func TestReconcile_FailedJobAttemptRecordErrors(t *testing.T) { + for name, patchErr := range map[string]error{ + "job deleted": apierrors.NewNotFound(schema.GroupResource{Group: "backups.cozystack.io", Resource: "backupjobs"}, failedJobName), + "apiserver": apierrors.NewServiceUnavailable("etcd timeout"), + } { + t.Run(name, func(t *testing.T) { + funcs := &interceptor.Funcs{ + Patch: func(context.Context, client.WithWatch, client.Object, client.Patch, ...client.PatchOption) error { + return patchErr + }, + } + c := newVeleroCleanupClient(t, funcs, + veleroCleanupJob(backupsv1alpha1.BackupJobPhaseFailed), + ownedVeleroBackup(failedVeleroBackup, velerov1.BackupPhaseFailed)) + r := &BackupJobReconciler{Client: c, Recorder: record.NewFakeRecorder(16)} + + want := failedJobSweepRequeue + if apierrors.IsNotFound(patchErr) { + want = 0 + } + if res := reconcileCleanupJob(t, r); res.RequeueAfter != want { + t.Errorf("RequeueAfter = %v, want %v", res.RequeueAfter, want) + } + if n := len(listDeleteBackupRequests(t, c)); n != 1 { + t.Errorf("expected the request to stay, got %d", n) + } + }) + } +} + func TestReconcile_FailedJobWithoutVeleroCRDs(t *testing.T) { funcs := &interceptor.Funcs{ List: func(ctx context.Context, c client.WithWatch, list client.ObjectList, opts ...client.ListOption) error { @@ -465,7 +568,7 @@ func TestRequestVeleroBackupDeletion_ReplacesByUID(t *testing.T) { }, } c := newVeleroCleanupClient(t, funcs, stale) - req, err := requestVeleroBackupDeletion(context.Background(), c, veleroNamespace, failedVeleroBackup) + req, err := requestVeleroBackupDeletion(context.Background(), c, veleroNamespace, failedVeleroBackup, true) if err != nil || !req.created || req.replaced == nil { t.Fatalf("requestVeleroBackupDeletion = (%+v, %v), want a replaced and a created request", req, err) } @@ -491,7 +594,7 @@ func TestRequestVeleroBackupDeletion_ReturnsAPIErrors(t *testing.T) { t.Run(name, func(t *testing.T) { c := newVeleroCleanupClient(t, &funcs, deleteRequest(failedVeleroBackup, velerov1.DeleteBackupRequestPhaseProcessed, "backup storage location unavailable")) - req, err := requestVeleroBackupDeletion(context.Background(), c, veleroNamespace, failedVeleroBackup) + req, err := requestVeleroBackupDeletion(context.Background(), c, veleroNamespace, failedVeleroBackup, true) if req.created || !apierrors.IsForbidden(err) { t.Fatalf("requestVeleroBackupDeletion = (%+v, %v), want a Forbidden error", req, err) } From 0ec0add6203f318eb02d5417c8d9c1102cd173fa Mon Sep 17 00:00:00 2001 From: Andrey Kolkov Date: Fri, 20 Nov 2026 15:49:15 +0700 Subject: [PATCH 16/17] chore(keycloak): bump Keycloak server to 26.8.2 quay.io/keycloak/keycloak:26.6.3 bundles OpenJDK 21.0.11, which is affected by CVE-2026-114938, an out-of-bounds write in the AVX-512 VBMI Base64 decoder that Keycloak reaches before authentication. Upstream fixed it by rebuilding the 26.8.2 image on OpenJDK 21.0.13.1 and did not rebuild 26.6 or 26.7. Pin the 26.8.2-3 tag: 26.8.2 moves when upstream rebuilds it, and 26.8.2-1 and 26.8.2-2 still carry the affected JDK. keycloak-configure runs kcadm.sh from the same image and was still on 26.5.2; move it along so the admin client matches the server. Tested by upgrading a two-replica 26.6.3 instance in place: the rolling update migrated the database and both realms to 26.8.2, the old and the new node shared one cluster while it ran, the keycloak-operator reconciled every resource against the new Admin API, and the kcadm.sh hook passed. Assisted-by: LLM Signed-off-by: Andrey Kolkov --- .../keycloak-configure/templates/enable-update-email.yaml | 2 +- packages/system/keycloak-configure/values.yaml | 2 +- packages/system/keycloak/values.yaml | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/system/keycloak-configure/templates/enable-update-email.yaml b/packages/system/keycloak-configure/templates/enable-update-email.yaml index c1bbdae39..952f326b2 100644 --- a/packages/system/keycloak-configure/templates/enable-update-email.yaml +++ b/packages/system/keycloak-configure/templates/enable-update-email.yaml @@ -41,7 +41,7 @@ spec: type: RuntimeDefault containers: - name: kcadm - image: {{ .Values.image | default "quay.io/keycloak/keycloak:26.5.2" | quote }} + image: {{ .Values.image | default "quay.io/keycloak/keycloak:26.8.2-3" | quote }} securityContext: allowPrivilegeEscalation: false readOnlyRootFilesystem: true diff --git a/packages/system/keycloak-configure/values.yaml b/packages/system/keycloak-configure/values.yaml index b19efbff1..3d5ca6495 100644 --- a/packages/system/keycloak-configure/values.yaml +++ b/packages/system/keycloak-configure/values.yaml @@ -5,7 +5,7 @@ _cluster: {} # Keycloak image used by the one-shot admin-API job that enables the # UPDATE_EMAIL required action. Only kcadm.sh is used, so it just needs # to track the Keycloak server major version (packages/system/keycloak). -image: quay.io/keycloak/keycloak:26.5.2 +image: quay.io/keycloak/keycloak:26.8.2-3 # Enable the Keycloak Organizations feature for the platform realm. # Mapped to ClusterKeycloakRealm.spec.organizationsEnabled. Defaults to diff --git a/packages/system/keycloak/values.yaml b/packages/system/keycloak/values.yaml index 1e5b4ff19..b85d00061 100644 --- a/packages/system/keycloak/values.yaml +++ b/packages/system/keycloak/values.yaml @@ -2,7 +2,7 @@ # default keeps the chart renderable on its own, outside a cluster. _cluster: {} -image: quay.io/keycloak/keycloak:26.6.3 +image: quay.io/keycloak/keycloak:26.8.2-3 ingress: # Custom hostname for the Keycloak Ingress. From 65f09437101511ab88b88b50df2d925afb8c0744 Mon Sep 17 00:00:00 2001 From: Andrey Kolkov Date: Fri, 20 Nov 2026 15:54:15 +0700 Subject: [PATCH 17/17] fix(opensearch): disable the Base64 intrinsics hit by CVE-2026-114938 CVE-2026-114938 is an out-of-bounds write in the AVX-512 VBMI Base64 decoder of OpenJDK 17.0.6 and later, reachable on x86-64 hosts with attacker-supplied Base64. OpenSearch decodes the Basic credentials of a request before it authenticates it, so a tenant's cluster is exposed to anyone who can reach its HTTP port. Two of the three versions this chart offers bundle an affected JDK: opensearchproject/opensearch:3.0.0 carries 21.0.7 and 2.11.1 carries 17.0.8. 1.3.20 carries 11.0.25, which is not affected. OpenSearch has not released a build on a patched JDK yet. Start the nodes with -XX:-UseBASE64Intrinsics, which removes the vulnerable code path and leaves the other AVX-512 optimizations in place. It is delivered as a jvm.options.d file mounted from a ConfigMap, because neither obvious route works: bin/opensearch-env unsets JAVA_TOOL_OPTIONS, and setting nodePools[].jvm makes the operator stop sizing the heap from the memory request. The operator mounts general.additionalVolumes into the node pools and the bootstrap pod alike. Rolling this out restarts every OpenSearch cluster once. Tested with helm unittest, and by starting 3.0.0, 2.11.1 and 1.3.20 with the file mounted: each server JVM runs with the flag, and the heap passed in OPENSEARCH_JAVA_OPTS still applies. Assisted-by: LLM Signed-off-by: Andrey Kolkov --- .../opensearch/templates/jvm-options.yaml | 11 +++++ .../apps/opensearch/templates/opensearch.yaml | 12 ++++++ .../opensearch/tests/jvm_options_test.yaml | 42 +++++++++++++++++++ 3 files changed, 65 insertions(+) create mode 100644 packages/apps/opensearch/templates/jvm-options.yaml create mode 100644 packages/apps/opensearch/tests/jvm_options_test.yaml diff --git a/packages/apps/opensearch/templates/jvm-options.yaml b/packages/apps/opensearch/templates/jvm-options.yaml new file mode 100644 index 000000000..7228c53b2 --- /dev/null +++ b/packages/apps/opensearch/templates/jvm-options.yaml @@ -0,0 +1,11 @@ +apiVersion: v1 +kind: ConfigMap +metadata: + name: {{ .Release.Name }}-jvm-options +data: + # -XX:-UseBASE64Intrinsics turns off the AVX-512 Base64 decoder hit by + # CVE-2026-114938: OpenSearch decodes the Basic credentials of a request + # before it authenticates it, and the image may bundle an OpenJDK that + # predates the fix. + cozystack.options: | + -XX:-UseBASE64Intrinsics diff --git a/packages/apps/opensearch/templates/opensearch.yaml b/packages/apps/opensearch/templates/opensearch.yaml index 9aba247ec..2f7cdbfef 100644 --- a/packages/apps/opensearch/templates/opensearch.yaml +++ b/packages/apps/opensearch/templates/opensearch.yaml @@ -17,6 +17,18 @@ spec: version: {{ include "opensearch.versionMap" $ }} httpPort: 9200 {{- /* + JVM options go in as a jvm.options.d file because neither other route works: + bin/opensearch-env unsets JAVA_TOOL_OPTIONS, and setting nodePools[].jvm makes + the operator stop sizing the heap from the memory request. + */}} + additionalVolumes: + - name: jvm-options + path: /usr/share/opensearch/config/jvm.options.d/cozystack.options + subPath: cozystack.options + restartPods: true + configMap: + name: {{ .Release.Name }}-jvm-options + {{- /* The operator's own way to raise vm.max_map_count is a privileged init container in every OpenSearch pod, and the PodSecurity level tenant namespaces run at refuses that before any pod exists. The sysctl comes from diff --git a/packages/apps/opensearch/tests/jvm_options_test.yaml b/packages/apps/opensearch/tests/jvm_options_test.yaml new file mode 100644 index 000000000..8195ee1d8 --- /dev/null +++ b/packages/apps/opensearch/tests/jvm_options_test.yaml @@ -0,0 +1,42 @@ +suite: opensearch JVM options + +release: + name: test-os + namespace: tenant-test + +set: + _cluster: + cluster-domain: cozy.local + +tests: + - it: ships the Base64 intrinsics switch as a jvm.options.d file + template: templates/jvm-options.yaml + asserts: + - isKind: + of: ConfigMap + - equal: + path: metadata.name + value: test-os-jvm-options + - equal: + path: data["cozystack.options"] + value: | + -XX:-UseBASE64Intrinsics + + - it: mounts that file into every pod of the cluster + template: templates/opensearch.yaml + documentSelector: + path: kind + value: OpenSearchCluster + asserts: + - contains: + path: spec.general.additionalVolumes + content: + name: jvm-options + path: /usr/share/opensearch/config/jvm.options.d/cozystack.options + subPath: cozystack.options + restartPods: true + configMap: + name: test-os-jvm-options + # setting jvm would stop the operator sizing the heap from the memory request + - notExists: + path: spec.nodePools[0].jvm