Commit Graph
875 Commits
Author SHA1 Message Date
Aleksei Sviridkin 8f0082a1c8 fix(clickhouse): delete the archive when its Backup is deleted (#5224)
<!-- Thank you for making a contribution! Here are some tips for you:
- Use Conventional Commits for the PR title: `type(scope): description`
- Types: feat, fix, docs, style, refactor, perf, test, build, ci, chore
- Scopes are not an exhaustive list — pick the most specific scope for
the change and extend the list when a genuinely new area appears.
Examples:
- System components: dashboard, platform, operator, cilium, kube-ovn,
linstor, fluxcd, cluster-api
- Managed apps: postgres, mariadb, redis, kafka, clickhouse,
virtual-machine, kubernetes
- Development and maintenance: api, hack, tests, ci, docs, maintenance
- Breaking changes: append `!` after type/scope (`feat(api)!: ...`) or
add a `BREAKING CHANGE:` footer
- If it's a work in progress, consider creating this PR as a draft.
- Don't hesistate to ask for opinion and review in the community chats,
even if it's still a draft.
- Add the label `kind/backport` if it's a bugfix that needs to be
backported to a previous version.
-->

## What this PR does

Builds on #5229 (merged), which gives every backup run an archive of its
own.

Deleting a `Backup` taken with the Altinity (ClickHouse) strategy
released its finalizer at once and left the archive in the bucket. On
the system bucket nothing else prunes it, so every ClickHouse backup
stayed until someone called the sidecar by hand, and the route the chart
and the examples documented for that, `DELETE /backup/<name>/remote`,
does not exist in clickhouse-backup 2.7 and answers 404.

The driver names each archive `<application>-<start time as
YYYYMMDDHHMMSS>-<first 12 hex digits of the BackupJob UID>` (#5229) and
records it on the `Backup` under
`altinity.strategy.backups.cozystack.io/archive`. This PR also records,
under `altinity.strategy.backups.cozystack.io/use-system-bucket`, the
application's `backup.useSystemBucket` as it read when the backup Job
was created: the setting is stamped on the backup Job and copied onto
the `Backup`, because the application may switch before the controller
sees the Job complete. A Job created before the stamp existed falls back
to the application as it reads at completion. For a system-bucket
application the bucket the projected credentials (`cozy-backups-creds`)
name is recorded the same way, under
`altinity.strategy.backups.cozystack.io/bucket`. The `Backup` is created
with its cleanup finalizer already set, so a `Backup` deleted before the
`Backup` reconciler first sees it still has its archive deleted.

On `backup.useSystemBucket: true`, deleting the `Backup` runs a one-shot
cleanup Job that calls `POST /backup/delete/remote/<name>` on the
application's sidecar and holds the finalizer until it completes. The
sidecar refuses a delete with 423 while any other operation runs and
cannot be reached while its Pod restarts, so the Job waits both out
within its deadline; an archive that is already gone counts as deleted,
and any other answer fails the Job, which is reported as an
`ArtifactCleanupFailed` Warning Event carrying the reason the Job failed
and retried after a wait that starts at 30 seconds and doubles with each
failure up to 30 minutes (kept on the `Backup` under
`altinity.strategy.backups.cozystack.io/cleanup-failures` and
`.../cleanup-retry-after`, since the failed Job is deleted to make room
for the next). The Job starts only once the projected credentials have
reached the sidecar, as the backup and restore Jobs do. It is built by
the controller, not rendered as a whole from the strategy template,
because the shipped and the example templates run `restore_remote` for
every mode other than `backup`; only the image, how to pull it and where
the Pod may be scheduled (node selector, tolerations, affinity, priority
class) come from the template, rendered as for the strategy's own Pods.

When the delete cannot or must not run, the `Backup` is released with an
`ArtifactNotDeleted` Warning Event naming the archive left behind: the
namespace is terminating, the strategy, the application or its API
Secret is gone, the application no longer uses the system bucket (also
when it leaves while the delete runs), the system bucket is no longer
the one the `Backup` records or cannot be read (also when it changes
while the delete runs; a sidecar on another bucket would answer "not
found" and the delete would count as done), another Job holds the
cleanup Job name, or the archive has the older
`clickhouse-<application>-<YYYYMMDDTHHMMSSZ>` form, without its
BackupJob's UID. Such a name comes from a controller that predates
per-run names; two runs of one application started within the same
second share it, and a run still in flight when the controller is
upgraded records it later, so it is never deleted.
`backups.cozystack.io/skip-artifact-cleanup: "true"` releases a `Backup`
without deleting anything. An application on its own bucket keeps the
archive's lifecycle, as with MongoDB. The wrong delete route is
corrected in the chart comments and the restore scenario.

A BackupJob or RestoreJob no longer takes the outcome of a batch Job of
its name that it does not control. A Job left by an earlier owner of the
same name is waited out, with the `Ready` condition
(`PredecessorJobPending`) naming it, until the garbage collector removes
it; any other Job holding the name fails the BackupJob or RestoreJob
with a message naming the Job. The condition is dropped once the run's
own Job starts.

The example strategy under `examples/backups/clickhouse` now uploads
under the archive name the controller chose and restores the archive the
`Backup` records, as the shipped strategy does, keeping its clock-made
name and the newest archive only as the fallback for a run given no
name; `hack/clickhouse-example-strategy.bats` runs it against a stubbed
sidecar. The backup scenario no longer says the archive is expired by
the upstream tool's retention, which the chart does not configure.

Known limitations: a `Backup` taken before #5208, or by a custom
strategy that does not use `.ArchiveName`, does not name its archive and
keeps it; a `Backup` that names its archive but not the bucket setting,
as every `Backup` taken before this change does (a 1.7.x release that
carries #5208 among them), keeps its archive too and is released without
an Event; a `Backup` that records no bucket, taken before buckets were
recorded, is deleted without the bucket check; a `Backup` deleted during
an application uninstall can lose its cleanup Job to the chart's own
`<release>-cleanup` hook and is then released with a Warning Event,
leaving the archive; the recorded setting and bucket are read when the
backup Job is created, not observed from the upload, so a switch made
just before a backup, while the sidecar still runs on the previous
bucket, is recorded for an archive written to the previous one.

Related gap outside this PR, in main today: an archive uploaded by a run
whose `Backup` name is already taken is recorded by nothing, so no
`Backup` deletes it.

Verified with unit tests that drive the cleanup path through a fake
client and the cleanup script against a stub `curl`, with mutation
checks on every guard, and on a test cluster running v1.7.0 with the
backup controllers built from this branch (before #5229 shortened the
run name to its current form, which leaves the deletion side unchanged),
against the real clickhouse-backup sidecar and SeaweedFS: a backup
records a per-run archive name and the bucket setting on a `Backup`
created with its finalizer; deleting the `Backup` deletes the archive's
objects in the bucket; a restore from a `Backup` brings the data back; a
BackupJob recreated under a used name waits for the earlier Job and then
writes an archive of its own; a Job of that name created by anything
else fails the BackupJob; a `Backup` recording an archive named without
a UID is released with `ArtifactNotDeleted` and its objects stay. The
changes made after that run (the recorded bucket, the retry wait, the
credentials wait before the cleanup Job, the rendered cleanup Pod
settings, the cleared predecessor condition, the example strategy) are
covered by the unit tests and bats, not by a live run.

### Screenshots

<!-- REQUIRED for UI changes: attach screenshots or screen recordings
demonstrating
the visual impact of your changes. PRs with UI changes without
screenshots will not be merged. -->

### Downstream repositories

<!--
Cozystack is upstream for repositories that are NOT kept in sync with it
automatically, and nothing in CI compares the two sides, so a change
here can break them silently.

Which change forces what, and which file to touch, is the trigger map in
docs/agents/contributing.md under "Downstream Repositories". Walk it
before you tick anything.

IF YOU ARE AN AI AGENT OR AN LLM, THIS IS PART OF THE TASK, NOT A FORM
TO FILL IN:

1. Walk the trigger map against the actual diff of this PR, file by
file. Do not decide from the PR title or from your memory of what you
changed.
2. For every repository you tick, open the follow-up PR there and link
it on the same line. A ticked box with no link claims work that does not
exist, which is worse than an empty box. Search that repository for an
open PR or issue covering it first, and link that instead of filing a
duplicate.
3. When the follow-up is out of scope, or needs a decision that is not
yours to make, open an issue in that repository instead, link that, and
say so in the PR body. Do not push a speculative PR into another
repository just to fill a line here.
4. Do not tick "No downstream repository is affected" to make the
checklist go away. If you are unsure, leave every box empty and say so
in the PR body, so a human decides.
-->

- [ ] No downstream repository is affected by this change
- [x] [cozystack/website](https://github.com/cozystack/website) -
follow-up: cozystack/website#809 (for cozystack/website#808; its `next/`
pages should merge after this PR)
- [ ]
[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:
- [ ] [cozystack/community](https://github.com/cozystack/community) -
follow-up:

### Release note

<!--  Write a release note:
- Explain what has changed internally and for users.
- Start with the same `type(scope):` prefix as in the PR title
- Follow the guidelines at
https://github.com/kubernetes/community/blob/master/contributors/guide/release-notes.md.
-->

```release-note
fix(clickhouse): deleting a Backup taken on the system bucket from this release on now deletes its clickhouse-backup archive and keeps the Backup until the delete finished, reporting an archive it cannot or must not delete (including one named without its BackupJob's UID, or in a system bucket the platform has left) as a Warning Event and retrying a failed delete with a growing wait; the cleanup Pod is scheduled as the strategy's own Pods; a BackupJob or RestoreJob no longer reports the outcome of a batch Job it did not create; the documented sidecar delete route is corrected to POST /backup/delete/remote/<name>.
```


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

## Summary by CodeRabbit

* **New Features**
* ClickHouse backups using the system bucket now remove their recorded
archive when the backup is deleted. Deletion waits for cleanup to
finish.
* Backup and restore operations use the controller-provided archive name
when available. Restores can fall back to the latest matching archive.
* **Bug Fixes**
* Temporary sidecar failures are retried with increasing delays. If
cleanup cannot safely remove an archive, it completes with a warning
rather than risking deletion of the wrong archive.
* **Documentation**
* Clarified that archives in tenant-owned buckets remain until manually
deleted or removed by bucket lifecycle rules.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-11-23 16:27:05 +03:00
Aleksei Sviridkin 2af1e21299 fix(gateway): copy allowed routes for the edge listener (#4167)
## What this PR does

Fixes #4118. The `edge` listener retained the renderer's local
`edgeAllowedRoutes` value, while `edge-apex` and child listeners already
received independent copies. Give `edge` its own `DeepCopy()` as well,
so later changes to the local value cannot reach the rendered listener.
The rendered Gateway configuration is unchanged.

The change is confined to that one assignment. Current main already
creates independent allowed-routes values for HTTPS and TLS-passthrough
listeners.

Validation: `go test ./internal/controller/tenantgateway -count=1`
passes. No new test is added, as accepted in the maintainer's review.

### Downstream repositories

- [x] 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:
- [ ] [cozystack/community](https://github.com/cozystack/community) -
follow-up:

The diff changes only ownership of a local allowed-routes value; API
fields, namespace selectors, route kinds, package layout and rendered
resources stay the same, so it reaches none of the downstream trigger
map's contracts.

### Release note

```release-note
fix(gateway): give the edge TenantGateway listener its own allowed-routes copy; rendered Gateway configuration is unchanged
```


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

* **Bug Fixes**
* Fixed edge-mode gateway listeners so each retains its own
allowed-routes configuration.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-11-23 15:12:14 +03:00
Aleksei Sviridkin b7e72840f9 fix(gateway): skip a child apex the wildcard certificate already covers (#5148)
## What this PR does

In DNS-01 mode the controller added every inheriting child tenant's apex
to the parent Gateway's wildcard Certificate. When the child's host
derives one label below the parent (`ci.mgmt.example.com` under
`mgmt.example.com`), the parent's `*.mgmt.example.com` already covers
that apex, and Let's Encrypt refuses the whole order as redundant, so
the parent Gateway is left with no certificate for any of its hostnames.

`renderWildcardCertificate` now skips a child apex when `*.` plus the
apex without its first label is among the wildcards in the same
Certificate, which is the check Boulder runs in `wildcardOverlap`. The
child's own `*.<child-apex>` stays, and an apex two labels below every
wildcard stays listed, because a certificate wildcard matches exactly
one label. That is also why this does not reuse `hostnameCovers`, which
follows Gateway API matching at any depth. The wildcard set is collected
before the loop because `childApexes` is sorted by name and a covering
child wildcard can sort after the apex it covers.

`TestReconcile_DNS01WildcardCertCoversInheritingChildApexes` asserted
the redundant `alice.example.org` SAN and now asserts its absence. The
new `TestRenderWildcardCertificate_SkipsChildApexCoveredByWildcard`
covers the reported case, a child two labels down, a covering wildcard
that sorts late, and an empty or unrelated apex; the reported case and
the late sorting case fail without the fix. The README paragraph that
describes the SAN list is updated to match. `go test -p 2 ./internal/...
-count=1` and `go vet ./internal/controller/tenantgateway/` pass
locally.

Fixes #5125

### Screenshots

No UI change.

### Downstream repositories

- [ ] No downstream repository is affected by this change
- [x] [cozystack/website](https://github.com/cozystack/website) -
follow-up: https://github.com/cozystack/website/issues/779
- [ ]
[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:
- [ ] [cozystack/community](https://github.com/cozystack/community) -
follow-up:

### Release note

```release-note
fix(gateway): the DNS-01 wildcard Certificate no longer lists a child tenant's apex that the parent's wildcard already covers, so Let's Encrypt stops refusing the order and the parent Gateway gets its certificate again.
```


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

## Summary by CodeRabbit

* **Bug Fixes**
* Wildcard certificates now omit child apex names already covered by an
existing wildcard while retaining the child wildcard names. Apex names
not covered by a wildcard remain included, and duplicate or empty apex
names are excluded. This keeps certificate names focused on the names
needed for coverage.
* **Documentation**
* Clarified how child apex and wildcard names are included in DNS-01
certificates, including when a child apex is covered by an existing
wildcard.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-11-23 14:58:09 +03:00
Alexey Artamonov a2f7ea18ee fix(clickhouse): drop the predecessor wait once a run's own Job starts
A BackupJob or RestoreJob that waited for the Job of an earlier owner
of its name kept its Ready=False PredecessorJobPending condition after
that Job was gone and its own Job had started, so for the whole run it
still said it was waiting for the garbage collector.

The condition is now dropped when the run's own Job is running, the
way the credentials wait is.

Assisted-by: LLM
Signed-off-by: Alexey Artamonov <aleksei.artamonov@aenix.io>
2026-11-23 12:15:07 +03:00
Alexey Artamonov 084fed9e2f fix(clickhouse): take no restore Job's result that this RestoreJob did not run
The restore path took any Job standing under a RestoreJob's Job name as
its own, so a RestoreJob re-created under a used name met the completed
Job of the earlier one before the garbage collector removed it and was
marked Succeeded although nothing was restored for it.

The restore path now refuses such a Job the way the backup path does:
the Job of an earlier RestoreJob of the same name is waited out, with
the Ready condition naming it, and any other Job holding the name
fails the RestoreJob.

Assisted-by: LLM
Signed-off-by: Alexey Artamonov <aleksei.artamonov@aenix.io>
2026-11-23 12:15:06 +03:00
Alexey Artamonov e199ef1d83 fix(clickhouse): take no backup Job's result that this BackupJob did not run
A Job standing under a BackupJob's Job name was taken as its own. A
BackupJob re-created under a used name, as a Plan does when the
BackupJob of a schedule slot is deleted within the slot's starting
deadline, met the completed Job of the earlier one before the garbage
collector removed it, was marked Succeeded without uploading anything,
and recorded a Backup for an archive nobody uploaded for it.

A Job controlled by an earlier BackupJob of the same name is now
waited out, with the Ready condition naming it; any other Job holding
the name fails the BackupJob, since nothing will remove it.

Assisted-by: LLM
Signed-off-by: Alexey Artamonov <aleksei.artamonov@aenix.io>
2026-11-23 12:15:05 +03:00
Alexey ArtamonovandYan Bondarenko 564bdd3a79 fix(clickhouse): delete the archive when its Backup is deleted
Deleting a Backup taken with the Altinity strategy released its
finalizer at once and left the archive in the bucket. On the system
bucket nothing else prunes it, so every ClickHouse backup stayed until
someone called the sidecar by hand.

Deleting such a Backup now runs a one-shot Job that asks the
application's sidecar to delete the archive the Backup records, and
holds the finalizer until the Job completes. The driver creates the
Backup with the finalizer already set, so a Backup deleted before the
reconciler first sees it still gets its archive deleted. An archive
that is already gone counts as deleted. The sidecar refuses a delete
while another operation runs, and cannot be reached while the
ClickHouse Pod restarts, so the Job waits both out within its
deadline; any other refusal fails the Job, which is reported as an
ArtifactCleanupFailed Warning Event carrying the reason it failed.

Each failure doubles the wait before the next cleanup Job, from 30
seconds up to 30 minutes, so a delete the sidecar refuses for good,
such as one made with a wrong password, does not cost a Job, its Pod
and a Warning Event every few seconds. The count of failures and the
time the next Job may start are kept on the Backup, because the Backup
controller does not watch Jobs; a start time further ahead than the
longest wait, from a skewed clock or a hand edit, is logged and
ignored. A Job the namespace's Job quota refuses is retried once a
slot frees up rather than released, since the Backup would be gone by
then and nothing would delete the archive.

The Job is built by the controller, not rendered from the strategy
template, because the shipped and the example templates run a restore
for every mode other than backup. Only the image, how to pull it, and
the node selector, tolerations, affinity and priority class come from
the template, rendered against the application and the Backup as for
the strategy's own Pods, so the cleanup Pod can be scheduled where
they are. The strategy is read only when a Job has to be created, so a
running delete outlives it. The Job also waits for the projected
credentials to reach the sidecar, as the backup and restore Jobs do: a
sidecar still serving the previous bucket answers "not found", and the
delete would count as done.

When the delete cannot run, the Backup is released with an
ArtifactNotDeleted Warning Event naming the archive left behind: the
namespace is terminating, the strategy, the application or its API
Secret is gone, the application has left the system bucket, the
platform's system bucket is no longer the one the Backup records (also
when it changes while the delete runs), another Job holds the cleanup
Job name, or the API server refuses the Job. An archive named without
its BackupJob's UID is released the same way: such a name comes from a
run that crossed the controller upgrade, and another run started in
the same second may share it. The
backups.cozystack.io/skip-artifact-cleanup annotation releases the
Backup without starting a delete. An application on its own bucket
keeps the archive's lifecycle, as with MongoDB.

The restore scenario and the chart comments told tenants to delete an
archive with DELETE /backup/<name>/remote, which clickhouse-backup 2.7
answers with 404; they now name POST /backup/delete/remote/<name>.

Co-authored-by: Yan Bondarenko <202671653+yankawai@users.noreply.github.com>
Assisted-by: LLM
Signed-off-by: Alexey Artamonov <aleksei.artamonov@aenix.io>
Signed-off-by: Yan Bondarenko <202671653+yankawai@users.noreply.github.com>
2026-11-23 12:15:05 +03:00
Alexey Artamonov b62f2f385f fix(clickhouse): record the bucket setting a ClickHouse backup was taken with
A ClickHouse application writes its archives either to the system
bucket, which nothing prunes, or to its own bucket, whose lifecycle is
the tenant's. A Backup did not say which applied, so nothing deciding
the fate of the archive when the Backup goes could tell them apart.

The application's useSystemBucket is read when the backup Job is
created, stamped on the Job and copied onto the Backup from there,
because the application may switch before the controller sees the Job
complete. It is the setting, not an observation of the bucket: the
sidecar uploads to the bucket it was last restarted with, so a switch
made just before the backup can be recorded while the sidecar still
writes to the previous bucket. A Job created before the stamp existed
falls back to the application as it reads then.

Assisted-by: LLM
Signed-off-by: Alexey Artamonov <aleksei.artamonov@aenix.io>
2026-11-23 12:15:04 +03:00
somazandYan Bondarenko 8382ed1a92 fix(gateway): skip a child apex the wildcard certificate already covers
In DNS-01 mode every inheriting child tenant's apex went into the
parent Gateway's wildcard Certificate. When a wildcard in the same
Certificate already covers that apex one label up, Let's Encrypt
refuses the whole order as redundant and the parent Gateway gets no
certificate at all. Skip such a SAN, matching the single-label check
Boulder runs in wildcardOverlap.

A child may also use a broader custom domain than the gateway. Its
wildcard then covers the gateway apex, so the same check drops the
gateway SAN too.

Closes: #5125
Co-authored-by: Yan Bondarenko <202671653+yankawai@users.noreply.github.com>
Assisted-by: LLM
Signed-off-by: somaz <genius5711@gmail.com>
Signed-off-by: Yan Bondarenko <202671653+yankawai@users.noreply.github.com>
2026-11-23 10:59:26 +03:00
Mattia Eleuteri addf7d1258 fix(lineage-webhook): leave a running Pod's scheduler alone on update
spec.schedulerName cannot change once a Pod exists, yet the webhook set
it on every Pod admission, updates included. A Pod created before its
tenant got a class, or before its application named one, then had
every later update refused by the apiserver, labels and annotations
written by controllers included. A class can only take effect when the
Pod is created.

Assisted-by: LLM
Signed-off-by: Mattia Eleuteri <mattia@hidora.io>
2026-11-23 08:05:10 +01:00
Mattia Eleuteri e67a514903 fix(lineage-webhook): keep the tenant class when an application's is refused
The webhook fell back to the tenant class only when an application
left spec.schedulingClass empty. A value naming a class that does not
exist, or one the tenant does not allow, left the pod with no
scheduler at all, so a typo, or a deliberate bogus name, in any
application lifted the placement constraint the tenant administrator
had set.

Admission sees the application only once, so a class removed from the
allowed list afterwards has to be caught here as well. Naming the
tenant's own class needs no entry in the list, being the same as
leaving the field empty.

The application class is looked up once, so a class deleted between
deciding and injecting cannot leave the pod with neither class. A
lookup error fails the admission instead of counting as absence:
otherwise a timeout or a 5xx from the apiserver would admit the Pod on
the default scheduler, outside the tenant's constraint, until it was
recreated. Under failurePolicy Fail its controller retries. Only an
absent class, or an absent SchedulingClass CRD, means there is nothing
to inject.

Assisted-by: LLM
Signed-off-by: Mattia Eleuteri <mattia@hidora.io>
2026-11-23 08:05:08 +01:00
Mattia Eleuteri aed71ed610 test(lineage-webhook): cover the per-application scheduling class
The applySchedulingClass tests only ever passed a nil owner, so the
path where an application's class takes over from the tenant's, and
the guard that keeps an over-long class name off the Pod labels, could
break unnoticed. The owner is built as unstructured, as the lineage
walk returns it, because its conversion into Application.Spec.Raw is
part of that path.

Assisted-by: LLM
Signed-off-by: Mattia Eleuteri <mattia@hidora.io>
2026-11-23 08:05:07 +01:00
Mattia Eleuteri 0132457260 feat(apps): expose schedulingClass across all managed applications
Placement could only be set per tenant, so two applications of the
same tenant could not be kept together, or apart, unless each had a
tenant to itself. With a class per application and the scheduling-class
Pod label, a SchedulingClass name can serve as a co-affinity group: a
database and the virtual machine that uses it can be kept in the same
region without pinning which one.

The field is capped at 63 characters. A SchedulingClass name may be up
to 253, but the webhook writes the class into a Pod label, and this is
the first source of the class the apiserver has not already validated
as a label value; capping it is cheap while the field is new and a
breaking change once released. A class created with a longer name must
still not break Pod admission, so for it only the label is left out.

kubernetes-nodes gets no field: the ownership walk from a worker Pod
reaches the parent Kubernetes application, never the pool, so a class
set on a pool would be accepted and silently ignored.

Placement per replica role (primary or standby of a clustered
database) is out of scope: the operator assigns the role after
election, once the webhook has already seen the pod.

Assisted-by: LLM
Signed-off-by: Mattia Eleuteri <mattia@hidora.io>
2026-11-23 08:05:06 +01:00
Timofei Larkin 65cb73e380 fix(lineage-webhook): keep an explicit tenantresource false (#4920)
## What this PR does

Lets a chart narrow the lineage webhook's
`internal.cozystack.io/tenantresource` verdict without being able to
widen it. The webhook computes the verdict from the
ApplicationDefinition's `secrets` selectors on first admission and
copied it over whatever label the chart rendered, so a Secret the
definition still selected was projected through
`core.cozystack.io/tenantsecrets` whatever the chart said. A `"false"`
rendered on a Secret the webhook admits for the first time (CREATE) is
now kept; a rendered `"true"` is still replaced by the computed verdict.
A re-admission (UPDATE with `managed-by-cozystack` dropped, which the
cacert controller does on a selector change) still gets the definition's
verdict, because the `"false"` it carries is the one this webhook wrote
earlier.

This is rollout step 2 of the accepted [user secrets API
proposal](https://github.com/cozystack/community/blob/main/design-proposals/user-secrets-api/README.md):
during a kind's conversion the converted chart renders the platform-only
`<release>-credentials` Secret with `tenantresource: "false"` while the
old definition may still select the name, and the label is what keeps
that Secret off the projection in the window. It ships on its own
because nothing else depends on it and the conversions do.

Behaviour otherwise unchanged: an object with no rendered label gets the
definition's verdict as before, and the re-admission short-circuit on
`managed-by-cozystack` is untouched.

Covered by a handler test: on CREATE, a rendered `false` kept where the
selector matches, a rendered `true` overwritten where it does not, and
no rendered label taking the verdict; on a re-admission UPDATE, a grant
where the selector now matches and a revoke where it no longer does.

### Screenshots

No UI change.

### Downstream repositories

Walked the trigger map against the diff: two files under
`internal/lineagecontrollerwebhook`, no CRD, no package, no chart, no
values, no `hack/` change. The ApplicationDefinition's selector
semantics gain one exception, but the website's ApplicationDefinition
page does not describe the projection verdict at that depth, so there is
nothing there to update.

- [x] 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:
- [ ] [cozystack/community](https://github.com/cozystack/community) -
follow-up:

### Release note

```release-note
fix(lineage-webhook): a Secret created with `internal.cozystack.io/tenantresource: "false"` keeps that label even where its ApplicationDefinition selects the name, so a chart can take a Secret off the tenantsecrets projection; a rendered `"true"` is still overwritten by the definition's verdict.
```


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

## Summary by CodeRabbit

* **Bug Fixes**
* On resource creation, an existing `false` tenant-resource label is
preserved even when the configured selector matches. Otherwise, the
label reflects the selector’s verdict. On updates, the label is set
according to the selector.
* **Tests**
* Added coverage for tenant-resource label behavior on creation and
updates, including existing and missing labels.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-11-22 23:53:22 +04:00
Andrei Kvapil e11ca91d81 fix(backups): stop leaking MariaDB dumps of stuck runs and torn-down namespaces (#5344)
## What this PR does

Closes #5291. Two paths left a MariaDB dump and its
`k8s.mariadb.com/Backup` behind after the dump cleanup from #5233.

**A run that never completes.** When the operator Backup stays short of
`Complete` past `mariadbDefaultBackupDeadline`, the BackupJob now
deletes it (background propagation, so its Job goes too) before it marks
itself `Failed`, and says so in the failure message. No Cozystack
`Backup` is ever made of such a run, so nothing else deleted it, and
while it stood its window had no end: `contestedMariaDBDump` counted it
as a possible writer of every later dump of the application, and every
later `Backup` was released with `ArtifactNotDeleted`. Deleting the Job
also stops a run that is still going from uploading a dump nobody
tracks. An operator Backup that is `Complete=True` on a reason the
driver does not know has a bounded window and is kept, as before.

The decision is made on the operator Backup read from the API server,
not the cache. A run the operator has just marked complete or failed
goes down the normal path and is not deleted. The delete carries the UID
and resourceVersion that were read, so a run that completes between the
read and the delete is not deleted either. Past the deadline no new run
is created, so a pass that deleted the run and then failed to persist
`Failed` does not start another one on retry. A delete the API server
keeps refusing shows as `Ready=False/OperatorBackupDeleteFailed` on the
BackupJob. The delete also removes the run's pod, so before it the
controller copies what held the pod up into the failure message: an
unschedulable pod, or a container that is waiting or has failed.

The MariaDB driver's other failure exits take the same path: the MariaDB
application was deleted, the MariaDB CR never came back, the strategy
disappeared past its deadline, the strategy no longer renders, the
applicationRef is rejected, or the run could not be created. Past the
deadline, the run is taken from the API server listing and
`ensureMariaDBBackup` is not called, so a cache that has not seen the
run cannot cause a second one to be created. mariadb-operator leaves the
run of a MariaDB that went away at `Complete=False` for good, so if the
application was later recreated under the same name, that run used to
contest every later dump.

The deadline is still 30 minutes from `StartedAt`, but a dump that is
still running at that point is now stopped instead of being left to
finish outside Cozystack.

**Namespace teardown.** mariadb-operator puts no finalizer on its
`Backup`, so during teardown it is usually gone before the Cozystack
`Backup` finalizer runs. When the operator Backup is not found, the
cleanup now:

- takes bucket, prefix and Secret references from the snapshot in
`status.underlyingResources`;
- goes on only for a recorded dump (`k8s.mariadb.com/dump-file`) on the
platform bucket written with the projected platform Secret, reached with
the platform credentials, which do not depend on the namespace;
- keeps the dump, with a `Warning ArtifactNotDeleted`, when another
operator Backup, finished or not, could have written it (the same
`contestedMariaDBDump` check as before);
- retries a failed delete through `retryMariaDBCleanup`, which releases
the `Backup` once the namespace is terminating.

The snapshot and the storage URI now record the storage the run was
created with, whatever its kind, rather than the strategy as rendered
when the run completed. A strategy edited during a run therefore cannot
send the cleanup to the wrong place. The BackupJob looks for its run on
the API server rather than in the cache, so a retry after a failed
status write never starts a second run. A `Running` BackupJob never
starts a run at all, and if its run is gone the job is failed.

A `Backup` with no recorded dump, no snapshot, a dump on another bucket
or written with the tenant's own Secret, or unreadable platform
credentials is released with a `Warning`, as before. A missing operator
CRD keeps the old release path.

The platform-bucket check that `mariadbCleanupConnection` used is now
`mariadbPlatformConnection`, shared by both paths. Its behaviour is
unchanged.

Not covered:
- Operator Backups left behind by BackupJobs that failed before this
change are still there, because terminal BackupJobs are not reconciled
again. Deleting them by hand releases the dumps they hold.
- Deleting a BackupJob that is still running leaves its operator Backup,
which has no ownerRef and no finalizer. This was already the case and is
not addressed here.
- The driver-independent terminal exits in `backupjob_controller.go`
(BackupClass resolution, credentials projection) still fail a BackupJob
without looking at a MariaDB run.
- A run that is stopped at the deadline after it has uploaded its dump
leaves that dump untracked. No `Backup` is ever made of such a run. The
other fail-safe cases listed in the issue (a `Restore` that never
completes, the single `Backup` worker, non-204 DELETE responses,
endpoint moves) are not addressed here.

Tests: `go test ./internal/backupcontroller/...`. The deadline outcome
table now also checks whether the operator Backup was deleted. New
cleanup tests cover a missing operator Backup: the dump deleted with the
platform credentials, already absent, contested by an unfinished run, a
failed delete held for retry, and each case it cannot reach (volume
storage, a recorded name that is not a dump, a snapshot of another
kind). Deadline tests cover a retry after a failed status write, a cache
that trails a completed run or misses a new one, a delete conditional on
the run that was read, a refused delete, and the application or MariaDB
going away mid-run.

### Screenshots

N/A, no UI changes.

### Downstream repositories

I checked the trigger map in `docs/agents/contributing.md` against the
diff. The diff touches `internal/backupcontroller/mariadbstrategy_*.go`
and their tests. It also adds a message helper in
`internal/backupcontroller/backupjob_controller.go` and changes comments
in `internal/backupcontroller/backup_controller.go` and
`packages/system/backupstrategy-controller/templates/rbac.yaml`. No
values, schemas, CRDs, RBAC rules, annotations or telemetry change.

- [x] 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:
- [ ] [cozystack/community](https://github.com/cozystack/community) -
follow-up:

### Release note

```release-note
fix(backups): MariaDB dumps are no longer left in the bucket when a backup run never completes or when a tenant namespace is deleted. A BackupJob that times out now deletes the operator Backup it gave up on, so that run no longer blocks the deletion of later dumps. A Backup whose operator Backup is already gone now deletes its recorded dump from the platform bucket using the platform credentials. A MariaDB backup run that has not completed 30 minutes after its BackupJob started is now stopped.
```


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

## Summary by CodeRabbit

* **Bug Fixes**
* MariaDB backup cleanup now removes a recorded dump from the platform
bucket when its operator Backup is already gone, while leaving contested
or insufficiently verified dumps untouched.
* Failed dump deletions are retried, and cleanup reports when a dump is
already absent.
* Backup jobs are less likely to start duplicate runs during retries,
and completed backups retain the storage configuration used by their
run.
* Failure handling preserves completed runs and includes operator-run
completion details when available.
* Backup jobs now recheck the operator Backup before failing on a
deadline, helping account for runs that completed or failed in the
meantime.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-11-20 04:59:41 -05:00
Andrey Kolkov dbc088f862 fix(backups): enforce the Velero deletion backoff of failed BackupJobs
The retry backoff of the failed-job sweep only set RequeueAfter. Writing the
retry counter onto the BackupJob triggers a reconcile at once, since the
BackupJob watch has no predicate. When Velero processes a request instantly,
as it does when the backup storage location is missing or read-only, that
reconcile replaced the request again, emitted another event and raised the
counter without any wait. The sweep now records when it last created a
request, in the backups.cozystack.io/velero-deletion-attempted-at annotation,
and replaces a processed request only after the backoff for the current
count has passed since then. Before that, it requeues for the remaining
time.

A request Velero never processes, because Velero is down, and a Velero
backup stuck in New or with no phase were checked at a fixed interval,
each check with an uncached list of Backups. They are now checked again
after as long as they have already waited, from the request's or the
backup's creation time, capped at one hour. Waiting emits no event.

Recording the attempt can fail after the request was created. If the job
was deleted meanwhile, the sweep ends without an error. Any other error is
logged and the computed requeue is kept, because failing the reconcile
would only retry sooner.

Unit tests drive the clock through two back-to-back reconciles of an
instantly processed request (one replacement, one event), then three
retries at 10, 20 and 40 minutes. They also check the waiting intervals for
requests and backups of different ages, and both annotation write errors.

Refs: #5355
Assisted-by: LLM
Signed-off-by: Andrey Kolkov <androndo@gmail.com>
2026-11-19 21:07:17 +07:00
Andrey Kolkov 73df99b77d fix(backups): retry stuck Velero deletions of failed BackupJobs and report them
Velero marks a backup Deleting before it removes the data and leaves it in
that phase when removing the data fails, with the deletion request
processed with errors. The failed-job sweep skipped Deleting backups and
did not requeue for them, so their data stayed in the bucket until
Velero's TTL. Deleting backups now go through the same request path: a
pending request is left alone, and a processed one of ours is replaced.

A request of ours that Velero processed without errors is also replaced
when the backup still exists, for example after the BSL sync brought it
back. Otherwise the request name blocked a new attempt until Velero
garbage-collects processed requests a day later.

When Velero can never carry out the deletion, because the backup storage
location is missing, read-only or unavailable, the sweep replaced the
request every 5 minutes without any sign of it. Each replacement now
emits a VeleroBackupDeletionFailed Warning event on the BackupJob with
Velero's status.errors, and doubles the requeue interval from 5 minutes
up to 1 hour. The count is kept in the
backups.cozystack.io/velero-deletion-retries annotation, because the
replaced request is gone and a requeue carries no state. The
controller's ClusterRole already allows patching BackupJobs.

Unit tests cover a Deleting backup with a pending request and with an
errored one, a cleanly processed request whose backup still exists, an
errored request under a foreign name that is left alone, three
consecutive failed deletions (three events, 10m, 20m and 40m requeues,
the 1h cap), and a cluster without the Velero CRDs.

Refs: #5355
Assisted-by: LLM
Signed-off-by: Andrey Kolkov <androndo@gmail.com>
2026-11-19 20:56:45 +07:00
Andrey Kolkov 887453c008 fix(backups): keep completed Velero backups of failed BackupJobs
The failed-job sweep treated a Completed Velero backup as deletable. A
BackupJob can fail after Velero completed, when creating or recording its
Backup fails transiently, and that Velero backup may be the only copy of a
good backup. The sweep now deletes only Failed, PartiallyFailed and
FailedValidation backups, also when several Velero backups reference one
job, and it reads the Backups that may reference them through the uncached
API reader, so a Backup the cache has not seen yet still protects its data.

The Velero strategy no longer requests the deletion before it records the
failure. If that status write failed, Velero removed the backup and the
retried run created a new one, so the failure was lost. The deletion now
comes only from the sweep, which runs on the reconcile that the persisted
Failed phase triggers; the BackupJob watch has no predicate that drops
status updates.

Replacing a request that Velero processed with errors deletes it, and the
backupstrategy-controller ClusterRole only allowed create, get, list and
watch on deletebackuprequests. That Delete failed with 403, and since the
Backup finalizer uses the same helper, a Backup deletion could get stuck
on it. The rule now includes delete.

Nothing watches DeleteBackupRequests, so the sweep did not run again after
Velero processed a request with errors. A Failed job now requeues every
5 minutes while a failed Velero backup of it remains, which replaces such a
request, and every minute while one is still running, instead of every 5
seconds.

Unit tests cover a rejected Failed status write, Completed, Deleting and
FailedValidation backups, a request processed with and without errors, the
UID precondition on the replacement, a Backup visible only to the uncached
reader, and API errors from the helper.

Refs: #5355
Assisted-by: LLM
Signed-off-by: Andrey Kolkov <androndo@gmail.com>
2026-11-19 20:44:11 +07:00
Andrey Kolkov 5fbf7e9a38 fix(backups): delete the Velero backup of a failed BackupJob
When a Velero strategy run ended Failed or PartiallyFailed, no Backup was
created, and the Backup finalizer was the only code that asked Velero to
delete backup data. The failed backup.velero.io object, labelled for the
BackupJob but not owned by it, stayed in the bucket with its partial
resources and logs until Velero's TTL (720h by default) expired it, and
deleting the BackupJob did not remove it.

The strategy now requests the deletion through a DeleteBackupRequest before
it marks the job Failed, and the failure message is still read from the
Velero backup first. A direct delete is not enough, because the BSL sync
recreates the object from the object store. A reconcile of a Failed
BackupJob, which used to return at once, now requests deletion of every
Velero backup still labelled for the job. That retries a request that could
not be created and removes backups that earlier versions leaked, after an
upgrade. A Velero backup that a Backup references (the job failed after its
Backup was created) is left alone, and one still running is polled until
Velero accepts a request for it. The sweep matches on the job labels, so it
also covers the Velero backup of a failed Kubernetes strategy run.

The request is named after the Velero backup, and the Backup finalizer uses
the same helper, so repeated reconciles converge on one request. Nothing is
created while another request for the backup is pending. A request that
Velero processed with errors is replaced, because Velero keeps it for a day
and its name would block the retry until then. A job with more than one
Velero backup now fails with a message that names them, not with an empty
one.

Fake-client unit tests cover Failed and PartiallyFailed runs, a repeated
reconcile, leftovers of already Failed jobs (no request, a pending request,
a request processed with errors, a Backup-referenced backup, a running
backup) and the unchanged Succeeded path.

Closes: #5355
Assisted-by: LLM
Signed-off-by: Andrey Kolkov <androndo@gmail.com>
2026-11-19 20:31:34 +07:00
Aleksei Sviridkin d88322197f chore(deps): roll up Renovate updates and raise dependencies to latest stable (#4869)
## What this PR does

One PR instead of separate Renovate PRs. Go modules, Dockerfile base
images and GitHub Actions move to newer versions that build and pass the
tests. Where a newer version is known to break something, it stays
behind, and `.github/renovate.json` holds it with the reason in the rule
description.

The tests come first, in their own commits:

- `make go-unit-tests` runs the Go tests under `pkg/` and `cmd/`, except
the backport-batch suite, which keeps its own target. The apiserver
serializer and fuzz tests, the generated OpenAPI and applyconfiguration
suites, the apis packages and the controller, operator and
observability-proxy commands did not run in CI before.
- The apps API surface that apiserver libraries shape is pinned:
server-side apply, content negotiation, Table output on watch, the
served OpenAPI v2 and v3 documents, and building the server without
etcd. Two answers look wrong and are pinned as they are today: applies
from different field managers never conflict (#4857), and protobuf is
refused with 406 even when the client offers JSON as a fallback (#5297).
- New tests cover the kubeovn webhook patch, the token proxy session
cookie and the mount-utils behaviour the kubevirt CSI node service
relies on.
- `hack/image-smoke.bats` checks the tools the CSI, LINSTOR, multus,
Harbor and redis-backup images take from their base images or build
stages, and that the kubevirt CSI node plugin and its sidecars need no
more than x86-64-v2. Each PR build job runs it against the images it
pushed; forks and the unit lane run no container.

The tests found two bugs:

- The kubeovn webhook dereferenced a nil pointer on an admission review
without a request, so the caller got a dropped connection instead of a
400.
- The token proxy cookie refresh never fired: securecookie decodes the
session times as int64 and the refresh looked for float64, so the
`--cookie-refresh=1h` the chart sets did nothing. A refreshed cookie
keeps the token's expiry. A session too large to encode now shows an
error at sign-in and leaves the current cookie alone on refresh.

What moved:

- GitHub Actions to their Node 24 majors. The flux action stays on the
tag of the Flux CLI it installs. The release job's checkout no longer
persists credentials, so its staging branch push uses the App token.
- Go 1.27.2 for the toolchain and builders. Builds that reproduce an
upstream release keep the Go upstream uses: Harbor, cilium-operator,
SeaweedFS and the chainsaw stage of the e2e sandbox.
- controller-runtime v0.25.2, gateway-api v1.6.3 on the minor of the
installed v1.6.1 CRDs, cel-go v0.30.0, grpc v1.84.0, etcd v3.7.2,
cert-manager v1.21.2, kubevirt csi-driver f10ae94 on Kubernetes v0.37.1.
- Node 24 for the dashboard console.

Held back, each with its reason in the Renovate rule:

- cel-go stays below v0.31: the old repository has no tags past v0.30.0,
and v0.32 moves to cel.dev/cel-go, which k8s.io/apiserver does not
import.
- kube-openapi stays on the commit its dependencies require, and
structured-merge-diff stays on v6, because k8s.io/apimachinery v0.37
does not compile against v7.
- The Flux API modules stay on the Flux v2.8 line the platform installs.
- gomodules.xyz/jsonpatch stays on v2, which controller-runtime's
admission.Patched takes.
- jwx stays on v3: v4 removes jwk.Cache, which the token proxy's JWKS
refresh is built on.
- kubevirt.io/api and the CDI API stay where upstream csi-driver builds.
- The kubevirt CSI driver image stays on AlmaLinux 9, because AlmaLinux
10 builds its amd64 userland for x86-64-v3.
- shadowbox stays on node 18, which outline-server declares in its
engines.
- The e2e sandbox stays on Ubuntu 24.04. 26.04 ships uutils coreutils,
whose `date` costs about 4x per call, and the test harness forks it per
traced line, which adds about ten minutes to the install phase.
- clastix/kubectl stays on v1.32 for the cleanup hooks, within kubectl's
one-minor skew.

The cert-manager Go module (v1.21.2) is one minor ahead of the installed
chart (v1.20.2). The Certificate objects the gateway controller writes
serialize the same either way.

`api/apps/v1alpha1` now requires Go 1.27.2, which applies to every
module that imports the published types.

The Linux run with Go 1.27.2 was done before the rebase onto current
main, and the rebased head has not been through it yet. There the five
modules built, vetted, tested and tidied cleanly, and the repository
unit, controller and envtest lane passed. `go test -race` passed in four
modules. In the root module it failed only on a pre-existing data race
in the workload monitor tests (#5296), which main has too. The image
smoke checks run in this PR's CI.

### Screenshots

No UI change.

### Downstream repositories

`api/apps/v1alpha1` moves to `go 1.27.2`, and
cozystack/terraform-provider-cozystack imports it, so that repository is
affected but needs no action. Its box stays empty for that reason, and
so does the "not affected" one.

- [ ] 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: none needed, because its Renovate raises the go directive
together with the pin bump and its CI takes Go from `go.mod`; the only
effect is that the provider's minimum Go becomes 1.27.2.
- [ ]
[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:
- [ ] [cozystack/community](https://github.com/cozystack/community) -
follow-up:

### Release note

```release-note
chore(deps): move the toolchain and builder images to Go 1.27.2 and raise Go modules, base images and GitHub Actions to newer working releases; the dashboard token proxy now refreshes its session cookie, and the kube-ovn webhook rejects an admission review without a request instead of dropping the connection.
```
2026-11-18 14:42:34 +03:00
Aleksei Sviridkin a3e60ec372 feat(kafka)!: run on Strimzi 1.2.0 and Kafka 4.x (#4900)
<!-- Thank you for making a contribution! Here are some tips for you:
- Use Conventional Commits for the PR title: `type(scope): description`
- Types: feat, fix, security (a fix that comes through a security
advisory), docs, style, refactor, perf, test, build, ci, chore
- Scopes are not an exhaustive list — pick the most specific scope for
the change and extend the list when a genuinely new area appears.
Examples:
- System components: dashboard, platform, operator, cilium, kube-ovn,
linstor, fluxcd, cluster-api
- Managed apps: postgres, mariadb, redis, kafka, clickhouse,
virtual-machine, kubernetes
- Development and maintenance: api, hack, tests, ci, docs, maintenance
- Breaking changes: append `!` after type/scope (`feat(api)!: ...`) or
add a `BREAKING CHANGE:` footer
- If it's a work in progress, consider creating this PR as a draft.
- Don't hesistate to ask for opinion and review in the community chats,
even if it's still a draft.
- Fixes merged to `main` reach the release lines the backport batch runs
for automatically, so do not open backport PRs by hand:
https://github.com/cozystack/cozystack/blob/main/docs/release/backports.md
-->

## What this PR does

This upgrades the Kafka operator to Strimzi 1.2.0. Kafka 4.3 is the
application default, with 4.2 also available. Upgrades must pass through
Cozystack v1.7 and finish the ZooKeeper-to-KRaft migration first.

The upgrade now stops while any Kafka lacks KRaft evidence. Every Kafka
must report a nonempty `kafkaMetadataVersion` and the `KRaft` metadata
state. The API conversion deletes that state, so without it a Kafka
needs `Ready=True` or the `cozystack.io/kraft-verified` annotation,
which migration 61 writes on every Kafka it accepts before it stops the
operators. Any other explicit state blocks, and the error gives the
reason for each Kafka. On every variant, the platform chart refuses to
switch package sources while Strimzi still serves `v1beta2` and a Kafka
fails that check. On variants without the migration hook, it also
refuses while any Strimzi CRD still stores `v1beta2`, so
`/migrations/61` has to run first. Migration 61 checks the same evidence
again, including on repeat runs, and blocks unfinished broker-pool
drains. A manual change that bypasses the managed package source is
outside this check.

Existing Kafka 3.x applications move to v4.3. Kafka 4 no longer accepts
clients older than Kafka 2.1. Kafka 4 also rejects the topic settings
`message.format.version`, `message.downconversion.enable` and
`message.timestamp.difference.max.ms`, and a `segment.bytes` below 1 MiB
(1048576), which Kafka 3.x accepted down to 14 bytes. A Kafka 4 broker
whose log holds such a topic does not start. The chart now refuses to
render a topic that sets any of these. The platform upgrade refuses to
start while a Kafka application sets one, and migration 61 also checks
KafkaTopic resources, so topics created outside the chart are caught
too. A topic created through the Kafka admin API without a KafkaTopic is
not visible to these checks. Restoring a topic-metadata backup taken on
Kafka 3.x skips the three removed settings and raises a smaller
`segment.bytes` to 1 MiB, with a warning for each. In-place downgrades
are unsupported. The default 10-minute Helm timeout can leave a long
broker roll Failed until its retry succeeds.

The migration does not run automatically on every platform variant. Only
the `isp-*` variants run it automatically. On other variants, run
`/migrations/61` from the matching migrations image before upgrading, as
the Kafka README describes. This includes clusters that run no Kafka but
have the kafka-operator package, from the `paas` bundle or
`bundles.enabledPackages`. Their Strimzi CRDs still store `v1beta2` even
with no objects. The migration converts Strimzi resources and stored
Helm references to `v1`. It stamps platform version 62. Running it
manually also skips earlier migrations on a later move to an `isp-*`
variant. Before it stops the operators, migration 61 refuses objects
that the Strimzi 0.51 conversion tool would reject and names each one,
for example a Kafka with `.spec.kafka.resources` or with OAuth, Keycloak
or OPA settings. A failed conversion can leave the old operators stopped
until the migration succeeds and the operator release upgrades. The
failed conversion Job stays for diagnosis, but its ClusterRole, binding
and ServiceAccount are removed. A Job that is still running when the
wait times out keeps them, because the retry waits for it.

Known limitations. Migration 61 converts with the old operator stopped,
while Strimzi's conversion guide expects a running operator of 0.49 or
later. I stop it because 0.45 keeps writing the Kafka status through
`v1beta2`, but I have not checked this on a live cluster. Objects
Strimzi created keep `ownerReferences` to `v1beta2` until Strimzi 1.2
reconciles them. Deleting a Kafka before that can leave dependents
behind, and the chart's pre-delete hook covers only StrimziPodSets. The
conversion image is pulled from quay.io by digest with no values
override, so an air-gapped cluster has to mirror it under the same name.

The full offline unit run passed on Linux on
`1171d63adfafb45be34214fb9a0f565723e255fd`: 2,576 cases, no failures,
errors or skipped tests. Later changes were checked on `69c704499fa4`
with the Bats tests for migration 61, the migration runner, the Kafka
hooks and the Kafka backup scripts (102), the platform Helm suite (310
tests) and the Kafka Helm suite (91 tests). After the rebase onto `main`
at `5a5d5cd3d85f`, `a48a2f259947` passes the same Bats tests (115) and
the platform and Kafka Helm suites (326 and 103 tests). It also passes
the new check against added `documentIndex` selectors. I have not
validated this revision on a live cluster.

Closes #4365

### Screenshots

<!-- REQUIRED for UI changes: attach screenshots or screen recordings
demonstrating
the visual impact of your changes. PRs with UI changes without
screenshots will not be merged. -->

Not a UI change.

### Downstream repositories

<!--
Cozystack is upstream for repositories that are NOT kept in sync with it
automatically, and nothing in CI compares the two sides, so a change
here can break them silently.

Which change forces what, and which file to touch, is the trigger map in
docs/agents/contributing.md under "Downstream Repositories". Walk it
before you tick anything.

IF YOU ARE AN AI AGENT OR AN LLM, THIS IS PART OF THE TASK, NOT A FORM
TO FILL IN:

1. Walk the trigger map against the actual diff of this PR, file by
file. Do not decide from the PR title or from your memory of what you
changed.
2. For every repository you tick, open the follow-up PR there and link
it on the same line. A ticked box with no link claims work that does not
exist, which is worse than an empty box. Search that repository for an
open PR or issue covering it first, and link that instead of filing a
duplicate.
3. When the follow-up is out of scope, or needs a decision that is not
yours to make, open an issue in that repository instead, link that, and
say so in the PR body. Do not push a speculative PR into another
repository just to fill a line here.
4. Do not tick "No downstream repository is affected" to make the
checklist go away. If you are unsure, leave every box empty and say so
in the PR body, so a human decides.
-->

- [ ] No downstream repository is affected by this change
- [x] [cozystack/website](https://github.com/cozystack/website) -
follow-up: https://github.com/cozystack/website/issues/805
- [ ]
[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:
- [ ] [cozystack/community](https://github.com/cozystack/community) -
follow-up:

The Terraform provider does not model the Kafka `version` field. The
website issue covers the upgrade notes the `default` variant needs.

### Release note

<!--  Write a release note:
- Explain what has changed internally and for users.
- Start with the same `type(scope):` prefix as in the PR title
- Follow the guidelines at
https://github.com/kubernetes/community/blob/master/contributors/guide/release-notes.md.
-->

```release-note
feat(kafka)!: upgrade to Strimzi 1.2.0 and Kafka 4.3 by default, with Kafka 4.2 also available. Platform migration 61 converts Strimzi resources to v1 and moves Kafka 3.x applications to v4.3. Every Kafka must have confirmed KRaft state before the upgrade, including on repeat runs. Upgrade through Cozystack v1.7 first. Kafka 4 drops clients older than Kafka 2.1 and the message.format.version, message.downconversion.enable and message.timestamp.difference.max.ms topic settings, and requires segment.bytes of at least 1 MiB; the chart and the upgrade refuse a topic that breaks either rule, and a topic-metadata backup taken on Kafka 3.x restores without the removed settings and with segment.bytes raised to 1 MiB. In-place downgrades are unsupported.
```
2026-11-18 13:26:31 +03:00
Andrey Kolkov 7145a67568 fix(backups): stop leaking MariaDB dumps of stuck runs and torn-down namespaces
A k8s.mariadb.com/Backup the BackupJob gave up on stayed for good: no
Backup is made of such a run, so nothing deleted it, and while it stood
short of Complete the dump cleanup counted its open window as a possible
writer of every later dump of the application and kept each of them.

Every failure exit of a started BackupJob in the MariaDB driver now goes
through failMariaDBBackupJob: the deadline, the application, MariaDB CR
or strategy going away, a run the operator failed at Complete=False, and
a run that could not be created. It lists the job's runs on the API
server, where the cache can trail a run created or completed a moment
ago, and deletes each one short of Complete under the UID and
resourceVersion it read, so a run that completes in between is handed
to the success path instead. Deleting the run takes its Job and pod, so
what held the pod up is first copied into the failure message. A
Running or expired job takes its run from that listing and never starts
another, so a retry after a failed status write cannot start a second.

During namespace teardown the operator Backup, which carries no
finalizer, is usually gone before the Backup finalizer runs, and the
cleanup, which read the storage from it, left the dump behind. A Backup
that recorded its dump on the platform bucket now has it deleted with
the platform credentials, which do not go with the namespace, reading
the storage from the snapshot in status.underlyingResources; the dump is
still kept when another run could have written it. The snapshot and the
storage URI now record the storage the run was created with rather than
the strategy as rendered at completion, which a strategy edited during
the run would otherwise send the cleanup away from.

Closes: #5291
Assisted-by: LLM
Signed-off-by: Andrey Kolkov <androndo@gmail.com>
2026-11-18 14:08:00 +07:00
scooby87 2495ebfaa0 fix(postgres): restore from an archive with the access it was written with (#5295)
## What this PR does

Stacked on #5221; review that one first. Once it merges this PR
retargets to `main`.

A CNPG restore took the destination path and endpoint of the source from
the Backup artifact, but the credentials Secret, its key names and the
endpoint CA from the CNPG strategy as it reads at restore time. Once the
strategy pointed at another bucket or endpoint, the restore combined the
recorded location with access settings meant for a different one, and
recovery failed after an in-place restore had already purged the target
Cluster.

The destination record that #5221 annotates on the `cnpg.io/Backup` now
also carries the key names and the CA, and the artifact copies them into
`driverMetadata["cnpg.io/archive-access"]`. The size probe reads them
from there too. The restore picks the access as follows:

1. While the strategy still points at the same endpoint and S3 bucket as
the artifact, the strategy's access is used, exactly as before. WAL
archiving keeps proving that access against the archive, and it carries
any credential rotation since the backup, after which the recorded
Secret may already be revoked. The prefix inside the bucket is not
compared, since access is taken to be granted per bucket.
2. Once the archive has moved, the recorded access is used if its Secret
and CA Secret exist and hold non-empty values under the recorded keys.
3. Otherwise the strategy's access is used, as before, with a
`RecordedArchiveAccessUnavailable` Warning event on the RestoreJob.
Credentials wider than one bucket can still read the old archive with
it.

An unreadable record fails the RestoreJob, and an error reading a Secret
is retried, both before the HelmRelease is suspended and the target is
purged. Artifacts written before this change keep working: one that
records only the Secret uses it with the strategy's key names and CA
once the archive has moved, and one without any record uses the
strategy.

This narrows the behaviour the issue asks for ("the recorded Secret, key
names and CA, falling back to the strategy only for artifacts that carry
no record") in two places, points 1 and 3 above, so that rotating
credentials for an archive that has not moved, and deleting the old
Secret after a move, keep working as they did. One case remains
uncovered: a recorded Secret that still exists but whose keys were
revoked, after the archive moved, while the strategy's credentials could
still read the old bucket.

### Screenshots

Not applicable: no UI change.

### Downstream repositories

The diff touches only `internal/backupcontroller`: no CRD, values, chart
or naming change, so nothing in the trigger map applies.

- [x] 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:
- [ ] [cozystack/community](https://github.com/cozystack/community) -
follow-up:

### Release note

```release-note
fix(postgres): restoring a Postgres backup after its CNPG strategy moved to another bucket or endpoint now reaches the archive with the credentials Secret, key names and CA the backup was written with, as long as those Secrets still exist; otherwise, and for an archive that has not moved, the strategy's current access is used as before.
```


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

<!-- coderabbit-ai-generated:v1 -->

## Summary by CodeRabbit

* **Bug Fixes**
* Restore operations now use the access settings recorded with the
backup when the archive destination has changed.
* When recorded access settings are unavailable, the controller falls
back to the current strategy settings and issues a warning. Invalid
access metadata or Secret read errors stop the restore before the target
is patched.
* **New Features**
* Backup records now retain the credential key names and CA reference
used to access the archive.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-11-17 13:53:28 +03:00
Aleksei Sviridkin 2cd41b411f fix(backups): read the Strimzi Kafka CR through the v1 API
Strimzi 1.x no longer serves kafka.strimzi.io/v1beta2, so the Kafka
backup driver's readiness check would fail on every backup and restore.

Assisted-by: LLM
Signed-off-by: Aleksei Sviridkin <f@lex.la>
2026-11-17 12:02:45 +03:00
scooby87 4f813fb6b2 fix(postgres): hold the WAL archive destination for backups no job tracks (#5294)
## What this PR does

Stacked on #5221; review that one first. Once it merges this PR
retargets to `main`.

After #5221 a Postgres BackupJob writes the shared WAL archive
destination only while no other running BackupJob of the application has
a `cnpg.io/Backup` in flight. A `cnpg.io/Backup` that no running
BackupJob tracks was not counted: one created by hand or by a
`ScheduledBackup`, or one whose BackupJob was deleted or had already
finished. A BackupJob using another BackupClass could then rewrite the
destination while CloudNativePG was running such a Backup, leaving its
base backup in one place and the WAL it needs in another, so the backup
could not be restored.

Such a Backup now holds the destination while CloudNativePG executes it,
that is in the `started` and `running` phases
(`BackupStatus.IsExecuting` in CloudNativePG 1.30). While a Backup of a
Cluster is in one of those phases, CloudNativePG's own
`BackupList.CanExecuteBackup` starts no other Backup of that Cluster, so
the hold never lasts longer than the queue the operator already imposes
and needs no separate deadline. A `pending` Backup does not hold,
including one that ran before and was sent back to `pending`:
CloudNativePG starts its base backup over against the destination
current at that time.

These Backups are found by `spec.cluster.name` in the controller's
cache, because a Backup created by hand need carry no label. The waiting
BackupJob reports `Ready=False` with reason `WaitingForUntrackedBackup`
and names the Backup.

### Screenshots

Not applicable: no UI change.

### Downstream repositories

The diff touches only `internal/backupcontroller`: no CRD, values, chart
or naming change, so nothing in the trigger map applies.

- [x] 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:
- [ ] [cozystack/community](https://github.com/cozystack/community) -
follow-up:

### Release note

```release-note
fix(postgres): a Postgres BackupJob no longer rewrites the WAL archive destination while CloudNativePG is running a backup of the same cluster that no BackupJob tracks, such as one created by hand or by a ScheduledBackup; it waits with reason WaitingForUntrackedBackup.
```


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

<!-- coderabbit-ai-generated:v1 -->

## Summary by CodeRabbit

* **Bug Fixes**
* Prevented shared WAL archive destinations from being written while an
untracked backup is actively running.
* Pending and finalizing backups no longer hold the destination, and the
destination becomes available again after the active backup completes.
* Improved handling of backup status and retry conditions when multiple
backups are in progress.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-11-16 15:05:08 +03:00
Aleksei Sviridkin ee0071dd1b chore(deps): update Go modules and move them to go 1.27.2
The five Go modules move to go 1.27.2. The root module moves to
controller-runtime v0.25.2, gateway-api v1.6.3 on the minor of the
installed v1.6.1 CRDs, grpc v1.84.0, etcd v3.7.2, cert-manager v1.21.2
and newer golang.org/x modules; prometheus/client_golang v1.25.0 raises
klauspost/compress to v1.20.1 by minimal version selection.
kubevirt-csi-driver builds upstream csi-driver f10ae94 against
Kubernetes v0.37.1, with its require and replace now naming the same
commit, kubeovn-webhook moves to client-go v0.37.1, and token-proxy to
newer releases of its dependencies.

Several stay behind, each for a stated reason. cel-go stops at v0.30.0:
its old repository has no tag past it, and v0.32 declares a module path
k8s.io/apiserver does not import. kube-openapi past the pinned commit
needs structured-merge-diff v7, which k8s.io/apimachinery v0.37 does not
compile against. The Flux API modules stay on the Flux v2.8 line the
platform installs. kubevirt.io/api and the CDI API stay on the releases
upstream csi-driver builds against, and jwx stays on v3 because v4
removes the jwk.Cache the proxy's JWKS refresh uses.

cert-manager v1.21 drops the deprecated ObjectReference alias, so the
gateway controller names IssuerReference directly; the Certificate
objects serialize the same for the installed v1.20 chart. gateway-api
marks SchemeGroupVersion deprecated, so a gateway test builds its
GroupKind from GroupName.

api/apps/v1alpha1 moves to go 1.27.2 with the rest, so a module that
imports the published types needs Go 1.27.2 or later.

Assisted-by: LLM
Signed-off-by: Aleksei Sviridkin <f@lex.la>
2026-11-16 01:07:38 +03:00
Aleksei Sviridkin 46cb99df5b fix(controller, platform): give unbounded pool members the root's LimitRange (#5265)
## What this PR does

Since tenant quotas became hierarchical (#3086), an unbounded sub-tenant
(no `resourceQuotas` of its own) shares its parent's pool and receives a
controller-owned `tenant-quota-allocated` ResourceQuota. The tenant
chart, however, renders the `tenant-range-limits` LimitRange only next
to the `tenant-quota` of a tenant that declares `resourceQuotas`, so
these namespaces end up with a quota on `limits.cpu`/`limits.memory` and
no container defaults. Admission then rejects every container that omits
one of those limits.

Pods that predate the quota keep running and fail as soon as they are
recreated. In production this took down CNPG postgres instances with
backups enabled: the `plugin-barman-cloud` sidecar injected by the
barman-cloud plugin sets CPU and memory requests and a memory limit but
no CPU limit, so the instance pod is refused on its next restart. The
same happened to the tenant `kubernetes` app: the `wait-for-kubeconfig`
init container of `cluster-autoscaler`, `kcsi-controller` and the
`bootstrap-token` jobs has no resources, so their ReplicaSets and Jobs
were refused with `failed quota: tenant-quota-allocated: must specify
limits.cpu` in every unbounded sub-tenant hosting a tenant cluster. On a
production cluster, 131 tenant pods currently get their CPU or memory
from the tenant LimitRange (VictoriaMetrics
`config-init`/`config-reloader`, Harbor exporter, MariaDB agent, Strimzi
entity operator, among others), so the defect is not specific to one
chart: any of them breaks once it lands in such a namespace. Workloads
that set every limit explicitly are unaffected.

The controller already decides which namespaces it clamps, so it now
copies the pool root's chart LimitRange into each unbounded member whose
allocated quota bounds `limits.cpu` or `limits.memory` as
`tenant-range-limits-allocated`, keeps it in step with the root, and
deletes it once the namespace leaves the pool (for instance when the
sub-tenant declares its own quota and the chart renders its own
LimitRange). The chart renders its LimitRange under any non-empty
`resourceQuotas`, including one that bounds no compute (#4930), so the
copy is limited to members whose quota bounds a compute limit: elsewhere
it would impose a 128Mi default memory limit the quota never asked for
and refuse pods, virt-launcher among them, that are admitted today. This
keeps the change independent of #4954. The copy has its own name so that
Helm can still create the chart-owned object in that case without an
ownership conflict. The root is the single source of truth for the
defaults, so the values stay defined in
`packages/apps/tenant/templates/quota.yaml` only. The controller gains
`limitranges` RBAC and watches the two LimitRange names so a change
propagates without waiting for the 60 s resync.

Tests: five reconciler cases cover a member under a non-compute quota
(no copy, and a stale one removed), the copy into an unbounded member
(and not into the root), propagation of a change on the root, garbage
collection once the member is bounded (the chart-owned object is left
alone), and a root without a LimitRange. Disabling the copy makes the
first two fail.

### Screenshots

Not a UI change.

### Downstream repositories

Walked the trigger map against the diff. The code touches only
`internal/controller/tenantquota/` and the `cozystack-controller` RBAC
template, but the website's `system-memory-limits.md` states that tenant
namespaces get defaults only from the chart's `tenant-range-limits`,
which this change makes untrue; the follow-up is an issue, since the
page should change once this is merged.

- [ ] No downstream repository is affected by this change
- [x] [cozystack/website](https://github.com/cozystack/website) -
follow-up: cozystack/website#806
- [ ]
[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:
- [ ] [cozystack/community](https://github.com/cozystack/community) -
follow-up:

### Release note

```release-note
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.
```


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

## Summary by CodeRabbit

* **New Features**
* Unbounded pool members now receive their pool’s CPU and memory limit
settings when their allocated quota sets those limits. Pool setting
updates are reflected in members during reconciliation.
* When a member has its own quota, inherited limit settings are removed
while settings configured directly for that member remain unchanged.
* No inherited settings are created when the pool has no limit settings
or the allocated quota does not set CPU or memory limits.
* Existing inherited settings are retained if an update temporarily
fails.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-11-15 02:33:34 +03:00
Maxim Belyy b24a9b4cb9 Merge branch 'main' into feat/observability-proxy-exported-namespace
Resolve the overlap with the per-application roots: the namespace root
keeps its platform exporter branch, the application root still replaces
the whole scope with its own selectors, and the label APIs mark the
repeated scope so that replacement reaches match[] as well.

Assisted-by: LLM
Signed-off-by: Maxim Belyy <maximbel2003@gmail.com>
2026-11-14 00:49:51 +07:00
Aleksei Sviridkin 4f7eb63447 feat(observability-proxy): serve per-application logs and metrics (#5220)
## What this PR does

Depends on #5219. This PR is stacked on that branch; the description
covers only what it adds on top.

Adds the per-application roots to the observability proxy, as described
in the design proposals [Tenant application
logs](https://github.com/cozystack/community/pull/95) and [Tenant
resource-consumption
metrics](https://github.com/cozystack/community/pull/94):

```text
/apis/apps.cozystack.io/v1alpha1/namespaces/<ns>/<plural>/<name>/log/select/logsql/<endpoint>
/apis/apps.cozystack.io/v1alpha1/namespaces/<ns>/<plural>/<name>/metrics/api/v1/<endpoint>
```

This lets the console show the logs and resource consumption of one
application rather than of the whole namespace.

What is added:

- Plural-to-Kind mapping from an informer over `ApplicationDefinitions`.
The Kind is looked up only after the `SubjectAccessReview` (`get
<plural>/log` or `get <plural>/metrics`), so an unauthenticated caller
cannot probe which plurals exist. An unknown plural answers `404`; an
unsynced cache or a plural declared by two kinds answers `503`.
- Logs: a second `extra_stream_filters` value with the application Kind
and name, on top of the unchanged namespace filter. VictoriaLogs ANDs
the two, on every endpoint including `tail`.
- Metrics: the forced `extra_filters[]` becomes an OR of three branches,
each still bound to the namespace:
  1. series carrying the application identity labels;
  2. series of the application's pods, found through `kube_pod_labels`;
3. series of the application's PVCs, found through
`kube_persistentvolumeclaim_labels`.
- The pod and PVC lookups cap the number of names
(`--metrics-app-max-pods`, `--metrics-app-max-pvcs`); over the cap
answers `422`. A failed pod or PVC lookup fails the request (`502`, or
`504` on the deadline) rather than answer without the application's
series, and so does a lookup that vmselect marks `isPartial`, since a
storage node that did not answer leaves names out (a partial list
already over the cap still answers `422`); vmselect's series-limit
refusal of a lookup is passed through as `422`. A query that reads
further back than `--metrics-app-lookback` (default 720h, chart value
`observabilityProxy.metrics.appLookback`), or by an unknown amount, and
a query whose samples lie at a time the lookup cannot cover answer `422`
on the application root; this includes every query with an `@` modifier,
`WITH` with a negative offset, and offsets that are not plain durations.
The namespace root still serves them. `rollup_candlestick`, a backslash
or a `#` comment outside a string, an offset directly followed by a
minus (compound durations such as `-1h-30m` or `1h-2h`), and a subquery
step that is not a plain duration are refused as well. The lookup
reaches past the evaluation time by any negative offset and by two steps
per subquery level.
- Application routes require read access to the namespace root as well
as the application subresource; a grant narrowed with `resourceNames`
alone answers `403`.
- The proxy's ClusterRole gains `list`/`watch` on
`cozystack.io/applicationdefinitions`. No tenant RBAC change is needed:
the `view` role already allows `get` on every `apps.cozystack.io`
resource and subresource.
- `/readyz` now also waits for the `ApplicationDefinitions` cache, so a
missing CRD or RBAC rule keeps the whole proxy unready, namespace roots
included.

#### Data comes from the identity labels

The application roots find data only through identity labels added by
three PRs that are now in main:

- #5215 `feat(monitoring-agents)`: export PVC labels from
kube-state-metrics (PVC branch).
- #5216 `feat(monitoring)`: stamp application identity on scraped series
(identity branch).
- #5217 `feat(monitoring-agents)`: keep application identity in
container log streams (logs root).

Merge after #5219.

The pod branch does not depend on them, because `kube_pod_labels`
already exports all pod labels. Logs and series written before those
changes rolled out carry no identity and are reachable only through the
namespace root.

#### Security condition: a convenience filter, not an isolation boundary

The application roots narrow the namespace roots; they do not isolate
applications from each other. Each application route therefore requires
two grants: the application subresource (`get <plural>/log` or `get
<plural>/metrics`) and read access to the namespace root (`list
cozystack.io/logs` or `cozystack.io/metrics` in the namespace). A grant
narrowed with `resourceNames` alone is refused. Every tenant role that
can read applications already has both. The application scope cannot
isolate yet because:

1. The lineage webhook keeps `apps.cozystack.io/application.*` labels
that a user sets on a pod or PVC that has no application owner, so such
an object can claim another application's identity.
2. The webhook's `objectSelector` skips any object created with
`internal.cozystack.io/managed-by-cozystack`, pods included, so forged
labels on such an object are never examined.
3. The pod and PVC branches match by name over the lookup window, so an
object that reuses the name of another application's recently deleted
pod or PVC pulls that object's older series into scope.

The proposed fix (a separate change to the lineage webhook) is to strip
the identity labels when no owner resolves, and to stop skipping CREATE
requests for objects carrying the managed-by label.

#### Other known gaps

- PVCs created from a StatefulSet's `volumeClaimTemplates` usually get
no lineage labels, so their volume series are not in the application
scope.
- ingress-nginx series intentionally carry no application identity, so
they are reachable only through the namespace root.
- A request for an application that does not exist answers `200` with an
empty result rather than `404`: the proxy checks authorization, not
existence. Nothing leaks; whether a `404` is wanted is open for review.

#### How it was tested

- `go test -race` and `go vet` for the proxy packages, including a
narrowed-grant test (access to application `a` only): every application
path for `b` answers `403` and no request reaches the store. Name
escaping in the pod and PVC branches is covered for regex metacharacters
and quotes.
- helm-unittest for `observability-proxy` (new RBAC rule).
- Verified on a test cluster, with the three identity PRs above applied:
the application logs root of a Redis instance returned only that
instance's lines and none from a neighbouring pod in the same namespace;
its application metrics root returned only the Redis pods' series.

### Screenshots

No UI changes.

### 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:
- [ ] [cozystack/community](https://github.com/cozystack/community) -
follow-up:

Downstream: no trigger matched. Candidate: none affected, because the
diff on top of #5219 is confined to the proxy's Go code and its own
chart RBAC; it reads `ApplicationDefinitions` but does not change their
semantics or the CRD. The security condition above may deserve a note in
the design proposals in `cozystack/community`, which is not a
trigger-map item.

### Release note

```release-note
feat(observability-proxy): add per-application logs and metrics roots under `/apis/apps.cozystack.io/v1alpha1/namespaces/<ns>/<plural>/<name>/{log,metrics}/`, scoped by application identity labels. Data appears for logs and series collected after the application identity changes to Fluent Bit, VMAgent and kube-state-metrics are rolled out.
```


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

## Summary by CodeRabbit

* **New Features**
* Added a tenant-aware observability proxy for logs and metrics, with
namespace and application scoping, access checks, and per-user request
limits.
* Enabled the proxy in the system package bundle and routed console log
and metrics requests through it.
* Added live log streaming and health, readiness, and metrics endpoints.
* **Bug Fixes**
* Invalid or excessive query parameters are rejected; requests with
uncertain application-metric scope are refused rather than returning
incomplete results.
* **Tests**
* Added end-to-end and integration coverage for tenant isolation,
console routing, access controls, and log streaming.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-11-13 20:47:10 +03:00
Aleksei Sviridkin 526f08e17d fix(mariadb): restore the dump a Backup was taken as (#5227)
## What this PR does

A RestoreJob that names a MariaDB `Backup` restored the newest dump of
the application, not the dump of that `Backup`. The driver created the
operator `Restore` with only `backupRef`, and mariadb-operator then
restores the dump nearest to the moment the restore starts, from the
prefix every run of the app shares. Restoring an older `Backup` brought
back the latest data, and when its own dump was already gone it silently
restored another one.

The `Backup` now records the dump its operator `Backup` wrote, the file
name in `k8s.mariadb.com/dump-file` and the timestamp from that name in
`k8s.mariadb.com/dump-time`. They come from the ownership-proven match
the size probe already makes, and nothing is recorded when ownership is
not proven. A restore first checks with a bounded S3 listing of the
operator `Backup`'s own storage that the dump still exists, then sets
`targetRecoveryTime` on the operator `Restore` to the dump's own
timestamp, which mariadb-operator matches exactly. If the dump is gone
the RestoreJob fails and names it. If the check cannot be made it waits
with `Ready=False/DumpCheckPending` until the restore deadline and then
fails with the cause.

`Backup`s taken before this stay restorable. The restore makes the same
ownership-proven match against their operator `Backup` and pins the dump
when it is provable, otherwise it restores the newest dump as before and
a `BestEffortDump` warning event on the RestoreJob says so. One case is
not covered: the `Backup`'s own dump is gone, a neighbour's dump from
within the minute of slack is still there and its operator `Backup` was
deleted, so that dump is taken as the match. Nothing in the platform
deletes operator `Backup`s, it needs someone to delete one by hand. A
`Backup` made of an operator `Backup` whose Job failed (`Complete` with
reason `JobFailed`) has no dump, so its RestoreJob now fails instead of
restoring another run's dump.

Stacked on https://github.com/cozystack/cozystack/pull/5223 and targets
its branch until that merges, only the last three commits belong here.

Checked on a test cluster with mariadb-operator 25.10.2. An operator
`Restore` of an older `Backup` with `targetRecoveryTime` set to its dump
timestamp restored exactly that dump (`obtained target backup` names it
and a row inserted after it is absent from the target), the same
`Restore` without the target restored the newest one. Against the real
bucket and operator `Backup`s the recording probe attributed to each
`Backup` the dump its backup pod logged, the existence check passed for
those dumps and refused a pruned one, legacy `Backup`s with a provable
dump got pinned while back-to-back runs fell back with the warning, and
the two failed runs on that cluster were refused. The controller itself
was not run on the cluster, only its code driven by a test against the
real bucket.

Fixes https://github.com/cozystack/cozystack/issues/5196

### Screenshots

Not a UI change.

### Downstream repositories

The diff is confined to the backup controller's Go code. It changes no
CRD or API type (`driverMetadata` is an opaque map), no chart, values,
package layout or `hack/` script, so no entry of the trigger map
applies.

- [x] 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:
- [ ] [cozystack/community](https://github.com/cozystack/community) -
follow-up:

### Release note

```release-note
fix(mariadb): a RestoreJob now restores the dump of the Backup it names instead of the newest dump of the application. It fails with a clear message when that dump no longer exists in storage, or when the Backup was made of a failed backup run. Backups taken before this release are restored by the one dump that can be matched to them, or else, as before, by the newest dump, with a BestEffortDump warning event on the RestoreJob.
```



<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

## Summary by CodeRabbit

* **New Features**
* MariaDB backups now record the selected dump’s filename and timestamp,
allowing restores to target the corresponding recovery time.
* For older backups without dump metadata, restores use a uniquely
matched dump when possible or fall back to the latest dump with a
warning.
* Restore processing verifies recorded dumps, retries temporary storage
checks, and reports failures for invalid or missing recorded dumps.
* **Bug Fixes**
* Deleting a MariaDB backup now removes its associated dump and operator
backup when ownership is verified and no restore is active. Cleanup
avoids deleting artifacts when it cannot safely identify them.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-11-13 20:46:45 +03:00
Aleksei Sviridkin 6f8171db89 fix(workloadmonitor): report a bucket's workloads not ready until its claim is provisioned (#5096)
## What this PR does

A Bucket app reports WorkloadsReady=True while its BucketClaim is never
provisioned. On a v1.6.5 cluster a tenant got a BucketClaim for bucket
class `tenant-root`, the root tenant there runs no SeaweedFS, and for
three days the claim had no status while the objectstorage controller
kept emitting `FailedCreateBucket` with
`bucketclasses.objectstorage.k8s.io "tenant-root" not found`. The Bucket
app showed Ready and WorkloadsReady the whole time.

The WorkloadMonitor controller already writes a Workload per BucketClaim
with `Operational` set from `status.bucketReady`, but the monitor itself
counts only pods. The bucket chart renders its monitor with `replicas:
0` and `minReplicas: 0`, so the monitor stays operational whatever
happens to the claim.

The monitor now names every selected BucketClaim that is not provisioned
in `status.message`, sets `status.reason` to the new
`BucketClaimNotReady` and turns `Operational` false, the same way it
already reports a DataVolume that is not ready. A DataVolume verdict
keeps the fields when both apply. BucketClaims are listed on every pass,
so a stored BucketClaim verdict is recomputed rather than kept like an
unread DataVolume verdict, and it clears once the claim is provisioned.
Any monitor whose selector picks a BucketClaim follows its readiness,
which is what the Workload objects already say. The Application then
shows WorkloadsReady=False with that message and reason. Its Ready
condition keeps following the HelmRelease, as
`pkg/registry/apps/application/rest.go` intends.

Three new tests cover a provisioned claim, a claim not provisioned with
and without a class, a claim outside the selector, the verdict clearing
after provisioning with and without a DataVolume reader, and the
DataVolume verdict winning over the BucketClaim one. Against the
controller on main the four not-provisioned and clearing cases fail and
the rest pass. `go test ./internal/controller/...` and `go vet` pass.
`make generate` does not run on my machine, gengo fails to parse the
go1.27.1 standard library, so I ran the controller-gen `object` and
`crd` steps of `hack/update-codegen.sh` for `./api/v1alpha1/...`
directly. The deepcopy file is unchanged and the generated
WorkloadMonitor CRD matches
`packages/system/cozystack-controller/definitions/cozystack.io_workloadmonitors.yaml`.
I have not run the change on a live cluster.

#5083 changes the Workload names of the same BucketClaims and does not
touch the monitor status, so the two do not overlap.

### Screenshots

Not a UI change.

### Downstream repositories

The controller, one exported constant and its tests. No CRD schema,
values key, default, telemetry metric or package change, so no trigger
map entry applies.

- [x] 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:
- [ ] [cozystack/community](https://github.com/cozystack/community) -
follow-up:

### Release note

```release-note
fix(workloadmonitor): a Bucket app reports WorkloadsReady=False with reason BucketClaimNotReady while its BucketClaim is not provisioned, instead of WorkloadsReady=True.
```


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

## Summary by CodeRabbit

* **New Features**
* Workload monitors now report when a selected bucket claim is not
provisioned and mark the monitor as non-operational. Status messages
include the bucket class when available and list multiple unprovisioned
claims in sorted order.
* **Bug Fixes**
* The bucket-claim status clears when the claim is provisioned or no
longer selected. When DataVolume information is available, its status
takes precedence over the bucket-claim status.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-11-13 18:11:43 +03:00
Alexey Artamonov f6f0be308f fix(postgres): restore a moved archive recorded without credentials
The postgres chart refuses to render bootstrap.enabled without a
credentials Secret, so a restore that patched the target with the
access recorded for an archive written without one failed at render
time, after the target Cluster had already been purged. Before the
access was recorded such a restore used the strategy's credentials,
which can still read the old bucket.

A recorded access without a credentials Secret now counts as unusable,
like one whose Secrets are gone: the restore takes the strategy's
access and says so in a Warning event. The tests that stop a restore on
an unreadable record or a failed Secret read now also check that the
target Cluster, its volumes and its HelmRelease are left alone.

Assisted-by: LLM
Signed-off-by: Alexey Artamonov <aleksei.artamonov@aenix.io>
2026-11-13 17:12:50 +03:00
Aleksei Sviridkin f12300943d chore: clear golangci-lint findings and handle the errors they flagged (#5306)
## What this PR does

This clears the golangci-lint findings on main and fixes the errors
several of them pointed at. With the default linter set (errcheck,
govet, ineffassign, staticcheck, unused), main had 197 findings when
this branch started. Rebased on main at 0f169540, the branch leaves 38,
all deprecations that need a design decision rather than a lint fix;
they are listed below.

Most commits are mechanical. They remove unused helpers and constants,
reword error strings, take the staticcheck simplifications, discard
best-effort cleanup errors explicitly, and move to the FieldsV1 and ptr
accessors. A loop in pkg/lineage that always ended in its first pass
becomes a helper, with a regression test for each fallback. These change
behaviour:

- Lost output is now a failure for the commands this PR touches: cozypkg
list, the validation report of validate, push and tap, the push status
line, the tap summary, and check-readiness. The command exits non-zero
and says whether the action it reports on already happened. A closed
pipe ends the process with SIGPIPE, as for other Unix tools.
- backport-batch writes its output before it pushes or publishes. Once a
write to stdout or stderr fails, the run changes nothing more: no push,
no GitHub write, no local branch move, and no new pick. A pick already
in flight still finishes its rollback. The run exits 2, and it catches
SIGPIPE, so a closed pipe is handled the same way. A confirmation
printed after an action is lost only when stderr itself fails, so a lost
confirmation can only be reported by the exit code.
- The SSE server drops a client as soon as a write to it fails. A stream
still open at shutdown no longer panics on a double close, the handler
waits for its pump before returning, and a stream that opens during
shutdown gets 503.
- The kube-ovn plunger now fails its manager when the status server
cannot bind :18080, as a metrics server bind failure does. Before, it
ran without the endpoint and logged nothing.
- A timed-out check-readiness --wait still ends with its verdict, and
the help lists the exit statuses.

The 37 findings left are SA1019 deprecations, kept out of this PR on
purpose:

- GetEventRecorderFor (12, in cmd/*/main.go). The events.k8s.io recorder
has a different interface and needs RBAC for that API group. It changes
what events look like, so it needs its own design.
- client.Apply (12, one more site arrived from main). Moving to
Client.Apply with apply configurations changes how every server-side
apply call is built and how the fake client in tests handles it. It
overlaps the dependency rollup in #4869 and should come after it.
- Result.Requeue (10). Requeue retries with rate-limited backoff,
RequeueAfter with a fixed delay. The interval has to come from whoever
owns each controller.
- scheme.Builder (3, in api/*). Replacing it changes the type of the
exported SchemeBuilder that other repositories import.
- cel.Functions (1, in pkg/reservation). It stays for its late binding,
as the comment next to it explains.

Each behaviour change has tests that failed before the fix. I ran go
test on every changed package (for cmd/backport-batch, the tests around
output and publishing, since the full package takes about ten minutes),
go build ./..., go vet on the changed packages, and a final
golangci-lint run with uncapped output on the rebased tree:
`golangci-lint run --verbose --max-same-issues=0
--max-issues-per-linter=0`, which reports the 38 findings above and
nothing else.

The tests in pkg/lineage, pkg/ovnstatus, pkg/reservation, cmd/cozypkg
and cmd/check-readiness now run in CI: a separate commit adds those
packages to go-unit-tests. Some packages with tests are still in no CI
target: cmd/cozystack-controller, cmd/cozystack-operator,
cmd/observability-proxy, pkg/apiserver, pkg/apis/apps/defaulting,
pkg/apis/apps/install, pkg/apis/apps/presets, pkg/apis/apps/validation,
pkg/apis/core/install, pkg/apis/sdn/install and pkg/version. That
predates this PR.

One known nit: when backport-batch refuses an action after its output
was lost, stderr can show two "output was lost" lines.

### Screenshots

No UI change.

### Downstream repositories

I walked the trigger map against the diff. cozypkg counts as developer
tooling, but only its error paths changed, not a flag, its usage or its
output format, so the development page needs no update. Telemetry metric
names and labels are unchanged.

- [x] 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:
- [ ] [cozystack/community](https://github.com/cozystack/community) -
follow-up:

### Release note

```release-note
chore: cozypkg, check-readiness and backport-batch now fail when their output cannot be written, and backport-batch pushes and publishes nothing once that happens. The kube-ovn plunger fails when its status server cannot start, drops status clients whose writes fail, and no longer panics when it shuts down with a client connected.
```


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

## Summary by CodeRabbit

* **Bug Fixes**
* Commands now report output failures instead of silently succeeding.
Backport operations stop before further external changes when required
output cannot be written; readiness checks return a failure status when
output writing fails.
* Package listings, validation reports, push status messages, and tap
summaries now report output errors. Tap commands indicate when changes
were applied before a summary could be written.
* Live event streams handle failed writes and shutdown more reliably,
and status-server startup errors are reported.

* **Documentation**
* Readiness-check help now explains exit statuses and closed-pipe
behavior.

* **Improvements**
* Error messages for several backup and inventory operations now provide
clearer context.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-11-13 16:44:32 +03:00
Aleksei Sviridkin 5d453c4d23 test(backups): give the fake S3 bucket a StatObject
main added StatObject to the object lister interface, so the fake
bucket the MariaDB cleanup tests use has to implement it to compile.

Assisted-by: LLM
Signed-off-by: Aleksei Sviridkin <f@lex.la>
2026-11-13 16:33:57 +03:00
Aleksei Sviridkin 8a37a70681 Merge branch 'main' into fix/mariadb-restore-dump
Assisted-by: LLM
Signed-off-by: Aleksei Sviridkin <f@lex.la>
2026-11-13 16:33:50 +03:00
Aleksei Sviridkin 03a2edf3db Merge branch 'main' into feat/observability-proxy-app-scope
Assisted-by: LLM
Signed-off-by: Aleksei Sviridkin <f@lex.la>
2026-11-13 16:31:05 +03:00
Aleksei Sviridkin 17bbca2088 feat(observability-proxy): serve tenant namespace metrics (#5219)
## What this PR does

Depends on #5214. This PR is stacked on that branch; the description
covers only what it adds on top.

Backward compatibility: this adds a new package and a new HelmRelease;
nothing existing is renamed, removed or changed, so no migration is
needed.

Adds the namespace metrics root to the observability proxy, as described
in the design proposal [Tenant resource-consumption
metrics](https://github.com/cozystack/community/pull/94). A tenant user
can query the metrics of their own namespace from VictoriaMetrics with
their Kubernetes credentials, without seeing other tenants' series.

What is added:

- Serves
`/apis/cozystack.io/v1alpha1/namespaces/<ns>/metrics/api/v1/{query,query_range,series,labels,label/<name>/values}`,
GET and POST. Anything else under the root answers `404`.
- Authorization by one `SubjectAccessReview` (`list` on
`cozystack.io/metrics` in the namespace); the aggregated tenant `view`
role gains that rule.
- The upstream request is rebuilt from an allowlist (`query`, `start`,
`end`, `step`, `time`, `match[]`, `timeout`). The scope is a single
forced `extra_filters[]={namespace="<ns>"}`; client-supplied
`extra_filters`, `extra_filters[]` and `extra_label` are dropped,
because vmselect would OR them with the forced filter. The query itself
is not rewritten.
- Label endpoints always carry a `match[]` (the namespace scope when the
client sent none), so they stay scoped even if vmselect's
`-search.ignoreExtraFiltersAtLabelsAPI` is ever enabled.
- Cost limits: maximum range (30 days), maximum points (11000), and a
clamped `timeout` (30 seconds); query-shape limits answer `422`, the
concurrency limit answers `429`. Times are accepted as unix seconds or
RFC3339; durations are rounded up to whole milliseconds before limits
are checked.
- Store selection between the short-term and long-term VictoriaMetrics
stores, configured by new chart values (`observabilityProxy.metrics`).

#### Store selection: a known limitation and an open question

The proxy has to send each query to the short-term store (3 days of
retention, finer deduplication) or the long-term store. The choice
depends on how far back the query reads, which is not only the request
window but also the windows, subquery steps and offsets inside the
expression.

The current implementation estimates that lookback with a conservative
scan of the expression text, not with a parser. It sums every `[...]`
window and subquery step, every positive `offset`, and allowances for
implicit subqueries and vmselect's default step and latency offset.
Anything it cannot read with certainty (`@`, `WITH` templates, step
multiples such as `5i`, template variables, unusual duration syntax)
goes to the long-term store. The query is forwarded unchanged, so the
estimate affects only the store choice, never the scope.

This is a heuristic. It is designed to err only towards the long-term
store, which holds the same recent data at coarser deduplication, so a
wrong guess returns coarser data rather than missing data in most cases.
A very short `rate` window sent to the long-term store can still come
back empty. Two review rounds each found new expressions the scan
underestimated, which were then fixed; there may be more.

Open question for reviewers: should the scan be replaced by parsing the
expression with `github.com/VictoriaMetrics/metricsql` (the library
vmselect itself uses), only for the store choice? That gives an exact
lookback at the cost of a new Go dependency. The namespace scope would
still be enforced by vmselect through the single `extra_filters[]`, so
the isolation design does not change either way.

A user-visible consequence of counting the lookback: a range whose start
sits right at the short-term retention edge (for example "last 3 days")
now goes to the long-term store.

#### How it was tested

- `go test -race` and `go vet` for the proxy packages; table tests for
the lookback estimate, including mutation checks of the `@` and
unparseable-window cases.
- helm-unittest for `observability-proxy` (new args and the tenant role
rule).
- Verified on a test cluster: `401` and `403` where expected; results
contain only the caller's namespace; a query naming another tenant's
namespace and a client-supplied `extra_filters[]` return nothing extra;
`query_range`, `label/<name>/values` and `series` are scoped; an admin
endpoint answers `404`.
- Not verified: the limits under load, and the store choice on windows
longer than 3 days (the test cluster had less than an hour of data).

#### Known limitations

- Relative times (`start=-1h`, `end=now`) are refused with `400`, while
the logs root accepts durations. The console sends unix seconds, so it
is not affected.
- The proxy bounds the evaluation window, the step, the number of points
of `query_range` and the timeout, not how far an expression reads:
windows and offsets inside the expression (`up[10y]`, `x[30d:1ms]`,
`offset 20d`) are bounded only by the store's retention and vmselect's
own limits.
- Times and durations are sent in a form vmselect parses exactly
(RFC3339 with milliseconds for times, durations that truncate to the
checked milliseconds); times outside 1970..2262 are refused with `400`.
A test repeats vmselect's parsing of the exact strings the proxy sends.
- `--metrics-max-range` defaults to 30 days while the longterm store
keeps 14, so the older part of a long range comes back empty rather than
refused. The two should be aligned or documented.
- The store estimate errs towards longterm: deeply nested expressions
with a large step can go to longterm although shortterm holds the data,
and longterm deduplicates at 5 minutes, so short windows such as
`rate(x[1m])` can come back sparse there.
- The `namespace` label is only as trustworthy as the writer. Any pod in
a child tenant may write to the vminsert of every ancestor tenant
(`packages/apps/tenant/templates/networkpolicy.yaml`), and vminsert does
not authenticate writers, so a child tenant can write series labelled
with another tenant's namespace. Through this proxy the owner of that
namespace would see those series as its own, and a flood of them could
push its queries over the series limit. Reading another tenant's data is
not possible this way. The write path predates this PR and already
affects the root tenant's dashboards and alerts; closing it needs the
write side to mark untrusted series, for example a vmauth in front of
vminsert that forces an `extra_label` the proxy then excludes.

### Screenshots

No UI changes.

### 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:
- [ ] [cozystack/community](https://github.com/cozystack/community) -
follow-up:

Downstream: no trigger matched. Candidate: none affected, because the
diff on top of #5214 is confined to the proxy's Go code and its own
chart under `packages/system/observability-proxy` (no platform values,
no package under `packages/apps/`, no CRD, no `hack/` change). A
user-facing page for the metrics API on the website would be useful but
is not required by the trigger map.

### Release note

```release-note
feat(observability-proxy): let tenant users query their namespace metrics from VictoriaMetrics with their Kubernetes credentials, under `/apis/cozystack.io/v1alpha1/namespaces/<ns>/metrics/api/v1/`. Access requires the tenant `view` role or higher. Ranges are limited to 30 days and 11000 points.
```


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

## Summary by CodeRabbit

* **New Features**
* The observability proxy now supports tenant-scoped metrics queries
alongside logs.
* Metrics requests are routed to short- or long-term stores based on
their time range, with configurable retention and query limits.
* Metrics access is subject to tenant authorization, request validation,
and concurrency limits.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-11-13 16:26:22 +03:00
Mattia Eleuteri cc412d44f2 test(controller): exercise the missing-root-LimitRange path under a compute-limit quota
TestReconcile_PoolRootWithoutLimitRange declared its root quota on cpu,
which the compute-limit gate does not count, so the sweep never looked
for the root's LimitRange and the test passed whatever that path did.
Declaring limits.cpu makes it reach the lookup, and it now fails if a
missing root LimitRange produces an empty copy.

Assisted-by: LLM
Signed-off-by: Mattia Eleuteri <mattia@hidora.io>
2026-11-13 13:07:08 +01:00
Aleksei Sviridkin 7c46e1e384 fix(backups): give the barman-cloud sidecar an explicit CPU limit (#5280)
## What this PR does

The barman-cloud sidecar of Postgres backups is deliberately left
without a CPU limit, so that a throttled sidecar slows WAL archiving
down instead of failing it. In a tenant with `resourceQuotas` set that
intent does not hold: `packages/apps/tenant/templates/quota.yaml`
creates the `tenant-range-limits` LimitRange, whose default CPU limit is
`250m`, and the sidecar receives it. Full backups and WAL segments are
then gzip-compressed on a quarter of a core. On a production tenant the
first full backup of a 1.6 GB database took 30 minutes, uploading at
about 0.5 MB/s with the sidecar pinned at its 250m limit, while a small
database on the same destination finished in 35 seconds.

This sets an explicit `limits.cpu: "1"` on the sidecar, in the two
places that build its configuration: `barmanSidecarConfiguration` in the
backup driver (platform-managed ObjectStores) and
`cozy-lib.barman.sidecarConfiguration` (ObjectStores rendered by the
postgres and keycloak charts). This mirrors how the memory request and
limit there already override the LimitRange's 128Mi default. One core
removes the 250m ceiling without letting the sidecar starve the
instance. Inside a tenant it counts against the `limits.cpu` quota, one
core per instance pod; the comments now say so.

The sidecar is injected when the instance pod is created, so existing
instances pick the new limit up at their next restart.

Tests: the Go test that asserted the absence of a CPU limit now asserts
one core, and so does
`packages/apps/postgres/tests/barman_resources_test.yaml`. Both fail
with the implementation reverted and pass with it. `go test
./internal/backupcontroller/`, `helm unittest packages/apps/postgres`
(220) and `helm unittest packages/system/keycloak` (121) pass.

### Screenshots

Not a UI change.

### Downstream repositories

Walked the trigger map against the diff (the backup driver, `cozy-lib`'s
barman template, two tests): no app, value, schema, default, CRD,
annotation or tooling change, so none of the listed repositories
restates anything touched here.

- [x] 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:
- [ ] [cozystack/community](https://github.com/cozystack/community) -
follow-up:

### Release note

```release-note
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.
```
2026-11-13 14:54:51 +03:00
Aleksei Sviridkin e8c8fa3ec7 Merge branch 'main' into fix/workloadmonitor-bucketclaim-ready
Assisted-by: LLM
Signed-off-by: Aleksei Sviridkin <f@lex.la>
2026-11-13 14:07:23 +03:00
Mattia Eleuteri e6127f7e42 fix(controller, platform): copy the LimitRange only under a compute-limit quota
The tenant chart renders tenant-range-limits under any non-empty
resourceQuotas, including one that bounds no compute, such as
services.loadbalancers alone. Copying it into an unbounded member whose
allocated quota bounds neither limits.cpu nor limits.memory imposes a
128Mi default memory limit the quota never asked for: a container that
requests more and sets no limit, virt-launcher among them, is refused
where it was admitted before. Only a quota on limits.cpu or
limits.memory makes admission reject a container that omits a limit, so
the copy is now limited to that case, and removed otherwise.

Assisted-by: LLM
Signed-off-by: Mattia Eleuteri <mattia@hidora.io>
2026-11-13 10:42:20 +01:00
Aleksei Sviridkin 6cab97f010 style: use tagged switches and drop unused test assignments
Use tagged switches where staticcheck suggests them and drop two test
assignments whose values are never read. Behaviour is unchanged.

Assisted-by: LLM
Signed-off-by: Aleksei Sviridkin <f@lex.la>
2026-11-13 12:35:10 +03:00
Aleksei Sviridkin 6f2d6ed17b fix(sse): refuse streams that open while the server shuts down
Shutdown stopped the clients registered at that moment and then shut
the HTTP server down. A stream accepted in between registered after the
stop loop, so nothing ended it, and http.Server.Shutdown waited for its
handler. The kube-ovn plunger calls Shutdown without a deadline, so
such a stream delayed stopping until the manager's graceful-shutdown
timeout and then failed it. Shutdown now marks the server as closing
under the same lock, and a stream that opens after that is answered 503
without being registered.

Assisted-by: LLM
Signed-off-by: Aleksei Sviridkin <f@lex.la>
2026-11-13 12:35:06 +03:00
Aleksei Sviridkin 40d340a3fc fix(sse): wait for the pump before returning
When a client disconnected, the handler stopped its pump and returned at
once, while the pump could still be writing an event or a heartbeat to
the response. net/http does not allow a write to a response after
ServeHTTP has returned. The handler now waits for the pump to exit; a
pump blocked in a write returns once the connection is gone.

Assisted-by: LLM
Signed-off-by: Aleksei Sviridkin <f@lex.la>
2026-11-13 12:35:06 +03:00
Aleksei Sviridkin 86da6c7a5b style(lineage-webhook): prefix sentinel error names with Err
Go names sentinel error variables Err...; the package is internal and
the webhook is their only user.

Assisted-by: LLM
Signed-off-by: Aleksei Sviridkin <f@lex.la>
2026-11-13 12:35:05 +03:00
Aleksei Sviridkin 648928f272 refactor(workloadmonitor): use k8s.io/utils/ptr instead of pointer
The pointer package is deprecated; its Bool and BoolPtr are aliases of
ptr.To, so the values written are unchanged.

Assisted-by: LLM
Signed-off-by: Aleksei Sviridkin <f@lex.la>
2026-11-13 12:35:04 +03:00
Aleksei Sviridkin 939a1ec44b refactor: read managed fields through FieldsV1 accessors
Direct access to FieldsV1.Raw is deprecated; GetRawBytes returns the
same bytes and is nil-safe, and NewFieldsV1 builds the test fixtures.

The write-options test still covers a raw-only orphanDependents delete
option, now decoded from its wire form, and asserts that the converted
options keep it.

Assisted-by: LLM
Signed-off-by: Aleksei Sviridkin <f@lex.la>
2026-11-13 12:35:03 +03:00
Aleksei Sviridkin 7a481c4765 chore(workloadmonitor): discard best-effort close errors explicitly
The Prometheus response body is closed after it has been read, and the
test stubs' writes fail on the client side of the test, so neither
error changes a result.

Assisted-by: LLM
Signed-off-by: Aleksei Sviridkin <f@lex.la>
2026-11-13 12:35:01 +03:00
Aleksei Sviridkin 87b794a992 chore: handle errors dropped in cleanup paths and tests
The drain tests now assert that RunThenDrain returns the run's nil
error, the idle-tail test fails on any error other than the stream
ending or being cut, and a test fixture file fails the test when it
cannot be closed.

Removing a temporary directory and closing a response body that has
been read are best-effort: a failure leaves nothing for the caller to
act on and does not change any result, so those errors are discarded
explicitly. The same holds for the stub servers' response writes, whose
failure surfaces on the client side of the test.

Assisted-by: LLM
Signed-off-by: Aleksei Sviridkin <f@lex.la>
2026-11-13 12:35:01 +03:00
Aleksei Sviridkin bd998d9653 fix(kube-ovn): fail the plunger when its status server cannot start
The status stream was started in a bare goroutine whose error was
dropped, and the runnable's registration error was discarded too, so a
port that could not be bound left the plunger running with no status
endpoint and nothing in its logs. The server now runs inside its
runnable: a listen error fails the manager, as a metrics server bind
failure does, and stopping the manager is not reported as an error.

Assisted-by: LLM
Signed-off-by: Aleksei Sviridkin <f@lex.la>
2026-11-13 12:35:00 +03:00