mirror of
https://github.com/cozystack/cozystack.git
synced 2026-11-30 12:16:03 +09:00
Merge branch 'main' into fix/cluster-flags-bool-false
Assisted-by: LLM Signed-off-by: Aleksei Sviridkin <f@lex.la>
This commit is contained in:
29 files changed
+2722
-304
No files matched your search
@@ -120,10 +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.
|
||||
// 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 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. 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"`
|
||||
}
|
||||
|
||||
@@ -26,4 +26,4 @@ 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 <image>@<digest> --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 <image>@<digest> --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 <image>@<digest> --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.
|
||||
+16
-8
@@ -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)
|
||||
|
||||
@@ -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,'
|
||||
|
||||
@@ -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 <keycloak-internal-url>
|
||||
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 <host:port> <query>
|
||||
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 <location> <must contain>... ; 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:-<none>}" >&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" <<EOF
|
||||
{
|
||||
"issuer": "$issuer",
|
||||
"authorization_endpoint": "$auth_url",
|
||||
"token_endpoint": "$issuer/protocol/openid-connect/token",
|
||||
"userinfo_endpoint": "$issuer/protocol/openid-connect/userinfo",
|
||||
"jwks_uri": "$issuer/protocol/openid-connect/certs",
|
||||
"end_session_endpoint": "$issuer/protocol/openid-connect/logout",
|
||||
"response_types_supported": ["code"],
|
||||
"subject_types_supported": ["public"],
|
||||
"id_token_signing_alg_values_supported": ["RS256"]
|
||||
}
|
||||
EOF
|
||||
openssl req -x509 -newkey rsa:2048 -nodes -days 1 -subj "/CN=keycloak.$HOST" \
|
||||
-addext "subjectAltName=DNS:keycloak.$HOST" \
|
||||
-keyout "$work/stub/tls.key" -out "$work/stub/tls.crt" 2>/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&'
|
||||
}
|
||||
@@ -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\&*|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:-<none>}"
|
||||
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:-<none>}"
|
||||
cat "$pf_log"
|
||||
false
|
||||
;;
|
||||
esac
|
||||
rm -f "$pf_log"
|
||||
}
|
||||
|
||||
@test "Aggregated API rejects Tenant name with dashes" {
|
||||
|
||||
@@ -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
|
||||
@@ -248,28 +249,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,
|
||||
},
|
||||
req, err := requestVeleroBackupDeletion(ctx, r.Client, veleroBackupNamespace, veleroBackupName, true)
|
||||
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 req.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
|
||||
}
|
||||
|
||||
|
||||
@@ -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) {
|
||||
@@ -60,12 +63,17 @@ 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.
|
||||
if j.Status.Phase == backupsv1alpha1.BackupJobPhaseSucceeded || j.Status.Phase == backupsv1alpha1.BackupJobPhaseFailed {
|
||||
// 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)
|
||||
}
|
||||
if j.Status.Phase == backupsv1alpha1.BackupJobPhaseSucceeded {
|
||||
logger.V(1).Info("BackupJob already terminal, skipping", "phase", j.Status.Phase)
|
||||
return ctrl.Result{}, nil
|
||||
}
|
||||
@@ -385,9 +393,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 +406,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)
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -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):
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,326 @@
|
||||
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"
|
||||
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"
|
||||
)
|
||||
|
||||
// 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
|
||||
// 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. 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. 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 {
|
||||
return res, fmt.Errorf("failed to list DeleteBackupRequests in %s: %w", namespace, err)
|
||||
}
|
||||
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 {
|
||||
res.pending = dbr
|
||||
return res, nil
|
||||
}
|
||||
if dbr.Name == name {
|
||||
own = dbr
|
||||
}
|
||||
}
|
||||
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})
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
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 res, nil
|
||||
}
|
||||
return res, fmt.Errorf("failed to create DeleteBackupRequest for %s/%s: %w", namespace, name, err)
|
||||
}
|
||||
res.created = true
|
||||
return res, nil
|
||||
}
|
||||
|
||||
const (
|
||||
// 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 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
|
||||
// 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)
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
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 attempted, replaced bool
|
||||
for i := range veleroBackups.Items {
|
||||
vb := &veleroBackups.Items[i]
|
||||
switch vb.Status.Phase {
|
||||
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, 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,
|
||||
waitingRequeue(now, vb.CreationTimestamp.Time, 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
|
||||
}
|
||||
|
||||
req, err := requestVeleroBackupDeletion(ctx, r.Client, vb.Namespace, vb.Name, replaceDue)
|
||||
if err != nil {
|
||||
return ctrl.Result{}, err
|
||||
}
|
||||
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 !attempted {
|
||||
return ctrl.Result{RequeueAfter: requeueAfter}, nil
|
||||
}
|
||||
|
||||
if replaced {
|
||||
retries++
|
||||
}
|
||||
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) {
|
||||
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 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++ {
|
||||
d *= 2
|
||||
}
|
||||
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
|
||||
}
|
||||
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.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{}
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,603 @@
|
||||
package backupcontroller
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"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"
|
||||
"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"
|
||||
velerov1 "github.com/vmware-tanzu/velero/pkg/apis/velero/v1"
|
||||
)
|
||||
|
||||
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 := newVeleroCleanupClient(t, nil, objs...)
|
||||
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 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{
|
||||
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 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},
|
||||
})
|
||||
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. 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) {
|
||||
j := veleroCleanupJob(backupsv1alpha1.BackupJobPhaseRunning)
|
||||
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)
|
||||
}
|
||||
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)
|
||||
}
|
||||
if dbrs := listDeleteBackupRequests(t, c); len(dbrs) != 0 {
|
||||
t.Fatalf("deletion must wait for the next reconcile, got %+v", dbrs)
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// 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)
|
||||
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)
|
||||
}
|
||||
if got := getCleanupJob(t, c); got.Status.Phase != backupsv1alpha1.BackupJobPhaseSucceeded {
|
||||
t.Fatalf("expected BackupJob Succeeded, got %q (%s)", got.Status.Phase, got.Status.Message)
|
||||
}
|
||||
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_SeveralVeleroBackupsKeepCompletedOne(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)
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
// 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
|
||||
wantRequests map[string]velerov1.DeleteBackupRequestPhase
|
||||
wantRequeue time.Duration
|
||||
wantEvent bool
|
||||
}{
|
||||
{
|
||||
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,
|
||||
wantRequests: map[string]velerov1.DeleteBackupRequestPhase{failedVeleroBackup: ""},
|
||||
wantRequeue: failedJobSweepRequeue,
|
||||
},
|
||||
{
|
||||
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(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")},
|
||||
wantRequests: map[string]velerov1.DeleteBackupRequestPhase{failedVeleroBackup: ""},
|
||||
wantRequeue: 2 * failedJobSweepRequeue,
|
||||
wantEvent: true,
|
||||
},
|
||||
{
|
||||
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: "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: failedJobRunningBackupRequeue,
|
||||
},
|
||||
{
|
||||
name: "new backup",
|
||||
veleroPhase: "",
|
||||
jobPhase: backupsv1alpha1.BackupJobPhaseFailed,
|
||||
wantRequeue: failedJobRunningBackupRequeue,
|
||||
},
|
||||
{
|
||||
name: "succeeded job",
|
||||
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(failedVeleroBackup, tc.veleroPhase)}, tc.existing...)
|
||||
r, c := newVeleroCleanupReconciler(t, objs...)
|
||||
if tc.uncached != nil {
|
||||
r.APIReader = newVeleroCleanupClient(t, nil, tc.uncached...)
|
||||
}
|
||||
|
||||
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.wantRequests) {
|
||||
t.Fatalf("expected requests %v, got %+v", tc.wantRequests, dbrs)
|
||||
}
|
||||
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 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)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
expectEvent("first request", false)
|
||||
|
||||
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)
|
||||
}
|
||||
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("%s: expected one request, got %d", step, n)
|
||||
}
|
||||
}
|
||||
|
||||
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 {
|
||||
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
|
||||
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)
|
||||
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)
|
||||
}
|
||||
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"))
|
||||
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)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -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()
|
||||
@@ -360,6 +360,8 @@ 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)
|
||||
return r.markBackupJobFailed(ctx, j, message)
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -193,12 +194,20 @@ 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)
|
||||
// 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"
|
||||
if selected {
|
||||
labels[corev1alpha1.TenantResourceLabelKey] = corev1alpha1.TenantResourceLabelValue
|
||||
}
|
||||
return labels, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,148 @@
|
||||
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
|
||||
// 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;
|
||||
// "" means the response must not touch the label at all.
|
||||
want string
|
||||
}{
|
||||
{
|
||||
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 {
|
||||
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)
|
||||
}
|
||||
|
||||
req := admissionv1.AdmissionRequest{
|
||||
Kind: metav1.GroupVersionKind{Version: "v1", Kind: "Secret"},
|
||||
Namespace: "tenant-demo",
|
||||
Name: tt.secret,
|
||||
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)
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
@@ -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
|
||||
|
||||
+12
-4
@@ -337,10 +337,18 @@ 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 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. 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.
|
||||
|
||||
@@ -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: [""]
|
||||
@@ -165,7 +166,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"]
|
||||
|
||||
@@ -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=<alias> 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 }}
|
||||
@@ -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
|
||||
|
||||
@@ -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.<host> 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}
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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.
|
||||
|
||||
Reference in new issue
Block a user