fix(backport): batch for release-1.6, 2026-11-13 (#5312)

## What this PR does

Backports to `release-1.6` from `main`, picked by the rules of the
[backport
policy](https://github.com/cozystack/cozystack/blob/main/docs/release/backports.md)
in merge order. A merged pull request comes as its own commits, picked
with `git cherry-pick -x` so each keeps its author, message and
sign-offs, and a merge commit that carries the original's merge message
with a `Backported-from:` trailer naming it; a squash-merged one comes
as one pick. `backport-batch verify` checks that shape. A pick listed as
changed differs from the commit it came from, and its release note waits
under Check these notes. A conflict or a failing check here is a
[backport
task](https://github.com/cozystack/cozystack/blob/main/docs/release/backport-tasks/README.md).

- [#3633](https://github.com/cozystack/cozystack/pull/3633)
`fix(tenant): retry failed monitoring and gateway installs in place`, 1
commit
- [#4095](https://github.com/cozystack/cozystack/pull/4095)
`fix(harbor): give the nginx proxy explicit resources so it survives the
tenant LimitRange`, 1 commit
- [#4289](https://github.com/cozystack/cozystack/pull/4289)
`fix(bucket): stop the ACME cleanup hook from talking to localhost, and
gate the class`, 1 commit
- [#4427](https://github.com/cozystack/cozystack/pull/4427)
`fix(monitoring): give kube-apiserver its own scrape size limit`, 3
commits
- [#4537](https://github.com/cozystack/cozystack/pull/4537)
`fix(mariadb): correct webhook cert-manager override key path`, 1 commit
- [#4673](https://github.com/cozystack/cozystack/pull/4673)
`fix(backups): create no driver object for a job that already finished`,
2 commits, changed in the pick: `c7dc37258041`
- [#5025](https://github.com/cozystack/cozystack/pull/5025)
`test(harbor): pin the resources of the nginx proxy and the portal`, 2
commits
- [#4985](https://github.com/cozystack/cozystack/pull/4985) `fix(etcd):
stop counting canceled watch streams as failed gRPC requests`, 1 commit
- [#5005](https://github.com/cozystack/cozystack/pull/5005)
`fix(tcp-balancer): cap HAProxy fds and threads by the pod's own
limits`, 1 commit
- [#5086](https://github.com/cozystack/cozystack/pull/5086)
`fix(tenant): stop the gateway release waiting on TenantGateway
listeners and certificates`, 1 commit
- [#5087](https://github.com/cozystack/cozystack/pull/5087)
`fix(controller): carry healthCheckExprs and waitStrategy to existing
releases`, 1 commit
- [#4004](https://github.com/cozystack/cozystack/pull/4004)
`fix(dashboard): link a tenant row to its detail page`, 2 commits,
changed in the pick: `663cf9edf85f`
- [#5212](https://github.com/cozystack/cozystack/pull/5212)
`fix(cilium): pass the CiliumNode list to jq on stdin in the IPAM hook`,
1 commit
- [#5213](https://github.com/cozystack/cozystack/pull/5213)
`fix(kubernetes): move the OIDC users out of the bootstrap Job's
script`, 1 commit
- [#5208](https://github.com/cozystack/cozystack/pull/5208)
`fix(clickhouse): restore the archive a Backup was taken as`, 3 commits
- [#5091](https://github.com/cozystack/cozystack/pull/5091)
`fix(postgres): render the declared databases in a stable order`, 1
commit
- [#5123](https://github.com/cozystack/cozystack/pull/5123)
`fix(mariadb-operator): derive the cluster name from the platform
domain`, 2 commits
- [#5124](https://github.com/cozystack/cozystack/pull/5124)
`fix(lineage, kubernetes): resolve CAPK node VMs to their cluster`, 2
commits, changed in the pick: `9ca427589e57`
- [#5184](https://github.com/cozystack/cozystack/pull/5184) `fix(api):
read pool usage under the quota key the controller counts`, 1 commit
- [#5190](https://github.com/cozystack/cozystack/pull/5190)
`fix(platform): remove the dead registries value and patch-containerd
Secret`, 2 commits
- [#5207](https://github.com/cozystack/cozystack/pull/5207)
`fix(mariadb): fail backup and restore jobs whose operator Job failed`,
5 commits
- [#5024](https://github.com/cozystack/cozystack/pull/5024)
`fix(kubernetes, monitoring): send tenant cluster metrics to the
tenant's vminsert`, 1 commit
- [#5284](https://github.com/cozystack/cozystack/pull/5284)
`fix(seaweedfs): bump the COSI driver to v0.4.0 for the lost-grant fix`,
1 commit
- [#5152](https://github.com/cozystack/cozystack/pull/5152)
`fix(monitoring-agents): let the release uninstall when the
VictoriaMetrics operator is gone first`, 1 commit
- [#5270](https://github.com/cozystack/cozystack/pull/5270)
`fix(vm-instance): keep an external PortList VM valid with no ports`, 1
commit
- [#5280](https://github.com/cozystack/cozystack/pull/5280)
`fix(backups): give the barman-cloud sidecar an explicit CPU limit`, 1
commit
- [#5100](https://github.com/cozystack/cozystack/pull/5100) `fix(etcd):
size the defrag job for the client it runs`, 1 commit
- [#5094](https://github.com/cozystack/cozystack/pull/5094)
`fix(monitoring): select the vmalert Service the operator creates`, 1
commit
- [#5250](https://github.com/cozystack/cozystack/pull/5250)
`fix(ingress-nginx): raise client keepalive_time above the 1h default`,
1 commit
- [#5102](https://github.com/cozystack/cozystack/pull/5102)
`fix(monitoring-agents): make a silent Watchdog an alarm in Alerta`, 1
commit
- [#4948](https://github.com/cozystack/cozystack/pull/4948)
`fix(monitoring): route InfoInhibitor to the blackhole receiver`, 2
commits
- [#5098](https://github.com/cozystack/cozystack/pull/5098)
`fix(vertical-pod-autoscaler): run two admission controllers spread over
nodes`, 2 commits
- [#5119](https://github.com/cozystack/cozystack/pull/5119)
`fix(postgres): accept a standard five-field backup schedule`, 2
commits, changed in the pick: `600a268351c7`
- [#4993](https://github.com/cozystack/cozystack/pull/4993)
`feat(monitoring): alert when pods of one workload share a node`, 1
commit
- [#5114](https://github.com/cozystack/cozystack/pull/5114)
`fix(kubevirt): let tenant admins upload a VMDisk image with virtctl`, 1
commit
- [#4963](https://github.com/cozystack/cozystack/pull/4963)
`fix(piraeus-operator): keep the LINSTOR error-report alerts quiet when
the controller pod moves`, 1 commit
- [#4946](https://github.com/cozystack/cozystack/pull/4946)
`fix(keycloak, foundationdb): apply operator CRD updates on upgrade`, 2
commits
- [#4965](https://github.com/cozystack/cozystack/pull/4965)
`fix(tcp-balancer): render the kubernetes and talos Service ports only
with kubernetesAndTalos`, 1 commit
- [#5242](https://github.com/cozystack/cozystack/pull/5242) `fix(vpa):
shorten the admission webhook timeout to 5s`, 2 commits
- [#5265](https://github.com/cozystack/cozystack/pull/5265)
`fix(controller, platform): give unbounded pool members the root's
LimitRange`, 3 commits
- [#5183](https://github.com/cozystack/cozystack/pull/5183) `fix(etcd):
scope tenant alerts to their scrape job`, 1 commit
- [#5189](https://github.com/cozystack/cozystack/pull/5189)
`fix(cozy-lib): render tenant hugepages quota only as requests`, 1
commit
- [#4893](https://github.com/cozystack/cozystack/pull/4893)
`fix(seaweedfs): keep Object Lock working for COSI credentials on
SeaweedFS 4.48`, 2 commits
- [#4915](https://github.com/cozystack/cozystack/pull/4915)
`fix(seaweedfs): remove identities left behind by deleted
BucketAccesses`, 1 commit, changed in the pick: `9d15a98369ec`
- [#4896](https://github.com/cozystack/cozystack/pull/4896)
`fix(kamaji): drop kubelet config fields older tenants do not know`, 1
commit
- [#5364](https://github.com/cozystack/cozystack/pull/5364)
`fix(backups): delete the Velero backup of a failed BackupJob`, 4
commits, changed in the pick: `9967676a6841`
- [#5373](https://github.com/cozystack/cozystack/pull/5373)
`fix(opensearch): disable the Base64 intrinsics hit by CVE-2026-114938`,
1 commit, changed in the pick: `330e8c516fb8`
- [#5340](https://github.com/cozystack/cozystack/pull/5340)
`fix(qdrant): scrape TLS metrics over HTTPS`, 1 commit
- [#5331](https://github.com/cozystack/cozystack/pull/5331)
`fix(kubernetes): remove cilium dependency from coredns HelmRelease`, 1
commit
- [#5134](https://github.com/cozystack/cozystack/pull/5134)
`fix(securitygroups): reject port ranges and malformed FQDNs on the
SecurityGroup path`, 2 commits
- [#4984](https://github.com/cozystack/cozystack/pull/4984)
`fix(postgres): keep users.app's password across pod restarts`, 1 commit
- [#5160](https://github.com/cozystack/cozystack/pull/5160)
`fix(linstor): roll affinity controller and scheduler on client cert
rotation`, 1 commit
- [#5358](https://github.com/cozystack/cozystack/pull/5358)
`fix(linstor): run the NFS server wait init container on the platform
CSI image`, 1 commit
- [#5326](https://github.com/cozystack/cozystack/pull/5326) `fix(api):
make monitor watch versions usable as delete preconditions`, 4 commits
- [#5348](https://github.com/cozystack/cozystack/pull/5348) `fix(api):
validate workload memory before storing an application`, 1 commit
- [#5392](https://github.com/cozystack/cozystack/pull/5392)
`fix(harbor): meter the registry bucket under the registry
WorkloadMonitor`, 1 commit
- [#5403](https://github.com/cozystack/cozystack/pull/5403)
`fix(platform): bump system PostgreSQL to 17.12`, 1 commit
- [#4797](https://github.com/cozystack/cozystack/pull/4797)
`fix(cozystack-basics): make the tenant super-admin VirtualMachine grant
read-only`, 1 commit
- [#5407](https://github.com/cozystack/cozystack/pull/5407)
`fix(ingress-nginx): turn off TLS session tickets for CVE-2026-97629`, 1
commit
- [#5210](https://github.com/cozystack/cozystack/pull/5210)
`fix(platform): do not gate cert-manager-issuers on ClusterIssuer
readiness`, 1 commit, changed in the pick: `9061f9a5e1a1`
- [#5443](https://github.com/cozystack/cozystack/pull/5443)
`fix(ingress): restore visitor IPs through SSL passthrough`, 2 commits

### Check these notes

These picks differ from their originals, so their release notes are left
out of the release-note block until someone checks that each still holds
for this line. Each comes with what to compare: every pick that differs
against the commit it came from, and the original's change against the
unit's.

[#4673](https://github.com/cozystack/cozystack/pull/4673) `fix(backups):
create no driver object for a job that already finished`, carried by
`4eb480d83bbf`:

```text
fix(backups): a BackupJob or RestoreJob that the controller has just marked Failed no longer gets a driver object created for it by the next reconcile, which could start on a cache that had not yet seen the Failed status and retry the step that failed — leaving, for instance, an untracked Velero Backup behind a Failed BackupJob, or a restore that halts the VM after its RestoreJob failed.
```

- `git range-diff --creation-factor=999 eafa441b9c36^! c7dc37258041^!`
- `git diff b1192bfcbcf4^1 b1192bfcbcf4`
- `git diff 4eb480d83bbf^1 4eb480d83bbf`

[#4004](https://github.com/cozystack/cozystack/pull/4004)
`fix(dashboard): link a tenant row to its detail page`, carried by
`19693538013e`:

```text
fix(dashboard): tenant name in the tenant list links to its detail page now (where Delete is), and top level tenants get their Edit button back.
```

- `git range-diff --creation-factor=999 7f55ff5d85fd^! 663cf9edf85f^!`
- `git diff a2cc9a30168f^1 a2cc9a30168f`
- `git diff 19693538013e^1 19693538013e`

[#5124](https://github.com/cozystack/cozystack/pull/5124) `fix(lineage,
kubernetes): resolve CAPK node VMs to their cluster`, carried by
`529b3b67295e`:

```text
fix(lineage, kubernetes): the virt-launcher pods of Kubernetes worker nodes are now resolved to their Kubernetes application and marked as managed by Cozystack, so a SecurityGroup attached to a Kubernetes cluster now applies to its worker nodes, not only to its control plane.
```

- `git range-diff --creation-factor=999 93faa7a8620d^! 9ca427589e57^!`
- `git diff 1f35c26ece02^1 1f35c26ece02`
- `git diff 529b3b67295e^1 529b3b67295e`

[#5119](https://github.com/cozystack/cozystack/pull/5119)
`fix(postgres): accept a standard five-field backup schedule`, carried
by `d54b11f14f0c`:

```text
fix(postgres): backup.schedule accepts a standard five-field cron such as 0 2 * * *, and the chart prepends a 0 seconds field before handing it to CloudNativePG, which reads the first field as seconds. Six-field values and descriptors render as before, and any other field count fails the render. A release that already sets five fields gets the standard meaning on upgrade, so 0 2 * * * moves from hourly to daily.
```

- `git range-diff --creation-factor=999 982db83dd22d^! 600a268351c7^!`
- `git diff 5fe356f57e8a^1 5fe356f57e8a`
- `git diff d54b11f14f0c^1 d54b11f14f0c`

[#4915](https://github.com/cozystack/cozystack/pull/4915)
`fix(seaweedfs): remove identities left behind by deleted
BucketAccesses`, carried by `ccdaa7779174`:

```text
fix(seaweedfs): remove S3 identities left behind by deleted BucketAccesses on install and upgrade. The new cosi.orphanIdentities value (auto, report, delete) controls it; auto only reports on a filer published to Client-topology clusters.
```

- `git range-diff --creation-factor=999 045f1a9bbc64^! 9d15a98369ec^!`
- `git diff 15e87fdbeaa1^1 15e87fdbeaa1`
- `git diff ccdaa7779174^1 ccdaa7779174`

[#5364](https://github.com/cozystack/cozystack/pull/5364) `fix(backups):
delete the Velero backup of a failed BackupJob`, carried by
`6b310132a6e1`:

```text
fix(backups): a BackupJob whose Velero backup ends Failed, PartiallyFailed or FailedValidation now asks Velero to delete that backup and its data in the bucket, instead of leaving them until Velero's TTL expires. A Velero backup that completed is never deleted this way. If Velero cannot carry out the deletion (for example, the backup storage location is missing, read-only or unavailable), the BackupJob gets a `VeleroBackupDeletionFailed` Warning event with Velero's errors, and the deletion is retried at a growing interval of up to one hour. After upgrading, the Velero backups of BackupJobs that already failed are deleted as well; to keep one for a manual `velero restore`, copy it before the upgrade. The backupstrategy-controller ClusterRole gains `delete` on `deletebackuprequests`.
```

- `git range-diff --creation-factor=999 5fbf7e9a3806^! 9967676a6841^!`
- `git diff 7f31011b99a2^1 7f31011b99a2`
- `git diff 6b310132a6e1^1 6b310132a6e1`

[#5373](https://github.com/cozystack/cozystack/pull/5373)
`fix(opensearch): disable the Base64 intrinsics hit by CVE-2026-114938`,
carried by `2fab06097342`:

```text
fix(opensearch): mitigate CVE-2026-114938 (Java4Shell) by starting OpenSearch nodes with -XX:-UseBASE64Intrinsics, which disables the vulnerable OpenJDK Base64 decoder. Every OpenSearch cluster restarts once on upgrade.
```

- `git range-diff --creation-factor=999 65f094371015^! 330e8c516fb8^!`
- `git diff 026b0156355a^1 026b0156355a`
- `git diff 2fab06097342^1 2fab06097342`

[#5210](https://github.com/cozystack/cozystack/pull/5210)
`fix(platform): do not gate cert-manager-issuers on ClusterIssuer
readiness`, carried by `150d36e0f65c`:

```text
fix(platform): the cert-manager-issuers release no longer waits for ClusterIssuers to become Ready, so an unreachable ACME endpoint (staging included) does not hold other platform packages in DependencyNotReady.
```

- `git range-diff --creation-factor=999 13fefcedda13^! 9061f9a5e1a1^!`
- `git diff a1be486fb6fd^1 a1be486fb6fd`
- `git diff 150d36e0f65c^1 150d36e0f65c`

### Parked

These cannot land on `release-1.6` whole, so the batch does not pick
them: each would leave part of it without effect there, or builds on a
change that never reaches the line. A maintainer ports what applies as a
pull request of its own, or drops the original with `backport-batch run
--drop`; `backport/include` does not lift a park.

- [#5071](https://github.com/cozystack/cozystack/pull/5071)
`fix(marketplace): do not install a connected repository's components on
connect`: builds on
[#3940](https://github.com/cozystack/cozystack/pull/3940),
[#4308](https://github.com/cozystack/cozystack/pull/4308), which never
reaches this line
- [#5088](https://github.com/cozystack/cozystack/pull/5088)
`fix(ingress-nginx): drop the admission-webhook policy a rebase brought
back`: only part of it applies; it would leave
`packages/system/ingress-nginx/templates/admission-webhook-networkpolicy.yaml`,
`packages/system/ingress-nginx/tests/admission_webhook_networkpolicy_test.yaml`
without effect
- [#4917](https://github.com/cozystack/cozystack/pull/4917)
`fix(kubernetes): run Proxmox CCM v0.16.1 and pin the Proxmox images by
digest`: builds on
[#4089](https://github.com/cozystack/cozystack/pull/4089), which never
reaches this line
- [#4974](https://github.com/cozystack/cozystack/pull/4974)
`fix(kubernetes-nodes): plan autoscaler capacity on the cores the VM
actually gets`: builds on
[#3315](https://github.com/cozystack/cozystack/pull/3315),
[#4386](https://github.com/cozystack/cozystack/pull/4386), which never
reaches this line
- [#4971](https://github.com/cozystack/cozystack/pull/4971) `fix(e2e):
keep the Proxmox tenant kubeconfig per run and remove it`: builds on
[#4089](https://github.com/cozystack/cozystack/pull/4089), which never
reaches this line
- [#4970](https://github.com/cozystack/cozystack/pull/4970) `fix(e2e):
read the KubernetesNodes pool release in the HelmRelease guard`: builds
on [#3594](https://github.com/cozystack/cozystack/pull/3594), which
never reaches this line
- [#4972](https://github.com/cozystack/cozystack/pull/4972) `fix(e2e):
validate the leak allowlist against every suite layout`: builds on
[#4492](https://github.com/cozystack/cozystack/pull/4492),
[#4658](https://github.com/cozystack/cozystack/pull/4658),
[#4713](https://github.com/cozystack/cozystack/pull/4713), which never
reaches this line
- [#5082](https://github.com/cozystack/cozystack/pull/5082)
`fix(marketplace): pin a tapped repository to a digest instead of a
mutable tag`: builds on
[#3940](https://github.com/cozystack/cozystack/pull/3940), which never
reaches this line
- [#5230](https://github.com/cozystack/cozystack/pull/5230)
`fix(backups): re-render the default backup objects when the S3 endpoint
changes`: builds on
[#3562](https://github.com/cozystack/cozystack/pull/3562),
[#3990](https://github.com/cozystack/cozystack/pull/3990),
[#3992](https://github.com/cozystack/cozystack/pull/3992),
[#4000](https://github.com/cozystack/cozystack/pull/4000),
[#4929](https://github.com/cozystack/cozystack/pull/4929), which never
reaches this line
- [#5133](https://github.com/cozystack/cozystack/pull/5133)
`fix(securitygroups): project a membership-only group to a policy Cilium
accepts`: builds on
[#4447](https://github.com/cozystack/cozystack/pull/4447), which never
reaches this line
- [#5151](https://github.com/cozystack/cozystack/pull/5151) `fix(redis):
run one Sentinel when Redis runs a single pod`: builds on
[#4832](https://github.com/cozystack/cozystack/pull/4832), which never
reaches this line
- [#5211](https://github.com/cozystack/cozystack/pull/5211)
`fix(postgres): fail a backup job as soon as its cnpg Backup fails`:
builds on [#4674](https://github.com/cozystack/cozystack/pull/4674),
which never reaches this line
- [#5226](https://github.com/cozystack/cozystack/pull/5226)
`fix(platform): leave tenant-root's ingress empty when the root tenant
has none`: builds on
[#3280](https://github.com/cozystack/cozystack/pull/3280), which never
reaches this line
- [#5228](https://github.com/cozystack/cozystack/pull/5228)
`fix(seaweedfs): enforce S3 bucket lifecycle rules`: builds on
[#3562](https://github.com/cozystack/cozystack/pull/3562),
[#3580](https://github.com/cozystack/cozystack/pull/3580), which never
reaches this line
- [#5308](https://github.com/cozystack/cozystack/pull/5308)
`fix(seaweedfs): stop the master crashing on the crowded volume map`:
builds on [#4819](https://github.com/cozystack/cozystack/pull/4819),
which never reaches this line
- [#4986](https://github.com/cozystack/cozystack/pull/4986) `fix(etcd):
require an even spread of members over nodes by default`: builds on
[#3962](https://github.com/cozystack/cozystack/pull/3962),
[#3964](https://github.com/cozystack/cozystack/pull/3964), which never
reaches this line
- [#5249](https://github.com/cozystack/cozystack/pull/5249)
`fix(kubernetes): detach volumes when the infra PVC is missing`: builds
on [#4447](https://github.com/cozystack/cozystack/pull/4447), which
never reaches this line
- [#4234](https://github.com/cozystack/cozystack/pull/4234)
`fix(seaweedfs, cozy-lib): cap the Go heap so components survive their
memory limit`: builds on
[#5228](https://github.com/cozystack/cozystack/pull/5228), which never
reaches this line
- [#5096](https://github.com/cozystack/cozystack/pull/5096)
`fix(workloadmonitor): report a bucket's workloads not ready until its
claim is provisioned`: builds on
[#4380](https://github.com/cozystack/cozystack/pull/4380), which never
reaches this line
- [#4945](https://github.com/cozystack/cozystack/pull/4945) `fix(apps):
keep Job and CronJob names within the Kubernetes limits`: builds on
[#2352](https://github.com/cozystack/cozystack/pull/2352), which never
reaches this line
- [#5011](https://github.com/cozystack/cozystack/pull/5011)
`fix(cozystack-basics): refuse a direct delete of a tenant namespace`:
builds on [#4639](https://github.com/cozystack/cozystack/pull/4639),
which never reaches this line
- [#5329](https://github.com/cozystack/cozystack/pull/5329) `fix(ci):
take main's ref for a bare first-party image ref in a drifted file`:
builds on [#4261](https://github.com/cozystack/cozystack/pull/4261),
[#4756](https://github.com/cozystack/cozystack/pull/4756), which never
reaches this line
- [#5153](https://github.com/cozystack/cozystack/pull/5153)
`fix(kubernetes): bring up a replacement worker before draining the old
one`: builds on
[#3280](https://github.com/cozystack/cozystack/pull/3280),
[#3315](https://github.com/cozystack/cozystack/pull/3315),
[#4713](https://github.com/cozystack/cozystack/pull/4713), which never
reaches this line
- [#5175](https://github.com/cozystack/cozystack/pull/5175) `fix(tests):
reject matcher failures in negative file assertions`: builds on
[#3548](https://github.com/cozystack/cozystack/pull/3548),
[#3637](https://github.com/cozystack/cozystack/pull/3637),
[#3676](https://github.com/cozystack/cozystack/pull/3676),
[#3723](https://github.com/cozystack/cozystack/pull/3723),
[#3804](https://github.com/cozystack/cozystack/pull/3804),
[#3836](https://github.com/cozystack/cozystack/pull/3836),
[#3843](https://github.com/cozystack/cozystack/pull/3843),
[#3886](https://github.com/cozystack/cozystack/pull/3886),
[#3888](https://github.com/cozystack/cozystack/pull/3888),
[#3889](https://github.com/cozystack/cozystack/pull/3889),
[#3890](https://github.com/cozystack/cozystack/pull/3890),
[#3919](https://github.com/cozystack/cozystack/pull/3919), which never
reaches this line
- [#5377](https://github.com/cozystack/cozystack/pull/5377)
`fix(ingress-nginx): pick up the nginx rebuild with the HTTP/2 CVE
fixes`: builds on
[#4549](https://github.com/cozystack/cozystack/pull/4549), which never
reaches this line
- [#5354](https://github.com/cozystack/cozystack/pull/5354)
`fix(platform): honour a bool false in ingress-enabled and
monitoring-enabled`: builds on
[#5226](https://github.com/cozystack/cozystack/pull/5226), which never
reaches this line
- [#5045](https://github.com/cozystack/cozystack/pull/5045) `fix(talos):
bump Talos to v1.14.4 (CVE-2026-99999)`: builds on
[#4552](https://github.com/cozystack/cozystack/pull/4552),
[#4598](https://github.com/cozystack/cozystack/pull/4598), which never
reaches this line
- [#5352](https://github.com/cozystack/cozystack/pull/5352)
`docs(gateway): stop saying the route-hostname policy admits
hostname-less routes`: builds on
[#3861](https://github.com/cozystack/cozystack/pull/3861), which never
reaches this line
- [#5356](https://github.com/cozystack/cozystack/pull/5356)
`fix(seaweedfs): point the Lance catalog consumers at the renamed s3
Service`: builds on
[#4079](https://github.com/cozystack/cozystack/pull/4079), which never
reaches this line
- [#5357](https://github.com/cozystack/cozystack/pull/5357) `fix(api):
skip an invalid ApplicationDefinition instead of failing startup`:
builds on [#4424](https://github.com/cozystack/cozystack/pull/4424),
which never reaches this line
- [#5148](https://github.com/cozystack/cozystack/pull/5148)
`fix(gateway): skip a child apex the wildcard certificate already
covers`: builds on
[#3342](https://github.com/cozystack/cozystack/pull/3342), which never
reaches this line
- [#4167](https://github.com/cozystack/cozystack/pull/4167)
`fix(gateway): copy allowed routes for the edge listener`: builds on
[#3861](https://github.com/cozystack/cozystack/pull/3861), which never
reaches this line
- [#4954](https://github.com/cozystack/cozystack/pull/4954)
`fix(tenant): render the LimitRange only under a compute quota`: builds
on [#3494](https://github.com/cozystack/cozystack/pull/3494), which
never reaches this line
- [#5399](https://github.com/cozystack/cozystack/pull/5399)
`fix(kubernetes-nodes): surge one worker at a time during a pool
rollout`: builds on
[#3315](https://github.com/cozystack/cozystack/pull/3315),
[#5153](https://github.com/cozystack/cozystack/pull/5153), which never
reaches this line
- [#5436](https://github.com/cozystack/cozystack/pull/5436)
`fix(ingress-nginx): pick up the nginx rebuild with the remaining CVE
fixes`: builds on
[#5377](https://github.com/cozystack/cozystack/pull/5377), which never
reaches this line
- [#5236](https://github.com/cozystack/cozystack/pull/5236)
`fix(kubernetes): include the namespace in the kubevirt-csi ClusterRole
name`: builds on
[#4563](https://github.com/cozystack/cozystack/pull/4563), which never
reaches this line

### Maintainer overrides

- [#3633](https://github.com/cozystack/cozystack/pull/3633)
`fix(tenant): retry failed monitoring and gateway installs in place`:
`backport/include`, on this branch
- [#4095](https://github.com/cozystack/cozystack/pull/4095)
`fix(harbor): give the nginx proxy explicit resources so it survives the
tenant LimitRange`: `backport/include`, on this branch
- [#4289](https://github.com/cozystack/cozystack/pull/4289)
`fix(bucket): stop the ACME cleanup hook from talking to localhost, and
gate the class`: `backport/include`, on this branch
- [#4427](https://github.com/cozystack/cozystack/pull/4427)
`fix(monitoring): give kube-apiserver its own scrape size limit`:
`backport/include`, on this branch
- [#4537](https://github.com/cozystack/cozystack/pull/4537)
`fix(mariadb): correct webhook cert-manager override key path`:
`backport/include`, on this branch
- [#4673](https://github.com/cozystack/cozystack/pull/4673)
`fix(backups): create no driver object for a job that already finished`:
`backport/include`, on this branch
- [#5025](https://github.com/cozystack/cozystack/pull/5025)
`test(harbor): pin the resources of the nginx proxy and the portal`:
`backport/include`, on this branch
- [#4985](https://github.com/cozystack/cozystack/pull/4985) `fix(etcd):
stop counting canceled watch streams as failed gRPC requests`:
`backport/include`, on this branch
- [#5005](https://github.com/cozystack/cozystack/pull/5005)
`fix(tcp-balancer): cap HAProxy fds and threads by the pod's own
limits`: `backport/include`, on this branch
- [#5083](https://github.com/cozystack/cozystack/pull/5083)
`fix(workloadmonitor): stop doubling the bucket- prefix in bucket
Workload names`: `backport/skip`, left out
- [#4973](https://github.com/cozystack/cozystack/pull/4973)
`fix(kubernetes-nodes): refuse a partial resources spec on every pool`:
`backport/skip`, left out
- [#5180](https://github.com/cozystack/cozystack/pull/5180) `fix(tests):
keep two unit tests green after the release image restamp`:
`backport/skip`, left out
- [#4993](https://github.com/cozystack/cozystack/pull/4993)
`feat(monitoring): alert when pods of one workload share a node`:
`backport/include`, on this branch
- [#5352](https://github.com/cozystack/cozystack/pull/5352)
`docs(gateway): stop saying the route-hostname policy admits
hostname-less routes`: `backport/include`, parked: builds on
[#3861](https://github.com/cozystack/cozystack/pull/3861), which never
reaches this line
- [#4990](https://github.com/cozystack/cozystack/pull/4990) `fix(redis,
valkey, harbor): spread sentinels and data pods over nodes`:
`backport/skip`, left out
- [#4989](https://github.com/cozystack/cozystack/pull/4989)
`fix(monitoring): spread monitoring replicas over nodes`:
`backport/skip`, left out
- [#5393](https://github.com/cozystack/cozystack/pull/5393)
`fix(kubernetes-nodes): label worker disks with the WorkloadMonitor
selector`: `backport/skip`, left out
- [#4817](https://github.com/cozystack/cozystack/pull/4817)
`feat(kubernetes): give each tenant Kubernetes cluster its own etcd`:
`backport/skip`, left out
- [#5407](https://github.com/cozystack/cozystack/pull/5407)
`fix(ingress-nginx): turn off TLS session tickets for CVE-2026-97629`:
`backport/include`, on this branch
- [#5156](https://github.com/cozystack/cozystack/pull/5156)
`fix(kafka)!: require SCRAM-SHA-512 on the external listener`:
`backport/skip`, left out
- [#5186](https://github.com/cozystack/cozystack/pull/5186)
`ci(workflows): run push and schedule workflows only in
cozystack/cozystack`: `backport/skip`, left out
- [#4921](https://github.com/cozystack/cozystack/pull/4921) `feat(api):
add the credentials API with mint and revoke subresources`:
`backport/skip`, left out
- [#5163](https://github.com/cozystack/cozystack/pull/5163)
`docs(release): add the v1.7.0 release notes`: `backport/skip`, left out
- [#5337](https://github.com/cozystack/cozystack/pull/5337)
`feat(kubernetes): run tenant clusters inside a cozyplane VPC`:
`backport/skip`, left out

### Skipped

- Rule 1, merged before `release-1.6` started under the policy on
2026-10-26: 553, too many to list here; the run's output lists them
- Rule 2, the title type is not `fix` or `security`, or the scope is
`deps`: 80, too many to list here; the run's output lists them
- Rule 3, a breaking change: 6
- Rule 4, touches platform migrations, `targetVersion` or a CRD, or
makes a sizeable API change: 3
- Rule 6, not on `release-1.7` yet: 16
- Dropped from `release-1.6` by a maintainer: 5

<details><summary>Rule 3, a breaking change</summary>

- [#5085](https://github.com/cozystack/cozystack/pull/5085)
`fix(kubernetes, opensearch, foundationdb)!: restrict managed
application images`, `! in the title`
- [#4818](https://github.com/cozystack/cozystack/pull/4818)
`fix(keycloak)!: make the KMS proxy keep its keys across restarts`, `!
in the title`
- [#5167](https://github.com/cozystack/cozystack/pull/5167)
`fix(monitoring-agents)!: isolate merged log payload under
log_processed`, `! in the title`
- [#5009](https://github.com/cozystack/cozystack/pull/5009)
`fix(cozy-lib)!: refuse memory below 1Mi instead of rendering a few
bytes`, `! in the title`
- [#5191](https://github.com/cozystack/cozystack/pull/5191)
`fix(kubernetes)!: remove the talos block and other leftovers of the
worker pool split`, `! in the title`
- [#4802](https://github.com/cozystack/cozystack/pull/4802)
`fix(vm-disk, kubernetes-nodes)!: refuse golden images whose import
keeps failing`, `! in the title`

</details>

<details><summary>Rule 4, touches platform migrations, `targetVersion`
or a CRD, or makes a sizeable API change</summary>

- [#5223](https://github.com/cozystack/cozystack/pull/5223)
`fix(backups): report sizeBytes for MariaDB and CNPG backup artifacts`,
`a CRD`
- [#5166](https://github.com/cozystack/cozystack/pull/5166)
`fix(linstor): update piraeus-operator to v2.12.1`, `a CRD`
- [#5430](https://github.com/cozystack/cozystack/pull/5430)
`fix(linstor): gate group snapshots on the v1 group snapshot API`,
`platform migrations`

</details>

<details><summary>Rule 6, not on `release-1.7` yet</summary>

- [#5232](https://github.com/cozystack/cozystack/pull/5232)
`fix(clickhouse): let a running backup sidecar pick up system-bucket
credentials`, `not on release-1.7 yet`
- [#5229](https://github.com/cozystack/cozystack/pull/5229)
`fix(clickhouse): keep failed backup attempts out of the bucket`, `not
on release-1.7 yet`
- [#5221](https://github.com/cozystack/cozystack/pull/5221)
`fix(postgres): stop backup jobs from fighting over the WAL archive
destination`, `not on release-1.7 yet`
- [#5227](https://github.com/cozystack/cozystack/pull/5227)
`fix(mariadb): restore the dump a Backup was taken as`, `not on
release-1.7 yet`
- [#5309](https://github.com/cozystack/cozystack/pull/5309)
`fix(linstor): restore snapshots on a schedulable node`, `not on
release-1.7 yet`
- [#5294](https://github.com/cozystack/cozystack/pull/5294)
`fix(postgres): hold the WAL archive destination for backups no job
tracks`, `not on release-1.7 yet`
- [#5295](https://github.com/cozystack/cozystack/pull/5295)
`fix(postgres): restore from an archive with the access it was written
with`, `not on release-1.7 yet`
- [#5344](https://github.com/cozystack/cozystack/pull/5344)
`fix(backups): stop leaking MariaDB dumps of stuck runs and torn-down
namespaces`, `not on release-1.7 yet`
- [#5375](https://github.com/cozystack/cozystack/pull/5375)
`fix(kubernetes): apply addons.monitoringAgents.valuesOverride`, `not on
release-1.7 yet`
- [#5224](https://github.com/cozystack/cozystack/pull/5224)
`fix(clickhouse): delete the archive when its Backup is deleted`, `not
on release-1.7 yet`
- [#5398](https://github.com/cozystack/cozystack/pull/5398)
`fix(cluster-api): name the kubeconfig the upgrade hook runs with`, `not
on release-1.7 yet`
- [#5415](https://github.com/cozystack/cozystack/pull/5415)
`fix(clickhouse): keep a quota-held archive delete and count a failed
one once`, `not on release-1.7 yet`
- [#5049](https://github.com/cozystack/cozystack/pull/5049)
`fix(kubernetes): bump tenant worker Talos to v1.13.12
(CVE-2026-99999)`, `not on release-1.7 yet`
- [#5426](https://github.com/cozystack/cozystack/pull/5426)
`fix(seaweedfs): stop reserving storage pool name suffixes`, `not on
release-1.7 yet`
- [#5427](https://github.com/cozystack/cozystack/pull/5427)
`fix(kubernetes): stop refusing extraOutputs hooks monitoring-agents
accepts`, `not on release-1.7 yet`
- [#5320](https://github.com/cozystack/cozystack/pull/5320)
`fix(postgres): bound a backup whose cnpg Backup stalls in pending`,
`not on release-1.7 yet`

</details>

<details><summary>Dropped from `release-1.6` by a maintainer</summary>

- [#5142](https://github.com/cozystack/cozystack/pull/5142)
`fix(release): keep release bodies within GitHub's size limit`, `dropped
on #5312: not needed on release-1.6, it ships only patches now and their
changelogs are 8-22 KB, far below release body limit`
- [#5155](https://github.com/cozystack/cozystack/pull/5155)
`fix(postgres): refuse system databases and never drop them`, `dropped
on #5312: builds on init script passes from #4078 and #4574, release-1.6
doesn't have them and #4078 is breaking`
- [#4960](https://github.com/cozystack/cozystack/pull/4960)
`fix(vm-disk): refuse a disk smaller than the golden image it clones`,
`dropped on #5312: builds on golden image checks of #4796, which is
breaking and won't reach release-1.6`
- [#4920](https://github.com/cozystack/cozystack/pull/4920)
`fix(lineage-webhook): keep an explicit tenantresource false`, `dropped
on #5312: its test needs newHandleTestWebhook from #4447, which never
reaches release-1.6`
- [#5405](https://github.com/cozystack/cozystack/pull/5405)
`fix(postgres): move tenant PostgreSQL to patched standard-trixie
images`, `dropped on #5312: reverted on release-1.7 in #5461, comes to
release-1.6 only as the hand port #5433 after #5459 is fixed`

</details>

```backport-batch
{"version":3,"line":"release-1.6","built":{"main":"a2b341e31be2fc4d7c044a4f5ad5239d5f342af6","line":"5de32a56267d6fb8e8c858af0e3b022e2dad0ec0","newer":"d096e1006921674455330a1b498a30a8b1309a67","policy":"a2b341e31be2fc4d7c044a4f5ad5239d5f342af6","batch":"6b310132a6e13e0f7df0fca067e6816e9a660fc1","tool":"fba9fa8278a08150215670406c7e6e63832c9dee","run":"","at":"2026-11-26T16:35:08Z","options":{"noWorkflowFiles":true,"mode":"drop"}},"report":"09ba042bd04aab5f5fe57b593a4959c24b9eee7dac2ab6acaca60a4e61c37759","closing":null,"deferred":[],"dropped":[{"original":4920,"merge":"65cb73e38098a127d9c09bca3cf16d431222696e","reason":"its test needs newHandleTestWebhook from #4447, which never reaches release-1.6","on":5312,"date":"2026-11-26"},{"original":4960,"merge":"a5c58e5e985399a687e5f676a7321f828eda5ff7","reason":"builds on golden image checks of #4796, which is breaking and won't reach release-1.6","on":5312,"date":"2026-11-26"},{"original":5142,"merge":"5c564f9154ddc03387fd4cd6b7a9185b11b0bdb3","reason":"not needed on release-1.6, it ships only patches now and their changelogs are 8-22 KB, far below release body limit","on":5312,"date":"2026-11-25"},{"original":5155,"merge":"b53ca1fedebcc6288856995ada2629c06c9e4ae7","reason":"builds on init script passes from #4078 and #4574, release-1.6 doesn't have them and #4078 is breaking","on":5312,"date":"2026-11-26"},{"original":5405,"merge":"30ce2a3cb1de5b64e629780ef70349608d5cd05d","reason":"reverted on release-1.7 in #5461, comes to release-1.6 only as the hand port #5433 after #5459 is fixed","on":5312,"date":"2026-11-26"}],"stale":[],"parked":[{"original":4167,"merge":"2af1e21299e161041e87d07d21fbfa4d81f97903","kind":"dependency","needs":[3861],"announced":true},{"original":4234,"merge":"df42104b13ff01ca23a5a9f0835530b38824af16","kind":"dependency","needs":[5228],"announced":true},{"original":4917,"merge":"44848b9c9d08f529bbef6e1347c2533a24121406","kind":"dependency","needs":[4089],"announced":true},{"original":4945,"merge":"ea4968cf4613f696cd955bb1f66a7cfd877529ce","kind":"dependency","needs":[2352],"announced":true},{"original":4954,"merge":"94d710e50fe728827cb34c0ff7023c772984d1d0","kind":"dependency","needs":[3494],"announced":true},{"original":4970,"merge":"013b166967e72cdd441e3efde58a4bc1ef75192c","kind":"dependency","needs":[3594],"announced":true},{"original":4971,"merge":"048c029e29607a0b4c5b9e3d9e3b70c76e53bb51","kind":"dependency","needs":[4089],"announced":true},{"original":4972,"merge":"ba0b1ac6ef250048dd33657ff0aca9934900d612","kind":"dependency","needs":[4492,4658,4713],"announced":true},{"original":4974,"merge":"60d1f53e82419ad2138807a54d1045007921d986","kind":"dependency","needs":[3315,4386],"announced":true},{"original":4986,"merge":"e4d059ceddfee96d30dabe3c1a4fade5e18c55cf","kind":"dependency","needs":[3962,3964],"announced":true},{"original":5011,"merge":"29e8522f4b8d2fdef964a8e3f60e1af44fcd08e9","kind":"dependency","needs":[4639],"announced":true},{"original":5045,"merge":"382169be52d15f1a0ae4f3500039e0e8a9beb7fb","kind":"dependency","needs":[4552,4598],"announced":true},{"original":5071,"merge":"7dc5c0b5e63e1a7b7308f8d18adf42cfb900148e","kind":"dependency","needs":[3940,4308],"announced":true},{"original":5082,"merge":"94ada11eefdccc9040db71b710334c878f6bed83","kind":"dependency","needs":[3940],"announced":true},{"original":5088,"merge":"b36628661f60d8076a1122487356406c6d5b86b9","kind":"partial","files":["packages/system/ingress-nginx/templates/admission-webhook-networkpolicy.yaml","packages/system/ingress-nginx/tests/admission_webhook_networkpolicy_test.yaml"],"announced":true},{"original":5096,"merge":"6f8171db8990e5a0c12b216c37877abd0798213e","kind":"dependency","needs":[4380],"announced":true},{"original":5133,"merge":"72ff22dc9ebd51c899f024ebefec111d8a36b7b1","kind":"dependency","needs":[4447],"announced":true},{"original":5148,"merge":"b7e72840f92b15241f8dc451819f3a054e70d84a","kind":"dependency","needs":[3342],"announced":true},{"original":5151,"merge":"23461e065d0fa210c2990122663e7f084f7b2a50","kind":"dependency","needs":[4832],"announced":true},{"original":5153,"merge":"da17254bbc2c739c33c06139e7c2cfb280ae60c5","kind":"dependency","needs":[3280,3315,4713],"announced":true},{"original":5175,"merge":"5a5d5cd3d85fec610516651ab9bc5623a83f62cf","kind":"dependency","needs":[3548,3637,3676,3723,3804,3836,3843,3886,3888,3889,3890,3919]},{"original":5211,"merge":"10e0ef9ece2b7a527c5c2c3fed9bdbecacdb668f","kind":"dependency","needs":[4674],"announced":true},{"original":5226,"merge":"aa97451bc2cec98e9ac04131b9efd2a065983fff","kind":"dependency","needs":[3280],"announced":true},{"original":5228,"merge":"238b3ee491f513302722972b50060e689292f826","kind":"dependency","needs":[3562,3580],"announced":true},{"original":5230,"merge":"9e8e10c307584061f497e9b6506765c0e87b6c91","kind":"dependency","needs":[3562,3990,3992,4000,4929],"announced":true},{"original":5236,"merge":"a2b341e31be2fc4d7c044a4f5ad5239d5f342af6","kind":"dependency","needs":[4563]},{"original":5249,"merge":"e5ab1d6a7e09ff10d92c497a3468c3f9800cff5b","kind":"dependency","needs":[4447],"announced":true},{"original":5308,"merge":"30c4232be19bc1b887228d66e5e0fb8dc508547a","kind":"dependency","needs":[4819],"announced":true},{"original":5329,"merge":"90797d9de977d791d32d16acf7286c848fa6aab2","kind":"dependency","needs":[4261,4756],"announced":true},{"original":5352,"merge":"dec14c736d32cd12798de9af23363469986c7ed4","kind":"dependency","needs":[3861],"announced":true},{"original":5354,"merge":"18a9530b873e557d0198c1b6f2bfeddead746445","kind":"dependency","needs":[5226],"announced":true},{"original":5356,"merge":"4190aa82f5ef93a2bd4edd59a7e1db3f75bc8d01","kind":"dependency","needs":[4079],"announced":true},{"original":5357,"merge":"ec8088e54c719be89fff58fcd17f88950a6cb1a0","kind":"dependency","needs":[4424],"announced":true},{"original":5377,"merge":"d7573c009c482aacfc957954b9c1ae228c844ce7","kind":"dependency","needs":[4549],"announced":true},{"original":5399,"merge":"22843c5c5c204249cf2599ad23abef203d492948","kind":"dependency","needs":[3315,5153],"announced":true},{"original":5436,"merge":"40b4fc6ad4f39d3c449beee2a492fbd7f621b8ba","kind":"dependency","needs":[5377],"announced":true}],"changed":[4004,4673,4915,5119,5124,5210,5364,5373]}
```

```backport-batch-report
{"format":2,"id":"09ba042bd04aab5f5fe57b593a4959c24b9eee7dac2ab6acaca60a4e61c37759","line":"release-1.6","built":{"main":"a2b341e31be2fc4d7c044a4f5ad5239d5f342af6","line":"5de32a56267d6fb8e8c858af0e3b022e2dad0ec0","newer":"d096e1006921674455330a1b498a30a8b1309a67","policy":"a2b341e31be2fc4d7c044a4f5ad5239d5f342af6","batch":"6b310132a6e13e0f7df0fca067e6816e9a660fc1","tool":"fba9fa8278a08150215670406c7e6e63832c9dee","run":"","at":"2026-11-26T16:35:08Z","options":{"noWorkflowFiles":true,"mode":"drop"}},"overrides":{"backport/include":[3633,4095,4289,4427,4537,4673,4985,4993,5005,5025,5352,5407],"backport/skip":[4817,4921,4973,4989,4990,5083,5156,5163,5180,5186,5337,5393]},"primary":{"picked":[3633,4004,4095,4289,4427,4537,4673,4797,4893,4896,4915,4946,4948,4963,4965,4984,4985,4993,5005,5024,5025,5086,5087,5091,5094,5098,5100,5102,5114,5119,5123,5124,5134,5152,5160,5183,5184,5189,5190,5207,5208,5210,5212,5213,5242,5250,5265,5270,5280,5284,5326,5331,5340,5348,5358,5364,5373,5392,5403,5407,5443],"missing":[],"deferred":[],"parked":[{"original":4167,"merge":"2af1e21299e161041e87d07d21fbfa4d81f97903","kind":"dependency","needs":[3861]},{"original":4234,"merge":"df42104b13ff01ca23a5a9f0835530b38824af16","kind":"dependency","needs":[5228]},{"original":4917,"merge":"44848b9c9d08f529bbef6e1347c2533a24121406","kind":"dependency","needs":[4089]},{"original":4945,"merge":"ea4968cf4613f696cd955bb1f66a7cfd877529ce","kind":"dependency","needs":[2352]},{"original":4954,"merge":"94d710e50fe728827cb34c0ff7023c772984d1d0","kind":"dependency","needs":[3494]},{"original":4970,"merge":"013b166967e72cdd441e3efde58a4bc1ef75192c","kind":"dependency","needs":[3594]},{"original":4971,"merge":"048c029e29607a0b4c5b9e3d9e3b70c76e53bb51","kind":"dependency","needs":[4089]},{"original":4972,"merge":"ba0b1ac6ef250048dd33657ff0aca9934900d612","kind":"dependency","needs":[4492,4658,4713]},{"original":4974,"merge":"60d1f53e82419ad2138807a54d1045007921d986","kind":"dependency","needs":[3315,4386]},{"original":4986,"merge":"e4d059ceddfee96d30dabe3c1a4fade5e18c55cf","kind":"dependency","needs":[3962,3964]},{"original":5011,"merge":"29e8522f4b8d2fdef964a8e3f60e1af44fcd08e9","kind":"dependency","needs":[4639]},{"original":5045,"merge":"382169be52d15f1a0ae4f3500039e0e8a9beb7fb","kind":"dependency","needs":[4552,4598]},{"original":5071,"merge":"7dc5c0b5e63e1a7b7308f8d18adf42cfb900148e","kind":"dependency","needs":[3940,4308]},{"original":5082,"merge":"94ada11eefdccc9040db71b710334c878f6bed83","kind":"dependency","needs":[3940]},{"original":5088,"merge":"b36628661f60d8076a1122487356406c6d5b86b9","kind":"partial","files":["packages/system/ingress-nginx/templates/admission-webhook-networkpolicy.yaml","packages/system/ingress-nginx/tests/admission_webhook_networkpolicy_test.yaml"]},{"original":5096,"merge":"6f8171db8990e5a0c12b216c37877abd0798213e","kind":"dependency","needs":[4380]},{"original":5133,"merge":"72ff22dc9ebd51c899f024ebefec111d8a36b7b1","kind":"dependency","needs":[4447]},{"original":5148,"merge":"b7e72840f92b15241f8dc451819f3a054e70d84a","kind":"dependency","needs":[3342]},{"original":5151,"merge":"23461e065d0fa210c2990122663e7f084f7b2a50","kind":"dependency","needs":[4832]},{"original":5153,"merge":"da17254bbc2c739c33c06139e7c2cfb280ae60c5","kind":"dependency","needs":[3280,3315,4713]},{"original":5175,"merge":"5a5d5cd3d85fec610516651ab9bc5623a83f62cf","kind":"dependency","needs":[3548,3637,3676,3723,3804,3836,3843,3886,3888,3889,3890,3919]},{"original":5211,"merge":"10e0ef9ece2b7a527c5c2c3fed9bdbecacdb668f","kind":"dependency","needs":[4674]},{"original":5226,"merge":"aa97451bc2cec98e9ac04131b9efd2a065983fff","kind":"dependency","needs":[3280]},{"original":5228,"merge":"238b3ee491f513302722972b50060e689292f826","kind":"dependency","needs":[3562,3580]},{"original":5230,"merge":"9e8e10c307584061f497e9b6506765c0e87b6c91","kind":"dependency","needs":[3562,3990,3992,4000,4929]},{"original":5236,"merge":"a2b341e31be2fc4d7c044a4f5ad5239d5f342af6","kind":"dependency","needs":[4563]},{"original":5249,"merge":"e5ab1d6a7e09ff10d92c497a3468c3f9800cff5b","kind":"dependency","needs":[4447]},{"original":5308,"merge":"30c4232be19bc1b887228d66e5e0fb8dc508547a","kind":"dependency","needs":[4819]},{"original":5329,"merge":"90797d9de977d791d32d16acf7286c848fa6aab2","kind":"dependency","needs":[4261,4756]},{"original":5352,"merge":"dec14c736d32cd12798de9af23363469986c7ed4","kind":"dependency","needs":[3861]},{"original":5354,"merge":"18a9530b873e557d0198c1b6f2bfeddead746445","kind":"dependency","needs":[5226]},{"original":5356,"merge":"4190aa82f5ef93a2bd4edd59a7e1db3f75bc8d01","kind":"dependency","needs":[4079]},{"original":5357,"merge":"ec8088e54c719be89fff58fcd17f88950a6cb1a0","kind":"dependency","needs":[4424]},{"original":5377,"merge":"d7573c009c482aacfc957954b9c1ae228c844ce7","kind":"dependency","needs":[4549]},{"original":5399,"merge":"22843c5c5c204249cf2599ad23abef203d492948","kind":"dependency","needs":[3315,5153]},{"original":5436,"merge":"40b4fc6ad4f39d3c449beee2a492fbd7f621b8ba","kind":"dependency","needs":[5377]}],"skipped":{"on-line":[],"before-start":[2195,2196,2198,2252,2352,2618,2621,2654,2666,2667,2680,2682,2683,2692,2698,2729,2914,2956,2984,3031,3115,3116,3158,3195,3208,3228,3260,3262,3266,3280,3315,3340,3341,3342,3353,3372,3373,3378,3379,3380,3383,3385,3391,3398,3399,3406,3407,3408,3409,3411,3412,3417,3421,3422,3427,3428,3429,3430,3435,3436,3441,3443,3444,3446,3447,3449,3454,3455,3460,3462,3463,3466,3468,3470,3471,3475,3476,3494,3495,3496,3500,3501,3505,3506,3507,3510,3511,3520,3522,3523,3524,3527,3529,3531,3535,3539,3546,3548,3551,3552,3557,3562,3564,3567,3569,3571,3572,3574,3575,3579,3580,3581,3584,3585,3586,3590,3591,3592,3593,3594,3595,3596,3598,3599,3602,3604,3605,3606,3607,3608,3616,3617,3620,3621,3622,3627,3630,3632,3636,3637,3639,3645,3647,3651,3659,3661,3662,3664,3670,3672,3673,3676,3677,3715,3723,3727,3735,3738,3742,3750,3760,3762,3763,3768,3769,3772,3775,3777,3780,3783,3784,3790,3791,3795,3797,3798,3799,3800,3802,3804,3808,3815,3817,3833,3834,3836,3837,3839,3840,3841,3843,3844,3845,3846,3848,3849,3856,3859,3860,3861,3862,3863,3872,3874,3886,3887,3888,3889,3890,3891,3897,3898,3899,3901,3907,3908,3910,3914,3919,3920,3922,3925,3926,3928,3931,3932,3934,3935,3936,3937,3938,3940,3945,3951,3954,3955,3956,3959,3960,3962,3963,3964,3967,3968,3969,3973,3980,3990,3992,3995,3997,4000,4011,4012,4013,4014,4015,4018,4019,4020,4021,4022,4023,4035,4039,4041,4042,4058,4063,4064,4077,4078,4079,4087,4088,4089,4090,4096,4097,4098,4099,4100,4101,4102,4103,4107,4109,4110,4121,4129,4130,4133,4134,4135,4136,4138,4143,4148,4152,4163,4170,4171,4182,4184,4185,4186,4188,4191,4200,4204,4220,4221,4222,4223,4225,4226,4228,4231,4232,4233,4236,4237,4242,4251,4252,4253,4254,4255,4256,4261,4271,4277,4278,4279,4280,4281,4282,4284,4286,4290,4291,4292,4293,4296,4299,4300,4306,4308,4317,4323,4326,4331,4333,4340,4341,4347,4356,4362,4363,4366,4367,4376,4379,4380,4381,4383,4386,4387,4390,4392,4394,4398,4399,4403,4405,4407,4411,4414,4415,4417,4424,4425,4426,4429,4436,4439,4441,4442,4443,4444,4447,4448,4451,4453,4455,4457,4458,4459,4460,4461,4462,4468,4469,4471,4473,4478,4480,4483,4485,4490,4492,4493,4494,4496,4497,4498,4501,4505,4512,4514,4517,4521,4522,4532,4534,4538,4544,4545,4549,4552,4557,4558,4562,4563,4567,4568,4569,4572,4573,4574,4576,4578,4583,4584,4585,4586,4587,4594,4595,4598,4603,4606,4608,4610,4612,4627,4632,4633,4634,4635,4637,4638,4639,4640,4643,4645,4648,4651,4652,4654,4657,4658,4660,4663,4664,4666,4669,4671,4672,4674,4675,4678,4682,4689,4692,4694,4695,4697,4701,4707,4710,4712,4713,4722,4724,4729,4738,4741,4742,4751,4754,4756,4757,4761,4766,4767,4768,4778,4779,4789,4790,4791,4792,4796,4799,4803,4804,4805,4807,4811,4812,4815,4819,4826,4828,4830,4831,4832,4833,4834,4843,4845,4847,4848,4861,4865,4866,4867,4873,4881,4888,4889,4898,4899,4914,4929,4936,4939,4940,4941,4955,4959,5027],"type":[2622,2664,2665,3149,3382,3440,4495,4508,4822,4859,4860,4869,4877,4879,4900,4902,4931,4944,4952,4953,4969,4983,4997,5000,5034,5039,5043,5046,5050,5090,5106,5110,5112,5144,5162,5168,5171,5174,5188,5214,5215,5216,5217,5218,5219,5220,5237,5238,5239,5240,5252,5254,5260,5264,5266,5267,5269,5277,5282,5285,5286,5287,5288,5306,5310,5318,5334,5336,5349,5360,5362,5372,5374,5376,5404,5408,5411,5424,5425,5428],"breaking":[4802,4818,5009,5085,5167,5191],"touches":[5166,5223,5430],"newer":[5049,5221,5224,5227,5229,5232,5294,5295,5309,5320,5344,5375,5398,5415,5426,5427],"skip-label":[4817,4921,4973,4989,4990,5083,5156,5163,5180,5186,5337,5393],"dropped":[4920,4960,5142,5155,5405]}},"overlays":{"dropped":[{"original":4920,"merge":"65cb73e38098a127d9c09bca3cf16d431222696e","reason":"its test needs newHandleTestWebhook from #4447, which never reaches release-1.6","on":5312,"date":"2026-11-26"},{"original":4960,"merge":"a5c58e5e985399a687e5f676a7321f828eda5ff7","reason":"builds on golden image checks of #4796, which is breaking and won't reach release-1.6","on":5312,"date":"2026-11-26"},{"original":5142,"merge":"5c564f9154ddc03387fd4cd6b7a9185b11b0bdb3","reason":"not needed on release-1.6, it ships only patches now and their changelogs are 8-22 KB, far below release body limit","on":5312,"date":"2026-11-25"},{"original":5155,"merge":"b53ca1fedebcc6288856995ada2629c06c9e4ae7","reason":"builds on init script passes from #4078 and #4574, release-1.6 doesn't have them and #4078 is breaking","on":5312,"date":"2026-11-26"},{"original":5405,"merge":"30ce2a3cb1de5b64e629780ef70349608d5cd05d","reason":"reverted on release-1.7 in #5461, comes to release-1.6 only as the hand port #5433 after #5459 is fixed","on":5312,"date":"2026-11-26"}],"stale":[],"changed":[4004,4673,4915,5119,5124,5210,5364,5373]},"diag":{},"other":[]}
```

### Screenshots

See the original pull requests.

### Downstream repositories

- [ ] No downstream repository is affected by this change
- [ ] [cozystack/website](https://github.com/cozystack/website) -
follow-up:
- [ ]
[cozystack/terraform-provider-cozystack](https://github.com/cozystack/terraform-provider-cozystack)
- follow-up:
- [ ]
[cozystack/ansible-cozystack](https://github.com/cozystack/ansible-cozystack)
- follow-up:
- [ ] [cozystack/ccp](https://github.com/cozystack/ccp) - follow-up:
- [ ] [cozystack/talm](https://github.com/cozystack/talm) - follow-up:
- [ ] [cozystack/cozyhr](https://github.com/cozystack/cozyhr) -
follow-up:
- [ ] [cozystack/cozy-proxy](https://github.com/cozystack/cozy-proxy) -
follow-up:
- [ ]
[cozystack/cozystack-telemetry-server](https://github.com/cozystack/cozystack-telemetry-server)
- follow-up:
- [ ]
[cozystack/external-apps-example](https://github.com/cozystack/external-apps-example)
- follow-up:
- [ ] [cozystack/examples](https://github.com/cozystack/examples) -
follow-up:

### Release note

```release-note
fix(tenant): retry a failed monitoring or gateway install instead of uninstalling the release, so a slow first install no longer runs the cleanup hooks that delete the tenant's metrics and logs volumes or its ACME account key

fix(harbor): set resources for the nginx proxy and raise the portal preset so neither is OOMKilled by the tenant LimitRange default (128Mi)

fix(bucket): the ACME cleanup hook now reaches the apiserver instead of reporting success while doing nothing

fix(monitoring): kube-apiserver is scraped with its own 128MB size limit (`vmagent.apiserverMaxScrapeSize` in the monitoring-agents component) instead of the global 32MB, so a large `/metrics` no longer makes KubeAPIDown fire on a healthy API server. A new VMAgentScrapeSizeExceeded alert reports any target whose response exceeds the scrape size limit.

fix(mariadb): correct webhook cert-manager override key path so cert-manager is actually used for the mariadb-operator webhook certificate

fix(etcd): the tenant etcd alert etcdHighNumberOfFailedGRPCRequests now counts only the gRPC codes that the etcd mixin and the platform copy of the alert count, so the Canceled watch streams of a Kubernetes API server that stops no longer fire it on every etcd member.

fix(tcp-balancer): HAProxy now takes its fd and thread caps from the replica's memory and CPU limits instead of the node, so a t1.nano balancer is no longer OOMKilled on nodes with many CPUs. maxconn follows the memory limit at about 16 connections per MiB, 2035 on t1.nano, and the pods roll once on upgrade.

fix(tenant): the tenant gateway release no longer times out on upgrade while TenantGateway listener certificates are pending, it waits only until the controller has observed the current TenantGateway spec.

fix(controller): existing HelmReleases now get `healthCheckExprs` and `waitStrategy` from their ApplicationDefinition. vm-disk and postgres releases created before these expressions were added stop waiting on DataVolume and KEDA ScaledObject during upgrades.

fix(cilium): the IPAM migration hook no longer fails with "Argument list too long" on clusters with more than a few nodes, which blocked the cilium upgrade and every package that depends on networking.

fix(kubernetes): the OIDC bootstrap Job no longer fails to start for a tenant cluster with about 240 or more oidc.users, the bindings now come from a ConfigMap the Job mounts.

fix(clickhouse): a RestoreJob now restores the archive its Backup was taken as, not the newest one. New Backups record the archive name, Backups taken before this release are restored best effort from the newest archive stamped no later than their takenAt, with a warning in the restore pod log. A ClickHouse BackupJob created again under a name whose Backup still exists now fails instead of reporting that Backup as its result.

fix(postgres): the init script renders the declared databases in a stable order, so an upgrade that leaves the databases unchanged no longer rewrites the init-script Secret.

fix(mariadb-operator): the MariaDB operator now uses the platform's networking.clusterDomain instead of a hard-coded cozy.local, so replication and User/Database/Grant reconciliation work on clusters with a non-default cluster domain.

fix(api): tenant quota admission now counts the parent pool's usage of extended resources and hugepages, so a child tenant can no longer get a share the parent has already used. After upgrading, updates to existing tenants may be rejected if their quota for these resources exceeds the parent's remaining budget. This includes updates that leave the quota unchanged.

fix(mariadb): a MariaDB BackupJob or RestoreJob whose operator Job failed now ends Failed instead of Succeeded, and a failed backup no longer creates a Ready Backup without an archive. Backups created by failed runs before this fix are not removed; restoring from one can fail or select another dump from the shared prefix.

fix(kubernetes, monitoring): the vmagent of tenant Kubernetes clusters now writes to the tenant's vminsert and labels series with the owning tenant instead of `cozy-monitoring`. Previously no tenant cluster metric reached the tenant's Monitoring.

fix(seaweedfs): bucket users granted together could get S3 keys that never work (403 InvalidAccessKeyId). COSI driver is bumped to v0.4.0, which writes each grant to per-identity IAM file.

fix(monitoring-agents): disabling the Monitoring Agents addon of a tenant Kubernetes cluster no longer leaves the monitoring-agents release stuck in UninstallFailed when the VictoriaMetrics operator is removed first; a pre-delete hook now releases the VictoriaMetrics objects' finalizers, and the VPA is only rendered when its CRD is served.

fix(vm-instance): an external PortList VM with an empty port list no longer fails to deploy; it keeps its external IP and blocks all inbound TCP and UDP traffic.

fix(backups): the barman-cloud sidecar of Postgres backups now has an explicit one-core CPU limit instead of inheriting the tenant LimitRange's 250m default, which made full backups and WAL archiving several times slower. Each instance pod of a tenant with a CPU quota now counts 750m more against `limits.cpu`; check the headroom before instance pods are recreated. Existing ObjectStores pick the limit up at their next backup (platform-managed) or HelmRelease upgrade (chart-rendered), and running pods at their next restart.

fix(etcd): the tenant etcd defrag job requests 10m and 32Mi instead of 200m and 256Mi, so it runs in tenants whose quota is nearly used up by their own services.

fix(monitoring): vmalert metrics are collected again. The vmalert VMServiceScrape selected app.kubernetes.io/instance=vmalert while the Service is labelled vmalert-<first metrics storage>, so it matched nothing.

fix(ingress-nginx): raise the client keepalive_time from the nginx 1h default to 12h, so long-lived HTTP/2 connections (for example kopia maintenance against S3) are no longer cut by a GOAWAY after one hour

fix(monitoring-agents): a Watchdog that stops reaching Alerta now raises a major HeartbeatFail about six minutes later. It used to raise an ok alert after a day.

fix(monitoring): InfoInhibitor no longer reaches Alerta as a major alert. It carries severity none again, which the platform Alertmanager routes to the blackhole, as upstream kube-prometheus intends. Before, any active alert with severity info, from a custom rule or from one CDI or KubeVirt generates, raised a major InfoInhibitor in Alerta and in its Telegram and Slack notifications.

fix(vertical-pod-autoscaler): the admission controller runs two replicas spread over nodes with a PodDisruptionBudget, so pods created during a drain still get their VPA recommendation.

feat(monitoring): new warning alert PodReplicasColocated fires when two or more running pods of one StatefulSet, ReplicaSet, CNPG Cluster, StrimziPodSet or etcd cluster have shared a node for an hour while the cluster has a schedulable node for each of them.

fix(kubevirt): tenant admins can upload an image into a VMDisk created with source upload using virtctl image-upload. The tenant admin and super-admin roles get get on persistentvolumeclaims and create on upload.cdi.kubevirt.io/uploadtokenrequests, and the vm-disk notes print the command with --no-create.

fix(piraeus-operator): the LINSTOR error-report alerts no longer fire on old reports when the LINSTOR controller pod moves to another node, when an external label of the scrape changes, or when a satellite reconnects within an hour. They now count reports per node, and their alerts carry the node's hostname instead of the controller pod's instance, job and controller_node labels.

fix(keycloak, foundationdb): keycloak-operator and foundationdb-operator now replace their CRDs on upgrade. Clusters upgraded from before v1.2.0 kept the v1.25.0 keycloak-operator CRDs, under which the apiserver dropped the Keycloak realm session settings and Keycloak could reject the dashboard client, and clusters upgraded from before v1.6.0 kept the v2.13.0 foundationdb-operator CRDs.

fix(tcp-balancer): the Service now publishes ports 6443 and 50000 only when kubernetesAndTalos is set, like the Deployment and the HAProxy config. Before, every tcp-balancer Service carried both ports with no container port behind them, on the LoadBalancer too when external was enabled, and a release with kubernetesAndTalos but without httpAndHttps had no Service port for them.

[vpa] Shorten the VPA admission webhook timeout to 5s so pod creation does not stall cluster-wide while the admission controller is unreachable.

fix(controller, platform): sub-tenants without their own resourceQuotas now receive their parent pool's container defaults (LimitRange) alongside the allocated quota, when that quota bounds a CPU or memory limit, so pods that omit such a limit, such as the postgres barman-cloud backup sidecar, are no longer rejected at admission.

fix(etcd): scope tenant etcd alerts to their release and avoid duplicate tenant peer RTT alerts from the global rules

fix(cozy-lib): a tenant quota with hugepages-2Mi or hugepages-1Gi now renders only requests.hugepages-<size>, so the tenant installs and its huge pages are bounded.

fix(seaweedfs): grant existing bucket credentials the Object Lock actions required by SeaweedFS 4.48 on install and upgrade, preserving their bucket restrictions and credentials.

fix(kamaji): stop writing kubelet config fields that older tenant Kubernetes versions do not know, such as memoryReservationPolicy on tenants before v1.36, so strict decoders of the kubelet-config ConfigMap no longer fail.

fix(qdrant): restore metrics scraping for TLS-enabled instances by using HTTPS and verifying the server certificate against the issued CA.

fix(kubernetes): remove cilium dependency from coredns HelmRelease to prevent a circular startup deadlock when Hubble Relay is enabled

fix(securitygroups): a port range now gets a clear "port ranges are not supported" error, and a malformed toFQDNs matchName or matchPattern is rejected on the SecurityGroup field instead of failing on the backing CiliumNetworkPolicy.

fix(postgres): a user named `app` no longer loses its password when the Postgres pod restarts. CNPG re-applied its own generated password to the `app` owner role on every pod start; the chart now hands CNPG the password stored in `<release>-credentials`.

fix(linstor): linstor-affinity-controller and linstor-scheduler now restart when their LINSTOR client certificate is rotated, instead of failing every LINSTOR API call with EOF once the certificate they loaded at startup expires.

fix(linstor): the NFS server's linstor-wait-node-online init container now runs the platform-built linstor-csi image instead of the operator's default.

fix(api): a resourceVersion from a WorkloadMonitor-triggered Application watch event now works as a delete precondition, and the event's spec matches its version.

fix(api): reject new workload memory values below 1Mi before storing an application. Updates to unrelated fields on existing applications with smaller values still pass admission.

fix(harbor): Harbor registry storage is billed again. The WorkloadMonitor controller finds BucketClaims by label, and the registry BucketClaim had no labels. It now carries the registry monitor's `release` and
  `component` labels, so its storage shows up as Workload under the registry WorkloadMonitor, the same way the registry PVC did before it moved to S3. And also registry WorkloadMonitor now reports not operational while the BucketClaim is not provisioned

fix(platform): system PostgreSQL databases (Keycloak, Harbor, Grafana, Alerta, SeaweedFS) move from 17.7 to 17.12-standard-trixie, which fixes CVE-2026-116331. On upgrade each of these databases is rolled: replicas first, then the primary is restarted in place, with a brief interruption of a few minutes per database.

fix(cozystack-basics): tenant super-admins can no longer create, edit or delete `kubevirt.io` VirtualMachines directly; they keep read and watch. Virtual machines are managed through VMInstance and VMDisk applications, power through the start/stop/restart actions. The install e2e now fails when a tenant super-admin gains a write verb outside a checked-in allowlist.

fix(ingress-nginx): TLS session tickets are turned off in the ingress-nginx controller (CVE-2026-97629). TLS session resumption keeps working through the shared session cache.

fix(ingress): restore visitor IP handling for Cloudflare-proxied HTTPS through ssl-passthrough while rejecting spoofed `CF-Connecting-IP` headers before IP whitelists
```
This commit is contained in:
myasnikovdaniil authored and GitHub committed 2026-11-27 10:16:05 +05:00
commit 7214c8ab90
183 files changed
+11589 -451

No files matched your search

+1
View File
@@ -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
+1 -1
View File
@@ -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 `<release>-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/<namespace>/<release>/`.
+1 -1
View File
@@ -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 `<tenant>-admin` / `<tenant>-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 `<tenant>-admin` / `<tenant>-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 `<tenant>-view` / `<tenant>-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). |
+2 -2
View File
@@ -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 `<tenant>-admin`, `<tenant>-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 `<tenant>-super-admin` group holds the `apps.cozystack.io/*` wildcard (and so can create child `Tenant`s); the `<tenant>-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 `<tenant>-admin`, `<tenant>-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 `<tenant>-super-admin` group holds the `apps.cozystack.io/*` wildcard (and so can create child `Tenant`s); the `<tenant>-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 `<tenant>-view`, `<tenant>-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.
+89
View File
@@ -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"
+218
View File
@@ -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" <<STUB
#!/usr/bin/env bash
set -eu
method=GET; url=""
for a in "\$@"; do
case "\$a" in POST) method=POST ;; http://*) url="\$a" ;; esac
done
echo "\$method \$url" >> "$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" <<STUB
#!/usr/bin/env bash
n=\$(cat "$state/sleeps" 2>/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"
}
+60
View File
@@ -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
}
@@ -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 <release>-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; }
}
+27
View File
@@ -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"
+82
View File
@@ -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
@@ -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"
+27
View File
@@ -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 ]
}
+187
View File
@@ -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 <dir> <count> renders the chart in System mode with <count>
# generated users and leaves one JSON document per object in <dir>/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 <dir> <users JSON> renders the chart in CustomConfig mode and unpacks
# what the bootstrap Job runs and mounts into <dir>: 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 <dir> <names> puts a kubectl first on PATH that logs every call and
# answers the script's list of existing bindings with <names>.
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 <dir> runs the unpacked script as the container does and leaves its
# status in $rc and its output in <dir>/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("<release>-<email>").
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"
}
+32
View File
@@ -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 ]
}
+312
View File
@@ -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 <job-name> <out>
# Extract the named Job's shell script from the rendered chart into <out>. 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 <dir>
# Emit fake `kubectl`, `date` and `sleep` into <dir>.
#
# 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 <file>
# 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" <<EOF
vmagents|$MA_RELEASE|$MA_NAMESPACE|$MA_NAMESPACE|vmagent
vmrules|$MA_RELEASE|$MA_NAMESPACE|$MA_NAMESPACE|alerts-node
vmservicescrapes|$MA_RELEASE|$MA_NAMESPACE|cozy-victoria-metrics-operator|operator
vmrules|other|$MA_NAMESPACE|$MA_NAMESPACE|foreign-rule
vmrules|$MA_RELEASE|other-namespace|$MA_NAMESPACE|foreign-ns-rule
vmservicescrapes|||$MA_NAMESPACE|unmanaged-scrape
EOF
}
# run_hook <dir>
# 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"
}
+49
View File
@@ -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 ]
}
+302
View File
@@ -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" ]
}
+336
View File
@@ -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 <file name>
identity() {
echo SECRET > "$IDS/$1"
}
# bucketaccess <uid> [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"
}
+100
View File
@@ -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'."
+198
View File
@@ -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
+572
View File
@@ -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.
+26
View File
@@ -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 ]
}
@@ -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-<release>-<timestamp>
// 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,
)
@@ -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)
}
}
})
}
}
+8 -20
View File
@@ -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
}
@@ -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
@@ -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"),
},
},
@@ -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,
@@ -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
}
@@ -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
// ---------------------------------------------------------------------------
@@ -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"`
}
@@ -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}
@@ -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)
}
}
@@ -0,0 +1,326 @@
package backupcontroller
import (
"context"
"fmt"
"strconv"
"strings"
"time"
corev1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
backupsv1alpha1 "github.com/cozystack/cozystack/api/backups/v1alpha1"
velerov1 "github.com/vmware-tanzu/velero/pkg/apis/velero/v1"
)
// veleroDeletionRequest is what requestVeleroBackupDeletion found and did.
type veleroDeletionRequest struct {
created bool
// replaced is a request of ours that Velero had processed and that this
// call deleted before creating a new one.
replaced *velerov1.DeleteBackupRequest
// pending is a request for the backup that Velero has not processed yet.
pending *velerov1.DeleteBackupRequest
// processed is a request of ours that Velero has processed and that was
// left in place because the caller did not allow a replacement.
processed *velerov1.DeleteBackupRequest
}
// requestVeleroBackupDeletion asks Velero to delete a backup together with its
// data in the object store. Deleting the backup.velero.io object directly only
// removes the Kubernetes object, and the BSL sync recreates it from the object
// store. Callers call it only for a backup that still exists.
//
// The request is named after the backup, so repeated calls converge on one
// request. Nothing is created while any request for the backup is
// unprocessed. A request of ours that Velero has processed means the backup
// survived it: the deletion failed, or the BSL sync brought the backup back.
// With replace set, such a request is deleted and created again, because
// Velero keeps a processed request for a day and its name would block a new
// attempt until then. Velero does not retry a processed request, so a caller
// that needs the deletion to happen must call again later.
func requestVeleroBackupDeletion(ctx context.Context, c client.Client, namespace, name string, replace bool) (veleroDeletionRequest, error) {
var res veleroDeletionRequest
requests := &velerov1.DeleteBackupRequestList{}
if err := c.List(ctx, requests, client.InNamespace(namespace)); err != nil {
return res, fmt.Errorf("failed to list DeleteBackupRequests in %s: %w", namespace, err)
}
var own *velerov1.DeleteBackupRequest
for i := range requests.Items {
dbr := &requests.Items[i]
if dbr.Spec.BackupName != name {
continue
}
if dbr.Status.Phase != velerov1.DeleteBackupRequestPhaseProcessed {
res.pending = dbr
return res, nil
}
if dbr.Name == name {
own = dbr
}
}
if own != nil {
if !replace {
res.processed = own
return res, nil
}
// The UID precondition keeps a stale cache from deleting a request
// that has already been replaced.
err := c.Delete(ctx, own, client.Preconditions{UID: &own.UID})
switch {
case err == nil:
res.replaced = own
case apierrors.IsNotFound(err), apierrors.IsConflict(err):
default:
return res, fmt.Errorf("failed to delete processed DeleteBackupRequest %s/%s: %w", namespace, name, err)
}
}
dbr := &velerov1.DeleteBackupRequest{
ObjectMeta: metav1.ObjectMeta{
Name: name,
Namespace: namespace,
},
Spec: velerov1.DeleteBackupRequestSpec{
BackupName: name,
},
}
if err := c.Create(ctx, dbr); err != nil {
if apierrors.IsAlreadyExists(err) {
return res, nil
}
return res, fmt.Errorf("failed to create DeleteBackupRequest for %s/%s: %w", namespace, name, err)
}
res.created = true
return res, nil
}
const (
// failedJobSweepRequeue is the first interval at which a Failed
// BackupJob is reconciled again while one of its Velero backups waits
// for deletion; failedJobSweepMaxRequeue caps every interval below.
// Nothing watches DeleteBackupRequests, so a request Velero processed is
// only noticed on such a requeue. A processed request is replaced once
// failedJobSweepBackoff(retries) has passed since the last attempt, so a
// deletion Velero can never carry out (a missing, read-only or
// unavailable BSL) is attempted at most once an hour, and the annotation
// writes that record each attempt cannot cut the wait short.
failedJobSweepRequeue = 5 * time.Minute
failedJobSweepMaxRequeue = time.Hour
// failedJobRunningBackupRequeue is the first interval at which a Failed
// BackupJob is reconciled again while one of its Velero backups is still
// running. Velero rejects a deletion request for a running backup.
failedJobRunningBackupRequeue = time.Minute
// veleroDeletionRetriesAnnotation counts, on a Failed BackupJob, the
// deletion requests that Velero processed while the backup survived.
veleroDeletionRetriesAnnotation = "backups.cozystack.io/velero-deletion-retries"
// veleroDeletionAttemptAnnotation is when the sweep last created a
// deletion request for a Failed BackupJob, in RFC 3339.
veleroDeletionAttemptAnnotation = "backups.cozystack.io/velero-deletion-attempted-at"
)
// deleteFailedJobVeleroBackups requests deletion of the failed Velero backups
// a Failed BackupJob left behind. A failed run creates no Backup, and the
// Backup finalizer is the only other path that deletes Velero data, so without
// this the backup and its objects stay in the bucket until Velero's TTL
// expires them. It runs on every reconcile of a Failed job, which also clears
// backups left by controller versions that did not request the deletion, and
// it requests the deletion only once the Failed phase is persisted: a request
// sent before that write would let a retried run start over with the failure
// already gone.
func (r *BackupJobReconciler) deleteFailedJobVeleroBackups(ctx context.Context, j *backupsv1alpha1.BackupJob) (ctrl.Result, error) {
logger := getLogger(ctx)
veleroBackups := &velerov1.BackupList{}
if err := r.List(ctx, veleroBackups, client.InNamespace(veleroNamespace), client.MatchingLabels{
backupsv1alpha1.OwningJobNamespaceLabel: j.Namespace,
backupsv1alpha1.OwningJobNameLabel: j.Name,
}); err != nil {
if meta.IsNoMatchError(err) {
return ctrl.Result{}, nil
}
return ctrl.Result{}, fmt.Errorf("failed to list Velero Backups of BackupJob %s/%s: %w", j.Namespace, j.Name, err)
}
if len(veleroBackups.Items) == 0 {
return ctrl.Result{}, nil
}
now := r.clock()
retries := veleroDeletionRetries(j)
lastAttempt := veleroDeletionAttempt(j)
nextAttempt := lastAttempt.Add(failedJobSweepBackoff(retries))
replaceDue := lastAttempt.IsZero() || !now.Before(nextAttempt)
var referenced map[client.ObjectKey]bool
var requeueAfter time.Duration
var attempted, replaced bool
for i := range veleroBackups.Items {
vb := &veleroBackups.Items[i]
switch vb.Status.Phase {
case velerov1.BackupPhasePartiallyFailed, velerov1.BackupPhaseFailed, velerov1.BackupPhaseFailedValidation,
// Velero marks the backup Deleting before it removes the data and
// leaves it so when that fails, so the request may need replacing.
velerov1.BackupPhaseDeleting:
case velerov1.BackupPhaseCompleted:
// A job can fail after Velero completed, when creating or
// recording its Backup fails. That Velero backup may be the only
// copy of good data, so a job-level failure never removes it: a
// Backup that references it deletes it with the Backup, and one
// that no Backup references stays until Velero's TTL expires it.
continue
default:
requeueAfter = shorterRequeue(requeueAfter,
waitingRequeue(now, vb.CreationTimestamp.Time, failedJobRunningBackupRequeue))
continue
}
if referenced == nil {
var err error
if referenced, err = r.veleroBackupsReferencedByBackups(ctx, j.Namespace); err != nil {
return ctrl.Result{}, err
}
}
if referenced[client.ObjectKeyFromObject(vb)] {
continue
}
req, err := requestVeleroBackupDeletion(ctx, r.Client, vb.Namespace, vb.Name, replaceDue)
if err != nil {
return ctrl.Result{}, err
}
switch {
case req.pending != nil:
requeueAfter = shorterRequeue(requeueAfter,
waitingRequeue(now, req.pending.CreationTimestamp.Time, failedJobSweepRequeue))
case req.processed != nil:
requeueAfter = shorterRequeue(requeueAfter, nextAttempt.Sub(now))
case req.created:
attempted = true
if req.replaced != nil {
replaced = true
r.warnVeleroDeletionRetried(j, vb.Name, req.replaced)
} else {
logger.Info("requested deletion of the Velero Backup of a failed BackupJob",
"backupjob", j.Name, "namespace", j.Namespace, "veleroBackup", vb.Name)
}
default:
requeueAfter = shorterRequeue(requeueAfter, failedJobSweepRequeue)
}
}
if !attempted {
return ctrl.Result{RequeueAfter: requeueAfter}, nil
}
if replaced {
retries++
}
requeueAfter = shorterRequeue(requeueAfter, failedJobSweepBackoff(retries))
patch := client.MergeFrom(j.DeepCopy())
if j.Annotations == nil {
j.Annotations = map[string]string{}
}
j.Annotations[veleroDeletionRetriesAnnotation] = strconv.Itoa(retries)
j.Annotations[veleroDeletionAttemptAnnotation] = now.UTC().Format(time.RFC3339)
if err := r.Patch(ctx, j, patch); err != nil {
if apierrors.IsNotFound(err) {
return ctrl.Result{}, nil
}
// The request is already in place; without the record the next
// attempt only comes sooner than the backoff asks for.
logger.Error(err, "failed to record the Velero deletion attempt on the BackupJob",
"backupjob", j.Name, "namespace", j.Namespace)
}
return ctrl.Result{RequeueAfter: requeueAfter}, nil
}
func (r *BackupJobReconciler) clock() time.Time {
if r.now != nil {
return r.now()
}
return time.Now()
}
func (r *BackupJobReconciler) warnVeleroDeletionRetried(j *backupsv1alpha1.BackupJob, veleroBackup string, processed *velerov1.DeleteBackupRequest) {
if r.Recorder == nil {
return
}
reason := "Velero reported no error, but the backup still exists"
if len(processed.Status.Errors) > 0 {
reason = strings.Join(processed.Status.Errors, "; ")
}
r.Recorder.Eventf(j, corev1.EventTypeWarning, "VeleroBackupDeletionFailed",
"Velero did not delete backup %s/%s: %s; requesting the deletion again",
veleroNamespace, veleroBackup, reason)
}
func veleroDeletionRetries(j *backupsv1alpha1.BackupJob) int {
n, err := strconv.Atoi(j.Annotations[veleroDeletionRetriesAnnotation])
if err != nil || n < 0 {
return 0
}
return n
}
func veleroDeletionAttempt(j *backupsv1alpha1.BackupJob) time.Time {
t, err := time.Parse(time.RFC3339, j.Annotations[veleroDeletionAttemptAnnotation])
if err != nil {
return time.Time{}
}
return t
}
func failedJobSweepBackoff(retries int) time.Duration {
d := failedJobSweepRequeue
for i := 0; i < retries && d < failedJobSweepMaxRequeue; i++ {
d *= 2
}
return min(d, failedJobSweepMaxRequeue)
}
// waitingRequeue paces the checks on something Velero has not acted on yet:
// the next check comes after as long as it has already waited, between floor
// and failedJobSweepMaxRequeue, so a Velero that is down is not polled at a
// fixed rate.
func waitingRequeue(now, since time.Time, floor time.Duration) time.Duration {
if since.IsZero() {
return floor
}
return min(max(now.Sub(since), floor), failedJobSweepMaxRequeue)
}
func shorterRequeue(current, next time.Duration) time.Duration {
if current == 0 || next < current {
return next
}
return current
}
// veleroBackupsReferencedByBackups reads Backups past the cache: a Backup the
// cache has not seen yet must still protect its Velero backup from deletion.
func (r *BackupJobReconciler) veleroBackupsReferencedByBackups(ctx context.Context, namespace string) (map[client.ObjectKey]bool, error) {
backups := &backupsv1alpha1.BackupList{}
if err := r.apiReader().List(ctx, backups, client.InNamespace(namespace)); err != nil {
return nil, fmt.Errorf("failed to list Backups in %s: %w", namespace, err)
}
referenced := map[client.ObjectKey]bool{}
for _, b := range backups.Items {
name := b.Spec.DriverMetadata[veleroBackupNameMetadataKey]
if name == "" {
continue
}
ns := b.Spec.DriverMetadata[veleroBackupNamespaceMetadataKey]
if ns == "" {
ns = veleroNamespace
}
referenced[client.ObjectKey{Namespace: ns, Name: name}] = true
}
return referenced, nil
}
@@ -0,0 +1,603 @@
package backupcontroller
import (
"context"
"errors"
"fmt"
"strings"
"testing"
"time"
corev1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/types"
"k8s.io/client-go/tools/record"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/client/fake"
"sigs.k8s.io/controller-runtime/pkg/client/interceptor"
strategyv1alpha1 "github.com/cozystack/cozystack/api/backups/strategy/v1alpha1"
backupsv1alpha1 "github.com/cozystack/cozystack/api/backups/v1alpha1"
velerov1 "github.com/vmware-tanzu/velero/pkg/apis/velero/v1"
)
const (
failedJobNamespace = "tenant-acme"
failedJobName = "vm-backup"
failedVeleroBackup = "tenant-acme.vm-backup-x7k2p"
)
func newVeleroCleanupClient(t *testing.T, funcs *interceptor.Funcs, objs ...client.Object) client.Client {
t.Helper()
b := fake.NewClientBuilder().
WithScheme(newReconcilerScheme(t)).
WithObjects(objs...).
WithStatusSubresource(&backupsv1alpha1.BackupJob{})
if funcs != nil {
b = b.WithInterceptorFuncs(*funcs)
}
return b.Build()
}
func newVeleroCleanupReconciler(t *testing.T, objs ...client.Object) (*BackupJobReconciler, client.Client) {
t.Helper()
c := newVeleroCleanupClient(t, nil, objs...)
return &BackupJobReconciler{Client: c, Recorder: record.NewFakeRecorder(16)}, c
}
func veleroCleanupJob(phase backupsv1alpha1.BackupJobPhase) *backupsv1alpha1.BackupJob {
started := metav1.Now()
return &backupsv1alpha1.BackupJob{
ObjectMeta: metav1.ObjectMeta{Namespace: failedJobNamespace, Name: failedJobName},
Status: backupsv1alpha1.BackupJobStatus{
Phase: phase,
StartedAt: &started,
},
}
}
func ownedVeleroBackup(name string, phase velerov1.BackupPhase) *velerov1.Backup {
return &velerov1.Backup{
ObjectMeta: metav1.ObjectMeta{
Namespace: veleroNamespace,
Name: name,
Labels: map[string]string{
backupsv1alpha1.OwningJobNameLabel: failedJobName,
backupsv1alpha1.OwningJobNamespaceLabel: failedJobNamespace,
},
},
Status: velerov1.BackupStatus{Phase: phase, FailureReason: "object store unreachable"},
}
}
func referencingBackup(veleroBackupName string) *backupsv1alpha1.Backup {
return &backupsv1alpha1.Backup{
ObjectMeta: metav1.ObjectMeta{Namespace: failedJobNamespace, Name: failedJobName},
Spec: backupsv1alpha1.BackupSpec{DriverMetadata: map[string]string{
veleroBackupNameMetadataKey: veleroBackupName,
veleroBackupNamespaceMetadataKey: veleroNamespace,
}},
}
}
func deleteRequest(name string, phase velerov1.DeleteBackupRequestPhase, errs ...string) *velerov1.DeleteBackupRequest {
return &velerov1.DeleteBackupRequest{
ObjectMeta: metav1.ObjectMeta{Namespace: veleroNamespace, Name: name, UID: types.UID(name + "-uid")},
Spec: velerov1.DeleteBackupRequestSpec{BackupName: failedVeleroBackup},
Status: velerov1.DeleteBackupRequestStatus{Phase: phase, Errors: errs},
}
}
func veleroCleanupResolved() *ResolvedBackupConfig {
apiGroup := strategyv1alpha1.GroupVersion.Group
return &ResolvedBackupConfig{StrategyRef: corev1.TypedLocalObjectReference{
APIGroup: &apiGroup, Kind: strategyv1alpha1.VeleroStrategyKind, Name: "velero",
}}
}
func veleroCleanupStrategy() *strategyv1alpha1.Velero {
return &strategyv1alpha1.Velero{ObjectMeta: metav1.ObjectMeta{Name: "velero"}}
}
func listDeleteBackupRequests(t *testing.T, c client.Client) []velerov1.DeleteBackupRequest {
t.Helper()
l := &velerov1.DeleteBackupRequestList{}
if err := c.List(context.Background(), l, client.InNamespace(veleroNamespace)); err != nil {
t.Fatalf("list DeleteBackupRequests: %v", err)
}
return l.Items
}
func reconcileCleanupJob(t *testing.T, r *BackupJobReconciler) ctrl.Result {
t.Helper()
res, err := r.Reconcile(context.Background(), ctrl.Request{
NamespacedName: types.NamespacedName{Namespace: failedJobNamespace, Name: failedJobName},
})
if err != nil {
t.Fatalf("Reconcile: %v", err)
}
return res
}
func getCleanupJob(t *testing.T, c client.Client) *backupsv1alpha1.BackupJob {
t.Helper()
j := &backupsv1alpha1.BackupJob{}
if err := c.Get(context.Background(), types.NamespacedName{Namespace: failedJobNamespace, Name: failedJobName}, j); err != nil {
t.Fatalf("get BackupJob: %v", err)
}
return j
}
// A Velero backup that ends Failed or PartiallyFailed produces no Backup. The
// run keeps its failure message, and the deletion is requested by the
// reconcile that follows the persisted Failed phase, once.
func TestReconcileVelero_FailedBackupRequestsDeletionAfterFailedIsPersisted(t *testing.T) {
for _, phase := range []velerov1.BackupPhase{velerov1.BackupPhaseFailed, velerov1.BackupPhasePartiallyFailed} {
t.Run(string(phase), func(t *testing.T) {
j := veleroCleanupJob(backupsv1alpha1.BackupJobPhaseRunning)
r, c := newVeleroCleanupReconciler(t, j, ownedVeleroBackup(failedVeleroBackup, phase), veleroCleanupStrategy())
if _, err := r.reconcileVelero(context.Background(), j, veleroCleanupResolved()); err != nil {
t.Fatalf("reconcileVelero: %v", err)
}
got := getCleanupJob(t, c)
if got.Status.Phase != backupsv1alpha1.BackupJobPhaseFailed {
t.Fatalf("expected BackupJob Failed, got %q", got.Status.Phase)
}
wantMsg := "Velero Backup failed with phase " + string(phase) + ": object store unreachable"
if got.Status.Message != wantMsg {
t.Errorf("message = %q, want %q", got.Status.Message, wantMsg)
}
if dbrs := listDeleteBackupRequests(t, c); len(dbrs) != 0 {
t.Fatalf("deletion must wait for the next reconcile, got %+v", dbrs)
}
if res := reconcileCleanupJob(t, r); res.RequeueAfter != failedJobSweepRequeue {
t.Errorf("RequeueAfter = %v, want %v", res.RequeueAfter, failedJobSweepRequeue)
}
dbrs := listDeleteBackupRequests(t, c)
if len(dbrs) != 1 || dbrs[0].Name != failedVeleroBackup || dbrs[0].Spec.BackupName != failedVeleroBackup {
t.Fatalf("expected one DeleteBackupRequest for %s, got %+v", failedVeleroBackup, dbrs)
}
reconcileCleanupJob(t, r)
if n := len(listDeleteBackupRequests(t, c)); n != 1 {
t.Fatalf("a second reconcile must not add a request, got %d", n)
}
})
}
}
// If the Failed phase cannot be written, the run is retried and must still
// find its Velero backup to report the failure from.
func TestReconcileVelero_FailedStatusWriteErrorRequestsNoDeletion(t *testing.T) {
j := veleroCleanupJob(backupsv1alpha1.BackupJobPhaseRunning)
funcs := &interceptor.Funcs{
SubResourceUpdate: func(ctx context.Context, c client.Client, sub string, obj client.Object, opts ...client.SubResourceUpdateOption) error {
if bj, ok := obj.(*backupsv1alpha1.BackupJob); ok && bj.Status.Phase == backupsv1alpha1.BackupJobPhaseFailed {
return apierrors.NewServiceUnavailable("etcd timeout")
}
return c.SubResource(sub).Update(ctx, obj, opts...)
},
}
c := newVeleroCleanupClient(t, funcs, j, ownedVeleroBackup(failedVeleroBackup, velerov1.BackupPhaseFailed), veleroCleanupStrategy())
r := &BackupJobReconciler{Client: c, Recorder: record.NewFakeRecorder(16)}
if _, err := r.reconcileVelero(context.Background(), j, veleroCleanupResolved()); err == nil {
t.Fatal("expected the status write error to be returned")
}
if got := getCleanupJob(t, c); got.Status.Phase == backupsv1alpha1.BackupJobPhaseFailed {
t.Fatalf("status write was rejected, got phase %q", got.Status.Phase)
}
if dbrs := listDeleteBackupRequests(t, c); len(dbrs) != 0 {
t.Fatalf("no deletion may be requested before Failed is persisted, got %+v", dbrs)
}
}
func TestReconcileVelero_CompletedBackupRequestsNoDeletion(t *testing.T) {
j := veleroCleanupJob(backupsv1alpha1.BackupJobPhaseRunning)
r, c := newVeleroCleanupReconciler(t, j, ownedVeleroBackup(failedVeleroBackup, velerov1.BackupPhaseCompleted), veleroCleanupStrategy())
if _, err := r.reconcileVelero(context.Background(), j, veleroCleanupResolved()); err != nil {
t.Fatalf("reconcileVelero: %v", err)
}
if got := getCleanupJob(t, c); got.Status.Phase != backupsv1alpha1.BackupJobPhaseSucceeded {
t.Fatalf("expected BackupJob Succeeded, got %q (%s)", got.Status.Phase, got.Status.Message)
}
reconcileCleanupJob(t, r)
if dbrs := listDeleteBackupRequests(t, c); len(dbrs) != 0 {
t.Fatalf("a succeeded run must not request deletion, got %+v", dbrs)
}
}
func TestReconcileVelero_SeveralVeleroBackupsKeepCompletedOne(t *testing.T) {
j := veleroCleanupJob(backupsv1alpha1.BackupJobPhaseRunning)
r, c := newVeleroCleanupReconciler(t, j, veleroCleanupStrategy(),
ownedVeleroBackup("vb-b", velerov1.BackupPhaseFailed),
ownedVeleroBackup("vb-a", velerov1.BackupPhaseCompleted))
if _, err := r.reconcileVelero(context.Background(), j, veleroCleanupResolved()); err != nil {
t.Fatalf("reconcileVelero: %v", err)
}
got := getCleanupJob(t, c)
if got.Status.Phase != backupsv1alpha1.BackupJobPhaseFailed || got.Status.CompletedAt == nil {
t.Fatalf("expected BackupJob Failed with completedAt, got %+v", got.Status)
}
if want := "more than one Velero Backup references this BackupJob: vb-a, vb-b"; got.Status.Message != want {
t.Errorf("message = %q, want %q", got.Status.Message, want)
}
reconcileCleanupJob(t, r)
dbrs := listDeleteBackupRequests(t, c)
if len(dbrs) != 1 || dbrs[0].Spec.BackupName != "vb-b" {
t.Fatalf("expected a request for the failed vb-b only, got %+v", dbrs)
}
}
// Reconciling a Failed BackupJob, including one that failed under a version
// without the cleanup, requests deletion of its failed Velero backups only.
func TestReconcile_FailedJobVeleroBackupSweep(t *testing.T) {
foreign := failedVeleroBackup + "-abcde"
cases := []struct {
name string
veleroPhase velerov1.BackupPhase
jobPhase backupsv1alpha1.BackupJobPhase
existing []client.Object
// Backups visible to the uncached reader only.
uncached []client.Object
wantRequests map[string]velerov1.DeleteBackupRequestPhase
wantRequeue time.Duration
wantEvent bool
}{
{
name: "PartiallyFailed without a request",
veleroPhase: velerov1.BackupPhasePartiallyFailed,
jobPhase: backupsv1alpha1.BackupJobPhaseFailed,
wantRequests: map[string]velerov1.DeleteBackupRequestPhase{failedVeleroBackup: ""},
wantRequeue: failedJobSweepRequeue,
},
{
name: "FailedValidation is deleted",
veleroPhase: velerov1.BackupPhaseFailedValidation,
jobPhase: backupsv1alpha1.BackupJobPhaseFailed,
wantRequests: map[string]velerov1.DeleteBackupRequestPhase{failedVeleroBackup: ""},
wantRequeue: failedJobSweepRequeue,
},
{
name: "pending request from elsewhere",
veleroPhase: velerov1.BackupPhaseFailed,
jobPhase: backupsv1alpha1.BackupJobPhaseFailed,
existing: []client.Object{deleteRequest(foreign, velerov1.DeleteBackupRequestPhaseInProgress)},
wantRequests: map[string]velerov1.DeleteBackupRequestPhase{foreign: velerov1.DeleteBackupRequestPhaseInProgress},
wantRequeue: failedJobSweepRequeue,
},
{
name: "errored request from elsewhere is left alone",
veleroPhase: velerov1.BackupPhaseFailed,
jobPhase: backupsv1alpha1.BackupJobPhaseFailed,
existing: []client.Object{deleteRequest(foreign, velerov1.DeleteBackupRequestPhaseProcessed, "backup storage location unavailable")},
wantRequests: map[string]velerov1.DeleteBackupRequestPhase{
failedVeleroBackup: "",
foreign: velerov1.DeleteBackupRequestPhaseProcessed,
},
wantRequeue: failedJobSweepRequeue,
},
{
name: "own request processed with errors is replaced",
veleroPhase: velerov1.BackupPhaseFailed,
jobPhase: backupsv1alpha1.BackupJobPhaseFailed,
existing: []client.Object{deleteRequest(failedVeleroBackup, velerov1.DeleteBackupRequestPhaseProcessed, "backup is still in progress")},
wantRequests: map[string]velerov1.DeleteBackupRequestPhase{failedVeleroBackup: ""},
wantRequeue: 2 * failedJobSweepRequeue,
wantEvent: true,
},
{
name: "own request processed without errors while the backup exists is replaced",
veleroPhase: velerov1.BackupPhaseFailed,
jobPhase: backupsv1alpha1.BackupJobPhaseFailed,
existing: []client.Object{deleteRequest(failedVeleroBackup, velerov1.DeleteBackupRequestPhaseProcessed)},
wantRequests: map[string]velerov1.DeleteBackupRequestPhase{failedVeleroBackup: ""},
wantRequeue: 2 * failedJobSweepRequeue,
wantEvent: true,
},
{
name: "Deleting with a request in progress",
veleroPhase: velerov1.BackupPhaseDeleting,
jobPhase: backupsv1alpha1.BackupJobPhaseFailed,
existing: []client.Object{deleteRequest(failedVeleroBackup, velerov1.DeleteBackupRequestPhaseInProgress)},
wantRequests: map[string]velerov1.DeleteBackupRequestPhase{failedVeleroBackup: velerov1.DeleteBackupRequestPhaseInProgress},
wantRequeue: failedJobSweepRequeue,
},
{
name: "Deleting left by an errored request",
veleroPhase: velerov1.BackupPhaseDeleting,
jobPhase: backupsv1alpha1.BackupJobPhaseFailed,
existing: []client.Object{deleteRequest(failedVeleroBackup, velerov1.DeleteBackupRequestPhaseProcessed, "error deleting backup from object storage")},
wantRequests: map[string]velerov1.DeleteBackupRequestPhase{failedVeleroBackup: ""},
wantRequeue: 2 * failedJobSweepRequeue,
wantEvent: true,
},
{
name: "Completed is never deleted",
veleroPhase: velerov1.BackupPhaseCompleted,
jobPhase: backupsv1alpha1.BackupJobPhaseFailed,
},
{
name: "failed backup referenced by a Backup the cache has not seen",
veleroPhase: velerov1.BackupPhaseFailed,
jobPhase: backupsv1alpha1.BackupJobPhaseFailed,
uncached: []client.Object{referencingBackup(failedVeleroBackup)},
},
{
name: "running backup",
veleroPhase: velerov1.BackupPhaseInProgress,
jobPhase: backupsv1alpha1.BackupJobPhaseFailed,
wantRequeue: failedJobRunningBackupRequeue,
},
{
name: "new backup",
veleroPhase: "",
jobPhase: backupsv1alpha1.BackupJobPhaseFailed,
wantRequeue: failedJobRunningBackupRequeue,
},
{
name: "succeeded job",
veleroPhase: velerov1.BackupPhaseFailed,
jobPhase: backupsv1alpha1.BackupJobPhaseSucceeded,
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
objs := append([]client.Object{veleroCleanupJob(tc.jobPhase), ownedVeleroBackup(failedVeleroBackup, tc.veleroPhase)}, tc.existing...)
r, c := newVeleroCleanupReconciler(t, objs...)
if tc.uncached != nil {
r.APIReader = newVeleroCleanupClient(t, nil, tc.uncached...)
}
if res := reconcileCleanupJob(t, r); res.RequeueAfter != tc.wantRequeue {
t.Errorf("RequeueAfter = %v, want %v", res.RequeueAfter, tc.wantRequeue)
}
dbrs := listDeleteBackupRequests(t, c)
if len(dbrs) != len(tc.wantRequests) {
t.Fatalf("expected requests %v, got %+v", tc.wantRequests, dbrs)
}
for _, dbr := range dbrs {
wantPhase, ok := tc.wantRequests[dbr.Name]
if !ok || dbr.Spec.BackupName != failedVeleroBackup {
t.Errorf("unexpected request %s for %s", dbr.Name, dbr.Spec.BackupName)
continue
}
if dbr.Status.Phase != wantPhase {
t.Errorf("request %s phase = %q, want %q", dbr.Name, dbr.Status.Phase, wantPhase)
}
}
events := r.Recorder.(*record.FakeRecorder).Events
if got := len(events); (got > 0) != tc.wantEvent {
t.Errorf("got %d events, want an event: %v", got, tc.wantEvent)
}
})
}
}
func markOwnRequestProcessed(t *testing.T, c client.Client, errs ...string) {
t.Helper()
dbr := &velerov1.DeleteBackupRequest{}
if err := c.Get(context.Background(), types.NamespacedName{Namespace: veleroNamespace, Name: failedVeleroBackup}, dbr); err != nil {
t.Fatalf("get request: %v", err)
}
dbr.Status = velerov1.DeleteBackupRequestStatus{Phase: velerov1.DeleteBackupRequestPhaseProcessed, Errors: errs}
if err := c.Update(context.Background(), dbr); err != nil {
t.Fatalf("mark request processed: %v", err)
}
}
// A deletion Velero keeps failing at once is retried only after a growing
// wait, even though recording each attempt triggers a new reconcile, and
// every retry is reported on the BackupJob with Velero's errors.
func TestReconcile_FailedJobVeleroDeletionBacksOff(t *testing.T) {
const readOnly = "backup storage location default is currently in read-only mode"
r, c := newVeleroCleanupReconciler(t,
veleroCleanupJob(backupsv1alpha1.BackupJobPhaseFailed),
ownedVeleroBackup(failedVeleroBackup, velerov1.BackupPhaseFailed))
now := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC)
r.now = func() time.Time { return now }
events := r.Recorder.(*record.FakeRecorder).Events
expectEvent := func(step string, want bool) {
t.Helper()
select {
case ev := <-events:
if !want {
t.Fatalf("%s: unexpected event %q", step, ev)
}
if !strings.Contains(ev, "Warning VeleroBackupDeletionFailed") || !strings.Contains(ev, readOnly) {
t.Errorf("%s: unexpected event %q", step, ev)
}
default:
if want {
t.Fatalf("%s: no Warning event", step)
}
}
}
if res := reconcileCleanupJob(t, r); res.RequeueAfter != failedJobSweepRequeue {
t.Fatalf("first request: RequeueAfter = %v, want %v", res.RequeueAfter, failedJobSweepRequeue)
}
expectEvent("first request", false)
markOwnRequestProcessed(t, c, readOnly)
if res := reconcileCleanupJob(t, r); res.RequeueAfter != failedJobSweepRequeue {
t.Errorf("before the backoff: RequeueAfter = %v, want %v", res.RequeueAfter, failedJobSweepRequeue)
}
expectEvent("before the backoff", false)
for i, wait := range []time.Duration{5 * time.Minute, 10 * time.Minute, 20 * time.Minute} {
now = now.Add(wait)
step := fmt.Sprintf("retry %d", i+1)
if res := reconcileCleanupJob(t, r); res.RequeueAfter != 2*wait {
t.Errorf("%s: RequeueAfter = %v, want %v", step, res.RequeueAfter, 2*wait)
}
expectEvent(step, true)
markOwnRequestProcessed(t, c, readOnly)
if res := reconcileCleanupJob(t, r); res.RequeueAfter != 2*wait {
t.Errorf("%s, reconcile right after: RequeueAfter = %v, want %v", step, res.RequeueAfter, 2*wait)
}
expectEvent(step+", reconcile right after", false)
if n := len(listDeleteBackupRequests(t, c)); n != 1 {
t.Fatalf("%s: expected one request, got %d", step, n)
}
}
if got := failedJobSweepBackoff(10); got != failedJobSweepMaxRequeue {
t.Errorf("backoff after 10 retries = %v, want the %v cap", got, failedJobSweepMaxRequeue)
}
}
// Requests and backups Velero has not acted on yet are checked less often the
// longer they wait, and waiting is not reported.
func TestReconcile_FailedJobWaitingOnVeleroBacksOff(t *testing.T) {
now := time.Date(2026, 1, 1, 12, 0, 0, 0, time.UTC)
cases := []struct {
name string
veleroPhase velerov1.BackupPhase
existing []client.Object
backupAge time.Duration
want time.Duration
}{
{name: "request waiting 20m", veleroPhase: velerov1.BackupPhaseFailed, want: 20 * time.Minute,
existing: []client.Object{agedRequest(now.Add(-20 * time.Minute))}},
{name: "request waiting 3h", veleroPhase: velerov1.BackupPhaseFailed, want: failedJobSweepMaxRequeue,
existing: []client.Object{agedRequest(now.Add(-3 * time.Hour))}},
{name: "request just created", veleroPhase: velerov1.BackupPhaseFailed, want: failedJobSweepRequeue,
existing: []client.Object{agedRequest(now)}},
{name: "backup new for 3h", veleroPhase: velerov1.BackupPhaseNew, backupAge: 3 * time.Hour, want: failedJobSweepMaxRequeue},
{name: "backup new for 10m", veleroPhase: "", backupAge: 10 * time.Minute, want: 10 * time.Minute},
{name: "backup just started", veleroPhase: velerov1.BackupPhaseInProgress, want: failedJobRunningBackupRequeue},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
vb := ownedVeleroBackup(failedVeleroBackup, tc.veleroPhase)
vb.CreationTimestamp = metav1.NewTime(now.Add(-tc.backupAge))
r, c := newVeleroCleanupReconciler(t, append([]client.Object{veleroCleanupJob(backupsv1alpha1.BackupJobPhaseFailed), vb}, tc.existing...)...)
r.now = func() time.Time { return now }
if res := reconcileCleanupJob(t, r); res.RequeueAfter != tc.want {
t.Errorf("RequeueAfter = %v, want %v", res.RequeueAfter, tc.want)
}
if n := len(listDeleteBackupRequests(t, c)); n != len(tc.existing) {
t.Errorf("waiting must not create requests, got %d", n)
}
if events := r.Recorder.(*record.FakeRecorder).Events; len(events) != 0 {
t.Errorf("waiting must not be reported, got %q", <-events)
}
})
}
}
func agedRequest(created time.Time) *velerov1.DeleteBackupRequest {
dbr := deleteRequest(failedVeleroBackup, velerov1.DeleteBackupRequestPhaseInProgress)
dbr.CreationTimestamp = metav1.NewTime(created)
return dbr
}
// Recording the attempt can fail after the request was created: a job deleted
// meanwhile ends the sweep, any other error still keeps the backoff requeue.
func TestReconcile_FailedJobAttemptRecordErrors(t *testing.T) {
for name, patchErr := range map[string]error{
"job deleted": apierrors.NewNotFound(schema.GroupResource{Group: "backups.cozystack.io", Resource: "backupjobs"}, failedJobName),
"apiserver": apierrors.NewServiceUnavailable("etcd timeout"),
} {
t.Run(name, func(t *testing.T) {
funcs := &interceptor.Funcs{
Patch: func(context.Context, client.WithWatch, client.Object, client.Patch, ...client.PatchOption) error {
return patchErr
},
}
c := newVeleroCleanupClient(t, funcs,
veleroCleanupJob(backupsv1alpha1.BackupJobPhaseFailed),
ownedVeleroBackup(failedVeleroBackup, velerov1.BackupPhaseFailed))
r := &BackupJobReconciler{Client: c, Recorder: record.NewFakeRecorder(16)}
want := failedJobSweepRequeue
if apierrors.IsNotFound(patchErr) {
want = 0
}
if res := reconcileCleanupJob(t, r); res.RequeueAfter != want {
t.Errorf("RequeueAfter = %v, want %v", res.RequeueAfter, want)
}
if n := len(listDeleteBackupRequests(t, c)); n != 1 {
t.Errorf("expected the request to stay, got %d", n)
}
})
}
}
func TestReconcile_FailedJobWithoutVeleroCRDs(t *testing.T) {
funcs := &interceptor.Funcs{
List: func(ctx context.Context, c client.WithWatch, list client.ObjectList, opts ...client.ListOption) error {
if _, ok := list.(*velerov1.BackupList); ok {
return &meta.NoKindMatchError{GroupKind: schema.GroupKind{Group: "velero.io", Kind: "Backup"}}
}
return c.List(ctx, list, opts...)
},
}
c := newVeleroCleanupClient(t, funcs, veleroCleanupJob(backupsv1alpha1.BackupJobPhaseFailed))
r := &BackupJobReconciler{Client: c, Recorder: record.NewFakeRecorder(16)}
if res := reconcileCleanupJob(t, r); res.RequeueAfter != 0 {
t.Errorf("RequeueAfter = %v, want none", res.RequeueAfter)
}
}
func TestRequestVeleroBackupDeletion_ReplacesByUID(t *testing.T) {
stale := deleteRequest(failedVeleroBackup, velerov1.DeleteBackupRequestPhaseProcessed, "backup storage location unavailable")
var preconditionUID types.UID
funcs := &interceptor.Funcs{
Delete: func(ctx context.Context, c client.WithWatch, obj client.Object, opts ...client.DeleteOption) error {
do := &client.DeleteOptions{}
do.ApplyOptions(opts)
if do.Preconditions != nil && do.Preconditions.UID != nil {
preconditionUID = *do.Preconditions.UID
}
return c.Delete(ctx, obj, opts...)
},
}
c := newVeleroCleanupClient(t, funcs, stale)
req, err := requestVeleroBackupDeletion(context.Background(), c, veleroNamespace, failedVeleroBackup, true)
if err != nil || !req.created || req.replaced == nil {
t.Fatalf("requestVeleroBackupDeletion = (%+v, %v), want a replaced and a created request", req, err)
}
if preconditionUID != stale.UID {
t.Errorf("Delete precondition UID = %q, want %q", preconditionUID, stale.UID)
}
}
func TestRequestVeleroBackupDeletion_ReturnsAPIErrors(t *testing.T) {
forbidden := apierrors.NewForbidden(schema.GroupResource{Group: "velero.io", Resource: "deletebackuprequests"}, failedVeleroBackup, errors.New("denied"))
cases := map[string]interceptor.Funcs{
"list": {List: func(context.Context, client.WithWatch, client.ObjectList, ...client.ListOption) error {
return forbidden
}},
"create": {Create: func(context.Context, client.WithWatch, client.Object, ...client.CreateOption) error {
return forbidden
}},
"delete": {Delete: func(context.Context, client.WithWatch, client.Object, ...client.DeleteOption) error {
return forbidden
}},
}
for name, funcs := range cases {
t.Run(name, func(t *testing.T) {
c := newVeleroCleanupClient(t, &funcs,
deleteRequest(failedVeleroBackup, velerov1.DeleteBackupRequestPhaseProcessed, "backup storage location unavailable"))
req, err := requestVeleroBackupDeletion(context.Background(), c, veleroNamespace, failedVeleroBackup, true)
if req.created || !apierrors.IsForbidden(err) {
t.Fatalf("requestVeleroBackupDeletion = (%+v, %v), want a Forbidden error", req, err)
}
})
}
}
@@ -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)
}
@@ -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 {
@@ -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)
}
}
+95 -2
View File
@@ -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{}
@@ -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")
}
}
@@ -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)
}
}
@@ -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."
@@ -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'
@@ -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:
+3 -1
View File
@@ -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 }}
@@ -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
@@ -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
+1 -1
View File
@@ -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.
@@ -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 }}
@@ -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:
@@ -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 }}
@@ -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 `<release>-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: {}
{{- /*
@@ -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
@@ -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
+183 -10
View File
@@ -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("<release>-<email>"). 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 #
@@ -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
@@ -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 }}
@@ -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
+7 -10
View File
@@ -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 `<release>-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/<namespace>/<release>/`. | `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` |
+18 -1
View File
@@ -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:
+23
View File
@@ -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 <release>-app, with its generated password, the
role silently loses the password the init-job set from <release>-credentials.
Point the bootstrap at the chart-rendered <release>-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 }}
@@ -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 }}
@@ -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 <release>-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
@@ -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".'
@@ -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
@@ -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"'
+1 -1
View File
@@ -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": ""
},
+1 -1
View File
@@ -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 `<release>-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/<namespace>/<release>/`.
## @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`.
@@ -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
@@ -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
@@ -27,7 +27,7 @@ spec:
port: 443
targetPort: https
{{- end }}
{{- with .Values.httpAndHttps }}
{{- with .Values.kubernetesAndTalos }}
- name: kubernetes
protocol: TCP
port: 6443
@@ -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$'
@@ -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
+1
View File
@@ -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-<size>` only, as Kubernetes has no limits quota for huge pages
**Object count quotas** (passed as-is):
- `pods` - Maximum number of pods
@@ -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
@@ -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=<release>-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:
@@ -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
@@ -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=<release>-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
+1 -1
View File
@@ -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 <path_to_image>
virtctl image-upload dv {{ .Release.Name }} --no-create --namespace {{ .Release.Namespace }} --image-path <path_to_image>
{{- end }}
@@ -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 <path_to_image>'
- notMatchRegexRaw:
pattern: 'virtctl image-upload dv -n'
@@ -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-{{ . }}
@@ -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
@@ -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"
@@ -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
@@ -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
@@ -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 }}
@@ -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 }}
@@ -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 <primary>.<ns>.svc.<CLUSTER_NAME> 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"$'
@@ -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
@@ -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
-31
View File
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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=~'
@@ -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
@@ -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:
+66 -64
View File
@@ -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: <zoneName>). | `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: <zoneName>). | `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` |
@@ -1 +1 @@
ghcr.io/seaweedfs/seaweedfs-cosi-driver:v0.3.1
ghcr.io/seaweedfs/seaweedfs-cosi-driver:v0.4.0
@@ -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"
Loaded 100 of 183 files, more files were not shown because too many files have changed in this diff. Show more