Files
cozystack/packages/apps/clickhouse
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
..
2024-08-12 14:47:11 +02:00
2025-09-24 12:32:37 +02:00

Managed ClickHouse Service

ClickHouse is an open source high-performance and column-oriented SQL database management system (DBMS). It is used for online analytical processing (OLAP).

Backup orchestration

Two backup paths coexist on the chart; pick one per release.

The cluster-scoped Altinity strategy (strategy.backups.cozystack.io/v1alpha1) wraps Altinity's clickhouse-backup in a one-shot batch/v1.Job per BackupJob / RestoreJob. It is engine-aware (FREEZE + upload), supports both in-place and targetApplicationRef (to-copy) restore, and does not require any in-chart CronJob.

Wiring per release:

  1. Set backup.enabled: true plus the s3* (or s3CredentialsSecret.name) fields on the chart values. The chart materialises a Secret named <release>-backup-s3 carrying bucket coordinates and credentials. That Secret is consumed by the chart-emitted clickhouse-backup sidecar (rendered into the ClickHouseInstallation Pod by templates/clickhouse.yaml); the strategy Pod itself is a curl/jq client that reaches the sidecar's HTTP API on port 7171 and never reads the Secret directly.
  2. Cluster admin one-time installs an Altinity strategy and a BackupClass that maps apps.cozystack.io/ClickHouse to it (see examples/backups/clickhouse/01-create-strategy.sh and 02-create-backupclass.sh).
  3. Tenant creates a Plan (cron schedule) or submits an ad-hoc BackupJob referencing the BackupClass. Restoring is a RestoreJob referencing the resulting Backup; omit targetApplicationRef for in-place, set it to a second ClickHouse instance for to-copy.

Bringing your own S3 credentials Secret

Setting backup.s3CredentialsSecret.name makes the chart skip the materialisation of <release>-backup-s3 and points the sidecar at the referenced Secret instead. The Secret must hold the five S3 fields as separate string keys, not a JSON blob; the per-key field names default to bucketName / endpoint / region / accessKey / secretKey and can be remapped via backup.s3CredentialsSecret.{bucketKey,endpointKey,…}.

Example:

apiVersion: v1
kind: Secret
metadata:
  name: my-s3-creds
  namespace: tenant-test
type: Opaque
stringData:
  bucketName: my-clickhouse-archive
  endpoint:   https://s3.example.org
  region:     us-east-1
  accessKey:  AKIAIOSFODNN7EXAMPLE
  secretKey:  wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
---
# In ClickHouse values.yaml:
backup:
  enabled: true
  s3CredentialsSecret:
    name: my-s3-creds

The Cozystack Bucket app's BucketInfo Secret (bucket-<name>-<user>, single BucketInfo key holding a JSON blob) is not directly consumable as s3CredentialsSecret. Either let the chart read the raw values via backup.s3* (as examples/backups/clickhouse/03-create-bucket.sh does — extract coordinates from BucketInfo and pass them to the chart values), or materialise an intermediate Secret with the five string keys above.

Legacy: chart-emitted Restic CronJob

The chart still ships a CronJob that streams per-table SHOW CREATE TABLE

  • SELECT * FORMAT TabSeparated into a Restic repository. This path is kept for backward compatibility; new installations should prefer the BackupClass flow above.

To opt in:

  1. Set backup.enabled: true, backup.schedule: "0 2 * * *" (or another non-empty cron), backup.s3* and backup.resticPassword.

  2. To restore manually:

    restic -r s3:s3.example.org/clickhouse-backups/table_name snapshots
    restic -r s3:s3.example.org/clickhouse-backups/table_name restore latest --target /tmp/
    

    For more details, read Restic: Effective Backup from Stdin.

The legacy backup.schedule, backup.cleanupStrategy, and backup.resticPassword values are deprecated and will be removed once the Altinity strategy is the default in all reference deployments. The chart-emitted CronJob renders only when backup.schedule is non-empty.

storageClass is annotated as immutable in the chart schema — see storageClass immutability for the contract and which consumers enforce it.

Parameters

Common parameters

Name Description Type Value
replicas Number of ClickHouse replicas. int 2
shards Number of ClickHouse shards. int 1
resources Explicit CPU and memory configuration for each ClickHouse replica. When omitted, the preset defined in resourcesPreset is applied. object {}
resources.cpu CPU available to each replica. quantity ""
resources.memory Memory (RAM) available to each replica. quantity ""
resourcesPreset Default sizing preset used when resources is omitted. string t1.small
size Persistent Volume Claim size available for application data. quantity 10Gi
storageClass StorageClass used to store the data. string ""
version ClickHouse major.minor version to deploy. Applies to both the ClickHouse server and ClickHouse Keeper images. Downgrading to an older major is unsafe (ClickHouse cannot read data written by a newer server and Keeper snapshots are not backward compatible) — only increase this value. string v24.9

Application-specific parameters

Name Description Type Value
logStorageSize Size of Persistent Volume for logs. quantity 2Gi
logTTL TTL (expiration time) for query_log and query_thread_log. int 15
users Users configuration map. map[string]object {}
users[name].password Password for the user. string ""
users[name].readonly User is readonly (default: false). bool false

Backup parameters

Name Description Type Value
backup Backup configuration. object {}
backup.enabled Enable backup integration. Materialises the chart-emitted <release>-backup-s3 Secret consumed by the Altinity backup strategy and, when schedule is non-empty, also renders the legacy chart-managed CronJob. bool false
backup.useSystemBucket Opt-in: when true, the chart-emitted <release>-backup-s3 Secret is skipped and the clickhouse-backup sidecar reads bucket coordinates + S3 credentials from the platform-projected cozy-backups-creds Secret. S3_PATH is set to <namespace>/<release> for cross-tenant isolation. Use together with the platform cozy-default BackupClass — tenants do not need to fill any s3* field below. bool false
backup.s3Region DEPRECATED. Per-tenant S3 configuration is being phased out in favour of the platform-managed cozy-default BackupClass. Optional now so tenants on useSystemBucket: true can omit it. string us-east-1
backup.s3Bucket DEPRECATED. Optional; see s3Region. string s3.example.org/clickhouse-backups
backup.endpoint DEPRECATED. S3 endpoint URL for the legacy chart-emitted sidecar. string ""
backup.s3PathOverride DEPRECATED. Object-key prefix inside the legacy s3Bucket; the new platform flow scopes by namespace automatically. string ""
backup.schedule Legacy. Cron schedule for the chart-emitted CronJob that runs the dump+restic backup. Empty (default) skips the legacy CronJob; recommended when a BackupClass + Plan from backups.cozystack.io already drives backup orchestration via the Altinity strategy. string ""
backup.cleanupStrategy Legacy. Restic retention policy passed to the legacy CronJob (restic forget …). Unused by the Altinity strategy. string --keep-last=3 --keep-daily=3 --keep-within-weekly=1m
backup.s3AccessKey DEPRECATED. Tenants no longer supply S3 keys; the platform-managed Bucket Secret is the source of truth. Optional now so useSystemBucket: true tenants can omit it. string <your-access-key>
backup.s3SecretKey DEPRECATED. Optional; see s3AccessKey. string <your-secret-key>
backup.resticPassword Legacy. Password for Restic backup encryption used by the legacy CronJob. Unused by the Altinity strategy. string <password>
backup.s3CredentialsSecret DEPRECATED. Pre-existing Secret reference for the legacy chart-emitted sidecar. The platform flow projects cozy-backups-creds instead. object {}
backup.s3CredentialsSecret.name Name of the Secret in the application namespace. Empty means the chart materialises <release>-backup-s3 from the legacy s3* fields. string ""
backup.s3CredentialsSecret.bucketKey Key in the Secret holding the bucket name. Defaults to bucketName. string ""
backup.s3CredentialsSecret.endpointKey Key in the Secret holding the S3 endpoint URL. Defaults to endpoint. string ""
backup.s3CredentialsSecret.regionKey Key in the Secret holding the S3 region. Defaults to region. string ""
backup.s3CredentialsSecret.accessKeyIDKey Key in the Secret holding the access key ID. Defaults to accessKey. string ""
backup.s3CredentialsSecret.secretAccessKeyKey Key in the Secret holding the secret access key. Defaults to secretKey. string ""
backup.endpointCA CA bundle the sidecar trusts when the S3 endpoint's certificate is signed by a private CA (e.g. Cozystack's in-cluster SeaweedFS). Applies to both the per-tenant and the useSystemBucket flow, and to the clickhouse-backup sidecar only — the legacy schedule CronJob writes to S3 through restic and does not consume it, so a private-CA endpoint combined with schedule still fails TLS. Use the BackupClass flow for such an endpoint. object {}
backup.endpointCA.name Name of the Secret in the application namespace. Empty (default) mounts nothing and leaves the sidecar on the system trust store only. string ""
backup.endpointCA.key Key inside the Secret holding the PEM CA bundle. Defaults to ca.crt. string ca.crt

ClickHouse Keeper parameters

Name Description Type Value
clickhouseKeeper ClickHouse Keeper configuration. object {}
clickhouseKeeper.enabled Deploy ClickHouse Keeper for cluster coordination. bool true
clickhouseKeeper.size Persistent Volume Claim size available for application data. quantity 1Gi
clickhouseKeeper.resourcesPreset Default sizing preset. string t1.micro
clickhouseKeeper.replicas Number of Keeper replicas. int 3

Scheduling parameters

Name Description Type Value
schedulingClass Name of a SchedulingClass CR (cluster-scoped, group cozystack.io) used in place of the tenant's for this application's pods. A pod gets its class when it is created, so running pods keep theirs until they are recreated. Must be the tenant's own class or one listed in the tenant's allowedSchedulingClasses. Setting any other value is refused, and the pods of an application whose class is not, or no longer, in that list get the tenant's class. Empty means inherit from the tenant. string ""

Parameter examples and reference

resources and resourcesPreset

resources sets explicit CPU and memory configurations for each replica. Every resource it leaves unset is taken from the preset defined in resourcesPreset.

resources:
  cpu: 4000m
  memory: 4Gi

resourcesPreset sets named CPU and memory configurations for each replica. This setting is ignored if the corresponding resources value is set.

Preset name CPU memory
nano 250m 128Mi
micro 500m 256Mi
small 1 512Mi
medium 1 1Gi
large 2 2Gi
xlarge 4 4Gi
2xlarge 8 8Gi