diff --git a/.gitattributes b/.gitattributes index fd0e72652..6762b7e93 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,2 +1,3 @@ # Unified diff context has a marker before Go tabs and blank lines. packages/system/capi-providers-infraprovider/images/cluster-api-provider-kubevirt/patches/*.diff -whitespace +packages/system/kamaji/images/kamaji/patches/*.diff -whitespace diff --git a/api/apps/v1alpha1/postgresql/types.go b/api/apps/v1alpha1/postgresql/types.go index 657cc0fb0..51698e558 100644 --- a/api/apps/v1alpha1/postgresql/types.go +++ b/api/apps/v1alpha1/postgresql/types.go @@ -88,7 +88,7 @@ type Backup struct { // DEPRECATED. See `s3AccessKey`. // +kubebuilder:default:="" S3SecretKey string `json:"s3SecretKey,omitempty"` - // Legacy. Cron schedule (CNPG 6-field format) for the chart-emitted ScheduledBackup. Empty means no chart-managed schedule, which is the recommended setup when a `BackupClass` from `backups.cozystack.io` already drives backup orchestration. In the legacy chart-managed flow `spec.plugins` plus the barman-cloud ObjectStore is rendered when `backup.enabled=true` AND `useSystemBucket=false` AND `destinationPath` is non-empty AND inline-or-external creds are supplied; in the platform `useSystemBucket=true` flow the chart skips emitting `spec.plugins` and the CNPG driver SSA-applies the ObjectStore and patches `spec.plugins` onto the live Cluster at first BackupJob time. + // Legacy. Cron schedule for the chart-emitted ScheduledBackup, either a standard five-field cron such as `0 2 * * *` for every day at 02:00, or six fields with leading seconds such as `0 0 2 * * *` for the same time. Empty means no chart-managed schedule, which is the recommended setup when a `BackupClass` from `backups.cozystack.io` already drives backup orchestration. In the legacy chart-managed flow `spec.plugins` plus the barman-cloud ObjectStore is rendered when `backup.enabled=true` AND `useSystemBucket=false` AND `destinationPath` is non-empty AND inline-or-external creds are supplied; in the platform `useSystemBucket=true` flow the chart skips emitting `spec.plugins` and the CNPG driver SSA-applies the ObjectStore and patches `spec.plugins` onto the live Cluster at first BackupJob time. // +kubebuilder:default:="" Schedule string `json:"schedule,omitempty"` // Opt-in: when true, the chart-emitted `-s3-creds` Secret is skipped AND `spec.plugins` (plus the barman-cloud ObjectStore) is left UNSET in the chart-rendered Cluster — the cozy-default BackupClass driver SSA-applies an ObjectStore (carrying destinationPath/endpointURL/credentials) and patches `spec.plugins` on the live Cluster when the first BackupJob runs. Consequence: plugin WAL archiving is NOT active until that first BackupJob fires; WAL accumulates on the PVC in the meantime, so fire an ad-hoc BackupJob immediately after enabling the flag on existing releases. Use together with the platform `cozy-default` BackupClass — tenants do not need to fill `s3AccessKey`/`s3SecretKey` or `destinationPath`/`endpointURL`. The destination path automatically scopes to `s3://cozy-backups///`. diff --git a/docs/security/self-assessment.md b/docs/security/self-assessment.md index d41dd4da6..142891b96 100644 --- a/docs/security/self-assessment.md +++ b/docs/security/self-assessment.md @@ -55,7 +55,7 @@ Actors are decomposed by **trust boundary**: two components are distinct actors | GitOps / Flux delivery layer | T1 — platform control plane | Reconciles HelmReleases/Kustomizations into arbitrary privileged manifests; effectively cluster-admin. | Tenants cannot create HelmReleases (RBAC); not tenant-network-reachable. | | `cozystack-api` aggregated API server | T1 — platform control plane | Converts tenant CRs into HelmReleases; can CRUD HelmReleases, Secrets, and Cilium policies cluster-wide. Acts as the policy-enforcing gateway. | Constrains tenants via fixed chart reference, name/quota/host validation, and admission. | | System operators / controllers | T1 — platform control plane | Domain-scoped cluster privileges (provision control planes, mint certs/secrets, program CNI). | Distinct ServiceAccounts; isolated from tenants by RBAC and network policy. | -| Tenant administrator (OIDC `-admin` / `-super-admin`) | T2 — tenant boundary | CRUD on `apps.cozystack.io` application kinds and `sdn.cozystack.io/securitygroups` in its namespace subtree; read on pods/services/ingress plus `delete` on a fixed set (pods/services/endpoints/events); no create/update of arbitrary core resources. (The ClusterRole also lists `persistentvolumes`, but that grant is inert under the namespace-scoped RoleBinding, since PVs are cluster-scoped.) `super-admin` holds the `apps.cozystack.io/*` wildcard (and can create child `Tenant`s); `admin` has an enumerated allowlist excluding some kinds (e.g. `tenants`, `monitoring`, `etcd`, `ingress`). | Namespace-scoped RBAC + admission policies + quota; no HelmRelease or cross-tenant access. | +| Tenant administrator (OIDC `-admin` / `-super-admin`) | T2 — tenant boundary | CRUD on `apps.cozystack.io` application kinds and `sdn.cozystack.io/securitygroups` in its namespace subtree; read on pods/services/ingress plus `delete` on a fixed set (pods/services/endpoints/events); `get` on persistentvolumeclaims and `create` on `upload.cdi.kubevirt.io/uploadtokenrequests`, the pair `virtctl image-upload` needs to upload into an existing VMDisk; no create/update of arbitrary core resources. (The ClusterRole also lists `persistentvolumes`, but that grant is inert under the namespace-scoped RoleBinding, since PVs are cluster-scoped.) `super-admin` holds the `apps.cozystack.io/*` wildcard (and can create child `Tenant`s); `admin` has an enumerated allowlist excluding some kinds (e.g. `tenants`, `monitoring`, `etcd`, `ingress`). | Namespace-scoped RBAC + admission policies + quota; no HelmRelease or cross-tenant access. | | Tenant user (OIDC `-view` / `-use`) | T2 — tenant boundary | Read-only view plus operational verbs (VM console/vnc/portforward, start/stop/restart). Cannot create Application CRs. | Strictly dominated by tenant-admin; cannot escalate. | | Parent vs child (nested) tenant | T2 — tenant boundary | Parent ServiceAccounts bind into descendant namespaces; children do not bind upward. Quota hierarchically capped. | Ancestor→descendant trust is one-way. | | Tenant workloads / managed services | T3 — workload boundary | Run tenant-controlled code; no cluster-API rights beyond their ServiceAccount. | Namespace-scoped RBAC/identity isolate API objects; on the network, Cilium egress confines each tenant pod to its own subtree + platform system services + `world`, so unrelated tenants cannot reach each other over the pod network (enforced on egress; ingress is open to `cluster` — see Non-goals). | diff --git a/docs/security/threat-model.md b/docs/security/threat-model.md index 2d40bf661..14c12d301 100644 --- a/docs/security/threat-model.md +++ b/docs/security/threat-model.md @@ -39,7 +39,7 @@ The actors below are decomposed **by trust boundary**, not by component: two com | GitOps / Flux delivery layer | T1 | Reconciles HelmReleases/Kustomizations into arbitrary privileged manifests; effectively cluster-admin. | Tenants cannot create HelmReleases/Kustomizations (RBAC); not tenant-network-reachable. | | `cozystack-api` aggregated API server (ServiceAccount) | T1 | CRUD HelmReleases, Secrets, and CiliumNetworkPolicies cluster-wide; reads Namespaces/RBAC/quotas/nodes. Acts as the policy-enforcing gateway that converts tenant CRs to HelmReleases. | A distinct, network-exposed attack surface from Flux; constrains tenants via fixed chart ref + name/quota/host validation + admission. | | System operators / controllers | T1 | Domain-scoped cluster privileges (provision control planes, mint certs/secrets, program CNI). | Distinct ServiceAccounts, but all cluster-admin-adjacent; isolated from tenants only by RBAC and network policy. | -| Tenant administrator (OIDC groups `-admin`, `-super-admin`) | T2 | CRUD on `apps.cozystack.io` application kinds and `sdn.cozystack.io/securitygroups` within its namespace subtree; read on pods/services/ingress plus `delete` on a fixed set (pods/services/endpoints/events); no create/update of arbitrary core resources. (The ClusterRole also lists `persistentvolumes`, but that grant is inert under the namespace-scoped RoleBinding, since PVs are cluster-scoped.) The `-super-admin` group holds the `apps.cozystack.io/*` wildcard (and so can create child `Tenant`s); the `-admin` group has an enumerated allowlist that excludes some kinds (e.g. `tenants`, `monitoring`, `etcd`, `ingress`, `external-dns`, `bootbox`). | Namespace-scoped RoleBindings + admission policies + quota; no access to HelmReleases, arbitrary core writes, or other tenants. | +| Tenant administrator (OIDC groups `-admin`, `-super-admin`) | T2 | CRUD on `apps.cozystack.io` application kinds and `sdn.cozystack.io/securitygroups` within its namespace subtree; read on pods/services/ingress plus `delete` on a fixed set (pods/services/endpoints/events); `get` on persistentvolumeclaims and `create` on `upload.cdi.kubevirt.io/uploadtokenrequests`, the pair `virtctl image-upload` needs to upload into an existing VMDisk; no create/update of arbitrary core resources. (The ClusterRole also lists `persistentvolumes`, but that grant is inert under the namespace-scoped RoleBinding, since PVs are cluster-scoped.) The `-super-admin` group holds the `apps.cozystack.io/*` wildcard (and so can create child `Tenant`s); the `-admin` group has an enumerated allowlist that excludes some kinds (e.g. `tenants`, `monitoring`, `etcd`, `ingress`, `external-dns`, `bootbox`). | Namespace-scoped RoleBindings + admission policies + quota; no access to HelmReleases, arbitrary core writes, or other tenants. | | Tenant user (OIDC groups `-view`, `-use`) | T2 | Read-only view of Application CRs, pods, and services, plus operational verbs only (VM console/vnc/portforward, start/stop/restart). Cannot create Application CRs. | Strictly dominated by tenant-admin; cannot escalate to create/delete, so it is a distinct actor. | | Parent tenant vs child (nested) tenant | T2 | Parent ServiceAccounts are bound into descendant namespaces; child ServiceAccounts are not bound upward. Quota is hierarchically capped. | Ancestor→descendant only; compromising a parent compromises its children, not the reverse. | | Tenant workloads / managed services | T3 | Run tenant-controlled code; no cluster-API rights beyond their ServiceAccount. | Namespace-scoped RBAC/identity isolate their API objects. On the network, Cilium egress confines each tenant pod to its own tenant subtree, platform system services, and `world` (out-of-cluster), so unrelated tenants cannot reach each other over the pod network — enforced on the egress side (tenant-pod ingress is open to `cluster`; see Non-goals for residual caveats). | @@ -92,7 +92,7 @@ The following are explicitly out of scope for the platform's security guarantees The single most load-bearing isolation control is the combination of two facts: -1. The tenant ClusterRoles (`packages/system/cozystack-basics/templates/clusterroles.yaml`) grant **no** `helm.toolkit.fluxcd.io` access and **no** create/update of arbitrary core resources — only CRUD on `apps.cozystack.io` application kinds (super-admin holds the `*` wildcard; admin an enumerated allowlist) and `sdn.cozystack.io/securitygroups`, read access to pods/services/ingresses, and (for tenant-admins) `delete` on a fixed set of core objects (pods/services/endpoints/events; the `persistentvolumes` entry in the ClusterRole is inert under the namespace-scoped RoleBinding). Tenant isolation is enforced by the *absence* of privileged grants in RBAC, not by an admission policy that whitelists `apps.cozystack.io/*` writes. +1. The tenant ClusterRoles (`packages/system/cozystack-basics/templates/clusterroles.yaml`) grant **no** `helm.toolkit.fluxcd.io` access and **no** create/update of arbitrary core resources — only CRUD on `apps.cozystack.io` application kinds (super-admin holds the `*` wildcard; admin an enumerated allowlist) and `sdn.cozystack.io/securitygroups`, read access to pods/services/ingresses, and (for tenant-admins) `delete` on a fixed set of core objects (pods/services/endpoints/events; the `persistentvolumes` entry in the ClusterRole is inert under the namespace-scoped RoleBinding), `get` on persistentvolumeclaims and `create` on `upload.cdi.kubevirt.io/uploadtokenrequests` (for uploading an image into an existing VMDisk with `virtctl image-upload`). Tenant isolation is enforced by the *absence* of privileged grants in RBAC, not by an admission policy that whitelists `apps.cozystack.io/*` writes. 2. The Application-to-HelmRelease conversion (`pkg/registry/apps/application/rest.go`) takes the chart reference, release-name prefix, and `valuesFrom` from server-side configuration; the tenant controls only the Helm values (`app.Spec`). If a future `ApplicationDefinition`, RBAC change, or API change ever let a tenant influence the chart reference, `valuesFrom`, or write HelmReleases directly, the T2→T1 isolation would collapse. Changes touching tenant RBAC or the Application REST layer should be reviewed against this invariant. diff --git a/hack/alert-severity-contract.bats b/hack/alert-severity-contract.bats index daf1c82a7..5639d04cc 100644 --- a/hack/alert-severity-contract.bats +++ b/hack/alert-severity-contract.bats @@ -7,6 +7,10 @@ # scope: they are re-vendored by `make update`, so a bad severity there is # fixed upstream or in patches/, not by editing the label. ALERT_SEVERITY_ALLOWED=" security critical major minor warning indeterminate informational normal ok cleared debug trace unknown " +# The alerts that exist only to be dropped, the one place `none` is right. +# InfoInhibitor is the source side of an Alertmanager inhibit rule, which the +# platform config does not have, so delivering it at any severity is noise. +ALERT_SEVERITY_BLACKHOLED=" InfoInhibitor " helm_actions_stripped() { awk ' @@ -102,6 +106,14 @@ alert_severity_contract() { break fi done + if [ "$severity" = "none" ]; then + for blackholed in $ALERT_SEVERITY_BLACKHOLED; do + if [ "$blackholed" = "$alert" ]; then + accepted=1 + break + fi + done + fi if [ "$accepted" -eq 0 ]; then echo "$file: $alert -> '$severity'" >&2 bad=$((bad + 1)) @@ -126,6 +138,83 @@ alert_severity_contract() { alert_severity_contract } +@test "InfoInhibitor is labelled for the blackhole route" { + rows=$(mktemp) || return 1 + if ! alert_severity_rows > "$rows"; then + rm -f "$rows" + return 1 + fi + tab=$(printf '\t') + found=$(grep -c "${tab}InfoInhibitor${tab}" "$rows" || true) + delivered=$(grep "${tab}InfoInhibitor${tab}" "$rows" | grep -vc "${tab}none\$" || true) + rm -f "$rows" + [ "$found" -gt 0 ] + [ "$delivered" -eq 0 ] +} + +@test "severity none passes only on an alert that exists to be dropped" { + fixture=$(mktemp -d) + mkdir -p "$fixture/packages/system/example/alerts" + printf '%s\n' \ + 'apiVersion: operator.victoriametrics.com/v1beta1' \ + 'kind: VMRule' \ + 'spec:' \ + ' groups:' \ + ' - name: general' \ + ' rules:' \ + ' - alert: InfoInhibitor' \ + ' labels:' \ + ' severity: none' \ + > "$fixture/packages/system/example/alerts/00-inhibitor.yaml" + git -C "$fixture" init -q + git -C "$fixture" add packages/system/example/alerts/00-inhibitor.yaml + + inhibitor_succeeded=0 + ALERT_SEVERITY_ROOT="$fixture" alert_severity_contract >/dev/null 2>&1 || inhibitor_succeeded=$? + + printf '%s\n' \ + 'apiVersion: operator.victoriametrics.com/v1beta1' \ + 'kind: VMRule' \ + 'spec:' \ + ' groups:' \ + ' - name: silent' \ + ' rules:' \ + ' - alert: SilentAlert' \ + ' labels:' \ + ' severity: none' \ + > "$fixture/packages/system/example/alerts/01-silent.yaml" + git -C "$fixture" add packages/system/example/alerts/01-silent.yaml + + silent_succeeded=0 + ALERT_SEVERITY_ROOT="$fixture" alert_severity_contract >/dev/null 2>&1 || silent_succeeded=$? + rm -rf "$fixture" + [ "$inhibitor_succeeded" -eq 0 ] + [ "$silent_succeeded" -ne 0 ] +} + +@test "an alert that exists to be dropped still fails on a refused severity" { + fixture=$(mktemp -d) + mkdir -p "$fixture/packages/system/example/alerts" + printf '%s\n' \ + 'apiVersion: operator.victoriametrics.com/v1beta1' \ + 'kind: VMRule' \ + 'spec:' \ + ' groups:' \ + ' - name: general' \ + ' rules:' \ + ' - alert: InfoInhibitor' \ + ' labels:' \ + ' severity: info' \ + > "$fixture/packages/system/example/alerts/00-inhibitor.yaml" + git -C "$fixture" init -q + git -C "$fixture" add packages/system/example/alerts/00-inhibitor.yaml + + contract_succeeded=0 + ALERT_SEVERITY_ROOT="$fixture" alert_severity_contract >/dev/null 2>&1 || contract_succeeded=$? + rm -rf "$fixture" + [ "$contract_succeeded" -ne 0 ] +} + @test "a parser failure cannot leave the contract green" { fixture=$(mktemp -d) mkdir -p "$fixture/packages/system/example/alerts" diff --git a/hack/altinity-backup-strategy.bats b/hack/altinity-backup-strategy.bats new file mode 100644 index 000000000..0861da42d --- /dev/null +++ b/hack/altinity-backup-strategy.bats @@ -0,0 +1,218 @@ +#!/usr/bin/env bats +# Behavioural tests for the shipped Altinity (ClickHouse) backup/restore +# strategy script, extracted from the rendered cozy-default-altinity Strategy +# CR and EXECUTED against a stubbed clickhouse-backup HTTP API, with the real +# jq doing the archive selection. Which archive a restore reads back is +# decided by that selection over list/remote, so it is exercised against +# several archives rather than string-matched. +# +# The script runs with `bash`, not `sh`, for the reason given in +# hack/redis-backup-strategy.bats: it opens `set -euo pipefail`, which the +# production image's busybox ash supports and the CI runner's dash rejects. + +load test_helper + +CHART=packages/system/backupstrategy-controller + +# Render the shipped strategy's in-Pod script into $1 and substitute the +# controller-render placeholders the way the driver fills them: $2 mode, $3 +# app (release and source application), $4 the archive name recorded on the +# Backup (empty for a Backup that records none), $5 the Backup name, $6 its +# takenAt in the archive-name layout. An empty render fails early, as does a +# placeholder left unsubstituted. +render_script() { + out=$1; mode=$2; app=$3; archive=$4; backup=$5; takenat=$6 + helm template t "$CHART" -n cozy-backup-controller \ + --set backupStorage.bucketNameOverride=test-bucket 2>/dev/null \ + | yq eval 'select(.kind == "Altinity") | .spec.template.spec.containers[0].args[0]' - \ + | sed -e "s#{{ .Mode }}#${mode}#g" \ + -e "s#{{ .Release.Name }}#${app}#g" \ + -e "s#{{ .Release.Namespace }}#tenant-x#g" \ + -e "s#{{ .Backup.ApplicationRef.Name }}#${app}#g" \ + -e "s#{{ .Backup.Name }}#${backup}#g" \ + -e "s#{{ .ArchiveName | default \"\" }}#${archive}#g" \ + -e "s#{{ .Backup.TakenAt | default \"\" }}#${takenat}#g" > "$out" + [ -s "$out" ] || return 1 + if grep -q '{{' "$out"; then + echo "rendered script still holds a controller placeholder" >&2 + return 1 + fi +} + +# Stub the clickhouse-backup API behind curl, first on PATH. list/remote +# serves $state/remote; actions serves $state/actions plus one success row per +# operation the script has issued, and after its first read swaps in +# $state/actions.next when a test seeds one (an operation that finishes while +# the script waits). Every request is logged to $state/curl.log. sleep is +# stubbed to fail after a few calls, so a script that never sees its +# operation finish fails the test instead of hanging it. +make_stubs() { + bin=$1; state=$2 + mkdir -p "$bin" + : > "$state/remote" + : > "$state/actions" + cat > "$bin/curl" <> "$state/curl.log" +case "\$method \$url" in + "GET "*/backup/status) echo '{}' ;; + "GET "*/backup/list/remote) cat "$state/remote" ;; + "GET "*/backup/actions) + cat "$state/actions" + if [ -f "$state/actions.done" ]; then cat "$state/actions.done"; fi + if [ -f "$state/actions.next" ]; then mv "$state/actions.next" "$state/actions"; fi + ;; + "POST "*/backup/create_remote*) + name=\${url#*name=}; name=\${name%%&*} + printf '{"command":"create_remote --resume %s","status":"success","start":"2099-01-01 00:00:00"}\n' "\$name" >> "$state/actions.done" + ;; + "POST "*/backup/restore_remote/*) + printf '{"command":"restore_remote %s","status":"success","start":"2099-01-01 00:00:00"}\n' "\${url##*/}" >> "$state/actions.done" + ;; + *) echo "unexpected request: \$method \$url" >&2; exit 22 ;; +esac +STUB + cat > "$bin/sleep" </dev/null || echo 0) +echo \$((n + 1)) > "$state/sleeps" +if [ "\$n" -ge 3 ]; then echo "sleep budget spent: the operation never finished" >&2; exit 1; fi +STUB + chmod 0755 "$bin/curl" "$bin/sleep" + export API_USERNAME=u API_PASSWORD=p +} + +# One list/remote row per argument, "name" or "name|desc"; created mirrors +# the name's timestamp, which is the order the pre-fix selection sorted by. +remote_rows() { + for row in "$@"; do + name=${row%%|*}; desc="tar, regular" + if [ "$row" != "$name" ]; then desc=${row#*|}; fi + ts=${name##*-} + printf '{"name":"%s","created":"%s","location":"remote","required":"","desc":"%s"}\n' "$name" "$ts" "$desc" + done +} + +@test "an empty render fails the fixture instead of passing as a no-op" { + tmp=$(mktemp -d) + CHART=$tmp/no-such-chart + if render_script "$tmp/s.sh" restore myapp "" bkp 20260304T050622Z 2>/dev/null; then + echo "FAIL: render_script reported success with no chart" + false + fi + rm -rf "$tmp" +} + +@test "restore reads back the archive the Backup recorded, not the newest one" { + tmp=$(mktemp -d) + make_stubs "$tmp/bin" "$tmp" + render_script "$tmp/s.sh" restore myapp clickhouse-myapp-20260304T050607Z bkp-a 20260304T050622Z + remote_rows clickhouse-myapp-20260304T040000Z clickhouse-myapp-20260304T050607Z \ + clickhouse-myapp-20260304T060000Z clickhouse-myapp-20260304T070000Z > "$tmp/remote" + PATH="$tmp/bin:$PATH" bash "$tmp/s.sh" + grep -qxF 'POST http://chi-clickhouse-myapp-clickhouse-0-0.tenant-x.svc:7171/backup/restore_remote/clickhouse-myapp-20260304T050607Z' "$tmp/curl.log" + [ "$(grep -c '/backup/restore_remote/' "$tmp/curl.log")" -eq 1 ] + rm -rf "$tmp" +} + +@test "restore fails naming the recorded archive when remote storage lacks it" { + tmp=$(mktemp -d) + make_stubs "$tmp/bin" "$tmp" + render_script "$tmp/s.sh" restore myapp clickhouse-myapp-20260304T050607Z bkp-a 20260304T050622Z + remote_rows clickhouse-myapp-20260304T040000Z clickhouse-myapp-20260304T060000Z > "$tmp/remote" + out="" + if out=$(PATH="$tmp/bin:$PATH" bash "$tmp/s.sh" 2>&1); then + echo "FAIL: restore succeeded without the recorded archive: $out" + false + fi + printf '%s\n' "$out" | grep -qF 'archive clickhouse-myapp-20260304T050607Z recorded on Backup bkp-a is not in remote storage' + if grep -qF '/backup/restore_remote/' "$tmp/curl.log"; then + echo "FAIL: restored another archive: $(cat "$tmp/curl.log")" + false + fi + rm -rf "$tmp" +} + +@test "restore of a Backup without a recorded archive takes the newest one stamped by its takenAt, and warns" { + tmp=$(mktemp -d) + make_stubs "$tmp/bin" "$tmp" + render_script "$tmp/s.sh" restore myapp "" bkp-a 20260304T050800Z + # Each decoy sorts after the expected archive and is ruled out by one + # filter: broken, not a bare timestamp after the prefix, or stamped after + # takenAt. + remote_rows clickhouse-myapp-20260304T040000Z clickhouse-myapp-20260304T050607Z \ + "clickhouse-myapp-20260304T050700Z|broken (can't stat metadata.json)" \ + clickhouse-myapp-20260304T050710Z-copy \ + clickhouse-myapp-20260304T060000Z > "$tmp/remote" + out=$(PATH="$tmp/bin:$PATH" bash "$tmp/s.sh" 2>&1) + grep -qxF 'POST http://chi-clickhouse-myapp-clickhouse-0-0.tenant-x.svc:7171/backup/restore_remote/clickhouse-myapp-20260304T050607Z' "$tmp/curl.log" + [ "$(grep -c '/backup/restore_remote/' "$tmp/curl.log")" -eq 1 ] + printf '%s\n' "$out" | grep -qF 'WARNING: Backup bkp-a records no archive name' + rm -rf "$tmp" +} + +@test "restore of a Backup without a recorded archive fails when no archive is stamped by its takenAt" { + tmp=$(mktemp -d) + make_stubs "$tmp/bin" "$tmp" + render_script "$tmp/s.sh" restore myapp "" bkp-a 20260304T050800Z + remote_rows clickhouse-myapp-20260304T060000Z clickhouse-myapp-20260304T070000Z > "$tmp/remote" + out="" + if out=$(PATH="$tmp/bin:$PATH" bash "$tmp/s.sh" 2>&1); then + echo "FAIL: restore succeeded with every archive newer than takenAt: $out" + false + fi + printf '%s\n' "$out" | grep -qF 'no archive of myapp stamped no later than 20260304T050800Z' + if grep -qF '/backup/restore_remote/' "$tmp/curl.log"; then + echo "FAIL: restored an archive newer than takenAt: $(cat "$tmp/curl.log")" + false + fi + rm -rf "$tmp" +} + +@test "backup writes the archive under the name the controller chose" { + tmp=$(mktemp -d) + make_stubs "$tmp/bin" "$tmp" + render_script "$tmp/s.sh" backup myapp clickhouse-myapp-20260304T050607Z "" "" + PATH="$tmp/bin:$PATH" bash "$tmp/s.sh" + grep -qxF 'POST http://chi-clickhouse-myapp-clickhouse-0-0.tenant-x.svc:7171/backup/create_remote?name=clickhouse-myapp-20260304T050607Z&resume=true' "$tmp/curl.log" + rm -rf "$tmp" +} + +@test "a retried backup waits on the attempt the sidecar is still running" { + tmp=$(mktemp -d) + make_stubs "$tmp/bin" "$tmp" + render_script "$tmp/s.sh" backup myapp clickhouse-myapp-20260304T050607Z "" "" + printf '{"command":"create_remote --resume clickhouse-myapp-20260304T050607Z","status":"in progress","start":"2026-03-04 05:06:08"}\n' > "$tmp/actions" + printf '{"command":"create_remote --resume clickhouse-myapp-20260304T050607Z","status":"success","start":"2026-03-04 05:06:08"}\n' > "$tmp/actions.next" + PATH="$tmp/bin:$PATH" bash "$tmp/s.sh" + # The sidecar answers a second operation with 423 while one runs. + if grep -qF 'POST ' "$tmp/curl.log"; then + echo "FAIL: started another operation over the running one: $(cat "$tmp/curl.log")" + false + fi + rm -rf "$tmp" +} + +@test "a retried backup after a failed attempt resumes the same archive" { + tmp=$(mktemp -d) + make_stubs "$tmp/bin" "$tmp" + render_script "$tmp/s.sh" backup myapp clickhouse-myapp-20260304T050607Z "" "" + printf '{"command":"create_remote clickhouse-myapp-20260304T050607Z","status":"error","start":"2026-03-04 05:06:08","error":"S3 PutObject 403"}\n' > "$tmp/actions" + PATH="$tmp/bin:$PATH" bash "$tmp/s.sh" + grep -qxF 'POST http://chi-clickhouse-myapp-clickhouse-0-0.tenant-x.svc:7171/backup/create_remote?name=clickhouse-myapp-20260304T050607Z&resume=true' "$tmp/curl.log" + rm -rf "$tmp" +} + +@test "backup falls back to a timestamped name when the controller supplies none" { + tmp=$(mktemp -d) + make_stubs "$tmp/bin" "$tmp" + render_script "$tmp/s.sh" backup myapp "" "" "" + PATH="$tmp/bin:$PATH" bash "$tmp/s.sh" + grep -qE '^POST http://[^ ]*/backup/create_remote\?name=clickhouse-myapp-[0-9]{8}T[0-9]{6}Z&resume=true$' "$tmp/curl.log" + rm -rf "$tmp" +} diff --git a/hack/check-hook-request-timeout.bats b/hack/check-hook-request-timeout.bats new file mode 100755 index 000000000..5395f5e99 --- /dev/null +++ b/hack/check-hook-request-timeout.bats @@ -0,0 +1,60 @@ +#!/usr/bin/env bats +# Repo-wide invariant: a kubectl call that relies on in-cluster credentials must +# not carry a non-zero --request-timeout. +# +# client-go loads in-cluster credentials only while the assembled config still +# equals the default. --request-timeout lands in that config, so any non-zero +# value diverts the call to kubectl's built-in default cluster, localhost:8080, +# where it is refused. Nothing about this is visible in a rendered manifest: the +# flag reads as ordinary defensive practice, the chart renders, and the failure +# appears only when the container runs against a real apiserver. It cost two +# packages before it was found (#4276, #4288), and in one of them the hook +# reported success while doing nothing. +# +# Scope and its limit. A file that names KUBECONFIG is skipped: it hands kubectl +# an explicit kubeconfig, so the in-cluster branch is not what serves it and the +# flag is harmless there. That is a per-file judgement, not per-command, which +# is the coarse part of this check and is why it is written down rather than +# inferred. Vendored charts under packages/*/*/charts are upstream and out of +# scope. +# +# Bounding the call is still available: --timeout bounds a watch, and +# activeDeadlineSeconds bounds the whole Job, which is what +# packages/apps/tenant/templates/cleanup-job.yaml uses and documents. + +REPO_ROOT="$(cd "$(dirname "${BATS_TEST_FILENAME:-$0}")/.." && pwd)" + +@test "no in-cluster kubectl call carries a non-zero --request-timeout" { + cd "$REPO_ROOT" + + # Files in scope: non-vendored templates that invoke kubectl. + candidates="$(grep -rl 'kubectl' packages/*/*/templates/ 2>/dev/null || true)" + [ -n "$candidates" ] || { echo "FAIL: found no templates invoking kubectl; this check is broken, not clean"; false; } + + # Guard against a vacuous pass: the tree ships many such templates, so a + # collapsed glob has to fail here rather than report success. + count="$(printf '%s\n' "$candidates" | grep -c . || true)" + [ "$count" -ge 10 ] || { echo "FAIL: only $count template(s) invoke kubectl; expected the tree's usual population"; false; } + + offenders="" + for f in $candidates; do + # An explicit kubeconfig means the in-cluster branch is not in play here. + if grep -q 'KUBECONFIG' "$f"; then + continue + fi + hits="$(grep -nE -- '--request-timeout=[^0[:space:]]' "$f" || true)" + if [ -n "$hits" ]; then + offenders="${offenders}${f} +${hits} +" + fi + done + + if [ -n "$offenders" ]; then + echo "FAIL: non-zero --request-timeout on a call that depends on in-cluster credentials." + echo "It diverts kubectl to localhost:8080 and the call never reaches the cluster." + echo "Bound the work with --timeout or activeDeadlineSeconds instead." + printf '%s\n' "$offenders" + false + fi +} diff --git a/hack/check-postgres-app-owner-password.bats b/hack/check-postgres-app-owner-password.bats new file mode 100644 index 000000000..724bb714c --- /dev/null +++ b/hack/check-postgres-app-owner-password.bats @@ -0,0 +1,25 @@ +#!/usr/bin/env bats +# Unit test: on a fresh install, packages/apps/postgres hands CNPG the same +# users.app password it stores in -credentials. +# +# The password is generated at render time, so the two Secrets can only be +# compared within one render. helm-unittest asserts each document against a +# fixed value and has no way to compare one document with another, so a chart +# generating two independent passwords would still pass the chart's own suite. + +load test_helper + +REPO_ROOT="$(cd "$(dirname "${BATS_TEST_FILENAME:-$0}")/.." && pwd)" +CHART="$REPO_ROOT/packages/apps/postgres" + +@test "a fresh users.app gets one generated password in both Secrets" { + rendered="$BATS_TEST_TMPDIR/init-script.yaml" + helm template pg "$CHART" --namespace tenant-test \ + --set-json '_cluster={"scheduling":{}}' --set-json 'users={"app":{}}' \ + --show-only templates/init-script.yaml > "$rendered" + + app=$(yq -e 'select(.kind == "Secret" and .metadata.name == "pg-credentials").stringData.app' "$rendered") + owner=$(yq -e 'select(.kind == "Secret" and .metadata.name == "pg-app-owner").stringData.password' "$rendered") + [ -n "$app" ] || { echo "no generated password for app in pg-credentials" >&2; return 1; } + [ "$app" = "$owner" ] || { printf 'pg-credentials app: %s\npg-app-owner password: %s\n' "$app" "$owner" >&2; return 1; } +} diff --git a/hack/cilium-ipam-migration.bats b/hack/cilium-ipam-migration.bats index c47bc41af..cd68a195e 100644 --- a/hack/cilium-ipam-migration.bats +++ b/hack/cilium-ipam-migration.bats @@ -486,6 +486,33 @@ pod_cidrs_of() { rm -rf "$STATE" } +@test "a CiliumNode list larger than one argument may hold still moves every node and names the pod on an old Ingress IP" { + init_state + add_ip web-0.tenant-c ovn-default 10.244.1.135 + add_ip web-1.tenant-c ovn-default 10.244.4.135 + add_ip db-0.tenant-c ovn-default 10.244.9.9 + # Cilium copies every Node label onto the CiliumNode, which takes six real + # ones past the 128 KiB Linux allows a single argument. One annotation stands + # in for the labels and keeps the list over that limit even printed compact. + for i in 1 2 3 4 5 6; do + add_node "n$i" "10.244.$i.0/24" "10.244.$i.223" "10.244.$i.135" + jq '.metadata.annotations.padding = ("x" * 24576)' "$STATE/ciliumnodes/n$i.json" > "$STATE/node.tmp" + mv "$STATE/node.tmp" "$STATE/ciliumnodes/n$i.json" + done + [ "$(kubectl get ciliumnodes -o json | jq -c . | wc -c)" -gt 131072 ] + "$SCRIPT" > "$STATE/out" 2>&1 + # Each pod is named with the node whose Ingress IP it holds, and a pod on an + # address that is no node's Ingress IP is not named at all. + grep -q "web-0.tenant-c holds 10.244.1.135, the Ingress IP of n1 before the move" "$STATE/out" + grep -q "web-1.tenant-c holds 10.244.4.135, the Ingress IP of n4 before the move" "$STATE/out" + if grep -q "db-0.tenant-c" "$STATE/out"; then + cat "$STATE/out" + false + fi + [ "$(pod_cidrs_of n6)" = '["10.244.248.40/29"]' ] + rm -rf "$STATE" +} + @test "a cluster without kube-ovn skips the exclusion and still moves its nodes" { init_state rm "$STATE/subnet.json" diff --git a/hack/e2e-install-cozystack.bats b/hack/e2e-install-cozystack.bats index c7cd8b293..6cbdb4496 100644 --- a/hack/e2e-install-cozystack.bats +++ b/hack/e2e-install-cozystack.bats @@ -490,6 +490,88 @@ EOF | grep -qx '250m 128Mi 25m 128Mi' } +@test "Tenant super-admin holds no write verb outside the allowlist" { + # cozy:tenant:super-admin is aggregated from every ClusterRole labelled for + # it or for a level below, across several packages, so a write path into a + # tenant namespace can arrive without touching the role that names it. The + # raw kubevirt.io VirtualMachine grant did: a '*' that let a tenant size a VM + # outside any application. The effective rules are read back from the + # apiserver, after aggregation, and any write verb the allowlist does not + # name fails the test; adding a line there is the statement that the write + # is accounted for. + # + # The bare system:authenticated identity is subtracted first, so what + # Kubernetes grants every user (the selfsubject* reviews) does not tie the + # list to a Kubernetes version. An allowlisted line the cluster does not + # grant is reported without failing: a lane with COZY_DISABLED_PACKAGES set + # lacks the tenant roles those packages ship. + # + # Rules and status come from the same SelfSubjectRulesReview response, so + # a partial list cannot pass on the strength of a later, complete one. + # can-i --list hides both failure modes behind exit 0: it only warns on + # incomplete, and says nothing when RBAC reports an evaluationError with + # incomplete left false. The jq rendering keeps can-i's resource column, + # which the allowlist is written in. + # + # Lines covered by a wildcard grant are folded into it, so a '*' on a whole + # group (apps.cozystack.io, the gated API) does not make every new kind an + # allowlist edit. Staged through files rather than pipes: /bin/sh here has + # no pipefail, and a failed kubectl must not pass as an empty grant list. + local complete normalize subsume review allowlist granted baseline effective unexpected missing f + complete='.status.incomplete == false and (.status.evaluationError // "") == ""' + normalize='.status.resourceRules[] | . as $r + | ($r.resourceNames // [] | if length == 0 then ["-"] else . end)[] as $name + | $r.apiGroups[] as $group | $r.resources[] as $resource | $r.verbs[] as $verb + | select($verb != "get" and $verb != "list" and $verb != "watch") + | ($resource | split("/")) as $part + | $part[0] + (if $group == "" then "" else "." + $group end) + + (if ($part | length) > 1 then "/" + ($part[1:] | join("/")) else "" end) + + " " + $name + " " + $verb' + subsume='NR == FNR { have[$0] = 1; next } + { + dot = index($1, ".") + if (dot > 1 && $1 !~ /^\*\./ && (("*" substr($1, dot) " - *") in have)) next + if ($3 != "*" && (($1 " " $2 " *") in have)) next + print + }' + review=$(mktemp); allowlist=$(mktemp); granted=$(mktemp); baseline=$(mktemp) + effective=$(mktemp); unexpected=$(mktemp); missing=$(mktemp) + echo '{"apiVersion":"authorization.k8s.io/v1","kind":"SelfSubjectRulesReview","spec":{"namespace":"tenant-test"}}' > "$review" + # --validate=false: client-side validation would run as the impersonated + # identity, which cannot list CRDs. + timeout -k 5 30 kubectl create --validate=false -f "$review" -o json \ + --as=e2e-rbac-probe --as-group=system:authenticated --as-group=tenant-test-super-admin > "$granted" + timeout -k 5 30 kubectl create --validate=false -f "$review" -o json \ + --as=e2e-rbac-probe --as-group=system:authenticated > "$baseline" + for f in "$granted" "$baseline"; do + if jq -e "$complete" "$f" > /dev/null; then :; else + echo "FAIL: the apiserver could not enumerate the tenant-test rules completely:" >&2 + jq -c '.status | {incomplete, evaluationError}' "$f" >&2 + false + fi + done + jq -r "$normalize" "$granted" > "$granted.n" + jq -r "$normalize" "$baseline" > "$baseline.n" + yq '.writeVerbs[]' hack/e2e-tenant-super-admin-write-verbs.yaml > "$allowlist" + LC_ALL=C sort -u -o "$granted.n" "$granted.n" + LC_ALL=C sort -u -o "$baseline.n" "$baseline.n" + LC_ALL=C sort -u -o "$allowlist" "$allowlist" + LC_ALL=C comm -23 "$granted.n" "$baseline.n" > "$effective.n" + awk "$subsume" "$effective.n" "$effective.n" > "$effective" + LC_ALL=C comm -23 "$effective" "$allowlist" > "$unexpected" + LC_ALL=C comm -13 "$effective" "$allowlist" > "$missing" + if [ -s "$missing" ]; then + echo "allowlisted but not granted on this cluster:" + cat "$missing" + fi + if [ -s "$unexpected" ]; then + echo "FAIL: tenant-test-super-admin holds write verbs hack/e2e-tenant-super-admin-write-verbs.yaml does not allow:" >&2 + cat "$unexpected" >&2 + false + fi + rm -f "$review" "$allowlist" "$granted" "$granted.n" "$baseline" "$baseline.n" "$effective" "$effective.n" "$unexpected" "$missing" +} + @test "Deletion-protection VAP denies delete on labeled cozystack-version ConfigMap" { # Locks down the contract delivered by packages/core/platform/templates/ # deletion-protection.yaml: a DELETE on any object carrying diff --git a/hack/e2e-tenant-super-admin-write-verbs.yaml b/hack/e2e-tenant-super-admin-write-verbs.yaml new file mode 100644 index 000000000..f267e1068 --- /dev/null +++ b/hack/e2e-tenant-super-admin-write-verbs.yaml @@ -0,0 +1,45 @@ +# Write verbs a tenant super-admin may hold in its own namespace, read by the +# "Tenant super-admin holds no write verb outside the allowlist" test in +# hack/e2e-install-cozystack.bats. One "resource names verb" entry per verb, +# as that test's jq renders the SelfSubjectRulesReview rather than as +# `kubectl auth can-i --list` prints it: the resource in can-i's +# resource-column form, "-" for no resource names, any verb other than get, +# list and watch. Adding an entry is a reviewed decision that the write is +# accounted for. apps.cozystack.io is listed whole because every write to it +# goes through the aggregated apiserver rather than straight to a workload. +writeVerbs: +- "*.apps.cozystack.io - *" +- "backupjobs.backups.cozystack.io - create" +- "backupjobs.backups.cozystack.io - delete" +- "backupjobs.backups.cozystack.io - patch" +- "backupjobs.backups.cozystack.io - update" +- "endpoints - delete" +- "events - delete" +- "persistentvolumes - delete" +- "plans.backups.cozystack.io - create" +- "plans.backups.cozystack.io - delete" +- "plans.backups.cozystack.io - patch" +- "plans.backups.cozystack.io - update" +- "pods - delete" +- "restorejobs.backups.cozystack.io - create" +- "restorejobs.backups.cozystack.io - delete" +- "restorejobs.backups.cozystack.io - patch" +- "restorejobs.backups.cozystack.io - update" +- "securitygroups.sdn.cozystack.io - create" +- "securitygroups.sdn.cozystack.io - delete" +- "securitygroups.sdn.cozystack.io - patch" +- "securitygroups.sdn.cozystack.io - update" +- "services - delete" +- "uploadtokenrequests.upload.cdi.kubevirt.io - create" +- "virtualmachineinstances.subresources.kubevirt.io/portforward - update" +- "virtualmachines.subresources.kubevirt.io/restart - update" +- "virtualmachines.subresources.kubevirt.io/start - update" +- "virtualmachines.subresources.kubevirt.io/stop - update" +- "vmimportsources.forklift.cozystack.io - create" +- "vmimportsources.forklift.cozystack.io - delete" +- "vmimportsources.forklift.cozystack.io - patch" +- "vmimportsources.forklift.cozystack.io - update" +- "vmimporttasks.forklift.cozystack.io - create" +- "vmimporttasks.forklift.cozystack.io - delete" +- "vmimporttasks.forklift.cozystack.io - patch" +- "vmimporttasks.forklift.cozystack.io - update" diff --git a/hack/etcd-grpc-alerts.bats b/hack/etcd-grpc-alerts.bats new file mode 100644 index 000000000..2fc4ddc12 --- /dev/null +++ b/hack/etcd-grpc-alerts.bats @@ -0,0 +1,27 @@ +#!/usr/bin/env bats + +load test_helper + +REPO_ROOT="$(cd "$(dirname "${BATS_TEST_FILENAME:-$0}")/.." && pwd)" +VMALERT_TOOL_IMAGE="victoriametrics/vmalert-tool:v1.136.0@sha256:417346d7b6fdb66d8e3984887c2ad114535ec7d983eeef53381b56c776f333f1" + +@test "tenant etcd failed gRPC request alerts pass their vmalert-tool cases" { + docker info >/dev/null 2>&1 || { + echo "docker is required to run the cases in $VMALERT_TOOL_IMAGE" >&2 + return 1 + } + work=$(mktemp -d) + helm template etcd "$REPO_ROOT/packages/extra/etcd" --namespace tenant-test \ + --set '_cluster.cluster-domain=cozy.local' \ + --show-only templates/prometheus-rules.yaml > "$work/rendered.yaml" + yq '.spec' "$work/rendered.yaml" > "$work/rules.yaml" + cp "$REPO_ROOT/hack/testdata/etcd-grpc-alerts/unittest.yaml" "$work/unittest.yaml" + rc=0 + docker run --rm --network none -v "$work:/w:ro" "$VMALERT_TOOL_IMAGE" \ + unittest --files /w/unittest.yaml > "$work/out" 2>&1 || rc=$? + cat "$work/out" + passed=$(grep -cx 'SUCCESS' "$work/out" || true) + rm -rf "$work" + [ "$rc" -eq 0 ] + [ "$passed" -eq 1 ] +} diff --git a/hack/kubernetes-oidc-bindings.bats b/hack/kubernetes-oidc-bindings.bats new file mode 100644 index 000000000..f37273802 --- /dev/null +++ b/hack/kubernetes-oidc-bindings.bats @@ -0,0 +1,187 @@ +#!/usr/bin/env bats +# ----------------------------------------------------------------------------- +# packages/apps/kubernetes: the OIDC bootstrap Job must not carry the users[] +# list inside its container command. +# +# The Job's script reaches the container as one `sh -c` argument, and Linux caps +# one exec argument at 128 KiB (MAX_ARG_STRLEN). With a ClusterRoleBinding per +# user written into that script, about 240 users take it past the cap: the +# container cannot start, the post-install/post-upgrade hook fails, and the +# tenant cluster's HelmRelease stays unready. The bindings reach the Job through +# a mounted ConfigMap instead, so the script is the same size for any list. +# +# The last three tests execute the rendered script against a fake kubectl, since +# no assertion on the script's text says what the prune step does with the list: +# a condition forced either way passes every helm-unittest case. +# +# Requires: helm, yq (mikefarah v4+), jq, like hack/admin-kubeconfig-invariant.bats. +# ----------------------------------------------------------------------------- + +load test_helper + +USERS=300 + +# render_users renders the chart in System mode with +# generated users and leaves one JSON document per object in /rendered.json. +render_users() { + jq -n --argjson n "$2" ' + {oidc: {users: [range($n) | {email: "user\(.)@example.org", role: (if . % 7 == 0 then "admin" else "view" end)}]}}' \ + > "$1/users.yaml" + helm template bindings packages/apps/kubernetes \ + --namespace tenant-test \ + --values packages/apps/kubernetes/tests/values/oidc-system.yaml \ + --values "$1/users.yaml" \ + > "$1/rendered.yaml" + yq --output-format=json eval-all '.' "$1/rendered.yaml" > "$1/rendered.json" +} + +# render_job renders the chart in CustomConfig mode and unpacks +# what the bootstrap Job runs and mounts into : script.sh is its `sh -c` +# script, bindings/ holds the two files of the mounted ConfigMap. -j keeps an +# empty value an empty file, as the kubelet writes it. +render_job() { + jq -n --argjson users "$2" ' + {_cluster: {"oidc-enabled": "false"}, + oidc: {mode: "CustomConfig", + customConfig: {config: "apiVersion: apiserver.config.k8s.io/v1beta1\nkind: AuthenticationConfiguration\njwt: []\n"}, + users: $users}}' > "$1/values.yaml" + helm template bindings packages/apps/kubernetes \ + --namespace tenant-test \ + --values packages/apps/kubernetes/tests/values/oidc-system.yaml \ + --values "$1/values.yaml" \ + > "$1/rendered.yaml" + yq --output-format=json eval-all '.' "$1/rendered.yaml" > "$1/rendered.json" + jq -s -j '.[] | select(.kind == "Job" and .metadata.name == "bindings-oidc-bootstrap") + | .spec.template.spec.containers[0].command[2]' "$1/rendered.json" > "$1/script.sh" + mkdir -p "$1/bindings" + jq -s -j '.[] | select(.kind == "ConfigMap" and .metadata.name == "bindings-oidc-bindings") + | .data["crbs.yaml"]' "$1/rendered.json" > "$1/bindings/crbs.yaml" + jq -s -j '.[] | select(.kind == "ConfigMap" and .metadata.name == "bindings-oidc-bindings") + | .data["desired.txt"]' "$1/rendered.json" > "$1/bindings/desired.txt" +} + +# fake_kubectl puts a kubectl first on PATH that logs every call and +# answers the script's list of existing bindings with . +fake_kubectl() { + mkdir -p "$1/bin" + printf '%s' "$2" > "$1/existing" + cat > "$1/bin/kubectl" <<'KEOF' +#!/bin/sh +echo "$*" >> "$KLOG" +case "$*" in + *"get clusterrolebindings"*) cat "$EXISTING" ;; +esac +KEOF + chmod +x "$1/bin/kubectl" +} + +# run_job runs the unpacked script as the container does and leaves its +# status in $rc and its output in /out. Run by bash, which has the pipefail +# the script sets and which is what the unit lane runs under; the container's own +# shell is not exercised. +run_job() { + : > "$1/kubectl.log" + echo kubeconfig > "$1/kubeconfig" + rc=0 + env PATH="$1/bin:$PATH" KLOG="$1/kubectl.log" EXISTING="$1/existing" HOME="$1" \ + KUBECONFIG_TENANT="$1/kubeconfig" RELEASE=bindings RELEASE_NAMESPACE=tenant-test \ + OIDC_MODE=CustomConfig OIDC_BINDINGS_DIR="$1/bindings" \ + bash "$1/script.sh" > "$1/out" 2>&1 || rc=$? +} + +@test "the OIDC bootstrap Job script stays under the exec argument cap and carries no user" { + dir=$(mktemp -d) + render_users "$dir" "$USERS" + jq -s -r '.[] | select(.kind == "Job" and .metadata.name == "bindings-oidc-bootstrap") + | .spec.template.spec.containers[0].command[2]' "$dir/rendered.json" > "$dir/script" + size=$(wc -c < "$dir/script") + [ "$size" -gt 0 ] + [ "$size" -lt 131072 ] + if grep -q -E 'user[0-9]+@example\.org' "$dir/script"; then + echo "the Job script still carries users[] entries" >&2 + false + fi + rm -rf "$dir" +} + +@test "every user keeps one ClusterRoleBinding with its old name and role in the bindings ConfigMap" { + dir=$(mktemp -d) + render_users "$dir" "$USERS" + jq -s -r '.[] | select(.kind == "ConfigMap" and .metadata.name == "bindings-oidc-bindings") + | .data["crbs.yaml"]' "$dir/rendered.json" > "$dir/crbs.yaml" + jq -s -r '.[] | select(.kind == "ConfigMap" and .metadata.name == "bindings-oidc-bindings") + | .data["desired.txt"]' "$dir/rendered.json" > "$dir/desired.txt" + [ -s "$dir/crbs.yaml" ] + yq --output-format=json eval-all '.' "$dir/crbs.yaml" | jq -s '.' > "$dir/crbs.json" + + [ "$(jq 'length' "$dir/crbs.json")" -eq "$USERS" ] + [ "$(jq -r '[.[].subjects[0].name] | unique | length' "$dir/crbs.json")" -eq "$USERS" ] + [ "$(jq -r '[.[] | select(.roleRef.name == "cluster-admin")] | length' "$dir/crbs.json")" -eq $(( (USERS + 6) / 7 )) ] + + # The name is what the prune step and every binding already in a tenant cluster + # go by, so it must not move: cozystack-oidc- plus the first 16 hex digits of + # sha256("-"). + for i in 0 1 6 7; do + email="user$i@example.org" + name="cozystack-oidc-$(printf '%s' "bindings-$email" | sha256sum | cut -c1-16)" + [ "$(jq -r --arg e "$email" '.[] | select(.subjects[0].name == $e) | .metadata.name' "$dir/crbs.json")" = "$name" ] + grep -q -x -F "$name" "$dir/desired.txt" + done + + # The list the prune step compares against is exactly the applied names. + [ "$(jq -r '.[].metadata.name' "$dir/crbs.json" | sort)" = "$(grep . "$dir/desired.txt" | sort)" ] + rm -rf "$dir" +} + +@test "the Job applies the mounted bindings and deletes only the bindings no user has" { + dir=$(mktemp -d) + render_job "$dir" '[{"email":"alice@example.org","role":"admin"},{"email":"bob@example.org","role":"view"}]' + alice="cozystack-oidc-$(printf '%s' 'bindings-alice@example.org' | sha256sum | cut -c1-16)" + bob="cozystack-oidc-$(printf '%s' 'bindings-bob@example.org' | sha256sum | cut -c1-16)" + fake_kubectl "$dir" "$alice cozystack-oidc-000000000000dead $bob cozystack-oidc-000000000000beef" + run_job "$dir" + if [ "$rc" -ne 0 ]; then + cat "$dir/out" + false + fi + grep -q -F -- "apply --filename $dir/bindings/crbs.yaml" "$dir/kubectl.log" + grep -q -F -- "delete clusterrolebinding cozystack-oidc-000000000000dead --ignore-not-found" "$dir/kubectl.log" + grep -q -F -- "delete clusterrolebinding cozystack-oidc-000000000000beef --ignore-not-found" "$dir/kubectl.log" + if grep -F -e "delete clusterrolebinding $alice" -e "delete clusterrolebinding $bob" "$dir/kubectl.log"; then + echo "the Job deleted a binding a user still has" >&2 + false + fi + [ "$(grep -c 'delete clusterrolebinding' "$dir/kubectl.log")" -eq 2 ] + rm -rf "$dir" +} + +@test "a release with no users applies nothing and deletes every binding it left behind" { + dir=$(mktemp -d) + render_job "$dir" '[]' + fake_kubectl "$dir" "cozystack-oidc-000000000000dead cozystack-oidc-000000000000beef" + run_job "$dir" + if [ "$rc" -ne 0 ]; then + cat "$dir/out" + false + fi + if grep -q -F -- ' apply ' "$dir/kubectl.log"; then + echo "the Job ran kubectl apply with no bindings to apply" >&2 + false + fi + [ "$(grep -c 'delete clusterrolebinding' "$dir/kubectl.log")" -eq 2 ] + rm -rf "$dir" +} + +@test "the Job stops before deleting anything when the desired list is not mounted" { + dir=$(mktemp -d) + render_job "$dir" '[{"email":"alice@example.org","role":"admin"}]' + fake_kubectl "$dir" "cozystack-oidc-000000000000dead cozystack-oidc-000000000000beef" + rm "$dir/bindings/desired.txt" + run_job "$dir" + [ "$rc" -ne 0 ] + if grep -q -E 'delete clusterrolebinding| apply ' "$dir/kubectl.log"; then + cat "$dir/kubectl.log" + false + fi + rm -rf "$dir" +} diff --git a/hack/linstor-error-report-alerts.bats b/hack/linstor-error-report-alerts.bats new file mode 100644 index 000000000..4c6124aad --- /dev/null +++ b/hack/linstor-error-report-alerts.bats @@ -0,0 +1,32 @@ +#!/usr/bin/env bats +# Replays the LINSTOR error-report alerts from +# packages/system/piraeus-operator/alerts/piraeus-datastore.yaml through +# vmalert-tool, pinned to the VictoriaMetrics release that the +# victoria-metrics-operator deploys by default. Its increase() counts the first +# samples of a series as new when they are small, and the report counts are +# small, so the cases pin that a series which starts over after a controller +# move, a label change or a disconnect does not report old error reports again. +# Only pulling the image touches the network. + +load test_helper + +REPO_ROOT="$(cd "$(dirname "${BATS_TEST_FILENAME:-$0}")/.." && pwd)" +VMALERT_TOOL_IMAGE="victoriametrics/vmalert-tool:v1.136.0@sha256:417346d7b6fdb66d8e3984887c2ad114535ec7d983eeef53381b56c776f333f1" + +@test "LINSTOR error-report alerts pass their vmalert-tool cases" { + docker info >/dev/null 2>&1 || { + echo "docker is required to run the cases in $VMALERT_TOOL_IMAGE" >&2 + return 1 + } + work=$(mktemp -d) + yq '.spec' "$REPO_ROOT/packages/system/piraeus-operator/alerts/piraeus-datastore.yaml" > "$work/rules.yaml" + cp "$REPO_ROOT/hack/testdata/linstor-error-report-alerts/unittest.yaml" "$work/unittest.yaml" + rc=0 + docker run --rm --network none -v "$work:/w:ro" "$VMALERT_TOOL_IMAGE" \ + unittest --files /w/unittest.yaml > "$work/out" 2>&1 || rc=$? + cat "$work/out" + passed=$(grep -cx 'SUCCESS' "$work/out" || true) + rm -rf "$work" + [ "$rc" -eq 0 ] + [ "$passed" -eq 1 ] +} diff --git a/hack/monitoring-agents-vm-cleanup-hook.bats b/hack/monitoring-agents-vm-cleanup-hook.bats new file mode 100644 index 000000000..290a91314 --- /dev/null +++ b/hack/monitoring-agents-vm-cleanup-hook.bats @@ -0,0 +1,312 @@ +#!/usr/bin/env bats +# Behavioural tests for the monitoring-agents pre-delete hook: +# +# packages/system/monitoring-agents/templates/vm-cleanup-hook.yaml +# +# The script is extracted from the rendered chart and RUN against a fake +# kubectl that keeps the VictoriaMetrics objects in a state file, with fake +# `date` and `sleep` so the 60s grace period passes in an instant. The +# helm-unittest suite in packages/system/monitoring-agents/tests/ +# uninstall_test.yaml matches the script text instead, and stayed green when the +# ownership condition was removed, when the finalizer patch was made a no-op and +# when the polling condition was inverted. Each of those turns this file red. +# +# What is pinned here: +# * only objects whose Helm annotations name this release, by name and +# namespace both, are deleted or patched: an object of another release, of +# a same-named release in another namespace, or one Helm does not own, is +# left alone; +# * with the operator gone, the hook waits before touching finalizers, then +# clears them, and nothing of this release is left behind; +# * with the operator alive, it finalizes the objects itself and the hook +# never patches a finalizer; +# * a kind whose CRD is gone, or a release with nothing left, exits 0, since a +# failing pre-delete hook would itself block the uninstall. +# +# Run from the repo root with make bats-unit-tests. Direct status checks +# retain compatibility with cozytest, which has no Bats run/setup helpers. +# Inline cleanup preserves Bats' TAP handler on failed assertions. + +load test_helper + +MA_CHART=packages/system/monitoring-agents +MA_RELEASE=monitoring-agents +MA_NAMESPACE=cozy-monitoring + +# render_hook +# Extract the named Job's shell script from the rendered chart into . The +# non-empty check must be an early `return 1`: hack/cozytest.sh rewrites every +# line matching ^}$ into `return 0` plus `}`, helpers included, so a check left +# in last-command position has its status discarded. +render_hook() { + helm template "$MA_RELEASE" "$MA_CHART" --namespace "$MA_NAMESPACE" \ + | yq eval "select(.kind == \"Job\" and .metadata.name == \"$1\") | .spec.template.spec.containers[0].command[2]" - > "$2" + [ -s "$2" ] || return 1 +} + +# write_fakes +# Emit fake `kubectl`, `date` and `sleep` into . +# +# kubectl reads and writes $STATE, one object per line as +# kind|release-name|release-namespace|namespace|name, where the two release +# fields are the Helm annotations (empty when Helm does not own the object). +# `get` prints this kind's objects in the hook's jsonpath format, or fails for a +# kind listed in $MISSING_KINDS as kubectl does when the CRD is gone. `delete` +# removes the object only when $OPERATOR_LIVE is 1, standing for an operator +# that finalizes it; otherwise the object stays, Terminating. `patch` removes it +# only when the payload actually clears the finalizers. Every call goes to $KLOG. +# +# date advances 1s per call from $CLOCK, so the 60s wait ends after sixty +# of polls, and records each time it returns in $KLOG; sleep records itself, +# and with $SLEEP_ADVANCES=1 also moves $CLOCK by its argument. The log thus +# shows how much fake time passed before each patch. +# No line below is a bare column-0 `}`, so cozytest.sh's parser leaves it alone. +write_fakes() { + cat > "$1/kubectl" <<'KEOF' +#!/bin/sh +echo "kubectl $*" >> "$KLOG" +drop() { + awk -F'|' -v k="$1" -v ns="$2" -v n="$3" '!($1 == k && $4 == ns && $5 == n)' "$STATE" > "$STATE.new" + mv "$STATE.new" "$STATE"; } +case "$1" in + get) + kind=${2%%.*} + case " ${MISSING_KINDS:-} " in + *" $kind "*) + echo "error: the server doesn't have a resource type \"$kind\"" >&2 + exit 1 ;; + esac + awk -F'|' -v k="$kind" '$1 == k { print $2 "|" $3 "|" $4 "|" $5 }' "$STATE" + exit 0 ;; + -n) + ns=$2 verb=$3 kind=${4%%.*} name=$5 + case "$verb" in + delete) + [ "${OPERATOR_LIVE:-0}" = 1 ] && drop "$kind" "$ns" "$name" + echo "$kind \"$name\" deleted" + exit 0 ;; + patch) + case "$*" in + *'"finalizers":null'*) drop "$kind" "$ns" "$name" ;; + esac + echo "$kind \"$name\" patched" + exit 0 ;; + esac ;; +esac +echo "fake kubectl: unexpected call: $*" >&2 +exit 64 +KEOF + cat > "$1/date" <<'KEOF' +#!/bin/sh +c=$(cat "$CLOCK" 2>/dev/null || echo 0) +echo $((c + 1)) > "$CLOCK" +echo "date $((1000000 + c))" >> "$KLOG" +echo $((1000000 + c)) +KEOF + cat > "$1/sleep" <<'KEOF' +#!/bin/sh +echo "sleep $*" >> "$KLOG" +if [ "${SLEEP_ADVANCES:-0}" = 1 ]; then + c=$(cat "$CLOCK" 2>/dev/null || echo 0) + echo $((c + $1)) > "$CLOCK" +fi +KEOF + chmod +x "$1/kubectl" "$1/date" "$1/sleep" +} + +# write_state +# Three objects of this release in two namespaces; a VMRule of another release; +# a VMRule whose release name matches but whose release namespace does not, so +# only the pair of annotations tells it apart; and a VMServiceScrape that +# carries no Helm annotations. +write_state() { + cat > "$1" < +# Run the rendered hook with the fakes first on PATH; its status lands in $rc. +run_hook() { + export KLOG="$1/calls" STATE="$1/state" CLOCK="$1/clock" + : > "$KLOG" + rc=0 + PATH="$1:$PATH" sh "$1/hook.sh" > "$1/out" 2> "$1/err" || rc=$? +} + +@test "a render that produces no script fails instead of passing as a no-op" { + # Guards the guard: every test below runs whatever render_hook produced, so an + # empty render would satisfy the exit-0 assertions without executing a line of + # the hook. + tmp=$(mktemp -d) + if render_hook no-such-job "$tmp/hook.sh"; then + echo "FAIL: render_hook reported success for a Job name the chart never emits" + false + fi + rm -rf "$tmp" +} + +@test "vm cleanup hook clears the finalizers of this release's objects only, after the grace period" { + tmp=$(mktemp -d) + write_fakes "$tmp" + write_state "$tmp/state" + render_hook vm-objects-cleanup "$tmp/hook.sh" + export OPERATOR_LIVE=0 MISSING_KINDS="" + run_hook "$tmp" + + if [ "$rc" -ne 0 ]; then + echo "FAIL: hook exited $rc" + cat "$tmp/out" "$tmp/err" + false + fi + for obj in "vmagents.operator.victoriametrics.com vmagent" \ + "vmrules.operator.victoriametrics.com alerts-node" \ + "vmservicescrapes.operator.victoriametrics.com operator"; do + if ! grep -q -- " delete $obj --wait=false" "$tmp/calls"; then + echo "FAIL: $obj was not deleted" + cat "$tmp/calls" + false + fi + done + # The objects of this release must be gone, which the fake only does for a + # patch that really clears the finalizers. + if grep -q "^[a-z]*|$MA_RELEASE|$MA_NAMESPACE|" "$tmp/state"; then + echo "FAIL: objects of this release are still there, Terminating" + cat "$tmp/state" "$tmp/calls" + false + fi + # Another release's object, one of a same-named release in another + # namespace, and an object Helm does not own are never touched. + if grep -E -q -- ' (delete|patch) [a-z.]+ (foreign-rule|foreign-ns-rule|unmanaged-scrape)( |$)' "$tmp/calls"; then + echo "FAIL: the hook touched an object this release does not own" + cat "$tmp/calls" + false + fi + if [ "$(grep -c '|' "$tmp/state")" -ne 3 ]; then + echo "FAIL: the three objects this release does not own should remain" + cat "$tmp/state" + false + fi + # The operator gets its chance first: the hook polls and sleeps before the + # first patch, and does not stop waiting before the 60s are up. + first_patch=$(grep -n ' patch ' "$tmp/calls" | head -1 | cut -d: -f1) + if [ -z "$first_patch" ]; then + echo "FAIL: no finalizer was cleared" + cat "$tmp/calls" + false + fi + # The first date call sets the deadline; the last one before the first patch + # is the time the hook gave up waiting. + start=$(grep '^date ' "$tmp/calls" | head -1 | cut -d' ' -f2) + waited_until=$(head -n "$first_patch" "$tmp/calls" | grep '^date ' | tail -1 | cut -d' ' -f2) + if [ -z "$start" ] || [ $((waited_until - start)) -lt 60 ]; then + echo "FAIL: finalizers cleared after $((waited_until - start))s; the 60s grace period was cut short" + cat "$tmp/calls" + false + fi + rm -rf "$tmp" +} + +@test "vm cleanup hook clears the finalizers before its Job's deadline" { + # The grace-period test above keeps sleep free so a shortened wait shows; here + # sleep costs its argument, so a poll interval long enough to overshoot the + # Job's activeDeadlineSeconds fails instead of passing. + tmp=$(mktemp -d) + write_fakes "$tmp" + write_state "$tmp/state" + render_hook vm-objects-cleanup "$tmp/hook.sh" + job_deadline=$(helm template "$MA_RELEASE" "$MA_CHART" --namespace "$MA_NAMESPACE" \ + | yq eval 'select(.kind == "Job" and .metadata.name == "vm-objects-cleanup") | .spec.activeDeadlineSeconds' -) + export OPERATOR_LIVE=0 MISSING_KINDS="" SLEEP_ADVANCES=1 + run_hook "$tmp" + unset SLEEP_ADVANCES + + if [ "$rc" -ne 0 ]; then + echo "FAIL: hook exited $rc" + cat "$tmp/out" "$tmp/err" + false + fi + first_patch=$(grep -n ' patch ' "$tmp/calls" | head -1 | cut -d: -f1) + start=$(grep '^date ' "$tmp/calls" | head -1 | cut -d' ' -f2) + waited_until=$(head -n "${first_patch:-0}" "$tmp/calls" | grep '^date ' | tail -1 | cut -d' ' -f2) + if [ -z "$first_patch" ] || [ -z "$job_deadline" ] || [ $((waited_until - start)) -ge "$job_deadline" ]; then + echo "FAIL: first finalizer patch at $((waited_until - start))s, Job deadline ${job_deadline}s" + cat "$tmp/calls" + false + fi + rm -rf "$tmp" +} + +@test "vm cleanup hook leaves the finalizers to a live operator" { + tmp=$(mktemp -d) + write_fakes "$tmp" + write_state "$tmp/state" + render_hook vm-objects-cleanup "$tmp/hook.sh" + export OPERATOR_LIVE=1 MISSING_KINDS="" + run_hook "$tmp" + + if [ "$rc" -ne 0 ]; then + echo "FAIL: hook exited $rc" + cat "$tmp/out" "$tmp/err" + false + fi + if ! grep -q ' delete vmagents.operator.victoriametrics.com vmagent ' "$tmp/calls"; then + echo "FAIL: the VMAgent was not deleted" + cat "$tmp/calls" + false + fi + if grep -q ' patch ' "$tmp/calls"; then + echo "FAIL: the hook cleared finalizers the live operator was handling" + cat "$tmp/calls" + false + fi + rm -rf "$tmp" +} + +@test "vm cleanup hook exits 0 and cleans the other kinds when a CRD is gone" { + tmp=$(mktemp -d) + write_fakes "$tmp" + write_state "$tmp/state" + render_hook vm-objects-cleanup "$tmp/hook.sh" + export OPERATOR_LIVE=0 MISSING_KINDS="vmrules vmpodscrapes vmnodescrapes" + run_hook "$tmp" + + if [ "$rc" -ne 0 ]; then + echo "FAIL: hook exited $rc with a CRD gone, which would block the uninstall" + cat "$tmp/out" "$tmp/err" + false + fi + if grep -q "^vmagents|$MA_RELEASE|" "$tmp/state"; then + echo "FAIL: the VMAgent was left Terminating because another kind's CRD was gone" + cat "$tmp/state" "$tmp/calls" + false + fi + rm -rf "$tmp" +} + +@test "vm cleanup hook exits 0 without deleting anything when the release owns nothing" { + tmp=$(mktemp -d) + write_fakes "$tmp" + printf 'vmrules|other|%s|%s|foreign-rule\nvmrules|%s|other-namespace|%s|foreign-ns-rule\n' \ + "$MA_NAMESPACE" "$MA_NAMESPACE" "$MA_RELEASE" "$MA_NAMESPACE" > "$tmp/state" + render_hook vm-objects-cleanup "$tmp/hook.sh" + export OPERATOR_LIVE=0 MISSING_KINDS="" + run_hook "$tmp" + + if [ "$rc" -ne 0 ]; then + echo "FAIL: hook exited $rc with nothing to clean" + cat "$tmp/out" "$tmp/err" + false + fi + if grep -E -q ' (delete|patch) ' "$tmp/calls"; then + echo "FAIL: the hook deleted or patched with nothing of this release left" + cat "$tmp/calls" + false + fi + rm -rf "$tmp" +} diff --git a/hack/qdrant-monitoring.bats b/hack/qdrant-monitoring.bats new file mode 100644 index 000000000..7c27a6423 --- /dev/null +++ b/hack/qdrant-monitoring.bats @@ -0,0 +1,49 @@ +#!/usr/bin/env bats + +load test_helper + +setup() { + strict_setup + REPO_ROOT="$(cd "$BATS_TEST_DIRNAME/.." && pwd)" + export KUBECONFIG=/dev/null +} + +render_monitor() { + helm template test-qdrant "$REPO_ROOT/packages/apps/qdrant" \ + --namespace tenant-test --set _namespace.host=tenant.example.test "$@" > "$BATS_TEST_TMPDIR/app.yaml" + yq 'select(.kind == "HelmRelease") | .spec.values' "$BATS_TEST_TMPDIR/app.yaml" > "$BATS_TEST_TMPDIR/values.yaml" + helm template test-qdrant-system "$REPO_ROOT/packages/system/qdrant" \ + --namespace tenant-test --values "$BATS_TEST_TMPDIR/values.yaml" > "$BATS_TEST_TMPDIR/system.yaml" + yq 'select(.kind == "HelmRelease") | { + "apiVersion": "kustomize.config.k8s.io/v1beta1", + "kind": "Kustomization", + "resources": ["system.yaml"], + "patches": (.spec.postRenderers[0].kustomize.patches // []) + }' "$BATS_TEST_TMPDIR/app.yaml" > "$BATS_TEST_TMPDIR/kustomization.yaml" + kubectl kustomize "$BATS_TEST_TMPDIR" > "$BATS_TEST_TMPDIR/rendered.yaml" + yq 'select(.kind == "ServiceMonitor") | .spec.endpoints[0]' "$BATS_TEST_TMPDIR/rendered.yaml" > "$BATS_TEST_TMPDIR/endpoint.yaml" + [ "$(yq '.authorization.credentials.name' "$BATS_TEST_TMPDIR/endpoint.yaml")" = test-qdrant-apikey ] + [ "$(yq '.authorization.credentials.key' "$BATS_TEST_TMPDIR/endpoint.yaml")" = api-key ] + [ "$(yq '.port' "$BATS_TEST_TMPDIR/endpoint.yaml")" = http ] +} + +@test "TLS monitoring uses the issued CA and a certificate SAN" { + render_monitor --set tls.enabled=true --set _cluster.cluster-domain=cluster.test + [ "$(yq '.scheme' "$BATS_TEST_TMPDIR/endpoint.yaml")" = https ] + [ "$(yq '.tlsConfig.ca.secret.name' "$BATS_TEST_TMPDIR/endpoint.yaml")" = test-qdrant-tls ] + [ "$(yq '.tlsConfig.ca.secret.key' "$BATS_TEST_TMPDIR/endpoint.yaml")" = ca.crt ] + [ "$(yq '.tlsConfig.insecureSkipVerify // false' "$BATS_TEST_TMPDIR/endpoint.yaml")" = false ] + server_name="$(yq '.tlsConfig.serverName' "$BATS_TEST_TMPDIR/endpoint.yaml")" + SERVER_NAME="$server_name" yq --exit-status 'select(.kind == "Certificate" and .metadata.name == "test-qdrant-tls") | .spec.dnsNames | contains([strenv(SERVER_NAME)])' "$BATS_TEST_TMPDIR/app.yaml" +} + +@test "external Qdrant enables HTTPS monitoring by default" { + render_monitor --set external=true + [ "$(yq '.scheme' "$BATS_TEST_TMPDIR/endpoint.yaml")" = https ] +} + +@test "disabled TLS keeps HTTP monitoring without TLS configuration" { + render_monitor --set external=true --set tls.enabled=false + [ "$(yq '.scheme' "$BATS_TEST_TMPDIR/endpoint.yaml")" = http ] + [ "$(yq 'has("tlsConfig")' "$BATS_TEST_TMPDIR/endpoint.yaml")" = false ] +} diff --git a/hack/seaweedfs-object-lock-actions.bats b/hack/seaweedfs-object-lock-actions.bats new file mode 100644 index 000000000..f209caaa7 --- /dev/null +++ b/hack/seaweedfs-object-lock-actions.bats @@ -0,0 +1,302 @@ +#!/usr/bin/env bats + +load test_helper + +SCRIPT="$PWD/packages/system/seaweedfs/files/object-lock-actions.sh" + +setup() { + strict_setup + BIN="$BATS_TEST_TMPDIR/bin" + mkdir -p "$BIN" + export STATE="$BATS_TEST_TMPDIR/iam.json" + export CALLS="$BATS_TEST_TMPDIR/calls" + export KUBECTL_LOG="$BATS_TEST_TMPDIR/kubectl" + : > "$CALLS" + : > "$KUBECTL_LOG" + cat > "$BIN/weed" <<'EOF' +#!/bin/bash +set -eu +[ "$1" = shell ] || exit 2 +[ -n "${WEED_SLEEP:-}" ] && sleep "$WEED_SLEEP" +drop=false +if [ -n "${WEED_DROP_SESSIONS:-}" ]; then + n=$(cat "$STATE.sessions" 2>/dev/null || echo 0) + # Only sessions that apply count. + input=$(cat) + case $input in *" -apply"*) + n=$((n + 1)); echo "$n" > "$STATE.sessions" + [ "$n" -le "$WEED_DROP_SESSIONS" ] && drop=true ;; + esac + exec <<< "$input" +fi +while read -r line; do + case $line in + "s3.configure") + if [ -n "${WEED_READS_OK:-}" ]; then + reads=$(cat "$STATE.reads" 2>/dev/null || echo 0) + echo $((reads + 1)) > "$STATE.reads" + [ "$reads" -lt "$WEED_READS_OK" ] || exit 1 + fi + if [ -n "${IDENTITIES_DIR:-}" ]; then + jq --slurp '{identities: .}' "$IDENTITIES_DIR"/*.json + else + cat "$STATE" + fi + ;; + "s3.configure -user="*) + echo "$line" >> "$CALLS" + user=${line#s3.configure -user=}; user=${user%% *} + rest=${line#* -actions=} + actions=${rest%% *} + apply=false + case $rest in *" -apply") apply=true ;; esac + if [ "$user" = "${WEED_UNRESOLVED:-}" ]; then + current='{"name":"'"$user"'","credentials":[],"actions":[]}' + elif [ -n "${IDENTITIES_DIR:-}" ]; then + current=$(cat "$IDENTITIES_DIR/$user.json") + else + current=$(jq -c --arg u "$user" '.identities[] | select(.name == $u)' "$STATE") + fi + updated=$(jq -c --arg a "$actions" '.actions = reduce ($a | split(","))[] as $x (.actions; if index([$x]) then . else . + [$x] end)' <<< "$current") + if $apply; then + { [ -n "${WEED_NOOP_APPLY:-}" ] || $drop; } && continue + if [ -n "${IDENTITIES_DIR:-}" ]; then + printf '%s\n' "$updated" > "$IDENTITIES_DIR/$user.json" + else + jq --arg u "$user" --argjson id "$updated" \ + '.identities |= map(if .name == $u then $id else . end)' "$STATE" > "$STATE.new" + mv "$STATE.new" "$STATE" + fi + echo "$updated" + else + echo "$updated" + echo 'Running in simulation mode. Use "-apply" option to apply the changes.' + fi + ;; + *) + exit 3 + ;; + esac +done +EOF + cat > "$BIN/kubectl" <<'EOF' +#!/bin/sh +case $1 in + get) echo "ARGS: $*" >> "$KUBECTL_LOG" ;; + *) { echo "ARGS: $*"; cat; } >> "$KUBECTL_LOG" ;; +esac +[ -z "${KUBECTL_SLEEP:-}" ] || exec sleep "$KUBECTL_SLEEP" +[ "$1" != get ] || printf 0b5e1a7e-0000-4000-8000-000000000001 +EOF + chmod +x "$BIN/weed" "$BIN/kubectl" + export PATH="$BIN:$PATH" + export MASTER=seaweedfs-master:9333 FILER=seaweedfs-filer-client:8888 + export NAMESPACE=tenant-foo RELEASE=seaweedfs-system + export ATTEMPTS=2 RETRY_DELAY=0 SHELL_TIMEOUT=5 +} + +identity() { + printf '{"name":"%s","credentials":[{"accessKey":"AK-%s","secretKey":"SECRET-%s"}],"actions":%s,"isStatic":%s}' \ + "$1" "$1" "$1" "$2" "${3:-false}" +} + +state() { + printf '{"identities":[%s]}\n' "$(IFS=,; echo "$*")" > "$STATE" +} + +event() { + sed '1,/^ARGS: create --filename -$/d' "$KUBECTL_LOG" | jq --exit-status "$@" > /dev/null +} + +actions_of() { + jq -c --arg u "$1" '.identities[] | select(.name == $u) | .actions | sort' "$STATE" +} + +@test "readwrite identity gains the Get and Put Object Lock actions for its bucket" { + state "$(identity rw '["Read:b1","Write:b1","List:b1","Tagging:b1"]')" + "$SCRIPT" + [ "$(actions_of rw)" = '["GetBucketObjectLockConfiguration:b1","GetObjectLegalHold:b1","GetObjectRetention:b1","List:b1","PutBucketObjectLockConfiguration:b1","PutObjectLegalHold:b1","PutObjectRetention:b1","Read:b1","Tagging:b1","Write:b1"]' ] +} + +@test "per-identity IAM migration preserves old credentials and leaves an already upgraded grant unchanged" { + export IDENTITIES_DIR="$BATS_TEST_TMPDIR/identities" + mkdir -p "$IDENTITIES_DIR" + state + identity old '["Read:b1","Write:b1","List:b1","Tagging:b1"]' > "$IDENTITIES_DIR/old.json" + identity new '["Read:b2","List:b2","GetObjectRetention:b2","GetObjectLegalHold:b2","GetBucketObjectLockConfiguration:b2"]' > "$IDENTITIES_DIR/new.json" + old_credentials=$(jq -c '.credentials' "$IDENTITIES_DIR/old.json") + new_identity=$(cat "$IDENTITIES_DIR/new.json") + "$SCRIPT" + [ "$(jq -c '.credentials' "$IDENTITIES_DIR/old.json")" = "$old_credentials" ] + [ "$(jq -c '.actions | sort' "$IDENTITIES_DIR/old.json")" = '["GetBucketObjectLockConfiguration:b1","GetObjectLegalHold:b1","GetObjectRetention:b1","List:b1","PutBucketObjectLockConfiguration:b1","PutObjectLegalHold:b1","PutObjectRetention:b1","Read:b1","Tagging:b1","Write:b1"]' ] + [ "$(cat "$IDENTITIES_DIR/new.json")" = "$new_identity" ] + [ "$(cat "$STATE")" = '{"identities":[]}' ] + [ "$(grep -c -- ' -apply$' "$CALLS")" -eq 1 ] + [ ! -s "$KUBECTL_LOG" ] + : > "$CALLS" + "$SCRIPT" + [ ! -s "$CALLS" ] +} + +@test "readonly identity gains only the Get Object Lock actions" { + state "$(identity ro '["Read:b1","List:b1"]')" + "$SCRIPT" + [ "$(actions_of ro)" = '["GetBucketObjectLockConfiguration:b1","GetObjectLegalHold:b1","GetObjectRetention:b1","List:b1","Read:b1"]' ] +} + +@test "the suffix of each grant is carried over verbatim, bare grants stay bare" { + state "$(identity w '["Write","Read:logs/*"]')" + "$SCRIPT" + [ "$(actions_of w)" = '["GetBucketObjectLockConfiguration:logs/*","GetObjectLegalHold:logs/*","GetObjectRetention:logs/*","PutBucketObjectLockConfiguration","PutObjectLegalHold","PutObjectRetention","Read:logs/*","Write"]' ] +} + +@test "actions that only start with Read or Write imply nothing" { + state "$(identity acp '["ReadAcp:b1","WriteAcp:b1","List:b1"]')" + "$SCRIPT" + [ "$(actions_of acp)" = '["List:b1","ReadAcp:b1","WriteAcp:b1"]' ] + [ ! -s "$CALLS" ] +} + +@test "admin and static identities are left alone" { + state "$(identity admin '["Admin"]')" "$(identity static '["Read","Write"]' true)" + "$SCRIPT" + [ "$(actions_of admin)" = '["Admin"]' ] + [ "$(actions_of static)" = '["Read","Write"]' ] + [ ! -s "$CALLS" ] +} + +@test "a second run changes nothing" { + state "$(identity rw '["Read:b1","Write:b1"]')" "$(identity ro '["Read:b2"]')" + "$SCRIPT" + [ "$(grep -c -- ' -apply$' "$CALLS")" -eq 2 ] + : > "$CALLS" + "$SCRIPT" + [ ! -s "$CALLS" ] +} + +@test "secret keys never reach the output" { + state "$(identity rw '["Read:b1","Write:b1"]')" + out=$("$SCRIPT" 2>&1) + case $out in + *SECRET-*) echo "FAIL: secret key printed: $out"; false ;; + esac + case $out in + *rw*) ;; + *) echo "FAIL: the identity it changed is not named: $out"; false ;; + esac +} + +@test "a grant that does not stick ends in a Warning Event on the HelmRelease and exit 0" { + state "$(identity rw '["Read:b1","Write:b1"]')" + WEED_NOOP_APPLY=1 "$SCRIPT" + [ "$(grep -c -- ' -apply$' "$CALLS")" -eq 2 ] + grep -q '^ARGS: create --filename -$' "$KUBECTL_LOG" + event '.type == "Warning"' + event '.involvedObject.kind == "HelmRelease"' + event '.involvedObject.name == "seaweedfs-system"' + event '.involvedObject.namespace == "tenant-foo"' + event '.involvedObject.uid == "0b5e1a7e-0000-4000-8000-000000000001"' + grep -q 'rw' "$KUBECTL_LOG" +} + +@test "an unreachable filer ends in a Warning Event and exit 0" { + rm -f "$STATE" + "$SCRIPT" + event '.type == "Warning"' + grep -q 'could not be read' "$KUBECTL_LOG" +} + +@test "a weed shell that never returns is cut off and still ends in an Event" { + state "$(identity rw '["Read:b1","Write:b1"]')" + SHELL_TIMEOUT=3 WEED_SLEEP=60 "$SCRIPT" + event '.type == "Warning"' +} + +@test "an identity s3.configure cannot resolve is never applied over" { + state "$(identity rw '["Read:b1","Write:b1"]')" "$(identity lost '["Read:b2","Write:b2"]')" + WEED_UNRESOLVED=lost "$SCRIPT" + [ "$(jq -c '.identities[] | select(.name == "lost")' "$STATE")" = '{"name":"lost","credentials":[{"accessKey":"AK-lost","secretKey":"SECRET-lost"}],"actions":["Read:b2","Write:b2"],"isStatic":false}' ] + if grep -q -- '-user=lost .* -apply$' "$CALLS"; then echo "FAIL: applied over an unresolved identity"; false; fi + [ "$(actions_of rw)" = '["GetBucketObjectLockConfiguration:b1","GetObjectLegalHold:b1","GetObjectRetention:b1","PutBucketObjectLockConfiguration:b1","PutObjectLegalHold:b1","PutObjectRetention:b1","Read:b1","Write:b1"]' ] + event '.type == "Warning"' + grep -q 'lost' "$KUBECTL_LOG" +} + +@test "output without an IAM configuration counts as a failed read" { + echo 'error: connection refused' > "$STATE" + "$SCRIPT" + grep -q 'could not be read' "$KUBECTL_LOG" +} + +@test "no Event is written when every grant sticks" { + state "$(identity rw '["Read:b1","Write:b1"]')" + "$SCRIPT" + [ ! -s "$KUBECTL_LOG" ] +} + +@test "JSON that is not an IAM configuration counts as a failed read" { + echo '{"error":"not ready"}' > "$STATE" + "$SCRIPT" + grep -q 'could not be read' "$KUBECTL_LOG" +} + +@test "grants that stick only on the last attempt raise no Event" { + state "$(identity rw '["Read:b1","Write:b1"]')" + WEED_DROP_SESSIONS=1 "$SCRIPT" + [ "$(grep -c -- ' -apply$' "$CALLS")" -eq 2 ] + [ ! -s "$KUBECTL_LOG" ] +} + +@test "a name or action weed shell would split never reaches a command line and is reported" { + state "$(identity rw '["Read:b1","Write:b1"]')" "$(identity 'x;s3.configure -user=rw -actions=Admin -apply' '["Read:b2"]')" "$(identity y '["Read:b3;s3.configure -user=rw -actions=Admin"]')" + "$SCRIPT" + if grep -q -- 'x;' "$CALLS"; then echo "FAIL: unsafe name reached weed shell"; false; fi + if grep -q -- 'Admin' "$CALLS"; then echo "FAIL: injected action reached weed shell"; false; fi + [ "$(actions_of rw)" = '["GetBucketObjectLockConfiguration:b1","GetObjectLegalHold:b1","GetObjectRetention:b1","PutBucketObjectLockConfiguration:b1","PutObjectLegalHold:b1","PutObjectRetention:b1","Read:b1","Write:b1"]' ] + event '.type == "Warning"' +} + +@test "a final read that fails reports the outcome as unverified, not the last plan" { + state "$(identity rw '["Read:b1","Write:b1"]')" + WEED_READS_OK=1 "$SCRIPT" + [ "$(actions_of rw)" = '["GetBucketObjectLockConfiguration:b1","GetObjectLegalHold:b1","GetObjectRetention:b1","PutBucketObjectLockConfiguration:b1","PutObjectLegalHold:b1","PutObjectRetention:b1","Read:b1","Write:b1"]' ] + grep -q 'could not be read' "$KUBECTL_LOG" + if grep -q 'missing them' "$KUBECTL_LOG"; then echo "FAIL: reported a stale plan"; false; fi +} + +# The stub logs its call before it hangs, so SHELL_TIMEOUT has to leave a +# loaded runner time to start it. +@test "a kubectl that never returns is cut off and the Job still exits 0" { + state "$(identity rw '["Read:b1","Write:b1"]')" + start=$SECONDS + SHELL_TIMEOUT=3 KUBECTL_SLEEP=60 WEED_NOOP_APPLY=1 "$SCRIPT" 2> "$BATS_TEST_TMPDIR/stderr" + [ $((SECONDS - start)) -lt 60 ] + grep -q '^ARGS: get helmrelease' "$KUBECTL_LOG" + grep -q '^ARGS: create --filename -$' "$KUBECTL_LOG" + grep -q 'could not record the Warning Event' "$BATS_TEST_TMPDIR/stderr" +} + +@test "a name or action ending in a newline never reaches a command line and is reported" { + state "$(identity rw '["Read:b1","Write:b1"]')" "$(identity 'foo\n' '["Read:b2"]')" "$(identity y '["Read:b3\n"]')" + "$SCRIPT" + if grep -q -- '-user=foo' "$CALLS"; then echo "FAIL: name with a trailing newline reached weed shell"; false; fi + if grep -q -- '-user=y' "$CALLS"; then echo "FAIL: action with a trailing newline reached weed shell"; false; fi + [ "$(actions_of rw)" = '["GetBucketObjectLockConfiguration:b1","GetObjectLegalHold:b1","GetObjectRetention:b1","PutBucketObjectLockConfiguration:b1","PutObjectLegalHold:b1","PutObjectRetention:b1","Read:b1","Write:b1"]' ] + event '.type == "Warning"' + grep -q 'foo' "$KUBECTL_LOG" +} + +@test "a document marker or a control character in an identity name stays inside the Event message" { + state "$(identity rw '["Read:b1","Write:b1"]')" "$(identity 'x\n--- \"y\\\u0080' '["Read:b2"]')" + "$SCRIPT" + [ "$(sed '1,/^ARGS: create --filename -$/d' "$KUBECTL_LOG" | jq --slurp length)" -eq 1 ] + event --arg name $'x\n--- "y\\\xc2\x80' '.message | contains($name)' +} + +@test "the identity public-read buckets share is never granted" { + state "$(identity rw '["Read:b1","Write:b1"]')" "$(identity anonymous '["Read:b2"]')" + "$SCRIPT" + [ "$(actions_of anonymous)" = '["Read:b2"]' ] + if grep -q -- '-user=anonymous' "$CALLS"; then echo "FAIL: anonymous reached weed shell"; false; fi + [ ! -s "$KUBECTL_LOG" ] +} diff --git a/hack/seaweedfs-orphan-identities.bats b/hack/seaweedfs-orphan-identities.bats new file mode 100644 index 000000000..4f7db6ab0 --- /dev/null +++ b/hack/seaweedfs-orphan-identities.bats @@ -0,0 +1,336 @@ +#!/usr/bin/env bats +# Unit tests for packages/system/seaweedfs/files/orphan-identities.sh, the +# post-install/post-upgrade hook that removes the per-identity IAM files of BucketAccesses +# that no longer exist. Drives it against a fake `weed shell` that keeps the +# identity files in a directory, and a fake kubectl. + +load test_helper + +SCRIPT="$PWD/packages/system/seaweedfs/files/orphan-identities.sh" + +OTHER=0b5e1a7e-0000-4000-8000-000000000009 +LIVE=0b5e1a7e-0000-4000-8000-00000000000a +GONE=0b5e1a7e-0000-4000-8000-00000000000b +GONE2=0b5e1a7e-0000-4000-8000-00000000000c + +setup() { + strict_setup + BIN="$BATS_TEST_TMPDIR/bin" + mkdir -p "$BIN" + export IDS="$BATS_TEST_TMPDIR/identities" + export BA_JSON="$BATS_TEST_TMPDIR/bucketaccesses.json" + export KUBECTL_LOG="$BATS_TEST_TMPDIR/kubectl" + export WEED_LOG="$BATS_TEST_TMPDIR/weed" + mkdir -p "$IDS" + : > "$KUBECTL_LOG" + : > "$WEED_LOG" + # One BucketAccess with no file, so the listing is never empty by accident. + echo '{"apiVersion":"v1","kind":"List","items":[{"metadata":{"uid":"'"$OTHER"'"},"status":{"accountID":"ba-'"$OTHER"'"}}]}' > "$BA_JSON" + cat > "$BIN/weed" <<'EOF' +#!/bin/bash +# A weed shell session over $IDS, one file per identity. +# Like the real one it reports a failed command on stderr and exits 0. +# WEED_SLEEP hangs every session. WEED_LS_FAIL fails a listing (WEED_LS_FAIL_FROM: from that listing on), +# WEED_RM_FAIL makes every removal fail. +set -eu +[ "$1" = shell ] || exit 2 +echo session >> "$WEED_LOG" +[ -z "${WEED_SLEEP:-}" ] || sleep "$WEED_SLEEP" +while read -r cmd path; do + echo "$cmd $path" >> "$WEED_LOG" + case $cmd in + fs.ls) + [ "$path" = /etc/iam/identities ] || exit 3 + n=$(($(cat "$WEED_LOG.ls" 2>/dev/null || echo 0) + 1)); echo "$n" > "$WEED_LOG.ls" + [ "$n" -ge "${WEED_LS_FAIL_FROM:-1}" ] || { ls -1 "$IDS"; continue; } + case ${WEED_LS_FAIL:-} in + exit) exit 1 ;; + print) echo "error: list $path: connection refused" >&2; continue ;; + esac + ls -1 "$IDS" + ;; + fs.rm) + [ -z "${WEED_RM_FAIL:-}" ] || { echo "error: rm $path: permission denied" >&2; continue; } + rm "$IDS/${path##*/}" + ;; + *) + exit 4 + ;; + esac +done +EOF + cat > "$BIN/kubectl" <<'EOF' +#!/bin/sh +echo "ARGS: $*" >> "$KUBECTL_LOG" +# Like the real one: any --request-timeout drops the in-cluster credentials. +case " $* " in + *" --request-timeout"*) echo 'The connection to the server localhost:8080 was refused' >&2; exit 1 ;; +esac +[ -z "${KUBECTL_SLEEP:-}" ] || exec sleep "$KUBECTL_SLEEP" +case $1 in + get) + case $2 in + helmrelease) printf 0b5e1a7e-0000-4000-8000-000000000001 ;; + *) + [ -z "${KUBECTL_BA_FAIL:-}" ] || { echo 'Error from server (Forbidden): bucketaccesses is forbidden' >&2; exit 1; } + # Child tenants keep their BucketAccesses in their own namespaces. + case " $* " in + *" --all-namespaces "*) + cat "$BA_JSON" + # A BucketAccess created and granted right after this listing. + [ -z "${KUBECTL_GRANT_AFTER:-}" ] || echo SECRET > "$IDS/ba-$KUBECTL_GRANT_AFTER.json" + ;; + *) echo '{"kind":"List","items":[]}' ;; + esac + ;; + esac + ;; + *) cat >> "$KUBECTL_LOG" ;; +esac +EOF + chmod +x "$BIN/weed" "$BIN/kubectl" + export PATH="$BIN:$PATH" + export MASTER=seaweedfs-master:9333 FILER=seaweedfs-filer-client:8888 + export NAMESPACE=tenant-foo RELEASE=seaweedfs-system JOB=seaweedfs-system-orphan-identities + export MODE=delete SHELL_TIMEOUT=5 +} + +# identity +identity() { + echo SECRET > "$IDS/$1" +} + +# bucketaccess [accountID] +bucketaccess() { + jq --arg uid "$1" --arg acct "${2:-}" \ + '.items += [{"metadata": {"uid": $uid}, "status": (if $acct == "" then {} else {"accountID": $acct} end)}]' \ + "$BA_JSON" > "$BA_JSON.new" + mv "$BA_JSON.new" "$BA_JSON" +} + +kept() { + [ -f "$IDS/$1" ] || { echo "FAIL: $1 was removed"; false; } +} + +removed() { + if [ -f "$IDS/$1" ]; then echo "FAIL: $1 is still there"; false; fi +} + +@test "an old identity file with no BucketAccess behind it is removed" { + identity "ba-$GONE.json" + identity "ba-$LIVE.json" + bucketaccess "$LIVE" "ba-$LIVE" + "$SCRIPT" + removed "ba-$GONE.json" + kept "ba-$LIVE.json" +} + +@test "a BucketAccess still being granted protects its file by uid alone" { + identity "ba-$LIVE.json" + bucketaccess "$LIVE" + "$SCRIPT" + kept "ba-$LIVE.json" +} + +@test "a BucketAccess restored under a new uid protects the file its accountID names" { + identity "ba-$GONE.json" + bucketaccess "$LIVE" "ba-$GONE" + "$SCRIPT" + kept "ba-$GONE.json" +} + +@test "an empty BucketAccess listing removes nothing" { + identity "ba-$GONE.json" + echo '{"kind":"List","items":[]}' > "$BA_JSON" + "$SCRIPT" + kept "ba-$GONE.json" + grep -q '^type: Warning$' "$KUBECTL_LOG" + grep -q '^reason: OrphanIdentitiesFound$' "$KUBECTL_LOG" +} + +@test "the identity directory is listed before the BucketAccesses" { + KUBECTL_GRANT_AFTER=$LIVE "$SCRIPT" + kept "ba-$LIVE.json" +} + +@test "a file rewritten by a grant a moment ago is removed once its BucketAccess is gone" { + identity "ba-$GONE.json" + touch "$IDS/ba-$GONE.json" + "$SCRIPT" + removed "ba-$GONE.json" +} + +@test "listing, removals and the check listing take one weed shell session each" { + identity "ba-$GONE.json" + identity "ba-$GONE2.json" + "$SCRIPT" + [ "$(grep -c '^session' "$WEED_LOG")" -eq 3 ] +} + +@test "identities the COSI driver did not name are never touched" { + identity admin.json + identity ba-backup.json + identity "ba-$GONE.json.old" + identity "BA-$GONE.json" + identity "xba-$GONE.json" + identity "ba-${GONE}0.json" + identity ba-1234.json + "$SCRIPT" + kept "xba-$GONE.json" + kept "ba-${GONE}0.json" + kept ba-1234.json + kept admin.json + kept ba-backup.json + kept "ba-$GONE.json.old" + kept "BA-$GONE.json" + if grep -q '^fs.rm' "$WEED_LOG"; then echo "FAIL: removed something"; cat "$WEED_LOG"; false; fi +} + +@test "report mode names the orphan and removes nothing" { + identity "ba-$GONE.json" + out=$(MODE=report "$SCRIPT" 2>&1) + kept "ba-$GONE.json" + if grep -q '^fs.rm' "$WEED_LOG"; then echo "FAIL: report mode removed a file"; false; fi + case $out in *"ba-$GONE"*) ;; *) echo "FAIL: orphan not named: $out"; false ;; esac + grep -q '^reason: OrphanIdentitiesFound$' "$KUBECTL_LOG" + grep -q "ba-$GONE" "$KUBECTL_LOG" + grep -q 'not removed (mode report)' "$KUBECTL_LOG" + grep -q 'cosi.orphanIdentities to delete' "$KUBECTL_LOG" + if grep -q 'other clusters' "$KUBECTL_LOG"; then echo "FAIL: Event claims a reason the script cannot know"; false; fi +} + +@test "an unknown mode only reports" { + identity "ba-$GONE.json" + MODE=Delete "$SCRIPT" + kept "ba-$GONE.json" + grep -q '^reason: OrphanIdentitiesFound$' "$KUBECTL_LOG" + grep -q 'not removed (mode Delete)' "$KUBECTL_LOG" +} + +@test "a BucketAccess listing that fails removes nothing and ends in a Warning Event" { + identity "ba-$GONE.json" + KUBECTL_BA_FAIL=1 "$SCRIPT" + kept "ba-$GONE.json" + if grep -q '^fs.rm' "$WEED_LOG"; then echo "FAIL: removed a file without a BucketAccess listing"; false; fi + grep -q '^type: Warning$' "$KUBECTL_LOG" + grep -q '^reason: OrphanIdentitiesNotChecked$' "$KUBECTL_LOG" +} + +@test "a BucketAccess listing that is not a list removes nothing" { + identity "ba-$GONE.json" + echo '{"kind":"Status","status":"Failure"}' > "$BA_JSON" + "$SCRIPT" + kept "ba-$GONE.json" + grep -q '^reason: OrphanIdentitiesNotChecked$' "$KUBECTL_LOG" +} + +@test "a listing item without a uid removes nothing" { + identity "ba-$GONE.json" + echo '{"kind":"List","items":[{"metadata":{}}]}' > "$BA_JSON" + "$SCRIPT" + kept "ba-$GONE.json" + grep -q '^reason: OrphanIdentitiesNotChecked$' "$KUBECTL_LOG" +} + +@test "a listing of the identity directory that exits non-zero removes nothing and ends in a Warning Event" { + identity "ba-$GONE.json" + WEED_LS_FAIL="exit" "$SCRIPT" + kept "ba-$GONE.json" + if grep -q '^fs.rm' "$WEED_LOG"; then echo "FAIL: removed a file"; false; fi + grep -q '^reason: OrphanIdentitiesNotChecked$' "$KUBECTL_LOG" +} + +@test "a listing of the identity directory that reports an error removes nothing" { + identity "ba-$GONE.json" + WEED_LS_FAIL="print" "$SCRIPT" + kept "ba-$GONE.json" + grep -q '^reason: OrphanIdentitiesNotChecked$' "$KUBECTL_LOG" +} + +@test "every removal is logged and recorded as an Event on the HelmRelease" { + identity "ba-$GONE.json" + identity "ba-$GONE2.json" + out=$("$SCRIPT" 2>&1) + case $out in *"removed ba-$GONE"*) ;; *) echo "FAIL: removal not logged: $out"; false ;; esac + case $out in *"removed ba-$GONE2"*) ;; *) echo "FAIL: removal not logged: $out"; false ;; esac + [ "$(grep -c '^reason: OrphanIdentityRemoved$' "$KUBECTL_LOG")" -eq 2 ] + grep -q '^ kind: HelmRelease$' "$KUBECTL_LOG" + grep -q '^ name: seaweedfs-system$' "$KUBECTL_LOG" + grep -q '^ namespace: tenant-foo$' "$KUBECTL_LOG" + grep -q '^ uid: "0b5e1a7e-0000-4000-8000-000000000001"$' "$KUBECTL_LOG" +} + +@test "a listing that fails after the removal ends in a Warning Event" { + identity "ba-$GONE.json" + WEED_LS_FAIL="exit" WEED_LS_FAIL_FROM=2 "$SCRIPT" + grep -q '^type: Warning$' "$KUBECTL_LOG" + grep -q '^reason: OrphanIdentityNotRemoved$' "$KUBECTL_LOG" + if grep -q '^reason: OrphanIdentityRemoved$' "$KUBECTL_LOG"; then echo "FAIL: claimed a removal it could not confirm"; false; fi +} + +@test "a listing after the removal that reports an error claims no removal" { + identity "ba-$GONE.json" + WEED_LS_FAIL="print" WEED_LS_FAIL_FROM=2 "$SCRIPT" + grep -q '^reason: OrphanIdentityNotRemoved$' "$KUBECTL_LOG" + if grep -q '^reason: OrphanIdentityRemoved$' "$KUBECTL_LOG"; then echo "FAIL: claimed a removal it could not confirm"; false; fi +} + +@test "a removal that fails ends in a Warning Event and exit 0" { + identity "ba-$GONE.json" + WEED_RM_FAIL=1 "$SCRIPT" + kept "ba-$GONE.json" + grep -q '^type: Warning$' "$KUBECTL_LOG" + grep -q '^reason: OrphanIdentityNotRemoved$' "$KUBECTL_LOG" +} + +@test "nothing to do records no Event" { + identity "ba-$LIVE.json" + bucketaccess "$LIVE" + "$SCRIPT" + if grep -q '^ARGS: create' "$KUBECTL_LOG"; then echo "FAIL: recorded an Event"; false; fi +} + +@test "a weed shell that never returns is cut off and removes nothing" { + identity "ba-$GONE.json" + start=$(date +%s) + SHELL_TIMEOUT=3 WEED_SLEEP=60 "$SCRIPT" + [ $(($(date +%s) - start)) -lt 60 ] + kept "ba-$GONE.json" + grep -q '^reason: OrphanIdentitiesNotChecked$' "$KUBECTL_LOG" +} + +@test "secret content of an identity file never reaches the output" { + identity "ba-$GONE.json" + out=$("$SCRIPT" 2>&1) + case $out in *SECRET*) echo "FAIL: file content printed: $out"; false ;; esac + if grep -q SECRET "$KUBECTL_LOG"; then echo "FAIL: file content in an Event"; false; fi +} + +# The Object Lock hook grants every identity with Read or Write, left-over +# ones included; removal has to come first. +@test "orphan removal runs before the Object Lock grant" { + helm template seaweedfs-system packages/system/seaweedfs --namespace tenant-foo > "$BATS_TEST_TMPDIR/manifest" + weight() { + yq eval-all "select(.kind == \"$1\" and .metadata.name == \"$2\") | .metadata.annotations[\"helm.sh/hook-weight\"]" "$BATS_TEST_TMPDIR/manifest" + } + orphan=$(weight Job seaweedfs-system-orphan-identities) + grant=$(weight Job seaweedfs-system-object-lock-actions) + [ -n "$orphan" ] && [ -n "$grant" ] + [ "$orphan" -lt "$grant" ] + for kind in ConfigMap ServiceAccount Role RoleBinding; do + [ "$(weight "$kind" seaweedfs-system-orphan-identities)" -lt "$orphan" ] + done +} + +# The stub logs its call before it hangs, so SHELL_TIMEOUT has to leave a +# loaded runner time to start it. +@test "a kubectl that never returns is cut off and removes nothing" { + identity "ba-$GONE.json" + start=$SECONDS + SHELL_TIMEOUT=3 KUBECTL_SLEEP=60 "$SCRIPT" + [ $((SECONDS - start)) -lt 60 ] + kept "ba-$GONE.json" + grep -q '^ARGS: get bucketaccesses' "$KUBECTL_LOG" + grep -q '^ARGS: get helmrelease' "$KUBECTL_LOG" + grep -q '^ARGS: create' "$KUBECTL_LOG" +} diff --git a/hack/testdata/etcd-grpc-alerts/unittest.yaml b/hack/testdata/etcd-grpc-alerts/unittest.yaml new file mode 100644 index 000000000..711e0d370 --- /dev/null +++ b/hack/testdata/etcd-grpc-alerts/unittest.yaml @@ -0,0 +1,100 @@ +rule_files: + - rules.yaml + +evaluation_interval: 15s + +tests: + - name: watch streams of a stopped API server end with Canceled + interval: 30s + input_series: + - series: 'grpc_server_handled_total{job="tenant-test/etcd-pod-scrape", instance="10.0.0.1:2381", grpc_service="etcdserverpb.Watch", grpc_method="Watch", grpc_type="bidi_stream", grpc_code="Canceled"}' + values: '0+19x80' + - series: 'grpc_server_handled_total{job="tenant-test/etcd-pod-scrape", instance="10.0.0.1:2381", grpc_service="etcdserverpb.Watch", grpc_method="Watch", grpc_type="bidi_stream", grpc_code="Unavailable"}' + values: '2x80' + - series: 'grpc_server_handled_total{job="tenant-test/etcd-pod-scrape", instance="10.0.0.1:2381", grpc_service="etcdserverpb.KV", grpc_method="Range", grpc_type="unary", grpc_code="OK"}' + values: '0+30x80' + alert_rule_test: + - eval_time: 6m + groupname: etcd + alertname: etcdHighNumberOfFailedGRPCRequests + - eval_time: 12m + groupname: etcd + alertname: etcdHighNumberOfFailedGRPCRequests + - eval_time: 30m + groupname: etcd + alertname: etcdHighNumberOfFailedGRPCRequests + + - name: range calls fail with Unavailable + interval: 30s + input_series: + - series: 'grpc_server_handled_total{job="tenant-test/etcd-pod-scrape", instance="10.0.0.1:2381", grpc_service="etcdserverpb.KV", grpc_method="Range", grpc_type="unary", grpc_code="OK"}' + values: '0+3x80' + - series: 'grpc_server_handled_total{job="tenant-test/etcd-pod-scrape", instance="10.0.0.1:2381", grpc_service="etcdserverpb.KV", grpc_method="Range", grpc_type="unary", grpc_code="Unavailable"}' + values: '0+1x80' + alert_rule_test: + - eval_time: 4m + groupname: etcd + alertname: etcdHighNumberOfFailedGRPCRequests + - eval_time: 7m + groupname: etcd + alertname: etcdHighNumberOfFailedGRPCRequests + exp_alerts: + - exp_labels: + job: tenant-test/etcd-pod-scrape + instance: 10.0.0.1:2381 + grpc_service: etcdserverpb.KV + grpc_method: Range + severity: critical + exp_annotations: + summary: "etcd cluster 'tenant-test/etcd-pod-scrape': '25' of requests for 'Range' failed on etcd instance '10.0.0.1:2381'." + - eval_time: 12m + groupname: etcd + alertname: etcdHighNumberOfFailedGRPCRequests + exp_alerts: + - exp_labels: + job: tenant-test/etcd-pod-scrape + instance: 10.0.0.1:2381 + grpc_service: etcdserverpb.KV + grpc_method: Range + severity: warning + exp_annotations: + summary: "etcd cluster 'tenant-test/etcd-pod-scrape': '25' of requests for 'Range' failed on etcd instance '10.0.0.1:2381'." + - exp_labels: + job: tenant-test/etcd-pod-scrape + instance: 10.0.0.1:2381 + grpc_service: etcdserverpb.KV + grpc_method: Range + severity: critical + exp_annotations: + summary: "etcd cluster 'tenant-test/etcd-pod-scrape': '25' of requests for 'Range' failed on etcd instance '10.0.0.1:2381'." + + - name: canceled watch streams next to failing range calls + interval: 30s + input_series: + - series: 'grpc_server_handled_total{job="tenant-test/etcd-pod-scrape", instance="10.0.0.1:2381", grpc_service="etcdserverpb.Watch", grpc_method="Watch", grpc_type="bidi_stream", grpc_code="Canceled"}' + values: '0+19x80' + - series: 'grpc_server_handled_total{job="tenant-test/etcd-pod-scrape", instance="10.0.0.1:2381", grpc_service="etcdserverpb.KV", grpc_method="Range", grpc_type="unary", grpc_code="OK"}' + values: '0+3x80' + - series: 'grpc_server_handled_total{job="tenant-test/etcd-pod-scrape", instance="10.0.0.1:2381", grpc_service="etcdserverpb.KV", grpc_method="Range", grpc_type="unary", grpc_code="Unavailable"}' + values: '0+1x80' + alert_rule_test: + - eval_time: 12m + groupname: etcd + alertname: etcdHighNumberOfFailedGRPCRequests + exp_alerts: + - exp_labels: + job: tenant-test/etcd-pod-scrape + instance: 10.0.0.1:2381 + grpc_service: etcdserverpb.KV + grpc_method: Range + severity: warning + exp_annotations: + summary: "etcd cluster 'tenant-test/etcd-pod-scrape': '25' of requests for 'Range' failed on etcd instance '10.0.0.1:2381'." + - exp_labels: + job: tenant-test/etcd-pod-scrape + instance: 10.0.0.1:2381 + grpc_service: etcdserverpb.KV + grpc_method: Range + severity: critical + exp_annotations: + summary: "etcd cluster 'tenant-test/etcd-pod-scrape': '25' of requests for 'Range' failed on etcd instance '10.0.0.1:2381'." diff --git a/hack/testdata/linstor-error-report-alerts/unittest.yaml b/hack/testdata/linstor-error-report-alerts/unittest.yaml new file mode 100644 index 000000000..41e332169 --- /dev/null +++ b/hack/testdata/linstor-error-report-alerts/unittest.yaml @@ -0,0 +1,198 @@ +rule_files: + - rules.yaml + +evaluation_interval: 15s + +tests: + - name: controller pod moves to another node + interval: 30s + input_series: + - series: 'up{job="linstor-controller", instance="10.0.0.1:3370", controller_node="node-a"}' + values: '1x38 0 stale' + - series: 'linstor_error_reports_count{job="linstor-controller", instance="10.0.0.1:3370", controller_node="node-a", hostname="node-a", module="SATELLITE"}' + values: '1x38 stale' + - series: 'linstor_error_reports_count{job="linstor-controller", instance="10.0.0.1:3370", controller_node="node-a", hostname="node-b", module="SATELLITE"}' + values: '2x38 stale' + - series: 'up{job="linstor-controller", instance="10.0.0.2:3370", controller_node="node-b"}' + values: '_x41 1x79' + - series: 'linstor_error_reports_count{job="linstor-controller", instance="10.0.0.2:3370", controller_node="node-b", hostname="node-a", module="SATELLITE"}' + values: '_x41 1x58 2x20' + - series: 'linstor_error_reports_count{job="linstor-controller", instance="10.0.0.2:3370", controller_node="node-b", hostname="node-b", module="SATELLITE"}' + values: '_x41 2x79' + alert_rule_test: + - eval_time: 21m + groupname: linstor.rules + alertname: linstorSatelliteErrorRate + - eval_time: 28m + groupname: linstor.rules + alertname: linstorSatelliteErrorRate + - eval_time: 35m + groupname: linstor.rules + alertname: linstorSatelliteErrorRate + - eval_time: 45m + groupname: linstor.rules + alertname: linstorSatelliteErrorRate + - eval_time: 51m + groupname: linstor.rules + alertname: linstorSatelliteErrorRate + exp_alerts: + - exp_labels: + hostname: node-a + severity: warning + exp_annotations: + description: | + LINSTOR Satellite "node-a" reports 1 errors in the last 15 minutes. + Use "linstor error-reports list --nodes node-a" to inspect the reports. + + - name: an external label of the scrape changes + interval: 30s + input_series: + - series: 'up{job="linstor-controller", instance="10.0.0.1:3370", cluster="cozystack"}' + values: '1x39 stale' + - series: 'linstor_error_reports_count{job="linstor-controller", instance="10.0.0.1:3370", cluster="cozystack", hostname="node-a", module="SATELLITE"}' + values: '1x39 stale' + - series: 'linstor_error_reports_count{job="linstor-controller", instance="10.0.0.1:3370", cluster="cozystack", hostname="linstor-controller-abc", module="CONTROLLER"}' + values: '1x39 stale' + - series: 'up{job="linstor-controller", instance="10.0.0.1:3370", cluster="cluster-a"}' + values: '_x41 1x79' + - series: 'linstor_error_reports_count{job="linstor-controller", instance="10.0.0.1:3370", cluster="cluster-a", hostname="node-a", module="SATELLITE"}' + values: '_x41 1x79' + - series: 'linstor_error_reports_count{job="linstor-controller", instance="10.0.0.1:3370", cluster="cluster-a", hostname="linstor-controller-abc", module="CONTROLLER"}' + values: '_x41 1x79' + alert_rule_test: + - eval_time: 21m + groupname: linstor.rules + alertname: linstorSatelliteErrorRate + - eval_time: 30m + groupname: linstor.rules + alertname: linstorSatelliteErrorRate + - eval_time: 21m + groupname: linstor.rules + alertname: linstorControllerErrorRate + - eval_time: 30m + groupname: linstor.rules + alertname: linstorControllerErrorRate + + - name: a satellite drops out of the metric while it is disconnected + interval: 30s + input_series: + - series: 'up{job="linstor-controller", instance="10.0.0.1:3370"}' + values: '1x220' + - series: 'linstor_error_reports_count{job="linstor-controller", instance="10.0.0.1:3370", hostname="node-a", module="SATELLITE"}' + values: '1x38 stale _x80 1x100' + - series: 'linstor_error_reports_count{job="linstor-controller", instance="10.0.0.1:3370", hostname="node-b", module="SATELLITE"}' + values: '2x220' + - series: 'linstor_error_reports_count{job="linstor-controller", instance="10.0.0.1:3370", hostname="node-c", module="SATELLITE"}' + values: '1x38 stale _x80 2x100' + alert_rule_test: + - eval_time: 61m + groupname: linstor.rules + alertname: linstorSatelliteErrorRate + exp_alerts: + - exp_labels: + hostname: node-c + severity: warning + exp_annotations: + description: | + LINSTOR Satellite "node-c" reports 1 errors in the last 15 minutes. + Use "linstor error-reports list --nodes node-c" to inspect the reports. + - eval_time: 70m + groupname: linstor.rules + alertname: linstorSatelliteErrorRate + exp_alerts: + - exp_labels: + hostname: node-c + severity: warning + exp_annotations: + description: | + LINSTOR Satellite "node-c" reports 1 errors in the last 15 minutes. + Use "linstor error-reports list --nodes node-c" to inspect the reports. + - eval_time: 76m + groupname: linstor.rules + alertname: linstorSatelliteErrorRate + + - name: a new report fires for the 15 minute window + interval: 30s + input_series: + - series: 'up{job="linstor-controller", instance="10.0.0.1:3370"}' + values: '1x120' + - series: 'linstor_error_reports_count{job="linstor-controller", instance="10.0.0.1:3370", hostname="node-a", module="SATELLITE"}' + values: '1x39 2x80' + - series: 'linstor_error_reports_count{job="linstor-controller", instance="10.0.0.1:3370", hostname="node-b", module="SATELLITE"}' + values: '2x120' + - series: 'linstor_error_reports_count{job="linstor-controller", instance="10.0.0.1:3370", hostname="node-c", module="SATELLITE"}' + values: '0x39 1x80' + - series: 'linstor_error_reports_count{job="linstor-controller", instance="10.0.0.1:3370", hostname="linstor-controller-abc", module="CONTROLLER"}' + values: '0x39 1x80' + alert_rule_test: + - eval_time: 21m + groupname: linstor.rules + alertname: linstorSatelliteErrorRate + exp_alerts: + - exp_labels: + hostname: node-a + severity: warning + exp_annotations: + description: | + LINSTOR Satellite "node-a" reports 1 errors in the last 15 minutes. + Use "linstor error-reports list --nodes node-a" to inspect the reports. + - exp_labels: + hostname: node-c + severity: warning + exp_annotations: + description: | + LINSTOR Satellite "node-c" reports 1 errors in the last 15 minutes. + Use "linstor error-reports list --nodes node-c" to inspect the reports. + - eval_time: 34m + groupname: linstor.rules + alertname: linstorSatelliteErrorRate + exp_alerts: + - exp_labels: + hostname: node-a + severity: warning + exp_annotations: + description: | + LINSTOR Satellite "node-a" reports 1 errors in the last 15 minutes. + Use "linstor error-reports list --nodes node-a" to inspect the reports. + - exp_labels: + hostname: node-c + severity: warning + exp_annotations: + description: | + LINSTOR Satellite "node-c" reports 1 errors in the last 15 minutes. + Use "linstor error-reports list --nodes node-c" to inspect the reports. + - eval_time: 36m + groupname: linstor.rules + alertname: linstorSatelliteErrorRate + - eval_time: 21m + groupname: linstor.rules + alertname: linstorControllerErrorRate + exp_alerts: + - exp_labels: + hostname: linstor-controller-abc + severity: warning + exp_annotations: + description: | + LINSTOR Controller reports 1 errors in the last 15 minutes. + Use "linstor error-reports list --since 15minutes" to see them. + - eval_time: 36m + groupname: linstor.rules + alertname: linstorControllerErrorRate + + - name: a failed controller scrape still holds the alert back + interval: 30s + input_series: + - series: 'up{job="linstor-controller", instance="10.0.0.1:3370"}' + values: '1x19 0x140 1x60' + - series: 'linstor_error_reports_count{job="linstor-controller", instance="10.0.0.1:3370", hostname="node-a", module="SATELLITE"}' + values: '1x19 stale _x140 1x60' + alert_rule_test: + - eval_time: 85m + groupname: linstor.rules + alertname: linstorSatelliteErrorRate + - eval_time: 93m + groupname: linstor.rules + alertname: linstorSatelliteErrorRate + - eval_time: 100m + groupname: linstor.rules + alertname: linstorSatelliteErrorRate diff --git a/hack/testdata/workload-placement-alerts/unittest.yaml b/hack/testdata/workload-placement-alerts/unittest.yaml new file mode 100644 index 000000000..2565a8241 --- /dev/null +++ b/hack/testdata/workload-placement-alerts/unittest.yaml @@ -0,0 +1,572 @@ +rule_files: + - rules.yaml + +evaluation_interval: 15s + +tests: + - name: two of three StatefulSet pods on one node + interval: 1m + input_series: + - series: 'kube_node_info{job="kube-state-metrics", cluster="cozystack", node="node-a"}' + values: '1x150' + - series: 'kube_node_info{job="kube-state-metrics", cluster="cozystack", node="node-b"}' + values: '1x150' + - series: 'kube_node_info{job="kube-state-metrics", cluster="cozystack", node="node-c"}' + values: '1x150' + - series: 'kube_pod_info{job="kube-state-metrics", cluster="cozystack", namespace="tenant-a", pod="db-0", node="node-a", created_by_kind="StatefulSet", created_by_name="db"}' + values: '1x150' + - series: 'kube_pod_info{job="kube-state-metrics", cluster="cozystack", namespace="tenant-a", pod="db-1", node="node-a", created_by_kind="StatefulSet", created_by_name="db"}' + values: '1x150' + - series: 'kube_pod_info{job="kube-state-metrics", cluster="cozystack", namespace="tenant-a", pod="db-2", node="node-b", created_by_kind="StatefulSet", created_by_name="db"}' + values: '1x150' + - series: 'kube_pod_status_phase{job="kube-state-metrics", cluster="cozystack", namespace="tenant-a", pod="db-0", phase="Running", node="node-c"}' + values: '1x150' + - series: 'kube_pod_status_phase{job="kube-state-metrics", cluster="cozystack", namespace="tenant-a", pod="db-1", phase="Running", node="node-c"}' + values: '1x150' + - series: 'kube_pod_status_phase{job="kube-state-metrics", cluster="cozystack", namespace="tenant-a", pod="db-2", phase="Running", node="node-c"}' + values: '1x150' + alert_rule_test: + - eval_time: 59m + groupname: workload-placement + alertname: PodReplicasColocated + - eval_time: 61m + groupname: workload-placement + alertname: PodReplicasColocated + exp_alerts: + - exp_labels: + cluster: cozystack + namespace: tenant-a + owner_kind: StatefulSet + owner_name: db + node: node-a + severity: warning + exported_instance: tenant-a/db + service: workload-placement + exp_annotations: + summary: Pods of one workload share a node. + description: >- + 2 running pods of StatefulSet tenant-a/db are on node node-a in cluster cozystack, + although the cluster has a schedulable node for each of its pods. Losing this node + stops these pods together, which can cost a quorum-based workload its quorum. The + scheduler does not move running pods, so they stay together until they are recreated. + + - name: StatefulSet pods spread over three nodes + interval: 1m + input_series: + - series: 'kube_node_info{job="kube-state-metrics", cluster="cozystack", node="node-a"}' + values: '1x150' + - series: 'kube_node_info{job="kube-state-metrics", cluster="cozystack", node="node-b"}' + values: '1x150' + - series: 'kube_node_info{job="kube-state-metrics", cluster="cozystack", node="node-c"}' + values: '1x150' + - series: 'kube_pod_info{job="kube-state-metrics", cluster="cozystack", namespace="tenant-a", pod="db-0", node="node-a", created_by_kind="StatefulSet", created_by_name="db"}' + values: '1x150' + - series: 'kube_pod_info{job="kube-state-metrics", cluster="cozystack", namespace="tenant-a", pod="db-1", node="node-b", created_by_kind="StatefulSet", created_by_name="db"}' + values: '1x150' + - series: 'kube_pod_info{job="kube-state-metrics", cluster="cozystack", namespace="tenant-a", pod="db-2", node="node-c", created_by_kind="StatefulSet", created_by_name="db"}' + values: '1x150' + - series: 'kube_pod_status_phase{job="kube-state-metrics", cluster="cozystack", namespace="tenant-a", pod="db-0", phase="Running", node="node-c"}' + values: '1x150' + - series: 'kube_pod_status_phase{job="kube-state-metrics", cluster="cozystack", namespace="tenant-a", pod="db-1", phase="Running", node="node-c"}' + values: '1x150' + - series: 'kube_pod_status_phase{job="kube-state-metrics", cluster="cozystack", namespace="tenant-a", pod="db-2", phase="Running", node="node-c"}' + values: '1x150' + alert_rule_test: + - eval_time: 61m + groupname: workload-placement + alertname: PodReplicasColocated + - eval_time: 120m + groupname: workload-placement + alertname: PodReplicasColocated + + - name: five ReplicaSet pods on three nodes + interval: 1m + input_series: + - series: 'kube_node_info{job="kube-state-metrics", cluster="cozystack", node="node-a"}' + values: '1x150' + - series: 'kube_node_info{job="kube-state-metrics", cluster="cozystack", node="node-b"}' + values: '1x150' + - series: 'kube_node_info{job="kube-state-metrics", cluster="cozystack", node="node-c"}' + values: '1x150' + - series: 'kube_pod_info{job="kube-state-metrics", cluster="cozystack", namespace="tenant-a", pod="worker-7c8d9-aaaaa", node="node-a", created_by_kind="ReplicaSet", created_by_name="worker-7c8d9"}' + values: '1x150' + - series: 'kube_pod_info{job="kube-state-metrics", cluster="cozystack", namespace="tenant-a", pod="worker-7c8d9-bbbbb", node="node-a", created_by_kind="ReplicaSet", created_by_name="worker-7c8d9"}' + values: '1x150' + - series: 'kube_pod_info{job="kube-state-metrics", cluster="cozystack", namespace="tenant-a", pod="worker-7c8d9-ccccc", node="node-b", created_by_kind="ReplicaSet", created_by_name="worker-7c8d9"}' + values: '1x150' + - series: 'kube_pod_info{job="kube-state-metrics", cluster="cozystack", namespace="tenant-a", pod="worker-7c8d9-ddddd", node="node-b", created_by_kind="ReplicaSet", created_by_name="worker-7c8d9"}' + values: '1x150' + - series: 'kube_pod_info{job="kube-state-metrics", cluster="cozystack", namespace="tenant-a", pod="worker-7c8d9-eeeee", node="node-c", created_by_kind="ReplicaSet", created_by_name="worker-7c8d9"}' + values: '1x150' + - series: 'kube_pod_status_phase{job="kube-state-metrics", cluster="cozystack", namespace="tenant-a", pod="worker-7c8d9-aaaaa", phase="Running", node="node-c"}' + values: '1x150' + - series: 'kube_pod_status_phase{job="kube-state-metrics", cluster="cozystack", namespace="tenant-a", pod="worker-7c8d9-bbbbb", phase="Running", node="node-c"}' + values: '1x150' + - series: 'kube_pod_status_phase{job="kube-state-metrics", cluster="cozystack", namespace="tenant-a", pod="worker-7c8d9-ccccc", phase="Running", node="node-c"}' + values: '1x150' + - series: 'kube_pod_status_phase{job="kube-state-metrics", cluster="cozystack", namespace="tenant-a", pod="worker-7c8d9-ddddd", phase="Running", node="node-c"}' + values: '1x150' + - series: 'kube_pod_status_phase{job="kube-state-metrics", cluster="cozystack", namespace="tenant-a", pod="worker-7c8d9-eeeee", phase="Running", node="node-c"}' + values: '1x150' + alert_rule_test: + - eval_time: 61m + groupname: workload-placement + alertname: PodReplicasColocated + - eval_time: 120m + groupname: workload-placement + alertname: PodReplicasColocated + + - name: DaemonSet surge pod next to the old one + interval: 1m + input_series: + - series: 'kube_node_info{job="kube-state-metrics", cluster="cozystack", node="node-a"}' + values: '1x150' + - series: 'kube_node_info{job="kube-state-metrics", cluster="cozystack", node="node-b"}' + values: '1x150' + - series: 'kube_node_info{job="kube-state-metrics", cluster="cozystack", node="node-c"}' + values: '1x150' + - series: 'kube_pod_info{job="kube-state-metrics", cluster="cozystack", namespace="cozy-system", pod="node-agent-x7k2p", node="node-a", created_by_kind="DaemonSet", created_by_name="node-agent"}' + values: '1x150' + - series: 'kube_pod_info{job="kube-state-metrics", cluster="cozystack", namespace="cozy-system", pod="node-agent-q9z4m", node="node-a", created_by_kind="DaemonSet", created_by_name="node-agent"}' + values: '1x150' + - series: 'kube_pod_info{job="kube-state-metrics", cluster="cozystack", namespace="cozy-system", pod="node-agent-b5n8w", node="node-b", created_by_kind="DaemonSet", created_by_name="node-agent"}' + values: '1x150' + - series: 'kube_pod_status_phase{job="kube-state-metrics", cluster="cozystack", namespace="cozy-system", pod="node-agent-x7k2p", phase="Running", node="node-c"}' + values: '1x150' + - series: 'kube_pod_status_phase{job="kube-state-metrics", cluster="cozystack", namespace="cozy-system", pod="node-agent-q9z4m", phase="Running", node="node-c"}' + values: '1x150' + - series: 'kube_pod_status_phase{job="kube-state-metrics", cluster="cozystack", namespace="cozy-system", pod="node-agent-b5n8w", phase="Running", node="node-c"}' + values: '1x150' + alert_rule_test: + - eval_time: 61m + groupname: workload-placement + alertname: PodReplicasColocated + - eval_time: 120m + groupname: workload-placement + alertname: PodReplicasColocated + + - name: two pods of one Job on one node + interval: 1m + input_series: + - series: 'kube_node_info{job="kube-state-metrics", cluster="cozystack", node="node-a"}' + values: '1x150' + - series: 'kube_node_info{job="kube-state-metrics", cluster="cozystack", node="node-b"}' + values: '1x150' + - series: 'kube_node_info{job="kube-state-metrics", cluster="cozystack", node="node-c"}' + values: '1x150' + - series: 'kube_pod_info{job="kube-state-metrics", cluster="cozystack", namespace="tenant-a", pod="backup-29345678-h2k4m", node="node-a", created_by_kind="Job", created_by_name="backup-29345678"}' + values: '1x150' + - series: 'kube_pod_info{job="kube-state-metrics", cluster="cozystack", namespace="tenant-a", pod="backup-29345678-p8r6t", node="node-a", created_by_kind="Job", created_by_name="backup-29345678"}' + values: '1x150' + - series: 'kube_pod_status_phase{job="kube-state-metrics", cluster="cozystack", namespace="tenant-a", pod="backup-29345678-h2k4m", phase="Running", node="node-c"}' + values: '1x150' + - series: 'kube_pod_status_phase{job="kube-state-metrics", cluster="cozystack", namespace="tenant-a", pod="backup-29345678-p8r6t", phase="Running", node="node-c"}' + values: '1x150' + alert_rule_test: + - eval_time: 61m + groupname: workload-placement + alertname: PodReplicasColocated + + - name: etcd members of one EtcdCluster on one node + interval: 1m + input_series: + - series: 'kube_node_info{job="kube-state-metrics", cluster="cozystack", node="node-a"}' + values: '1x150' + - series: 'kube_node_info{job="kube-state-metrics", cluster="cozystack", node="node-b"}' + values: '1x150' + - series: 'kube_node_info{job="kube-state-metrics", cluster="cozystack", node="node-c"}' + values: '1x150' + - series: 'kube_pod_info{job="kube-state-metrics", cluster="cozystack", namespace="tenant-a", pod="etcd-x7k2p", node="node-a", created_by_kind="EtcdMember", created_by_name="etcd-x7k2p"}' + values: '1x150' + - series: 'kube_pod_info{job="kube-state-metrics", cluster="cozystack", namespace="tenant-a", pod="etcd-q9z4m", node="node-a", created_by_kind="EtcdMember", created_by_name="etcd-q9z4m"}' + values: '1x150' + - series: 'kube_pod_info{job="kube-state-metrics", cluster="cozystack", namespace="tenant-a", pod="etcd-b5n8w", node="node-b", created_by_kind="EtcdMember", created_by_name="etcd-b5n8w"}' + values: '1x150' + - series: 'kube_pod_info{job="kube-state-metrics", cluster="cozystack", namespace="tenant-b", pod="etcd-0", node="node-b", created_by_kind="EtcdMember", created_by_name="etcd-0"}' + values: '1x150' + - series: 'kube_pod_info{job="kube-state-metrics", cluster="cozystack", namespace="tenant-b", pod="etcd-1", node="node-c", created_by_kind="EtcdMember", created_by_name="etcd-1"}' + values: '1x150' + - series: 'kube_pod_info{job="kube-state-metrics", cluster="cozystack", namespace="tenant-b", pod="etcd-2", node="node-c", created_by_kind="EtcdMember", created_by_name="etcd-2"}' + values: '1x150' + - series: 'kube_pod_status_phase{job="kube-state-metrics", cluster="cozystack", namespace="tenant-a", pod="etcd-x7k2p", phase="Running", node="node-c"}' + values: '1x150' + - series: 'kube_pod_status_phase{job="kube-state-metrics", cluster="cozystack", namespace="tenant-a", pod="etcd-q9z4m", phase="Running", node="node-c"}' + values: '1x150' + - series: 'kube_pod_status_phase{job="kube-state-metrics", cluster="cozystack", namespace="tenant-a", pod="etcd-b5n8w", phase="Running", node="node-c"}' + values: '1x150' + - series: 'kube_pod_status_phase{job="kube-state-metrics", cluster="cozystack", namespace="tenant-b", pod="etcd-0", phase="Running", node="node-c"}' + values: '1x150' + - series: 'kube_pod_status_phase{job="kube-state-metrics", cluster="cozystack", namespace="tenant-b", pod="etcd-1", phase="Running", node="node-c"}' + values: '1x150' + - series: 'kube_pod_status_phase{job="kube-state-metrics", cluster="cozystack", namespace="tenant-b", pod="etcd-2", phase="Running", node="node-c"}' + values: '1x150' + alert_rule_test: + - eval_time: 61m + groupname: workload-placement + alertname: PodReplicasColocated + exp_alerts: + - exp_labels: + cluster: cozystack + namespace: tenant-a + owner_kind: EtcdCluster + owner_name: etcd + node: node-a + severity: warning + exported_instance: tenant-a/etcd + service: workload-placement + exp_annotations: + summary: Pods of one workload share a node. + description: >- + 2 running pods of EtcdCluster tenant-a/etcd are on node node-a in cluster cozystack, + although the cluster has a schedulable node for each of its pods. Losing this node + stops these pods together, which can cost a quorum-based workload its quorum. The + scheduler does not move running pods, so they stay together until they are recreated. + - exp_labels: + cluster: cozystack + namespace: tenant-b + owner_kind: EtcdCluster + owner_name: etcd + node: node-c + severity: warning + exported_instance: tenant-b/etcd + service: workload-placement + exp_annotations: + summary: Pods of one workload share a node. + description: >- + 2 running pods of EtcdCluster tenant-b/etcd are on node node-c in cluster cozystack, + although the cluster has a schedulable node for each of its pods. Losing this node + stops these pods together, which can cost a quorum-based workload its quorum. The + scheduler does not move running pods, so they stay together until they are recreated. + + - name: replacement pod next to its terminating predecessor for twenty minutes + interval: 1m + input_series: + - series: 'kube_node_info{job="kube-state-metrics", cluster="cozystack", node="node-a"}' + values: '1x150' + - series: 'kube_node_info{job="kube-state-metrics", cluster="cozystack", node="node-b"}' + values: '1x150' + - series: 'kube_node_info{job="kube-state-metrics", cluster="cozystack", node="node-c"}' + values: '1x150' + - series: 'kube_pod_info{job="kube-state-metrics", cluster="cozystack", namespace="tenant-a", pod="web-6b8f4-aaaaa", node="node-a", created_by_kind="ReplicaSet", created_by_name="web-6b8f4"}' + values: '1x150' + - series: 'kube_pod_info{job="kube-state-metrics", cluster="cozystack", namespace="tenant-a", pod="web-6b8f4-bbbbb", node="node-b", created_by_kind="ReplicaSet", created_by_name="web-6b8f4"}' + values: '1x30 stale' + - series: 'kube_pod_info{job="kube-state-metrics", cluster="cozystack", namespace="tenant-a", pod="web-6b8f4-ccccc", node="node-b", created_by_kind="ReplicaSet", created_by_name="web-6b8f4"}' + values: '_x10 1x140' + - series: 'kube_pod_status_phase{job="kube-state-metrics", cluster="cozystack", namespace="tenant-a", pod="web-6b8f4-aaaaa", phase="Running", node="node-c"}' + values: '1x150' + - series: 'kube_pod_status_phase{job="kube-state-metrics", cluster="cozystack", namespace="tenant-a", pod="web-6b8f4-bbbbb", phase="Running", node="node-c"}' + values: '1x30 stale' + - series: 'kube_pod_status_phase{job="kube-state-metrics", cluster="cozystack", namespace="tenant-a", pod="web-6b8f4-ccccc", phase="Running", node="node-c"}' + values: '_x10 1x140' + alert_rule_test: + - eval_time: 29m + groupname: workload-placement + alertname: PodReplicasColocated + - eval_time: 75m + groupname: workload-placement + alertname: PodReplicasColocated + - eval_time: 120m + groupname: workload-placement + alertname: PodReplicasColocated + + - name: the same overlap held past the hour + interval: 1m + input_series: + - series: 'kube_node_info{job="kube-state-metrics", cluster="cozystack", node="node-a"}' + values: '1x150' + - series: 'kube_node_info{job="kube-state-metrics", cluster="cozystack", node="node-b"}' + values: '1x150' + - series: 'kube_node_info{job="kube-state-metrics", cluster="cozystack", node="node-c"}' + values: '1x150' + - series: 'kube_pod_info{job="kube-state-metrics", cluster="cozystack", namespace="tenant-a", pod="web-6b8f4-aaaaa", node="node-a", created_by_kind="ReplicaSet", created_by_name="web-6b8f4"}' + values: '1x150' + - series: 'kube_pod_info{job="kube-state-metrics", cluster="cozystack", namespace="tenant-a", pod="web-6b8f4-bbbbb", node="node-b", created_by_kind="ReplicaSet", created_by_name="web-6b8f4"}' + values: '1x100 stale' + - series: 'kube_pod_info{job="kube-state-metrics", cluster="cozystack", namespace="tenant-a", pod="web-6b8f4-ccccc", node="node-b", created_by_kind="ReplicaSet", created_by_name="web-6b8f4"}' + values: '_x10 1x140' + - series: 'kube_pod_status_phase{job="kube-state-metrics", cluster="cozystack", namespace="tenant-a", pod="web-6b8f4-aaaaa", phase="Running", node="node-c"}' + values: '1x150' + - series: 'kube_pod_status_phase{job="kube-state-metrics", cluster="cozystack", namespace="tenant-a", pod="web-6b8f4-bbbbb", phase="Running", node="node-c"}' + values: '1x100 stale' + - series: 'kube_pod_status_phase{job="kube-state-metrics", cluster="cozystack", namespace="tenant-a", pod="web-6b8f4-ccccc", phase="Running", node="node-c"}' + values: '_x10 1x140' + alert_rule_test: + - eval_time: 69m + groupname: workload-placement + alertname: PodReplicasColocated + - eval_time: 71m + groupname: workload-placement + alertname: PodReplicasColocated + exp_alerts: + - exp_labels: + cluster: cozystack + namespace: tenant-a + owner_kind: ReplicaSet + owner_name: web-6b8f4 + node: node-b + severity: warning + exported_instance: tenant-a/web-6b8f4 + service: workload-placement + exp_annotations: + summary: Pods of one workload share a node. + description: >- + 2 running pods of ReplicaSet tenant-a/web-6b8f4 are on node node-b in cluster cozystack, + although the cluster has a schedulable node for each of its pods. Losing this node + stops these pods together, which can cost a quorum-based workload its quorum. The + scheduler does not move running pods, so they stay together until they are recreated. + - eval_time: 105m + groupname: workload-placement + alertname: PodReplicasColocated + + - name: a cordoned node does not count until it is uncordoned + interval: 1m + input_series: + - series: 'kube_node_info{job="kube-state-metrics", cluster="cozystack", node="node-a"}' + values: '1x150' + - series: 'kube_node_info{job="kube-state-metrics", cluster="cozystack", node="node-b"}' + values: '1x150' + - series: 'kube_node_info{job="kube-state-metrics", cluster="cozystack", node="node-c"}' + values: '1x150' + - series: 'kube_node_spec_unschedulable{job="kube-state-metrics", cluster="cozystack", node="node-a"}' + values: '0x150' + - series: 'kube_node_spec_unschedulable{job="kube-state-metrics", cluster="cozystack", node="node-b"}' + values: '0x150' + - series: 'kube_node_spec_unschedulable{job="kube-state-metrics", cluster="cozystack", node="node-c"}' + values: '1x30 0x120' + - series: 'kube_node_spec_taint{job="kube-state-metrics", cluster="cozystack", node="node-c", key="node.kubernetes.io/unschedulable", value="", effect="NoSchedule"}' + values: '1x30 stale' + - series: 'kube_pod_info{job="kube-state-metrics", cluster="cozystack", namespace="tenant-a", pod="kv-0", node="node-a", created_by_kind="StatefulSet", created_by_name="kv"}' + values: '1x150' + - series: 'kube_pod_info{job="kube-state-metrics", cluster="cozystack", namespace="tenant-a", pod="kv-1", node="node-a", created_by_kind="StatefulSet", created_by_name="kv"}' + values: '1x150' + - series: 'kube_pod_info{job="kube-state-metrics", cluster="cozystack", namespace="tenant-a", pod="kv-2", node="node-b", created_by_kind="StatefulSet", created_by_name="kv"}' + values: '1x150' + - series: 'kube_pod_status_phase{job="kube-state-metrics", cluster="cozystack", namespace="tenant-a", pod="kv-0", phase="Running", node="node-a"}' + values: '1x150' + - series: 'kube_pod_status_phase{job="kube-state-metrics", cluster="cozystack", namespace="tenant-a", pod="kv-1", phase="Running", node="node-a"}' + values: '1x150' + - series: 'kube_pod_status_phase{job="kube-state-metrics", cluster="cozystack", namespace="tenant-a", pod="kv-2", phase="Running", node="node-a"}' + values: '1x150' + alert_rule_test: + - eval_time: 61m + groupname: workload-placement + alertname: PodReplicasColocated + - eval_time: 90m + groupname: workload-placement + alertname: PodReplicasColocated + - eval_time: 92m + groupname: workload-placement + alertname: PodReplicasColocated + exp_alerts: + - exp_labels: + cluster: cozystack + namespace: tenant-a + owner_kind: StatefulSet + owner_name: kv + node: node-a + severity: warning + exported_instance: tenant-a/kv + service: workload-placement + exp_annotations: + summary: Pods of one workload share a node. + description: >- + 2 running pods of StatefulSet tenant-a/kv are on node node-a in cluster cozystack, + although the cluster has a schedulable node for each of its pods. Losing this node + stops these pods together, which can cost a quorum-based workload its quorum. The + scheduler does not move running pods, so they stay together until they are recreated. + + - name: a node that is down does not count + interval: 1m + input_series: + - series: 'kube_node_info{job="kube-state-metrics", cluster="cozystack", node="node-a"}' + values: '1x150' + - series: 'kube_node_info{job="kube-state-metrics", cluster="cozystack", node="node-b"}' + values: '1x150' + - series: 'kube_node_info{job="kube-state-metrics", cluster="cozystack", node="node-c"}' + values: '1x150' + - series: 'kube_node_spec_unschedulable{job="kube-state-metrics", cluster="cozystack", node="node-a"}' + values: '0x150' + - series: 'kube_node_spec_unschedulable{job="kube-state-metrics", cluster="cozystack", node="node-b"}' + values: '0x150' + - series: 'kube_node_spec_unschedulable{job="kube-state-metrics", cluster="cozystack", node="node-c"}' + values: '0x150' + - series: 'kube_node_spec_taint{job="kube-state-metrics", cluster="cozystack", node="node-c", key="node.kubernetes.io/unreachable", value="", effect="NoSchedule"}' + values: '1x150' + - series: 'kube_node_spec_taint{job="kube-state-metrics", cluster="cozystack", node="node-c", key="node.kubernetes.io/unreachable", value="", effect="NoExecute"}' + values: '1x150' + - series: 'kube_pod_info{job="kube-state-metrics", cluster="cozystack", namespace="tenant-a", pod="kv-0", node="node-a", created_by_kind="StatefulSet", created_by_name="kv"}' + values: '1x150' + - series: 'kube_pod_info{job="kube-state-metrics", cluster="cozystack", namespace="tenant-a", pod="kv-1", node="node-a", created_by_kind="StatefulSet", created_by_name="kv"}' + values: '1x150' + - series: 'kube_pod_info{job="kube-state-metrics", cluster="cozystack", namespace="tenant-a", pod="kv-2", node="node-b", created_by_kind="StatefulSet", created_by_name="kv"}' + values: '1x150' + - series: 'kube_pod_status_phase{job="kube-state-metrics", cluster="cozystack", namespace="tenant-a", pod="kv-0", phase="Running", node="node-a"}' + values: '1x150' + - series: 'kube_pod_status_phase{job="kube-state-metrics", cluster="cozystack", namespace="tenant-a", pod="kv-1", phase="Running", node="node-a"}' + values: '1x150' + - series: 'kube_pod_status_phase{job="kube-state-metrics", cluster="cozystack", namespace="tenant-a", pod="kv-2", phase="Running", node="node-a"}' + values: '1x150' + alert_rule_test: + - eval_time: 61m + groupname: workload-placement + alertname: PodReplicasColocated + - eval_time: 120m + groupname: workload-placement + alertname: PodReplicasColocated + + - name: pods that are not running do not count + interval: 1m + input_series: + - series: 'kube_node_info{job="kube-state-metrics", cluster="cozystack", node="node-a"}' + values: '1x150' + - series: 'kube_node_info{job="kube-state-metrics", cluster="cozystack", node="node-b"}' + values: '1x150' + - series: 'kube_node_info{job="kube-state-metrics", cluster="cozystack", node="node-c"}' + values: '1x150' + - series: 'kube_pod_info{job="kube-state-metrics", cluster="cozystack", namespace="tenant-a", pod="api-5c6d7-aaaaa", node="node-a", created_by_kind="ReplicaSet", created_by_name="api-5c6d7"}' + values: '1x150' + - series: 'kube_pod_info{job="kube-state-metrics", cluster="cozystack", namespace="tenant-a", pod="api-5c6d7-bbbbb", node="node-a", created_by_kind="ReplicaSet", created_by_name="api-5c6d7"}' + values: '1x150' + - series: 'kube_pod_info{job="kube-state-metrics", cluster="cozystack", namespace="tenant-a", pod="api-5c6d7-ccccc", node="node-b", created_by_kind="ReplicaSet", created_by_name="api-5c6d7"}' + values: '1x150' + - series: 'kube_pod_status_phase{job="kube-state-metrics", cluster="cozystack", namespace="tenant-a", pod="api-5c6d7-aaaaa", phase="Running", node="node-c"}' + values: '1x150' + - series: 'kube_pod_status_phase{job="kube-state-metrics", cluster="cozystack", namespace="tenant-a", pod="api-5c6d7-bbbbb", phase="Running", node="node-c"}' + values: '0x150' + - series: 'kube_pod_status_phase{job="kube-state-metrics", cluster="cozystack", namespace="tenant-a", pod="api-5c6d7-bbbbb", phase="Failed", node="node-c"}' + values: '1x150' + - series: 'kube_pod_status_phase{job="kube-state-metrics", cluster="cozystack", namespace="tenant-a", pod="api-5c6d7-ccccc", phase="Running", node="node-c"}' + values: '1x150' + alert_rule_test: + - eval_time: 61m + groupname: workload-placement + alertname: PodReplicasColocated + + - name: one pod each in two clusters that share workload and node names + interval: 1m + input_series: + - series: 'kube_node_info{job="kube-state-metrics", cluster="cozystack", node="node-a"}' + values: '1x150' + - series: 'kube_node_info{job="kube-state-metrics", cluster="cozystack", node="node-b"}' + values: '1x150' + - series: 'kube_node_info{job="kube-state-metrics", cluster="cozystack", node="node-c"}' + values: '1x150' + - series: 'kube_node_info{job="kube-state-metrics", cluster="kubernetes-example", node="node-a"}' + values: '1x150' + - series: 'kube_node_info{job="kube-state-metrics", cluster="kubernetes-example", node="node-b"}' + values: '1x150' + - series: 'kube_node_info{job="kube-state-metrics", cluster="kubernetes-example", node="node-c"}' + values: '1x150' + - series: 'kube_pod_info{job="kube-state-metrics", cluster="cozystack", namespace="kube-system", pod="coredns-5d78c9869d-x7k2p", node="node-a", created_by_kind="ReplicaSet", created_by_name="coredns-5d78c9869d"}' + values: '1x150' + - series: 'kube_pod_info{job="kube-state-metrics", cluster="kubernetes-example", namespace="kube-system", pod="coredns-5d78c9869d-q9z4m", node="node-a", created_by_kind="ReplicaSet", created_by_name="coredns-5d78c9869d"}' + values: '1x150' + - series: 'kube_pod_status_phase{job="kube-state-metrics", cluster="cozystack", namespace="kube-system", pod="coredns-5d78c9869d-x7k2p", phase="Running", node="node-c"}' + values: '1x150' + - series: 'kube_pod_status_phase{job="kube-state-metrics", cluster="kubernetes-example", namespace="kube-system", pod="coredns-5d78c9869d-q9z4m", phase="Running", node="node-b"}' + values: '1x150' + alert_rule_test: + - eval_time: 61m + groupname: workload-placement + alertname: PodReplicasColocated + + - name: ReplicaSet, CNPG Cluster and StrimziPodSet pods on one node + interval: 1m + input_series: + - series: 'kube_node_info{job="kube-state-metrics", cluster="cozystack", node="node-a"}' + values: '1x150' + - series: 'kube_node_info{job="kube-state-metrics", cluster="cozystack", node="node-b"}' + values: '1x150' + - series: 'kube_node_info{job="kube-state-metrics", cluster="cozystack", node="node-c"}' + values: '1x150' + - series: 'kube_pod_info{job="kube-state-metrics", cluster="cozystack", namespace="tenant-a", pod="rfs-cache-6f7d8b9c5d-h2k4m", node="node-a", created_by_kind="ReplicaSet", created_by_name="rfs-cache-6f7d8b9c5d"}' + values: '1x150' + - series: 'kube_pod_info{job="kube-state-metrics", cluster="cozystack", namespace="tenant-a", pod="rfs-cache-6f7d8b9c5d-p8r6t", node="node-a", created_by_kind="ReplicaSet", created_by_name="rfs-cache-6f7d8b9c5d"}' + values: '1x150' + - series: 'kube_pod_info{job="kube-state-metrics", cluster="cozystack", namespace="tenant-a", pod="rfs-cache-6f7d8b9c5d-w3x5z", node="node-b", created_by_kind="ReplicaSet", created_by_name="rfs-cache-6f7d8b9c5d"}' + values: '1x150' + - series: 'kube_pod_info{job="kube-state-metrics", cluster="cozystack", namespace="tenant-a", pod="postgres-db-1", node="node-a", created_by_kind="Cluster", created_by_name="postgres-db"}' + values: '1x150' + - series: 'kube_pod_info{job="kube-state-metrics", cluster="cozystack", namespace="tenant-a", pod="postgres-db-2", node="node-b", created_by_kind="Cluster", created_by_name="postgres-db"}' + values: '1x150' + - series: 'kube_pod_info{job="kube-state-metrics", cluster="cozystack", namespace="tenant-a", pod="postgres-db-3", node="node-b", created_by_kind="Cluster", created_by_name="postgres-db"}' + values: '1x150' + - series: 'kube_pod_info{job="kube-state-metrics", cluster="cozystack", namespace="tenant-a", pod="kafka-kafka-0", node="node-c", created_by_kind="StrimziPodSet", created_by_name="kafka-kafka"}' + values: '1x150' + - series: 'kube_pod_info{job="kube-state-metrics", cluster="cozystack", namespace="tenant-a", pod="kafka-kafka-1", node="node-c", created_by_kind="StrimziPodSet", created_by_name="kafka-kafka"}' + values: '1x150' + - series: 'kube_pod_info{job="kube-state-metrics", cluster="cozystack", namespace="tenant-a", pod="kafka-kafka-2", node="node-a", created_by_kind="StrimziPodSet", created_by_name="kafka-kafka"}' + values: '1x150' + - series: 'kube_pod_status_phase{job="kube-state-metrics", cluster="cozystack", namespace="tenant-a", pod="rfs-cache-6f7d8b9c5d-h2k4m", phase="Running", node="node-c"}' + values: '1x150' + - series: 'kube_pod_status_phase{job="kube-state-metrics", cluster="cozystack", namespace="tenant-a", pod="rfs-cache-6f7d8b9c5d-p8r6t", phase="Running", node="node-c"}' + values: '1x150' + - series: 'kube_pod_status_phase{job="kube-state-metrics", cluster="cozystack", namespace="tenant-a", pod="rfs-cache-6f7d8b9c5d-w3x5z", phase="Running", node="node-c"}' + values: '1x150' + - series: 'kube_pod_status_phase{job="kube-state-metrics", cluster="cozystack", namespace="tenant-a", pod="postgres-db-1", phase="Running", node="node-c"}' + values: '1x150' + - series: 'kube_pod_status_phase{job="kube-state-metrics", cluster="cozystack", namespace="tenant-a", pod="postgres-db-2", phase="Running", node="node-c"}' + values: '1x150' + - series: 'kube_pod_status_phase{job="kube-state-metrics", cluster="cozystack", namespace="tenant-a", pod="postgres-db-3", phase="Running", node="node-c"}' + values: '1x150' + - series: 'kube_pod_status_phase{job="kube-state-metrics", cluster="cozystack", namespace="tenant-a", pod="kafka-kafka-0", phase="Running", node="node-c"}' + values: '1x150' + - series: 'kube_pod_status_phase{job="kube-state-metrics", cluster="cozystack", namespace="tenant-a", pod="kafka-kafka-1", phase="Running", node="node-c"}' + values: '1x150' + - series: 'kube_pod_status_phase{job="kube-state-metrics", cluster="cozystack", namespace="tenant-a", pod="kafka-kafka-2", phase="Running", node="node-c"}' + values: '1x150' + alert_rule_test: + - eval_time: 61m + groupname: workload-placement + alertname: PodReplicasColocated + exp_alerts: + - exp_labels: + cluster: cozystack + namespace: tenant-a + owner_kind: ReplicaSet + owner_name: rfs-cache-6f7d8b9c5d + node: node-a + severity: warning + exported_instance: tenant-a/rfs-cache-6f7d8b9c5d + service: workload-placement + exp_annotations: + summary: Pods of one workload share a node. + description: >- + 2 running pods of ReplicaSet tenant-a/rfs-cache-6f7d8b9c5d are on node node-a in cluster + cozystack, although the cluster has a schedulable node for each of its pods. Losing this + node stops these pods together, which can cost a quorum-based workload its quorum. The + scheduler does not move running pods, so they stay together until they are recreated. + - exp_labels: + cluster: cozystack + namespace: tenant-a + owner_kind: Cluster + owner_name: postgres-db + node: node-b + severity: warning + exported_instance: tenant-a/postgres-db + service: workload-placement + exp_annotations: + summary: Pods of one workload share a node. + description: >- + 2 running pods of Cluster tenant-a/postgres-db are on node node-b in cluster cozystack, + although the cluster has a schedulable node for each of its pods. Losing this node + stops these pods together, which can cost a quorum-based workload its quorum. The + scheduler does not move running pods, so they stay together until they are recreated. + - exp_labels: + cluster: cozystack + namespace: tenant-a + owner_kind: StrimziPodSet + owner_name: kafka-kafka + node: node-c + severity: warning + exported_instance: tenant-a/kafka-kafka + service: workload-placement + exp_annotations: + summary: Pods of one workload share a node. + description: >- + 2 running pods of StrimziPodSet tenant-a/kafka-kafka are on node node-c in cluster + cozystack, although the cluster has a schedulable node for each of its pods. Losing + this node stops these pods together, which can cost a quorum-based workload its quorum. + The scheduler does not move running pods, so they stay together until they are + recreated. diff --git a/hack/workload-placement-alerts.bats b/hack/workload-placement-alerts.bats new file mode 100644 index 000000000..3f7b9b961 --- /dev/null +++ b/hack/workload-placement-alerts.bats @@ -0,0 +1,26 @@ +#!/usr/bin/env bats + +load test_helper + +REPO_ROOT="$(cd "$(dirname "${BATS_TEST_FILENAME:-$0}")/.." && pwd)" +VMALERT_TOOL_IMAGE="victoriametrics/vmalert-tool:v1.136.0@sha256:417346d7b6fdb66d8e3984887c2ad114535ec7d983eeef53381b56c776f333f1" + +@test "workload placement alerts pass their vmalert-tool cases" { + docker info >/dev/null 2>&1 || { + echo "docker is required to run the cases in $VMALERT_TOOL_IMAGE" >&2 + return 1 + } + work=$(mktemp -d) + rc=0 + yq '.spec' "$REPO_ROOT/packages/system/monitoring-agents/alerts/workload-placement.yaml" > "$work/rules.yaml" || rc=$? + cp "$REPO_ROOT/hack/testdata/workload-placement-alerts/unittest.yaml" "$work/unittest.yaml" || rc=$? + if [ "$rc" -eq 0 ]; then + docker run --rm --network none -v "$work:/w:ro" "$VMALERT_TOOL_IMAGE" \ + unittest --files /w/unittest.yaml > "$work/out" 2>&1 || rc=$? + cat "$work/out" + fi + passed=$(grep -cx 'SUCCESS' "$work/out" 2>/dev/null || true) + rm -rf "$work" + [ "$rc" -eq 0 ] + [ "$passed" -eq 1 ] +} diff --git a/internal/backupcontroller/altinitystrategy_controller.go b/internal/backupcontroller/altinitystrategy_controller.go index 3d44f0033..f160169a4 100644 --- a/internal/backupcontroller/altinitystrategy_controller.go +++ b/internal/backupcontroller/altinitystrategy_controller.go @@ -2,7 +2,9 @@ package backupcontroller import ( + "bytes" "context" + "encoding/json" "fmt" "strings" "time" @@ -42,6 +44,18 @@ const ( // were in effect at backup time. altinityParamPrefix = "altinity.strategy.backups.cozystack.io/parameter/" + // altinityArchiveMetaKey records, on the Backup, the clickhouse-backup + // archive its Job wrote, as named by altinityArchiveName. A restore reads + // back exactly that archive: the newest one under the release's prefix + // may belong to a later Backup. + altinityArchiveMetaKey = "altinity.strategy.backups.cozystack.io/archive" + + // altinityArchiveTimeLayout is the UTC timestamp that ends an archive + // name. It is fixed-width, so names sharing a prefix sort chronologically + // as plain strings, which is what a restore of a Backup that records no + // archive relies on. + altinityArchiveTimeLayout = "20060102T150405Z" + // Polling cadence for the Altinity Job lifecycle. Mirrors the CNPG / // Velero strategy cadence so behaviour is uniform across drivers. altinityPollInterval = 5 * time.Second @@ -101,14 +115,37 @@ func backupParameters(b *backupsv1alpha1.Backup) map[string]string { return out } +// altinityArchiveName mints the archive name for one BackupJob from its +// persisted StartedAt, so every reconcile and every Pod retry of the Job +// writes the same archive. It keeps the clickhouse-- +// shape, because a Backup that records no archive is restored by the +// timestamp in that shape. +func altinityArchiveName(j *backupsv1alpha1.BackupJob) string { + return fmt.Sprintf("clickhouse-%s-%s", j.Spec.ApplicationRef.Name, j.Status.StartedAt.UTC().Format(altinityArchiveTimeLayout)) +} + +// altinityJobCarriesArchive reports whether the Job's Pod was rendered with +// the archive name. A Job created by a controller that predates archive +// names, or rendered from a strategy that names its own archives, wrote an +// archive under another name, and recording this one would point the Backup +// at an archive that does not exist. +func altinityJobCarriesArchive(job *batchv1.Job, archive string) bool { + spec, err := json.Marshal(job.Spec.Template.Spec) + if err != nil { + return false + } + return bytes.Contains(spec, []byte(archive)) +} + // renderAltinityTemplate runs the strategy's PodTemplateSpec through the // repository's text/template engine with the same context shape as the CNPG // driver: every string field is templated against the application object, -// the release shorthand, the run mode, and the resolved parameters. +// the release shorthand, the run mode, the archive name, and the resolved +// parameters. func renderAltinityTemplate( tmpl corev1.PodTemplateSpec, app map[string]interface{}, - releaseName, releaseNamespace, mode string, + releaseName, releaseNamespace, mode, archiveName string, parameters map[string]string, backup *backupsv1alpha1.Backup, ) (*corev1.PodTemplateSpec, error) { @@ -118,8 +155,9 @@ func renderAltinityTemplate( "Name": releaseName, "Namespace": releaseNamespace, }, - "Mode": mode, - "Parameters": parameters, + "Mode": mode, + "ArchiveName": archiveName, + "Parameters": parameters, } if backup != nil { // Expose ApplicationRef so restore strategies can reference the @@ -142,6 +180,9 @@ func renderAltinityTemplate( "Kind": backup.Spec.ApplicationRef.Kind, "Name": backup.Spec.ApplicationRef.Name, }, + // In the archive-name layout, so a strategy can compare it with + // the timestamp an archive name ends in. + "TakenAt": backup.Spec.TakenAt.UTC().Format(altinityArchiveTimeLayout), } } return template.Template(&tmpl, ctxMap) @@ -208,12 +249,14 @@ func (r *BackupJobReconciler) reconcileAltinity(ctx context.Context, j *backupsv return ctrl.Result{}, err } + archive := altinityArchiveName(j) rendered, err := renderAltinityTemplate( strategy.Spec.Template, app, j.Spec.ApplicationRef.Name, j.Namespace, altinityModeBackup, + archive, resolved.Parameters, nil, ) @@ -238,7 +281,10 @@ func (r *BackupJobReconciler) reconcileAltinity(ctx context.Context, j *backupsv if j.Status.BackupRef != nil { return ctrl.Result{}, nil } - artifact, err := r.createAltinityBackupArtifact(ctx, j, resolved) + if !altinityJobCarriesArchive(batchJob, archive) { + archive = "" + } + artifact, err := r.createAltinityBackupArtifact(ctx, j, resolved, archive) if err != nil { return r.markBackupJobFailed(ctx, j, fmt.Sprintf("failed to create Backup artifact: %v", err)) } @@ -416,16 +462,20 @@ func jobFailureMessage(j *batchv1.Job) string { } // createAltinityBackupArtifact materialises a Cozystack Backup carrying the -// strategy reference and the BackupClassStrategy parameters in effect at -// backup time. Parameters round-trip via DriverMetadata under -// altinityParamPrefix so a later RestoreJob can re-render the strategy -// template against the same values. +// strategy reference, the archive the Job wrote (when known) and the +// BackupClassStrategy parameters in effect at backup time. Parameters +// round-trip via DriverMetadata under altinityParamPrefix so a later +// RestoreJob can re-render the strategy template against the same values. func (r *BackupJobReconciler) createAltinityBackupArtifact( ctx context.Context, j *backupsv1alpha1.BackupJob, resolved *ResolvedBackupConfig, + archive string, ) (*backupsv1alpha1.Backup, error) { driverMD := map[string]string{} + if archive != "" { + driverMD[altinityArchiveMetaKey] = archive + } for k, v := range resolved.Parameters { driverMD[altinityParamPrefix+k] = v } @@ -464,6 +514,13 @@ func (r *BackupJobReconciler) createAltinityBackupArtifact( if getErr := r.Get(ctx, types.NamespacedName{Namespace: backup.Namespace, Name: backup.Name}, existing); getErr != nil { return nil, getErr } + // A Backup outlives its BackupJob, so a BackupJob re-created under a + // used name meets the earlier run's Backup here. Only one recording + // this run's archive was created by an earlier reconcile of this run. + if got := existing.Spec.DriverMetadata[altinityArchiveMetaKey]; got != archive { + return nil, fmt.Errorf("Backup %s/%s already exists and records archive %q, not %q that this run wrote", + backup.Namespace, backup.Name, got, archive) + } return existing, nil } return backup, nil @@ -621,6 +678,7 @@ func (r *RestoreJobReconciler) reconcileAltinityRestore(ctx context.Context, res targetAppName, targetNamespace, altinityModeRestore, + backup.Spec.DriverMetadata[altinityArchiveMetaKey], backupParameters(backup), backup, ) diff --git a/internal/backupcontroller/altinitystrategy_controller_test.go b/internal/backupcontroller/altinitystrategy_controller_test.go index 143d8c092..d44f64627 100644 --- a/internal/backupcontroller/altinitystrategy_controller_test.go +++ b/internal/backupcontroller/altinitystrategy_controller_test.go @@ -3,7 +3,9 @@ package backupcontroller import ( "context" + "strings" "testing" + "time" batchv1 "k8s.io/api/batch/v1" corev1 "k8s.io/api/core/v1" @@ -697,6 +699,7 @@ func TestBackupParameters_RoundTrip(t *testing.T) { DriverMetadata: map[string]string{ altinityParamPrefix + "bucketName": "b1", altinityParamPrefix + "endpoint": "https://s3", + altinityArchiveMetaKey: "clickhouse-ch-test-20260304T050607Z", "job.batch/name": "ignored", "": "ignored", }, @@ -706,7 +709,326 @@ func TestBackupParameters_RoundTrip(t *testing.T) { if got["bucketName"] != "b1" || got["endpoint"] != "https://s3" { t.Errorf("backupParameters = %v", got) } - if _, ok := got["job.batch/name"]; ok { + if len(got) != 2 { t.Errorf("non-parameter key leaked through: %v", got) } } + +// newAltinityArchiveStrategy renders the archive name and the Backup's +// takenAt where a test can read them back off the Job. +func newAltinityArchiveStrategy(name string) *strategyv1alpha1.Altinity { + s := newAltinityStrategy(name) + s.Spec.Template.Spec.Containers[0].Args = []string{ + "--mode={{ .Mode }}", + "--archive={{ .ArchiveName }}", + "--taken-at={{ .Backup.TakenAt }}", + "--bucket={{ .Parameters.bucketName }}", + } + return s +} + +func TestAltinityArchiveName_FromStartedAtInUTC(t *testing.T) { + startedAt := metav1.NewTime(time.Date(2026, 3, 4, 8, 6, 7, 890000000, time.FixedZone("UTC+3", 3*3600))) + j := &backupsv1alpha1.BackupJob{ + Spec: backupsv1alpha1.BackupJobSpec{ApplicationRef: newAltinityClickHouseRef("ch-test")}, + Status: backupsv1alpha1.BackupJobStatus{StartedAt: &startedAt}, + } + if got, want := altinityArchiveName(j), "clickhouse-ch-test-20260304T050607Z"; got != want { + t.Errorf("altinityArchiveName = %q, want %q", got, want) + } +} + +// TestReconcileAltinity_RecordsTheArchiveTheJobWasGiven drives one BackupJob +// through Job creation and completion in separate reconciles. The archive +// name has to come out of the persisted StartedAt both times: the Pod is +// told it on the first, the Backup records it on the second, and a restore +// later reads back exactly that archive. +func TestReconcileAltinity_RecordsTheArchiveTheJobWasGiven(t *testing.T) { + app := newAltinityClickHouseApp("ch-test", "tenant-test") + strategy := newAltinityArchiveStrategy("clickhouse-strategy") + startedAt := metav1.NewTime(time.Date(2026, 3, 4, 5, 6, 7, 0, time.UTC)) + backupJob := &backupsv1alpha1.BackupJob{ + ObjectMeta: metav1.ObjectMeta{Name: "test-bj", Namespace: "tenant-test"}, + Spec: backupsv1alpha1.BackupJobSpec{ + ApplicationRef: newAltinityClickHouseRef("ch-test"), + BackupClassName: "clickhouse-backup", + }, + Status: backupsv1alpha1.BackupJobStatus{StartedAt: &startedAt, Phase: backupsv1alpha1.BackupJobPhaseRunning}, + } + resolved := &ResolvedBackupConfig{ + StrategyRef: corev1.TypedLocalObjectReference{ + APIGroup: new(strategyv1alpha1.GroupVersion.Group), + Kind: strategyv1alpha1.AltinityStrategyKind, + Name: "clickhouse-strategy", + }, + Parameters: map[string]string{"bucketName": "ch-bucket"}, + } + r, _, _ := newAltinityTestEnv(t, app, clientfake.NewClientBuilder().WithObjects(backupJob, strategy)) + ctx := context.Background() + const want = "clickhouse-ch-test-20260304T050607Z" + + if _, err := r.reconcileAltinity(ctx, backupJob, resolved); err != nil { + t.Fatalf("reconcileAltinity() creating the Job: %v", err) + } + job := &batchv1.Job{} + if err := r.Get(ctx, client.ObjectKey{Namespace: "tenant-test", Name: jobNameForBackupJob(backupJob)}, job); err != nil { + t.Fatalf("get backup Job: %v", err) + } + if got := job.Spec.Template.Spec.Containers[0].Args[1]; got != "--archive="+want { + t.Fatalf("backup Pod was rendered with %q, want --archive=%s", got, want) + } + + job.Status.Conditions = []batchv1.JobCondition{{Type: batchv1.JobComplete, Status: corev1.ConditionTrue}} + if err := r.Status().Update(ctx, job); err != nil { + t.Fatalf("mark backup Job complete: %v", err) + } + if err := r.Get(ctx, client.ObjectKeyFromObject(backupJob), backupJob); err != nil { + t.Fatalf("refresh BackupJob: %v", err) + } + if _, err := r.reconcileAltinity(ctx, backupJob, resolved); err != nil { + t.Fatalf("reconcileAltinity() on the completed Job: %v", err) + } + + created := &backupsv1alpha1.Backup{} + if err := r.Get(ctx, client.ObjectKey{Namespace: "tenant-test", Name: backupJob.Name}, created); err != nil { + t.Fatalf("get Backup: %v", err) + } + if got := created.Spec.DriverMetadata[altinityArchiveMetaKey]; got != want { + t.Errorf("Backup records archive %q, want %q", got, want) + } + if got := created.Spec.DriverMetadata[altinityParamPrefix+"bucketName"]; got != "ch-bucket" { + t.Errorf("expected driverMetadata[parameter/bucketName]=ch-bucket, got %q", got) + } +} + +// TestReconcileAltinity_RecordsNoArchiveTheJobWasNotGiven covers a Job whose +// Pod never carried the driver's archive name: one created before the +// upgrade that introduced the names, or rendered from a strategy that names +// its own archives. Recording the name would send the restore after an +// archive nobody wrote; recording none leaves it the fallback for Backups +// without a name. +func TestReconcileAltinity_RecordsNoArchiveTheJobWasNotGiven(t *testing.T) { + app := newAltinityClickHouseApp("ch-test", "tenant-test") + strategy := newAltinityArchiveStrategy("clickhouse-strategy") + startedAt := metav1.NewTime(time.Date(2026, 3, 4, 5, 6, 7, 0, time.UTC)) + backupJob := &backupsv1alpha1.BackupJob{ + ObjectMeta: metav1.ObjectMeta{Name: "test-bj", Namespace: "tenant-test"}, + Spec: backupsv1alpha1.BackupJobSpec{ + ApplicationRef: newAltinityClickHouseRef("ch-test"), + BackupClassName: "clickhouse-backup", + }, + Status: backupsv1alpha1.BackupJobStatus{StartedAt: &startedAt, Phase: backupsv1alpha1.BackupJobPhaseRunning}, + } + completedK8sJob := &batchv1.Job{ + ObjectMeta: metav1.ObjectMeta{Name: jobNameForBackupJob(backupJob), Namespace: backupJob.Namespace}, + Spec: batchv1.JobSpec{ + Template: corev1.PodTemplateSpec{Spec: corev1.PodSpec{ + RestartPolicy: corev1.RestartPolicyNever, + Containers: []corev1.Container{{ + Name: "clickhouse-backup", + Image: "altinity/clickhouse-backup:test", + Args: []string{`target="clickhouse-ch-test-$(date -u +%Y%m%dT%H%M%SZ)"`}, + }}, + }}, + }, + Status: batchv1.JobStatus{ + Conditions: []batchv1.JobCondition{{Type: batchv1.JobComplete, Status: corev1.ConditionTrue}}, + }, + } + resolved := &ResolvedBackupConfig{ + StrategyRef: corev1.TypedLocalObjectReference{ + APIGroup: new(strategyv1alpha1.GroupVersion.Group), + Kind: strategyv1alpha1.AltinityStrategyKind, + Name: "clickhouse-strategy", + }, + Parameters: map[string]string{"bucketName": "ch-bucket"}, + } + r, _, _ := newAltinityTestEnv(t, app, + clientfake.NewClientBuilder().WithObjects(backupJob, strategy, completedK8sJob)) + ctx := context.Background() + + if _, err := r.reconcileAltinity(ctx, backupJob, resolved); err != nil { + t.Fatalf("reconcileAltinity() error = %v", err) + } + created := &backupsv1alpha1.Backup{} + if err := r.Get(ctx, client.ObjectKey{Namespace: "tenant-test", Name: backupJob.Name}, created); err != nil { + t.Fatalf("get Backup: %v", err) + } + if got, ok := created.Spec.DriverMetadata[altinityArchiveMetaKey]; ok { + t.Errorf("Backup records archive %q its Job was never given", got) + } + if got := created.Spec.DriverMetadata[altinityParamPrefix+"bucketName"]; got != "ch-bucket" { + t.Errorf("expected driverMetadata[parameter/bucketName]=ch-bucket, got %q", got) + } +} + +// TestReconcileAltinity_BackupNameAlreadyTaken covers a completed Job whose +// Backup name is already in use. A Backup outlives its BackupJob, so a +// BackupJob re-created under an earlier run's name finds that run's Backup, +// and claiming it would point the new run at an archive it did not write. +// A Backup recording this run's own archive is the one an earlier reconcile +// created before its status write was lost, and is adopted. +func TestReconcileAltinity_BackupNameAlreadyTaken(t *testing.T) { + const thisRun = "clickhouse-ch-test-20260305T050607Z" + cases := []struct { + name string + existing string // archive the existing Backup records; empty for none + wantSucceeded bool + }{ + {name: "earlier run's Backup records another archive", existing: "clickhouse-ch-test-20260304T050607Z"}, + {name: "earlier run's Backup records no archive", existing: ""}, + {name: "this run's Backup from a reconcile whose status write was lost", existing: thisRun, wantSucceeded: true}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + app := newAltinityClickHouseApp("ch-test", "tenant-test") + strategy := newAltinityArchiveStrategy("clickhouse-strategy") + startedAt := metav1.NewTime(time.Date(2026, 3, 5, 5, 6, 7, 0, time.UTC)) + backupJob := &backupsv1alpha1.BackupJob{ + ObjectMeta: metav1.ObjectMeta{Name: "test-bj", Namespace: "tenant-test"}, + Spec: backupsv1alpha1.BackupJobSpec{ + ApplicationRef: newAltinityClickHouseRef("ch-test"), + BackupClassName: "clickhouse-backup", + }, + Status: backupsv1alpha1.BackupJobStatus{StartedAt: &startedAt, Phase: backupsv1alpha1.BackupJobPhaseRunning}, + } + driverMD := map[string]string{altinityParamPrefix + "bucketName": "ch-bucket"} + if tc.existing != "" { + driverMD[altinityArchiveMetaKey] = tc.existing + } + existing := &backupsv1alpha1.Backup{ + ObjectMeta: metav1.ObjectMeta{Name: backupJob.Name, Namespace: backupJob.Namespace}, + Spec: backupsv1alpha1.BackupSpec{ + ApplicationRef: newAltinityClickHouseRef("ch-test"), + StrategyRef: corev1.TypedLocalObjectReference{ + APIGroup: new(strategyv1alpha1.GroupVersion.Group), + Kind: strategyv1alpha1.AltinityStrategyKind, + Name: "clickhouse-strategy", + }, + TakenAt: metav1.NewTime(time.Date(2026, 3, 4, 5, 6, 22, 0, time.UTC)), + DriverMetadata: driverMD, + }, + } + resolved := &ResolvedBackupConfig{ + StrategyRef: corev1.TypedLocalObjectReference{ + APIGroup: new(strategyv1alpha1.GroupVersion.Group), + Kind: strategyv1alpha1.AltinityStrategyKind, + Name: "clickhouse-strategy", + }, + Parameters: map[string]string{"bucketName": "ch-bucket"}, + } + r, _, _ := newAltinityTestEnv(t, app, + clientfake.NewClientBuilder().WithObjects(backupJob, strategy, existing)) + ctx := context.Background() + + if _, err := r.reconcileAltinity(ctx, backupJob, resolved); err != nil { + t.Fatalf("reconcileAltinity() creating the Job: %v", err) + } + job := &batchv1.Job{} + if err := r.Get(ctx, client.ObjectKey{Namespace: "tenant-test", Name: jobNameForBackupJob(backupJob)}, job); err != nil { + t.Fatalf("get backup Job: %v", err) + } + if got := job.Spec.Template.Spec.Containers[0].Args[1]; got != "--archive="+thisRun { + t.Fatalf("backup Pod was rendered with %q, want --archive=%s", got, thisRun) + } + job.Status.Conditions = []batchv1.JobCondition{{Type: batchv1.JobComplete, Status: corev1.ConditionTrue}} + if err := r.Status().Update(ctx, job); err != nil { + t.Fatalf("mark backup Job complete: %v", err) + } + if err := r.Get(ctx, client.ObjectKeyFromObject(backupJob), backupJob); err != nil { + t.Fatalf("refresh BackupJob: %v", err) + } + if _, err := r.reconcileAltinity(ctx, backupJob, resolved); err != nil { + t.Fatalf("reconcileAltinity() on the completed Job: %v", err) + } + + updated := &backupsv1alpha1.BackupJob{} + if err := r.Get(ctx, client.ObjectKeyFromObject(backupJob), updated); err != nil { + t.Fatalf("get BackupJob: %v", err) + } + if tc.wantSucceeded { + if updated.Status.Phase != backupsv1alpha1.BackupJobPhaseSucceeded { + t.Errorf("phase = %q (%s), want Succeeded", updated.Status.Phase, updated.Status.Message) + } + if updated.Status.BackupRef == nil || updated.Status.BackupRef.Name != existing.Name { + t.Errorf("BackupRef = %v, want %s", updated.Status.BackupRef, existing.Name) + } + } else { + if updated.Status.Phase != backupsv1alpha1.BackupJobPhaseFailed { + t.Errorf("phase = %q, want Failed: the run would claim a Backup recording %q instead of %q", updated.Status.Phase, tc.existing, thisRun) + } + if updated.Status.BackupRef != nil { + t.Errorf("BackupRef = %v, want none", updated.Status.BackupRef) + } + if !strings.Contains(updated.Status.Message, thisRun) { + t.Errorf("failure message %q does not name the archive this run wrote", updated.Status.Message) + } + } + kept := &backupsv1alpha1.Backup{} + if err := r.Get(ctx, client.ObjectKeyFromObject(existing), kept); err != nil { + t.Fatalf("get existing Backup: %v", err) + } + if got := kept.Spec.DriverMetadata[altinityArchiveMetaKey]; got != tc.existing { + t.Errorf("existing Backup now records archive %q, want %q left in place", got, tc.existing) + } + }) + } +} + +func TestReconcileAltinityRestore_RendersTheBackupsArchive(t *testing.T) { + cases := []struct { + name string + archive string // recorded on the Backup; empty for a Backup taken before names were recorded + wantArchive string + }{ + {name: "recorded archive", archive: "clickhouse-ch-test-20260304T050607Z", wantArchive: "--archive=clickhouse-ch-test-20260304T050607Z"}, + {name: "no recorded archive", archive: "", wantArchive: "--archive="}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + targetApp := newAltinityClickHouseApp("ch-test", "tenant-test") + strategy := newAltinityArchiveStrategy("clickhouse-strategy") + driverMD := map[string]string{altinityParamPrefix + "bucketName": "ch-bucket"} + if tc.archive != "" { + driverMD[altinityArchiveMetaKey] = tc.archive + } + now := metav1.Now() + backup := &backupsv1alpha1.Backup{ + ObjectMeta: metav1.ObjectMeta{Name: "ch-backup", Namespace: "tenant-test"}, + Spec: backupsv1alpha1.BackupSpec{ + ApplicationRef: newAltinityClickHouseRef("ch-test"), + StrategyRef: corev1.TypedLocalObjectReference{ + APIGroup: new(strategyv1alpha1.GroupVersion.Group), + Kind: strategyv1alpha1.AltinityStrategyKind, + Name: "clickhouse-strategy", + }, + TakenAt: metav1.NewTime(time.Date(2026, 3, 4, 8, 6, 22, 0, time.FixedZone("UTC+3", 3*3600))), + DriverMetadata: driverMD, + }, + } + restoreJob := &backupsv1alpha1.RestoreJob{ + ObjectMeta: metav1.ObjectMeta{Name: "rj", Namespace: "tenant-test"}, + Spec: backupsv1alpha1.RestoreJobSpec{BackupRef: corev1.LocalObjectReference{Name: backup.Name}}, + Status: backupsv1alpha1.RestoreJobStatus{StartedAt: &now, Phase: backupsv1alpha1.RestoreJobPhaseRunning}, + } + _, rr, _ := newAltinityTestEnv(t, targetApp, + clientfake.NewClientBuilder().WithObjects(strategy, backup, restoreJob)) + ctx := context.Background() + + if _, err := rr.reconcileAltinityRestore(ctx, restoreJob, backup); err != nil { + t.Fatalf("reconcileAltinityRestore: %v", err) + } + job := &batchv1.Job{} + if err := rr.Get(ctx, client.ObjectKey{Namespace: "tenant-test", Name: jobNameForRestoreJob(restoreJob)}, job); err != nil { + t.Fatalf("get restore Job: %v", err) + } + args := job.Spec.Template.Spec.Containers[0].Args + want := []string{"--mode=restore", tc.wantArchive, "--taken-at=20260304T050622Z", "--bucket=ch-bucket"} + for i, w := range want { + if i >= len(args) || args[i] != w { + t.Errorf("rendered restore args[%d]: want %q, got %q", i, w, args) + } + } + }) + } +} diff --git a/internal/backupcontroller/backup_controller.go b/internal/backupcontroller/backup_controller.go index 0b379b686..6d1da8a32 100644 --- a/internal/backupcontroller/backup_controller.go +++ b/internal/backupcontroller/backup_controller.go @@ -187,28 +187,16 @@ func (r *BackupReconciler) cleanupVeleroBackup(ctx context.Context, backup *back return fmt.Errorf("failed to get Velero backup %s/%s: %w", veleroBackupNamespace, veleroBackupName, err) } - // Create a DeleteBackupRequest so Velero removes backup data from storage. - // Without this, BSL sync will recreate the backup.velero.io resource. - dbr := &velerov1.DeleteBackupRequest{ - ObjectMeta: metav1.ObjectMeta{ - GenerateName: veleroBackupName + "-", - Namespace: veleroBackupNamespace, - }, - Spec: velerov1.DeleteBackupRequestSpec{ - BackupName: veleroBackupName, - }, + req, err := requestVeleroBackupDeletion(ctx, r.Client, veleroBackupNamespace, veleroBackupName, true) + if err != nil { + return err } - if err := r.Create(ctx, dbr); err != nil { - if apierrors.IsAlreadyExists(err) { - logger.V(1).Info("DeleteBackupRequest already exists", "backup", veleroBackupName) - return nil - } - return fmt.Errorf("failed to create DeleteBackupRequest for %s/%s: %w", veleroBackupNamespace, veleroBackupName, err) + if req.created { + logger.Info("created DeleteBackupRequest for Velero backup", + "name", veleroBackupName, "namespace", veleroBackupNamespace) + } else { + logger.V(1).Info("deletion of Velero backup already requested", "backup", veleroBackupName) } - - logger.Info("created DeleteBackupRequest for Velero backup", - "name", veleroBackupName, "namespace", veleroBackupNamespace, - "deleteRequest", dbr.Name) return nil } diff --git a/internal/backupcontroller/backupjob_controller.go b/internal/backupcontroller/backupjob_controller.go index e7145eec0..c95706ed1 100644 --- a/internal/backupcontroller/backupjob_controller.go +++ b/internal/backupcontroller/backupjob_controller.go @@ -34,6 +34,13 @@ type BackupJobReconciler struct { Scheme *runtime.Scheme Recorder record.EventRecorder CredentialsConfig BackupCredentialsConfig + // APIReader is the manager's uncached reader, through which Reconcile + // re-reads the BackupJob before dispatching to a driver. Wired in + // SetupWithManager. + APIReader client.Reader + + // now is a test seam for the clock that paces Velero deletion retries. + now func() time.Time } func (r *BackupJobReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { @@ -51,16 +58,39 @@ func (r *BackupJobReconciler) Reconcile(ctx context.Context, req ctrl.Request) ( return ctrl.Result{}, err } - // Skip terminal BackupJobs: a Succeeded/Failed run must not keep - // projecting Secrets or re-running dispatch on every requeue, which - // would otherwise materialise cozy-backups-creds in tenant namespaces - // long after the BackupJob is done and pin needless work on the - // apiserver. - if j.Status.Phase == backupsv1alpha1.BackupJobPhaseSucceeded || j.Status.Phase == backupsv1alpha1.BackupJobPhaseFailed { + // A terminal BackupJob never reaches credentials projection or strategy + // dispatch: a finished run must not keep projecting Secrets or + // re-running dispatch on every requeue, which would otherwise + // materialise cozy-backups-creds in tenant namespaces long after the + // BackupJob is done and pin needless work on the apiserver. A Failed + // one only has the failed Velero backups it left behind deleted. + if j.Status.Phase == backupsv1alpha1.BackupJobPhaseFailed { + logger.V(1).Info("BackupJob already terminal, cleaning up its Velero Backups", "phase", j.Status.Phase) + return r.deleteFailedJobVeleroBackups(ctx, j) + } + if j.Status.Phase == backupsv1alpha1.BackupJobPhaseSucceeded { logger.V(1).Info("BackupJob already terminal, skipping", "phase", j.Status.Phase) return ctrl.Result{}, nil } + // The cache can trail this reconciler's own writes. A pass that stamps + // StartedAt and then fails the job has already requeued it through the + // first write, so the next pass can start before the informer has seen + // Failed, retry the step that failed, and create a driver object for a + // job that is over and that nothing will track. Re-read the job past the + // cache; the check above only spares finished jobs the extra request. + if err := r.apiReader().Get(ctx, req.NamespacedName, j); err != nil { + if apierrors.IsNotFound(err) { + return ctrl.Result{}, nil + } + logger.Error(err, "failed to re-read BackupJob") + return ctrl.Result{}, err + } + if j.Status.Phase == backupsv1alpha1.BackupJobPhaseSucceeded || j.Status.Phase == backupsv1alpha1.BackupJobPhaseFailed { + logger.V(1).Info("BackupJob terminal on the apiserver ahead of the cache, skipping", "phase", j.Status.Phase) + return ctrl.Result{}, nil + } + // Normalize ApplicationRef (default apiGroup if not specified) normalizedAppRef := NormalizeApplicationRef(j.Spec.ApplicationRef) @@ -223,6 +253,7 @@ func (r *BackupJobReconciler) SetupWithManager(mgr ctrl.Manager) error { return err } + r.APIReader = mgr.GetAPIReader() cfg := mgr.GetConfig() var err error if r.Interface, err = dynamic.NewForConfig(cfg); err != nil { @@ -240,6 +271,16 @@ func (r *BackupJobReconciler) 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 *BackupJobReconciler) apiReader() client.Reader { + if r.APIReader != nil { + return r.APIReader + } + return r.Client +} + // handleProjectionError classifies a credentials-projection error as // transient (requeue) or terminal (mark Failed). Transient errors record // a Ready=False condition without setting Phase=Failed so the BackupJob diff --git a/internal/backupcontroller/cnpgstrategy_controller.go b/internal/backupcontroller/cnpgstrategy_controller.go index 8cea998b1..499336730 100644 --- a/internal/backupcontroller/cnpgstrategy_controller.go +++ b/internal/backupcontroller/cnpgstrategy_controller.go @@ -1452,9 +1452,12 @@ func buildBarmanPlugin(objectStoreName, serverName string) cnpgtypes.PluginConfi // high-water mark on a 38 MB database is 254 MiB, so 128Mi cannot hold it. A // tenant that leaves resourceQuotas empty has no LimitRange, and there the // sidecar had no requests and no limit at all. 256Mi holds the measured working -// set and 1Gi is four times the measurement. No CPU limit is set, matching the -// entityOperator precedent in packages/apps/kafka: a throttled sidecar stalls -// WAL archiving instead of failing it. +// set and 1Gi is four times the measurement. The CPU limit is explicit for the +// same reason: left unset, that LimitRange gives the sidecar its 250m default, +// so gzip compression of full backups and WAL segments runs on a quarter of a +// core (a 1.6 GB database took 30 minutes to back up). One core keeps the +// sidecar from starving the instance while removing that ceiling; it counts +// against the tenant's limits.cpu budget, one core per instance pod. // // Checksum: since botocore ~1.36 the default (when_supported) attaches a // flexible checksum to every PutObject, which non-AWS S3-compatible backends @@ -1474,6 +1477,7 @@ func barmanSidecarConfiguration() *cnpgtypes.InstanceSidecarConfiguration { corev1.ResourceMemory: resource.MustParse("256Mi"), }, Limits: corev1.ResourceList{ + corev1.ResourceCPU: resource.MustParse("1"), corev1.ResourceMemory: resource.MustParse("1Gi"), }, }, diff --git a/internal/backupcontroller/cnpgstrategy_controller_test.go b/internal/backupcontroller/cnpgstrategy_controller_test.go index ceac7899a..4b7a1b3b4 100644 --- a/internal/backupcontroller/cnpgstrategy_controller_test.go +++ b/internal/backupcontroller/cnpgstrategy_controller_test.go @@ -1605,8 +1605,11 @@ func TestApplyClusterPluginBackup_PatchesExistingCluster(t *testing.T) { sc.Resources.Requests.Cpu().MilliValue() != 100 { t.Errorf("ObjectStore leaves Barman subject to undersized tenant resource defaults: %+v", sc.Resources) } - if _, ok := sc.Resources.Limits[corev1.ResourceCPU]; ok { - t.Errorf("ObjectStore caps sidecar CPU, which throttles WAL archiving instead of failing it: %+v", sc.Resources.Limits) + // Without an explicit CPU limit the tenant LimitRange caps the sidecar at + // its 250m default, and every backup and WAL upload compresses on a + // quarter of a core. + if sc.Resources.Limits.Cpu().MilliValue() != 1000 { + t.Errorf("ObjectStore leaves the sidecar CPU limit to the tenant LimitRange default: %+v", sc.Resources.Limits) } // The ObjectStore must be owner-referenced to the Cluster so Kubernetes GC // removes it when the Cluster is deleted (no orphan in the platform flow, diff --git a/internal/backupcontroller/mariadbstrategy_controller.go b/internal/backupcontroller/mariadbstrategy_controller.go index c5bfcdb80..01e599905 100644 --- a/internal/backupcontroller/mariadbstrategy_controller.go +++ b/internal/backupcontroller/mariadbstrategy_controller.go @@ -7,6 +7,7 @@ import ( "fmt" "time" + batchv1 "k8s.io/api/batch/v1" corev1 "k8s.io/api/core/v1" apierrors "k8s.io/apimachinery/pkg/api/errors" apimeta "k8s.io/apimachinery/pkg/api/meta" @@ -203,7 +204,10 @@ func (r *BackupJobReconciler) reconcileMariaDB(ctx context.Context, j *backupsv1 cond := apimeta.FindStatusCondition(mdbBackup.Status.Conditions, mariadbtypes.ConditionTypeComplete) switch { - case cond != nil && cond.Status == metav1.ConditionTrue: + case cond != nil && cond.Reason == mariadbtypes.ConditionReasonJobFailed: + return r.markBackupJobFailed(ctx, j, mariadbJobFailedMessage(ctx, r.Client, "Backup", mdbBackup.Namespace, mdbBackup.Name, cond)) + + case cond != nil && cond.Status == metav1.ConditionTrue && cond.Reason == mariadbtypes.ConditionReasonJobComplete: // Backup completed successfully. Materialise the Cozystack artifact // and finalise the BackupJob. Idempotent: if the artifact already // exists (a previous reconcile created it and then raced on the @@ -230,34 +234,54 @@ func (r *BackupJobReconciler) reconcileMariaDB(ctx context.Context, j *backupsv1 } return ctrl.Result{}, nil - case cond != nil && cond.Status == metav1.ConditionFalse && cond.Reason == mariadbtypes.ConditionReasonJobFailed: - // Terminal failure. The operator marks Complete=False/JobFailed only - // after the underlying Job exhausts its backoff budget, so we can - // fail the BackupJob immediately rather than waiting for the - // driver-side deadline. - message := cond.Message - if message == "" { - message = "k8s.mariadb.com Backup terminal failure" - } - return r.markBackupJobFailed(ctx, j, message) - default: // Still running (Complete=False/JobRunning, Complete=False/JobNotComplete, - // JobSuspended, or no Complete condition yet). Apply a wall-clock - // deadline so a permanently-stuck Backup eventually fails the - // BackupJob instead of pinning it Running forever. + // JobSuspended, a reason this driver does not know, or no Complete + // condition yet). Apply a wall-clock deadline so a permanently-stuck + // Backup eventually fails the BackupJob instead of pinning it Running + // forever. if mariadbBackupDeadlineExceeded(j.Status.StartedAt) { - detail := "no Complete condition observed" - if cond != nil { - detail = fmt.Sprintf("Complete=%s/%s", cond.Status, cond.Reason) - } return r.markBackupJobFailed(ctx, j, fmt.Sprintf( - "k8s.mariadb.com Backup did not complete within %s (%s)", mariadbDefaultBackupDeadline, detail)) + "k8s.mariadb.com Backup did not complete within %s (%s)", mariadbDefaultBackupDeadline, mariadbCompleteDetail(cond))) } return ctrl.Result{RequeueAfter: mariadbPollInterval}, nil } } +// mariadbJobFailedMessage names the operator object whose Job failed and +// carries that Job's own Failed condition, because the operator's condition +// message is only "Failed". The operator names the Job after the object. +func mariadbJobFailedMessage(ctx context.Context, c client.Reader, kind, namespace, name string, cond *metav1.Condition) string { + message := fmt.Sprintf("k8s.mariadb.com/%s %s/%s failed (Complete=%s/%s)", kind, namespace, name, cond.Status, cond.Reason) + job := &batchv1.Job{} + if err := c.Get(ctx, types.NamespacedName{Namespace: namespace, Name: name}, job); err != nil { + if apierrors.IsNotFound(err) { + return fmt.Sprintf("%s; Job %s/%s not found", message, namespace, name) + } + return fmt.Sprintf("%s; reading Job %s/%s: %v", message, namespace, name, err) + } + for _, jc := range job.Status.Conditions { + if jc.Type == batchv1.JobFailed && jc.Status == corev1.ConditionTrue { + return fmt.Sprintf("%s; Job %s/%s: %s: %s", message, namespace, name, jc.Reason, jc.Message) + } + } + return fmt.Sprintf("%s; Job %s/%s reports no Failed condition", message, namespace, name) +} + +// mariadbCompleteDetail describes the last Complete condition for a deadline +// failure. The message matters for reason Failed, which the operator sets +// with its own cause ("Error creating Job", "Backup not complete") rather +// than from a Job. +func mariadbCompleteDetail(cond *metav1.Condition) string { + if cond == nil { + return "no Complete condition observed" + } + if cond.Message == "" { + return fmt.Sprintf("Complete=%s/%s", cond.Status, cond.Reason) + } + return fmt.Sprintf("Complete=%s/%s: %s", cond.Status, cond.Reason, cond.Message) +} + // mariadbBackupDeadlineExceeded reports whether enough wall-clock time has // elapsed since the BackupJob started that we should give up on a stuck // operator Backup. Returns false when StartedAt is nil so the very first @@ -565,7 +589,10 @@ func (r *RestoreJobReconciler) reconcileMariaDBRestore(ctx context.Context, rest cond := apimeta.FindStatusCondition(mdbRestore.Status.Conditions, mariadbtypes.ConditionTypeComplete) switch { - case cond != nil && cond.Status == metav1.ConditionTrue: + case cond != nil && cond.Reason == mariadbtypes.ConditionReasonJobFailed: + return r.markRestoreJobFailed(ctx, restoreJob, mariadbJobFailedMessage(ctx, r.Client, "Restore", mdbRestore.Namespace, mdbRestore.Name, cond)) + + case cond != nil && cond.Status == metav1.ConditionTrue && cond.Reason == mariadbtypes.ConditionReasonJobComplete: now := metav1.Now() restoreJob.Status.CompletedAt = &now restoreJob.Status.Phase = backupsv1alpha1.RestoreJobPhaseSucceeded @@ -580,23 +607,12 @@ func (r *RestoreJobReconciler) reconcileMariaDBRestore(ctx context.Context, rest } return ctrl.Result{}, nil - case cond != nil && cond.Status == metav1.ConditionFalse && cond.Reason == mariadbtypes.ConditionReasonJobFailed: - message := cond.Message - if message == "" { - message = fmt.Sprintf("k8s.mariadb.com/Restore %s/%s terminal failure", mdbRestore.Namespace, mdbRestore.Name) - } - return r.markRestoreJobFailed(ctx, restoreJob, message) - default: deadline := options.effectiveRestoreDeadline() if restoreJob.Status.StartedAt != nil && time.Since(restoreJob.Status.StartedAt.Time) > deadline { - detail := "no Complete condition observed" - if cond != nil { - detail = fmt.Sprintf("Complete=%s/%s", cond.Status, cond.Reason) - } return r.markRestoreJobFailed(ctx, restoreJob, fmt.Sprintf( "k8s.mariadb.com/Restore did not complete within %s (%s; override via spec.options.restoreTimeoutSeconds)", - deadline, detail)) + deadline, mariadbCompleteDetail(cond))) } return ctrl.Result{RequeueAfter: mariadbPollInterval}, nil } diff --git a/internal/backupcontroller/mariadbstrategy_controller_test.go b/internal/backupcontroller/mariadbstrategy_controller_test.go index 9d0001e81..df6dff6f9 100644 --- a/internal/backupcontroller/mariadbstrategy_controller_test.go +++ b/internal/backupcontroller/mariadbstrategy_controller_test.go @@ -4,12 +4,15 @@ package backupcontroller import ( "context" "encoding/json" + "errors" "strings" "testing" "time" + batchv1 "k8s.io/api/batch/v1" corev1 "k8s.io/api/core/v1" apiequality "k8s.io/apimachinery/pkg/api/equality" + apierrors "k8s.io/apimachinery/pkg/api/errors" apimeta "k8s.io/apimachinery/pkg/api/meta" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" @@ -17,6 +20,7 @@ import ( "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" @@ -860,6 +864,302 @@ func TestReconcileMariaDBRestore_KindCheckedBeforeSrcBackupGet(t *testing.T) { } } +// The operator reports a failed backing Job as Complete=True with reason +// JobFailed (SetCompleteWithJob in mariadb-operator 25.10.2), so the +// Complete status alone does not tell success from failure. +var mariadbCompleteOutcomeCases = []struct { + name string + noCondition bool + status metav1.ConditionStatus + reason string + message string + expired bool + failedJob bool + wantFailed bool + wantDone bool + wantMessage []string +}{ + {name: "Complete=True/JobComplete succeeds", status: metav1.ConditionTrue, reason: mariadbtypes.ConditionReasonJobComplete, message: "Success", wantDone: true}, + {name: "Complete=True/JobFailed fails with the Job's failure", status: metav1.ConditionTrue, reason: mariadbtypes.ConditionReasonJobFailed, message: "Failed", failedJob: true, wantFailed: true, + wantMessage: []string{"tenant/op", "BackoffLimitExceeded", "Job has reached the specified backoff limit"}}, + {name: "Complete=False/JobFailed fails with the Job's failure", status: metav1.ConditionFalse, reason: mariadbtypes.ConditionReasonJobFailed, message: "Failed", failedJob: true, wantFailed: true, + wantMessage: []string{"tenant/op", "BackoffLimitExceeded", "Job has reached the specified backoff limit"}}, + {name: "Complete=True/JobFailed with its Job gone fails", status: metav1.ConditionTrue, reason: mariadbtypes.ConditionReasonJobFailed, message: "Failed", wantFailed: true, + wantMessage: []string{"tenant/op", "Job tenant/op not found"}}, + {name: "Complete=True with an unknown reason keeps waiting", status: metav1.ConditionTrue, reason: "SomethingElse", message: "Something"}, + {name: "Complete=False/JobComplete keeps waiting", status: metav1.ConditionFalse, reason: mariadbtypes.ConditionReasonJobComplete, message: "Success"}, + {name: "Complete=False/JobRunning keeps waiting", status: metav1.ConditionFalse, reason: mariadbtypes.ConditionReasonJobRunning, message: "Running"}, + {name: "Complete=False/Failed keeps waiting", status: metav1.ConditionFalse, reason: "Failed", message: "Error creating Job"}, + {name: "no Complete condition keeps waiting", noCondition: true}, + {name: "no Complete condition past the deadline fails", noCondition: true, expired: true, wantFailed: true, + wantMessage: []string{"no Complete condition observed"}}, + {name: "Complete=True with an unknown reason past the deadline fails", status: metav1.ConditionTrue, reason: "SomethingElse", message: "Something", expired: true, wantFailed: true, + wantMessage: []string{"Complete=True/SomethingElse"}}, + {name: "Complete=False/Failed past the deadline carries the operator's message", status: metav1.ConditionFalse, reason: "Failed", message: "Error creating Job", expired: true, wantFailed: true, + wantMessage: []string{"Complete=False/Failed: Error creating Job"}}, +} + +func mariadbCompleteConditions(noCondition bool, status metav1.ConditionStatus, reason, message string) []metav1.Condition { + if noCondition { + return nil + } + return []metav1.Condition{{ + Type: mariadbtypes.ConditionTypeComplete, + Status: status, + Reason: reason, + Message: message, + LastTransitionTime: metav1.Now(), + }} +} + +// mariadbOutcomeStartedAt returns a StartedAt that is fresh, or older than +// both the backup and the default restore deadline. +func mariadbOutcomeStartedAt(expired bool) *metav1.Time { + if !expired { + now := metav1.Now() + return &now + } + past := metav1.NewTime(time.Now().Add(-2 * max(mariadbDefaultBackupDeadline, mariadbDefaultRestoreDeadline))) + return &past +} + +// mariadbOutcomeObjects adds the operator's Job, named after the operator +// Backup or Restore, failed the way the Job controller fails it once the +// backoff limit is spent. +func mariadbOutcomeObjects(failedJob bool, objs ...client.Object) []client.Object { + if !failedJob { + return objs + } + return append(objs, &batchv1.Job{ + ObjectMeta: metav1.ObjectMeta{Namespace: "tenant", Name: "op"}, + Status: batchv1.JobStatus{Conditions: []batchv1.JobCondition{{ + Type: batchv1.JobFailed, + Status: corev1.ConditionTrue, + Reason: batchv1.JobReasonBackoffLimitExceeded, + Message: "Job has reached the specified backoff limit", + }}}, + }) +} + +func assertMariaDBFailureMessage(t *testing.T, message string, want []string) { + t.Helper() + if strings.Contains(message, "logs") { + t.Errorf("failure message must not send the reader to Job logs, which are gone with the deleted pod: %q", message) + } + for _, w := range want { + if !strings.Contains(message, w) { + t.Errorf("failure message must contain %q, got %q", w, message) + } + } +} + +func TestReconcileMariaDBBackup_CompleteConditionOutcome(t *testing.T) { + strategyAPIGroup := strategyv1alpha1.GroupVersion.Group + resolved := &ResolvedBackupConfig{ + StrategyRef: corev1.TypedLocalObjectReference{ + APIGroup: &strategyAPIGroup, + Kind: strategyv1alpha1.MariaDBStrategyKind, + Name: "mdb-strategy", + }, + } + + for _, tc := range mariadbCompleteOutcomeCases { + t.Run(tc.name, func(t *testing.T) { + seed := newMariaDBBackupJob("bj", "tenant") + seed.Status.StartedAt = mariadbOutcomeStartedAt(tc.expired) + strategy := &strategyv1alpha1.MariaDB{ + ObjectMeta: metav1.ObjectMeta{Name: "mdb-strategy"}, + Spec: strategyv1alpha1.MariaDBSpec{Template: *newRenderedMariaDBTemplate()}, + } + operatorMariaDB := &mariadbtypes.MariaDB{ + ObjectMeta: metav1.ObjectMeta{Namespace: "tenant", Name: mariadbNameForApp(seed.Spec.ApplicationRef.Name)}, + } + operatorBackup := &mariadbtypes.Backup{ + ObjectMeta: metav1.ObjectMeta{ + Namespace: "tenant", + Name: "op", + Labels: map[string]string{ + backupsv1alpha1.OwningJobNameLabel: seed.Name, + backupsv1alpha1.OwningJobNamespaceLabel: seed.Namespace, + }, + }, + Status: mariadbtypes.BackupStatus{Conditions: mariadbCompleteConditions(tc.noCondition, tc.status, tc.reason, tc.message)}, + } + c := newMariaDBStrategyTestClient(t, mariadbOutcomeObjects(tc.failedJob, seed, newMariaDBApp(seed.Spec.ApplicationRef.Name, "tenant"), + strategy, operatorMariaDB, operatorBackup)...) + r := &BackupJobReconciler{Client: c, Scheme: c.Scheme(), Recorder: record.NewFakeRecorder(10)} + + bj := &backupsv1alpha1.BackupJob{} + if err := c.Get(context.Background(), client.ObjectKeyFromObject(seed), bj); err != nil { + t.Fatalf("seed Get: %v", err) + } + res, err := r.reconcileMariaDB(context.Background(), bj, resolved) + if err != nil { + t.Fatalf("reconcileMariaDB: %v", err) + } + + stored := &backupsv1alpha1.BackupJob{} + if err := c.Get(context.Background(), client.ObjectKeyFromObject(seed), stored); err != nil { + t.Fatalf("persisted Get: %v", err) + } + artifacts := &backupsv1alpha1.BackupList{} + if err := c.List(context.Background(), artifacts, client.InNamespace("tenant")); err != nil { + t.Fatalf("list Backups: %v", err) + } + switch { + case tc.wantFailed: + if stored.Status.Phase != backupsv1alpha1.BackupJobPhaseFailed { + t.Errorf("expected Phase=Failed, got %q", stored.Status.Phase) + } + assertMariaDBFailureMessage(t, stored.Status.Message, tc.wantMessage) + if stored.Status.BackupRef != nil || len(artifacts.Items) != 0 { + t.Errorf("a failed run must not produce a Backup: ref=%v artifacts=%d", stored.Status.BackupRef, len(artifacts.Items)) + } + case tc.wantDone: + if stored.Status.Phase != backupsv1alpha1.BackupJobPhaseSucceeded { + t.Errorf("expected Phase=Succeeded, got %q (message %q)", stored.Status.Phase, stored.Status.Message) + } + if stored.Status.BackupRef == nil || len(artifacts.Items) != 1 { + t.Errorf("a successful run must produce exactly one Backup: ref=%v artifacts=%d", stored.Status.BackupRef, len(artifacts.Items)) + } + default: + if stored.Status.Phase != backupsv1alpha1.BackupJobPhaseRunning { + t.Errorf("expected Phase=Running, got %q", stored.Status.Phase) + } + if res.RequeueAfter == 0 { + t.Errorf("expected a requeue while the run is in progress, got %+v", res) + } + if len(artifacts.Items) != 0 { + t.Errorf("an unfinished run must not produce a Backup, got %d", len(artifacts.Items)) + } + } + }) + } +} + +func TestMariaDBJobFailedMessage_JobUnreadable(t *testing.T) { + cond := &metav1.Condition{Type: mariadbtypes.ConditionTypeComplete, Status: metav1.ConditionTrue, Reason: mariadbtypes.ConditionReasonJobFailed} + readErr := apierrors.NewForbidden(batchv1.Resource("jobs"), "op", errors.New("rbac")) + c := interceptor.NewClient(newMariaDBStrategyTestClient(t).(client.WithWatch), interceptor.Funcs{ + Get: func(ctx context.Context, cl client.WithWatch, key client.ObjectKey, obj client.Object, opts ...client.GetOption) error { + if _, ok := obj.(*batchv1.Job); ok { + return readErr + } + return cl.Get(ctx, key, obj, opts...) + }, + }) + + got := mariadbJobFailedMessage(context.Background(), c, "Backup", "tenant", "op", cond) + for _, want := range []string{"k8s.mariadb.com/Backup tenant/op failed (Complete=True/JobFailed)", "reading Job tenant/op", readErr.Error()} { + if !strings.Contains(got, want) { + t.Errorf("message must contain %q, got %q", want, got) + } + } +} + +func TestMariaDBJobFailedMessage_JobWithoutFailedCondition(t *testing.T) { + cond := &metav1.Condition{Type: mariadbtypes.ConditionTypeComplete, Status: metav1.ConditionTrue, Reason: mariadbtypes.ConditionReasonJobFailed} + c := newMariaDBStrategyTestClient(t, &batchv1.Job{ + ObjectMeta: metav1.ObjectMeta{Namespace: "tenant", Name: "op"}, + Status: batchv1.JobStatus{Conditions: []batchv1.JobCondition{ + {Type: batchv1.JobFailureTarget, Status: corev1.ConditionTrue, Reason: batchv1.JobReasonPodFailurePolicy}, + {Type: batchv1.JobFailed, Status: corev1.ConditionFalse, Reason: batchv1.JobReasonBackoffLimitExceeded}, + }}, + }) + + got := mariadbJobFailedMessage(context.Background(), c, "Restore", "tenant", "op", cond) + if !strings.Contains(got, "Job tenant/op reports no Failed condition") || + strings.Contains(got, batchv1.JobReasonBackoffLimitExceeded) || strings.Contains(got, batchv1.JobReasonPodFailurePolicy) { + t.Errorf("a Failed condition that is not True must not be reported as the cause, got %q", got) + } +} + +func TestMariaDBCompleteDetail(t *testing.T) { + for _, tc := range []struct { + cond *metav1.Condition + want string + }{ + {nil, "no Complete condition observed"}, + {&metav1.Condition{Status: metav1.ConditionFalse, Reason: "Failed", Message: "Backup not complete"}, "Complete=False/Failed: Backup not complete"}, + {&metav1.Condition{Status: metav1.ConditionFalse, Reason: "Failed"}, "Complete=False/Failed"}, + } { + if got := mariadbCompleteDetail(tc.cond); got != tc.want { + t.Errorf("mariadbCompleteDetail(%+v) = %q, want %q", tc.cond, got, tc.want) + } + } +} + +func TestReconcileMariaDBRestore_CompleteConditionOutcome(t *testing.T) { + apps := mariadbapp.GroupName + + for _, tc := range mariadbCompleteOutcomeCases { + t.Run(tc.name, func(t *testing.T) { + cozyBackup := &backupsv1alpha1.Backup{ + ObjectMeta: metav1.ObjectMeta{Namespace: "tenant", Name: "src-cozy-bk"}, + Spec: backupsv1alpha1.BackupSpec{ + ApplicationRef: corev1.TypedLocalObjectReference{Kind: "MariaDB", Name: "src", APIGroup: &apps}, + DriverMetadata: map[string]string{mariadbBackupNameKey: "src-op-bk"}, + }, + } + seed := &backupsv1alpha1.RestoreJob{ + ObjectMeta: metav1.ObjectMeta{Namespace: "tenant", Name: "rj"}, + Spec: backupsv1alpha1.RestoreJobSpec{ + BackupRef: corev1.LocalObjectReference{Name: cozyBackup.Name}, + TargetApplicationRef: &corev1.TypedLocalObjectReference{Kind: "MariaDB", Name: "target", APIGroup: &apps}, + }, + Status: backupsv1alpha1.RestoreJobStatus{StartedAt: mariadbOutcomeStartedAt(tc.expired), Phase: backupsv1alpha1.RestoreJobPhaseRunning}, + } + operatorRestore := &mariadbtypes.Restore{ + ObjectMeta: metav1.ObjectMeta{ + Namespace: "tenant", + Name: "op", + Labels: map[string]string{ + backupsv1alpha1.OwningJobNameLabel: seed.Name, + backupsv1alpha1.OwningJobNamespaceLabel: seed.Namespace, + }, + }, + Status: mariadbtypes.RestoreStatus{Conditions: mariadbCompleteConditions(tc.noCondition, tc.status, tc.reason, tc.message)}, + } + c := newMariaDBStrategyTestClient(t, mariadbOutcomeObjects(tc.failedJob, cozyBackup, seed, operatorRestore, + &mariadbtypes.Backup{ObjectMeta: metav1.ObjectMeta{Namespace: "tenant", Name: "src-op-bk"}}, + &mariadbtypes.MariaDB{ObjectMeta: metav1.ObjectMeta{Namespace: "tenant", Name: mariadbNameForApp("target")}})...) + r := &RestoreJobReconciler{Client: c, Recorder: record.NewFakeRecorder(10)} + + rj := &backupsv1alpha1.RestoreJob{} + if err := c.Get(context.Background(), client.ObjectKeyFromObject(seed), rj); err != nil { + t.Fatalf("seed Get: %v", err) + } + res, err := r.reconcileMariaDBRestore(context.Background(), rj, cozyBackup) + if err != nil { + t.Fatalf("reconcileMariaDBRestore: %v", err) + } + + stored := &backupsv1alpha1.RestoreJob{} + if err := c.Get(context.Background(), client.ObjectKeyFromObject(seed), stored); err != nil { + t.Fatalf("persisted Get: %v", err) + } + switch { + case tc.wantFailed: + if stored.Status.Phase != backupsv1alpha1.RestoreJobPhaseFailed { + t.Errorf("expected Phase=Failed, got %q", stored.Status.Phase) + } + assertMariaDBFailureMessage(t, stored.Status.Message, tc.wantMessage) + case tc.wantDone: + if stored.Status.Phase != backupsv1alpha1.RestoreJobPhaseSucceeded { + t.Errorf("expected Phase=Succeeded, got %q (message %q)", stored.Status.Phase, stored.Status.Message) + } + default: + if stored.Status.Phase != backupsv1alpha1.RestoreJobPhaseRunning { + t.Errorf("expected Phase=Running, got %q", stored.Status.Phase) + } + if res.RequeueAfter == 0 { + t.Errorf("expected a requeue while the run is in progress, got %+v", res) + } + } + }) + } +} + // --------------------------------------------------------------------------- // Test helpers // --------------------------------------------------------------------------- diff --git a/internal/backupcontroller/mariadbtypes/types.go b/internal/backupcontroller/mariadbtypes/types.go index 3a1be22c7..debdbb0ef 100644 --- a/internal/backupcontroller/mariadbtypes/types.go +++ b/internal/backupcontroller/mariadbtypes/types.go @@ -27,16 +27,20 @@ const ( GroupName = "k8s.mariadb.com" Version = "v1alpha1" - // Operator-side condition type set on Backup and Restore once the run - // terminates. Status=True means success; Status=False with Reason - // explains the failure or in-progress state. + // Operator-side condition type set on Backup and Restore. Status=True + // means the backing Job terminated, successfully or not; only the + // Reason tells the two apart (SetCompleteWithJob in mariadb-operator). ConditionTypeComplete = "Complete" // Reason values the upstream operator emits on the Complete condition. // JobComplete -> Status=True (run succeeded). - // JobFailed -> Status=False (terminal failure of the backing Job). + // JobFailed -> Status=True (terminal failure of the backing Job). // JobRunning -> Status=False (still in progress). // JobSuspended -> Status=False (admin-suspended via spec). + // The operator also writes reason Failed with Status=False and its own + // message ("Error creating Job", "Backup not complete") when a run fails + // outside its Job. It retries those, so the driver keeps waiting on + // Failed until its deadline rather than failing the run at once. ConditionReasonJobComplete = "JobComplete" ConditionReasonJobFailed = "JobFailed" ConditionReasonJobRunning = "JobRunning" @@ -172,7 +176,7 @@ type S3TLS struct { } // BackupStatus mirrors Backup.status. The operator expresses success -// via condition type "Complete" with status=True. +// via condition type "Complete" with reason JobComplete. type BackupStatus struct { Conditions []metav1.Condition `json:"conditions,omitempty"` } @@ -206,7 +210,7 @@ type RestoreSpec struct { } // RestoreStatus mirrors Restore.status. Same condition convention as -// Backup: type=Complete, Status=True on success. +// Backup: type=Complete, reason JobComplete on success. type RestoreStatus struct { Conditions []metav1.Condition `json:"conditions,omitempty"` } diff --git a/internal/backupcontroller/restorejob_controller.go b/internal/backupcontroller/restorejob_controller.go index def91c382..17855d41d 100644 --- a/internal/backupcontroller/restorejob_controller.go +++ b/internal/backupcontroller/restorejob_controller.go @@ -37,9 +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 is the manager's uncached reader. Reconcile re-reads the + // RestoreJob through it before dispatching to a driver, and the + // keepOriginalPVC rename reads back objects it has just written, which + // the cache may not have seen yet. Wired in SetupWithManager. APIReader client.Reader } @@ -92,6 +93,22 @@ func (r *RestoreJobReconciler) Reconcile(ctx context.Context, req ctrl.Request) return ctrl.Result{}, nil } + // Re-read past the cache for the reason BackupJobReconciler.Reconcile + // gives. Here the step retried for a job already over can be destructive: + // halting the VM, renaming its PVCs, deleting the Postgres cluster. + if err := r.apiReader().Get(ctx, req.NamespacedName, restoreJob); err != nil { + if apierrors.IsNotFound(err) { + return ctrl.Result{}, nil + } + logger.Error(err, "failed to re-read RestoreJob") + return ctrl.Result{}, err + } + if restoreJob.Status.Phase == backupsv1alpha1.RestoreJobPhaseSucceeded || + restoreJob.Status.Phase == backupsv1alpha1.RestoreJobPhaseFailed { + logger.V(1).Info("RestoreJob terminal on the apiserver ahead of the cache, skipping", "phase", restoreJob.Status.Phase) + return ctrl.Result{}, nil + } + // Step 1: Fetch the referenced Backup backup := &backupsv1alpha1.Backup{} backupKey := types.NamespacedName{Namespace: req.Namespace, Name: restoreJob.Spec.BackupRef.Name} diff --git a/internal/backupcontroller/stale_cache_test.go b/internal/backupcontroller/stale_cache_test.go new file mode 100644 index 000000000..916f562c5 --- /dev/null +++ b/internal/backupcontroller/stale_cache_test.go @@ -0,0 +1,197 @@ +// SPDX-License-Identifier: Apache-2.0 +package backupcontroller + +import ( + "context" + "testing" + "time" + + corev1 "k8s.io/api/core/v1" + "k8s.io/apimachinery/pkg/api/meta" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/runtime/schema" + dynamicfake "k8s.io/client-go/dynamic/fake" + "k8s.io/client-go/kubernetes/scheme" + "k8s.io/client-go/tools/record" + "sigs.k8s.io/controller-runtime/pkg/client" + clientfake "sigs.k8s.io/controller-runtime/pkg/client/fake" + "sigs.k8s.io/controller-runtime/pkg/reconcile" + + strategyv1alpha1 "github.com/cozystack/cozystack/api/backups/strategy/v1alpha1" + backupsv1alpha1 "github.com/cozystack/cozystack/api/backups/v1alpha1" + velerov1 "github.com/vmware-tanzu/velero/pkg/apis/velero/v1" +) + +// staleCacheScheme registers what both the cache and the apiserver stand-in +// hold. +func staleCacheScheme() *runtime.Scheme { + s := runtime.NewScheme() + _ = scheme.AddToScheme(s) + _ = backupsv1alpha1.AddToScheme(s) + _ = strategyv1alpha1.AddToScheme(s) + _ = velerov1.AddToScheme(s) + return s +} + +// apiServerHolding stands in for the apiserver: it holds job as the cache +// does, except for its phase. +func apiServerHolding(s *runtime.Scheme, job client.Object, phase string) client.Reader { + onAPI := job.DeepCopyObject().(client.Object) + switch j := onAPI.(type) { + case *backupsv1alpha1.BackupJob: + j.Status.Phase = backupsv1alpha1.BackupJobPhase(phase) + case *backupsv1alpha1.RestoreJob: + j.Status.Phase = backupsv1alpha1.RestoreJobPhase(phase) + } + onAPI.SetResourceVersion("") + return clientfake.NewClientBuilder().WithScheme(s).WithObjects(onAPI).Build() +} + +func countIn(t *testing.T, c client.Client, list client.ObjectList) int { + t.Helper() + if err := c.List(context.Background(), list); err != nil { + t.Fatalf("list %T: %v", list, err) + } + return meta.LenList(list) +} + +// TestReconcile_DoesNotRetryAJobItAlreadyFailed reproduces a pass that +// starts on a cache trailing the controller's own writes: the previous pass +// stamped StartedAt, which requeued the job, then failed it on a transient +// error. The cache holds the job with StartedAt and no phase; the apiserver +// holds it Failed. Before the re-read, the pass retried the Velero Backup +// creation and the job ended Failed with a Velero Backup nothing tracks. +func TestReconcile_DoesNotRetryAJobItAlreadyFailed(t *testing.T) { + appsGroup := "apps.cozystack.io" + strategyGroup := strategyv1alpha1.GroupVersion.Group + started := metav1.NewTime(time.Now().Add(-time.Second).Truncate(time.Second)) + + run := func(t *testing.T, apiPhase backupsv1alpha1.BackupJobPhase) (created int, cached backupsv1alpha1.BackupJobPhase) { + s := staleCacheScheme() + bc := &backupsv1alpha1.BackupClass{ + ObjectMeta: metav1.ObjectMeta{Name: "bc"}, + Spec: backupsv1alpha1.BackupClassSpec{Strategies: []backupsv1alpha1.BackupClassStrategy{{ + Application: backupsv1alpha1.ApplicationSelector{APIGroup: &appsGroup, Kind: "Bucket"}, + StrategyRef: corev1.TypedLocalObjectReference{APIGroup: &strategyGroup, Kind: strategyv1alpha1.VeleroStrategyKind, Name: "velero"}, + }}}, + } + j := &backupsv1alpha1.BackupJob{ + ObjectMeta: metav1.ObjectMeta{Namespace: "tenant", Name: "bj"}, + Spec: backupsv1alpha1.BackupJobSpec{ + BackupClassName: "bc", + ApplicationRef: corev1.TypedLocalObjectReference{APIGroup: &appsGroup, Kind: "Bucket", Name: "app"}, + }, + Status: backupsv1alpha1.BackupJobStatus{StartedAt: &started}, + } + strategy := &strategyv1alpha1.Velero{ObjectMeta: metav1.ObjectMeta{Name: "velero"}} + c := clientfake.NewClientBuilder().WithScheme(s).WithObjects(j, bc, strategy). + WithStatusSubresource(&backupsv1alpha1.BackupJob{}).Build() + gvr := schema.GroupVersionResource{Group: appsGroup, Version: "v1alpha1", Resource: "buckets"} + app := &unstructured.Unstructured{} + app.SetGroupVersionKind(gvr.GroupVersion().WithKind("Bucket")) + app.SetNamespace("tenant") + app.SetName("app") + r := &BackupJobReconciler{ + Client: c, + APIReader: apiServerHolding(s, j, string(apiPhase)), + Interface: dynamicfake.NewSimpleDynamicClientWithCustomListKinds(runtime.NewScheme(), map[schema.GroupVersionResource]string{gvr: "BucketList"}, app), + RESTMapper: &mockRESTMapper{mapping: &meta.RESTMapping{ + Resource: gvr, + GroupVersionKind: gvr.GroupVersion().WithKind("Bucket"), + Scope: meta.RESTScopeNamespace, + }}, + Scheme: s, + Recorder: record.NewFakeRecorder(10), + } + if _, err := r.Reconcile(context.Background(), reconcile.Request{NamespacedName: client.ObjectKeyFromObject(j)}); err != nil { + t.Fatalf("Reconcile: %v", err) + } + got := &backupsv1alpha1.BackupJob{} + if err := c.Get(context.Background(), client.ObjectKeyFromObject(j), got); err != nil { + t.Fatalf("get BackupJob: %v", err) + } + return countIn(t, c, &velerov1.BackupList{}), got.Status.Phase + } + + if created, _ := run(t, ""); created != 1 { + t.Fatalf("job still active on the apiserver: %d Velero Backups created, want 1", created) + } + created, cached := run(t, backupsv1alpha1.BackupJobPhaseFailed) + if created != 0 { + t.Errorf("job Failed on the apiserver: %d Velero Backups created, want 0", created) + } + if cached != "" { + t.Errorf("the pass wrote phase %q over a job it should have left alone", cached) + } +} + +// TestReconcileRestore_DoesNotRetryAJobItAlreadyFailed is the restore-side +// counterpart. The retried step is destructive there: before creating the +// Velero Restore, the pass suspends the VM's HelmRelease and halts the VM. +func TestReconcileRestore_DoesNotRetryAJobItAlreadyFailed(t *testing.T) { + const ns = "tenant" + strategyGroup := strategyv1alpha1.GroupVersion.Group + hrName := vmNamePrefix + "vm" + started := metav1.NewTime(time.Now().Add(-time.Second).Truncate(time.Second)) + + run := func(t *testing.T, apiPhase backupsv1alpha1.RestoreJobPhase) (restores int, hrSuspended bool, cached backupsv1alpha1.RestoreJobPhase) { + s := staleCacheScheme() + backup := &backupsv1alpha1.Backup{ + ObjectMeta: metav1.ObjectMeta{Name: "bk", Namespace: ns}, + Spec: backupsv1alpha1.BackupSpec{ + ApplicationRef: corev1.TypedLocalObjectReference{APIGroup: new("apps.cozystack.io"), Kind: vmInstanceKind, Name: "vm"}, + StrategyRef: corev1.TypedLocalObjectReference{APIGroup: &strategyGroup, Kind: strategyv1alpha1.VeleroStrategyKind, Name: "velero"}, + DriverMetadata: map[string]string{veleroBackupNameMetadataKey: "vb"}, + }, + } + rj := &backupsv1alpha1.RestoreJob{ + ObjectMeta: metav1.ObjectMeta{Name: "rj", Namespace: ns, Finalizers: []string{restoreJobFinalizer}}, + Spec: backupsv1alpha1.RestoreJobSpec{BackupRef: corev1.LocalObjectReference{Name: "bk"}}, + Status: backupsv1alpha1.RestoreJobStatus{StartedAt: &started, Phase: backupsv1alpha1.RestoreJobPhaseRunning}, + } + strategy := &strategyv1alpha1.Velero{ObjectMeta: metav1.ObjectMeta{Name: "velero"}} + veleroBackup := &velerov1.Backup{ + ObjectMeta: metav1.ObjectMeta{Name: "vb", Namespace: veleroNamespace}, + Status: velerov1.BackupStatus{Phase: velerov1.BackupPhaseCompleted}, + } + c := clientfake.NewClientBuilder().WithScheme(s).WithObjects(rj, backup, strategy, veleroBackup). + WithStatusSubresource(&backupsv1alpha1.RestoreJob{}).Build() + dyn := dynamicfake.NewSimpleDynamicClient(testCNPGScheme(t), makeUnstructuredHelmRelease(hrName, ns, nil)) + r := &RestoreJobReconciler{ + Client: c, + APIReader: apiServerHolding(s, rj, string(apiPhase)), + Interface: dyn, + Scheme: s, + Recorder: record.NewFakeRecorder(100), + } + if _, err := r.Reconcile(context.Background(), reconcile.Request{NamespacedName: client.ObjectKeyFromObject(rj)}); err != nil { + t.Fatalf("Reconcile: %v", err) + } + hr, err := dyn.Resource(helmReleaseGVR).Namespace(ns).Get(context.Background(), hrName, metav1.GetOptions{}) + if err != nil { + t.Fatalf("get HelmRelease: %v", err) + } + hrSuspended, _, _ = unstructured.NestedBool(hr.Object, "spec", "suspend") + got := &backupsv1alpha1.RestoreJob{} + if err := c.Get(context.Background(), client.ObjectKeyFromObject(rj), got); err != nil { + t.Fatalf("get RestoreJob: %v", err) + } + return countIn(t, c, &velerov1.RestoreList{}), hrSuspended, got.Status.Phase + } + + if restores, suspended, _ := run(t, backupsv1alpha1.RestoreJobPhaseRunning); restores != 1 || !suspended { + t.Fatalf("job still active on the apiserver: %d Velero Restores, HelmRelease suspended=%v; want 1 and true", restores, suspended) + } + restores, suspended, cached := run(t, backupsv1alpha1.RestoreJobPhaseFailed) + if suspended { + t.Error("job Failed on the apiserver: the pass suspended the VM's HelmRelease") + } + if restores != 0 { + t.Errorf("job Failed on the apiserver: %d Velero Restores created, want 0", restores) + } + if cached != backupsv1alpha1.RestoreJobPhaseRunning { + t.Errorf("the pass wrote phase %q over a job it should have left alone", cached) + } +} diff --git a/internal/backupcontroller/velero_backup_deletion.go b/internal/backupcontroller/velero_backup_deletion.go new file mode 100644 index 000000000..5e4a51c20 --- /dev/null +++ b/internal/backupcontroller/velero_backup_deletion.go @@ -0,0 +1,326 @@ +package backupcontroller + +import ( + "context" + "fmt" + "strconv" + "strings" + "time" + + corev1 "k8s.io/api/core/v1" + + apierrors "k8s.io/apimachinery/pkg/api/errors" + "k8s.io/apimachinery/pkg/api/meta" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + ctrl "sigs.k8s.io/controller-runtime" + "sigs.k8s.io/controller-runtime/pkg/client" + + backupsv1alpha1 "github.com/cozystack/cozystack/api/backups/v1alpha1" + + velerov1 "github.com/vmware-tanzu/velero/pkg/apis/velero/v1" +) + +// veleroDeletionRequest is what requestVeleroBackupDeletion found and did. +type veleroDeletionRequest struct { + created bool + // replaced is a request of ours that Velero had processed and that this + // call deleted before creating a new one. + replaced *velerov1.DeleteBackupRequest + // pending is a request for the backup that Velero has not processed yet. + pending *velerov1.DeleteBackupRequest + // processed is a request of ours that Velero has processed and that was + // left in place because the caller did not allow a replacement. + processed *velerov1.DeleteBackupRequest +} + +// requestVeleroBackupDeletion asks Velero to delete a backup together with its +// data in the object store. Deleting the backup.velero.io object directly only +// removes the Kubernetes object, and the BSL sync recreates it from the object +// store. Callers call it only for a backup that still exists. +// +// The request is named after the backup, so repeated calls converge on one +// request. Nothing is created while any request for the backup is +// unprocessed. A request of ours that Velero has processed means the backup +// survived it: the deletion failed, or the BSL sync brought the backup back. +// With replace set, such a request is deleted and created again, because +// Velero keeps a processed request for a day and its name would block a new +// attempt until then. Velero does not retry a processed request, so a caller +// that needs the deletion to happen must call again later. +func requestVeleroBackupDeletion(ctx context.Context, c client.Client, namespace, name string, replace bool) (veleroDeletionRequest, error) { + var res veleroDeletionRequest + requests := &velerov1.DeleteBackupRequestList{} + if err := c.List(ctx, requests, client.InNamespace(namespace)); err != nil { + return res, fmt.Errorf("failed to list DeleteBackupRequests in %s: %w", namespace, err) + } + var own *velerov1.DeleteBackupRequest + for i := range requests.Items { + dbr := &requests.Items[i] + if dbr.Spec.BackupName != name { + continue + } + if dbr.Status.Phase != velerov1.DeleteBackupRequestPhaseProcessed { + res.pending = dbr + return res, nil + } + if dbr.Name == name { + own = dbr + } + } + if own != nil { + if !replace { + res.processed = own + return res, nil + } + // The UID precondition keeps a stale cache from deleting a request + // that has already been replaced. + err := c.Delete(ctx, own, client.Preconditions{UID: &own.UID}) + switch { + case err == nil: + res.replaced = own + case apierrors.IsNotFound(err), apierrors.IsConflict(err): + default: + return res, fmt.Errorf("failed to delete processed DeleteBackupRequest %s/%s: %w", namespace, name, err) + } + } + + dbr := &velerov1.DeleteBackupRequest{ + ObjectMeta: metav1.ObjectMeta{ + Name: name, + Namespace: namespace, + }, + Spec: velerov1.DeleteBackupRequestSpec{ + BackupName: name, + }, + } + if err := c.Create(ctx, dbr); err != nil { + if apierrors.IsAlreadyExists(err) { + return res, nil + } + return res, fmt.Errorf("failed to create DeleteBackupRequest for %s/%s: %w", namespace, name, err) + } + res.created = true + return res, nil +} + +const ( + // failedJobSweepRequeue is the first interval at which a Failed + // BackupJob is reconciled again while one of its Velero backups waits + // for deletion; failedJobSweepMaxRequeue caps every interval below. + // Nothing watches DeleteBackupRequests, so a request Velero processed is + // only noticed on such a requeue. A processed request is replaced once + // failedJobSweepBackoff(retries) has passed since the last attempt, so a + // deletion Velero can never carry out (a missing, read-only or + // unavailable BSL) is attempted at most once an hour, and the annotation + // writes that record each attempt cannot cut the wait short. + failedJobSweepRequeue = 5 * time.Minute + failedJobSweepMaxRequeue = time.Hour + // failedJobRunningBackupRequeue is the first interval at which a Failed + // BackupJob is reconciled again while one of its Velero backups is still + // running. Velero rejects a deletion request for a running backup. + failedJobRunningBackupRequeue = time.Minute + + // veleroDeletionRetriesAnnotation counts, on a Failed BackupJob, the + // deletion requests that Velero processed while the backup survived. + veleroDeletionRetriesAnnotation = "backups.cozystack.io/velero-deletion-retries" + // veleroDeletionAttemptAnnotation is when the sweep last created a + // deletion request for a Failed BackupJob, in RFC 3339. + veleroDeletionAttemptAnnotation = "backups.cozystack.io/velero-deletion-attempted-at" +) + +// deleteFailedJobVeleroBackups requests deletion of the failed Velero backups +// a Failed BackupJob left behind. A failed run creates no Backup, and the +// Backup finalizer is the only other path that deletes Velero data, so without +// this the backup and its objects stay in the bucket until Velero's TTL +// expires them. It runs on every reconcile of a Failed job, which also clears +// backups left by controller versions that did not request the deletion, and +// it requests the deletion only once the Failed phase is persisted: a request +// sent before that write would let a retried run start over with the failure +// already gone. +func (r *BackupJobReconciler) deleteFailedJobVeleroBackups(ctx context.Context, j *backupsv1alpha1.BackupJob) (ctrl.Result, error) { + logger := getLogger(ctx) + + veleroBackups := &velerov1.BackupList{} + if err := r.List(ctx, veleroBackups, client.InNamespace(veleroNamespace), client.MatchingLabels{ + backupsv1alpha1.OwningJobNamespaceLabel: j.Namespace, + backupsv1alpha1.OwningJobNameLabel: j.Name, + }); err != nil { + if meta.IsNoMatchError(err) { + return ctrl.Result{}, nil + } + return ctrl.Result{}, fmt.Errorf("failed to list Velero Backups of BackupJob %s/%s: %w", j.Namespace, j.Name, err) + } + if len(veleroBackups.Items) == 0 { + return ctrl.Result{}, nil + } + + now := r.clock() + retries := veleroDeletionRetries(j) + lastAttempt := veleroDeletionAttempt(j) + nextAttempt := lastAttempt.Add(failedJobSweepBackoff(retries)) + replaceDue := lastAttempt.IsZero() || !now.Before(nextAttempt) + + var referenced map[client.ObjectKey]bool + var requeueAfter time.Duration + var attempted, replaced bool + for i := range veleroBackups.Items { + vb := &veleroBackups.Items[i] + switch vb.Status.Phase { + case velerov1.BackupPhasePartiallyFailed, velerov1.BackupPhaseFailed, velerov1.BackupPhaseFailedValidation, + // Velero marks the backup Deleting before it removes the data and + // leaves it so when that fails, so the request may need replacing. + velerov1.BackupPhaseDeleting: + case velerov1.BackupPhaseCompleted: + // A job can fail after Velero completed, when creating or + // recording its Backup fails. That Velero backup may be the only + // copy of good data, so a job-level failure never removes it: a + // Backup that references it deletes it with the Backup, and one + // that no Backup references stays until Velero's TTL expires it. + continue + default: + requeueAfter = shorterRequeue(requeueAfter, + waitingRequeue(now, vb.CreationTimestamp.Time, failedJobRunningBackupRequeue)) + continue + } + + if referenced == nil { + var err error + if referenced, err = r.veleroBackupsReferencedByBackups(ctx, j.Namespace); err != nil { + return ctrl.Result{}, err + } + } + if referenced[client.ObjectKeyFromObject(vb)] { + continue + } + + req, err := requestVeleroBackupDeletion(ctx, r.Client, vb.Namespace, vb.Name, replaceDue) + if err != nil { + return ctrl.Result{}, err + } + switch { + case req.pending != nil: + requeueAfter = shorterRequeue(requeueAfter, + waitingRequeue(now, req.pending.CreationTimestamp.Time, failedJobSweepRequeue)) + case req.processed != nil: + requeueAfter = shorterRequeue(requeueAfter, nextAttempt.Sub(now)) + case req.created: + attempted = true + if req.replaced != nil { + replaced = true + r.warnVeleroDeletionRetried(j, vb.Name, req.replaced) + } else { + logger.Info("requested deletion of the Velero Backup of a failed BackupJob", + "backupjob", j.Name, "namespace", j.Namespace, "veleroBackup", vb.Name) + } + default: + requeueAfter = shorterRequeue(requeueAfter, failedJobSweepRequeue) + } + } + if !attempted { + return ctrl.Result{RequeueAfter: requeueAfter}, nil + } + + if replaced { + retries++ + } + requeueAfter = shorterRequeue(requeueAfter, failedJobSweepBackoff(retries)) + patch := client.MergeFrom(j.DeepCopy()) + if j.Annotations == nil { + j.Annotations = map[string]string{} + } + j.Annotations[veleroDeletionRetriesAnnotation] = strconv.Itoa(retries) + j.Annotations[veleroDeletionAttemptAnnotation] = now.UTC().Format(time.RFC3339) + if err := r.Patch(ctx, j, patch); err != nil { + if apierrors.IsNotFound(err) { + return ctrl.Result{}, nil + } + // The request is already in place; without the record the next + // attempt only comes sooner than the backoff asks for. + logger.Error(err, "failed to record the Velero deletion attempt on the BackupJob", + "backupjob", j.Name, "namespace", j.Namespace) + } + return ctrl.Result{RequeueAfter: requeueAfter}, nil +} + +func (r *BackupJobReconciler) clock() time.Time { + if r.now != nil { + return r.now() + } + return time.Now() +} + +func (r *BackupJobReconciler) warnVeleroDeletionRetried(j *backupsv1alpha1.BackupJob, veleroBackup string, processed *velerov1.DeleteBackupRequest) { + if r.Recorder == nil { + return + } + reason := "Velero reported no error, but the backup still exists" + if len(processed.Status.Errors) > 0 { + reason = strings.Join(processed.Status.Errors, "; ") + } + r.Recorder.Eventf(j, corev1.EventTypeWarning, "VeleroBackupDeletionFailed", + "Velero did not delete backup %s/%s: %s; requesting the deletion again", + veleroNamespace, veleroBackup, reason) +} + +func veleroDeletionRetries(j *backupsv1alpha1.BackupJob) int { + n, err := strconv.Atoi(j.Annotations[veleroDeletionRetriesAnnotation]) + if err != nil || n < 0 { + return 0 + } + return n +} + +func veleroDeletionAttempt(j *backupsv1alpha1.BackupJob) time.Time { + t, err := time.Parse(time.RFC3339, j.Annotations[veleroDeletionAttemptAnnotation]) + if err != nil { + return time.Time{} + } + return t +} + +func failedJobSweepBackoff(retries int) time.Duration { + d := failedJobSweepRequeue + for i := 0; i < retries && d < failedJobSweepMaxRequeue; i++ { + d *= 2 + } + return min(d, failedJobSweepMaxRequeue) +} + +// waitingRequeue paces the checks on something Velero has not acted on yet: +// the next check comes after as long as it has already waited, between floor +// and failedJobSweepMaxRequeue, so a Velero that is down is not polled at a +// fixed rate. +func waitingRequeue(now, since time.Time, floor time.Duration) time.Duration { + if since.IsZero() { + return floor + } + return min(max(now.Sub(since), floor), failedJobSweepMaxRequeue) +} + +func shorterRequeue(current, next time.Duration) time.Duration { + if current == 0 || next < current { + return next + } + return current +} + +// veleroBackupsReferencedByBackups reads Backups past the cache: a Backup the +// cache has not seen yet must still protect its Velero backup from deletion. +func (r *BackupJobReconciler) veleroBackupsReferencedByBackups(ctx context.Context, namespace string) (map[client.ObjectKey]bool, error) { + backups := &backupsv1alpha1.BackupList{} + if err := r.apiReader().List(ctx, backups, client.InNamespace(namespace)); err != nil { + return nil, fmt.Errorf("failed to list Backups in %s: %w", namespace, err) + } + referenced := map[client.ObjectKey]bool{} + for _, b := range backups.Items { + name := b.Spec.DriverMetadata[veleroBackupNameMetadataKey] + if name == "" { + continue + } + ns := b.Spec.DriverMetadata[veleroBackupNamespaceMetadataKey] + if ns == "" { + ns = veleroNamespace + } + referenced[client.ObjectKey{Namespace: ns, Name: name}] = true + } + return referenced, nil +} diff --git a/internal/backupcontroller/velero_backup_deletion_test.go b/internal/backupcontroller/velero_backup_deletion_test.go new file mode 100644 index 000000000..f375bbb17 --- /dev/null +++ b/internal/backupcontroller/velero_backup_deletion_test.go @@ -0,0 +1,603 @@ +package backupcontroller + +import ( + "context" + "errors" + "fmt" + "strings" + "testing" + "time" + + corev1 "k8s.io/api/core/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + "k8s.io/apimachinery/pkg/api/meta" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime/schema" + "k8s.io/apimachinery/pkg/types" + "k8s.io/client-go/tools/record" + ctrl "sigs.k8s.io/controller-runtime" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/client/fake" + "sigs.k8s.io/controller-runtime/pkg/client/interceptor" + + strategyv1alpha1 "github.com/cozystack/cozystack/api/backups/strategy/v1alpha1" + backupsv1alpha1 "github.com/cozystack/cozystack/api/backups/v1alpha1" + velerov1 "github.com/vmware-tanzu/velero/pkg/apis/velero/v1" +) + +const ( + failedJobNamespace = "tenant-acme" + failedJobName = "vm-backup" + failedVeleroBackup = "tenant-acme.vm-backup-x7k2p" +) + +func newVeleroCleanupClient(t *testing.T, funcs *interceptor.Funcs, objs ...client.Object) client.Client { + t.Helper() + b := fake.NewClientBuilder(). + WithScheme(newReconcilerScheme(t)). + WithObjects(objs...). + WithStatusSubresource(&backupsv1alpha1.BackupJob{}) + if funcs != nil { + b = b.WithInterceptorFuncs(*funcs) + } + return b.Build() +} + +func newVeleroCleanupReconciler(t *testing.T, objs ...client.Object) (*BackupJobReconciler, client.Client) { + t.Helper() + c := newVeleroCleanupClient(t, nil, objs...) + return &BackupJobReconciler{Client: c, Recorder: record.NewFakeRecorder(16)}, c +} + +func veleroCleanupJob(phase backupsv1alpha1.BackupJobPhase) *backupsv1alpha1.BackupJob { + started := metav1.Now() + return &backupsv1alpha1.BackupJob{ + ObjectMeta: metav1.ObjectMeta{Namespace: failedJobNamespace, Name: failedJobName}, + Status: backupsv1alpha1.BackupJobStatus{ + Phase: phase, + StartedAt: &started, + }, + } +} + +func ownedVeleroBackup(name string, phase velerov1.BackupPhase) *velerov1.Backup { + return &velerov1.Backup{ + ObjectMeta: metav1.ObjectMeta{ + Namespace: veleroNamespace, + Name: name, + Labels: map[string]string{ + backupsv1alpha1.OwningJobNameLabel: failedJobName, + backupsv1alpha1.OwningJobNamespaceLabel: failedJobNamespace, + }, + }, + Status: velerov1.BackupStatus{Phase: phase, FailureReason: "object store unreachable"}, + } +} + +func referencingBackup(veleroBackupName string) *backupsv1alpha1.Backup { + return &backupsv1alpha1.Backup{ + ObjectMeta: metav1.ObjectMeta{Namespace: failedJobNamespace, Name: failedJobName}, + Spec: backupsv1alpha1.BackupSpec{DriverMetadata: map[string]string{ + veleroBackupNameMetadataKey: veleroBackupName, + veleroBackupNamespaceMetadataKey: veleroNamespace, + }}, + } +} + +func deleteRequest(name string, phase velerov1.DeleteBackupRequestPhase, errs ...string) *velerov1.DeleteBackupRequest { + return &velerov1.DeleteBackupRequest{ + ObjectMeta: metav1.ObjectMeta{Namespace: veleroNamespace, Name: name, UID: types.UID(name + "-uid")}, + Spec: velerov1.DeleteBackupRequestSpec{BackupName: failedVeleroBackup}, + Status: velerov1.DeleteBackupRequestStatus{Phase: phase, Errors: errs}, + } +} + +func veleroCleanupResolved() *ResolvedBackupConfig { + apiGroup := strategyv1alpha1.GroupVersion.Group + return &ResolvedBackupConfig{StrategyRef: corev1.TypedLocalObjectReference{ + APIGroup: &apiGroup, Kind: strategyv1alpha1.VeleroStrategyKind, Name: "velero", + }} +} + +func veleroCleanupStrategy() *strategyv1alpha1.Velero { + return &strategyv1alpha1.Velero{ObjectMeta: metav1.ObjectMeta{Name: "velero"}} +} + +func listDeleteBackupRequests(t *testing.T, c client.Client) []velerov1.DeleteBackupRequest { + t.Helper() + l := &velerov1.DeleteBackupRequestList{} + if err := c.List(context.Background(), l, client.InNamespace(veleroNamespace)); err != nil { + t.Fatalf("list DeleteBackupRequests: %v", err) + } + return l.Items +} + +func reconcileCleanupJob(t *testing.T, r *BackupJobReconciler) ctrl.Result { + t.Helper() + res, err := r.Reconcile(context.Background(), ctrl.Request{ + NamespacedName: types.NamespacedName{Namespace: failedJobNamespace, Name: failedJobName}, + }) + if err != nil { + t.Fatalf("Reconcile: %v", err) + } + return res +} + +func getCleanupJob(t *testing.T, c client.Client) *backupsv1alpha1.BackupJob { + t.Helper() + j := &backupsv1alpha1.BackupJob{} + if err := c.Get(context.Background(), types.NamespacedName{Namespace: failedJobNamespace, Name: failedJobName}, j); err != nil { + t.Fatalf("get BackupJob: %v", err) + } + return j +} + +// A Velero backup that ends Failed or PartiallyFailed produces no Backup. The +// run keeps its failure message, and the deletion is requested by the +// reconcile that follows the persisted Failed phase, once. +func TestReconcileVelero_FailedBackupRequestsDeletionAfterFailedIsPersisted(t *testing.T) { + for _, phase := range []velerov1.BackupPhase{velerov1.BackupPhaseFailed, velerov1.BackupPhasePartiallyFailed} { + t.Run(string(phase), func(t *testing.T) { + j := veleroCleanupJob(backupsv1alpha1.BackupJobPhaseRunning) + r, c := newVeleroCleanupReconciler(t, j, ownedVeleroBackup(failedVeleroBackup, phase), veleroCleanupStrategy()) + + if _, err := r.reconcileVelero(context.Background(), j, veleroCleanupResolved()); err != nil { + t.Fatalf("reconcileVelero: %v", err) + } + got := getCleanupJob(t, c) + if got.Status.Phase != backupsv1alpha1.BackupJobPhaseFailed { + t.Fatalf("expected BackupJob Failed, got %q", got.Status.Phase) + } + wantMsg := "Velero Backup failed with phase " + string(phase) + ": object store unreachable" + if got.Status.Message != wantMsg { + t.Errorf("message = %q, want %q", got.Status.Message, wantMsg) + } + if dbrs := listDeleteBackupRequests(t, c); len(dbrs) != 0 { + t.Fatalf("deletion must wait for the next reconcile, got %+v", dbrs) + } + + if res := reconcileCleanupJob(t, r); res.RequeueAfter != failedJobSweepRequeue { + t.Errorf("RequeueAfter = %v, want %v", res.RequeueAfter, failedJobSweepRequeue) + } + dbrs := listDeleteBackupRequests(t, c) + if len(dbrs) != 1 || dbrs[0].Name != failedVeleroBackup || dbrs[0].Spec.BackupName != failedVeleroBackup { + t.Fatalf("expected one DeleteBackupRequest for %s, got %+v", failedVeleroBackup, dbrs) + } + + reconcileCleanupJob(t, r) + if n := len(listDeleteBackupRequests(t, c)); n != 1 { + t.Fatalf("a second reconcile must not add a request, got %d", n) + } + }) + } +} + +// If the Failed phase cannot be written, the run is retried and must still +// find its Velero backup to report the failure from. +func TestReconcileVelero_FailedStatusWriteErrorRequestsNoDeletion(t *testing.T) { + j := veleroCleanupJob(backupsv1alpha1.BackupJobPhaseRunning) + funcs := &interceptor.Funcs{ + SubResourceUpdate: func(ctx context.Context, c client.Client, sub string, obj client.Object, opts ...client.SubResourceUpdateOption) error { + if bj, ok := obj.(*backupsv1alpha1.BackupJob); ok && bj.Status.Phase == backupsv1alpha1.BackupJobPhaseFailed { + return apierrors.NewServiceUnavailable("etcd timeout") + } + return c.SubResource(sub).Update(ctx, obj, opts...) + }, + } + c := newVeleroCleanupClient(t, funcs, j, ownedVeleroBackup(failedVeleroBackup, velerov1.BackupPhaseFailed), veleroCleanupStrategy()) + r := &BackupJobReconciler{Client: c, Recorder: record.NewFakeRecorder(16)} + + if _, err := r.reconcileVelero(context.Background(), j, veleroCleanupResolved()); err == nil { + t.Fatal("expected the status write error to be returned") + } + if got := getCleanupJob(t, c); got.Status.Phase == backupsv1alpha1.BackupJobPhaseFailed { + t.Fatalf("status write was rejected, got phase %q", got.Status.Phase) + } + if dbrs := listDeleteBackupRequests(t, c); len(dbrs) != 0 { + t.Fatalf("no deletion may be requested before Failed is persisted, got %+v", dbrs) + } +} + +func TestReconcileVelero_CompletedBackupRequestsNoDeletion(t *testing.T) { + j := veleroCleanupJob(backupsv1alpha1.BackupJobPhaseRunning) + r, c := newVeleroCleanupReconciler(t, j, ownedVeleroBackup(failedVeleroBackup, velerov1.BackupPhaseCompleted), veleroCleanupStrategy()) + + if _, err := r.reconcileVelero(context.Background(), j, veleroCleanupResolved()); err != nil { + t.Fatalf("reconcileVelero: %v", err) + } + if got := getCleanupJob(t, c); got.Status.Phase != backupsv1alpha1.BackupJobPhaseSucceeded { + t.Fatalf("expected BackupJob Succeeded, got %q (%s)", got.Status.Phase, got.Status.Message) + } + reconcileCleanupJob(t, r) + if dbrs := listDeleteBackupRequests(t, c); len(dbrs) != 0 { + t.Fatalf("a succeeded run must not request deletion, got %+v", dbrs) + } +} + +func TestReconcileVelero_SeveralVeleroBackupsKeepCompletedOne(t *testing.T) { + j := veleroCleanupJob(backupsv1alpha1.BackupJobPhaseRunning) + r, c := newVeleroCleanupReconciler(t, j, veleroCleanupStrategy(), + ownedVeleroBackup("vb-b", velerov1.BackupPhaseFailed), + ownedVeleroBackup("vb-a", velerov1.BackupPhaseCompleted)) + + if _, err := r.reconcileVelero(context.Background(), j, veleroCleanupResolved()); err != nil { + t.Fatalf("reconcileVelero: %v", err) + } + got := getCleanupJob(t, c) + if got.Status.Phase != backupsv1alpha1.BackupJobPhaseFailed || got.Status.CompletedAt == nil { + t.Fatalf("expected BackupJob Failed with completedAt, got %+v", got.Status) + } + if want := "more than one Velero Backup references this BackupJob: vb-a, vb-b"; got.Status.Message != want { + t.Errorf("message = %q, want %q", got.Status.Message, want) + } + + reconcileCleanupJob(t, r) + dbrs := listDeleteBackupRequests(t, c) + if len(dbrs) != 1 || dbrs[0].Spec.BackupName != "vb-b" { + t.Fatalf("expected a request for the failed vb-b only, got %+v", dbrs) + } +} + +// Reconciling a Failed BackupJob, including one that failed under a version +// without the cleanup, requests deletion of its failed Velero backups only. +func TestReconcile_FailedJobVeleroBackupSweep(t *testing.T) { + foreign := failedVeleroBackup + "-abcde" + cases := []struct { + name string + veleroPhase velerov1.BackupPhase + jobPhase backupsv1alpha1.BackupJobPhase + existing []client.Object + // Backups visible to the uncached reader only. + uncached []client.Object + wantRequests map[string]velerov1.DeleteBackupRequestPhase + wantRequeue time.Duration + wantEvent bool + }{ + { + name: "PartiallyFailed without a request", + veleroPhase: velerov1.BackupPhasePartiallyFailed, + jobPhase: backupsv1alpha1.BackupJobPhaseFailed, + wantRequests: map[string]velerov1.DeleteBackupRequestPhase{failedVeleroBackup: ""}, + wantRequeue: failedJobSweepRequeue, + }, + { + name: "FailedValidation is deleted", + veleroPhase: velerov1.BackupPhaseFailedValidation, + jobPhase: backupsv1alpha1.BackupJobPhaseFailed, + wantRequests: map[string]velerov1.DeleteBackupRequestPhase{failedVeleroBackup: ""}, + wantRequeue: failedJobSweepRequeue, + }, + { + name: "pending request from elsewhere", + veleroPhase: velerov1.BackupPhaseFailed, + jobPhase: backupsv1alpha1.BackupJobPhaseFailed, + existing: []client.Object{deleteRequest(foreign, velerov1.DeleteBackupRequestPhaseInProgress)}, + wantRequests: map[string]velerov1.DeleteBackupRequestPhase{foreign: velerov1.DeleteBackupRequestPhaseInProgress}, + wantRequeue: failedJobSweepRequeue, + }, + { + name: "errored request from elsewhere is left alone", + veleroPhase: velerov1.BackupPhaseFailed, + jobPhase: backupsv1alpha1.BackupJobPhaseFailed, + existing: []client.Object{deleteRequest(foreign, velerov1.DeleteBackupRequestPhaseProcessed, "backup storage location unavailable")}, + wantRequests: map[string]velerov1.DeleteBackupRequestPhase{ + failedVeleroBackup: "", + foreign: velerov1.DeleteBackupRequestPhaseProcessed, + }, + wantRequeue: failedJobSweepRequeue, + }, + { + name: "own request processed with errors is replaced", + veleroPhase: velerov1.BackupPhaseFailed, + jobPhase: backupsv1alpha1.BackupJobPhaseFailed, + existing: []client.Object{deleteRequest(failedVeleroBackup, velerov1.DeleteBackupRequestPhaseProcessed, "backup is still in progress")}, + wantRequests: map[string]velerov1.DeleteBackupRequestPhase{failedVeleroBackup: ""}, + wantRequeue: 2 * failedJobSweepRequeue, + wantEvent: true, + }, + { + name: "own request processed without errors while the backup exists is replaced", + veleroPhase: velerov1.BackupPhaseFailed, + jobPhase: backupsv1alpha1.BackupJobPhaseFailed, + existing: []client.Object{deleteRequest(failedVeleroBackup, velerov1.DeleteBackupRequestPhaseProcessed)}, + wantRequests: map[string]velerov1.DeleteBackupRequestPhase{failedVeleroBackup: ""}, + wantRequeue: 2 * failedJobSweepRequeue, + wantEvent: true, + }, + { + name: "Deleting with a request in progress", + veleroPhase: velerov1.BackupPhaseDeleting, + jobPhase: backupsv1alpha1.BackupJobPhaseFailed, + existing: []client.Object{deleteRequest(failedVeleroBackup, velerov1.DeleteBackupRequestPhaseInProgress)}, + wantRequests: map[string]velerov1.DeleteBackupRequestPhase{failedVeleroBackup: velerov1.DeleteBackupRequestPhaseInProgress}, + wantRequeue: failedJobSweepRequeue, + }, + { + name: "Deleting left by an errored request", + veleroPhase: velerov1.BackupPhaseDeleting, + jobPhase: backupsv1alpha1.BackupJobPhaseFailed, + existing: []client.Object{deleteRequest(failedVeleroBackup, velerov1.DeleteBackupRequestPhaseProcessed, "error deleting backup from object storage")}, + wantRequests: map[string]velerov1.DeleteBackupRequestPhase{failedVeleroBackup: ""}, + wantRequeue: 2 * failedJobSweepRequeue, + wantEvent: true, + }, + { + name: "Completed is never deleted", + veleroPhase: velerov1.BackupPhaseCompleted, + jobPhase: backupsv1alpha1.BackupJobPhaseFailed, + }, + { + name: "failed backup referenced by a Backup the cache has not seen", + veleroPhase: velerov1.BackupPhaseFailed, + jobPhase: backupsv1alpha1.BackupJobPhaseFailed, + uncached: []client.Object{referencingBackup(failedVeleroBackup)}, + }, + { + name: "running backup", + veleroPhase: velerov1.BackupPhaseInProgress, + jobPhase: backupsv1alpha1.BackupJobPhaseFailed, + wantRequeue: failedJobRunningBackupRequeue, + }, + { + name: "new backup", + veleroPhase: "", + jobPhase: backupsv1alpha1.BackupJobPhaseFailed, + wantRequeue: failedJobRunningBackupRequeue, + }, + { + name: "succeeded job", + veleroPhase: velerov1.BackupPhaseFailed, + jobPhase: backupsv1alpha1.BackupJobPhaseSucceeded, + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + objs := append([]client.Object{veleroCleanupJob(tc.jobPhase), ownedVeleroBackup(failedVeleroBackup, tc.veleroPhase)}, tc.existing...) + r, c := newVeleroCleanupReconciler(t, objs...) + if tc.uncached != nil { + r.APIReader = newVeleroCleanupClient(t, nil, tc.uncached...) + } + + if res := reconcileCleanupJob(t, r); res.RequeueAfter != tc.wantRequeue { + t.Errorf("RequeueAfter = %v, want %v", res.RequeueAfter, tc.wantRequeue) + } + + dbrs := listDeleteBackupRequests(t, c) + if len(dbrs) != len(tc.wantRequests) { + t.Fatalf("expected requests %v, got %+v", tc.wantRequests, dbrs) + } + for _, dbr := range dbrs { + wantPhase, ok := tc.wantRequests[dbr.Name] + if !ok || dbr.Spec.BackupName != failedVeleroBackup { + t.Errorf("unexpected request %s for %s", dbr.Name, dbr.Spec.BackupName) + continue + } + if dbr.Status.Phase != wantPhase { + t.Errorf("request %s phase = %q, want %q", dbr.Name, dbr.Status.Phase, wantPhase) + } + } + + events := r.Recorder.(*record.FakeRecorder).Events + if got := len(events); (got > 0) != tc.wantEvent { + t.Errorf("got %d events, want an event: %v", got, tc.wantEvent) + } + }) + } +} + +func markOwnRequestProcessed(t *testing.T, c client.Client, errs ...string) { + t.Helper() + dbr := &velerov1.DeleteBackupRequest{} + if err := c.Get(context.Background(), types.NamespacedName{Namespace: veleroNamespace, Name: failedVeleroBackup}, dbr); err != nil { + t.Fatalf("get request: %v", err) + } + dbr.Status = velerov1.DeleteBackupRequestStatus{Phase: velerov1.DeleteBackupRequestPhaseProcessed, Errors: errs} + if err := c.Update(context.Background(), dbr); err != nil { + t.Fatalf("mark request processed: %v", err) + } +} + +// A deletion Velero keeps failing at once is retried only after a growing +// wait, even though recording each attempt triggers a new reconcile, and +// every retry is reported on the BackupJob with Velero's errors. +func TestReconcile_FailedJobVeleroDeletionBacksOff(t *testing.T) { + const readOnly = "backup storage location default is currently in read-only mode" + r, c := newVeleroCleanupReconciler(t, + veleroCleanupJob(backupsv1alpha1.BackupJobPhaseFailed), + ownedVeleroBackup(failedVeleroBackup, velerov1.BackupPhaseFailed)) + now := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC) + r.now = func() time.Time { return now } + events := r.Recorder.(*record.FakeRecorder).Events + expectEvent := func(step string, want bool) { + t.Helper() + select { + case ev := <-events: + if !want { + t.Fatalf("%s: unexpected event %q", step, ev) + } + if !strings.Contains(ev, "Warning VeleroBackupDeletionFailed") || !strings.Contains(ev, readOnly) { + t.Errorf("%s: unexpected event %q", step, ev) + } + default: + if want { + t.Fatalf("%s: no Warning event", step) + } + } + } + + if res := reconcileCleanupJob(t, r); res.RequeueAfter != failedJobSweepRequeue { + t.Fatalf("first request: RequeueAfter = %v, want %v", res.RequeueAfter, failedJobSweepRequeue) + } + expectEvent("first request", false) + + markOwnRequestProcessed(t, c, readOnly) + if res := reconcileCleanupJob(t, r); res.RequeueAfter != failedJobSweepRequeue { + t.Errorf("before the backoff: RequeueAfter = %v, want %v", res.RequeueAfter, failedJobSweepRequeue) + } + expectEvent("before the backoff", false) + + for i, wait := range []time.Duration{5 * time.Minute, 10 * time.Minute, 20 * time.Minute} { + now = now.Add(wait) + step := fmt.Sprintf("retry %d", i+1) + if res := reconcileCleanupJob(t, r); res.RequeueAfter != 2*wait { + t.Errorf("%s: RequeueAfter = %v, want %v", step, res.RequeueAfter, 2*wait) + } + expectEvent(step, true) + + markOwnRequestProcessed(t, c, readOnly) + if res := reconcileCleanupJob(t, r); res.RequeueAfter != 2*wait { + t.Errorf("%s, reconcile right after: RequeueAfter = %v, want %v", step, res.RequeueAfter, 2*wait) + } + expectEvent(step+", reconcile right after", false) + if n := len(listDeleteBackupRequests(t, c)); n != 1 { + t.Fatalf("%s: expected one request, got %d", step, n) + } + } + + if got := failedJobSweepBackoff(10); got != failedJobSweepMaxRequeue { + t.Errorf("backoff after 10 retries = %v, want the %v cap", got, failedJobSweepMaxRequeue) + } +} + +// Requests and backups Velero has not acted on yet are checked less often the +// longer they wait, and waiting is not reported. +func TestReconcile_FailedJobWaitingOnVeleroBacksOff(t *testing.T) { + now := time.Date(2026, 1, 1, 12, 0, 0, 0, time.UTC) + cases := []struct { + name string + veleroPhase velerov1.BackupPhase + existing []client.Object + backupAge time.Duration + want time.Duration + }{ + {name: "request waiting 20m", veleroPhase: velerov1.BackupPhaseFailed, want: 20 * time.Minute, + existing: []client.Object{agedRequest(now.Add(-20 * time.Minute))}}, + {name: "request waiting 3h", veleroPhase: velerov1.BackupPhaseFailed, want: failedJobSweepMaxRequeue, + existing: []client.Object{agedRequest(now.Add(-3 * time.Hour))}}, + {name: "request just created", veleroPhase: velerov1.BackupPhaseFailed, want: failedJobSweepRequeue, + existing: []client.Object{agedRequest(now)}}, + {name: "backup new for 3h", veleroPhase: velerov1.BackupPhaseNew, backupAge: 3 * time.Hour, want: failedJobSweepMaxRequeue}, + {name: "backup new for 10m", veleroPhase: "", backupAge: 10 * time.Minute, want: 10 * time.Minute}, + {name: "backup just started", veleroPhase: velerov1.BackupPhaseInProgress, want: failedJobRunningBackupRequeue}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + vb := ownedVeleroBackup(failedVeleroBackup, tc.veleroPhase) + vb.CreationTimestamp = metav1.NewTime(now.Add(-tc.backupAge)) + r, c := newVeleroCleanupReconciler(t, append([]client.Object{veleroCleanupJob(backupsv1alpha1.BackupJobPhaseFailed), vb}, tc.existing...)...) + r.now = func() time.Time { return now } + + if res := reconcileCleanupJob(t, r); res.RequeueAfter != tc.want { + t.Errorf("RequeueAfter = %v, want %v", res.RequeueAfter, tc.want) + } + if n := len(listDeleteBackupRequests(t, c)); n != len(tc.existing) { + t.Errorf("waiting must not create requests, got %d", n) + } + if events := r.Recorder.(*record.FakeRecorder).Events; len(events) != 0 { + t.Errorf("waiting must not be reported, got %q", <-events) + } + }) + } +} + +func agedRequest(created time.Time) *velerov1.DeleteBackupRequest { + dbr := deleteRequest(failedVeleroBackup, velerov1.DeleteBackupRequestPhaseInProgress) + dbr.CreationTimestamp = metav1.NewTime(created) + return dbr +} + +// Recording the attempt can fail after the request was created: a job deleted +// meanwhile ends the sweep, any other error still keeps the backoff requeue. +func TestReconcile_FailedJobAttemptRecordErrors(t *testing.T) { + for name, patchErr := range map[string]error{ + "job deleted": apierrors.NewNotFound(schema.GroupResource{Group: "backups.cozystack.io", Resource: "backupjobs"}, failedJobName), + "apiserver": apierrors.NewServiceUnavailable("etcd timeout"), + } { + t.Run(name, func(t *testing.T) { + funcs := &interceptor.Funcs{ + Patch: func(context.Context, client.WithWatch, client.Object, client.Patch, ...client.PatchOption) error { + return patchErr + }, + } + c := newVeleroCleanupClient(t, funcs, + veleroCleanupJob(backupsv1alpha1.BackupJobPhaseFailed), + ownedVeleroBackup(failedVeleroBackup, velerov1.BackupPhaseFailed)) + r := &BackupJobReconciler{Client: c, Recorder: record.NewFakeRecorder(16)} + + want := failedJobSweepRequeue + if apierrors.IsNotFound(patchErr) { + want = 0 + } + if res := reconcileCleanupJob(t, r); res.RequeueAfter != want { + t.Errorf("RequeueAfter = %v, want %v", res.RequeueAfter, want) + } + if n := len(listDeleteBackupRequests(t, c)); n != 1 { + t.Errorf("expected the request to stay, got %d", n) + } + }) + } +} + +func TestReconcile_FailedJobWithoutVeleroCRDs(t *testing.T) { + funcs := &interceptor.Funcs{ + List: func(ctx context.Context, c client.WithWatch, list client.ObjectList, opts ...client.ListOption) error { + if _, ok := list.(*velerov1.BackupList); ok { + return &meta.NoKindMatchError{GroupKind: schema.GroupKind{Group: "velero.io", Kind: "Backup"}} + } + return c.List(ctx, list, opts...) + }, + } + c := newVeleroCleanupClient(t, funcs, veleroCleanupJob(backupsv1alpha1.BackupJobPhaseFailed)) + r := &BackupJobReconciler{Client: c, Recorder: record.NewFakeRecorder(16)} + if res := reconcileCleanupJob(t, r); res.RequeueAfter != 0 { + t.Errorf("RequeueAfter = %v, want none", res.RequeueAfter) + } +} + +func TestRequestVeleroBackupDeletion_ReplacesByUID(t *testing.T) { + stale := deleteRequest(failedVeleroBackup, velerov1.DeleteBackupRequestPhaseProcessed, "backup storage location unavailable") + var preconditionUID types.UID + funcs := &interceptor.Funcs{ + Delete: func(ctx context.Context, c client.WithWatch, obj client.Object, opts ...client.DeleteOption) error { + do := &client.DeleteOptions{} + do.ApplyOptions(opts) + if do.Preconditions != nil && do.Preconditions.UID != nil { + preconditionUID = *do.Preconditions.UID + } + return c.Delete(ctx, obj, opts...) + }, + } + c := newVeleroCleanupClient(t, funcs, stale) + req, err := requestVeleroBackupDeletion(context.Background(), c, veleroNamespace, failedVeleroBackup, true) + if err != nil || !req.created || req.replaced == nil { + t.Fatalf("requestVeleroBackupDeletion = (%+v, %v), want a replaced and a created request", req, err) + } + if preconditionUID != stale.UID { + t.Errorf("Delete precondition UID = %q, want %q", preconditionUID, stale.UID) + } +} + +func TestRequestVeleroBackupDeletion_ReturnsAPIErrors(t *testing.T) { + forbidden := apierrors.NewForbidden(schema.GroupResource{Group: "velero.io", Resource: "deletebackuprequests"}, failedVeleroBackup, errors.New("denied")) + cases := map[string]interceptor.Funcs{ + "list": {List: func(context.Context, client.WithWatch, client.ObjectList, ...client.ListOption) error { + return forbidden + }}, + "create": {Create: func(context.Context, client.WithWatch, client.Object, ...client.CreateOption) error { + return forbidden + }}, + "delete": {Delete: func(context.Context, client.WithWatch, client.Object, ...client.DeleteOption) error { + return forbidden + }}, + } + for name, funcs := range cases { + t.Run(name, func(t *testing.T) { + c := newVeleroCleanupClient(t, &funcs, + deleteRequest(failedVeleroBackup, velerov1.DeleteBackupRequestPhaseProcessed, "backup storage location unavailable")) + req, err := requestVeleroBackupDeletion(context.Background(), c, veleroNamespace, failedVeleroBackup, true) + if req.created || !apierrors.IsForbidden(err) { + t.Fatalf("requestVeleroBackupDeletion = (%+v, %v), want a Forbidden error", req, err) + } + }) + } +} diff --git a/internal/backupcontroller/velerostrategy_controller.go b/internal/backupcontroller/velerostrategy_controller.go index 819caa60a..91882a4c3 100644 --- a/internal/backupcontroller/velerostrategy_controller.go +++ b/internal/backupcontroller/velerostrategy_controller.go @@ -6,6 +6,7 @@ import ( "encoding/hex" "encoding/json" "fmt" + "sort" "strings" "time" @@ -306,12 +307,12 @@ func (r *BackupJobReconciler) reconcileVelero(ctx context.Context, j *backupsv1a } if len(veleroBackupList.Items) > 1 { - logger.Error(fmt.Errorf("too many Velero backups for BackupJob"), "found more than one Velero Backup referencing a single BackupJob as owner") - j.Status.Phase = backupsv1alpha1.BackupJobPhaseFailed - if err := r.Status().Update(ctx, j); err != nil { - logger.Error(err, "failed to update BackupJob status") + names := make([]string, 0, len(veleroBackupList.Items)) + for _, vb := range veleroBackupList.Items { + names = append(names, vb.Name) } - return ctrl.Result{}, nil + sort.Strings(names) + return r.markBackupJobFailed(ctx, j, fmt.Sprintf("more than one Velero Backup references this BackupJob: %s", strings.Join(names, ", "))) } veleroBackup := veleroBackupList.Items[0].DeepCopy() @@ -359,6 +360,8 @@ func (r *BackupJobReconciler) reconcileVelero(ctx context.Context, j *backupsv1a // Step 5: On failure if phase == "Failed" || phase == "PartiallyFailed" { + // The Velero backup is deleted by deleteFailedJobVeleroBackups once + // the Failed phase written here triggers the next reconcile. message := formatVeleroBackupFailureMessageForBackupJob(ctx, r.Client, veleroBackup) return r.markBackupJobFailed(ctx, j, message) } diff --git a/internal/controller/applicationdefinition_helmreconciler.go b/internal/controller/applicationdefinition_helmreconciler.go index 2a07fe04c..36ae14ab6 100644 --- a/internal/controller/applicationdefinition_helmreconciler.go +++ b/internal/controller/applicationdefinition_helmreconciler.go @@ -2,12 +2,14 @@ package controller import ( "context" + "errors" "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/api/equality" "k8s.io/apimachinery/pkg/runtime" ctrl "sigs.k8s.io/controller-runtime" @@ -85,16 +87,20 @@ func (r *ApplicationDefinitionHelmReconciler) updateHelmReleasesForAppDef(ctx co logger.V(4).Info("Found HelmReleases to update", "appDef", appDef.Name, "kind", applicationKind, "count", len(hrList.Items)) - // Update each HelmRelease + // Update each HelmRelease. Only definition events and the manager's + // hours-long resync enqueue this reconciler, so a release whose update + // failed (a conflict with helm-controller writing it, say) would stay out + // of sync until then unless the failure is returned and retried. + var errs []error for i := range hrList.Items { hr := &hrList.Items[i] if err := r.updateHelmReleaseChart(ctx, hr, appDef); err != nil { logger.Error(err, "failed to update HelmRelease", "name", hr.Name, "namespace", hr.Namespace) - continue + errs = append(errs, err) } } - return nil + return errors.Join(errs...) } // expectedValuesFrom returns the expected valuesFrom configuration for HelmReleases @@ -202,6 +208,31 @@ func (r *ApplicationDefinitionHelmReconciler) updateHelmReleaseChart(ctx context } } + // Check and update the health checks the wait applies. cozystack-api writes + // healthCheckExprs and the wait strategy only when it builds a release, so + // a release created before the definition exempted an object would keep + // waiting on it at every upgrade, and fail for good on one that never + // settles. Both are derived the way the API derives them, in both + // directions, so the release matches what a fresh write would produce. A + // release another chart renders carries Flux's origin label and takes its + // gate from that chart. + if _, rendered := hr.Labels["helm.toolkit.fluxcd.io/name"]; !rendered { + exprs := appDef.Spec.Release.HealthCheckExprs + // Semantic equality treats nil and empty as equal, so a release + // already in sync is not rewritten. + if !equality.Semantic.DeepEqual(hrCopy.Spec.HealthCheckExprs, exprs) { + logger.V(4).Info("Updating HelmRelease healthCheckExprs", "name", hr.Name, "namespace", hr.Namespace) + hrCopy.Spec.HealthCheckExprs = exprs + updated = true + } + waitStrategy := config.ResolveWaitStrategy(appDef.Spec.Release.WaitStrategy, len(exprs) > 0) + if !equality.Semantic.DeepEqual(hrCopy.Spec.WaitStrategy, waitStrategy) { + logger.V(4).Info("Updating HelmRelease waitStrategy", "name", hr.Name, "namespace", hr.Namespace, "waitStrategy", waitStrategy) + hrCopy.Spec.WaitStrategy = waitStrategy + 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 f8d055184..a75fb4fcc 100644 --- a/internal/controller/applicationdefinition_helmreconciler_test.go +++ b/internal/controller/applicationdefinition_helmreconciler_test.go @@ -2,15 +2,21 @@ package controller import ( "context" + "errors" + "reflect" "testing" cozyv1alpha1 "github.com/cozystack/cozystack/api/v1alpha1" "github.com/cozystack/cozystack/pkg/config" helmv2 "github.com/fluxcd/helm-controller/api/v2" + "github.com/fluxcd/pkg/apis/kustomize" + apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/types" + "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/client/fake" + "sigs.k8s.io/controller-runtime/pkg/client/interceptor" "sigs.k8s.io/controller-runtime/pkg/reconcile" ) @@ -581,3 +587,295 @@ func TestAppDefHelm_DisableWaitScopedToKind(t *testing.T) { t.Fatalf("expected Harbor Upgrade.DisableWait=false, got %+v", gotOther.Spec.Upgrade) } } + +// dataVolumeCurrent is the expression the vm-disk definition carries, so that a +// disk CDI is still importing does not hold its release's wait. +var dataVolumeCurrent = kustomize.CustomHealthCheck{ + APIVersion: "cdi.kubevirt.io/v1beta1", + Kind: "DataVolume", + HealthCheckExpressions: kustomize.HealthCheckExpressions{Current: "true"}, +} + +// vmDiskRelease builds a VMDisk HelmRelease the way cozystack-api wrote it +// before the definition declared any expression: chartRef and valuesFrom in +// sync, no healthCheckExprs, no waitStrategy. +func vmDiskRelease() *helmv2.HelmRelease { + return &helmv2.HelmRelease{ + ObjectMeta: metav1.ObjectMeta{ + Name: "vm-disk-data", + Namespace: "tenant-foo", + Labels: map[string]string{ + "apps.cozystack.io/application.kind": "VMDisk", + "apps.cozystack.io/application.group": "apps.cozystack.io", + }, + }, + Spec: helmv2.HelmReleaseSpec{ + ChartRef: &helmv2.CrossNamespaceSourceReference{ + Kind: "ExternalArtifact", + Name: "cozystack-vm-disk-application-kubevirt-vm-disk", + Namespace: "cozy-system", + }, + ValuesFrom: expectedValuesFrom(), + }, + } +} + +// vmDiskAppDef builds the VMDisk ApplicationDefinition with the given wait +// strategy and expressions. +func vmDiskAppDef(waitStrategy string, exprs ...kustomize.CustomHealthCheck) *cozyv1alpha1.ApplicationDefinition { + return &cozyv1alpha1.ApplicationDefinition{ + ObjectMeta: metav1.ObjectMeta{Name: "vm-disk"}, + Spec: cozyv1alpha1.ApplicationDefinitionSpec{ + Application: cozyv1alpha1.ApplicationDefinitionApplication{Kind: "VMDisk"}, + Release: cozyv1alpha1.ApplicationDefinitionRelease{ + ChartRef: &helmv2.CrossNamespaceSourceReference{ + Kind: "ExternalArtifact", + Name: "cozystack-vm-disk-application-kubevirt-vm-disk", + Namespace: "cozy-system", + }, + WaitStrategy: waitStrategy, + HealthCheckExprs: exprs, + }, + }, + } +} + +// TestAppDefHelm_HealthCheckExprsApplied pins the drift behind #4409: +// cozystack-api writes healthCheckExprs only when it builds a release, so a +// disk created before the definition exempted its DataVolume kept waiting on +// it at every upgrade, and one CDI never finished importing failed its upgrade +// for good. The expressions must land, with the poller strategy that is the +// only one evaluating them. +func TestAppDefHelm_HealthCheckExprsApplied(t *testing.T) { + got := reconcileVMInstance(t, vmDiskAppDef("", dataVolumeCurrent), vmDiskRelease()) + + if want := []kustomize.CustomHealthCheck{dataVolumeCurrent}; !reflect.DeepEqual(got.Spec.HealthCheckExprs, want) { + t.Fatalf("expected HealthCheckExprs %+v, got %+v", want, got.Spec.HealthCheckExprs) + } + if got.Spec.WaitStrategy == nil || got.Spec.WaitStrategy.Name != helmv2.WaitStrategyPoller { + t.Fatalf("expected WaitStrategy poller, got %+v", got.Spec.WaitStrategy) + } +} + +// TestAppDefHelm_HealthCheckExprsRemoved pins the other direction: the API +// rebuilds the whole spec on every write, so a release left carrying what the +// definition dropped would differ from one written a moment later. +func TestAppDefHelm_HealthCheckExprsRemoved(t *testing.T) { + hr := vmDiskRelease() + hr.Spec.HealthCheckExprs = []kustomize.CustomHealthCheck{dataVolumeCurrent} + hr.Spec.WaitStrategy = &helmv2.WaitStrategy{Name: helmv2.WaitStrategyPoller} + + got := reconcileVMInstance(t, vmDiskAppDef(""), hr) + + if len(got.Spec.HealthCheckExprs) != 0 { + t.Fatalf("expected HealthCheckExprs removed, got %+v", got.Spec.HealthCheckExprs) + } + if got.Spec.WaitStrategy != nil { + t.Fatalf("expected WaitStrategy removed, got %+v", got.Spec.WaitStrategy) + } +} + +// TestAppDefHelm_WaitStrategyWithoutExprsApplied pins that an explicit strategy +// is carried on its own, not only as the default the expressions imply. +func TestAppDefHelm_WaitStrategyWithoutExprsApplied(t *testing.T) { + got := reconcileVMInstance(t, vmDiskAppDef("legacy"), vmDiskRelease()) + + if got.Spec.WaitStrategy == nil || got.Spec.WaitStrategy.Name != helmv2.WaitStrategyLegacy { + t.Fatalf("expected WaitStrategy legacy, got %+v", got.Spec.WaitStrategy) + } + if len(got.Spec.HealthCheckExprs) != 0 { + t.Fatalf("expected no HealthCheckExprs, got %+v", got.Spec.HealthCheckExprs) + } +} + +// TestAppDefHelm_HealthCheckExprsInSyncSkipsUpdate pins idempotence, like +// TestAppDefHelm_DisableWaitInSyncSkipsUpdate. A definition read with +// healthCheckExprs: [] decodes to an empty slice, while a release built without +// expressions carries none at all; comparing the two as different would +// rewrite every release of the kind on every reconcile. The fake client drops +// an empty slice on its JSON round trip, so the objects are handed to +// updateHelmReleaseChart directly. +func TestAppDefHelm_HealthCheckExprsInSyncSkipsUpdate(t *testing.T) { + cases := []struct { + name string + defExprs []kustomize.CustomHealthCheck + hrExprs []kustomize.CustomHealthCheck + hrStrategy *helmv2.WaitStrategy + }{ + { + name: "expressions and poller already set", + defExprs: []kustomize.CustomHealthCheck{dataVolumeCurrent}, + hrExprs: []kustomize.CustomHealthCheck{dataVolumeCurrent}, + hrStrategy: &helmv2.WaitStrategy{Name: helmv2.WaitStrategyPoller}, + }, + { + name: "empty on the definition, absent on the release", + defExprs: []kustomize.CustomHealthCheck{}, + }, + { + name: "absent on the definition, empty on the release", + hrExprs: []kustomize.CustomHealthCheck{}, + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + stored := vmDiskRelease() + stored.Spec.HealthCheckExprs = tc.hrExprs + stored.Spec.WaitStrategy = tc.hrStrategy + + scheme := newAppDefHelmScheme(t) + fakeClient := fake.NewClientBuilder().WithScheme(scheme).WithObjects(stored).Build() + + before := &helmv2.HelmRelease{} + if err := fakeClient.Get(context.TODO(), types.NamespacedName{Name: stored.Name, Namespace: stored.Namespace}, before); err != nil { + t.Fatalf("get HR: %v", err) + } + hr := before.DeepCopy() + hr.Spec.HealthCheckExprs = tc.hrExprs + + r := &ApplicationDefinitionHelmReconciler{Client: fakeClient, Scheme: scheme} + if err := r.updateHelmReleaseChart(context.TODO(), hr, vmDiskAppDef("", tc.defExprs...)); err != nil { + t.Fatalf("unexpected error: %v", err) + } + + after := &helmv2.HelmRelease{} + if err := fakeClient.Get(context.TODO(), types.NamespacedName{Name: stored.Name, Namespace: stored.Namespace}, after); err != nil { + t.Fatalf("get HR after update: %v", err) + } + if after.ResourceVersion != before.ResourceVersion { + t.Fatalf("release rewritten with nothing to change: %q -> %q", before.ResourceVersion, after.ResourceVersion) + } + }) + } +} + +// TestAppDefHelm_HealthCheckExprsLeaveRenderedReleaseAlone pins the scope of +// the sync. The tenant chart renders an Etcd HelmRelease carrying the same kind +// labels as one the API builds, and it sets that release's wait gate itself; +// rewriting it from the definition would strip the chart's gate until the +// parent's next upgrade put it back. Its chartRef still follows the definition. +func TestAppDefHelm_HealthCheckExprsLeaveRenderedReleaseAlone(t *testing.T) { + chartGate := kustomize.CustomHealthCheck{ + APIVersion: "etcd-operator.cozystack.io/v1alpha2", + Kind: "EtcdCluster", + HealthCheckExpressions: kustomize.HealthCheckExpressions{Current: "status.readyMembers == spec.replicas"}, + } + hr := &helmv2.HelmRelease{ + ObjectMeta: metav1.ObjectMeta{Name: "etcd", Namespace: "tenant-foo", Labels: map[string]string{ + "apps.cozystack.io/application.kind": "Etcd", + "apps.cozystack.io/application.group": "apps.cozystack.io", + "helm.toolkit.fluxcd.io/name": "tenant-foo", + }}, + Spec: helmv2.HelmReleaseSpec{ + ChartRef: &helmv2.CrossNamespaceSourceReference{Kind: "ExternalArtifact", Name: "stale", Namespace: "cozy-system"}, + ValuesFrom: expectedValuesFrom(), + HealthCheckExprs: []kustomize.CustomHealthCheck{chartGate}, + WaitStrategy: &helmv2.WaitStrategy{Name: helmv2.WaitStrategyPoller}, + }, + } + appDef := &cozyv1alpha1.ApplicationDefinition{ + ObjectMeta: metav1.ObjectMeta{Name: "etcd"}, + Spec: cozyv1alpha1.ApplicationDefinitionSpec{ + Application: cozyv1alpha1.ApplicationDefinitionApplication{Kind: "Etcd"}, + Release: cozyv1alpha1.ApplicationDefinitionRelease{ + ChartRef: &helmv2.CrossNamespaceSourceReference{Kind: "ExternalArtifact", Name: "cozystack-etcd-application-default-etcd", Namespace: "cozy-system"}, + }, + }, + } + + got := reconcileVMInstance(t, appDef, hr) + + if got.Spec.ChartRef == nil || got.Spec.ChartRef.Name != "cozystack-etcd-application-default-etcd" { + t.Fatalf("expected ChartRef synced from the definition, got %+v", got.Spec.ChartRef) + } + if want := []kustomize.CustomHealthCheck{chartGate}; !reflect.DeepEqual(got.Spec.HealthCheckExprs, want) { + t.Fatalf("expected the chart's HealthCheckExprs %+v kept, got %+v", want, got.Spec.HealthCheckExprs) + } + if got.Spec.WaitStrategy == nil || got.Spec.WaitStrategy.Name != helmv2.WaitStrategyPoller { + t.Fatalf("expected the chart's WaitStrategy poller kept, got %+v", got.Spec.WaitStrategy) + } +} + +// TestAppDefHelm_HealthCheckExprsScopedToKind pins the kind label in the +// selector: a release of another kind must not pick up the VMDisk expressions. +func TestAppDefHelm_HealthCheckExprsScopedToKind(t *testing.T) { + disk := vmDiskRelease() + other := vmDiskRelease() + other.Name = "harbor-registry" + other.Labels["apps.cozystack.io/application.kind"] = "Harbor" + + scheme := newAppDefHelmScheme(t) + appDef := vmDiskAppDef("", dataVolumeCurrent) + fakeClient := fake.NewClientBuilder().WithScheme(scheme).WithObjects(appDef, disk, 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) + } + + gotDisk := &helmv2.HelmRelease{} + if err := fakeClient.Get(context.TODO(), types.NamespacedName{Name: disk.Name, Namespace: disk.Namespace}, gotDisk); err != nil { + t.Fatalf("get VMDisk HR: %v", err) + } + if len(gotDisk.Spec.HealthCheckExprs) != 1 { + t.Fatalf("expected VMDisk HealthCheckExprs synced, got %+v", gotDisk.Spec.HealthCheckExprs) + } + + 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 len(gotOther.Spec.HealthCheckExprs) != 0 { + t.Fatalf("expected Harbor HealthCheckExprs untouched, got %+v", gotOther.Spec.HealthCheckExprs) + } + if gotOther.Spec.WaitStrategy != nil { + t.Fatalf("expected Harbor WaitStrategy untouched, got %+v", gotOther.Spec.WaitStrategy) + } +} + +// TestAppDefHelm_UpdateFailureRequeues pins that a failed write is returned +// rather than logged and dropped: nothing else re-enqueues the definition for +// hours, so a release that lost a conflict to helm-controller would keep its +// old wait until then. The releases after it are still written. +func TestAppDefHelm_UpdateFailureRequeues(t *testing.T) { + first := vmDiskRelease() + second := vmDiskRelease() + second.Name = "vm-disk-logs" + + failed := "" + scheme := newAppDefHelmScheme(t) + appDef := vmDiskAppDef("", dataVolumeCurrent) + fakeClient := fake.NewClientBuilder().WithScheme(scheme).WithObjects(appDef, first, second). + WithInterceptorFuncs(interceptor.Funcs{ + Update: func(ctx context.Context, cl client.WithWatch, obj client.Object, opts ...client.UpdateOption) error { + // Fail whichever release is written first, so the assertion + // below does not depend on the order List returns them in. + if failed == "" { + failed = obj.GetName() + return apierrors.NewConflict(helmv2.GroupVersion.WithResource("helmreleases").GroupResource(), obj.GetName(), errors.New("the object has been modified")) + } + return cl.Update(ctx, obj, opts...) + }, + }).Build() + + r := &ApplicationDefinitionHelmReconciler{Client: fakeClient, Scheme: scheme} + if _, err := r.Reconcile(context.TODO(), reconcile.Request{ + NamespacedName: types.NamespacedName{Name: appDef.Name}, + }); !apierrors.IsConflict(err) { + t.Fatalf("expected the conflict returned so the definition is requeued, got %v", err) + } + + written := first.Name + if failed == first.Name { + written = second.Name + } + got := &helmv2.HelmRelease{} + if err := fakeClient.Get(context.TODO(), types.NamespacedName{Name: written, Namespace: "tenant-foo"}, got); err != nil { + t.Fatalf("get HR: %v", err) + } + if len(got.Spec.HealthCheckExprs) != 1 { + t.Fatalf("expected %s synced past the failed %s, got %+v", written, failed, got.Spec.HealthCheckExprs) + } +} diff --git a/internal/controller/tenantquota/reconciler.go b/internal/controller/tenantquota/reconciler.go index dddd0fbac..ed18499ce 100644 --- a/internal/controller/tenantquota/reconciler.go +++ b/internal/controller/tenantquota/reconciler.go @@ -52,6 +52,17 @@ const ( // whenever it is below the chart quota, without the controller fighting Flux // over the chart-owned object. allocatedQuotaName = "tenant-quota-allocated" + // chartLimitRangeName is the LimitRange the tenant chart renders next to + // chartQuotaName, giving containers default requests and limits. The chart + // renders both only for a tenant that declares resourceQuotas. + chartLimitRangeName = "tenant-range-limits" + // allocatedLimitRangeName is the controller-owned copy of the pool root's + // chart LimitRange, written into every unbounded pool member. Those members + // render no chart LimitRange, yet carry an allocated quota; without + // container defaults, any pod omitting a limit the quota bounds is rejected + // at admission. A distinct name keeps the copy from colliding with the + // chart-owned object if the member later declares its own quota. + allocatedLimitRangeName = "tenant-range-limits-allocated" // managedByLabel marks the controller-owned ResourceQuotas so they can be // listed and garbage-collected. managedByLabel = "quota.cozystack.io/managed-by" @@ -102,6 +113,9 @@ func (r *Reconciler) Reconcile(ctx context.Context, _ ctrl.Request) (ctrl.Result pools := ComputePools(tenants) desired := map[string]corev1.ResourceList{} + // limitRangeSource maps each unbounded pool member whose quota bounds a + // compute limit to the pool root whose chart LimitRange it must inherit. + limitRangeSource := map[string]string{} for _, p := range pools { if over := p.Overcommitted(); len(over) > 0 { logger.Info("tenant quota pool is overcommitted by sub-tenant carve-outs", "pool", p.Root, "overcommit", over) @@ -120,6 +134,9 @@ func (r *Reconciler) Reconcile(ctx context.Context, _ ctrl.Request) (ctrl.Result for _, ns := range p.Members { if existing[ns] { desired[ns] = buffered.EnforcedHard(ns, usedByNS) + if ns != p.Root && boundsComputeLimits(desired[ns]) { + limitRangeSource[ns] = p.Root + } } } } @@ -134,6 +151,22 @@ func (r *Reconciler) Reconcile(ctx context.Context, _ ctrl.Request) (ctrl.Result logger.Error(err, "failed to garbage-collect stale allocated quotas") } + written := map[string]bool{} + for ns, root := range limitRangeSource { + ok, err := r.upsertAllocatedLimitRange(ctx, ns, root) + if err != nil { + logger.Error(err, "failed to apply allocated limit range", "namespace", ns, "poolRoot", root) + } + // Keep the existing copy on a transient error rather than dropping the + // defaults the namespace's pods rely on. + if ok || err != nil { + written[ns] = true + } + } + if err := r.gcAllocatedLimitRanges(ctx, written); err != nil { + logger.Error(err, "failed to garbage-collect stale allocated limit ranges") + } + return ctrl.Result{RequeueAfter: resyncInterval}, nil } @@ -224,6 +257,50 @@ func (r *Reconciler) gcAllocatedQuotas(ctx context.Context, desired map[string]c return nil } +// upsertAllocatedLimitRange copies the pool root's chart LimitRange into an +// unbounded member namespace. It reports false, without error, when the root +// has no chart LimitRange to copy. +func (r *Reconciler) upsertAllocatedLimitRange(ctx context.Context, namespace, poolRoot string) (bool, error) { + source := &corev1.LimitRange{} + if err := r.Get(ctx, types.NamespacedName{Namespace: poolRoot, Name: chartLimitRangeName}, source); err != nil { + if apierrors.IsNotFound(err) { + return false, nil + } + return false, err + } + lr := &corev1.LimitRange{ObjectMeta: metav1.ObjectMeta{Name: allocatedLimitRangeName, Namespace: namespace}} + _, err := controllerutil.CreateOrUpdate(ctx, r.Client, lr, func() error { + if lr.Labels == nil { + lr.Labels = map[string]string{} + } + lr.Labels[managedByLabel] = managedByValue + lr.Labels["internal.cozystack.io/managed-by-cozystack"] = "" + lr.Spec = *source.Spec.DeepCopy() + return nil + }) + return err == nil, err +} + +// gcAllocatedLimitRanges deletes controller-owned LimitRanges in namespaces +// that are no longer unbounded pool members (e.g. the tenant gained its own +// quota and now renders the chart LimitRange, or was deleted). +func (r *Reconciler) gcAllocatedLimitRanges(ctx context.Context, keep map[string]bool) error { + managed := &corev1.LimitRangeList{} + if err := r.List(ctx, managed, client.MatchingLabels{managedByLabel: managedByValue}); err != nil { + return err + } + for i := range managed.Items { + m := &managed.Items[i] + if keep[m.Namespace] { + continue + } + if err := r.Delete(ctx, m); err != nil && !apierrors.IsNotFound(err) { + return err + } + } + return nil +} + func (r *Reconciler) recordOvercommit(ctx context.Context, rootNamespace string, over corev1.ResourceList) { if r.Recorder == nil { return @@ -237,8 +314,8 @@ func (r *Reconciler) recordOvercommit(ctx context.Context, rootNamespace string, } // SetupWithManager wires the controller. Every relevant change (a tenant -// HelmRelease, a namespace, or a tenant ResourceQuota whose usage moved) -// coalesces into one full-tree sweep. +// HelmRelease, a namespace, a tenant ResourceQuota whose usage moved, or a +// tenant LimitRange) coalesces into one full-tree sweep. func (r *Reconciler) SetupWithManager(mgr ctrl.Manager) error { toSweep := handler.EnqueueRequestsFromMapFunc(func(context.Context, client.Object) []reconcile.Request { return []reconcile.Request{sweepKey} @@ -249,11 +326,15 @@ func (r *Reconciler) SetupWithManager(mgr ctrl.Manager) error { tenantQuotas := predicate.NewPredicateFuncs(func(o client.Object) bool { return o.GetName() == chartQuotaName || o.GetName() == allocatedQuotaName }) + tenantLimitRanges := predicate.NewPredicateFuncs(func(o client.Object) bool { + return o.GetName() == chartLimitRangeName || o.GetName() == allocatedLimitRangeName + }) return ctrl.NewControllerManagedBy(mgr). Named("tenantquota-controller"). Watches(&helmv2.HelmRelease{}, toSweep, builder.WithPredicates(tenantReleases)). Watches(&corev1.Namespace{}, toSweep). Watches(&corev1.ResourceQuota{}, toSweep, builder.WithPredicates(tenantQuotas)). + Watches(&corev1.LimitRange{}, toSweep, builder.WithPredicates(tenantLimitRanges)). Complete(r) } @@ -271,6 +352,18 @@ func ownedNamespace(hrNamespace, appName string) string { } } +// boundsComputeLimits reports whether a quota bounds limits.cpu or +// limits.memory, the only case in which admission rejects a container that +// omits a limit. The chart renders its LimitRange under any non-empty +// resourceQuotas, so the root may carry one under a quota that bounds no +// compute at all; copying it then would impose default limits the quota +// never asked for. +func boundsComputeLimits(hard corev1.ResourceList) bool { + _, cpu := hard[corev1.ResourceLimitsCPU] + _, memory := hard[corev1.ResourceLimitsMemory] + return cpu || memory +} + // maxResourceList returns the per-resource maximum of a and b. func maxResourceList(a, b corev1.ResourceList) corev1.ResourceList { out := corev1.ResourceList{} diff --git a/internal/controller/tenantquota/reconciler_test.go b/internal/controller/tenantquota/reconciler_test.go index 5f19ed1b1..b869825dc 100644 --- a/internal/controller/tenantquota/reconciler_test.go +++ b/internal/controller/tenantquota/reconciler_test.go @@ -227,3 +227,172 @@ func TestReconcile_GarbageCollect(t *testing.T) { t.Fatalf("stale allocated quota in tenant-gone should have been garbage-collected") } } + +// chartLimitRange builds the chart-rendered "tenant-range-limits" LimitRange, +// which the tenant chart emits alongside its "tenant-quota". +func chartLimitRange(namespace, defaultCPU string) *corev1.LimitRange { + return &corev1.LimitRange{ + ObjectMeta: metav1.ObjectMeta{Name: chartLimitRangeName, Namespace: namespace}, + Spec: corev1.LimitRangeSpec{Limits: []corev1.LimitRangeItem{{ + Type: corev1.LimitTypeContainer, + Default: resourceList(map[string]string{"cpu": defaultCPU, "memory": "128Mi"}), + DefaultRequest: resourceList(map[string]string{"cpu": "25m", "memory": "128Mi"}), + }}}, + } +} + +func getLimitRange(c client.Client, namespace, name string) (*corev1.LimitRange, bool) { + lr := &corev1.LimitRange{} + if err := c.Get(context.Background(), types.NamespacedName{Namespace: namespace, Name: name}, lr); err != nil { + return nil, false + } + return lr, true +} + +// TestReconcile_UnboundedMemberGetsPoolLimitRange: an unbounded child renders +// no chart quota and therefore no chart LimitRange, yet the controller clamps +// it with an allocated quota. Without container defaults, every pod that omits +// a limit the quota bounds (e.g. a sidecar without a CPU limit) is rejected at +// admission, so the controller must copy the pool root's LimitRange into it. +func TestReconcile_UnboundedMemberGetsPoolLimitRange(t *testing.T) { + r, c := newReconciler(t, + tenantHR("foo", "tenant-root"), + tenantHR("bar", "tenant-foo"), + ns("tenant-foo"), ns("tenant-foo-bar"), + chartQuota("tenant-foo", map[string]string{"limits.cpu": "10"}, nil), + chartLimitRange("tenant-foo", "250m"), + ) + if _, err := r.Reconcile(context.Background(), sweepKey); err != nil { + t.Fatalf("reconcile: %v", err) + } + lr, ok := getLimitRange(c, "tenant-foo-bar", allocatedLimitRangeName) + if !ok { + t.Fatalf("unbounded member tenant-foo-bar has an allocated quota but no LimitRange") + } + if len(lr.Spec.Limits) != 1 { + t.Fatalf("tenant-foo-bar LimitRange limits = %d, want 1", len(lr.Spec.Limits)) + } + if got := lr.Spec.Limits[0].Default[corev1.ResourceCPU]; got.String() != "250m" { + t.Fatalf("tenant-foo-bar default cpu = %q, want 250m copied from the pool root", got.String()) + } + if lr.Labels[managedByLabel] != managedByValue { + t.Fatalf("tenant-foo-bar LimitRange is not marked as controller-owned") + } + if _, ok := getLimitRange(c, "tenant-foo", allocatedLimitRangeName); ok { + t.Fatalf("pool root tenant-foo already has the chart LimitRange and must not get a second one") + } +} + +// TestReconcile_PoolLimitRangeFollowsRoot: a change to the root's chart +// LimitRange propagates to the members on the next sweep. +func TestReconcile_PoolLimitRangeFollowsRoot(t *testing.T) { + root := chartLimitRange("tenant-foo", "250m") + r, c := newReconciler(t, + tenantHR("foo", "tenant-root"), + tenantHR("bar", "tenant-foo"), + ns("tenant-foo"), ns("tenant-foo-bar"), + chartQuota("tenant-foo", map[string]string{"limits.cpu": "10"}, nil), + root, + ) + if _, err := r.Reconcile(context.Background(), sweepKey); err != nil { + t.Fatalf("reconcile: %v", err) + } + root.Spec.Limits[0].Default[corev1.ResourceCPU] = resource.MustParse("500m") + if err := c.Update(context.Background(), root); err != nil { + t.Fatalf("update root LimitRange: %v", err) + } + if _, err := r.Reconcile(context.Background(), sweepKey); err != nil { + t.Fatalf("reconcile: %v", err) + } + lr, ok := getLimitRange(c, "tenant-foo-bar", allocatedLimitRangeName) + if !ok { + t.Fatalf("tenant-foo-bar lost its LimitRange") + } + if got := lr.Spec.Limits[0].Default[corev1.ResourceCPU]; got.String() != "500m" { + t.Fatalf("tenant-foo-bar default cpu = %q, want 500m after the root changed", got.String()) + } +} + +// TestReconcile_PoolLimitRangeGarbageCollected: once the child declares its own +// quota, the chart renders its LimitRange and the controller-owned copy goes. +func TestReconcile_PoolLimitRangeGarbageCollected(t *testing.T) { + stale := &corev1.LimitRange{ + ObjectMeta: metav1.ObjectMeta{ + Name: allocatedLimitRangeName, + Namespace: "tenant-foo-bar", + Labels: map[string]string{managedByLabel: managedByValue}, + }, + } + r, c := newReconciler(t, + tenantHR("foo", "tenant-root"), + tenantHR("bar", "tenant-foo"), + ns("tenant-foo"), ns("tenant-foo-bar"), + chartQuota("tenant-foo", map[string]string{"limits.cpu": "10"}, nil), + chartLimitRange("tenant-foo", "250m"), + chartQuota("tenant-foo-bar", map[string]string{"limits.cpu": "4"}, nil), + chartLimitRange("tenant-foo-bar", "250m"), + stale, + ) + if _, err := r.Reconcile(context.Background(), sweepKey); err != nil { + t.Fatalf("reconcile: %v", err) + } + if _, ok := getLimitRange(c, "tenant-foo-bar", allocatedLimitRangeName); ok { + t.Fatalf("bounded child tenant-foo-bar renders its own LimitRange; the controller copy must be removed") + } + if _, ok := getLimitRange(c, "tenant-foo-bar", chartLimitRangeName); !ok { + t.Fatalf("the chart-owned LimitRange must never be touched") + } +} + +// TestReconcile_PoolRootWithoutLimitRange: if the root has no chart LimitRange +// there is nothing to copy; the quota is still enforced and the sweep succeeds. +func TestReconcile_PoolRootWithoutLimitRange(t *testing.T) { + r, c := newReconciler(t, + tenantHR("foo", "tenant-root"), + tenantHR("bar", "tenant-foo"), + ns("tenant-foo"), ns("tenant-foo-bar"), + chartQuota("tenant-foo", map[string]string{"limits.cpu": "10"}, nil), + ) + if _, err := r.Reconcile(context.Background(), sweepKey); err != nil { + t.Fatalf("reconcile: %v", err) + } + if _, ok := allocatedHard(t, c, "tenant-foo-bar", "limits.cpu"); !ok { + t.Fatalf("tenant-foo-bar must still get its allocated quota") + } + if _, ok := getLimitRange(c, "tenant-foo-bar", allocatedLimitRangeName); ok { + t.Fatalf("no LimitRange can be copied from a root that has none") + } +} + +// TestReconcile_NoLimitRangeWithoutComputeLimitQuota: the chart renders its +// LimitRange for any non-empty resourceQuotas, compute or not. A member whose +// allocated quota bounds neither limits.cpu nor limits.memory is admitted +// without limits today; copying the root's defaults there would cap or refuse +// pods (one requesting more than the default memory limit, for instance) +// that the quota itself never constrains. +func TestReconcile_NoLimitRangeWithoutComputeLimitQuota(t *testing.T) { + stale := &corev1.LimitRange{ + ObjectMeta: metav1.ObjectMeta{ + Name: allocatedLimitRangeName, + Namespace: "tenant-foo-bar", + Labels: map[string]string{managedByLabel: managedByValue}, + }, + } + r, c := newReconciler(t, + tenantHR("foo", "tenant-root"), + tenantHR("bar", "tenant-foo"), + ns("tenant-foo"), ns("tenant-foo-bar"), + chartQuota("tenant-foo", map[string]string{"services.loadbalancers": "1"}, nil), + chartLimitRange("tenant-foo", "250m"), + stale, + ) + if _, err := r.Reconcile(context.Background(), sweepKey); err != nil { + t.Fatalf("reconcile: %v", err) + } + if _, ok := allocatedHard(t, c, "tenant-foo-bar", "services.loadbalancers"); !ok { + t.Fatalf("tenant-foo-bar must still get its allocated quota") + } + if _, ok := getLimitRange(c, "tenant-foo-bar", allocatedLimitRangeName); ok { + t.Fatalf("tenant-foo-bar's quota bounds no compute limit; it must carry no LimitRange copy") + } +} diff --git a/internal/operator/package_reconciler_test.go b/internal/operator/package_reconciler_test.go index 74d2a8466..480dc07dc 100644 --- a/internal/operator/package_reconciler_test.go +++ b/internal/operator/package_reconciler_test.go @@ -20,6 +20,7 @@ import ( "encoding/json" "os" "path/filepath" + "reflect" "testing" "time" @@ -269,3 +270,49 @@ func TestPackageSourceCRDHasUpgradeCRDsEnum(t *testing.T) { } } } + +// TestCertManagerIssuersReleaseIgnoresACMEReadiness builds the HelmRelease spec +// from the shipped cert-manager source. A ClusterIssuer turns Ready only after +// cert-manager has registered an account with the CA, and every package behind +// cozystack.cert-manager dependsOn this release, so a kstatus wait on the +// issuers would let one unreachable CA hold the whole platform rollout. +func TestCertManagerIssuersReleaseIgnoresACMEReadiness(t *testing.T) { + want := []kustomize.CustomHealthCheck{{ + APIVersion: "cert-manager.io/v1", + Kind: "ClusterIssuer", + HealthCheckExpressions: kustomize.HealthCheckExpressions{ + Current: "true", + }, + }} + + path := filepath.Join("..", "..", "packages", "core", "platform", "sources", "cert-manager.yaml") + data, err := os.ReadFile(path) + if err != nil { + t.Fatalf("read %s: %v", path, err) + } + var ps cozyv1alpha1.PackageSource + if err := yaml.Unmarshal(data, &ps); err != nil { + t.Fatalf("unmarshal %s: %v", path, err) + } + + var install *cozyv1alpha1.ComponentInstall + for _, v := range ps.Spec.Variants { + for _, c := range v.Components { + if c.Name == "cert-manager-issuers" { + install = c.Install + } + } + } + if install == nil { + t.Fatalf("%s: component cert-manager-issuers has no install block", path) + } + + spec := (&PackageReconciler{}).buildHelmReleaseSpec(install, "x") + + if !reflect.DeepEqual(spec.HealthCheckExprs, want) { + t.Errorf("HealthCheckExprs = %+v, want %+v", spec.HealthCheckExprs, want) + } + if spec.WaitStrategy == nil || spec.WaitStrategy.Name != helmv2.WaitStrategyPoller { + t.Errorf("WaitStrategy = %+v, want poller: the expressions are not evaluated under any other strategy", spec.WaitStrategy) + } +} diff --git a/packages/apps/bucket/templates/hooks/cleanup-acme.yaml b/packages/apps/bucket/templates/hooks/cleanup-acme.yaml index dcb6f7e97..94814a2c1 100644 --- a/packages/apps/bucket/templates/hooks/cleanup-acme.yaml +++ b/packages/apps/bucket/templates/hooks/cleanup-acme.yaml @@ -59,11 +59,20 @@ spec: # one reliable per-release identifier for ACME solver objects (they # carry no app/release label of their own). HOST="{{ .Release.Name }}.{{ .Values._namespace.host }}" + # None of the calls below carries --request-timeout. A non-zero + # value makes kubectl skip its in-cluster credentials: client-go + # consults them only while the assembled config still equals the + # default, and the flag lands in that config. Every call then goes + # to localhost:8080 and is refused, which here is worse than + # failing -- each one is guarded by `|| echo WARNING`, so the hook + # exits 0, prints "ACME cleanup complete.", and hook-succeeded + # deletes the Job carrying those warnings (#4288). The whole + # cleanup stays bounded by activeDeadlineSeconds above. # Delete the per-bucket Certificate/Order/Challenge. cert-manager # then cascade-removes the cm-acme-http-solver-* solver objects it # owns. The release's TLS Certificate is named after the secret it # populates ({{ .Release.Name }}-ui-tls). - kubectl delete certificate {{ .Release.Name }}-ui-tls -n {{ .Release.Namespace }} --ignore-not-found --wait=false --request-timeout=30s \ + kubectl delete certificate {{ .Release.Name }}-ui-tls -n {{ .Release.Namespace }} --ignore-not-found --wait=false \ || echo "WARNING: cert-manager cleanup failed for {{ .Release.Name }}; orphaned ACME resources may remain" >&2 # Orders are owned by the Certificate and are removed by the cascade # above; Challenges carry no labels and are reaped by the @@ -81,10 +90,10 @@ spec: # # Delete Challenges for our host (cascades the solver # Ingress/Service/Pod they own). - challenges="$(kubectl get challenge -n {{ .Release.Namespace }} --request-timeout=30s -o jsonpath="{range .items[?(@.spec.dnsName=='$HOST')]}{.metadata.name} {end}")" \ + challenges="$(kubectl get challenge -n {{ .Release.Namespace }} -o jsonpath="{range .items[?(@.spec.dnsName=='$HOST')]}{.metadata.name} {end}")" \ || { echo "WARNING: failed to list challenges for {{ .Release.Name }}; orphaned ACME resources may remain" >&2; challenges=""; } for ch in $challenges; do - kubectl delete challenge -n {{ .Release.Namespace }} "$ch" --ignore-not-found --wait=false --request-timeout=30s \ + kubectl delete challenge -n {{ .Release.Namespace }} "$ch" --ignore-not-found --wait=false \ || echo "WARNING: failed to delete challenge $ch for {{ .Release.Name }}; orphaned ACME resources may remain" >&2 done # Delete any orphaned solver Ingress for our host (no live owner @@ -92,10 +101,10 @@ spec: # Challenge and are cascade-deleted with it; truly owner-less # solver Service/Pod with no matching Challenge are not expected # and are not swept namespace-wide. - ingresses="$(kubectl get ingress -n {{ .Release.Namespace }} -l acme.cert-manager.io/http01-solver=true --request-timeout=30s -o jsonpath="{range .items[?(@.spec.rules[0].host=='$HOST')]}{.metadata.name} {end}")" \ + ingresses="$(kubectl get ingress -n {{ .Release.Namespace }} -l acme.cert-manager.io/http01-solver=true -o jsonpath="{range .items[?(@.spec.rules[0].host=='$HOST')]}{.metadata.name} {end}")" \ || { echo "WARNING: failed to list solver ingresses for {{ .Release.Name }}; orphaned ACME resources may remain" >&2; ingresses=""; } for ing in $ingresses; do - kubectl delete ingress -n {{ .Release.Namespace }} "$ing" --ignore-not-found --wait=false --request-timeout=30s \ + kubectl delete ingress -n {{ .Release.Namespace }} "$ing" --ignore-not-found --wait=false \ || echo "WARNING: failed to delete solver ingress $ing for {{ .Release.Name }}; orphaned ACME resources may remain" >&2 done echo "ACME cleanup complete." diff --git a/packages/apps/bucket/tests/cleanup_acme_test.yaml b/packages/apps/bucket/tests/cleanup_acme_test.yaml index a90695520..0de27fae7 100644 --- a/packages/apps/bucket/tests/cleanup_acme_test.yaml +++ b/packages/apps/bucket/tests/cleanup_acme_test.yaml @@ -84,14 +84,14 @@ tests: # Host-scoped challenge sweep filtering on .spec.dnsName == our host - matchRegex: path: spec.template.spec.containers[0].command[2] - pattern: "kubectl get challenge -n tenant-root --request-timeout=30s -o jsonpath=.*@.spec.dnsName=='\\$HOST'" + pattern: "kubectl get challenge -n tenant-root -o jsonpath=.*@.spec.dnsName=='\\$HOST'" - matchRegex: path: spec.template.spec.containers[0].command[2] pattern: 'kubectl delete challenge -n tenant-root "\$ch" --ignore-not-found' # Host-scoped orphaned solver Ingress sweep filtering on rules[0].host - matchRegex: path: spec.template.spec.containers[0].command[2] - pattern: "kubectl get ingress -n tenant-root -l acme.cert-manager.io/http01-solver=true --request-timeout=30s -o jsonpath=.*@.spec.rules\\[0\\].host=='\\$HOST'" + pattern: "kubectl get ingress -n tenant-root -l acme.cert-manager.io/http01-solver=true -o jsonpath=.*@.spec.rules\\[0\\].host=='\\$HOST'" - matchRegex: path: spec.template.spec.containers[0].command[2] pattern: 'kubectl delete ingress -n tenant-root "\$ing" --ignore-not-found' diff --git a/packages/apps/harbor/templates/bucket.yaml b/packages/apps/harbor/templates/bucket.yaml index a9e60988d..5394ad229 100644 --- a/packages/apps/harbor/templates/bucket.yaml +++ b/packages/apps/harbor/templates/bucket.yaml @@ -3,6 +3,9 @@ apiVersion: objectstorage.k8s.io/v1alpha1 kind: BucketClaim metadata: name: {{ .Release.Name }}-registry + labels: + release: {{ .Release.Name }}-system + component: registry spec: bucketClassName: {{ $seaweedfs }} protocols: diff --git a/packages/apps/harbor/templates/harbor.yaml b/packages/apps/harbor/templates/harbor.yaml index 3bb00f0ce..5601b1411 100644 --- a/packages/apps/harbor/templates/harbor.yaml +++ b/packages/apps/harbor/templates/harbor.yaml @@ -191,8 +191,10 @@ spec: {{- end }} {{- end }} {{- end }} + nginx: + resources: {{- include "cozy-lib.resources.defaultingSanitize" (list "t1.small" (dict) $) | nindent 10 }} portal: - resources: {{- include "cozy-lib.resources.defaultingSanitize" (list "t1.nano" (dict) $) | nindent 10 }} + resources: {{- include "cozy-lib.resources.defaultingSanitize" (list "t1.micro" (dict) $) | nindent 10 }} core: {{- if and $tokenKey $tokenCert }} tokenKey: {{ $tokenKey | quote }} diff --git a/packages/apps/harbor/tests/nginx_resources_test.yaml b/packages/apps/harbor/tests/nginx_resources_test.yaml new file mode 100644 index 000000000..654615837 --- /dev/null +++ b/packages/apps/harbor/tests/nginx_resources_test.yaml @@ -0,0 +1,76 @@ +suite: nginx proxy and portal resources + +release: + name: harbor + namespace: tenant-test + +set: + _namespace: + host: example.org + ingress: nginx + gateway: "" + seaweedfs: seaweedfs + _cluster: + solver: http01 + +tests: + - it: sizes the nginx proxy with t1.small instead of leaving it to the namespace LimitRange + template: templates/harbor.yaml + documentSelector: + path: kind + value: HelmRelease + asserts: + - equal: + path: spec.values.harbor.nginx.resources.limits.memory + value: 512Mi + - equal: + path: spec.values.harbor.nginx.resources.limits.cpu + value: "1" + - exists: + path: spec.values.harbor.nginx.resources.requests.memory + + - it: sizes the portal with t1.micro + template: templates/harbor.yaml + documentSelector: + path: kind + value: HelmRelease + asserts: + - equal: + path: spec.values.harbor.portal.resources.limits.memory + value: 256Mi + - equal: + path: spec.values.harbor.portal.resources.limits.cpu + value: 500m + - exists: + path: spec.values.harbor.portal.resources.requests.memory + + - it: keeps both sizes when the other components are resized + template: templates/harbor.yaml + documentSelector: + path: kind + value: HelmRelease + set: + core: + resourcesPreset: t1.nano + registry: + resources: + cpu: "2" + memory: 1Gi + jobservice: + resourcesPreset: t1.medium + asserts: + - equal: + path: spec.values.harbor.core.resources.limits.memory + value: 128Mi + - equal: + path: spec.values.harbor.registry.registry.resources.limits.memory + value: 1Gi + - equal: + path: spec.values.harbor.jobservice.resources.limits.memory + value: 1Gi + - equal: + path: spec.values.harbor.nginx.resources.limits.memory + value: 512Mi + - equal: + path: spec.values.harbor.portal.resources.limits.memory + value: 256Mi diff --git a/packages/apps/harbor/tests/registry_bucket_monitor_test.yaml b/packages/apps/harbor/tests/registry_bucket_monitor_test.yaml new file mode 100644 index 000000000..6327a8bc9 --- /dev/null +++ b/packages/apps/harbor/tests/registry_bucket_monitor_test.yaml @@ -0,0 +1,46 @@ +suite: registry BucketClaim is selected by the registry WorkloadMonitor + +release: + name: harbor + namespace: tenant-test + +# The WorkloadMonitor controller lists BucketClaims by the monitor's selector, +# so a BucketClaim without matching labels gets no Workload and its storage +# never reaches billing. The registry keeps its images in this bucket, so it is +# reported under the registry monitor, as the registry PVC was before storage +# moved to S3. Both sides are asserted so that renaming either one fails here. +set: + _namespace: + host: example.org + ingress: nginx + gateway: "" + seaweedfs: seaweedfs + _cluster: + solver: http01 + +tests: + - it: labels the registry BucketClaim with the registry monitor's selector + template: templates/bucket.yaml + documentSelector: + path: kind + value: BucketClaim + asserts: + - equal: + path: metadata.labels + value: + release: harbor-system + component: registry + + - it: selects the registry BucketClaim from the registry monitor + template: templates/harbor.yaml + documentSelector: + path: metadata.name + value: harbor-registry + asserts: + - isKind: + of: WorkloadMonitor + - equal: + path: spec.selector + value: + release: harbor-system + component: registry diff --git a/packages/apps/kubernetes/README.md b/packages/apps/kubernetes/README.md index ab6eb958f..6affbe7f3 100644 --- a/packages/apps/kubernetes/README.md +++ b/packages/apps/kubernetes/README.md @@ -87,7 +87,7 @@ See the reference for components utilized in this service: - **`ephemeralStorage` renamed to `diskSize`** (v1.4): The `nodeGroups[name].ephemeralStorage` field has been renamed to `nodeGroups[name].diskSize`. Existing clusters are migrated transparently by platform migration 41 during the pre-upgrade hook — no manual action is required. Newly written values should use `diskSize`. Existing VMs are rolling-updated via CAPI when the new values are applied. With the Talos worker rollover in this release the field now sizes the **single system disk** (Talos OS image streamed from `factory.talos.dev`, kubelet state, containerd image cache, local-path PVCs) — the pre-Talos `disk-kubelet` PVC layout was removed. State on that single disk persists across same-VM reboots (virt-launcher restart, guest reboot, node failure); VM replacement by CAPI (e.g. nodeGroup field change, MachineHealthCheck remediation) provisions a fresh disk. -- **Air-gapped tenant workers (Phase 1 Talos rollover)**: tenant worker bootstrap moves from Ubuntu containerDisk + kubeadm to a Talos OS disk image fetched over HTTP by CDI and a `.../installer/...` installer reference. Both sources are now overridable — set `talos.imageFactoryURL` (default `https://factory.talos.dev`) to a self-hosted Image Factory, a caching mirror, or an internal HTTP file server, and `talos.installerRepository` (default `factory.talos.dev/installer`) to a mirrored registry. The Helm-rendered `*-patch-containerd` Secret that previously plumbed the platform-wide `registries.mirrors` config to tenant workers (via the kubeadm template's containerd certs.d mount) has no consumer in the Talos machineconfig and was removed in this release; **in-guest container-image pulls** (pods pulling from registries inside the tenant cluster) still honour no per-tenant `registries.mirrors` override until Phase 2 restores it via `machine.registries.mirrors` knobs. So a strict-egress tenant can now mirror the Talos OS image and installer, but rate-limited in-guest registry pulls remain a Phase 2 follow-up — file an issue if you depend on this and it is not yet landed. +- **Air-gapped tenant workers (Phase 1 Talos rollover)**: tenant worker bootstrap moves from Ubuntu containerDisk + kubeadm to a Talos OS disk image fetched over HTTP by CDI and a `.../installer/...` installer reference. Both sources are now overridable — set `talos.imageFactoryURL` (default `https://factory.talos.dev`) to a self-hosted Image Factory, a caching mirror, or an internal HTTP file server, and `talos.installerRepository` (default `factory.talos.dev/installer`) to a mirrored registry. The Helm-rendered `*-patch-containerd` Secret that previously plumbed the platform-wide `registries.mirrors` config to tenant workers (via the kubeadm template's containerd certs.d mount) has no consumer in the Talos machineconfig, so the Secret is removed together with the platform `registries` value that fed it. A Package that still sets `registries` keeps installing, the key is ignored. Registry mirrors for tenant workers, **in-guest container-image pulls** (pods pulling from registries inside the tenant cluster) included, are configured per worker pool through `talos.registryMirrors` of the `KubernetesNodes` resource. - **Worker MachineHealthCheck remediation is now enabled by default** (Phase 1 Talos rollover): the worker MHC `maxUnhealthy` moved from a hard-coded `0` (remediation effectively **off**) to a configurable `nodeHealthCheck.maxUnhealthy` defaulting to `"50%"`. CAPI now auto-remediates (deletes and replaces) unhealthy worker Machines while at least 50% of a group stays healthy. `"50%"` deliberately leaves headroom for transient unhealthy nodes during the kubeadm→Talos rollover and slow first boots from `factory.talos.dev`; set `nodeHealthCheck.maxUnhealthy: "0%"` to keep the previous remediation-off behaviour until your fleet is stable on Talos workers. diff --git a/packages/apps/kubernetes/templates/helmreleases/coredns.yaml b/packages/apps/kubernetes/templates/helmreleases/coredns.yaml index 0ade90341..03ae8ee91 100644 --- a/packages/apps/kubernetes/templates/helmreleases/coredns.yaml +++ b/packages/apps/kubernetes/templates/helmreleases/coredns.yaml @@ -35,7 +35,4 @@ spec: retries: -1 values: {{- toYaml (deepCopy .Values.addons.coredns.valuesOverride | mergeOverwrite (fromYaml (include "cozystack.defaultCoreDNSValues" .))) | nindent 4 }} - dependsOn: - - name: {{ .Release.Name }}-cilium - namespace: {{ .Release.Namespace }} {{- end }} diff --git a/packages/apps/kubernetes/templates/helmreleases/monitoring-agents.yaml b/packages/apps/kubernetes/templates/helmreleases/monitoring-agents.yaml index 2ec0bc3ca..7e5c45e64 100644 --- a/packages/apps/kubernetes/templates/helmreleases/monitoring-agents.yaml +++ b/packages/apps/kubernetes/templates/helmreleases/monitoring-agents.yaml @@ -45,7 +45,8 @@ spec: cluster: {{ .Release.Name }} tenant: {{ .Release.Namespace }} remoteWrite: - url: http://vminsert-shortterm.{{ $targetTenant }}.svc.{{ $clusterDomain }}:8480/insert/0/prometheus + urls: + - http://vminsert-shortterm.{{ $targetTenant }}.svc.{{ $clusterDomain }}:8480/insert/0/prometheus fluent-bit: readinessProbe: httpGet: diff --git a/packages/apps/kubernetes/templates/oidc-rbac-bindings.yaml b/packages/apps/kubernetes/templates/oidc-rbac-bindings.yaml new file mode 100644 index 000000000..a8517da4f --- /dev/null +++ b/packages/apps/kubernetes/templates/oidc-rbac-bindings.yaml @@ -0,0 +1,42 @@ +{{- /* + The ClusterRoleBindings the OIDC bootstrap Job (oidc-rbac-job.yaml) applies + inside the tenant cluster, one per `oidc.users` entry, and the list of their + names it prunes against. They travel in a ConfigMap the Job mounts and not as + text inside its script: the script reaches the container as a single `sh -c` + argument, Linux caps one argument at 128 KiB, and a binding per user crosses + that cap at about 240 users, after which the container cannot start. + + A release-owned object, not a hook resource, so it exists before the + post-install and post-upgrade hooks run. It is rendered only where users are + bound; at `mode: None` the Job takes its early branch and the volume is + optional. +*/}} +{{- if ne .Values.oidc.mode "None" }} +{{- $desired := "" }} +{{- $bindings := "" }} +{{- range .Values.oidc.users }} +{{- $name := printf "cozystack-oidc-%s" (printf "%s-%s" $.Release.Name .email | sha256sum | trunc 16) }} +{{- $role := "view" }} +{{- if eq .role "admin" }} +{{- $role = "cluster-admin" }} +{{- end }} +{{- $desired = printf "%s%s\n" $desired $name }} +{{- $binding := dict + "apiVersion" "rbac.authorization.k8s.io/v1" + "kind" "ClusterRoleBinding" + "metadata" (dict "name" $name "labels" (dict "app.kubernetes.io/managed-by" "cozystack-oidc" "app.kubernetes.io/instance" $.Release.Name)) + "roleRef" (dict "apiGroup" "rbac.authorization.k8s.io" "kind" "ClusterRole" "name" $role) + "subjects" (list (dict "kind" "User" "apiGroup" "rbac.authorization.k8s.io" "name" .email)) }} +{{- $bindings = printf "%s---\n%s\n" $bindings (toYaml $binding) }} +{{- end }} +--- +apiVersion: v1 +kind: ConfigMap +metadata: + name: {{ .Release.Name }}-oidc-bindings + namespace: {{ .Release.Namespace }} + labels: + {{- include "kubernetes.labels" . | nindent 4 }} +data: + {{- dict "crbs.yaml" $bindings "desired.txt" $desired | toYaml | nindent 2 }} +{{- end }} diff --git a/packages/apps/kubernetes/templates/oidc-rbac-job.yaml b/packages/apps/kubernetes/templates/oidc-rbac-job.yaml index 04b11164f..e46736e78 100644 --- a/packages/apps/kubernetes/templates/oidc-rbac-job.yaml +++ b/packages/apps/kubernetes/templates/oidc-rbac-job.yaml @@ -25,7 +25,9 @@ - `mode: System | CustomConfig`: - Apply one ClusterRoleBinding per `users[]` entry inside the tenant cluster (`admin` → `cluster-admin`, `view` → `view`, subject = the - literal email matched against the `email` claim). + literal email matched against the `email` claim). The bindings are + rendered by oidc-rbac-bindings.yaml into a ConfigMap this Job mounts, + not into the script below. - Prune stale CRBs labelled by this release. - `mode: System`: patch the pre-rendered `-oidc-kubeconfig` Secret with a real kubeconfig wired to `kubectl oidc-login` @@ -168,6 +170,8 @@ spec: value: {{ $issuer | quote }} - name: OIDC_SERVER_URL value: {{ printf "https://%s:443" $externalHost | quote }} + - name: OIDC_BINDINGS_DIR + value: /etc/oidc-bindings resources: requests: cpu: 10m @@ -254,46 +258,32 @@ spec: sleep 5 done + # A missing list must stop the Job here: grep on a file that is not + # there exits 2, `! grep` is then true, and the prune below would + # delete every binding of the release. + BINDINGS=$OIDC_BINDINGS_DIR + if [ ! -f "$BINDINGS/desired.txt" ]; then + echo "$BINDINGS/desired.txt is not mounted (ConfigMap $RELEASE-oidc-bindings); refusing to prune against a list that is not there" >&2 + exit 1 + fi + echo "Applying ${OIDC_MODE} ClusterRoleBindings to the tenant cluster..." - DESIRED_FILE=$(mktemp) - {{- range .Values.oidc.users }} - {{- $hash := printf "%s-%s" $.Release.Name .email | sha256sum | trunc 16 }} - {{- $crbName := printf "cozystack-oidc-%s" $hash }} - {{- $role := "view" }} - {{- if eq .role "admin" }} - {{- $role = "cluster-admin" }} - {{- end }} - echo "{{ $crbName }}" >> "$DESIRED_FILE" - cat <<'EOF' | kubectl --kubeconfig "$KUBECONFIG_TENANT" apply --filename - - apiVersion: rbac.authorization.k8s.io/v1 - kind: ClusterRoleBinding - metadata: - name: {{ $crbName }} - labels: - app.kubernetes.io/managed-by: cozystack-oidc - app.kubernetes.io/instance: {{ $.Release.Name }} - roleRef: - apiGroup: rbac.authorization.k8s.io - kind: ClusterRole - name: {{ $role }} - subjects: - - kind: User - apiGroup: rbac.authorization.k8s.io - name: {{ .email | quote }} - EOF - {{- end }} + # kubectl apply fails on a file with no objects, and a release with + # no users has none. + if [ -s "$BINDINGS/crbs.yaml" ]; then + kubectl --kubeconfig "$KUBECONFIG_TENANT" apply --filename "$BINDINGS/crbs.yaml" + fi echo "Pruning stale ClusterRoleBindings labelled by this release..." EXISTING=$(kubectl --kubeconfig "$KUBECONFIG_TENANT" get clusterrolebindings \ --selector=app.kubernetes.io/managed-by=cozystack-oidc,app.kubernetes.io/instance=$RELEASE \ --output=jsonpath='{.items[*].metadata.name}') for crb in $EXISTING; do - if ! grep -x -q -F "$crb" "$DESIRED_FILE"; then + if ! grep -x -q -F "$crb" "$BINDINGS/desired.txt"; then echo " removing $crb" kubectl --kubeconfig "$KUBECONFIG_TENANT" delete clusterrolebinding "$crb" --ignore-not-found fi done - rm -f "$DESIRED_FILE" if [ "$OIDC_MODE" = "System" ]; then echo "Patching the OIDC kubeconfig Secret on the management cluster..." @@ -349,6 +339,9 @@ spec: - name: kubeconfig mountPath: /etc/kubernetes/kubeconfig readOnly: true + - name: oidc-bindings + mountPath: /etc/oidc-bindings + readOnly: true - name: tmp mountPath: /tmp volumes: @@ -356,6 +349,10 @@ spec: secret: secretName: {{ .Release.Name }}-admin-kubeconfig optional: true + - name: oidc-bindings + configMap: + name: {{ .Release.Name }}-oidc-bindings + optional: true - name: tmp emptyDir: {} {{- /* diff --git a/packages/apps/kubernetes/tests/coredns_no_cilium_dependency_test.yaml b/packages/apps/kubernetes/tests/coredns_no_cilium_dependency_test.yaml new file mode 100644 index 000000000..ff55c4596 --- /dev/null +++ b/packages/apps/kubernetes/tests/coredns_no_cilium_dependency_test.yaml @@ -0,0 +1,30 @@ +suite: CoreDNS HelmRelease dependency tests +templates: + - templates/helmreleases/coredns.yaml +values: + - values-ci.yaml +tests: + # When Hubble Relay is enabled at cluster creation, hubble-relay resolves + # hubble-peer.cozy-cilium.svc.cluster.local before the Cilium HelmRelease can + # report Ready. CoreDNS must not declare dependsOn on Cilium, otherwise both + # HelmReleases deadlock; without a CNI CoreDNS pods stay Pending and retry + # until Cilium comes up. + - it: does not depend on the Cilium HelmRelease so cluster DNS can bootstrap alongside CNI + set: + addons: + cilium: + valuesOverride: + cilium: + hubble: + enabled: true + relay: + enabled: true + asserts: + - isNull: + path: spec.dependsOn + - equal: + path: spec.install.remediation.retries + value: -1 + - equal: + path: spec.upgrade.remediation.retries + value: -1 diff --git a/packages/apps/kubernetes/tests/monitoring_agents_test.yaml b/packages/apps/kubernetes/tests/monitoring_agents_test.yaml new file mode 100644 index 000000000..1dc21181a --- /dev/null +++ b/packages/apps/kubernetes/tests/monitoring_agents_test.yaml @@ -0,0 +1,42 @@ +suite: monitoring-agents HelmRelease values match the monitoring-agents chart + +# The values below are consumed by packages/system/monitoring-agents, which +# reads vmagent.remoteWrite.urls as a list and the tenant label from +# vmagent.externalLabels.tenant. A key the chart does not read is dropped in +# silence, and the chart then falls back to cozy-monitoring defaults that do +# not resolve inside a tenant cluster. Its counterpart is +# packages/system/monitoring-agents/tests/vmagent_remote_write_test.yaml. +templates: + - templates/helmreleases/monitoring-agents.yaml + +values: + - values/common.yaml + +release: + name: kubernetes-clusterprod + namespace: tenant-a + +set: + addons.monitoringAgents.enabled: true + _namespace.monitoring: tenant-root + _cluster: + cluster-domain: cozy.local + +tests: + - it: sends metrics to the shortterm vminsert of the monitoring tenant as a urls list + asserts: + - equal: + path: spec.values.vmagent.remoteWrite + value: + urls: + - http://vminsert-shortterm.tenant-root.svc.cozy.local:8480/insert/0/prometheus + + - it: labels series with the tenant that owns the cluster, not the monitoring tenant + asserts: + - equal: + path: spec.values.vmagent.externalLabels + value: + cluster: kubernetes-clusterprod + tenant: tenant-a + - notExists: + path: spec.values.global diff --git a/packages/apps/kubernetes/tests/oidc_test.yaml b/packages/apps/kubernetes/tests/oidc_test.yaml index 182ad4f93..8f10e3c23 100644 --- a/packages/apps/kubernetes/tests/oidc_test.yaml +++ b/packages/apps/kubernetes/tests/oidc_test.yaml @@ -465,7 +465,73 @@ tests: value: "true" documentIndex: 3 - - it: bootstrap Job command builds a CRB for each users[] entry + - it: the bindings ConfigMap holds a CRB for each users[] entry + release: + name: kubernetes-app + namespace: tenant-foo + template: templates/oidc-rbac-bindings.yaml + set: + _cluster.oidc-enabled: "true" + _cluster.root-host: example.org + oidc.mode: System + oidc.users: + - email: alice@example.org + role: admin + - email: bob@example.org + role: view + asserts: + - isKind: + of: ConfigMap + - equal: + path: metadata.name + value: kubernetes-app-oidc-bindings + - matchRegex: + path: data["crbs.yaml"] + pattern: 'name: alice@example.org' + - matchRegex: + path: data["crbs.yaml"] + pattern: 'name: bob@example.org' + - matchRegex: + path: data["crbs.yaml"] + pattern: 'app.kubernetes.io/managed-by: cozystack-oidc' + - matchRegex: + path: data["crbs.yaml"] + pattern: 'app.kubernetes.io/instance: kubernetes-app' + + - it: the binding names and roles stay what the Job script used to render + # The prune step and every binding already in a tenant cluster go by these + # names: cozystack-oidc- plus the first 16 hex digits of + # sha256("-"). A different name leaves the old binding + # behind next to the new one. + release: + name: kubernetes-app + namespace: tenant-foo + template: templates/oidc-rbac-bindings.yaml + set: + _cluster.oidc-enabled: "true" + _cluster.root-host: example.org + oidc.mode: System + oidc.users: + - email: alice@example.org + role: admin + - email: bob@example.org + role: view + asserts: + - equal: + path: data["desired.txt"] + value: "cozystack-oidc-0001a28136ca1a02\ncozystack-oidc-ec8dfb1cbc75e699\n" + - matchRegex: + path: data["crbs.yaml"] + pattern: 'name: cozystack-oidc-0001a28136ca1a02\nroleRef:\n apiGroup: rbac.authorization.k8s.io\n kind: ClusterRole\n name: cluster-admin\nsubjects:\n- apiGroup: rbac.authorization.k8s.io\n kind: User\n name: alice@example.org\n' + - matchRegex: + path: data["crbs.yaml"] + pattern: 'name: cozystack-oidc-ec8dfb1cbc75e699\nroleRef:\n apiGroup: rbac.authorization.k8s.io\n kind: ClusterRole\n name: view\nsubjects:\n- apiGroup: rbac.authorization.k8s.io\n kind: User\n name: bob@example.org\n' + + - it: the bootstrap Job mounts the bindings ConfigMap and carries no users[] entry in its script + # The script is one `sh -c` argument and Linux caps one argument at 128 KiB: + # a binding per user in it stops the container from starting at about 240 + # users. hack/kubernetes-oidc-bindings.bats renders 300 users to hold the + # size itself. release: name: kubernetes-app namespace: tenant-foo @@ -479,23 +545,130 @@ tests: role: admin - email: bob@example.org role: view + asserts: + - contains: + path: spec.template.spec.volumes + content: + name: oidc-bindings + configMap: + name: kubernetes-app-oidc-bindings + optional: true + documentIndex: 3 + - contains: + path: spec.template.spec.containers[0].volumeMounts + content: + name: oidc-bindings + mountPath: /etc/oidc-bindings + readOnly: true + documentIndex: 3 + # The script reads the directory from the environment, which is also how + # hack/kubernetes-oidc-bindings.bats points it at a scratch directory. + - contains: + path: spec.template.spec.containers[0].env + content: + name: OIDC_BINDINGS_DIR + value: /etc/oidc-bindings + documentIndex: 3 + - notMatchRegex: + path: spec.template.spec.containers[0].command[2] + pattern: 'alice@example\.org' + documentIndex: 3 + - notMatchRegex: + path: spec.template.spec.containers[0].command[2] + pattern: 'bob@example\.org' + documentIndex: 3 + + - it: the bootstrap Job stops before pruning when the desired list is not mounted + # `! grep -F` on a file that is not there is true, so a missing mount would + # delete every binding of the release. + release: + name: kubernetes-app + namespace: tenant-foo + template: templates/oidc-rbac-job.yaml + set: + _cluster.oidc-enabled: "true" + _cluster.root-host: example.org + oidc.mode: System asserts: - matchRegex: path: spec.template.spec.containers[0].command[2] - pattern: 'name: "alice@example.org"' + pattern: '(?s)if \[ ! -f "\$BINDINGS/desired\.txt" \]; then.*?exit 1\n\s*fi.*Pruning stale ClusterRoleBindings' documentIndex: 3 + + - it: the bootstrap Job applies the bindings file only when it has objects in it + # kubectl apply exits non-zero on a file with no objects, and a release + # with no users has none. + release: + name: kubernetes-app + namespace: tenant-foo + template: templates/oidc-rbac-job.yaml + set: + _cluster.oidc-enabled: "true" + _cluster.root-host: example.org + oidc.mode: System + asserts: - matchRegex: path: spec.template.spec.containers[0].command[2] - pattern: 'name: "bob@example.org"' + pattern: 'if \[ -s "\$BINDINGS/crbs\.yaml" \]; then\n\s+kubectl --kubeconfig "\$KUBECONFIG_TENANT" apply --filename "\$BINDINGS/crbs\.yaml"\n\s*fi' documentIndex: 3 + + - it: a release with no users renders an empty bindings ConfigMap + release: + name: kubernetes-app + namespace: tenant-foo + template: templates/oidc-rbac-bindings.yaml + set: + _cluster.oidc-enabled: "true" + _cluster.root-host: example.org + oidc.mode: System + oidc.users: [] + asserts: + - equal: + path: data["crbs.yaml"] + value: "" + - equal: + path: data["desired.txt"] + value: "" + + - it: CustomConfig mode renders the bindings ConfigMap for its users + release: + name: kubernetes-app + namespace: tenant-foo + template: templates/oidc-rbac-bindings.yaml + set: + _cluster.oidc-enabled: "false" + oidc.mode: CustomConfig + oidc.customConfig.config: | + apiVersion: apiserver.config.k8s.io/v1beta1 + kind: AuthenticationConfiguration + jwt: + - issuer: + url: https://idp.example.com + audiences: [my-cluster] + oidc.users: + - email: alice@example.org + role: admin + asserts: + - isKind: + of: ConfigMap - matchRegex: - path: spec.template.spec.containers[0].command[2] - pattern: 'name: cluster-admin' - documentIndex: 3 - - matchRegex: - path: spec.template.spec.containers[0].command[2] - pattern: 'name: view' - documentIndex: 3 + path: data["crbs.yaml"] + pattern: 'name: alice@example.org' + + - it: mode=None renders no bindings ConfigMap even when users are set + # The Job takes its early branch at mode None and never reads the file. + release: + name: kubernetes-app + namespace: tenant-foo + template: templates/oidc-rbac-bindings.yaml + set: + oidc.mode: None + oidc.users: + - email: alice@example.org + role: admin + asserts: + - hasDocuments: + count: 0 ############################################### # mode: CustomConfig # diff --git a/packages/apps/opensearch/templates/jvm-options.yaml b/packages/apps/opensearch/templates/jvm-options.yaml new file mode 100644 index 000000000..7228c53b2 --- /dev/null +++ b/packages/apps/opensearch/templates/jvm-options.yaml @@ -0,0 +1,11 @@ +apiVersion: v1 +kind: ConfigMap +metadata: + name: {{ .Release.Name }}-jvm-options +data: + # -XX:-UseBASE64Intrinsics turns off the AVX-512 Base64 decoder hit by + # CVE-2026-114938: OpenSearch decodes the Basic credentials of a request + # before it authenticates it, and the image may bundle an OpenJDK that + # predates the fix. + cozystack.options: | + -XX:-UseBASE64Intrinsics diff --git a/packages/apps/opensearch/templates/opensearch.yaml b/packages/apps/opensearch/templates/opensearch.yaml index adcdb63ad..96632ec6d 100644 --- a/packages/apps/opensearch/templates/opensearch.yaml +++ b/packages/apps/opensearch/templates/opensearch.yaml @@ -13,6 +13,18 @@ spec: serviceName: {{ .Release.Name }} version: {{ include "opensearch.versionMap" $ }} httpPort: 9200 + {{- /* + JVM options go in as a jvm.options.d file because neither other route works: + bin/opensearch-env unsets JAVA_TOOL_OPTIONS, and setting nodePools[].jvm makes + the operator stop sizing the heap from the memory request. + */}} + additionalVolumes: + - name: jvm-options + path: /usr/share/opensearch/config/jvm.options.d/cozystack.options + subPath: cozystack.options + restartPods: true + configMap: + name: {{ .Release.Name }}-jvm-options setVMMaxMapCount: true drainDataNodes: true {{- if gt (len .Values.images.opensearch) 0 }} diff --git a/packages/apps/opensearch/tests/jvm_options_test.yaml b/packages/apps/opensearch/tests/jvm_options_test.yaml new file mode 100644 index 000000000..8195ee1d8 --- /dev/null +++ b/packages/apps/opensearch/tests/jvm_options_test.yaml @@ -0,0 +1,42 @@ +suite: opensearch JVM options + +release: + name: test-os + namespace: tenant-test + +set: + _cluster: + cluster-domain: cozy.local + +tests: + - it: ships the Base64 intrinsics switch as a jvm.options.d file + template: templates/jvm-options.yaml + asserts: + - isKind: + of: ConfigMap + - equal: + path: metadata.name + value: test-os-jvm-options + - equal: + path: data["cozystack.options"] + value: | + -XX:-UseBASE64Intrinsics + + - it: mounts that file into every pod of the cluster + template: templates/opensearch.yaml + documentSelector: + path: kind + value: OpenSearchCluster + asserts: + - contains: + path: spec.general.additionalVolumes + content: + name: jvm-options + path: /usr/share/opensearch/config/jvm.options.d/cozystack.options + subPath: cozystack.options + restartPods: true + configMap: + name: test-os-jvm-options + # setting jvm would stop the operator sizing the heap from the memory request + - notExists: + path: spec.nodePools[0].jvm diff --git a/packages/apps/postgres/README.md b/packages/apps/postgres/README.md index 9386e2e60..649e2e177 100644 --- a/packages/apps/postgres/README.md +++ b/packages/apps/postgres/README.md @@ -20,7 +20,7 @@ together rather than picking one: | ---------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | | **Archive plumbing** (chart, legacy) | Renders `spec.plugins` (referencing a barman-cloud `ObjectStore`) on the cnpg.io Cluster from helm-install onwards. CNPG runs the barman-cloud plugin as a WAL-archiver sidecar, every WAL switch ships to object storage, and any backup driver gets a complete WAL chain to start replay from. Renders only when `backup.enabled=true`, `useSystemBucket=false`, `destinationPath` is non-empty, AND inline-or-external creds are supplied. **Skipped in the platform `useSystemBucket=true` mode** — the CNPG backup driver SSA-applies the `ObjectStore` and patches `spec.plugins` onto the live Cluster at first BackupJob time; until that first BackupJob fires, plugin WAL archiving is not active and WAL accumulates on the PVC. Fire an ad-hoc BackupJob immediately after enabling the flag on existing releases. | Legacy: `backup.enabled=true` plus `backup.destinationPath`, `backup.endpointURL`, and either `backup.s3AccessKey`+`backup.s3SecretKey` or `backup.s3CredentialsSecret`. Platform: `backup.enabled=true` plus `backup.useSystemBucket=true` — no S3 fields. | | **Backup orchestration** (recommended) | Drives ad-hoc and scheduled backups, retention, and restores from `backups.cozystack.io` resources that can span multiple Postgres apps in a tenant. The driver SSA-applies its own barman-cloud `ObjectStore` and patches `spec.plugins` with `ForceOwnership` (so compression / target settings flow from the strategy template, while the live Cluster's `serverName` — its WAL-archive S3 prefix — is always preserved); chart-managed values cover the same destination so there is no tug-of-war on the live Cluster. | `strategy.backups.cozystack.io/CNPG` + `BackupClass` + `Plan` (recurring) or `BackupJob` (ad-hoc), restores via `RestoreJob` | -| Legacy chart-emitted scheduled backup | The chart can also emit a `cnpg.io/ScheduledBackup` directly. Superseded by the BackupClass + Plan path, kept around for clusters that did not migrate. **Off by default** - rendered only when both `backup.enabled` and `backup.schedule` are non-empty. With `backup.schedule=""` plugin WAL archiving still runs; only the chart-emitted scheduled backup is silent. | `backup.enabled=true` plus `backup.schedule` (CNPG 6-field cron, e.g. `"0 2 * * * *"`) | +| Legacy chart-emitted scheduled backup | The chart can also emit a `cnpg.io/ScheduledBackup` directly. Superseded by the BackupClass + Plan path, kept around for clusters that did not migrate. **Off by default** - rendered only when both `backup.enabled` and `backup.schedule` are non-empty. With `backup.schedule=""` plugin WAL archiving still runs; only the chart-emitted scheduled backup is silent. | `backup.enabled=true` plus `backup.schedule` (five-field cron such as `"0 2 * * *"`, or six fields with leading seconds) | The **canonical setup** depends on whether the cluster ships the platform `cozy-default` BackupClass. @@ -87,16 +87,13 @@ field. ### How to enable chart-managed scheduled backups (legacy) -The chart can also emit a `cnpg.io/ScheduledBackup` directly, without a -BackupClass. Superseded by the BackupClass + Plan path above and kept -around for clusters that did not migrate. It does not run by default - -`backup.schedule` defaults to an empty string, which gates the chart's -ScheduledBackup template off. To turn it on, fill in a CNPG 6-field cron -expression: +The chart can also emit a `cnpg.io/ScheduledBackup` directly, without a BackupClass. Superseded by the BackupClass + Plan path above and kept around for clusters that did not migrate. It does not run by default - `backup.schedule` defaults to an empty string, which gates the chart's ScheduledBackup template off. To turn it on, set a standard five-field cron such as `0 2 * * *` for every day at 02:00, or the CloudNativePG six-field form with a leading seconds field such as `0 0 2 * * *` for the same time. The chart prepends a `0` seconds field to a five-field value, because CloudNativePG reads the first field as seconds and would otherwise run `0 2 * * *` every hour. + +On upgrade, an existing `backup.schedule: "0 2 * * *"` changes from hourly at minute 2 to daily at 02:00. To keep the previous hourly schedule, set `backup.schedule: "0 2 * * * *"` before upgrading. ```yaml ## @param backup.enabled Enable plugin WAL archiving + render the chart-managed ScheduledBackup -## @param backup.schedule Cron schedule (CNPG 6-field). Empty means no chart-managed ScheduledBackup +## @param backup.schedule Cron schedule, five fields or six with leading seconds. Empty means no chart-managed ScheduledBackup ## @param backup.retentionPolicy Retention policy ## @param backup.destinationPath Path to store the backup (i.e. s3://bucket/path/to/folder) ## @param backup.endpointURL S3 Endpoint used to upload data to the cloud @@ -107,7 +104,7 @@ backup: retentionPolicy: 30d destinationPath: s3://bucket/path/to/folder/ endpointURL: http://minio-gateway-service:9000 - schedule: "0 2 * * * *" # opt in - empty (the default) means no chart-managed schedule + schedule: "0 2 * * *" # opt in - empty (the default) means no chart-managed schedule s3AccessKey: oobaiRus9pah8PhohL1ThaeTa4UVa7gu s3SecretKey: ju3eum4dekeich9ahM1te8waeGai0oog ``` @@ -263,7 +260,7 @@ For `sslmode=verify-full` to work, the CA bundle retrieved above must be saved t | `backup` | Backup configuration. | `object` | `{}` | | `backup.enabled` | Enable regular backups. | `bool` | `false` | | `backup.useSystemBucket` | Opt-in: when true, the chart-emitted `-s3-creds` Secret is skipped AND `spec.plugins` (plus the barman-cloud ObjectStore) is left UNSET in the chart-rendered Cluster — the cozy-default BackupClass driver SSA-applies an ObjectStore (carrying destinationPath/endpointURL/credentials) and patches `spec.plugins` on the live Cluster when the first BackupJob runs. Consequence: plugin WAL archiving is NOT active until that first BackupJob fires; WAL accumulates on the PVC in the meantime, so fire an ad-hoc BackupJob immediately after enabling the flag on existing releases. Use together with the platform `cozy-default` BackupClass — tenants do not need to fill `s3AccessKey`/`s3SecretKey` or `destinationPath`/`endpointURL`. The destination path automatically scopes to `s3://cozy-backups///`. | `bool` | `false` | -| `backup.schedule` | Legacy. Cron schedule (CNPG 6-field format) for the chart-emitted ScheduledBackup. Empty means no chart-managed schedule, which is the recommended setup when a `BackupClass` from `backups.cozystack.io` already drives backup orchestration. In the legacy chart-managed flow `spec.plugins` plus the barman-cloud ObjectStore is rendered when `backup.enabled=true` AND `useSystemBucket=false` AND `destinationPath` is non-empty AND inline-or-external creds are supplied; in the platform `useSystemBucket=true` flow the chart skips emitting `spec.plugins` and the CNPG driver SSA-applies the ObjectStore and patches `spec.plugins` onto the live Cluster at first BackupJob time. | `string` | `""` | +| `backup.schedule` | Legacy. Cron schedule for the chart-emitted ScheduledBackup, either a standard five-field cron such as `0 2 * * *` for every day at 02:00, or six fields with leading seconds such as `0 0 2 * * *` for the same time. Empty means no chart-managed schedule, which is the recommended setup when a `BackupClass` from `backups.cozystack.io` already drives backup orchestration. In the legacy chart-managed flow `spec.plugins` plus the barman-cloud ObjectStore is rendered when `backup.enabled=true` AND `useSystemBucket=false` AND `destinationPath` is non-empty AND inline-or-external creds are supplied; in the platform `useSystemBucket=true` flow the chart skips emitting `spec.plugins` and the CNPG driver SSA-applies the ObjectStore and patches `spec.plugins` onto the live Cluster at first BackupJob time. | `string` | `""` | | `backup.retentionPolicy` | Retention policy (e.g. "30d"). | `string` | `30d` | | `backup.destinationPath` | DEPRECATED. Per-tenant S3 configuration is superseded by the platform-managed `cozy-default` BackupClass and the `cozy-backups` system bucket. Leave empty for new installations; the BackupClass driver picks up the system-managed coordinates. Kept for in-place upgrade compatibility. | `string` | `s3://bucket/path/to/folder/` | | `backup.endpointURL` | DEPRECATED. See `destinationPath`. | `string` | `http://minio-gateway-service:9000` | diff --git a/packages/apps/postgres/templates/backup.yaml b/packages/apps/postgres/templates/backup.yaml index aa1d888e3..4025ca571 100644 --- a/packages/apps/postgres/templates/backup.yaml +++ b/packages/apps/postgres/templates/backup.yaml @@ -23,15 +23,32 @@ against a Cluster with no backup configuration and fail. This mirrors the ClickHouse `useSystemBucket` gates on the chart-managed backup resources. + + CNPG parses `schedule` with robfig/cron v1 `Parse`, which takes the first + field as seconds and makes day-of-week optional. A standard five-field + cron passes its webhook with only a warning and then runs one field off, + so `5 * * * *` fires every minute instead of hourly. A five-field value + therefore gets a leading `0` seconds field. Six fields and descriptors + such as `@daily` pass through as they are, and any other field count + fails the render, which CNPG would reject at admission anyway. */}} {{- if and .Values.backup.enabled .Values.backup.schedule (not .Values.backup.useSystemBucket) }} +{{- $schedule := .Values.backup.schedule }} +{{- $fields := regexFindAll `\S+` $schedule -1 }} +{{- if not (hasPrefix "@" (trim $schedule)) }} +{{- if eq (len $fields) 5 }} +{{- $schedule = printf "0 %s" (join " " $fields) }} +{{- else if ne (len $fields) 6 }} +{{- fail (printf "postgres: backup.schedule %q is not a cron schedule with 5 or 6 fields (it has %d). Use a standard five-field cron such as \"0 2 * * *\", a six-field cron with leading seconds such as \"0 0 2 * * *\", or a descriptor such as \"@daily\"." $schedule (len $fields)) }} +{{- end }} +{{- end }} --- apiVersion: postgresql.cnpg.io/v1 kind: ScheduledBackup metadata: name: {{ .Release.Name }} spec: - schedule: {{ .Values.backup.schedule | quote }} + schedule: {{ $schedule | quote }} backupOwnerReference: self method: plugin pluginConfiguration: diff --git a/packages/apps/postgres/templates/db.yaml b/packages/apps/postgres/templates/db.yaml index 3392c0086..9cfb93def 100644 --- a/packages/apps/postgres/templates/db.yaml +++ b/packages/apps/postgres/templates/db.yaml @@ -186,6 +186,29 @@ spec: # cluster's name — which would read the wrong S3 prefix on restore. barmanObjectName: {{ .Release.Name }}-recovery serverName: {{ .Values.bootstrap.serverName | default .Values.bootstrap.oldName }} + {{- else if hasKey (.Values.users | default dict) "app" }} + {{- /* + "app" is the owner CNPG bootstraps, and users.app adopts that role. CNPG's + instance manager re-applies the owner's password from the bootstrap secret + on every reconcile whose secret version it has not seen, so on every pod + restart: left on CNPG's own -app, with its generated password, the + role silently loses the password the init-job set from -credentials. + Point the bootstrap at the chart-rendered -app-owner, which holds that + same password. It goes on the method the live Cluster was bootstrapped with, + because CNPG rejects a second one, and a restored Cluster keeps its recovery + block. Changing bootstrap on an existing Cluster is accepted, and the + remaining fields come from the live object or CNPG's defaults (app/app). + A release turning bootstrap.enabled off still drops recovery.source and + recoveryTarget: they are read only at bootstrap, and CNPG's webhook + rejects a source once its externalClusters entry, rendered only with + bootstrap.enabled, is gone. + */}} + {{- $live := lookup "postgresql.cnpg.io/v1" "Cluster" .Release.Namespace .Release.Name }} + {{- $liveBootstrap := dig "spec" "bootstrap" dict ($live | default dict) }} + bootstrap: + {{ ternary "recovery" "initdb" (hasKey $liveBootstrap "recovery") }}: + secret: + name: {{ .Release.Name }}-app-owner {{- end }} resources: {{- include "cozy-lib.resources.defaultingSanitize" (list .Values.resourcesPreset .Values.resources $) | nindent 4 }} diff --git a/packages/apps/postgres/templates/init-script.yaml b/packages/apps/postgres/templates/init-script.yaml index 1dfb4960a..89a1ea3b2 100644 --- a/packages/apps/postgres/templates/init-script.yaml +++ b/packages/apps/postgres/templates/init-script.yaml @@ -75,7 +75,7 @@ stringData: echo "== delete databases" MANAGED_DBS=$(psql -v ON_ERROR_STOP=1 -t -A -c "SELECT datname FROM pg_database d JOIN pg_shdescription s ON d.oid = s.objoid WHERE s.description = 'database managed by helm'") - DEFINED_DBS="{{ join " " (keys .Values.databases) }}" + DEFINED_DBS="{{ join " " (keys .Values.databases | sortAlpha) }}" DELETE_DBS=$(for db in $MANAGED_DBS; do case " $DEFINED_DBS " in *" $db "*) :;; *) echo $db;; esac; done) echo "databases to delete: $DELETE_DBS" @@ -230,3 +230,15 @@ stringData: {{- end }} {{- end }} {{- end }} +{{- if hasKey (.Values.users | default dict) "app" }} +--- +{{- /* The bootstrap secret db.yaml gives CNPG for its "app" owner; see there. */}} +apiVersion: v1 +kind: Secret +metadata: + name: {{ .Release.Name }}-app-owner +type: kubernetes.io/basic-auth +stringData: + username: app + password: {{ quote (index $passwords "app") }} +{{- end }} diff --git a/packages/apps/postgres/tests/app_owner_secret_test.yaml b/packages/apps/postgres/tests/app_owner_secret_test.yaml new file mode 100644 index 000000000..65a5fd571 --- /dev/null +++ b/packages/apps/postgres/tests/app_owner_secret_test.yaml @@ -0,0 +1,270 @@ +suite: users.app keeps its password across pod restarts + +# "app" is the owner CNPG bootstraps, and CNPG's instance manager re-applies the +# owner's password from the bootstrap secret on every pod restart. A declared +# users.app must therefore hand CNPG a secret holding the very password stored +# in -credentials, or the role reverts to CNPG's generated one. + +release: + name: pg-test + namespace: tenant-test + +set: + _cluster: + scheduling: {} + +tests: + - it: gives CNPG the password users.app has in the credentials Secret + templates: + - templates/init-script.yaml + kubernetesProvider: + scheme: + "v1/Secret": + gvr: + version: v1 + resource: secrets + namespaced: true + objects: + - apiVersion: v1 + kind: Secret + metadata: + name: pg-test-credentials + namespace: tenant-test + data: + app: Y29uc29sZS1wYXNzd29yZA== + set: + users: + app: {} + asserts: + - equal: + path: stringData.app + value: console-password + documentSelector: + path: metadata.name + value: pg-test-credentials + - equal: + path: stringData.password + value: console-password + documentSelector: + path: metadata.name + value: pg-test-app-owner + - equal: + path: stringData.username + value: app + documentSelector: + path: metadata.name + value: pg-test-app-owner + - equal: + path: type + value: kubernetes.io/basic-auth + documentSelector: + path: metadata.name + value: pg-test-app-owner + + # Both Secrets sharing this password is checked by + # hack/check-postgres-app-owner-password.bats, which compares them in one render. + - it: generates a 16-character password for a fresh app owner + templates: + - templates/init-script.yaml + set: + users: + app: {} + asserts: + - matchRegex: + path: stringData.password + pattern: ^[a-zA-Z0-9]{16}$ + documentSelector: + path: metadata.name + value: pg-test-app-owner + + - it: renders no owner secret when no user is named app + templates: + - templates/init-script.yaml + set: + users: + other: {} + asserts: + # pg-test-credentials and pg-test-init-script only + - hasDocuments: + count: 2 + + - it: points a new Cluster's initdb at the owner secret + templates: + - templates/db.yaml + set: + users: + app: {} + documentSelector: + path: kind + value: Cluster + asserts: + - equal: + path: spec.bootstrap + value: + initdb: + secret: + name: pg-test-app-owner + + - it: points a live initdb Cluster at the owner secret + templates: + - templates/db.yaml + kubernetesProvider: + scheme: + "postgresql.cnpg.io/v1/Cluster": + gvr: + group: postgresql.cnpg.io + version: v1 + resource: clusters + namespaced: true + objects: + - apiVersion: postgresql.cnpg.io/v1 + kind: Cluster + metadata: + name: pg-test + namespace: tenant-test + spec: + bootstrap: + initdb: + database: app + owner: app + set: + users: + app: {} + documentSelector: + path: kind + value: Cluster + asserts: + - equal: + path: spec.bootstrap.initdb.secret.name + value: pg-test-app-owner + - notExists: + path: spec.bootstrap.recovery + + - it: keeps a restored Cluster on its recovery method + # CNPG rejects a Cluster with two bootstrap methods, and a Cluster restored + # from a backup keeps bootstrap.recovery in its live spec. + templates: + - templates/db.yaml + kubernetesProvider: + scheme: + "postgresql.cnpg.io/v1/Cluster": + gvr: + group: postgresql.cnpg.io + version: v1 + resource: clusters + namespaced: true + objects: + - apiVersion: postgresql.cnpg.io/v1 + kind: Cluster + metadata: + name: pg-test + namespace: tenant-test + spec: + bootstrap: + recovery: + database: app + owner: app + source: pg-old + set: + users: + app: {} + documentSelector: + path: kind + value: Cluster + asserts: + - equal: + path: spec.bootstrap.recovery.secret.name + value: pg-test-app-owner + - notExists: + path: spec.bootstrap.initdb + + - it: leaves bootstrap unrendered when no user is named app + templates: + - templates/db.yaml + set: + users: + other: {} + documentSelector: + path: kind + value: Cluster + asserts: + - notExists: + path: spec.bootstrap + + - it: leaves an in-progress restore's recovery block untouched + # While bootstrap.enabled is on the init-job is skipped and the credentials + # are flagged pending, so the owner password is not taken over mid-restore. + templates: + - templates/db.yaml + set: + users: + app: {} + backup: + enabled: true + useSystemBucket: false + s3AccessKey: AKIAEXAMPLE + s3SecretKey: s3cr3t + destinationPath: s3://bucket/pg-test/ + endpointURL: https://s3.example:9000 + bootstrap: + enabled: true + oldName: pg-old + serverName: pg-old + documentSelector: + path: kind + value: Cluster + asserts: + - equal: + path: spec.bootstrap.recovery.source + value: pg-old + - notExists: + path: spec.bootstrap.recovery.secret + + - it: drops recovery.source with its external cluster once bootstrap.enabled is off + # A source naming an absent externalClusters entry is rejected by CNPG's + # webhook, and both are read only at bootstrap. + templates: + - templates/db.yaml + kubernetesProvider: + scheme: + "postgresql.cnpg.io/v1/Cluster": + gvr: + group: postgresql.cnpg.io + version: v1 + resource: clusters + namespaced: true + objects: + - apiVersion: postgresql.cnpg.io/v1 + kind: Cluster + metadata: + name: pg-test + namespace: tenant-test + spec: + bootstrap: + recovery: + database: app + owner: app + source: pg-old + recoveryTarget: + backupID: 20261019T000000 + externalClusters: + - name: pg-old + set: + users: + app: {} + bootstrap: + enabled: false + oldName: pg-old + backupID: 20261019T000000 + documentSelector: + path: kind + value: Cluster + asserts: + - equal: + path: spec.bootstrap + value: + recovery: + secret: + name: pg-test-app-owner + - notExists: + path: spec.externalClusters diff --git a/packages/apps/postgres/tests/backup_schedule_test.yaml b/packages/apps/postgres/tests/backup_schedule_test.yaml new file mode 100644 index 000000000..e78526848 --- /dev/null +++ b/packages/apps/postgres/tests/backup_schedule_test.yaml @@ -0,0 +1,80 @@ +suite: chart-managed scheduled backup takes five-field and six-field cron + +# CNPG parses the ScheduledBackup schedule with robfig/cron v1 Parse, which +# takes the first field as seconds and accepts five fields with only a +# warning, so an unconverted "5 * * * *" would run every minute. + +templates: + - templates/backup.yaml + +release: + name: pg-test + namespace: tenant-test + +tests: + - it: prepends a zero seconds field to a standard five-field schedule + set: + backup: + enabled: true + schedule: "5 * * * *" + asserts: + - equal: + path: spec.schedule + value: "0 5 * * * *" + + - it: joins the fields of a five-field schedule with single spaces + set: + backup: + enabled: true + schedule: " 0 2 * *\t* " + asserts: + - equal: + path: spec.schedule + value: "0 0 2 * * *" + + - it: passes a six-field schedule through unchanged + set: + backup: + enabled: true + schedule: "0 5 * * * *" + asserts: + - equal: + path: spec.schedule + value: "0 5 * * * *" + + - it: passes a descriptor through unchanged + set: + backup: + enabled: true + schedule: "@every 6h" + asserts: + - equal: + path: spec.schedule + value: "@every 6h" + + - it: refuses a schedule with four fields + set: + backup: + enabled: true + schedule: "5 * * *" + asserts: + - failedTemplate: + errorMessage: 'postgres: backup.schedule "5 * * *" is not a cron schedule with 5 or 6 fields (it has 4). Use a standard five-field cron such as "0 2 * * *", a six-field cron with leading seconds such as "0 0 2 * * *", or a descriptor such as "@daily".' + + - it: refuses a schedule with seven fields + set: + backup: + enabled: true + schedule: "0 0 2 * * * 2026" + asserts: + - failedTemplate: + errorMessage: 'postgres: backup.schedule "0 0 2 * * * 2026" is not a cron schedule with 5 or 6 fields (it has 7). Use a standard five-field cron such as "0 2 * * *", a six-field cron with leading seconds such as "0 0 2 * * *", or a descriptor such as "@daily".' + + - it: refuses a schedule of only spaces + set: + backup: + enabled: true + schedule: " " + asserts: + - failedTemplate: + errorMessage: 'postgres: backup.schedule " " is not a cron schedule with 5 or 6 fields (it has 0). Use a standard five-field cron such as "0 2 * * *", a six-field cron with leading seconds such as "0 0 2 * * *", or a descriptor such as "@daily".' diff --git a/packages/apps/postgres/tests/barman_resources_test.yaml b/packages/apps/postgres/tests/barman_resources_test.yaml index 905fde2bb..1903fe8b1 100644 --- a/packages/apps/postgres/tests/barman_resources_test.yaml +++ b/packages/apps/postgres/tests/barman_resources_test.yaml @@ -13,7 +13,7 @@ set: s3CredentialsSecret: name: postgres-backup tests: - - it: sets resources for native backup without inheriting the tenant 128Mi limit + - it: sets resources for native backup without inheriting the tenant 128Mi and 250m limits set: backup.enabled: true asserts: @@ -24,15 +24,11 @@ tests: cpu: 100m memory: 256Mi limits: + cpu: "1" memory: 1Gi documentSelector: path: kind value: ObjectStore - - notExists: - path: spec.instanceSidecarConfiguration.resources.limits.cpu - documentSelector: - path: kind - value: ObjectStore - equal: path: spec.configuration.s3Credentials.accessKeyId.name value: postgres-backup diff --git a/packages/apps/postgres/tests/init_script_deterministic_test.yaml b/packages/apps/postgres/tests/init_script_deterministic_test.yaml new file mode 100644 index 000000000..25d0facdd --- /dev/null +++ b/packages/apps/postgres/tests/init_script_deterministic_test.yaml @@ -0,0 +1,37 @@ +suite: init-script renders the same for the same values + +# keys returns a map's keys in Go's randomized iteration order, so a release with +# several databases rendered DEFINED_DBS in a different order on each upgrade. The +# init-script Secret then changed on upgrades that changed nothing in the +# databases, and so did the checksum the init Job carries. + +templates: + - templates/init-script.yaml + +release: + name: pg-test + namespace: tenant-test + +set: + _cluster: + scheduling: {} + +tests: + - it: lists the declared databases in a stable order + set: + databases: + hotel: {} + alpha: {} + golf: {} + charlie: {} + foxtrot: {} + bravo: {} + echo: {} + delta: {} + documentSelector: + path: metadata.name + value: pg-test-init-script + asserts: + - matchRegex: + path: stringData["init.sh"] + pattern: 'DEFINED_DBS="alpha bravo charlie delta echo foxtrot golf hotel"' diff --git a/packages/apps/postgres/values.schema.json b/packages/apps/postgres/values.schema.json index f3b39de66..bd5331788 100644 --- a/packages/apps/postgres/values.schema.json +++ b/packages/apps/postgres/values.schema.json @@ -330,7 +330,7 @@ "default": "" }, "schedule": { - "description": "Legacy. Cron schedule (CNPG 6-field format) for the chart-emitted ScheduledBackup. Empty means no chart-managed schedule, which is the recommended setup when a `BackupClass` from `backups.cozystack.io` already drives backup orchestration. In the legacy chart-managed flow `spec.plugins` plus the barman-cloud ObjectStore is rendered when `backup.enabled=true` AND `useSystemBucket=false` AND `destinationPath` is non-empty AND inline-or-external creds are supplied; in the platform `useSystemBucket=true` flow the chart skips emitting `spec.plugins` and the CNPG driver SSA-applies the ObjectStore and patches `spec.plugins` onto the live Cluster at first BackupJob time.", + "description": "Legacy. Cron schedule for the chart-emitted ScheduledBackup, either a standard five-field cron such as `0 2 * * *` for every day at 02:00, or six fields with leading seconds such as `0 0 2 * * *` for the same time. Empty means no chart-managed schedule, which is the recommended setup when a `BackupClass` from `backups.cozystack.io` already drives backup orchestration. In the legacy chart-managed flow `spec.plugins` plus the barman-cloud ObjectStore is rendered when `backup.enabled=true` AND `useSystemBucket=false` AND `destinationPath` is non-empty AND inline-or-external creds are supplied; in the platform `useSystemBucket=true` flow the chart skips emitting `spec.plugins` and the CNPG driver SSA-applies the ObjectStore and patches `spec.plugins` onto the live Cluster at first BackupJob time.", "type": "string", "default": "" }, diff --git a/packages/apps/postgres/values.yaml b/packages/apps/postgres/values.yaml index 8b129e652..3c6d68f59 100644 --- a/packages/apps/postgres/values.yaml +++ b/packages/apps/postgres/values.yaml @@ -212,7 +212,7 @@ databases: {} ## @typedef {struct} Backup - Backup configuration. ## @field {bool} enabled - Enable regular backups. ## @field {bool} [useSystemBucket] - Opt-in: when true, the chart-emitted `-s3-creds` Secret is skipped AND `spec.plugins` (plus the barman-cloud ObjectStore) is left UNSET in the chart-rendered Cluster — the cozy-default BackupClass driver SSA-applies an ObjectStore (carrying destinationPath/endpointURL/credentials) and patches `spec.plugins` on the live Cluster when the first BackupJob runs. Consequence: plugin WAL archiving is NOT active until that first BackupJob fires; WAL accumulates on the PVC in the meantime, so fire an ad-hoc BackupJob immediately after enabling the flag on existing releases. Use together with the platform `cozy-default` BackupClass — tenants do not need to fill `s3AccessKey`/`s3SecretKey` or `destinationPath`/`endpointURL`. The destination path automatically scopes to `s3://cozy-backups///`. -## @field {string} [schedule] - Legacy. Cron schedule (CNPG 6-field format) for the chart-emitted ScheduledBackup. Empty means no chart-managed schedule, which is the recommended setup when a `BackupClass` from `backups.cozystack.io` already drives backup orchestration. In the legacy chart-managed flow `spec.plugins` plus the barman-cloud ObjectStore is rendered when `backup.enabled=true` AND `useSystemBucket=false` AND `destinationPath` is non-empty AND inline-or-external creds are supplied; in the platform `useSystemBucket=true` flow the chart skips emitting `spec.plugins` and the CNPG driver SSA-applies the ObjectStore and patches `spec.plugins` onto the live Cluster at first BackupJob time. +## @field {string} [schedule] - Legacy. Cron schedule for the chart-emitted ScheduledBackup, either a standard five-field cron such as `0 2 * * *` for every day at 02:00, or six fields with leading seconds such as `0 0 2 * * *` for the same time. Empty means no chart-managed schedule, which is the recommended setup when a `BackupClass` from `backups.cozystack.io` already drives backup orchestration. In the legacy chart-managed flow `spec.plugins` plus the barman-cloud ObjectStore is rendered when `backup.enabled=true` AND `useSystemBucket=false` AND `destinationPath` is non-empty AND inline-or-external creds are supplied; in the platform `useSystemBucket=true` flow the chart skips emitting `spec.plugins` and the CNPG driver SSA-applies the ObjectStore and patches `spec.plugins` onto the live Cluster at first BackupJob time. ## @field {string} [retentionPolicy] - Retention policy (e.g. "30d"). ## @field {string} [destinationPath] - DEPRECATED. Per-tenant S3 configuration is superseded by the platform-managed `cozy-default` BackupClass and the `cozy-backups` system bucket. Leave empty for new installations; the BackupClass driver picks up the system-managed coordinates. Kept for in-place upgrade compatibility. ## @field {string} [endpointURL] - DEPRECATED. See `destinationPath`. diff --git a/packages/apps/qdrant/templates/qdrant.yaml b/packages/apps/qdrant/templates/qdrant.yaml index 2aca225fb..4caf04403 100644 --- a/packages/apps/qdrant/templates/qdrant.yaml +++ b/packages/apps/qdrant/templates/qdrant.yaml @@ -18,6 +18,28 @@ spec: upgrade: remediation: retries: -1 + {{- if $tlsEnabled }} + postRenderers: + - kustomize: + patches: + - target: + group: monitoring.coreos.com + version: v1 + kind: ServiceMonitor + name: {{ .Release.Name }} + patch: | + - op: replace + path: /spec/endpoints/0/scheme + value: https + - op: add + path: /spec/endpoints/0/tlsConfig + value: + ca: + secret: + name: {{ .Release.Name }}-tls + key: ca.crt + serverName: {{ .Release.Name }}.{{ .Release.Namespace }}.svc + {{- end }} valuesFrom: - kind: Secret name: cozystack-values diff --git a/packages/apps/tcp-balancer/templates/configmap.yaml b/packages/apps/tcp-balancer/templates/configmap.yaml index 122c10254..327b8200e 100644 --- a/packages/apps/tcp-balancer/templates/configmap.yaml +++ b/packages/apps/tcp-balancer/templates/configmap.yaml @@ -11,6 +11,9 @@ default-server observe layer4 error-limit 10 on-error mark-down check send-proxy {{- fail (printf "mode %s is not supported" .) }} {{- end }} {{- end }} +{{- $resources := include "cozy-lib.resources.defaultingSanitize" (list .Values.resourcesPreset .Values.resources $) | fromYaml }} +{{- $memoryMi := div (include "cozy-lib.resources.toFloat" $resources.limits.memory | float64 | int64) 1048576 }} +{{- $cpu := include "cozy-lib.resources.toFloat" $resources.limits.cpu | float64 }} apiVersion: v1 kind: ConfigMap @@ -21,6 +24,10 @@ metadata: app.kubernetes.io/managed-by: {{ .Release.Service }} data: haproxy.cfg: | + global + fd-hard-limit {{ mul $memoryMi 32 }} + thread-hard-limit {{ max (ceil $cpu | int64) 1 }} + defaults mode tcp option dontlognull diff --git a/packages/apps/tcp-balancer/templates/service.yaml b/packages/apps/tcp-balancer/templates/service.yaml index 8384cc85b..689db7e16 100644 --- a/packages/apps/tcp-balancer/templates/service.yaml +++ b/packages/apps/tcp-balancer/templates/service.yaml @@ -27,7 +27,7 @@ spec: port: 443 targetPort: https {{- end }} - {{- with .Values.httpAndHttps }} + {{- with .Values.kubernetesAndTalos }} - name: kubernetes protocol: TCP port: 6443 diff --git a/packages/apps/tcp-balancer/tests/haproxy-config_test.yaml b/packages/apps/tcp-balancer/tests/haproxy-config_test.yaml index 4c8844583..d1abbee44 100644 --- a/packages/apps/tcp-balancer/tests/haproxy-config_test.yaml +++ b/packages/apps/tcp-balancer/tests/haproxy-config_test.yaml @@ -130,3 +130,39 @@ tests: - matchRegex: path: data["haproxy.cfg"] pattern: '(?m)^frontend talos$\n(?:[ \t]+.*\n)*?[ \t]+acl whitelist src 10\.0\.0\.0/8\n[ \t]+acl all src 0\.0\.0\.0\n[ \t]+tcp-request content accept if whitelist\n[ \t]+tcp-request content reject$' + + - it: caps the automatic fd and thread counts by the default preset + asserts: + - matchRegex: + path: data["haproxy.cfg"] + pattern: '\Aglobal\n[ \t]+fd-hard-limit 4096\n[ \t]+thread-hard-limit 1\n\n' + - notMatchRegex: + path: data["haproxy.cfg"] + pattern: '\Aglobal\n(?:[ \t]+.*\n)*?[ \t]+(?:maxconn|nbthread)\b' + + - it: scales the caps with the preset + set: + resourcesPreset: t1.medium + asserts: + - matchRegex: + path: data["haproxy.cfg"] + pattern: '\Aglobal\n[ \t]+fd-hard-limit 32768\n[ \t]+thread-hard-limit 2\n\n' + + - it: takes the caps from explicit resources and rounds the CPU limit up + set: + resources: + cpu: 2500m + memory: 768Mi + asserts: + - matchRegex: + path: data["haproxy.cfg"] + pattern: '\Aglobal\n[ \t]+fd-hard-limit 24576\n[ \t]+thread-hard-limit 3\n\n' + + - it: never renders a thread cap of zero, which HAProxy refuses to parse + set: + resources: + cpu: "0" + asserts: + - matchRegex: + path: data["haproxy.cfg"] + pattern: '(?m)^[ \t]+thread-hard-limit 1$' diff --git a/packages/apps/tcp-balancer/tests/service_test.yaml b/packages/apps/tcp-balancer/tests/service_test.yaml new file mode 100644 index 000000000..57191115c --- /dev/null +++ b/packages/apps/tcp-balancer/tests/service_test.yaml @@ -0,0 +1,97 @@ +suite: haproxy service + +templates: + - templates/service.yaml + - templates/deployment.yaml + - templates/configmap.yaml + +tests: + - it: publishes only http and https by default, both on container ports the Deployment declares + asserts: + - equal: + path: spec.ports + value: + - name: http + protocol: TCP + port: 80 + targetPort: http + - name: https + protocol: TCP + port: 443 + targetPort: https + template: templates/service.yaml + - equal: + path: spec.template.spec.containers[0].ports + value: + - containerPort: 8080 + name: http + - containerPort: 8443 + name: https + template: templates/deployment.yaml + + - it: publishes kubernetes and talos for kubernetesAndTalos alone, both on container ports the Deployment declares + set: + httpAndHttps: null + kubernetesAndTalos: + endpoints: + - 10.1.1.1 + asserts: + - equal: + path: spec.ports + value: + - name: kubernetes + protocol: TCP + port: 6443 + targetPort: kubernetes + - name: talos + protocol: TCP + port: 50000 + targetPort: talos + template: templates/service.yaml + - equal: + path: spec.template.spec.containers[0].ports + value: + - containerPort: 6443 + name: kubernetes + - containerPort: 50000 + name: talos + template: templates/deployment.yaml + + - it: publishes all four ports when both are set, each on a container port the Deployment declares + set: + kubernetesAndTalos: + endpoints: + - 10.1.1.1 + asserts: + - equal: + path: spec.ports + value: + - name: http + protocol: TCP + port: 80 + targetPort: http + - name: https + protocol: TCP + port: 443 + targetPort: https + - name: kubernetes + protocol: TCP + port: 6443 + targetPort: kubernetes + - name: talos + protocol: TCP + port: 50000 + targetPort: talos + template: templates/service.yaml + - equal: + path: spec.template.spec.containers[0].ports + value: + - containerPort: 8080 + name: http + - containerPort: 8443 + name: https + - containerPort: 6443 + name: kubernetes + - containerPort: 50000 + name: talos + template: templates/deployment.yaml diff --git a/packages/apps/tenant/README.md b/packages/apps/tenant/README.md index 52ec7cd46..dd350bad3 100644 --- a/packages/apps/tenant/README.md +++ b/packages/apps/tenant/README.md @@ -101,6 +101,7 @@ The `resourceQuotas` parameter allows you to limit resources available to the te - `memory` - Total memory (e.g., `"4Gi"` or `"512Mi"`) - `ephemeral-storage` - Ephemeral storage limit (e.g., `"10Gi"`) - `storage` - Total persistent storage (e.g., `"100Gi"`) +- `hugepages-2Mi`, `hugepages-1Gi` - Total huge pages of that size (e.g., `"4Gi"`), converted to `requests.hugepages-` only, as Kubernetes has no limits quota for huge pages **Object count quotas** (passed as-is): - `pods` - Maximum number of pods diff --git a/packages/apps/tenant/templates/gateway.yaml b/packages/apps/tenant/templates/gateway.yaml index afb539811..ec5e1d619 100644 --- a/packages/apps/tenant/templates/gateway.yaml +++ b/packages/apps/tenant/templates/gateway.yaml @@ -19,12 +19,54 @@ spec: namespace: cozy-system interval: 5m timeout: 10m + {{- /* Install remediation is an uninstall in every case Flux offers, and this + release does not disable hooks on it, so a remediated install runs the + gateway chart's post-delete cleanup Job. That Job deletes the + cozystack-acme-account Secret. The key regenerates on the next install, + so unlike the storage-owning releases this costs no data: it costs a + re-registration against the ACME provider, and repeated cycles run into + its rate limits, which can hold certificate issuance for the tenant + down for hours. RetryOnFailure keeps the manifests applied and retries + the failed release instead, so no uninstall happens and the cleanup Job + never runs. Both actions carry the strategy because the controller + performs that retry as an upgrade. Two things are traded away: a real + upgrade failure now retries rather than rolls back, which gives up no + stable safety net, since with retries: -1 the default strategy 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 it until an operator removes the release. 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 + {{- /* Listener certificates depend on ACME or DNS and, under HTTP-01, on + routes other releases own, so the TenantGateway sits at + Ready=False/ListenersNotReady while any of them is pending, which + kstatus reads as InProgress until the wait runs out. The expression + replaces kstatus for this kind only. Flux still reads InProgress + while status.observedGeneration lags the generation, before any + expression runs, so the release still waits for the controller to + observe the current TenantGateway spec, never for listener or + certificate health. The strategy is pinned because expressions are + read only under poller, and the UseHelm3Defaults gate turns the + default to legacy. */}} + waitStrategy: + name: poller + healthCheckExprs: + - apiVersion: gateway.cozystack.io/v1alpha1 + kind: TenantGateway + current: "true" valuesFrom: - kind: Secret name: cozystack-values diff --git a/packages/apps/tenant/templates/monitoring.yaml b/packages/apps/tenant/templates/monitoring.yaml index a66b11d45..30bc83ed8 100644 --- a/packages/apps/tenant/templates/monitoring.yaml +++ b/packages/apps/tenant/templates/monitoring.yaml @@ -30,10 +30,35 @@ spec: namespace: cozy-system interval: 5m timeout: 10m + {{- /* Install remediation is an uninstall in every case Flux offers, and this + release does not disable hooks on it, so a remediated install runs the + monitoring chart's post-delete cleanup Job. That Job deletes PVCs by + apps.cozystack.io/application.name=-system, which is the label + the metrics and logs claim templates stamp so the operator copies it + onto the storage PVCs. An install that only missed its readiness budget + therefore takes the tenant's metrics and logs with it, and nothing + reconstructs them. RetryOnFailure keeps the manifests applied and + retries the failed release instead, so no uninstall happens and the + cleanup Job never runs. Both actions carry the strategy because the + controller performs that retry as an upgrade. Two things are traded + away: a real upgrade failure now retries rather than rolls back, which + gives up no stable safety net, since with retries: -1 the default + strategy 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 it until an operator removes the + release. 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/gateway_wait_test.yaml b/packages/apps/tenant/tests/gateway_wait_test.yaml new file mode 100644 index 000000000..889a3673c --- /dev/null +++ b/packages/apps/tenant/tests/gateway_wait_test.yaml @@ -0,0 +1,44 @@ +suite: tenant gateway HelmRelease waits for the TenantGateway generation, not its certificates + +# A TenantGateway reads Ready=False/ListenersNotReady while any listener's +# certificate is pending, and kstatus reads that as InProgress, so under the +# default wait every upgrade of this release times out and retries. The release +# swaps kstatus for an always-Current expression on that kind. The wait itself +# must stay on: Flux still holds it while status.observedGeneration lags, and +# that is the only gate left between the gateway spec and its controller. The +# list is pinned whole because a `failed` or `inProgress` expression that reads +# status would wait again, at least until the controller's first status write. +templates: + - templates/gateway.yaml + +release: + name: tenant-test + namespace: tenant-test + +tests: + - it: reads the TenantGateway through an expression under the poller wait + set: + gateway: true + asserts: + # Pins the document first: the notExists checks below pass on an empty render. + - equal: + path: metadata.name + value: gateway + - equal: + path: spec.waitStrategy.name + value: poller + - equal: + path: spec.healthCheckExprs + value: + - apiVersion: gateway.cozystack.io/v1alpha1 + kind: TenantGateway + current: "true" + - notExists: + path: spec.install.disableWait + - notExists: + path: spec.upgrade.disableWait + + - it: renders no gateway release when the tenant does not own one + asserts: + - hasDocuments: + count: 0 diff --git a/packages/apps/tenant/tests/monitoring_gateway_install_retry_test.yaml b/packages/apps/tenant/tests/monitoring_gateway_install_retry_test.yaml new file mode 100644 index 000000000..c89c233b6 --- /dev/null +++ b/packages/apps/tenant/tests/monitoring_gateway_install_retry_test.yaml @@ -0,0 +1,104 @@ +suite: monitoring and gateway tenant HelmReleases retry a failed install in place + +# Named after the two releases rather than after a class. They do not share one: +# monitoring loses storage and gateway loses a regenerable key. The tenant's +# etcd and seaweedfs releases lose storage as well and are outside this suite, +# so a class-shaped title here 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/monitoring.yaml + - templates/gateway.yaml + +release: + name: tenant-test + namespace: tenant-test + +set: + monitoring: true + gateway: true + +tests: + # Install remediation is an uninstall in every case Flux offers, and neither + # release disables hooks on it, so a remediated install runs the app chart's + # post-delete cleanup Job. The monitoring one deletes PVCs by the + # apps.cozystack.io/application.name=-system label, and the metrics + # and logs claim templates stamp exactly that label so the operator copies it + # onto the storage PVCs. An install that misses its budget therefore deletes + # the tenant's metrics and logs, which nothing reconstructs. + - it: retries a failed monitoring install instead of deleting the storage + asserts: + - template: templates/monitoring.yaml + equal: + path: spec.install.strategy.name + value: RetryOnFailure + - template: templates/monitoring.yaml + equal: + path: spec.install.strategy.retryInterval + value: 30s + + # The gateway cleanup Job deletes the cozystack-acme-account Secret. That key + # regenerates on the next install, so the cost is re-registration against the + # ACME provider and its rate limits rather than lost data. Same mechanism, + # smaller stake, and worth fixing for the same reason: remediation invokes a + # teardown written for an honest uninstall. + - it: retries a failed gateway install instead of discarding the ACME account + asserts: + - template: templates/gateway.yaml + equal: + path: spec.install.strategy.name + value: RetryOnFailure + - template: templates/gateway.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/monitoring.yaml + equal: + path: spec.upgrade.strategy.name + value: RetryOnFailure + - template: templates/monitoring.yaml + equal: + path: spec.upgrade.strategy.retryInterval + value: 30s + - template: templates/gateway.yaml + equal: + path: spec.upgrade.strategy.name + value: RetryOnFailure + - template: templates/gateway.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/monitoring.yaml + equal: + path: spec.install.remediation.retries + value: -1 + - template: templates/monitoring.yaml + equal: + path: spec.upgrade.remediation.retries + value: -1 + - template: templates/gateway.yaml + equal: + path: spec.install.remediation.retries + value: -1 + - template: templates/gateway.yaml + equal: + path: spec.upgrade.remediation.retries + value: -1 diff --git a/packages/apps/vm-disk/templates/NOTES.txt b/packages/apps/vm-disk/templates/NOTES.txt index 73d07cc59..0940e75ba 100644 --- a/packages/apps/vm-disk/templates/NOTES.txt +++ b/packages/apps/vm-disk/templates/NOTES.txt @@ -1,5 +1,5 @@ {{- if and .Values.source (hasKey .Values.source "upload") }} To upload your disk run: -virtctl image-upload dv -n {{ .Release.Namespace }} {{ .Release.Name }} --image-path +virtctl image-upload dv {{ .Release.Name }} --no-create --namespace {{ .Release.Namespace }} --image-path {{- end }} diff --git a/packages/apps/vm-disk/tests/upload_notes_test.yaml b/packages/apps/vm-disk/tests/upload_notes_test.yaml new file mode 100644 index 000000000..16a6432a3 --- /dev/null +++ b/packages/apps/vm-disk/tests/upload_notes_test.yaml @@ -0,0 +1,18 @@ +suite: VM disk upload notes +templates: + - templates/NOTES.txt + +release: + name: vm-disk-demo + namespace: tenant-root + +tests: + - it: reuses the chart-created DataVolume for local image upload + set: + source: + upload: {} + asserts: + - matchRegexRaw: + pattern: 'virtctl image-upload dv vm-disk-demo --no-create --namespace tenant-root --image-path ' + - notMatchRegexRaw: + pattern: 'virtctl image-upload dv -n' diff --git a/packages/apps/vm-instance/templates/service.yaml b/packages/apps/vm-instance/templates/service.yaml index cfeffa810..b757ab96d 100644 --- a/packages/apps/vm-instance/templates/service.yaml +++ b/packages/apps/vm-instance/templates/service.yaml @@ -30,6 +30,13 @@ spec: {{- if .Values.external }} {{- if and (eq .Values.externalMethod "WholeIP") (not .Values.externalPorts) }} - port: 65535 + {{- else if not .Values.externalPorts }} + {{- /* A Service needs at least one port. cozy-proxy only admits TCP and + UDP ports into its PortList filter, so an SCTP placeholder keeps the + external IP while every inbound TCP and UDP packet is dropped. */}} + - name: no-ports + port: 65535 + protocol: SCTP {{- else }} {{- range .Values.externalPorts }} - name: port-{{ . }} diff --git a/packages/apps/vm-instance/tests/service_ports_test.yaml b/packages/apps/vm-instance/tests/service_ports_test.yaml new file mode 100644 index 000000000..d7689d957 --- /dev/null +++ b/packages/apps/vm-instance/tests/service_ports_test.yaml @@ -0,0 +1,70 @@ +suite: vm-instance external Service ports + +# The API server rejects a Service without ports, so an external PortList VM +# whose port list was emptied could not be upgraded at all. The placeholder +# must be SCTP: cozy-proxy only admits TCP and UDP ports into its filter, so +# any TCP or UDP placeholder would open that port on the VM. +release: + name: test-vm + namespace: tenant-test +templates: + - templates/service.yaml +set: + fullnameOverride: test-vm + external: true + +tests: + - it: renders an SCTP placeholder for PortList with no ports + set: + externalMethod: PortList + externalPorts: [] + asserts: + - equal: + path: spec.type + value: LoadBalancer + - equal: + path: metadata.annotations["networking.cozystack.io/wholeIP"] + value: "false" + - lengthEqual: + path: spec.ports + count: 1 + - equal: + path: spec.ports[0] + value: + name: no-ports + port: 65535 + protocol: SCTP + + - it: renders the listed ports for PortList + set: + externalMethod: PortList + externalPorts: [22, 443] + asserts: + - lengthEqual: + path: spec.ports + count: 2 + - equal: + path: spec.ports[0] + value: + name: port-22 + port: 22 + targetPort: 22 + - notContains: + path: spec.ports + content: + name: no-ports + port: 65535 + protocol: SCTP + + - it: keeps the WholeIP placeholder when no ports are listed + set: + externalMethod: WholeIP + externalPorts: [] + asserts: + - equal: + path: metadata.annotations["networking.cozystack.io/wholeIP"] + value: "true" + - equal: + path: spec.ports + value: + - port: 65535 diff --git a/packages/core/platform/sources/cert-manager.yaml b/packages/core/platform/sources/cert-manager.yaml index 857e9a08e..731fa5aaf 100644 --- a/packages/core/platform/sources/cert-manager.yaml +++ b/packages/core/platform/sources/cert-manager.yaml @@ -34,3 +34,12 @@ spec: releaseName: cert-manager-issuers dependsOn: - cert-manager + # A ClusterIssuer is Ready only after cert-manager has registered an + # ACME account with the CA. Under kstatus that holds this release, and + # through dependsOn every package behind cozystack.cert-manager, for as + # long as the CA is unreachable. Issuance fails and recovers on its own + # in that window; the platform rollout must not wait for it. + healthCheckExprs: + - apiVersion: cert-manager.io/v1 + kind: ClusterIssuer + current: "true" diff --git a/packages/core/platform/sources/foundationdb-operator.yaml b/packages/core/platform/sources/foundationdb-operator.yaml index 0af881f60..28328c3d1 100644 --- a/packages/core/platform/sources/foundationdb-operator.yaml +++ b/packages/core/platform/sources/foundationdb-operator.yaml @@ -20,3 +20,9 @@ spec: install: namespace: cozy-foundationdb-operator releaseName: foundationdb-operator + # helm-controller leaves existing CRDs alone on upgrade, so a cluster + # installed before v1.6.0 keeps the v2.13.0 schema under the v2.30.0 + # operator, and the apiserver prunes the fields added since, + # status.backupDetails.restorable among them. The schema diff adds + # fields and drops none, so replace is safe. + upgradeCRDs: CreateReplace diff --git a/packages/core/platform/sources/keycloak-operator.yaml b/packages/core/platform/sources/keycloak-operator.yaml index ce3a5f7e0..5b116e5e6 100644 --- a/packages/core/platform/sources/keycloak-operator.yaml +++ b/packages/core/platform/sources/keycloak-operator.yaml @@ -20,3 +20,10 @@ spec: install: namespace: cozy-keycloak releaseName: keycloak-operator + # helm-controller leaves existing CRDs alone on upgrade, so a cluster + # installed before v1.2.0 keeps the v1.25.0 schema and the apiserver + # prunes the realm session settings keycloak-configure sets. v1.32.0 + # drops the realm, targetRealm and keycloakOwner fields deprecated in + # favour of realmRef and keycloakRef. The platform renders only the + # refs, so replace is safe. + upgradeCRDs: CreateReplace diff --git a/packages/core/platform/templates/apps.yaml b/packages/core/platform/templates/apps.yaml index f7a6b9aa5..bc2290faa 100644 --- a/packages/core/platform/templates/apps.yaml +++ b/packages/core/platform/templates/apps.yaml @@ -29,6 +29,14 @@ stringData: opensearch-operator: manager: dnsBase: {{ .Values.networking.clusterDomain | quote }} + {{- /* + The operator resolves its own MariaDB pods, and the webhook certificate + gets its SAN, from CLUSTER_NAME, which the vendored subchart reads from + clusterName. Same subchart-key route as above; a package rendered + without this Secret falls back to the literal in its values.yaml. + */}} + mariadb-operator: + clusterName: {{ .Values.networking.clusterDomain | quote }} _cluster: root-host: {{ $rootHost | quote }} bundle-name: {{ .Values.bundles.system.variant | quote }} diff --git a/packages/core/platform/templates/containerd-registry-secret.yaml b/packages/core/platform/templates/containerd-registry-secret.yaml deleted file mode 100644 index 6e9fb6408..000000000 --- a/packages/core/platform/templates/containerd-registry-secret.yaml +++ /dev/null @@ -1,35 +0,0 @@ -{{- if .Values.registries.mirrors }} -apiVersion: v1 -kind: Secret -metadata: - name: patch-containerd - namespace: cozy-system -type: Opaque -stringData: -{{- range $registry, $mirror := .Values.registries.mirrors }} -{{- if $mirror.endpoints }} - {{ $registry }}.toml: | - server = "https://{{ $registry }}" -{{- range $endpoint := $mirror.endpoints }} - [host."{{ $endpoint }}"] - capabilities = ["pull", "resolve"] -{{- $endpointConfig := index $.Values.registries.config $endpoint }} -{{- if $endpointConfig }} -{{- if $endpointConfig.tls }} -{{- if $endpointConfig.tls.insecureSkipVerify }} - skip_verify = true -{{- end }} -{{- end }} -{{- if $endpointConfig.auth }} - [host."{{ $endpoint }}".auth] - username = "{{ $endpointConfig.auth.username }}" - password = "{{ $endpointConfig.auth.password }}" -{{- end }} -{{- else }} - skip_verify = true -{{- end }} -{{- end }} -{{- end }} -{{- end }} -{{- end }} - diff --git a/packages/core/platform/tests/apps_mariadb_operator_cluster_name_test.yaml b/packages/core/platform/tests/apps_mariadb_operator_cluster_name_test.yaml new file mode 100644 index 000000000..6cd9426ba --- /dev/null +++ b/packages/core/platform/tests/apps_mariadb_operator_cluster_name_test.yaml @@ -0,0 +1,33 @@ +suite: apps.yaml networking.clusterDomain reaches the mariadb-operator cluster name + +templates: + - templates/apps.yaml + +release: + name: cozy-platform + namespace: cozy-system + +# The operator dials ..svc. to set up replication and +# to reconcile User, Database and Grant, and the vendored subchart fills +# CLUSTER_NAME from clusterName. A cluster whose domain is not cozy.local got +# NXDOMAIN on every such lookup while the literal was pinned in the package. +# Every pattern anchors clusterName to its mariadb-operator parent, 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)^mariadb-operator:\n clusterName: "cozy\.local"$' + + - it: tracks a non-default networking.clusterDomain + set: + networking.clusterDomain: example.test + asserts: + - matchRegex: + path: stringData["values.yaml"] + pattern: '(?m)^mariadb-operator:\n clusterName: "example\.test"$' + - notMatchRegex: + path: stringData["values.yaml"] + pattern: '(?m)^mariadb-operator:\n clusterName: "cozy\.local"$' diff --git a/packages/core/platform/tests/sources_foundationdb_operator_crds_test.yaml b/packages/core/platform/tests/sources_foundationdb_operator_crds_test.yaml new file mode 100644 index 000000000..a0976ae57 --- /dev/null +++ b/packages/core/platform/tests/sources_foundationdb_operator_crds_test.yaml @@ -0,0 +1,20 @@ +suite: foundationdb-operator applies CRD updates on upgrade +# The fdb-operator v2.30.0 CRDs add fields the v2.13.0 ones lack, among them +# status.backupDetails.restorable on FoundationDBBackup. Helm never upgrades +# CRDs shipped in crds/, so without CreateReplace a cluster installed before +# v1.6.0 keeps the v2.13.0 CRDs and the apiserver prunes those fields on every +# write. Pin the policy so an upgrade cannot silently regress. +templates: + - templates/sources.yaml +release: + name: cozystack + namespace: cozy-system +tests: + - it: foundationdb-operator PackageSource sets upgradeCRDs to CreateReplace + documentSelector: + path: metadata.name + value: cozystack.foundationdb-operator + asserts: + - equal: + path: spec.variants[0].components[0].install.upgradeCRDs + value: CreateReplace diff --git a/packages/core/platform/tests/sources_keycloak_operator_crds_test.yaml b/packages/core/platform/tests/sources_keycloak_operator_crds_test.yaml new file mode 100644 index 000000000..5cccfc757 --- /dev/null +++ b/packages/core/platform/tests/sources_keycloak_operator_crds_test.yaml @@ -0,0 +1,22 @@ +suite: keycloak-operator applies CRD updates on upgrade +# keycloak-configure sets spec.sessions and spec.organizationsEnabled, and +# spec.login when configured, on the cozy ClusterKeycloakRealm. The CRDs of +# keycloak-operator v1.25.0 declare none of them. Helm never upgrades CRDs +# shipped in crds/, so without CreateReplace a cluster installed before v1.2.0 +# keeps those CRDs, the apiserver drops the fields without an error, and the +# operator never applies them to the realm. Pin the policy so an upgrade cannot +# silently regress. +templates: + - templates/sources.yaml +release: + name: cozystack + namespace: cozy-system +tests: + - it: keycloak-operator PackageSource sets upgradeCRDs to CreateReplace + documentSelector: + path: metadata.name + value: cozystack.keycloak-operator + asserts: + - equal: + path: spec.variants[0].components[0].install.upgradeCRDs + value: CreateReplace diff --git a/packages/core/platform/values.yaml b/packages/core/platform/values.yaml index 96e297c51..d7566b3ea 100644 --- a/packages/core/platform/values.yaml +++ b/packages/core/platform/values.yaml @@ -486,37 +486,6 @@ scheduling: # loginTheme: acme # loginThemeImage: registry.example.com/acme-keycloak-theme:v1 branding: {} -# Container registry mirrors configuration -# -# Example: -# registries: -# mirrors: -# docker.io: -# endpoints: -# - http://10.0.0.1:8082 -# ghcr.io: -# endpoints: -# - http://10.0.0.1:8083 -# gcr.io: -# endpoints: -# - http://10.0.0.1:8084 -# registry.k8s.io: -# endpoints: -# - http://10.0.0.1:8085 -# quay.io: -# endpoints: -# - http://10.0.0.1:8086 -# cr.fluentbit.io: -# endpoints: -# - http://10.0.0.1:8087 -# docker-registry3.mariadb.com: -# endpoints: -# - http://10.0.0.1:8088 -# config: -# "10.0.0.1:8082": -# tls: -# insecureSkipVerify: true -registries: {} # Resource allocation ratios resources: cpuAllocationRatio: 10 diff --git a/packages/extra/etcd/templates/etcd-defrag.yaml b/packages/extra/etcd/templates/etcd-defrag.yaml index 52cc63518..c1eefa0db 100644 --- a/packages/extra/etcd/templates/etcd-defrag.yaml +++ b/packages/extra/etcd/templates/etcd-defrag.yaml @@ -29,11 +29,11 @@ spec: drop: ["ALL"] resources: requests: - cpu: 200m - memory: 256Mi + cpu: 10m + memory: 32Mi limits: - cpu: 500m - memory: 512Mi + cpu: 100m + memory: 64Mi args: # The v1alpha2 operator names the headless Service after the # cluster ({{ $.Release.Name }}) and does not use StatefulSet diff --git a/packages/extra/etcd/templates/prometheus-rules.yaml b/packages/extra/etcd/templates/prometheus-rules.yaml index 97294eba1..6f2be8590 100644 --- a/packages/extra/etcd/templates/prometheus-rules.yaml +++ b/packages/extra/etcd/templates/prometheus-rules.yaml @@ -10,7 +10,7 @@ spec: annotations: summary: "etcd cluster '{{`{{ $labels.job }}`}}': insufficient members '{{`{{ $value }}`}}'." expr: | - sum(up{job=~".*etcd.*"} == bool 1) by (job) < ((count(up{job=~".*etcd.*"}) by (job) + 1) / 2) + sum(up{job="{{ .Release.Namespace }}/etcd-pod-scrape"} == bool 1) by (job) < ((count(up{job="{{ .Release.Namespace }}/etcd-pod-scrape"}) by (job) + 1) / 2) for: 3m labels: severity: critical @@ -19,7 +19,7 @@ spec: annotations: summary: "etcd cluster '{{`{{ $labels.job }}`}}': member '{{`{{ $labels.instance }}`}}' has no leader." expr: | - etcd_server_has_leader{job=~".*etcd.*"} == 0 + etcd_server_has_leader{job="{{ .Release.Namespace }}/etcd-pod-scrape"} == 0 for: 1m labels: severity: critical @@ -28,7 +28,7 @@ spec: annotations: summary: "etcd cluster '{{`{{ $labels.job }}`}}': instance '{{`{{ $labels.instance }}`}}' has seen '{{`{{ $value }}`}}' leader changes within the last hour." expr: | - rate(etcd_server_leader_changes_seen_total{job=~".*etcd.*"}[15m]) > 3 + rate(etcd_server_leader_changes_seen_total{job="{{ .Release.Namespace }}/etcd-pod-scrape"}[15m]) > 3 for: 15m labels: severity: warning @@ -37,9 +37,9 @@ spec: annotations: summary: "etcd cluster '{{`{{ $labels.job }}`}}': '{{`{{ $value }}`}}' of requests for '{{`{{ $labels.grpc_method }}`}}' failed on etcd instance '{{`{{ $labels.instance }}`}}'." expr: | - 100 * sum(rate(grpc_server_handled_total{job=~".*etcd.*", grpc_code!="OK"}[5m])) BY (job, instance, grpc_service, grpc_method) + 100 * sum(rate(grpc_server_handled_total{job="{{ .Release.Namespace }}/etcd-pod-scrape", grpc_code=~"Unknown|FailedPrecondition|ResourceExhausted|Internal|Unavailable|DataLoss|DeadlineExceeded"}[5m])) BY (job, instance, grpc_service, grpc_method) / - sum(rate(grpc_server_handled_total{job=~".*etcd.*"}[5m])) BY (job, instance, grpc_service, grpc_method) + sum(rate(grpc_server_handled_total{job="{{ .Release.Namespace }}/etcd-pod-scrape"}[5m])) BY (job, instance, grpc_service, grpc_method) > 1 for: 10m labels: @@ -49,9 +49,9 @@ spec: annotations: summary: "etcd cluster '{{`{{ $labels.job }}`}}': '{{`{{ $value }}`}}' of requests for '{{`{{ $labels.grpc_method }}`}}' failed on etcd instance '{{`{{ $labels.instance }}`}}'." expr: | - 100 * sum(rate(grpc_server_handled_total{job=~".*etcd.*", grpc_code!="OK"}[5m])) BY (job, instance, grpc_service, grpc_method) + 100 * sum(rate(grpc_server_handled_total{job="{{ .Release.Namespace }}/etcd-pod-scrape", grpc_code=~"Unknown|FailedPrecondition|ResourceExhausted|Internal|Unavailable|DataLoss|DeadlineExceeded"}[5m])) BY (job, instance, grpc_service, grpc_method) / - sum(rate(grpc_server_handled_total{job=~".*etcd.*"}[5m])) BY (job, instance, grpc_service, grpc_method) + sum(rate(grpc_server_handled_total{job="{{ .Release.Namespace }}/etcd-pod-scrape"}[5m])) BY (job, instance, grpc_service, grpc_method) > 5 for: 5m labels: @@ -61,7 +61,7 @@ spec: annotations: summary: "etcd cluster '{{`{{ $labels.job }}`}}': gRPC requests to '{{`{{ $labels.grpc_method }}`}}' are taking '{{`{{ $value }}`}}' on etcd instance '{{`{{ $labels.instance }}`}}'." expr: | - histogram_quantile(0.99, sum(rate(grpc_server_handling_seconds_bucket{job=~".*etcd.*", grpc_type="unary"}[5m])) by (job, instance, grpc_service, grpc_method, le)) + histogram_quantile(0.99, sum(rate(grpc_server_handling_seconds_bucket{job="{{ .Release.Namespace }}/etcd-pod-scrape", grpc_type="unary"}[5m])) by (job, instance, grpc_service, grpc_method, le)) > 0.15 for: 10m labels: @@ -71,7 +71,7 @@ spec: annotations: summary: "etcd cluster '{{`{{ $labels.job }}`}}': member communication with '{{`{{ $labels.To }}`}}' is taking '{{`{{ $value }}`}}' on etcd instance '{{`{{ $labels.instance }}`}}'." expr: | - histogram_quantile(0.99, rate(etcd_network_peer_round_trip_time_seconds_bucket{job=~".*etcd.*"}[5m])) + histogram_quantile(0.99, rate(etcd_network_peer_round_trip_time_seconds_bucket{job="{{ .Release.Namespace }}/etcd-pod-scrape"}[5m])) > 0.15 for: 10m labels: @@ -81,7 +81,7 @@ spec: annotations: summary: "etcd cluster '{{`{{ $labels.job }}`}}': '{{`{{ $value }}`}}' proposal failures within the last hour on etcd instance '{{`{{ $labels.instance }}`}}'." expr: | - rate(etcd_server_proposals_failed_total{job=~".*etcd.*"}[15m]) > 5 + rate(etcd_server_proposals_failed_total{job="{{ .Release.Namespace }}/etcd-pod-scrape"}[15m]) > 5 for: 15m labels: severity: warning @@ -90,7 +90,7 @@ spec: annotations: summary: "'{{`{{ $value }}`}}' of requests for '{{`{{ $labels.method }}`}}' failed on etcd instance '{{`{{ $labels.instance }}`}}'." expr: | - sum(rate(etcd_http_failed_total{job=~".*etcd.*", code!="404"}[5m])) BY (method) / sum(rate(etcd_http_received_total{job=~".*etcd.*"}[5m])) BY (method) > 0.01 + sum(rate(etcd_http_failed_total{job="{{ .Release.Namespace }}/etcd-pod-scrape", code!="404"}[5m])) BY (method) / sum(rate(etcd_http_received_total{job="{{ .Release.Namespace }}/etcd-pod-scrape"}[5m])) BY (method) > 0.01 for: 10m labels: severity: warning @@ -99,7 +99,7 @@ spec: annotations: summary: "'{{`{{ $value }}`}}' of requests for '{{`{{ $labels.method }}`}}' failed on etcd instance '{{`{{ $labels.instance }}`}}'." expr: | - sum(rate(etcd_http_failed_total{job=~".*etcd.*", code!="404"}[5m])) BY (method) / sum(rate(etcd_http_received_total{job=~".*etcd.*"}[5m])) BY (method) > 0.05 + sum(rate(etcd_http_failed_total{job="{{ .Release.Namespace }}/etcd-pod-scrape", code!="404"}[5m])) BY (method) / sum(rate(etcd_http_received_total{job="{{ .Release.Namespace }}/etcd-pod-scrape"}[5m])) BY (method) > 0.05 for: 10m labels: severity: critical @@ -108,7 +108,7 @@ spec: annotations: summary: "etcd instance '{{`{{ $labels.instance }}`}}' HTTP requests to '{{`{{ $labels.method }}`}}' are slow." expr: | - histogram_quantile(0.99, rate(etcd_http_successful_duration_seconds_bucket[5m])) + histogram_quantile(0.99, rate(etcd_http_successful_duration_seconds_bucket{job="{{ .Release.Namespace }}/etcd-pod-scrape"}[5m])) > 0.15 for: 10m labels: @@ -120,10 +120,10 @@ spec: description: 'etcd cluster "{{`{{ $labels.job }}`}}": members are down {{`{{ $value }}`}}.' expr: | max without (endpoint) ( - sum without (instance, pod) (up{job=~".*etcd.*"} == bool 0) + sum without (instance, pod) (up{job="{{ .Release.Namespace }}/etcd-pod-scrape"} == bool 0) or count without (To) ( - sum without (instance, pod) (rate(etcd_network_peer_sent_failures_total{job=~".*etcd.*"}[120s])) > 0.01 + sum without (instance, pod) (rate(etcd_network_peer_sent_failures_total{job="{{ .Release.Namespace }}/etcd-pod-scrape"}[120s])) > 0.01 ) ) > 0 diff --git a/packages/extra/etcd/tests/defrag_test.yaml b/packages/extra/etcd/tests/defrag_test.yaml index 8d74e1a6b..b3acc3401 100644 --- a/packages/extra/etcd/tests/defrag_test.yaml +++ b/packages/extra/etcd/tests/defrag_test.yaml @@ -41,3 +41,16 @@ tests: documentSelector: path: kind value: EtcdCluster + + - it: asks the tenant quota only for what the defrag client uses + template: templates/etcd-defrag.yaml + asserts: + - equal: + path: spec.jobTemplate.spec.template.spec.containers[0].resources + value: + requests: + cpu: 10m + memory: 32Mi + limits: + cpu: 100m + memory: 64Mi diff --git a/packages/extra/etcd/tests/namespace_rules_test.yaml b/packages/extra/etcd/tests/namespace_rules_test.yaml new file mode 100644 index 000000000..e972f3cd0 --- /dev/null +++ b/packages/extra/etcd/tests/namespace_rules_test.yaml @@ -0,0 +1,18 @@ +suite: etcd alerts stay inside their release namespace + +release: + name: etcd + namespace: tenant-scope + +templates: + - templates/prometheus-rules.yaml + +tests: + - it: scopes every alert query to this tenant's scrape job + asserts: + - matchRegex: + path: spec.groups[0].rules[*].expr + pattern: 'job="tenant-scope/etcd-pod-scrape"' + - notMatchRegex: + path: spec.groups[0].rules[*].expr + pattern: 'job=~' diff --git a/packages/extra/ingress/templates/nginx-ingress.yaml b/packages/extra/ingress/templates/nginx-ingress.yaml index 006e97501..4354a532e 100644 --- a/packages/extra/ingress/templates/nginx-ingress.yaml +++ b/packages/extra/ingress/templates/nginx-ingress.yaml @@ -120,9 +120,37 @@ spec: whitelist-source-range: "{{ join "," . }}" {{- end }} {{- if .Values.cloudflareProxy }} - proxy-real-ip-cidr: "{{ include "ingress.cloudflare-ips" . }}" + {{- /* ssl-passthrough forwards HTTPS from loopback with the edge address + in PROXY protocol. Trust loopback only together with the rewrite-phase + guard below, or a direct client could choose CF-Connecting-IP. Port 80 + has no PROXY protocol peer, so use its original socket address: realip + has already replaced remote_addr with the visitor address when the map + is evaluated. This values override also has to carry the system chart's + keepalive_time, because it replaces that chart's http-snippet value as + a whole. */}} + proxy-real-ip-cidr: "{{ include "ingress.cloudflare-ips" . }},127.0.0.1/32,::1/128" use-forwarded-headers: "true" - server-snippet: "real_ip_header CF-Connecting-IP;" + http-snippet: | + keepalive_time 12h; + map $proxy_protocol_addr $cozy_cf_source { + "" $realip_remote_addr; + default $proxy_protocol_addr; + } + geo $cozy_cf_source $cozy_cf_trusted { + default 0; + {{- range $cidr := splitList "," (include "ingress.cloudflare-ips" .) }} + {{ $cidr }} 1; + {{- end }} + } + map "$cozy_cf_trusted:$http_cf_connecting_ip" $cozy_cf_reject { + default 0; + "~^0:.+$" 1; + } + server-snippet: | + real_ip_header CF-Connecting-IP; + if ($cozy_cf_reject = 1) { + return 403; + } {{- end }} {{- if $proxyProtocol }} {{- /* real-ip-header + enable-real-ip make the PROXY-protocol frame the diff --git a/packages/extra/ingress/tests/cloudflare_proxy_test.yaml b/packages/extra/ingress/tests/cloudflare_proxy_test.yaml index 24869abe8..5462c3701 100644 --- a/packages/extra/ingress/tests/cloudflare_proxy_test.yaml +++ b/packages/extra/ingress/tests/cloudflare_proxy_test.yaml @@ -8,7 +8,7 @@ set: _cluster: {} cloudflareProxy: true tests: - - it: trusts CF-Connecting-IP only from the Cloudflare ranges + - it: trusts CF-Connecting-IP from Cloudflare ranges and the passthrough proxy asserts: - matchRegex: path: spec.values.ingress-nginx.controller.config.proxy-real-ip-cidr @@ -16,12 +16,48 @@ tests: - notMatchRegex: path: spec.values.ingress-nginx.controller.config.proxy-real-ip-cidr pattern: (^|,)(0\.0\.0\.0/0|::/0)(,|$) + - matchRegex: + path: spec.values.ingress-nginx.controller.config.proxy-real-ip-cidr + pattern: '(^|,)127\.0\.0\.1/32(,|$)' + - matchRegex: + path: spec.values.ingress-nginx.controller.config.proxy-real-ip-cidr + pattern: '(^|,)::1/128(,|$)' - equal: path: spec.values.ingress-nginx.controller.config.use-forwarded-headers value: "true" - - equal: + - matchRegex: path: spec.values.ingress-nginx.controller.config.server-snippet - value: "real_ip_header CF-Connecting-IP;" + pattern: 'real_ip_header CF-Connecting-IP;' + + - it: rejects a spoofed Cloudflare header before the whitelist + asserts: + - matchRegex: + path: spec.values.ingress-nginx.controller.config.http-snippet + pattern: 'geo \$cozy_cf_source \$cozy_cf_trusted \{\n default 0;' + - matchRegex: + path: spec.values.ingress-nginx.controller.config.http-snippet + pattern: '173\.245\.48\.0/20 1;' + - matchRegex: + path: spec.values.ingress-nginx.controller.config.http-snippet + pattern: '2400:cb00::/32 1;' + - matchRegex: + path: spec.values.ingress-nginx.controller.config.http-snippet + pattern: 'map "\$cozy_cf_trusted:\$http_cf_connecting_ip" \$cozy_cf_reject \{\n default 0;\n "~\^0:\.\+\$" 1;\n\}' + - matchRegex: + path: spec.values.ingress-nginx.controller.config.server-snippet + pattern: 'if \(\$cozy_cf_reject = 1\) \{\n return 403;\n\}' + + - it: checks the original socket peer when PROXY protocol is absent on port 80 + asserts: + - matchRegex: + path: spec.values.ingress-nginx.controller.config.http-snippet + pattern: 'map \$proxy_protocol_addr \$cozy_cf_source \{\n "" \$realip_remote_addr;\n default \$proxy_protocol_addr;\n\}' + + - it: preserves the controller keepalive override + asserts: + - matchRegex: + path: spec.values.ingress-nginx.controller.config.http-snippet + pattern: 'keepalive_time 12h;' - it: does not use set_real_ip_from, which is not an ingress-nginx ConfigMap key asserts: diff --git a/packages/extra/seaweedfs/README.md b/packages/extra/seaweedfs/README.md index 5a3f6cf2f..66c41f78b 100644 --- a/packages/extra/seaweedfs/README.md +++ b/packages/extra/seaweedfs/README.md @@ -13,68 +13,70 @@ ### SeaweedFS Components Configuration -| Name | Description | Type | Value | -| ------------------------------------------------- | ------------------------------------------------------------------------------------------------------------- | ------------------- | ---------- | -| `db` | Database configuration. | `object` | `{}` | -| `db.replicas` | Number of database replicas. | `int` | `2` | -| `db.size` | Persistent Volume size. | `quantity` | `10Gi` | -| `db.storageClass` | StorageClass used to store the data. | `string` | `""` | -| `db.resources` | Explicit CPU and memory configuration. When omitted, the preset defined in `resourcesPreset` is applied. | `object` | `{}` | -| `db.resources.cpu` | Number of CPU cores allocated. | `quantity` | `""` | -| `db.resources.memory` | Amount of memory allocated. | `quantity` | `""` | -| `db.resourcesPreset` | Default sizing preset used when `resources` is omitted. | `string` | `t1.small` | -| `master` | Master service configuration. | `object` | `{}` | -| `master.replicas` | Number of master replicas. | `int` | `3` | -| `master.resources` | Explicit CPU and memory configuration. When omitted, the preset defined in `resourcesPreset` is applied. | `object` | `{}` | -| `master.resources.cpu` | Number of CPU cores allocated. | `quantity` | `""` | -| `master.resources.memory` | Amount of memory allocated. | `quantity` | `""` | -| `master.resourcesPreset` | Default sizing preset used when `resources` is omitted. | `string` | `t1.small` | -| `filer` | Filer service configuration. | `object` | `{}` | -| `filer.replicas` | Number of filer replicas. | `int` | `2` | -| `filer.resources` | Explicit CPU and memory configuration. When omitted, the preset defined in `resourcesPreset` is applied. | `object` | `{}` | -| `filer.resources.cpu` | Number of CPU cores allocated. | `quantity` | `""` | -| `filer.resources.memory` | Amount of memory allocated. | `quantity` | `""` | -| `filer.resourcesPreset` | Default sizing preset used when `resources` is omitted. | `string` | `t1.small` | -| `filer.grpcHost` | The hostname used to expose or access the filer service externally. | `string` | `""` | -| `filer.grpcPort` | The port used to access the filer service externally. | `int` | `443` | -| `filer.whitelist` | A list of IP addresses or CIDR ranges that are allowed to access the filer service. | `[]string` | `[]` | -| `volume` | Volume service configuration. | `object` | `{}` | -| `volume.replicas` | Number of volume replicas. | `int` | `2` | -| `volume.size` | Persistent Volume size. | `quantity` | `10Gi` | -| `volume.storageClass` | StorageClass used to store the data. | `string` | `""` | -| `volume.diskType` | SeaweedFS disk type tag for the default volume servers (e.g., "hdd", "ssd"). | `string` | `""` | -| `volume.resources` | Explicit CPU and memory configuration. When omitted, the preset defined in `resourcesPreset` is applied. | `object` | `{}` | -| `volume.resources.cpu` | Number of CPU cores allocated. | `quantity` | `""` | -| `volume.resources.memory` | Amount of memory allocated. | `quantity` | `""` | -| `volume.resourcesPreset` | Default sizing preset used when `resources` is omitted. | `string` | `t1.small` | -| `volume.zones` | A map of zones for MultiZone topology. Each zone can have its own number of replicas and size. | `map[string]object` | `{}` | -| `volume.zones[name].replicas` | Number of replicas in the zone. | `int` | `0` | -| `volume.zones[name].size` | Zone storage size. | `quantity` | `""` | -| `volume.zones[name].dataCenter` | SeaweedFS data center name for this zone. Defaults to the zone name. | `string` | `""` | -| `volume.zones[name].nodeSelector` | YAML nodeSelector for this zone (default: topology.kubernetes.io/zone: ). | `string` | `""` | -| `volume.zones[name].storageClass` | StorageClass used to store zone data. Defaults to volume.storageClass. | `string` | `""` | -| `volume.zones[name].pools` | A map of storage pools for this zone. Each pool creates a separate Volume StatefulSet per zone. | `map[string]object` | `{}` | -| `volume.zones[name].pools[name].diskType` | SeaweedFS disk type tag (e.g., "ssd", "hdd", "nvme"). | `string` | `""` | -| `volume.zones[name].pools[name].replicas` | Number of volume replicas. Defaults to volume.replicas (Simple) or zone.replicas/volume.replicas (MultiZone). | `int` | `0` | -| `volume.zones[name].pools[name].size` | Persistent Volume size. Defaults to volume.size (Simple) or zone.size/volume.size (MultiZone). | `quantity` | `""` | -| `volume.zones[name].pools[name].storageClass` | Kubernetes StorageClass for the pool. Defaults to volume.storageClass. | `string` | `""` | -| `volume.zones[name].pools[name].resources` | Explicit CPU and memory configuration. When omitted, the preset defined in `resourcesPreset` is applied. | `object` | `{}` | -| `volume.zones[name].pools[name].resources.cpu` | Number of CPU cores allocated. | `quantity` | `""` | -| `volume.zones[name].pools[name].resources.memory` | Amount of memory allocated. | `quantity` | `""` | -| `volume.zones[name].pools[name].resourcesPreset` | Default sizing preset used when `resources` is omitted. Defaults to volume.resourcesPreset. | `string` | `{}` | -| `volume.pools` | A map of storage pools. Each pool creates a separate Volume StatefulSet with its own disk type. | `map[string]object` | `{}` | -| `volume.pools[name].diskType` | SeaweedFS disk type tag (e.g., "ssd", "hdd", "nvme"). | `string` | `""` | -| `volume.pools[name].replicas` | Number of volume replicas. Defaults to volume.replicas (Simple) or zone.replicas/volume.replicas (MultiZone). | `int` | `0` | -| `volume.pools[name].size` | Persistent Volume size. Defaults to volume.size (Simple) or zone.size/volume.size (MultiZone). | `quantity` | `""` | -| `volume.pools[name].storageClass` | Kubernetes StorageClass for the pool. Defaults to volume.storageClass. | `string` | `""` | -| `volume.pools[name].resources` | Explicit CPU and memory configuration. When omitted, the preset defined in `resourcesPreset` is applied. | `object` | `{}` | -| `volume.pools[name].resources.cpu` | Number of CPU cores allocated. | `quantity` | `""` | -| `volume.pools[name].resources.memory` | Amount of memory allocated. | `quantity` | `""` | -| `volume.pools[name].resourcesPreset` | Default sizing preset used when `resources` is omitted. Defaults to volume.resourcesPreset. | `string` | `{}` | -| `s3` | S3 service configuration. | `object` | `{}` | -| `s3.replicas` | Number of S3 replicas. | `int` | `2` | -| `s3.resources` | Explicit CPU and memory configuration. When omitted, the preset defined in `resourcesPreset` is applied. | `object` | `{}` | -| `s3.resources.cpu` | Number of CPU cores allocated. | `quantity` | `""` | -| `s3.resources.memory` | Amount of memory allocated. | `quantity` | `""` | -| `s3.resourcesPreset` | Default sizing preset used when `resources` is omitted. | `string` | `t1.small` | +| Name | Description | Type | Value | +| ------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------- | ---------- | +| `db` | Database configuration. | `object` | `{}` | +| `db.replicas` | Number of database replicas. | `int` | `2` | +| `db.size` | Persistent Volume size. | `quantity` | `10Gi` | +| `db.storageClass` | StorageClass used to store the data. | `string` | `""` | +| `db.resources` | Explicit CPU and memory configuration. When omitted, the preset defined in `resourcesPreset` is applied. | `object` | `{}` | +| `db.resources.cpu` | Number of CPU cores allocated. | `quantity` | `""` | +| `db.resources.memory` | Amount of memory allocated. | `quantity` | `""` | +| `db.resourcesPreset` | Default sizing preset used when `resources` is omitted. | `string` | `t1.small` | +| `master` | Master service configuration. | `object` | `{}` | +| `master.replicas` | Number of master replicas. | `int` | `3` | +| `master.resources` | Explicit CPU and memory configuration. When omitted, the preset defined in `resourcesPreset` is applied. | `object` | `{}` | +| `master.resources.cpu` | Number of CPU cores allocated. | `quantity` | `""` | +| `master.resources.memory` | Amount of memory allocated. | `quantity` | `""` | +| `master.resourcesPreset` | Default sizing preset used when `resources` is omitted. | `string` | `t1.small` | +| `filer` | Filer service configuration. | `object` | `{}` | +| `filer.replicas` | Number of filer replicas. | `int` | `2` | +| `filer.resources` | Explicit CPU and memory configuration. When omitted, the preset defined in `resourcesPreset` is applied. | `object` | `{}` | +| `filer.resources.cpu` | Number of CPU cores allocated. | `quantity` | `""` | +| `filer.resources.memory` | Amount of memory allocated. | `quantity` | `""` | +| `filer.resourcesPreset` | Default sizing preset used when `resources` is omitted. | `string` | `t1.small` | +| `filer.grpcHost` | The hostname used to expose or access the filer service externally. | `string` | `""` | +| `filer.grpcPort` | The port used to access the filer service externally. | `int` | `443` | +| `filer.whitelist` | A list of IP addresses or CIDR ranges that are allowed to access the filer service. | `[]string` | `[]` | +| `volume` | Volume service configuration. | `object` | `{}` | +| `volume.replicas` | Number of volume replicas. | `int` | `2` | +| `volume.size` | Persistent Volume size. | `quantity` | `10Gi` | +| `volume.storageClass` | StorageClass used to store the data. | `string` | `""` | +| `volume.diskType` | SeaweedFS disk type tag for the default volume servers (e.g., "hdd", "ssd"). | `string` | `""` | +| `volume.resources` | Explicit CPU and memory configuration. When omitted, the preset defined in `resourcesPreset` is applied. | `object` | `{}` | +| `volume.resources.cpu` | Number of CPU cores allocated. | `quantity` | `""` | +| `volume.resources.memory` | Amount of memory allocated. | `quantity` | `""` | +| `volume.resourcesPreset` | Default sizing preset used when `resources` is omitted. | `string` | `t1.small` | +| `volume.zones` | A map of zones for MultiZone topology. Each zone can have its own number of replicas and size. | `map[string]object` | `{}` | +| `volume.zones[name].replicas` | Number of replicas in the zone. | `int` | `0` | +| `volume.zones[name].size` | Zone storage size. | `quantity` | `""` | +| `volume.zones[name].dataCenter` | SeaweedFS data center name for this zone. Defaults to the zone name. | `string` | `""` | +| `volume.zones[name].nodeSelector` | YAML nodeSelector for this zone (default: topology.kubernetes.io/zone: ). | `string` | `""` | +| `volume.zones[name].storageClass` | StorageClass used to store zone data. Defaults to volume.storageClass. | `string` | `""` | +| `volume.zones[name].pools` | A map of storage pools for this zone. Each pool creates a separate Volume StatefulSet per zone. | `map[string]object` | `{}` | +| `volume.zones[name].pools[name].diskType` | SeaweedFS disk type tag (e.g., "ssd", "hdd", "nvme"). | `string` | `""` | +| `volume.zones[name].pools[name].replicas` | Number of volume replicas. Defaults to volume.replicas (Simple) or zone.replicas/volume.replicas (MultiZone). | `int` | `0` | +| `volume.zones[name].pools[name].size` | Persistent Volume size. Defaults to volume.size (Simple) or zone.size/volume.size (MultiZone). | `quantity` | `""` | +| `volume.zones[name].pools[name].storageClass` | Kubernetes StorageClass for the pool. Defaults to volume.storageClass. | `string` | `""` | +| `volume.zones[name].pools[name].resources` | Explicit CPU and memory configuration. When omitted, the preset defined in `resourcesPreset` is applied. | `object` | `{}` | +| `volume.zones[name].pools[name].resources.cpu` | Number of CPU cores allocated. | `quantity` | `""` | +| `volume.zones[name].pools[name].resources.memory` | Amount of memory allocated. | `quantity` | `""` | +| `volume.zones[name].pools[name].resourcesPreset` | Default sizing preset used when `resources` is omitted. Defaults to volume.resourcesPreset. | `string` | `{}` | +| `volume.pools` | A map of storage pools. Each pool creates a separate Volume StatefulSet with its own disk type. | `map[string]object` | `{}` | +| `volume.pools[name].diskType` | SeaweedFS disk type tag (e.g., "ssd", "hdd", "nvme"). | `string` | `""` | +| `volume.pools[name].replicas` | Number of volume replicas. Defaults to volume.replicas (Simple) or zone.replicas/volume.replicas (MultiZone). | `int` | `0` | +| `volume.pools[name].size` | Persistent Volume size. Defaults to volume.size (Simple) or zone.size/volume.size (MultiZone). | `quantity` | `""` | +| `volume.pools[name].storageClass` | Kubernetes StorageClass for the pool. Defaults to volume.storageClass. | `string` | `""` | +| `volume.pools[name].resources` | Explicit CPU and memory configuration. When omitted, the preset defined in `resourcesPreset` is applied. | `object` | `{}` | +| `volume.pools[name].resources.cpu` | Number of CPU cores allocated. | `quantity` | `""` | +| `volume.pools[name].resources.memory` | Amount of memory allocated. | `quantity` | `""` | +| `volume.pools[name].resourcesPreset` | Default sizing preset used when `resources` is omitted. Defaults to volume.resourcesPreset. | `string` | `{}` | +| `s3` | S3 service configuration. | `object` | `{}` | +| `s3.replicas` | Number of S3 replicas. | `int` | `2` | +| `s3.resources` | Explicit CPU and memory configuration. When omitted, the preset defined in `resourcesPreset` is applied. | `object` | `{}` | +| `s3.resources.cpu` | Number of CPU cores allocated. | `quantity` | `""` | +| `s3.resources.memory` | Amount of memory allocated. | `quantity` | `""` | +| `s3.resourcesPreset` | Default sizing preset used when `resources` is omitted. | `string` | `t1.small` | +| `cosi` | Bucket provisioning configuration. | `object` | `{}` | +| `cosi.orphanIdentities` | What installs and upgrades do with S3 identities left behind by deleted BucketAccesses: `delete` removes them, `report` only lists them in an Event, `auto` reports when `filer.grpcHost` is set (other clusters may use this filer) and removes them otherwise. Set `report` if the filer is reachable from other clusters some other way. Ignored with the Client topology, whose identities live on the filer of the instance it connects to. | `string` | `auto` | diff --git a/packages/extra/seaweedfs/images/seaweedfs-cosi-driver.tag b/packages/extra/seaweedfs/images/seaweedfs-cosi-driver.tag index 49f252950..bf4084277 100644 --- a/packages/extra/seaweedfs/images/seaweedfs-cosi-driver.tag +++ b/packages/extra/seaweedfs/images/seaweedfs-cosi-driver.tag @@ -1 +1 @@ -ghcr.io/seaweedfs/seaweedfs-cosi-driver:v0.3.1 +ghcr.io/seaweedfs/seaweedfs-cosi-driver:v0.4.0 diff --git a/packages/extra/seaweedfs/templates/seaweedfs.yaml b/packages/extra/seaweedfs/templates/seaweedfs.yaml index 393323429..92d3d2ee3 100644 --- a/packages/extra/seaweedfs/templates/seaweedfs.yaml +++ b/packages/extra/seaweedfs/templates/seaweedfs.yaml @@ -370,6 +370,14 @@ spec: cosi: driverName: "{{ .Release.Namespace }}.seaweedfs.objectstorage.k8s.io" bucketClassName: "{{ .Release.Namespace }}" + orphanIdentities: + {{- $orphans := dig "orphanIdentities" "auto" (.Values.cosi | default dict) }} + {{- if eq $orphans "auto" }} + {{- /* A filer published for Client-topology clusters (ingress.yaml) + holds identities of BucketAccesses in those clusters. */}} + {{- $orphans = ternary "report" "delete" (not (empty .Values.filer.grpcHost)) }} + {{- end }} + mode: {{ $orphans | quote }} resources: requests: cpu: "100m" diff --git a/packages/extra/seaweedfs/tests/orphan_identities_mode_test.yaml b/packages/extra/seaweedfs/tests/orphan_identities_mode_test.yaml new file mode 100644 index 000000000..1a1539181 --- /dev/null +++ b/packages/extra/seaweedfs/tests/orphan_identities_mode_test.yaml @@ -0,0 +1,100 @@ +suite: seaweedfs orphan identities cleanup mode + +templates: + - templates/seaweedfs.yaml + +release: + name: seaweedfs + namespace: tenant-root + +tests: + - it: auto removes orphaned identities when the filer serves only this cluster + set: &platform + _namespace: + host: example.org + ingress: tenant-root + _cluster: + issuer-name: letsencrypt-prod + solver: http01 + documentSelector: + path: metadata.name + value: seaweedfs-system + asserts: + - equal: + path: spec.values.seaweedfs.cosi.orphanIdentities.mode + value: delete + + - it: auto only reports them when the filer is published for Client-topology clusters + set: + <<: *platform + filer: + grpcHost: filer.example.org + documentSelector: + path: metadata.name + value: seaweedfs-system + asserts: + - equal: + path: spec.values.seaweedfs.cosi.orphanIdentities.mode + value: report + + - it: report holds even when the filer is not published + set: + <<: *platform + cosi: + orphanIdentities: report + documentSelector: + path: metadata.name + value: seaweedfs-system + asserts: + - equal: + path: spec.values.seaweedfs.cosi.orphanIdentities.mode + value: report + + - it: delete holds even when the filer is published + set: + <<: *platform + filer: + grpcHost: filer.example.org + cosi: + orphanIdentities: delete + documentSelector: + path: metadata.name + value: seaweedfs-system + asserts: + - equal: + path: spec.values.seaweedfs.cosi.orphanIdentities.mode + value: delete + + - it: an empty cosi block behaves as auto + set: + <<: *platform + filer: + grpcHost: filer.example.org + cosi: null + documentSelector: + path: metadata.name + value: seaweedfs-system + asserts: + - equal: + path: spec.values.seaweedfs.cosi.orphanIdentities.mode + value: report + + - it: an empty cosi block removes when the filer is not published + set: + <<: *platform + cosi: null + documentSelector: + path: metadata.name + value: seaweedfs-system + asserts: + - equal: + path: spec.values.seaweedfs.cosi.orphanIdentities.mode + value: delete + + - it: an unknown mode is rejected + set: + <<: *platform + cosi: + orphanIdentities: bogus + asserts: + - failedTemplate: {} diff --git a/packages/extra/seaweedfs/values.schema.json b/packages/extra/seaweedfs/values.schema.json index 9ce047d1c..e25f6fcfe 100644 --- a/packages/extra/seaweedfs/values.schema.json +++ b/packages/extra/seaweedfs/values.schema.json @@ -861,6 +861,23 @@ ] } } + }, + "cosi": { + "description": "Bucket provisioning configuration.", + "type": "object", + "default": {}, + "properties": { + "orphanIdentities": { + "description": "What installs and upgrades do with S3 identities left behind by deleted BucketAccesses: `delete` removes them, `report` only lists them in an Event, `auto` reports when `filer.grpcHost` is set (other clusters may use this filer) and removes them otherwise. Set `report` if the filer is reachable from other clusters some other way. Ignored with the Client topology, whose identities live on the filer of the instance it connects to.", + "type": "string", + "default": "auto", + "enum": [ + "auto", + "report", + "delete" + ] + } + } } } } diff --git a/packages/extra/seaweedfs/values.yaml b/packages/extra/seaweedfs/values.yaml index 71934780f..3d2779245 100644 --- a/packages/extra/seaweedfs/values.yaml +++ b/packages/extra/seaweedfs/values.yaml @@ -170,3 +170,15 @@ s3: replicas: 2 resources: {} resourcesPreset: "t1.small" + +## @enum {string} OrphanIdentities - What installs and upgrades do with S3 identities left behind by deleted BucketAccesses. +## @value auto +## @value report +## @value delete + +## @typedef {struct} Cosi - Bucket provisioning configuration. +## @field {OrphanIdentities} [orphanIdentities] - What installs and upgrades do with S3 identities left behind by deleted BucketAccesses: `delete` removes them, `report` only lists them in an Event, `auto` reports when `filer.grpcHost` is set (other clusters may use this filer) and removes them otherwise. Set `report` if the filer is reachable from other clusters some other way. Ignored with the Client topology, whose identities live on the filer of the instance it connects to. + +## @param {Cosi} [cosi] - Bucket provisioning configuration. +cosi: + orphanIdentities: auto diff --git a/packages/library/cozy-lib/templates/_barman.tpl b/packages/library/cozy-lib/templates/_barman.tpl index c37b9673f..3b187dda6 100644 --- a/packages/library/cozy-lib/templates/_barman.tpl +++ b/packages/library/cozy-lib/templates/_barman.tpl @@ -13,10 +13,12 @@ LimitRange, which is cozy-keycloak and any tenant that leaves resourceQuotas empty, gave the sidecar no requests and no limit at all, so nothing reserved memory for it and nothing bounded it. The same request and limit settle both: 256Mi holds the measured working set and 1Gi is four times the measurement. -No CPU limit is set, matching the entityOperator precedent in -packages/apps/kafka: a throttled sidecar stalls WAL archiving instead of -failing it. Inside a tenant the limit counts against the ResourceQuota -limits.memory budget, 1Gi per instance pod. +The CPU limit is explicit for the same reason: left unset, that LimitRange +gives the sidecar its 250m default, so gzip compression of full backups and +WAL segments runs on a quarter of a core (a 1.6 GB database took 30 minutes +to back up). One core keeps the sidecar from starving the instance while +removing that ceiling. Inside a tenant both limits count against the +ResourceQuota budget, one core and 1Gi per instance pod. Checksum: since botocore ~1.36 (early 2025) the default RequestChecksumCalculation is when_supported, which attaches a flexible checksum @@ -39,6 +41,7 @@ instanceSidecarConfiguration: cpu: 100m memory: 256Mi limits: + cpu: "1" memory: 1Gi env: - name: AWS_REQUEST_CHECKSUM_CALCULATION diff --git a/packages/library/cozy-lib/templates/_resources.tpl b/packages/library/cozy-lib/templates/_resources.tpl index 79c9ae48b..c97e38d88 100644 --- a/packages/library/cozy-lib/templates/_resources.tpl +++ b/packages/library/cozy-lib/templates/_resources.tpl @@ -234,6 +234,12 @@ {{- $out := "" }} {{- if and (eq $section "limits") (eq $type "storage") }} {{- $out = "" }} +{{- /* + A ResourceQuota accepts hugepages only as requests.hugepages-, + limits.hugepages- is rejected and the whole quota with it. +*/}} +{{- else if and (eq $section "limits") (hasPrefix "hugepages-" $type) }} +{{- $out = "" }} {{- else if and (eq $section "limits") (has $type $rawQuotaKeys) }} {{- $out = $type }} {{- else if not (has $type $rawQuotaKeys) }} diff --git a/packages/system/backupstrategy-controller/templates/rbac.yaml b/packages/system/backupstrategy-controller/templates/rbac.yaml index cb84c6309..f41ed80ee 100644 --- a/packages/system/backupstrategy-controller/templates/rbac.yaml +++ b/packages/system/backupstrategy-controller/templates/rbac.yaml @@ -82,10 +82,11 @@ rules: - apiGroups: ["velero.io"] resources: ["backupstoragelocations"] verbs: ["get"] -# Velero DeleteBackupRequest: used by BackupReconciler to delete Velero backups with their storage data +# Velero DeleteBackupRequest: used to delete Velero backups with their storage +# data. delete replaces a request Velero processed with errors. - apiGroups: ["velero.io"] resources: ["deletebackuprequests"] - verbs: ["create", "get", "list", "watch"] + verbs: ["create", "get", "list", "watch", "delete"] # Namespaces: validate target namespace exists for cross-namespace restore # controller-runtime cache requires list/watch for any resource accessed via r.Get() - apiGroups: [""] diff --git a/packages/system/backupstrategy-controller/templates/strategy-altinity-default.yaml b/packages/system/backupstrategy-controller/templates/strategy-altinity-default.yaml index 592fd50e7..be17b91dd 100644 --- a/packages/system/backupstrategy-controller/templates/strategy-altinity-default.yaml +++ b/packages/system/backupstrategy-controller/templates/strategy-altinity-default.yaml @@ -3,8 +3,8 @@ 1. Helm renders this file at chart install time. Anything inside `{{ ... }}` is interpreted by Helm. 2. The strategy controller renders the resulting Strategy CR - per-BackupJob, expanding `{{ .Application | .Release | .Mode }}` - against the live application object. + per-BackupJob, expanding `{{ .Application | .Release | .Mode | + .ArchiveName | .Backup }}` against the live application object. To emit a literal "{{ .Foo }}" that survives Helm, we pass it as the string argument of `printf` — Helm does not interpret inner template delimiters inside printf's quoted strings. Do NOT simplify by inlining @@ -60,23 +60,56 @@ spec: host="chi-clickhouse-{{ printf "{{ .Release.Name }}" }}-clickhouse-0-0.{{ printf "{{ .Release.Namespace }}" }}.svc" api="http://${host}:7171" auth="-u ${API_USERNAME}:${API_PASSWORD}" + # The archive the controller named for this BackupJob and records + # on its Backup. The default renders it empty, rather than as + # text/template's missing-key marker, when a controller that + # predates archive names renders this template during an upgrade. + archive="{{ printf `{{ .ArchiveName | default "" }}` }}" for _ in $(seq 1 60); do if curl -fsS ${auth} --max-time 2 "${api}/backup/status" >/dev/null 2>&1; then break; fi sleep 5 done if [ "{{ printf "{{ .Mode }}" }}" = "backup" ]; then prefix="clickhouse-{{ printf "{{ .Release.Name }}" }}-" - target="${prefix}$(date -u +%Y%m%dT%H%M%SZ)" - echo "create_remote ${target}" - curl -fsS ${auth} -X POST "${api}/backup/create_remote?name=${target}" >/dev/null + # Only that older controller leaves the name empty, and it + # records no name on the Backup either. + target="${archive:-${prefix}$(date -u +%Y%m%dT%H%M%SZ)}" + # A retried Pod gets the same name. Wait on an attempt the + # sidecar is still running, which would answer a new one with + # 423, and ask for resume, so a local or partial remote backup + # an earlier attempt left is resumed rather than refused as + # existing, whatever use_resumable_state the sidecar runs with. + state=$(curl -fsS ${auth} "${api}/backup/actions" \ + | jq -rs --arg suffix "${target}" \ + '[.[] | select((.command // "") | endswith($suffix))] | sort_by(.start) | last | .status // ""') + if [ "${state}" != "in progress" ]; then + echo "create_remote ${target}" + curl -fsS ${auth} -X POST "${api}/backup/create_remote?name=${target}&resume=true" >/dev/null + fi else - prefix="clickhouse-{{ printf "{{ .Backup.ApplicationRef.Name }}" }}-" - target=$(curl -fsS ${auth} "${api}/backup/list/remote" \ - | jq -rs --arg prefix "${prefix}" \ - '[.[] | select((.name // "") | startswith($prefix))] | sort_by(.created // "") | last.name // ""') - if [ -z "${target}" ] || [ "${target}" = "null" ]; then - echo "no remote backup found" >&2 - exit 1 + app="{{ printf "{{ .Backup.ApplicationRef.Name }}" }}" + backup="{{ printf "{{ .Backup.Name }}" }}" + prefix="clickhouse-${app}-" + remote=$(curl -fsS ${auth} "${api}/backup/list/remote") + if [ -n "${archive}" ]; then + if ! printf '%s\n' "${remote}" | jq -es --arg name "${archive}" 'any(.[]; .name == $name)' >/dev/null; then + echo "archive ${archive} recorded on Backup ${backup} is not in remote storage; not restoring any other archive" >&2 + exit 1 + fi + target="${archive}" + else + # takenAt is set after the backup Job finished, so the + # archive that Job wrote is stamped no later than it. + notafter="{{ printf `{{ .Backup.TakenAt | default "" }}` }}" + echo "WARNING: Backup ${backup} records no archive name; restoring the newest archive of ${app} stamped no later than its takenAt (${notafter}), a best-effort choice that may not be the archive this Backup was taken as" >&2 + target=$(printf '%s\n' "${remote}" | jq -rs --arg prefix "${prefix}" --arg notafter "${notafter}" ' + [.[] | select((.desc // "") | startswith("broken") | not) | .name // "" + | select(startswith($prefix) and (ltrimstr($prefix) | test("^[0-9]{8}T[0-9]{6}Z$")) and ltrimstr($prefix) <= $notafter)] + | sort | last // ""') + if [ -z "${target}" ]; then + echo "no archive of ${app} stamped no later than ${notafter} in remote storage" >&2 + exit 1 + fi fi echo "restore_remote ${target}" curl -fsS ${auth} -X POST "${api}/backup/restore_remote/${target}" >/dev/null diff --git a/packages/system/cilium/files/ipam-migration.sh b/packages/system/cilium/files/ipam-migration.sh index 002a1bf78..9345c19f6 100755 --- a/packages/system/cilium/files/ipam-migration.sh +++ b/packages/system/cilium/files/ipam-migration.sh @@ -240,10 +240,12 @@ exclude_from_kube_ovn() { fi # A pod that holds a node's current Ingress IP keeps the address after the # move, and that node keeps it in its ipcache as reserved:ingress, so the pod - # stays unreachable from there until it is recreated. - jq -r --argjson cn "$ciliumnodes" ' - ([$cn.items[] | select(.spec.ingress.ipv4) | {key: .spec.ingress.ipv4, value: .metadata.name}] | from_entries) as $ingress - | .[] | select($ingress[.ip]) | "\(.name) \(.ip) \($ingress[.ip])"' <<<"$ipobjects" \ + # stays unreachable from there until it is recreated. The CiliumNode list goes + # in on stdin, because the Node labels Cilium copies onto every CiliumNode take + # it past the 128 KiB a single argument may hold within a handful of nodes. + jq -rn 'input as $cn + | ([$cn.items[] | select(.spec.ingress.ipv4) | {key: .spec.ingress.ipv4, value: .metadata.name}] | from_entries) as $ingress + | input[] | select($ingress[.ip]) | "\(.name) \(.ip) \($ingress[.ip])"' <<<"$ciliumnodes"$'\n'"$ipobjects" \ | while read -r ipname ip node; do if ! in_any "$POOL" "$ip"; then log "$ipname holds $ip, the Ingress IP of $node before the move. Recreate it once the run is done, $node keeps that address as reserved:ingress" diff --git a/packages/system/cozystack-basics/templates/clusterroles.yaml b/packages/system/cozystack-basics/templates/clusterroles.yaml index 973171a8e..a979ce66f 100644 --- a/packages/system/cozystack-basics/templates/clusterroles.yaml +++ b/packages/system/cozystack-basics/templates/clusterroles.yaml @@ -213,6 +213,17 @@ metadata: labels: rbac.cozystack.io/aggregate-to-tenant-admin: "true" rules: +# virtctl reads both the disk PVC and CDI's dynamically named PVC Prime. +- apiGroups: [""] + resources: + - persistentvolumeclaims + verbs: + - get +- apiGroups: ["upload.cdi.kubevirt.io"] + resources: + - uploadtokenrequests + verbs: + - create - apiGroups: [""] resources: - pods @@ -288,11 +299,18 @@ metadata: labels: rbac.cozystack.io/aggregate-to-tenant-super-admin: "true" rules: +{{- /* Read-only. A VirtualMachine written directly is sized outside any + application, and every legitimate change already has a route: VMInstance + values for size, disks and networking, the subresources granted at the use + level for power and console. watch backs the dashboard's live power state, + which watches the VM rather than polling it. */}} - apiGroups: ["kubevirt.io"] resources: - virtualmachines verbs: - - '*' + - get + - list + - watch - apiGroups: ["apps.cozystack.io"] resources: - '*' diff --git a/packages/system/cozystack-basics/tests/cdi_upload_rbac_test.yaml b/packages/system/cozystack-basics/tests/cdi_upload_rbac_test.yaml new file mode 100644 index 000000000..b99df44bf --- /dev/null +++ b/packages/system/cozystack-basics/tests/cdi_upload_rbac_test.yaml @@ -0,0 +1,97 @@ +suite: tenant admin CDI upload RBAC + +templates: + - templates/clusterroles.yaml + +release: + name: cozystack-basics + namespace: cozy-system + +tests: + - it: lets tenant admins inspect upload PVCs and create CDI upload tokens + documentSelector: + path: metadata.name + value: cozy:tenant:admin:base + asserts: + - equal: + path: metadata.labels["rbac.cozystack.io/aggregate-to-tenant-admin"] + value: "true" + - contains: + path: rules + content: + apiGroups: [""] + resources: ["persistentvolumeclaims"] + verbs: ["get"] + - contains: + path: rules + content: + apiGroups: ["upload.cdi.kubevirt.io"] + resources: ["uploadtokenrequests"] + verbs: ["create"] + + - it: keeps the admin grant out of the use, view and service-account aggregation + documentSelector: + path: metadata.name + value: cozy:tenant:admin:base + asserts: + - notExists: + path: metadata.labels["rbac.cozystack.io/aggregate-to-tenant-use"] + - notExists: + path: metadata.labels["rbac.cozystack.io/aggregate-to-tenant-view"] + - notExists: + path: metadata.labels["rbac.cozystack.io/aggregate-to-tenant"] + + - it: does not grant CDI upload permissions to the use tier + documentSelector: + path: metadata.name + value: cozy:tenant:use:base + asserts: + - notContains: + path: rules + content: + apiGroups: [""] + resources: ["persistentvolumeclaims"] + verbs: ["get"] + - notContains: + path: rules + content: + apiGroups: ["upload.cdi.kubevirt.io"] + resources: ["uploadtokenrequests"] + verbs: ["create"] + + - it: aggregates upload permissions through admin into super-admin + documentSelector: + path: metadata.name + value: cozy:tenant:admin + asserts: + - equal: + path: metadata.labels["rbac.cozystack.io/aggregate-to-tenant-super-admin"] + value: "true" + - contains: + path: aggregationRule.clusterRoleSelectors + content: + matchLabels: + rbac.cozystack.io/aggregate-to-tenant-admin: "true" + + - it: selects admin permissions for super-admin + documentSelector: + path: metadata.name + value: cozy:tenant:super-admin + asserts: + - contains: + path: aggregationRule.clusterRoleSelectors + content: + matchLabels: + rbac.cozystack.io/aggregate-to-tenant-super-admin: "true" + + - it: does not grant CDI upload token creation to the view tier + documentSelector: + path: metadata.name + value: cozy:tenant:view:base + asserts: + - notContains: + path: rules + content: + apiGroups: ["upload.cdi.kubevirt.io"] + resources: ["uploadtokenrequests"] + verbs: ["create"] diff --git a/packages/system/cozystack-basics/tests/clusterroles-tenant-super-admin_test.yaml b/packages/system/cozystack-basics/tests/clusterroles-tenant-super-admin_test.yaml new file mode 100644 index 000000000..b077d9959 --- /dev/null +++ b/packages/system/cozystack-basics/tests/clusterroles-tenant-super-admin_test.yaml @@ -0,0 +1,32 @@ +suite: cozystack-basics tenant super-admin cannot write a raw VirtualMachine + +templates: + - templates/clusterroles.yaml + +release: + name: cozystack-basics + namespace: cozy-system + +# A kubevirt.io VirtualMachine written directly is sized outside any +# application, so the super-admin keeps read and watch on it and nothing else. +# The cluster-side check, after every aggregated role is folded in, is the +# allowlist test in hack/e2e-install-cozystack.bats; this one fails earlier, on +# the unit lane, for the role that carried the grant. +tests: + - it: cozy:tenant:super-admin:base grants read and watch only on kubevirt.io virtualmachines + documentSelector: + path: metadata.name + value: cozy:tenant:super-admin:base + asserts: + - contains: + path: rules + content: + apiGroups: ["kubevirt.io"] + resources: ["virtualmachines"] + verbs: ["get", "list", "watch"] + - notContains: + path: rules + content: + apiGroups: ["kubevirt.io"] + resources: ["virtualmachines"] + verbs: ["*"] diff --git a/packages/system/cozystack-controller/templates/rbac.yaml b/packages/system/cozystack-controller/templates/rbac.yaml index b53e00216..630ed17df 100644 --- a/packages/system/cozystack-controller/templates/rbac.yaml +++ b/packages/system/cozystack-controller/templates/rbac.yaml @@ -26,10 +26,12 @@ rules: resources: ["namespaces"] verbs: ["get", "list", "watch", "patch", "update"] # TenantQuotaReconciler manages the per-namespace "tenant-quota-allocated" -# ResourceQuota that enforces each tenant's share of its parent pool, and emits -# events on the tenant namespace when sub-tenant quotas overcommit the budget. +# ResourceQuota that enforces each tenant's share of its parent pool, copies the +# pool root's "tenant-range-limits" LimitRange into unbounded members as +# "tenant-range-limits-allocated", and emits events on the tenant namespace when +# sub-tenant quotas overcommit the budget. - apiGroups: [""] - resources: ["resourcequotas"] + resources: ["resourcequotas", "limitranges"] verbs: ["get", "list", "watch", "create", "update", "patch", "delete"] - apiGroups: [""] resources: ["events"] diff --git a/packages/system/dashboard/images/console/apps/console/src/lib/links.test.ts b/packages/system/dashboard/images/console/apps/console/src/lib/links.test.ts new file mode 100644 index 000000000..84ae4ed2a --- /dev/null +++ b/packages/system/dashboard/images/console/apps/console/src/lib/links.test.ts @@ -0,0 +1,33 @@ +import { describe, it, expect } from "vitest" +import type { MouseEvent } from "react" +import { navigatesThisTab } from "./links.ts" + +function click(overrides: Partial = {}): MouseEvent { + return { + button: 0, + metaKey: false, + altKey: false, + ctrlKey: false, + shiftKey: false, + ...overrides, + } as MouseEvent +} + +describe("navigatesThisTab", () => { + it("accepts a plain primary click", () => { + expect(navigatesThisTab(click())).toBe(true) + }) + + // Each of these hands the navigation to a new tab or window, so the tab the + // click happened in keeps whatever tenant it was showing. + it.each(["metaKey", "ctrlKey", "shiftKey", "altKey"] as const)( + "refuses a click modified with %s", + (modifier) => { + expect(navigatesThisTab(click({ [modifier]: true }))).toBe(false) + }, + ) + + it("refuses a non-primary button", () => { + expect(navigatesThisTab(click({ button: 1 }))).toBe(false) + }) +}) diff --git a/packages/system/dashboard/images/console/apps/console/src/lib/links.ts b/packages/system/dashboard/images/console/apps/console/src/lib/links.ts new file mode 100644 index 000000000..c6dc28599 --- /dev/null +++ b/packages/system/dashboard/images/console/apps/console/src/lib/links.ts @@ -0,0 +1,13 @@ +import type { MouseEvent } from "react" + +/** + * Whether a click on an anchor will navigate the tab it happened in, rather + * than open a new tab or window. React runs `onClick` either way, and a + * cross-tenant link's handler aligns the tenant context of the tab it is + * leaving — which is wrong when that tab is staying where it is. Same button + * and modifier test react-router's own `Link` applies before it intercepts a + * click, minus the `target` check these links have no attribute for. + */ +export function navigatesThisTab(e: MouseEvent): boolean { + return e.button === 0 && !e.metaKey && !e.altKey && !e.ctrlKey && !e.shiftKey +} diff --git a/packages/system/dashboard/images/console/apps/console/src/lib/tenant-tree.test.ts b/packages/system/dashboard/images/console/apps/console/src/lib/tenant-tree.test.ts new file mode 100644 index 000000000..bf48ae03c --- /dev/null +++ b/packages/system/dashboard/images/console/apps/console/src/lib/tenant-tree.test.ts @@ -0,0 +1,59 @@ +import { describe, it, expect } from "vitest" +import type { TenantNamespace } from "@cozystack/types" +import { realParentNamespace } from "./tenant-tree.ts" + +function tn(name: string, ancestors: string[]): TenantNamespace { + const labels: Record = {} + for (const a of [...ancestors, name]) labels[`tenant.cozystack.io/${a}`] = "" + return { + apiVersion: "core.cozystack.io/v1alpha1", + kind: "TenantNamespace", + metadata: { name, labels }, + } as TenantNamespace +} + +describe("realParentNamespace", () => { + it("takes the deepest ancestor that prefixes the namespace", () => { + // The full chain is on the labels; only the longest prefix is the parent. + expect( + realParentNamespace( + tn("tenant-acme-eu-dev", ["tenant-root", "tenant-acme", "tenant-acme-eu"]), + ), + ).toBe("tenant-acme-eu") + }) + + it("names an inaccessible parent, which is the point of asking", () => { + // Visibility is the caller's problem: the CR of a bridged row lives in a + // namespace the user may not read, and the caller has to be able to tell. + expect( + realParentNamespace(tn("tenant-acme-eu", ["tenant-root", "tenant-acme"])), + ).toBe("tenant-acme") + }) + + it("resolves a tenant ordered directly in the root", () => { + // A tenant `acme` created in `tenant-root` owns `tenant-acme`, not + // `tenant-root-acme`, so the prefix rule alone leaves every top-level + // tenant — most tenants on a normal cluster — looking parentless. + expect(realParentNamespace(tn("tenant-acme", ["tenant-root"]))).toBe( + "tenant-root", + ) + }) + + it("does not mistake a root-level name that starts with root", () => { + // `tenant-root-x` is the tenant `root-x` ordered in the root, and the + // prefix branch answers with the same parent the label does. + expect(realParentNamespace(tn("tenant-root-x", ["tenant-root"]))).toBe( + "tenant-root", + ) + }) + + it("has no parent for the hierarchy root", () => { + expect(realParentNamespace(tn("tenant-root", []))).toBeUndefined() + }) + + it("has no parent when the ancestor labels are gone", () => { + // A TenantNamespace carrying only its own label is either the root or + // mislabelled; either way there is no CR namespace to derive. + expect(realParentNamespace(tn("tenant-acme", []))).toBeUndefined() + }) +}) diff --git a/packages/system/dashboard/images/console/apps/console/src/lib/tenant-tree.ts b/packages/system/dashboard/images/console/apps/console/src/lib/tenant-tree.ts index a8f474bf9..8f16b583d 100644 --- a/packages/system/dashboard/images/console/apps/console/src/lib/tenant-tree.ts +++ b/packages/system/dashboard/images/console/apps/console/src/lib/tenant-tree.ts @@ -1,4 +1,5 @@ import type { TenantNamespace } from "@cozystack/types" +import { ROOT_TENANT_NAMESPACE } from "./constants.ts" import { tenantDisplayName } from "./tenant-context.tsx" const ANCESTOR_LABEL_PREFIX = "tenant.cozystack.io/" @@ -76,11 +77,18 @@ export function flattenTenantForest( /** * Row label relative to the visible parent: `tenant-whmcs-crpjxhwm` under * `tenant-whmcs` shows as `crpjxhwm`. Forest roots keep their full display - * name — there is no parent on screen to be relative to. + * name — there is no parent on screen to be relative to, and neither do the + * root's own children, whose namespace never carries the parent's name: under + * `tenant-root` the tenant `root-x` owns `tenant-root-x`, and stripping the + * prefix there would label it `x` while its CR is `root-x`. */ export function relativeTenantName(node: TenantTreeNode): string { const ns = node.tn.metadata.name - if (node.parentNs && ns.startsWith(`${node.parentNs}-`)) { + if ( + node.parentNs && + node.parentNs !== ROOT_TENANT_NAMESPACE && + ns.startsWith(`${node.parentNs}-`) + ) { return ns.slice(node.parentNs.length + 1) } return tenantDisplayName(node.tn) @@ -96,7 +104,16 @@ export function relativeTenantName(node: TenantTreeNode): string { */ export function realParentNamespace(tn: TenantNamespace): string | undefined { const ns = tn.metadata.name - return ancestorNamespaces(tn) + const ancestors = ancestorNamespaces(tn) + const nested = ancestors .filter((ancestor) => ns.startsWith(`${ancestor}-`)) .sort((a, b) => b.length - a.length)[0] + if (nested) return nested + // The root is the one level the naming rule skips: a tenant `x` ordered in + // `tenant-root` owns `tenant-x`, not `tenant-root-x`, so the prefix test + // never matches and every top-level tenant — most tenants on a normal + // cluster — looked parentless. The ancestor labels still say otherwise. + return ancestors.includes(ROOT_TENANT_NAMESPACE) + ? ROOT_TENANT_NAMESPACE + : undefined } diff --git a/packages/system/dashboard/images/console/apps/console/src/routes/TenantsPage.test.tsx b/packages/system/dashboard/images/console/apps/console/src/routes/TenantsPage.test.tsx index 78d61696d..86eb5e58f 100644 --- a/packages/system/dashboard/images/console/apps/console/src/routes/TenantsPage.test.tsx +++ b/packages/system/dashboard/images/console/apps/console/src/routes/TenantsPage.test.tsx @@ -1,13 +1,14 @@ import { describe, it, expect, vi, beforeAll } from "vitest" -import { screen } from "@testing-library/react" +import { fireEvent, screen } from "@testing-library/react" import userEvent from "@testing-library/user-event" +import { useLocation } from "react-router" import { K8sClient, type K8sList, type APIGroupList, } from "@cozystack/k8s-client" import { TenantsPage } from "./TenantsPage.tsx" -import { TenantProvider } from "../lib/tenant-context.tsx" +import { TenantProvider, useTenantContext } from "../lib/tenant-context.tsx" import { SELECTED_TENANT_KEY } from "../lib/constants.ts" import { renderWithK8sProvider } from "../test-utils/render.tsx" @@ -30,10 +31,19 @@ const VISIBLE = [ tn("tenant-whmcs-a-b", ["tenant-root", "tenant-whmcs", "tenant-whmcs-a"]), ] -function makeClient(): K8sClient { +function LocationProbe() { + const { pathname } = useLocation() + return
{pathname}
+} + +function SelectedTenant() { + return {useTenantContext().selectedTenant} +} + +function makeClient(tenants: unknown[] = VISIBLE): K8sClient { const client = new K8sClient() vi.spyOn(client, "list").mockImplementation(async (_g, _v, plural) => { - const items = plural === "tenantnamespaces" ? VISIBLE : [] + const items = plural === "tenantnamespaces" ? tenants : [] return { apiVersion: "v1", kind: `${plural}List`, @@ -89,6 +99,12 @@ describe("TenantsPage tree", () => { expect(editButtons).toHaveLength(1) expect(screen.getByTitle("Edit tenant whmcs-x")).toBeInTheDocument() expect(screen.queryByTitle("Edit tenant whmcs-a-b")).not.toBeInTheDocument() + + // The name links to the detail page, where Delete is, exactly where Edit is + // offered: a row whose CR namespace cannot be read stays plain text. + expect(screen.getByRole("link", { name: "x" })).toHaveAttribute("href", "/admin/tenants/x") + expect(screen.queryByRole("link", { name: "a-b" })).toBeNull() + expect(screen.queryByRole("link", { name: "whmcs" })).toBeNull() }) it("collapses a subtree via the row toggle", async () => { @@ -109,3 +125,131 @@ describe("TenantsPage tree", () => { expect(await screen.findByText("x")).toBeInTheDocument() }) }) + +// Tenants ordered directly in the root are the common case on a normal +// cluster, and they are the one level the hierarchical namespace naming skips: +// `acme` created in `tenant-root` owns `tenant-acme`, not `tenant-root-acme`. +const ROOT_VISIBLE = [ + tn("tenant-root", []), + tn("tenant-acme", ["tenant-root"]), + tn("tenant-acme-eu", ["tenant-root", "tenant-acme"]), + // A root-level tenant whose own name starts with `root`, which is the case + // that makes "strip the parent's prefix" the wrong rule rather than merely + // an incomplete one. + tn("tenant-root-x", ["tenant-root"]), +] + +function renderTenants(tenants: unknown[], selected: string) { + localStorage.setItem(SELECTED_TENANT_KEY, selected) + renderWithK8sProvider( + + + + + , + { client: makeClient(tenants), initialRoute: "/admin/tenants" }, + ) +} + +describe("TenantsPage under a visible root", () => { + it("offers Edit on a tenant ordered directly in the root", async () => { + renderTenants(ROOT_VISIBLE, "root") + + await userEvent.click(await screen.findByTitle("Edit tenant acme")) + + expect(screen.getByTestId("location")).toHaveTextContent("/admin/tenants/acme/edit") + }) + + it("names a nested tenant's CR relative to its parent", async () => { + renderTenants(ROOT_VISIBLE, "root") + + await userEvent.click(await screen.findByTitle("Edit tenant acme-eu")) + + expect(screen.getByTestId("location")).toHaveTextContent("/admin/tenants/eu/edit") + }) + + // `tenant-root-x` is the tenant `root-x`, not the tenant `x`: the row label + // and the CR the row opens have to agree on that. + it("keeps a root-level tenant named root-x whole", async () => { + renderTenants(ROOT_VISIBLE, "root") + + expect(await screen.findByText("root-x")).toBeInTheDocument() + await userEvent.click(screen.getByTitle("Edit tenant root-x")) + + expect(screen.getByTestId("location")).toHaveTextContent("/admin/tenants/root-x/edit") + }) +}) + +// A forest root that carries no ancestor labels is self-referential: its CR +// lives in its own namespace, and deriving the CR name must not subtract the +// node's own name from itself and leave nothing. +describe("TenantsPage self-referential root", () => { + it("names the CR of a root that is not tenant-root", async () => { + renderTenants([tn("tenant-whmcs", [])], "whmcs") + + await userEvent.click(await screen.findByTitle("Edit tenant whmcs")) + + expect(screen.getByTestId("location")).toHaveTextContent("/admin/tenants/whmcs/edit") + }) +}) + +describe("TenantsPage row link", () => { + it("links every row whose Tenant CR it can name", async () => { + renderTenants(ROOT_VISIBLE, "root") + + // The root's CR is self-referential: `root` inside its own namespace. + expect(await screen.findByRole("link", { name: "root" })).toHaveAttribute( + "href", + "/admin/tenants/root", + ) + expect(screen.getByRole("link", { name: "acme" })).toHaveAttribute("href", "/admin/tenants/acme") + expect(screen.getByRole("link", { name: "eu" })).toHaveAttribute("href", "/admin/tenants/eu") + expect(screen.getByRole("link", { name: "root-x" })).toHaveAttribute( + "href", + "/admin/tenants/root-x", + ) + }) + + it("links a self-referential root to its own CR", async () => { + renderTenants([tn("tenant-whmcs", [])], "whmcs") + + expect(await screen.findByRole("link", { name: "whmcs" })).toHaveAttribute( + "href", + "/admin/tenants/whmcs", + ) + }) + + // The detail page resolves `eu` in the selected tenant's namespace, and eu's + // CR lives in acme's, so the click has to land the tab on acme. + it("switches to the row's parent and opens the detail page", async () => { + renderTenants(ROOT_VISIBLE, "root") + + fireEvent.click(await screen.findByRole("link", { name: "eu" })) + + expect(screen.getByTestId("selected-tenant").textContent).toBe("acme") + expect(screen.getByTestId("location")).toHaveTextContent("/admin/tenants/eu") + }) + + // Edit shares the route with the link, and its form resolves the CR the same + // way, so it has to land on the parent too. + it("switches to the row's parent before opening the edit form", async () => { + renderTenants(ROOT_VISIBLE, "root") + + await userEvent.click(await screen.findByTitle("Edit tenant acme-eu")) + + expect(screen.getByTestId("selected-tenant").textContent).toBe("acme") + }) + + // A ctrl-click opens a new tab; the tab it happened in stays where it is. + it("leaves the current tab alone on a ctrl-click", async () => { + renderTenants(ROOT_VISIBLE, "root") + const link = await screen.findByRole("link", { name: "eu" }) + // jsdom cannot open the new tab; the handler under test has run by then. + link.addEventListener("click", (e) => e.preventDefault()) + + fireEvent.click(link, { ctrlKey: true }) + + expect(screen.getByTestId("selected-tenant").textContent).toBe("root") + expect(screen.getByTestId("location")).toHaveTextContent(/^\/admin\/tenants$/) + }) +}) diff --git a/packages/system/dashboard/images/console/apps/console/src/routes/TenantsPage.tsx b/packages/system/dashboard/images/console/apps/console/src/routes/TenantsPage.tsx index 2366ee320..3944467f4 100644 --- a/packages/system/dashboard/images/console/apps/console/src/routes/TenantsPage.tsx +++ b/packages/system/dashboard/images/console/apps/console/src/routes/TenantsPage.tsx @@ -1,5 +1,5 @@ import { useMemo, useState } from "react" -import { useNavigate } from "react-router" +import { Link, useNavigate } from "react-router" import { Plus, Edit, Info, ChevronDown, ChevronRight, CornerDownRight } from "lucide-react" import { Spinner, Section, Button } from "@cozystack/ui" import { useK8sList } from "@cozystack/k8s-client" @@ -13,7 +13,8 @@ import { relativeTenantName, type TenantTreeNode, } from "../lib/tenant-tree.ts" -import { TENANT_NAMESPACE_PREFIX } from "../lib/constants.ts" +import { ROOT_TENANT_NAMESPACE, TENANT_NAMESPACE_PREFIX } from "../lib/constants.ts" +import { navigatesThisTab } from "../lib/links.ts" import { formatAge } from "../lib/status.ts" import { TenantQuotaCompact } from "../components/QuotaDisplay.tsx" import type { ResourceQuota } from "../components/QuotaDisplay.tsx" @@ -34,11 +35,17 @@ type TreeNode = TenantTreeNode /** * The Tenant CR of a namespace lives in its parent's namespace under the * short name: `tenant-whmcs-jzmnbwum` under `tenant-whmcs` is CR `jzmnbwum`. - * Root-level children (`tenant-kvaps` under `tenant-root`) collapse to the - * same rule via the plain `tenant-` prefix strip. + * Under the root the naming rule drops a level — a tenant `kvaps` ordered in + * `tenant-root` owns `tenant-kvaps` — so there the CR name is the plain + * prefix strip, which also names the root's own self-referential CR (`root`). + * Excluding the root from the prefix branch rather than dropping the branch + * keeps two things right at once: a root-level tenant called `root-x` + * resolves to the CR `root-x` and not `x`, and a self-referential node whose + * namespace is not `tenant-root` still names itself instead of the empty + * string that subtracting its own name would leave. */ function tenantCrName(ns: string, parentNs: string): string { - return ns.startsWith(`${parentNs}-`) + return parentNs !== ROOT_TENANT_NAMESPACE && ns.startsWith(`${parentNs}-`) ? ns.slice(parentNs.length + 1) : ns.slice(TENANT_NAMESPACE_PREFIX.length) } @@ -125,8 +132,8 @@ export function TenantsPage() { // A node's Tenant CR lives in its REAL parent's namespace, which is not // necessarily the parent it hangs under: a node whose real parent is // inaccessible is bridged onto the nearest visible ancestor. Deriving the CR - // from that bridged ancestor names a CR that does not exist, so the edit - // target comes from realParentNamespace instead — and is offered only when + // from that bridged ancestor names a CR that does not exist, so Tenant CR + // routes come from realParentNamespace instead — and are offered only when // that namespace is actually readable, since otherwise there is no CR the // user could open. The hierarchy root (no ancestor labels at all) is // self-referential: its CR (`root`) lives in its own namespace. @@ -137,12 +144,20 @@ export function TenantsPage() { const real = realParentNamespace(node.tn) return real && visibleNs.has(real) ? real : undefined } - const canEdit = (node: TreeNode) => !!editParentNs(node) - const editNode = (node: TreeNode) => { + const tenantRoute = (node: TreeNode) => { const parentNs = editParentNs(node) - if (!parentNs) return - selectTenant(parentNs.slice(TENANT_NAMESPACE_PREFIX.length)) - navigate(`${basePath}/tenants/${tenantCrName(node.tn.metadata.name, parentNs)}/edit`) + if (!parentNs) return undefined + return { + parentTenant: parentNs.slice(TENANT_NAMESPACE_PREFIX.length), + path: `${basePath}/tenants/${tenantCrName(node.tn.metadata.name, parentNs)}`, + } + } + const canEdit = (node: TreeNode) => !!tenantRoute(node) + const editNode = (node: TreeNode) => { + const route = tenantRoute(node) + if (!route) return + selectTenant(route.parentTenant) + navigate(`${route.path}/edit`) } return ( @@ -183,6 +198,7 @@ export function TenantsPage() { const modules = modulesByNamespace.get(ns) ?? [] const tenantQuotas = quotasByNamespace.get(ns) ?? [] const host = node.tn.metadata.labels?.[HOST_LABEL] + const route = tenantRoute(node) return ( @@ -207,9 +223,26 @@ export function TenantsPage() { ) : null}
-

- {relativeTenantName(node)} -

+ {route ? ( + { + if (!navigatesThisTab(e)) return + selectTenant(route.parentTenant) + }} + className="block truncate text-sm font-medium text-slate-900 hover:underline" + > + {relativeTenantName(node)} + + ) : ( +

+ {relativeTenantName(node)} +

+ )}

{ns}

diff --git a/packages/system/harbor/templates/database.yaml b/packages/system/harbor/templates/database.yaml index 9a9486017..d33f63678 100644 --- a/packages/system/harbor/templates/database.yaml +++ b/packages/system/harbor/templates/database.yaml @@ -6,8 +6,8 @@ metadata: spec: instances: {{ .Values.db.replicas }} {{- $existingCluster := lookup "postgresql.cnpg.io/v1" "Cluster" .Release.Namespace (printf "%s-db" .Values.harbor.fullnameOverride) }} - {{- $image := dig "spec" "imageName" "ghcr.io/cloudnative-pg/postgresql:17.7-standard-trixie" $existingCluster }} - imageName: {{ if regexMatch ":17\\." $image }}ghcr.io/cloudnative-pg/postgresql:17.7-standard-trixie{{ else if regexMatch ":[0-9]+\\.[0-9]+$" $image }}{{ printf "%s-standard-trixie" $image }}{{ else }}{{ $image }}{{ end }} + {{- $image := dig "spec" "imageName" "ghcr.io/cloudnative-pg/postgresql:17.12-standard-trixie" $existingCluster }} + imageName: {{ if regexMatch ":17\\." $image }}ghcr.io/cloudnative-pg/postgresql:17.12-standard-trixie{{ else if regexMatch ":[0-9]+\\.[0-9]+$" $image }}{{ printf "%s-standard-trixie" $image }}{{ else }}{{ $image }}{{ end }} storage: size: {{ .Values.db.size }} {{- with .Values.db.storageClass }} diff --git a/packages/system/ingress-nginx/tests/client_keepalive_time_test.yaml b/packages/system/ingress-nginx/tests/client_keepalive_time_test.yaml new file mode 100644 index 000000000..bb492e57c --- /dev/null +++ b/packages/system/ingress-nginx/tests/client_keepalive_time_test.yaml @@ -0,0 +1,26 @@ +suite: ingress-nginx client keepalive_time +release: + name: ingress-nginx + namespace: cozy-ingress-nginx +templates: + - charts/ingress-nginx/templates/controller-configmap.yaml +tests: + - it: raises the client keepalive_time above the nginx 1h default + asserts: + - equal: + path: data.http-snippet + value: keepalive_time 12h; + - it: keeps the snippet when a tenant ingress sets its own config keys + # The tenant ingress HelmRelease passes controller.config for whitelist, + # Cloudflare and PROXY protocol; Helm merges maps, so those keys must not + # drop the default snippet. + set: + ingress-nginx.controller.config.use-proxy-protocol: "true" + ingress-nginx.controller.config.whitelist-source-range: 10.0.0.0/8 + asserts: + - equal: + path: data.http-snippet + value: keepalive_time 12h; + - equal: + path: data.use-proxy-protocol + value: "true" diff --git a/packages/system/ingress-nginx/values.yaml b/packages/system/ingress-nginx/values.yaml index 68436f51f..672c7688b 100644 --- a/packages/system/ingress-nginx/values.yaml +++ b/packages/system/ingress-nginx/values.yaml @@ -46,7 +46,19 @@ ingress-nginx: upstream-keepalive-time: '1m' upstream-keepalive-timeout: "60" upstream-keepalive-connections: "320" - ssl-session-tickets: "true" + # Off for CVE-2026-97629: with tickets on and no ssl-session-ticket-key, + # nginx rotates its ticket keys and before 1.30.6 leaves one of them + # uninitialized in the workers. Resumption keeps working through the + # shared session cache; with no fixed key each pod had its own ticket + # keys, so tickets never resumed across replicas anyway. + ssl-session-tickets: "false" + # Client-side keepalive_time has no ConfigMap key, so nginx keeps its + # 1h default and sends GOAWAY to any HTTP/2 connection older than that. + # A long S3 operation (kopia maintenance behind Velero) multiplexes its + # requests over one connection, and the in-flight object listing fails + # instead of being retried. Idle connections still close after + # keep-alive (75s). + http-snippet: "keepalive_time 12h;" resources: limits: cpu: "1" diff --git a/packages/system/kamaji/images/kamaji/patches/fix-kubelet-config-compat.diff b/packages/system/kamaji/images/kamaji/patches/fix-kubelet-config-compat.diff index ceb10686b..53d1f6c2f 100644 --- a/packages/system/kamaji/images/kamaji/patches/fix-kubelet-config-compat.diff +++ b/packages/system/kamaji/images/kamaji/patches/fix-kubelet-config-compat.diff @@ -1,8 +1,16 @@ diff --git a/internal/kubeadm/uploadconfig.go b/internal/kubeadm/uploadconfig.go -index 89c9b54..1ee38cd 100644 +index e8bbd58..2e52b6a 100644 --- a/internal/kubeadm/uploadconfig.go +++ b/internal/kubeadm/uploadconfig.go -@@ -41,7 +41,7 @@ func UploadKubeletConfig(client kubernetes.Interface, config *Configuration, pat +@@ -11,6 +11,7 @@ import ( + corev1 "k8s.io/api/core/v1" + rbacv1 "k8s.io/api/rbac/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ++ "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/client-go/kubernetes" + kubelettypes "k8s.io/kubelet/config/v1beta1" + kubeadmconstants "k8s.io/kubernetes/cmd/kubeadm/app/constants" +@@ -41,7 +42,7 @@ func UploadKubeletConfig(client kubernetes.Interface, config *Configuration, pat TenantControlPlaneCgroupDriver: config.Parameters.TenantControlPlaneCGroupDriver, } @@ -11,22 +19,34 @@ index 89c9b54..1ee38cd 100644 if err != nil { return nil, err } -@@ -72,7 +72,13 @@ func UploadKubeletConfig(client kubernetes.Interface, config *Configuration, pat +@@ -72,7 +73,25 @@ func UploadKubeletConfig(client kubernetes.Interface, config *Configuration, pat return nil, nil } -func getKubeletConfigmapContent(kubeletConfiguration KubeletConfiguration, patch jsonpatchv5.Patch) ([]byte, error) { -+// minVerKubeletNewDefaults is the minimum Kubernetes version that supports the -+// CrashLoopBackOff and ImagePullCredentialsVerificationPolicy kubelet -+// configuration fields (gated by KubeletCrashLoopBackOffMax and -+// KubeletEnsureSecretPulledImages feature gates respectively). ++// minVerKubeletNewDefaults is the first Kubernetes version whose kubelet ++// accepts the CrashLoopBackOff and ImagePullCredentialsVerificationPolicy ++// defaults without enabling the KubeletCrashLoopBackOffMax and ++// KubeletEnsureSecretPulledImages feature gates. +var minVerKubeletNewDefaults = semver.MustParse("1.35.0") + ++// kubeletConfigFieldsMinVersion maps the KubeletConfiguration fields Kamaji ++// emits by default to the first Kubernetes release whose kubelet config API ++// knows them: older kubelets and kubeadm fail strict decoding on them. ++// A pre-release compares below its minor and loses that minor's fields, which ++// its early alphas do not have yet. ++// Tenants older than v1.31 would need more entries, starting with failCgroupV1. ++var kubeletConfigFieldsMinVersion = map[string]semver.Version{ ++ "crashLoopBackOff": semver.MustParse("1.32.0"), ++ "mergeDefaultEvictionSettings": semver.MustParse("1.33.0"), ++ "memoryReservationPolicy": semver.MustParse("1.36.0"), ++} ++ +func getKubeletConfigmapContent(kubeletConfiguration KubeletConfiguration, patch jsonpatchv5.Patch, version string) ([]byte, error) { var kc kubelettypes.KubeletConfiguration kubeletv1beta1.SetDefaults_KubeletConfiguration(&kc) -@@ -94,6 +100,20 @@ func getKubeletConfigmapContent(kubeletConfiguration KubeletConfiguration, patch +@@ -89,6 +108,20 @@ func getKubeletConfigmapContent(kubeletConfiguration KubeletConfiguration, patch // determine the resolvConf location, as reported in clastix/kamaji#581. kc.ResolverConfig = nil @@ -47,3 +67,155 @@ index 89c9b54..1ee38cd 100644 if len(patch) > 0 { kubeletConfig, patchErr := utilities.EncodeToJSON(&kc) if patchErr != nil { +@@ -105,7 +138,25 @@ func getKubeletConfigmapContent(kubeletConfiguration KubeletConfiguration, patch + } + } + +- return utilities.EncodeToYaml(&kc) ++ // Non-pointer struct fields survive zeroing and the JSON patch round trip, ++ // so the fields are dropped from the encoded object instead. ++ content, err := utilities.EncodeToJSON(&kc) ++ if err != nil { ++ return nil, fmt.Errorf("unable to encode KubeletConfiguration to JSON: %w", err) ++ } ++ ++ var u unstructured.Unstructured ++ if err = u.UnmarshalJSON(content); err != nil { ++ return nil, fmt.Errorf("unable to decode KubeletConfiguration JSON: %w", err) ++ } ++ ++ for field, minVer := range kubeletConfigFieldsMinVersion { ++ if parsedVer.LT(minVer) { ++ unstructured.RemoveNestedField(u.Object, field) ++ } ++ } ++ ++ return utilities.EncodeToYaml(&u) + } + + func createConfigMapRBACRules(client kubernetes.Interface, configMapName string) error { +diff --git a/internal/kubeadm/uploadconfig_test.go b/internal/kubeadm/uploadconfig_test.go +new file mode 100644 +index 0000000..e5927c9 +--- /dev/null ++++ b/internal/kubeadm/uploadconfig_test.go +@@ -0,0 +1,119 @@ ++// Copyright 2022 Clastix Labs ++// SPDX-License-Identifier: Apache-2.0 ++ ++package kubeadm ++ ++import ( ++ "testing" ++ ++ jsonpatchv5 "github.com/evanphx/json-patch/v5" ++ "github.com/stretchr/testify/require" ++ metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ++ "k8s.io/client-go/kubernetes/fake" ++ kubeadmconstants "k8s.io/kubernetes/cmd/kubeadm/app/constants" ++) ++ ++func TestGetKubeletConfigmapContentFieldsByTenantVersion(t *testing.T) { ++ testCases := []struct { ++ version string ++ present []string ++ absent []string ++ }{ ++ { ++ version: "v1.31.14", ++ absent: []string{"crashLoopBackOff", "mergeDefaultEvictionSettings", "memoryReservationPolicy", "imagePullCredentialsVerificationPolicy"}, ++ }, ++ { ++ version: "v1.32.13", ++ present: []string{"crashLoopBackOff"}, ++ absent: []string{"mergeDefaultEvictionSettings", "memoryReservationPolicy", "imagePullCredentialsVerificationPolicy"}, ++ }, ++ { ++ version: "v1.33.0", ++ present: []string{"crashLoopBackOff", "mergeDefaultEvictionSettings"}, ++ absent: []string{"memoryReservationPolicy", "imagePullCredentialsVerificationPolicy"}, ++ }, ++ { ++ version: "v1.34.9", ++ present: []string{"crashLoopBackOff", "mergeDefaultEvictionSettings"}, ++ absent: []string{"memoryReservationPolicy", "imagePullCredentialsVerificationPolicy"}, ++ }, ++ { ++ version: "v1.35.0-rc.1", ++ present: []string{"crashLoopBackOff", "mergeDefaultEvictionSettings"}, ++ absent: []string{"memoryReservationPolicy", "imagePullCredentialsVerificationPolicy"}, ++ }, ++ { ++ version: "v1.35.6", ++ present: []string{"crashLoopBackOff", "mergeDefaultEvictionSettings", "imagePullCredentialsVerificationPolicy"}, ++ absent: []string{"memoryReservationPolicy"}, ++ }, ++ { ++ version: "v1.36.0-rc.1", ++ present: []string{"crashLoopBackOff", "mergeDefaultEvictionSettings", "imagePullCredentialsVerificationPolicy"}, ++ absent: []string{"memoryReservationPolicy"}, ++ }, ++ { ++ version: "v1.36.0", ++ present: []string{"crashLoopBackOff", "mergeDefaultEvictionSettings", "imagePullCredentialsVerificationPolicy", "memoryReservationPolicy"}, ++ }, ++ { ++ version: "v1.37.0", ++ present: []string{"crashLoopBackOff", "mergeDefaultEvictionSettings", "imagePullCredentialsVerificationPolicy", "memoryReservationPolicy"}, ++ }, ++ } ++ ++ for _, testCase := range testCases { ++ t.Run(testCase.version, func(t *testing.T) { ++ content, err := getKubeletConfigmapContent(KubeletConfiguration{}, nil, testCase.version) ++ require.NoError(t, err) ++ ++ for _, field := range testCase.present { ++ require.Regexp(t, `(?m)^`+field+`:`, string(content)) ++ } ++ ++ for _, field := range testCase.absent { ++ require.NotRegexp(t, `(?m)^`+field+`:`, string(content)) ++ } ++ }) ++ } ++} ++ ++func TestGetKubeletConfigmapContentCrashLoopBackOffByTenantVersion(t *testing.T) { ++ for _, version := range []string{"v1.34.9", "v1.35.0-rc.1"} { ++ content, err := getKubeletConfigmapContent(KubeletConfiguration{}, nil, version) ++ require.NoError(t, err) ++ require.Regexp(t, `(?m)^crashLoopBackOff: \{\}$`, string(content)) ++ } ++ ++ content, err := getKubeletConfigmapContent(KubeletConfiguration{}, nil, "v1.35.0") ++ require.NoError(t, err) ++ require.Regexp(t, `(?m)^crashLoopBackOff:\n maxContainerRestartPeriod: `, string(content)) ++} ++ ++func TestUploadKubeletConfigRendersForTenantVersion(t *testing.T) { ++ client := fake.NewClientset() ++ config := &Configuration{Parameters: Parameters{TenantControlPlaneVersion: "v1.35.6"}} ++ ++ _, err := UploadKubeletConfig(client, config, nil) ++ require.NoError(t, err) ++ ++ configMap, err := client.CoreV1().ConfigMaps(metav1.NamespaceSystem).Get(t.Context(), "kubelet-config", metav1.GetOptions{}) ++ require.NoError(t, err) ++ require.NotRegexp(t, `(?m)^memoryReservationPolicy:`, configMap.Data[kubeadmconstants.KubeletBaseConfigurationConfigMapKey]) ++} ++ ++func TestGetKubeletConfigmapContentDropsUnknownFieldsAfterPatch(t *testing.T) { ++ patch, err := jsonpatchv5.DecodePatch([]byte(`[{"op": "add", "path": "/memoryReservationPolicy", "value": "None"}, {"op": "add", "path": "/maxPods", "value": 250}]`)) ++ require.NoError(t, err) ++ ++ content, err := getKubeletConfigmapContent(KubeletConfiguration{}, patch, "v1.35.6") ++ require.NoError(t, err) ++ require.NotRegexp(t, `(?m)^memoryReservationPolicy:`, string(content)) ++ require.Regexp(t, `(?m)^maxPods: 250$`, string(content)) ++} ++ ++func TestGetKubeletConfigmapContentInvalidVersion(t *testing.T) { ++ _, err := getKubeletConfigmapContent(KubeletConfiguration{}, nil, "not-a-version") ++ require.Error(t, err) ++} diff --git a/packages/system/keycloak-operator/Makefile b/packages/system/keycloak-operator/Makefile index e144b0245..0d28779fe 100644 --- a/packages/system/keycloak-operator/Makefile +++ b/packages/system/keycloak-operator/Makefile @@ -4,6 +4,9 @@ export NAMESPACE=cozy-keycloak include ../../../hack/common-envs.mk include ../../../hack/package.mk +test: + helm unittest . + image: docker buildx build images/keycloak-operator \ $(call image-tags,keycloak-operator,v$(COZYSTACK_VERSION)) \ diff --git a/packages/system/keycloak-operator/tests/crds_test.yaml b/packages/system/keycloak-operator/tests/crds_test.yaml new file mode 100644 index 000000000..1be3fe611 --- /dev/null +++ b/packages/system/keycloak-operator/tests/crds_test.yaml @@ -0,0 +1,19 @@ +suite: keycloak-operator CRDs declare the realm settings the platform sets +# keycloak-configure renders the cozy ClusterKeycloakRealm with spec.sessions +# and spec.organizationsEnabled, and spec.login when configured. The apiserver +# drops any field the CRD does not declare without an error, so with a chart +# that lacks them the realm never gets those settings. +includeCrds: true +templates: + - charts/keycloak-operator/crds/v1.edp.epam.com_clusterkeycloakrealms.yaml +tests: + - it: declares the session, organization and login settings + asserts: + - exists: + path: spec.versions[0].schema.openAPIV3Schema.properties.spec.properties.sessions.properties.ssoSessionSettings.properties.idleTimeout + - exists: + path: spec.versions[0].schema.openAPIV3Schema.properties.spec.properties.sessions.properties.ssoSessionSettings.properties.maxLifespan + - exists: + path: spec.versions[0].schema.openAPIV3Schema.properties.spec.properties.organizationsEnabled + - exists: + path: spec.versions[0].schema.openAPIV3Schema.properties.spec.properties.login diff --git a/packages/system/keycloak/templates/db.yaml b/packages/system/keycloak/templates/db.yaml index a8f680a6f..b0ebe98a5 100644 --- a/packages/system/keycloak/templates/db.yaml +++ b/packages/system/keycloak/templates/db.yaml @@ -5,8 +5,8 @@ metadata: spec: instances: 2 {{- $existingCluster := lookup "postgresql.cnpg.io/v1" "Cluster" .Release.Namespace "keycloak-db" }} - {{- $image := dig "spec" "imageName" "ghcr.io/cloudnative-pg/postgresql:17.7-standard-trixie" $existingCluster }} - imageName: {{ if regexMatch ":17\\." $image }}ghcr.io/cloudnative-pg/postgresql:17.7-standard-trixie{{ else if regexMatch ":[0-9]+\\.[0-9]+$" $image }}{{ printf "%s-standard-trixie" $image }}{{ else }}{{ $image }}{{ end }} + {{- $image := dig "spec" "imageName" "ghcr.io/cloudnative-pg/postgresql:17.12-standard-trixie" $existingCluster }} + imageName: {{ if regexMatch ":17\\." $image }}ghcr.io/cloudnative-pg/postgresql:17.12-standard-trixie{{ else if regexMatch ":[0-9]+\\.[0-9]+$" $image }}{{ printf "%s-standard-trixie" $image }}{{ else }}{{ $image }}{{ end }} storage: size: 20Gi {{- with .Values.database.affinity }} diff --git a/packages/system/linstor-scheduler/charts/linstor-scheduler/templates/deployment.yaml b/packages/system/linstor-scheduler/charts/linstor-scheduler/templates/deployment.yaml index 289021fd6..d08601994 100644 --- a/packages/system/linstor-scheduler/charts/linstor-scheduler/templates/deployment.yaml +++ b/packages/system/linstor-scheduler/charts/linstor-scheduler/templates/deployment.yaml @@ -3,6 +3,10 @@ apiVersion: apps/v1 kind: Deployment metadata: name: {{ include "linstor-scheduler.fullname" . }} + {{- with include "linstor-scheduler.linstorClientSecretName" . }} + annotations: + secret.reloader.stakater.com/reload: {{ . | quote }} + {{- end }} labels: {{- include "linstor-scheduler.labels" . | nindent 4 }} spec: diff --git a/packages/system/linstor-scheduler/patches/cozystack-scheduler-deployment.patch b/packages/system/linstor-scheduler/patches/cozystack-scheduler-deployment.patch index 308459175..4edb2e320 100644 --- a/packages/system/linstor-scheduler/patches/cozystack-scheduler-deployment.patch +++ b/packages/system/linstor-scheduler/patches/cozystack-scheduler-deployment.patch @@ -1,5 +1,5 @@ # Cozystack downstream customizations to the linstor-scheduler Deployment. -# Both edits touch the same file and are deliberately kept in one patch: +# All edits touch the same file and are deliberately kept in one patch: # splitting them into two patches on deployment.yaml would create fragile # line-offset coupling between the hunks. # @@ -10,13 +10,29 @@ # helper instead of raw .Capabilities.KubeVersion.Version, so a # distribution suffix (e.g. v1.31.0+k3s1) does not resolve to a # non-existent registry.k8s.io/kube-scheduler image tag. +# (c) Annotate the Deployment for Stakater Reloader with the LINSTOR client +# secret. The extender reads that certificate from env vars resolved at +# container start, so without a roll on rotation a pod that outlives the +# certificate fails every new TLS handshake to the controller (EOF). +# The annotation goes on the Deployment rather than via podAnnotations, +# which the admission Deployment shares and would roll for nothing. # # Chart source: https://piraeus.io/helm-charts (linstor-scheduler 0.3.1) diff --git a/packages/system/linstor-scheduler/charts/linstor-scheduler/templates/deployment.yaml b/packages/system/linstor-scheduler/charts/linstor-scheduler/templates/deployment.yaml -index 49898b8..289021f 100644 --- a/packages/system/linstor-scheduler/charts/linstor-scheduler/templates/deployment.yaml +++ b/packages/system/linstor-scheduler/charts/linstor-scheduler/templates/deployment.yaml -@@ -20,6 +20,7 @@ spec: +@@ -3,6 +3,10 @@ + kind: Deployment + metadata: + name: {{ include "linstor-scheduler.fullname" . }} ++ {{- with include "linstor-scheduler.linstorClientSecretName" . }} ++ annotations: ++ secret.reloader.stakater.com/reload: {{ . | quote }} ++ {{- end }} + labels: + {{- include "linstor-scheduler.labels" . | nindent 4 }} + spec: +@@ -20,6 +24,7 @@ {{- end }} labels: {{- include "linstor-scheduler.selectorLabels" . | nindent 8 }} @@ -24,7 +40,7 @@ index 49898b8..289021f 100644 spec: {{- with .Values.imagePullSecrets }} imagePullSecrets: -@@ -30,7 +31,7 @@ spec: +@@ -30,7 +35,7 @@ {{- toYaml .Values.podSecurityContext | nindent 8 }} containers: - name: kube-scheduler diff --git a/packages/system/linstor-scheduler/tests/deployment_test.yaml b/packages/system/linstor-scheduler/tests/deployment_test.yaml new file mode 100644 index 000000000..9e32bfeba --- /dev/null +++ b/packages/system/linstor-scheduler/tests/deployment_test.yaml @@ -0,0 +1,73 @@ +suite: scheduler Deployment (cozystack) + +templates: + - charts/linstor-scheduler/templates/deployment.yaml + - charts/linstor-scheduler/templates/admission-deployment.yaml + +release: + name: linstor-scheduler + +tests: + # The extender reads its LINSTOR client certificate from env vars resolved + # at container start. Reloader must watch the very secret those env vars + # reference, or a pod older than the certificate lifetime loses the LINSTOR + # API (EOF on every new TLS handshake) and the scheduler stops placing pods + # next to their replicas. + - it: Reloader watches the secret the extender takes its client certificate from + template: charts/linstor-scheduler/templates/deployment.yaml + asserts: + - equal: + path: metadata.annotations["secret.reloader.stakater.com/reload"] + value: linstor-client-tls + - contains: + path: spec.template.spec.containers[1].env + content: + name: LS_USER_CERTIFICATE + valueFrom: + secretKeyRef: + name: linstor-client-tls + key: tls.crt + - contains: + path: spec.template.spec.containers[1].env + content: + name: LS_USER_KEY + valueFrom: + secretKeyRef: + name: linstor-client-tls + key: tls.key + + - it: the Reloader annotation follows linstor.clientSecret + template: charts/linstor-scheduler/templates/deployment.yaml + set: + linstor-scheduler.linstor.clientSecret: other-client-tls + asserts: + - equal: + path: metadata.annotations["secret.reloader.stakater.com/reload"] + value: other-client-tls + - contains: + path: spec.template.spec.containers[1].env + content: + name: LS_USER_CERTIFICATE + valueFrom: + secretKeyRef: + name: other-client-tls + key: tls.crt + - contains: + path: spec.template.spec.containers[1].env + content: + name: LS_USER_KEY + valueFrom: + secretKeyRef: + name: other-client-tls + key: tls.key + + # The admission webhook does not use the LINSTOR client secret; rolling it + # on that secret's rotation would only restart it for nothing. + - it: the admission Deployment is not rolled on LINSTOR client secret rotation + template: charts/linstor-scheduler/templates/admission-deployment.yaml + asserts: + - notExists: + path: spec.template.metadata.annotations["secret.reloader.stakater.com/reload"] + - notEqual: + path: metadata.annotations["secret.reloader.stakater.com/reload"] + value: linstor-client-tls diff --git a/packages/system/linstor/templates/cluster.yaml b/packages/system/linstor/templates/cluster.yaml index 4e94c80f9..d5d7a2e36 100644 --- a/packages/system/linstor/templates/cluster.yaml +++ b/packages/system/linstor/templates/cluster.yaml @@ -92,6 +92,17 @@ spec: containers: - name: linstor-csi image: {{ .Values.linstorCSI.image.repository }}:{{ .Values.linstorCSI.image.tag }} + {{- /* The NFS server DaemonSet runs one init container on the CSI image. + Left unset it follows the operator's default image and tag, not + linstorCSI.image. An absent nfsServer means enabled to the operator, + so enabled is stated explicitly to keep that unchanged. */}} + nfsServer: + enabled: true + podTemplate: + spec: + initContainers: + - name: linstor-wait-node-online + image: {{ .Values.linstorCSI.image.repository }}:{{ .Values.linstorCSI.image.tag }} patches: - target: kind: Deployment @@ -114,3 +125,10 @@ spec: - op: add path: /metadata/annotations/reloader.stakater.com~1auto value: "true" + - target: + kind: Deployment + name: linstor-affinity-controller + patch: |- + - op: add + path: /metadata/annotations/reloader.stakater.com~1auto + value: "true" diff --git a/packages/system/linstor/tests/linstor_test.yaml b/packages/system/linstor/tests/linstor_test.yaml index 1d0441d46..57b5be514 100644 --- a/packages/system/linstor/tests/linstor_test.yaml +++ b/packages/system/linstor/tests/linstor_test.yaml @@ -16,6 +16,34 @@ tests: path: spec.csiController.podTemplate.spec.containers[0].image pattern: '^ghcr\.io/cozystack/cozystack/linstor-csi:[^@]+@sha256:[0-9a-f]{64}$' + - it: pins the NFS server's wait-node-online init container to the cozystack-built CSI image + template: templates/cluster.yaml + documentSelector: + path: kind + value: LinstorCluster + asserts: + - matchRegex: + path: spec.nfsServer.podTemplate.spec.initContainers[?(@.name=="linstor-wait-node-online")].image + pattern: '^ghcr\.io/cozystack/cozystack/linstor-csi:[^@]+@sha256:[0-9a-f]{64}$' + - equal: + path: spec.nfsServer.enabled + value: true + + - it: the NFS server's wait-node-online init container follows linstorCSI.image + template: templates/cluster.yaml + documentSelector: + path: kind + value: LinstorCluster + set: + linstorCSI: + image: + repository: registry.example/linstor-csi + tag: v0.0.0-test + asserts: + - equal: + path: spec.nfsServer.podTemplate.spec.initContainers[?(@.name=="linstor-wait-node-online")].image + value: registry.example/linstor-csi:v0.0.0-test + - it: pins the satellite to the cozystack-built piraeus-server image template: templates/satellites-cozy.yaml documentSelector: diff --git a/packages/system/linstor/tests/reloader_test.yaml b/packages/system/linstor/tests/reloader_test.yaml new file mode 100644 index 000000000..1f5a095ad --- /dev/null +++ b/packages/system/linstor/tests/reloader_test.yaml @@ -0,0 +1,54 @@ +suite: Reloader patches on operator-managed LINSTOR API clients + +templates: + - templates/cluster.yaml + +tests: + # Every operator-managed workload that authenticates to the LINSTOR API with + # a cert-manager client certificate must roll when that secret rotates. The + # affinity controller reads its certificate from env vars at startup, so + # without the patch it keeps the old one and, after expiry, every request + # to the controller fails with EOF while PV node affinities stop following + # replica moves. + - it: every LINSTOR API client workload carries the Reloader auto annotation + asserts: + - contains: + path: spec.patches + content: + target: + kind: Deployment + name: linstor-controller + patch: |- + - op: add + path: /metadata/annotations/reloader.stakater.com~1auto + value: "true" + - contains: + path: spec.patches + content: + target: + kind: Deployment + name: linstor-csi-controller + patch: |- + - op: add + path: /metadata/annotations/reloader.stakater.com~1auto + value: "true" + - contains: + path: spec.patches + content: + target: + kind: DaemonSet + name: linstor-csi-node + patch: |- + - op: add + path: /metadata/annotations/reloader.stakater.com~1auto + value: "true" + - contains: + path: spec.patches + content: + target: + kind: Deployment + name: linstor-affinity-controller + patch: |- + - op: add + path: /metadata/annotations/reloader.stakater.com~1auto + value: "true" diff --git a/packages/system/mariadb-operator/Makefile b/packages/system/mariadb-operator/Makefile index 905653cac..e80038778 100644 --- a/packages/system/mariadb-operator/Makefile +++ b/packages/system/mariadb-operator/Makefile @@ -3,6 +3,9 @@ export NAMESPACE=cozy-$(NAME) include ../../../hack/package.mk +test: + helm unittest . + update: rm -rf charts helm repo add mariadb-operator https://mariadb-operator.github.io/mariadb-operator diff --git a/packages/system/mariadb-operator/tests/cluster_name_test.yaml b/packages/system/mariadb-operator/tests/cluster_name_test.yaml new file mode 100644 index 000000000..45d762727 --- /dev/null +++ b/packages/system/mariadb-operator/tests/cluster_name_test.yaml @@ -0,0 +1,43 @@ +suite: mariadb-operator package resolves its pods in the platform cluster domain +release: + name: mariadb-operator + namespace: cozy-mariadb-operator +# core/platform hands the cluster domain to this package as +# mariadb-operator.clusterName in the shared values Secret. Guard that the +# vendored chart still threads that key into what the operator and the webhook +# certificate use, so a re-vendor that renames it goes red here. +tests: + - it: sets the operator CLUSTER_NAME from the injected domain + templates: + - charts/mariadb-operator/templates/operator/deployment.yaml + set: + mariadb-operator.clusterName: example.test + asserts: + - contains: + path: spec.template.spec.containers[0].env + content: + name: CLUSTER_NAME + value: example.test + + - it: issues the webhook certificate for the injected domain + templates: + - charts/mariadb-operator/templates/webhook/certificate.yaml + documentSelector: + path: kind + value: Certificate + set: + mariadb-operator.clusterName: example.test + asserts: + - contains: + path: spec.dnsNames + content: mariadb-operator-webhook.cozy-mariadb-operator.svc.example.test + + - it: keeps cozy.local as the standalone default + templates: + - charts/mariadb-operator/templates/operator/deployment.yaml + asserts: + - contains: + path: spec.template.spec.containers[0].env + content: + name: CLUSTER_NAME + value: cozy.local diff --git a/packages/system/mariadb-operator/values.yaml b/packages/system/mariadb-operator/values.yaml index 11aadd80d..285975440 100644 --- a/packages/system/mariadb-operator/values.yaml +++ b/packages/system/mariadb-operator/values.yaml @@ -1,7 +1,10 @@ mariadb-operator: + # Fallback only: core/platform injects networking.clusterDomain into this key + # through the shared cozystack-values Secret (see its apps.yaml). clusterName: cozy.local metrics: enabled: true webhook: - certificate: - certManager: true + cert: + certManager: + enabled: true diff --git a/packages/system/monitoring-agents/alerts/etcd.yaml b/packages/system/monitoring-agents/alerts/etcd.yaml index 72c5ef7b2..48cdc84d9 100644 --- a/packages/system/monitoring-agents/alerts/etcd.yaml +++ b/packages/system/monitoring-agents/alerts/etcd.yaml @@ -116,8 +116,9 @@ spec: {{ $labels.To }} is taking {{ $value }}s on etcd instance {{ $labels.instance }}.' summary: etcd cluster member communication is slow. + # Tenant peer RTT is covered by the tenant etcd rules. expr: |- - histogram_quantile(0.99, rate(etcd_network_peer_round_trip_time_seconds_bucket{job=~".*etcd.*"}[5m])) + histogram_quantile(0.99, rate(etcd_network_peer_round_trip_time_seconds_bucket{job=~".*etcd.*", job!~"tenant-.*/etcd-pod-scrape"}[5m])) > 0.15 for: 10m labels: diff --git a/packages/system/monitoring-agents/alerts/general.rules.yaml b/packages/system/monitoring-agents/alerts/general.rules.yaml index 924870c40..e713a4970 100644 --- a/packages/system/monitoring-agents/alerts/general.rules.yaml +++ b/packages/system/monitoring-agents/alerts/general.rules.yaml @@ -33,7 +33,8 @@ spec: is working properly. expr: vector(1) labels: - severity: ok + severity: major + timeout: "300" exported_instance: global service: general.rules event: Heartbeat @@ -52,6 +53,6 @@ spec: != "InfoInhibitor", severity =~ "warning|critical", alertstate="firing"} == 1 labels: - severity: major + severity: none exported_instance: global service: general.rules diff --git a/packages/system/monitoring-agents/alerts/vmagent.yaml b/packages/system/monitoring-agents/alerts/vmagent.yaml new file mode 100644 index 000000000..3fb69fde2 --- /dev/null +++ b/packages/system/monitoring-agents/alerts/vmagent.yaml @@ -0,0 +1,26 @@ +apiVersion: operator.victoriametrics.com/v1beta1 +kind: VMRule +metadata: + name: alerts-vmagent +spec: + groups: + - name: vmagent + params: {} + rules: + - alert: VMAgentScrapeSizeExceeded + expr: increase(vm_promscrape_max_scrape_size_exceeded_errors_total[10m]) > 0 + for: 5m + labels: + severity: warning + exported_instance: '{{ $labels.namespace }}/{{ $labels.pod }}' + service: vmagent + annotations: + summary: vmagent refuses scrape responses larger than its size limit. + description: >- + vmagent {{ $labels.namespace }}/{{ $labels.pod }} in cluster {{ $labels.cluster }} dropped + scrape responses that exceed -promscrape.maxScrapeSize or the scrape's max_scrape_size. + The affected targets report up == 0, so TargetDown or KubeAPIDown may fire for a healthy + target. The counter carries no target label: find the target on the vmagent /targets + page, where the last error names the size limit, then raise max_scrape_size on that + scrape. For kube-apiserver on the management cluster this is the + vmagent.apiserverMaxScrapeSize value of the monitoring-agents component. diff --git a/packages/system/monitoring-agents/alerts/workload-placement.yaml b/packages/system/monitoring-agents/alerts/workload-placement.yaml new file mode 100644 index 000000000..3ae9c8f50 --- /dev/null +++ b/packages/system/monitoring-agents/alerts/workload-placement.yaml @@ -0,0 +1,81 @@ +apiVersion: operator.victoriametrics.com/v1beta1 +kind: VMRule +metadata: + name: alerts-workload-placement +spec: + groups: + - name: workload-placement + params: {} + rules: + - alert: PodReplicasColocated + expr: |- + count by (cluster, namespace, owner_kind, owner_name, node) ( + label_replace( + label_replace( + ( + max by (cluster, namespace, pod, node, created_by_kind, created_by_name) ( + kube_pod_info{job="kube-state-metrics", created_by_kind=~"StatefulSet|ReplicaSet|Cluster|StrimziPodSet"} + ) + or + label_replace( + label_replace( + max by (cluster, namespace, pod, node, created_by_kind, created_by_name) ( + kube_pod_info{job="kube-state-metrics", created_by_kind="EtcdMember"} + ), + "created_by_name", "$1", "created_by_name", "(.+)-[^-]+" + ), + "created_by_kind", "EtcdCluster", "", "" + ) + ) + and on (cluster, namespace, pod) + kube_pod_status_phase{job="kube-state-metrics", phase="Running"} == 1, + "owner_kind", "$1", "created_by_kind", "(.+)" + ), + "owner_name", "$1", "created_by_name", "(.+)" + ) + ) > 1 + and on (cluster, namespace, owner_kind, owner_name) + count by (cluster, namespace, owner_kind, owner_name) ( + label_replace( + label_replace( + ( + max by (cluster, namespace, pod, node, created_by_kind, created_by_name) ( + kube_pod_info{job="kube-state-metrics", created_by_kind=~"StatefulSet|ReplicaSet|Cluster|StrimziPodSet"} + ) + or + label_replace( + label_replace( + max by (cluster, namespace, pod, node, created_by_kind, created_by_name) ( + kube_pod_info{job="kube-state-metrics", created_by_kind="EtcdMember"} + ), + "created_by_name", "$1", "created_by_name", "(.+)-[^-]+" + ), + "created_by_kind", "EtcdCluster", "", "" + ) + ) + and on (cluster, namespace, pod) + kube_pod_status_phase{job="kube-state-metrics", phase="Running"} == 1, + "owner_kind", "$1", "created_by_kind", "(.+)" + ), + "owner_name", "$1", "created_by_name", "(.+)" + ) + ) + <= on (cluster) group_left () + count by (cluster) ( + max by (cluster, node) (kube_node_info{job="kube-state-metrics"}) + unless on (cluster, node) + kube_node_spec_taint{job="kube-state-metrics", effect=~"NoSchedule|NoExecute"} + ) + for: 1h + labels: + severity: warning + exported_instance: '{{ $labels.namespace }}/{{ $labels.owner_name }}' + service: workload-placement + annotations: + summary: Pods of one workload share a node. + description: >- + {{ $value }} running pods of {{ $labels.owner_kind }} {{ $labels.namespace }}/{{ $labels.owner_name }} + are on node {{ $labels.node }} in cluster {{ $labels.cluster }}, although the cluster has a + schedulable node for each of its pods. Losing this node stops these pods together, which can cost + a quorum-based workload its quorum. The scheduler does not move running pods, so they stay + together until they are recreated. diff --git a/packages/system/monitoring-agents/templates/apiserver-scrape.yaml b/packages/system/monitoring-agents/templates/apiserver-scrape.yaml index f3f7b9826..5750b55f9 100644 --- a/packages/system/monitoring-agents/templates/apiserver-scrape.yaml +++ b/packages/system/monitoring-agents/templates/apiserver-scrape.yaml @@ -9,6 +9,9 @@ spec: - bearerTokenFile: /var/run/secrets/kubernetes.io/serviceaccount/token port: https scheme: https + {{- with .Values.vmagent.apiserverMaxScrapeSize }} + max_scrape_size: {{ . | quote }} + {{- end }} relabelConfigs: - action: labeldrop regex: (endpoint|namespace|pod|container) diff --git a/packages/system/monitoring-agents/templates/vm-cleanup-hook.yaml b/packages/system/monitoring-agents/templates/vm-cleanup-hook.yaml new file mode 100644 index 000000000..efdbd1158 --- /dev/null +++ b/packages/system/monitoring-agents/templates/vm-cleanup-hook.yaml @@ -0,0 +1,167 @@ +{{- /* + The VictoriaMetrics operator puts its finalizer on the VMAgent and is the only + thing that ever removes it. The operator ships as a separate release that is + gated on the same addon flag, so disabling the addon removes both at once and + Flux does not order deletions: when the operator goes first, the VMAgent stays + Terminating and the uninstall never finishes. The other kinds are handled the + same way in case an operator version finalizes them too; for those the patch + is a no-op. + + So delete them before Helm does, give a live operator a bounded chance to + finalize them itself, and only then clear the finalizers by hand. The VMAgent's + Deployment, Service and Secrets carry owner references and are garbage + collected once it is gone. + + Cluster-scoped RBAC because the objects span two namespaces, and a Role in the + operator's namespace could not be created if that namespace were already + gone. The hook always exits 0: a cleanup that cannot complete must not be what + keeps the release from uninstalling. +*/ -}} +{{- $name := "vm-objects-cleanup" }} +{{- $img := printf "%s:%s" .Values.kubectlImage.repository .Values.kubectlImage.tag }} +{{- with .Values.kubectlImage.digest }}{{- $img = printf "%s@%s" $img . }}{{- end }} +{{- $kinds := list "vmagents" "vmrules" "vmservicescrapes" "vmpodscrapes" "vmnodescrapes" }} +apiVersion: v1 +kind: ServiceAccount +metadata: + name: {{ $name }} + namespace: {{ .Release.Namespace }} + annotations: + helm.sh/hook: pre-delete + helm.sh/hook-weight: "-10" + helm.sh/hook-delete-policy: hook-succeeded,hook-failed,before-hook-creation +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRole +metadata: + name: {{ .Release.Namespace }}-{{ $name }} + annotations: + helm.sh/hook: pre-delete + helm.sh/hook-weight: "-10" + helm.sh/hook-delete-policy: hook-succeeded,hook-failed,before-hook-creation +rules: + - apiGroups: ["operator.victoriametrics.com"] + resources: + {{- toYaml $kinds | nindent 6 }} + verbs: ["get", "list", "delete", "patch"] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRoleBinding +metadata: + name: {{ .Release.Namespace }}-{{ $name }} + annotations: + helm.sh/hook: pre-delete + helm.sh/hook-weight: "-10" + helm.sh/hook-delete-policy: hook-succeeded,hook-failed,before-hook-creation +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: ClusterRole + name: {{ .Release.Namespace }}-{{ $name }} +subjects: + - kind: ServiceAccount + name: {{ $name }} + namespace: {{ .Release.Namespace }} +--- +apiVersion: batch/v1 +kind: Job +metadata: + name: {{ $name }} + namespace: {{ .Release.Namespace }} + annotations: + helm.sh/hook: pre-delete + helm.sh/hook-weight: "0" + helm.sh/hook-delete-policy: hook-succeeded,before-hook-creation +spec: + # Bounds every kubectl call as well: --request-timeout would make kubectl + # skip the in-cluster credentials (hack/check-hook-request-timeout.bats). + # Well inside the HelmRelease's 10m uninstall budget, and above the 60s + # wait plus one call per object on either side of it. + activeDeadlineSeconds: 180 + backoffLimit: 0 + ttlSecondsAfterFinished: 600 + template: + spec: + serviceAccountName: {{ $name }} + restartPolicy: Never + securityContext: + runAsNonRoot: true + # The image user is the non-numeric `nonroot`, which the kubelet cannot + # check against runAsNonRoot. + runAsUser: 65532 + seccompProfile: + type: RuntimeDefault + volumes: + - name: home + emptyDir: {} + containers: + - name: cleanup + image: {{ $img | quote }} + imagePullPolicy: {{ .Values.kubectlImage.pullPolicy }} + resources: + requests: + cpu: 10m + memory: 32Mi + limits: + cpu: 100m + memory: 64Mi + securityContext: + allowPrivilegeEscalation: false + readOnlyRootFilesystem: true + capabilities: + drop: ["ALL"] + # kubectl writes its discovery cache under $HOME. + env: + - name: HOME + value: /tmp + volumeMounts: + - name: home + mountPath: /tmp + command: + - /bin/sh + - -c + - | + rel={{ .Release.Name | quote }} + relns={{ .Release.Namespace | quote }} + kinds={{ join " " $kinds | quote }} + + # Selected by Helm's ownership annotations rather than by name, so + # the alert rules added under alerts/ are covered without a list + # to keep in step. A kind whose CRD is gone just prints an error. + owned() { + for k in $kinds; do + kubectl get "$k.operator.victoriametrics.com" -A \ + -o jsonpath='{range .items[*]}{.metadata.annotations.meta\.helm\.sh/release-name}{"|"}{.metadata.annotations.meta\.helm\.sh/release-namespace}{"|"}{.metadata.namespace}{"|"}{.metadata.name}{"\n"}{end}' | + while IFS='|' read -r r rns ns n; do + if [ "$r" = "$rel" ] && [ "$rns" = "$relns" ]; then + echo "$k.operator.victoriametrics.com $ns $n" + fi + done + done + } + + objs=$(owned) + if [ -z "$objs" ]; then + echo "no VictoriaMetrics objects left for $relns/$rel" + exit 0 + fi + + echo "$objs" | while read -r k ns n; do + kubectl -n "$ns" delete "$k" "$n" --wait=false + done + + deadline=$(( $(date +%s) + 60 )) + while [ "$(date +%s)" -lt "$deadline" ]; do + sleep 2 + objs=$(owned) + if [ -z "$objs" ]; then + echo "the operator finalized every object" + exit 0 + fi + done + + echo "finalizers still held after 60s; clearing them by hand" + echo "$objs" | while read -r k ns n; do + kubectl -n "$ns" patch "$k" "$n" --type=merge \ + -p '{"metadata":{"finalizers":null}}' + done + exit 0 diff --git a/packages/system/monitoring-agents/templates/vmagent.yaml b/packages/system/monitoring-agents/templates/vmagent.yaml index 00ab63c10..7a87fa5b5 100644 --- a/packages/system/monitoring-agents/templates/vmagent.yaml +++ b/packages/system/monitoring-agents/templates/vmagent.yaml @@ -10,7 +10,7 @@ spec: shardCount: 1 externalLabels: cluster: {{ .Values.vmagent.externalLabels.cluster }} - tenant: {{ .Values.global.target }} + tenant: {{ .Values.vmagent.externalLabels.tenant | default .Values.global.target | quote }} extraArgs: {{- toYaml (deepCopy .Values.vmagent.extraArgs | mergeOverwrite (fromYaml (include "monitoring-agents.vmagent.defaultExtraArgs" .))) | nindent 4 }} remoteWrite: diff --git a/packages/system/monitoring-agents/templates/vpa.yaml b/packages/system/monitoring-agents/templates/vpa.yaml index 9a31fab94..1ac949f30 100644 --- a/packages/system/monitoring-agents/templates/vpa.yaml +++ b/packages/system/monitoring-agents/templates/vpa.yaml @@ -6,6 +6,11 @@ Initial sets requests at creation without evicting, removing the trigger. Do not switch back to Auto without fixing the underlying Cilium IP-reuse race. */ -}} +{{- /* + Rendered only when the CRD is served: a release manifest that records a VPA + the cluster cannot map is one Helm can no longer uninstall. +*/ -}} +{{- if .Capabilities.APIVersions.Has "autoscaling.k8s.io/v1/VerticalPodAutoscaler" }} apiVersion: autoscaling.k8s.io/v1 kind: VerticalPodAutoscaler metadata: @@ -34,3 +39,4 @@ spec: maxAllowed: cpu: 4000m memory: 6G +{{- end }} diff --git a/packages/system/monitoring-agents/tests/etcd_rules_test.yaml b/packages/system/monitoring-agents/tests/etcd_rules_test.yaml new file mode 100644 index 000000000..78651297c --- /dev/null +++ b/packages/system/monitoring-agents/tests/etcd_rules_test.yaml @@ -0,0 +1,20 @@ +suite: tenant peer RTT is evaluated once + +templates: + - templates/alerts.yaml + +tests: + - it: leaves tenant peer RTT to the tenant rules + documentSelector: + path: metadata.name + value: alerts-etcd + asserts: + - matchRegex: + path: spec.groups[0].rules[7].expr + pattern: 'job!~"tenant-\.\*/etcd-pod-scrape"' + - notMatchRegex: + path: spec.groups[0].rules[9].expr + pattern: 'job!~' + - notMatchRegex: + path: spec.groups[0].rules[10].expr + pattern: 'job!~' diff --git a/packages/system/monitoring-agents/tests/uninstall_test.yaml b/packages/system/monitoring-agents/tests/uninstall_test.yaml new file mode 100644 index 000000000..df8a3eaa6 --- /dev/null +++ b/packages/system/monitoring-agents/tests/uninstall_test.yaml @@ -0,0 +1,141 @@ +suite: the release uninstalls whatever order its dependencies go in + +# Disabling the addon removes this release, the VictoriaMetrics operator and the +# VPA CRDs together, and Flux deletes them in parallel. When the operator goes +# first, nothing clears its finalizer on the objects this chart created and the +# uninstall hangs; when the VPA CRD goes first, a release manifest recording a +# VPA cannot be built and the uninstall fails. +release: + name: cozy-monitoring-agents + namespace: cozy-monitoring +templates: + - templates/vm-cleanup-hook.yaml + - templates/vpa.yaml +tests: + - it: runs before Helm deletes anything, bounded and with one attempt + template: templates/vm-cleanup-hook.yaml + documentSelector: + path: kind + value: Job + asserts: + - equal: + path: metadata.annotations["helm.sh/hook"] + value: pre-delete + - equal: + path: metadata.namespace + value: cozy-monitoring + - equal: + path: spec.activeDeadlineSeconds + value: 180 + - equal: + path: spec.backoffLimit + value: 0 + - matchRegex: + path: spec.template.spec.containers[0].image + pattern: ^docker\.io/clastix/kubectl:v[0-9.]+@sha256:[0-9a-f]{64}$ + + - it: its RBAC exists only for the hook and is removed with it + template: templates/vm-cleanup-hook.yaml + documentSelector: + path: kind + value: ClusterRole + asserts: + - equal: + path: metadata.annotations["helm.sh/hook"] + value: pre-delete + - equal: + path: metadata.annotations["helm.sh/hook-weight"] + value: "-10" + - matchRegex: + path: metadata.annotations["helm.sh/hook-delete-policy"] + pattern: hook-succeeded + + - it: may delete and clear finalizers on every VictoriaMetrics kind the chart renders + template: templates/vm-cleanup-hook.yaml + documentSelector: + path: kind + value: ClusterRole + asserts: + - equal: + path: rules[0].apiGroups + value: ["operator.victoriametrics.com"] + - contains: + path: rules[0].resources + content: vmagents + - contains: + path: rules[0].resources + content: vmrules + - contains: + path: rules[0].resources + content: vmservicescrapes + - contains: + path: rules[0].resources + content: vmpodscrapes + - contains: + path: rules[0].resources + content: vmnodescrapes + - equal: + path: rules[0].verbs + value: ["get", "list", "delete", "patch"] + - lengthEqual: + path: rules + count: 1 + + - it: grants that role to the hook's own service account + template: templates/vm-cleanup-hook.yaml + documentSelector: + path: kind + value: ClusterRoleBinding + asserts: + - equal: + path: roleRef.name + value: cozy-monitoring-vm-objects-cleanup + - equal: + path: subjects[0] + value: + kind: ServiceAccount + name: vm-objects-cleanup + namespace: cozy-monitoring + + - it: touches only objects this release owns, and clears their finalizers + template: templates/vm-cleanup-hook.yaml + documentSelector: + path: kind + value: Job + asserts: + - matchRegex: + path: spec.template.spec.containers[0].command[2] + pattern: rel="cozy-monitoring-agents" + - matchRegex: + path: spec.template.spec.containers[0].command[2] + pattern: relns="cozy-monitoring" + - matchRegex: + path: spec.template.spec.containers[0].command[2] + pattern: meta\\\.helm\\\.sh/release-name + - matchRegex: + path: spec.template.spec.containers[0].command[2] + pattern: 'delete "\$k" "\$n" --wait=false' + - matchRegex: + path: spec.template.spec.containers[0].command[2] + pattern: '"finalizers":null' + # A pre-delete hook that fails aborts the uninstall it exists to unblock. + - matchRegex: + path: spec.template.spec.containers[0].command[2] + pattern: exit 0\s*$ + + - it: the VPA is rendered when its CRD is served + template: templates/vpa.yaml + capabilities: + apiVersions: + - autoscaling.k8s.io/v1/VerticalPodAutoscaler + asserts: + - hasDocuments: + count: 1 + - isKind: + of: VerticalPodAutoscaler + + - it: the VPA stays out of the release manifest when its CRD is not served + template: templates/vpa.yaml + asserts: + - hasDocuments: + count: 0 diff --git a/packages/system/monitoring-agents/tests/vmagent_remote_write_test.yaml b/packages/system/monitoring-agents/tests/vmagent_remote_write_test.yaml new file mode 100644 index 000000000..894a1c053 --- /dev/null +++ b/packages/system/monitoring-agents/tests/vmagent_remote_write_test.yaml @@ -0,0 +1,65 @@ +suite: vmagent remote write targets and tenant label + +# The root bundle sets only global.target, and the chart defaults derive both +# the remote write URLs and the tenant label from it. A tenant Kubernetes +# cluster gets this chart through packages/apps/kubernetes instead, which +# passes vmagent.remoteWrite.urls and vmagent.externalLabels.tenant and leaves +# global.target at its default. If either value is dropped, vmagent writes to +# cozy-monitoring services that do not exist in the tenant cluster, or labels +# every series tenant="cozy-monitoring". +templates: + - templates/vmagent.yaml +release: + name: cozy-monitoring-agents + namespace: cozy-monitoring +tests: + - it: root install writes to both stores of global.target and labels series with it + set: + global.target: tenant-root + asserts: + - equal: + path: spec.remoteWrite + value: + - url: http://vminsert-shortterm.tenant-root.svc:8480/insert/0/prometheus + - url: http://vminsert-longterm.tenant-root.svc:8480/insert/0/prometheus + - equal: + path: spec.externalLabels.tenant + value: tenant-root + + - it: tenant cluster writes only to the URLs its parent app passes + set: + vmagent: + externalLabels: + cluster: kubernetes-clusterprod + tenant: tenant-a + remoteWrite: + urls: + - http://vminsert-shortterm.tenant-a.svc.cozy.local:8480/insert/0/prometheus + asserts: + - equal: + path: spec.remoteWrite + value: + - url: http://vminsert-shortterm.tenant-a.svc.cozy.local:8480/insert/0/prometheus + + - it: tenant cluster labels series with the owning tenant, not global.target + set: + vmagent: + externalLabels: + cluster: kubernetes-clusterprod + tenant: tenant-a + asserts: + - equal: + path: spec.externalLabels + value: + cluster: kubernetes-clusterprod + tenant: tenant-a + + - it: tenant label stays a string when the value reads as a YAML scalar + set: + vmagent: + externalLabels: + tenant: "true" + asserts: + - equal: + path: spec.externalLabels.tenant + value: "true" diff --git a/packages/system/monitoring-agents/tests/vmagent_scrape_size_test.yaml b/packages/system/monitoring-agents/tests/vmagent_scrape_size_test.yaml new file mode 100644 index 000000000..b4e3809d9 --- /dev/null +++ b/packages/system/monitoring-agents/tests/vmagent_scrape_size_test.yaml @@ -0,0 +1,69 @@ +suite: kube-apiserver scrape size limit and its alert + +# kube-apiserver's /metrics grows with the number of resources and CRDs, and a +# full install pushes it past the global 32MB -promscrape.maxScrapeSize. vmagent +# then refuses every scrape of it, so up == 0 and KubeAPIDown fires on a +# healthy API server. The apiserver endpoint carries its own max_scrape_size, +# which replaces the global flag for that job only (upward too), so the guard +# for every other target stays at 32MB. vmagent buffers the whole uncompressed +# body even with streamParse, so the per-job limit is a memory ceiling and must +# stay finite. +release: + name: monitoring-agents + namespace: cozy-monitoring +tests: + - it: apiserver endpoint gets its own scrape size limit by default + template: templates/apiserver-scrape.yaml + asserts: + - equal: + path: spec.endpoints[0].max_scrape_size + value: 128MB + + - it: apiserver scrape size limit follows the value + template: templates/apiserver-scrape.yaml + set: + vmagent.apiserverMaxScrapeSize: 512MB + asserts: + - equal: + path: spec.endpoints[0].max_scrape_size + value: 512MB + + - it: a byte count renders as a string, as the CRD field requires + template: templates/apiserver-scrape.yaml + set: + vmagent.apiserverMaxScrapeSize: 134217728 + asserts: + - matchRegex: + path: spec.endpoints[0].max_scrape_size + pattern: ^[0-9.e+]+$ + + - it: an empty value falls back to the global flag + template: templates/apiserver-scrape.yaml + set: + vmagent.apiserverMaxScrapeSize: "" + asserts: + - notExists: + path: spec.endpoints[0].max_scrape_size + + - it: the global limit for every other target is not loosened + template: templates/vmagent.yaml + asserts: + - equal: + path: spec.extraArgs["promscrape.maxScrapeSize"] + value: 32MB + + - it: a refused oversized scrape raises its own alert + template: templates/alerts.yaml + documentSelector: + path: metadata.name + value: alerts-vmagent + asserts: + - equal: + path: spec.groups[0].rules[0].alert + value: VMAgentScrapeSizeExceeded + - equal: + path: spec.groups[0].rules[0].expr + value: increase(vm_promscrape_max_scrape_size_exceeded_errors_total[10m]) > 0 + - equal: + path: spec.groups[0].rules[0].labels.severity + value: warning diff --git a/packages/system/monitoring-agents/tests/watchdog_heartbeat_test.yaml b/packages/system/monitoring-agents/tests/watchdog_heartbeat_test.yaml new file mode 100644 index 000000000..fe630a80c --- /dev/null +++ b/packages/system/monitoring-agents/tests/watchdog_heartbeat_test.yaml @@ -0,0 +1,29 @@ +suite: Watchdog heartbeat raises an alarm in Alerta when it stops +templates: + - templates/alerts.yaml + +release: + name: monitoring-agents + namespace: cozy-monitoring + +tests: + - it: gives the heartbeat a severity Alerta reports as an alarm + documentSelector: + path: metadata.name + value: alerts-general.rules + asserts: + - equal: + path: spec.groups[0].rules[?(@.alert == "Watchdog")].labels.severity + value: major + + - it: lets the heartbeat go stale within minutes, not a day + documentSelector: + path: metadata.name + value: alerts-general.rules + asserts: + - equal: + path: spec.groups[0].rules[?(@.alert == "Watchdog")].labels.timeout + value: "300" + - equal: + path: spec.groups[0].rules[?(@.alert == "Watchdog")].labels.event + value: Heartbeat diff --git a/packages/system/monitoring-agents/values.yaml b/packages/system/monitoring-agents/values.yaml index 6433a74d0..74757d4d9 100644 --- a/packages/system/monitoring-agents/values.yaml +++ b/packages/system/monitoring-agents/values.yaml @@ -283,6 +283,13 @@ vmagent: - http://vminsert-shortterm.{{ .Values.global.target }}.svc:8480/insert/0/prometheus - http://vminsert-longterm.{{ .Values.global.target }}.svc:8480/insert/0/prometheus extraArgs: {} + # Replaces the global promscrape.maxScrapeSize (32MB) for the kube-apiserver + # job only. Its /metrics grows with the number of CRDs and outgrows 32MB on a + # full install. vmagent buffers the whole uncompressed response even with + # streamParse, so keep this finite. It replaces the global in both + # directions: if extraArgs raises promscrape.maxScrapeSize above this value, + # raise this one too. An empty value falls back to the global. + apiserverMaxScrapeSize: 128MB fluent-bit: rbac: @@ -445,3 +452,15 @@ fluent-bit: scrapeRules: etcd: enabled: false + +# Image for the pre-delete hook that releases the VictoriaMetrics objects (see +# templates/vm-cleanup-hook.yaml). Only needs a kubectl binary. Digest-pinned so +# an upstream retag does not change what runs across the fleet; refresh with +# `docker manifest inspect docker.io/clastix/kubectl:v1.32`. Same pin as the +# etcd-operator hook. +# renovate: datasource=docker depName=docker.io/clastix/kubectl +kubectlImage: + repository: docker.io/clastix/kubectl + tag: v1.32 + digest: sha256:b9ef7d8dbe65bcc81a46c09b8dc7543103055021c4f43287bf59e92a8f4fe05c + pullPolicy: IfNotPresent diff --git a/packages/system/monitoring/templates/alerta/alerta-db.yaml b/packages/system/monitoring/templates/alerta/alerta-db.yaml index af9dc72c5..2bc47af37 100644 --- a/packages/system/monitoring/templates/alerta/alerta-db.yaml +++ b/packages/system/monitoring/templates/alerta/alerta-db.yaml @@ -6,8 +6,8 @@ metadata: spec: instances: 2 {{- $existingCluster := lookup "postgresql.cnpg.io/v1" "Cluster" .Release.Namespace "alerta-db" }} - {{- $image := dig "spec" "imageName" "ghcr.io/cloudnative-pg/postgresql:17.7-standard-trixie" $existingCluster }} - imageName: {{ if regexMatch ":17\\." $image }}ghcr.io/cloudnative-pg/postgresql:17.7-standard-trixie{{ else if regexMatch ":[0-9]+\\.[0-9]+$" $image }}{{ printf "%s-standard-trixie" $image }}{{ else }}{{ $image }}{{ end }} + {{- $image := dig "spec" "imageName" "ghcr.io/cloudnative-pg/postgresql:17.12-standard-trixie" $existingCluster }} + imageName: {{ if regexMatch ":17\\." $image }}ghcr.io/cloudnative-pg/postgresql:17.12-standard-trixie{{ else if regexMatch ":[0-9]+\\.[0-9]+$" $image }}{{ printf "%s-standard-trixie" $image }}{{ else }}{{ $image }}{{ end }} {{- if .Values._cluster.scheduling }} {{- $rawConstraints := get .Values._cluster.scheduling "globalAppTopologySpreadConstraints" }} {{- if $rawConstraints }} diff --git a/packages/system/monitoring/templates/grafana/db.yaml b/packages/system/monitoring/templates/grafana/db.yaml index afc2d0d79..e192ab9f8 100644 --- a/packages/system/monitoring/templates/grafana/db.yaml +++ b/packages/system/monitoring/templates/grafana/db.yaml @@ -5,8 +5,8 @@ metadata: spec: instances: 2 {{- $existingCluster := lookup "postgresql.cnpg.io/v1" "Cluster" .Release.Namespace "grafana-db" }} - {{- $image := dig "spec" "imageName" "ghcr.io/cloudnative-pg/postgresql:17.7-standard-trixie" $existingCluster }} - imageName: {{ if regexMatch ":17\\." $image }}ghcr.io/cloudnative-pg/postgresql:17.7-standard-trixie{{ else if regexMatch ":[0-9]+\\.[0-9]+$" $image }}{{ printf "%s-standard-trixie" $image }}{{ else }}{{ $image }}{{ end }} + {{- $image := dig "spec" "imageName" "ghcr.io/cloudnative-pg/postgresql:17.12-standard-trixie" $existingCluster }} + imageName: {{ if regexMatch ":17\\." $image }}ghcr.io/cloudnative-pg/postgresql:17.12-standard-trixie{{ else if regexMatch ":[0-9]+\\.[0-9]+$" $image }}{{ printf "%s-standard-trixie" $image }}{{ else }}{{ $image }}{{ end }} storage: size: {{ .Values.grafana.db.size }} {{- if .Values._cluster.scheduling }} diff --git a/packages/system/monitoring/templates/vm/vmalert-scrape.yaml b/packages/system/monitoring/templates/vm/vmalert-scrape.yaml index ee406a275..b467d5564 100644 --- a/packages/system/monitoring/templates/vm/vmalert-scrape.yaml +++ b/packages/system/monitoring/templates/vm/vmalert-scrape.yaml @@ -1,3 +1,4 @@ +{{- with first .Values.metricsStorages }} --- apiVersion: operator.victoriametrics.com/v1beta1 kind: VMServiceScrape @@ -13,5 +14,6 @@ spec: selector: matchLabels: app.kubernetes.io/component: monitoring - app.kubernetes.io/instance: vmalert + app.kubernetes.io/instance: vmalert-{{ .name }} app.kubernetes.io/name: vmalert +{{- end }} diff --git a/packages/system/monitoring/tests/alertmanager_blackhole_test.yaml b/packages/system/monitoring/tests/alertmanager_blackhole_test.yaml new file mode 100644 index 000000000..d4e366180 --- /dev/null +++ b/packages/system/monitoring/tests/alertmanager_blackhole_test.yaml @@ -0,0 +1,51 @@ +suite: Alertmanager blackhole route +templates: + - templates/alerta/alerta.yaml + +release: + name: monitoring + namespace: tenant-root + +set: + _cluster: + root-host: example.org + _namespace: + host: tenant-root.example.org + ingress: tenant-root + +# Rules labelled severity="none", InfoInhibitor among them, exist to be +# dropped, and Alerta answers that severity with a 500. Only the heartbeat +# route may come ahead of the blackhole, so no delivering route claims them. +tests: + - it: drops severity none ahead of every delivering route + asserts: + - documentSelector: + path: metadata.labels.app + value: alertmanager + matchRegex: + path: stringData["alertmanager.yaml"] + pattern: '\n routes:\n - receiver: alerta_no_resolve\n repeat_interval: 1m\n matchers:\n - .event="Heartbeat".\n - receiver: blackhole\n matchers:\n - .severity="none".\n' + + - it: keeps severity none out of email even when its alert name is listed + set: + alerta: + alerts: + email: + to: "oncall@example.org" + from: "alerts@example.org" + smarthost: "smtp.example.org:465" + alertnames: + - InfoInhibitor + asserts: + - documentSelector: + path: metadata.labels.app + value: alertmanager + matchRegex: + path: stringData["alertmanager.yaml"] + pattern: '\n routes:\n - receiver: alerta_no_resolve\n repeat_interval: 1m\n matchers:\n - .event="Heartbeat".\n - receiver: blackhole\n matchers:\n - .severity="none".\n' + - documentSelector: + path: metadata.labels.app + value: alertmanager + matchRegex: + path: stringData["alertmanager.yaml"] + pattern: '(?s)\n - receiver: blackhole\n matchers:\n - .severity="none".\n.*\n - receiver: email\n group_wait: 1m\n group_interval: 5m\n repeat_interval: .12h.\n matchers:\n - .alertname=~"\^\(InfoInhibitor\)\$".\n' diff --git a/packages/system/monitoring/tests/vmalert_scrape_test.yaml b/packages/system/monitoring/tests/vmalert_scrape_test.yaml new file mode 100644 index 000000000..1dfb9ec3e --- /dev/null +++ b/packages/system/monitoring/tests/vmalert_scrape_test.yaml @@ -0,0 +1,38 @@ +suite: vmalert metrics are scraped +templates: + - templates/vm/vmalert-scrape.yaml + +release: + name: monitoring + namespace: tenant-root + +set: + _cluster: + root-host: example.org + _namespace: + host: tenant-root.example.org + ingress: tenant-root + metricsStorages: + - name: shortterm + retentionPeriod: "3d" + deduplicationInterval: "15s" + - name: longterm + retentionPeriod: "14d" + deduplicationInterval: "5m" + +tests: + - it: selects the Service of the VMAlert the chart renders + asserts: + - equal: + path: spec.selector.matchLabels + value: + app.kubernetes.io/component: monitoring + app.kubernetes.io/instance: vmalert-shortterm + app.kubernetes.io/name: vmalert + + - it: renders nothing without metrics storages, like the VMAlert itself + set: + metricsStorages: [] + asserts: + - hasDocuments: + count: 0 diff --git a/packages/system/piraeus-operator/alerts/piraeus-datastore.yaml b/packages/system/piraeus-operator/alerts/piraeus-datastore.yaml index ab679d663..8be364a72 100644 --- a/packages/system/piraeus-operator/alerts/piraeus-datastore.yaml +++ b/packages/system/piraeus-operator/alerts/piraeus-datastore.yaml @@ -29,8 +29,8 @@ spec: LINSTOR Satellite "{{ $labels.hostname }}" reports {{ $value }} errors in the last 15 minutes. Use "linstor error-reports list --nodes {{ $labels.hostname }}" to inspect the reports. expr: | - increase(linstor_error_reports_count{module="SATELLITE"}[15m]) > 0 - and on(instance, job) + increase((max by (hostname) (last_over_time(linstor_error_reports_count{module="SATELLITE"}[1h])))[15m:1m]) > 0 + and on() min_over_time(up{job="linstor-controller"}[15m]) == 1 labels: severity: warning @@ -39,7 +39,7 @@ spec: description: | LINSTOR Controller reports {{ $value }} errors in the last 15 minutes. Use "linstor error-reports list --since 15minutes" to see them. - expr: increase(linstor_error_reports_count{module="CONTROLLER"}[15m]) > 0 + expr: increase((max by (hostname) (last_over_time(linstor_error_reports_count{module="CONTROLLER"}[1h])))[15m:1m]) > 0 labels: severity: warning - alert: linstorSatelliteNotOnline diff --git a/packages/system/postgres-rd/cozyrds/postgres.yaml b/packages/system/postgres-rd/cozyrds/postgres.yaml index 217febdb6..ef67e44cd 100644 --- a/packages/system/postgres-rd/cozyrds/postgres.yaml +++ b/packages/system/postgres-rd/cozyrds/postgres.yaml @@ -8,7 +8,7 @@ spec: singular: postgres plural: postgreses openAPISchema: |- - {"title":"Chart Values","type":"object","properties":{"replicas":{"description":"Number of Postgres replicas.","type":"integer","default":2},"resources":{"description":"Explicit CPU and memory configuration for each PostgreSQL replica. When omitted, the preset defined in `resourcesPreset` is applied.","type":"object","default":{},"properties":{"cpu":{"description":"CPU available to each replica.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"memory":{"description":"Memory (RAM) available to each replica.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true}}},"resourcesPreset":{"description":"Default sizing preset used when `resources` is omitted.","type":"string","default":"t1.micro","enum":["t1.nano","t1.micro","t1.small","t1.medium","t1.large","t1.xlarge","t1.2xlarge","t1.4xlarge","c1.nano","c1.micro","c1.small","c1.medium","c1.large","c1.xlarge","c1.2xlarge","c1.4xlarge","s1.nano","s1.micro","s1.small","s1.medium","s1.large","s1.xlarge","s1.2xlarge","s1.4xlarge","u1.nano","u1.micro","u1.small","u1.medium","u1.large","u1.xlarge","u1.2xlarge","u1.4xlarge","m1.nano","m1.micro","m1.small","m1.medium","m1.large","m1.xlarge","m1.2xlarge","m1.4xlarge","nano","micro","small","medium","large","xlarge","2xlarge"]},"size":{"description":"Persistent Volume Claim size available for application data.","default":"10Gi","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"storageClass":{"description":"StorageClass used to store the data.","type":"string","default":"","x-kubernetes-validations":[{"rule":"self == oldSelf","message":"storageClass is immutable"}],"x-cozystack-options":{"source":"storageclass"}},"external":{"description":"Enable external access from outside the cluster.","type":"boolean","default":false},"version":{"description":"PostgreSQL major version to deploy","type":"string","default":"v18","enum":["v18","v17","v16","v15","v14","v13"]},"tls":{"description":"TLS configuration for server connections.","type":"object","default":{},"properties":{"enabled":{"description":"Tri-state switch controlling whether the chart injects the external hostname into the operator-managed CNPG cert via spec.certificates.serverAltDNSNames. When omitted, the chart injects the SAN if `external: true` and skips it otherwise. Set explicitly to `true` to inject regardless of `external` (no-op when `external: false` since there is no external hostname to add). Set to `false` to skip injection. Note that CNPG keeps its built-in TLS on the wire regardless of this flag — this toggle only controls the chart-side SAN injection; to disable PostgreSQL TLS entirely set `postgresql.parameters.ssl = \"off\"` at the CNPG layer.","type":"boolean"}}},"postgresql":{"description":"PostgreSQL server configuration.","type":"object","default":{},"properties":{"parameters":{"description":"PostgreSQL server parameters. Values may be strings or integers; integers are coerced to strings by the template (e.g. both `max_connections: 100` and `max_connections: \"100\"` are accepted). BLOCKED (enable arbitrary code execution): archive_command, restore_command, ssl_passphrase_command, archive_cleanup_command, recovery_end_command, dynamic_library_path, local_preload_libraries, session_preload_libraries, shared_preload_libraries. Do NOT override CloudNativePG-managed parameters: archive_mode, primary_conninfo, wal_level, max_replication_slots.","type":"object","default":{"max_connections":"100"},"additionalProperties":{"anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true}}}},"quorum":{"description":"Quorum configuration for synchronous replication.","type":"object","default":{},"required":["maxSyncReplicas","minSyncReplicas"],"properties":{"maxSyncReplicas":{"description":"Maximum number of synchronous replicas allowed (must be less than total replicas).","type":"integer","default":0},"minSyncReplicas":{"description":"Minimum number of synchronous replicas required for commit.","type":"integer","default":0}}},"users":{"description":"Users configuration map.","type":"object","default":{},"additionalProperties":{"type":"object","properties":{"password":{"description":"Password for the user.","type":"string"},"replication":{"description":"Whether the user has replication privileges.","type":"boolean"}}}},"databases":{"description":"Databases configuration map.","type":"object","default":{},"additionalProperties":{"type":"object","properties":{"extensions":{"description":"List of enabled PostgreSQL extensions.","type":"array","items":{"type":"string"}},"roles":{"description":"Roles assigned to users.","type":"object","properties":{"admin":{"description":"List of users with admin privileges.","type":"array","items":{"type":"string"}},"readonly":{"description":"List of users with read-only privileges.","type":"array","items":{"type":"string"}}}}}}},"backup":{"description":"Backup configuration.","type":"object","default":{},"required":["enabled"],"properties":{"destinationPath":{"description":"DEPRECATED. Per-tenant S3 configuration is superseded by the platform-managed `cozy-default` BackupClass and the `cozy-backups` system bucket. Leave empty for new installations; the BackupClass driver picks up the system-managed coordinates. Kept for in-place upgrade compatibility.","type":"string","default":"s3://bucket/path/to/folder/"},"enabled":{"description":"Enable regular backups.","type":"boolean","default":false},"endpointCA":{"description":"DEPRECATED. Pre-existing Secret with the CA bundle the barman-cloud plugin should trust when reaching a self-signed S3 endpoint. Used for both backup and bootstrap recovery in the legacy chart-managed flow.","type":"object","default":{},"properties":{"key":{"description":"Key within the Secret containing the CA bundle. Defaults to `ca.crt`.","type":"string","default":""},"name":{"description":"Name of the Secret in the application namespace. Empty means no endpointCA is emitted (the plugin uses the system trust store).","type":"string","default":""}}},"endpointURL":{"description":"DEPRECATED. See `destinationPath`.","type":"string","default":"http://minio-gateway-service:9000"},"retentionPolicy":{"description":"Retention policy (e.g. \"30d\").","type":"string","default":"30d"},"s3AccessKey":{"description":"DEPRECATED. Tenants no longer supply S3 keys; the system Bucket Secret is projected into the tenant namespace by the backup controller. Ignored when `s3CredentialsSecret.name` is set or `useSystemBucket` is true. The chart skips materialising `-s3-creds` whenever this field is empty so a default install does not leak placeholder credentials into the tenant namespace.","type":"string","default":""},"s3CredentialsSecret":{"description":"DEPRECATED. Pre-existing Secret with S3 credentials. Use the platform-managed `cozy-default` BackupClass instead. When set, the chart references this Secret directly (legacy chart-managed flow). The CNPG backup driver writes this field on restore so credentials never land in the CR `.spec`.","type":"object","default":{},"properties":{"accessKeyIDKey":{"description":"Key in the Secret holding the access key ID. Defaults to `AWS_ACCESS_KEY_ID`.","type":"string","default":""},"name":{"description":"Name of the Secret in the application namespace. Empty means the chart materialises `-s3-creds` from `s3AccessKey`/`s3SecretKey`.","type":"string","default":""},"secretAccessKeyKey":{"description":"Key in the Secret holding the secret access key. Defaults to `AWS_SECRET_ACCESS_KEY`.","type":"string","default":""}}},"s3SecretKey":{"description":"DEPRECATED. See `s3AccessKey`.","type":"string","default":""},"schedule":{"description":"Legacy. Cron schedule (CNPG 6-field format) for the chart-emitted ScheduledBackup. Empty means no chart-managed schedule, which is the recommended setup when a `BackupClass` from `backups.cozystack.io` already drives backup orchestration. In the legacy chart-managed flow `spec.plugins` plus the barman-cloud ObjectStore is rendered when `backup.enabled=true` AND `useSystemBucket=false` AND `destinationPath` is non-empty AND inline-or-external creds are supplied; in the platform `useSystemBucket=true` flow the chart skips emitting `spec.plugins` and the CNPG driver SSA-applies the ObjectStore and patches `spec.plugins` onto the live Cluster at first BackupJob time.","type":"string","default":""},"useSystemBucket":{"description":"Opt-in: when true, the chart-emitted `-s3-creds` Secret is skipped AND `spec.plugins` (plus the barman-cloud ObjectStore) is left UNSET in the chart-rendered Cluster — the cozy-default BackupClass driver SSA-applies an ObjectStore (carrying destinationPath/endpointURL/credentials) and patches `spec.plugins` on the live Cluster when the first BackupJob runs. Consequence: plugin WAL archiving is NOT active until that first BackupJob fires; WAL accumulates on the PVC in the meantime, so fire an ad-hoc BackupJob immediately after enabling the flag on existing releases. Use together with the platform `cozy-default` BackupClass — tenants do not need to fill `s3AccessKey`/`s3SecretKey` or `destinationPath`/`endpointURL`. The destination path automatically scopes to `s3://cozy-backups///`.","type":"boolean","default":false}}},"bootstrap":{"description":"Bootstrap configuration.","type":"object","default":{},"required":["enabled","oldName"],"properties":{"enabled":{"description":"Whether to restore from a backup.","type":"boolean","default":false},"newServerName":{"description":"WAL-archive server name (S3 path prefix) the RESTORED cluster writes to. Must differ from `serverName` (the recovery source) so a restored cluster archives to a fresh, empty prefix and barman-cloud-check-wal-archive passes while it recovers from the source's prefix. The CNPG backup driver sets this on restore; empty means the cluster archives under its own name.","type":"string","default":""},"oldName":{"description":"Previous cluster name before deletion.","type":"string","default":""},"recoveryTime":{"description":"Timestamp (RFC3339) for point-in-time recovery; empty means latest.","type":"string","default":""},"serverName":{"description":"Server name (S3 path prefix) used by the original cluster when writing backups; passed to the barman-cloud plugin via `externalClusters[].plugin.parameters.serverName`. Defaults to `bootstrap.oldName`. Set this only when the original cluster wrote backups under an explicit server name that differed from its Kubernetes resource name.","type":"string","default":""}}}}} + {"title":"Chart Values","type":"object","properties":{"replicas":{"description":"Number of Postgres replicas.","type":"integer","default":2},"resources":{"description":"Explicit CPU and memory configuration for each PostgreSQL replica. When omitted, the preset defined in `resourcesPreset` is applied.","type":"object","default":{},"properties":{"cpu":{"description":"CPU available to each replica.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"memory":{"description":"Memory (RAM) available to each replica.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true}}},"resourcesPreset":{"description":"Default sizing preset used when `resources` is omitted.","type":"string","default":"t1.micro","enum":["t1.nano","t1.micro","t1.small","t1.medium","t1.large","t1.xlarge","t1.2xlarge","t1.4xlarge","c1.nano","c1.micro","c1.small","c1.medium","c1.large","c1.xlarge","c1.2xlarge","c1.4xlarge","s1.nano","s1.micro","s1.small","s1.medium","s1.large","s1.xlarge","s1.2xlarge","s1.4xlarge","u1.nano","u1.micro","u1.small","u1.medium","u1.large","u1.xlarge","u1.2xlarge","u1.4xlarge","m1.nano","m1.micro","m1.small","m1.medium","m1.large","m1.xlarge","m1.2xlarge","m1.4xlarge","nano","micro","small","medium","large","xlarge","2xlarge"]},"size":{"description":"Persistent Volume Claim size available for application data.","default":"10Gi","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"storageClass":{"description":"StorageClass used to store the data.","type":"string","default":"","x-kubernetes-validations":[{"rule":"self == oldSelf","message":"storageClass is immutable"}],"x-cozystack-options":{"source":"storageclass"}},"external":{"description":"Enable external access from outside the cluster.","type":"boolean","default":false},"version":{"description":"PostgreSQL major version to deploy","type":"string","default":"v18","enum":["v18","v17","v16","v15","v14","v13"]},"tls":{"description":"TLS configuration for server connections.","type":"object","default":{},"properties":{"enabled":{"description":"Tri-state switch controlling whether the chart injects the external hostname into the operator-managed CNPG cert via spec.certificates.serverAltDNSNames. When omitted, the chart injects the SAN if `external: true` and skips it otherwise. Set explicitly to `true` to inject regardless of `external` (no-op when `external: false` since there is no external hostname to add). Set to `false` to skip injection. Note that CNPG keeps its built-in TLS on the wire regardless of this flag — this toggle only controls the chart-side SAN injection; to disable PostgreSQL TLS entirely set `postgresql.parameters.ssl = \"off\"` at the CNPG layer.","type":"boolean"}}},"postgresql":{"description":"PostgreSQL server configuration.","type":"object","default":{},"properties":{"parameters":{"description":"PostgreSQL server parameters. Values may be strings or integers; integers are coerced to strings by the template (e.g. both `max_connections: 100` and `max_connections: \"100\"` are accepted). BLOCKED (enable arbitrary code execution): archive_command, restore_command, ssl_passphrase_command, archive_cleanup_command, recovery_end_command, dynamic_library_path, local_preload_libraries, session_preload_libraries, shared_preload_libraries. Do NOT override CloudNativePG-managed parameters: archive_mode, primary_conninfo, wal_level, max_replication_slots.","type":"object","default":{"max_connections":"100"},"additionalProperties":{"anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true}}}},"quorum":{"description":"Quorum configuration for synchronous replication.","type":"object","default":{},"required":["maxSyncReplicas","minSyncReplicas"],"properties":{"maxSyncReplicas":{"description":"Maximum number of synchronous replicas allowed (must be less than total replicas).","type":"integer","default":0},"minSyncReplicas":{"description":"Minimum number of synchronous replicas required for commit.","type":"integer","default":0}}},"users":{"description":"Users configuration map.","type":"object","default":{},"additionalProperties":{"type":"object","properties":{"password":{"description":"Password for the user.","type":"string"},"replication":{"description":"Whether the user has replication privileges.","type":"boolean"}}}},"databases":{"description":"Databases configuration map.","type":"object","default":{},"additionalProperties":{"type":"object","properties":{"extensions":{"description":"List of enabled PostgreSQL extensions.","type":"array","items":{"type":"string"}},"roles":{"description":"Roles assigned to users.","type":"object","properties":{"admin":{"description":"List of users with admin privileges.","type":"array","items":{"type":"string"}},"readonly":{"description":"List of users with read-only privileges.","type":"array","items":{"type":"string"}}}}}}},"backup":{"description":"Backup configuration.","type":"object","default":{},"required":["enabled"],"properties":{"destinationPath":{"description":"DEPRECATED. Per-tenant S3 configuration is superseded by the platform-managed `cozy-default` BackupClass and the `cozy-backups` system bucket. Leave empty for new installations; the BackupClass driver picks up the system-managed coordinates. Kept for in-place upgrade compatibility.","type":"string","default":"s3://bucket/path/to/folder/"},"enabled":{"description":"Enable regular backups.","type":"boolean","default":false},"endpointCA":{"description":"DEPRECATED. Pre-existing Secret with the CA bundle the barman-cloud plugin should trust when reaching a self-signed S3 endpoint. Used for both backup and bootstrap recovery in the legacy chart-managed flow.","type":"object","default":{},"properties":{"key":{"description":"Key within the Secret containing the CA bundle. Defaults to `ca.crt`.","type":"string","default":""},"name":{"description":"Name of the Secret in the application namespace. Empty means no endpointCA is emitted (the plugin uses the system trust store).","type":"string","default":""}}},"endpointURL":{"description":"DEPRECATED. See `destinationPath`.","type":"string","default":"http://minio-gateway-service:9000"},"retentionPolicy":{"description":"Retention policy (e.g. \"30d\").","type":"string","default":"30d"},"s3AccessKey":{"description":"DEPRECATED. Tenants no longer supply S3 keys; the system Bucket Secret is projected into the tenant namespace by the backup controller. Ignored when `s3CredentialsSecret.name` is set or `useSystemBucket` is true. The chart skips materialising `-s3-creds` whenever this field is empty so a default install does not leak placeholder credentials into the tenant namespace.","type":"string","default":""},"s3CredentialsSecret":{"description":"DEPRECATED. Pre-existing Secret with S3 credentials. Use the platform-managed `cozy-default` BackupClass instead. When set, the chart references this Secret directly (legacy chart-managed flow). The CNPG backup driver writes this field on restore so credentials never land in the CR `.spec`.","type":"object","default":{},"properties":{"accessKeyIDKey":{"description":"Key in the Secret holding the access key ID. Defaults to `AWS_ACCESS_KEY_ID`.","type":"string","default":""},"name":{"description":"Name of the Secret in the application namespace. Empty means the chart materialises `-s3-creds` from `s3AccessKey`/`s3SecretKey`.","type":"string","default":""},"secretAccessKeyKey":{"description":"Key in the Secret holding the secret access key. Defaults to `AWS_SECRET_ACCESS_KEY`.","type":"string","default":""}}},"s3SecretKey":{"description":"DEPRECATED. See `s3AccessKey`.","type":"string","default":""},"schedule":{"description":"Legacy. Cron schedule for the chart-emitted ScheduledBackup, either a standard five-field cron such as `0 2 * * *` for every day at 02:00, or six fields with leading seconds such as `0 0 2 * * *` for the same time. Empty means no chart-managed schedule, which is the recommended setup when a `BackupClass` from `backups.cozystack.io` already drives backup orchestration. In the legacy chart-managed flow `spec.plugins` plus the barman-cloud ObjectStore is rendered when `backup.enabled=true` AND `useSystemBucket=false` AND `destinationPath` is non-empty AND inline-or-external creds are supplied; in the platform `useSystemBucket=true` flow the chart skips emitting `spec.plugins` and the CNPG driver SSA-applies the ObjectStore and patches `spec.plugins` onto the live Cluster at first BackupJob time.","type":"string","default":""},"useSystemBucket":{"description":"Opt-in: when true, the chart-emitted `-s3-creds` Secret is skipped AND `spec.plugins` (plus the barman-cloud ObjectStore) is left UNSET in the chart-rendered Cluster — the cozy-default BackupClass driver SSA-applies an ObjectStore (carrying destinationPath/endpointURL/credentials) and patches `spec.plugins` on the live Cluster when the first BackupJob runs. Consequence: plugin WAL archiving is NOT active until that first BackupJob fires; WAL accumulates on the PVC in the meantime, so fire an ad-hoc BackupJob immediately after enabling the flag on existing releases. Use together with the platform `cozy-default` BackupClass — tenants do not need to fill `s3AccessKey`/`s3SecretKey` or `destinationPath`/`endpointURL`. The destination path automatically scopes to `s3://cozy-backups///`.","type":"boolean","default":false}}},"bootstrap":{"description":"Bootstrap configuration.","type":"object","default":{},"required":["enabled","oldName"],"properties":{"enabled":{"description":"Whether to restore from a backup.","type":"boolean","default":false},"newServerName":{"description":"WAL-archive server name (S3 path prefix) the RESTORED cluster writes to. Must differ from `serverName` (the recovery source) so a restored cluster archives to a fresh, empty prefix and barman-cloud-check-wal-archive passes while it recovers from the source's prefix. The CNPG backup driver sets this on restore; empty means the cluster archives under its own name.","type":"string","default":""},"oldName":{"description":"Previous cluster name before deletion.","type":"string","default":""},"recoveryTime":{"description":"Timestamp (RFC3339) for point-in-time recovery; empty means latest.","type":"string","default":""},"serverName":{"description":"Server name (S3 path prefix) used by the original cluster when writing backups; passed to the barman-cloud plugin via `externalClusters[].plugin.parameters.serverName`. Defaults to `bootstrap.oldName`. Set this only when the original cluster wrote backups under an explicit server name that differed from its Kubernetes resource name.","type":"string","default":""}}}}} release: prefix: postgres- labels: diff --git a/packages/system/seaweedfs-db/templates/database.yaml b/packages/system/seaweedfs-db/templates/database.yaml index 807bd13af..282141d4c 100644 --- a/packages/system/seaweedfs-db/templates/database.yaml +++ b/packages/system/seaweedfs-db/templates/database.yaml @@ -6,8 +6,8 @@ metadata: spec: instances: {{ .Values.db.replicas }} {{- $existingCluster := lookup "postgresql.cnpg.io/v1" "Cluster" .Release.Namespace "seaweedfs-db" }} - {{- $image := dig "spec" "imageName" "ghcr.io/cloudnative-pg/postgresql:17.7-standard-trixie" $existingCluster }} - imageName: {{ if regexMatch ":17\\." $image }}ghcr.io/cloudnative-pg/postgresql:17.7-standard-trixie{{ else if regexMatch ":[0-9]+\\.[0-9]+$" $image }}{{ printf "%s-standard-trixie" $image }}{{ else }}{{ $image }}{{ end }} + {{- $image := dig "spec" "imageName" "ghcr.io/cloudnative-pg/postgresql:17.12-standard-trixie" $existingCluster }} + imageName: {{ if regexMatch ":17\\." $image }}ghcr.io/cloudnative-pg/postgresql:17.12-standard-trixie{{ else if regexMatch ":[0-9]+\\.[0-9]+$" $image }}{{ printf "%s-standard-trixie" $image }}{{ else }}{{ $image }}{{ end }} storage: size: {{ .Values.db.size }} {{- with .Values.db.storageClass }} diff --git a/packages/system/seaweedfs-db/tests/database_test.yaml b/packages/system/seaweedfs-db/tests/database_test.yaml index 3eff5a112..1fa9a80ee 100644 --- a/packages/system/seaweedfs-db/tests/database_test.yaml +++ b/packages/system/seaweedfs-db/tests/database_test.yaml @@ -43,14 +43,14 @@ tests: path: spec.storage.storageClass value: replicated - - it: fresh install pins the default postgres 17.7 image + - it: fresh install pins the default postgres 17.12 image release: name: seaweedfs-db namespace: cozy-seaweedfs asserts: - equal: path: spec.imageName - value: ghcr.io/cloudnative-pg/postgresql:17.7-standard-trixie + value: ghcr.io/cloudnative-pg/postgresql:17.12-standard-trixie - it: carries the apiserver-allow inherited label release: diff --git a/packages/system/seaweedfs-rd/cozyrds/seaweedfs.yaml b/packages/system/seaweedfs-rd/cozyrds/seaweedfs.yaml index 80ef77bea..60532840b 100644 --- a/packages/system/seaweedfs-rd/cozyrds/seaweedfs.yaml +++ b/packages/system/seaweedfs-rd/cozyrds/seaweedfs.yaml @@ -8,7 +8,7 @@ spec: singular: seaweedfs plural: seaweedfses openAPISchema: |- - {"title":"Chart Values","type":"object","properties":{"host":{"description":"The hostname used to access SeaweedFS externally (defaults to 's3' subdomain for the tenant host).","type":"string","default":""},"topology":{"description":"The topology of the SeaweedFS cluster.","type":"string","default":"Simple","enum":["Simple","MultiZone","Client"]},"replicationFactor":{"description":"Replication factor: number of replicas for each volume in the SeaweedFS cluster.","type":"integer","default":2},"db":{"description":"Database configuration.","type":"object","default":{},"properties":{"replicas":{"description":"Number of database replicas.","type":"integer","default":2},"resources":{"description":"Explicit CPU and memory configuration. When omitted, the preset defined in `resourcesPreset` is applied.","type":"object","default":{},"properties":{"cpu":{"description":"Number of CPU cores allocated.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"memory":{"description":"Amount of memory allocated.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true}}},"resourcesPreset":{"description":"Default sizing preset used when `resources` is omitted.","type":"string","default":"t1.small","enum":["t1.nano","t1.micro","t1.small","t1.medium","t1.large","t1.xlarge","t1.2xlarge","t1.4xlarge","c1.nano","c1.micro","c1.small","c1.medium","c1.large","c1.xlarge","c1.2xlarge","c1.4xlarge","s1.nano","s1.micro","s1.small","s1.medium","s1.large","s1.xlarge","s1.2xlarge","s1.4xlarge","u1.nano","u1.micro","u1.small","u1.medium","u1.large","u1.xlarge","u1.2xlarge","u1.4xlarge","m1.nano","m1.micro","m1.small","m1.medium","m1.large","m1.xlarge","m1.2xlarge","m1.4xlarge","nano","micro","small","medium","large","xlarge","2xlarge"]},"size":{"description":"Persistent Volume size.","default":"10Gi","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"storageClass":{"description":"StorageClass used to store the data.","type":"string","default":""}}},"master":{"description":"Master service configuration.","type":"object","default":{},"properties":{"replicas":{"description":"Number of master replicas.","type":"integer","default":3},"resources":{"description":"Explicit CPU and memory configuration. When omitted, the preset defined in `resourcesPreset` is applied.","type":"object","default":{},"properties":{"cpu":{"description":"Number of CPU cores allocated.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"memory":{"description":"Amount of memory allocated.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true}}},"resourcesPreset":{"description":"Default sizing preset used when `resources` is omitted.","type":"string","default":"t1.small","enum":["t1.nano","t1.micro","t1.small","t1.medium","t1.large","t1.xlarge","t1.2xlarge","t1.4xlarge","c1.nano","c1.micro","c1.small","c1.medium","c1.large","c1.xlarge","c1.2xlarge","c1.4xlarge","s1.nano","s1.micro","s1.small","s1.medium","s1.large","s1.xlarge","s1.2xlarge","s1.4xlarge","u1.nano","u1.micro","u1.small","u1.medium","u1.large","u1.xlarge","u1.2xlarge","u1.4xlarge","m1.nano","m1.micro","m1.small","m1.medium","m1.large","m1.xlarge","m1.2xlarge","m1.4xlarge","nano","micro","small","medium","large","xlarge","2xlarge"]}}},"filer":{"description":"Filer service configuration.","type":"object","default":{},"properties":{"grpcHost":{"description":"The hostname used to expose or access the filer service externally.","type":"string","default":""},"grpcPort":{"description":"The port used to access the filer service externally.","type":"integer","default":443},"replicas":{"description":"Number of filer replicas.","type":"integer","default":2},"resources":{"description":"Explicit CPU and memory configuration. When omitted, the preset defined in `resourcesPreset` is applied.","type":"object","default":{},"properties":{"cpu":{"description":"Number of CPU cores allocated.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"memory":{"description":"Amount of memory allocated.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true}}},"resourcesPreset":{"description":"Default sizing preset used when `resources` is omitted.","type":"string","default":"t1.small","enum":["t1.nano","t1.micro","t1.small","t1.medium","t1.large","t1.xlarge","t1.2xlarge","t1.4xlarge","c1.nano","c1.micro","c1.small","c1.medium","c1.large","c1.xlarge","c1.2xlarge","c1.4xlarge","s1.nano","s1.micro","s1.small","s1.medium","s1.large","s1.xlarge","s1.2xlarge","s1.4xlarge","u1.nano","u1.micro","u1.small","u1.medium","u1.large","u1.xlarge","u1.2xlarge","u1.4xlarge","m1.nano","m1.micro","m1.small","m1.medium","m1.large","m1.xlarge","m1.2xlarge","m1.4xlarge","nano","micro","small","medium","large","xlarge","2xlarge"]},"whitelist":{"description":"A list of IP addresses or CIDR ranges that are allowed to access the filer service.","type":"array","default":[],"items":{"type":"string"}}}},"volume":{"description":"Volume service configuration.","type":"object","default":{},"properties":{"diskType":{"description":"SeaweedFS disk type tag for the default volume servers (e.g., \"hdd\", \"ssd\").","type":"string","default":""},"pools":{"description":"A map of storage pools. Each pool creates a separate Volume StatefulSet with its own disk type.","type":"object","default":{},"additionalProperties":{"type":"object","required":["diskType"],"properties":{"diskType":{"description":"SeaweedFS disk type tag (e.g., \"ssd\", \"hdd\", \"nvme\").","type":"string"},"replicas":{"description":"Number of volume replicas. Defaults to volume.replicas (Simple) or zone.replicas/volume.replicas (MultiZone).","type":"integer"},"resources":{"description":"Explicit CPU and memory configuration. When omitted, the preset defined in `resourcesPreset` is applied.","type":"object","properties":{"cpu":{"description":"Number of CPU cores allocated.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"memory":{"description":"Amount of memory allocated.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true}}},"resourcesPreset":{"description":"Default sizing preset used when `resources` is omitted. Defaults to volume.resourcesPreset.","type":"string","enum":["t1.nano","t1.micro","t1.small","t1.medium","t1.large","t1.xlarge","t1.2xlarge","t1.4xlarge","c1.nano","c1.micro","c1.small","c1.medium","c1.large","c1.xlarge","c1.2xlarge","c1.4xlarge","s1.nano","s1.micro","s1.small","s1.medium","s1.large","s1.xlarge","s1.2xlarge","s1.4xlarge","u1.nano","u1.micro","u1.small","u1.medium","u1.large","u1.xlarge","u1.2xlarge","u1.4xlarge","m1.nano","m1.micro","m1.small","m1.medium","m1.large","m1.xlarge","m1.2xlarge","m1.4xlarge","nano","micro","small","medium","large","xlarge","2xlarge"]},"size":{"description":"Persistent Volume size. Defaults to volume.size (Simple) or zone.size/volume.size (MultiZone).","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"storageClass":{"description":"Kubernetes StorageClass for the pool. Defaults to volume.storageClass.","type":"string"}}}},"replicas":{"description":"Number of volume replicas.","type":"integer","default":2},"resources":{"description":"Explicit CPU and memory configuration. When omitted, the preset defined in `resourcesPreset` is applied.","type":"object","default":{},"properties":{"cpu":{"description":"Number of CPU cores allocated.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"memory":{"description":"Amount of memory allocated.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true}}},"resourcesPreset":{"description":"Default sizing preset used when `resources` is omitted.","type":"string","default":"t1.small","enum":["t1.nano","t1.micro","t1.small","t1.medium","t1.large","t1.xlarge","t1.2xlarge","t1.4xlarge","c1.nano","c1.micro","c1.small","c1.medium","c1.large","c1.xlarge","c1.2xlarge","c1.4xlarge","s1.nano","s1.micro","s1.small","s1.medium","s1.large","s1.xlarge","s1.2xlarge","s1.4xlarge","u1.nano","u1.micro","u1.small","u1.medium","u1.large","u1.xlarge","u1.2xlarge","u1.4xlarge","m1.nano","m1.micro","m1.small","m1.medium","m1.large","m1.xlarge","m1.2xlarge","m1.4xlarge","nano","micro","small","medium","large","xlarge","2xlarge"]},"size":{"description":"Persistent Volume size.","default":"10Gi","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"storageClass":{"description":"StorageClass used to store the data.","type":"string","default":""},"zones":{"description":"A map of zones for MultiZone topology. Each zone can have its own number of replicas and size.","type":"object","default":{},"additionalProperties":{"type":"object","properties":{"dataCenter":{"description":"SeaweedFS data center name for this zone. Defaults to the zone name.","type":"string"},"nodeSelector":{"description":"YAML nodeSelector for this zone (default: topology.kubernetes.io/zone: ).","type":"string"},"pools":{"description":"A map of storage pools for this zone. Each pool creates a separate Volume StatefulSet per zone.","type":"object","additionalProperties":{"type":"object","required":["diskType"],"properties":{"diskType":{"description":"SeaweedFS disk type tag (e.g., \"ssd\", \"hdd\", \"nvme\").","type":"string"},"replicas":{"description":"Number of volume replicas. Defaults to volume.replicas (Simple) or zone.replicas/volume.replicas (MultiZone).","type":"integer"},"resources":{"description":"Explicit CPU and memory configuration. When omitted, the preset defined in `resourcesPreset` is applied.","type":"object","properties":{"cpu":{"description":"Number of CPU cores allocated.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"memory":{"description":"Amount of memory allocated.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true}}},"resourcesPreset":{"description":"Default sizing preset used when `resources` is omitted. Defaults to volume.resourcesPreset.","type":"string","enum":["t1.nano","t1.micro","t1.small","t1.medium","t1.large","t1.xlarge","t1.2xlarge","t1.4xlarge","c1.nano","c1.micro","c1.small","c1.medium","c1.large","c1.xlarge","c1.2xlarge","c1.4xlarge","s1.nano","s1.micro","s1.small","s1.medium","s1.large","s1.xlarge","s1.2xlarge","s1.4xlarge","u1.nano","u1.micro","u1.small","u1.medium","u1.large","u1.xlarge","u1.2xlarge","u1.4xlarge","m1.nano","m1.micro","m1.small","m1.medium","m1.large","m1.xlarge","m1.2xlarge","m1.4xlarge","nano","micro","small","medium","large","xlarge","2xlarge"]},"size":{"description":"Persistent Volume size. Defaults to volume.size (Simple) or zone.size/volume.size (MultiZone).","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"storageClass":{"description":"Kubernetes StorageClass for the pool. Defaults to volume.storageClass.","type":"string"}}}},"replicas":{"description":"Number of replicas in the zone.","type":"integer"},"size":{"description":"Zone storage size.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"storageClass":{"description":"StorageClass used to store zone data. Defaults to volume.storageClass.","type":"string"}}}}}},"s3":{"description":"S3 service configuration.","type":"object","default":{},"properties":{"replicas":{"description":"Number of S3 replicas.","type":"integer","default":2},"resources":{"description":"Explicit CPU and memory configuration. When omitted, the preset defined in `resourcesPreset` is applied.","type":"object","default":{},"properties":{"cpu":{"description":"Number of CPU cores allocated.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"memory":{"description":"Amount of memory allocated.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true}}},"resourcesPreset":{"description":"Default sizing preset used when `resources` is omitted.","type":"string","default":"t1.small","enum":["t1.nano","t1.micro","t1.small","t1.medium","t1.large","t1.xlarge","t1.2xlarge","t1.4xlarge","c1.nano","c1.micro","c1.small","c1.medium","c1.large","c1.xlarge","c1.2xlarge","c1.4xlarge","s1.nano","s1.micro","s1.small","s1.medium","s1.large","s1.xlarge","s1.2xlarge","s1.4xlarge","u1.nano","u1.micro","u1.small","u1.medium","u1.large","u1.xlarge","u1.2xlarge","u1.4xlarge","m1.nano","m1.micro","m1.small","m1.medium","m1.large","m1.xlarge","m1.2xlarge","m1.4xlarge","nano","micro","small","medium","large","xlarge","2xlarge"]}}}}} + {"title":"Chart Values","type":"object","properties":{"host":{"description":"The hostname used to access SeaweedFS externally (defaults to 's3' subdomain for the tenant host).","type":"string","default":""},"topology":{"description":"The topology of the SeaweedFS cluster.","type":"string","default":"Simple","enum":["Simple","MultiZone","Client"]},"replicationFactor":{"description":"Replication factor: number of replicas for each volume in the SeaweedFS cluster.","type":"integer","default":2},"db":{"description":"Database configuration.","type":"object","default":{},"properties":{"replicas":{"description":"Number of database replicas.","type":"integer","default":2},"resources":{"description":"Explicit CPU and memory configuration. When omitted, the preset defined in `resourcesPreset` is applied.","type":"object","default":{},"properties":{"cpu":{"description":"Number of CPU cores allocated.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"memory":{"description":"Amount of memory allocated.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true}}},"resourcesPreset":{"description":"Default sizing preset used when `resources` is omitted.","type":"string","default":"t1.small","enum":["t1.nano","t1.micro","t1.small","t1.medium","t1.large","t1.xlarge","t1.2xlarge","t1.4xlarge","c1.nano","c1.micro","c1.small","c1.medium","c1.large","c1.xlarge","c1.2xlarge","c1.4xlarge","s1.nano","s1.micro","s1.small","s1.medium","s1.large","s1.xlarge","s1.2xlarge","s1.4xlarge","u1.nano","u1.micro","u1.small","u1.medium","u1.large","u1.xlarge","u1.2xlarge","u1.4xlarge","m1.nano","m1.micro","m1.small","m1.medium","m1.large","m1.xlarge","m1.2xlarge","m1.4xlarge","nano","micro","small","medium","large","xlarge","2xlarge"]},"size":{"description":"Persistent Volume size.","default":"10Gi","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"storageClass":{"description":"StorageClass used to store the data.","type":"string","default":""}}},"master":{"description":"Master service configuration.","type":"object","default":{},"properties":{"replicas":{"description":"Number of master replicas.","type":"integer","default":3},"resources":{"description":"Explicit CPU and memory configuration. When omitted, the preset defined in `resourcesPreset` is applied.","type":"object","default":{},"properties":{"cpu":{"description":"Number of CPU cores allocated.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"memory":{"description":"Amount of memory allocated.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true}}},"resourcesPreset":{"description":"Default sizing preset used when `resources` is omitted.","type":"string","default":"t1.small","enum":["t1.nano","t1.micro","t1.small","t1.medium","t1.large","t1.xlarge","t1.2xlarge","t1.4xlarge","c1.nano","c1.micro","c1.small","c1.medium","c1.large","c1.xlarge","c1.2xlarge","c1.4xlarge","s1.nano","s1.micro","s1.small","s1.medium","s1.large","s1.xlarge","s1.2xlarge","s1.4xlarge","u1.nano","u1.micro","u1.small","u1.medium","u1.large","u1.xlarge","u1.2xlarge","u1.4xlarge","m1.nano","m1.micro","m1.small","m1.medium","m1.large","m1.xlarge","m1.2xlarge","m1.4xlarge","nano","micro","small","medium","large","xlarge","2xlarge"]}}},"filer":{"description":"Filer service configuration.","type":"object","default":{},"properties":{"grpcHost":{"description":"The hostname used to expose or access the filer service externally.","type":"string","default":""},"grpcPort":{"description":"The port used to access the filer service externally.","type":"integer","default":443},"replicas":{"description":"Number of filer replicas.","type":"integer","default":2},"resources":{"description":"Explicit CPU and memory configuration. When omitted, the preset defined in `resourcesPreset` is applied.","type":"object","default":{},"properties":{"cpu":{"description":"Number of CPU cores allocated.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"memory":{"description":"Amount of memory allocated.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true}}},"resourcesPreset":{"description":"Default sizing preset used when `resources` is omitted.","type":"string","default":"t1.small","enum":["t1.nano","t1.micro","t1.small","t1.medium","t1.large","t1.xlarge","t1.2xlarge","t1.4xlarge","c1.nano","c1.micro","c1.small","c1.medium","c1.large","c1.xlarge","c1.2xlarge","c1.4xlarge","s1.nano","s1.micro","s1.small","s1.medium","s1.large","s1.xlarge","s1.2xlarge","s1.4xlarge","u1.nano","u1.micro","u1.small","u1.medium","u1.large","u1.xlarge","u1.2xlarge","u1.4xlarge","m1.nano","m1.micro","m1.small","m1.medium","m1.large","m1.xlarge","m1.2xlarge","m1.4xlarge","nano","micro","small","medium","large","xlarge","2xlarge"]},"whitelist":{"description":"A list of IP addresses or CIDR ranges that are allowed to access the filer service.","type":"array","default":[],"items":{"type":"string"}}}},"volume":{"description":"Volume service configuration.","type":"object","default":{},"properties":{"diskType":{"description":"SeaweedFS disk type tag for the default volume servers (e.g., \"hdd\", \"ssd\").","type":"string","default":""},"pools":{"description":"A map of storage pools. Each pool creates a separate Volume StatefulSet with its own disk type.","type":"object","default":{},"additionalProperties":{"type":"object","required":["diskType"],"properties":{"diskType":{"description":"SeaweedFS disk type tag (e.g., \"ssd\", \"hdd\", \"nvme\").","type":"string"},"replicas":{"description":"Number of volume replicas. Defaults to volume.replicas (Simple) or zone.replicas/volume.replicas (MultiZone).","type":"integer"},"resources":{"description":"Explicit CPU and memory configuration. When omitted, the preset defined in `resourcesPreset` is applied.","type":"object","properties":{"cpu":{"description":"Number of CPU cores allocated.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"memory":{"description":"Amount of memory allocated.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true}}},"resourcesPreset":{"description":"Default sizing preset used when `resources` is omitted. Defaults to volume.resourcesPreset.","type":"string","enum":["t1.nano","t1.micro","t1.small","t1.medium","t1.large","t1.xlarge","t1.2xlarge","t1.4xlarge","c1.nano","c1.micro","c1.small","c1.medium","c1.large","c1.xlarge","c1.2xlarge","c1.4xlarge","s1.nano","s1.micro","s1.small","s1.medium","s1.large","s1.xlarge","s1.2xlarge","s1.4xlarge","u1.nano","u1.micro","u1.small","u1.medium","u1.large","u1.xlarge","u1.2xlarge","u1.4xlarge","m1.nano","m1.micro","m1.small","m1.medium","m1.large","m1.xlarge","m1.2xlarge","m1.4xlarge","nano","micro","small","medium","large","xlarge","2xlarge"]},"size":{"description":"Persistent Volume size. Defaults to volume.size (Simple) or zone.size/volume.size (MultiZone).","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"storageClass":{"description":"Kubernetes StorageClass for the pool. Defaults to volume.storageClass.","type":"string"}}}},"replicas":{"description":"Number of volume replicas.","type":"integer","default":2},"resources":{"description":"Explicit CPU and memory configuration. When omitted, the preset defined in `resourcesPreset` is applied.","type":"object","default":{},"properties":{"cpu":{"description":"Number of CPU cores allocated.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"memory":{"description":"Amount of memory allocated.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true}}},"resourcesPreset":{"description":"Default sizing preset used when `resources` is omitted.","type":"string","default":"t1.small","enum":["t1.nano","t1.micro","t1.small","t1.medium","t1.large","t1.xlarge","t1.2xlarge","t1.4xlarge","c1.nano","c1.micro","c1.small","c1.medium","c1.large","c1.xlarge","c1.2xlarge","c1.4xlarge","s1.nano","s1.micro","s1.small","s1.medium","s1.large","s1.xlarge","s1.2xlarge","s1.4xlarge","u1.nano","u1.micro","u1.small","u1.medium","u1.large","u1.xlarge","u1.2xlarge","u1.4xlarge","m1.nano","m1.micro","m1.small","m1.medium","m1.large","m1.xlarge","m1.2xlarge","m1.4xlarge","nano","micro","small","medium","large","xlarge","2xlarge"]},"size":{"description":"Persistent Volume size.","default":"10Gi","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"storageClass":{"description":"StorageClass used to store the data.","type":"string","default":""},"zones":{"description":"A map of zones for MultiZone topology. Each zone can have its own number of replicas and size.","type":"object","default":{},"additionalProperties":{"type":"object","properties":{"dataCenter":{"description":"SeaweedFS data center name for this zone. Defaults to the zone name.","type":"string"},"nodeSelector":{"description":"YAML nodeSelector for this zone (default: topology.kubernetes.io/zone: ).","type":"string"},"pools":{"description":"A map of storage pools for this zone. Each pool creates a separate Volume StatefulSet per zone.","type":"object","additionalProperties":{"type":"object","required":["diskType"],"properties":{"diskType":{"description":"SeaweedFS disk type tag (e.g., \"ssd\", \"hdd\", \"nvme\").","type":"string"},"replicas":{"description":"Number of volume replicas. Defaults to volume.replicas (Simple) or zone.replicas/volume.replicas (MultiZone).","type":"integer"},"resources":{"description":"Explicit CPU and memory configuration. When omitted, the preset defined in `resourcesPreset` is applied.","type":"object","properties":{"cpu":{"description":"Number of CPU cores allocated.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"memory":{"description":"Amount of memory allocated.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true}}},"resourcesPreset":{"description":"Default sizing preset used when `resources` is omitted. Defaults to volume.resourcesPreset.","type":"string","enum":["t1.nano","t1.micro","t1.small","t1.medium","t1.large","t1.xlarge","t1.2xlarge","t1.4xlarge","c1.nano","c1.micro","c1.small","c1.medium","c1.large","c1.xlarge","c1.2xlarge","c1.4xlarge","s1.nano","s1.micro","s1.small","s1.medium","s1.large","s1.xlarge","s1.2xlarge","s1.4xlarge","u1.nano","u1.micro","u1.small","u1.medium","u1.large","u1.xlarge","u1.2xlarge","u1.4xlarge","m1.nano","m1.micro","m1.small","m1.medium","m1.large","m1.xlarge","m1.2xlarge","m1.4xlarge","nano","micro","small","medium","large","xlarge","2xlarge"]},"size":{"description":"Persistent Volume size. Defaults to volume.size (Simple) or zone.size/volume.size (MultiZone).","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"storageClass":{"description":"Kubernetes StorageClass for the pool. Defaults to volume.storageClass.","type":"string"}}}},"replicas":{"description":"Number of replicas in the zone.","type":"integer"},"size":{"description":"Zone storage size.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"storageClass":{"description":"StorageClass used to store zone data. Defaults to volume.storageClass.","type":"string"}}}}}},"s3":{"description":"S3 service configuration.","type":"object","default":{},"properties":{"replicas":{"description":"Number of S3 replicas.","type":"integer","default":2},"resources":{"description":"Explicit CPU and memory configuration. When omitted, the preset defined in `resourcesPreset` is applied.","type":"object","default":{},"properties":{"cpu":{"description":"Number of CPU cores allocated.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"memory":{"description":"Amount of memory allocated.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true}}},"resourcesPreset":{"description":"Default sizing preset used when `resources` is omitted.","type":"string","default":"t1.small","enum":["t1.nano","t1.micro","t1.small","t1.medium","t1.large","t1.xlarge","t1.2xlarge","t1.4xlarge","c1.nano","c1.micro","c1.small","c1.medium","c1.large","c1.xlarge","c1.2xlarge","c1.4xlarge","s1.nano","s1.micro","s1.small","s1.medium","s1.large","s1.xlarge","s1.2xlarge","s1.4xlarge","u1.nano","u1.micro","u1.small","u1.medium","u1.large","u1.xlarge","u1.2xlarge","u1.4xlarge","m1.nano","m1.micro","m1.small","m1.medium","m1.large","m1.xlarge","m1.2xlarge","m1.4xlarge","nano","micro","small","medium","large","xlarge","2xlarge"]}}},"cosi":{"description":"Bucket provisioning configuration.","type":"object","default":{},"properties":{"orphanIdentities":{"description":"What installs and upgrades do with S3 identities left behind by deleted BucketAccesses: `delete` removes them, `report` only lists them in an Event, `auto` reports when `filer.grpcHost` is set (other clusters may use this filer) and removes them otherwise. Set `report` if the filer is reachable from other clusters some other way. Ignored with the Client topology, whose identities live on the filer of the instance it connects to.","type":"string","default":"auto","enum":["auto","report","delete"]}}}}} release: prefix: "" labels: @@ -26,7 +26,7 @@ spec: description: Seaweedfs module: true icon: PHN2ZyB3aWR0aD0iMTQ0IiBoZWlnaHQ9IjE0NCIgdmlld0JveD0iMCAwIDE0NCAxNDQiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxyZWN0IHdpZHRoPSIxNDQiIGhlaWdodD0iMTQ0IiByeD0iMjQiIGZpbGw9InVybCgjcGFpbnQwX2xpbmVhcl82NzlfMTkxMCkiLz4KPHBhdGggZD0iTTEzOC42ODUgMTIxLjA1N0MxMzguNjg1IDEyNi42NTIgMTM2LjQ2MiAxMzIuMDE3IDEzMi41MDQgMTM1Ljk3M0MxMjguNTQ3IDEzOS45MjkgMTIzLjE3OSAxNDIuMTUxIDExNy41ODIgMTQyLjE1MUMxMTEuOTg1IDE0Mi4xNTEgMTA2LjYxOCAxMzkuOTI5IDEwMi42NiAxMzUuOTczQzk4LjcwMjggMTMyLjAxNyA5Ni40Nzk1IDEyNi42NTIgOTYuNDc5NSAxMjEuMDU3Qzk2LjQ3OTUgMTE4LjI4NyA5Ny4wMjUzIDExNS41NDQgOTguMDg1OCAxMTIuOTg1Qzk5LjE0NjMgMTEwLjQyNSAxMDAuNzAxIDEwOC4xIDEwMi42NiAxMDYuMTQxQzEwNC42MiAxMDQuMTgyIDEwNi45NDYgMTAyLjYyOSAxMDkuNTA3IDEwMS41NjlDMTEyLjA2NyAxMDAuNTA5IDExNC44MTEgOTkuOTYyOSAxMTcuNTgyIDk5Ljk2MjlDMTIwLjM1MyA5OS45NjI5IDEyMy4wOTggMTAwLjUwOSAxMjUuNjU4IDEwMS41NjlDMTI4LjIxOCAxMDIuNjI5IDEzMC41NDQgMTA0LjE4MiAxMzIuNTA0IDEwNi4xNDFDMTM0LjQ2NCAxMDguMSAxMzYuMDE4IDExMC40MjUgMTM3LjA3OSAxMTIuOTg1QzEzOC4xMzkgMTE1LjU0NCAxMzguNjg1IDExOC4yODcgMTM4LjY4NSAxMjEuMDU3WiIgZmlsbD0idXJsKCNwYWludDFfcmFkaWFsXzY3OV8xOTEwKSIvPgo8cGF0aCBkPSJNMTEwLjMzNiAxMjYuMTQ3SDEyMy42OFYxMzYuODIzSDExMC4zMzZWMTI2LjE0N1oiIGZpbGw9IiMwRjVFOUMiLz4KPHBhdGggZD0iTTExOS4yNyAxMTIuMjk0QzExOS4yNyAxMTIuNzE0IDExOS4xNzggMTEzLjEzMSAxMTkgMTEzLjUxOUMxMTguODIxIDExMy45MDggMTE4LjU2IDExNC4yNjEgMTE4LjIzIDExNC41NThDMTE3LjkwMSAxMTQuODU1IDExNy41MDkgMTE1LjA5MSAxMTcuMDc5IDExNS4yNTJDMTE2LjY0OCAxMTUuNDEzIDExNi4xODYgMTE1LjQ5NiAxMTUuNzIgMTE1LjQ5NkMxMTQuNzc4IDExNS40OTYgMTEzLjg3NSAxMTUuMTU4IDExMy4yMSAxMTQuNTU4QzExMi41NDQgMTEzLjk1NyAxMTIuMTcgMTEzLjE0MyAxMTIuMTcgMTEyLjI5NEMxMTIuMTcgMTExLjQ0NSAxMTIuNTQ0IDExMC42MyAxMTMuMjEgMTEwLjAzQzExMy44NzUgMTA5LjQyOSAxMTQuNzc4IDEwOS4wOTIgMTE1LjcyIDEwOS4wOTJDMTE2LjE4NiAxMDkuMDkyIDExNi42NDggMTA5LjE3NSAxMTcuMDc5IDEwOS4zMzZDMTE3LjUwOSAxMDkuNDk2IDExNy45MDEgMTA5LjczMiAxMTguMjMgMTEwLjAzQzExOC41NiAxMTAuMzI3IDExOC44MjEgMTEwLjY4IDExOSAxMTEuMDY4QzExOS4xNzggMTExLjQ1NyAxMTkuMjcgMTExLjg3MyAxMTkuMjcgMTEyLjI5NFoiIGZpbGw9IiM1OTY4NkYiLz4KPHBhdGggZD0iTTEyOC4xMSAxMTQuMTAzQzEyOC4xMSAxMTQuOTUzIDEyNy43MzYgMTE1Ljc2NyAxMjcuMDcgMTE2LjM2OEMxMjYuNDA0IDExNi45NjggMTI1LjUwMSAxMTcuMzA1IDEyNC41NiAxMTcuMzA1QzEyNC4wOTQgMTE3LjMwNSAxMjMuNjMyIDExNy4yMjMgMTIzLjIwMSAxMTcuMDYyQzEyMi43NzEgMTE2LjkwMSAxMjIuMzc5IDExNi42NjUgMTIyLjA1IDExNi4zNjhDMTIxLjcyIDExNi4wNyAxMjEuNDU4IDExNS43MTcgMTIxLjI4IDExNS4zMjlDMTIxLjEwMiAxMTQuOTQgMTIxLjAxIDExNC41MjQgMTIxLjAxIDExNC4xMDNDMTIxLjAxIDExMy42ODMgMTIxLjEwMiAxMTMuMjY2IDEyMS4yOCAxMTIuODc4QzEyMS40NTggMTEyLjQ5IDEyMS43MiAxMTIuMTM3IDEyMi4wNSAxMTEuODM5QzEyMi4zNzkgMTExLjU0MiAxMjIuNzcxIDExMS4zMDYgMTIzLjIwMSAxMTEuMTQ1QzEyMy42MzIgMTEwLjk4NCAxMjQuMDk0IDExMC45MDEgMTI0LjU2IDExMC45MDFDMTI1LjUwMSAxMTAuOTAxIDEyNi40MDQgMTExLjIzOSAxMjcuMDcgMTExLjgzOUMxMjcuNzM2IDExMi40NCAxMjguMTEgMTEzLjI1NCAxMjguMTEgMTE0LjEwM1oiIGZpbGw9IiM1OTY4NkYiLz4KPHBhdGggZD0iTTEyMi4zMzMgMTE4Ljk3NkMxMjIuMzMzIDExOS44MjYgMTIxLjk1OCAxMjAuNjQgMTIxLjI5MyAxMjEuMjQxQzEyMC42MjcgMTIxLjg0MSAxMTkuNzI0IDEyMi4xNzggMTE4Ljc4MiAxMjIuMTc4QzExOC4zMTYgMTIyLjE3OCAxMTcuODU1IDEyMi4wOTYgMTE3LjQyNCAxMjEuOTM1QzExNi45OTMgMTIxLjc3NCAxMTYuNjAyIDEyMS41MzggMTE2LjI3MiAxMjEuMjQxQzExNS45NDMgMTIwLjk0MyAxMTUuNjgxIDEyMC41OSAxMTUuNTAzIDEyMC4yMDJDMTE1LjMyNCAxMTkuODEzIDExNS4yMzIgMTE5LjM5NyAxMTUuMjMyIDExOC45NzZDMTE1LjIzMiAxMTguNTU2IDExNS4zMjQgMTE4LjE0IDExNS41MDMgMTE3Ljc1MUMxMTUuNjgxIDExNy4zNjMgMTE1Ljk0MyAxMTcuMDEgMTE2LjI3MiAxMTYuNzEyQzExNi42MDIgMTE2LjQxNSAxMTYuOTkzIDExNi4xNzkgMTE3LjQyNCAxMTYuMDE4QzExNy44NTUgMTE1Ljg1NyAxMTguMzE2IDExNS43NzQgMTE4Ljc4MiAxMTUuNzc0QzExOS43MjQgMTE1Ljc3NCAxMjAuNjI3IDExNi4xMTIgMTIxLjI5MyAxMTYuNzEyQzEyMS45NTggMTE3LjMxMyAxMjIuMzMzIDExOC4xMjcgMTIyLjMzMyAxMTguOTc2WiIgZmlsbD0iIzU5Njg2RiIvPgo8cGF0aCBkPSJNMTE1LjMwOCAxMjEuOTA1QzExMy43MzUgMTIxLjQyNiAxMTUuNzA3IDEyMC42OCAxMTUuNDI5IDEyMC41NzNDMTE0LjY1MyAxMjAuMjc2IDExNS43MyAxMTkuMzMzIDExNi43NCAxMTguNTM5QzExNy42MjggMTE3Ljg0MSAxMTcuNjU5IDExNy44MzkgMTE3Ljg5MiAxMTguNDY4QzExOC4wMjQgMTE4LjgyMyAxMTguMzcxIDExOS4yMDYgMTE4LjY2NSAxMTkuMzE5QzExOS4yODkgMTE5LjU1OCAxMjAuOTUxIDExOS4yNjkgMTIwLjk1MSAxMTguODM1QzEyMC45NTEgMTE4LjIyMyAxMjEuNDE1IDExOC42OTkgMTIxLjc5NCAxMTkuNTMxQzEyMi40NTcgMTIwLjk4NyAxMjIuNDM3IDEyMi40NzIgMTIxLjQ1IDEyMi40NzJDMTIwLjg1OSAxMjIuNDcyIDEyMC4zMSAxMjIuNjkxIDEyMC4xOSAxMjMuMTQ3QzExNS4wNDYgMTI0LjYgMTE2LjQ3MSAxMjMuMjg0IDExNS4zMDggMTIxLjkwNVpNMTIzLjA5NCAxMTguMDU0QzEyMS42MDkgMTE3LjQ2NiAxMjAuNTQ3IDExNC44MzggMTIwLjU0NyAxMTMuMzA5QzEyMC41NDcgMTExLjMyMyAxMjIuNTQxIDEwOS4wOTUgMTI0LjMxNyAxMDkuMDk1QzEyOC4zMTUgMTA5LjA5NSAxMzAuNjg0IDExMi4yNjEgMTI4LjgzOCAxMTguNDA5QzEyOC4zODUgMTE5LjkxOSAxMjMuOTMzIDExOC4zODcgMTIzLjA5NCAxMTguMDU0Wk0xMjUuODY2IDExNS42NDlDMTI3LjU0NCAxMTQuNDc0IDEyNS44NTcgMTExLjc1NSAxMjMuOTgxIDExMi42MUMxMjIuNDc5IDExMy4yOTQgMTIzLjExOSAxMTYuMTE1IDEyNC43NyAxMTYuMTY0QzEyNC45NjEgMTE2LjE2OSAxMjUuNDU0IDExNS45MzggMTI1Ljg2NiAxMTUuNjQ5Wk0xMjQuMzM5IDExNC41NzlDMTIzLjc3MSAxMTQuMzgxIDEyMy44MDMgMTEzLjI1NiAxMjQuMzgzIDExMy4wMzRDMTI0LjkwMiAxMTIuODM1IDEyNS42MDQgMTEzLjM5OCAxMjUuNjA0IDExNC4wMTRDMTI1LjYwNCAxMTQuNDg5IDEyNC45MzYgMTE0Ljc4NyAxMjQuMzM5IDExNC41NzlaTTExMi4zMTkgMTE2Ljk4QzEwOS45NiAxMTUuNjcgMTEwLjI4NiAxMTEuMDA2IDExMi40MTcgMTA4Ljk2NUMxMTQuMzk2IDEwNy4wNjkgMTE4Ljc3OCAxMDcuMTAzIDExOS43NjQgMTA5LjQ2MkMxMjAuNDE1IDExMS4wMjEgMTIwLjIyOCAxMTIuNiAxMTkuMzk4IDExNC4wNzdDMTE4LjE5NCAxMTYuMjE5IDExNC4yNDIgMTE4LjA0OSAxMTIuMzE5IDExNi45OFpNMTE2LjU2IDExMy41OTNDMTE3LjMyNSAxMTIuOTAxIDExNy4yOTcgMTEyLjA2IDExNi41NzIgMTExLjI1OUMxMTUuNzc3IDExMC4zNzkgMTE0LjY5MiAxMTAuMzQ1IDExNC4wMzUgMTExLjM0N0MxMTMuNTI0IDExMi4xMjcgMTEzLjQzMSAxMTIuNTI4IDExMy45NDMgMTEzLjMwOUMxMTQuNTggMTE0LjI4IDExNS42NyAxMTQuMzk5IDExNi41NiAxMTMuNTkzWk0xMTQuMzc0IDExMi4zNEMxMTQuMTI4IDExMS42OTggMTE0Ljk4NSAxMTAuOTgxIDExNS42OCAxMTEuMjQ3QzExNS45NzQgMTExLjM2IDExNi4xNjQgMTExLjcxOCAxMTYuMTAyIDExMi4wNDRDMTE1Ljk2MSAxMTIuNzg1IDExNC42MzIgMTEzLjAxMiAxMTQuMzc0IDExMi4zNFoiIGZpbGw9IiNEM0Q2REEiLz4KPHBhdGggZD0iTTExOC40NjMgMTIxLjAwOEwxMTcuOTQ1IDEyMC43OEMxMTcuNTEgMTIwLjY4NSAxMTcuMjMxIDEyMS4xMDcgMTE3LjEzNiAxMjEuNTQzTDExNi44ODEgMTIyLjcwOUMxMTYuNzg2IDEyMy4xNDUgMTE3LjA2MSAxMjMuNTcxIDExNy40OTYgMTIzLjY2NkwxMTguNDQ3IDEyMy44NzRDMTE4Ljg4MiAxMjMuOTY5IDExOS4zMTEgMTIzLjY5NCAxMTkuNDA2IDEyMy4yNTlMMTE5LjY4NSAxMjEuNTU2QzExOS43OCAxMjEuMTIgMTE5LjQ3OSAxMjEuMjI4IDExOS4wNDMgMTIxLjEzM0wxMTguNjI4IDEyMS4wNDNDMTE4LjU3MyAxMjEuMzIxIDExOC41MTYgMTIxLjYxMyAxMTguNDcxIDEyMS44MzNDMTE4LjQzOCAxMjEuOTk4IDExOC40MDcgMTIyLjE0OCAxMTguMzc5IDEyMi4yODJDMTE4LjM1MSAxMjIuNDE1IDExOC4zMjcgMTIyLjUzMyAxMTguMzA1IDEyMi42MzVDMTE4LjI4MiAxMjIuNzM4IDExOC4yNjIgMTIyLjgyNSAxMTguMjQ1IDEyMi44OTdDMTE4LjIyOCAxMjIuOTY5IDExOC4yMTQgMTIzLjAyNSAxMTguMjAyIDEyMy4wNjhDMTE4LjE5NiAxMjMuMDg5IDExOC4xOTMgMTIzLjEwNyAxMTguMTg4IDEyMy4xMjFDMTE4LjE4MyAxMjMuMTM1IDExOC4xNzggMTIzLjE0NSAxMTguMTc1IDEyMy4xNTJDMTE4LjE3MyAxMjMuMTU1IDExOC4xNzIgMTIzLjE1NiAxMTguMTcxIDEyMy4xNThDMTE4LjE3IDEyMy4xNTkgMTE4LjE2OCAxMjMuMTYgMTE4LjE2NyAxMjMuMTZMMTE4LjE2NSAxMjMuMTU4QzExOC4xNjQgMTIzLjE1NiAxMTguMTYzIDEyMy4xNTIgMTE4LjE2MyAxMjMuMTQ4QzExOC4xNjIgMTIzLjE0IDExOC4xNjIgMTIzLjEyOSAxMTguMTYzIDEyMy4xMTVDMTE4LjE2MyAxMjMuMSAxMTguMTYzIDEyMy4wODMgMTE4LjE2NSAxMjMuMDYxQzExOC4xNjggMTIzLjAxOCAxMTguMTc1IDEyMi45NjEgMTE4LjE4MyAxMjIuODkxQzExOC4xOTIgMTIyLjgyIDExOC4yMDMgMTIyLjczNiAxMTguMjE2IDEyMi42NEMxMTguMjI5IDEyMi41NDMgMTE4LjI0NiAxMjIuNDMxIDExOC4yNjQgMTIyLjMwOEMxMTguMjgxIDEyMi4xODUgMTE4LjMwMSAxMjIuMDUxIDExOC4zMjMgMTIxLjkwM0MxMTguMzQ2IDEyMS43NTUgMTE4LjM3IDEyMS41OTIgMTE4LjM5NyAxMjEuNDE5QzExOC40MTYgMTIxLjI5OSAxMTguNDQyIDEyMS4xNCAxMTguNDYzIDEyMS4wMDhaIiBmaWxsPSIjOThDNkQ4Ii8+CjxwYXRoIGQ9Ik0xMDMuNTgxIDExNi4zNjdDMTAzLjQ3OSAxMTYuMTAzIDEwMy42MjIgMTE1LjY5OSAxMDMuODk4IDExNS40NjlDMTA0LjMwMyAxMTUuMTMzIDEwNC41MDQgMTE1LjE1NSAxMDQuOTMgMTE1LjU4MUMxMDUuMjIgMTE1Ljg3MSAxMDUuMzU1IDExNi4yNzYgMTA1LjIzIDExNi40NzlDMTA0LjkwMiAxMTcuMDA5IDEwMy43OTggMTE2LjkzNCAxMDMuNTgxIDExNi4zNjdaIiBmaWxsPSIjOThDNkQ4Ii8+CjxwYXRoIGQ9Ik0xMDYuMDM4IDExMi4yODFDMTA1LjY4IDExMS44NDkgMTA1LjcwMiAxMTEuNjYgMTA2LjE2NSAxMTEuMTk3QzEwNi42ODkgMTEwLjY3NCAxMDYuNzY0IDExMC42NzQgMTA3LjI4NyAxMTEuMTk3QzEwNy43NTEgMTExLjY2IDEwNy43NzMgMTExLjg0OSAxMDcuNDE1IDExMi4yODFDMTA3LjE3NiAxMTIuNTY4IDEwNi44NjYgMTEyLjgwMyAxMDYuNzI2IDExMi44MDNDMTA2LjU4NiAxMTIuODAzIDEwNi4yNzcgMTEyLjU2OCAxMDYuMDM4IDExMi4yODFaIiBmaWxsPSIjOThDNkQ4Ii8+CjxwYXRoIGQ9Ik0xMDYuMDM4IDEwNy4yMjRDMTA1LjY4MiAxMDYuNzk1IDEwNS42OTQgMTA2LjYxMiAxMDYuMTA2IDEwNi4yMDFDMTA2LjY1IDEwNS42NTcgMTA3LjczOCAxMDUuODggMTA3LjczOCAxMDYuNTM2QzEwNy43MzggMTA2Ljk3IDEwNy4wNzIgMTA3Ljc0NyAxMDYuNyAxMDcuNzQ3QzEwNi41NzUgMTA3Ljc0NyAxMDYuMjc3IDEwNy41MTIgMTA2LjAzOCAxMDcuMjI0WiIgZmlsbD0iIzk4QzZEOCIvPgo8cGF0aCBkPSJNMTE3Ljk1NSAxMzYuNTQxQzExNC41NzggMTM2LjExMSAxMTAuMDg3IDEzNC44ODEgMTA5LjQxIDEzNC4yNzRDMTA4LjEyMyAxMzMuMTE5IDEwOC45NDIgMTI3Ljg3OSAxMTAuNDY2IDEyNi41NEMxMTEuMzg3IDEyNS43MzEgMTE1LjAzOSAxMjQuNjYzIDExNy4xODIgMTI1LjE2OUMxMTkuNjQyIDEyNS43NDkgMTIzLjkzMiAxMjguNjQ4IDEyNC4yNSAxMjkuNTA4QzEyNC42MjUgMTMwLjUyMiAxMjQuMDQ4IDEzNC41NDEgMTIzLjMyMyAxMzUuNTM2QzEyMi42OTQgMTM2LjM5OSAxMjAuMzI1IDEzNi44NDMgMTE3Ljk1NSAxMzYuNTQxWk0xMjAuNTQgMTM0LjA4NEMxMjEuMjk3IDEzMy4zOTkgMTIxLjM0MiAxMzEuODQyIDEyMC42MjcgMTMxLjEyNkMxMTkuNDkgMTI5Ljk4OSAxMTcuMTEyIDEzMC44NjkgMTE3LjExMiAxMzIuNDI4QzExNy4xMTIgMTM0LjMwNCAxMTkuMTg5IDEzNS4zMDcgMTIwLjU0IDEzNC4wODRaTTExOC41ODIgMTMzLjEyNUMxMTguMzExIDEzMi40MTkgMTE4LjY4IDEzMS42MDggMTE5LjI3MiAxMzEuNjA4QzEyMCAxMzEuNjA4IDEyMC4yMjggMTMyLjE3MyAxMTkuODEyIDEzMi45NDlDMTE5LjM4MSAxMzMuNzU1IDExOC44NTMgMTMzLjgzIDExOC41ODIgMTMzLjEyNVpNMTE2LjQyMiAxMzMuMTQzQzExNy4wOTQgMTMyLjMzMyAxMTYuNzExIDEzMS4xNzYgMTE1LjY4MSAxMzAuOTAyQzExNC41ODEgMTMwLjYxIDExNC4wNTIgMTMxLjE4MyAxMTQuODY5IDEzMS43OEMxMTUuNjgzIDEzMi4zNzUgMTE1LjU1MSAxMzIuNjc5IDExNC41MzMgMTMyLjU1N0MxMTMuMzI3IDEzMi40MTMgMTEyLjgzMyAxMzEuNTY2IDExMy4yNTQgMTMwLjM2MkMxMTMuNjgxIDEyOS4xNDIgMTE1LjE5NyAxMjguODYzIDExNS43NTMgMTI5LjkwMkMxMTYuMTkzIDEzMC43MjUgMTE2LjYyNyAxMzAuNzkzIDExNi45IDEzMC4wODNDMTE3LjIyOSAxMjkuMjI0IDExNS45MTQgMTI4LjIzNyAxMTQuNDQgMTI4LjIzN0MxMTEuOTkzIDEyOC4yMzcgMTEwLjgxNiAxMzEuMDc0IDExMi41NDYgMTMyLjgwM0MxMTMuNSAxMzMuNzU4IDExNS43NDkgMTMzLjk1NSAxMTYuNDIyIDEzMy4xNDNaIiBmaWxsPSIjN0JBOUI5Ii8+CjxwYXRoIGQ9Ik0xMjAuMTE4IDEzOC41OTJDMTE4Ljc1MSAxMzcuMjk3IDEyMS45MTYgMTM2LjA5NiAxMjMuNjA2IDEzOC4yODNDMTI0LjQ2OSAxMzkuMzIyIDEyMi44NTMgMTM5Ljk3NiAxMjAuMTE4IDEzOC41OTJaTTEwNi4xMiAxMzUuNjU4QzEwNC43NTEgMTM0LjI4OSAxMDYuOTYzIDEzMy45MDQgMTA4LjU4MSAxMzUuMjNMMTA5Ljk0MSAxMzUuOTJMMTA4LjA1OSAxMzYuMDYxQzEwNy4yMTUgMTM2LjA2MiAxMDYuMzQzIDEzNS44ODEgMTA2LjEyIDEzNS42NThWMTM1LjY1OFpNMTI1LjM2MyAxMjcuODY2QzEyNS4wODIgMTI3LjQxIDEyOC4zMzMgMTI2LjI2NyAxMjguNjg4IDEyNi40ODZDMTI4Ljg0NiAxMjYuNTg0IDEyOC45NzUgMTI3LjMzNyAxMjguOTc1IDEyOC4xNjFDMTI4Ljk3NSAxMjkuMjM5IDEyOC44NCAxMjkuNjU4IDEyOC40OSAxMjkuNjU4QzEyOC4yMjIgMTI5LjY1OCAxMjUuNDc2IDEyOC4wNDcgMTI1LjM2MyAxMjcuODY2Wk0xMTguNjQxIDEyMS4wOTVDMTE0Ljg3MSAxMjAuNzUzIDExNS4zNzggMTE5LjMyNyAxMTYuMzYxIDExOC40OTlDMTE2LjkyOCAxMTguMDIxIDExNy4zNCAxMTcuNzc5IDExNy45MTMgMTE3LjY2N0MxMTcuOTEzIDExNy42NjcgMTE3Ljg3MiAxMTkuMDQ2IDExOC42NjYgMTE5LjMxOUMxMTkuMjk3IDExOS41MzYgMTIwLjI3OCAxMTkuMDY0IDEyMC40NzEgMTE4LjY3NUMxMjIuMTg4IDExNS4yMDEgMTIxLjQxNSAxMTguNjk5IDEyMS43OTQgMTE5LjUzMkMxMjMuMjM4IDEyNC4wMDcgMTIwLjE4OCAxMjEuNzMgMTE4LjY0MSAxMjEuMDk1Wk0xMDQuOTEyIDEyMS4yM0MxMDQuMjQyIDEyMC40ODcgMTAzLjY5MyAxMTkuNzI5IDEwMy42OTMgMTE5LjU0NEMxMDMuNjkzIDExOS4xMTYgMTA0Ljc0NiAxMTkuMTEyIDEwNS44NjMgMTE5LjUzN0MxMDYuNTkzIDExOS44MTQgMTEwLjM0NyAxMjAuMDA2IDExMC4zNDcgMTIxLjE1M0MxMTAuMzQ3IDEyMS44OTkgMTA4Ljg5IDEyMy43NjIgMTA4LjcyNiAxMjMuNzYyQzEwOC41NjMgMTIzLjc2MiAxMDUuNTgzIDEyMS45NzIgMTA0LjkxMiAxMjEuMjNaIiBmaWxsPSIjQTZCM0MyIi8+CjxwYXRoIGQ9Ik0xMTguNDYzIDEyMS4wMDhDMTE4LjQ0MiAxMjEuMTQgMTE4LjQxNiAxMjEuMjk5IDExOC4zOTcgMTIxLjQxOUMxMTguMzcgMTIxLjU5MiAxMTguMzQ1IDEyMS43NTUgMTE4LjMyMyAxMjEuOTAzQzExOC4zIDEyMi4wNTEgMTE4LjI4MSAxMjIuMTg1IDExOC4yNjMgMTIyLjMwOEMxMTguMjQ1IDEyMi40MzEgMTE4LjIyOSAxMjIuNTQyIDExOC4yMTYgMTIyLjYzOUMxMTguMjAzIDEyMi43MzYgMTE4LjE5MSAxMjIuODIgMTE4LjE4MyAxMjIuODlDMTE4LjE3NSAxMjIuOTYxIDExOC4xNjggMTIzLjAxOCAxMTguMTY1IDEyMy4wNjFDMTE4LjE2MyAxMjMuMDgzIDExOC4xNjQgMTIzLjEgMTE4LjE2MyAxMjMuMTE1QzExOC4xNjIgMTIzLjEyOSAxMTguMTYyIDEyMy4xNCAxMTguMTYzIDEyMy4xNDhDMTE4LjE2MyAxMjMuMTUyIDExOC4xNjQgMTIzLjE1NiAxMTguMTY1IDEyMy4xNThMMTE4LjE2NyAxMjMuMTZDMTE4LjE2OCAxMjMuMTYgMTE4LjE3IDEyMy4xNTkgMTE4LjE3MSAxMjMuMTU4QzExOC4xNzIgMTIzLjE1NyAxMTguMTczIDEyMy4xNTUgMTE4LjE3NSAxMjMuMTUyQzExOC4xNzggMTIzLjE0NSAxMTguMTgyIDEyMy4xMzUgMTE4LjE4NyAxMjMuMTIxQzExOC4xOTIgMTIzLjEwNyAxMTguMTk2IDEyMy4wODkgMTE4LjIwMiAxMjMuMDY3QzExOC4yMTMgMTIzLjAyNSAxMTguMjI4IDEyMi45NjkgMTE4LjI0NSAxMjIuODk3QzExOC4yNjIgMTIyLjgyNSAxMTguMjgyIDEyMi43MzggMTE4LjMwNSAxMjIuNjM1QzExOC4zMjcgMTIyLjUzMyAxMTguMzUxIDEyMi40MTUgMTE4LjM3OSAxMjIuMjgxQzExOC40MDYgMTIyLjE0OCAxMTguNDM4IDEyMS45OTggMTE4LjQ3MSAxMjEuODMzQzExOC41MTYgMTIxLjYxMyAxMTguNTczIDEyMS4zMjEgMTE4LjYyOCAxMjEuMDQzTDExOC40NjMgMTIxLjAwOFoiIGZpbGw9IiM0QzlDQkIiLz4KPHBhdGggZD0iTTMwLjk5ODYgMTQyLjY3M0MyNi40NDg5IDE0MC45MTYgMjEuNDY2NCAxMzYuODA1IDE4Ljc5MjEgMTMyLjYwM0MxNS40MDUzIDEyNy4yODEgMTQuNDA1MiAxMjMuNDE5IDE1LjA2MzYgMTE4LjIwM0MxNS42ODA2IDExMy4zMTUgMTcuMzU1OCAxMTAuNTU3IDIyLjIyMzIgMTA2LjQxM0MyOS4wNDE3IDEwMC42MDggMzQuNDg0NiA5Ny45Nzk5IDQwLjU5NDcgOTcuNTQxNUM0OS44MjEyIDk2Ljg3OTQgNTUuMDk3OCA5OS44MTA5IDU3LjY0NjUgMTA3LjAxNUM1OC41MDQzIDEwOS40MzkgNTguNjg1NiAxMTUuNTcgNTguMDU0NCAxMjAuODA5QzU3LjgzMTEgMTIyLjY2MyA1Ny40Nzg5IDEyNi4wNTUgNTcuMjcxOCAxMjguMzQ4QzU2LjU0NjcgMTM2LjM3NSA1NC40MTQ3IDE0MC40MTcgNDkuNjI1MyAxNDIuODQzQzQ4LjI5NzkgMTQzLjUxNiA0Ny43MTk5IDE0My41NjEgNDAuNjkyNCAxNDMuNTM5QzMzLjUxNTEgMTQzLjUxNiAzMy4wODEgMTQzLjQ3OCAzMC45OTg2IDE0Mi42NzNaTTAuMDc5NTc2NSAxMDQuOTY1QzAuMDgxNTcyMyAxMDMuODUzIDAuMTQ0NDAzIDEwMy40MzggMC4yMTk0MjcgMTA0LjA0NEMwLjI5NDQ1MSAxMDQuNjUgMC4yOTI4OTkgMTA1LjU2IDAuMjE1OTk2IDEwNi4wNjdDMC4xMzkwNzkgMTA2LjU3MyAwLjA3NzY4MzggMTA2LjA3OCAwLjA3OTU3NjUgMTA0Ljk2NVpNMC4wMDE3MzM1MSAxMDIuMjRDMC4wMTc4OTkyIDEwMS44NDggMC4wOTc3ODk3IDEwMS43NjggMC4yMDUzOTggMTAyLjAzN0MwLjMwMjc3MiAxMDIuMjggMC4yOTA3OTcgMTAyLjU3MSAwLjE3ODc4NyAxMDIuNjgzQzAuMDY2Nzc0OCAxMDIuNzk1IC0wLjAxMjkwMjEgMTAyLjU5NiAwLjAwMTczMzUxIDEwMi4yNFpNMC4wMjgzNDQ0IDc1LjEzMjZDMC4wMjgzNDQ0IDc0LjY2OTEgMC4xMDQ4NTcgNzQuNDc5NSAwLjE5ODM2OSA3NC43MTEyQzAuMjkxODg0IDc0Ljk0MyAwLjI5MTg4NCA3NS4zMjIyIDAuMTk4MzY5IDc1LjU1MzlDMC4xMDQ4NTcgNzUuNzg1NyAwLjAyODM0NDQgNzUuNTk2MSAwLjAyODM0NDQgNzUuMTMyNloiIGZpbGw9InVybCgjcGFpbnQyX3JhZGlhbF82NzlfMTkxMCkiLz4KPHBhdGggZD0iTTM1LjMxMzMgMTEyLjU0NEwzNy45IDExMS4wOTFMMzkuMzUxNyAxMjEuNDZMMzkuMjQ4IDEyOC45MjZMMzUuMzcwMyAxMzAuODUxTDMyLjkyMjkgMTI2LjQzN0wzNS4zMTMzIDExMi41NDRaIiBmaWxsPSIjMzA2MEFEIi8+CjxwYXRoIGQ9Ik0zOC43Mjk1IDExNi42OUwzOS4zNTE2IDEyNC41NzFMNDMuMjkxOSAxMjUuOTE5TDQzLjM5NTYgMTA5LjIyNUw0MC4xODEyIDExMC4wNTRMMzguNzI5NSAxMTYuNjlaIiBmaWxsPSIjNjA2MzY4Ii8+CjxwYXRoIGQ9Ik0zNS4zNjk5IDEzMC44NTFDMzMuMDMyNCAxMjkuNzMgMjkuNzMwMSAxMjYuNDA4IDI4LjY2MjEgMTI0LjEwM0MyOC4wMzMyIDEyMi43NDUgMjcuNjM5NyAxMjIuMzEgMjYuODkyMyAxMjIuMTQ2QzI1Ljc4NzkgMTIxLjkwMyAyNS44MDg0IDEyMS45NzEgMjYuMzIxOCAxMjAuMjU4QzI2LjU5MzYgMTE5LjM1IDI2LjkwMzIgMTE4Ljk1NCAyNy4zNDA2IDExOC45NTRDMjcuNjg2MiAxMTguOTU0IDI5LjE1OTcgMTE3Ljg0MSAzMC42MTQ5IDExNi40OEMzMi4wNzAyIDExNS4xMTkgMzMuNzIyNiAxMTMuNjc3IDM0LjI4NjkgMTEzLjI3NUwzNS4zMTI5IDExMi41NDRMMzUuNjc2NyAxMTQuMjQxQzM3LjA0NDMgMTIwLjYxOCAzNy4wMjcgMTI0LjI2NiAzNS42MTk4IDEyNi4yNDNDMzQuNTUyMSAxMjcuNzQ0IDM0Ljg0MTcgMTI4LjM5MyAzNi41NzkxIDEyOC4zOTNDMzcuMzk3IDEyOC4zOTMgMzcuODIyMiAxMjguMTg1IDM4LjEzMDUgMTI3LjYzNEMzOC42NzQ4IDEyNi42NjMgMzguNjMxNSAxMjAuOTY4IDM4LjA0NTQgMTE2LjQyNkMzNy4zNDQ2IDExMC45OTUgMzcuMzEyNyAxMTEuMTY3IDM5LjE1NzggMTEwLjM5OEM0MC4wMzYgMTEwLjAzMSA0MC44MTggMTA5Ljc5NyA0MC44OTU1IDEwOS44NzdDNDAuOTczMSAxMDkuOTU2IDQwLjgxOTEgMTExLjIzNSA0MC41NTM0IDExMi43MThDMzkuNjA2NyAxMTguMDAzIDM5LjkzMTUgMTIzLjIzOCA0MS4yNzUyIDEyNC4zNTNDNDEuNjg1MSAxMjQuNjkzIDQxLjcyMzMgMTIzLjk2OSA0MS41NDUyIDExOS4yMzJDNDEuMzE1NiAxMTMuMTIzIDQxLjUxNzQgMTEwLjkxOSA0Mi40MDc1IDEwOS44MkM0Mi45MTk4IDEwOS4xODggNDMuMjEzIDEwOS4xMTYgNDQuNDk1OSAxMDkuMzFDNDYuOTU2NiAxMDkuNjgyIDQ2Ljk1MDYgMTA5LjY2OCA0Ni4yMDk5IDExMy4yNTRDNDUuODQ5NiAxMTQuOTk5IDQ1LjQ0ODMgMTE3LjIyNCA0NS4zMTggMTE4LjJMNDUuMDgxMiAxMTkuOTczTDQ1Ljk0NDYgMTE5LjY0NUM0Ni40MTk1IDExOS40NjUgNDcuNDQxMyAxMTguOTk0IDQ4LjIxNTMgMTE4LjU5OUw0OS42MjI2IDExNy44ODFMNDkuMzg5MyAxMTguNjdDNDkuMjYxIDExOS4xMDUgNDkuMDY3MiAxMjAuNzAxIDQ4Ljk1ODcgMTIyLjIxOEw0OC43NjE0IDEyNC45NzZMNDcuMTA5NSAxMjQuMzI1QzQ2LjIwMSAxMjMuOTY3IDQ1LjMxMTYgMTIzLjY3NCA0NS4xMzMxIDEyMy42NzRDNDQuOTQxIDEyMy42NzQgNDQuODA4NSAxMjUuNTMyIDQ0LjgwODUgMTI4LjIyNEM0NC44MDg1IDEzMS44OTEgNDQuNzE3MSAxMzIuNzc1IDQ0LjMzODYgMTMyLjc3NUM0MS4wMTk4IDEzMi4yOTUgMzguNzg0MiAxMzIuNDU4IDM1LjM2OTkgMTMwLjg1MVoiIGZpbGw9IiNFRUMyM0IiLz4KPHBhdGggZD0iTTQxLjE2MzkgMTMyLjQxOEM0MS4xNjM5IDEzMi4yODMgNDEuMzQwOCAxMzAuNTE1IDQxLjY2OTIgMTI4LjE0NUM0MS45OTc3IDEyNS43NzUgNDIuMzU3NyAxMjIuOTYxIDQyLjQ2OTIgMTIxLjg5M0M0Mi41ODA4IDEyMC44MjQgNDIuNzk2OSAxMjAuMDI3IDQyLjk0OTUgMTIwLjEyMUM0My42NDQzIDEyMC41NTEgNDQuMjkzOCAxMjkuMzc1IDQ0LjA0NzQgMTMxLjQyQzQzLjg5MDkgMTMyLjcxOSA0My42NTk1IDEzMi43MzcgNDMuMzAxOSAxMzIuNjc3QzQyLjY2MDIgMTMyLjU3IDQxLjkxMDEgMTMyLjUxMyA0MS4xNjM5IDEzMi40MThaTTMyLjU5NjkgMTIyLjczNUMzMS42ODEzIDEyMi41ODMgMzAuODI0MiAxMjEuNDQyIDMwLjgyNDIgMTIwLjM3NEMzMC44MjQyIDExOS40MDcgMzIuMjM4MSAxMTcuOTM3IDMzLjE2ODUgMTE3LjkzN0MzNC42NjY2IDExNy45MzcgMzUuODM5MiAxMjAuNTEzIDM0Ljk0ODQgMTIxLjg0N0MzNC41NTE3IDEyMi40NDEgMzMuNDE0NyAxMjIuODcgMzIuNTk2OSAxMjIuNzM1WiIgZmlsbD0id2hpdGUiLz4KPHBhdGggZD0iTTExNC4wMjEgMTM3LjQ5OEMxMDcuMzE4IDEzNS43NCAxMDYuMjczIDEzNC4xMDQgMTA2LjYwOSAxMjUuODkxQzEwNi43MTYgMTIzLjI4MSAxMDYuODg1IDEyMC41MzkgMTA2Ljk4NiAxMTkuNzk3QzEwNy41NDUgMTE1LjY2NCAxMDguMzQyIDExMi4xNzMgMTA5LjA4NiAxMTAuNTk5QzEwOS43NDQgMTA5LjIwNiAxMDkuODQyIDEwOC43MTIgMTA5LjUzNSAxMDguMzQyQzEwOC40NSAxMDcuMDM1IDExMC4zNzEgMTA0Ljk5NSAxMTEuOTEgMTA1LjgxOUMxMTIuNDU3IDEwNi4xMTEgMTEyLjkxOCAxMDYuMDc3IDExMy45NDUgMTA1LjY2NUMxMTcuMDYyIDEwNC40MTkgMTIzLjExNyAxMDUuNTcxIDEyNi44MTQgMTA4LjExNUMxMjguMTQ5IDEwOS4wMzMgMTI4LjQ4NSAxMDkuMTM2IDEyOS4wMzggMTA4Ljc5MUMxMzAuNTIzIDEwNy44NjMgMTMyLjQ1MSAxMTAuNTczIDEzMS4yNSAxMTEuOUMxMzAuNzg3IDExMi40MTIgMTMwLjc1NSAxMTIuNzA1IDEzMS4wNjUgMTEzLjU5NkMxMzEuODUgMTE1Ljg0NiAxMzEuNzk0IDExNi4xMDQgMTI4LjAwNiAxMjcuNzE5QzEyNS41OCAxMzUuMTYgMTI0LjU0MyAxMzcuMzY1IDEyMy4yNjQgMTM3LjgxMUMxMjEuNjUzIDEzOC4zNzMgMTE2LjcyMyAxMzguMjA2IDExNC4wMjEgMTM3LjQ5OFpNMTIyLjU0MSAxMzUuMjI5QzEyMy4wMDMgMTM0LjU0MSAxMjMuMzU5IDEzMy4zMTMgMTIzLjUxMyAxMzEuODc4QzEyMy43OTQgMTI5LjI1IDEyMy44MTkgMTI5LjI4MyAxMjAuMzE3IDEyNy42MDFDMTE3LjY4NSAxMjYuMzM4IDExMy44MzMgMTI1Ljk3MiAxMTEuODU1IDEyNi43OThDMTEwLjgyOSAxMjcuMjI3IDExMC41OTUgMTI3LjU1NiAxMTAuMDU5IDEyOS4zMjdDMTA5LjExNiAxMzIuNDQzIDEwOS43MDMgMTM0LjMwOCAxMTEuODMyIDEzNC45NThDMTEzLjEzOSAxMzUuMzU3IDEyMC4wOSAxMzYuNDMgMTIwLjk4IDEzNi4zN0MxMjEuNTA0IDEzNi4zMzUgMTIyLjA4MiAxMzUuOTEyIDEyMi41NDEgMTM1LjIyOVpNMTE5LjQ1MSAxMjIuNDJDMTE5LjYzIDEyMi4wODEgMTE5LjY4NSAxMjEuNTU2IDExOS42ODUgMTIxLjU1NkMxMjAuMTU2IDEyMS42NTQgMTIwLjQ4IDEyMS42ODMgMTIwLjcyNiAxMjEuNzE5QzEyMS4xMDUgMTIxLjc3NCAxMjEuNTY0IDEyMS41ODcgMTIxLjc0NSAxMjEuMzAzQzEyMi4xNDkgMTIwLjY3MSAxMjAuNDc0IDExNy43MDEgMTE5LjU0OCAxMTcuNDA4QzExOC42NjggMTE3LjEyOCAxMTUuOTM1IDExOC44MjcgMTE1LjkzNSAxMTkuNjUzQzExNS45MzUgMTIwLjAyMiAxMTYuNTUzIDEyMC40MTEgMTE2LjgzMSAxMjAuNTE4QzExNi45ODIgMTIwLjU3NiAxMTcuMjUyIDEyMC43MzggMTE3LjU3NiAxMjAuOTM4QzExNy4zOCAxMjEuMzUxIDExNy4zNDYgMTIxLjQ3OCAxMTcuMzEyIDEyMS43MjRDMTE3LjIwNCAxMjIuNDk4IDExNy40MzUgMTIyLjY4NiAxMTguNDE2IDEyMi45MTJDMTE5LjE1MSAxMjIuOTkxIDExOS4yNSAxMjIuODQ1IDExOS40NTEgMTIyLjQyWk0xMjcuMjY1IDExNi44MzZDMTMwLjkzMyAxMTMuNDc1IDEyNy4wNzQgMTA3LjQxIDEyMi43MDUgMTA5LjY3QzEyMS42MjYgMTEwLjIyOCAxMjAuNjU0IDExMi4wMTkgMTIwLjY1NCAxMTMuNDQ5QzEyMC42NTQgMTE1LjY2NCAxMjIuODMxIDExNy45MzcgMTI0Ljk1NyAxMTcuOTQxQzEyNS43MzMgMTE3Ljk0MyAxMjYuNDE0IDExNy42MTcgMTI3LjI2NSAxMTYuODM2Wk0xMTcuMTQxIDExNS42MjJDMTE5LjAzNSAxMTQuNDY4IDExOS44MDQgMTExLjc5NSAxMTguODAyIDEwOS44NTdDMTE4LjA4MiAxMDguNDY0IDExNy4wMDggMTA3LjgzIDExNS4zNjYgMTA3LjgzQzExMS41MDggMTA3LjgzIDEwOS40ODUgMTEzLjIzNCAxMTIuNDY1IDExNS41NzhDMTEzLjU3IDExNi40NDggMTE1Ljc1NCAxMTYuNDY4IDExNy4xNDEgMTE1LjYyMloiIGZpbGw9IiMwOTk2RDEiLz4KPHBhdGggb3BhY2l0eT0iMC45IiBkPSJNMzMuMTc1NyAyNkwzMi4zODEgMjcuMjE5QzMxLjk0NDkgMjcuODg5IDMxLjI4MzYgMjkuMzI0OCAzMC45MDkxIDMwLjQwODhDMzAuNTM0NyAzMS40OTI4IDI5Ljk5MjIgMzIuOTcwMSAyOS43MDQzIDMzLjY5MjhDMjkuNDE2MyAzNC40MTU0IDI5LjE3MzMgMzYuMTE1IDI5LjE2MzggMzcuNDdDMjkuMTQzNiA0MC4zNTMgMjguNzQ5NCA0MS44ODg4IDI3LjYzNjQgNDMuNDIyNUMyNi45MjEyIDQ0LjQwOCAyNi42NzUxIDQ0LjUyMjMgMjUuNDUzMiA0NC40NDFDMjMuODk5NSA0NC4zMzc3IDIyLjgxNTMgNDUuMDgxNSAyMS4yMTcgNDcuMzQ4MUMyMC43MTY1IDQ4LjA1OCAyMC4xMzY3IDQ4LjYzOTMgMTkuOTI4OSA0OC42MzkzQzE5LjcyMTEgNDguNjM5MyAxOS4xODA1IDQ4LjIzMTkgMTguNzI2MiA0Ny43MzUxQzE4LjI3MTkgNDcuMjM4MiAxNy45OTQ0IDQ3LjAxMTUgMTguMTExIDQ3LjIyOThDMTguNDkgNDcuOTM5NiAxNy41OTA0IDUzLjI2MTUgMTYuODM3OCA1NC43NjQyQzE1Ljk2NyA1Ni41MDI4IDE0LjM4NzIgNTcuNzIzMyAxMi41MzU0IDU4LjA4NDNDMTEuMDA1OSA1OC4zODI2IDExLjIyODMgNTguMDkgOC43MTc5NSA2My4wOTQ2QzYuNjYzMzQgNjcuMTkwNyA1Ljk2OTM1IDY3LjgyNjQgMi42NTUzMyA2OC42NTQyQzEuNDk3MTcgNjguOTQzNCAwLjQ1ODc1OSA2OS43MTQyIDAgNzAuNTI4N1Y3Mi44MjYzQzAuMzU2MTkzIDcyLjc0NzMgMC44Mjg3MjggNzIuNjIwMyAxLjYxNDk5IDcyLjM4NzNDMi45OTQ4NiA3MS45NzgyIDQuODIzNDggNzEuNDgwNiA1LjY3ODEgNzEuMjgwNkM3LjcyOTM0IDcwLjgwMDYgOS4zOTM1MSA2OS4yMTk1IDkuOTIyNzkgNjcuMjQ2N0MxMC4yNDI0IDY2LjA1NTQgMTAuNzAzMyA2NS40MjQxIDExLjk5OTIgNjQuNDA1OEMxMy4yODQgNjMuMzk2MiAxMy43NTY1IDYyLjc1NDYgMTQuMDY3MSA2MS41OTY5QzE0LjM3MzkgNjAuNDUzMiAxNC43MDExIDYwLjAwNCAxNS40NDA3IDU5LjcwNjNDMTcuMDE1MyA1OS4wNzI0IDIwLjY0NDQgNTUuODY1NSAyMS4yMzYzIDU0LjU4NThDMjEuNTM3MyA1My45MzQ5IDIyLjExOTggNTIuNTM5OSAyMi41Mjg3IDUxLjQ4NjJDMjMuMjYzNCA0OS41OTMyIDI1LjAxOTUgNDcuMzI2MSAyNS43NTAxIDQ3LjMyNjFDMjUuOTU3NCA0Ny4zMjYxIDI3LjEwOSA0Ni43MjQ4IDI4LjMwOTMgNDUuOTkwOEMzMS4yMzc2IDQ0LjIwMDMgMzEuNTk5MSA0My40MTM2IDMxLjU5OTEgMzguODYxNEMzMS41OTkxIDM1LjY4MTQgMzEuNjg3IDM1LjE1NTcgMzIuMzQ2OCAzNC4zNjg0QzMzLjAwMzcgMzMuNTg0NyAzMy4wOTk3IDMzLjAyNDkgMzMuMTM1MSAyOS43MzkxTDMzLjE3NTcgMjZaTTI0LjMzMzggNjMuNTk1OEMyNC4yMDM3IDYzLjYxMzUgMjQuMDczOCA2My42NjE4IDIzLjkyNTggNjMuNzM2MkMyMi45Mzk3IDY0LjIzMTUgMjIuNjEzNiA2NC45MTAyIDIxLjU5NzMgNjguNTg2QzIxLjAxNzkgNzAuNjgxNSAyMC40MjEyIDcyLjA4MTkgMTkuODc5OCA3Mi42MTc4QzE5LjQyMzUgNzMuMDY5NSAxOC45MzgzIDczLjg4MjMgMTguODAxIDc0LjQyNDJDMTguMTgxIDc2Ljg3MTUgMTYuNzQ1NCA3OC42MDczIDE0LjQ0OTUgNzkuNjg3MUMxMi40NTU1IDgwLjYyNDkgMTAuNjQwNyA4Mi4xMTc5IDkuMTExMDIgODQuMDc5OEM4LjMyMTA5IDg1LjA5MjkgNy40ODc1MiA4Ni4wMjkgNy4yNTY3OCA4Ni4xNjA5QzYuNzYxNjQgODYuNDQ0IDUuNzA4OTkgODguODk0MSA0LjYwNzg1IDkyLjMyOEMzLjcxMDkyIDk1LjEyNSAxLjcxMDY1IDk3LjQ2ODIgMC40Nzg1MTQgOTcuMTY1OEMwLjI1NDkzMSA5Ny4xMTA5IDAuMTA2OTExIDk3LjExMzcgMCA5Ny4yOTAxVjEwNC40OTJDMC41NTY0MTEgMTAzLjY2NCAxLjIzNDIgMTAyLjYyOSAyLjU2MzQ3IDEwMC41NEM0LjM0NTExIDk3LjczOTcgNi40NjM4NSA5NC40ODY3IDcuMjcxNzMgOTMuMzEyNEM4LjA3OTYgOTIuMTM4MSA5LjM1Njg3IDkwLjE0ODggMTAuMTA4NiA4OC44OTE2QzExLjIzNDIgODcuMDA5MiAxMi4xMDE2IDg2LjEyNDMgMTUuMDI4NCA4My44ODMzTDE4LjU4MzEgODEuMTYyN0wyMC40MDUzIDc1Ljk4ODFDMjMuMTg5NSA2OC4wODE3IDIzLjk1ODUgNjcuMTk5NyAyNy43NjI0IDY3LjU1MTVDMjkuNDYwNSA2Ny43MDg1IDMwLjYzMzQgNjcuNjE5NiAzMi4wNzM0IDY3LjIyNjdDMzQuMTgyNiA2Ni42NTEyIDM0LjQ3OTkgNjYuMTg3MiAzMy4zNTUxIDY1LjIzMThDMzIuNjU1NCA2NC42Mzc2IDMxLjMxNTMgNjQuNjQgMjguMjM4OCA2NS4yNDE4QzI3LjMzOTcgNjUuNDE3NyAyNi45MzQzIDY1LjI3NTcgMjUuODkzMiA2NC40MTc4QzI1LjEwNTEgNjMuNzY4NCAyNC43MjQxIDYzLjU0MjYgMjQuMzMzOCA2My41OTU4Wk0zMS43MTY2IDgzLjI1OThDMzEuNjYwNSA4My4yNzQ5IDMxLjU5MjEgODMuMzEyNiAzMS41MTE1IDgzLjM3MjFDMzEuMjcwOSA4My41NSAzMC42NTM2IDgzLjc5IDMwLjEzNzkgODMuOTA1NEMyOS4zODc2IDg0LjA3MzQgMjkuMDQ5OCA4NC40OTMyIDI4LjQ0ODIgODYuMDA0NUMyOC4wMzQ3IDg3LjA0MzIgMjcuNDkxNSA4OC4xMTUzIDI3LjI0MTIgODguMzg2M0MyNi45OTA5IDg4LjY1NzMgMjYuNDc1IDg5LjU1MSAyNi4wOTQxIDkwLjM3MzJDMjQuOTQyMiA5Mi44NTkyIDIzLjUyODIgOTQuMDYxOCAxOS45MDExIDk1LjY0MjFDMTYuNjEwNyA5Ny4wNzU2IDE2LjU2NyA5Ny4xMDg2IDE1LjY2NzEgOTguOTgwMkMxNS4xMDI3IDEwMC4xNTQgMTQuNjc5MiAxMDEuNzU3IDE0LjU0OTkgMTAzLjIwNUMxNC4yNzMxIDEwNi4zMDIgMTMuNTk2MiAxMDcuMDMxIDkuNTIxMTggMTA4LjYxNkM1LjkxNDk3IDExMC4wMTkgMy41NzcwMiAxMTEuNzQ1IDMuNDE1ODMgMTEzLjEyM0MzLjI0MDQxIDExNC42MjMgMi41OTgxMyAxMTUuMDg0IDAuOTI5MjYgMTE0LjkwN0MwLjUzOTUyOSAxMTQuODY2IDAuMjQ0MzMyIDExNC44NTEgMCAxMTQuODgxVjEyMUMxLjAyNjU4IDExOS42NTggMi43MTkyMiAxMTguMzYxIDYuMjI0OTcgMTE2LjIwNkMxMC4zNjA0IDExMy42NjUgMTIuNzA2NSAxMTEuNTc1IDEzLjU3NzkgMTA5LjY1NEMxMy45MjYgMTA4Ljg4NyAxNC42NTQ3IDEwNy4zOTMgMTUuMTk3MSAxMDYuMzM0QzE1LjczOTUgMTA1LjI3NSAxNi4yODQ1IDEwMy45MDEgMTYuNDA4NCAxMDMuMjgxQzE2LjczMjQgMTAxLjY2IDE4LjMwMzIgMTAwLjM0OSAyMC42NjU5IDk5LjcyNkMyNS4xNzcgOTguNTM3MiAyNS43NDYxIDk4LjAxNjMgMjYuMzUyNSA5NC41MzU0QzI2Ljg1NjEgOTEuNjQ1MiAyOC42MTIgODguMDY2MSAzMC41MjY3IDg2LjAyNDZDMzEuMzA5NSA4NS4xOSAzMS45NDk1IDg0LjE4IDMxLjk0OTUgODMuNzc5MUMzMS45NDk1IDgzLjM3NjYgMzEuODg0OSA4My4yMTQ2IDMxLjcxNjYgODMuMjU5OFoiIGZpbGw9IiMzNTkxMzYiLz4KPHBhdGggZD0iTTguMDgxNzcgNzQuNDA4M0M2LjAzNDE5IDczLjg3MDUgNS44OTQ0MyA3My43MzAyIDYuMDQyNzEgNzIuMzYxNUM2LjEzMDI1IDcxLjU1MzMgNi4yNDAxNyA3MC44NTc1IDYuMjg2OTYgNzAuODE1NEM2LjMzMzc2IDcwLjc3MzMgNy43MDQ0MyA3MS4wNjg3IDkuMzMyOTIgNzEuNDcxOUMxMS45NzY4IDcyLjEyNjQgMTIuNDg2NiA3Mi4xMjM4IDE0LjA5NDcgNzEuNDQ3NEMxNi40MDQxIDcwLjQ3NiAxNy4yMzgzIDY4Ljc3NTMgMTYuNDAyMiA2Ni43NDMxQzE1Ljk0MjQgNjUuNjI1NyAxNC45MjA0IDY0LjgyODEgMTIuMjM4NCA2My40OTRDNy42NDE3IDYxLjIwNzUgNi41MzA2MiA1OS45OTkgNi4yNzQ2NSA1Ny4wMDc2QzUuODkzMzcgNTIuNTUxOSA4Ljg0Njg5IDQ5Ljk4MzYgMTQuMzUyMiA0OS45ODM2QzE1Ljk3MzMgNDkuOTgzNiAxNy44NDg3IDUwLjE5MzcgMTguNTE5NiA1MC40NTA1QzE5LjYzNjggNTAuODc4MSAxOS42OTM3IDUxLjAzOTkgMTkuMTk0NSA1Mi4zNzEyQzE4LjcxODIgNTMuNjQxNiAxOC41MDI3IDUzLjc2ODggMTcuNDg2MSA1My4zNzk2QzE1LjUxOTkgNTIuNjI3IDEyLjE5NDggNTIuODU1NCAxMS4wMDU4IDUzLjgyNDdDOS43OTA1OCA1NC44MTUzIDkuNTU3MzYgNTYuOTI1MiAxMC41MzI0IDU4LjEwNzlDMTAuODcyNyA1OC41MjA3IDEyLjkwODcgNTkuNzc5IDE1LjA1NjkgNjAuOTA0MUMxOC40NjI4IDYyLjY4ODEgMTkuMDgyIDYzLjIyMTQgMTkuODk1MSA2NS4wNzE5QzIxLjExNTIgNjcuODQ4NyAyMC42Nzg4IDcwLjM0MzcgMTguNjA3OCA3Mi40MzIzQzE2LjE2MDcgNzQuOTAwMiAxMi41NDEzIDc1LjU3OTYgOC4wODE3NyA3NC40MDgzWk0yOC45MzI4IDc0LjM4MjNDMjUuMjM2NSA3Mi45OTU4IDIzLjcxMzggNzAuNTQwNSAyMy43MTM4IDY1Ljk2NjdDMjMuNzEzOCA2Mi41MDM0IDI0LjU1ODggNjAuNDY5NyAyNi44MzMzIDU4LjQ1OTNDMjguMzk2NCA1Ny4wNzc2IDI4Ljk4NjcgNTYuODY4NiAzMS4zMjY4IDU2Ljg2ODZDMzIuODE2OCA1Ni44Njg2IDM0LjY4MjEgNTcuMjEyOSAzNS41MDA1IDU3LjYzODlDMzcuMzE2OSA1OC41ODQ2IDM4LjgzMTkgNjEuNzQyNiAzOC44NDY2IDY0LjYxNDNMMzguODU3MyA2Ni43MDQ0SDMyLjk0MjNIMjcuMDI3M0wyNy4zNDIgNjguMDU2OUMyNy41MTUgNjguODAwNyAyOC4zMzU0IDcwLjAzOTEgMjkuMTY1IDcwLjgwOUMzMC41NzczIDcyLjExOTYgMzAuODk0OSA3Mi4xOTc5IDM0LjE1NDcgNzIuMDM4NUMzNy4zOTM4IDcxLjg4MDEgMzcuNjQ2MyA3MS45NDA5IDM3Ljc4NCA3Mi45MTIyQzM3Ljk2MjYgNzQuMTcyNSAzNy4xODgyIDc0LjUyMzYgMzMuNTI0MiA3NC44NDM0QzMxLjgwODUgNzQuOTkzMiAzMC4xMDU2IDc0LjgyMjIgMjguOTMyOCA3NC4zODIzWk0zNS4wODgxIDYyLjUyNDJDMzQuOTU1OCA2MC42NzMgMzMuMzY0NCA1OS4zMjc2IDMxLjMwNzIgNTkuMzI3NkMyOS43MDg2IDU5LjMyNzYgMjguNzI4MSA2MC4wOTA5IDI3LjY2MiA2Mi4xNjU1QzI2Ljc0NTcgNjMuOTQ4NiAyNy40MTIgNjQuMjk2NSAzMS40NDg4IDY0LjE0MjVMMzUuMTkzNiA2My45OTk2TDM1LjA4ODEgNjIuNTI0MlpNNDQuMzkxNCA3NC4zNzA4QzQyLjU3MTEgNzMuNTQ2OCA0MS43MDU5IDcyLjEyODYgNDEuNjQyMSA2OS44NjQ3QzQxLjU0MTYgNjYuMjk0NCA0NC4xMTEgNjQuMTQ2OCA0OS4yNTc2IDYzLjQ5OTRDNTEuODQxNCA2My4xNzQ0IDUyLjA0OTUgNjMuMDU3NyA1MS43NTkzIDYyLjA5NjlDNTAuOTY1IDU5LjQ2NjYgNDguMjQyMyA1OC41NjQ0IDQ0LjkyNzYgNTkuODMzMUM0My40MzAzIDYwLjQwNjMgNDMuNDg2OCA2MC40MzEzIDQzLjA1MTQgNTkuMDAzMkM0Mi43ODAxIDU4LjExMzUgNDIuOTk4MiA1Ny44NTExIDQ0LjM5NSA1Ny4zODdDNDYuOTM2NCA1Ni41NDI3IDUxLjM3NDUgNTYuNjM0MiA1Mi43Nzc5IDU3LjU2QzU0LjkzOTIgNTguOTg1NyA1NS4zNzUxIDYwLjYwMTkgNTUuNTQ4NyA2Ny44MzI4TDU1LjcxMDYgNzQuNTc0NUw1NC4xMjMgNzQuNTc0QzUzLjAzNzcgNzQuNTczMyA1Mi41MzUzIDc0LjMzOTYgNTIuNTM1MyA3My44MzU0QzUyLjUzNTMgNzIuOTA2NiA1Mi4wNTI4IDcyLjkwMjQgNTAuNzUyIDczLjgxOTZDNDkuMjAxMyA3NC45MTMgNDYuMTY5NyA3NS4xNzU3IDQ0LjM5MTQgNzQuMzcwOFpNNTAuOTQ3NyA3MC44MTc1QzUxLjcwOTkgNjkuOTczNSA1Mi4wNDY4IDY4Ljk4NiA1Mi4wNDY4IDY3LjU5NjZWNjUuNTkyOUw0OS44MTgyIDY1Ljg0NThDNDUuNzE5IDY2LjMxMSA0My44NzQ5IDY5LjUxMTggNDYuNTA1OCA3MS41OTUzQzQ4LjAzNzEgNzIuODA3OSA0OS4zNTk0IDcyLjU3NjMgNTAuOTQ3NyA3MC44MTc1Wk05Mi4wMDIgNzQuNTc4OEM4OC40MDI0IDczLjQ4NjQgODYuMjQxOSA3MC4yNDY2IDg2LjI0MTkgNjUuOTQxQzg2LjI0MTkgNjAuNDA0MiA4OS41MjExIDU2LjgzMjUgOTQuNjQxIDU2Ljc5MjVDOTguNjk4OSA1Ni43NjA5IDEwMS4yNjMgNTkuNDY3OSAxMDEuNTAzIDY0LjAzNjZMMTAxLjYzIDY2LjQ1ODVMOTYuMjU2MiA2Ni41ODg1QzkzLjMwMDcgNjYuNjYgOTAuNjE1OCA2Ni44MTYgOTAuMjg5NyA2Ni45MzUxQzg5LjM4MTggNjcuMjY2OCA5MC40Nzg4IDY5Ljk0NyA5Mi4wMzA2IDcxLjE4ODZDOTMuMTU5OSA3Mi4wOTIxIDkzLjc3MSA3Mi4xOTEyIDk2LjgxNzggNzEuOTY1QzEwMC4xOTMgNzEuNzE0NCAxMDAuMzE4IDcxLjc0NDkgMTAwLjUzMSA3Mi44Njg0QzEwMC43MyA3My45MTMzIDEwMC41MDkgNzQuMDgzNSA5OC4zNTc5IDc0LjU0OEM5NS42MTAzIDc1LjE0MTIgOTMuODgyOSA3NS4xNDk2IDkyLjAwMiA3NC41Nzg4Wk05Ny45NjU5IDYzLjA4MjNDOTcuOTY1OSA2MS4xMjMxIDk2LjE4NTggNTkuMzI3NiA5NC4yNDM0IDU5LjMyNzZDOTIuMjQ5NCA1OS4zMjc2IDkwLjE0OTkgNjEuMjU2MiA5MC4xNDk5IDYzLjA4NzhDOTAuMTQ5OSA2NC4yMDcgOTAuMjc5NyA2NC4yNDU1IDk0LjA1NzkgNjQuMjQ1NUM5Ny44NDE0IDY0LjI0NTUgOTcuOTY1OSA2NC4yMDg0IDk3Ljk2NTkgNjMuMDgyM1pNMTEwLjA0MiA3NC40N0MxMDYuMTQ5IDczLjQzIDEwMy45MyA2OS40MDI5IDEwNC41NCA2NC40ODYyQzEwNS4xNjYgNTkuNDQ0MiAxMDcuOTUxIDU2Ljg3MzYgMTEyLjc5MiA1Ni44NzA1QzExNS4zNzQgNTYuODY5IDExNS44MDUgNTcuMDI0OSAxMTcuMjYgNTguNDlDMTE4Ljg3OCA2MC4xMTg1IDExOS45NDEgNjIuODM0MyAxMTkuOTQ2IDY1LjM1MkwxMTkuOTQ5IDY2LjcwNDRIMTE0LjA4N0MxMDguNDg4IDY2LjcwNDQgMTA4LjIyNSA2Ni43NTAxIDEwOC4yMjUgNjcuNzIwM0MxMDguMjI1IDcwLjcxMjIgMTEwLjk1MiA3Mi4zNDQyIDExNS4zNTcgNzEuOTg4MkMxMTguMTM2IDcxLjc2MzcgMTE4LjQyMyA3MS44MzE1IDExOC42NjcgNzIuNzY3NEMxMTguOTk4IDc0LjA0NDMgMTE4Ljk2OCA3NC4wNzIgMTE2LjY5IDc0LjYwNDNDMTE0LjM2NyA3NS4xNDcgMTEyLjQzIDc1LjEwNzggMTEwLjA0MiA3NC40N1pNMTE2LjExOSA2Mi43NzAxQzExNS44NjQgNjAuODc4NyAxMTQuMTU5IDU5LjMyNzYgMTEyLjMzNSA1OS4zMjc2QzExMC41NjYgNTkuMzI3NiAxMDguMjI0IDYxLjYwMTQgMTA4LjIyNCA2My4zMTk1QzEwOC4yMjQgNjQuMjEyOCAxMDguNTI3IDY0LjI3NDYgMTEyLjI1NSA2NC4xNDI0QzExNi4yNDEgNjQuMDAxMSAxMTYuMjgzIDYzLjk4NjIgMTE2LjExOSA2Mi43NzAxWk0xMjYuODk0IDc0LjI0N0MxMjQuODI2IDczLjIyMDggMTIzLjUzMiA3MS4zNTg5IDEyMi44OTQgNjguNDg4OUMxMjEuOTc1IDY0LjM2MDUgMTIzLjA3NCA2MC40OTE0IDEyNS44MyA1OC4xNTY3QzEyNy44MjcgNTYuNDY1NyAxMzEuODM4IDU2LjMzMDUgMTMzLjgwNSA1Ny44ODc5TDEzNS4wOTIgNTguOTA3MlY1My45NTM2VjQ5SDEzNy4wNDZIMTM5VjYxLjc4NjVWNzQuNTczMUgxMzcuMjlDMTM1Ljc2MiA3NC41NzMxIDEzNS41OCA3NC40MzMxIDEzNS41OCA3My4yNTc5VjcxLjk0MjdMMTM0LjQ4MSA3Mi45NzkyQzEzMi4yMzMgNzUuMDk5OCAxMjkuNTI1IDc1LjU1MjMgMTI2Ljg5NCA3NC4yNDdaTTEzMy42NjQgNzAuNjc2NkMxMzQuOTc2IDY5LjM1NTcgMTM1LjA5MiA2OC45NTM3IDEzNS4wOTIgNjUuNzIwOUMxMzUuMDkyIDYyLjQ1NzIgMTM0Ljk4NSA2Mi4wOTQ1IDEzMy42MDcgNjAuNzA3NkMxMzIuMzY1IDU5LjQ1NzUgMTMxLjg2NSA1OS4yNjIyIDEzMC41NTQgNTkuNTE1NEMxMjYuMTQ0IDYwLjM2NzIgMTI0LjgzNSA2OC4xNDIzIDEyOC41OTggNzEuMTIyOUMxMzAuMzQ4IDcyLjUwODEgMTMxLjk4OCA3Mi4zNjM1IDEzMy42NjQgNzAuNjc2NlpNNjEuNDEwNyA2Ni4wNTg0QzYwLjAyMiA2MS4zNzU0IDU4Ljg4NTkgNTcuMzkxOSA1OC44ODU5IDU3LjIwNjJDNTguODg1OSA1Ny4wMjA2IDU5LjcyNzQgNTYuODY4NiA2MC43NTU5IDU2Ljg2ODZINjIuNjI1OUw2NC4yNTUxIDYzLjg3NjZDNjUuMTUxMiA2Ny43MzEgNjUuOTU2IDcwLjY2MzMgNjYuMDQzNyA3MC4zOTI5QzY2LjEzMTMgNzAuMTIyNCA2Ny4wNTU3IDY3LjAyNDEgNjguMDk3OCA2My41MDc4TDY5Ljk5MjYgNTcuMTE0NUg3MS41OTY5SDczLjIwMTJMNzQuODg2NSA2My4yNjE5Qzc1LjgxMzQgNjYuNjQzIDc2LjY4MzIgNjkuNzQxMiA3Ni44MTk0IDcwLjE0N0M3Ni45NTU3IDcwLjU1MjcgNzcuODQxOSA2Ny43MzEgNzguNzg5IDYzLjg3NjZMODAuNTEwOSA1Ni44Njg2SDgyLjQ1MTdDODMuOTUxNyA1Ni44Njg2IDg0LjMzMDMgNTcuMDMxNiA4NC4xMTkgNTcuNTg2QzgzLjk2ODYgNTcuOTgwNiA4Mi42OTU2IDYxLjk2NDEgODEuMjkwMiA2Ni40MzgyTDc4LjczNDkgNzQuNTczMUg3Ni45NjM1SDc1LjE5MjFMNzMuNTgxMiA2OC43OTQ1QzcyLjY5NTIgNjUuNjE2MyA3MS44NTg1IDYyLjY4NDEgNzEuNzIxNyA2Mi4yNzgzQzcxLjQ0NjUgNjEuNDYxNiA3MS41OTExIDYxLjA3MzMgNjkuMTExNCA2OS4yODYzTDY3LjUxNTIgNzQuNTczMUg2NS43MjU0SDYzLjkzNTZMNjEuNDEwNyA2Ni4wNTg0WiIgZmlsbD0id2hpdGUiLz4KPHBhdGggZD0iTTE5Ljk3NDYgMTE5LjI3NEMxOS4wMTU4IDExOC4xMTkgMjAuMzM4MSAxMTYuMTY2IDIxLjU2MDQgMTE2LjkzMkMyMi43NjMyIDExNy42ODYgMjIuMzMwNSAxMTkuNzYxIDIwLjk3MDQgMTE5Ljc2MUMyMC42NDUgMTE5Ljc2MSAyMC4xOTY5IDExOS41NDIgMTkuOTc0NiAxMTkuMjc0WiIgZmlsbD0idXJsKCNwYWludDNfcmFkaWFsXzY3OV8xOTEwKSIvPgo8cGF0aCBkPSJNMjMuODM2IDExMi42M0MyMi4xMTUyIDExMS42ODkgMjEuODAyOSAxMDkuNzk3IDIzLjE0NjUgMTA4LjQ1M0MyNC4wODU3IDEwNy41MTQgMjUuMjEgMTA3LjM5NCAyNi4yNTA3IDEwOC4xMjNDMjcuODU3MSAxMDkuMjQ5IDI3LjQ2NTUgMTEyLjAxMyAyNS42MDc5IDExMi42NkMyNS42MDc5IDExMi42NiAyNC40NzQ1IDExMi45NzMgMjMuODM2IDExMi42M1oiIGZpbGw9InVybCgjcGFpbnQ0X3JhZGlhbF82NzlfMTkxMCkiLz4KPHBhdGggZD0iTTMzLjc4NTUgMTIwLjAzNkMzMy43ODU1IDEyMC4xODggMzMuNzU1NyAxMjAuMzM4IDMzLjY5NzYgMTIwLjQ3OUMzMy42Mzk1IDEyMC42MTkgMzMuNTU0NCAxMjAuNzQ2IDMzLjQ0NzEgMTIwLjg1M0MzMy4zMzk4IDEyMC45NjEgMzMuMjEyNCAxMjEuMDQ2IDMzLjA3MjMgMTIxLjEwNEMzMi45MzIxIDEyMS4xNjIgMzIuNzgxOCAxMjEuMTkyIDMyLjYzMDEgMTIxLjE5MkMzMi40NzgzIDEyMS4xOTIgMzIuMzI4MSAxMjEuMTYyIDMyLjE4NzkgMTIxLjEwNEMzMi4wNDc3IDEyMS4wNDYgMzEuOTIwMyAxMjAuOTYxIDMxLjgxMyAxMjAuODUzQzMxLjcwNTcgMTIwLjc0NiAzMS42MjA2IDEyMC42MTkgMzEuNTYyNiAxMjAuNDc5QzMxLjUwNDUgMTIwLjMzOCAzMS40NzQ2IDEyMC4xODggMzEuNDc0NiAxMjAuMDM2QzMxLjQ3NDYgMTE5LjczIDMxLjU5NjMgMTE5LjQzNiAzMS44MTMgMTE5LjIxOUMzMi4wMjk3IDExOS4wMDMgMzIuMzIzNiAxMTguODgxIDMyLjYzMDEgMTE4Ljg4MUMzMi45MzY1IDExOC44ODEgMzMuMjMwNCAxMTkuMDAzIDMzLjQ0NzEgMTE5LjIxOUMzMy42NjM4IDExOS40MzYgMzMuNzg1NSAxMTkuNzMgMzMuNzg1NSAxMjAuMDM2WiIgZmlsbD0iYmxhY2siLz4KPHBhdGggZD0iTTEyMC43MjEgMTE4LjI3NkMxMjAuNzIxIDExOC42MjMgMTIwLjU2NSAxMTguOTU2IDEyMC4yODcgMTE5LjIwMUMxMjAuMDA5IDExOS40NDYgMTE5LjYzMiAxMTkuNTg0IDExOS4yMzkgMTE5LjU4NEMxMTguODQ2IDExOS41ODQgMTE4LjQ2OSAxMTkuNDQ2IDExOC4xOTEgMTE5LjIwMUMxMTcuOTEzIDExOC45NTYgMTE3Ljc1NyAxMTguNjIzIDExNy43NTcgMTE4LjI3NkMxMTcuNzU3IDExOC4xMDUgMTE3Ljc5NSAxMTcuOTM1IDExNy44NyAxMTcuNzc2QzExNy45NDQgMTE3LjYxNyAxMTguMDUzIDExNy40NzMgMTE4LjE5MSAxMTcuMzUyQzExOC4zMjkgMTE3LjIzIDExOC40OTIgMTE3LjEzNCAxMTguNjcyIDExNy4wNjhDMTE4Ljg1MSAxMTcuMDAzIDExOS4wNDQgMTE2Ljk2OSAxMTkuMjM5IDExNi45NjlDMTE5LjQzMyAxMTYuOTY5IDExOS42MjYgMTE3LjAwMyAxMTkuODA2IDExNy4wNjhDMTE5Ljk4NiAxMTcuMTM0IDEyMC4xNDkgMTE3LjIzIDEyMC4yODcgMTE3LjM1MkMxMjAuNDI0IDExNy40NzMgMTIwLjUzMyAxMTcuNjE3IDEyMC42MDggMTE3Ljc3NkMxMjAuNjgyIDExNy45MzUgMTIwLjcyMSAxMTguMTA1IDEyMC43MjEgMTE4LjI3NloiIGZpbGw9IiM1OTY4NkYiLz4KPGRlZnM+CjxsaW5lYXJHcmFkaWVudCBpZD0icGFpbnQwX2xpbmVhcl82NzlfMTkxMCIgeDE9IjExIiB5MT0iLTQuNzc3NjhlLTA3IiB4Mj0iMTY0LjUiIHkyPSIxNTAuNSIgZ3JhZGllbnRVbml0cz0idXNlclNwYWNlT25Vc2UiPgo8c3RvcCBzdG9wLWNvbG9yPSIjNjRCN0ZGIi8+CjxzdG9wIG9mZnNldD0iMSIgc3RvcC1jb2xvcj0iIzAwNURBRCIvPgo8L2xpbmVhckdyYWRpZW50Pgo8cmFkaWFsR3JhZGllbnQgaWQ9InBhaW50MV9yYWRpYWxfNjc5XzE5MTAiIGN4PSIwIiBjeT0iMCIgcj0iMSIgZ3JhZGllbnRVbml0cz0idXNlclNwYWNlT25Vc2UiIGdyYWRpZW50VHJhbnNmb3JtPSJ0cmFuc2xhdGUoMTI0LjkwNCAxMjguNjM2KSByb3RhdGUoLTAuMDQ4NTUyKSBzY2FsZSgzNi4yODAyIDMxLjQwMzIpIj4KPHN0b3Agc3RvcC1jb2xvcj0iIzExNzdDRSIvPgo8c3RvcCBvZmZzZXQ9IjEiIHN0b3AtY29sb3I9IiM3RUM3RkYiIHN0b3Atb3BhY2l0eT0iMCIvPgo8L3JhZGlhbEdyYWRpZW50Pgo8cmFkaWFsR3JhZGllbnQgaWQ9InBhaW50Ml9yYWRpYWxfNjc5XzE5MTAiIGN4PSIwIiBjeT0iMCIgcj0iMSIgZ3JhZGllbnRVbml0cz0idXNlclNwYWNlT25Vc2UiIGdyYWRpZW50VHJhbnNmb3JtPSJ0cmFuc2xhdGUoMzkuMzUxMiAxMjEuNDYpIHJvdGF0ZSgtMC4wNTczKSBzY2FsZSg1MC4yMjc2IDUxLjMwOTEpIj4KPHN0b3Agc3RvcC1jb2xvcj0iIzExNzdDRSIvPgo8c3RvcCBvZmZzZXQ9IjEiIHN0b3AtY29sb3I9IiM3RUM3RkYiIHN0b3Atb3BhY2l0eT0iMCIvPgo8L3JhZGlhbEdyYWRpZW50Pgo8cmFkaWFsR3JhZGllbnQgaWQ9InBhaW50M19yYWRpYWxfNjc5XzE5MTAiIGN4PSIwIiBjeT0iMCIgcj0iMSIgZ3JhZGllbnRVbml0cz0idXNlclNwYWNlT25Vc2UiIGdyYWRpZW50VHJhbnNmb3JtPSJ0cmFuc2xhdGUoMjAuOTU0OCAxMTguMjYpIHNjYWxlKDEuMzA5MjkgMS41MDEyNykiPgo8c3RvcCBzdG9wLWNvbG9yPSIjODhBM0QwIi8+CjxzdG9wIG9mZnNldD0iMSIgc3RvcC1jb2xvcj0iIzVEODNCRiIvPgo8L3JhZGlhbEdyYWRpZW50Pgo8cmFkaWFsR3JhZGllbnQgaWQ9InBhaW50NF9yYWRpYWxfNjc5XzE5MTAiIGN4PSIwIiBjeT0iMCIgcj0iMSIgZ3JhZGllbnRVbml0cz0idXNlclNwYWNlT25Vc2UiIGdyYWRpZW50VHJhbnNmb3JtPSJ0cmFuc2xhdGUoMjQuNzg0MyAxMTAuMjIxKSBzY2FsZSgyLjQ3Mjc3IDIuNTY5NTQpIj4KPHN0b3Agc3RvcC1jb2xvcj0iIzg4QTNEMCIvPgo8c3RvcCBvZmZzZXQ9IjEiIHN0b3AtY29sb3I9IiM1RDgzQkYiLz4KPC9yYWRpYWxHcmFkaWVudD4KPC9kZWZzPgo8L3N2Zz4K - keysOrder: [["apiVersion"], ["appVersion"], ["kind"], ["metadata"], ["metadata", "name"], ["spec", "host"], ["spec", "topology"], ["spec", "replicationFactor"], ["spec", "db"], ["spec", "db", "replicas"], ["spec", "db", "size"], ["spec", "db", "storageClass"], ["spec", "db", "resources"], ["spec", "db", "resourcesPreset"], ["spec", "master"], ["spec", "master", "replicas"], ["spec", "master", "resources"], ["spec", "master", "resourcesPreset"], ["spec", "filer"], ["spec", "filer", "replicas"], ["spec", "filer", "resources"], ["spec", "filer", "resourcesPreset"], ["spec", "filer", "grpcHost"], ["spec", "filer", "grpcPort"], ["spec", "filer", "whitelist"], ["spec", "volume"], ["spec", "volume", "replicas"], ["spec", "volume", "size"], ["spec", "volume", "storageClass"], ["spec", "volume", "diskType"], ["spec", "volume", "resources"], ["spec", "volume", "resourcesPreset"], ["spec", "volume", "zones"], ["spec", "volume", "pools"], ["spec", "s3"], ["spec", "s3", "replicas"], ["spec", "s3", "resources"], ["spec", "s3", "resourcesPreset"]] + keysOrder: [["apiVersion"], ["appVersion"], ["kind"], ["metadata"], ["metadata", "name"], ["spec", "host"], ["spec", "topology"], ["spec", "replicationFactor"], ["spec", "db"], ["spec", "db", "replicas"], ["spec", "db", "size"], ["spec", "db", "storageClass"], ["spec", "db", "resources"], ["spec", "db", "resourcesPreset"], ["spec", "master"], ["spec", "master", "replicas"], ["spec", "master", "resources"], ["spec", "master", "resourcesPreset"], ["spec", "filer"], ["spec", "filer", "replicas"], ["spec", "filer", "resources"], ["spec", "filer", "resourcesPreset"], ["spec", "filer", "grpcHost"], ["spec", "filer", "grpcPort"], ["spec", "filer", "whitelist"], ["spec", "volume"], ["spec", "volume", "replicas"], ["spec", "volume", "size"], ["spec", "volume", "storageClass"], ["spec", "volume", "diskType"], ["spec", "volume", "resources"], ["spec", "volume", "resourcesPreset"], ["spec", "volume", "zones"], ["spec", "volume", "pools"], ["spec", "s3"], ["spec", "s3", "replicas"], ["spec", "s3", "resources"], ["spec", "s3", "resourcesPreset"], ["spec", "cosi"], ["spec", "cosi", "orphanIdentities"]] secrets: exclude: [] include: [] diff --git a/packages/system/seaweedfs/Chart.yaml b/packages/system/seaweedfs/Chart.yaml index b6aee5353..1d8beac8d 100644 --- a/packages/system/seaweedfs/Chart.yaml +++ b/packages/system/seaweedfs/Chart.yaml @@ -1,3 +1,7 @@ apiVersion: v2 name: cozy-seaweedfs version: 0.0.0 # Placeholder, the actual version will be automatically set during the build process +dependencies: + - name: seaweedfs + version: "*" + repository: file://charts/seaweedfs diff --git a/packages/system/seaweedfs/files/object-lock-actions.sh b/packages/system/seaweedfs/files/object-lock-actions.sh new file mode 100755 index 000000000..415dfc6a1 --- /dev/null +++ b/packages/system/seaweedfs/files/object-lock-actions.sh @@ -0,0 +1,122 @@ +#!/bin/sh +# SeaweedFS 4.48 requires dedicated Object Lock actions. Upgrading the COSI +# driver does not re-grant access for Ready BucketAccesses, so old identities +# still need those actions. Governance bypass was never implied by Write. +# The IAM listing and apply output contain secret keys; neither is printed. +# Grant migration is best-effort: handled errors must not fail the Helm action. +set -eu + +: "${MASTER:?}" "${FILER:?}" "${NAMESPACE:?}" "${RELEASE:?}" +JOB=${JOB:-$RELEASE-object-lock-actions} +# weed shell waits for the master without a deadline, and kubectl waits for the +# API server without one. +ATTEMPTS=${ATTEMPTS:-3} +RETRY_DELAY=${RETRY_DELAY:-20} +SHELL_TIMEOUT=${SHELL_TIMEOUT:-30} + +weed_shell() { + timeout "$SHELL_TIMEOUT" weed shell -master="$MASTER" -filer="$FILER" +} + +# Public-read buckets share this identity, and the COSI driver revokes public +# read by removing only Read:; derived actions would outlive it. +ANONYMOUS=anonymous + +# Static identities come from a config file the IAM API cannot change. +plan_from_config() { + sed -n '/^{/,$p' | jq -c --arg anonymous "$ANONYMOUS" ' + def implied: + if test("^Write(:|$)") then + sub("^Write"; "") as $s + | ["PutObjectRetention", "PutObjectLegalHold", "PutBucketObjectLockConfiguration"] | map(. + $s) + elif test("^Read(:|$)") then + sub("^Read"; "") as $s + | ["GetObjectRetention", "GetObjectLegalHold", "GetBucketObjectLockConfiguration"] | map(. + $s) + else [] end; + if has("identities") | not then error("no IAM configuration in the output") else . end + | [.identities[]? + | select(.isStatic != true and .name != $anonymous) + | (.actions // []) as $have + | {name, have: $have, missing: ([$have[] | implied[]] | unique - $have)} + | select(.missing | length > 0)]' +} + +# s3.configure resolves the user on its own, and creates a fresh identity +# with no keys when it cannot, which would then replace the one listed. The +# dry run shows what it resolved; only an identity that still carries every +# action the listing showed is applied. +safe_commands() { + sed '/^Running in simulation mode/d' | jq -rs --argjson plan "$1" ' + (map({key: .name, value: (.actions // [])}) | from_entries) as $resolved + | $plan[] + | select(($resolved[.name] // []) as $r | .have - $r | length == 0) + | "s3.configure -user=\(.name) -actions=\(.missing | join(",")) -apply"' +} + +# weed shell splits a line on ";" and on whitespace, so an identity whose name +# or actions carry anything else is never put on a command line. It stays in +# the plan and is reported. +dry_run_commands() { + jq -r '.[] + | select(.name | test("^[A-Za-z0-9._@+=-]+\\z")) + | select(.missing | all(test("^[A-Za-z0-9._@+=:/*?-]+\\z"))) + | "s3.configure -user=\(.name) -actions=\(.missing | join(","))"' +} + +# Each attempt reads, then grants; the read after the last attempt is what +# decides the outcome. A failed read keeps the previous plan for the next +# grant, but the outcome is never reported from it. +plan='[]' +attempt=0 +while :; do + read_ok=false + if config=$(echo s3.configure | weed_shell) && fresh=$(printf '%s\n' "$config" | plan_from_config) && [ -n "$fresh" ]; then + read_ok=true + plan=$fresh + if [ "$plan" = '[]' ]; then + echo "every identity carries the Object Lock actions its grants imply" + exit 0 + fi + fi + [ "$attempt" -ge "$ATTEMPTS" ] && break + attempt=$((attempt + 1)) + if [ -n "$plan" ] && dry=$(printf '%s\n' "$plan" | dry_run_commands) && [ -n "$dry" ] && + commands=$(printf '%s\n' "$dry" | weed_shell | safe_commands "$plan") && [ -n "$commands" ]; then + printf '%s\n' "$commands" | sed 's/^s3.configure -user=\([^ ]*\) -actions=\([^ ]*\) -apply$/granting \2 to \1/' + printf '%s\n' "$commands" | weed_shell >/dev/null || true + fi + sleep "$RETRY_DELAY" +done + +if $read_ok; then + pending=$(printf '%s\n' "$plan" | jq -r '[.[].name] | join(" ")') + message="Object Lock actions not granted after $ATTEMPTS attempts; identities still missing them: $pending. See the logs of Job $JOB." +else + message="Object Lock actions unverified after $ATTEMPTS attempts: the IAM configuration could not be read. See the logs of Job $JOB." +fi +echo "$message" >&2 +now=$(date -u +%Y-%m-%dT%H:%M:%SZ) +# kubectl describe matches events by uid as well as name. +uid=$(timeout "$SHELL_TIMEOUT" kubectl get helmrelease "$RELEASE" --namespace "$NAMESPACE" --output jsonpath='{.metadata.uid}') || uid= +# JSON, not YAML: kubectl splits a YAML stream on document markers and its YAML +# reader rejects control characters, either of which an identity name can carry. +jq -n --arg job "$JOB" --arg namespace "$NAMESPACE" --arg release "$RELEASE" \ + --arg uid "$uid" --arg message "$message" --arg now "$now" '{ + apiVersion: "v1", + kind: "Event", + metadata: {generateName: "\($job)-", namespace: $namespace}, + involvedObject: { + apiVersion: "helm.toolkit.fluxcd.io/v2", + kind: "HelmRelease", + name: $release, + namespace: $namespace, + uid: $uid + }, + type: "Warning", + reason: "ObjectLockActionsNotGranted", + message: $message, + source: {component: $job}, + firstTimestamp: $now, + lastTimestamp: $now, + count: 1 +}' | timeout "$SHELL_TIMEOUT" kubectl create --filename - || echo "could not record the Warning Event" >&2 diff --git a/packages/system/seaweedfs/files/orphan-identities.sh b/packages/system/seaweedfs/files/orphan-identities.sh new file mode 100755 index 000000000..6de094388 --- /dev/null +++ b/packages/system/seaweedfs/files/orphan-identities.sh @@ -0,0 +1,137 @@ +#!/bin/sh +# Removes the per-identity IAM files of BucketAccesses that no longer exist. +# Since SeaweedFS 4.08 the S3 gateways move every identity out of +# /etc/iam/identity.json into /etc/iam/identities/.json, and COSI driver +# releases up to v0.3.1 revoke only from identity.json, so each deleted +# BucketAccess left its file behind. +# +# The COSI sidecar names every identity it creates ba-. A +# file of that shape that no BucketAccess in any namespace names, by uid or by +# status.accountID, is left over; anything else on the filer is never touched. +# The uid covers a BucketAccess still being granted, which has no accountID +# yet; the accountID covers one restored with its status under a new uid. +# One restored without its status is granted afresh, so a workload still +# holding the old keys loses them once their file is removed. +# +# The directory is listed before the BucketAccesses. A BucketAccess exists +# before its grant writes a file, so every file in the first listing whose +# BucketAccess still exists is named by the second one. File ages are not +# used: grants and gateway migrations rewrite left-over files too. +# +# MODE=delete removes; anything else only reports. A filer that other clusters +# reach as Client topology carries identities whose BucketAccesses this +# cluster cannot see, so the chart sets report there. +# +# Identity files carry secret keys, so their content is never printed. Any +# failure to list leaves everything in place, and no failure the script meets +# fails the release: it ends in a Warning Event on the HelmRelease instead. +set -eu + +: "${MASTER:?}" "${FILER:?}" "${NAMESPACE:?}" "${RELEASE:?}" +JOB=${JOB:-$RELEASE-orphan-identities} +MODE=${MODE:-report} +SHELL_TIMEOUT=${SHELL_TIMEOUT:-30} +DIR=/etc/iam/identities + +# weed shell reports a failed command as an "error:" line on stderr and still +# exits 0, so stderr is kept with the output for the callers to check. +weed_shell() { + timeout "$SHELL_TIMEOUT" weed shell -master="$MASTER" -filer="$FILER" 2>&1 +} + +# event +event() { + message=$(printf '%s' "$3" | tr -d '"\134') + stamp=$(date -u +%Y-%m-%dT%H:%M:%SZ) + # kubectl describe matches events by uid as well as name. + if [ -z "${hr_uid+set}" ]; then + hr_uid=$(timeout "$SHELL_TIMEOUT" kubectl get helmrelease "$RELEASE" --namespace "$NAMESPACE" --output jsonpath='{.metadata.uid}') || hr_uid= + fi + timeout "$SHELL_TIMEOUT" kubectl create --filename - </dev/null || echo "could not record the $2 Event" >&2 +apiVersion: v1 +kind: Event +metadata: + generateName: $JOB- + namespace: $NAMESPACE +involvedObject: + apiVersion: helm.toolkit.fluxcd.io/v2 + kind: HelmRelease + name: $RELEASE + namespace: $NAMESPACE + uid: "$hr_uid" +type: $1 +reason: $2 +message: "$message" +source: + component: $JOB +firstTimestamp: "$stamp" +lastTimestamp: "$stamp" +count: 1 +EOF +} + +not_checked() { + echo "$1" >&2 + event Warning OrphanIdentitiesNotChecked "$1 Nothing was removed. See the logs of Job $JOB." + exit 0 +} + +# The ba- names in a listing of $DIR, without the .json suffix. +cosi_names() { + grep -E '^ba-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\.json$' | sed 's/\.json$//' +} + +if ! files=$(echo "fs.ls $DIR" | weed_shell) || printf '%s\n' "$files" | grep -q '^error'; then + not_checked "Could not list $DIR." +fi + +if ! listing=$(timeout "$SHELL_TIMEOUT" kubectl get bucketaccesses.objectstorage.k8s.io --all-namespaces --output json) || + ! live=$(printf '%s\n' "$listing" | jq -r ' + .items[] + | (.metadata.uid | if type == "string" and . != "" then "ba-" + . else error("no uid") end), + (.status.accountID // empty)' 2>/dev/null); then + not_checked "Could not list BucketAccesses." +fi + +orphans= +for name in $(printf '%s\n' "$files" | cosi_names); do + printf '%s\n' "$live" | grep -qxF "$name" || orphans="$orphans $name" +done +orphans=${orphans# } + +if [ -z "$orphans" ]; then + echo "nothing to remove" + exit 0 +fi + +if [ "$MODE" != delete ]; then + echo "left over from deleted BucketAccesses, not removed: $orphans" + event Warning OrphanIdentitiesFound "Identities left over from deleted BucketAccesses, not removed (mode $MODE): $orphans. Set cosi.orphanIdentities to delete in the SeaweedFS application to remove them, once no other cluster uses this filer." + exit 0 +fi + +# An empty list next to identities on the filer is likelier a wrong answer +# than every bucket user gone at once. +if [ -z "$live" ]; then + echo "no BucketAccess exists, not removed: $orphans" >&2 + event Warning OrphanIdentitiesFound "No BucketAccess exists in the cluster, so these identities on the filer were not removed: $orphans" + exit 0 +fi + +# fs.rm exits 0 and may print nothing on failure, so what is gone is read back. +for name in $orphans; do echo "fs.rm $DIR/$name.json"; done | weed_shell >/dev/null || true +if ! after=$(echo "fs.ls $DIR" | weed_shell) || printf '%s\n' "$after" | grep -q '^error'; then + echo "could not list $DIR after removing: $orphans" >&2 + event Warning OrphanIdentityNotRemoved "Could not confirm the removal of identities left over from deleted BucketAccesses: $orphans. See the logs of Job $JOB." + exit 0 +fi +left=$(printf '%s\n' "$after" | cosi_names) +for name in $orphans; do + if printf '%s\n' "$left" | grep -qxF "$name"; then + echo "could not remove $name" >&2 + event Warning OrphanIdentityNotRemoved "Could not remove identity $name, left over from a deleted BucketAccess. See the logs of Job $JOB." + else + echo "removed $name" + event Normal OrphanIdentityRemoved "Removed identity $name, left over from a deleted BucketAccess." + fi +done diff --git a/packages/system/seaweedfs/templates/object-lock-actions-hook.yaml b/packages/system/seaweedfs/templates/object-lock-actions-hook.yaml new file mode 100644 index 000000000..a45825609 --- /dev/null +++ b/packages/system/seaweedfs/templates/object-lock-actions-hook.yaml @@ -0,0 +1,165 @@ +{{- /* Install also covers Flux reinstalling a release whose filer kept its identities. */}} +{{- if .Values.seaweedfs.cosi.enabled }} +{{- $name := printf "%s-object-lock-actions" .Release.Name | trunc 63 | trimSuffix "-" }} +{{- $env := .Values.global.seaweedfs.extraEnvironmentVars }} +{{- $security := .Values.global.seaweedfs.enableSecurity }} +{{- $fullname := include "seaweedfs.fullname" .Subcharts.seaweedfs }} +--- +apiVersion: v1 +kind: ConfigMap +metadata: + name: {{ $name }} + annotations: + helm.sh/hook: post-install,post-upgrade + helm.sh/hook-weight: "-1" + helm.sh/hook-delete-policy: before-hook-creation,hook-succeeded +data: + object-lock-actions.sh: | + {{- .Files.Get "files/object-lock-actions.sh" | nindent 4 }} +--- +apiVersion: v1 +kind: ServiceAccount +metadata: + name: {{ $name }} + annotations: + helm.sh/hook: post-install,post-upgrade + helm.sh/hook-weight: "-1" + helm.sh/hook-delete-policy: before-hook-creation,hook-succeeded +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: Role +metadata: + name: {{ $name }} + annotations: + helm.sh/hook: post-install,post-upgrade + helm.sh/hook-weight: "-1" + helm.sh/hook-delete-policy: before-hook-creation,hook-succeeded +rules: +- apiGroups: [""] + resources: ["events"] + verbs: ["create"] +- apiGroups: ["helm.toolkit.fluxcd.io"] + resources: ["helmreleases"] + resourceNames: [{{ .Release.Name | quote }}] + verbs: ["get"] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: RoleBinding +metadata: + name: {{ $name }} + annotations: + helm.sh/hook: post-install,post-upgrade + helm.sh/hook-weight: "-1" + helm.sh/hook-delete-policy: before-hook-creation,hook-succeeded +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: Role + name: {{ $name }} +subjects: +- kind: ServiceAccount + name: {{ $name }} + namespace: {{ .Release.Namespace | quote }} +--- +apiVersion: batch/v1 +kind: Job +metadata: + name: {{ $name }} + annotations: + helm.sh/hook: post-install,post-upgrade + helm.sh/hook-weight: "0" + helm.sh/hook-delete-policy: before-hook-creation +spec: + backoffLimit: 0 + template: + metadata: + labels: + policy.cozystack.io/allow-to-apiserver: "true" + spec: + serviceAccountName: {{ $name }} + restartPolicy: Never + securityContext: + runAsNonRoot: true + runAsUser: 65534 + seccompProfile: + type: RuntimeDefault + initContainers: + - name: weed + image: {{ include "seaweedfs.s3.image" .Subcharts.seaweedfs }} + command: ["cp", "/usr/bin/weed", "/opt/weed/weed"] + resources: + requests: + cpu: 10m + memory: 64Mi + limits: + memory: 256Mi + securityContext: + allowPrivilegeEscalation: false + capabilities: + drop: ["ALL"] + volumeMounts: + - name: weed + mountPath: /opt/weed + containers: + - name: grant + image: {{ .Values.seaweedfs.volume.resizeHook.image }} + command: ["/bin/sh", "/opt/script/object-lock-actions.sh"] + resources: + requests: + cpu: 10m + memory: 64Mi + limits: + memory: 256Mi + env: + - name: PATH + value: /opt/weed:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin + - name: MASTER + value: {{ $env.WEED_CLUSTER_SW_MASTER | quote }} + - name: FILER + value: {{ $env.WEED_CLUSTER_SW_FILER | quote }} + - name: RELEASE + value: {{ .Release.Name | quote }} + - name: JOB + value: {{ $name | quote }} + - name: NAMESPACE + valueFrom: + fieldRef: + fieldPath: metadata.namespace + securityContext: + allowPrivilegeEscalation: false + capabilities: + drop: ["ALL"] + volumeMounts: + - name: weed + mountPath: /opt/weed + - name: script + mountPath: /opt/script + {{- if $security }} + - name: security-config + mountPath: /etc/seaweedfs/security.toml + subPath: security.toml + readOnly: true + - name: ca-cert + mountPath: /usr/local/share/ca-certificates/ca/ + readOnly: true + - name: client-cert + mountPath: /usr/local/share/ca-certificates/client/ + readOnly: true + {{- end }} + volumes: + - name: weed + emptyDir: {} + - name: script + configMap: + name: {{ $name }} + {{- if $security }} + - name: security-config + configMap: + name: {{ $fullname }}-security-config + - name: ca-cert + secret: + secretName: {{ $fullname }}-ca-cert + - name: client-cert + secret: + secretName: {{ $fullname }}-client-cert + {{- end }} +{{- end }} diff --git a/packages/system/seaweedfs/templates/orphan-identities-hook.yaml b/packages/system/seaweedfs/templates/orphan-identities-hook.yaml new file mode 100644 index 000000000..1212d1064 --- /dev/null +++ b/packages/system/seaweedfs/templates/orphan-identities-hook.yaml @@ -0,0 +1,205 @@ +{{- /* Removes identity files left behind by deleted BucketAccesses; + files/orphan-identities.sh says why and how it decides. Runs on every + install and upgrade, before the Object Lock hook, so in delete mode a + left-over identity is gone before that hook grants it anything. Errors + the script handles do not fail the hook, and the Job stays behind for + its logs. A pod that never runs still fails the hook. */}} +{{- if .Values.seaweedfs.cosi.enabled }} +{{- $name := printf "%s-orphan-identities" .Release.Name | trunc 63 | trimSuffix "-" }} +{{- $clusterName := printf "%s-%s-orphan-identities" .Release.Namespace .Release.Name }} +{{- $env := .Values.global.seaweedfs.extraEnvironmentVars }} +{{- $security := .Values.global.seaweedfs.enableSecurity }} +{{- $fullname := include "seaweedfs.fullname" .Subcharts.seaweedfs }} +--- +apiVersion: v1 +kind: ConfigMap +metadata: + name: {{ $name }} + annotations: + helm.sh/hook: post-install,post-upgrade + helm.sh/hook-weight: "-2" + helm.sh/hook-delete-policy: before-hook-creation,hook-succeeded +data: + orphan-identities.sh: | + {{- .Files.Get "files/orphan-identities.sh" | nindent 4 }} +--- +apiVersion: v1 +kind: ServiceAccount +metadata: + name: {{ $name }} + annotations: + helm.sh/hook: post-install,post-upgrade + helm.sh/hook-weight: "-2" + helm.sh/hook-delete-policy: before-hook-creation,hook-succeeded +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: Role +metadata: + name: {{ $name }} + annotations: + helm.sh/hook: post-install,post-upgrade + helm.sh/hook-weight: "-2" + helm.sh/hook-delete-policy: before-hook-creation,hook-succeeded +rules: +- apiGroups: [""] + resources: ["events"] + verbs: ["create"] +- apiGroups: ["helm.toolkit.fluxcd.io"] + resources: ["helmreleases"] + resourceNames: [{{ .Release.Name | quote }}] + verbs: ["get"] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: RoleBinding +metadata: + name: {{ $name }} + annotations: + helm.sh/hook: post-install,post-upgrade + helm.sh/hook-weight: "-2" + helm.sh/hook-delete-policy: before-hook-creation,hook-succeeded +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: Role + name: {{ $name }} +subjects: +- kind: ServiceAccount + name: {{ $name }} + namespace: {{ .Release.Namespace | quote }} +{{- /* A tenant's SeaweedFS also serves its child tenants, whose BucketAccesses + live in their own namespaces. */}} +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRole +metadata: + name: {{ $clusterName }} + annotations: + helm.sh/hook: post-install,post-upgrade + helm.sh/hook-weight: "-2" + helm.sh/hook-delete-policy: before-hook-creation,hook-succeeded +rules: +- apiGroups: ["objectstorage.k8s.io"] + resources: ["bucketaccesses"] + verbs: ["list"] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRoleBinding +metadata: + name: {{ $clusterName }} + annotations: + helm.sh/hook: post-install,post-upgrade + helm.sh/hook-weight: "-2" + helm.sh/hook-delete-policy: before-hook-creation,hook-succeeded +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: ClusterRole + name: {{ $clusterName }} +subjects: +- kind: ServiceAccount + name: {{ $name }} + namespace: {{ .Release.Namespace | quote }} +--- +apiVersion: batch/v1 +kind: Job +metadata: + name: {{ $name }} + annotations: + helm.sh/hook: post-install,post-upgrade + helm.sh/hook-weight: "-1" + helm.sh/hook-delete-policy: before-hook-creation +spec: + backoffLimit: 0 + template: + metadata: + labels: + policy.cozystack.io/allow-to-apiserver: "true" + spec: + serviceAccountName: {{ $name }} + restartPolicy: Never + securityContext: + runAsNonRoot: true + runAsUser: 65534 + seccompProfile: + type: RuntimeDefault + initContainers: + - name: weed + image: {{ include "seaweedfs.s3.image" .Subcharts.seaweedfs }} + command: ["cp", "/usr/bin/weed", "/opt/weed/weed"] + resources: + requests: + cpu: 10m + memory: 64Mi + limits: + memory: 256Mi + securityContext: + allowPrivilegeEscalation: false + capabilities: + drop: ["ALL"] + volumeMounts: + - name: weed + mountPath: /opt/weed + containers: + - name: cleanup + image: {{ .Values.seaweedfs.volume.resizeHook.image }} + command: ["/bin/sh", "/opt/script/orphan-identities.sh"] + resources: + requests: + cpu: 10m + memory: 64Mi + limits: + memory: 256Mi + env: + - name: PATH + value: /opt/weed:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin + - name: MASTER + value: {{ $env.WEED_CLUSTER_SW_MASTER | quote }} + - name: FILER + value: {{ $env.WEED_CLUSTER_SW_FILER | quote }} + - name: RELEASE + value: {{ .Release.Name | quote }} + - name: JOB + value: {{ $name | quote }} + - name: MODE + value: {{ .Values.seaweedfs.cosi.orphanIdentities.mode | quote }} + - name: NAMESPACE + valueFrom: + fieldRef: + fieldPath: metadata.namespace + securityContext: + allowPrivilegeEscalation: false + capabilities: + drop: ["ALL"] + volumeMounts: + - name: weed + mountPath: /opt/weed + - name: script + mountPath: /opt/script + {{- if $security }} + - name: security-config + mountPath: /etc/seaweedfs/security.toml + subPath: security.toml + readOnly: true + - name: ca-cert + mountPath: /usr/local/share/ca-certificates/ca/ + readOnly: true + - name: client-cert + mountPath: /usr/local/share/ca-certificates/client/ + readOnly: true + {{- end }} + volumes: + - name: weed + emptyDir: {} + - name: script + configMap: + name: {{ $name }} + {{- if $security }} + - name: security-config + configMap: + name: {{ $fullname }}-security-config + - name: ca-cert + secret: + secretName: {{ $fullname }}-ca-cert + - name: client-cert + secret: + secretName: {{ $fullname }}-client-cert + {{- end }} +{{- end }} diff --git a/packages/system/seaweedfs/tests/cosi_image_test.yaml b/packages/system/seaweedfs/tests/cosi_image_test.yaml index 7840d200d..d43aa176e 100644 --- a/packages/system/seaweedfs/tests/cosi_image_test.yaml +++ b/packages/system/seaweedfs/tests/cosi_image_test.yaml @@ -7,7 +7,7 @@ suite: seaweedfs COSI driver image pin # BucketAccess and ignores the accessPolicy parameter. The chart ships a # -readonly BucketAccessClass with parameters.accessPolicy: readonly, so on # v0.1.2 a credential meant to be read-only is silently granted read-write. -# The package values.yaml overrides cosi.image to v0.3.1, which honours +# The package values.yaml overrides cosi.image to v0.4.0, which honours # accessPolicy: readonly. # # This test does not set the image itself; it relies on the package values.yaml @@ -25,7 +25,7 @@ release: namespace: cozy-seaweedfs tests: - - it: pins the cosi-driver container to v0.3.1 (read-only access enforcement) + - it: pins the cosi-driver container to v0.4.0 (read-only access enforcement) template: charts/seaweedfs/templates/cosi/cosi-deployment.yaml set: seaweedfs.cosi.enabled: true @@ -35,4 +35,4 @@ tests: value: seaweedfs-cosi-driver - equal: path: spec.template.spec.containers[0].image - value: ghcr.io/seaweedfs/seaweedfs-cosi-driver:v0.3.1 + value: ghcr.io/seaweedfs/seaweedfs-cosi-driver:v0.4.0 diff --git a/packages/system/seaweedfs/tests/object_lock_actions_hook_test.yaml b/packages/system/seaweedfs/tests/object_lock_actions_hook_test.yaml new file mode 100644 index 000000000..b98bb950a --- /dev/null +++ b/packages/system/seaweedfs/tests/object_lock_actions_hook_test.yaml @@ -0,0 +1,167 @@ +suite: seaweedfs Object Lock actions hook + +templates: + - templates/object-lock-actions-hook.yaml + +release: + name: seaweedfs-system + namespace: tenant-foo + +tests: + - it: renders nothing without COSI + set: + seaweedfs.cosi.enabled: false + asserts: + - hasDocuments: + count: 0 + + - it: every object is a hook on both install and upgrade + asserts: + - hasDocuments: + count: 5 + - equal: + path: metadata.annotations["helm.sh/hook"] + value: post-install,post-upgrade + + - it: the Job outlives a run so its logs stay readable + documentSelector: + path: kind + value: Job + asserts: + - equal: + path: metadata.annotations["helm.sh/hook-delete-policy"] + value: before-hook-creation + - equal: + path: metadata.annotations["helm.sh/hook-weight"] + value: "0" + + - it: everything the Job uses is created before it + documentSelector: + path: kind + value: ConfigMap + asserts: + - equal: + path: metadata.annotations["helm.sh/hook-weight"] + value: "-1" + + - it: the weed binary comes from the image the s3 gateway runs + documentSelector: + path: kind + value: Job + set: + seaweedfs.image.repository: registry.example.test/seaweedfs + seaweedfs.image.tag: "9.99" + asserts: + - equal: + path: spec.template.spec.initContainers[0].image + value: registry.example.test/seaweedfs:9.99 + + - it: the grant container runs the package's kubectl image + documentSelector: + path: kind + value: Job + set: + seaweedfs.volume.resizeHook.image: registry.example.test/k8s:9.99 + asserts: + - equal: + path: spec.template.spec.containers[0].image + value: registry.example.test/k8s:9.99 + + - it: ships the script and points it at the cluster + documentSelector: + path: kind + value: Job + asserts: + - equal: + path: spec.template.spec.containers[0].command + value: ["/bin/sh", "/opt/script/object-lock-actions.sh"] + - contains: + path: spec.template.spec.containers[0].env + content: + name: MASTER + value: seaweedfs-master:9333 + - contains: + path: spec.template.spec.containers[0].env + content: + name: FILER + value: seaweedfs-filer-client:8888 + - contains: + path: spec.template.spec.containers[0].env + content: + name: RELEASE + value: seaweedfs-system + + - it: both containers set a memory limit so a namespace default cannot pick one + documentSelector: + path: kind + value: Job + asserts: + - equal: + path: spec.template.spec.initContainers[0].resources.limits.memory + value: 256Mi + - equal: + path: spec.template.spec.containers[0].resources.limits.memory + value: 256Mi + + - it: the script in the ConfigMap is the file under test + documentSelector: + path: kind + value: ConfigMap + asserts: + - matchRegex: + path: data["object-lock-actions.sh"] + pattern: 'safe_commands\(\)' + + - it: mounts the gRPC client credentials when security is on + documentSelector: + path: kind + value: Job + asserts: + - contains: + path: spec.template.spec.volumes + content: + name: client-cert + secret: + secretName: seaweedfs-client-cert + - contains: + path: spec.template.spec.volumes + content: + name: ca-cert + secret: + secretName: seaweedfs-ca-cert + - contains: + path: spec.template.spec.volumes + content: + name: security-config + configMap: + name: seaweedfs-security-config + + - it: mounts no credentials when security is off + documentSelector: + path: kind + value: Job + set: + global.seaweedfs.enableSecurity: false + asserts: + - lengthEqual: + path: spec.template.spec.volumes + count: 2 + - lengthEqual: + path: spec.template.spec.containers[0].volumeMounts + count: 2 + + - it: the Job name fits a label value for the longest release name + release: + name: a-tenant-seaweedfs-instance-with-a-long-name-xx-syste + documentSelector: + path: kind + value: Job + asserts: + - matchRegex: + path: metadata.name + pattern: ^.{1,63}$ + - contains: + path: spec.template.spec.containers[0].env + content: + name: JOB + value: a-tenant-seaweedfs-instance-with-a-long-name-xx-syste-object-lo diff --git a/packages/system/seaweedfs/tests/orphan_identities_hook_test.yaml b/packages/system/seaweedfs/tests/orphan_identities_hook_test.yaml new file mode 100644 index 000000000..3e1932c83 --- /dev/null +++ b/packages/system/seaweedfs/tests/orphan_identities_hook_test.yaml @@ -0,0 +1,145 @@ +suite: seaweedfs orphan identities hook + +templates: + - templates/orphan-identities-hook.yaml + +release: + name: seaweedfs-system + namespace: tenant-foo + +tests: + - it: renders nothing without COSI + set: + seaweedfs.cosi.enabled: false + asserts: + - hasDocuments: + count: 0 + + - it: every object is a hook on both install and upgrade + asserts: + - hasDocuments: + count: 7 + - equal: + path: metadata.annotations["helm.sh/hook"] + value: post-install,post-upgrade + + - it: only reports unless the chart is told to delete + documentSelector: + path: kind + value: Job + asserts: + - contains: + path: spec.template.spec.containers[0].env + content: + name: MODE + value: report + + - it: passes delete through when set + documentSelector: + path: kind + value: Job + set: + seaweedfs.cosi.orphanIdentities.mode: delete + asserts: + - contains: + path: spec.template.spec.containers[0].env + content: + name: MODE + value: delete + + - it: can list BucketAccesses in every namespace and nothing else cluster-wide + documentSelector: + path: kind + value: ClusterRole + asserts: + - equal: + path: rules + value: + - apiGroups: ["objectstorage.k8s.io"] + resources: ["bucketaccesses"] + verbs: ["list"] + + - it: names its cluster-scoped objects after the namespace so tenants do not share them + release: + name: seaweedfs-system + namespace: tenant-bar + documentSelector: + path: kind + value: ClusterRoleBinding + asserts: + - equal: + path: metadata.name + value: tenant-bar-seaweedfs-system-orphan-identities + - equal: + path: roleRef.name + value: tenant-bar-seaweedfs-system-orphan-identities + - contains: + path: subjects + content: + kind: ServiceAccount + name: seaweedfs-system-orphan-identities + namespace: tenant-bar + + - it: the Job outlives a run so its logs stay readable + documentSelector: + path: kind + value: Job + asserts: + - equal: + path: metadata.annotations["helm.sh/hook-delete-policy"] + value: before-hook-creation + - equal: + path: metadata.annotations["helm.sh/hook-weight"] + value: "-1" + + - it: the Job runs under a restrictive non-root securityContext + documentSelector: + path: kind + value: Job + asserts: + - equal: + path: spec.template.spec.securityContext.runAsNonRoot + value: true + - equal: + path: spec.template.spec.containers[0].securityContext.allowPrivilegeEscalation + value: false + + - it: ships the script and points it at the cluster + documentSelector: + path: kind + value: Job + asserts: + - equal: + path: spec.template.spec.containers[0].command + value: ["/bin/sh", "/opt/script/orphan-identities.sh"] + - contains: + path: spec.template.spec.containers[0].env + content: + name: MASTER + value: seaweedfs-master:9333 + - contains: + path: spec.template.spec.containers[0].env + content: + name: FILER + value: seaweedfs-filer-client:8888 + + - it: the script in the ConfigMap is the file under test + documentSelector: + path: kind + value: ConfigMap + asserts: + - matchRegex: + path: data["orphan-identities.sh"] + pattern: 'OrphanIdentityRemoved' + + - it: mounts the gRPC client credentials when security is on + documentSelector: + path: kind + value: Job + asserts: + - contains: + path: spec.template.spec.volumes + content: + name: client-cert + secret: + secretName: seaweedfs-client-cert diff --git a/packages/system/seaweedfs/values.yaml b/packages/system/seaweedfs/values.yaml index 7a3a16835..a33b57f2a 100644 --- a/packages/system/seaweedfs/values.yaml +++ b/packages/system/seaweedfs/values.yaml @@ -252,12 +252,21 @@ seaweedfs: # S3 actions for every BucketAccess and ignores the accessPolicy parameter. # v0.3.x honours accessPolicy: readonly, so a -readonly BucketAccessClass # actually issues read-only (Read,List) credentials instead of read-write. - image: "ghcr.io/seaweedfs/seaweedfs-cosi-driver:v0.3.1" + # v0.4.0 also writes each grant to the per-identity IAM file: v0.3.1 + # rewrites only the legacy identity.json, which the S3 gateways migrate + # concurrently, so a grant could be lost for good. + image: "ghcr.io/seaweedfs/seaweedfs-cosi-driver:v0.4.0" podLabels: policy.cozystack.io/allow-to-apiserver: "true" driverName: "seaweedfs.objectstorage.k8s.io" bucketClassName: "seaweedfs" region: "" + # What the post-install/post-upgrade hook does with identity files no BucketAccess + # carries (files/orphan-identities.sh): "delete" removes them, anything + # else only reports them. extra/seaweedfs sets it from its + # cosi.orphanIdentities value. + orphanIdentities: + mode: report sidecar: image: "ghcr.io/cozystack/cozystack/objectstorage-sidecar:v1.6.5@sha256:6d832ba3537a5395d230cc2a0db86b874170f6cd05a231bb4b6fb78b0eadf429" certificates: diff --git a/packages/system/vertical-pod-autoscaler/tests/vpa_test.yaml b/packages/system/vertical-pod-autoscaler/tests/vpa_test.yaml index ea8c23417..e6fe988bb 100644 --- a/packages/system/vertical-pod-autoscaler/tests/vpa_test.yaml +++ b/packages/system/vertical-pod-autoscaler/tests/vpa_test.yaml @@ -233,3 +233,38 @@ tests: count: 0 + + - it: runs two admission controllers spread over nodes + template: charts/vertical-pod-autoscaler/templates/admission-controller/deployment.yaml + asserts: + - equal: + path: spec.replicas + value: 2 + - equal: + path: spec.template.spec.topologySpreadConstraints[0].topologyKey + value: kubernetes.io/hostname + - equal: + path: spec.template.spec.topologySpreadConstraints[0].maxSkew + value: 1 + - equal: + path: spec.template.spec.topologySpreadConstraints[0].whenUnsatisfiable + value: ScheduleAnyway + - equal: + path: spec.template.spec.topologySpreadConstraints[0].labelSelector.matchLabels + value: + app.kubernetes.io/name: vertical-pod-autoscaler + app.kubernetes.io/instance: vpa + app.kubernetes.io/component: admission-controller + + - it: keeps one admission controller up through a voluntary disruption + template: charts/vertical-pod-autoscaler/templates/admission-controller/pdb.yaml + asserts: + - equal: + path: spec.minAvailable + value: 1 + - equal: + path: spec.selector.matchLabels + value: + app.kubernetes.io/name: vertical-pod-autoscaler + app.kubernetes.io/instance: vpa + app.kubernetes.io/component: admission-controller diff --git a/packages/system/vertical-pod-autoscaler/values.yaml b/packages/system/vertical-pod-autoscaler/values.yaml index 46678903e..619a2ce09 100644 --- a/packages/system/vertical-pod-autoscaler/values.yaml +++ b/packages/system/vertical-pod-autoscaler/values.yaml @@ -37,6 +37,29 @@ vertical-pod-autoscaler: prometheus-cadvisor-job-name: cadvisor admissionController: + replicaCount: 2 + pdb: + create: true + topologySpreadConstraints: + - maxSkew: 1 + topologyKey: kubernetes.io/hostname + whenUnsatisfiable: ScheduleAnyway + labelSelector: + matchLabels: + app.kubernetes.io/name: vertical-pod-autoscaler + app.kubernetes.io/instance: "{{ .Release.Name }}" + app.kubernetes.io/component: admission-controller + extraArgs: + # The admission controller registers its mutating webhook for Pod CREATE in every + # namespace with failurePolicy Ignore and, by default, a 30s timeout. Ignore only + # applies after the timeout: when its pod is down and the Service IP blackholes (e.g. a + # cold start after a full cluster shutdown, before the CNI is back), the API server + # still waits the full 30s. The Pod CREATE webhooks are called one after another within + # one request, so their waits add up; past the request's deadline the creation fails + # with "context deadline exceeded", including for the CNI's own DaemonSet pods (#3125). + # A mutation takes milliseconds; 5s keeps slow responses working and keeps the total + # wait well inside the deadline. + webhook-timeout-seconds: 5 resources: limits: memory: 256Mi diff --git a/packages/tests/cozy-lib-tests/tests/quota_test.yaml b/packages/tests/cozy-lib-tests/tests/quota_test.yaml index 0ba2260c4..0604ca5ee 100644 --- a/packages/tests/cozy-lib-tests/tests/quota_test.yaml +++ b/packages/tests/cozy-lib-tests/tests/quota_test.yaml @@ -48,3 +48,32 @@ tests: - notExists: path: spec.hard["requests.services.loadbalancers"] + + - it: renders hugepages only as requests + set: + quota: + hugepages-2Mi: "4Gi" + hugepages-1Gi: "2Gi" + _cluster: {} + _namespace: {} + + release: + name: myrelease + namespace: default + revision: 1 + isUpgrade: false + + asserts: + - equal: + path: spec.hard["requests.hugepages-2Mi"] + value: "4Gi" + + - equal: + path: spec.hard["requests.hugepages-1Gi"] + value: "2Gi" + + - notExists: + path: spec.hard["limits.hugepages-2Mi"] + + - notExists: + path: spec.hard["limits.hugepages-1Gi"] diff --git a/pkg/apis/sdn/DESIGN.md b/pkg/apis/sdn/DESIGN.md index 857afc494..d30736017 100644 --- a/pkg/apis/sdn/DESIGN.md +++ b/pkg/apis/sdn/DESIGN.md @@ -170,4 +170,4 @@ The aggregated-API + controller model is intentionally minimal. The following ca - **Cluster-scope** SecurityGroups projecting to CiliumClusterwideNetworkPolicy. - Reusable **CIDR/FQDN groups**, and exposing more of the CiliumNetworkPolicy rule surface (ICMP, `toServices`, CIDR-set exceptions) as demand appears. - An optional **existence/authorization check** on attachments and SG peers (SubjectAccessReview) to fail fast on a typo instead of silently matching zero pods. -- **Richer spec validation.** Create and update already validate the highest-risk fields synchronously — CIDR syntax, port range, the protocol enum, attachment/peer label validity, reserved-entity names — and reject a bad value with `Invalid` instead of writing a policy Cilium would silently discard. Still deferred: FQDN `matchName`/`matchPattern` syntax and cross-rule consistency, which pass through to Cilium. +- **Richer spec validation.** Create and update already validate the highest-risk fields synchronously — CIDR syntax, port number bounds (a `first-last` port range is rejected, since a port entry carries a single port and Cilium's `endPort` is not exposed), the protocol enum, attachment/peer label validity, reserved-entity names, and FQDN selectors against the CiliumNetworkPolicy CRD's own rules (exactly one of `matchName`/`matchPattern`, the CRD's patterns, at most 255 characters) — and reject a bad value with a field error on the SecurityGroup path instead of writing a policy that Cilium would silently discard or that the CiliumNetworkPolicy schema would refuse on the backing write. Still deferred: cross-rule consistency, which passes through to Cilium. diff --git a/pkg/lineage/capk_test.go b/pkg/lineage/capk_test.go new file mode 100644 index 000000000..0c17300d2 --- /dev/null +++ b/pkg/lineage/capk_test.go @@ -0,0 +1,129 @@ +package lineage + +import ( + "context" + "testing" + + helmv2 "github.com/fluxcd/helm-controller/api/v2" + "k8s.io/apimachinery/pkg/api/meta" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/runtime/schema" + dynamicfake "k8s.io/client-go/dynamic/fake" +) + +const capkNamespace = "tenant-demo" + +// kubernetesAppMapper maps the cluster's HelmRelease to its Kubernetes +// application, as the webhook's ApplicationDefinition mapper does. +type kubernetesAppMapper struct{} + +func (kubernetesAppMapper) Map(*helmv2.HelmRelease) (string, string, string, error) { + return "apps.cozystack.io/v1alpha1", "Kubernetes", "kubernetes-", nil +} + +func capkObject(apiVersion, kind, name string, labels map[string]string, owner *unstructured.Unstructured) *unstructured.Unstructured { + o := &unstructured.Unstructured{} + o.SetAPIVersion(apiVersion) + o.SetKind(kind) + o.SetNamespace(capkNamespace) + o.SetName(name) + o.SetLabels(labels) + if owner != nil { + o.SetOwnerReferences([]metav1.OwnerReference{{APIVersion: owner.GetAPIVersion(), Kind: owner.GetKind(), Name: owner.GetName()}}) + } + return o +} + +// capkNodeChain builds the objects behind the virt-launcher pod of a +// Kubernetes worker node, as observed on a live cluster: the pod is owned by +// its VMI and the VMI by its VM, but CAPK leaves the VM without an +// ownerReference and points at its KubevirtMachine through labels only. From +// the KubevirtMachine up, ownerReferences run to the CAPI Cluster, which the +// cluster's HelmRelease labels. +func capkNodeChain(vmLabels map[string]string) (*unstructured.Unstructured, []runtime.Object, meta.RESTMapper) { + app := capkObject("apps.cozystack.io/v1alpha1", "Kubernetes", "cluster-a", nil, nil) + hr := capkObject(HRAPIVersion, HRKind, "kubernetes-cluster-a", nil, nil) + cluster := capkObject("cluster.x-k8s.io/v1beta1", "Cluster", "kubernetes-cluster-a", map[string]string{HRLabel: "kubernetes-cluster-a"}, nil) + md := capkObject("cluster.x-k8s.io/v1beta1", "MachineDeployment", "kubernetes-cluster-a-md0", nil, cluster) + ms := capkObject("cluster.x-k8s.io/v1beta1", "MachineSet", "kubernetes-cluster-a-md0-x", nil, md) + machine := capkObject("cluster.x-k8s.io/v1beta1", "Machine", "kubernetes-cluster-a-md0-x-y", nil, ms) + kvm := capkObject(KubevirtMachineAPIVersion, KubevirtMachineKind, "kubernetes-cluster-a-md0-x-y", nil, machine) + vm := capkObject(VMAPIVersion, VMKind, "kubernetes-cluster-a-md0-x-y", vmLabels, nil) + vmi := capkObject("kubevirt.io/v1", "VirtualMachineInstance", "kubernetes-cluster-a-md0-x-y", nil, vm) + pod := capkObject("v1", "Pod", "virt-launcher-kubernetes-cluster-a-md0-x-y-abcde", nil, vmi) + + objs := []runtime.Object{app, hr, cluster, md, ms, machine, kvm, vm, vmi} + mapper := meta.NewDefaultRESTMapper(nil) + for _, o := range objs { + mapper.Add(o.GetObjectKind().GroupVersionKind(), meta.RESTScopeNamespace) + } + mapper.Add(schema.GroupVersionKind{Version: "v1", Kind: "Pod"}, meta.RESTScopeNamespace) + return pod, objs, mapper +} + +func walkNodePod(t *testing.T, vmLabels map[string]string) []ObjectID { + t.Helper() + pod, objs, mapper := capkNodeChain(vmLabels) + dyn := dynamicfake.NewSimpleDynamicClient(runtime.NewScheme(), objs...) + return WalkOwnershipGraph(context.Background(), dyn, mapper, kubernetesAppMapper{}, pod) +} + +func TestWalkResolvesCAPKNodeVMToKubernetesApp(t *testing.T) { + got := walkNodePod(t, map[string]string{ + KubevirtMachineNameLabel: "kubernetes-cluster-a-md0-x-y", + KubevirtMachineNamespaceLabel: capkNamespace, + }) + want := ObjectID{APIVersion: "apps.cozystack.io/v1alpha1", Kind: "Kubernetes", Namespace: capkNamespace, Name: "cluster-a"} + if len(got) != 1 || got[0] != want { + t.Fatalf("WalkOwnershipGraph(node pod) = %+v, want [%+v]", got, want) + } +} + +func TestWalkFollowsCAPKLabelsOnlyFromKubeVirtVMs(t *testing.T) { + // The CAPK labels name a valid KubevirtMachine in the same namespace in + // every case: only the kind and API group of the labelled object differ, so + // each case fails solely on the guard that restricts the bridge to + // kubevirt.io/v1 VirtualMachines. + capkLabels := map[string]string{ + KubevirtMachineNameLabel: "kubernetes-cluster-a-md0-x-y", + KubevirtMachineNamespaceLabel: capkNamespace, + } + for _, tc := range []struct { + name, apiVersion, kind string + }{ + {name: "other kind in the kubevirt.io group", apiVersion: VMAPIVersion, kind: "Cluster"}, + {name: "VirtualMachineInstance", apiVersion: VMAPIVersion, kind: "VirtualMachineInstance"}, + {name: "VirtualMachine of another group", apiVersion: "example.com/v1", kind: VMKind}, + {name: "VirtualMachine of another kubevirt.io version", apiVersion: "kubevirt.io/v1alpha3", kind: VMKind}, + } { + t.Run(tc.name, func(t *testing.T) { + _, objs, mapper := capkNodeChain(nil) + impostor := capkObject(tc.apiVersion, tc.kind, "impostor", capkLabels, nil) + dyn := dynamicfake.NewSimpleDynamicClient(runtime.NewScheme(), objs...) + if got := WalkOwnershipGraph(context.Background(), dyn, mapper, kubernetesAppMapper{}, impostor); len(got) != 0 { + t.Fatalf("WalkOwnershipGraph(%s %s) = %+v, want no ancestors", tc.apiVersion, tc.kind, got) + } + }) + } +} + +func TestWalkIgnoresKubevirtMachineOfAnotherNamespace(t *testing.T) { + // A VM pointing at a KubevirtMachine outside its own namespace (an external + // infrastructure cluster, or a forged label) must not be resolved through it. + got := walkNodePod(t, map[string]string{ + KubevirtMachineNameLabel: "kubernetes-cluster-a-md0-x-y", + KubevirtMachineNamespaceLabel: "tenant-other", + }) + if len(got) != 0 { + t.Fatalf("WalkOwnershipGraph(node pod) = %+v, want no ancestors", got) + } +} + +func TestWalkStopsAtUnlabelledVM(t *testing.T) { + // A standalone VM with no CAPK labels and no ownerReference has no ancestors. + if got := walkNodePod(t, nil); len(got) != 0 { + t.Fatalf("WalkOwnershipGraph(pod of standalone VM) = %+v, want no ancestors", got) + } +} diff --git a/pkg/lineage/lineage.go b/pkg/lineage/lineage.go index 94be77b75..918782769 100644 --- a/pkg/lineage/lineage.go +++ b/pkg/lineage/lineage.go @@ -20,6 +20,16 @@ const ( HRAPIVersion = "helm.toolkit.fluxcd.io/v2" HRKind = "HelmRelease" HRLabel = "helm.toolkit.fluxcd.io/name" + + // KubeVirt VirtualMachines created by the Cluster API KubeVirt provider + // (CAPK) for cluster nodes carry no ownerReference: CAPK links them to + // their KubevirtMachine through these labels only. + VMAPIVersion = "kubevirt.io/v1" + VMKind = "VirtualMachine" + KubevirtMachineAPIVersion = "infrastructure.cluster.x-k8s.io/v1alpha1" + KubevirtMachineKind = "KubevirtMachine" + KubevirtMachineNameLabel = "capk.cluster.x-k8s.io/kubevirt-machine-name" + KubevirtMachineNamespaceLabel = "capk.cluster.x-k8s.io/kubevirt-machine-namespace" ) // AppMapper maps HelmRelease to application metadata. @@ -103,6 +113,18 @@ func WalkOwnershipGraph( return } + // A node VM of a Kubernetes cluster has no ownerReference, so without this + // step the walk would stop at it and never reach the cluster's application. + if name, ok := kubevirtMachineName(obj); ok { + ownerObj, err := getUnstructuredObject(ctx, client, mapper, KubevirtMachineAPIVersion, KubevirtMachineKind, obj.GetNamespace(), name) + if err != nil { + fmt.Fprintf(os.Stderr, "Could not fetch KubevirtMachine %s/%s of VirtualMachine %s: %v\n", obj.GetNamespace(), name, obj.GetName(), err) + return + } + out = append(out, WalkOwnershipGraph(ctx, client, mapper, appMapper, ownerObj, visited)...) + return + } + // I want "if err1 != nil go to next block, if err2 != nil, go to next block, etc semantics", // like an early return from a function, but if all checks succeed, I don't want to do the rest // of the function, so it's a `for { if err { break } if othererr { break } if allgood { return } @@ -150,6 +172,22 @@ func WalkOwnershipGraph( return } +// kubevirtMachineName returns the KubevirtMachine a CAPK-created +// VirtualMachine belongs to. It only follows a KubevirtMachine in the VM's own +// namespace: CAPK can also run against an external infrastructure cluster, +// where the KubevirtMachine lives elsewhere and is not ours to resolve. +func kubevirtMachineName(obj *unstructured.Unstructured) (string, bool) { + if obj.GetAPIVersion() != VMAPIVersion || obj.GetKind() != VMKind { + return "", false + } + labels := obj.GetLabels() + name := labels[KubevirtMachineNameLabel] + if name == "" || labels[KubevirtMachineNamespaceLabel] != obj.GetNamespace() { + return "", false + } + return name, true +} + func getUnstructuredObject( ctx context.Context, client dynamic.Interface, diff --git a/pkg/registry/apps/application/memory_floor.go b/pkg/registry/apps/application/memory_floor.go new file mode 100644 index 000000000..32cd3ad2a --- /dev/null +++ b/pkg/registry/apps/application/memory_floor.go @@ -0,0 +1,99 @@ +/* +Copyright 2024 The Cozystack Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package application + +import ( + "bytes" + "encoding/json" + "fmt" + "reflect" + + apiextv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" + structuralschema "k8s.io/apiextensions-apiserver/pkg/apiserver/schema" + apierrors "k8s.io/apimachinery/pkg/api/errors" + "k8s.io/apimachinery/pkg/api/resource" + "k8s.io/apimachinery/pkg/util/validation/field" + + appsv1alpha1 "github.com/cozystack/cozystack/pkg/apis/apps/v1alpha1" +) + +var minimumWorkloadMemory = resource.MustParse("1Mi") + +func workloadValues(values *apiextv1.JSON) (map[string]any, error) { + if values == nil || len(values.Raw) == 0 { + return nil, nil + } + var result map[string]any + decoder := json.NewDecoder(bytes.NewReader(values.Raw)) + decoder.UseNumber() + err := decoder.Decode(&result) + return result, err +} + +func (r *REST) validateWorkloadMemory(app *appsv1alpha1.Application, previous *apiextv1.JSON) error { + if r.specSchema == nil || app.Spec == nil { + return nil + } + values, err := workloadValues(app.Spec) + if err != nil { + return apierrors.NewBadRequest("invalid application spec") + } + old, err := workloadValues(previous) + if err != nil { + return apierrors.NewInternalError(fmt.Errorf("cannot decode stored application spec")) + } + if errs := changedWorkloadMemory(values, old, r.specSchema, field.NewPath("spec")); len(errs) > 0 { + return apierrors.NewInvalid(r.gvk.GroupKind(), app.Name, errs) + } + return nil +} + +// Only walk declared object fields. Arbitrary chart settings and tenant resourceQuotas +// can also contain keys named "memory", with different semantics. +func changedWorkloadMemory(values, old map[string]any, schema *structuralschema.Structural, path *field.Path) field.ErrorList { + var errs field.ErrorList + for _, key := range sortedKeys(values) { + child, declared := schema.Properties[key] + current, ok := values[key].(map[string]any) + if !declared || !ok { + continue + } + previous, _ := old[key].(map[string]any) + where := path.Child(key) + _, preset := schema.Properties["resourcesPreset"] + if key == "resources" && preset && child.Properties["memory"].XIntOrString && child.Properties["cpu"].XIntOrString { + memory := current["memory"] + if memory == nil || reflect.DeepEqual(memory, previous["memory"]) { + continue + } + q, err := resource.ParseQuantity(fmt.Sprint(memory)) + if err != nil { + errs = append(errs, field.Invalid(where.Child("memory"), memory, "expected a Kubernetes quantity")) + continue + } + if q.Cmp(minimumWorkloadMemory) < 0 { + prior, err := resource.ParseQuantity(fmt.Sprint(previous["memory"])) + if err != nil || prior.Cmp(q) != 0 { + errs = append(errs, field.Invalid(where.Child("memory"), memory, "must be at least 1Mi; use a unit such as 512Mi or 8Gi")) + } + } + continue + } + errs = append(errs, changedWorkloadMemory(current, previous, &child, where)...) + } + return errs +} diff --git a/pkg/registry/apps/application/memory_floor_test.go b/pkg/registry/apps/application/memory_floor_test.go new file mode 100644 index 000000000..413afd102 --- /dev/null +++ b/pkg/registry/apps/application/memory_floor_test.go @@ -0,0 +1,176 @@ +/* +Copyright 2024 The Cozystack Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package application + +import ( + "context" + "errors" + "testing" + + appsv1alpha1 "github.com/cozystack/cozystack/pkg/apis/apps/v1alpha1" + helmv2 "github.com/fluxcd/helm-controller/api/v2" + apiextv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime/schema" + "k8s.io/apiserver/pkg/endpoints/request" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/client/interceptor" +) + +func TestWorkloadMemoryAdmission(t *testing.T) { + for _, tc := range []struct { + name, chart, old, next string + upsert, reject bool + }{ + {"new bare bytes", "tcp-balancer", "", `{"resources":{"memory":8}}`, false, true}, + {"upsert respects floor", "tcp-balancer", "", `{"resources":{"memory":"8"}}`, true, true}, + {"new zero", "tcp-balancer", "", `{"resources":{"memory":0}}`, false, true}, + {"minimum", "tcp-balancer", "", `{"resources":{"memory":"1Mi"}}`, false, false}, + {"bytes above minimum", "tcp-balancer", "", `{"resources":{"memory":1048576}}`, false, false}, + {"unchanged scaled to zero", "tcp-balancer", `{"resources":{"memory":8},"replicas":0}`, `{"resources":{"memory":8},"replicas":0,"other":true}`, false, false}, + {"same quantity spelling", "tcp-balancer", `{"resources":{"memory":8}}`, `{"resources":{"memory":"8"}}`, false, false}, + {"changed zero", "tcp-balancer", `{"resources":{"memory":8}}`, `{"resources":{"memory":0}}`, false, true}, + {"repaired", "tcp-balancer", `{"resources":{"memory":8}}`, `{"resources":{"memory":"8Gi"}}`, false, false}, + {"back to preset", "tcp-balancer", `{"resources":{"memory":8}}`, `{"resourcesPreset":"t1.nano"}`, false, false}, + {"nested component", "kubernetes", "", `{"controlPlane":{"apiServer":{"resources":{"memory":"1023Ki"}}}}`, false, true}, + {"quota zero", "tenant", "", `{"resourceQuotas":{"memory":0}}`, false, false}, + {"free form config", "nats", "", `{"config":{"merge":{"resourcesPreset":"example","resources":{"memory":8}}}}`, false, false}, + } { + t.Run(tc.name, func(t *testing.T) { + app := &appsv1alpha1.Application{ + TypeMeta: metav1.TypeMeta{Kind: kubernetesKind, APIVersion: "apps.cozystack.io/v1alpha1"}, + ObjectMeta: metav1.ObjectMeta{Name: "good-name", Namespace: "tenant-foo"}, + } + app.Spec = &apiextv1.JSON{Raw: []byte(tc.next)} + var stored []client.Object + if tc.old != "" { + stored = []client.Object{&helmv2.HelmRelease{ObjectMeta: metav1.ObjectMeta{Name: "kubernetes-" + app.Name, Namespace: app.Namespace, Labels: map[string]string{ + ApplicationKindLabel: kubernetesKind, ApplicationGroupLabel: appsv1alpha1.GroupName, ApplicationNameLabel: app.Name, + }}, Spec: helmv2.HelmReleaseSpec{Values: &apiextv1.JSON{Raw: []byte(tc.old)}}}} + } + r := newKubernetesWarnREST(t, stored...) + r.specSchema = chartSpecSchema(t, tc.chart) + ctx := request.WithNamespace(context.Background(), app.Namespace) + var err error + if tc.old != "" || tc.upsert { + _, _, err = r.Update(ctx, app.Name, newDefaultUpdatedObjectInfo(app), nil, nil, tc.upsert, &metav1.UpdateOptions{}) + } else { + _, err = r.Create(ctx, app, nil, &metav1.CreateOptions{}) + } + if tc.reject && !apierrors.IsInvalid(err) || !tc.reject && err != nil { + t.Fatalf("reject=%v, got %v", tc.reject, err) + } + if tc.reject { + list := &helmv2.HelmReleaseList{} + if err := r.c.List(ctx, list); err != nil { + t.Fatal(err) + } + if len(list.Items) != len(stored) || len(stored) > 0 && string(list.Items[0].Spec.Values.Raw) != tc.old { + t.Fatal("a rejected request changed storage") + } + } + }) + } +} + +// A caller that read the app before another writer fixed its memory still +// carries the old value. It must not put that value back, whether the fix lands +// before Update reads the live release or between that read and the write. +func TestWorkloadMemoryRecheckedAgainstLiveRelease(t *testing.T) { + const stale, fixed = `{"resources":{"memory":8}}`, `{"resources":{"memory":"512Mi"}}` + conflict := func(name string) error { + return apierrors.NewConflict(schema.GroupResource{Group: "helm.toolkit.fluxcd.io", Resource: "helmreleases"}, name, errors.New("simulated concurrent write")) + } + setValues := func(ctx context.Context, c client.WithWatch, key client.ObjectKey, values string) error { + live := &helmv2.HelmRelease{} + if err := c.Get(ctx, key, live); err != nil { + return err + } + live.Spec.Values = &apiextv1.JSON{Raw: []byte(values)} + return c.Update(ctx, live) + } + for _, tc := range []struct { + name, next, want string + reject bool + funcs func() interceptor.Funcs + }{ + {"fixed after the first read", `{"resources":{"memory":8},"other":true}`, fixed, true, func() interceptor.Funcs { + gets := 0 + return interceptor.Funcs{Get: func(ctx context.Context, c client.WithWatch, key client.ObjectKey, obj client.Object, opts ...client.GetOption) error { + err := c.Get(ctx, key, obj, opts...) + if _, ok := obj.(*helmv2.HelmRelease); ok && err == nil { + if gets++; gets == 1 { + return setValues(ctx, c, key, fixed) + } + } + return err + }} + }}, + {"fixed between the live read and the write", `{"resources":{"memory":8},"other":true}`, fixed, true, func() interceptor.Funcs { + writes := 0 + return interceptor.Funcs{Update: func(ctx context.Context, c client.WithWatch, obj client.Object, opts ...client.UpdateOption) error { + if _, ok := obj.(*helmv2.HelmRelease); ok { + if writes++; writes == 1 { + if err := setValues(ctx, c, client.ObjectKeyFromObject(obj), fixed); err != nil { + return err + } + return conflict(obj.GetName()) + } + } + return c.Update(ctx, obj, opts...) + }} + }}, + {"unrelated edit after a conflict", `{"resources":{"memory":8},"other":true}`, `{"resources":{"memory":8},"other":true}`, false, func() interceptor.Funcs { + writes := 0 + return interceptor.Funcs{Update: func(ctx context.Context, c client.WithWatch, obj client.Object, opts ...client.UpdateOption) error { + if _, ok := obj.(*helmv2.HelmRelease); ok { + if writes++; writes == 1 { + return conflict(obj.GetName()) + } + } + return c.Update(ctx, obj, opts...) + }} + }}, + } { + t.Run(tc.name, func(t *testing.T) { + app := &appsv1alpha1.Application{ + TypeMeta: metav1.TypeMeta{Kind: kubernetesKind, APIVersion: "apps.cozystack.io/v1alpha1"}, + ObjectMeta: metav1.ObjectMeta{Name: "good-name", Namespace: "tenant-foo"}, + Spec: &apiextv1.JSON{Raw: []byte(tc.next)}, + } + stored := &helmv2.HelmRelease{ObjectMeta: metav1.ObjectMeta{Name: "kubernetes-" + app.Name, Namespace: app.Namespace, Labels: map[string]string{ + ApplicationKindLabel: kubernetesKind, ApplicationGroupLabel: appsv1alpha1.GroupName, ApplicationNameLabel: app.Name, + }}, Spec: helmv2.HelmReleaseSpec{Values: &apiextv1.JSON{Raw: []byte(stale)}}} + r := newKubernetesWarnREST(t, stored) + r.specSchema = chartSpecSchema(t, "tcp-balancer") + r.c = interceptor.NewClient(r.w, tc.funcs()) + ctx := request.WithNamespace(context.Background(), app.Namespace) + _, _, err := r.Update(ctx, app.Name, newDefaultUpdatedObjectInfo(app), nil, nil, false, &metav1.UpdateOptions{}) + if tc.reject && !apierrors.IsInvalid(err) || !tc.reject && err != nil { + t.Fatalf("reject=%v, got %v", tc.reject, err) + } + got := &helmv2.HelmRelease{} + if err := r.w.Get(ctx, client.ObjectKeyFromObject(stored), got); err != nil { + t.Fatal(err) + } + if string(got.Spec.Values.Raw) != tc.want { + t.Fatalf("stored values %s, want %s", got.Spec.Values.Raw, tc.want) + } + }) + } +} diff --git a/pkg/registry/apps/application/quota.go b/pkg/registry/apps/application/quota.go index eb6f20622..5376139c0 100644 --- a/pkg/registry/apps/application/quota.go +++ b/pkg/registry/apps/application/quota.go @@ -233,7 +233,7 @@ func (r *REST) validateTenantResourceQuotas(ctx context.Context, app *appsv1alph } parentLimit := parentQuota[res] allocated := siblings[res] // zero value when no sibling bounds this resource - used := poolUsed[renderedLimitKey(res)] + used := poolUsed[usageKey(res)] remaining := parentLimit.DeepCopy() remaining.Sub(allocated) remaining.Sub(used) @@ -285,25 +285,39 @@ var rawQuotaKeys = map[string]struct{}{ "resourcequotas": {}, } -// renderedLimitKey maps a shorthand resourceQuotas key (the vocabulary admission -// works in) to the rendered ResourceQuota key that carries its limit-side -// budget, mirroring cozy-lib.resources.flatten. The mapping is allocation-ratio -// independent: ratios only scale the requests.* side that flatten derives from -// the same shorthand value, so the limit-side key always holds the operator's -// declared amount. This lets admission read a tenant's current usage from its -// rendered ResourceQuota.status.used without replicating the chart's ratio math. +// limitCountedKeys are the shorthand keys whose usage the ResourceQuota pod +// evaluator reports under limits.*. For every other resource it counts only +// requests.*, so limits. or limits.hugepages-* never carries +// usage even though the chart renders it. +var limitCountedKeys = map[string]struct{}{ + "cpu": {}, + "memory": {}, + "ephemeral-storage": {}, +} + +// usageKey maps a shorthand resourceQuotas key (the vocabulary admission works +// in) to the rendered ResourceQuota key whose status.used carries its usage. +// cozy-lib.resources.flatten renders a shorthand key both as limits. and as +// requests.; usage is read from whichever of the two the quota controller +// counts. For cpu, memory and ephemeral-storage that is the limit side, which +// holds the operator's declared amount whatever allocation ratio scales the +// request side. Every other resource is counted only on the request side, where +// flatten applies no ratio, so requests. holds the declared amount too. +// This lets admission read a tenant's current usage from its rendered +// ResourceQuota.status.used without replicating the chart's ratio math. // -// cpu, memory, ephemeral-storage, custom resources -> "limits." +// cpu, memory, ephemeral-storage -> "limits." // storage -> "requests.storage" (no hard limits.storage) // pods, services, services.loadbalancers, ... -> "" (verbatim) -func renderedLimitKey(raw string) string { - if raw == "storage" { - return "requests.storage" - } +// extended resources, hugepages-, ... -> "requests." +func usageKey(raw string) string { if _, ok := rawQuotaKeys[raw]; ok { return raw } - return "limits." + raw + if _, ok := limitCountedKeys[raw]; ok { + return "limits." + raw + } + return "requests." + raw } // parentNamespaceOf returns the namespace owned by the parent of the tenant that @@ -341,7 +355,7 @@ func (r *REST) poolRootOf(ns string, bounded map[string]bool) string { // created/updated). Usage is read from each member's ResourceQuota.status.used, // taking a per-resource max within a namespace to avoid double-counting the // chart-rendered and controller-allocated quotas, and is keyed in the rendered -// quota key space (see renderedLimitKey). Boundedness is decided by declared +// quota key space (see usageKey). Boundedness is decided by declared // resourceQuotas so the result does not depend on whether Flux has rendered a // freshly-created tenant's quota yet. func (r *REST) parentPoolUsage(ctx context.Context, parentNS, excludeNS string) (map[string]resource.Quantity, error) { diff --git a/pkg/registry/apps/application/quota_test.go b/pkg/registry/apps/application/quota_test.go index f6e5d3054..3ea2b7a2b 100644 --- a/pkg/registry/apps/application/quota_test.go +++ b/pkg/registry/apps/application/quota_test.go @@ -136,19 +136,20 @@ func usageQuota(t *testing.T, namespace, name string, used map[string]string) *c } } -func TestRenderedLimitKey(t *testing.T) { +func TestUsageKey(t *testing.T) { cases := map[string]string{ "cpu": "limits.cpu", "memory": "limits.memory", "ephemeral-storage": "limits.ephemeral-storage", - "devices.com/nvidia": "limits.devices.com/nvidia", + "devices.com/nvidia": "requests.devices.com/nvidia", + "hugepages-2Mi": "requests.hugepages-2Mi", "storage": "requests.storage", "pods": "pods", "services.loadbalancers": "services.loadbalancers", } for raw, want := range cases { - if got := renderedLimitKey(raw); got != want { - t.Errorf("renderedLimitKey(%q) = %q, want %q", raw, got, want) + if got := usageKey(raw); got != want { + t.Errorf("usageKey(%q) = %q, want %q", raw, got, want) } } } @@ -339,6 +340,26 @@ func TestValidateTenantResourceQuotas_PoolUsage(t *testing.T) { } }) + t.Run("parent usage of an extended resource shrinks remaining", func(t *testing.T) { + parent := tenantHelmRelease(t, "foo", "tenant-root", map[string]string{"example.com/device": "2"}) + used := usageQuota(t, "tenant-foo", "tenant-quota", map[string]string{"requests.example.com/device": "2"}) + r := newTenantREST(t, parent, used) + + if errs := r.validateTenantResourceQuotas(context.Background(), childApplication(t, "bar", "tenant-foo", map[string]string{"example.com/device": "1"})); len(errs) == 0 { + t.Fatalf("child example.com/device=1 should be denied when the parent pool already uses 2 of 2") + } + }) + + t.Run("parent usage of an extended resource leaves the rest grantable", func(t *testing.T) { + parent := tenantHelmRelease(t, "foo", "tenant-root", map[string]string{"example.com/device": "2"}) + used := usageQuota(t, "tenant-foo", "tenant-quota", map[string]string{"requests.example.com/device": "1"}) + r := newTenantREST(t, parent, used) + + if errs := r.validateTenantResourceQuotas(context.Background(), childApplication(t, "bar", "tenant-foo", map[string]string{"example.com/device": "1"})); len(errs) > 0 { + t.Fatalf("child example.com/device=1 should be allowed when the parent pool uses 1 of 2, got: %v", errs) + } + }) + // No rendered usage yet (freshly-created parent, Flux has not rendered the // quota): usage degrades to zero and behaviour matches the pre-usage gate. t.Run("absent usage degrades to budget-only check", func(t *testing.T) { diff --git a/pkg/registry/apps/application/rest.go b/pkg/registry/apps/application/rest.go index 826e7819b..86249a35c 100644 --- a/pkg/registry/apps/application/rest.go +++ b/pkg/registry/apps/application/rest.go @@ -19,6 +19,7 @@ package application import ( "context" "encoding/json" + "errors" "fmt" "net/http" "slices" @@ -200,6 +201,10 @@ func (r *REST) Create(ctx context.Context, obj runtime.Object, createValidation } } + if err := r.validateWorkloadMemory(app, nil); err != nil { + return nil, err + } + // Validate that values don't contain reserved keys (starting with "_") if err := validateNoInternalKeys(app.Spec); err != nil { return nil, apierrors.NewBadRequest(err.Error()) @@ -522,6 +527,7 @@ func (r *REST) Update(ctx context.Context, name string, objInfo rest.UpdatedObje return nil, false, err } + previousValues := oldObj.(*appsv1alpha1.Application).Spec.DeepCopy() previousFinalizers := slices.Clone(oldObj.(*appsv1alpha1.Application).Finalizers) // Update the Application object @@ -544,6 +550,10 @@ func (r *REST) Update(ctx context.Context, name string, objInfo rest.UpdatedObje // Update because Kubernetes names are immutable. Validating here would block // updates to pre-existing resources whose names don't conform to the new rules. + if err := r.validateWorkloadMemory(app, previousValues); err != nil { + return nil, false, err + } + // Validate that values don't contain reserved keys (starting with "_") if err := validateNoInternalKeys(app.Spec); err != nil { return nil, false, apierrors.NewBadRequest(err.Error()) @@ -596,6 +606,12 @@ func (r *REST) Update(ctx context.Context, name string, objInfo rest.UpdatedObje if helmRelease.ResourceVersion == "" { helmRelease.SetResourceVersion(cur.GetResourceVersion()) } + // The memory check above compared against the read at the start of Update. + // Compare again against the live release, so a stale value below 1Mi cannot + // overwrite memory that another writer has fixed since. + if err := r.validateWorkloadMemory(app, cur.Spec.Values); err != nil { + return nil, false, err + } r.applyLiveMetadata(helmRelease, cur, app, previousFinalizers) // Suspension is not part of the Application, so the rebuilt object always @@ -636,6 +652,9 @@ func (r *REST) Update(ctx context.Context, name string, objInfo rest.UpdatedObje if getErr := r.c.Get(ctx, client.ObjectKey{Namespace: helmRelease.Namespace, Name: helmRelease.Name}, cur, &client.GetOptions{Raw: &metav1.GetOptions{}}); getErr != nil { return getErr } + if memErr := r.validateWorkloadMemory(app, cur.Spec.Values); memErr != nil { + return memErr + } helmRelease = converted.DeepCopy() r.applyLiveMetadata(helmRelease, cur, app, previousFinalizers) helmRelease.SetResourceVersion(cur.GetResourceVersion()) @@ -675,9 +694,20 @@ func (r *REST) Delete(ctx context.Context, name string, deleteValidation rest.Va // Construct HelmRelease name with the configured prefix helmReleaseName := r.releaseConfig.Prefix + name + // A resourceVersion precondition is judged against the live release, so + // read it uncached. + var callerRV *string + if options != nil && options.Preconditions != nil { + callerRV = options.Preconditions.ResourceVersion + } + reader := client.Reader(r.c) + if callerRV != nil { + reader = r.w + } + // Retrieve the HelmRelease before attempting to delete helmRelease := &helmv2.HelmRelease{} - err = r.c.Get(ctx, client.ObjectKey{Namespace: namespace, Name: helmReleaseName}, helmRelease, &client.GetOptions{Raw: &metav1.GetOptions{}}) + err = reader.Get(ctx, client.ObjectKey{Namespace: namespace, Name: helmReleaseName}, helmRelease, &client.GetOptions{Raw: &metav1.GetOptions{}}) if err != nil { if apierrors.IsNotFound(err) { // If HelmRelease does not exist, return NotFound error for Application @@ -696,6 +726,15 @@ func (r *REST) Delete(ctx context.Context, name string, deleteValidation rest.Va return nil, false, apierrors.NewNotFound(r.gvr.GroupResource(), name) } + if callerRV != nil { + if err := r.checkResourceVersion(name, *callerRV, helmRelease.ResourceVersion); err != nil { + return nil, false, err + } + options = options.DeepCopy() + liveRV := helmRelease.ResourceVersion + options.Preconditions.ResourceVersion = &liveRV + } + // Run the genericapiserver-supplied admission chain (validating webhooks // and ValidatingAdmissionPolicies) on the resolved Application before // removing the underlying HelmRelease. Custom REST handlers must invoke @@ -725,6 +764,46 @@ func (r *REST) Delete(ctx context.Context, name string, deleteValidation rest.Va return nil, true, nil } +// checkResourceVersion applies a caller's resourceVersion precondition to the +// live HelmRelease. Every resourceVersion is a revision of the same etcd. An +// Application carries the version of the release its spec came from or, on a +// WorkloadMonitor-triggered watch event, a monitor revision, which is newer +// than that release only when the release was read at or after it. A value +// newer than the live release therefore names the current spec, and only an +// older one is a conflict. +func (r *REST) checkResourceVersion(name, callerRV, liveRV string) error { + caller, err := strconv.ParseUint(callerRV, 10, 64) + if err != nil { + return apierrors.NewBadRequest(fmt.Sprintf("invalid resourceVersion %q: %v", callerRV, err)) + } + live, err := strconv.ParseUint(liveRV, 10, 64) + if err != nil { + return fmt.Errorf("HelmRelease for %s has an invalid resourceVersion %q: %w", name, liveRV, err) + } + if caller < live { + return apierrors.NewConflict(r.gvr.GroupResource(), name, errors.New("the object has been modified; please apply your changes to the latest version and try again")) + } + return nil +} + +// newerResourceVersion returns whichever of two numeric resourceVersions is +// higher, preferring b when either does not parse. +func newerResourceVersion(a, b string) string { + av, aErr := strconv.ParseUint(a, 10, 64) + bv, bErr := strconv.ParseUint(b, 10, 64) + if aErr != nil || bErr != nil || bv >= av { + return b + } + return a +} + +// Watches bypass the API server's default one-minute request timeout. +const ( + liveReleaseReadAttempts = 3 + liveReleaseReadRetryDelay = 100 * time.Millisecond + liveReleaseReadTimeout = time.Minute +) + // Watch sets up a watch on HelmReleases, filters them based on application labels, and converts events to Applications func (r *REST) Watch(ctx context.Context, options *metainternalversion.ListOptions) (watch.Interface, error) { namespace, err := r.getNamespace(ctx) @@ -864,6 +943,17 @@ func (r *REST) Watch(ctx context.Context, options *metainternalversion.ListOptio if wmWatcherForCleanup != nil { defer wmWatcherForCleanup.Stop() } + // Live reads use a context that Stop cancels, so a stopped watch + // never waits on the API server. + readCtx, cancelReads := context.WithCancel(ctx) + defer cancelReads() + go func() { + select { + case <-customW.stopChan: + cancelReads() + case <-readCtx.Done(): + } + }() // Buffer of WorkloadMonitor events that arrived before the initial // snapshot finished. The watch-list contract requires the stream to @@ -873,7 +963,12 @@ func (r *REST) Watch(ctx context.Context, options *metainternalversion.ListOptio // workload whose status flips during the snapshot window (after the // Application ADDED but before the bookmark) and then stops changing // would leave the client with a stale WorkloadsReady forever. - var pendingWMEvents []watch.Event + type monitorEvent struct { + event watch.Event + monitorRV string + releaseRV string + } + var pendingWMEvents []monitorEvent // Get the starting resourceVersion from options // If client provides resourceVersion (e.g., from a previous List), we should skip @@ -897,9 +992,38 @@ func (r *REST) Watch(ctx context.Context, options *metainternalversion.ListOptio } } + // lastSent holds, per Application, the resourceVersion of the last + // event this watch sent. + lastSent := map[client.ObjectKey]string{} + remember := func(app *appsv1alpha1.Application, eventType watch.EventType) { + key := client.ObjectKey{Namespace: app.Namespace, Name: app.Name} + if eventType == watch.Deleted { + delete(lastSent, key) + return + } + lastSent[key] = app.ResourceVersion + } + + // sendMonitorEvent falls back to the monitor's own resourceVersion + // when the event might repeat the one the client already holds, which + // a shared informer hides from its handlers. Without an entry for the + // object, a client resuming this watch may hold any release version, + // so the release's own version counts as held. The object the client + // caches from a fallback event gets a conflict on a precondition-checked + // delete until its next event. + sendMonitorEvent := func(me monitorEvent) bool { + app := me.event.Object.(*appsv1alpha1.Application) + last, known := lastSent[client.ObjectKey{Namespace: app.Namespace, Name: app.Name}] + if (known && app.ResourceVersion == last) || (!known && app.ResourceVersion == me.releaseRV) { + app.SetResourceVersion(me.monitorRV) + } + remember(app, me.event.Type) + return send(me.event) + } + drainPendingWMEvents := func() bool { for _, ev := range pendingWMEvents { - if !send(ev) { + if !sendMonitorEvent(ev) { return false } } @@ -1014,6 +1138,7 @@ func (r *REST) Watch(ctx context.Context, options *metainternalversion.ListOptio // When startingRV == 0, always send ADDED events (client wants full state) // Send event to custom watcher + remember(&app, event.Type) if !send(watch.Event{Type: event.Type, Object: &app}) { return } @@ -1072,10 +1197,39 @@ func (r *REST) Watch(ctx context.Context, options *metainternalversion.ListOptio } else if !fieldFilter.MatchesNamespace(hrNS) { continue } + // The event's resourceVersion may be the monitor's, which a + // Delete precondition accepts as current while the release has + // not moved past it. A cached release older than the monitor + // revision could pair a stale spec with that version, so only + // then is the release read live. + hrKey := client.ObjectKey{Namespace: hrNS, Name: hrName} hr := &helmv2.HelmRelease{} - if err := r.c.Get(ctx, client.ObjectKey{Namespace: hrNS, Name: hrName}, hr); err != nil { - klog.V(4).Infof("Cannot find HelmRelease %s/%s for WorkloadMonitor event: %v", hrNS, hrName, err) - continue + if err := r.c.Get(ctx, hrKey, hr); err != nil || newerResourceVersion(wm.GetResourceVersion(), hr.GetResourceVersion()) != hr.GetResourceVersion() { + hr = &helmv2.HelmRelease{} + // Nothing replays a monitor event this watch drops, so a + // transient failure of the live read is retried briefly. + // A missing release is final. + liveCtx, cancelLiveRead := context.WithTimeout(readCtx, liveReleaseReadTimeout) + liveErr := r.w.Get(liveCtx, hrKey, hr) + for attempt := 1; liveErr != nil && !apierrors.IsNotFound(liveErr) && attempt < liveReleaseReadAttempts; attempt++ { + select { + case <-liveCtx.Done(): + case <-time.After(liveReleaseReadRetryDelay): + } + if liveCtx.Err() != nil { + break + } + liveErr = r.w.Get(liveCtx, hrKey, hr) + } + readEnded := liveCtx.Err() != nil + cancelLiveRead() + if readEnded { + return + } + if liveErr != nil { + klog.V(4).Infof("Cannot find HelmRelease %s/%s for WorkloadMonitor event: %v", hrNS, hrName, liveErr) + continue + } } // Pass the fresh WorkloadMonitor so conversion uses the latest // operational status even if the cache (r.c) has not yet @@ -1096,10 +1250,8 @@ func (r *REST) Watch(ctx context.Context, options *metainternalversion.ListOptio continue } } - // Use the WorkloadMonitor's ResourceVersion for the emitted event - // so clients see a monotonically increasing RV and don't skip this update. - app.SetResourceVersion(wm.GetResourceVersion()) - outEvent := watch.Event{Type: watch.Modified, Object: &app} + app.SetResourceVersion(newerResourceVersion(wm.GetResourceVersion(), hr.GetResourceVersion())) + outEvent := monitorEvent{event: watch.Event{Type: watch.Modified, Object: &app}, monitorRV: wm.GetResourceVersion(), releaseRV: hr.GetResourceVersion()} // Buffer WM-triggered events that arrive before the // initial-events-end bookmark. They will be replayed in order // immediately after the bookmark is emitted. @@ -1108,7 +1260,7 @@ func (r *REST) Watch(ctx context.Context, options *metainternalversion.ListOptio continue } bookmarker.Observe(wm.GetResourceVersion()) - if !send(outEvent) { + if !sendMonitorEvent(outEvent) { return } diff --git a/pkg/registry/apps/application/rest_watch_deadline_test.go b/pkg/registry/apps/application/rest_watch_deadline_test.go new file mode 100644 index 000000000..3d4bc68f5 --- /dev/null +++ b/pkg/registry/apps/application/rest_watch_deadline_test.go @@ -0,0 +1,149 @@ +package application + +import ( + "context" + "errors" + "testing" + "testing/synctest" + "time" + + metainternalversion "k8s.io/apimachinery/pkg/apis/meta/internalversion" + "k8s.io/apimachinery/pkg/watch" + "k8s.io/apiserver/pkg/endpoints/request" +) + +func expectLiveReadWatchClosed(t *testing.T, w watch.Interface) { + t.Helper() + select { + case event, open := <-w.ResultChan(): + if open { + t.Fatalf("unexpected %s event instead of watch closure", event.Type) + } + default: + t.Fatal("watch remains open after the live-read deadline") + } +} + +func TestWatchHungLiveReadDeadlineClosesAndReconnects(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + f := newRVWatchFixture(t) + parent, w := startRVWatch(t, f) + cached := f.liveRelease(t) + f.hrW.Modify(cached.DeepCopy()) + resume := nextApplication(t, w).ResourceVersion + live := f.advanceLive(t, "before-timeout") + readsBefore := f.liveReleaseGets + entered := make(chan context.Context, 1) + f.liveReleaseErrs = []error{errors.New("live read failed")} + f.onLiveReleaseError = func(ctx context.Context) { + entered <- ctx + <-ctx.Done() + } + + readStarted := time.Now() + f.monitorEvent(live.ResourceVersion) + synctest.Wait() + var liveCtx context.Context + select { + case liveCtx = <-entered: + default: + t.Fatal("live read did not start") + } + time.Sleep(time.Minute) + synctest.Wait() + expectLiveReadWatchClosed(t, w) + if !errors.Is(liveCtx.Err(), context.DeadlineExceeded) { + t.Fatalf("live read ended with %v, want its own deadline", liveCtx.Err()) + } + deadline, bounded := liveCtx.Deadline() + if !bounded || deadline.Sub(readStarted) != time.Minute { + t.Fatalf("live read budget %v, bounded=%t, want exactly one minute", deadline.Sub(readStarted), bounded) + } + if parent.Err() != nil { + t.Fatalf("watch parent unexpectedly ended: %v", parent.Err()) + } + if got := f.liveReleaseGets - readsBefore; got != 1 { + t.Fatalf("live release reads %d, want one bounded hung read", got) + } + + f.hrW, f.wmW = watch.NewFake(), watch.NewFake() + fresh := f.advanceLive(t, "after-reconnect") + reconnected := startRVWatchFrom(t, f, resume) + f.monitorEvent(fresh.ResourceVersion) + app := nextApplication(t, reconnected) + if got := specMarker(t, app); got != "after-reconnect" { + t.Fatalf("reconnected spec marker %q, want fresh live state", got) + } + if app.ResourceVersion != fresh.ResourceVersion { + t.Fatalf("reconnected version %q, want %q", app.ResourceVersion, fresh.ResourceVersion) + } + }) +} + +func TestWatchLiveReadDeadlineIncludesRetries(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + f := newRVWatchFixture(t) + _, w := startRVWatch(t, f) + live := f.advanceLive(t, "live") + readsBefore := f.liveReleaseGets + f.liveReleaseErrs = []error{errors.New("temporary live read failure")} + f.onLiveReleaseError = func(context.Context) { + time.Sleep(45 * time.Second) + f.liveReleaseHang = true + } + + f.monitorEvent(live.ResourceVersion) + synctest.Wait() + time.Sleep(time.Minute) + synctest.Wait() + expectLiveReadWatchClosed(t, w) + if got := f.liveReleaseGets - readsBefore; got != 2 { + t.Fatalf("live release reads %d, want one slow failure and one hung retry", got) + } + }) +} + +func TestWatchCancellationEndsHungLiveReadBeforeDeadline(t *testing.T) { + for _, mode := range []string{"stop", "context"} { + t.Run(mode, func(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + f := newRVWatchFixture(t) + parent, cancel := context.WithCancel(request.WithNamespace(context.Background(), "default")) + t.Cleanup(cancel) + w, err := f.rest.Watch(parent, &metainternalversion.ListOptions{}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(w.Stop) + live := f.advanceLive(t, "live") + readsBefore := f.liveReleaseGets + entered := make(chan context.Context, 1) + f.liveReleaseErrs = []error{errors.New("live read failed")} + f.onLiveReleaseError = func(ctx context.Context) { + entered <- ctx + <-ctx.Done() + } + f.monitorEvent(live.ResourceVersion) + synctest.Wait() + liveCtx := <-entered + before := time.Now() + if mode == "stop" { + w.Stop() + } else { + cancel() + } + synctest.Wait() + expectLiveReadWatchClosed(t, w) + if !errors.Is(liveCtx.Err(), context.Canceled) { + t.Fatalf("live read ended with %v, want cancellation", liveCtx.Err()) + } + if time.Since(before) != 0 { + t.Fatal("cancellation waited for a timer") + } + if got := f.liveReleaseGets - readsBefore; got != 1 { + t.Fatalf("live release reads %d, want exactly one", got) + } + }) + }) + } +} diff --git a/pkg/registry/apps/application/rest_watch_rv_test.go b/pkg/registry/apps/application/rest_watch_rv_test.go new file mode 100644 index 000000000..06640d72e --- /dev/null +++ b/pkg/registry/apps/application/rest_watch_rv_test.go @@ -0,0 +1,633 @@ +package application + +import ( + "context" + "encoding/json" + "errors" + "strconv" + "testing" + "time" + + cozyv1alpha1 "github.com/cozystack/cozystack/api/v1alpha1" + appsv1alpha1 "github.com/cozystack/cozystack/pkg/apis/apps/v1alpha1" + "github.com/cozystack/cozystack/pkg/config" + helmv2 "github.com/fluxcd/helm-controller/api/v2" + apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + metainternalversion "k8s.io/apimachinery/pkg/apis/meta/internalversion" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/watch" + "k8s.io/apiserver/pkg/endpoints/request" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/client/fake" + "sigs.k8s.io/controller-runtime/pkg/client/interceptor" +) + +// rvWatchFixture models the two clients REST uses: c reads from an informer +// cache and writes to the API server, w talks to the API server directly. +// The cache can be left behind the live release, and the HelmRelease and +// WorkloadMonitor watches are fake watchers the test drives. +type rvWatchFixture struct { + rest *REST + cache client.Client + live client.WithWatch + hrW *watch.FakeWatcher + wmW *watch.FakeWatcher + // liveReleaseGets counts HelmRelease reads that bypass the cache. The + // watch goroutine and the test both update it; receiving an event from + // the watch orders the watch's updates before the test's next access. + liveReleaseGets int + // liveReleaseErrs are returned by the next live HelmRelease reads, one + // per read, before reads reach the store again. + liveReleaseErrs []error + onLiveReleaseError func(context.Context) + // liveReleaseHang makes live HelmRelease reads block until their context + // ends, like a request to an API server that never answers. + liveReleaseHang bool + // cacheStore is the store behind cache, for tests that leave the cache + // without the release. + cacheStore client.WithWatch +} + +var rvReleaseKey = client.ObjectKey{Namespace: "default", Name: "postgresql-mydb"} + +func newRVWatchFixture(t *testing.T) *rvWatchFixture { + t.Helper() + scheme := runtime.NewScheme() + if err := cozyv1alpha1.AddToScheme(scheme); err != nil { + t.Fatal(err) + } + if err := helmv2.AddToScheme(scheme); err != nil { + t.Fatal(err) + } + release := func() *helmv2.HelmRelease { + return &helmv2.HelmRelease{ + ObjectMeta: metav1.ObjectMeta{ + Name: rvReleaseKey.Name, + Namespace: rvReleaseKey.Namespace, + Labels: map[string]string{ + ApplicationKindLabel: "PostgreSQL", + ApplicationGroupLabel: appsv1alpha1.GroupName, + ApplicationNameLabel: "mydb", + }, + }, + Spec: helmv2.HelmReleaseSpec{Values: &apiextensionsv1.JSON{Raw: []byte(`{"marker":"cached"}`)}}, + } + } + + f := &rvWatchFixture{hrW: watch.NewFake(), wmW: watch.NewFake()} + liveStore := fake.NewClientBuilder().WithScheme(scheme).WithObjects(release()).Build() + f.live = interceptor.NewClient(liveStore, interceptor.Funcs{ + Get: func(ctx context.Context, c client.WithWatch, key client.ObjectKey, obj client.Object, opts ...client.GetOption) error { + if _, ok := obj.(*helmv2.HelmRelease); ok { + f.liveReleaseGets++ + if f.liveReleaseHang { + <-ctx.Done() + return ctx.Err() + } + if len(f.liveReleaseErrs) > 0 { + err := f.liveReleaseErrs[0] + f.liveReleaseErrs = f.liveReleaseErrs[1:] + if hook := f.onLiveReleaseError; hook != nil { + f.onLiveReleaseError = nil + hook(ctx) + } + return err + } + } + return c.Get(ctx, key, obj, opts...) + }, + Watch: func(_ context.Context, _ client.WithWatch, list client.ObjectList, _ ...client.ListOption) (watch.Interface, error) { + if _, ok := list.(*cozyv1alpha1.WorkloadMonitorList); ok { + return f.wmW, nil + } + return f.hrW, nil + }, + }) + f.cacheStore = fake.NewClientBuilder().WithScheme(scheme).WithObjects(release()).Build() + f.cache = interceptor.NewClient(f.cacheStore, interceptor.Funcs{ + Delete: func(ctx context.Context, _ client.WithWatch, obj client.Object, opts ...client.DeleteOption) error { + return liveStore.Delete(ctx, obj, opts...) + }, + }) + f.rest = NewREST(f.cache, f.live, &config.Resource{ + Application: config.ApplicationConfig{Kind: "PostgreSQL", Plural: "postgresqls", Singular: "postgresql"}, + Release: config.ReleaseConfig{Prefix: "postgresql-"}, + }) + return f +} + +func (f *rvWatchFixture) liveRelease(t *testing.T) *helmv2.HelmRelease { + t.Helper() + hr := &helmv2.HelmRelease{} + if err := f.live.Get(context.Background(), rvReleaseKey, hr); err != nil { + t.Fatal(err) + } + return hr +} + +// advanceLive writes a new spec to the live release only, leaving the cache +// one version behind, and returns the new live release. +func (f *rvWatchFixture) advanceLive(t *testing.T, marker string) *helmv2.HelmRelease { + t.Helper() + hr := f.liveRelease(t) + before := hr.ResourceVersion + hr.Spec.Values = &apiextensionsv1.JSON{Raw: []byte(`{"marker":"` + marker + `"}`)} + if err := f.live.Update(context.Background(), hr); err != nil { + t.Fatal(err) + } + if hr.ResourceVersion == before { + t.Fatal("fake client did not advance the release version") + } + return hr +} + +func (f *rvWatchFixture) monitorEvent(rv string) { + f.wmW.Modify(&cozyv1alpha1.WorkloadMonitor{ + ObjectMeta: metav1.ObjectMeta{ + Name: "mon-1", + Namespace: "default", + ResourceVersion: rv, + Labels: map[string]string{ + appsv1alpha1.ApplicationKindLabel: "PostgreSQL", + appsv1alpha1.ApplicationGroupLabel: appsv1alpha1.GroupName, + appsv1alpha1.ApplicationNameLabel: "mydb", + }, + }, + Status: cozyv1alpha1.WorkloadMonitorStatus{Operational: new(true)}, + }) +} + +func startRVWatch(t *testing.T, f *rvWatchFixture) (context.Context, watch.Interface) { + t.Helper() + ctx, cancel := context.WithCancel(request.WithNamespace(context.Background(), "default")) + t.Cleanup(cancel) + w, err := f.rest.Watch(ctx, &metainternalversion.ListOptions{}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(w.Stop) + return ctx, w +} + +func nextApplication(t *testing.T, w watch.Interface) *appsv1alpha1.Application { + t.Helper() + select { + case ev, ok := <-w.ResultChan(): + if !ok { + t.Fatal("watch closed") + } + app, ok := ev.Object.(*appsv1alpha1.Application) + if !ok { + t.Fatalf("got %s %T, want an Application", ev.Type, ev.Object) + } + return app + case <-time.After(5 * time.Second): + t.Fatal("no event") + } + return nil +} + +func specMarker(t *testing.T, app *appsv1alpha1.Application) string { + t.Helper() + var v struct { + Marker string `json:"marker"` + } + if app.Spec == nil { + t.Fatal("application has no spec") + } + if err := json.Unmarshal(app.Spec.Raw, &v); err != nil { + t.Fatal(err) + } + return v.Marker +} + +func rvNumber(t *testing.T, rv string) uint64 { + t.Helper() + n, err := strconv.ParseUint(rv, 10, 64) + if err != nil { + t.Fatalf("resourceVersion %q: %v", rv, err) + } + return n +} + +// The spec in a monitor-triggered event must come from a release read no +// earlier than the monitor revision the event carries, or a precondition on +// that version would accept a write built on a stale spec. +func TestWatchMonitorEventReadsReleaseLive(t *testing.T) { + f := newRVWatchFixture(t) + _, w := startRVWatch(t, f) + f.advanceLive(t, "live") + + f.monitorEvent("5000") + app := nextApplication(t, w) + if got := specMarker(t, app); got != "live" { + t.Fatalf("spec marker %q, want the live release's", got) + } + if app.ResourceVersion != "5000" { + t.Fatalf("resourceVersion %q, want the monitor's 5000", app.ResourceVersion) + } + if f.liveReleaseGets != 2 { + t.Fatalf("%d live release reads, want the test's own plus one for the event", f.liveReleaseGets) + } +} + +// A release cached at or past the monitor revision already pairs its spec +// with its own version, so the event uses it without a live read: a watch +// replays every existing monitor as ADDED when it starts. With nothing sent +// for the object yet, the client may hold that release version, so the event +// carries the monitor's. +func TestWatchMonitorEventUsesCacheNotOlderThanMonitor(t *testing.T) { + f := newRVWatchFixture(t) + _, w := startRVWatch(t, f) + cached := &helmv2.HelmRelease{} + if err := f.cache.Get(context.Background(), rvReleaseKey, cached); err != nil { + t.Fatal(err) + } + f.advanceLive(t, "live") + gets := f.liveReleaseGets + + f.monitorEvent("1") + app := nextApplication(t, w) + if got := specMarker(t, app); got != "cached" { + t.Fatalf("spec marker %q, want the cached release's", got) + } + if app.ResourceVersion != "1" { + t.Fatalf("resourceVersion %q, want the monitor's 1 rather than the cached release's %q", app.ResourceVersion, cached.ResourceVersion) + } + if f.liveReleaseGets != gets { + t.Fatalf("%d live release reads for a monitor older than the cached release, want none", f.liveReleaseGets-gets) + } +} + +// Shared informers deliver an update whose resourceVersion equals the stored +// one only to handlers due for a resync, so each monitor-only change must +// arrive with a resourceVersion different from the previous event's. +func TestWatchMonitorOnlyChangeAdvancesVersion(t *testing.T) { + f := newRVWatchFixture(t) + _, w := startRVWatch(t, f) + live := f.advanceLive(t, "live") + + f.hrW.Modify(live.DeepCopy()) + prev := rvNumber(t, nextApplication(t, w).ResourceVersion) + for _, rv := range []string{"5000", "5001"} { + f.monitorEvent(rv) + got := rvNumber(t, nextApplication(t, w).ResourceVersion) + if got <= prev { + t.Fatalf("monitor event resourceVersion %d, want above the previous event's %d", got, prev) + } + prev = got + } +} + +// A monitor event processed after the release event it predates must not +// repeat the resourceVersion the client already holds, or a shared informer +// hides it from its handlers. It falls back to the monitor's older version, +// and a delete with that version gets a conflict instead of acting on a spec +// the client may not have. +func TestWatchLateMonitorEventDoesNotRepeatVersion(t *testing.T) { + f := newRVWatchFixture(t) + ctx, w := startRVWatch(t, f) + live := f.liveRelease(t) + + f.hrW.Modify(live.DeepCopy()) + if got := nextApplication(t, w).ResourceVersion; got != live.ResourceVersion { + t.Fatalf("release event resourceVersion %q, want %q", got, live.ResourceVersion) + } + f.monitorEvent("1") + rv := nextApplication(t, w).ResourceVersion + if rv != "1" { + t.Fatalf("late monitor event resourceVersion %q, want the monitor's 1 rather than the held %q", rv, live.ResourceVersion) + } + _, _, err := f.rest.Delete(ctx, "mydb", nil, &metav1.DeleteOptions{Preconditions: &metav1.Preconditions{ResourceVersion: &rv}}) + if !apierrors.IsConflict(err) { + t.Fatalf("delete with the monitor's older version: got %v, want Conflict", err) + } +} + +// A release the client already holds is skipped on a resumed watch, so the +// next monitor event must not repeat its version either. +func TestWatchLateMonitorEventAfterSkippedReplay(t *testing.T) { + f := newRVWatchFixture(t) + live := f.liveRelease(t) + w := startRVWatchFrom(t, f, live.ResourceVersion) + + f.hrW.Add(live.DeepCopy()) + f.monitorEvent("1") + if rv := nextApplication(t, w).ResourceVersion; rv != "1" { + t.Fatalf("monitor event after the skipped replay has resourceVersion %q, want the monitor's 1 rather than the held %q", rv, live.ResourceVersion) + } +} + +// Once this watch has sent the object a monitor version, the release version +// is no longer what the client holds, and the event can carry it. +func TestWatchMonitorEventCarriesReleaseAfterFallback(t *testing.T) { + f := newRVWatchFixture(t) + _, w := startRVWatch(t, f) + live := f.liveRelease(t) + + f.monitorEvent("1") + if rv := nextApplication(t, w).ResourceVersion; rv != "1" { + t.Fatalf("first monitor event resourceVersion %q, want the monitor's 1", rv) + } + f.monitorEvent("2") + if rv := nextApplication(t, w).ResourceVersion; rv != live.ResourceVersion { + t.Fatalf("second monitor event resourceVersion %q, want the release's %q", rv, live.ResourceVersion) + } +} + +// expectNoApplication fails if the watch delivers anything within the wait, +// then sends a release event and receives it so that the watch goroutine's +// earlier bookkeeping is ordered before the caller's next read of it. +func expectNoApplication(t *testing.T, f *rvWatchFixture, w watch.Interface, release *helmv2.HelmRelease) { + t.Helper() + select { + case ev := <-w.ResultChan(): + t.Fatalf("unexpected %s event", ev.Type) + case <-time.After((liveReleaseReadAttempts + 2) * liveReleaseReadRetryDelay): + } + f.hrW.Modify(release) + nextApplication(t, w) +} + +// A transient failure of the live read must not cost the client the monitor +// change: nothing replays it, so the read is retried. +func TestWatchMonitorEventRetriesLiveRead(t *testing.T) { + f := newRVWatchFixture(t) + _, w := startRVWatch(t, f) + live := f.advanceLive(t, "live") + readsBefore := f.liveReleaseGets + timeout := errors.New("etcdserver: request timed out") + f.liveReleaseErrs = []error{timeout, timeout} + + f.monitorEvent(live.ResourceVersion) + app := nextApplication(t, w) + if got := f.liveReleaseGets - readsBefore; got != 3 { + t.Fatalf("live release reads %d, want two failed attempts and one success", got) + } + if got := specMarker(t, app); got != "live" { + t.Fatalf("spec marker %q, want the live spec", got) + } + if app.ResourceVersion != live.ResourceVersion { + t.Fatalf("resourceVersion %q, want the live release's %q", app.ResourceVersion, live.ResourceVersion) + } +} + +// A read that keeps failing is given up after the last attempt, so a broken +// apiserver cannot hold the watch goroutine. +func TestWatchMonitorEventGivesUpAfterRetries(t *testing.T) { + f := newRVWatchFixture(t) + _, w := startRVWatch(t, f) + live := f.advanceLive(t, "live") + readsBefore := f.liveReleaseGets + timeout := errors.New("etcdserver: request timed out") + for range liveReleaseReadAttempts { + f.liveReleaseErrs = append(f.liveReleaseErrs, timeout) + } + + f.monitorEvent(live.ResourceVersion) + expectNoApplication(t, f, w, live) + if got := f.liveReleaseGets - readsBefore; got != liveReleaseReadAttempts { + t.Fatalf("live release reads %d, want %d attempts and no more", got, liveReleaseReadAttempts) + } +} + +// Cancel before the first failed Get returns: a send to FakeWatcher only +// orders event receipt, so cancelling after the send can lose the retry window. +func stopAtFailedLiveRead(t *testing.T, f *rvWatchFixture, w watch.Interface, stop func()) { + t.Helper() + live := f.advanceLive(t, "live") + readsBefore := f.liveReleaseGets + timeout := errors.New("etcdserver: request timed out") + for range liveReleaseReadAttempts { + f.liveReleaseErrs = append(f.liveReleaseErrs, timeout) + } + + f.onLiveReleaseError = func(ctx context.Context) { + stop() + select { + case <-ctx.Done(): + case <-time.After(5 * time.Second): + t.Error("live read context still open after cancellation") + } + } + f.monitorEvent(live.ResourceVersion) + select { + case ev, ok := <-w.ResultChan(): + if ok { + t.Fatalf("unexpected %s event", ev.Type) + } + case <-time.After(5 * time.Second): + t.Fatal("watch still open") + } + if got := f.liveReleaseGets - readsBefore; got != 1 { + t.Fatalf("live release reads %d, want the one before the stop", got) + } +} + +func TestWatchStopAtFailedLiveReadPreventsRetry(t *testing.T) { + f := newRVWatchFixture(t) + _, w := startRVWatch(t, f) + stopAtFailedLiveRead(t, f, w, w.Stop) +} + +func TestWatchContextCancelAtFailedLiveReadPreventsRetry(t *testing.T) { + f := newRVWatchFixture(t) + ctx, cancel := context.WithCancel(request.WithNamespace(context.Background(), "default")) + t.Cleanup(cancel) + w, err := f.rest.Watch(ctx, &metainternalversion.ListOptions{}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(w.Stop) + stopAtFailedLiveRead(t, f, w, cancel) +} + +// A live read that never answers must not outlive the watch: Stop cancels +// the read's context, and the watch closes. +func TestWatchStopCancelsHungLiveRead(t *testing.T) { + f := newRVWatchFixture(t) + _, w := startRVWatch(t, f) + live := f.advanceLive(t, "live") + f.liveReleaseHang = true + + f.monitorEvent(live.ResourceVersion) + w.Stop() + select { + case ev, ok := <-w.ResultChan(): + if ok { + t.Fatalf("unexpected %s event", ev.Type) + } + case <-time.After(5 * time.Second): + t.Fatal("watch still open while a live read hangs") + } +} + +// A release that is gone is final: the event is dropped after one read, +// without retries that would delay the next event. +func TestWatchMonitorEventDroppedWhenReleaseIsGone(t *testing.T) { + f := newRVWatchFixture(t) + _, w := startRVWatch(t, f) + release := f.liveRelease(t) + for _, c := range []client.Client{f.cacheStore, f.live} { + if err := c.Delete(context.Background(), release.DeepCopy()); err != nil { + t.Fatal(err) + } + } + readsBefore := f.liveReleaseGets + + f.monitorEvent(strconv.FormatUint(rvNumber(t, release.ResourceVersion)+1, 10)) + expectNoApplication(t, f, w, release) + if got := f.liveReleaseGets - readsBefore; got != 1 { + t.Fatalf("live release reads %d, want a single read", got) + } +} + +// A release the cache has not seen yet is read live and delivered. +func TestWatchMonitorEventReadsReleaseMissingFromCache(t *testing.T) { + f := newRVWatchFixture(t) + _, w := startRVWatch(t, f) + live := f.advanceLive(t, "live") + if err := f.cacheStore.Delete(context.Background(), live.DeepCopy()); err != nil { + t.Fatal(err) + } + readsBefore := f.liveReleaseGets + + f.monitorEvent(live.ResourceVersion) + app := nextApplication(t, w) + if got := f.liveReleaseGets - readsBefore; got != 1 { + t.Fatalf("live release reads %d, want one", got) + } + if got := specMarker(t, app); got != "live" { + t.Fatalf("spec marker %q, want the live spec", got) + } +} + +// A release event in between makes the release version the held one again. +func TestWatchReleaseEventResetsHeldVersion(t *testing.T) { + f := newRVWatchFixture(t) + _, w := startRVWatch(t, f) + live := f.liveRelease(t) + + f.monitorEvent("1") + nextApplication(t, w) + f.hrW.Modify(live.DeepCopy()) + if rv := nextApplication(t, w).ResourceVersion; rv != live.ResourceVersion { + t.Fatalf("release event resourceVersion %q, want %q", rv, live.ResourceVersion) + } + f.monitorEvent("2") + if rv := nextApplication(t, w).ResourceVersion; rv != "2" { + t.Fatalf("monitor event after the release event has resourceVersion %q, want the monitor's 2 rather than the held %q", rv, live.ResourceVersion) + } +} + +func startRVWatchFrom(t *testing.T, f *rvWatchFixture, resourceVersion string) watch.Interface { + t.Helper() + ctx, cancel := context.WithCancel(request.WithNamespace(context.Background(), "default")) + t.Cleanup(cancel) + w, err := f.rest.Watch(ctx, &metainternalversion.ListOptions{ResourceVersion: resourceVersion}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(w.Stop) + return w +} + +// On a resumed watch the replayed monitor can arrive before the replayed +// release, so nothing is known yet about the version the client holds. +func TestWatchResumedMonitorReplayBeforeRelease(t *testing.T) { + f := newRVWatchFixture(t) + live := f.liveRelease(t) + w := startRVWatchFrom(t, f, live.ResourceVersion) + + f.monitorEvent("1") + if rv := nextApplication(t, w).ResourceVersion; rv != "1" { + t.Fatalf("replayed monitor event has resourceVersion %q, want the monitor's 1 rather than the possibly held %q", rv, live.ResourceVersion) + } +} + +// A fallback event steps the client's resume point below versions it holds, +// so a resumed client can hold a release version above the one it resumes +// from. +func TestWatchResumedBelowHeldReleaseVersion(t *testing.T) { + f := newRVWatchFixture(t) + live := f.liveRelease(t) + if rvNumber(t, live.ResourceVersion) <= 500 { + t.Fatalf("fixture release version %q must be above the resume point", live.ResourceVersion) + } + w := startRVWatchFrom(t, f, "500") + + f.monitorEvent("1") + if rv := nextApplication(t, w).ResourceVersion; rv != "1" { + t.Fatalf("replayed monitor event has resourceVersion %q, want the monitor's 1 rather than the possibly held %q", rv, live.ResourceVersion) + } +} + +func TestDeleteWithVersionFromMonitorEvent(t *testing.T) { + f := newRVWatchFixture(t) + ctx, w := startRVWatch(t, f) + f.advanceLive(t, "live") + + f.monitorEvent("5000") + rv := nextApplication(t, w).ResourceVersion + _, _, err := f.rest.Delete(ctx, "mydb", nil, &metav1.DeleteOptions{Preconditions: &metav1.Preconditions{ResourceVersion: &rv}}) + if err != nil { + t.Fatalf("delete with resourceVersion %q from the watch event: %v", rv, err) + } + if err := f.live.Get(context.Background(), rvReleaseKey, &helmv2.HelmRelease{}); !apierrors.IsNotFound(err) { + t.Fatalf("release still present after delete: %v", err) + } +} + +func TestDeleteRejectsVersionOlderThanLive(t *testing.T) { + f := newRVWatchFixture(t) + cached := &helmv2.HelmRelease{} + if err := f.cache.Get(context.Background(), rvReleaseKey, cached); err != nil { + t.Fatal(err) + } + f.advanceLive(t, "live") + + ctx := request.WithNamespace(context.Background(), "default") + rv := cached.ResourceVersion + _, _, err := f.rest.Delete(ctx, "mydb", nil, &metav1.DeleteOptions{Preconditions: &metav1.Preconditions{ResourceVersion: &rv}}) + if !apierrors.IsConflict(err) { + t.Fatalf("delete with stale resourceVersion %q: got %v, want Conflict", rv, err) + } + if err := f.live.Get(context.Background(), rvReleaseKey, &helmv2.HelmRelease{}); err != nil { + t.Fatalf("release gone after a rejected delete: %v", err) + } +} + +func TestCheckResourceVersion(t *testing.T) { + r := newTestRESTWithSchemesFromClient(nil) + for _, tc := range []struct { + caller string + check func(error) bool + }{ + {"100", func(err error) bool { return err == nil }}, + {"101", func(err error) bool { return err == nil }}, + {"99", apierrors.IsConflict}, + {"0", apierrors.IsConflict}, + {"", apierrors.IsBadRequest}, + {"abc", apierrors.IsBadRequest}, + } { + if err := r.checkResourceVersion("mydb", tc.caller, "100"); !tc.check(err) { + t.Errorf("caller resourceVersion %q against live 100: unexpected result %v", tc.caller, err) + } + } +} + +func TestNewerResourceVersion(t *testing.T) { + for _, tc := range []struct{ a, b, want string }{ + {"7", "5", "7"}, + {"5", "7", "7"}, + {"7", "7", "7"}, + {"x", "5", "5"}, + {"7", "y", "y"}, + } { + if got := newerResourceVersion(tc.a, tc.b); got != tc.want { + t.Errorf("newerResourceVersion(%q, %q) = %q, want %q", tc.a, tc.b, got, tc.want) + } + } +} diff --git a/pkg/registry/apps/application/rest_write_options_test.go b/pkg/registry/apps/application/rest_write_options_test.go index 823a7327c..fd6417c3f 100644 --- a/pkg/registry/apps/application/rest_write_options_test.go +++ b/pkg/registry/apps/application/rest_write_options_test.go @@ -58,7 +58,7 @@ func newOptionsTestREST(t *testing.T, funcs interceptor.Funcs, objects ...client WithObjects(objects...). WithInterceptorFuncs(funcs). Build() - return NewREST(c, nil, &config.Resource{ + return NewREST(c, c, &config.Resource{ Application: config.ApplicationConfig{ Kind: "PostgreSQL", Plural: "postgresqls", @@ -185,7 +185,9 @@ func TestDeletePropagatesWriteOptions(t *testing.T) { grace := int64(3) propagation := metav1.DeletePropagationForeground uid := types.UID("expected-uid") - rv := "17" + // The version the fake client stamps on seeded objects: a resourceVersion + // precondition is checked against the live release. + rv := "999" want := &metav1.DeleteOptions{ GracePeriodSeconds: &grace, Preconditions: &metav1.Preconditions{UID: &uid, ResourceVersion: &rv}, diff --git a/pkg/registry/sdn/securitygroup/rest_test.go b/pkg/registry/sdn/securitygroup/rest_test.go index 5f01242b6..26e3499f2 100644 --- a/pkg/registry/sdn/securitygroup/rest_test.go +++ b/pkg/registry/sdn/securitygroup/rest_test.go @@ -1470,6 +1470,97 @@ func TestCreateRejectsEmptyFQDNSelector(t *testing.T) { } } +func sgWithEgress(name string, eg sdnv1alpha1.EgressRule) *sdnv1alpha1.SecurityGroup { + return &sdnv1alpha1.SecurityGroup{ + ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: testNamespace}, + Spec: sdnv1alpha1.SecurityGroupSpec{ + Attachments: []sdnv1alpha1.ApplicationReference{{Kind: "Postgres", Name: "db"}}, + Egress: []sdnv1alpha1.EgressRule{eg}, + }, + } +} + +// TestCreateRejectsInvalidPortOrFQDN pins the field and the reason of each +// rejection. A port range used to be reported as a malformed port name, and a +// malformed FQDN reached the backing write, where the CiliumNetworkPolicy CRD +// rejected it with an error about an object the tenant never wrote. +func TestCreateRejectsInvalidPortOrFQDN(t *testing.T) { + fqdn := func(sel sdnv1alpha1.FQDNSelector) sdnv1alpha1.EgressRule { + return sdnv1alpha1.EgressRule{ToFQDNs: []sdnv1alpha1.FQDNSelector{sel}} + } + port := func(p string) sdnv1alpha1.EgressRule { + return sdnv1alpha1.EgressRule{ToPorts: []sdnv1alpha1.PortRule{{Ports: []sdnv1alpha1.PortProtocol{{Port: p}}}}} + } + cases := map[string]struct { + rule sdnv1alpha1.EgressRule + field string + detail string + }{ + "port range": {port("80-90"), "spec.egress[0].toPorts[0].ports[0].port", "port ranges are not supported"}, + "full port range": {port("1-65535"), "spec.egress[0].toPorts[0].ports[0].port", "port ranges are not supported"}, + "matchName with space": {fqdn(sdnv1alpha1.FQDNSelector{MatchName: "bad name.example.org"}), "spec.egress[0].toFQDNs[0].matchName", "must be a DNS name"}, + "matchName with wildcard": {fqdn(sdnv1alpha1.FQDNSelector{MatchName: "*.example.org"}), "spec.egress[0].toFQDNs[0].matchName", "must be a DNS name"}, + "matchName with leading dot": {fqdn(sdnv1alpha1.FQDNSelector{MatchName: ".example.org"}), "spec.egress[0].toFQDNs[0].matchName", "must be a DNS name"}, + "matchName with empty label": {fqdn(sdnv1alpha1.FQDNSelector{MatchName: "example..org"}), "spec.egress[0].toFQDNs[0].matchName", "must be a DNS name"}, + "matchName with scheme": {fqdn(sdnv1alpha1.FQDNSelector{MatchName: "https://example.org"}), "spec.egress[0].toFQDNs[0].matchName", "must be a DNS name"}, + "matchName too long": {fqdn(sdnv1alpha1.FQDNSelector{MatchName: strings.Repeat("a", 256)}), "spec.egress[0].toFQDNs[0].matchName", "may not be more than 255"}, + "matchPattern with slash": {fqdn(sdnv1alpha1.FQDNSelector{MatchPattern: "*.example.org/path"}), "spec.egress[0].toFQDNs[0].matchPattern", "must be a DNS name"}, + "matchPattern with question": {fqdn(sdnv1alpha1.FQDNSelector{MatchPattern: "?.example.org"}), "spec.egress[0].toFQDNs[0].matchPattern", "must be a DNS name"}, + "matchPattern with empty label": {fqdn(sdnv1alpha1.FQDNSelector{MatchPattern: "*..example.org"}), "spec.egress[0].toFQDNs[0].matchPattern", "must be a DNS name"}, + "matchPattern too long": {fqdn(sdnv1alpha1.FQDNSelector{MatchPattern: "*." + strings.Repeat("a", 254)}), "spec.egress[0].toFQDNs[0].matchPattern", "may not be more than 255"}, + "both matchName and pattern": {fqdn(sdnv1alpha1.FQDNSelector{MatchName: "example.org", MatchPattern: "*.example.org"}), "spec.egress[0].toFQDNs[0]", "only one of matchName or matchPattern"}, + } + for name, tc := range cases { + t.Run(name, func(t *testing.T) { + r := newTestREST(t) + _, err := r.Create(ctxNS(), sgWithEgress("sg-bad", tc.rule), nil, &metav1.CreateOptions{}) + var status apierrors.APIStatus + if !apierrors.IsInvalid(err) || !errors.As(err, &status) { + t.Fatalf("Create with %s: got err %v, want Invalid", name, err) + } + causes := status.Status().Details.Causes + if len(causes) != 1 || causes[0].Field != tc.field || !strings.Contains(causes[0].Message, tc.detail) { + t.Fatalf("Create with %s: causes = %+v, want one on %s containing %q", name, causes, tc.field, tc.detail) + } + np := &CiliumNetworkPolicy{} + if err := r.c.Get(context.Background(), types.NamespacedName{Namespace: testNamespace, Name: "sg-bad"}, np); !apierrors.IsNotFound(err) { + t.Fatalf("invalid SecurityGroup was persisted: err=%v", err) + } + }) + } +} + +func TestCreateAcceptsValidPortOrFQDN(t *testing.T) { + cases := map[string]sdnv1alpha1.EgressRule{ + "single port": {ToPorts: []sdnv1alpha1.PortRule{{Ports: []sdnv1alpha1.PortProtocol{{Port: "8080"}}}}}, + "named port with digits": {ToPorts: []sdnv1alpha1.PortRule{{Ports: []sdnv1alpha1.PortProtocol{{Port: "http-8080"}}}}}, + "matchName": {ToFQDNs: []sdnv1alpha1.FQDNSelector{{MatchName: "api.example.org"}}}, + "matchName with trailing dot": {ToFQDNs: []sdnv1alpha1.FQDNSelector{{MatchName: "api.example.org."}}}, + "matchName with underscore": {ToFQDNs: []sdnv1alpha1.FQDNSelector{{MatchName: "_sip._tcp.example.org"}}}, + "matchName single label": {ToFQDNs: []sdnv1alpha1.FQDNSelector{{MatchName: "localhost"}}}, + "matchName at max length": {ToFQDNs: []sdnv1alpha1.FQDNSelector{{MatchName: strings.Repeat("a", 255)}}}, + "matchPattern subdomain": {ToFQDNs: []sdnv1alpha1.FQDNSelector{{MatchPattern: "*.example.org"}}}, + "matchPattern multilevel": {ToFQDNs: []sdnv1alpha1.FQDNSelector{{MatchPattern: "**.example.org"}}}, + "matchPattern infix": {ToFQDNs: []sdnv1alpha1.FQDNSelector{{MatchPattern: "sub*.example.org"}}}, + "matchPattern match all": {ToFQDNs: []sdnv1alpha1.FQDNSelector{{MatchPattern: "*"}}}, + } + for name, rule := range cases { + t.Run(name, func(t *testing.T) { + r := newTestREST(t) + if _, err := r.Create(ctxNS(), sgWithEgress("sg-ok", rule), nil, &metav1.CreateOptions{}); err != nil { + t.Fatalf("Create with %s returned error: %v", name, err) + } + np := &CiliumNetworkPolicy{} + if err := r.c.Get(context.Background(), types.NamespacedName{Namespace: testNamespace, Name: "sg-ok"}, np); err != nil { + t.Fatalf("backing policy not found: %v", err) + } + if got := np.Spec.Egress[0]; !reflect.DeepEqual(got.ToFQDNs, rule.ToFQDNs) || !reflect.DeepEqual(got.ToPorts, rule.ToPorts) { + t.Fatalf("egress rule not projected 1:1: got %+v, want %+v", got, rule) + } + }) + } +} + // TestCreateRejectsNamespaceMismatch asserts Create rejects a SecurityGroup // whose metadata.namespace differs from the request namespace, so a caller // cannot post to one namespace and persist into another. The aggregated diff --git a/pkg/registry/sdn/securitygroup/validate.go b/pkg/registry/sdn/securitygroup/validate.go index 4aa37f765..172a21887 100644 --- a/pkg/registry/sdn/securitygroup/validate.go +++ b/pkg/registry/sdn/securitygroup/validate.go @@ -5,6 +5,7 @@ package securitygroup import ( "net/netip" + "regexp" "strconv" "strings" @@ -19,6 +20,21 @@ import ( // An empty protocol defaults to ANY and is allowed. var validProtocols = map[string]struct{}{"TCP": {}, "UDP": {}, "SCTP": {}, "ANY": {}} +// The FQDN rules of the cilium.io/v2 CiliumNetworkPolicy CRD +// (spec.egress[].toFQDNs[]). The API server enforces them on the backing +// write, so a value they reject must be caught here to fail on the +// SecurityGroup path rather than with a CiliumNetworkPolicy schema error. +var ( + fqdnMatchNameRE = regexp.MustCompile(`^([-a-zA-Z0-9_]+[.]?)+$`) + fqdnMatchPatternRE = regexp.MustCompile(`^([-a-zA-Z0-9_*]+[.]?)+$`) +) + +const fqdnMaxLength = 255 + +// portRangeRE matches a "first-last" port range, which PortProtocol cannot +// express: it carries a single port, and Cilium's endPort is not exposed. +var portRangeRE = regexp.MustCompile(`^[0-9]+-[0-9]+$`) + // reservedEntities are Cilium's built-in entity names. They stay // platform-managed and are deliberately not tenant-expressible — a SecurityGroup // reaches external destinations through CIDR/FQDN, not entities — so the API @@ -158,13 +174,33 @@ func validateCIDRs(path *field.Path, cidrs []string) field.ErrorList { func validateFQDNs(path *field.Path, fqdns []sdnv1alpha1.FQDNSelector) field.ErrorList { var errs field.ErrorList for i := range fqdns { - if fqdns[i].MatchName == "" && fqdns[i].MatchPattern == "" { + name, pattern := fqdns[i].MatchName, fqdns[i].MatchPattern + switch { + case name == "" && pattern == "": errs = append(errs, field.Required(path.Index(i), "must set matchName or matchPattern")) + case name != "" && pattern != "": + errs = append(errs, field.Forbidden(path.Index(i), "must set only one of matchName or matchPattern")) + case name != "": + errs = append(errs, validateFQDNValue(path.Index(i).Child("matchName"), name, fqdnMatchNameRE, + "must be a DNS name made of letters, digits, '-', '_' and single '.' separators")...) + default: + errs = append(errs, validateFQDNValue(path.Index(i).Child("matchPattern"), pattern, fqdnMatchPatternRE, + "must be a DNS name made of letters, digits, '-', '_', '*' and single '.' separators")...) } } return errs } +func validateFQDNValue(path *field.Path, value string, re *regexp.Regexp, msg string) field.ErrorList { + if len(value) > fqdnMaxLength { + return field.ErrorList{field.TooLong(path, value, fqdnMaxLength)} + } + if !re.MatchString(value) { + return field.ErrorList{field.Invalid(path, value, msg)} + } + return nil +} + func validatePortRules(path *field.Path, rules []sdnv1alpha1.PortRule) field.ErrorList { var errs field.ErrorList for i := range rules { @@ -177,6 +213,8 @@ func validatePortRules(path *field.Path, rules []sdnv1alpha1.PortRule) field.Err if n < 1 || n > 65535 { errs = append(errs, field.Invalid(pPath.Child("port"), pp.Port, "port number must be between 1 and 65535")) } + } else if portRangeRE.MatchString(pp.Port) { + errs = append(errs, field.Invalid(pPath.Child("port"), pp.Port, "port ranges are not supported; list each port as its own entry")) } else { for _, msg := range validation.IsValidPortName(pp.Port) { errs = append(errs, field.Invalid(pPath.Child("port"), pp.Port, msg))