diff --git a/docs/gpu-vgpu.md b/docs/gpu-vgpu.md index 405d594cd..5d4d1013f 100644 --- a/docs/gpu-vgpu.md +++ b/docs/gpu-vgpu.md @@ -39,9 +39,9 @@ The `default` (passthrough) variant assumes the GPU is **owned by the host kerne **`FORCE_REINSTALL` does not bypass this.** `k8s-driver-manager` v0.10.0 exposes a `FORCE_REINSTALL` / `--force-reinstall` env+flag pair (visible in the binary's strings table), but it gates a later "same-config already loaded" branch inside `uninstallDriver`, not the `isHostDriver` short-circuit at the top — operators who set it and expect a bypass will report a false bug. There is currently no opt-out for the `isHostDriver` guard itself. -**Current mitigation.** The only mitigation available on `main` today is to remove the host NVIDIA stack before enabling the variant (the "Clean-host workaround" section below). +**Current mitigation.** The only mitigation that keeps VM passthrough working is to remove the host NVIDIA stack before enabling the variant (the "Clean-host workaround" section below). -**Future alternatives and scope.** An upcoming `container` variant of `cozystack.gpu-operator` is tracked in [#2766](https://github.com/cozystack/cozystack/pull/2766) — once merged it will give operators a no-purge path that keeps the host driver and exposes GPUs to pods rather than VMs — but it is not part of the current package and is **not** a usable workaround until it lands. Talos is unaffected because the Talos image ships only the `vfio-pci` extension; this section applies to Linux distributions where you installed the host driver yourself (typically Ubuntu / Debian / RHEL with `apt install nvidia-driver-*` or equivalent). See also [`packages/system/gpu-operator/examples/README.md`](../packages/system/gpu-operator/examples/README.md) for the native-pod-workload reference flow that predates the `container` variant. +**Alternatives and scope.** The `container` variant of `cozystack.gpu-operator` is the no-purge path: it keeps the host driver and exposes GPUs to pods rather than VMs, so it does not replace passthrough for anyone who actually needs a GPU inside a VM. Talos is unaffected because the Talos image ships only the `vfio-pci` extension; this section applies to Linux distributions where you installed the host driver yourself (typically Ubuntu / Debian / RHEL with `apt install nvidia-driver-*` or equivalent). See also [`packages/system/gpu-operator/examples/README.md`](../packages/system/gpu-operator/examples/README.md) for the native-pod-workload reference flow that predates the `container` variant. ### Symptom @@ -147,10 +147,10 @@ kubectl label node nvidia.com/gpu.deploy.driver- ### Known limitation -The skip-on-pre-installed behavior lives in the upstream [`NVIDIA/k8s-driver-manager`](https://github.com/NVIDIA/k8s-driver-manager) Go binary at `cmd/driver-manager/main.go`: the method `(*DriverManager).isHostDriver` is called from `(*DriverManager).uninstallDriver` and has no in-band opt-out in `:v0.10.0`. `FORCE_REINSTALL` exists as an env / CLI flag in the same binary but gates the later "same-config already loaded" branch inside `uninstallDriver`, not the `isHostDriver` short-circuit. Hosts that need to keep the NVIDIA host driver installed for non-Kubernetes workloads cannot currently share the same GPU with the passthrough variant. Two future mitigation paths are in flight; **neither is available today**: +The skip-on-pre-installed behavior lives in the upstream [`NVIDIA/k8s-driver-manager`](https://github.com/NVIDIA/k8s-driver-manager) Go binary at `cmd/driver-manager/main.go`: the method `(*DriverManager).isHostDriver` is called from `(*DriverManager).uninstallDriver` and has no in-band opt-out in `:v0.10.0`. `FORCE_REINSTALL` exists as an env / CLI flag in the same binary but gates the later "same-config already loaded" branch inside `uninstallDriver`, not the `isHostDriver` short-circuit. Hosts that need to keep the NVIDIA host driver installed for non-Kubernetes workloads cannot currently share the same GPU with the passthrough variant. Two mitigation paths: -- **`container` variant — not yet merged** — [#2766](https://github.com/cozystack/cozystack/pull/2766) adds a third variant of `cozystack.gpu-operator` that targets the apt-installed-driver host shape and exposes GPUs to pods (not VMs) without unbinding the host driver. Once it lands, operators on hosts where the purge workaround is unacceptable will have a path that does not require touching the host driver. -- **Upstream override** — an env-var override of `isHostDriver` is the only structural fix that would let the passthrough variant coexist with a host driver. Requested in [NVIDIA/k8s-driver-manager#191](https://github.com/NVIDIA/k8s-driver-manager/issues/191). +- **`container` variant** — a third variant of `cozystack.gpu-operator` that targets the apt-installed-driver host shape and exposes GPUs to pods (not VMs) without unbinding the host driver. Available now, and selectable from platform values with `bundles.iaas.gpuOperatorVariant: container`. It solves the host-driver conflict by giving up VM passthrough, so it is a mitigation only for workloads that can run in a pod. +- **Upstream override** — an env-var override of `isHostDriver` is the only structural fix that would let the passthrough variant coexist with a host driver. Not available today; requested in [NVIDIA/k8s-driver-manager#191](https://github.com/NVIDIA/k8s-driver-manager/issues/191). ## Building the vGPU Manager image @@ -218,13 +218,13 @@ For Pascal–Ampere GPUs (V100, T4, A100, A30) the mdev model still applies. Fli ## KubeVirt configuration -When `cozystack.gpu-operator` is in `bundles.enabledPackages` (and not also in `bundles.disabledPackages`), the platform mirrors the chosen GPU variant into the `KubeVirt` CR automatically. There is no manual `kubectl patch` step. +When `cozystack.gpu-operator` is in `bundles.enabledPackages` (and not also in `bundles.disabledPackages`), the platform mirrors the chosen GPU variant into the `KubeVirt` CR automatically. There is no manual `kubectl patch` step. This applies to the two VM variants only: `container` serves GPUs to pods and never to VMs, so selecting it emits the gpu-operator Package with no host-device wiring on the KubeVirt side. If you opt out of bundle management and hand-craft a `cozystack.gpu-operator` Package CR directly — typically to apply overrides the bundle does not expose (driver settings, custom node selectors, validator / dcgmExporter tweaks, etc.) — the platform does NOT auto-wire `HostDevices` or `permittedHostDevices` into the KubeVirt CR. In that flow you also hand-craft a `cozystack.kubevirt` Package CR with `components.kubevirt.values.extraFeatureGates: [HostDevices]` and the appropriate `permittedHostDevices` block. The escape-hatch values shape under `.gpu` (below) is intentionally documented in the bundle-managed flow only; the manual Package-CR override path takes precedence over the bundle render whenever both exist. - `developerConfiguration.featureGates` gets `HostDevices` appended (current KubeVirt splits this from the `GPU` gate; the admission webhook rejects `spec.template.spec.domain.devices.hostDevices` without it). -- `permittedHostDevices.pciHostDevices` is filled from `packages/core/platform/files/gpu-passthrough-defaults.yaml` when `bundles.iaas.gpuOperatorVariant: default` (the package default). The table covers Hopper (H100/H200), Ada Lovelace (L4/L40/L40S), Ampere (A100 PCIe/SXM, A40, A30, A10), Turing (T4), Volta (V100/V100S). All entries carry `externalResourceProvider: true` because the resource names come from `nvidia-sandbox-device-plugin`, not from KubeVirt's in-tree device plugin. -- `permittedHostDevices.mediatedDevices` is filled from `packages/core/platform/files/gpu-vgpu-defaults.yaml` when `bundles.iaas.gpuOperatorVariant: vgpu`. This list only EXPOSES, by profile name (`mdevNameSelector`), mdevs that the GPU Operator's vGPU Device Manager CREATES on the node; the platform does not ship a numeric `mediatedDevicesConfiguration` default (those `nvidia-NNN` type ids are per-SKU/driver sysfs indices with no portable value — set `.gpu.mediatedDevicesConfiguration` yourself, with host-verified ids, only if you want KubeVirt rather than the Device Manager to create mdevs). The starter set covers Pascal–Ampere mdev profiles (A100-40C/80C, A40-24Q/48Q, A30-24C, A10-24Q, V100D-32C, T4-16Q) — the same family range as the upstream `vgpu-device-manager` walks `/sys/class/mdev_bus/` for. Ada Lovelace / Blackwell SR-IOV vGPU is out of scope for the chart's default list; advertise those VFs via the user-override hook below. +- `permittedHostDevices.pciHostDevices` is filled from `packages/core/platform/files/gpu-passthrough-defaults.yaml` when `bundles.iaas.gpuOperatorVariant: default` (the package default) and `gpu.replaceDefaults` is left at `false`. The table covers Hopper (H100/H200), Ada Lovelace (L4/L40/L40S), Ampere (A100 PCIe/SXM, A40, A30, A10), Turing (T4), Volta (V100/V100S). All entries carry `externalResourceProvider: true` because the resource names come from `nvidia-sandbox-device-plugin`, not from KubeVirt's in-tree device plugin. +- `permittedHostDevices.mediatedDevices` is filled from `packages/core/platform/files/gpu-vgpu-defaults.yaml` when `bundles.iaas.gpuOperatorVariant: vgpu` **and** `gpu.vgpuDeviceManager.enabled: true` — that knob defaults to `false`, so a stock vgpu cluster ships no mdev table at all (see the Ada Lovelace / Blackwell note below for why). `gpu.replaceDefaults: true` also suppresses it. This list only EXPOSES, by profile name (`mdevNameSelector`), mdevs that the GPU Operator's vGPU Device Manager CREATES on the node; the platform does not ship a numeric `mediatedDevicesConfiguration` default (those `nvidia-NNN` type ids are per-SKU/driver sysfs indices with no portable value — set `.gpu.mediatedDevicesConfiguration` yourself, with host-verified ids, only if you want KubeVirt rather than the Device Manager to create mdevs). The starter set covers Pascal–Ampere mdev profiles (A100-40C/80C, A40-24Q/48Q, A30-24C, A10-24Q, V100D-32C, T4-16Q) — the same family range as the upstream `vgpu-device-manager` walks `/sys/class/mdev_bus/` for. Ada Lovelace / Blackwell SR-IOV vGPU is out of scope for the chart's default list; advertise those VFs via the user-override hook below. ### Extending or replacing the default table @@ -232,11 +232,13 @@ The platform exposes three knobs under `.gpu`: ```yaml gpu: - # Extend the platform defaults with cluster-specific entries. Both list - # keys are read in both variants: pciHostDevices feeds the passthrough + # Extend the platform defaults with cluster-specific entries. Read by + # the two VM variants only; the container variant reads neither key. + # pciHostDevices is read in both of them — it feeds the passthrough # (vfio-pci) path AND the post-kubevirt#16890 SR-IOV vGPU VF path on - # Ada Lovelace / Blackwell; mediatedDevices feeds the pre-#16890 mdev - # path on Pascal–Ampere. Both render into the same KubeVirt CR. + # Ada Lovelace / Blackwell. mediatedDevices is read in vgpu alone, for + # the pre-#16890 mdev path on Pascal–Ampere; the passthrough variant + # ignores it. Both render into the same KubeVirt CR. permittedHostDevices: pciHostDevices: - pciVendorSelector: "10DE:26B9" # L40S, advertised as a VF for SR-IOV vGPU diff --git a/docs/security/self-assessment.md b/docs/security/self-assessment.md index d4315d1a1..d41dd4da6 100644 --- a/docs/security/self-assessment.md +++ b/docs/security/self-assessment.md @@ -93,6 +93,7 @@ Actors are decomposed by **trust boundary**: two components are distinct actors - **Upstream-only vulnerabilities** not introduced or worsened by Cozystack packaging or defaults. - **Ingress-side isolation of tenant pods.** Tenant-pod ingress is open to `world` and `cluster`, so a tenant pod is reachable by any in-cluster peer whose own egress permits it (platform components) or by a workload not governed by Cozystack's tenant egress policies. Cross-tenant isolation is enforced on the *egress* side, not tenant-pod ingress. - **Blocking cross-tenant reachability through externally-exposed services.** If a tenant publishes a LoadBalancer external IP, another tenant can reach it via `world` egress. +- **Network isolation between tenants on a hosted cluster without Cilium.** On the `isp-hosted` and `isp-hosted-slim` variants the CNI belongs to the host, and tenant Cilium policies are created only if the host serves the Cilium policy API. Without it, tenants get no network isolation from Cozystack, and isolating them is up to the host. - **Noisy-neighbour / side-channel** guarantees for co-located tenant pods beyond namespace scoping (and, for tenant Kubernetes/VMs, virtualization). - Acting as an **egress firewall**: tenant workloads may egress to `world` by default. - Supporting **pre-release builds and end-of-life versions**. diff --git a/docs/security/threat-model.md b/docs/security/threat-model.md index f1bedb91a..2d40bf661 100644 --- a/docs/security/threat-model.md +++ b/docs/security/threat-model.md @@ -83,6 +83,7 @@ The following are explicitly out of scope for the platform's security guarantees - **Upstream-only vulnerabilities** that Cozystack packaging and defaults do not introduce or worsen. - **Ingress-side isolation of tenant pods.** Tenant-pod ingress is open to the `world` and `cluster` entities, so a tenant pod is reachable by any in-cluster peer whose own egress permits it (platform components) and by a workload not governed by Cozystack's tenant egress policies (e.g. a privileged or system pod). Cross-tenant isolation is enforced on the *egress* side, not on tenant-pod ingress. - **Blocking cross-tenant reachability through externally-exposed services.** If a tenant publishes a LoadBalancer with an external IP, another tenant can reach it via `world` egress. +- **Network isolation between tenants on a hosted cluster without Cilium.** On the `isp-hosted` and `isp-hosted-slim` variants the CNI belongs to the host, and the tenant chart creates its Cilium policies only if the host serves the Cilium policy API (`packages/apps/tenant/templates/_helpers.tpl`, helper `tenant.ciliumPolicies`). Without it, tenants get no network isolation from Cozystack, and isolating them is up to the host. - **Noisy-neighbour and side-channel guarantees** for co-located tenant pods beyond namespace scoping (and, for tenant Kubernetes/VMs, virtualization). Co-located pods are not claimed to be side-channel isolated. - **Acting as an egress firewall.** Tenant workloads are allowed egress to `world` by default (`packages/apps/tenant/templates/networkpolicy.yaml`). - **Supporting pre-release builds and end-of-life versions** (`SECURITY.md`). diff --git a/examples/backups/vmi/scenario-user-restore.md b/examples/backups/vmi/scenario-user-restore.md index 1d35b22b0..b52453c45 100644 --- a/examples/backups/vmi/scenario-user-restore.md +++ b/examples/backups/vmi/scenario-user-restore.md @@ -39,6 +39,22 @@ The backup controller performs the following steps automatically: After the Velero Restore completes, the HelmReleases resume and the VM boots with the restored disk data while retaining its original IP and MAC addresses. +### Reclaiming the kept disks + +With `keepOriginalPVC: true`, the default, step 3 switches each disk's PV to the `Retain` reclaim policy so that it outlives the PVC it is renamed from. Nothing removes the `-orig` PVCs or sets the policy back afterwards: they stay until an operator deletes them. + +The policy the PV had before the restore is recorded in the `backups.cozystack.io/original-reclaim-policy` annotation, on the PV and on the `-orig` PVC. Set it back on the PV before deleting the `-orig` PVC, or a PV that was `Delete` stays `Retain` once released and its volume is never reclaimed. A PVC renamed by an older controller carries no annotation; the snippet then leaves the PV on `Retain` for you to decide. + +```bash +PVC=vm-disk-ubuntu-source-orig-1a2b +PV=$(kubectl -n "$NAMESPACE" get pvc "$PVC" -o jsonpath='{.spec.volumeName}') +POLICY=$(kubectl get pv "$PV" -o jsonpath='{.metadata.annotations.backups\.cozystack\.io/original-reclaim-policy}') +kubectl patch pv "$PV" --type=merge -p "{\"spec\":{\"persistentVolumeReclaimPolicy\":\"${POLICY:-Retain}\"}}" +kubectl -n "$NAMESPACE" delete pvc "$PVC" +``` + +The `` is derived from the RestoreJob name, so an `-orig` PVC left behind by a deleted RestoreJob takes the name a new RestoreJob of the same name would use. That RestoreJob fails before it halts the VM, naming the PVC, rather than restoring without keeping the current disk. Reclaim the leftover PVC as above, or give the new RestoreJob another name. + ## Method 2: Cross-Namespace Restore (Copy) ```bash diff --git a/hack/capi-core-components_test.bats b/hack/capi-core-components_test.bats new file mode 100644 index 000000000..4a9689279 --- /dev/null +++ b/hack/capi-core-components_test.bats @@ -0,0 +1,32 @@ +#!/usr/bin/env bats +# capi-providers-core ships the Cluster API core manifests twice: as +# files/core-components.yaml, which a reviewer reads, and as files/components.gz, +# which the chart mounts into the cluster. Both are edited by hand; this package +# has no `make components`. An edit to the YAML alone reviews cleanly and changes +# nothing in a cluster, which is how the startupProbe from #2946 stayed out of +# the shipped manager. This holds the two files to the same bytes. +# +# The comparison is on the decompressed bytes, so the gzip header plays no part +# in it. `gzip -n` is still the flag to regenerate with: without it the header +# carries a timestamp and every regeneration rewrites the committed blob even +# when the input has not changed. + +REPO_ROOT="$(cd "$(dirname "${BATS_TEST_FILENAME:-$0}")/.." && pwd)" +FILES="$REPO_ROOT/packages/system/capi-providers-core/files" + +@test "core provider components.gz matches core-components.yaml" { + [ -f "$FILES/core-components.yaml" ] || { echo "missing core-components.yaml" >&2; return 1; } + [ -f "$FILES/components.gz" ] || { echo "missing components.gz" >&2; return 1; } + + local work; work="$(mktemp -d)" + gzip -dc "$FILES/components.gz" > "$work/decompressed.yaml" + if ! cmp -s "$work/decompressed.yaml" "$FILES/core-components.yaml"; then + echo "components.gz does not match core-components.yaml" >&2 + echo "the chart mounts the blob, so the cluster would run what the YAML does not say" >&2 + echo "regenerate: gzip -9 -n -c files/core-components.yaml > files/components.gz" >&2 + diff "$work/decompressed.yaml" "$FILES/core-components.yaml" | head -20 >&2 || true + rm -rf "$work" + return 1 + fi + rm -rf "$work" +} diff --git a/hack/capi-operator_test.bats b/hack/capi-operator_test.bats new file mode 100644 index 000000000..5a1f485e7 --- /dev/null +++ b/hack/capi-operator_test.bats @@ -0,0 +1,23 @@ +#!/usr/bin/env bats +# The operator's resync period is what bounds the stale-Ready window after an +# operator restart (kubernetes-sigs/cluster-api-operator#1031): about two +# periods. It reaches the manager only through patches/sync-period.diff, which +# `make update` has to reapply on every re-vendor, and through the value in +# values.yaml. Losing either silently returns the window to about 20 minutes, +# so this checks the argument the rendered Deployment actually carries. + +REPO_ROOT="$(cd "$(dirname "${BATS_TEST_FILENAME:-$0}")/.." && pwd)" +OPERATOR="$REPO_ROOT/packages/system/capi-operator" + +@test "the operator manager runs with a one-minute resync period" { + local rendered args + rendered="${BATS_TEST_TMPDIR:-${tmp:?cozytest workspace is missing}}/operator.yaml" + helm template capi-operator "$OPERATOR" --namespace cozy-cluster-api > "$rendered" + args="$(yq -N 'select(.kind == "Deployment") | .spec.template.spec.containers[] | select(.name == "manager") | .args[]' "$rendered")" + [ -n "$args" ] || { echo "no manager container args rendered from $OPERATOR" >&2; return 1; } + case "$(printf '%s\n' "$args" | grep -c '^--sync-period=')" in + 1) ;; + *) echo "expected exactly one --sync-period in the manager args, got:" >&2; echo "$args" >&2; return 1 ;; + esac + printf '%s\n' "$args" | grep -qx -- '--sync-period=1m' || { echo "manager args: $args" >&2; return 1; } +} diff --git a/hack/console-nginx-header-buffers.bats b/hack/console-nginx-header-buffers.bats new file mode 100644 index 000000000..20fa9a046 --- /dev/null +++ b/hack/console-nginx-header-buffers.bats @@ -0,0 +1,77 @@ +#!/usr/bin/env bats +# The console image bakes its nginx config into the Containerfile as an inline +# heredoc, so no chart template and no helm-unittest case can see it. This pins +# the header-buffer pair that image ships. The per-buffer size in +# large_client_header_buffers is what bounds a single Cookie header: on the +# default 4 8k an access token carrying many group claims does not fit one +# buffer, and nginx answers 400 "request header or cookie too large" before the +# request reaches the /apis, /api or /k8s/ upstream. client_header_buffer_size +# is raised alongside it so such a request is read without escalating to a large +# buffer at all. Either line is cheap to drop in an unrelated rewrite of that +# config, and the loss is invisible until a user with a big token logs in. +# +# The check reads the heredoc body, not the whole Containerfile, so a directive +# that moved out of the served config -- into a comment, or into a build stage +# that ships nothing -- does not read as present. +# +# Harness note: the CI path is hack/cozytest.sh, NOT real bats. No `run`, +# `$status`, `$output`, `skip` or setup()/teardown(); each @test is a shell +# function under `set -eu -x`, and paths resolve from the repo root. The two +# runners disagree on negative assertions, so an assertion written for bats can +# be vacuous under the one that gates a merge. +# Run with: hack/cozytest.sh hack/console-nginx-header-buffers.bats + +REPO_ROOT="$(cd "$(dirname "${BATS_TEST_FILENAME:-$0}")/.." && pwd)" +CONSOLE_CONTAINERFILE="packages/system/dashboard/images/console/Containerfile" + +# Prints an nginx size in KiB, or -1 for a spelling this check cannot read. +nginx_size_kib() { + printf '%s\n' "$1" | awk ' + /^[0-9]+[kK]$/ { print int(substr($0, 1, length($0) - 1)); next } + /^[0-9]+[mM]$/ { print int(substr($0, 1, length($0) - 1)) * 1024; next } + /^[0-9]+$/ { print int($0 / 1024); next } + { print -1 } + ' +} + +@test "console nginx config reads client request headers into buffers larger than the nginx defaults" { + cd "$REPO_ROOT" + + conf=$(awk ' + /^COPY <<.EOF. \/etc\/nginx\/conf\.d\/default\.conf$/ { inblock = 1; next } + inblock && /^EOF$/ { inblock = 0; next } + inblock { print } + ' "$CONSOLE_CONTAINERFILE") + [ -n "$conf" ] || { echo "no /etc/nginx/conf.d/default.conf heredoc found in $CONSOLE_CONTAINERFILE" >&2; exit 1; } + + # An extraction that silently grabbed the wrong slice would let every + # assertion below pass on an empty-ish config, so anchor on a line the + # served config is known to carry. + printf '%s\n' "$conf" | grep -q 'proxy_pass https://kubernetes.default.svc:443;' \ + || { echo "extracted heredoc carries no apiserver proxy_pass; the extraction is wrong, not the config" >&2; exit 1; } + + header_buffer=$(printf '%s\n' "$conf" | awk '$1 == "client_header_buffer_size" { sub(/;$/, "", $2); print $2 }') + [ -n "$header_buffer" ] || { echo "client_header_buffer_size is absent; the console ships it at 16k next to large_client_header_buffers" >&2; exit 1; } + header_buffer_kib=$(nginx_size_kib "$header_buffer") + [ "$header_buffer_kib" -ge 16 ] \ + || { echo "client_header_buffer_size reads as $header_buffer, and this check wants at least 16k" >&2; exit 1; } + + # Third field, because the directive is `large_client_header_buffers ` + # and it is the per-buffer size that bounds one Cookie header. + large_buffer=$(printf '%s\n' "$conf" | awk '$1 == "large_client_header_buffers" { sub(/;$/, "", $3); print $3 }') + [ -n "$large_buffer" ] || { echo "large_client_header_buffers is absent: a Cookie header over 8k gets a 400 from the console nginx" >&2; exit 1; } + large_buffer_kib=$(nginx_size_kib "$large_buffer") + [ "$large_buffer_kib" -ge 16 ] \ + || { echo "large_client_header_buffers reads as $large_buffer per buffer, and a large OIDC token needs at least 16k" >&2; exit 1; } + + # Placement, not only presence. A header field read before the Host header + # has selected the virtual server is measured against the default server's + # buffers, so the same lines inside a server block cover that server only + # while it stays the default one. The shipped config puts them ahead of the + # first server block, and that is the shape checked here. + prelude=$(printf '%s\n' "$conf" | awk '/^server[[:space:]]*{/ { exit } { print }') + printf '%s\n' "$prelude" | grep -q '^client_header_buffer_size' \ + || { echo "client_header_buffer_size does not stand at the top of the config, ahead of the first server block" >&2; exit 1; } + printf '%s\n' "$prelude" | grep -q '^large_client_header_buffers' \ + || { echo "large_client_header_buffers does not stand at the top of the config, ahead of the first server block" >&2; exit 1; } +} diff --git a/internal/backupcontroller/backupjob_controller.go b/internal/backupcontroller/backupjob_controller.go index edbadbb56..e7145eec0 100644 --- a/internal/backupcontroller/backupjob_controller.go +++ b/internal/backupcontroller/backupjob_controller.go @@ -135,6 +135,23 @@ func (r *BackupJobReconciler) Reconcile(ctx context.Context, req ctrl.Request) ( return r.markBackupJobFailed(ctx, j, fmt.Sprintf("strategy Kind %q is not supported by this controller (supported: %s)", strategyRef.Kind, strings.Join(supportedBackupStrategyKinds(), ", "))) } + // Hold a run that has not started while a restore writes into its + // application. Only before StartedAt: every driver stamps it on its + // first pass, and a run already moving data is not interrupted here. + if j.Status.StartedAt == nil { + restore, err := activeRestoreTargeting(ctx, r.Client, j.Namespace, normalizedAppRef) + if err != nil { + logger.Error(err, "failed to check for a restore in progress") + return ctrl.Result{}, err + } + if restore != "" { + return r.holdForRestore(ctx, j, restore) + } + if err := r.releaseRestoreHold(ctx, j); err != nil { + return ctrl.Result{}, err + } + } + // Now project the platform-managed S3 credentials into the tenant // namespace so default Strategy CRs can reference a deterministic // Secret name. The projection is idempotent and silently skipped on diff --git a/internal/backupcontroller/backupjob_restore_lock.go b/internal/backupcontroller/backupjob_restore_lock.go new file mode 100644 index 000000000..06f165285 --- /dev/null +++ b/internal/backupcontroller/backupjob_restore_lock.go @@ -0,0 +1,170 @@ +// SPDX-License-Identifier: Apache-2.0 +package backupcontroller + +import ( + "context" + "encoding/json" + "fmt" + "sort" + "time" + + corev1 "k8s.io/api/core/v1" + "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" + + strategyv1alpha1 "github.com/cozystack/cozystack/api/backups/strategy/v1alpha1" + backupsv1alpha1 "github.com/cozystack/cozystack/api/backups/v1alpha1" +) + +// RestoreInProgressRequeue is how often a BackupJob held by a restore checks +// again. Restores run for minutes, so there is nothing to gain from polling +// faster. +const RestoreInProgressRequeue = 30 * time.Second + +// ConditionReasonRestoreInProgress is the Ready=False reason of a BackupJob +// held back because its application is being restored. +const ConditionReasonRestoreInProgress = "RestoreInProgress" + +// activeRestoreTargeting returns the name of a non-terminal RestoreJob in +// namespace that writes into app, or "" when there is none. +// +// A backup must not start against an application a restore is rewriting. It +// would capture a half-restored state at best, and on the CNPG path it does +// worse: every BackupJob reconcile re-applies the Cluster's barman plugin, and +// one landing between the restore re-rendering the Cluster with its new +// serverName and the plugin being attached can put the restored cluster back +// on the source's WAL prefix, where its recovery fails with "Expected empty +// archive". Plan-created runs are the ones that hit this, since nothing else +// looks at restores before creating a BackupJob. +func activeRestoreTargeting(ctx context.Context, c client.Client, namespace string, app corev1.TypedLocalObjectReference) (string, error) { + app = NormalizeApplicationRef(app) + list := &backupsv1alpha1.RestoreJobList{} + if err := c.List(ctx, list, client.InNamespace(namespace)); err != nil { + return "", fmt.Errorf("list RestoreJobs: %w", err) + } + var holding []string + for i := range list.Items { + rj := &list.Items[i] + if rj.Status.Phase == backupsv1alpha1.RestoreJobPhaseSucceeded || rj.Status.Phase == backupsv1alpha1.RestoreJobPhaseFailed { + continue + } + target, ok, err := restoreJobTarget(ctx, c, rj) + if err != nil { + return "", err + } + if ok && sameApplication(target, app) { + holding = append(holding, rj.Name) + } + } + if len(holding) == 0 { + return "", nil + } + sort.Strings(holding) + return holding[0], nil +} + +// restoreJobTarget resolves the application a RestoreJob writes into in its +// own namespace, as the drivers resolve it (resolveCNPGRestoreTarget and the +// Job-based paths): the Backup's applicationRef, with the target's kind and +// name when a target is set — the CRD requires both — and the target's API +// group only when it names one. A target without an API group therefore stays +// in the Backup's group, which is not always the default one. The Velero +// driver drops the target's API group (resolveRestoreTarget) and restores the +// Backup's resources, so a Velero restore always stays in the Backup's group. +// +// It reports false for a restore that writes nothing here. One whose Backup is +// gone is failed by the restore controller on its next pass. A Velero restore +// whose options name another namespace writes there: only the Velero driver +// reads options.targetNamespace, so the option is looked at only when the +// Backup's strategy is Velero — the CNPG and Job-based drivers ignore it and +// restore in place. +func restoreJobTarget(ctx context.Context, c client.Client, rj *backupsv1alpha1.RestoreJob) (corev1.TypedLocalObjectReference, bool, error) { + backup := &backupsv1alpha1.Backup{} + if err := c.Get(ctx, client.ObjectKey{Namespace: rj.Namespace, Name: rj.Spec.BackupRef.Name}, backup); err != nil { + if client.IgnoreNotFound(err) == nil { + return corev1.TypedLocalObjectReference{}, false, nil + } + return corev1.TypedLocalObjectReference{}, false, fmt.Errorf("get Backup %s of RestoreJob %s: %w", rj.Spec.BackupRef.Name, rj.Name, err) + } + if backup.Spec.StrategyRef.Kind == strategyv1alpha1.VeleroStrategyKind && restoresIntoAnotherNamespace(rj, backup.Namespace) { + return corev1.TypedLocalObjectReference{}, false, nil + } + ref := backup.Spec.ApplicationRef + if t := rj.Spec.TargetApplicationRef; t != nil { + ref.Kind, ref.Name = t.Kind, t.Name + if t.APIGroup != nil && backup.Spec.StrategyRef.Kind != strategyv1alpha1.VeleroStrategyKind { + ref.APIGroup = t.APIGroup + } + } + return NormalizeApplicationRef(ref), true, nil +} + +// restoresIntoAnotherNamespace reports whether a Velero RestoreJob's +// options.targetNamespace sends it away from namespace, compared as the Velero +// driver compares it. Options that do not parse are read as none. +func restoresIntoAnotherNamespace(rj *backupsv1alpha1.RestoreJob, namespace string) bool { + if rj.Spec.Options == nil || len(rj.Spec.Options.Raw) == 0 { + return false + } + var opts struct { + TargetNamespace string `json:"targetNamespace"` + } + if err := json.Unmarshal(rj.Spec.Options.Raw, &opts); err != nil { + return false + } + return opts.TargetNamespace != "" && opts.TargetNamespace != namespace +} + +// sameApplication expects both references normalized: an API group left +// unset compares equal only once it has been defaulted on both sides. +func sameApplication(a, b corev1.TypedLocalObjectReference) bool { + return a.Kind == b.Kind && a.Name == b.Name && ptrString(a.APIGroup) == ptrString(b.APIGroup) +} + +func ptrString(s *string) string { + if s == nil { + return "" + } + return *s +} + +// holdForRestore keeps a BackupJob that has not started yet waiting while a +// restore writes into its application. It stays non-terminal, so a scheduled +// run still happens once the restore ends, only later than its slot. +// +// A failed status write is returned so the manager retries it with backoff. +// The job is held either way, since nothing past the gate ran, but a hold +// nobody can see reads as a run stuck for no reason. +func (r *BackupJobReconciler) holdForRestore(ctx context.Context, j *backupsv1alpha1.BackupJob, restore string) (ctrl.Result, error) { + if j.Status.Phase == backupsv1alpha1.BackupJobPhaseEmpty { + j.Status.Phase = backupsv1alpha1.BackupJobPhasePending + } + meta.SetStatusCondition(&j.Status.Conditions, metav1.Condition{ + Type: "Ready", + Status: metav1.ConditionFalse, + Reason: ConditionReasonRestoreInProgress, + Message: fmt.Sprintf("waiting for RestoreJob %q to finish: application %s/%s is being restored", restore, j.Spec.ApplicationRef.Kind, j.Spec.ApplicationRef.Name), + }) + if err := r.Status().Update(ctx, j); err != nil { + return ctrl.Result{}, fmt.Errorf("record RestoreInProgress on BackupJob %s: %w", j.Name, err) + } + return ctrl.Result{RequeueAfter: RestoreInProgressRequeue}, nil +} + +// releaseRestoreHold removes the condition holdForRestore left, once the +// restore has ended and the job goes on to start. Left in place it would read +// "waiting for RestoreJob" until the driver next writes Ready, which for a +// healthy run is when the backup completes. +func (r *BackupJobReconciler) releaseRestoreHold(ctx context.Context, j *backupsv1alpha1.BackupJob) error { + cond := meta.FindStatusCondition(j.Status.Conditions, "Ready") + if cond == nil || cond.Reason != ConditionReasonRestoreInProgress { + return nil + } + meta.RemoveStatusCondition(&j.Status.Conditions, "Ready") + if err := r.Status().Update(ctx, j); err != nil { + return fmt.Errorf("clear RestoreInProgress on BackupJob %s: %w", j.Name, err) + } + return nil +} diff --git a/internal/backupcontroller/backupjob_restore_lock_test.go b/internal/backupcontroller/backupjob_restore_lock_test.go new file mode 100644 index 000000000..edb1972e0 --- /dev/null +++ b/internal/backupcontroller/backupjob_restore_lock_test.go @@ -0,0 +1,341 @@ +// SPDX-License-Identifier: Apache-2.0 +package backupcontroller + +import ( + "context" + "errors" + "testing" + + corev1 "k8s.io/api/core/v1" + "k8s.io/apimachinery/pkg/api/meta" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/types" + "k8s.io/client-go/kubernetes/scheme" + "sigs.k8s.io/controller-runtime/pkg/client" + clientfake "sigs.k8s.io/controller-runtime/pkg/client/fake" + "sigs.k8s.io/controller-runtime/pkg/client/interceptor" + "sigs.k8s.io/controller-runtime/pkg/reconcile" + + strategyv1alpha1 "github.com/cozystack/cozystack/api/backups/strategy/v1alpha1" + backupsv1alpha1 "github.com/cozystack/cozystack/api/backups/v1alpha1" +) + +const lockNS = "tenant-acme" + +func lockTestClient(t *testing.T, objs ...client.Object) client.Client { + t.Helper() + s := runtime.NewScheme() + _ = scheme.AddToScheme(s) + _ = backupsv1alpha1.AddToScheme(s) + return clientfake.NewClientBuilder(). + WithScheme(s). + WithObjects(objs...). + WithStatusSubresource(&backupsv1alpha1.BackupJob{}, &backupsv1alpha1.RestoreJob{}). + Build() +} + +func pgRef(name string) corev1.TypedLocalObjectReference { + return corev1.TypedLocalObjectReference{APIGroup: new("apps.cozystack.io"), Kind: "Postgres", Name: name} +} + +func lockBackup(name string, app corev1.TypedLocalObjectReference) *backupsv1alpha1.Backup { + return lockBackupBy(name, app, strategyv1alpha1.CNPGStrategyKind) +} + +func lockBackupBy(name string, app corev1.TypedLocalObjectReference, strategyKind string) *backupsv1alpha1.Backup { + return &backupsv1alpha1.Backup{ + ObjectMeta: metav1.ObjectMeta{Namespace: lockNS, Name: name}, + Spec: backupsv1alpha1.BackupSpec{ + ApplicationRef: app, + StrategyRef: corev1.TypedLocalObjectReference{APIGroup: new(strategyv1alpha1.GroupVersion.Group), Kind: strategyKind, Name: "s"}, + }, + } +} + +func lockRestore(name, backup string, phase backupsv1alpha1.RestoreJobPhase, target *corev1.TypedLocalObjectReference, options string) *backupsv1alpha1.RestoreJob { + rj := &backupsv1alpha1.RestoreJob{ + ObjectMeta: metav1.ObjectMeta{Namespace: lockNS, Name: name}, + Spec: backupsv1alpha1.RestoreJobSpec{ + BackupRef: corev1.LocalObjectReference{Name: backup}, + TargetApplicationRef: target, + }, + Status: backupsv1alpha1.RestoreJobStatus{Phase: phase}, + } + if options != "" { + rj.Spec.Options = &runtime.RawExtension{Raw: []byte(options)} + } + return rj +} + +func TestActiveRestoreTargeting(t *testing.T) { + other := pgRef("other") + anotherKind := corev1.TypedLocalObjectReference{APIGroup: new("apps.cozystack.io"), Kind: "MariaDB", Name: "pg"} + anotherGroup := corev1.TypedLocalObjectReference{APIGroup: new("example.com"), Kind: "Postgres", Name: "pg"} + vm := corev1.TypedLocalObjectReference{APIGroup: new("apps.cozystack.io"), Kind: "VMInstance", Name: "vm"} + vmInGroup := corev1.TypedLocalObjectReference{APIGroup: new("example.com"), Kind: "VMInstance", Name: "vm"} + pg2InGroup := corev1.TypedLocalObjectReference{APIGroup: new("example.com"), Kind: "Postgres", Name: "pg2"} + pg2Default := pgRef("pg2") + for _, tc := range []struct { + name string + app *corev1.TypedLocalObjectReference // pgRef("pg") when nil + objects []client.Object + want string + }{ + {"no restore", nil, nil, ""}, + {"in-place restore of the same application", nil, []client.Object{ + lockBackup("pg-1", pgRef("pg")), lockRestore("r1", "pg-1", backupsv1alpha1.RestoreJobPhaseRunning, nil, ""), + }, "r1"}, + {"restore not picked up yet", nil, []client.Object{ + lockBackup("pg-1", pgRef("pg")), lockRestore("r1", "pg-1", "", nil, ""), + }, "r1"}, + {"to-copy restore into this application", nil, []client.Object{ + lockBackup("other-1", other), lockRestore("r1", "other-1", backupsv1alpha1.RestoreJobPhaseRunning, &corev1.TypedLocalObjectReference{Kind: "Postgres", Name: "pg"}, ""), + }, "r1"}, + {"to-copy restore out of this application", nil, []client.Object{ + lockBackup("pg-1", pgRef("pg")), lockRestore("r1", "pg-1", backupsv1alpha1.RestoreJobPhaseRunning, &other, ""), + }, ""}, + {"finished restores", nil, []client.Object{ + lockBackup("pg-1", pgRef("pg")), + lockRestore("r1", "pg-1", backupsv1alpha1.RestoreJobPhaseSucceeded, nil, ""), + lockRestore("r2", "pg-1", backupsv1alpha1.RestoreJobPhaseFailed, nil, ""), + }, ""}, + {"same name, another kind", nil, []client.Object{ + lockBackup("m-1", anotherKind), lockRestore("r1", "m-1", backupsv1alpha1.RestoreJobPhaseRunning, nil, ""), + }, ""}, + {"same kind and name, another API group", nil, []client.Object{ + lockBackup("x-1", anotherGroup), lockRestore("r1", "x-1", backupsv1alpha1.RestoreJobPhaseRunning, nil, ""), + }, ""}, + // A target without an API group stays in the Backup's group. + {"to-copy target inheriting the Backup's API group", &pg2InGroup, []client.Object{ + lockBackup("x-1", anotherGroup), lockRestore("r1", "x-1", backupsv1alpha1.RestoreJobPhaseRunning, &corev1.TypedLocalObjectReference{Kind: "Postgres", Name: "pg2"}, ""), + }, "r1"}, + {"to-copy target without an API group is not in the default one", &pg2Default, []client.Object{ + lockBackup("x-1", anotherGroup), lockRestore("r1", "x-1", backupsv1alpha1.RestoreJobPhaseRunning, &corev1.TypedLocalObjectReference{Kind: "Postgres", Name: "pg2"}, ""), + }, ""}, + // Only the Velero driver reads targetNamespace. + {"Velero restore sent to another namespace", &vm, []client.Object{ + lockBackupBy("vm-1", vm, strategyv1alpha1.VeleroStrategyKind), lockRestore("r1", "vm-1", backupsv1alpha1.RestoreJobPhaseRunning, nil, `{"targetNamespace":"tenant-other"}`), + }, ""}, + {"Velero restore naming its own namespace", &vm, []client.Object{ + lockBackupBy("vm-1", vm, strategyv1alpha1.VeleroStrategyKind), lockRestore("r1", "vm-1", backupsv1alpha1.RestoreJobPhaseRunning, nil, `{"targetNamespace":"`+lockNS+`"}`), + }, "r1"}, + // The Velero driver drops the target's API group and restores the + // Backup's resources, in the Backup's group. + {"Velero target naming another API group restores in the Backup's", &vm, []client.Object{ + lockBackupBy("vm-1", vm, strategyv1alpha1.VeleroStrategyKind), lockRestore("r1", "vm-1", backupsv1alpha1.RestoreJobPhaseRunning, &corev1.TypedLocalObjectReference{APIGroup: new("example.com"), Kind: "VMInstance", Name: "vm"}, ""), + }, "r1"}, + {"Velero target naming another API group does not hold that group", &vmInGroup, []client.Object{ + lockBackupBy("vm-1", vm, strategyv1alpha1.VeleroStrategyKind), lockRestore("r1", "vm-1", backupsv1alpha1.RestoreJobPhaseRunning, &corev1.TypedLocalObjectReference{APIGroup: new("example.com"), Kind: "VMInstance", Name: "vm"}, ""), + }, ""}, + {"Postgres restore carrying targetNamespace, which CNPG ignores", nil, []client.Object{ + lockBackup("pg-1", pgRef("pg")), lockRestore("r1", "pg-1", backupsv1alpha1.RestoreJobPhaseRunning, nil, `{"targetNamespace":"tenant-other"}`), + }, "r1"}, + {"backup gone", nil, []client.Object{ + lockRestore("r1", "pg-1", backupsv1alpha1.RestoreJobPhaseRunning, nil, ""), + }, ""}, + // The restore controller fails it on its next pass for want of its + // Backup, however complete its target. + {"backup gone, target complete", nil, []client.Object{ + lockRestore("r1", "pg-1", backupsv1alpha1.RestoreJobPhaseRunning, &corev1.TypedLocalObjectReference{Kind: "Postgres", Name: "pg"}, ""), + }, ""}, + } { + t.Run(tc.name, func(t *testing.T) { + c := lockTestClient(t, tc.objects...) + app := pgRef("pg") + if tc.app != nil { + app = *tc.app + } + got, err := activeRestoreTargeting(context.Background(), c, lockNS, app) + if err != nil { + t.Fatalf("activeRestoreTargeting: %v", err) + } + if got != tc.want { + t.Errorf("got %q, want %q", got, tc.want) + } + }) + } +} + +func lockBackupClass() *backupsv1alpha1.BackupClass { + return &backupsv1alpha1.BackupClass{ + ObjectMeta: metav1.ObjectMeta{Name: "cozy-default"}, + Spec: backupsv1alpha1.BackupClassSpec{ + Strategies: []backupsv1alpha1.BackupClassStrategy{{ + Application: backupsv1alpha1.ApplicationSelector{APIGroup: new("apps.cozystack.io"), Kind: "Postgres"}, + StrategyRef: corev1.TypedLocalObjectReference{ + APIGroup: new(strategyv1alpha1.GroupVersion.Group), Kind: strategyv1alpha1.CNPGStrategyKind, Name: "cozy-default-cnpg", + }, + }}, + }, + } +} + +func lockBackupJob(started bool) *backupsv1alpha1.BackupJob { + j := &backupsv1alpha1.BackupJob{ + ObjectMeta: metav1.ObjectMeta{Namespace: lockNS, Name: "nightly-29842560"}, + Spec: backupsv1alpha1.BackupJobSpec{BackupClassName: "cozy-default", ApplicationRef: pgRef("pg")}, + } + if started { + now := metav1.Now() + j.Status.StartedAt = &now + j.Status.Phase = backupsv1alpha1.BackupJobPhaseRunning + } + return j +} + +// TestReconcile_HoldsABackupJobWhileItsApplicationIsRestored is the +// regression: a Plan-created BackupJob for a Postgres application under an +// in-place restore reached the CNPG driver, which re-applied the Cluster's +// barman plugin and put the restored cluster back on the source's WAL +// prefix. The job must wait, non-terminal, without reaching projection or +// dispatch; and once the restore is over, it must go ahead. +func TestReconcile_HoldsABackupJobWhileItsApplicationIsRestored(t *testing.T) { + restore := lockRestore("restore-pg", "pg-1", backupsv1alpha1.RestoreJobPhaseRunning, nil, "") + c := lockTestClient(t, lockBackupJob(false), lockBackupClass(), lockBackup("pg-1", pgRef("pg")), restore, flatSourceSecret()) + r := &BackupJobReconciler{Client: c, CredentialsConfig: defaultCfg()} + key := types.NamespacedName{Namespace: lockNS, Name: "nightly-29842560"} + + res, err := r.Reconcile(context.Background(), reconcile.Request{NamespacedName: key}) + if err != nil { + t.Fatalf("Reconcile: %v", err) + } + if res.RequeueAfter != RestoreInProgressRequeue { + t.Errorf("RequeueAfter = %v, want %v", res.RequeueAfter, RestoreInProgressRequeue) + } + got := &backupsv1alpha1.BackupJob{} + if err := c.Get(context.Background(), key, got); err != nil { + t.Fatal(err) + } + if got.Status.Phase != backupsv1alpha1.BackupJobPhasePending { + t.Errorf("Phase = %q, want Pending", got.Status.Phase) + } + if got.Status.StartedAt != nil { + t.Error("a held BackupJob must not be marked started") + } + cond := meta.FindStatusCondition(got.Status.Conditions, "Ready") + if cond == nil || cond.Reason != ConditionReasonRestoreInProgress { + t.Fatalf("Ready condition = %+v, want reason %s", cond, ConditionReasonRestoreInProgress) + } + secret := &corev1.Secret{} + if err := c.Get(context.Background(), types.NamespacedName{Namespace: lockNS, Name: "cozy-backups-creds"}, secret); err == nil { + t.Error("a held BackupJob went on to project credentials") + } + + // The restore ends: the job is no longer held. + fresh := &backupsv1alpha1.RestoreJob{} + if err := c.Get(context.Background(), types.NamespacedName{Namespace: lockNS, Name: "restore-pg"}, fresh); err != nil { + t.Fatal(err) + } + fresh.Status.Phase = backupsv1alpha1.RestoreJobPhaseSucceeded + if err := c.Status().Update(context.Background(), fresh); err != nil { + t.Fatal(err) + } + if held, err := activeRestoreTargeting(context.Background(), c, lockNS, pgRef("pg")); err != nil || held != "" { + t.Errorf("after the restore ended: held by %q (%v), want none", held, err) + } + + // The next reconcile starts the job without the hold's condition. + _, _ = r.Reconcile(context.Background(), reconcile.Request{NamespacedName: key}) + released := &backupsv1alpha1.BackupJob{} + if err := c.Get(context.Background(), key, released); err != nil { + t.Fatal(err) + } + if cond := meta.FindStatusCondition(released.Status.Conditions, "Ready"); cond != nil && cond.Reason == ConditionReasonRestoreInProgress { + t.Errorf("Ready = %+v: a job the restore released still says it is waiting for it", cond) + } +} + +// TestReconcile_DoesNotHoldARunningBackupJob: the gate is on starting. A run +// already moving data is left to its driver, whose own state it would +// otherwise strand. +func TestReconcile_DoesNotHoldARunningBackupJob(t *testing.T) { + restore := lockRestore("restore-pg", "pg-1", backupsv1alpha1.RestoreJobPhaseRunning, nil, "") + // No source Secret: projection fails transiently, which stops the + // reconcile before dispatch and shows the gate was passed. + c := lockTestClient(t, lockBackupJob(true), lockBackupClass(), lockBackup("pg-1", pgRef("pg")), restore) + r := &BackupJobReconciler{Client: c, CredentialsConfig: defaultCfg()} + key := types.NamespacedName{Namespace: lockNS, Name: "nightly-29842560"} + + if _, err := r.Reconcile(context.Background(), reconcile.Request{NamespacedName: key}); err != nil { + t.Fatalf("Reconcile: %v", err) + } + got := &backupsv1alpha1.BackupJob{} + if err := c.Get(context.Background(), key, got); err != nil { + t.Fatal(err) + } + if cond := meta.FindStatusCondition(got.Status.Conditions, "Ready"); cond != nil && cond.Reason == ConditionReasonRestoreInProgress { + t.Error("a BackupJob already started was held") + } +} + +// TestReconcile_RetriesAHoldItCouldNotRecord: a hold whose status write fails +// is returned as an error, so the manager retries it, rather than requeued as +// though it had been recorded. +func TestReconcile_RetriesAHoldItCouldNotRecord(t *testing.T) { + s := runtime.NewScheme() + _ = scheme.AddToScheme(s) + _ = backupsv1alpha1.AddToScheme(s) + writeFailed := errors.New("apiserver unavailable") + c := clientfake.NewClientBuilder(). + WithScheme(s). + WithObjects(lockBackupJob(false), lockBackupClass(), lockBackup("pg-1", pgRef("pg")), + lockRestore("restore-pg", "pg-1", backupsv1alpha1.RestoreJobPhaseRunning, nil, ""), flatSourceSecret()). + WithStatusSubresource(&backupsv1alpha1.BackupJob{}, &backupsv1alpha1.RestoreJob{}). + WithInterceptorFuncs(interceptor.Funcs{ + SubResourceUpdate: func(ctx context.Context, cl client.Client, sub string, obj client.Object, opts ...client.SubResourceUpdateOption) error { + if _, ok := obj.(*backupsv1alpha1.BackupJob); ok { + return writeFailed + } + return cl.SubResource(sub).Update(ctx, obj, opts...) + }, + }). + Build() + r := &BackupJobReconciler{Client: c, CredentialsConfig: defaultCfg()} + + res, err := r.Reconcile(context.Background(), reconcile.Request{NamespacedName: types.NamespacedName{Namespace: lockNS, Name: "nightly-29842560"}}) + if !errors.Is(err, writeFailed) { + t.Fatalf("Reconcile error = %v, want the failed status write", err) + } + if res.RequeueAfter != 0 { + t.Errorf("RequeueAfter = %v: a failed hold must be retried through the error, not requeued as recorded", res.RequeueAfter) + } +} + +// TestReleaseRestoreHold: once the restore has ended, the job starts without +// the "waiting for RestoreJob" condition, which the drivers would otherwise +// leave in place for the whole run. Any other Ready condition is not ours to +// remove. +func TestReleaseRestoreHold(t *testing.T) { + for _, tc := range []struct { + name string + reason string + wantKept bool + }{ + {"held by a restore", ConditionReasonRestoreInProgress, false}, + {"another reason", "CredentialsNotReady", true}, + } { + t.Run(tc.name, func(t *testing.T) { + j := lockBackupJob(false) + j.Status.Phase = backupsv1alpha1.BackupJobPhasePending + meta.SetStatusCondition(&j.Status.Conditions, metav1.Condition{Type: "Ready", Status: metav1.ConditionFalse, Reason: tc.reason, Message: "x"}) + c := lockTestClient(t, j) + r := &BackupJobReconciler{Client: c} + live := &backupsv1alpha1.BackupJob{} + key := types.NamespacedName{Namespace: lockNS, Name: j.Name} + if err := c.Get(context.Background(), key, live); err != nil { + t.Fatal(err) + } + if err := r.releaseRestoreHold(context.Background(), live); err != nil { + t.Fatalf("releaseRestoreHold: %v", err) + } + got := &backupsv1alpha1.BackupJob{} + if err := c.Get(context.Background(), key, got); err != nil { + t.Fatal(err) + } + if kept := meta.FindStatusCondition(got.Status.Conditions, "Ready") != nil; kept != tc.wantKept { + t.Errorf("Ready condition kept = %v, want %v", kept, tc.wantKept) + } + }) + } +} diff --git a/internal/backupcontroller/restorejob_controller.go b/internal/backupcontroller/restorejob_controller.go index 23b65279e..def91c382 100644 --- a/internal/backupcontroller/restorejob_controller.go +++ b/internal/backupcontroller/restorejob_controller.go @@ -37,6 +37,10 @@ type RestoreJobReconciler struct { Scheme *runtime.Scheme Recorder record.EventRecorder CredentialsConfig BackupCredentialsConfig + // APIReader is the manager's uncached reader. The keepOriginalPVC rename + // reads back objects it has just written, which the cache may not have + // seen yet. Wired in SetupWithManager. + APIReader client.Reader } func (r *RestoreJobReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { @@ -160,6 +164,7 @@ func (r *RestoreJobReconciler) Reconcile(ctx context.Context, req ctrl.Request) // SetupWithManager registers our controller with the Manager and sets up watches. func (r *RestoreJobReconciler) SetupWithManager(mgr ctrl.Manager) error { + r.APIReader = mgr.GetAPIReader() cfg := mgr.GetConfig() var err error if r.Interface, err = dynamic.NewForConfig(cfg); err != nil { @@ -177,6 +182,16 @@ func (r *RestoreJobReconciler) SetupWithManager(mgr ctrl.Manager) error { Complete(r) } +// apiReader returns the uncached reader. Reconcilers built by hand in unit +// tests have none and fall back to their fake Client, which has no cache to +// bypass. +func (r *RestoreJobReconciler) apiReader() client.Reader { + if r.APIReader != nil { + return r.APIReader + } + return r.Client +} + // handleProjectionError classifies a credentials-projection error as // transient (requeue with Ready=False/CredentialsProjectionPending) or // terminal (markRestoreJobFailed). Mirrors the BackupJob variant — both diff --git a/internal/backupcontroller/velerostrategy_controller.go b/internal/backupcontroller/velerostrategy_controller.go index 1c6a06226..819caa60a 100644 --- a/internal/backupcontroller/velerostrategy_controller.go +++ b/internal/backupcontroller/velerostrategy_controller.go @@ -18,6 +18,7 @@ import ( "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" + "k8s.io/client-go/util/retry" ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/log" @@ -58,6 +59,17 @@ const ( // Annotation key for persisting underlying resources on the Velero Backup object underlyingResourcesAnnotation = "backups.cozystack.io/underlying-resources" + // keepOriginalPVC moves a disk's PV to Retain so it survives the deletion + // of its PVC. The policy it had is kept here, on the PV and on the + // -orig- PVC, because nothing in the controller restores it: + // whoever deletes the -orig PVC must set it back first, or a PV that was + // Delete stays Retain and its volume is never reclaimed. + originalReclaimPolicyAnnotation = "backups.cozystack.io/original-reclaim-policy" + // The -orig suffix hashes the RestoreJob name, and a name can be reused + // once the previous RestoreJob is deleted, leaving its -orig PVC behind. + // The UID tells a rename this RestoreJob started apart from that one. + origPVCRestoreJobUIDAnnotation = "backups.cozystack.io/restore-job-uid" + // VM-specific constants vmInstanceKind = "VMInstance" vmDiskAppKind = "VMDisk" @@ -106,7 +118,8 @@ type CommonRestoreOptions struct { // KeepOriginalIpAndMac) are only effective when the application kind is VMInstance. type RestoreOptions struct { CommonRestoreOptions `json:",inline"` - // KeepOriginalPVC renames the original PVC to -orig- before restore. + // KeepOriginalPVC renames the original PVC to -orig- before restore; + // when false, the original PVC is deleted so that Velero recreates it. // Only effective for in-place VMInstance restore (no targetNamespace). Defaults to true when omitted. KeepOriginalPVC *bool `json:"keepOriginalPVC,omitempty"` // KeepOriginalIpAndMac preserves the original IP and MAC address via OVN @@ -606,6 +619,27 @@ func (r *RestoreJobReconciler) reconcileVeleroRestore(ctx context.Context, resto "Use options.targetNamespace to restore into a different namespace") } + // Validate: rename is only implemented for VMInstance. Failing here beats a + // Succeeded RestoreJob whose application silently keeps the source name. + if target.IsRenamed && !veleroRenameSupported(backup.Spec.ApplicationRef.Kind) { + msg := fmt.Sprintf( + "restoring %s %q under a different name (%q) is not supported by the Velero strategy: "+ + "Velero DataUpload always restores volumes under their original names and only a VMInstance "+ + "can adopt them. Omit targetApplicationRef.name to keep the source name", + backup.Spec.ApplicationRef.Kind, backup.Spec.ApplicationRef.Name, target.AppName) + if backup.Spec.ApplicationRef.Kind != vmDiskAppKind { + msg += ", or use the application's engine-native strategy to restore into a new application" + } + if restoreJob.Status.StartedAt != nil { + // The job predates this check: its Velero Restore may already have + // restored the application under the source name. + r.cleanupResourceModifierConfigMaps(ctx, restoreJob) + msg += fmt.Sprintf(". This RestoreJob was already running, so %q may have been restored into namespace %q under its source name", + backup.Spec.ApplicationRef.Name, target.Namespace) + } + return r.markRestoreJobFailed(ctx, restoreJob, msg) + } + // Step 1: On first reconcile, set startedAt and phase = Running if restoreJob.Status.StartedAt == nil { logger.Debug("setting RestoreJob StartedAt and phase to Running") @@ -673,8 +707,26 @@ func (r *RestoreJobReconciler) reconcileVeleroRestore(ctx context.Context, resto } } + // The Backup artifact outlives the Velero Backup it points to, which + // Velero garbage-collects once its TTL expires. Checked before + // prepareForRestore halts the application and deletes its disks, so a + // restore that cannot run leaves them in place. + veleroBackup := &velerov1.Backup{} + if err := r.Get(ctx, client.ObjectKey{Namespace: veleroNamespace, Name: veleroBackupName}, veleroBackup); err != nil { + if errors.IsNotFound(err) { + return r.markRestoreJobFailed(ctx, restoreJob, fmt.Sprintf( + "Velero Backup %s/%s not found; it may have expired", veleroNamespace, veleroBackupName)) + } + return ctrl.Result{}, fmt.Errorf("failed to get Velero Backup %s: %w", veleroBackupName, err) + } + if veleroBackup.Status.Phase != velerov1.BackupPhaseCompleted { + return r.markRestoreJobFailed(ctx, restoreJob, fmt.Sprintf( + "Velero Backup %s/%s is %q, not %q", veleroNamespace, veleroBackupName, + veleroBackup.Status.Phase, velerov1.BackupPhaseCompleted)) + } + // Resolve underlying resources once; prefer Backup status, fall back to Velero annotation. - ur := r.resolveUnderlyingResourcesForRestore(ctx, backup, veleroBackupName) + ur := resolveUnderlyingResourcesForRestore(backup, veleroBackup) // Pre-restore: graceful shutdown, suspend HRs, rename PVCs (skipped for copy) ready, result, err := r.prepareForRestore(ctx, restoreJob, backup, ur, target, restoreOpts) @@ -936,14 +988,10 @@ func (r *RestoreJobReconciler) createResourceModifiersConfigMap(ctx context.Cont // resolveUnderlyingResourcesForRestore returns underlying resources for symmetric // restore label selectors. Velero Backup annotation is used when Backup.status was empty // (e.g. CRD without underlyingResources in schema). -func (r *RestoreJobReconciler) resolveUnderlyingResourcesForRestore(ctx context.Context, backup *backupsv1alpha1.Backup, veleroBackupName string) *runtime.RawExtension { +func resolveUnderlyingResourcesForRestore(backup *backupsv1alpha1.Backup, vb *velerov1.Backup) *runtime.RawExtension { if backup.Status.UnderlyingResources != nil && len(backup.Status.UnderlyingResources.Raw) > 0 { return backup.Status.UnderlyingResources } - vb := &velerov1.Backup{} - if err := r.Get(ctx, client.ObjectKey{Namespace: veleroNamespace, Name: veleroBackupName}, vb); err != nil { - return backup.Status.UnderlyingResources - } if urJSON, ok := vb.Annotations[underlyingResourcesAnnotation]; ok && urJSON != "" { return &runtime.RawExtension{Raw: []byte(urJSON)} } @@ -958,6 +1006,16 @@ var ( dataVolumeGVR = schema.GroupVersionResource{Group: "cdi.kubevirt.io", Version: "v1beta1", Resource: "datavolumes"} ) +// veleroRenameSupported reports whether postRestoreRename can restore the +// given application kind under a new name. Velero DataUpload writes volumes +// under their original names, and only a VMInstance re-attaches them after its +// HelmRelease is renamed: its disks keep their names and CDI adopts the restored +// PVCs. Every other kind (a standalone VMDisk, a database operator's Cluster) +// renders fresh volumes for the new name and comes up empty. +func veleroRenameSupported(appKind string) bool { + return appKind == vmInstanceKind +} + // helmReleaseNameForApp returns the HelmRelease name for the given application // kind and name. Returns empty string for unsupported kinds. func helmReleaseNameForApp(appKind, appName string) string { @@ -1002,8 +1060,13 @@ func shortHash(input string) string { // 5. Renames existing PVCs to -orig- so Velero can create fresh // ones via Data Movement. // -// Failures in individual steps are non-fatal: missing resources are expected -// (e.g. restore requested when app was already deleted). Each action emits +// Missing resources are expected (e.g. restore requested when app was already +// deleted), and a failure to suspend or halt is non-fatal. A failed rename +// holds the restore back and is retried, since the DataVolume deletion after +// it would hand a disk that was not kept to the restore, as +// keepOriginalPVC=false does, and an -orig name another PVC holds fails the +// restore. A DataVolume or a replaced PVC that cannot be deleted fails the +// restore, since Velero would skip the claim left in place. Each action emits // a Kubernetes Event on the RestoreJob for observability. // // postRestoreRename renames VMInstance HelmRelease after Velero Restore completes. @@ -1095,8 +1158,25 @@ func (r *RestoreJobReconciler) prepareForRestore(ctx context.Context, restoreJob appKind := backup.Spec.ApplicationRef.Kind origSuffix := "-orig-" + shortHash(restoreJob.Name) - // --- Step 1: Suspend HelmReleases --- vmRes := getVMInstanceResources(ur) + + // Refuse a taken -orig name before anything is halted or deleted, rather + // than fail halfway through a multi-disk rename. + if opts.GetKeepOriginalPVC() && vmRes != nil { + for _, dv := range vmRes.DataVolumes { + origPVC, err := r.getOrigPVC(ctx, ns, dv.DataVolumeName+origSuffix) + if err != nil { + r.Recorder.Event(restoreJob, corev1.EventTypeWarning, "PrepareForRestore", + fmt.Sprintf("Failed to check PVC %s: %v", dv.DataVolumeName+origSuffix, err)) + return false, ctrl.Result{RequeueAfter: defaultRestoreRequeueAfter}, nil + } + if err := foreignOrigPVC(origPVC, restoreJob); err != nil { + return false, ctrl.Result{}, err + } + } + } + + // --- Step 1: Suspend HelmReleases --- hrNames := []string{} if appKind == vmInstanceKind { hrNames = append(hrNames, vmNamePrefix+appName) @@ -1143,20 +1223,59 @@ func (r *RestoreJobReconciler) prepareForRestore(ctx context.Context, restoreJob if err := r.renamePVC(ctx, restoreJob, ns, dv.DataVolumeName, dv.DataVolumeName+origSuffix); err != nil { r.Recorder.Event(restoreJob, corev1.EventTypeWarning, "PrepareForRestore", fmt.Sprintf("Failed to keep old PVC %s: %v", dv.DataVolumeName, err)) + return false, ctrl.Result{RequeueAfter: defaultRestoreRequeueAfter}, nil } } } // --- Step 4: Delete DataVolumes so CDI doesn't recreate PVCs --- + // A DataVolume still present makes CDI recreate its claim under the original + // name, which Velero then skips as an existing PVC: the restore would end + // Succeeded on a freshly imported disk, so nothing goes further until every + // DataVolume is gone. if vmRes != nil { + var terminating []string for _, dv := range vmRes.DataVolumes { - if err := r.deleteDataVolume(ctx, ns, dv.DataVolumeName); err != nil { - r.Recorder.Event(restoreJob, corev1.EventTypeWarning, "PrepareForRestore", - fmt.Sprintf("Failed to delete DataVolume %s: %v", dv.DataVolumeName, err)) - } else { - r.Recorder.Event(restoreJob, corev1.EventTypeNormal, "PrepareForRestore", - fmt.Sprintf("Deleted DataVolume %s", dv.DataVolumeName)) + gone, err := r.deleteDataVolume(ctx, ns, dv.DataVolumeName) + if err != nil { + return false, ctrl.Result{}, fmt.Errorf("failed to delete DataVolume %s: %w", dv.DataVolumeName, err) } + if !gone { + terminating = append(terminating, dv.DataVolumeName) + continue + } + r.Recorder.Event(restoreJob, corev1.EventTypeNormal, "PrepareForRestore", + fmt.Sprintf("Deleted DataVolume %s", dv.DataVolumeName)) + } + if len(terminating) > 0 { + r.Recorder.Event(restoreJob, corev1.EventTypeNormal, "PrepareForRestore", + fmt.Sprintf("Waiting for DataVolumes %s to be deleted", strings.Join(terminating, ", "))) + return false, ctrl.Result{RequeueAfter: defaultRestoreRequeueAfter}, nil + } + } + + // --- Step 5: Delete the PVCs a restore without keepOriginalPVC replaces --- + // Velero restores a PVC only by creating it: its CSI restore action skips the + // data mover for a PVC that already exists, and existingResourcePolicy=update + // cannot patch the immutable spec of a bound claim. A PVC left in place keeps + // its old data, and, orphaned from its DataVolume in step 4 and without the + // cdi.kubevirt.io/storage.populatedFor the backed-up copy carries, it makes + // CDI refuse the DataVolume the resumed HelmRelease creates. + if !opts.GetKeepOriginalPVC() && vmRes != nil { + var terminating []string + for _, dv := range vmRes.DataVolumes { + gone, err := r.deletePVC(ctx, ns, dv.DataVolumeName) + if err != nil { + return false, ctrl.Result{}, fmt.Errorf("failed to delete PVC %s: %w", dv.DataVolumeName, err) + } + if !gone { + terminating = append(terminating, dv.DataVolumeName) + } + } + if len(terminating) > 0 { + r.Recorder.Event(restoreJob, corev1.EventTypeNormal, "PrepareForRestore", + fmt.Sprintf("Waiting for PVCs %s to be deleted", strings.Join(terminating, ", "))) + return false, ctrl.Result{RequeueAfter: defaultRestoreRequeueAfter}, nil } } @@ -1217,102 +1336,202 @@ func (r *RestoreJobReconciler) haltVirtualMachine(ctx context.Context, ns, vmNam return false, nil } -// deleteDataVolume deletes a DataVolume so CDI doesn't recreate the PVC after rename. -// Uses Orphan propagation to avoid cascade-deleting the PVC that the DV owns via -// ownerReference. Without this, keepOriginalPVC=false would silently destroy the -// original PVC through garbage collection instead of leaving it for Velero to overwrite. -func (r *RestoreJobReconciler) deleteDataVolume(ctx context.Context, ns, name string) error { - orphan := metav1.DeletePropagationOrphan - err := r.Resource(dataVolumeGVR).Namespace(ns).Delete(ctx, name, metav1.DeleteOptions{ - PropagationPolicy: &orphan, - }) - if err != nil && !errors.IsNotFound(err) { - return err +// deleteDataVolume deletes a DataVolume so CDI doesn't recreate the PVC after +// rename, and reports whether it is gone. Orphan propagation holds the DV behind +// the orphan finalizer until garbage collection has released its PVC, and leaves +// that PVC to prepareForRestore, which waits for its deletion, rather than to +// background garbage collection, which nothing waits for before the Velero +// Restore starts. +func (r *RestoreJobReconciler) deleteDataVolume(ctx context.Context, ns, name string) (bool, error) { + dvClient := r.Resource(dataVolumeGVR).Namespace(ns) + dv, err := dvClient.Get(ctx, name, metav1.GetOptions{}) + if err != nil { + if errors.IsNotFound(err) { + return true, nil + } + return false, err } - return nil + if dv.GetDeletionTimestamp() == nil { + orphan := metav1.DeletePropagationOrphan + err := dvClient.Delete(ctx, name, metav1.DeleteOptions{PropagationPolicy: &orphan}) + if err != nil && !errors.IsNotFound(err) { + return false, err + } + } + if _, err := dvClient.Get(ctx, name, metav1.GetOptions{}); err != nil { + if errors.IsNotFound(err) { + return true, nil + } + return false, err + } + return false, nil +} + +// getOrigPVC returns the PVC named name, or nil when there is none. It reads +// past the cache: a retried rename must see the -orig PVC it created, not +// take the name for free and fail to create it again. +func (r *RestoreJobReconciler) getOrigPVC(ctx context.Context, ns, name string) (*corev1.PersistentVolumeClaim, error) { + pvc := &corev1.PersistentVolumeClaim{} + if err := r.apiReader().Get(ctx, client.ObjectKey{Namespace: ns, Name: name}, pvc); err != nil { + return nil, client.IgnoreNotFound(err) + } + return pvc, nil +} + +// foreignOrigPVC fails when pvc exists and restoreJob did not create it. +// Proceeding would hand the live disk to the restore under its own name, as +// keepOriginalPVC=false does, while the -orig name holds some other disk. +func foreignOrigPVC(pvc *corev1.PersistentVolumeClaim, restoreJob *backupsv1alpha1.RestoreJob) error { + if pvc == nil || pvc.Annotations[origPVCRestoreJobUIDAnnotation] == string(restoreJob.UID) { + return nil + } + return fmt.Errorf("PVC %s/%s already exists and was not created by this RestoreJob, so the current disk cannot be kept under that name: "+ + "remove that PVC or create the RestoreJob under another name", pvc.Namespace, pvc.Name) +} + +// deletePVC deletes a PVC and reports whether it is gone. A claim still mounted +// stays Terminating behind kubernetes.io/pvc-protection, and Velero would find +// it still there. +func (r *RestoreJobReconciler) deletePVC(ctx context.Context, ns, name string) (bool, error) { + key := client.ObjectKey{Namespace: ns, Name: name} + pvc := &corev1.PersistentVolumeClaim{} + if err := r.Get(ctx, key, pvc); err != nil { + if errors.IsNotFound(err) { + return true, nil + } + return false, err + } + if pvc.DeletionTimestamp == nil { + if err := r.Delete(ctx, pvc); err != nil && !errors.IsNotFound(err) { + return false, err + } + } + if err := r.Get(ctx, key, pvc); err != nil { + if errors.IsNotFound(err) { + return true, nil + } + return false, err + } + return false, nil } // renamePVC preserves an existing PVC by rebinding it under a new name. // The original PVC is deleted and a new one pointing to the same PV is created. -// Missing resources are silently skipped (non-fatal). +// Missing resources are silently skipped (non-fatal). Each step can be +// resumed, so a rename interrupted by a controller restart completes on the +// next reconcile. func (r *RestoreJobReconciler) renamePVC(ctx context.Context, restoreJob *backupsv1alpha1.RestoreJob, ns, oldName, newName string) error { logger := getLogger(ctx) - // Check if already renamed - existingNew := &corev1.PersistentVolumeClaim{} - if err := r.Get(ctx, client.ObjectKey{Namespace: ns, Name: newName}, existingNew); err == nil { - return nil - } - - // Get the original PVC - oldPVC := &corev1.PersistentVolumeClaim{} - if err := r.Get(ctx, client.ObjectKey{Namespace: ns, Name: oldName}, oldPVC); err != nil { - if errors.IsNotFound(err) { - return nil // nothing to rename - } + newPVC, err := r.getOrigPVC(ctx, ns, newName) + if err != nil { return err } + if err := foreignOrigPVC(newPVC, restoreJob); err != nil { + return err + } + resuming := newPVC != nil - pvName := oldPVC.Spec.VolumeName - if pvName == "" { + oldPVC := &corev1.PersistentVolumeClaim{} + if err := r.apiReader().Get(ctx, client.ObjectKey{Namespace: ns, Name: oldName}, oldPVC); err != nil { + if !errors.IsNotFound(err) { + return err + } + oldPVC = nil + } + + pv := &corev1.PersistentVolume{} + var pvName string + switch { + case resuming: + pvName = newPVC.Spec.VolumeName + case oldPVC == nil: + return nil // nothing to rename + case oldPVC.Spec.VolumeName == "": logger.Debug("PVC not bound, deleting", "name", oldName) return r.Delete(ctx, oldPVC) - } + default: + pvName = oldPVC.Spec.VolumeName - // Patch PV reclaim policy to Retain so it survives PVC deletion - pv := &corev1.PersistentVolume{} - if err := r.Get(ctx, client.ObjectKey{Name: pvName}, pv); err != nil { - return fmt.Errorf("failed to get PV %s: %w", pvName, err) - } - if pv.Spec.PersistentVolumeReclaimPolicy != corev1.PersistentVolumeReclaimRetain { - pv.Spec.PersistentVolumeReclaimPolicy = corev1.PersistentVolumeReclaimRetain - if err := r.Update(ctx, pv); err != nil { - return fmt.Errorf("failed to set Retain policy on PV %s: %w", pvName, err) + // Patch PV reclaim policy to Retain so it survives PVC deletion. + // A policy already recorded is the one from before any rename. + if err := r.apiReader().Get(ctx, client.ObjectKey{Name: pvName}, pv); err != nil { + return fmt.Errorf("failed to get PV %s: %w", pvName, err) + } + originalPolicy, recorded := pv.Annotations[originalReclaimPolicyAnnotation] + if !recorded { + originalPolicy = string(pv.Spec.PersistentVolumeReclaimPolicy) + metav1.SetMetaDataAnnotation(&pv.ObjectMeta, originalReclaimPolicyAnnotation, originalPolicy) + } + if !recorded || pv.Spec.PersistentVolumeReclaimPolicy != corev1.PersistentVolumeReclaimRetain { + pv.Spec.PersistentVolumeReclaimPolicy = corev1.PersistentVolumeReclaimRetain + if err := r.Update(ctx, pv); err != nil { + return fmt.Errorf("failed to set Retain policy on PV %s: %w", pvName, err) + } + } + + // Create the new -orig PVC first (unbound, just the object) + newPVC = &corev1.PersistentVolumeClaim{ + ObjectMeta: metav1.ObjectMeta{ + Name: newName, + Namespace: ns, + Annotations: map[string]string{ + originalReclaimPolicyAnnotation: originalPolicy, + origPVCRestoreJobUIDAnnotation: string(restoreJob.UID), + }, + }, + Spec: corev1.PersistentVolumeClaimSpec{ + AccessModes: oldPVC.Spec.AccessModes, + Resources: oldPVC.Spec.Resources, + StorageClassName: oldPVC.Spec.StorageClassName, + VolumeMode: oldPVC.Spec.VolumeMode, + VolumeName: pvName, + }, + } + // Create fills in the UID the claimRef needs. Reading the PVC back + // through the cache can miss it, as it is this reconcile's own write. + if err := r.Create(ctx, newPVC); err != nil { + return fmt.Errorf("failed to create -orig PVC %s: %w", newName, err) } } - // Create the new -orig PVC first (unbound, just the object) - newPVC := &corev1.PersistentVolumeClaim{ - ObjectMeta: metav1.ObjectMeta{ - Name: newName, - Namespace: ns, - }, - Spec: corev1.PersistentVolumeClaimSpec{ - AccessModes: oldPVC.Spec.AccessModes, - Resources: oldPVC.Spec.Resources, - StorageClassName: oldPVC.Spec.StorageClassName, - VolumeMode: oldPVC.Spec.VolumeMode, - VolumeName: pvName, - }, - } - if err := r.Create(ctx, newPVC); err != nil && !errors.IsAlreadyExists(err) { - return fmt.Errorf("failed to create -orig PVC %s: %w", newName, err) - } - // Re-read to get UID for the claimRef - if err := r.Get(ctx, client.ObjectKey{Namespace: ns, Name: newName}, newPVC); err != nil { - return fmt.Errorf("failed to get -orig PVC %s: %w", newName, err) - } - - // Delete the original PVC - if err := r.Delete(ctx, oldPVC); err != nil && !errors.IsNotFound(err) { - return fmt.Errorf("failed to delete PVC %s: %w", oldName, err) + // Delete the original PVC. Only while it still claims the kept PV: after + // an interrupted rename, CDI may have recreated an empty one under the old + // name, and that one is left to the restore. + if oldPVC != nil && oldPVC.Spec.VolumeName == pvName { + if err := r.Delete(ctx, oldPVC); err != nil && !errors.IsNotFound(err) { + return fmt.Errorf("failed to delete PVC %s: %w", oldName, err) + } } // Point the PV's claimRef directly to the new -orig PVC. // This is atomic — no window where the PV is Available for other PVCs to grab. - if err := r.Get(ctx, client.ObjectKey{Name: pvName}, pv); err != nil { - return fmt.Errorf("failed to re-fetch PV %s: %w", pvName, err) - } - pv.Spec.ClaimRef = &corev1.ObjectReference{ - APIVersion: "v1", - Kind: "PersistentVolumeClaim", - Namespace: ns, - Name: newName, - UID: newPVC.UID, - } - if err := r.Update(ctx, pv); err != nil { + // The PV controller writes the PV too once the original PVC is gone, so + // the read is uncached and a conflict is retried. + rebound := false + err = retry.RetryOnConflict(retry.DefaultRetry, func() error { + if err := r.apiReader().Get(ctx, client.ObjectKey{Name: pvName}, pv); err != nil { + return err + } + if ref := pv.Spec.ClaimRef; ref != nil && ref.Namespace == ns && ref.Name == newName && ref.UID == newPVC.UID { + return nil + } + pv.Spec.ClaimRef = &corev1.ObjectReference{ + APIVersion: "v1", + Kind: "PersistentVolumeClaim", + Namespace: ns, + Name: newName, + UID: newPVC.UID, + } + rebound = true + return r.Update(ctx, pv) + }) + if err != nil { return fmt.Errorf("failed to rebind PV %s to %s: %w", pvName, newName, err) } + if !rebound { + return nil + } r.Recorder.Event(restoreJob, corev1.EventTypeNormal, "PrepareForRestore", fmt.Sprintf("Keep old PVC %s as %s (PV: %s)", oldName, newName, pvName)) diff --git a/internal/backupcontroller/velerostrategy_controller_test.go b/internal/backupcontroller/velerostrategy_controller_test.go index 7b085dbfe..c21ddc0a0 100644 --- a/internal/backupcontroller/velerostrategy_controller_test.go +++ b/internal/backupcontroller/velerostrategy_controller_test.go @@ -3,9 +3,11 @@ package backupcontroller import ( "context" "encoding/json" + "strings" "testing" corev1 "k8s.io/api/core/v1" + "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/api/meta" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" @@ -13,9 +15,11 @@ import ( "k8s.io/apimachinery/pkg/runtime/schema" dynamicfake "k8s.io/client-go/dynamic/fake" "k8s.io/client-go/kubernetes/scheme" + k8stesting "k8s.io/client-go/testing" "k8s.io/client-go/tools/record" "sigs.k8s.io/controller-runtime/pkg/client" clientfake "sigs.k8s.io/controller-runtime/pkg/client/fake" + "sigs.k8s.io/controller-runtime/pkg/client/interceptor" strategyv1alpha1 "github.com/cozystack/cozystack/api/backups/strategy/v1alpha1" backupsv1alpha1 "github.com/cozystack/cozystack/api/backups/v1alpha1" @@ -400,18 +404,9 @@ func newTestRestoreJobReconciler(t *testing.T, objects ...client.Object) *Restor } } -func TestPrepareForRestore_KeepOriginalPVCFalse_SkipsRename(t *testing.T) { - ns := "tenant-root" - - // Create a PVC that would be renamed if keepOriginalPVC were true - pvc := &corev1.PersistentVolumeClaim{ - ObjectMeta: metav1.ObjectMeta{ - Name: "vm-disk-ubuntu-source", - Namespace: ns, - }, - Spec: corev1.PersistentVolumeClaimSpec{}, - } - +// inPlaceVMRestoreWithoutKeep is an in-place VMInstance restore of one disk, +// vm-disk-ubuntu-source, with keepOriginalPVC=false. +func inPlaceVMRestoreWithoutKeep(ns string) (*backupsv1alpha1.RestoreJob, *backupsv1alpha1.Backup, *runtime.RawExtension, restoreTarget, RestoreOptions) { restoreJob := &backupsv1alpha1.RestoreJob{ ObjectMeta: metav1.ObjectMeta{ Name: "restore-test", @@ -436,14 +431,12 @@ func TestPrepareForRestore_KeepOriginalPVCFalse_SkipsRename(t *testing.T) { }, } - // underlyingResources with a DataVolume referencing the PVC urData := vmInstanceResources{ DataVolumes: []backupsv1alpha1.DataVolumeResource{ {DataVolumeName: "vm-disk-ubuntu-source", ApplicationName: "ubuntu-source"}, }, } urRaw, _ := json.Marshal(urData) - ur := &runtime.RawExtension{Raw: urRaw} target := restoreTarget{ Namespace: ns, @@ -452,9 +445,21 @@ func TestPrepareForRestore_KeepOriginalPVCFalse_SkipsRename(t *testing.T) { IsCopy: false, } - // keepOriginalPVC = false → PVCs should NOT be renamed - opts := RestoreOptions{ - KeepOriginalPVC: boolPtr(false), + return restoreJob, backup, &runtime.RawExtension{Raw: urRaw}, target, RestoreOptions{KeepOriginalPVC: new(false)} +} + +// Velero only restores a PVC it creates: one still in place keeps its old data +// and blocks the DataVolume the HelmRelease recreates. +func TestPrepareForRestore_KeepOriginalPVCFalse_DeletesPVC(t *testing.T) { + ns := "tenant-root" + restoreJob, backup, ur, target, opts := inPlaceVMRestoreWithoutKeep(ns) + + pvc := &corev1.PersistentVolumeClaim{ + ObjectMeta: metav1.ObjectMeta{ + Name: "vm-disk-ubuntu-source", + Namespace: ns, + }, + Spec: corev1.PersistentVolumeClaimSpec{}, } reconciler := newTestRestoreJobReconciler(t, pvc, restoreJob, backup) @@ -468,22 +473,263 @@ func TestPrepareForRestore_KeepOriginalPVCFalse_SkipsRename(t *testing.T) { t.Fatal("expected ready=true, got false") } - // Verify the original PVC still exists with its original name (not renamed) - origPVC := &corev1.PersistentVolumeClaim{} - err = reconciler.Get(ctx, client.ObjectKey{Namespace: ns, Name: "vm-disk-ubuntu-source"}, origPVC) - if err != nil { - t.Errorf("original PVC should still exist with original name when keepOriginalPVC=false, got error: %v", err) + err = reconciler.Get(ctx, client.ObjectKey{Namespace: ns, Name: "vm-disk-ubuntu-source"}, &corev1.PersistentVolumeClaim{}) + if !errors.IsNotFound(err) { + t.Errorf("original PVC should be gone before Velero restores it when keepOriginalPVC=false, got error: %v", err) } - // Verify no -orig PVC was created origSuffix := "-orig-" + shortHash(restoreJob.Name) - renamedPVC := &corev1.PersistentVolumeClaim{} - err = reconciler.Get(ctx, client.ObjectKey{Namespace: ns, Name: "vm-disk-ubuntu-source" + origSuffix}, renamedPVC) + err = reconciler.Get(ctx, client.ObjectKey{Namespace: ns, Name: "vm-disk-ubuntu-source" + origSuffix}, &corev1.PersistentVolumeClaim{}) if err == nil { t.Error("PVC should NOT have been renamed when keepOriginalPVC=false, but found renamed PVC") } } +func TestPrepareForRestore_KeepOriginalPVCFalse_WaitsForTerminatingPVC(t *testing.T) { + ns := "tenant-root" + restoreJob, backup, ur, target, opts := inPlaceVMRestoreWithoutKeep(ns) + + pvc := &corev1.PersistentVolumeClaim{ + ObjectMeta: metav1.ObjectMeta{ + Name: "vm-disk-ubuntu-source", + Namespace: ns, + Finalizers: []string{"kubernetes.io/pvc-protection"}, + }, + Spec: corev1.PersistentVolumeClaimSpec{}, + } + + reconciler := newTestRestoreJobReconciler(t, pvc, restoreJob, backup) + + ctx := context.Background() + ready, result, err := reconciler.prepareForRestore(ctx, restoreJob, backup, ur, target, opts) + if err != nil { + t.Fatalf("prepareForRestore() error = %v", err) + } + if ready { + t.Fatal("expected ready=false while the PVC is still terminating, got true") + } + if result.RequeueAfter == 0 { + t.Error("expected a requeue while the PVC is still terminating") + } + + stuck := &corev1.PersistentVolumeClaim{} + if err := reconciler.Get(ctx, client.ObjectKey{Namespace: ns, Name: "vm-disk-ubuntu-source"}, stuck); err != nil { + t.Fatalf("terminating PVC should still be readable: %v", err) + } + if stuck.DeletionTimestamp == nil { + t.Fatal("PVC should have been marked for deletion") + } + stuck.Finalizers = nil + if err := reconciler.Update(ctx, stuck); err != nil { + t.Fatalf("failed to release the PVC finalizer: %v", err) + } + + ready, _, err = reconciler.prepareForRestore(ctx, restoreJob, backup, ur, target, opts) + if err != nil { + t.Fatalf("prepareForRestore() error = %v", err) + } + if !ready { + t.Fatal("expected ready=true once the PVC is gone, got false") + } +} + +func makeUnstructuredDataVolume(name, namespace string) *unstructured.Unstructured { + dv := &unstructured.Unstructured{} + dv.SetAPIVersion("cdi.kubevirt.io/v1beta1") + dv.SetKind("DataVolume") + dv.SetName(name) + dv.SetNamespace(namespace) + return dv +} + +// A DataVolume still in place makes CDI recreate the claim under its original +// name, so the PVC must survive until the DataVolume is confirmed gone. +func TestPrepareForRestore_KeepOriginalPVCFalse_KeepsPVCWhileDataVolumeRemains(t *testing.T) { + tests := []struct { + name string + deleteErr error + wantErr bool + }{ + { + name: "DataVolume deletion fails", + deleteErr: errors.NewForbidden(dataVolumeGVR.GroupResource(), "vm-disk-ubuntu-source", nil), + wantErr: true, + }, + { + name: "DataVolume deletion is still pending", + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + ns := "tenant-root" + restoreJob, backup, ur, target, opts := inPlaceVMRestoreWithoutKeep(ns) + pvc := &corev1.PersistentVolumeClaim{ + ObjectMeta: metav1.ObjectMeta{Name: "vm-disk-ubuntu-source", Namespace: ns}, + } + reconciler := newTestRestoreJobReconcilerWithDynamic(t, + []runtime.Object{makeUnstructuredDataVolume("vm-disk-ubuntu-source", ns)}, + pvc, restoreJob, backup) + reconciler.Interface.(*dynamicfake.FakeDynamicClient).PrependReactor("delete", "datavolumes", + func(k8stesting.Action) (bool, runtime.Object, error) { + return true, nil, tt.deleteErr + }) + + ctx := context.Background() + ready, result, err := reconciler.prepareForRestore(ctx, restoreJob, backup, ur, target, opts) + if tt.wantErr { + if err == nil { + t.Fatal("expected an error when the DataVolume cannot be deleted") + } + } else { + if err != nil { + t.Fatalf("prepareForRestore() error = %v", err) + } + if result.RequeueAfter == 0 { + t.Error("expected a requeue while the DataVolume is still present") + } + } + if ready { + t.Fatal("expected ready=false while the DataVolume is still present") + } + + got := &corev1.PersistentVolumeClaim{} + if err := reconciler.Get(ctx, client.ObjectKeyFromObject(pvc), got); err != nil { + t.Fatalf("original PVC should survive while its DataVolume remains: %v", err) + } + if got.DeletionTimestamp != nil { + t.Error("original PVC should not be marked for deletion while its DataVolume remains") + } + }) + } +} + +// keepOriginalPVC=true must never delete the original claim, even when the +// rename that preserves it fails and leaves it under its original name. +func TestPrepareForRestore_KeepOriginalPVCTrue_FailedRenameKeepsPVC(t *testing.T) { + ns := "tenant-root" + restoreJob, backup, ur, target, _ := inPlaceVMRestoreWithoutKeep(ns) + opts := RestoreOptions{KeepOriginalPVC: new(true)} + + pvc := &corev1.PersistentVolumeClaim{ + ObjectMeta: metav1.ObjectMeta{Name: "vm-disk-ubuntu-source", Namespace: ns}, + // The PV does not exist, so renamePVC fails before touching the claim. + Spec: corev1.PersistentVolumeClaimSpec{VolumeName: "pv-missing"}, + } + reconciler := newTestRestoreJobReconciler(t, pvc, restoreJob, backup) + + ctx := context.Background() + if _, _, err := reconciler.prepareForRestore(ctx, restoreJob, backup, ur, target, opts); err != nil { + t.Fatalf("prepareForRestore() error = %v", err) + } + + if err := reconciler.Get(ctx, client.ObjectKeyFromObject(pvc), &corev1.PersistentVolumeClaim{}); err != nil { + t.Errorf("original PVC should survive a failed rename when keepOriginalPVC=true, got error: %v", err) + } +} + +// A Backup artifact can outlive its Velero Backup, which Velero garbage-collects +// at TTL. The restore must fail before it halts the VM or deletes its disks. +func TestReconcileVeleroRestore_UnusableVeleroBackupTouchesNothing(t *testing.T) { + tests := []struct { + name string + veleroBackup *velerov1.Backup + wantMessage string + }{ + { + name: "Velero Backup expired", + wantMessage: "Velero Backup cozy-velero/vb not found", + }, + { + name: "Velero Backup being deleted", + veleroBackup: &velerov1.Backup{ + ObjectMeta: metav1.ObjectMeta{Name: "vb", Namespace: veleroNamespace}, + Status: velerov1.BackupStatus{Phase: velerov1.BackupPhaseDeleting}, + }, + wantMessage: `Velero Backup cozy-velero/vb is "Deleting"`, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + ns := "tenant-root" + restoreJob, backup, ur, _, opts := inPlaceVMRestoreWithoutKeep(ns) + rawOpts, err := json.Marshal(opts) + if err != nil { + t.Fatalf("marshal options: %v", err) + } + started := metav1.Now() + restoreJob.Spec.Options = &runtime.RawExtension{Raw: rawOpts} + restoreJob.Status = backupsv1alpha1.RestoreJobStatus{ + Phase: backupsv1alpha1.RestoreJobPhaseRunning, + StartedAt: &started, + } + backup.Spec.StrategyRef = corev1.TypedLocalObjectReference{Kind: "Velero", Name: "cozy-default-velero"} + backup.Spec.DriverMetadata = map[string]string{veleroBackupNameMetadataKey: "vb"} + backup.Status.UnderlyingResources = ur + + pvc := &corev1.PersistentVolumeClaim{ + ObjectMeta: metav1.ObjectMeta{Name: "vm-disk-ubuntu-source", Namespace: ns}, + } + strategy := &strategyv1alpha1.Velero{ObjectMeta: metav1.ObjectMeta{Name: "cozy-default-velero"}} + objs := []client.Object{restoreJob, backup, pvc, strategy} + if tt.veleroBackup != nil { + objs = append(objs, tt.veleroBackup) + } + + vm := &unstructured.Unstructured{} + vm.SetAPIVersion("kubevirt.io/v1") + vm.SetKind("VirtualMachine") + vm.SetName(vmNamePrefix + "test-vm") + vm.SetNamespace(ns) + if err := unstructured.SetNestedField(vm.Object, "Always", "spec", "runStrategy"); err != nil { + t.Fatalf("set runStrategy: %v", err) + } + reconciler := newTestRestoreJobReconcilerWithDynamic(t, + []runtime.Object{vm, makeUnstructuredDataVolume("vm-disk-ubuntu-source", ns)}) + testScheme := runtime.NewScheme() + _ = scheme.AddToScheme(testScheme) + _ = backupsv1alpha1.AddToScheme(testScheme) + _ = velerov1.AddToScheme(testScheme) + _ = strategyv1alpha1.AddToScheme(testScheme) + reconciler.Client = clientfake.NewClientBuilder(). + WithScheme(testScheme). + WithObjects(objs...). + WithStatusSubresource(&backupsv1alpha1.RestoreJob{}). + Build() + ctx := context.Background() + + if _, err := reconciler.reconcileVeleroRestore(ctx, restoreJob, backup); err != nil { + t.Fatalf("reconcileVeleroRestore() error = %v", err) + } + + got := &backupsv1alpha1.RestoreJob{} + if err := reconciler.Get(ctx, client.ObjectKeyFromObject(restoreJob), got); err != nil { + t.Fatalf("get RestoreJob: %v", err) + } + if got.Status.Phase != backupsv1alpha1.RestoreJobPhaseFailed { + t.Fatalf("phase = %q, want %q", got.Status.Phase, backupsv1alpha1.RestoreJobPhaseFailed) + } + ready := meta.FindStatusCondition(got.Status.Conditions, "Ready") + if ready == nil || !strings.Contains(ready.Message, tt.wantMessage) { + t.Errorf("Ready condition = %+v, want a message containing %q", ready, tt.wantMessage) + } + + if err := reconciler.Get(ctx, client.ObjectKeyFromObject(pvc), &corev1.PersistentVolumeClaim{}); err != nil { + t.Errorf("original PVC should survive a restore that cannot run: %v", err) + } + if _, err := reconciler.Resource(dataVolumeGVR).Namespace(ns).Get(ctx, "vm-disk-ubuntu-source", metav1.GetOptions{}); err != nil { + t.Errorf("DataVolume should survive a restore that cannot run: %v", err) + } + gotVM, err := reconciler.Resource(virtualMachineGVR).Namespace(ns).Get(ctx, vm.GetName(), metav1.GetOptions{}) + if err != nil { + t.Fatalf("get VirtualMachine: %v", err) + } + if rs, _, _ := unstructured.NestedString(gotVM.Object, "spec", "runStrategy"); rs != "Always" { + t.Errorf("VirtualMachine runStrategy = %q, want it left at %q", rs, "Always") + } + }) + } +} + func TestResolveRestoreTarget_VMDisk_CommonRestoreOptions(t *testing.T) { tests := []struct { name string @@ -1122,6 +1368,300 @@ func TestHelmReleaseNameForApp(t *testing.T) { } } +func TestVeleroRenameSupported(t *testing.T) { + tests := []struct { + kind string + want bool + }{ + {vmInstanceKind, true}, + {vmDiskAppKind, false}, + {"Postgres", false}, + {"MariaDB", false}, + {"ClickHouse", false}, + {"MongoDB", false}, + {"", false}, + } + for _, tt := range tests { + t.Run(tt.kind, func(t *testing.T) { + if got := veleroRenameSupported(tt.kind); got != tt.want { + t.Errorf("veleroRenameSupported(%q) = %v, want %v", tt.kind, got, tt.want) + } + }) + } +} + +// TestReconcileVeleroRestore_RenameGuard covers the fix for a RestoreJob that +// asked for a new application name via targetApplicationRef.name but whose +// kind cannot be renamed by postRestoreRename: it used to report Succeeded +// with the application restored under the source name. +func TestReconcileVeleroRestore_RenameGuard(t *testing.T) { + const ( + sourceNS = "tenant-src" + targetNS = "tenant-dst" + ) + + tests := []struct { + name string + appKind string + targetKind string // targetApplicationRef.kind; defaults to appKind + targetName string // targetApplicationRef.name; "" omits targetApplicationRef + targetNS string + wantPhase backupsv1alpha1.RestoreJobPhase + wantMessage string + wantMissing string // a remedy the message must not offer for this kind + }{ + { + name: "postgres cross-namespace rename is rejected", + appKind: "Postgres", + targetName: "dst", + targetNS: targetNS, + wantPhase: backupsv1alpha1.RestoreJobPhaseFailed, + wantMessage: `restoring Postgres "src" under a different name ("dst") is not supported by the Velero strategy`, + }, + { + name: "postgres rejection points at the engine-native strategy", + appKind: "Postgres", + targetName: "dst", + targetNS: targetNS, + wantPhase: backupsv1alpha1.RestoreJobPhaseFailed, + wantMessage: "engine-native strategy", + }, + { + name: "vmdisk cross-namespace rename is rejected", + appKind: vmDiskAppKind, + targetName: "dst", + targetNS: targetNS, + wantPhase: backupsv1alpha1.RestoreJobPhaseFailed, + wantMessage: `restoring VMDisk "src" under a different name ("dst") is not supported by the Velero strategy`, + wantMissing: "engine-native strategy", + }, + { + name: "vmdisk rename is rejected by the backup kind, not the target kind", + appKind: vmDiskAppKind, + targetKind: vmInstanceKind, + targetName: "dst", + targetNS: targetNS, + wantPhase: backupsv1alpha1.RestoreJobPhaseFailed, + wantMessage: `restoring VMDisk "src" under a different name ("dst") is not supported by the Velero strategy`, + }, + { + name: "postgres same-namespace rename keeps the DataUpload message", + appKind: "Postgres", + targetName: "dst", + targetNS: "", + wantPhase: backupsv1alpha1.RestoreJobPhaseFailed, + wantMessage: "restoring to the same namespace with a different application name is not supported", + }, + { + name: "vminstance cross-namespace rename passes the guard", + appKind: vmInstanceKind, + targetName: "dst", + targetNS: targetNS, + wantPhase: backupsv1alpha1.RestoreJobPhaseRunning, + }, + { + name: "vmdisk cross-namespace copy keeping the source name passes the guard", + appKind: vmDiskAppKind, + targetName: "src", + targetNS: targetNS, + wantPhase: backupsv1alpha1.RestoreJobPhaseRunning, + }, + { + name: "vmdisk in-place restore without targetApplicationRef passes the guard", + appKind: vmDiskAppKind, + targetNS: "", + wantPhase: backupsv1alpha1.RestoreJobPhaseRunning, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + backup := &backupsv1alpha1.Backup{ + ObjectMeta: metav1.ObjectMeta{Name: "src-sb", Namespace: sourceNS}, + Spec: backupsv1alpha1.BackupSpec{ + ApplicationRef: corev1.TypedLocalObjectReference{ + APIGroup: stringPtr("apps.cozystack.io"), + Kind: tt.appKind, + Name: "src", + }, + StrategyRef: corev1.TypedLocalObjectReference{Kind: "Velero", Name: "cozy-default-velero"}, + }, + } + restoreJob := &backupsv1alpha1.RestoreJob{ + ObjectMeta: metav1.ObjectMeta{Name: "src-restore", Namespace: sourceNS}, + Spec: backupsv1alpha1.RestoreJobSpec{ + BackupRef: corev1.LocalObjectReference{Name: "src-sb"}, + }, + } + if tt.targetName != "" { + targetKind := tt.targetKind + if targetKind == "" { + targetKind = tt.appKind + } + restoreJob.Spec.TargetApplicationRef = &corev1.TypedLocalObjectReference{ + APIGroup: stringPtr("apps.cozystack.io"), + Kind: targetKind, + Name: tt.targetName, + } + } + if tt.targetNS != "" { + raw, err := json.Marshal(RestoreOptions{CommonRestoreOptions: CommonRestoreOptions{TargetNamespace: tt.targetNS}}) + if err != nil { + t.Fatalf("marshal options: %v", err) + } + restoreJob.Spec.Options = &runtime.RawExtension{Raw: raw} + } + targetNamespace := &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: targetNS}} + + reconciler := newTestRestoreJobReconcilerWithDynamic(t, nil, restoreJob, backup, targetNamespace) + reconciler.Client = newRestoreJobTestClient(t, restoreJob, backup, targetNamespace) + ctx := context.Background() + + if _, err := reconciler.reconcileVeleroRestore(ctx, restoreJob, backup); err != nil { + t.Fatalf("reconcileVeleroRestore() error = %v", err) + } + + got := &backupsv1alpha1.RestoreJob{} + if err := reconciler.Get(ctx, client.ObjectKeyFromObject(restoreJob), got); err != nil { + t.Fatalf("get RestoreJob: %v", err) + } + if got.Status.Phase != tt.wantPhase { + t.Fatalf("phase = %q, want %q", got.Status.Phase, tt.wantPhase) + } + if tt.wantMessage == "" { + return + } + ready := meta.FindStatusCondition(got.Status.Conditions, "Ready") + if ready == nil { + t.Fatalf("Ready condition missing, conditions: %+v", got.Status.Conditions) + } + if !strings.Contains(ready.Message, tt.wantMessage) { + t.Errorf("Ready message = %q, want it to contain %q", ready.Message, tt.wantMessage) + } + if tt.wantMissing != "" && strings.Contains(ready.Message, tt.wantMissing) { + t.Errorf("Ready message = %q, must not offer %q", ready.Message, tt.wantMissing) + } + }) + } +} + +// TestReconcileVeleroRestore_RenameGuard_InFlight covers a rename RestoreJob +// that was already Running when the guard was introduced: its Velero Restore +// has completed under the source name, so the job must fail with a message +// saying so and release its resource-modifier ConfigMap instead of waiting +// for the job's deletion. A VMInstance in the same state still succeeds. +func TestReconcileVeleroRestore_RenameGuard_InFlight(t *testing.T) { + const ( + sourceNS = "tenant-src" + targetNS = "tenant-dst" + ) + tests := []struct { + name string + appKind string + wantPhase backupsv1alpha1.RestoreJobPhase + wantMessage string + }{ + { + name: "vmdisk in-flight rename fails and names the source-name copy", + appKind: vmDiskAppKind, + wantPhase: backupsv1alpha1.RestoreJobPhaseFailed, + wantMessage: `This RestoreJob was already running, so "src" may have been restored into namespace "tenant-dst" under its source name`, + }, + { + name: "vminstance in-flight rename still succeeds", + appKind: vmInstanceKind, + wantPhase: backupsv1alpha1.RestoreJobPhaseSucceeded, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + started := metav1.Now() + backup := &backupsv1alpha1.Backup{ + ObjectMeta: metav1.ObjectMeta{Name: "src-sb", Namespace: sourceNS}, + Spec: backupsv1alpha1.BackupSpec{ + ApplicationRef: corev1.TypedLocalObjectReference{ + APIGroup: stringPtr("apps.cozystack.io"), + Kind: tt.appKind, + Name: "src", + }, + StrategyRef: corev1.TypedLocalObjectReference{Kind: "Velero", Name: "cozy-default-velero"}, + DriverMetadata: map[string]string{veleroBackupNameMetadataKey: "vb"}, + }, + } + raw, err := json.Marshal(RestoreOptions{CommonRestoreOptions: CommonRestoreOptions{TargetNamespace: targetNS}}) + if err != nil { + t.Fatalf("marshal options: %v", err) + } + restoreJob := &backupsv1alpha1.RestoreJob{ + ObjectMeta: metav1.ObjectMeta{Name: "src-restore", Namespace: sourceNS}, + Spec: backupsv1alpha1.RestoreJobSpec{ + BackupRef: corev1.LocalObjectReference{Name: "src-sb"}, + TargetApplicationRef: &corev1.TypedLocalObjectReference{ + APIGroup: stringPtr("apps.cozystack.io"), + Kind: tt.appKind, + Name: "dst", + }, + Options: &runtime.RawExtension{Raw: raw}, + }, + Status: backupsv1alpha1.RestoreJobStatus{ + Phase: backupsv1alpha1.RestoreJobPhaseRunning, + StartedAt: &started, + }, + } + owningLabels := map[string]string{ + backupsv1alpha1.OwningJobNameLabel: restoreJob.Name, + backupsv1alpha1.OwningJobNamespaceLabel: restoreJob.Namespace, + } + veleroRestore := &velerov1.Restore{ + ObjectMeta: metav1.ObjectMeta{Name: "vr", Namespace: veleroNamespace, Labels: owningLabels}, + Status: velerov1.RestoreStatus{Phase: velerov1.RestorePhaseCompleted}, + } + modifiers := &corev1.ConfigMap{ + ObjectMeta: metav1.ObjectMeta{Name: "restore-modifiers-tenant-src-src-restore", Namespace: veleroNamespace, Labels: owningLabels}, + } + strategy := &strategyv1alpha1.Velero{ObjectMeta: metav1.ObjectMeta{Name: "cozy-default-velero"}} + targetNamespace := &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: targetNS}} + + reconciler := newTestRestoreJobReconcilerWithDynamic(t, nil) + testScheme := runtime.NewScheme() + _ = scheme.AddToScheme(testScheme) + _ = backupsv1alpha1.AddToScheme(testScheme) + _ = velerov1.AddToScheme(testScheme) + _ = strategyv1alpha1.AddToScheme(testScheme) + reconciler.Client = clientfake.NewClientBuilder(). + WithScheme(testScheme). + WithObjects(restoreJob, backup, veleroRestore, modifiers, strategy, targetNamespace). + WithStatusSubresource(&backupsv1alpha1.RestoreJob{}). + Build() + ctx := context.Background() + + if _, err := reconciler.reconcileVeleroRestore(ctx, restoreJob, backup); err != nil { + t.Fatalf("reconcileVeleroRestore() error = %v", err) + } + + got := &backupsv1alpha1.RestoreJob{} + if err := reconciler.Get(ctx, client.ObjectKeyFromObject(restoreJob), got); err != nil { + t.Fatalf("get RestoreJob: %v", err) + } + if got.Status.Phase != tt.wantPhase { + t.Fatalf("phase = %q, want %q", got.Status.Phase, tt.wantPhase) + } + if err := reconciler.Get(ctx, client.ObjectKeyFromObject(modifiers), &corev1.ConfigMap{}); !errors.IsNotFound(err) { + t.Errorf("resource-modifier ConfigMap should be deleted, get err = %v", err) + } + if tt.wantMessage == "" { + return + } + ready := meta.FindStatusCondition(got.Status.Conditions, "Ready") + if ready == nil { + t.Fatalf("Ready condition missing, conditions: %+v", got.Status.Conditions) + } + if !strings.Contains(ready.Message, tt.wantMessage) { + t.Errorf("Ready message = %q, want it to contain %q", ready.Message, tt.wantMessage) + } + }) + } +} + func TestTargetHelmReleaseExists_VMDisk(t *testing.T) { ns := "tenant-copy" hr := makeUnstructuredHelmRelease("vm-disk-ubuntu-source", ns, nil) @@ -1211,3 +1751,307 @@ func containsString(s, substr string) bool { } return false } + +// keepPVCFixture is an in-place VMInstance restore of one disk, whose PVC +// vm-disk-ubuntu-source is bound to PV pv-current under a Delete policy. +type keepPVCFixture struct { + ns string + restoreJob *backupsv1alpha1.RestoreJob + backup *backupsv1alpha1.Backup + ur *runtime.RawExtension + target restoreTarget + opts RestoreOptions + livePVC *corev1.PersistentVolumeClaim + pv *corev1.PersistentVolume + origName string +} + +func newKeepPVCFixture(t *testing.T) *keepPVCFixture { + t.Helper() + ns := "tenant-root" + restoreJob := &backupsv1alpha1.RestoreJob{ + ObjectMeta: metav1.ObjectMeta{Name: "restore-test", Namespace: ns, UID: "restore-job-uid"}, + Spec: backupsv1alpha1.RestoreJobSpec{BackupRef: corev1.LocalObjectReference{Name: "my-backup"}}, + } + backup := &backupsv1alpha1.Backup{ + ObjectMeta: metav1.ObjectMeta{Name: "my-backup", Namespace: ns}, + Spec: backupsv1alpha1.BackupSpec{ + ApplicationRef: corev1.TypedLocalObjectReference{ + APIGroup: new("apps.cozystack.io"), + Kind: "VMInstance", + Name: "test-vm", + }, + }, + } + urRaw, err := json.Marshal(vmInstanceResources{ + DataVolumes: []backupsv1alpha1.DataVolumeResource{ + {DataVolumeName: "vm-disk-ubuntu-source", ApplicationName: "ubuntu-source"}, + }, + }) + if err != nil { + t.Fatal(err) + } + return &keepPVCFixture{ + ns: ns, + restoreJob: restoreJob, + backup: backup, + ur: &runtime.RawExtension{Raw: urRaw}, + target: restoreTarget{Namespace: ns, AppName: "test-vm", AppKind: "VMInstance"}, + opts: RestoreOptions{KeepOriginalPVC: new(true)}, + livePVC: &corev1.PersistentVolumeClaim{ + ObjectMeta: metav1.ObjectMeta{Name: "vm-disk-ubuntu-source", Namespace: ns, UID: "live-pvc-uid"}, + Spec: corev1.PersistentVolumeClaimSpec{VolumeName: "pv-current"}, + }, + pv: &corev1.PersistentVolume{ + ObjectMeta: metav1.ObjectMeta{Name: "pv-current"}, + Spec: corev1.PersistentVolumeSpec{ + PersistentVolumeReclaimPolicy: corev1.PersistentVolumeReclaimDelete, + ClaimRef: &corev1.ObjectReference{ + Kind: "PersistentVolumeClaim", Namespace: ns, Name: "vm-disk-ubuntu-source", UID: "live-pvc-uid", + }, + }, + }, + origName: "vm-disk-ubuntu-source-orig-" + shortHash(restoreJob.Name), + } +} + +func (f *keepPVCFixture) reconciler(t *testing.T, objects ...client.Object) *RestoreJobReconciler { + t.Helper() + dv := &unstructured.Unstructured{} + dv.SetAPIVersion("cdi.kubevirt.io/v1beta1") + dv.SetKind("DataVolume") + dv.SetName("vm-disk-ubuntu-source") + dv.SetNamespace(f.ns) + return newTestRestoreJobReconcilerWithDynamic(t, []runtime.Object{dv}, + append([]client.Object{f.restoreJob, f.backup}, objects...)...) +} + +func (f *keepPVCFixture) dataVolumeExists(t *testing.T, r *RestoreJobReconciler) bool { + t.Helper() + _, err := r.Resource(dataVolumeGVR).Namespace(f.ns).Get(context.Background(), "vm-disk-ubuntu-source", metav1.GetOptions{}) + if err != nil && !errors.IsNotFound(err) { + t.Fatalf("get DataVolume: %v", err) + } + return err == nil +} + +// A -orig PVC this RestoreJob did not create, such as one left by a deleted +// RestoreJob of the same name, must stop the restore before the DataVolume is +// deleted: skipping the rename would leave the live disk under its own name +// for the restore to overwrite. +func TestPrepareForRestore_KeepOriginalPVC_RefusesForeignOrigPVC(t *testing.T) { + for _, tc := range []struct { + name string + annotations map[string]string + }{ + {name: "no restore job annotation"}, + {name: "another restore job with the same name", annotations: map[string]string{origPVCRestoreJobUIDAnnotation: "previous-restore-job-uid"}}, + } { + t.Run(tc.name, func(t *testing.T) { + f := newKeepPVCFixture(t) + foreign := &corev1.PersistentVolumeClaim{ + ObjectMeta: metav1.ObjectMeta{Name: f.origName, Namespace: f.ns, Annotations: tc.annotations}, + Spec: corev1.PersistentVolumeClaimSpec{VolumeName: "pv-previous"}, + } + r := f.reconciler(t, f.livePVC, f.pv, foreign) + ctx := context.Background() + + ready, _, err := r.prepareForRestore(ctx, f.restoreJob, f.backup, f.ur, f.target, f.opts) + if err == nil { + t.Errorf("prepareForRestore() = ready %v, nil error; want an error naming %s", ready, f.origName) + } else if !strings.Contains(err.Error(), f.origName) { + t.Errorf("error %q does not name the taken PVC %s", err, f.origName) + } + + if !f.dataVolumeExists(t, r) { + t.Error("DataVolume was deleted although the disk could not be kept") + } + live := &corev1.PersistentVolumeClaim{} + if err := r.Get(ctx, client.ObjectKeyFromObject(f.livePVC), live); err != nil { + t.Fatalf("live PVC is gone: %v", err) + } + pv := &corev1.PersistentVolume{} + if err := r.Get(ctx, client.ObjectKey{Name: "pv-current"}, pv); err != nil { + t.Fatal(err) + } + if pv.Spec.PersistentVolumeReclaimPolicy != corev1.PersistentVolumeReclaimDelete || pv.Spec.ClaimRef.Name != f.livePVC.Name { + t.Errorf("PV was modified: policy %s, claim %s", pv.Spec.PersistentVolumeReclaimPolicy, pv.Spec.ClaimRef.Name) + } + got := &corev1.PersistentVolumeClaim{} + if err := r.Get(ctx, client.ObjectKey{Namespace: f.ns, Name: f.origName}, got); err != nil { + t.Fatal(err) + } + if got.Spec.VolumeName != "pv-previous" { + t.Errorf("foreign -orig PVC now points at %q", got.Spec.VolumeName) + } + }) + } +} + +// A rename interrupted after the -orig PVC was created must complete on the +// next reconcile, and a rename already complete must be left alone. +func TestPrepareForRestore_KeepOriginalPVC_ResumesOwnRename(t *testing.T) { + f := newKeepPVCFixture(t) + f.pv.Spec.PersistentVolumeReclaimPolicy = corev1.PersistentVolumeReclaimRetain + f.pv.Annotations = map[string]string{originalReclaimPolicyAnnotation: "Delete"} + own := &corev1.PersistentVolumeClaim{ + ObjectMeta: metav1.ObjectMeta{ + Name: f.origName, Namespace: f.ns, + Annotations: map[string]string{ + origPVCRestoreJobUIDAnnotation: string(f.restoreJob.UID), + originalReclaimPolicyAnnotation: "Delete", + }, + }, + Spec: corev1.PersistentVolumeClaimSpec{VolumeName: "pv-current"}, + } + r := f.reconciler(t, f.livePVC, f.pv, own) + ctx := context.Background() + + for pass := 1; pass <= 2; pass++ { + ready, _, err := r.prepareForRestore(ctx, f.restoreJob, f.backup, f.ur, f.target, f.opts) + if err != nil || !ready { + t.Fatalf("pass %d: prepareForRestore() = ready %v, error %v; want ready", pass, ready, err) + } + if err := r.Get(ctx, client.ObjectKeyFromObject(f.livePVC), &corev1.PersistentVolumeClaim{}); !errors.IsNotFound(err) { + t.Errorf("pass %d: original PVC still exists (err %v)", pass, err) + } + kept := &corev1.PersistentVolumeClaim{} + if err := r.Get(ctx, client.ObjectKey{Namespace: f.ns, Name: f.origName}, kept); err != nil { + t.Fatalf("pass %d: -orig PVC is gone: %v", pass, err) + } + pv := &corev1.PersistentVolume{} + if err := r.Get(ctx, client.ObjectKey{Name: "pv-current"}, pv); err != nil { + t.Fatal(err) + } + if ref := pv.Spec.ClaimRef; ref == nil || ref.Name != f.origName || ref.UID != kept.UID { + t.Errorf("pass %d: PV claimRef = %+v, want %s", pass, ref, f.origName) + } + } + if f.dataVolumeExists(t, r) { + t.Error("DataVolume was not deleted after the rename completed") + } +} + +// The PV goes to Retain so it outlives the original PVC; the policy it had +// must be recorded, or nobody can set it back on the -orig PVC's PV. +func TestRenamePVC_RecordsOriginalReclaimPolicy(t *testing.T) { + for _, policy := range []corev1.PersistentVolumeReclaimPolicy{ + corev1.PersistentVolumeReclaimDelete, + corev1.PersistentVolumeReclaimRetain, + } { + t.Run(string(policy), func(t *testing.T) { + f := newKeepPVCFixture(t) + f.pv.Spec.PersistentVolumeReclaimPolicy = policy + r := f.reconciler(t, f.livePVC, f.pv) + ctx := context.Background() + + if err := r.renamePVC(ctx, f.restoreJob, f.ns, f.livePVC.Name, f.origName); err != nil { + t.Fatalf("renamePVC() error = %v", err) + } + + pv := &corev1.PersistentVolume{} + if err := r.Get(ctx, client.ObjectKey{Name: "pv-current"}, pv); err != nil { + t.Fatal(err) + } + if pv.Spec.PersistentVolumeReclaimPolicy != corev1.PersistentVolumeReclaimRetain { + t.Errorf("PV policy = %s, want Retain while the -orig PVC holds it", pv.Spec.PersistentVolumeReclaimPolicy) + } + if got := pv.Annotations[originalReclaimPolicyAnnotation]; got != string(policy) { + t.Errorf("PV %s = %q, want %q", originalReclaimPolicyAnnotation, got, policy) + } + kept := &corev1.PersistentVolumeClaim{} + if err := r.Get(ctx, client.ObjectKey{Namespace: f.ns, Name: f.origName}, kept); err != nil { + t.Fatal(err) + } + if got := kept.Annotations[originalReclaimPolicyAnnotation]; got != string(policy) { + t.Errorf("-orig PVC %s = %q, want %q", originalReclaimPolicyAnnotation, got, policy) + } + }) + } +} + +// Any failure to keep the disk must hold the restore back before its +// DataVolume is deleted, not only a taken -orig name, and the retry must +// finish the rename once the cause is gone. +func TestPrepareForRestore_KeepOriginalPVC_FailedRenameKeepsDataVolume(t *testing.T) { + f := newKeepPVCFixture(t) + r := f.reconciler(t, f.livePVC) // PV pv-current is missing + ctx := context.Background() + + ready, result, err := r.prepareForRestore(ctx, f.restoreJob, f.backup, f.ur, f.target, f.opts) + if err != nil || ready || result.RequeueAfter == 0 { + t.Errorf("prepareForRestore() = ready %v, %+v, error %v; want a requeue without failing the restore", ready, result, err) + } + if !f.dataVolumeExists(t, r) { + t.Fatal("DataVolume was deleted although the disk could not be kept") + } + + if err := r.Create(ctx, f.pv); err != nil { + t.Fatal(err) + } + ready, _, err = r.prepareForRestore(ctx, f.restoreJob, f.backup, f.ur, f.target, f.opts) + if err != nil || !ready { + t.Fatalf("retry: prepareForRestore() = ready %v, error %v; want ready", ready, err) + } + if err := r.Get(ctx, client.ObjectKey{Namespace: f.ns, Name: f.origName}, &corev1.PersistentVolumeClaim{}); err != nil { + t.Errorf("retry: -orig PVC: %v", err) + } + if f.dataVolumeExists(t, r) { + t.Error("retry: DataVolume was not deleted after the rename completed") + } +} + +// laggingCacheReconciler serves every cached read from the objects as they +// were seeded, as an informer that has not caught up with this reconcile's +// own writes would; APIReader sees the writes. +func (f *keepPVCFixture) laggingCacheReconciler(t *testing.T, objects ...client.Object) *RestoreJobReconciler { + t.Helper() + r := f.reconciler(t, objects...) + seeded := append([]client.Object{f.restoreJob, f.backup}, objects...) + for i, obj := range seeded { + seeded[i] = obj.DeepCopyObject().(client.Object) + } + cache := clientfake.NewClientBuilder().WithScheme(r.Scheme).WithObjects(seeded...).Build() + apiServer := r.Client.(client.WithWatch) + r.Client = interceptor.NewClient(apiServer, interceptor.Funcs{ + Get: func(ctx context.Context, _ client.WithWatch, key client.ObjectKey, obj client.Object, opts ...client.GetOption) error { + return cache.Get(ctx, key, obj, opts...) + }, + }) + r.APIReader = apiServer + return r +} + +// On the lab, a two-disk restore failed one disk with "failed to get -orig +// PVC ...: not found": the PVC had just been created, and the cache had not +// seen it yet. The rename must not depend on the cache seeing its own writes. +func TestPrepareForRestore_KeepOriginalPVC_CacheLagsBehindWrites(t *testing.T) { + f := newKeepPVCFixture(t) + r := f.laggingCacheReconciler(t, f.livePVC, f.pv) + ctx := context.Background() + + ready, _, err := r.prepareForRestore(ctx, f.restoreJob, f.backup, f.ur, f.target, f.opts) + if err != nil || !ready { + t.Fatalf("prepareForRestore() = ready %v, error %v; want ready", ready, err) + } + kept := &corev1.PersistentVolumeClaim{} + if err := r.APIReader.Get(ctx, client.ObjectKey{Namespace: f.ns, Name: f.origName}, kept); err != nil { + t.Fatalf("-orig PVC: %v", err) + } + if err := r.APIReader.Get(ctx, client.ObjectKeyFromObject(f.livePVC), &corev1.PersistentVolumeClaim{}); !errors.IsNotFound(err) { + t.Errorf("original PVC still exists (err %v)", err) + } + pv := &corev1.PersistentVolume{} + if err := r.APIReader.Get(ctx, client.ObjectKey{Name: "pv-current"}, pv); err != nil { + t.Fatal(err) + } + if ref := pv.Spec.ClaimRef; ref == nil || ref.Name != f.origName || ref.UID != kept.UID { + t.Errorf("PV claimRef = %+v, want %s", ref, f.origName) + } + if pv.Spec.PersistentVolumeReclaimPolicy != corev1.PersistentVolumeReclaimRetain { + t.Errorf("PV policy = %s, want Retain", pv.Spec.PersistentVolumeReclaimPolicy) + } + if f.dataVolumeExists(t, r) { + t.Error("DataVolume was not deleted after the rename completed") + } +} diff --git a/internal/controller/applicationdefinition_controller.go b/internal/controller/applicationdefinition_controller.go index 6ce252490..6570d12b0 100644 --- a/internal/controller/applicationdefinition_controller.go +++ b/internal/controller/applicationdefinition_controller.go @@ -6,10 +6,12 @@ import ( "encoding/hex" "encoding/json" "slices" + "strings" "sync" "time" cozyv1alpha1 "github.com/cozystack/cozystack/api/v1alpha1" + "github.com/cozystack/cozystack/pkg/config" appsv1 "k8s.io/api/apps/v1" corev1 "k8s.io/api/core/v1" @@ -67,6 +69,33 @@ func (r *ApplicationDefinitionReconciler) SetupWithManager(mgr ctrl.Manager) err type appDefHashView struct { Name string `json:"name"` Spec cozyv1alpha1.ApplicationDefinitionSpec `json:"spec"` + // Annotations holds the release.cozystack.io/* subset of the definition's + // metadata annotations. They belong in the hash because cozystack-api reads + // them once, at start-up (CozyServerOptions.Complete in pkg/cmd/server/start.go), + // and this rollout is the only thing that delivers a change in one: a + // definition whose whole change is an annotation would otherwise leave the + // running api serving the previous behaviour until its pod restarted for an + // unrelated reason. Only that prefix is hashed, because kubectl and Helm + // rewrite annotations of their own on every apply and hashing those would + // roll the api Deployment on every reconcile. + Annotations map[string]string `json:"annotations,omitempty"` +} + +// releaseAnnotations returns the release.cozystack.io/* annotations of a +// definition, or nil when it carries none, so a definition without them hashes +// exactly as it did before this field existed. +func releaseAnnotations(annotations map[string]string) map[string]string { + var selected map[string]string + for k, v := range annotations { + if !strings.HasPrefix(k, config.ReleaseAnnotationPrefix) { + continue + } + if selected == nil { + selected = make(map[string]string) + } + selected[k] = v + } + return selected } func (r *ApplicationDefinitionReconciler) computeConfigHash(ctx context.Context) (string, error) { @@ -80,8 +109,9 @@ func (r *ApplicationDefinitionReconciler) computeConfigHash(ctx context.Context) views := make([]appDefHashView, 0, len(list.Items)) for i := range list.Items { views = append(views, appDefHashView{ - Name: list.Items[i].Name, - Spec: list.Items[i].Spec, + Name: list.Items[i].Name, + Spec: list.Items[i].Spec, + Annotations: releaseAnnotations(list.Items[i].Annotations), }) } b, err := json.Marshal(views) diff --git a/internal/controller/applicationdefinition_controller_test.go b/internal/controller/applicationdefinition_controller_test.go index f3ac64375..e7a661cfd 100644 --- a/internal/controller/applicationdefinition_controller_test.go +++ b/internal/controller/applicationdefinition_controller_test.go @@ -6,6 +6,7 @@ import ( "time" cozyv1alpha1 "github.com/cozystack/cozystack/api/v1alpha1" + "github.com/cozystack/cozystack/pkg/config" appsv1 "k8s.io/api/apps/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" @@ -229,3 +230,65 @@ func TestApplicationDefinition_HashUnchangedSkipsPatch(t *testing.T) { t.Fatalf("expected lastHandled advanced after no-op reconcile") } } + +// hashWithAnnotations computes the config hash for a single ApplicationDefinition +// carrying the given metadata annotations. +func hashWithAnnotations(t *testing.T, annotations map[string]string) string { + t.Helper() + + scheme := newAppDefScheme(t) + appDef := &cozyv1alpha1.ApplicationDefinition{ + ObjectMeta: metav1.ObjectMeta{Name: "vm-instance", Annotations: annotations}, + } + r := &ApplicationDefinitionReconciler{ + Client: fake.NewClientBuilder().WithScheme(scheme).WithObjects(appDef).Build(), + Scheme: scheme, + } + + hash, err := r.computeConfigHash(context.TODO()) + if err != nil { + t.Fatalf("computeConfigHash: %v", err) + } + return hash +} + +// TestApplicationDefinition_HashCoversReleaseAnnotations pins that a change +// confined to a release.cozystack.io/* annotation moves the hash. cozystack-api +// reads those annotations once, at start-up (pkg/cmd/server/start.go), so the +// config-hash rollout is the only thing that makes such a change take effect. +// A hash built from spec alone leaves the annotation inert on an existing +// cluster until the api pod happens to restart for an unrelated reason, which +// is indistinguishable from the change never having been delivered. +func TestApplicationDefinition_HashCoversReleaseAnnotations(t *testing.T) { + bare := hashWithAnnotations(t, nil) + annotated := hashWithAnnotations(t, map[string]string{ + config.HelmInstallDisableWaitAnnotation: "true", + }) + + if bare == annotated { + t.Fatalf("hash ignores %s: %q for both", config.HelmInstallDisableWaitAnnotation, bare) + } + + flipped := hashWithAnnotations(t, map[string]string{ + config.HelmInstallDisableWaitAnnotation: "false", + }) + if flipped == annotated { + t.Fatalf("hash ignores the annotation's value: %q for both true and false", annotated) + } +} + +// TestApplicationDefinition_HashIgnoresUnrelatedAnnotations pins the other half: +// only the release.cozystack.io/ prefix counts. kubectl and Flux rewrite their +// own annotations on every apply, and hashing those would roll out cozystack-api +// on every reconcile of every ApplicationDefinition. +func TestApplicationDefinition_HashIgnoresUnrelatedAnnotations(t *testing.T) { + bare := hashWithAnnotations(t, nil) + noisy := hashWithAnnotations(t, map[string]string{ + "kubectl.kubernetes.io/last-applied-configuration": `{"metadata":{"name":"vm-instance"}}`, + "meta.helm.sh/release-name": "vm-instance-rd", + }) + + if bare != noisy { + t.Fatalf("unrelated annotations moved the hash: %q vs %q", bare, noisy) + } +} diff --git a/internal/controller/applicationdefinition_helmreconciler.go b/internal/controller/applicationdefinition_helmreconciler.go index 5f4f63bd6..2a07fe04c 100644 --- a/internal/controller/applicationdefinition_helmreconciler.go +++ b/internal/controller/applicationdefinition_helmreconciler.go @@ -5,6 +5,7 @@ import ( "fmt" cozyv1alpha1 "github.com/cozystack/cozystack/api/v1alpha1" + "github.com/cozystack/cozystack/pkg/config" helmv2 "github.com/fluxcd/helm-controller/api/v2" "k8s.io/apimachinery/pkg/runtime" @@ -163,6 +164,44 @@ func (r *ApplicationDefinitionHelmReconciler) updateHelmReleaseChart(ctx context updated = true } + // Check and update the readiness wait. cozystack-api reads + // release.cozystack.io/helm-install-disable-wait off the definition when it + // builds a release, and only there, so a release created before the + // annotation appeared keeps waiting on readiness until its Application is + // written through the apps API again. Where the wait is what broke, that is + // every existing instance of the kind at once, each looping upgrade and + // timeout until an operator rewrites it by hand. The definition is the + // source of truth in both directions, since the API rebuilds the whole spec + // on every write and emits DisableWait=false once the annotation is gone. + disableWait, err := config.ParseHelmInstallDisableWaitAnnotation( + appDef.Annotations[config.HelmInstallDisableWaitAnnotation], + ) + if err != nil { + // cozystack-api refuses to start on this same value, so the cluster + // already has a loud signal; leave the field as it is rather than guess. + logger.Error(err, "Skipping HelmRelease wait update: invalid annotation", + "appDef", appDef.Name, "annotation", config.HelmInstallDisableWaitAnnotation) + } else { + // An absent install/upgrade block already behaves as DisableWait=false, + // so it is only materialised when the definition asks to disable the wait. + if disableWait && hrCopy.Spec.Install == nil { + hrCopy.Spec.Install = &helmv2.Install{} + } + if hrCopy.Spec.Install != nil && hrCopy.Spec.Install.DisableWait != disableWait { + logger.V(4).Info("Updating HelmRelease install wait", "name", hr.Name, "namespace", hr.Namespace, "disableWait", disableWait) + hrCopy.Spec.Install.DisableWait = disableWait + updated = true + } + if disableWait && hrCopy.Spec.Upgrade == nil { + hrCopy.Spec.Upgrade = &helmv2.Upgrade{} + } + if hrCopy.Spec.Upgrade != nil && hrCopy.Spec.Upgrade.DisableWait != disableWait { + logger.V(4).Info("Updating HelmRelease upgrade wait", "name", hr.Name, "namespace", hr.Namespace, "disableWait", disableWait) + hrCopy.Spec.Upgrade.DisableWait = disableWait + updated = true + } + } + // Check and update labels from ApplicationDefinition if len(appDef.Spec.Release.Labels) > 0 { if hrCopy.Labels == nil { diff --git a/internal/controller/applicationdefinition_helmreconciler_test.go b/internal/controller/applicationdefinition_helmreconciler_test.go index e7215067a..f8d055184 100644 --- a/internal/controller/applicationdefinition_helmreconciler_test.go +++ b/internal/controller/applicationdefinition_helmreconciler_test.go @@ -5,6 +5,7 @@ import ( "testing" cozyv1alpha1 "github.com/cozystack/cozystack/api/v1alpha1" + "github.com/cozystack/cozystack/pkg/config" helmv2 "github.com/fluxcd/helm-controller/api/v2" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" @@ -352,3 +353,231 @@ func TestValuesFromEqual(t *testing.T) { }) } } + +// vmInstanceRelease builds a VMInstance HelmRelease carrying the application +// labels this reconciler selects on, with the given wait configuration. +func vmInstanceRelease(install, upgrade *bool) *helmv2.HelmRelease { + hr := &helmv2.HelmRelease{ + ObjectMeta: metav1.ObjectMeta{ + Name: "vm-instance-web", + Namespace: "tenant-foo", + Labels: map[string]string{ + "apps.cozystack.io/application.kind": "VMInstance", + "apps.cozystack.io/application.group": "apps.cozystack.io", + }, + }, + Spec: helmv2.HelmReleaseSpec{ + ChartRef: &helmv2.CrossNamespaceSourceReference{ + Kind: "ExternalArtifact", + Name: "vm-instance-app", + Namespace: "cozy-system", + }, + }, + } + if install != nil { + hr.Spec.Install = &helmv2.Install{DisableWait: *install} + } + if upgrade != nil { + hr.Spec.Upgrade = &helmv2.Upgrade{DisableWait: *upgrade} + } + return hr +} + +// vmInstanceAppDef builds the VMInstance ApplicationDefinition, optionally +// carrying the disable-wait annotation. +func vmInstanceAppDef(annotations map[string]string) *cozyv1alpha1.ApplicationDefinition { + return &cozyv1alpha1.ApplicationDefinition{ + ObjectMeta: metav1.ObjectMeta{Name: "vm-instance", Annotations: annotations}, + Spec: cozyv1alpha1.ApplicationDefinitionSpec{ + Application: cozyv1alpha1.ApplicationDefinitionApplication{Kind: "VMInstance"}, + Release: cozyv1alpha1.ApplicationDefinitionRelease{ + ChartRef: &helmv2.CrossNamespaceSourceReference{ + Kind: "ExternalArtifact", + Name: "vm-instance-app", + Namespace: "cozy-system", + }, + }, + }, + } +} + +func reconcileVMInstance(t *testing.T, appDef *cozyv1alpha1.ApplicationDefinition, hr *helmv2.HelmRelease) *helmv2.HelmRelease { + t.Helper() + + scheme := newAppDefHelmScheme(t) + fakeClient := fake.NewClientBuilder().WithScheme(scheme).WithObjects(appDef, hr).Build() + r := &ApplicationDefinitionHelmReconciler{Client: fakeClient, Scheme: scheme} + + if _, err := r.Reconcile(context.TODO(), reconcile.Request{ + NamespacedName: types.NamespacedName{Name: appDef.Name}, + }); err != nil { + t.Fatalf("unexpected error: %v", err) + } + + got := &helmv2.HelmRelease{} + if err := fakeClient.Get(context.TODO(), types.NamespacedName{Name: hr.Name, Namespace: hr.Namespace}, got); err != nil { + t.Fatalf("get HR: %v", err) + } + return got +} + +// TestAppDefHelm_DisableWaitApplied pins the drift this reconciler exists to +// close, for the one field a running release cannot pick up on its own: a +// HelmRelease created before the definition carried +// release.cozystack.io/helm-install-disable-wait keeps waiting on readiness +// until its Application is written through the apps API again. On a cluster +// where the wait is what broke (a KubeVirt VirtualMachine the kstatus poller +// reads as permanently InProgress), that is every existing VM, each one +// looping upgrade and timeout, and re-writing them by hand is the operator's +// only way out. Bring the field to what the definition asks for instead. +func TestAppDefHelm_DisableWaitApplied(t *testing.T) { + no := false + got := reconcileVMInstance(t, + vmInstanceAppDef(map[string]string{config.HelmInstallDisableWaitAnnotation: "true"}), + vmInstanceRelease(&no, &no)) + + if got.Spec.Install == nil || !got.Spec.Install.DisableWait { + t.Fatalf("expected Install.DisableWait=true, got %+v", got.Spec.Install) + } + if got.Spec.Upgrade == nil || !got.Spec.Upgrade.DisableWait { + t.Fatalf("expected Upgrade.DisableWait=true, got %+v", got.Spec.Upgrade) + } +} + +// TestAppDefHelm_DisableWaitAppliedToAbsentBlocks pins the same on a release +// that carries no install/upgrade block at all: the field still has to land. +func TestAppDefHelm_DisableWaitAppliedToAbsentBlocks(t *testing.T) { + got := reconcileVMInstance(t, + vmInstanceAppDef(map[string]string{config.HelmInstallDisableWaitAnnotation: "true"}), + vmInstanceRelease(nil, nil)) + + if got.Spec.Install == nil || !got.Spec.Install.DisableWait { + t.Fatalf("expected Install.DisableWait=true, got %+v", got.Spec.Install) + } + if got.Spec.Upgrade == nil || !got.Spec.Upgrade.DisableWait { + t.Fatalf("expected Upgrade.DisableWait=true, got %+v", got.Spec.Upgrade) + } +} + +// TestAppDefHelm_DisableWaitRemoved pins the other direction, because the +// definition is the source of truth in both: cozystack-api rebuilds the whole +// spec on every write and emits DisableWait=false once the annotation is gone, +// so a release left at true would drift back the moment anyone touched it. +func TestAppDefHelm_DisableWaitRemoved(t *testing.T) { + yes := true + got := reconcileVMInstance(t, vmInstanceAppDef(nil), vmInstanceRelease(&yes, &yes)) + + if got.Spec.Install == nil || got.Spec.Install.DisableWait { + t.Fatalf("expected Install.DisableWait=false, got %+v", got.Spec.Install) + } + if got.Spec.Upgrade == nil || got.Spec.Upgrade.DisableWait { + t.Fatalf("expected Upgrade.DisableWait=false, got %+v", got.Spec.Upgrade) + } +} + +// TestAppDefHelm_DisableWaitLeavesAbsentBlocksAlone pins that the false case +// does not materialise empty install/upgrade blocks on a release that has +// none: writing them would change nothing about the release's behaviour and +// would make every such reconcile an update. +func TestAppDefHelm_DisableWaitLeavesAbsentBlocksAlone(t *testing.T) { + got := reconcileVMInstance(t, vmInstanceAppDef(nil), vmInstanceRelease(nil, nil)) + + if got.Spec.Install != nil { + t.Fatalf("expected Install left absent, got %+v", got.Spec.Install) + } + if got.Spec.Upgrade != nil { + t.Fatalf("expected Upgrade left absent, got %+v", got.Spec.Upgrade) + } +} + +// TestAppDefHelm_DisableWaitInSyncSkipsUpdate pins idempotence: a release that +// already matches must not be written, or every reconcile of every definition +// bumps the resourceVersion of every release it owns and wakes helm-controller. +func TestAppDefHelm_DisableWaitInSyncSkipsUpdate(t *testing.T) { + yes := true + hr := vmInstanceRelease(&yes, &yes) + hr.Spec.ValuesFrom = expectedValuesFrom() + + scheme := newAppDefHelmScheme(t) + appDef := vmInstanceAppDef(map[string]string{config.HelmInstallDisableWaitAnnotation: "true"}) + fakeClient := fake.NewClientBuilder().WithScheme(scheme).WithObjects(appDef, hr).Build() + + before := &helmv2.HelmRelease{} + if err := fakeClient.Get(context.TODO(), types.NamespacedName{Name: hr.Name, Namespace: hr.Namespace}, before); err != nil { + t.Fatalf("get HR: %v", err) + } + + r := &ApplicationDefinitionHelmReconciler{Client: fakeClient, Scheme: scheme} + if _, err := r.Reconcile(context.TODO(), reconcile.Request{ + NamespacedName: types.NamespacedName{Name: appDef.Name}, + }); err != nil { + t.Fatalf("unexpected error: %v", err) + } + + after := &helmv2.HelmRelease{} + if err := fakeClient.Get(context.TODO(), types.NamespacedName{Name: hr.Name, Namespace: hr.Namespace}, after); err != nil { + t.Fatalf("get HR after reconcile: %v", err) + } + if after.ResourceVersion != before.ResourceVersion { + t.Fatalf("release rewritten with nothing to change: %q -> %q", before.ResourceVersion, after.ResourceVersion) + } +} + +// TestAppDefHelm_DisableWaitInvalidAnnotationLeavesReleaseAlone pins the +// invalid-annotation branch. The parser returns false alongside its error, so +// applying that value would switch the wait back on for every release of the +// kind; the release must keep what it has instead. +func TestAppDefHelm_DisableWaitInvalidAnnotationLeavesReleaseAlone(t *testing.T) { + yes := true + got := reconcileVMInstance(t, + vmInstanceAppDef(map[string]string{config.HelmInstallDisableWaitAnnotation: "yes"}), + vmInstanceRelease(&yes, &yes)) + + if got.Spec.Install == nil || !got.Spec.Install.DisableWait { + t.Fatalf("expected Install.DisableWait=true kept, got %+v", got.Spec.Install) + } + if got.Spec.Upgrade == nil || !got.Spec.Upgrade.DisableWait { + t.Fatalf("expected Upgrade.DisableWait=true kept, got %+v", got.Spec.Upgrade) + } +} + +// TestAppDefHelm_DisableWaitScopedToKind pins the kind label in the selector: +// a release of another kind in the same group must not pick up the wait +// setting of the VMInstance definition. +func TestAppDefHelm_DisableWaitScopedToKind(t *testing.T) { + no := false + vm := vmInstanceRelease(&no, &no) + other := vmInstanceRelease(&no, &no) + other.Name = "harbor-registry" + other.Labels["apps.cozystack.io/application.kind"] = "Harbor" + + scheme := newAppDefHelmScheme(t) + appDef := vmInstanceAppDef(map[string]string{config.HelmInstallDisableWaitAnnotation: "true"}) + fakeClient := fake.NewClientBuilder().WithScheme(scheme).WithObjects(appDef, vm, other).Build() + + r := &ApplicationDefinitionHelmReconciler{Client: fakeClient, Scheme: scheme} + if _, err := r.Reconcile(context.TODO(), reconcile.Request{ + NamespacedName: types.NamespacedName{Name: appDef.Name}, + }); err != nil { + t.Fatalf("unexpected error: %v", err) + } + + gotVM := &helmv2.HelmRelease{} + if err := fakeClient.Get(context.TODO(), types.NamespacedName{Name: vm.Name, Namespace: vm.Namespace}, gotVM); err != nil { + t.Fatalf("get VMInstance HR: %v", err) + } + if gotVM.Spec.Install == nil || !gotVM.Spec.Install.DisableWait { + t.Fatalf("expected VMInstance Install.DisableWait=true, got %+v", gotVM.Spec.Install) + } + + gotOther := &helmv2.HelmRelease{} + if err := fakeClient.Get(context.TODO(), types.NamespacedName{Name: other.Name, Namespace: other.Namespace}, gotOther); err != nil { + t.Fatalf("get Harbor HR: %v", err) + } + if gotOther.Spec.Install == nil || gotOther.Spec.Install.DisableWait { + t.Fatalf("expected Harbor Install.DisableWait=false, got %+v", gotOther.Spec.Install) + } + if gotOther.Spec.Upgrade == nil || gotOther.Spec.Upgrade.DisableWait { + t.Fatalf("expected Harbor Upgrade.DisableWait=false, got %+v", gotOther.Spec.Upgrade) + } +} diff --git a/internal/controller/workloadmonitor_controller.go b/internal/controller/workloadmonitor_controller.go index 039b90893..daf3a682a 100644 --- a/internal/controller/workloadmonitor_controller.go +++ b/internal/controller/workloadmonitor_controller.go @@ -454,7 +454,7 @@ func (r *WorkloadMonitorReconciler) reconcilePVCForMonitor( for resourceName, resourceQuantity := range pvc.Status.Capacity { storageClass := "default" - if pvc.Spec.StorageClassName != nil || *pvc.Spec.StorageClassName == "" { + if pvc.Spec.StorageClassName != nil && *pvc.Spec.StorageClassName != "" { storageClass = *pvc.Spec.StorageClassName } resourceLabel := fmt.Sprintf("%s.storageclass.storage.k8s.io/requests.%s", storageClass, resourceName.String()) diff --git a/internal/controller/workloadmonitor_controller_test.go b/internal/controller/workloadmonitor_controller_test.go index ddea1ce7b..ee85f422c 100644 --- a/internal/controller/workloadmonitor_controller_test.go +++ b/internal/controller/workloadmonitor_controller_test.go @@ -14,6 +14,7 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/types" + "k8s.io/utils/ptr" cosiv1alpha1 "sigs.k8s.io/container-object-storage-interface-api/apis/objectstorage/v1alpha1" "sigs.k8s.io/controller-runtime/pkg/client/fake" "sigs.k8s.io/controller-runtime/pkg/reconcile" @@ -1240,3 +1241,62 @@ func TestGetWorkloadMetadata(t *testing.T) { }) } } + +func TestReconcile_PVCStorageClassResourceKey(t *testing.T) { + cases := []struct { + name string + storageClass *string + wantKey string + }{ + {"unset falls back to default", nil, "default.storageclass.storage.k8s.io/requests.storage"}, + {"empty falls back to default", ptr.To(""), "default.storageclass.storage.k8s.io/requests.storage"}, + {"explicit class is kept", ptr.To("replicated"), "replicated.storageclass.storage.k8s.io/requests.storage"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + scheme := newTestScheme() + monitor := &cozyv1alpha1.WorkloadMonitor{ + ObjectMeta: metav1.ObjectMeta{Name: "test-monitor", Namespace: "default"}, + Spec: cozyv1alpha1.WorkloadMonitorSpec{ + Selector: map[string]string{"app": "test"}, + Kind: "postgres", + Type: "postgres", + }, + } + pvc := &corev1.PersistentVolumeClaim{ + ObjectMeta: metav1.ObjectMeta{ + Name: "data", + Namespace: "default", + Labels: map[string]string{"app": "test"}, + }, + Spec: corev1.PersistentVolumeClaimSpec{StorageClassName: tc.storageClass}, + Status: corev1.PersistentVolumeClaimStatus{ + Phase: corev1.ClaimBound, + Capacity: corev1.ResourceList{corev1.ResourceStorage: resource.MustParse("10Gi")}, + }, + } + fakeClient := fake.NewClientBuilder(). + WithScheme(scheme). + WithObjects(monitor, pvc). + WithStatusSubresource(monitor). + Build() + + reconciler := &WorkloadMonitorReconciler{Client: fakeClient, Scheme: scheme} + req := reconcile.Request{NamespacedName: types.NamespacedName{Name: "test-monitor", Namespace: "default"}} + if _, err := reconciler.Reconcile(context.TODO(), req); err != nil { + t.Fatalf("Reconcile returned error: %v", err) + } + + workload := &cozyv1alpha1.Workload{} + if err := fakeClient.Get(context.TODO(), types.NamespacedName{Name: "pvc-data", Namespace: "default"}, workload); err != nil { + t.Fatalf("Failed to get Workload: %v", err) + } + if len(workload.Status.Resources) != 1 { + t.Fatalf("expected one resource entry, got %v", workload.Status.Resources) + } + if _, ok := workload.Status.Resources[tc.wantKey]; !ok { + t.Errorf("expected resource key %q, got %v", tc.wantKey, workload.Status.Resources) + } + }) + } +} diff --git a/internal/operator/packagesource_reconciler.go b/internal/operator/packagesource_reconciler.go index 8a6baacdb..d495b4651 100644 --- a/internal/operator/packagesource_reconciler.go +++ b/internal/operator/packagesource_reconciler.go @@ -78,6 +78,10 @@ const ( annotationFluxRequestedAt = "reconcile.fluxcd.io/requestedAt" annotationRecoveryAttempts = "cozystack.io/source-watcher-recovery-attempts" annotationLastRecoveryAt = "cozystack.io/source-watcher-last-recovery-at" + // annotationVerifiedGeneration records the last AG generation for which a + // rebuild was forced after source-watcher first reported it Ready; see + // verifyArtifactGeneratorGeneration. + annotationVerifiedGeneration = "cozystack.io/source-watcher-verified-generation" reasonAwaitingRecovery = "AwaitingSourceWatcherRecovery" reasonSourceWatcherBad = "SourceWatcherStalled" @@ -537,6 +541,10 @@ func (r *PackageSourceReconciler) updateStatus(ctx context.Context, packageSourc return ctrl.Result{RequeueAfter: agFollowUpDelay(ag.CreationTimestamp.Time, now)}, r.Status().Update(ctx, packageSource) } + if needsGenerationVerification(ag, readyCondition) { + return r.verifyArtifactGeneratorGeneration(ctx, packageSource, ag, now) + } + // Copy Ready condition from ArtifactGenerator to PackageSource meta.SetStatusCondition(&packageSource.Status.Conditions, metav1.Condition{ Type: "Ready", @@ -582,6 +590,63 @@ func agFollowUpDelay(transitionOrCreation time.Time, now time.Time) time.Duratio return remaining } +// needsGenerationVerification reports whether source-watcher has just claimed +// a successful build of an AG generation this operator has not yet verified. +// +// source-watcher builds from the spec it read when its reconcile started, but +// its final status patch re-reads the live object and stamps Ready with the +// live generation (fluxcd/source-watcher#384). When this operator changes the +// spec mid-build, the AG ends up Ready on the new generation with artifacts +// from the old one, and detectDrift never rebuilds it. Nothing in the AG +// status tells the two apart, so every generation that reaches Ready=True is +// rebuilt once. An unchanged spec rebuilds to the same digest, leaving the +// ExternalArtifacts and their HelmReleases untouched. +// +// Generation 1 is exempt: the race needs a spec change during a build. +// +// TODO(remove once fluxcd/source-watcher#384 is fixed and rolled out). +func needsGenerationVerification(ag *sourcewatcherv1beta1.ArtifactGenerator, ready *metav1.Condition) bool { + if ag.Generation <= 1 || ready.Status != metav1.ConditionTrue || ready.ObservedGeneration != ag.Generation { + return false + } + return ag.Annotations[annotationVerifiedGeneration] != strconv.FormatInt(ag.Generation, 10) +} + +// verifyArtifactGeneratorGeneration forces the one rebuild described on +// needsGenerationVerification through the fluxcd/pkg#934 force-drift path, so +// the follow-up reconciles are driven by maybeRecoverArtifactGenerator and the +// synthetic Ready=False never reaches the PackageSource. It starts a fresh +// attempt budget, since a counter left by an earlier stall may have survived +// the best-effort clearRecoveryTracking. The verified generation is recorded +// after the force: if that write fails, the next Ready=True costs one more +// rebuild rather than a skipped one. +func (r *PackageSourceReconciler) verifyArtifactGeneratorGeneration(ctx context.Context, packageSource *cozyv1alpha1.PackageSource, ag *sourcewatcherv1beta1.ArtifactGenerator, now time.Time) (ctrl.Result, error) { + if err := r.forceArtifactGeneratorDrift(ctx, ag, now, 1); err != nil { + return ctrl.Result{}, fmt.Errorf("failed to force ArtifactGenerator rebuild: %w", err) + } + patchBase := ag.DeepCopy() + ag.Annotations[annotationVerifiedGeneration] = strconv.FormatInt(ag.Generation, 10) + if err := r.Patch(ctx, ag, client.MergeFrom(patchBase)); err != nil { + return ctrl.Result{}, fmt.Errorf("failed to record verified ArtifactGenerator generation: %w", err) + } + meta.SetStatusCondition(&packageSource.Status.Conditions, metav1.Condition{ + Type: "Ready", + Status: metav1.ConditionUnknown, + Reason: reasonAwaitingRecovery, + Message: fmt.Sprintf( + "rebuilding ArtifactGenerator generation %d once, since source-watcher may have built it from the previous spec (fluxcd/source-watcher#384).", + ag.Generation, + ), + ObservedGeneration: packageSource.Generation, + }) + if err := r.Status().Update(ctx, packageSource); err != nil { + return ctrl.Result{}, err + } + log.FromContext(ctx).Info("forced ArtifactGenerator rebuild to verify generation", + "packageSource", packageSource.Name, "artifactGenerator", ag.Name, "generation", ag.Generation) + return ctrl.Result{RequeueAfter: backoffFor(1)}, nil +} + // maybeRecoverArtifactGenerator advances the bounded-recovery schedule for an // AG whose Ready condition is stuck in the fluxcd/pkg#934 window (Inventory // and ObservedSourcesDigest persisted on the current spec generation, Ready @@ -624,11 +689,10 @@ func agFollowUpDelay(transitionOrCreation time.Time, now time.Time) time.Duratio // source-watcher lands a definitive Ready=True or Ready=False with a // real upstream reason. // -// TODO(remove once fluxcd/pkg#934 lands and is rolled out): once source-watcher -// consumes a patch.Helper that either serialises or transactionally combines -// the .status / .status.conditions writes, this whole recovery driver can be -// deleted and updateStatus can copy the AG's Ready condition through -// unconditionally. +// TODO(remove once fluxcd/pkg#934 and fluxcd/source-watcher#384 are both +// fixed and rolled out): verifyArtifactGeneratorGeneration drives its rebuild +// through this driver, so it goes only together with that verification. Then +// updateStatus can copy the AG's Ready condition through unconditionally. func (r *PackageSourceReconciler) maybeRecoverArtifactGenerator(ctx context.Context, packageSource *cozyv1alpha1.PackageSource, ag *sourcewatcherv1beta1.ArtifactGenerator, ready *metav1.Condition, now time.Time) (ctrl.Result, error) { logger := log.FromContext(ctx) @@ -655,8 +719,8 @@ func (r *PackageSourceReconciler) maybeRecoverArtifactGenerator(ctx context.Cont switch decision.action { case recoveryActionGiveUp: message := fmt.Sprintf( - "ArtifactGenerator %s/%s has been stuck with a lost Ready condition through %d force-drift attempts; "+ - "source-watcher is not recovering. See https://github.com/fluxcd/pkg/issues/934. "+ + "ArtifactGenerator %s/%s has not been rebuilt through %d force-drift attempts; "+ + "source-watcher is not recovering (see fluxcd/pkg#934 and fluxcd/source-watcher#384). "+ "An operator must restart source-watcher or manually inspect the ArtifactGenerator.", ag.Namespace, ag.Name, maxRecoveryAttempts, ) @@ -677,8 +741,7 @@ func (r *PackageSourceReconciler) maybeRecoverArtifactGenerator(ctx context.Cont Status: metav1.ConditionUnknown, Reason: reasonAwaitingRecovery, Message: fmt.Sprintf( - "ArtifactGenerator Ready condition lost to fluxcd/pkg#934 patch.Helper race; "+ - "force-drift %d/%d issued, waiting for source-watcher to rebuild.", + "force-drift %d/%d issued, waiting for source-watcher to rebuild the ArtifactGenerator.", attempts, maxRecoveryAttempts, ), ObservedGeneration: packageSource.Generation, @@ -698,8 +761,7 @@ func (r *PackageSourceReconciler) maybeRecoverArtifactGenerator(ctx context.Cont Status: metav1.ConditionUnknown, Reason: reasonAwaitingRecovery, Message: fmt.Sprintf( - "ArtifactGenerator Ready condition lost to fluxcd/pkg#934 patch.Helper race; "+ - "forced drift on AG.status.conditions[Ready]=False (attempt %d/%d) so source-watcher rebuilds.", + "forced drift on AG.status.conditions[Ready]=False (attempt %d/%d) so source-watcher rebuilds.", nextAttempt, maxRecoveryAttempts, ), ObservedGeneration: packageSource.Generation, @@ -877,7 +939,7 @@ func (r *PackageSourceReconciler) forceArtifactGeneratorDrift(ctx context.Contex Type: "Ready", Status: metav1.ConditionFalse, Reason: reasonRecoveryForced, - Message: "cozystack-operator forced drift after fluxcd/pkg#934 stall; source-watcher will rebuild", + Message: "cozystack-operator forced drift; source-watcher will rebuild", ObservedGeneration: ag.Generation, }) if err := r.Status().Patch(ctx, ag, client.MergeFrom(statusBase)); err != nil { diff --git a/internal/operator/packagesource_reconciler_test.go b/internal/operator/packagesource_reconciler_test.go index f21cb6978..5fb130759 100644 --- a/internal/operator/packagesource_reconciler_test.go +++ b/internal/operator/packagesource_reconciler_test.go @@ -1432,3 +1432,297 @@ func TestUpdateStatus_OwnMarkerAttemptsExhaustedButFinalBackoffPending(t *testin t.Errorf("PS Ready = %+v, want Unknown/%s — give-up must wait for final backoff to elapse", psReady, reasonAwaitingRecovery) } } + +// builtAG returns a PackageSource and an ArtifactGenerator on the given +// generation whose Ready condition reports a finished build. +func builtAG(gen int64, readyStatus metav1.ConditionStatus, readyGen int64, annotations map[string]string) (*cozyv1alpha1.PackageSource, *sourcewatcherv1beta1.ArtifactGenerator) { + ps := &cozyv1alpha1.PackageSource{ + ObjectMeta: metav1.ObjectMeta{Name: "example", Namespace: "cozy-system", Generation: 1}, + Spec: cozyv1alpha1.PackageSourceSpec{ + SourceRef: &cozyv1alpha1.PackageSourceRef{Name: "src", Kind: "OCIRepository", Namespace: "cozy-system"}, + }, + } + ag := &sourcewatcherv1beta1.ArtifactGenerator{ + ObjectMeta: metav1.ObjectMeta{ + Name: "example", Namespace: "cozy-system", Generation: gen, + CreationTimestamp: metav1.NewTime(referenceTime.Add(-time.Hour)), + Annotations: annotations, + }, + Status: sourcewatcherv1beta1.ArtifactGeneratorStatus{ + Inventory: []sourcewatcherv1beta1.ExternalArtifactReference{ + {Name: "one", Namespace: "cozy-system", Digest: "sha256:aaa"}, + }, + ObservedSourcesDigest: "sha256:0e7", + Conditions: []metav1.Condition{{ + Type: "Ready", + Status: readyStatus, + Reason: "Succeeded", + ObservedGeneration: readyGen, + LastTransitionTime: metav1.NewTime(referenceTime.Add(-time.Second)), + }}, + }, + } + return ps, ag +} + +// TestUpdateStatus_ReadyOnUnverifiedGeneration_ForcesRebuild pins the guard +// against the source-watcher race where a build started on generation N-1 +// finishes after the spec moved to N and still records N as observed: the +// first Ready=True on a spec generation the operator changed forces one +// rebuild and records that generation as verified. +func TestUpdateStatus_ReadyOnUnverifiedGeneration_ForcesRebuild(t *testing.T) { + cases := []struct { + name string + gen int64 + annotations map[string]string + }{ + {"first spec change", 2, nil}, + {"later spec change", 3, map[string]string{annotationVerifiedGeneration: "2"}}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + testReadyOnUnverifiedGenerationForcesRebuild(t, tc.gen, tc.annotations) + }) + } +} + +func testReadyOnUnverifiedGenerationForcesRebuild(t *testing.T, gen int64, annotations map[string]string) { + ps, ag := builtAG(gen, metav1.ConditionTrue, gen, annotations) + c := fake.NewClientBuilder().WithScheme(testScheme(t)).WithStatusSubresource(ps, ag).WithObjects(ps, ag).Build() + r := &PackageSourceReconciler{Client: c, Scheme: testScheme(t)} + + res, err := r.updateStatus(context.Background(), ps, referenceTime) + if err != nil { + t.Fatalf("updateStatus: %v", err) + } + if res.RequeueAfter != backoffFor(1) { + t.Errorf("RequeueAfter = %v, want %v", res.RequeueAfter, backoffFor(1)) + } + + persistedAG := &sourcewatcherv1beta1.ArtifactGenerator{} + if err := c.Get(context.Background(), client.ObjectKeyFromObject(ag), persistedAG); err != nil { + t.Fatalf("Get AG: %v", err) + } + agReady := meta.FindStatusCondition(persistedAG.Status.Conditions, "Ready") + if agReady == nil || agReady.Status != metav1.ConditionFalse || agReady.Reason != reasonRecoveryForced { + t.Errorf("AG Ready = %+v, want False/%s", agReady, reasonRecoveryForced) + } + if persistedAG.Annotations[annotationFluxRequestedAt] == "" { + t.Errorf("requestedAt not bumped: %v", persistedAG.Annotations) + } + if got, want := persistedAG.Annotations[annotationVerifiedGeneration], strconv.FormatInt(gen, 10); got != want { + t.Errorf("verified generation = %q, want %q", got, want) + } + + persistedPS := &cozyv1alpha1.PackageSource{} + if err := c.Get(context.Background(), client.ObjectKeyFromObject(ps), persistedPS); err != nil { + t.Fatalf("Get PS: %v", err) + } + psReady := meta.FindStatusCondition(persistedPS.Status.Conditions, "Ready") + if psReady == nil || psReady.Status != metav1.ConditionUnknown || psReady.Reason != reasonAwaitingRecovery { + t.Errorf("PS Ready = %+v, want Unknown/%s", psReady, reasonAwaitingRecovery) + } +} + +// TestUpdateStatus_VerificationSkipped covers every state where the forced +// rebuild must not happen, so a verified or never-changed generator is not +// rebuilt on every reconcile and a failed or in-flight build is left to +// source-watcher. +func TestUpdateStatus_VerificationSkipped(t *testing.T) { + cases := []struct { + name string + gen int64 + status metav1.ConditionStatus + readyGen int64 + annotations map[string]string + }{ + {"generation already verified", 2, metav1.ConditionTrue, 2, map[string]string{annotationVerifiedGeneration: "2"}}, + {"spec never changed after creation", 1, metav1.ConditionTrue, 1, nil}, + {"build failed", 2, metav1.ConditionFalse, 2, nil}, + {"source-watcher has not caught up with the spec", 3, metav1.ConditionTrue, 2, map[string]string{annotationVerifiedGeneration: "2"}}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + ps, ag := builtAG(tc.gen, tc.status, tc.readyGen, tc.annotations) + c := fake.NewClientBuilder().WithScheme(testScheme(t)).WithStatusSubresource(ps, ag).WithObjects(ps, ag).Build() + r := &PackageSourceReconciler{Client: c, Scheme: testScheme(t)} + + if _, err := r.updateStatus(context.Background(), ps, referenceTime); err != nil { + t.Fatalf("updateStatus: %v", err) + } + persistedAG := &sourcewatcherv1beta1.ArtifactGenerator{} + if err := c.Get(context.Background(), client.ObjectKeyFromObject(ag), persistedAG); err != nil { + t.Fatalf("Get AG: %v", err) + } + if _, ok := persistedAG.Annotations[annotationFluxRequestedAt]; ok { + t.Errorf("rebuild forced: %v", persistedAG.Annotations) + } + persistedPS := &cozyv1alpha1.PackageSource{} + if err := c.Get(context.Background(), client.ObjectKeyFromObject(ps), persistedPS); err != nil { + t.Fatalf("Get PS: %v", err) + } + psReady := meta.FindStatusCondition(persistedPS.Status.Conditions, "Ready") + if psReady == nil || psReady.Status != tc.status { + t.Errorf("PS Ready = %+v, want %s copied through", psReady, tc.status) + } + }) + } +} + +// TestUpdateStatus_VerifiedRebuildSettles walks the forced rebuild to its end: +// once source-watcher reports Ready=True again, the recovery bookkeeping is +// cleared and the condition is copied through without another rebuild. +func TestUpdateStatus_VerifiedRebuildSettles(t *testing.T) { + forcedAt := referenceTime.Add(-10 * time.Second).UTC().Format(time.RFC3339Nano) + ps, ag := builtAG(2, metav1.ConditionTrue, 2, map[string]string{ + annotationVerifiedGeneration: "2", + annotationRecoveryAttempts: "1", + annotationLastRecoveryAt: forcedAt, + annotationFluxRequestedAt: forcedAt, + }) + c := fake.NewClientBuilder().WithScheme(testScheme(t)).WithStatusSubresource(ps, ag).WithObjects(ps, ag).Build() + r := &PackageSourceReconciler{Client: c, Scheme: testScheme(t)} + + res, err := r.updateStatus(context.Background(), ps, referenceTime) + if err != nil { + t.Fatalf("updateStatus: %v", err) + } + if res.RequeueAfter != 0 { + t.Errorf("RequeueAfter = %v, want none", res.RequeueAfter) + } + persistedAG := &sourcewatcherv1beta1.ArtifactGenerator{} + if err := c.Get(context.Background(), client.ObjectKeyFromObject(ag), persistedAG); err != nil { + t.Fatalf("Get AG: %v", err) + } + if _, ok := persistedAG.Annotations[annotationRecoveryAttempts]; ok { + t.Errorf("recovery tracking not cleared: %v", persistedAG.Annotations) + } + if got := persistedAG.Annotations[annotationFluxRequestedAt]; got != forcedAt { + t.Errorf("requestedAt = %q, want %q (no second rebuild)", got, forcedAt) + } +} + +// TestUpdateStatus_VerificationForceFailure_LeavesGenerationUnverified pins +// the ordering the verification relies on: a generation is marked verified +// only after the rebuild was forced, so a failed force is retried instead of +// being recorded as done. +func TestUpdateStatus_VerificationForceFailure_LeavesGenerationUnverified(t *testing.T) { + ps, ag := builtAG(2, metav1.ConditionTrue, 2, nil) + baseClient := fake.NewClientBuilder().WithScheme(testScheme(t)).WithStatusSubresource(ps, ag).WithObjects(ps, ag).Build() + failing := interceptor.NewClient(baseClient, interceptor.Funcs{ + SubResourcePatch: func(_ context.Context, _ client.Client, _ string, _ client.Object, _ client.Patch, _ ...client.SubResourcePatchOption) error { + return errors.New("simulated status patch failure") + }, + }) + r := &PackageSourceReconciler{Client: failing, Scheme: testScheme(t)} + + if _, err := r.updateStatus(context.Background(), ps, referenceTime); err == nil { + t.Fatal("updateStatus succeeded, want error from the forced rebuild") + } + persistedAG := &sourcewatcherv1beta1.ArtifactGenerator{} + if err := baseClient.Get(context.Background(), client.ObjectKeyFromObject(ag), persistedAG); err != nil { + t.Fatalf("Get AG: %v", err) + } + if _, ok := persistedAG.Annotations[annotationVerifiedGeneration]; ok { + t.Errorf("generation marked verified although the rebuild was never forced: %v", persistedAG.Annotations) + } + persistedPS := &cozyv1alpha1.PackageSource{} + if err := baseClient.Get(context.Background(), client.ObjectKeyFromObject(ps), persistedPS); err != nil { + t.Fatalf("Get PS: %v", err) + } + if psReady := meta.FindStatusCondition(persistedPS.Status.Conditions, "Ready"); psReady != nil { + t.Errorf("PS Ready = %+v, want unset: the unverified Ready=True must not be copied through", psReady) + } +} + +// TestUpdateStatus_VerificationIgnoresStaleRecoveryCounter pins that the +// verification rebuild starts its own attempt budget: clearing a counter left +// by an earlier stall is best-effort, and inheriting it could leave the +// verification a single backoff window before SourceWatcherStalled. +func TestUpdateStatus_VerificationIgnoresStaleRecoveryCounter(t *testing.T) { + ps, ag := builtAG(2, metav1.ConditionTrue, 2, map[string]string{ + annotationRecoveryAttempts: "4", + annotationLastRecoveryAt: referenceTime.Add(-time.Hour).UTC().Format(time.RFC3339Nano), + }) + baseClient := fake.NewClientBuilder().WithScheme(testScheme(t)).WithStatusSubresource(ps, ag).WithObjects(ps, ag).Build() + patches := 0 + failing := interceptor.NewClient(baseClient, interceptor.Funcs{ + Patch: func(ctx context.Context, c client.WithWatch, obj client.Object, patch client.Patch, opts ...client.PatchOption) error { + patches++ + if patches == 1 { + return errors.New("simulated failure clearing recovery tracking") + } + return c.Patch(ctx, obj, patch, opts...) + }, + }) + r := &PackageSourceReconciler{Client: failing, Scheme: testScheme(t)} + + res, err := r.updateStatus(context.Background(), ps, referenceTime) + if err != nil { + t.Fatalf("updateStatus: %v", err) + } + if res.RequeueAfter != backoffFor(1) { + t.Errorf("RequeueAfter = %v, want %v", res.RequeueAfter, backoffFor(1)) + } + persistedAG := &sourcewatcherv1beta1.ArtifactGenerator{} + if err := baseClient.Get(context.Background(), client.ObjectKeyFromObject(ag), persistedAG); err != nil { + t.Fatalf("Get AG: %v", err) + } + if got := persistedAG.Annotations[annotationRecoveryAttempts]; got != "1" { + t.Errorf("recovery attempts = %q, want \"1\"", got) + } +} + +// TestUpdateStatus_VerificationMarkFailure_RebuildsAgain covers the other +// half of that ordering: when the rebuild was forced but recording the +// generation failed, the next Ready=True forces the rebuild again. +func TestUpdateStatus_VerificationMarkFailure_RebuildsAgain(t *testing.T) { + ps, ag := builtAG(2, metav1.ConditionTrue, 2, nil) + baseClient := fake.NewClientBuilder().WithScheme(testScheme(t)).WithStatusSubresource(ps, ag).WithObjects(ps, ag).Build() + failMark := true + failing := interceptor.NewClient(baseClient, interceptor.Funcs{ + Patch: func(ctx context.Context, c client.WithWatch, obj client.Object, patch client.Patch, opts ...client.PatchOption) error { + if _, marking := obj.GetAnnotations()[annotationVerifiedGeneration]; marking && failMark { + return errors.New("simulated metadata patch failure") + } + return c.Patch(ctx, obj, patch, opts...) + }, + }) + r := &PackageSourceReconciler{Client: failing, Scheme: testScheme(t)} + + if _, err := r.updateStatus(context.Background(), ps, referenceTime); err == nil { + t.Fatal("updateStatus succeeded, want error from recording the verified generation") + } + persistedAG := &sourcewatcherv1beta1.ArtifactGenerator{} + if err := baseClient.Get(context.Background(), client.ObjectKeyFromObject(ag), persistedAG); err != nil { + t.Fatalf("Get AG: %v", err) + } + if _, ok := persistedAG.Annotations[annotationVerifiedGeneration]; ok { + t.Fatalf("verified generation persisted despite the failed patch: %v", persistedAG.Annotations) + } + firstForce := persistedAG.Annotations[annotationFluxRequestedAt] + if firstForce == "" { + t.Fatalf("rebuild was not forced before the mark: %v", persistedAG.Annotations) + } + + // source-watcher finishes the forced rebuild and reports Ready=True again. + meta.SetStatusCondition(&persistedAG.Status.Conditions, metav1.Condition{ + Type: "Ready", Status: metav1.ConditionTrue, Reason: "Succeeded", ObservedGeneration: 2, + }) + if err := baseClient.Status().Update(context.Background(), persistedAG); err != nil { + t.Fatalf("Update AG status: %v", err) + } + failMark = false + if _, err := r.updateStatus(context.Background(), ps, referenceTime.Add(time.Minute)); err != nil { + t.Fatalf("second updateStatus: %v", err) + } + if err := baseClient.Get(context.Background(), client.ObjectKeyFromObject(ag), persistedAG); err != nil { + t.Fatalf("Get AG: %v", err) + } + if got := persistedAG.Annotations[annotationFluxRequestedAt]; got == firstForce { + t.Errorf("requestedAt = %q unchanged, want a second forced rebuild", got) + } + if got := persistedAG.Annotations[annotationVerifiedGeneration]; got != "2" { + t.Errorf("verified generation = %q, want \"2\"", got) + } +} diff --git a/packages/apps/clickhouse/templates/backup-script.yaml b/packages/apps/clickhouse/templates/backup-script.yaml index d804008ff..1caff64f8 100644 --- a/packages/apps/clickhouse/templates/backup-script.yaml +++ b/packages/apps/clickhouse/templates/backup-script.yaml @@ -18,7 +18,7 @@ stringData: JOB_ID="job-$(uuidgen|cut -f1 -d-)" TABLE_LIST=$(clickhouse-client --host "$CLICKHOUSE_HOST" -q 'SHOW TABLES;' | grep -v '^.inner.' || true) - echo DB_LIST=$(echo "$TABLE_LIST" | shuf) # shuffle list + DB_LIST=$(echo "$TABLE_LIST" | shuf) # shuffle list echo "Job ID: $JOB_ID" echo "Target repo: $REPO_PREFIX" echo "Cleanup strategy: $CLEANUP_STRATEGY" diff --git a/packages/apps/clickhouse/templates/clickhouse.yaml b/packages/apps/clickhouse/templates/clickhouse.yaml index df5519f30..f5421d704 100644 --- a/packages/apps/clickhouse/templates/clickhouse.yaml +++ b/packages/apps/clickhouse/templates/clickhouse.yaml @@ -96,7 +96,6 @@ spec: {{- $replicas := int .Values.clickhouseKeeper.replicas }} {{- $keeper := include "clickhouse.keeperName" $ }} {{- $namespace := .Release.Namespace }} - {{- $clusterDomain := .Values.clusterDomain }} {{- range $i := until $replicas }} - host: "chk-{{ $keeper }}-cluster1-0-{{ $i }}.{{ $namespace }}.svc.{{ $clusterDomain }}" port: 2181 diff --git a/packages/apps/clickhouse/tests/backup_test.yaml b/packages/apps/clickhouse/tests/backup_test.yaml index 03680c39c..0098dea19 100644 --- a/packages/apps/clickhouse/tests/backup_test.yaml +++ b/packages/apps/clickhouse/tests/backup_test.yaml @@ -15,6 +15,7 @@ templates: - templates/clickhouse.yaml - templates/backup-strategy-secret.yaml - templates/backup-secret.yaml + - templates/backup-script.yaml release: name: ch-test @@ -150,3 +151,24 @@ tests: asserts: - failedTemplate: errorMessage: "clickhouse: backup.s3PathOverride is incompatible with backup.useSystemBucket=true. The platform flow scopes the S3 path to / automatically; clear s3PathOverride or disable useSystemBucket. To restore from another release's prefix, use a backups.cozystack.io/RestoreJob with spec.targetApplicationRef." + + # Regression for #3758. The legacy per-instance backup script's retention + # cleanup loop iterates $DB_LIST, which must be assigned from the table list. + # A prior `echo DB_LIST=$(...)` typo left DB_LIST unset, so the cleanup loop + # ran zero iterations and `restic forget`/`restic prune` never executed — + # snapshots accumulated in object storage forever while the Job still + # reported success. Assert the assignment is present and the echo typo is gone. + - it: "legacy backup script: DB_LIST is assigned so retention cleanup runs (#3758)" + template: templates/backup-script.yaml + set: + backup: + enabled: true + schedule: "0 3 * * *" + useSystemBucket: false + asserts: + - matchRegex: + path: stringData["backup.sh"] + pattern: '(?m)^\s*DB_LIST=\$\(echo "\$TABLE_LIST"' + - notMatchRegex: + path: stringData["backup.sh"] + pattern: 'echo DB_LIST=' diff --git a/packages/apps/clickhouse/tests/keeper_name_test.yaml b/packages/apps/clickhouse/tests/keeper_name_test.yaml index 0194ae9c4..13c135202 100644 --- a/packages/apps/clickhouse/tests/keeper_name_test.yaml +++ b/packages/apps/clickhouse/tests/keeper_name_test.yaml @@ -3,7 +3,6 @@ suite: keeper name budget set: _cluster: cluster-domain: cluster.local - clusterDomain: cluster.local tests: - it: "keeps -keeper for a short release name" diff --git a/packages/apps/harbor/templates/harbor.yaml b/packages/apps/harbor/templates/harbor.yaml index 8cb8b38c0..3bb00f0ce 100644 --- a/packages/apps/harbor/templates/harbor.yaml +++ b/packages/apps/harbor/templates/harbor.yaml @@ -89,10 +89,38 @@ spec: namespace: cozy-system interval: 5m timeout: 15m + {{- /* This nested release owns the whole harbor workload: the Deployments, + the inline RedisFailover and its volume. Flux's default install + strategy remediates a failed install by uninstalling, and install + remediation is an uninstall in every case Flux offers, so a first + install that goes over budget is torn down between attempts and the + next one re-provisions the redis PVC and re-runs the master election + from zero. It goes over budget on a busy runner: harbor-core blocks on + redis, and the nginx Deployment reaches the default + progressDeadlineSeconds of 600s, which Flux reads as a stalled + resource and fails the install early. RetryOnFailure keeps the + manifests applied and retries the failed release, so the convergence + already under way continues instead of restarting. Both actions carry + the strategy because the controller performs that retry as an upgrade + and the retry's own failure would otherwise fall through to upgrade + remediation. The cost is that a genuine upgrade failure retries rather + than rolls back, which gives up no stable safety net: with retries: -1 + and the default strategy, upgrade remediation already rolled back and + retried without end. The remediation blocks stay because an absent + release consults install and an out-of-sync one consults upgrade, both + by retry count rather than by strategy. The parent release that + renders this one already carries the same strategy, stamped by the + apiserver that builds it from the Application. */}} install: + strategy: + name: RetryOnFailure + retryInterval: 30s remediation: retries: -1 upgrade: + strategy: + name: RetryOnFailure + retryInterval: 30s remediation: retries: -1 valuesFrom: diff --git a/packages/apps/harbor/tests/install_retry_test.yaml b/packages/apps/harbor/tests/install_retry_test.yaml new file mode 100644 index 000000000..703e626bd --- /dev/null +++ b/packages/apps/harbor/tests/install_retry_test.yaml @@ -0,0 +1,76 @@ +suite: nested system HelmRelease install retry strategy + +release: + name: harbor + namespace: tenant-test + +# helm-unittest renders every template in the chart, so the platform-injected +# globals consumed by the ingress/httproute/bucket templates must be supplied +# even though only templates/harbor.yaml is asserted on. +set: + _namespace: + host: example.org + ingress: nginx + gateway: "" + seaweedfs: seaweedfs + _cluster: + solver: http01 + +# templates/harbor.yaml renders a Secret, this HelmRelease and three +# WorkloadMonitors, so the release is selected by kind rather than by document +# index: a template gaining a document ahead of it moves the index onto another +# object, and these asserts would then red for a reason that has nothing to do +# with the strategy they exist to pin. The selector names what it wants, so it +# keeps pointing at the release wherever the release ends up, and a selector +# that matches nothing fails loudly rather than quietly matching the wrong +# document. +tests: + # The workload lives in this nested release: the harbor Deployments, the + # inline RedisFailover and its PVC. Install remediation is an uninstall in + # every case Flux offers, so under the default strategy an install that goes + # over budget deletes all of it, and the next attempt re-provisions the redis + # volume and re-runs the master election from zero. + - it: retries a failed install instead of uninstalling the harbor workload + template: templates/harbor.yaml + documentSelector: + path: kind + value: HelmRelease + asserts: + - equal: + path: spec.install.strategy.name + value: RetryOnFailure + - equal: + path: spec.install.strategy.retryInterval + value: 30s + + # The controller performs the retry of a failed install as an upgrade, so + # without a strategy here that retry's own failure falls through to upgrade + # remediation instead of retrying again. + - it: carries the strategy on the upgrade action the retry runs as + template: templates/harbor.yaml + documentSelector: + path: kind + value: HelmRelease + asserts: + - equal: + path: spec.upgrade.strategy.name + value: RetryOnFailure + - equal: + path: spec.upgrade.strategy.retryInterval + value: 30s + + # The strategy governs a failed release. An absent release and an out-of-sync + # one take different branches, which consult the retry count instead and stop + # acting once it is exhausted. + - it: keeps unlimited retries for the branches the strategy does not reach + template: templates/harbor.yaml + documentSelector: + path: kind + value: HelmRelease + asserts: + - equal: + path: spec.install.remediation.retries + value: -1 + - equal: + path: spec.upgrade.remediation.retries + value: -1 diff --git a/packages/apps/http-cache/templates/haproxy/configmap.yaml b/packages/apps/http-cache/templates/haproxy/configmap.yaml index 4012649de..4d0e3dbe9 100644 --- a/packages/apps/http-cache/templates/haproxy/configmap.yaml +++ b/packages/apps/http-cache/templates/haproxy/configmap.yaml @@ -63,9 +63,9 @@ data: # overwrite real IP header from anywhere else http-request set-header X-Forwarded-For %[src] if !from_cf - default_backend http + default_backend cache - backend http + backend cache mode http balance uri whole hash-type consistent diff --git a/packages/apps/kubernetes/images/kubevirt-cloud-provider/patches/vmi-informer.diff b/packages/apps/kubernetes/images/kubevirt-cloud-provider/patches/vmi-informer.diff new file mode 100644 index 000000000..e300bf458 --- /dev/null +++ b/packages/apps/kubernetes/images/kubevirt-cloud-provider/patches/vmi-informer.diff @@ -0,0 +1,429 @@ +diff --git a/pkg/controller/kubevirteps/kubevirteps_controller.go b/pkg/controller/kubevirteps/kubevirteps_controller.go +index 8af51fbe8..e8f1a4488 100644 +--- a/pkg/controller/kubevirteps/kubevirteps_controller.go ++++ b/pkg/controller/kubevirteps/kubevirteps_controller.go +@@ -12,12 +12,15 @@ import ( + apiequality "k8s.io/apimachinery/pkg/api/equality" + k8serrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ++ "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" ++ "k8s.io/apimachinery/pkg/labels" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/runtime/schema" + utilruntime "k8s.io/apimachinery/pkg/util/runtime" + "k8s.io/apimachinery/pkg/util/sets" + "k8s.io/apimachinery/pkg/util/wait" + "k8s.io/client-go/dynamic" ++ "k8s.io/client-go/dynamic/dynamicinformer" + "k8s.io/client-go/informers" + "k8s.io/client-go/kubernetes" + "k8s.io/client-go/tools/cache" +@@ -31,8 +34,19 @@ import ( + + const ( + ControllerName = controllerName("kubevirt_eps_controller") ++ ++ // A periodic resync re-reconciles every LoadBalancer Service even if an event was ++ // missed, so infra EndpointSlices cannot stay stale indefinitely. ++ defaultResyncPeriod = 5 * time.Minute ++ ++ // clusterNameLabel is set by CAPK on the VMIs backing a tenant cluster. It is used to ++ // avoid selecting VMIs that do not belong to this cluster when falling back to all VMIs. ++ clusterNameLabel = "cluster.x-k8s.io/cluster-name" + ) + ++var vmiGVR = kubevirtv1.VirtualMachineInstanceGroupVersionKind.GroupVersion(). ++ WithResource("virtualmachineinstances") ++ + type controllerName string + + func (c controllerName) dashed() string { +@@ -49,9 +63,10 @@ type Controller struct { + tenantFactory informers.SharedInformerFactory + tenantEPSTracker tenantEPSTracker + +- infraClient kubernetes.Interface +- infraDynamic dynamic.Interface +- infraFactory informers.SharedInformerFactory ++ infraClient kubernetes.Interface ++ infraDynamic dynamic.Interface ++ infraFactory informers.SharedInformerFactory ++ infraDynamicFactory dynamicinformer.DynamicSharedInformerFactory + + infraNamespace string + clusterName string +@@ -67,8 +82,11 @@ func NewKubevirtEPSController( + infraNamespace string, + clusterName string, + ) *Controller { +- tenantFactory := informers.NewSharedInformerFactory(tenantClient, 0) +- infraFactory := informers.NewSharedInformerFactoryWithOptions(infraClient, 0, informers.WithNamespace(infraNamespace)) ++ tenantFactory := informers.NewSharedInformerFactory(tenantClient, defaultResyncPeriod) ++ infraFactory := informers.NewSharedInformerFactoryWithOptions(infraClient, defaultResyncPeriod, ++ informers.WithNamespace(infraNamespace)) ++ infraDynamicFactory := dynamicinformer.NewFilteredDynamicSharedInformerFactory(infraDynamic, ++ defaultResyncPeriod, infraNamespace, nil) + queue := workqueue.NewRateLimitingQueue(workqueue.DefaultControllerRateLimiter()) + + return &Controller{ +@@ -78,6 +96,7 @@ func NewKubevirtEPSController( + infraClient: infraClient, + infraDynamic: infraDynamic, + infraFactory: infraFactory, ++ infraDynamicFactory: infraDynamicFactory, + infraNamespace: infraNamespace, + clusterName: clusterName, + queue: queue, +@@ -236,9 +255,84 @@ func (c *Controller) Init() error { + return err + } + ++ // The desired infra endpoints of a LoadBalancer Service are derived from the VMIs backing the ++ // tenant nodes, so a VMI appearing, disappearing or changing its address must trigger a ++ // reconciliation. Without this, EndpointSlices keep pointing at VMIs that no longer exist ++ // (for example after a MachineDeployment rollout or a cluster-autoscaler scale down) and the ++ // LoadBalancer blackholes the share of the traffic hashed onto those dead addresses. ++ _, err = c.infraDynamicFactory.ForResource(vmiGVR).Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{ ++ AddFunc: func(obj interface{}) { ++ c.enqueueLoadBalancerServices(fmt.Sprintf("VMI added: %s", vmiKey(obj))) ++ }, ++ UpdateFunc: func(oldObj, newObj interface{}) { ++ if vmiEndpointFingerprint(oldObj) == vmiEndpointFingerprint(newObj) { ++ return ++ } ++ c.enqueueLoadBalancerServices(fmt.Sprintf("VMI updated: %s", vmiKey(newObj))) ++ }, ++ DeleteFunc: func(obj interface{}) { ++ if tombstone, ok := obj.(cache.DeletedFinalStateUnknown); ok { ++ obj = tombstone.Obj ++ } ++ c.enqueueLoadBalancerServices(fmt.Sprintf("VMI deleted: %s", vmiKey(obj))) ++ }, ++ }) ++ if err != nil { ++ return err ++ } ++ + return nil + } + ++func vmiKey(obj interface{}) string { ++ u, ok := obj.(*unstructured.Unstructured) ++ if !ok { ++ return "" ++ } ++ return u.GetNamespace() + "/" + u.GetName() ++} ++ ++// vmiEndpointFingerprint returns the parts of a VMI that influence the endpoints derived from it: ++// the cluster it belongs to, the infra node it runs on, its phase and the address of its "default" ++// interface. Any other update, and a running VMI sees many, cannot change an EndpointSlice. ++func vmiEndpointFingerprint(obj interface{}) string { ++ u, ok := obj.(*unstructured.Unstructured) ++ if !ok { ++ return "" ++ } ++ vmi := &kubevirtv1.VirtualMachineInstance{} ++ if err := runtime.DefaultUnstructuredConverter.FromUnstructured(u.Object, vmi); err != nil { ++ // Fall back to the resource version so an unparsable update is never silently dropped. ++ return u.GetResourceVersion() ++ } ++ ip := "" ++ for _, i := range vmi.Status.Interfaces { ++ if i.Name == "default" { ++ ip = i.IP ++ break ++ } ++ } ++ return fmt.Sprintf("%s|%s|%s|%s", u.GetLabels()[clusterNameLabel], vmi.Status.NodeName, vmi.Status.Phase, ip) ++} ++ ++// enqueueLoadBalancerServices requeues the LoadBalancer Services of this cluster only: the infra ++// namespace can hold the Services of other tenant clusters, which reconcile would skip anyway. ++func (c *Controller) enqueueLoadBalancerServices(reason string) { ++ svcs, err := c.infraFactory.Core().V1().Services().Lister().Services(c.infraNamespace). ++ List(labels.SelectorFromSet(labels.Set{kubevirt.TenantClusterNameLabelKey: c.clusterName})) ++ if err != nil { ++ klog.Errorf("Failed to list Services in namespace %s: %v", c.infraNamespace, err) ++ return ++ } ++ for _, svc := range svcs { ++ if svc.Spec.Type != v1.ServiceTypeLoadBalancer { ++ continue ++ } ++ klog.Infof("%s, requeuing Service: %v/%v", reason, svc.Namespace, svc.Name) ++ c.queue.Add(newRequest(UpdateReq, svc, nil)) ++ } ++} ++ + // getInfraServiceForEPS returns the Service in the infra cluster associated with the given EndpointSlice. + // It does this by reading the "kubernetes.io/service-name" label from the EndpointSlice, which should correspond + // to the Service name. If not found or if the Service doesn't exist, it returns nil. +@@ -276,10 +370,12 @@ func (c *Controller) Run(numWorkers int, stopCh <-chan struct{}, controllerManag + + c.tenantFactory.Start(stopCh) + c.infraFactory.Start(stopCh) ++ c.infraDynamicFactory.Start(stopCh) + + if !cache.WaitForNamedCacheSync(ControllerName.String(), stopCh, + c.infraFactory.Core().V1().Services().Informer().HasSynced, +- c.tenantFactory.Discovery().V1().EndpointSlices().Informer().HasSynced) { ++ c.tenantFactory.Discovery().V1().EndpointSlices().Informer().HasSynced, ++ c.infraDynamicFactory.ForResource(vmiGVR).Informer().HasSynced) { + return + } + +@@ -868,17 +964,45 @@ func (c *Controller) getDesiredEndpoints(service *v1.Service, tenantSlices []*di + func (c *Controller) getAllVMIEndpoints() []*discovery.Endpoint { + var endpoints []*discovery.Endpoint + +- // List all VMIs in the infra namespace +- vmiList, err := c.infraDynamic. +- Resource(kubevirtv1.VirtualMachineInstanceGroupVersionKind.GroupVersion().WithResource("virtualmachineinstances")). +- Namespace(c.infraNamespace). ++ // List every VMI of the infra namespace, then keep only the ones of this cluster. An infra ++ // namespace can hold more than one tenant cluster, as well as plain VirtualMachines, and those ++ // VMIs do not serve this Service's NodePort: selecting them would add endpoints that blackhole ++ // the traffic, or route it to another tenant. ++ vmiList, err := c.infraDynamic.Resource(vmiGVR).Namespace(c.infraNamespace). + List(context.TODO(), metav1.ListOptions{}) + if err != nil { + klog.Errorf("Failed to list VMIs in namespace %q: %v", c.infraNamespace, err) + return endpoints + } + +- for _, obj := range vmiList.Items { ++ items := vmiList.Items ++ if c.clusterName != "" { ++ mine := make([]unstructured.Unstructured, 0, len(items)) ++ anyLabelled := false ++ for i := range items { ++ name, found := items[i].GetLabels()[clusterNameLabel] ++ if !found { ++ continue ++ } ++ anyLabelled = true ++ if name == c.clusterName { ++ mine = append(mine, items[i]) ++ } ++ } ++ // Widen to every VMI only when NONE of them carries the label: the VMIs are then not ++ // managed by CAPK (or by an older version of it) and there is no way to tell the clusters ++ // apart, so returning nothing would take the LoadBalancer down. As soon as some VMIs are ++ // labelled, an empty selection is a legitimate answer -- this cluster currently has no ++ // node -- and must not be widened to the VMIs of another cluster. ++ if anyLabelled { ++ items = mine ++ } else { ++ klog.Warningf("No VMI carries %q in namespace %s, selecting every VMI of the namespace", ++ clusterNameLabel, c.infraNamespace) ++ } ++ } ++ ++ for _, obj := range items { + vmi := &kubevirtv1.VirtualMachineInstance{} + err = runtime.DefaultUnstructuredConverter.FromUnstructured(obj.Object, vmi) + if err != nil { +@@ -916,7 +1040,8 @@ func (c *Controller) getAllVMIEndpoints() []*discovery.Endpoint { + } + } + +- klog.Infof("Fallback: created %d endpoints from all VMIs in namespace %s", len(endpoints), c.infraNamespace) ++ klog.Infof("Fallback: created %d endpoints from the VMIs of cluster %q in namespace %s", ++ len(endpoints), c.clusterName, c.infraNamespace) + return endpoints + } + +diff --git a/pkg/controller/kubevirteps/kubevirteps_controller_test.go b/pkg/controller/kubevirteps/kubevirteps_controller_test.go +index 17608fa10..8fa76678b 100644 +--- a/pkg/controller/kubevirteps/kubevirteps_controller_test.go ++++ b/pkg/controller/kubevirteps/kubevirteps_controller_test.go +@@ -965,3 +965,188 @@ var _ = g.Describe("getDesiredEndpoints", func() { + Expect(endpoints).To(HaveLen(0), "Expected no endpoints due to missing NodeName or IP") + }) + }) ++ ++func createUnstructuredVMIForCluster(name, nodeName, ip, clusterName string) *unstructured.Unstructured { ++ vmi := createUnstructuredVMINode(name, nodeName, ip) ++ if clusterName != "" { ++ vmi.SetLabels(map[string]string{clusterNameLabel: clusterName}) ++ } ++ return vmi ++} ++ ++var _ = g.Describe("KubevirtEPSController VMI tracking", func() { ++ ++ createVMI := func(t *testKubevirtEPSController, vmi *unstructured.Unstructured) { ++ _, err := t.infraDynamic.Resource(vmiGVR).Namespace(infraNamespace). ++ Create(context.TODO(), vmi, metav1.CreateOptions{}) ++ Expect(err).To(BeNil()) ++ } ++ ++ g.It("Should only select the VMIs of its own cluster when falling back to all VMIs", func() { ++ t := setupTestKubevirtEPSController() ++ // "test-cluster" is the cluster name the controller is created with. ++ createVMI(t, createUnstructuredVMIForCluster("mine-1", "infra-1", "10.0.0.1", "test-cluster")) ++ createVMI(t, createUnstructuredVMIForCluster("mine-2", "infra-2", "10.0.0.2", "test-cluster")) ++ createVMI(t, createUnstructuredVMIForCluster("other", "infra-3", "10.0.0.3", "another-cluster")) ++ ++ endpoints := t.controller.getAllVMIEndpoints() ++ ++ Expect(endpoints).To(HaveLen(2), "Only the VMIs of test-cluster should be selected") ++ var addresses []string ++ for _, e := range endpoints { ++ addresses = append(addresses, e.Addresses[0]) ++ } ++ Expect(addresses).To(ConsistOf("10.0.0.1", "10.0.0.2")) ++ Expect(addresses).ToNot(ContainElement("10.0.0.3"), "A VMI of another cluster must never be an endpoint") ++ }) ++ ++ g.It("Should keep selecting every VMI when none carries the cluster label", func() { ++ t := setupTestKubevirtEPSController() ++ createVMI(t, createUnstructuredVMIForCluster("unlabelled-1", "infra-1", "10.0.0.1", "")) ++ createVMI(t, createUnstructuredVMIForCluster("unlabelled-2", "infra-2", "10.0.0.2", "")) ++ ++ endpoints := t.controller.getAllVMIEndpoints() ++ ++ Expect(endpoints).To(HaveLen(2), "Unlabelled VMIs must still be selected, so the LB does not lose every endpoint") ++ }) ++ ++ g.It("Should return no endpoint when only another cluster's VMIs are present", func() { ++ t := setupTestKubevirtEPSController() ++ // The controller's cluster is "test-cluster" and has no VMI right now (scaled to zero, or ++ // every VMI being replaced by a rollout), while another tenant cluster of the same infra ++ // namespace does have some. Widening to every VMI here would publish the other cluster's ++ // addresses as this Service's endpoints. ++ createVMI(t, createUnstructuredVMIForCluster("other-1", "infra-1", "10.0.0.1", "another-cluster")) ++ createVMI(t, createUnstructuredVMIForCluster("other-2", "infra-2", "10.0.0.2", "another-cluster")) ++ ++ endpoints := t.controller.getAllVMIEndpoints() ++ ++ Expect(endpoints).To(BeEmpty(), ++ "An empty selection is legitimate and must not be widened to another cluster's VMIs") ++ }) ++ ++ g.It("Should ignore the unlabelled VMIs when some VMIs carry the cluster label", func() { ++ t := setupTestKubevirtEPSController() ++ createVMI(t, createUnstructuredVMIForCluster("mine", "infra-1", "10.0.0.1", "test-cluster")) ++ // A standalone VirtualMachine of the same namespace, not part of any tenant cluster. ++ createVMI(t, createUnstructuredVMIForCluster("standalone", "infra-2", "10.0.0.2", "")) ++ ++ endpoints := t.controller.getAllVMIEndpoints() ++ ++ Expect(endpoints).To(HaveLen(1)) ++ Expect(endpoints[0].Addresses).To(ConsistOf("10.0.0.1")) ++ }) ++ ++ // startTracking starts the informers the VMI event handlers rely on, with a LoadBalancer Service ++ // of this cluster and one of another cluster, and returns once the initial events, want of them, ++ // have been drained from the queue. ++ startTracking := func(t *testKubevirtEPSController, stop chan struct{}, want int) { ++ for _, svc := range []*v1.Service{ ++ createInfraServiceLB("lb-svc", "tenant-svc", "test-cluster", ++ v1.ServicePort{Name: "http", Port: 80, Protocol: v1.ProtocolTCP, TargetPort: intstr.FromInt32(30000)}, ++ v1.ServiceExternalTrafficPolicyCluster), ++ createInfraServiceLB("other-lb-svc", "tenant-svc", "another-cluster", ++ v1.ServicePort{Name: "http", Port: 80, Protocol: v1.ProtocolTCP, TargetPort: intstr.FromInt32(30001)}, ++ v1.ServiceExternalTrafficPolicyCluster), ++ } { ++ _, err := t.infraClient.CoreV1().Services(infraNamespace).Create(context.TODO(), svc, metav1.CreateOptions{}) ++ Expect(err).To(BeNil()) ++ } ++ ++ // Services first, so that the add event of a VMI already present finds them in the lister. ++ t.controller.infraFactory.Start(stop) ++ Expect(cache.WaitForCacheSync(stop, ++ t.controller.infraFactory.Core().V1().Services().Informer().HasSynced)).To(BeTrue()) ++ t.controller.infraDynamicFactory.Start(stop) ++ Expect(cache.WaitForCacheSync(stop, ++ t.controller.infraDynamicFactory.ForResource(vmiGVR).Informer().HasSynced)).To(BeTrue()) ++ ++ Eventually(func() int { return t.controller.queue.Len() }, "10s", "20ms").Should(Equal(want)) ++ drainQueue(t) ++ } ++ ++ updateVMI := func(t *testKubevirtEPSController, name string, mutate func(*unstructured.Unstructured)) { ++ vmi, err := t.infraDynamic.Resource(vmiGVR).Namespace(infraNamespace). ++ Get(context.TODO(), name, metav1.GetOptions{}) ++ Expect(err).To(BeNil()) ++ mutate(vmi) ++ _, err = t.infraDynamic.Resource(vmiGVR).Namespace(infraNamespace). ++ Update(context.TODO(), vmi, metav1.UpdateOptions{}) ++ Expect(err).To(BeNil()) ++ } ++ ++ expectRequeueOf := func(t *testKubevirtEPSController, why string) { ++ Eventually(func() int { return t.controller.queue.Len() }, "10s", "20ms").Should(Equal(1), why) ++ item, _ := t.controller.queue.Get() ++ t.controller.queue.Done(item) ++ Expect(item.(*Request).Obj.(*v1.Service).Name).To(Equal("lb-svc"), ++ "Only the Service of this cluster should be requeued") ++ Consistently(func() int { return t.controller.queue.Len() }, "200ms", "20ms").Should(BeZero()) ++ } ++ ++ expectNoRequeue := func(t *testKubevirtEPSController, why string) { ++ Consistently(func() int { return t.controller.queue.Len() }, "500ms", "20ms").Should(BeZero(), why) ++ } ++ ++ g.It("Should requeue the LoadBalancer Services when a VMI appears or disappears", func() { ++ t := setupTestKubevirtEPSController() ++ stop := make(chan struct{}) ++ defer close(stop) ++ startTracking(t, stop, 2) ++ ++ // A new VMI must trigger a reconciliation, otherwise a node added by a scale up or a ++ // rollout never becomes an endpoint. ++ createVMI(t, createUnstructuredVMIForCluster("vmi-1", "infra-1", "10.0.0.1", "test-cluster")) ++ expectRequeueOf(t, "Creating a VMI should requeue the LoadBalancer Service") ++ ++ // A deleted VMI must trigger a reconciliation as well, otherwise its address stays in the ++ // EndpointSlice and the LoadBalancer blackholes the traffic hashed onto it. ++ err := t.infraDynamic.Resource(vmiGVR).Namespace(infraNamespace). ++ Delete(context.TODO(), "vmi-1", metav1.DeleteOptions{}) ++ Expect(err).To(BeNil()) ++ expectRequeueOf(t, "Deleting a VMI should requeue the LoadBalancer Service") ++ }) ++ ++ g.It("Should requeue the LoadBalancer Services only on the VMI updates that can change an endpoint", func() { ++ t := setupTestKubevirtEPSController() ++ stop := make(chan struct{}) ++ defer close(stop) ++ createVMI(t, createUnstructuredVMIForCluster("vmi-1", "infra-1", "10.0.0.1", "test-cluster")) ++ // Both Service adds, plus the add of the VMI already present. ++ startTracking(t, stop, 3) ++ ++ updateVMI(t, "vmi-1", func(u *unstructured.Unstructured) { ++ u.SetAnnotations(map[string]string{"unrelated": "change"}) ++ }) ++ expectNoRequeue(t, "An update that touches no endpoint field must not requeue") ++ ++ updateVMI(t, "vmi-1", func(u *unstructured.Unstructured) { ++ Expect(unstructured.SetNestedField(u.Object, "Failed", "status", "phase")).To(Succeed()) ++ }) ++ expectRequeueOf(t, "A phase change should requeue the LoadBalancer Service") ++ ++ updateVMI(t, "vmi-1", func(u *unstructured.Unstructured) { ++ Expect(unstructured.SetNestedField(u.Object, "infra-2", "status", "nodeName")).To(Succeed()) ++ }) ++ expectRequeueOf(t, "A node change should requeue the LoadBalancer Service") ++ ++ updateVMI(t, "vmi-1", func(u *unstructured.Unstructured) { ++ Expect(unstructured.SetNestedSlice(u.Object, []interface{}{ ++ map[string]interface{}{"name": "default", "ipAddress": "10.0.0.9"}, ++ }, "status", "interfaces")).To(Succeed()) ++ }) ++ expectRequeueOf(t, "An address change should requeue the LoadBalancer Service") ++ ++ updateVMI(t, "vmi-1", func(u *unstructured.Unstructured) { ++ u.SetLabels(map[string]string{clusterNameLabel: "another-cluster"}) ++ }) ++ expectRequeueOf(t, "Moving a VMI to another cluster should requeue the LoadBalancer Service") ++ }) ++}) ++ ++func drainQueue(t *testKubevirtEPSController) { ++ for t.controller.queue.Len() > 0 { ++ item, _ := t.controller.queue.Get() ++ t.controller.queue.Done(item) ++ } ++} diff --git a/packages/apps/kubernetes/images/kubevirt-csi-driver/main.go b/packages/apps/kubernetes/images/kubevirt-csi-driver/main.go index 1b48bfb42..377ccf9c0 100644 --- a/packages/apps/kubernetes/images/kubevirt-csi-driver/main.go +++ b/packages/apps/kubernetes/images/kubevirt-csi-driver/main.go @@ -37,6 +37,17 @@ var ( runNodeService = flag.Bool("run-node-service", true, "Specifies rather or not to run the node service, the default is true") runControllerService = flag.Bool("run-controller-service", true, "Specifies rather or not to run the controller service, the default is true") + + kubeAPIQPS = flag.Float64("kube-api-qps", defaultKubeAPIQPS, "QPS limit for the infra- and tenant-cluster Kubernetes API clients. client-go defaults to 5, which starves the once-per-second infra PVC-bound poll in the NFS ControllerPublishVolume path under a burst of concurrent attaches.") + kubeAPIBurst = flag.Int("kube-api-burst", defaultKubeAPIBurst, "Burst limit for the infra- and tenant-cluster Kubernetes API clients (client-go default is 10).") +) + +// Chosen well above the client-go defaults (5 QPS / 10 burst) so a scale-out +// burst of PVC attaches does not starve the bound poll, while staying well +// within the infra API server's capacity. +const ( + defaultKubeAPIQPS = 100 + defaultKubeAPIBurst = 200 ) func init() { @@ -65,6 +76,9 @@ func handle() { if volumePrefix == nil || *volumePrefix == "" { klog.Fatal("volume-prefix must be set") } + if err := validateRateLimitFlags(*kubeAPIQPS, *kubeAPIBurst); err != nil { + klog.Fatal(err) + } inClusterConfig, err := rest.InClusterConfig() if err != nil { @@ -89,6 +103,9 @@ func handle() { infraRestConfig = inClusterConfig } + applyKubeAPIRateLimits(tenantRestConfig, *kubeAPIQPS, *kubeAPIBurst) + applyKubeAPIRateLimits(infraRestConfig, *kubeAPIQPS, *kubeAPIBurst) + tenantClientSet, err := kubernetes.NewForConfig(tenantRestConfig) if err != nil { klog.Fatalf("Failed to build tenant client set: %v", err) @@ -184,6 +201,32 @@ func handle() { s.Wait() } +// validateRateLimitFlags rejects non-positive limits. client-go treats QPS == 0 +// as "use the 5 QPS default" and QPS < 0 as "no rate limiting at all", so an +// operator passing 0 expecting "unlimited" would silently get the starving +// default this fix exists to avoid; refuse both rather than surprise them. +func validateRateLimitFlags(qps float64, burst int) error { + if qps <= 0 { + return fmt.Errorf("kube-api-qps must be positive, got %v", qps) + } + if burst <= 0 { + return fmt.Errorf("kube-api-burst must be positive, got %d", burst) + } + return nil +} + +// applyKubeAPIRateLimits raises a rest.Config's client-side rate limiter above +// the client-go default of 5 QPS / 10 burst. The NFS-volume ControllerPublishVolume +// path polls the infra PersistentVolumeClaim once per second for up to two minutes; +// when a tenant scales out and several volumes attach at once, the default limiter +// starves and the poll fails with "client rate limiter Wait returned an error: +// context deadline exceeded", which the tenant kubelet surfaces as +// FailedAttachVolume. +func applyKubeAPIRateLimits(cfg *rest.Config, qps float64, burst int) { + cfg.QPS = float32(qps) + cfg.Burst = burst +} + func configureStorageClassEnforcement(infraStorageClassEnforcement string) util.StorageClassEnforcement { var storageClassEnforcement util.StorageClassEnforcement diff --git a/packages/apps/kubernetes/images/kubevirt-csi-driver/main_test.go b/packages/apps/kubernetes/images/kubevirt-csi-driver/main_test.go new file mode 100644 index 000000000..abbccd9e2 --- /dev/null +++ b/packages/apps/kubernetes/images/kubevirt-csi-driver/main_test.go @@ -0,0 +1,109 @@ +package main + +import ( + "context" + "testing" + "time" + + "k8s.io/client-go/rest" + "k8s.io/client-go/util/flowcontrol" +) + +// client-go applies these limits to a rest.Config that leaves QPS/Burst unset. +// They are what the driver ran with before this fix. +const ( + clientGoDefaultQPS float32 = 5 + clientGoDefaultBurst int = 10 +) + +// applyKubeAPIRateLimits must raise the client both above the client-go default, +// otherwise the ControllerPublishVolume PVC-bound poll keeps starving under a +// burst of concurrent attaches. +func TestApplyKubeAPIRateLimitsRaisesAboveClientGoDefault(t *testing.T) { + cfg := &rest.Config{} + applyKubeAPIRateLimits(cfg, defaultKubeAPIQPS, defaultKubeAPIBurst) + + if cfg.QPS <= clientGoDefaultQPS { + t.Errorf("QPS = %v, want > %v (client-go default)", cfg.QPS, clientGoDefaultQPS) + } + if cfg.Burst <= clientGoDefaultBurst { + t.Errorf("Burst = %d, want > %d (client-go default)", cfg.Burst, clientGoDefaultBurst) + } +} + +// A non-default qps/burst must actually reach the config, so --kube-api-qps and +// --kube-api-burst are real tuning knobs and not just decoration over the constants. +func TestApplyKubeAPIRateLimitsPropagatesValues(t *testing.T) { + cfg := &rest.Config{} + applyKubeAPIRateLimits(cfg, 42, 84) + + if cfg.QPS != 42 { + t.Errorf("QPS = %v, want 42", cfg.QPS) + } + if cfg.Burst != 84 { + t.Errorf("Burst = %d, want 84", cfg.Burst) + } +} + +// The default flag values must pass validation, and a non-positive value — which +// client-go would silently turn into the starving default (0) or unlimited +// (<0) — must be rejected. +func TestValidateRateLimitFlags(t *testing.T) { + if err := validateRateLimitFlags(defaultKubeAPIQPS, defaultKubeAPIBurst); err != nil { + t.Errorf("defaults must be valid, got %v", err) + } + + cases := []struct { + name string + qps float64 + burst int + }{ + {"zero qps falls back to the starving default", 0, defaultKubeAPIBurst}, + {"negative qps disables rate limiting", -1, defaultKubeAPIBurst}, + {"zero burst", defaultKubeAPIQPS, 0}, + {"negative burst", defaultKubeAPIQPS, -5}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + if err := validateRateLimitFlags(tc.qps, tc.burst); err == nil { + t.Errorf("validateRateLimitFlags(%v, %d) = nil, want error", tc.qps, tc.burst) + } + }) + } +} + +// Behavioural regression for the FailedAttachVolume flake. The NFS-volume +// ControllerPublishVolume path polls the infra PVC once per second for up to two +// minutes; when several volumes attach at once the default 5 QPS / 10 burst limiter starves and Wait returns +// "context deadline exceeded" — the exact error the tenant kubelet reports as +// FailedAttachVolume. The limits applyKubeAPIRateLimits sets must admit that burst. +func TestRateLimitedConfigAdmitsBurstThatDefaultStarves(t *testing.T) { + // A burst larger than any refill the deadline can supply: 5 QPS over 500ms + // tops up ~2.5 tokens on top of a 10-token bucket, so the default limiter + // cannot admit 200 waiters before the deadline, while a bucket sized for the + // burst admits them immediately. Both outcomes are deterministic. + const burst = 200 + const deadline = 500 * time.Millisecond + + drain := func(qps float32, b int) error { + lim := flowcontrol.NewTokenBucketRateLimiter(qps, b) + ctx, cancel := context.WithTimeout(context.Background(), deadline) + defer cancel() + for range burst { + if err := lim.Wait(ctx); err != nil { + return err + } + } + return nil + } + + if err := drain(clientGoDefaultQPS, clientGoDefaultBurst); err == nil { + t.Fatal("default 5 QPS / 10 burst limiter admitted the burst; the test can no longer prove the fix") + } + + cfg := &rest.Config{} + applyKubeAPIRateLimits(cfg, defaultKubeAPIQPS, defaultKubeAPIBurst) + if err := drain(cfg.QPS, cfg.Burst); err != nil { + t.Errorf("configured limiter (%v QPS / %d burst) still starved on the attach burst: %v", cfg.QPS, cfg.Burst, err) + } +} diff --git a/packages/apps/kubernetes/templates/delete.yaml b/packages/apps/kubernetes/templates/delete.yaml index cf45d016a..7c5289358 100644 --- a/packages/apps/kubernetes/templates/delete.yaml +++ b/packages/apps/kubernetes/templates/delete.yaml @@ -8,6 +8,37 @@ metadata: "helm.sh/hook-delete-policy": hook-succeeded,before-hook-creation name: {{ .Release.Name }}-pre-cleanup spec: + # One attempt. restartPolicy Never turns the default of 6 into seven pods in + # series, each restarting the script from Step 1 and each paying its own image + # pull, which outlives the uninstall budget: helm then times out on its own + # instead of reporting which step failed. + # + # Zero and not one, because a second attempt does not fit. Both waits below + # are guarded, so an attempt can spend all of its budget without failing and a + # retry starts from Step 1 with the clock already there; on a nodeless tenant + # it also re-pays Step 4, since attempt one leaves the TenantControlPlane + # terminating. The failure a retry would cover is an eviction (this pod + # tolerates control-plane taints), which is not bounded in time and costs most + # when it arrives late. The price is that such an eviction fails the whole + # attempt and flux repeats it on its own interval — slower, and predictable. + backoffLimit: 0 + # No activeDeadlineSeconds, for arithmetic rather than oversight. A deadline + # has to sit above the sum of the waits below, or it cuts runs that were going + # to finish, and far enough under helm-controller's uninstall budget to be + # what helm reports rather than what it waits through. Those two bounds do not + # currently leave a gap, and the image pull comes from Docker Hub with no + # mirror in front of it. + # + # Note that the sum is a whole-Job figure only while backoffLimit is 0: + # activeDeadlineSeconds runs from status.startTime and a retry does not reset + # it, so allowing retries means the deadline has to clear all of them. + # + # Room comes from raising spec.uninstall.timeout on the generated HelmRelease, + # not from squeezing the waits further. + # packages/apps/bucket/templates/hooks/cleanup-acme.yaml is the shape to copy + # then: same image, with the deadline and the retry budget set together, and + # --request-timeout on each call so an unresponsive apiserver is bounded too, + # which --wait=false below does not cover. template: metadata: labels: @@ -90,8 +121,21 @@ spec: fi echo "Step 3: Deleting KamajiControlPlane {{ .Release.Name }}" + # --wait is spelled out because kubectl defaults it to true, and a + # --timeout it does not carry defaults to 0, which kubectl reads + # as "wait forever" and turns into a week. + # + # false rather than a bound, because there is nothing here worth + # waiting for. What matters downstream is the TenantControlPlane, + # and Step 4 deletes that one directly and waits for it; blocking + # on the KamajiControlPlane first only adds a second place for a + # CAPI finalizer to stall the hook. Not waiting also keeps this + # step under `set -e` with no guard: with no timeout to expire, + # every remaining non-zero exit is a real failure — the API + # rejecting the request, discovery breaking, RBAC being wrong — + # and none of those should be reported as a cleanup that happened. kubectl -n {{ .Release.Namespace }} delete kamajicontrolplanes.controlplane.cluster.x-k8s.io {{ .Release.Name }} \ - --ignore-not-found=true + --ignore-not-found=true --wait=false echo "Step 4: Deleting TenantControlPlane {{ .Release.Name }} and waiting for it to be removed" # --wait=true blocks until the TenantControlPlane object is fully @@ -137,16 +181,24 @@ spec: echo " Secret {{ .Release.Name }}-datastore-config not present; nothing to do" fi + # Steps 5 and 6 do not wait. Both defaulted to --wait=true with no + # --timeout, so either one parked this hook for a week on a single + # stuck finalizer: a DataVolume held by a CDI importer or a PVC + # finalizer is the reachable case. Waiting buys nothing here. + # Nothing after these steps reads their result, and the DELETE has + # already been accepted either way — an expired wait and + # --wait=false leave the same cluster state, with the same objects + # finalizing in the background once the hook has moved on. echo "Step 5: Cleaning up DataVolumes" kubectl -n {{ .Release.Namespace }} delete datavolumes \ -l "cluster.x-k8s.io/cluster-name={{ .Release.Name }}" \ - --ignore-not-found=true + --ignore-not-found=true --wait=false echo "Step 6: Cleaning up LoadBalancer Services" kubectl -n {{ .Release.Namespace }} delete services \ -l "cluster.x-k8s.io/cluster-name={{ .Release.Name }}" \ --field-selector spec.type=LoadBalancer \ - --ignore-not-found=true + --ignore-not-found=true --wait=false echo "Cleanup completed successfully" volumeMounts: @@ -184,6 +236,9 @@ rules: - watch - patch - delete + # watch is granted only where a delete still waits: Step 2 on helmreleases and + # Step 4 on tenantcontrolplanes. The other three deletes pass --wait=false, so + # kubectl never opens a watch for them and the verb would be unexercised. - apiGroups: - "controlplane.cluster.x-k8s.io" resources: @@ -191,7 +246,6 @@ rules: verbs: - get - list - - watch - delete - apiGroups: - "kamaji.clastix.io" @@ -209,7 +263,6 @@ rules: verbs: - get - list - - watch - delete - apiGroups: - "" @@ -218,7 +271,6 @@ rules: verbs: - get - list - - watch - delete # Scoped to the single Kamaji datastore connection Secret so Step 4b can # strip the leftover finalizer.kamaji.clastix.io/datastore-secret finalizer diff --git a/packages/apps/kubernetes/templates/helmreleases/csi.yaml b/packages/apps/kubernetes/templates/helmreleases/csi.yaml index c1cc6502f..86d560aa9 100644 --- a/packages/apps/kubernetes/templates/helmreleases/csi.yaml +++ b/packages/apps/kubernetes/templates/helmreleases/csi.yaml @@ -21,11 +21,36 @@ spec: key: super-admin.svc targetNamespace: cozy-csi storageNamespace: cozy-csi + {{- /* Flux defaults to the RemediateOnFailure strategy, and install + remediation is always an uninstall, so an install that outruns the + spec.timeout above is torn down between attempts: the tenant loses + its CSI node plugin and the StorageClasses this release propagates, + and the next attempt restarts the DaemonSet rollout instead of + resuming one already under way. RetryOnFailure keeps the manifests + in place and retries the failed release. Both actions carry it + because the controller picks the active retry by + .status.lastAttemptedReleaseAction and performs that retry as an + upgrade, so on install alone the retry's own failure falls through + to upgrade remediation, a rollback with no previous release to + reach. The cost is that a real upgrade failure retries rather than + rolls back, which gives up no stable safety net: with retries: -1 + and the default rollback strategy, upgrade remediation already + rolled back and retried without end. The remediation blocks stay + for a different reason, that an absent release + consults install and an out-of-sync one consults upgrade, both by + retry count rather than by strategy, so retries: -1 keeps them + open. */}} install: createNamespace: true + strategy: + name: RetryOnFailure + retryInterval: 30s remediation: retries: -1 upgrade: + strategy: + name: RetryOnFailure + retryInterval: 30s remediation: retries: -1 values: diff --git a/packages/apps/kubernetes/tests/csi_install_retry_test.yaml b/packages/apps/kubernetes/tests/csi_install_retry_test.yaml new file mode 100644 index 000000000..a4bd3e0f2 --- /dev/null +++ b/packages/apps/kubernetes/tests/csi_install_retry_test.yaml @@ -0,0 +1,54 @@ +suite: csi.yaml install retry strategy + +templates: + - templates/helmreleases/csi.yaml + +values: + - values/common.yaml + +tests: + # Install remediation is an uninstall in every case Flux offers, so under the + # default strategy an install that misses its budget takes the tenant's CSI + # node plugin and propagated StorageClasses away until a later attempt lands + # them again. RetryOnFailure keeps the manifests applied and retries instead. + - it: retries a failed install instead of uninstalling the tenant CSI + release: + name: kubernetes-test + namespace: tenant-test + asserts: + - equal: + path: spec.install.strategy.name + value: RetryOnFailure + - equal: + path: spec.install.strategy.retryInterval + value: 30s + + # The controller performs the retry of a failed install as an upgrade, so + # without a strategy here that retry's own failure falls through to upgrade + # remediation instead of retrying again. + - it: carries the strategy on the upgrade action the retry runs as + release: + name: kubernetes-test + namespace: tenant-test + asserts: + - equal: + path: spec.upgrade.strategy.name + value: RetryOnFailure + - equal: + path: spec.upgrade.strategy.retryInterval + value: 30s + + # The strategy governs a failed release. An absent release and an out-of-sync + # one take different branches, which consult the retry count instead and stop + # acting once it is exhausted. + - it: keeps unlimited retries for the branches the strategy does not reach + release: + name: kubernetes-test + namespace: tenant-test + asserts: + - equal: + path: spec.install.remediation.retries + value: -1 + - equal: + path: spec.upgrade.remediation.retries + value: -1 diff --git a/packages/apps/kubernetes/tests/delete_hook_test.yaml b/packages/apps/kubernetes/tests/delete_hook_test.yaml index 01027942c..bb9a3fbe1 100644 --- a/packages/apps/kubernetes/tests/delete_hook_test.yaml +++ b/packages/apps/kubernetes/tests/delete_hook_test.yaml @@ -68,3 +68,124 @@ tests: - matchRegex: path: spec.template.spec.containers[0].command[2] pattern: 'get tenantcontrolplanes\.kamaji\.clastix\.io test-k8s[\s\S]*still present[\s\S]*patch secret test-k8s-datastore-config' + + # The remaining tests pin the wall-clock bounds on every delete in the hook. + # kubectl defaults --wait to true and reads --timeout=0 as a week, so a delete + # written with neither flag is one stuck finalizer away from parking this hook + # for 168 hours. + + - it: every delete in the hook carries a wall-clock bound + documentSelector: + path: kind + value: Job + asserts: + # Each pattern walks only continuation lines — the ones ending in a + # backslash — so it stays inside the command it names. A cross-line + # wildcard reaches a flag belonging to the next command instead, and RE2, + # which helm-unittest matches with, has no lookahead to exclude the echo + # in between. + # + # None of the three waits, so none of them needs a guard to swallow an + # expired one — which matters, because a guard cannot tell a timeout from + # a rejected request and would report both as cleanup that happened. + # + # Step 3. What matters downstream is the TenantControlPlane, which Step 4 + # deletes and waits for; waiting here only adds a second place for a CAPI + # finalizer to stall. + - matchRegex: + path: spec.template.spec.containers[0].command[2] + pattern: 'delete kamajicontrolplanes\.controlplane\.cluster\.x-k8s\.io test-k8s(?:[^\n]*\\\n)*[^\n]*--wait=false' + # Steps 5 and 6: nothing after them reads the result, and a DELETE that + # has been accepted is not made more complete by watching it. --wait=false + # and an expired --wait leave the same cluster state, one of them sooner. + - matchRegex: + path: spec.template.spec.containers[0].command[2] + pattern: 'delete datavolumes(?:[^\n]*\\\n)*[^\n]*--wait=false' + - matchRegex: + path: spec.template.spec.containers[0].command[2] + pattern: 'delete services(?:[^\n]*\\\n)*[^\n]*--wait=false' + # And the two that were already bounded stay bounded. --wait=false and + # --timeout bound the waiting, not the request: --request-timeout is still + # 0 on every call here, so an apiserver that stops answering hangs this + # hook the same as before. That is a different failure from the stuck + # finalizer these bounds are for, and it wants one answer across all the + # calls rather than a flag on the deletes. + - matchRegex: + path: spec.template.spec.containers[0].command[2] + pattern: 'delete helmreleases\.helm\.toolkit\.fluxcd\.io(?:[^\n]*\\\n)*[^\n]*--timeout=[1-9][0-9]*s' + - matchRegex: + path: spec.template.spec.containers[0].command[2] + pattern: 'delete tenantcontrolplanes\.kamaji\.clastix\.io test-k8s(?:[^\n]*\\\n)*[^\n]*--timeout=[1-9][0-9]*s' + + - it: cleanup Role keeps watch on exactly the two resources whose deletes wait + documentSelector: + path: kind + value: Role + asserts: + # kubectl opens a watch only on the wait path, so watch is granted to the + # two resources Steps 2 and 4 wait on and to no others. Removing it from + # either of those does not error — the delete hangs instead, which is the + # failure mode that is hardest to read from the outside, so it is pinned + # rather than left to the reviewer of the next RBAC change. + # + # Whole-rule contains, not per-index verb assertions. notContains passes + # when its path does not resolve, so an index-addressed "and nowhere else" + # goes quiet the moment the rules list is reordered or shortened — the + # failure it is written to prevent would take the assertion with it. + # Matching the entire rule pins the verb set in both directions and names + # the resource when it fails; lengthEqual is what closes the remaining + # hole, a sixth rule appended past everything asserted here. + - lengthEqual: + path: rules + count: 6 + - contains: + path: rules + content: + apiGroups: ["helm.toolkit.fluxcd.io"] + resources: ["helmreleases"] + verbs: ["get", "list", "watch", "patch", "delete"] + - contains: + path: rules + content: + apiGroups: ["kamaji.clastix.io"] + resources: ["tenantcontrolplanes"] + verbs: ["get", "list", "watch", "delete"] + - contains: + path: rules + content: + apiGroups: ["controlplane.cluster.x-k8s.io"] + resources: ["kamajicontrolplanes"] + verbs: ["get", "list", "delete"] + - contains: + path: rules + content: + apiGroups: ["cdi.kubevirt.io"] + resources: ["datavolumes"] + verbs: ["get", "list", "delete"] + - contains: + path: rules + content: + apiGroups: [""] + resources: ["services"] + verbs: ["get", "list", "delete"] + + - it: pre-delete Job makes a single attempt + documentSelector: + path: kind + value: Job + asserts: + # restartPolicy is Never, so the default backoffLimit of 6 allows seven + # pods in series, each re-running every step from the top and each paying + # its own image pull. That outlives the uninstall budget, and helm gives + # up on its own timeout without reporting which step failed. + # + # Zero and not one: both remaining waits are guarded, so an attempt can + # spend its full 240s without failing, and a retry starts from Step 1 with + # the clock already there. On a nodeless tenant it also re-pays Step 4's + # 120s, because attempt 1 leaves the TenantControlPlane still terminating. + - equal: + path: spec.backoffLimit + value: 0 + - equal: + path: spec.template.spec.restartPolicy + value: Never diff --git a/packages/apps/opensearch/templates/opensearch.yaml b/packages/apps/opensearch/templates/opensearch.yaml index 411c57a4b..adcdb63ad 100644 --- a/packages/apps/opensearch/templates/opensearch.yaml +++ b/packages/apps/opensearch/templates/opensearch.yaml @@ -32,6 +32,34 @@ spec: name: {{ .Release.Name }}-security-config adminCredentialsSecret: name: {{ .Release.Name }}-admin-credentials + {{- /* + securityadmin.sh runs java with no -Xmx of its own, so the JVM sizes its + heap from whatever the container is allowed. With nothing set here the + tenant LimitRange supplies the namespace default instead, and the operator + builds this Job with backoffLimit 0, so the single OOM kill that follows is + final: the security index is never written and every node sits behind + "Not yet initialized (you may need to run securityadmin)" until the release + is deleted. + + Measured against opensearchproject/opensearch:2.11.1 on linux/amd64, + applying a security config to a fresh single-node cluster: OOMKilled + mid-apply at 128Mi and at 192Mi, completes from 256Mi up. Having no -Xmx it + grows into what it is given, peaking at 208Mi under a 256Mi limit and at + 253Mi under the 512Mi one below, so the headroom here is the point rather + than the peak. + + Constants rather than the preset: the tool configures the cluster once and + exits, so what it needs does not grow with the nodes it configures, and the + smallest preset would hand it back the 128Mi it dies at. + */}} + updateJob: + resources: + requests: + cpu: 100m + memory: 256Mi + limits: + cpu: "1" + memory: 512Mi {{- if .Values.dashboards.enabled }} dashboards: enable: true diff --git a/packages/apps/opensearch/tests/opensearch_test.yaml b/packages/apps/opensearch/tests/opensearch_test.yaml index 2959ec180..10c32284f 100644 --- a/packages/apps/opensearch/tests/opensearch_test.yaml +++ b/packages/apps/opensearch/tests/opensearch_test.yaml @@ -530,3 +530,50 @@ tests: path: spec.selector["opster.io/opensearch-cluster"] value: mydb documentIndex: 1 + + ################################### + # securityconfig update job # + ################################### + + - it: gives the securityconfig update job its own resources + release: + name: test-os + namespace: tenant-test + set: + _cluster: + cluster-domain: cozy.local + asserts: + - equal: + path: spec.security.config.updateJob.resources.requests.memory + value: 256Mi + documentIndex: 0 + - equal: + path: spec.security.config.updateJob.resources.limits.memory + value: 512Mi + documentIndex: 0 + - equal: + path: spec.security.config.updateJob.resources.requests.cpu + value: 100m + documentIndex: 0 + - equal: + path: spec.security.config.updateJob.resources.limits.cpu + value: "1" + documentIndex: 0 + + # securityadmin configures the cluster once and exits, so what it needs does + # not grow with the cluster. Tying it to the preset would hand it 128Mi again + # on the smallest one, which is the amount it is OOMKilled at. + - it: keeps the update job resources off the node sizing preset + release: + name: test-os + namespace: tenant-test + set: + _cluster: + cluster-domain: cozy.local + resourcesPreset: "nano" + resources: {} + asserts: + - equal: + path: spec.security.config.updateJob.resources.limits.memory + value: 512Mi + documentIndex: 0 diff --git a/packages/apps/tenant/README.md b/packages/apps/tenant/README.md index c70ff0f27..52ec7cd46 100644 --- a/packages/apps/tenant/README.md +++ b/packages/apps/tenant/README.md @@ -70,6 +70,10 @@ tenant-u1 └── postgres-db1 ``` +### Network isolation + +Tenant network isolation is enforced with Cilium network policies. On the `isp-hosted` and `isp-hosted-slim` platform variants the CNI belongs to the host, so these policies are created only if the host serves the Cilium policy API when the tenant is installed or updated. On a host without Cilium, tenants get no network isolation from Cozystack, and isolating them is up to the host. If Cilium appears on the host later, the policies are created on the tenant's next chart or values change, not automatically. + ## Parameters ### Common parameters diff --git a/packages/apps/tenant/templates/_helpers.tpl b/packages/apps/tenant/templates/_helpers.tpl index 0f7d064d9..4df1d3c23 100644 --- a/packages/apps/tenant/templates/_helpers.tpl +++ b/packages/apps/tenant/templates/_helpers.tpl @@ -92,3 +92,16 @@ false {{- if .Values.gateway -}}true{{- else -}}false{{- end -}} {{- end -}} {{- end -}} + +{{- /* Every variant but the isp-hosted ones installs Cilium itself, so the + policies render unconditionally there: a CRD missing at render time + must fail the install, not leave the tenant unisolated for good, since + helm-controller does not re-render a release when discovery changes. + isp-hosted runs on the host's CNI, which may or may not be Cilium. */ -}} +{{- define "tenant.ciliumPolicies" -}} +{{- if not (has (include "cozy-lib.bundle-name" .) (list "isp-hosted" "isp-hosted-slim")) -}} +true +{{- else if and (.Capabilities.APIVersions.Has "cilium.io/v2/CiliumNetworkPolicy") (.Capabilities.APIVersions.Has "cilium.io/v2/CiliumClusterwideNetworkPolicy") -}} +true +{{- end -}} +{{- end -}} diff --git a/packages/apps/tenant/templates/etcd.yaml b/packages/apps/tenant/templates/etcd.yaml index 38da293aa..12eccde82 100644 --- a/packages/apps/tenant/templates/etcd.yaml +++ b/packages/apps/tenant/templates/etcd.yaml @@ -28,10 +28,40 @@ spec: namespace: cozy-system interval: 5m timeout: 30m + {{- /* Flux's default install strategy remediates a failed install by + uninstalling, and install remediation is an uninstall in every case + Flux offers. This release does not disable hooks on it, so that + uninstall runs the etcd chart's post-delete cleanup Job, which deletes + the data-etcd- PVCs by name because the etcd-operator does not + reclaim them when the EtcdCluster goes. An install that misses its + budget therefore destroys the datastore the tenant control planes keep + their state in, and the next attempt starts from an empty cluster + rather than resuming the one already converging. RetryOnFailure keeps + the manifests applied and retries the failed release, so no uninstall + happens and the cleanup Job never runs. Both actions carry the strategy + because the controller performs that retry as an upgrade, so on install + alone the retry's own failure falls through to upgrade remediation. + Two things are traded away. A genuine upgrade failure now retries + rather than rolls back, which gives up no stable safety net: with + retries: -1 and the default strategy, upgrade remediation already + rolled back and retried without end. And the uninstall was the only + automatic clean slate, so an install wedged on a bad resource state + retries against that state until an operator removes the release. For + a release that owns data that is the right exchange, because lost data + does not come back and a wedged install does. The remediation blocks + stay because an absent release consults + install and an out-of-sync one consults upgrade, both by retry count + rather than by strategy. */}} install: + strategy: + name: RetryOnFailure + retryInterval: 30s remediation: retries: -1 upgrade: + strategy: + name: RetryOnFailure + retryInterval: 30s remediation: retries: -1 valuesFrom: diff --git a/packages/apps/tenant/templates/networkpolicy.yaml b/packages/apps/tenant/templates/networkpolicy.yaml index 4bd3ba02a..d0ff69a38 100644 --- a/packages/apps/tenant/templates/networkpolicy.yaml +++ b/packages/apps/tenant/templates/networkpolicy.yaml @@ -1,3 +1,4 @@ +{{- if include "tenant.ciliumPolicies" . }} --- apiVersion: cilium.io/v2 kind: CiliumNetworkPolicy @@ -224,6 +225,23 @@ spec: - toEndpoints: - matchLabels: "k8s:io.kubernetes.pod.namespace": cozy-kubevirt-cdi +--- +apiVersion: cilium.io/v2 +kind: CiliumNetworkPolicy +metadata: + name: allow-to-vm-exportproxy + namespace: {{ include "tenant.name" . }} +spec: + endpointSelector: {} + egress: + - toEndpoints: + - matchLabels: + "k8s:io.kubernetes.pod.namespace": cozy-kubevirt + kubevirt.io: virt-exportproxy + toPorts: + - ports: + - port: "8443" + protocol: TCP {{- if .Values.monitoring }} --- apiVersion: cilium.io/v2 @@ -257,3 +275,4 @@ spec: - toEndpoints: - matchLabels: cozystack.io/service: ingress +{{- end }} diff --git a/packages/apps/tenant/templates/seaweedfs.yaml b/packages/apps/tenant/templates/seaweedfs.yaml index c0a1cf0c0..a02cc22a3 100644 --- a/packages/apps/tenant/templates/seaweedfs.yaml +++ b/packages/apps/tenant/templates/seaweedfs.yaml @@ -19,10 +19,40 @@ spec: namespace: cozy-system interval: 5m timeout: 10m + {{- /* Flux's default install strategy remediates a failed install by + uninstalling, and install remediation is an uninstall in every case + Flux offers. This release does not disable hooks on it, so that + uninstall runs the seaweedfs chart's post-delete cleanup Job, which + deletes the volume PVCs by label and explicitly reclaims the + keep-protected CNPG Cluster holding the filer metadata, precisely + because nothing else removes it. An install that misses its budget + therefore destroys the object store's data and the metadata database + that indexes it, and the next attempt starts from nothing rather than + resuming. RetryOnFailure keeps the manifests applied and retries the + failed release, so no uninstall happens and the cleanup Job never runs. + Both actions carry the strategy because the controller performs that + retry as an upgrade, so on install alone the retry's own failure falls + through to upgrade remediation. Two things are traded away. A genuine + upgrade failure now retries rather than rolls back, which gives up no + stable safety net: with retries: -1 and the default strategy, upgrade + remediation already rolled back and retried without end. And the + uninstall was the only automatic clean slate, so an install wedged on a + bad resource state retries against that state until an operator removes + the release. For a release that owns data that is the right exchange, + because lost data does not come back and a wedged install does. The + remediation blocks stay because an absent release consults install and + an out-of-sync one consults upgrade, both by retry count rather than by + strategy. */}} install: + strategy: + name: RetryOnFailure + retryInterval: 30s remediation: retries: -1 upgrade: + strategy: + name: RetryOnFailure + retryInterval: 30s remediation: retries: -1 valuesFrom: diff --git a/packages/apps/tenant/tests/networkpolicy_cilium_guard_test.yaml b/packages/apps/tenant/tests/networkpolicy_cilium_guard_test.yaml new file mode 100644 index 000000000..29f2186fe --- /dev/null +++ b/packages/apps/tenant/tests/networkpolicy_cilium_guard_test.yaml @@ -0,0 +1,66 @@ +suite: tenant Cilium policies follow the platform variant's CNI +templates: + - templates/networkpolicy.yaml +release: + name: tenant-ktj + namespace: tenant-root +tests: + - it: renders no Cilium objects on isp-hosted without the cilium.io API + set: + _cluster: + bundle-name: isp-hosted + asserts: + - hasDocuments: + count: 0 + + - it: renders no Cilium objects on isp-hosted-slim without the cilium.io API + set: + _cluster: + bundle-name: isp-hosted-slim + asserts: + - hasDocuments: + count: 0 + + - it: renders no Cilium objects on isp-hosted when only one Cilium kind is served + set: + _cluster: + bundle-name: isp-hosted + capabilities: + apiVersions: + - cilium.io/v2/CiliumNetworkPolicy + asserts: + - hasDocuments: + count: 0 + + - it: renders the Cilium policies on isp-hosted when the host runs Cilium + set: + _cluster: + bundle-name: isp-hosted + capabilities: + apiVersions: + - cilium.io/v2/CiliumNetworkPolicy + - cilium.io/v2/CiliumClusterwideNetworkPolicy + asserts: &policiesRendered + - template: templates/networkpolicy.yaml + documentSelector: + path: metadata.name + value: allow-internal-communication + isKind: + of: CiliumNetworkPolicy + - template: templates/networkpolicy.yaml + documentSelector: + path: metadata.name + value: tenant-ktj-ingress + isKind: + of: CiliumClusterwideNetworkPolicy + + - it: renders the Cilium policies on a Cilium variant even when the API is not discoverable + set: + _cluster: + bundle-name: isp-full + asserts: *policiesRendered + + - it: renders the Cilium policies when the platform injected no bundle-name + set: + _cluster: {} + asserts: *policiesRendered diff --git a/packages/apps/tenant/tests/networkpolicy_vm_exportproxy_test.yaml b/packages/apps/tenant/tests/networkpolicy_vm_exportproxy_test.yaml new file mode 100644 index 000000000..597e000d9 --- /dev/null +++ b/packages/apps/tenant/tests/networkpolicy_vm_exportproxy_test.yaml @@ -0,0 +1,85 @@ +suite: tenant egress to the KubeVirt export proxy +# The vm-exportproxy Ingress in cozy-kubevirt is served by the ingress +# controller running in tenant-root. Tenant egress is default-deny plus +# explicit allow-to-* policies, so without this one the controller cannot +# reach virt-exportproxy. It follows allow-to-cdi-upload-proxy, the policy for +# the sibling CDI upload proxy, in where and when it renders. +templates: + - templates/networkpolicy.yaml +tests: + - it: renders next to allow-to-cdi-upload-proxy in the root tenant + release: + name: tenant-root + namespace: tenant-root + asserts: + - documentSelector: + path: metadata.name + value: allow-to-cdi-upload-proxy + equal: + path: metadata.namespace + value: tenant-root + - documentSelector: + path: metadata.name + value: allow-to-vm-exportproxy + isKind: + of: CiliumNetworkPolicy + - documentSelector: + path: metadata.name + value: allow-to-vm-exportproxy + equal: + path: metadata.namespace + value: tenant-root + + - it: renders next to allow-to-cdi-upload-proxy in a nested tenant with every module off + release: + name: tenant-bar + namespace: tenant-foo + set: + monitoring: false + ingress: false + etcd: false + asserts: + - documentSelector: + path: metadata.name + value: allow-to-cdi-upload-proxy + equal: + path: metadata.namespace + value: tenant-foo-bar + - documentSelector: + path: metadata.name + value: allow-to-vm-exportproxy + equal: + path: metadata.namespace + value: tenant-foo-bar + + - it: applies to every pod of the tenant, as allow-to-cdi-upload-proxy does + release: + name: tenant-root + namespace: tenant-root + asserts: + - documentSelector: + path: metadata.name + value: allow-to-vm-exportproxy + equal: + path: spec.endpointSelector + value: {} + + - it: allows only the export proxy pods on their container port + release: + name: tenant-root + namespace: tenant-root + asserts: + - documentSelector: + path: metadata.name + value: allow-to-vm-exportproxy + equal: + path: spec.egress + value: + - toEndpoints: + - matchLabels: + "k8s:io.kubernetes.pod.namespace": cozy-kubevirt + kubevirt.io: virt-exportproxy + toPorts: + - ports: + - port: "8443" + protocol: TCP diff --git a/packages/apps/tenant/tests/volume_owner_install_retry_test.yaml b/packages/apps/tenant/tests/volume_owner_install_retry_test.yaml new file mode 100644 index 000000000..b0db647e8 --- /dev/null +++ b/packages/apps/tenant/tests/volume_owner_install_retry_test.yaml @@ -0,0 +1,102 @@ +suite: etcd and seaweedfs tenant HelmReleases retry a failed install in place + +# Named after the two releases rather than after the class they belong to. The +# tenant's monitoring release owns storage as well and its own post-delete Job +# deletes it, and that release is outside this suite, so a class-shaped title +# would print as PASS over members it never looked at. +# +# Restrict rendering to the two templates asserted on, so a template this suite +# makes no claim about cannot fail it. That is not hypothetical: at the time of +# writing, dropping the restriction reds all four tests on keycloakgroups.yaml, +# which errors with "index of untyped nil" on the `.Values._cluster` the +# platform injects and this suite has no reason to set. Adding a template to +# the list below is safe. +templates: + - templates/etcd.yaml + - templates/seaweedfs.yaml + +release: + name: tenant-test + namespace: tenant-test + +set: + etcd: true + seaweedfs: true + host: "" + +tests: + # Install remediation is an uninstall in every case Flux offers, and neither + # release disables hooks on it, so a remediated install runs each chart's + # post-delete cleanup Job. Those Jobs delete data on purpose: the etcd one + # removes the data-etcd- PVCs by name, because the etcd-operator does + # not reclaim them when the EtcdCluster goes. An install that misses its + # budget therefore destroys the datastore the tenant control planes keep their + # state in, rather than merely restarting. + - it: retries a failed etcd install instead of deleting the datastore + asserts: + - template: templates/etcd.yaml + equal: + path: spec.install.strategy.name + value: RetryOnFailure + - template: templates/etcd.yaml + equal: + path: spec.install.strategy.retryInterval + value: 30s + + # The seaweedfs cleanup Job deletes the volume PVCs by label and explicitly + # reclaims the keep-protected CNPG Cluster holding the filer metadata, which + # nothing else removes. Same consequence for a remediated install. + - it: retries a failed seaweedfs install instead of deleting the filer metadata + asserts: + - template: templates/seaweedfs.yaml + equal: + path: spec.install.strategy.name + value: RetryOnFailure + - template: templates/seaweedfs.yaml + equal: + path: spec.install.strategy.retryInterval + value: 30s + + # The controller performs the retry of a failed install as an upgrade, so + # without a strategy here that retry's own failure falls through to upgrade + # remediation instead of retrying again. + - it: carries the strategy on the upgrade action the retry runs as + asserts: + - template: templates/etcd.yaml + equal: + path: spec.upgrade.strategy.name + value: RetryOnFailure + - template: templates/etcd.yaml + equal: + path: spec.upgrade.strategy.retryInterval + value: 30s + - template: templates/seaweedfs.yaml + equal: + path: spec.upgrade.strategy.name + value: RetryOnFailure + - template: templates/seaweedfs.yaml + equal: + path: spec.upgrade.strategy.retryInterval + value: 30s + + # The strategy governs a failed release. An absent release and an out-of-sync + # one take different branches, which consult the retry count instead and stop + # acting once it is exhausted. + - it: keeps unlimited retries for the branches the strategy does not reach + asserts: + - template: templates/etcd.yaml + equal: + path: spec.install.remediation.retries + value: -1 + - template: templates/etcd.yaml + equal: + path: spec.upgrade.remediation.retries + value: -1 + - template: templates/seaweedfs.yaml + equal: + path: spec.install.remediation.retries + value: -1 + - template: templates/seaweedfs.yaml + equal: + path: spec.upgrade.remediation.retries + value: -1 diff --git a/packages/apps/vm-instance/templates/vm.yaml b/packages/apps/vm-instance/templates/vm.yaml index b6d20dfa6..6f394c192 100644 --- a/packages/apps/vm-instance/templates/vm.yaml +++ b/packages/apps/vm-instance/templates/vm.yaml @@ -35,12 +35,14 @@ spec: metadata: annotations: kubevirt.io/allow-pod-bridge-network-live-migration: "true" + {{- if .Capabilities.APIVersions.Has "kubeovn.io/v1/IP" }} {{- $ovnIPName := printf "%s.%s" (include "virtual-machine.fullname" .) .Release.Namespace }} {{- $ovnIP := lookup "kubeovn.io/v1" "IP" "" $ovnIPName }} {{- if $ovnIP }} ovn.kubernetes.io/mac_address: {{ $ovnIP.spec.macAddress | quote }} ovn.kubernetes.io/ip_address: {{ $ovnIP.spec.ipAddress | quote }} {{- end }} + {{- end }} labels: {{- include "virtual-machine.labels" . | nindent 8 }} spec: diff --git a/packages/apps/vm-instance/tests/kubeovn_capability_test.yaml b/packages/apps/vm-instance/tests/kubeovn_capability_test.yaml new file mode 100644 index 000000000..c2d9e63ed --- /dev/null +++ b/packages/apps/vm-instance/tests/kubeovn_capability_test.yaml @@ -0,0 +1,61 @@ +suite: vm-instance Kube-OVN IP pinning follows API discovery + +# On a live cluster Helm's `lookup` propagates the discovery error when the +# requested API group is not served, so the chart could not render at all +# without the Kube-OVN CRDs. helm-unittest's fake lookup never errors: it just +# returns nothing for an unserved kind, so an IP object is mocked here to pin +# both sides. With the API advertised the annotations must carry the mocked +# values; with the API absent they must be missing even though the object +# exists, which is the branch the discovery guard adds. +release: + name: test-vm + namespace: tenant-test +templates: + - templates/vm.yaml +set: + fullnameOverride: test-vm + instanceType: "" + instanceProfile: "" + resources: + cpu: 1 + sockets: 1 + memory: 1Gi + _cluster: + scheduling: + dedicatedNodesForWindowsVMs: "false" +kubernetesProvider: + scheme: + "kubeovn.io/v1/IP": + gvr: + group: kubeovn.io + version: v1 + resource: ips + namespaced: false + objects: + - apiVersion: kubeovn.io/v1 + kind: IP + metadata: + name: test-vm.tenant-test + spec: + macAddress: "00:00:5E:00:53:01" + ipAddress: "192.0.2.10" +tests: + - it: pins the Kube-OVN IP and MAC when the IP API is served + capabilities: + apiVersions: + - kubeovn.io/v1/IP + asserts: + - equal: + path: spec.template.metadata.annotations["ovn.kubernetes.io/mac_address"] + value: "00:00:5E:00:53:01" + - equal: + path: spec.template.metadata.annotations["ovn.kubernetes.io/ip_address"] + value: "192.0.2.10" + - it: skips the lookup when the IP API is not served, even if an IP object exists + capabilities: + apiVersions: [] + asserts: + - notExists: + path: spec.template.metadata.annotations["ovn.kubernetes.io/mac_address"] + - notExists: + path: spec.template.metadata.annotations["ovn.kubernetes.io/ip_address"] diff --git a/packages/core/platform/images/migrations/run-migrations.sh b/packages/core/platform/images/migrations/run-migrations.sh index aeea5ec44..6bb9f353f 100755 --- a/packages/core/platform/images/migrations/run-migrations.sh +++ b/packages/core/platform/images/migrations/run-migrations.sh @@ -10,8 +10,11 @@ TARGET_VERSION="${TARGET_VERSION:-0}" echo "Starting migrations from version $CURRENT_VERSION to $TARGET_VERSION" -# Check if ConfigMap exists -if ! kubectl get configmap --namespace "$NAMESPACE" cozystack-version >/dev/null 2>&1; then +# --ignore-not-found turns only NotFound into empty output; any other failure +# still exits non-zero and aborts here, so the Job retries it. Reading such a +# failure as absence would stamp the target over migrations that never ran. +EXISTING=$(kubectl get configmap --namespace "$NAMESPACE" cozystack-version --ignore-not-found --output name) +if [ -z "$EXISTING" ]; then echo "ConfigMap cozystack-version does not exist, creating it with version $TARGET_VERSION" # Stamp via the shared helper so the bootstrap ConfigMap carries the # platform.cozystack.io/no-delete label, matching every go-forward stamp diff --git a/packages/core/platform/templates/apps.yaml b/packages/core/platform/templates/apps.yaml index 779db50b0..f7a6b9aa5 100644 --- a/packages/core/platform/templates/apps.yaml +++ b/packages/core/platform/templates/apps.yaml @@ -18,6 +18,17 @@ metadata: type: Opaque stringData: values.yaml: | + {{- /* + The operator builds every in-cluster name it needs from DNS_BASE: the + securityconfig job target, its own OpenSearch API client URL, the + Dashboards host, and the SANs it writes into node certificates. This is + a vendored subchart value, so it travels under the subchart key; _cluster + stops at each package's own templates and never reaches a subchart. + A package rendered without this Secret falls back to cluster.local. + */}} + opensearch-operator: + manager: + dnsBase: {{ .Values.networking.clusterDomain | quote }} _cluster: root-host: {{ $rootHost | quote }} bundle-name: {{ .Values.bundles.system.variant | quote }} diff --git a/packages/core/platform/templates/bundles/iaas.yaml b/packages/core/platform/templates/bundles/iaas.yaml index 1f8f11b8b..928c19f6c 100644 --- a/packages/core/platform/templates/bundles/iaas.yaml +++ b/packages/core/platform/templates/bundles/iaas.yaml @@ -19,10 +19,25 @@ {{- end -}} {{- /* When cozystack.gpu-operator is enabled the platform mirrors the variant - into the KubeVirt CR: the HostDevices feature gate plus a starter - permittedHostDevices block. Without this the admission webhook rejects - any VM that references a host-device GPU by resourceName. See - docs/gpu-vgpu.md for the user-facing knobs. + into the KubeVirt CR: the HostDevices feature gate, without which the + admission webhook rejects any VM that references a host-device GPU by + resourceName, plus a permittedHostDevices block assembled per variant. + The platform's own tables are the passthrough one in the default + variant and the mdev one in vgpu behind gpu.vgpuDeviceManager.enabled; + gpu.replaceDefaults drops whichever would apply, and the operator's own + .gpu entries are appended on top (see the per-key comment below for + which key each variant reads). A vgpu cluster at stock values therefore + gets the gate and no device table. See docs/gpu-vgpu.md for the + user-facing knobs. + + Both pieces are VM-facing and are emitted only for the two variants + that hand a GPU resource to a VM: default (the whole card, rebound to + vfio-pci) and vgpu (mdev profiles or SR-IOV VFs carved out by the host + vGPU driver). The container variant serves GPUs to ordinary pods + through the device plugin and runs no VM-facing GPU stack at all — + sandboxWorkloads and vfioManager are both off — so the gate would + advertise a capability the node cannot serve and the device table + would list resources no plugin ever registers there. */ -}} {{- /* Mirror the cozystack.platform.package.optional helper's enable/disable @@ -35,16 +50,21 @@ {{- $gpuEnabled := and (has $gpuName (default (list) .Values.bundles.enabledPackages)) (not (has $gpuName (default (list) .Values.bundles.disabledPackages))) -}} {{- $gpuVariant := .Values.bundles.iaas.gpuOperatorVariant | default "default" -}} {{- /* - Validate the variant up front, not behind $gpuEnabled — a typo like + The accepted set is the variant list of the cozystack.gpu-operator + PackageSource in sources/gpu-operator.yaml — default, vgpu, container. + A variant added there needs adding here too, or the bundle rejects a + value the package ships. + + Validate up front, not behind $gpuEnabled — a typo like gpuOperatorVariant: passthrough (instead of "default") would otherwise render fine until someone flips gpu-operator into enabledPackages, at which point the bundle breaks. Failing fast here surfaces the typo on the first render after the values file changes. */ -}} -{{- if not (or (eq $gpuVariant "default") (eq $gpuVariant "vgpu")) -}} -{{- fail (printf "bundles.iaas.gpuOperatorVariant must be \"default\" or \"vgpu\", got %q" $gpuVariant) -}} +{{- if not (or (eq $gpuVariant "default") (eq $gpuVariant "vgpu") (eq $gpuVariant "container")) -}} +{{- fail (printf "bundles.iaas.gpuOperatorVariant must be \"default\", \"vgpu\" or \"container\", got %q" $gpuVariant) -}} {{- end -}} -{{- if $gpuEnabled }} +{{- if and $gpuEnabled (ne $gpuVariant "container") }} {{- $_ := set $kubevirtValues "extraFeatureGates" (list "HostDevices") -}} {{- /* Each .Values.gpu access is fully parenthesized — (((.Values.gpu).x).y) — @@ -63,9 +83,10 @@ {{- $userMdevConfig := default (dict) (.Values.gpu).mediatedDevicesConfiguration -}} {{- $replace := default false (.Values.gpu).replaceDefaults -}} {{- /* - pciHostDevices applies in both variants — passthrough (vfio-pci, whole - GPU) and post-kubevirt#16890 SR-IOV vGPU VFs (Ada Lovelace / Blackwell - with the vGPU 17/20 driver branch) both advertise via pciHostDevices. + pciHostDevices applies in both VM variants — passthrough (vfio-pci, + whole GPU) and post-kubevirt#16890 SR-IOV vGPU VFs (Ada Lovelace / + Blackwell with the vGPU 17/20 driver branch) both advertise via + pciHostDevices. The container variant never reaches this block. mediatedDevices is vgpu-only: it EXPOSES, by stable profile name (mdevNameSelector), the mdev devices the GPU Operator's vGPU Device Manager creates on the node. Emitting it in the passthrough variant diff --git a/packages/core/platform/tests/apps_opensearch_operator_dns_base_test.yaml b/packages/core/platform/tests/apps_opensearch_operator_dns_base_test.yaml new file mode 100644 index 000000000..5d2cd0693 --- /dev/null +++ b/packages/core/platform/tests/apps_opensearch_operator_dns_base_test.yaml @@ -0,0 +1,33 @@ +suite: apps.yaml networking.clusterDomain reaches the opensearch-operator DNS base + +templates: + - templates/apps.yaml + +release: + name: cozy-platform + namespace: cozy-system + +# The operator builds every in-cluster name it needs from DNS_BASE, which the +# vendored subchart reads from manager.dnsBase and defaults to cluster.local. +# The platform carries the authoritative domain to it under the subchart key in +# the shared values Secret. Every pattern here anchors dnsBase to its +# opensearch-operator and manager parents, so a sibling block carrying the same +# domain cannot satisfy the assertion on its own. + +tests: + - it: carries the cozy.local default under the subchart key + asserts: + - matchRegex: + path: stringData["values.yaml"] + pattern: '(?m)^opensearch-operator:\n manager:\n dnsBase: "cozy\.local"$' + + - it: tracks a non-default networking.clusterDomain + set: + networking.clusterDomain: example.test + asserts: + - matchRegex: + path: stringData["values.yaml"] + pattern: '(?m)^opensearch-operator:\n manager:\n dnsBase: "example\.test"$' + - notMatchRegex: + path: stringData["values.yaml"] + pattern: '(?m)^opensearch-operator:\n manager:\n dnsBase: "cozy\.local"$' diff --git a/packages/core/platform/tests/bundles_gpu_kubevirt_wiring_test.yaml b/packages/core/platform/tests/bundles_gpu_kubevirt_wiring_test.yaml index 7e06f6bf2..52ffe36bb 100644 --- a/packages/core/platform/tests/bundles_gpu_kubevirt_wiring_test.yaml +++ b/packages/core/platform/tests/bundles_gpu_kubevirt_wiring_test.yaml @@ -220,12 +220,12 @@ tests: variant: isp-full iaas: enabled: true - gpuOperatorVariant: container + gpuOperatorVariant: sriov enabledPackages: - cozystack.gpu-operator asserts: - failedTemplate: - errorMessage: 'bundles.iaas.gpuOperatorVariant must be "default" or "vgpu", got "container"' + errorMessage: 'bundles.iaas.gpuOperatorVariant must be "default", "vgpu" or "container", got "sriov"' - it: rejects an invalid gpuOperatorVariant even when gpu-operator is not enabled so the typo is caught at edit time, not at gpu-enable time set: @@ -239,7 +239,92 @@ tests: enabledPackages: [] asserts: - failedTemplate: - errorMessage: 'bundles.iaas.gpuOperatorVariant must be "default" or "vgpu", got "passthrough"' + errorMessage: 'bundles.iaas.gpuOperatorVariant must be "default", "vgpu" or "container", got "passthrough"' + + # The container variant is the third variant the cozystack.gpu-operator + # PackageSource ships (values.yaml + values-container.yaml). The bundle + # guard rejected it for its first release, which made a shipped and tested + # variant unselectable from platform values. + - it: emits the gpu-operator Package at the container variant so the third shipped variant is selectable from platform values + set: + bundles: + system: + enabled: true + variant: isp-full + iaas: + enabled: true + gpuOperatorVariant: container + enabledPackages: + - cozystack.gpu-operator + # Both legs of the vgpu forwarding block are armed on purpose. It is + # the only writer of spec.components on this Package and container + # newly reaches its gate; with these unset the block yields an empty + # dict either way, so the notExists below would hold even if the gate + # admitted container. + gpu: + vgpuManager: + imagePullSecrets: + - nvidia-registry-secret + vgpuDeviceManager: + enabled: true + documentSelector: + path: metadata.name + value: cozystack.gpu-operator + asserts: + - equal: + path: kind + value: Package + - equal: + path: spec.variant + value: container + - notExists: + path: spec.components + + # The container variant keeps the host NVIDIA driver bound and pins + # vfioManager off, so no GPU can be detached for a VM. Emitting the + # HostDevices gate would advertise a KubeVirt capability the node cannot + # serve, and the pciHostDevices table would name resources that no + # sandbox device plugin ever registers. + - it: leaves the KubeVirt host-device wiring out entirely in the container variant, even with gpu.* overrides set + set: + bundles: + system: + enabled: true + variant: isp-full + iaas: + enabled: true + gpuOperatorVariant: container + enabledPackages: + - cozystack.gpu-operator + gpu: + permittedHostDevices: + pciHostDevices: + - pciVendorSelector: "1002:744C" + resourceName: amd.com/MI300X + externalResourceProvider: true + mediatedDevices: + - mdevNameSelector: NVIDIA A100-40C + resourceName: nvidia.com/A100-40C + externalResourceProvider: true + mediatedDevicesConfiguration: + mediatedDeviceTypes: + - nvidia-559 + documentSelector: + path: metadata.name + value: cozystack.kubevirt + asserts: + - notExists: + path: spec.components.kubevirt.values.extraFeatureGates + - notExists: + path: spec.components.kubevirt.values.permittedHostDevices + - notExists: + path: spec.components.kubevirt.values.mediatedDevicesConfiguration + # The rest of the kubevirt component values are untouched by the + # variant — this pins that the container branch skips only the GPU + # wiring, not the whole component block. + - equal: + path: spec.components.kubevirt.values.cpuAllocationRatio + value: 10 - it: emits the gpu-operator Package without component overrides for the passthrough variant so vfio-pci defaults from the chart apply unchanged set: diff --git a/packages/core/platform/values.yaml b/packages/core/platform/values.yaml index 9d0fac251..96e297c51 100644 --- a/packages/core/platform/values.yaml +++ b/packages/core/platform/values.yaml @@ -42,14 +42,21 @@ bundles: enabled: false # gpu-operator variant selector — applies when cozystack.gpu-operator is # in bundles.enabledPackages. "default" runs the vfio-pci passthrough - # stack (whole GPU → one VM); "vgpu" runs the vGPU Manager stack. The - # platform mirrors this into the KubeVirt CR: passthrough auto-wires the - # HostDevices feature gate plus a default permittedHostDevices.pciHostDevices - # table covering common NVIDIA datacenter GPUs (vendor 10DE); vgpu - # auto-wires permittedHostDevices.mediatedDevices plus a starter - # mediatedDevicesConfiguration. Operators with additional or non-NVIDIA - # cards extend the defaults via gpu.permittedHostDevices / - # gpu.mediatedDevicesConfiguration / gpu.replaceDefaults below. + # stack (whole GPU → one VM); "vgpu" runs the vGPU Manager stack; + # "container" serves GPUs to ordinary pods through the device plugin on + # hosts that already provide the NVIDIA driver and container toolkit. + # The platform mirrors the two VM variants into the KubeVirt CR: both + # get the HostDevices feature gate; passthrough also gets a default + # permittedHostDevices.pciHostDevices table covering common NVIDIA + # datacenter GPUs (vendor 10DE), and vgpu gets + # permittedHostDevices.mediatedDevices when + # gpu.vgpuDeviceManager.enabled is true. No mediatedDevicesConfiguration + # default ships in either variant — see the gpu block below for why. + # "container" gets none of that wiring: it keeps the host driver bound, + # so no GPU is available for VM passthrough. + # Operators with additional or non-NVIDIA cards extend the defaults via + # gpu.permittedHostDevices / gpu.mediatedDevicesConfiguration / + # gpu.replaceDefaults below — read by the two VM variants only. gpuOperatorVariant: default paas: enabled: false @@ -523,10 +530,15 @@ kubevirt: # Passed to spec.configuration.migrations on the KubeVirt CR. # Empty keeps KubeVirt's defaults. bandwidthPerMigration is bytes/second. migrations: {} -# GPU host-device wiring for VirtualMachine workloads. Auto-injected into the -# KubeVirt CR's permittedHostDevices when bundles.enabledPackages contains -# cozystack.gpu-operator. Without it the admission webhook rejects any VM -# that references a GPU host-device by resourceName. +# GPU host-device wiring for VirtualMachine workloads. Merged into the KubeVirt +# CR's permittedHostDevices when bundles.enabledPackages contains +# cozystack.gpu-operator and bundles.iaas.gpuOperatorVariant is one of the two +# VM variants, default or vgpu. The platform's own defaults join it there: the +# passthrough table in the default variant, the mdev table in vgpu only when +# gpu.vgpuDeviceManager.enabled is true, and neither when replaceDefaults below +# is true. So a stock vgpu cluster that sets nothing here gets the HostDevices +# gate and no device table at all. The container variant serves GPUs to pods +# and never to VMs, so nothing in this block reaches the KubeVirt CR under it. gpu: # When false (default), the lists below are appended to the platform's # NVIDIA defaults. When true, the user lists fully replace the defaults @@ -534,11 +546,12 @@ gpu: # strictly curated allowlist is required. replaceDefaults: false permittedHostDevices: - # PCI passthrough devices. Always rendered when non-empty regardless of - # gpuOperatorVariant — pciHostDevices covers both the vfio-pci passthrough - # path (default variant) and the post-kubevirt#16890 SR-IOV vGPU path + # PCI passthrough devices. Rendered when non-empty under either VM + # variant — pciHostDevices covers both the vfio-pci passthrough path + # (default variant) and the post-kubevirt#16890 SR-IOV vGPU path # (vgpu variant on Ada Lovelace / Blackwell, where VFs are advertised - # via pciHostDevices, not via mediatedDevices). Default-table coverage: + # via pciHostDevices, not via mediatedDevices). The container variant + # renders neither list. Default-table coverage: # H100, H200, A100 PCIe/SXM, A40, A30, A10, L40, L40S, L4, T4, V100, # V100S (PCI vendor 10DE). Item shape matches KubeVirt's pciHostDevices: # - pciVendorSelector: "10DE:2335" diff --git a/packages/library/cozy-lib/templates/_cozyconfig.tpl b/packages/library/cozy-lib/templates/_cozyconfig.tpl index 04c891c28..3e96ab9bb 100644 --- a/packages/library/cozy-lib/templates/_cozyconfig.tpl +++ b/packages/library/cozy-lib/templates/_cozyconfig.tpl @@ -8,7 +8,7 @@ Get the root host for the cluster. Usage: {{ include "cozy-lib.root-host" . }} */}} {{- define "cozy-lib.root-host" -}} -{{- (index .Values._cluster "root-host") | default "" }} +{{- (index (.Values._cluster | default dict) "root-host") | default "" }} {{- end }} {{/* @@ -16,7 +16,7 @@ Get the bundle name for the cluster. Usage: {{ include "cozy-lib.bundle-name" . }} */}} {{- define "cozy-lib.bundle-name" -}} -{{- (index .Values._cluster "bundle-name") | default "" }} +{{- (index (.Values._cluster | default dict) "bundle-name") | default "" }} {{- end }} {{/* @@ -53,7 +53,7 @@ Get the ipv4 cluster CIDR. Usage: {{ include "cozy-lib.ipv4-cluster-cidr" . }} */}} {{- define "cozy-lib.ipv4-cluster-cidr" -}} -{{- (index .Values._cluster "ipv4-cluster-cidr") | default "" }} +{{- (index (.Values._cluster | default dict) "ipv4-cluster-cidr") | default "" }} {{- end }} {{/* @@ -61,7 +61,7 @@ Get the ipv4 service CIDR. Usage: {{ include "cozy-lib.ipv4-service-cidr" . }} */}} {{- define "cozy-lib.ipv4-service-cidr" -}} -{{- (index .Values._cluster "ipv4-service-cidr") | default "" }} +{{- (index (.Values._cluster | default dict) "ipv4-service-cidr") | default "" }} {{- end }} {{/* @@ -69,7 +69,7 @@ Get the ipv4 join CIDR. Usage: {{ include "cozy-lib.ipv4-join-cidr" . }} */}} {{- define "cozy-lib.ipv4-join-cidr" -}} -{{- (index .Values._cluster "ipv4-join-cidr") | default "" }} +{{- (index (.Values._cluster | default dict) "ipv4-join-cidr") | default "" }} {{- end }} {{/* @@ -78,8 +78,9 @@ Usage: {{ include "cozy-lib.scheduling" . }} Returns: YAML string of scheduling configuration */}} {{- define "cozy-lib.scheduling" -}} -{{- if .Values._cluster.scheduling }} -{{- .Values._cluster.scheduling | toYaml }} +{{- $scheduling := (.Values._cluster | default dict).scheduling }} +{{- if $scheduling }} +{{- $scheduling | toYaml }} {{- end }} {{- end }} @@ -89,8 +90,9 @@ Usage: {{ include "cozy-lib.branding" . }} Returns: YAML string of branding configuration */}} {{- define "cozy-lib.branding" -}} -{{- if .Values._cluster.branding }} -{{- .Values._cluster.branding | toYaml }} +{{- $branding := (.Values._cluster | default dict).branding }} +{{- if $branding }} +{{- $branding | toYaml }} {{- end }} {{- end }} @@ -104,7 +106,7 @@ Get the host for this namespace. Usage: {{ include "cozy-lib.ns-host" . }} */}} {{- define "cozy-lib.ns-host" -}} -{{- .Values._namespace.host | default "" }} +{{- (.Values._namespace | default dict).host | default "" }} {{- end }} {{/* @@ -112,7 +114,7 @@ Get the etcd namespace reference. Usage: {{ include "cozy-lib.ns-etcd" . }} */}} {{- define "cozy-lib.ns-etcd" -}} -{{- .Values._namespace.etcd | default "" }} +{{- (.Values._namespace | default dict).etcd | default "" }} {{- end }} {{/* @@ -120,7 +122,7 @@ Get the ingress namespace reference. Usage: {{ include "cozy-lib.ns-ingress" . }} */}} {{- define "cozy-lib.ns-ingress" -}} -{{- .Values._namespace.ingress | default "" }} +{{- (.Values._namespace | default dict).ingress | default "" }} {{- end }} {{/* @@ -128,7 +130,7 @@ Get the monitoring namespace reference. Usage: {{ include "cozy-lib.ns-monitoring" . }} */}} {{- define "cozy-lib.ns-monitoring" -}} -{{- .Values._namespace.monitoring | default "" }} +{{- (.Values._namespace | default dict).monitoring | default "" }} {{- end }} {{/* @@ -136,7 +138,7 @@ Get the seaweedfs namespace reference. Usage: {{ include "cozy-lib.ns-seaweedfs" . }} */}} {{- define "cozy-lib.ns-seaweedfs" -}} -{{- .Values._namespace.seaweedfs | default "" }} +{{- (.Values._namespace | default dict).seaweedfs | default "" }} {{- end }} {{/* diff --git a/packages/system/backupstrategy-controller/templates/rbac.yaml b/packages/system/backupstrategy-controller/templates/rbac.yaml index b61c7eb56..cb84c6309 100644 --- a/packages/system/backupstrategy-controller/templates/rbac.yaml +++ b/packages/system/backupstrategy-controller/templates/rbac.yaml @@ -49,10 +49,12 @@ rules: - apiGroups: ["kubevirt.io"] resources: ["virtualmachineinstances"] verbs: ["get"] -# CDI DataVolumes: pre-restore deletes DVs so CDI doesn't recreate PVCs after rename +# CDI DataVolumes: pre-restore deletes DVs so CDI doesn't recreate PVCs after rename, +# and reads each one back to hold the restore until it is gone (a point Get +# through the dynamic client, so no list/watch) - apiGroups: ["cdi.kubevirt.io"] resources: ["datavolumes"] - verbs: ["delete"] + verbs: ["get", "delete"] # HelmReleases: pre-restore suspends HRs; post-restore rename creates new HR # and deletes old. patch additionally lets the DefaultObjectsGate stamp # reconcile.fluxcd.io/forceAt + requestedAt on THIS chart's own release to diff --git a/packages/system/backupstrategy-controller/tests/restore_rbac_test.yaml b/packages/system/backupstrategy-controller/tests/restore_rbac_test.yaml new file mode 100644 index 000000000..b13b88173 --- /dev/null +++ b/packages/system/backupstrategy-controller/tests/restore_rbac_test.yaml @@ -0,0 +1,23 @@ +suite: RBAC of the Velero restore preparation + +# prepareForRestore reads every DataVolume back after deleting it and holds +# the Velero Restore until it is gone. The read goes through the dynamic +# client, which the Go unit tests run with no authorization, so a missing verb +# only shows up on a cluster, where it fails every in-place VM restore. + +templates: + - templates/rbac.yaml + +release: + name: backupstrategy-controller + namespace: cozy-backup-controller + +tests: + - it: "ClusterRole can read and delete DataVolumes" + asserts: + - contains: + path: rules + content: + apiGroups: ["cdi.kubevirt.io"] + resources: ["datavolumes"] + verbs: ["get", "delete"] diff --git a/packages/system/capi-operator/Makefile b/packages/system/capi-operator/Makefile index 9349f5499..e90c8fe88 100644 --- a/packages/system/capi-operator/Makefile +++ b/packages/system/capi-operator/Makefile @@ -9,3 +9,6 @@ include ../../../hack/package.mk update: clean capi-operator-update rm -rf charts/cluster-api-operator/charts/ + # The upstream chart has no value for --sync-period; values.yaml explains + # why we set it. + patch -p1 < patches/sync-period.diff diff --git a/packages/system/capi-operator/charts/cluster-api-operator/templates/deployment.yaml b/packages/system/capi-operator/charts/cluster-api-operator/templates/deployment.yaml index 598d85c8a..1d51dce18 100644 --- a/packages/system/capi-operator/charts/cluster-api-operator/templates/deployment.yaml +++ b/packages/system/capi-operator/charts/cluster-api-operator/templates/deployment.yaml @@ -86,6 +86,9 @@ spec: - --leader-elect-retry-period={{ .retryPeriod }} {{- end }} {{- end }} + {{- with .Values.syncPeriod }} + - --sync-period={{ . }} + {{- end }} command: - /manager {{- with .Values.image.manager }} diff --git a/packages/system/capi-operator/patches/sync-period.diff b/packages/system/capi-operator/patches/sync-period.diff new file mode 100644 index 000000000..4c10946ad --- /dev/null +++ b/packages/system/capi-operator/patches/sync-period.diff @@ -0,0 +1,12 @@ +--- a/charts/cluster-api-operator/templates/deployment.yaml ++++ b/charts/cluster-api-operator/templates/deployment.yaml +@@ -86,6 +86,9 @@ + - --leader-elect-retry-period={{ .retryPeriod }} + {{- end }} + {{- end }} ++ {{- with .Values.syncPeriod }} ++ - --sync-period={{ . }} ++ {{- end }} + command: + - /manager + {{- with .Values.image.manager }} diff --git a/packages/system/capi-operator/values.yaml b/packages/system/capi-operator/values.yaml index 7e8b95c50..40cffd7a8 100644 --- a/packages/system/capi-operator/values.yaml +++ b/packages/system/capi-operator/values.yaml @@ -1,4 +1,12 @@ cluster-api-operator: + # A restarted v0.19 operator ignores the provider Deployments it finds + # running (kubernetes-sigs/cluster-api-operator#1031), so a stale + # Ready=False on a provider clears only at the first informer resync, + # two periods after the restart: ~20 min at the 10m default, ~2 min at + # 1m (both measured). A resync is served from the cache and changes + # nothing when providers are in sync, so the short period costs no API + # writes. Applied through patches/sync-period.diff. + syncPeriod: 1m resources: manager: limits: diff --git a/packages/system/capi-providers-core/.helmignore b/packages/system/capi-providers-core/.helmignore index 7a69e7e1d..aba9a295f 100644 --- a/packages/system/capi-providers-core/.helmignore +++ b/packages/system/capi-providers-core/.helmignore @@ -1 +1 @@ -files/.*-components.yaml +files/*-components.yaml diff --git a/packages/system/capi-providers-core/files/components.gz b/packages/system/capi-providers-core/files/components.gz index 438087eb6..bf045689a 100644 Binary files a/packages/system/capi-providers-core/files/components.gz and b/packages/system/capi-providers-core/files/components.gz differ diff --git a/packages/system/dashboard/images/console/Containerfile b/packages/system/dashboard/images/console/Containerfile index 600672f37..9ad0f90a7 100644 --- a/packages/system/dashboard/images/console/Containerfile +++ b/packages/system/dashboard/images/console/Containerfile @@ -38,6 +38,14 @@ map $http_upgrade $connection_upgrade { '' close; } +# An OIDC access token with many group claims pushes the Cookie header past the +# 8k default, and a header field must fit in a single buffer. Kept here rather +# than inside the server block: a field read before the Host header has selected +# the virtual server is measured against the default server's buffers, so the +# same lines inside a server block cover this one only while it stays default. +client_header_buffer_size 16k; +large_client_header_buffers 4 16k; + server { listen 8080 default_server; listen [::]:8080 default_server; diff --git a/packages/system/dashboard/images/console/apps/console/src/__tests__/k8s-client/client.unauthorized.test.ts b/packages/system/dashboard/images/console/apps/console/src/__tests__/k8s-client/client.unauthorized.test.ts new file mode 100644 index 000000000..2d6fbbbec --- /dev/null +++ b/packages/system/dashboard/images/console/apps/console/src/__tests__/k8s-client/client.unauthorized.test.ts @@ -0,0 +1,170 @@ +import { describe, it, expect, vi, afterEach } from "vitest" +import { K8sClient, K8sApiError } from "@cozystack/k8s-client" + +function fakeResponse(opts: { + ok?: boolean + status?: number + statusText?: string + body?: string +}): Response { + return { + ok: opts.ok ?? true, + status: opts.status ?? 200, + statusText: opts.statusText ?? "OK", + text: async () => opts.body ?? "", + json: async () => JSON.parse(opts.body ?? "null"), + } as unknown as Response +} + +const unauthorized = () => + fakeResponse({ ok: false, status: 401, statusText: "Unauthorized" }) + +afterEach(() => { + vi.unstubAllGlobals() + vi.restoreAllMocks() +}) + +describe("K8sClient onUnauthorized (401) handling", () => { + it("invokes onUnauthorized exactly once when a request returns 401", async () => { + const onUnauthorized = vi.fn() + vi.stubGlobal("fetch", vi.fn(async () => unauthorized())) + const client = new K8sClient({ onUnauthorized }) + + await expect(client.get("", "v1", "pods", "p", "ns")).rejects.toThrow( + K8sApiError, + ) + + expect(onUnauthorized).toHaveBeenCalledTimes(1) + }) + + it("invokes onUnauthorized only once across two concurrent 401s", async () => { + const onUnauthorized = vi.fn() + vi.stubGlobal("fetch", vi.fn(async () => unauthorized())) + const client = new K8sClient({ onUnauthorized }) + + // The unauthorizedHandled latch must collapse a redirect storm when many + // in-flight calls 401 at once into a single re-auth navigation. + await Promise.allSettled([ + client.get("", "v1", "pods", "a", "ns"), + client.get("", "v1", "pods", "b", "ns"), + ]) + + expect(onUnauthorized).toHaveBeenCalledTimes(1) + }) + + it("re-arms the latch after a success so a later 401 handles again", async () => { + const onUnauthorized = vi.fn() + const responses = [ + unauthorized(), + fakeResponse({ body: JSON.stringify({ kind: "Pod" }) }), + unauthorized(), + ] + let call = 0 + vi.stubGlobal("fetch", vi.fn(async () => responses[call++])) + const client = new K8sClient({ onUnauthorized }) + + // A 2xx in between means the session recovered, so the next expiry is a + // new episode. Without the re-arm a custom in-page handler would fire + // once for the client's whole lifetime. + await expect(client.get("", "v1", "pods", "p", "ns")).rejects.toThrow( + K8sApiError, + ) + await client.get("", "v1", "pods", "p", "ns") + await expect(client.get("", "v1", "pods", "p", "ns")).rejects.toThrow( + K8sApiError, + ) + + expect(onUnauthorized).toHaveBeenCalledTimes(2) + }) + + it("does not invoke onUnauthorized on a non-401 error", async () => { + const onUnauthorized = vi.fn() + vi.stubGlobal( + "fetch", + vi.fn(async () => + fakeResponse({ + ok: false, + status: 403, + statusText: "Forbidden", + body: JSON.stringify({ message: "forbidden" }), + }), + ), + ) + const client = new K8sClient({ onUnauthorized }) + + await expect(client.get("", "v1", "pods", "p", "ns")).rejects.toThrow( + K8sApiError, + ) + + expect(onUnauthorized).not.toHaveBeenCalled() + }) + + it("does not invoke onUnauthorized on a successful response", async () => { + const onUnauthorized = vi.fn() + vi.stubGlobal( + "fetch", + vi.fn(async () => fakeResponse({ body: JSON.stringify({ kind: "Pod" }) })), + ) + const client = new K8sClient({ onUnauthorized }) + + await client.get("", "v1", "pods", "p", "ns") + + expect(onUnauthorized).not.toHaveBeenCalled() + }) + + it("invokes onUnauthorized when the watch stream returns 401", async () => { + const onUnauthorized = vi.fn() + vi.stubGlobal("fetch", vi.fn(async () => unauthorized())) + const client = new K8sClient({ onUnauthorized }) + + // watch() is fire-and-forget; resolve once its onError fires. + await new Promise((resolve) => { + client.watch( + "", + "v1", + "pods", + "ns", + "0", + () => {}, + () => resolve(), + ) + }) + + expect(onUnauthorized).toHaveBeenCalledTimes(1) + }) +}) + +describe("K8sClient default unauthorized handler", () => { + it("redirects to /oauth2/sign_in with the current location preserved as rd", async () => { + // jsdom's location.assign is non-configurable, so swap the whole object. + const original = window.location + const assign = vi.fn() + Object.defineProperty(window, "location", { + configurable: true, + value: { pathname: "/apps/postgres", search: "?tab=config", hash: "#x", assign }, + }) + vi.stubGlobal("fetch", vi.fn(async () => unauthorized())) + // No onUnauthorized override -> the browser default redirect kicks in. + const client = new K8sClient() + + try { + await expect(client.get("", "v1", "pods", "p", "ns")).rejects.toThrow( + K8sApiError, + ) + + // Relative rd (no origin) preserves the destination without tripping + // oauth2-proxy's open-redirect rejection. The target must stay + // /oauth2/sign_in: token-proxy (oidc-enabled=false) serves no + // /oauth2/start, so that path falls through to its catch-all. + expect(assign).toHaveBeenCalledTimes(1) + expect(assign).toHaveBeenCalledWith( + `/oauth2/sign_in?rd=${encodeURIComponent("/apps/postgres?tab=config#x")}`, + ) + } finally { + Object.defineProperty(window, "location", { + configurable: true, + value: original, + }) + } + }) +}) diff --git a/packages/system/dashboard/images/console/packages/k8s-client/src/client.ts b/packages/system/dashboard/images/console/packages/k8s-client/src/client.ts index 4639d9f84..12f50e0fd 100644 --- a/packages/system/dashboard/images/console/packages/k8s-client/src/client.ts +++ b/packages/system/dashboard/images/console/packages/k8s-client/src/client.ts @@ -1,6 +1,16 @@ export interface K8sClientConfig { baseUrl?: string getToken?: () => Promise + onUnauthorized?: () => void +} + +// /oauth2/sign_in is the only sign-in entry both gatekeeper modes serve: +// oauth2-proxy jumps straight to the provider there (--skip-provider-button) +// and token-proxy renders its token form; /oauth2/start is oauth2-proxy-only. +function defaultOnUnauthorized(): void { + if (typeof window === "undefined") return + const rd = window.location.pathname + window.location.search + window.location.hash + window.location.assign(`/oauth2/sign_in?rd=${encodeURIComponent(rd)}`) } export class K8sApiError extends Error { @@ -24,10 +34,19 @@ export class K8sApiError extends Error { export class K8sClient { private baseUrl: string private getToken?: () => Promise + private onUnauthorized: () => void + private unauthorizedHandled = false constructor(config: K8sClientConfig = {}) { this.baseUrl = config.baseUrl ?? "" this.getToken = config.getToken + this.onUnauthorized = config.onUnauthorized ?? defaultOnUnauthorized + } + + private handleUnauthorized(): void { + if (this.unauthorizedHandled) return + this.unauthorizedHandled = true + this.onUnauthorized() } private async request(path: string, init?: RequestInit): Promise { @@ -63,9 +82,14 @@ export class K8sClient { } catch { body = `Server returned ${res.status} ${res.statusText}` } + if (res.status === 401) this.handleUnauthorized() throw new K8sApiError(res.status, body) } + // A 2xx means the session is alive again, so re-arm the latch: the default + // handler navigates away, but a custom one may re-auth in place. + this.unauthorizedHandled = false + if (res.status === 204) return undefined as T // Some endpoints (e.g. KubeVirt action subresources like // virtualmachines/{name}/restart) return 2xx with an empty body; @@ -256,11 +280,13 @@ export class K8sClient { }) if (!res.ok) { + if (res.status === 401) this.handleUnauthorized() throw new K8sApiError( res.status, await res.json().catch(() => res.statusText), ) } + this.unauthorizedHandled = false if (!res.body) throw new Error("No response body for watch") const reader = res.body.getReader() diff --git a/packages/system/dashboard/templates/gatekeeper.yaml b/packages/system/dashboard/templates/gatekeeper.yaml index 3aa6c5bef..652675300 100644 --- a/packages/system/dashboard/templates/gatekeeper.yaml +++ b/packages/system/dashboard/templates/gatekeeper.yaml @@ -77,7 +77,14 @@ spec: - --cookie-secure=true - --cookie-secret=$(OAUTH2_PROXY_COOKIE_SECRET) - --skip-provider-button - - --scope=openid email profile offline_access + # 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 }} diff --git a/packages/system/dashboard/templates/keycloakclient.yaml b/packages/system/dashboard/templates/keycloakclient.yaml index cd455af7f..27d5a032a 100644 --- a/packages/system/dashboard/templates/keycloakclient.yaml +++ b/packages/system/dashboard/templates/keycloakclient.yaml @@ -69,8 +69,11 @@ spec: defaultClientScopes: - groups - kubernetes-client - optionalClientScopes: - - offline_access + # offline_access is intentionally not offered: an offline refresh token + # survives logout (see the proxy Deployment's --scope). NB the + # keycloak-operator only adds client scopes, so dropping this does not strip + # the realm-default offline_access from an already-created client; the proxy + # --scope change is what prevents issuance. attributes: post.logout.redirect.uris: "+" client.session.idle.timeout: "86400" diff --git a/packages/system/etcd-operator-crds/Makefile b/packages/system/etcd-operator-crds/Makefile index c80b23383..118810767 100644 --- a/packages/system/etcd-operator-crds/Makefile +++ b/packages/system/etcd-operator-crds/Makefile @@ -4,7 +4,7 @@ export NAMESPACE=cozy-etcd-operator include ../../../hack/package.mk # Pinned ref of github.com/cozystack/etcd-operator to vendor CRDs from. -ETCD_OPERATOR_REF ?= v0.5.5 +ETCD_OPERATOR_REF ?= v0.5.6 # controller-gen writes the CRDs to charts/etcd-operator/crd-bases/ upstream (there # is no config/crd kustomization). Vendor each verbatim and stamp diff --git a/packages/system/etcd-operator/Chart.yaml b/packages/system/etcd-operator/Chart.yaml index 0cec5b7c6..a2321eb30 100644 --- a/packages/system/etcd-operator/Chart.yaml +++ b/packages/system/etcd-operator/Chart.yaml @@ -3,4 +3,4 @@ name: cozy-etcd-operator description: Cozystack etcd-operator (etcd-operator.cozystack.io/v1alpha2) controller-manager type: application version: 0.0.0 # Placeholder, the actual version will be automatically set during the build process -appVersion: v0.5.5 +appVersion: v0.5.6 diff --git a/packages/system/etcd-operator/Makefile b/packages/system/etcd-operator/Makefile index 2e64757e7..184ef2e1f 100644 --- a/packages/system/etcd-operator/Makefile +++ b/packages/system/etcd-operator/Makefile @@ -8,7 +8,7 @@ include ../../../hack/package.mk # domain, VPA), so only the RBAC role is re-vendored; refresh templates/rbac.yaml # by hand from charts/etcd-operator/files/manager-role-rules.yaml at this ref. # CRDs live in the sibling etcd-operator-crds package. -ETCD_OPERATOR_REF ?= v0.5.5 +ETCD_OPERATOR_REF ?= v0.5.6 update: @echo "etcd-operator is a cozystack-authored chart; refresh templates/rbac.yaml" diff --git a/packages/system/etcd-operator/tests/deployment_test.yaml b/packages/system/etcd-operator/tests/deployment_test.yaml index b3509824b..2b0d1bd57 100644 --- a/packages/system/etcd-operator/tests/deployment_test.yaml +++ b/packages/system/etcd-operator/tests/deployment_test.yaml @@ -20,12 +20,12 @@ tests: asserts: - equal: path: spec.template.spec.containers[0].image - value: ghcr.io/cozystack/etcd-operator:v0.5.5 + value: ghcr.io/cozystack/etcd-operator:v0.5.6 - contains: path: spec.template.spec.containers[0].env content: name: OPERATOR_IMAGE - value: ghcr.io/cozystack/etcd-operator:v0.5.5 + value: ghcr.io/cozystack/etcd-operator:v0.5.6 any: true - it: "image.tag overrides the appVersion default for both the container and the agent env" diff --git a/packages/system/gpu-operator/examples/README.md b/packages/system/gpu-operator/examples/README.md index 29c347934..27a98ebad 100644 --- a/packages/system/gpu-operator/examples/README.md +++ b/packages/system/gpu-operator/examples/README.md @@ -2,7 +2,7 @@ The files in this directory are **not** templates. They are reference artifacts that document one working configuration for running GPU workloads directly in pods on a Talos-based Cozystack cluster, together with the DCGM metrics needed by the `gpu/gpu-performance` Grafana dashboard. -For non-Talos Linux hosts that already provide the NVIDIA driver and `nvidia-container-toolkit` via the distro package manager (the typical apt-installed Ubuntu/Debian shape), pick the first-class `container` variant instead — `variant: container` in your Package CR is the starting point. Two host prerequisites still apply: containerd must have the `nvidia` runtime registered (`nvidia-ctk runtime configure --runtime=containerd` + restart; `apt install` lays down binaries only, it does not wire containerd), and because the variant runs with `driver.enabled=false` the operator uses the pre-installed host driver at its standard location — so a stock apt install needs no `hostPaths.driverInstallDir` override. The files here remain the right starting point on Talos, where the driver lands under a non-standard prefix and the operator does not find it at the default location without the override below. +For non-Talos Linux hosts that already provide the NVIDIA driver and `nvidia-container-toolkit` via the distro package manager (the typical apt-installed Ubuntu/Debian shape), pick the first-class `container` variant instead — set `bundles.iaas.gpuOperatorVariant: container` in platform values and put `cozystack.gpu-operator` in `bundles.enabledPackages`, or hand-craft a Package CR with `variant: container` if you need overrides the bundle does not expose. Two host prerequisites still apply: containerd must have the `nvidia` runtime registered (`nvidia-ctk runtime configure --runtime=containerd` + restart; `apt install` lays down binaries only, it does not wire containerd), and because the variant runs with `driver.enabled=false` the operator uses the pre-installed host driver at its standard location — so a stock apt install needs no `hostPaths.driverInstallDir` override. The files here remain the right starting point on Talos, where the driver lands under a non-standard prefix and the operator does not find it at the default location without the override below. The out-of-the-box `values-passthrough.yaml` for this package targets the sandbox (VFIO passthrough to KubeVirt VMs) scenario. The files here illustrate an alternative — running CUDA workloads in regular pods with the NVIDIA device plugin — and the workarounds it currently requires on Talos. diff --git a/packages/system/kubevirt/templates/vm-exportproxy-ingress.yaml b/packages/system/kubevirt/templates/vm-exportproxy-ingress.yaml index fc19e16fc..482c02a73 100644 --- a/packages/system/kubevirt/templates/vm-exportproxy-ingress.yaml +++ b/packages/system/kubevirt/templates/vm-exportproxy-ingress.yaml @@ -20,7 +20,7 @@ spec: paths: - backend: service: - name: vm-exportproxy + name: virt-exportproxy port: number: 443 path: / diff --git a/packages/system/kubevirt/templates/vm-exportproxy-tlsroute.yaml b/packages/system/kubevirt/templates/vm-exportproxy-tlsroute.yaml index d2bcbfb77..c1246f612 100644 --- a/packages/system/kubevirt/templates/vm-exportproxy-tlsroute.yaml +++ b/packages/system/kubevirt/templates/vm-exportproxy-tlsroute.yaml @@ -18,6 +18,6 @@ spec: - {{ printf "vm-exportproxy.%s" $host | quote }} rules: - backendRefs: - - name: vm-exportproxy + - name: virt-exportproxy port: 443 {{- end }} diff --git a/packages/system/kubevirt/tests/vm_exportproxy_backend_test.yaml b/packages/system/kubevirt/tests/vm_exportproxy_backend_test.yaml new file mode 100644 index 000000000..fd938e9b4 --- /dev/null +++ b/packages/system/kubevirt/tests/vm_exportproxy_backend_test.yaml @@ -0,0 +1,38 @@ +suite: vm-exportproxy routes reach the Service KubeVirt creates +templates: + - templates/vm-exportproxy-ingress.yaml + - templates/vm-exportproxy-tlsroute.yaml + +release: + name: kubevirt + namespace: cozy-kubevirt + +# virt-operator names the export proxy Service virt-exportproxy +# (VirtExportProxyName in pkg/virt-operator/resource/generate/components). +# The public hostname is vm-exportproxy.; the Service name is not +# derived from it. + +tests: + - it: the Ingress backend is virt-exportproxy + set: + _cluster: + root-host: example.org + expose-services: "vm-exportproxy" + gateway-enabled: "false" + template: templates/vm-exportproxy-ingress.yaml + asserts: + - equal: + path: spec.rules[0].http.paths[0].backend.service.name + value: virt-exportproxy + + - it: the TLSRoute backend is virt-exportproxy + set: + _cluster: + root-host: example.org + expose-services: "vm-exportproxy" + gateway-enabled: "true" + template: templates/vm-exportproxy-tlsroute.yaml + asserts: + - equal: + path: spec.rules[0].backendRefs[0].name + value: virt-exportproxy diff --git a/packages/system/linstor-gui/templates/gatekeeper.yaml b/packages/system/linstor-gui/templates/gatekeeper.yaml index 81451f418..8bb172fc8 100644 --- a/packages/system/linstor-gui/templates/gatekeeper.yaml +++ b/packages/system/linstor-gui/templates/gatekeeper.yaml @@ -89,7 +89,14 @@ spec: - --cookie-secure=true - --cookie-secret=$(OAUTH2_PROXY_COOKIE_SECRET) - --skip-provider-button - - --scope=openid email profile groups offline_access + # 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 groups - --allowed-group=cozystack-cluster-admin {{- if eq $oidcInsecureSkipVerify "true" }} - --ssl-insecure-skip-verify=true diff --git a/packages/system/linstor-gui/templates/keycloakclient.yaml b/packages/system/linstor-gui/templates/keycloakclient.yaml index e5dab87b2..d32a8d133 100644 --- a/packages/system/linstor-gui/templates/keycloakclient.yaml +++ b/packages/system/linstor-gui/templates/keycloakclient.yaml @@ -63,8 +63,11 @@ spec: webUrl: "https://linstor-gui.{{ $host }}" defaultClientScopes: - groups - optionalClientScopes: - - offline_access + # offline_access is intentionally not offered: an offline refresh token + # survives logout (see the proxy Deployment's --scope). NB the + # keycloak-operator only adds client scopes, so dropping this does not strip + # the realm-default offline_access from an already-created client; the proxy + # --scope change is what prevents issuance. attributes: post.logout.redirect.uris: "+" redirectUris: diff --git a/packages/system/linstor-gui/tests/ingress_auth_test.yaml b/packages/system/linstor-gui/tests/ingress_auth_test.yaml index 913405da5..c17868982 100644 --- a/packages/system/linstor-gui/tests/ingress_auth_test.yaml +++ b/packages/system/linstor-gui/tests/ingress_auth_test.yaml @@ -127,7 +127,7 @@ tests: content: --oidc-issuer-url=https://keycloak.dev10.example.org/realms/cozy - contains: path: spec.template.spec.containers[0].args - content: --scope=openid email profile groups offline_access + content: --scope=openid email profile groups - contains: path: spec.template.spec.containers[0].args content: --allowed-group=cozystack-cluster-admin diff --git a/packages/system/linstor/images/piraeus-server/patches/README.md b/packages/system/linstor/images/piraeus-server/patches/README.md index cc37ee736..f39c690fb 100644 --- a/packages/system/linstor/images/piraeus-server/patches/README.md +++ b/packages/system/linstor/images/piraeus-server/patches/README.md @@ -12,6 +12,9 @@ Custom patches for piraeus-server (linstor-server) v1.33.3. - Source PR/comment: [#472](https://github.com/LINBIT/linstor-server/pull/472), [maintainer note](https://github.com/LINBIT/linstor-server/pull/472#issuecomment-3949687603) - Backported from commits: [`ccc85fbd2`](https://github.com/LINBIT/linstor-server/commit/ccc85fbd2c65f0b97c52403fa80f1efdb886ec4e), [`71b601554`](https://github.com/LINBIT/linstor-server/commit/71b601554f41bcb50cd5bd06989c5b0d3a814acd) - Note: upstream commit [`3d0402a0c`](https://github.com/LINBIT/linstor-server/commit/3d0402a0c25f0a4b57b380321f10e89982f26e7a) is already included in `v1.33.1` +- **fix-k8s-create-already-exists.diff** — Adopt the existing object when a create in the Kubernetes CRD backend returns 409 AlreadyExists. The HTTP client retries a POST after a 5xx or a dropped connection, so a create the apiserver already persisted comes back as 409; a single-object transaction has no rollback entry, the key is dropped from memory while the CR stays, and every later write of that key fails until the controller restarts. Seen as a PV stuck in `Released` because linstor-csi could not set `BalanceResourcesEnabled` on the resource definition. + - Source PR: [#531](https://github.com/LINBIT/linstor-server/pull/531) + - Backported from commit: [`8badf8f05`](https://github.com/lexfrei/linstor-server/commit/8badf8f0526ff3b1b391857e4a046ed46b95a79c) - **retry-adjust-after-stale-bitmap.diff** — Retry `drbdadm adjust` after detaching a stale local bitmap state - Source PR: [#491](https://github.com/LINBIT/linstor-server/pull/491) - Backported from commit: [`51ae50a84`](https://github.com/kvaps/linstor-server/commit/51ae50a84dcb98093f543b819652c750a94d96c9) @@ -22,3 +25,9 @@ Custom patches for piraeus-server (linstor-server) v1.33.3. - **fix-min-io-probe-device-wait.diff** — Wait for temporary probe devices before reading pool I/O properties; retry failures and fall back to a probe when ZFS volumes have no usable device path. - Source PR: [#528](https://github.com/LINBIT/linstor-server/pull/528), fixes [#527](https://github.com/LINBIT/linstor-server/issues/527) - Adapted for v1.33.3; inactive LVM volumes retain the existing no-probe behavior. + +- **snapshot-restore-drbd-initialized.diff** — Mark the volume definitions of a restored snapshot as DRBD-initialized, unless the restored resource definition carries `DrbdOptions/ForceInitialSyncPermanent`, which keeps the existing path that recreates metadata, as for a backup. Without the flag the initial UpToDate race is still open on a restored volume, and `Linstor/Drbd/InitialUptoDateOn`, copied from the source volume through the snapshot, names whichever node won it for the source. When linstor-csi autoplaces a replica on that node, the empty new volume wins the race, gets mkfs and goes StandAlone against the restored replica, so a pod attached there sees an empty filesystem. With the flag set, nothing wins the race, and an autoplaced replica resyncs from the restored one like any replica added to an existing volume. + - Backported from upstream commit: [`9d8cdf511`](https://github.com/LINBIT/linstor-server/commit/9d8cdf5118338fc72a34bb99799e452e031ea8f6), first released in v1.34.0; the `CHANGELOG.md` hunk is left out + - Drop when LINSTOR is upgraded to v1.34.0 or later + - On ZFS and thin pools the autoplaced replicas still skip the initial sync and rely on the source volume's day0 UUID being in the restored replica's history, upstream included; if it is not, DRBD reports unrelated data and goes StandAlone rather than syncing + - Fixes [cozystack/cozystack#4862](https://github.com/cozystack/cozystack/issues/4862) diff --git a/packages/system/linstor/images/piraeus-server/patches/fix-k8s-create-already-exists.diff b/packages/system/linstor/images/piraeus-server/patches/fix-k8s-create-already-exists.diff new file mode 100644 index 000000000..40bf4db69 --- /dev/null +++ b/packages/system/linstor/images/piraeus-server/patches/fix-k8s-create-already-exists.diff @@ -0,0 +1,169 @@ +diff --git a/server/src/main/java/com/linbit/linstor/dbdrivers/k8s/K8sCachingClient.java b/server/src/main/java/com/linbit/linstor/dbdrivers/k8s/K8sCachingClient.java +index 5ae6a95fa..533e41541 100644 +--- a/server/src/main/java/com/linbit/linstor/dbdrivers/k8s/K8sCachingClient.java ++++ b/server/src/main/java/com/linbit/linstor/dbdrivers/k8s/K8sCachingClient.java +@@ -2,6 +2,7 @@ package com.linbit.linstor.dbdrivers.k8s; + + import com.linbit.linstor.annotation.Nullable; + ++import java.net.HttpURLConnection; + import java.util.ArrayList; + import java.util.List; + import java.util.concurrent.ConcurrentHashMap; +@@ -9,6 +10,7 @@ import java.util.concurrent.ConcurrentHashMap; + import io.fabric8.kubernetes.api.model.HasMetadata; + import io.fabric8.kubernetes.api.model.KubernetesResourceList; + import io.fabric8.kubernetes.api.model.StatusDetails; ++import io.fabric8.kubernetes.client.KubernetesClientException; + import io.fabric8.kubernetes.client.dsl.MixedOperation; + import io.fabric8.kubernetes.client.dsl.Resource; + +@@ -47,7 +49,29 @@ public class K8sCachingClient> client; ++ private Resource resource; ++ private K8sCachingClient> cachingClient; ++ ++ @SuppressWarnings("unchecked") ++ @Before ++ public void setUp() ++ { ++ client = mock(MixedOperation.class); ++ resource = mock(Resource.class); ++ ConfigMapList emptyList = new ConfigMapList(); ++ emptyList.setItems(Collections.emptyList()); ++ when(client.list()).thenReturn(emptyList); ++ when(client.withName(NAME)).thenReturn(resource); ++ cachingClient = new K8sCachingClient<>(client); ++ } ++ ++ private static ConfigMap item(String resourceVersion) ++ { ++ return new ConfigMapBuilder() ++ .withNewMetadata().withName(NAME).withResourceVersion(resourceVersion).endMetadata() ++ .addToData("value", "false") ++ .build(); ++ } ++ ++ private static KubernetesClientException httpError(int code) ++ { ++ return new KubernetesClientException("error " + code, code, null); ++ } ++ ++ @Test ++ public void createAdoptsObjectPersistedByRetriedRequest() ++ { ++ ConfigMap wanted = item(null); ++ ConfigMap replaced = item("43"); ++ when(client.create(wanted)).thenThrow(httpError(HttpURLConnection.HTTP_CONFLICT)); ++ when(resource.get()).thenReturn(item("42")); ++ when(client.replace(wanted)).thenReturn(replaced); ++ ++ assertSame(replaced, cachingClient.create(wanted)); ++ assertEquals("42", wanted.getMetadata().getResourceVersion()); ++ assertSame(replaced, cachingClient.get(NAME)); ++ } ++ ++ @Test ++ public void createRethrowsConflictWhenObjectIsGone() ++ { ++ ConfigMap wanted = item(null); ++ KubernetesClientException conflict = httpError(HttpURLConnection.HTTP_CONFLICT); ++ when(client.create(wanted)).thenThrow(conflict); ++ when(resource.get()).thenReturn(null); ++ ++ try ++ { ++ cachingClient.create(wanted); ++ fail("expected the original conflict"); ++ } ++ catch (KubernetesClientException exc) ++ { ++ assertSame(conflict, exc); ++ } ++ verify(client, never()).replace(any()); ++ assertEquals(null, cachingClient.get(NAME)); ++ } ++ ++ @Test ++ public void createRethrowsOtherErrorsUnchanged() ++ { ++ ConfigMap wanted = item(null); ++ KubernetesClientException serverError = httpError(HttpURLConnection.HTTP_INTERNAL_ERROR); ++ when(client.create(wanted)).thenThrow(serverError); ++ ++ try ++ { ++ cachingClient.create(wanted); ++ fail("expected the original error"); ++ } ++ catch (KubernetesClientException exc) ++ { ++ assertSame(serverError, exc); ++ } ++ verify(client, never()).withName(any()); ++ verify(client, never()).replace(any()); ++ } ++} diff --git a/packages/system/linstor/images/piraeus-server/patches/snapshot-restore-drbd-initialized.diff b/packages/system/linstor/images/piraeus-server/patches/snapshot-restore-drbd-initialized.diff new file mode 100644 index 000000000..7c72aab69 --- /dev/null +++ b/packages/system/linstor/images/piraeus-server/patches/snapshot-restore-drbd-initialized.diff @@ -0,0 +1,67 @@ +diff --git a/controller/src/main/java/com/linbit/linstor/core/apicallhandler/controller/CtrlSnapshotRestoreApiCallHandler.java b/controller/src/main/java/com/linbit/linstor/core/apicallhandler/controller/CtrlSnapshotRestoreApiCallHandler.java +index a639c27cc..4dabc1a83 100644 +--- a/controller/src/main/java/com/linbit/linstor/core/apicallhandler/controller/CtrlSnapshotRestoreApiCallHandler.java ++++ b/controller/src/main/java/com/linbit/linstor/core/apicallhandler/controller/CtrlSnapshotRestoreApiCallHandler.java +@@ -434,26 +434,39 @@ public class CtrlSnapshotRestoreApiCallHandler + } + } + +- /* +- * When a snapshot was received as a backup, it is marked to re-create its local metadata. Before the +- * snapshot was sent the new DRBD_INITIALIZED flag and the VlmDfn property InitialUpToDateOn were ++ /** ++ *

Sets the {@value InternalApiConsts#KEY_LINSTOR_DRBD_INITIAL_UPTODATE_ON} property to the nodeName ++ * of the first Snapshot (which has to have a disk) of the given SnapshotDefinition.

++ * ++ *

If this SnapshotDefinition is a backup, we also unset the {@link VolumeDefinition.Flags#DRBD_INITIALIZED} ++ * flag. Otherwise we ensure the same flag is set.

++ * ++ *

Backup path: When a snapshot was received as a backup, it is marked to re-create its local metadata. ++ * Before the snapshot was sent the new DRBD_INITIALIZED flag and the VlmDfn property InitialUpToDateOn were + * cleared. If DRBD_INITIALZED would be set, no peer would even read the property (on purpose). + * Without the property, no peer would think of itself as a winner, thus the DRBD resource would never + * become UpToDate. + * To avoid this, this method sets the InitialUpToDateOn property to let the first resource win the +- * race, so it can become UpToDate and therefore also pull the other peers eventually into UpToDate state. ++ * race, so it can become UpToDate and therefore also pull the other peers eventually into UpToDate state.

+ * +- * If the given SnapDfn had also non-backup snapshots, those should be able to keep their metadata. ++ *

If the given SnapDfn had also non-backup snapshots, those should be able to keep their metadata. + * In that case we do not have to do anything. If however all snapshots are descendants from backups + * we must pick one and decide the UpToDate race upfront so that the winner can set its local DRBD +- * as UpToDate, which also triggers the controller to set the DRBD_INITIALZED flag eventually. ++ * as UpToDate, which also triggers the controller to set the DRBD_INITIALZED flag eventually.

++ * ++ *

Non-Backup path: When a regular snapshot (i.e. not from a backup) is restored, we can or even should ++ * assume that the backing snapshot LVs have correct metadata which do not need be be initialized. When ++ * a SnapshotVolumeDefinition is created it unfortunately does not properly store the VolumeDefinition's flags, ++ * therefore the restored VolumeDefinition will also not have the DRBD_INITIALIZED flag set, although it ++ * refers to a device with healthy and UpToDate metadata. To fix this issue we simply set the flag in this case.

+ */ + private void checkDrbdInitializedState(ResourceDefinition rscDfnRef) throws AccessDeniedException + { + AccessContext accCtx = peerAccCtx.get(); +- if (DrbdLayerUtils.isForceInitialSyncSet(accCtx, rscDfnRef) && rscDfnRef.getDiskfulCount(accCtx) > 0) ++ if (rscDfnRef.getDiskfulCount(accCtx) > 0) + { + String winnerNodeName = rscDfnRef.getDiskfulResources(accCtx).get(0).getNode().getName().value; ++ boolean uninitializeDrbd = DrbdLayerUtils.isForceInitialSyncSet(accCtx, rscDfnRef); + Iterator vlmDfnIt = rscDfnRef.iterateVolumeDfn(accCtx); + while (vlmDfnIt.hasNext()) + { +@@ -462,7 +475,14 @@ public class CtrlSnapshotRestoreApiCallHandler + { + vlmDfn.getProps(accCtx) + .setProp(InternalApiConsts.KEY_LINSTOR_DRBD_INITIAL_UPTODATE_ON, winnerNodeName); +- vlmDfn.getFlags().disableFlags(accCtx, VolumeDefinition.Flags.DRBD_INITIALIZED); ++ if (uninitializeDrbd) ++ { ++ vlmDfn.getFlags().disableFlags(accCtx, VolumeDefinition.Flags.DRBD_INITIALIZED); ++ } ++ else ++ { ++ vlmDfn.getFlags().enableFlags(accCtx, VolumeDefinition.Flags.DRBD_INITIALIZED); ++ } + } + catch (InvalidKeyException | InvalidValueException exc) + { diff --git a/packages/system/monitoring-agents/values.yaml b/packages/system/monitoring-agents/values.yaml index 4357db276..6433a74d0 100644 --- a/packages/system/monitoring-agents/values.yaml +++ b/packages/system/monitoring-agents/values.yaml @@ -377,7 +377,7 @@ fluent-bit: Host vlinsert-generic.{{ .Values.global.target }}.svc port 9481 compress gzip - uri /insert/jsonline?_stream_fields=log_source,reason,meatdata_namespace,metadata_name&_msg_field=message&_time_field=date + uri /insert/jsonline?_stream_fields=log_source,reason,metadata_namespace,metadata_name&_msg_field=message&_time_field=date format json_lines json_date_format iso8601 header AccountID 0 diff --git a/packages/system/opensearch-operator/images/opensearch-operator/Dockerfile b/packages/system/opensearch-operator/images/opensearch-operator/Dockerfile index b77455d27..c3ed8a587 100644 --- a/packages/system/opensearch-operator/images/opensearch-operator/Dockerfile +++ b/packages/system/opensearch-operator/images/opensearch-operator/Dockerfile @@ -1,8 +1,48 @@ -# Build the manager binary from the upstream sources with the Cozystack patch -# applied. The patch keeps a single-replica cluster electable when the operator -# retires its bootstrap pod; see patches/bootstrap-voting-exclusion.diff and +# Build the manager binary from the upstream sources with the Cozystack patches +# applied. +# +# patches/bootstrap-voting-exclusion.diff keeps a single-replica cluster +# electable when the operator retires its bootstrap pod; see # https://github.com/opensearch-project/opensearch-k8s-operator/issues/1448. # +# patches/restart-on-permanently-yellow.diff carries +# https://github.com/opensearch-project/opensearch-k8s-operator/pull/1569 back to +# this version: a cluster whose replicas can never be assigned stays yellow for +# good, and the restart gate held every rolling restart and upgrade on it. The +# part of that change that counts tiered data roles (data_hot and the like) as +# data nodes is left out, because packages/apps/opensearch renders the plain +# data role only; carry it as well if that ever changes. Drop the patch on the +# first operator release that includes the change. +# +# patches/skip-unusable-drain-exclusion.diff is the other half of that change, +# for a release with three or more nodes, where packages/apps/opensearch turns +# drainDataNodes on. The gate above now lets a permanently yellow cluster reach +# PreparePodForDelete, which excludes the candidate from allocation before it can +# know whether the drain will finish. On the cluster that made the gate wait, it +# never does, and the exclusion is only withdrawn after a pod is really deleted, +# so a data node stays out of allocation for as long as the restart is stuck. The +# patch asks the allocator first, and only while nothing is moving. Tracked +# upstream as opensearch-project/opensearch-k8s-operator#1585, fixed by #1586; +# drop it on the first release carrying that. +# +# patches/timeout-cluster-api-calls.diff bounds the calls the operator makes to +# a cluster's HTTP API. Upstream builds its own http.Transport, which carries no +# dial, handshake or response-header timeout; it passes context.Background() to +# every call it makes on its own behalf; the calls that take a context from the +# caller are handed one with no deadline on it; and no http.Client is +# configured, so there is no timeout there either. A cluster that accepts a +# connection and then says nothing therefore holds the call for as long as the +# process lives, and with one worker per controller that one call stops every +# OpenSearchCluster from being reconciled. The deletion that then waits out its +# whole termination timeout is the visible end of it. The patch bounds a request +# on the RoundTripper, the one level that also reaches the product check +# opensearch-go runs for itself before a client's first request, and bounds the +# call again where the call site can be reached, because the library retries a +# request up to three more times on 502, 503 and 504 and the transport's +# deadline starts over on each. Tracked as cozystack/cozystack#4337; +# it belongs upstream, there is no upstream issue for it yet, and the patch goes +# away with the first release that carries a fix. +# # patches/trace-stalled-component-reconcilers.diff names the component a # reconcile is stuck in. The cluster controller runs nine component reconcilers # in sequence and none of them logs unconditionally when it is entered, so a @@ -14,6 +54,13 @@ # nothing while a component behaves, so it costs nothing on a healthy cluster. # It reports rather than repairs: drop it once the stall itself is understood # and fixed. +# +# The patches are applied in the order the glob expands, which is alphabetical. +# skip-unusable-drain-exclusion builds on restart-on-permanently-yellow, and +# timeout-cluster-api-calls rewrites os_client.go call sites that +# skip-unusable-drain-exclusion both adds and quotes as context, so it has to +# come after it. A rename that reorders them fails the build rather than +# producing a wrong binary. FROM golang:1.26@sha256:079e59808d2d252516e27e3f3a9c003740dee7f75e55aa71528766d52bcfc16a AS builder # Keep in step with the chart version pulled by `make update`: the chart's @@ -33,6 +80,15 @@ RUN git apply /patches/*.diff WORKDIR /workspace/opensearch-operator +# The patches carry their own tests and nothing else in this repository runs +# them: the build below compiles main.go, so a test file that had stopped +# compiling, or stopped asserting, would still produce an image. These two +# package trees are the ones the patches touch, and both run without a cluster. +# -race is on because the timeout tests run a listener in one goroutine and +# inspect what it accepted from another: an unsynchronised access there passes +# the plain run, so nothing else would catch it. The builder has cgo and gcc. +RUN go test -race ./opensearch-gateway/... ./pkg/reconcilers/... + RUN GOOS=$TARGETOS GOARCH=$TARGETARCH CGO_ENABLED=0 go build -a -o manager main.go FROM gcr.io/distroless/static:nonroot@sha256:d29e660cc75a5b6b1334e03c5c81ccf9bc0884a002c6000dbf0fb96034814478 diff --git a/packages/system/opensearch-operator/images/opensearch-operator/patches/restart-on-permanently-yellow.diff b/packages/system/opensearch-operator/images/opensearch-operator/patches/restart-on-permanently-yellow.diff new file mode 100644 index 000000000..8362eb2e8 --- /dev/null +++ b/packages/system/opensearch-operator/images/opensearch-operator/patches/restart-on-permanently-yellow.diff @@ -0,0 +1,368 @@ +diff --git a/opensearch-operator/opensearch-gateway/responses/ClusterHealthResponse.go b/opensearch-operator/opensearch-gateway/responses/ClusterHealthResponse.go +--- a/opensearch-operator/opensearch-gateway/responses/ClusterHealthResponse.go ++++ b/opensearch-operator/opensearch-gateway/responses/ClusterHealthResponse.go +@@ -2,10 +2,13 @@ + + type ClusterHealthResponse struct { + Status string `json:"status,omitempty"` ++ NumberOfDataNodes int `json:"number_of_data_nodes,omitempty"` + ActiveShards int `json:"active_shards,omitempty"` + RelocatingShards int `json:"relocating_shards,omitempty"` + InitializingShards int `json:"initializing_shards,omitempty"` + UnassignedShards int `json:"unassigned_shards,omitempty"` ++ DelayedUnassigned int `json:"delayed_unassigned_shards,omitempty"` ++ InFlightFetch int `json:"number_of_in_flight_fetch,omitempty"` + PercentActive float32 `json:"active_shards_percent_as_number,omitempty"` + Indices map[string]IndexHealth `json:"indices,omitempty"` + } +diff --git a/opensearch-operator/opensearch-gateway/services/os_data_service.go b/opensearch-operator/opensearch-gateway/services/os_data_service.go +--- a/opensearch-operator/opensearch-gateway/services/os_data_service.go ++++ b/opensearch-operator/opensearch-gateway/services/os_data_service.go +@@ -54,6 +54,26 @@ + return false, err + } + ++// extractNodeName returns the source node of a _cat/shards node column, which ++// for a relocating shard reads "source -> ip id target". ++func extractNodeName(fullNodeName string) string { ++ fields := strings.Fields(fullNodeName) ++ if len(fields) == 0 { ++ return "" ++ } ++ return fields[0] ++} ++ ++func shardsOnNodeFromResponse(response []responses.CatShardsResponse, nodeName string) []responses.CatShardsResponse { ++ var matched []responses.CatShardsResponse ++ for _, shard := range response { ++ if extractNodeName(shard.NodeName) == nodeName { ++ matched = append(matched, shard) ++ } ++ } ++ return matched ++} ++ + func HasIndexPrimariesOnNode(service *OsClusterClient, nodeName string, indices []string) (bool, error) { + var headers []string + response, err := service.CatNamedIndicesShards(headers, indices) +@@ -153,7 +173,7 @@ + }} + } + +-func CheckClusterStatusForRestart(service *OsClusterClient, drainNodes bool) (bool, string, error) { ++func CheckClusterStatusForRestart(service *OsClusterClient, drainNodes bool, dataNodes int32) (bool, string, error) { + health, err := service.GetHealth() + if err != nil { + return false, "failed to fetch health", err +@@ -163,7 +183,33 @@ + return true, "", nil + } + +- if continueRestartWithYellowHealth(health) { ++ if health.Status == "yellow" { ++ // Yellow means every primary is active. Lift our own allocation throttle ++ // (PreparePodForDelete sets "primaries") so it can't masquerade as a ++ // permanently unassignable replica. ++ flatSettings, err := service.GetFlatClusterSettings() ++ if err != nil { ++ return false, "could not fetch cluster settings", err ++ } ++ if flatSettings.Transient.ClusterRoutingAllocationEnable != string(ClusterSettingsAllocationAll) { ++ if err := SetClusterShardAllocation(service, ClusterSettingsAllocationAll); err != nil { ++ return false, "failed to set shard allocation", err ++ } ++ return false, "enabled shard allocation", nil ++ } ++ // A data node that hasn't (re)joined yet leaves no trace in the shard ++ // activity counters once its delayed allocation expires, and a pod can be ++ // Ready before it joins. Wait until every data node is part of the cluster. ++ if health.NumberOfDataNodes < int(dataNodes) { ++ return false, "waiting for all data nodes to join the cluster", nil ++ } ++ // With all data nodes present, allocation enabled and no shard activity, ++ // the allocator has already decided the remaining replicas cannot be placed ++ // (same_shard, awareness, filters, disk watermarks): waiting never turns it ++ // green. The candidate itself is vetted in PreparePodForDelete. ++ if hasShardActivity(health) { ++ return false, "waiting for shard recovery to finish", nil ++ } + return true, "", nil + } + +@@ -222,19 +268,40 @@ + if err != nil { + return false, err + } +- lg.Info(fmt.Sprintf("Waiting to drain primary replicas for system indices from node %s before deleting", podName)) +- return !systemPrimaries, nil ++ if systemPrimaries { ++ lg.Info(fmt.Sprintf("Waiting to drain primary replicas for system indices from node %s before deleting", podName)) ++ return false, nil ++ } ++ } else { ++ // Check if there are any shards on the node ++ nodeNotEmpty, err := HasShardsOnNode(service, podName) ++ if err != nil { ++ return false, err ++ } ++ if nodeNotEmpty { ++ // If the node isn't empty requeue to wait for shards to drain ++ lg.Info(fmt.Sprintf("Waiting for node %s to drain before deleting", podName)) ++ return false, nil ++ } + } +- +- // Check if there are any shards on the node +- nodeNotEmpty, err := HasShardsOnNode(service, podName) ++ } ++ // Whatever is still on the node goes offline with it. Never take down the ++ // only active copy of a shard that is supposed to have others (red window, ++ // permanent loss on emptyDir). A lone data node is exempt: there is nowhere ++ // else a copy could live, same as a green cluster with number_of_replicas: 0. ++ if nodeCount > 1 { ++ shards, err := service.CatShards([]string{"index", "shard", "prirep", "state", "node"}) + if err != nil { + return false, err + } +- // If the node isn't empty requeue to wait for shards to drain +- lg.Info(fmt.Sprintf("Waiting for node %s to drain before deleting", podName)) +- return !nodeNotEmpty, nil ++ if shard, ok := soleActiveCopyOnNode(shards, podName); ok { ++ lg.Info(fmt.Sprintf("Not restarting %s: it holds the only active copy of %s[%s]", podName, shard.Index, shard.Shard)) ++ return false, nil ++ } + } ++ if drainNode { ++ return true, nil ++ } + // Update cluster routing before deleting appropriate ordinal pod + if err := SetClusterShardAllocation(service, ClusterSettingsAllocationPrimaries); err != nil { + return false, err +@@ -263,24 +330,37 @@ + return existing, nil + } + +-// continueRestartWithYellowHealth allows upgrades and rolling restarts to continue when the cluster is yellow +-// if the yellow status is caused by the .opensearch-observability index. This is a new index that is created +-// on upgrade and will be yellow until at least 2 data nodes are upgraded. +-func continueRestartWithYellowHealth(health responses.ClusterHealthResponse) bool { +- if health.Status != "yellow" { +- return false +- } ++// hasShardActivity reports whether the allocator is still making progress: ++// shards moving, initializing, waiting on delayed allocation or on shard fetches. ++func hasShardActivity(h responses.ClusterHealthResponse) bool { ++ return h.RelocatingShards > 0 || h.InitializingShards > 0 || h.DelayedUnassigned > 0 || h.InFlightFetch > 0 ++} + +- if health.RelocatingShards > 0 || health.InitializingShards > 0 || health.UnassignedShards > 1 { +- return false ++// soleActiveCopyOnNode returns a shard whose only active copy is on nodeName ++// while other copies of it exist but are not active. Shards with no other ++// copies (number_of_replicas: 0) are ignored, as they are on a green cluster. ++// Search replicas can't be promoted to primary, so they are not counted. ++func soleActiveCopyOnNode(shards []responses.CatShardsResponse, nodeName string) (responses.CatShardsResponse, bool) { ++ type key struct{ index, shard string } ++ copies := map[key]int{} ++ activeElsewhere := map[key]int{} ++ for _, s := range shards { ++ if s.PrimaryOrReplica == "s" { ++ continue ++ } ++ k := key{s.Index, s.Shard} ++ copies[k]++ ++ if extractNodeName(s.NodeName) != nodeName && (s.State == "STARTED" || s.State == "RELOCATING") { ++ activeElsewhere[k]++ ++ } + } +- +- observabilityIndex, ok := health.Indices[".opensearch-observability"] +- if !ok { +- return false ++ for _, s := range shardsOnNodeFromResponse(shards, nodeName) { ++ k := key{s.Index, s.Shard} ++ if copies[k] > 1 && activeElsewhere[k] == 0 { ++ return s, true ++ } + } +- +- return observabilityIndex.Status == "yellow" ++ return responses.CatShardsResponse{}, false + } + + // IndexTemplatePath returns a strings.Builder pointing to /_index_template/ +diff --git a/opensearch-operator/opensearch-gateway/services/restart_gate_test.go b/opensearch-operator/opensearch-gateway/services/restart_gate_test.go +new file mode 100644 +--- /dev/null ++++ b/opensearch-operator/opensearch-gateway/services/restart_gate_test.go +@@ -0,0 +1,146 @@ ++package services ++ ++import ( ++ "net/http" ++ "testing" ++ ++ "github.com/Opster/opensearch-k8s-operator/opensearch-operator/opensearch-gateway/responses" ++ "github.com/go-logr/logr" ++ "github.com/jarcoal/httpmock" ++) ++ ++func TestSoleActiveCopyOnNode(t *testing.T) { ++ sh := func(idx, s, pr, state, node string) responses.CatShardsResponse { ++ return responses.CatShardsResponse{Index: idx, Shard: s, PrimaryOrReplica: pr, State: state, NodeName: node} ++ } ++ tests := []struct { ++ name string ++ shards []responses.CatShardsResponse ++ node string ++ want bool ++ }{ ++ {"primary with unassigned replica", []responses.CatShardsResponse{sh("a", "0", "p", "STARTED", "n0"), sh("a", "0", "r", "UNASSIGNED", "")}, "n0", true}, ++ {"replica started elsewhere", []responses.CatShardsResponse{sh("a", "0", "p", "STARTED", "n0"), sh("a", "0", "r", "STARTED", "n1")}, "n0", false}, ++ {"zero replicas behaves like green", []responses.CatShardsResponse{sh("a", "0", "p", "STARTED", "n0")}, "n0", false}, ++ {"replica on candidate, primary elsewhere, extra replica unassigned", []responses.CatShardsResponse{sh("a", "0", "p", "STARTED", "n1"), sh("a", "0", "r", "STARTED", "n0"), sh("a", "0", "r", "UNASSIGNED", "")}, "n0", false}, ++ {"candidate holds only an initializing copy", []responses.CatShardsResponse{sh("a", "0", "p", "STARTED", "n1"), sh("a", "0", "r", "INITIALIZING", "n0")}, "n0", false}, ++ {"relocating source elsewhere counts as active", []responses.CatShardsResponse{sh("a", "0", "p", "RELOCATING", "n1 -> 10.0.0.2 id n2"), sh("a", "0", "r", "STARTED", "n0")}, "n0", false}, ++ {"candidate is relocating source of a sole copy", []responses.CatShardsResponse{sh("a", "0", "p", "RELOCATING", "n0 -> 10.0.0.2 id n2"), sh("a", "0", "r", "UNASSIGNED", "")}, "n0", true}, ++ {"master-only candidate holds nothing", []responses.CatShardsResponse{sh("a", "0", "p", "STARTED", "n0"), sh("a", "0", "r", "UNASSIGNED", "")}, "master-0", false}, ++ {"search replica elsewhere is not a copy", []responses.CatShardsResponse{sh("a", "0", "p", "STARTED", "n0"), sh("a", "0", "s", "STARTED", "n1"), sh("a", "0", "r", "UNASSIGNED", "")}, "n0", true}, ++ {"search replica with zero replicas behaves like green", []responses.CatShardsResponse{sh("a", "0", "p", "STARTED", "n0"), sh("a", "0", "s", "STARTED", "n1")}, "n0", false}, ++ } ++ for _, tt := range tests { ++ t.Run(tt.name, func(t *testing.T) { ++ if _, got := soleActiveCopyOnNode(tt.shards, tt.node); got != tt.want { ++ t.Errorf("got %v, want %v", got, tt.want) ++ } ++ }) ++ } ++} ++ ++func mockClient(t *testing.T, health, transientEnable, catShards string) (*OsClusterClient, *httpmock.MockTransport, *string) { ++ tr := httpmock.NewMockTransport() ++ for _, m := range []string{http.MethodGet, http.MethodHead} { ++ tr.RegisterResponder(m, `=~^http://os.test:9200/?$`, httpmock.NewStringResponder(200, `{"version":{"number":"2.0.0"}}`)) ++ } ++ tr.RegisterResponder(http.MethodGet, `=~/_cluster/health`, httpmock.NewStringResponder(200, health)) ++ tr.RegisterResponder(http.MethodGet, `=~/_cluster/settings`, httpmock.NewStringResponder(200, `{"transient":{"cluster.routing.allocation.enable":"`+transientEnable+`"},"persistent":{}}`)) ++ put := new(string) ++ tr.RegisterResponder(http.MethodPut, `=~/_cluster/settings`, func(r *http.Request) (*http.Response, error) { ++ *put = "called" ++ return httpmock.NewStringResponse(200, `{}`), nil ++ }) ++ tr.RegisterResponder(http.MethodGet, `=~/_cat/shards`, httpmock.NewStringResponder(200, catShards)) ++ c, err := NewOsClusterClient("http://os.test:9200", "u", "p", WithTransport(tr)) ++ if err != nil { ++ t.Fatal(err) ++ } ++ return c, tr, put ++} ++ ++func TestCheckClusterStatusForRestartYellow(t *testing.T) { ++ quiet := `{"status":"yellow","unassigned_shards":3,"number_of_data_nodes":3}` ++ tests := []struct { ++ name, health, enable string ++ drain, want bool ++ wantPut bool ++ }{ ++ {"quiet yellow proceeds", quiet, "all", false, true, false}, ++ {"quiet yellow proceeds with drain", quiet, "all", true, true, false}, ++ {"own primaries throttle is lifted first", quiet, "primaries", false, false, true}, ++ {"throttle lifted with drain too", quiet, "none", true, false, true}, ++ {"missing data node waits", `{"status":"yellow","number_of_data_nodes":2}`, "all", false, false, false}, ++ {"initializing waits", `{"status":"yellow","number_of_data_nodes":3,"initializing_shards":1}`, "all", false, false, false}, ++ {"delayed allocation waits", `{"status":"yellow","number_of_data_nodes":3,"delayed_unassigned_shards":2}`, "all", false, false, false}, ++ {"in-flight fetch waits", `{"status":"yellow","number_of_data_nodes":3,"number_of_in_flight_fetch":1}`, "all", false, false, false}, ++ {"red never proceeds", `{"status":"red"}`, "all", true, false, false}, ++ } ++ for _, tt := range tests { ++ t.Run(tt.name, func(t *testing.T) { ++ c, tr, put := mockClient(t, tt.health, tt.enable, `[]`) ++ got, msg, err := CheckClusterStatusForRestart(c, tt.drain, 3) ++ if err != nil { ++ t.Fatal(err) ++ } ++ if got != tt.want || (*put != "") != tt.wantPut { ++ t.Errorf("got %v (%q) put=%q, want %v put=%v", got, msg, *put, tt.want, tt.wantPut) ++ } ++ if n := tr.GetCallCountInfo()["GET =~/_cat/shards"]; n != 0 { ++ t.Errorf("health gate must not list shards, got %d calls", n) ++ } ++ }) ++ } ++} ++ ++func TestPreparePodForDeleteSoleCopy(t *testing.T) { ++ sole := `[{"index":"a","shard":"0","prirep":"p","state":"STARTED","node":"n0"},{"index":"a","shard":"0","prirep":"r","state":"UNASSIGNED","node":null}]` ++ tests := []struct { ++ name string ++ nodeCount int32 ++ want bool ++ }{ ++ {"multi-node blocks sole copy", 3, false}, ++ {"single data node is exempt", 1, true}, ++ } ++ for _, tt := range tests { ++ t.Run(tt.name, func(t *testing.T) { ++ c, _, put := mockClient(t, `{}`, "all", sole) ++ got, err := PreparePodForDelete(c, logr.Discard(), "n0", false, tt.nodeCount) ++ if err != nil { ++ t.Fatal(err) ++ } ++ if got != tt.want || (*put != "") != tt.want { ++ t.Errorf("got %v put=%q, want %v", got, *put, tt.want) ++ } ++ }) ++ } ++} ++ ++// With drain and 2 data nodes only system-index primaries are drained, so the ++// sole-copy check must still guard the rest. ++func TestPreparePodForDeleteDrainTwoNodes(t *testing.T) { ++ system := `[{"index":".opendistro_security","shard":"0","prirep":"p","state":"STARTED","node":"n1"}]` ++ tests := []struct { ++ name, shards string ++ want bool ++ }{ ++ {"sole copy blocks", `[{"index":"a","shard":"0","prirep":"p","state":"STARTED","node":"n0"},{"index":"a","shard":"0","prirep":"r","state":"UNASSIGNED","node":null}]`, false}, ++ {"replica elsewhere proceeds", `[{"index":"a","shard":"0","prirep":"p","state":"STARTED","node":"n0"},{"index":"a","shard":"0","prirep":"r","state":"STARTED","node":"n1"}]`, true}, ++ } ++ for _, tt := range tests { ++ t.Run(tt.name, func(t *testing.T) { ++ c, tr, _ := mockClient(t, `{}`, "all", tt.shards) ++ tr.RegisterResponder(http.MethodGet, `=~/_cat/indices/`, httpmock.NewStringResponder(404, `{}`)) ++ tr.RegisterResponder(http.MethodGet, `http://os.test:9200/_cat/indices/.opendistro_security`, httpmock.NewStringResponder(200, `[{"index":".opendistro_security"}]`)) ++ tr.RegisterResponder(http.MethodGet, `http://os.test:9200/_cat/shards/.opendistro_security`, httpmock.NewStringResponder(200, system)) ++ got, err := PreparePodForDelete(c, logr.Discard(), "n0", true, 2) ++ if err != nil { ++ t.Fatal(err) ++ } ++ if got != tt.want { ++ t.Errorf("got %v, want %v", got, tt.want) ++ } ++ }) ++ } ++} +diff --git a/opensearch-operator/pkg/reconcilers/rollingRestart.go b/opensearch-operator/pkg/reconcilers/rollingRestart.go +--- a/opensearch-operator/pkg/reconcilers/rollingRestart.go ++++ b/opensearch-operator/pkg/reconcilers/rollingRestart.go +@@ -174,7 +174,7 @@ + lg.Info("Only 2 data nodes and drain is set, some shards may not drain") + } + +- ready, message, err := services.CheckClusterStatusForRestart(r.osClient, r.instance.Spec.General.DrainDataNodes) ++ ready, message, err := services.CheckClusterStatusForRestart(r.osClient, r.instance.Spec.General.DrainDataNodes, dataCount) + if err != nil { + return ctrl.Result{}, err + } +diff --git a/opensearch-operator/pkg/reconcilers/upgrade.go b/opensearch-operator/pkg/reconcilers/upgrade.go +--- a/opensearch-operator/pkg/reconcilers/upgrade.go ++++ b/opensearch-operator/pkg/reconcilers/upgrade.go +@@ -303,7 +303,7 @@ + return nil + } + +- ready, condition, err := services.CheckClusterStatusForRestart(r.osClient, r.instance.Spec.General.DrainDataNodes) ++ ready, condition, err := services.CheckClusterStatusForRestart(r.osClient, r.instance.Spec.General.DrainDataNodes, dataCount) + if err != nil { + r.logger.Error(err, "Could not check opensearch cluster status") + conditions = append(conditions, "Could not check opensearch cluster status") diff --git a/packages/system/opensearch-operator/images/opensearch-operator/patches/skip-unusable-drain-exclusion.diff b/packages/system/opensearch-operator/images/opensearch-operator/patches/skip-unusable-drain-exclusion.diff new file mode 100644 index 000000000..c9602c3ca --- /dev/null +++ b/packages/system/opensearch-operator/images/opensearch-operator/patches/skip-unusable-drain-exclusion.diff @@ -0,0 +1,300 @@ +diff --git a/opensearch-operator/opensearch-gateway/responses/AllocationExplainResponse.go b/opensearch-operator/opensearch-gateway/responses/AllocationExplainResponse.go +new file mode 100644 +--- /dev/null ++++ b/opensearch-operator/opensearch-gateway/responses/AllocationExplainResponse.go +@@ -0,0 +1,13 @@ ++package responses ++ ++// AllocationExplainResponse carries the part of _cluster/allocation/explain this ++// operator reads. The endpoint returns a great deal more; everything else is ++// left out on purpose, so a field the operator never consults cannot break ++// decoding when OpenSearch renames it. ++type AllocationExplainResponse struct { ++ Index string `json:"index"` ++ Shard int `json:"shard"` ++ // CanMoveToOtherNode is "yes", "no" or "throttled", and is only present for a ++ // shard that is currently assigned. ++ CanMoveToOtherNode string `json:"can_move_to_other_node,omitempty"` ++} +diff --git a/opensearch-operator/opensearch-gateway/services/drain_progress_test.go b/opensearch-operator/opensearch-gateway/services/drain_progress_test.go +new file mode 100644 +--- /dev/null ++++ b/opensearch-operator/opensearch-gateway/services/drain_progress_test.go +@@ -0,0 +1,165 @@ ++package services ++ ++import ( ++ "encoding/json" ++ "io" ++ "net/http" ++ "strings" ++ "testing" ++ ++ "github.com/go-logr/logr" ++ "github.com/jarcoal/httpmock" ++) ++ ++// drainMockClient serves the endpoints a drain decision reads: health, cluster ++// settings (with the exclude list), the shard table, and one allocation ++// explanation per shard, keyed by "/". ++func drainMockClient(t *testing.T, health, excluded, catShards string, explains map[string]string) (*OsClusterClient, *httpmock.MockTransport, *[]string) { ++ t.Helper() ++ tr := httpmock.NewMockTransport() ++ for _, m := range []string{http.MethodGet, http.MethodHead} { ++ tr.RegisterResponder(m, `=~^http://os.test:9200/?$`, httpmock.NewStringResponder(200, `{"version":{"number":"2.0.0"}}`)) ++ } ++ tr.RegisterResponder(http.MethodGet, `=~/_cluster/health`, httpmock.NewStringResponder(200, health)) ++ tr.RegisterResponder(http.MethodGet, `=~/_cluster/settings`, httpmock.NewStringResponder(200, ++ `{"transient":{"cluster":{"routing":{"allocation":{"enable":"all","exclude":{"_name":"`+excluded+`"}}}}},"persistent":{}}`)) ++ puts := &[]string{} ++ tr.RegisterResponder(http.MethodPut, `=~/_cluster/settings`, func(r *http.Request) (*http.Response, error) { ++ b, _ := io.ReadAll(r.Body) ++ *puts = append(*puts, string(b)) ++ return httpmock.NewStringResponse(200, `{}`), nil ++ }) ++ tr.RegisterResponder(http.MethodGet, `=~/_cat/shards`, httpmock.NewStringResponder(200, catShards)) ++ tr.RegisterResponder(http.MethodGet, `=~/_cat/indices`, httpmock.NewStringResponder(200, `[]`)) ++ tr.RegisterResponder(http.MethodPost, `=~/_cluster/allocation/explain`, func(r *http.Request) (*http.Response, error) { ++ var req struct { ++ Index string `json:"index"` ++ Shard int `json:"shard"` ++ } ++ b, _ := io.ReadAll(r.Body) ++ if err := json.Unmarshal(b, &req); err != nil { ++ return httpmock.NewStringResponse(400, `{}`), nil ++ } ++ body, ok := explains[req.Index] ++ if !ok { ++ return httpmock.NewStringResponse(404, `{}`), nil ++ } ++ return httpmock.NewStringResponse(200, body), nil ++ }) ++ c, err := NewOsClusterClient("http://os.test:9200", "u", "p", WithTransport(tr)) ++ if err != nil { ++ t.Fatal(err) ++ } ++ return c, tr, puts ++} ++ ++func explainBody(canMove string) string { ++ return `{"index":"a","shard":0,"primary":true,"current_state":"started","can_remain_on_current_node":"no","can_move_to_other_node":"` + canMove + `","node_allocation_decisions":[]}` ++} ++ ++func TestDrainCanProceed(t *testing.T) { ++ onNode := `[{"index":"a","shard":"0","prirep":"p","state":"STARTED","node":"n0"}]` ++ tests := []struct { ++ name string ++ shards string ++ explains map[string]string ++ want bool ++ }{ ++ {"a shard that can move keeps the drain alive", onNode, map[string]string{"a": explainBody("yes")}, true}, ++ {"a shard with nowhere to go stops it", onNode, map[string]string{"a": explainBody("no")}, false}, ++ { ++ "one immovable shard is enough to stop it", ++ `[{"index":"a","shard":"0","prirep":"p","state":"STARTED","node":"n0"},{"index":"b","shard":"0","prirep":"p","state":"STARTED","node":"n0"}]`, ++ map[string]string{"a": explainBody("yes"), "b": explainBody("no")}, ++ false, ++ }, ++ {"an empty node has nothing to block it", `[]`, nil, true}, ++ {"shards on other nodes are not this node's problem", ++ `[{"index":"a","shard":"0","prirep":"p","state":"STARTED","node":"n1"}]`, ++ map[string]string{"a": explainBody("no")}, true}, ++ {"a relocating shard is already moving", ++ `[{"index":"a","shard":"0","prirep":"p","state":"RELOCATING","node":"n0 -> 10.0.0.2 id n2"}]`, ++ map[string]string{"a": explainBody("no")}, true}, ++ } ++ for _, tt := range tests { ++ t.Run(tt.name, func(t *testing.T) { ++ c, _, _ := drainMockClient(t, `{"status":"yellow"}`, "", tt.shards, tt.explains) ++ got, _, err := drainCanProceed(c, "n0") ++ if err != nil { ++ t.Fatal(err) ++ } ++ if got != tt.want { ++ t.Errorf("got %v, want %v", got, tt.want) ++ } ++ }) ++ } ++} ++ ++// The node holds a shard nothing else can take, so the drain will not finish. ++// The exclusion has to be released rather than held for as long as the restart ++// is stuck, and it must not be re-applied on the next pass either. ++func TestPreparePodForDeleteReleasesAnUnproductiveExclusion(t *testing.T) { ++ stuck := `[{"index":"a","shard":"0","prirep":"p","state":"STARTED","node":"n0"},{"index":"a","shard":"0","prirep":"r","state":"UNASSIGNED","node":null}]` ++ quietYellow := `{"status":"yellow","number_of_data_nodes":3,"unassigned_shards":1}` ++ ++ t.Run("an exclusion already in place is withdrawn", func(t *testing.T) { ++ c, _, puts := drainMockClient(t, quietYellow, "n0", stuck, map[string]string{"a": explainBody("no")}) ++ ready, err := PreparePodForDelete(c, logr.Discard(), "n0", true, 3) ++ if err != nil { ++ t.Fatal(err) ++ } ++ if ready { ++ t.Fatal("the pod is not safe to delete, it still holds a shard") ++ } ++ if len(*puts) != 1 { ++ t.Fatalf("expected exactly one settings write, got %d: %v", len(*puts), *puts) ++ } ++ if strings.Contains((*puts)[0], `"n0"`) { ++ t.Errorf("the write should clear the exclusion, got %s", (*puts)[0]) ++ } ++ }) ++ ++ t.Run("no exclusion is applied in the first place", func(t *testing.T) { ++ c, _, puts := drainMockClient(t, quietYellow, "", stuck, map[string]string{"a": explainBody("no")}) ++ ready, err := PreparePodForDelete(c, logr.Discard(), "n0", true, 3) ++ if err != nil { ++ t.Fatal(err) ++ } ++ if ready { ++ t.Fatal("the pod is not safe to delete, it still holds a shard") ++ } ++ if len(*puts) != 0 { ++ t.Errorf("nothing should be written when the node was never excluded, got %v", *puts) ++ } ++ }) ++} ++ ++// A drain that can still make progress keeps the behaviour it had: exclude the ++// node and wait for it to empty. ++func TestPreparePodForDeleteStillDrainsWhenItCan(t *testing.T) { ++ movable := `[{"index":"a","shard":"0","prirep":"p","state":"STARTED","node":"n0"},{"index":"a","shard":"0","prirep":"r","state":"STARTED","node":"n1"}]` ++ c, _, puts := drainMockClient(t, `{"status":"green","number_of_data_nodes":3}`, "", movable, map[string]string{"a": explainBody("yes")}) ++ ready, err := PreparePodForDelete(c, logr.Discard(), "n0", true, 3) ++ if err != nil { ++ t.Fatal(err) ++ } ++ if ready { ++ t.Fatal("the node is not empty yet") ++ } ++ if len(*puts) != 1 || !strings.Contains((*puts)[0], `n0`) { ++ t.Fatalf("expected the node to be excluded, writes were %v", *puts) ++ } ++} ++ ++// While shards are actually moving there is nothing to decide, and the ++// allocation explanation must not be asked for at all. ++func TestPreparePodForDeleteDoesNotExplainWhileShardsMove(t *testing.T) { ++ moving := `[{"index":"a","shard":"0","prirep":"p","state":"STARTED","node":"n0"},{"index":"a","shard":"0","prirep":"r","state":"UNASSIGNED","node":null}]` ++ c, tr, _ := drainMockClient(t, `{"status":"yellow","number_of_data_nodes":3,"relocating_shards":1}`, "n0", moving, map[string]string{"a": explainBody("no")}) ++ if _, err := PreparePodForDelete(c, logr.Discard(), "n0", true, 3); err != nil { ++ t.Fatal(err) ++ } ++ if n := tr.GetCallCountInfo()["POST =~/_cluster/allocation/explain"]; n != 0 { ++ t.Errorf("explain must not be called while the allocator is busy, got %d calls", n) ++ } ++} +diff --git a/opensearch-operator/opensearch-gateway/services/os_client.go b/opensearch-operator/opensearch-gateway/services/os_client.go +--- a/opensearch-operator/opensearch-gateway/services/os_client.go ++++ b/opensearch-operator/opensearch-gateway/services/os_client.go +@@ -171,6 +171,26 @@ func (client *OsClusterClient) CatIndices() ([]responses.CatIndicesResponse, err + return response, err + } + ++func (client *OsClusterClient) GetAllocationExplain(index string, shard int, primary bool) (responses.AllocationExplainResponse, error) { ++ body := map[string]interface{}{ ++ "index": index, ++ "shard": shard, ++ "primary": primary, ++ } ++ req := opensearchapi.ClusterAllocationExplainRequest{Body: opensearchutil.NewJSONReader(body)} ++ explainRes, err := req.Do(context.Background(), client.client) ++ var response responses.AllocationExplainResponse ++ if err != nil { ++ return response, err ++ } ++ defer helpers.SafeClose(explainRes.Body) ++ if explainRes.IsError() { ++ return response, fmt.Errorf("failed to get allocation explanation: %s", explainRes.String()) ++ } ++ err = json.NewDecoder(explainRes.Body).Decode(&response) ++ return response, err ++} ++ + func (client *OsClusterClient) CatShards(headers []string) ([]responses.CatShardsResponse, error) { + req := opensearchapi.CatShardsRequest{Format: "json", H: headers} + indicesRes, err := req.Do(context.Background(), client.client) +diff --git a/opensearch-operator/opensearch-gateway/services/os_data_service.go b/opensearch-operator/opensearch-gateway/services/os_data_service.go +--- a/opensearch-operator/opensearch-gateway/services/os_data_service.go ++++ b/opensearch-operator/opensearch-gateway/services/os_data_service.go +@@ -4,6 +4,7 @@ import ( + "context" + "encoding/json" + "fmt" ++ "strconv" + "strings" + + "github.com/google/go-cmp/cmp" +@@ -249,8 +250,70 @@ func ReactivateShardAllocation(service *OsClusterClient) error { + return nil + } + ++// drainCanProceed reports whether the allocator still has somewhere to put what ++// is left on nodeName. A drain waits for the node to empty, so one shard that ++// can be placed nowhere else is what turns that wait into a permanent one; the ++// reason for the first such shard is returned for the caller's log line. ++// ++// Only STARTED copies are asked about: a relocating one is already on its way ++// out, and an unassigned one is not on this node to begin with. ++func drainCanProceed(service *OsClusterClient, nodeName string) (bool, string, error) { ++ shards, err := service.CatShards([]string{"index", "shard", "prirep", "state", "node"}) ++ if err != nil { ++ return false, "", err ++ } ++ for _, shard := range shardsOnNodeFromResponse(shards, nodeName) { ++ if shard.State != "STARTED" { ++ continue ++ } ++ shardNum, err := strconv.Atoi(shard.Shard) ++ if err != nil { ++ continue ++ } ++ explain, err := service.GetAllocationExplain(shard.Index, shardNum, shard.PrimaryOrReplica == "p") ++ if err != nil { ++ return false, "", err ++ } ++ if strings.EqualFold(explain.CanMoveToOtherNode, "no") { ++ return false, fmt.Sprintf("%s[%s] has no other node to move to", shard.Index, shard.Shard), nil ++ } ++ } ++ return true, "", nil ++} ++ + func PreparePodForDelete(service *OsClusterClient, lg logr.Logger, podName string, drainNode bool, nodeCount int32) (bool, error) { + if drainNode { ++ // Excluding a node is only worth anything while the allocator can move its ++ // shards elsewhere. When it cannot, the node never empties, the restart ++ // waits for something that will not happen, and the exclusion keeps a data ++ // node out of allocation for the whole of it. Two data nodes are exempt: ++ // that path never waits for a full drain, only for system-index primaries. ++ // ++ // Asked only while nothing is moving, so a drain in progress pays nothing: ++ // the cost is one allocation explanation per started shard on the node, and ++ // it stops at the first shard that cannot move. ++ if nodeCount != 2 { ++ health, err := service.GetHealth() ++ if err != nil { ++ return false, err ++ } ++ if !hasShardActivity(health) { ++ canDrain, reason, err := drainCanProceed(service, podName) ++ if err != nil { ++ return false, err ++ } ++ if !canDrain { ++ // Withdraw an exclusion left by an earlier pass. With an empty ++ // exclude list this writes nothing. ++ if _, err := RemoveExcludeNodeHost(service, podName); err != nil { ++ return false, err ++ } ++ lg.Info(fmt.Sprintf("Not draining %s: %s. Leaving allocation as it is until that changes", podName, reason)) ++ return false, nil ++ } ++ } ++ } ++ + // If we are draining nodes then drain the working node + _, err := AppendExcludeNodeHost(service, podName) + if err != nil { diff --git a/packages/system/opensearch-operator/images/opensearch-operator/patches/timeout-cluster-api-calls.diff b/packages/system/opensearch-operator/images/opensearch-operator/patches/timeout-cluster-api-calls.diff new file mode 100644 index 000000000..d0230dacf --- /dev/null +++ b/packages/system/opensearch-operator/images/opensearch-operator/patches/timeout-cluster-api-calls.diff @@ -0,0 +1,783 @@ +diff --git a/opensearch-operator/opensearch-gateway/services/http_request.go b/opensearch-operator/opensearch-gateway/services/http_request.go +index 724ccf8..8ef9a5e 100644 +--- a/opensearch-operator/opensearch-gateway/services/http_request.go ++++ b/opensearch-operator/opensearch-gateway/services/http_request.go +@@ -17,16 +17,7 @@ func doHTTPGet(ctx context.Context, client *opensearch.Client, path strings.Buil + return nil, err + } + +- if ctx != nil { +- req = req.WithContext(ctx) +- } +- +- res, err := client.Perform(req) +- if err != nil { +- return nil, err +- } +- +- return &opensearchapi.Response{StatusCode: res.StatusCode, Body: res.Body, Header: res.Header}, nil ++ return performRequest(ctx, client, req) + } + + // doHTTPPost performs a HTTP POST request +@@ -36,17 +27,9 @@ func doHTTPPost(ctx context.Context, client *opensearch.Client, path strings.Bui + return nil, err + } + +- if ctx != nil { +- req = req.WithContext(ctx) +- } + req.Header.Add(headerContentType, jsonContentHeader) + +- res, err := client.Perform(req) +- if err != nil { +- return nil, err +- } +- +- return &opensearchapi.Response{StatusCode: res.StatusCode, Body: res.Body, Header: res.Header}, nil ++ return performRequest(ctx, client, req) + } + + // doHTTPHead performs a HTTP HEAD request +@@ -56,16 +39,7 @@ func doHTTPHead(ctx context.Context, client *opensearch.Client, path strings.Bui + return nil, err + } + +- if ctx != nil { +- req = req.WithContext(ctx) +- } +- +- res, err := client.Perform(req) +- if err != nil { +- return nil, err +- } +- +- return &opensearchapi.Response{StatusCode: res.StatusCode, Body: res.Body, Header: res.Header}, nil ++ return performRequest(ctx, client, req) + } + + // doHTTPPut performs a HTTP PUT request +@@ -75,17 +49,9 @@ func doHTTPPut(ctx context.Context, client *opensearch.Client, path strings.Buil + return nil, err + } + +- if ctx != nil { +- req = req.WithContext(ctx) +- } + req.Header.Add(headerContentType, jsonContentHeader) + +- res, err := client.Perform(req) +- if err != nil { +- return nil, err +- } +- +- return &opensearchapi.Response{StatusCode: res.StatusCode, Body: res.Body, Header: res.Header}, nil ++ return performRequest(ctx, client, req) + } + + // doHTTPDelete performs a HTTP DELETE request +@@ -95,14 +61,51 @@ func doHTTPDelete(ctx context.Context, client *opensearch.Client, path strings.B + return nil, err + } + +- if ctx != nil { +- req = req.WithContext(ctx) ++ return performRequest(ctx, client, req) ++} ++ ++// performRequest sends req and bounds the whole exchange, the body read ++// included, with requestTimeout. ++// ++// The deadline has to outlive this function, because the response body goes ++// back to the caller still open and cancelling here would fail their read. It ++// therefore rides on the body and is released when the body is closed, which is ++// how http.Client applies its own Timeout. A caller that never closes the body ++// holds the timer until the deadline passes, and the deadline then closes the ++// connection on its behalf. ++// ++// boundedTransport already bounds each request that goes out, and this is the ++// deadline for the series: opensearch-go retries a request up to three more ++// times on 502, 503 and 504, and the transport's deadline starts again on every ++// one of them. Nothing on the reconcile path puts a deadline on the context it ++// passes in, so without this the series has no bound. ++func performRequest(ctx context.Context, client *opensearch.Client, req *http.Request) (*opensearchapi.Response, error) { ++ if ctx == nil { ++ ctx = context.Background() + } ++ ctx, cancel := context.WithTimeout(ctx, requestTimeout) + +- res, err := client.Perform(req) ++ res, err := client.Perform(req.WithContext(ctx)) + if err != nil { ++ cancel() + return nil, err + } + +- return &opensearchapi.Response{StatusCode: res.StatusCode, Body: res.Body, Header: res.Header}, nil ++ return &opensearchapi.Response{ ++ StatusCode: res.StatusCode, ++ Body: &deadlineBody{ReadCloser: res.Body, cancel: cancel}, ++ Header: res.Header, ++ }, nil ++} ++ ++// deadlineBody releases its request's deadline when the body is closed. ++type deadlineBody struct { ++ io.ReadCloser ++ cancel context.CancelFunc ++} ++ ++func (b *deadlineBody) Close() error { ++ err := b.ReadCloser.Close() ++ b.cancel() ++ return err + } +diff --git a/opensearch-operator/opensearch-gateway/services/os_client.go b/opensearch-operator/opensearch-gateway/services/os_client.go +index 741ea4a..2496c54 100644 +--- a/opensearch-operator/opensearch-gateway/services/os_client.go ++++ b/opensearch-operator/opensearch-gateway/services/os_client.go +@@ -8,6 +8,7 @@ import ( + "github.com/Opster/opensearch-k8s-operator/opensearch-operator/pkg/helpers" + "io" + "k8s.io/utils/ptr" ++ "net" + "net/http" + "strconv" + "strings" +@@ -42,6 +43,100 @@ var AdditionalSystemIndices = []string{ + ".replication-metadata-store", + } + ++// A request to a cluster's HTTP API has no bound of its own: a fresh ++// http.Transport carries no dial, handshake or response-header timeout, the ++// client is built without an http.Client, and the Timeout field on a request ++// type is the server-side query parameter, which only helps once something ++// answers. The operator runs one worker per controller, so a single call that ++// never returns stops every OpenSearchCluster from being reconciled, and the ++// finalizer on the next deletion waits out its own termination timeout with ++// nothing in the log to say why. ++// ++// requestTimeout is applied at two levels, because one of them alone leaves a ++// gap. boundedTransport puts it on every request that goes out, which is the ++// only level that reaches the requests opensearch-go builds for itself. That ++// bounds an attempt, and opensearch-go retries a request up to three times on ++// 502, 503 and 504, so the calls below carry it a second time for the series: ++// through requestContext where the call decodes the answer before it returns, ++// and through performRequest where the still-open body goes back to the caller. ++// ++// These are variables rather than constants so the tests can shorten them. ++var ( ++ // requestTimeout bounds one exchange with a cluster, from the dial to the ++ // last byte of the body. Every call answers in well under a second on a ++ // healthy cluster, and the controllers requeue on the order of tens of ++ // seconds, so a call still running at this point is not going to produce an ++ // answer worth waiting for. ++ requestTimeout = 30 * time.Second ++ ++ // connectTimeout bounds getting a connection up: the dial and the TLS ++ // handshake, each separately. Both sit inside requestTimeout, which would ++ // end the attempt anyway; what this buys is an unreachable node failing in ++ // a third of the budget, with an error that names what went wrong. ++ connectTimeout = 10 * time.Second ++) ++ ++// requestContext bounds a single call. The caller must cancel it only once it ++// is done with the response body, which for the calls that use it is when the ++// body has been decoded: cancelling earlier fails the read. ++// ++// It hangs off context.Background() rather than the caller's context, which the ++// methods below do not take: threading one through would change every signature ++// and every call site of a patch meant to be dropped. The cost is that an ++// operator shutting down waits out a call it could have abandoned. ++func requestContext() (context.Context, context.CancelFunc) { ++ return context.WithTimeout(context.Background(), requestTimeout) ++} ++ ++// clusterDialer is the dialer the transport below dials with. It is built here ++// rather than inline so the bound on it can be read back: DialContext is a ++// function on the transport, and a timeout closed over inside one is not ++// something a test can assert. ++func clusterDialer() *net.Dialer { ++ return &net.Dialer{Timeout: connectTimeout} ++} ++ ++// clusterTransport is the transport used when the caller supplies none. ++func clusterTransport() *http.Transport { ++ return &http.Transport{ ++ TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, ++ // These options are needed as otherwise connections would be kept and leak memory ++ // Connection reuse is not really possible due to each reconcile run being independent ++ DisableKeepAlives: true, ++ MaxIdleConns: 1, ++ DialContext: clusterDialer().DialContext, ++ TLSHandshakeTimeout: connectTimeout, ++ } ++} ++ ++// boundedTransport puts requestTimeout on every request that goes through it. ++// It is the only level that reaches the requests opensearch-go makes for ++// itself: before a client's first request the library runs a product check, ++// which builds its own request with a context.Background() and decodes the body ++// of the answer, so a cluster that flushes the headers and then stops holds the ++// check, and with it the reconcile, for as long as the process lives. Each ++// reconcile builds its own client, so each one runs that check. ++// ++// The deadline outlives RoundTrip, because the body goes back to the caller ++// still open and cancelling here would fail their read. It rides on the body ++// and is released by Close, the same way http.Client applies its own Timeout. ++type boundedTransport struct { ++ http.RoundTripper ++} ++ ++func (t boundedTransport) RoundTrip(req *http.Request) (*http.Response, error) { ++ ctx, cancel := context.WithTimeout(req.Context(), requestTimeout) ++ ++ res, err := t.RoundTripper.RoundTrip(req.WithContext(ctx)) ++ if err != nil || res.Body == nil { ++ cancel() ++ return res, err ++ } ++ ++ res.Body = &deadlineBody{ReadCloser: res.Body, cancel: cancel} ++ return res, nil ++} ++ + type OsClusterClient struct { + OsClusterClientOptions + client *opensearch.Client +@@ -74,13 +169,7 @@ func NewOsClusterClient(clusterUrl string, username string, password string, opt + if options.transport != nil { + return options.transport + } +- return &http.Transport{ +- TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, +- // These options are needed as otherwise connections would be kept and leak memory +- // Connection reuse is not really possible due to each reconcile run being independent +- DisableKeepAlives: true, +- MaxIdleConns: 1, +- } ++ return clusterTransport() + }(), + Addresses: []string{clusterUrl}, + Username: username, +@@ -97,13 +186,23 @@ func NewOsClusterClient(clusterUrl string, username string, password string, opt + } + + func NewOsClusterClientFromConfig(config opensearch.Config) (*OsClusterClient, error) { ++ // Every request a client makes goes through its RoundTripper, the ones ++ // opensearch-go makes for itself included, so this is the one place a ++ // deadline reaches all of them. Both ways into this package arrive here. ++ if config.Transport == nil { ++ config.Transport = http.DefaultTransport ++ } ++ config.Transport = boundedTransport{config.Transport} ++ + service := new(OsClusterClient) + client, err := opensearch.NewClient(config) + if err == nil { + service.client = client + } + pingReq := opensearchapi.PingRequest{} +- pingRes, err := pingReq.Do(context.Background(), client) ++ ctx, cancel := requestContext() ++ defer cancel() ++ pingRes, err := pingReq.Do(ctx, client) + if err == nil && pingRes.StatusCode == 200 { + mainPageResponse, err := MainPage(client) + if err == nil { +@@ -115,7 +214,9 @@ func NewOsClusterClientFromConfig(config opensearch.Config) (*OsClusterClient, e + + func MainPage(client *opensearch.Client) (responses.MainResponse, error) { + req := opensearchapi.InfoRequest{} +- infoRes, err := req.Do(context.Background(), client) ++ ctx, cancel := requestContext() ++ defer cancel() ++ infoRes, err := req.Do(ctx, client) + var response responses.MainResponse + if err == nil { + defer helpers.SafeClose(infoRes.Body) +@@ -128,7 +229,9 @@ func (client *OsClusterClient) GetHealth() (responses.ClusterHealthResponse, err + req := opensearchapi.ClusterHealthRequest{ + Level: "indices", + } +- catNodesRes, err := req.Do(context.Background(), client.client) ++ ctx, cancel := requestContext() ++ defer cancel() ++ catNodesRes, err := req.Do(ctx, client.client) + var response responses.ClusterHealthResponse + if err == nil { + defer helpers.SafeClose(catNodesRes.Body) +@@ -139,7 +242,9 @@ func (client *OsClusterClient) GetHealth() (responses.ClusterHealthResponse, err + + func (client *OsClusterClient) CatNodes() ([]responses.CatNodesResponse, error) { + req := opensearchapi.CatNodesRequest{Format: "json"} +- catNodesRes, err := req.Do(context.Background(), client.client) ++ ctx, cancel := requestContext() ++ defer cancel() ++ catNodesRes, err := req.Do(ctx, client.client) + var response []responses.CatNodesResponse + if err == nil { + defer helpers.SafeClose(catNodesRes.Body) +@@ -150,7 +255,9 @@ func (client *OsClusterClient) CatNodes() ([]responses.CatNodesResponse, error) + + func (client *OsClusterClient) NodesStats() (responses.NodesStatsResponse, error) { + req := opensearchapi.NodesStatsRequest{} +- catNodesRes, err := req.Do(context.Background(), client.client) ++ ctx, cancel := requestContext() ++ defer cancel() ++ catNodesRes, err := req.Do(ctx, client.client) + var response responses.NodesStatsResponse + if err == nil { + defer helpers.SafeClose(catNodesRes.Body) +@@ -161,7 +268,9 @@ func (client *OsClusterClient) NodesStats() (responses.NodesStatsResponse, error + + func (client *OsClusterClient) CatIndices() ([]responses.CatIndicesResponse, error) { + req := opensearchapi.CatIndicesRequest{Format: "json"} +- indicesRes, err := req.Do(context.Background(), client.client) ++ ctx, cancel := requestContext() ++ defer cancel() ++ indicesRes, err := req.Do(ctx, client.client) + var response []responses.CatIndicesResponse + if err != nil { + return response, err +@@ -178,7 +287,9 @@ func (client *OsClusterClient) GetAllocationExplain(index string, shard int, pri + "primary": primary, + } + req := opensearchapi.ClusterAllocationExplainRequest{Body: opensearchutil.NewJSONReader(body)} +- explainRes, err := req.Do(context.Background(), client.client) ++ ctx, cancel := requestContext() ++ defer cancel() ++ explainRes, err := req.Do(ctx, client.client) + var response responses.AllocationExplainResponse + if err != nil { + return response, err +@@ -193,7 +304,9 @@ func (client *OsClusterClient) GetAllocationExplain(index string, shard int, pri + + func (client *OsClusterClient) CatShards(headers []string) ([]responses.CatShardsResponse, error) { + req := opensearchapi.CatShardsRequest{Format: "json", H: headers} +- indicesRes, err := req.Do(context.Background(), client.client) ++ ctx, cancel := requestContext() ++ defer cancel() ++ indicesRes, err := req.Do(ctx, client.client) + var response []responses.CatShardsResponse + if err != nil { + return response, err +@@ -209,7 +322,9 @@ func (client *OsClusterClient) CatNamedIndicesShards(headers []string, indices [ + Format: "json", + H: headers, + } +- indicesRes, err := req.Do(context.Background(), client.client) ++ ctx, cancel := requestContext() ++ defer cancel() ++ indicesRes, err := req.Do(ctx, client.client) + var response []responses.CatShardsResponse + if err != nil { + return response, err +@@ -221,7 +336,9 @@ func (client *OsClusterClient) CatNamedIndicesShards(headers []string, indices [ + + func (client *OsClusterClient) GetClusterSettings() (responses.ClusterSettingsResponse, error) { + req := opensearchapi.ClusterGetSettingsRequest{Pretty: true} +- settingsRes, err := req.Do(context.Background(), client.client) ++ ctx, cancel := requestContext() ++ defer cancel() ++ settingsRes, err := req.Do(ctx, client.client) + var response responses.ClusterSettingsResponse + if err != nil { + return response, err +@@ -235,7 +352,9 @@ func (client *OsClusterClient) GetFlatClusterSettings() (responses.FlatClusterSe + req := opensearchapi.ClusterGetSettingsRequest{ + FlatSettings: ptr.To(true), + } +- settingsRes, err := req.Do(context.Background(), client.client) ++ ctx, cancel := requestContext() ++ defer cancel() ++ settingsRes, err := req.Do(ctx, client.client) + var response responses.FlatClusterSettingsResponse + if err != nil { + return response, err +@@ -253,7 +372,9 @@ func (client *OsClusterClient) GetFlatClusterSettings() (responses.FlatClusterSe + func (client *OsClusterClient) PutClusterSettings(settings responses.ClusterSettingsResponse) (responses.ClusterSettingsResponse, error) { + body := opensearchutil.NewJSONReader(settings) + req := opensearchapi.ClusterPutSettingsRequest{Body: body} +- settingsRes, err := req.Do(context.Background(), client.client) ++ ctx, cancel := requestContext() ++ defer cancel() ++ settingsRes, err := req.Do(ctx, client.client) + var response responses.ClusterSettingsResponse + if err != nil { + return response, err +@@ -266,7 +387,9 @@ func (client *OsClusterClient) PutClusterSettings(settings responses.ClusterSett + func (client *OsClusterClient) ReRouteShard(rerouteJson string) (responses.ClusterRerouteResponse, error) { + body := strings.NewReader(rerouteJson) + req := opensearchapi.ClusterRerouteRequest{Body: body} +- settingsRes, err := req.Do(context.Background(), client.client) ++ ctx, cancel := requestContext() ++ defer cancel() ++ settingsRes, err := req.Do(ctx, client.client) + var response responses.ClusterRerouteResponse + if err != nil { + return response, err +@@ -282,7 +405,9 @@ func (client *OsClusterClient) GetClusterHealth() (responses.ClusterHealthRespon + } + + health := responses.ClusterHealthResponse{} +- resp, err := req.Do(context.Background(), client.client) ++ ctx, cancel := requestContext() ++ defer cancel() ++ resp, err := req.Do(ctx, client.client) + if err != nil { + return health, err + } +@@ -303,7 +428,9 @@ func (client *OsClusterClient) IndexExists(indexName string) (bool, error) { + indexName, + }, + } +- indicesRes, err := req.Do(context.Background(), client.client) ++ ctx, cancel := requestContext() ++ defer cancel() ++ indicesRes, err := req.Do(ctx, client.client) + if err != nil { + return false, err + } +diff --git a/opensearch-operator/opensearch-gateway/services/os_client_timeout_test.go b/opensearch-operator/opensearch-gateway/services/os_client_timeout_test.go +new file mode 100644 +index 0000000..4a8ce1f +--- /dev/null ++++ b/opensearch-operator/opensearch-gateway/services/os_client_timeout_test.go +@@ -0,0 +1,336 @@ ++package services ++ ++import ( ++ "context" ++ "io" ++ "net" ++ "net/http" ++ "net/http/httptest" ++ "runtime" ++ "strings" ++ "sync" ++ "testing" ++ "time" ++ ++ "github.com/opensearch-project/opensearch-go" ++) ++ ++// blockedTransport is a cluster that has stopped answering: the request goes ++// out and nothing comes back until whoever sent it gives up. ++// ++// It answers the root path, and only the root path, because opensearch-go ++// checks the product it is talking to on a client's first request and gives ++// that check a context.Background() of its own, inside the library, where a ++// deadline set at the call site cannot reach it. This transport is handed ++// straight to opensearch.NewClient rather than going through ++// NewOsClusterClient, so boundedTransport is not in the way here and the ++// deadline under test is the one the call carries. ++type blockedTransport struct{} ++ ++func (blockedTransport) RoundTrip(req *http.Request) (*http.Response, error) { ++ if req.URL.Path == "/" { ++ return &http.Response{ ++ StatusCode: http.StatusOK, ++ Header: http.Header{"Content-Type": []string{"application/json"}}, ++ Body: io.NopCloser(strings.NewReader(`{"version":{"number":"2.0.0","distribution":"opensearch"}}`)), ++ Request: req, ++ }, nil ++ } ++ <-req.Context().Done() ++ return nil, req.Context().Err() ++} ++ ++// callIsAnsweredOrAbandoned runs call in the background and fails the test if it ++// is still running after grace. Waiting in the test rather than in the call is ++// what turns an unbounded call into a failure instead of a test run that hangs ++// until the CI job is killed. ++func callIsAnsweredOrAbandoned(t *testing.T, grace time.Duration, what string, call func() error) { ++ t.Helper() ++ done := make(chan error, 1) ++ go func() { done <- call() }() ++ select { ++ case err := <-done: ++ if err == nil { ++ t.Fatalf("%s: expected the call to fail once its deadline passed", what) ++ } ++ case <-time.After(grace): ++ t.Fatalf("%s: still running after %s, so the call is unbounded", what, grace) ++ } ++} ++ ++// silentListener accepts connections and answers nothing on them. The accepted ++// connections are returned rather than dropped because an unreachable net.Conn ++// is closed by the garbage collector: net.netFD carries a finalizer that closes ++// the descriptor, so a dropped connection turns this into a server that resets ++// the connection, and a request against it then fails for a reason that has ++// nothing to do with the timeout under test. ++func silentListener(t *testing.T) (net.Listener, *[]net.Conn) { ++ t.Helper() ++ ln, err := net.Listen("tcp", "127.0.0.1:0") ++ if err != nil { ++ t.Fatal(err) ++ } ++ t.Cleanup(func() { _ = ln.Close() }) ++ ++ var mu sync.Mutex ++ accepted := &[]net.Conn{} ++ go func() { ++ for { ++ conn, err := ln.Accept() ++ if err != nil { ++ return ++ } ++ mu.Lock() ++ *accepted = append(*accepted, conn) ++ mu.Unlock() ++ } ++ }() ++ ++ // Collect throughout, so that a connection this listener stops holding is ++ // closed while the test is still waiting rather than after it. ++ stop := make(chan struct{}) ++ t.Cleanup(func() { close(stop) }) ++ go func() { ++ for { ++ select { ++ case <-stop: ++ return ++ default: ++ runtime.GC() ++ time.Sleep(10 * time.Millisecond) ++ } ++ } ++ }() ++ ++ return ln, accepted ++} ++ ++// keepReachable is the deferred hold that keeps the accepted connections alive ++// to the end of the test, and the reason silentListener forces a collection on ++// every accept: with the connections dropped instead, that collection closes ++// them and the test passes with the bound it exists to pin removed. It holds ++// the slice without reading it, because the accept goroutine writes the header ++// under a lock this side has no access to, and reading it here is a data race. ++func keepReachable(conns *[]net.Conn) { ++ runtime.KeepAlive(conns) ++} ++ ++func TestCallToAClusterThatNeverAnswersGivesUp(t *testing.T) { ++ old := requestTimeout ++ requestTimeout = 200 * time.Millisecond ++ t.Cleanup(func() { requestTimeout = old }) ++ ++ raw, err := opensearch.NewClient(opensearch.Config{ ++ Addresses: []string{"http://os.test:9200"}, ++ Transport: blockedTransport{}, ++ }) ++ if err != nil { ++ t.Fatal(err) ++ } ++ client := &OsClusterClient{client: raw} ++ ++ callIsAnsweredOrAbandoned(t, 10*time.Second, "GetHealth", func() error { ++ _, err := client.GetHealth() ++ return err ++ }) ++ callIsAnsweredOrAbandoned(t, 10*time.Second, "CatNodes", func() error { ++ _, err := client.CatNodes() ++ return err ++ }) ++} ++ ++func TestTransportGivesUpOnAServerThatAcceptsAndSaysNothing(t *testing.T) { ++ old := requestTimeout ++ requestTimeout = 200 * time.Millisecond ++ t.Cleanup(func() { requestTimeout = old }) ++ ++ ln, accepted := silentListener(t) ++ defer keepReachable(accepted) ++ ++ req, err := http.NewRequest(http.MethodGet, "http://"+ln.Addr().String()+"/", nil) ++ if err != nil { ++ t.Fatal(err) ++ } ++ inner := clusterTransport() ++ t.Cleanup(inner.CloseIdleConnections) ++ transport := boundedTransport{inner} ++ ++ callIsAnsweredOrAbandoned(t, 10*time.Second, "GET through the operator's transport", func() error { ++ res, err := transport.RoundTrip(req) ++ if res != nil { ++ _ = res.Body.Close() ++ } ++ return err ++ }) ++} ++ ++// TestTransportCarriesConnectionTimeouts pins the bounds the test above cannot ++// reach. A dial that hangs needs an address that neither answers nor refuses, ++// and a TLS handshake that hangs needs a server that stops mid-handshake: ++// neither is something a test can arrange on loopback. Both are therefore ++// asserted by value, the dial through the dialer the transport is built from, ++// since a dialer reaches the transport as a function and a timeout closed over ++// inside one cannot be read back. ++func TestTransportCarriesConnectionTimeouts(t *testing.T) { ++ transport := clusterTransport() ++ ++ if transport.DialContext == nil { ++ t.Error("DialContext is unset, so the transport dials with no timeout at all") ++ } ++ if dialer := clusterDialer(); dialer.Timeout != connectTimeout { ++ t.Errorf("the dialer's Timeout is %s, want %s", dialer.Timeout, connectTimeout) ++ } ++ if transport.TLSHandshakeTimeout != connectTimeout { ++ t.Errorf("TLSHandshakeTimeout is %s, want %s", transport.TLSHandshakeTimeout, connectTimeout) ++ } ++} ++ ++// answeringServer answers the two requests a new client makes before anything ++// else: the ping, and the product check opensearch-go runs on a client's first ++// request. Every other path is handed to serve. ++func answeringServer(t *testing.T, serve http.HandlerFunc) *httptest.Server { ++ t.Helper() ++ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { ++ if r.URL.Path == "/" { ++ _, _ = io.WriteString(w, `{"version":{"number":"2.0.0","distribution":"opensearch"}}`) ++ return ++ } ++ serve(w, r) ++ })) ++ t.Cleanup(srv.Close) ++ return srv ++} ++ ++// TestBodyThatStopsHalfwayIsBounded covers the calls that take a context from ++// the caller: nothing on the reconcile path puts a deadline on that context, ++// and the transport's ResponseHeaderTimeout stops counting the moment the ++// headers arrive, so a body that starts and then stops is bounded by the ++// deadline the request carries or by nothing. ++func TestBodyThatStopsHalfwayIsBounded(t *testing.T) { ++ oldRequest := requestTimeout ++ requestTimeout = 200 * time.Millisecond ++ t.Cleanup(func() { requestTimeout = oldRequest }) ++ ++ stall := make(chan struct{}) ++ srv := answeringServer(t, func(w http.ResponseWriter, r *http.Request) { ++ w.Header().Set("Content-Length", "100") ++ w.WriteHeader(http.StatusOK) ++ w.(http.Flusher).Flush() ++ <-stall ++ }) ++ t.Cleanup(func() { close(stall) }) ++ ++ client, err := NewOsClusterClient(srv.URL, "u", "p") ++ if err != nil { ++ t.Fatal(err) ++ } ++ ++ callIsAnsweredOrAbandoned(t, 10*time.Second, "reading a body that stopped halfway", func() error { ++ res, err := client.GetIndices(context.Background(), "test-*") ++ if err != nil { ++ return err ++ } ++ defer func() { _ = res.Body.Close() }() ++ _, err = io.ReadAll(res.Body) ++ return err ++ }) ++} ++ ++// TestBodyOutlivesTheCallThatFetchedIt is the other half: the deadline is ++// released by the body's Close and not by the call's return, because these ++// calls hand the body back still open and the caller reads it afterwards. ++func TestBodyOutlivesTheCallThatFetchedIt(t *testing.T) { ++ const chunk = 64 << 10 ++ const chunks = 16 ++ ++ srv := answeringServer(t, func(w http.ResponseWriter, r *http.Request) { ++ w.Header().Set("Content-Type", "application/json") ++ w.WriteHeader(http.StatusOK) ++ for i := 0; i < chunks; i++ { ++ _, _ = w.Write([]byte(strings.Repeat("x", chunk))) ++ w.(http.Flusher).Flush() ++ time.Sleep(5 * time.Millisecond) ++ } ++ }) ++ ++ client, err := NewOsClusterClient(srv.URL, "u", "p") ++ if err != nil { ++ t.Fatal(err) ++ } ++ ++ res, err := client.GetIndices(context.Background(), "test-*") ++ if err != nil { ++ t.Fatal(err) ++ } ++ defer func() { _ = res.Body.Close() }() ++ ++ body, err := io.ReadAll(res.Body) ++ if err != nil { ++ t.Fatalf("reading the body after the call returned: %v", err) ++ } ++ if len(body) != chunk*chunks { ++ t.Errorf("read %d bytes of the body, want %d", len(body), chunk*chunks) ++ } ++} ++ ++// TestNewClientGivesUpWhenTheProductCheckStalls covers the one request the call ++// site cannot reach: opensearch-go runs a product check before the first ++// request a client makes, builds it with a context.Background() of its own and ++// decodes its body, so a cluster that flushes the headers of that response and ++// then stops holds the check for as long as the process lives. The check runs ++// per client, and the operator builds one per reconcile. ++func TestNewClientGivesUpWhenTheProductCheckStalls(t *testing.T) { ++ old := requestTimeout ++ requestTimeout = 200 * time.Millisecond ++ t.Cleanup(func() { requestTimeout = old }) ++ ++ stall := make(chan struct{}) ++ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { ++ w.Header().Set("Content-Type", "application/json") ++ w.Header().Set("Content-Length", "57") ++ w.WriteHeader(http.StatusOK) ++ w.(http.Flusher).Flush() ++ <-stall ++ })) ++ t.Cleanup(srv.Close) ++ t.Cleanup(func() { close(stall) }) ++ ++ callIsAnsweredOrAbandoned(t, 10*time.Second, "a new client whose product check stalls", func() error { ++ _, err := NewOsClusterClient(srv.URL, "u", "p") ++ return err ++ }) ++} ++ ++// TestARetriedCallIsBoundedAsAWhole covers what a per-request deadline does not ++// reach: opensearch-go retries a request up to three more times on 502, 503 and ++// 504, and a bound that only sits on the transport starts again on each of ++// them, so a proxy that answers 504 slowly holds the call for four times the ++// budget. The deadline the call carries is what bounds the series. ++func TestARetriedCallIsBoundedAsAWhole(t *testing.T) { ++ const perAttempt = 200 * time.Millisecond ++ ++ old := requestTimeout ++ requestTimeout = 300 * time.Millisecond ++ t.Cleanup(func() { requestTimeout = old }) ++ ++ srv := answeringServer(t, func(w http.ResponseWriter, r *http.Request) { ++ time.Sleep(perAttempt) ++ w.WriteHeader(http.StatusServiceUnavailable) ++ }) ++ ++ client, err := NewOsClusterClient(srv.URL, "u", "p") ++ if err != nil { ++ t.Fatal(err) ++ } ++ ++ start := time.Now() ++ res, err := client.GetIndices(context.Background(), "test-*") ++ elapsed := time.Since(start) ++ if err == nil { ++ _ = res.Body.Close() ++ t.Fatal("expected the call to fail once its deadline passed, not to run the retries out") ++ } ++ if elapsed > 3*perAttempt { ++ t.Errorf("the call took %s, which is more than one attempt plus its deadline: the series is unbounded", elapsed) ++ } ++} diff --git a/packages/system/opensearch-operator/tests/dns_base_test.yaml b/packages/system/opensearch-operator/tests/dns_base_test.yaml new file mode 100644 index 000000000..0b2c758fc --- /dev/null +++ b/packages/system/opensearch-operator/tests/dns_base_test.yaml @@ -0,0 +1,40 @@ +suite: opensearch-operator DNS base follows the value set on the umbrella key + +release: + name: opensearch-operator + namespace: cozy-opensearch-operator + +# The platform carries the cluster domain to this package under the subchart key +# in the shared values Secret (packages/core/platform/templates/apps.yaml). The +# vendored chart reads it as manager.dnsBase and hands it to the manager as +# DNS_BASE, from which the operator builds the securityconfig job target, its own +# OpenSearch API client URL, the Dashboards host and the SANs it writes into node +# certificates. Rendered without the Secret the package stays on the upstream +# cluster.local default. + +tests: + - it: passes the domain set on the umbrella key through to the manager env + set: + opensearch-operator.manager.dnsBase: example.test + template: charts/opensearch-operator/templates/opensearch-operator-controller-manager-deployment.yaml + documentSelector: + path: kind + value: Deployment + asserts: + - contains: + path: spec.template.spec.containers[1].env + content: + name: DNS_BASE + value: example.test + + - it: keeps the upstream default when the platform sets nothing + template: charts/opensearch-operator/templates/opensearch-operator-controller-manager-deployment.yaml + documentSelector: + path: kind + value: Deployment + asserts: + - contains: + path: spec.template.spec.containers[1].env + content: + name: DNS_BASE + value: cluster.local diff --git a/packages/system/opensearch-operator/values.yaml b/packages/system/opensearch-operator/values.yaml index d03fc6b59..bd4069cce 100644 --- a/packages/system/opensearch-operator/values.yaml +++ b/packages/system/opensearch-operator/values.yaml @@ -8,8 +8,8 @@ opensearch-operator: replicaCount: 1 # Enable cluster-wide mode to watch all namespaces watchNamespace: "" - # Built in-tree from images/opensearch-operator, which carries the - # bootstrap voting-exclusion patch. Without this block the vendored chart + # Built in-tree from images/opensearch-operator, which carries the patches + # under its patches/ directory. Without this block the vendored chart # falls back to opensearchproject/opensearch-operator at the chart's # appVersion, which is the unpatched upstream build, and the reference stays # outside the first-party set hack/lib/image-refs.sh collects for promote, diff --git a/packages/system/vertical-pod-autoscaler/templates/vpa-for-vpa.yaml b/packages/system/vertical-pod-autoscaler/templates/vpa-for-vpa.yaml index a38ae42ef..dc9a5ff9b 100644 --- a/packages/system/vertical-pod-autoscaler/templates/vpa-for-vpa.yaml +++ b/packages/system/vertical-pod-autoscaler/templates/vpa-for-vpa.yaml @@ -51,7 +51,7 @@ spec: recommender-name: vpa-for-vpa resources: limits: - memory: 512Mi + memory: 1Gi requests: cpu: 100m memory: 512Mi diff --git a/packages/system/vm-instance-rd/Makefile b/packages/system/vm-instance-rd/Makefile index 621d74bd3..b7d7d6221 100644 --- a/packages/system/vm-instance-rd/Makefile +++ b/packages/system/vm-instance-rd/Makefile @@ -2,3 +2,7 @@ export NAME=vm-instance-rd export NAMESPACE=cozy-system include ../../../hack/package.mk + +.PHONY: test +test: + helm unittest . diff --git a/packages/system/vm-instance-rd/cozyrds/vm-instance.yaml b/packages/system/vm-instance-rd/cozyrds/vm-instance.yaml index cad2cf052..2d7d45b24 100644 --- a/packages/system/vm-instance-rd/cozyrds/vm-instance.yaml +++ b/packages/system/vm-instance-rd/cozyrds/vm-instance.yaml @@ -2,6 +2,10 @@ apiVersion: cozystack.io/v1alpha1 kind: ApplicationDefinition metadata: name: vm-instance + annotations: + # KubeVirt leaves a VirtualMachine's status.observedGeneration behind its + # generation, so kstatus never reports the VM Current and the wait never ends. + release.cozystack.io/helm-install-disable-wait: "true" spec: application: kind: VMInstance diff --git a/packages/system/vm-instance-rd/tests/readiness_gate_test.yaml b/packages/system/vm-instance-rd/tests/readiness_gate_test.yaml new file mode 100644 index 000000000..ce5f39206 --- /dev/null +++ b/packages/system/vm-instance-rd/tests/readiness_gate_test.yaml @@ -0,0 +1,33 @@ +suite: vm-instance ApplicationDefinition readiness gate +templates: + - templates/cozyrd.yaml + +# A VMInstance is served as a Flux HelmRelease that renders a KubeVirt +# VirtualMachine. From cozystack v1.5.0 (helm-controller v1.4.3 to v1.5.0) the +# generated release is health-assessed by the kstatus poller, whose generation +# check (checkGeneration in fluxcd/cli-utils pkg/kstatus/status/generic.go) +# returns InProgress for any object whose status.observedGeneration trails +# metadata.generation. vm-instance sets no healthCheckExprs, so that check is +# what decides. KubeVirt legitimately runs a VirtualMachine with +# observedGeneration behind generation (a template change pending a restart, a +# stopped VM, or kubevirt/kubevirt#18700), so a healthy VM is read as +# permanently InProgress and the release never converges. Disabling the wait +# restores the pre-1.5.0 behaviour: the release settles once the manifests are +# applied and VM health is observed on the VirtualMachine itself, not on the +# HelmRelease. +tests: + - it: renders the vm-instance ApplicationDefinition + asserts: + - containsDocument: + apiVersion: cozystack.io/v1alpha1 + kind: ApplicationDefinition + name: vm-instance + + - it: disables the helm-controller readiness wait for the VMInstance release + documentSelector: + path: metadata.name + value: vm-instance + asserts: + - equal: + path: metadata.annotations["release.cozystack.io/helm-install-disable-wait"] + value: "true" diff --git a/packages/tests/cozy-lib-tests/templates/tests/cozyconfig.yaml b/packages/tests/cozy-lib-tests/templates/tests/cozyconfig.yaml new file mode 100644 index 000000000..dbcbb0f07 --- /dev/null +++ b/packages/tests/cozy-lib-tests/templates/tests/cozyconfig.yaml @@ -0,0 +1,18 @@ +apiVersion: v1 +kind: ConfigMap +metadata: + name: {{ .Release.Name }}-cozyconfig +data: + root-host: {{ include "cozy-lib.root-host" . | quote }} + bundle-name: {{ include "cozy-lib.bundle-name" . | quote }} + images-registry: {{ include "cozy-lib.images-registry" . | quote }} + ipv4-cluster-cidr: {{ include "cozy-lib.ipv4-cluster-cidr" . | quote }} + ipv4-service-cidr: {{ include "cozy-lib.ipv4-service-cidr" . | quote }} + ipv4-join-cidr: {{ include "cozy-lib.ipv4-join-cidr" . | quote }} + scheduling: {{ include "cozy-lib.scheduling" . | quote }} + branding: {{ include "cozy-lib.branding" . | quote }} + ns-host: {{ include "cozy-lib.ns-host" . | quote }} + ns-etcd: {{ include "cozy-lib.ns-etcd" . | quote }} + ns-ingress: {{ include "cozy-lib.ns-ingress" . | quote }} + ns-monitoring: {{ include "cozy-lib.ns-monitoring" . | quote }} + ns-seaweedfs: {{ include "cozy-lib.ns-seaweedfs" . | quote }} diff --git a/packages/tests/cozy-lib-tests/tests/cozyconfig_test.yaml b/packages/tests/cozy-lib-tests/tests/cozyconfig_test.yaml new file mode 100644 index 000000000..85dbb3217 --- /dev/null +++ b/packages/tests/cozy-lib-tests/tests/cozyconfig_test.yaml @@ -0,0 +1,81 @@ +# ./tests/cozyconfig_test.yaml +suite: cozyconfig helpers survive an uninjected _cluster and _namespace + +templates: + - templates/tests/cozyconfig.yaml + +# `_cluster` and `_namespace` are injected by the platform through valuesFrom on +# the cozystack-values Secret. A chart rendered on its own therefore has neither, +# which is the state of `helm lint`, a plain `helm template`, and any suite that +# does not set them. These helpers must degrade to their empty defaults there +# rather than abort the render, because every consumer of this library inherits +# whatever they do. + +tests: + - it: returns empty defaults when the platform injected nothing + # No `set:` at all: this is the uninjected state, and it needs no mocking. + asserts: + - equal: {path: 'data["root-host"]', value: ""} + - equal: {path: 'data["bundle-name"]', value: ""} + - equal: {path: 'data["images-registry"]', value: ""} + - equal: {path: 'data["ipv4-cluster-cidr"]', value: ""} + - equal: {path: 'data["ipv4-service-cidr"]', value: ""} + - equal: {path: 'data["ipv4-join-cidr"]', value: ""} + - equal: {path: 'data["scheduling"]', value: ""} + - equal: {path: 'data["branding"]', value: ""} + - equal: {path: 'data["ns-host"]', value: ""} + - equal: {path: 'data["ns-etcd"]', value: ""} + - equal: {path: 'data["ns-ingress"]', value: ""} + - equal: {path: 'data["ns-monitoring"]', value: ""} + - equal: {path: 'data["ns-seaweedfs"]', value: ""} + + - it: returns the injected values unchanged when the platform did inject them + # The other half of the guard: making the helpers survive an absent map must + # not change what they return when the map is present. + set: + _cluster: + root-host: example.com + bundle-name: paas-full + images-registry: registry.example.com + ipv4-cluster-cidr: 10.244.0.0/16 + ipv4-service-cidr: 10.96.0.0/16 + ipv4-join-cidr: 100.64.0.0/16 + scheduling: + nodeSelector: + node-role.kubernetes.io/worker: "" + branding: + logo: + light: /logos/light.svg + _namespace: + host: tenant.example.com + etcd: etcd-ns + ingress: ingress-ns + monitoring: monitoring-ns + seaweedfs: seaweedfs-ns + asserts: + - equal: {path: 'data["root-host"]', value: "example.com"} + - equal: {path: 'data["bundle-name"]', value: "paas-full"} + - equal: {path: 'data["images-registry"]', value: "registry.example.com"} + - equal: {path: 'data["ipv4-cluster-cidr"]', value: "10.244.0.0/16"} + - equal: {path: 'data["ipv4-service-cidr"]', value: "10.96.0.0/16"} + - equal: {path: 'data["ipv4-join-cidr"]', value: "100.64.0.0/16"} + - equal: {path: 'data["ns-host"]', value: "tenant.example.com"} + - equal: {path: 'data["ns-etcd"]', value: "etcd-ns"} + - equal: {path: 'data["ns-ingress"]', value: "ingress-ns"} + - equal: {path: 'data["ns-monitoring"]', value: "monitoring-ns"} + - equal: {path: 'data["ns-seaweedfs"]', value: "seaweedfs-ns"} + # scheduling and branding are the two helpers whose body was rewritten + # rather than wrapped, so they need the present-map half most. Their + # value is a whole YAML document, and it is pinned as one: a substring + # match here would survive the loss of the `toYaml` that produces it, + # because the key name also appears in Go's default map formatting. + - equal: + path: 'data["scheduling"]' + value: |- + nodeSelector: + node-role.kubernetes.io/worker: "" + - equal: + path: 'data["branding"]' + value: |- + logo: + light: /logos/light.svg diff --git a/pkg/config/config.go b/pkg/config/config.go index cd87bdf02..d330970d1 100644 --- a/pkg/config/config.go +++ b/pkg/config/config.go @@ -26,6 +26,13 @@ import ( "github.com/fluxcd/pkg/apis/kustomize" ) +// ReleaseAnnotationPrefix is the prefix shared by every ApplicationDefinition +// metadata annotation that changes how cozystack-api builds the generated +// HelmRelease (the three constants below). cozystack-api reads them once, at +// start-up, so cozystack-controller has to roll the api Deployment when one of +// them changes; it selects them by this prefix when hashing the definitions. +const ReleaseAnnotationPrefix = "release.cozystack.io/" + // HelmInstallTimeoutAnnotation is the ApplicationDefinition metadata // annotation key that overrides the Flux HelmRelease Install.Timeout and // Upgrade.Timeout for a given Application kind. diff --git a/pkg/config/config_test.go b/pkg/config/config_test.go index f97bd5f42..46d268200 100644 --- a/pkg/config/config_test.go +++ b/pkg/config/config_test.go @@ -272,3 +272,22 @@ func TestParseHelmInstallDisableWaitAnnotation(t *testing.T) { }) } } + +// TestReleaseAnnotationsShareThePrefix pins that every annotation cozystack-api +// reads off an ApplicationDefinition lives under ReleaseAnnotationPrefix. +// cozystack-operator selects them by that prefix when it hashes the definitions +// to decide whether to roll the api Deployment, so an annotation introduced +// outside the prefix would be read at start-up but never trigger the restart +// that delivers it. +func TestReleaseAnnotationsShareThePrefix(t *testing.T) { + for _, annotation := range []string{ + HelmInstallTimeoutAnnotation, + HelmUpgradeTimeoutAnnotation, + HelmInstallDisableWaitAnnotation, + } { + if !strings.HasPrefix(annotation, ReleaseAnnotationPrefix) { + t.Errorf("annotation %q is outside %q, so a change to it never rolls cozystack-api", + annotation, ReleaseAnnotationPrefix) + } + } +} diff --git a/pkg/registry/core/tenantsecret/rest.go b/pkg/registry/core/tenantsecret/rest.go index 3515f286c..85d0ad109 100644 --- a/pkg/registry/core/tenantsecret/rest.go +++ b/pkg/registry/core/tenantsecret/rest.go @@ -358,7 +358,13 @@ func (r *REST) Update( cur = previous } - newObj, err := objInfo.UpdatedObject(ctx, nil) + // The apiserver's patch handler builds the patched object from the old + // object alone; a nil old object makes it answer 404 (and admit as CREATE). + var oldObj runtime.Object + if cur != nil { + oldObj = secretToTenant(cur) + } + newObj, err := objInfo.UpdatedObject(ctx, oldObj) if err != nil { return nil, false, err } diff --git a/pkg/registry/core/tenantsecret/rest_write_options_test.go b/pkg/registry/core/tenantsecret/rest_write_options_test.go index 41eadf860..902b54d5c 100644 --- a/pkg/registry/core/tenantsecret/rest_write_options_test.go +++ b/pkg/registry/core/tenantsecret/rest_write_options_test.go @@ -4,6 +4,7 @@ package tenantsecret import ( "context" + "errors" "reflect" "testing" @@ -134,3 +135,31 @@ func TestTenantSecretDeletePropagatesWriteOptions(t *testing.T) { t.Fatalf("Delete options lost: got %#v, want %#v", got, expected) } } + +// The apiserver's patch handler builds the patched object from the old object +// handed to UpdatedObject and answers 404 when it is nil, so Update has to pass +// the stored TenantSecret rather than nil. +func TestUpdate_PassesStoredObjectToUpdatedObjectInfo(t *testing.T) { + r := newTestREST(t, makeTenantSecret("creds", nil)) + + patch := func(_ context.Context, _, oldObj runtime.Object) (runtime.Object, error) { + if oldObj == nil { + return nil, errors.New("UpdatedObject received a nil old object") + } + out := oldObj.DeepCopyObject().(*corev1alpha1.TenantSecret) + out.Labels = map[string]string{"probe": "x"} + return out, nil + } + + ctx := request.WithNamespace(context.Background(), testNamespace) + if _, _, err := r.Update(ctx, "creds", rest.DefaultUpdatedObjectInfo(nil, patch), nil, nil, false, &metav1.UpdateOptions{}); err != nil { + t.Fatalf("Update returned error: %v", err) + } + stored := &corev1.Secret{} + if err := r.c.Get(ctx, client.ObjectKey{Namespace: testNamespace, Name: "creds"}, stored); err != nil { + t.Fatalf("get stored secret: %v", err) + } + if got := stored.Labels["probe"]; got != "x" { + t.Fatalf("patched label not stored: got %q", got) + } +}