Repository navigation
Conversation
d0d0ec5 to
d81d518
Compare
ddc3980 to
c3e4b29
Compare
c3e4b29 to
3c76ca0
Compare
eaf9557 to
a9e00ff
Compare
|
@Slach , for consistency sake, could you change the secret reference to valueFrom syntax? Like: It has been missed in secrets review. |
|
claude AI review, maybe slop but JFYI: |
|
API:
also slot matching is fragile because of DST time changes. Missed runs. Say operator was down, when backup will be done? another point to the bucketed retention above is better control that nothing will be deleted if there was a miss. types:
Jitter, we start backup on all replicas without delay now as I understand? One-off backups, no pruning strategy for them? ttl or some keep until? |
|
@denisok thanks for review Thanks, I went through both comments point by point against the code. AI reviewReal, will be fixed before merge:
Not a bug:
APIChanging now, while unreleased:
Keeping, with the reasons:
Agreed that consistency with the Altinity usual backup workflow is the baseline, not the goal. The PR already goes beyond it, e.g. held backups survive a retention change until they expire by the old schedule, and the DST fixes above are cases the old workflow never handled. |
There was a problem hiding this comment.
I am still thinking separating retention from backup schedule might be the right thing to do.
It makes backups more reliable so retention is actually based on time and presence and not on slots.
Also I am not sure what is wrong with literals like Monday/Tuesday/...
clickhouse-backup is current tool to do it but Interface shouldn't depend on it.
Let's discuss and come to conclusion before merging this.
46069a9 to
586c246
Compare
| - period: hour | ||
| keep: 24 | ||
| - period: daily | ||
| time: "02:30" |
There was a problem hiding this comment.
why it has to start the same time ... if time has to be same globally, would it make sense to make it global instead of relying on people repeating the same value?
There was a problem hiding this comment.
Entries share one slot, so one run counts for daily, weekly and monthly at once (GFS) and the weekly backup is also a daily one. Agree, a schedule-level time would be simpler than repeating it.
| # - releaseHeld: releases the holds of a change, and of all earlier changes, at once. | ||
| # retention: | ||
| # onScheduleChange: Hold | ||
| # keepBackups: |
There was a problem hiding this comment.
who is responsible for deleting keep records, maybe it would make sense to store the information of when it expires on the backup itself, then this wont be needed because backups will expire with the expiration time configured when they were made
There was a problem hiding this comment.
Normal expiration needs no record: retention computes it from the schedule entries on every run. keepBackups is only for manual exceptions, the user owns it. An entry whose until passed is ignored, so leaving it there is harmless.
e5e8d01 to
7f94cde
Compare
|
I am trying to decode if |
|
|
|
@ondrej-smola diagrams for full vs incremental and for the rebase of a |
| } | ||
| run = run.DeepCopy() | ||
| for _, host := range cluster.Hosts { | ||
| run.Hosts = append(run.Hosts, api.BackupRunHost{Host: host, Backup: chb.Status.BackupName}) |
There was a problem hiding this comment.
should this be hostsOfInsertedCommands so we e.g. on manual duplicate backup name incorrectly attribute clsuter hosts
There was a problem hiding this comment.
Right, a delete could remove another backup of the same name. Fixed in 7513322, it uses hostsOfInsertedCommands.
| spec := newRunSpec(api.BackupRunOperationRestore, topology, chr.Spec.GetActiveDeadlineSeconds()) | ||
| spec.BackupName = cmp.Or(chr.Status.BackupName, chr.Spec.BackupName) | ||
| spec.SchemaHosts = topology.AllReplicas() | ||
| spec.DataHosts = topology.FirstPerShard() |
There was a problem hiding this comment.
does this download data even when only schema is set?
There was a problem hiding this comment.
Yes, it did: the first replica of each shard downloaded the data. Fixed in f84123a, it downloads only the schema now.
| // The T keeps a ClickHouseBackup name apart from the names of scheduled runs. | ||
| func BackupTag(t time.Time, atOnce bool) string { | ||
| if atOnce { | ||
| return t.Format("20060102T150405") |
There was a problem hiding this comment.
looks like the same constant is present on multiple places in the codebase (retention, builder)
There was a problem hiding this comment.
Now api.BackupTagLayout and api.BackupTagLayoutAtOnce, used everywhere. 91869f4.
| // scheduleTimestampLayout formats the time a scheduled run was due into the "-YYYYMMDD-HHMMSS" | ||
| // suffix of its backup name, as the Job script does. | ||
| scheduleTimestampLayout = "20060102-150405" | ||
| scheduleTimestampLayout = "20060102150405" |
There was a problem hiding this comment.
this looks like unused outside tests
| // Actions keep the last command per host and step. | ||
| Actions []BackupRunAction `json:"actions,omitempty" yaml:"actions,omitempty"` | ||
| // Plan holds decisions made before anything changed, so steps after a restart follow them. | ||
| Plan map[string]string `json:"plan,omitempty" yaml:"plan,omitempty"` |
There was a problem hiding this comment.
why this needs to be "stringly typed"?
| type orchestrator struct { | ||
| spec *model.RunSpec | ||
| sc sidecars | ||
| // mu guards status, which the controller reads while the run goes on. | ||
| mu *sync.Mutex | ||
| status *api.BackupRunStatus | ||
| event func(eventType, reason, message string) | ||
| changed func() | ||
| logPrefix string | ||
| clock clock.WithTicker | ||
| poll time.Duration | ||
| startedAt time.Time | ||
| resumed bool | ||
| elapsed time.Duration | ||
|
|
||
| lastWarning string | ||
| bestEffort bool | ||
| outcome runOutcome | ||
| sourceEnv string | ||
| sourceShown string | ||
| sourceOwnPath bool | ||
| sourceHint string | ||
| sourceCopies []string | ||
| noLocalCopy map[string]bool | ||
| ownBackups map[string]map[string]bool | ||
| pathResult model.PathCheckResult | ||
| backupNames map[string]string | ||
| resumable map[string]bool | ||
| } | ||
|
|
There was a problem hiding this comment.
looks to me like many fields are just some form of scratch/strange values - makes it really hard for human to fully understand, e.g. resumable, ownBackups, noLocalCopy
| return strings.HasPrefix(command, commandDeleteLocal+" ") || strings.HasPrefix(command, commandDeleteRemote+" ") | ||
| } | ||
|
|
||
| func (o *orchestrator) lost(ctx context.Context, action *api.BackupRunAction, name string) (bool, bool, error) { |
There was a problem hiding this comment.
this is also example where actuall documentation would really help to make it clear
| for i := 1; i < len(hosts); i++ { | ||
| if slices.Contains(hosts[:i], hosts[i]) { | ||
| return nil, failf("the backup lists %s twice: hosts of one backup must not share a storage path", hosts[i]) | ||
| } | ||
| } |
There was a problem hiding this comment.
do we need this check, looks to me like dead safecode?
| case spec.BackupName != "": | ||
| key, prefix, err := naming.Key("backup name", spec.BackupName, spec.Prefix) | ||
| if err != nil { | ||
| return nil, failf("%v", err) | ||
| } | ||
| plan.key, plan.namingPrefix = key, prefix | ||
| case naming.IsTemplate(): | ||
| if naming.HoldsPrefix() && (spec.Prefix == "") { | ||
| return nil, failf("the naming template '%s' holds {prefix}, which the backup name prefix gives", naming.Template) | ||
| } | ||
| plan.key, plan.namingPrefix = slotTag, spec.Prefix | ||
| case spec.Prefix != "": | ||
| plan.key = spec.Prefix + "-" + slotTag | ||
| default: | ||
| return nil, failf("the backup has no name") | ||
| } |
There was a problem hiding this comment.
looks like to me we have always backupname or prefix, also this code is extremely hard to reason about
…clickhouse-backup sidecars, multi-period schedules - ClickHouseBackup, ClickHouseRestore and ClickHouseBackupSchedule resources; the operator drives every run through SQL on the clickhouse-backup sidecar of each host - per-cluster backup settings in the ClickHouseInstallation: sidecar, storage config from a Secret, naming, preferred replica - schedules with several periods, full or incremental backups, retention with keep counts, pins and held backups - restore of a new installation from a backup (recovery), schema-only restore, table filters, configOverrides - reruns through spec.taskID, starting deadlines, missed slots warnings, DST-aware slots - status.backups lists the backups in storage - docs, CRD descriptions and e2e tests Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
b423f88 to
1a29fa0
Compare
fix #2146
What changes
The operator itself runs backups and restores. There is no orchestrator script, no Job, no CronJob and no backup Pod: the operator drives the
clickhouse-backupsidecar of every host through SQL on the integration tables of that host's ClickHouse, as the Altinity usual backup workflow does.Transport: sidecar only. Every Pod of a backup-enabled cluster gets a
clickhouse-backup serversidecar. Its configuration, generated by the operator, always turns onapi.create_integration_tables, sosystem.backup_actionsandsystem.backup_listreadhttp://127.0.0.1:7171. The sidecar runs withTZ=UTC, andrestore_distributed_clusterdefaults to{cluster}.backup.modeand pod mode are removed.Credentials. The operator connects to each host by its FQDN, port, scheme and the cluster TLS, with the ClickHouse credentials of its own configuration (
clickhouse.accessor its Secret). They must be set explicitly: the built-in defaults do not count, and without them a backup or restore waits with reasonNoClickHouseAccess.Commands. A command is a row inserted into
system.backup_actionsof the host afternow('UTC')of that host (async_insert = 0,http_receive_timeout/http_send_timeoutfromhttpReceiveTimeout), and polled every 5 seconds, matched by its exact command text and start time, until it finishes. A busy sidecar (another operation is currently running) is retried with exponential backoff from 5 seconds up to 5 minutes. After an operator restart the leader resumes every run from its status: a running command is followed, a finished one is settled.Timeouts.
spec.timeoutsof aClickHouseBackup,ClickHouseRestoreandClickHouseBackupSchedule, defaults in the operator configurationbackup.timeoutsand in code, as Go durations:actionTimeout(12h),unreachableTimeout(10m),httpReceiveTimeout(4h),errorResponsesMax(5). Errors and empty polls are counted apart; the logs carry the response code.Backup.
create_remote --rbacon one replica per shard (replicaSelection: FirstPerShard,preferredReplica, fallback to another replica reported byOrchestratorReplicaFallback) or on every replica (AllReplicas). A shard is backed up once any of its replicas made the backup. A failed backup deletes only its local copy, once, and reports a remote leftover (OrchestratorFailedBackupLeft,OrchestratorFailedBackupRemoteLeft) with the SQL to delete it by hand.Storage paths. Before any command,
pathandobject_disks_pathof every writer of a backup, with the macros of each host expanded, must be unique (AllReplicas: every replica; embedded backups and CAS disks included). Otherwise the backup or schedule isAbortedwithStoragePathConflict, e.g.storage path 's3://backups/backup/main/0' is not unique: replicas ... both write a backup of one name there. Unknown macros give anOrchestratorStoragePathAdvicewarning.Backup names.
spec.backup.naming/clusters[].backup.naming, a template such asshard{shardNum}-{YYYYMMDDHHIISS}with{shard}(the shard macro),{shardNum}(shard_num, from 1),{cluster},{chi},{namespace},{prefix}and the time tokens. Retention, the incremental base and restore parse names back with it, so backups named by the Altinity usual backup workflow on a shared remote path are recognized. Empty keeps the current names.Schedules.
ClickHouseBackupSchedule.spec.schedules[](minute,hour,6hours,daily,weekly,monthly, withtime,day,keep,incremental,configOverrides) andspec.timeZone:ClickHouseBackupis created per run: a run lives instatus.activewhile it runs and instatus.recentRunsafterwards, bounded bysuccessfulRunsHistoryLimit(3) andfailedRunsHistoryLimit(1);startingDeadlineSecondsskips a slot missed by more; runs of one cluster never overlap;ClickHouseBackupwithscheduleRefruns the schedule now: its incremental entry, retention after it, a base of the next incremental backup.Retention follows the Altinity usual backup workflow: each entry keeps its own
keepnewest backups (GFS); the newest backup is always kept; run-now backups live within the window of the scheduled ones; an incomplete backup is deleted only once a newer complete one exists andsystem.backup_actionsshows nocreate_remoteoruploadof it on its shard; nothing is deleted during a restore; incremental bases are rebased byclickhouse-backup(forcedbackups_to_keep_remote: 0,rebase_*: true).Schedule changes.
spec.retention.onScheduleChange: Hold(default) records a change of the entries or the time zone instatus.retention.previous[]with itsexpires. The backups the schedule kept before it and the current one would delete are held, listed instatus.clusters[].heldBackupswithexpires: backup time +keep× the period of the longest old entry that kept it. Expired holds are deleted (OrchestratorRetentionHeldExpired), an expired change leavesprevious[](RetentionHeldExpired).keepBackups: [{name, until}]pins backups: withuntiluntil then; without it a backup held by a change until its expiry, any other backup while it is listed. Pins protect incomplete backups too.releaseHeld: <changeID>releases a change and all earlier ones,Pruneapplies a change at once.Config overrides.
schedules[].configOverridesandClickHouseBackup.spec.configOverrides: up to 16KEY=VALUEclickhouse-backup settings for one backup, sent ascreate_remote --env=.... Keys the operator pins (TZincluded),API_*, paths, buckets, endpoints, the embedded backup disk and secrets are refused.Restore, as in the Altinity usual backup workflow:
download --hardlink-exists-fileson every host (an incomplete local copy is resumed);restore --schema=1 --ignore-dependencieson every replica, the first replica of the first shard withRESTORE_SCHEMA_ON_CLUSTER={cluster}; skipped forpartitions;spec.replicatedCopyToDetached(default true): the other replicas of each shard runrestore --data=1 --ignore-dependencies --replicated-copy-to-detachedat the same time, so the parts of replicated tables are already local; with false they download only the schema;restore --data=1 --ignore-dependencieson one replica per shard, the next answering replica when the first does not;delete localon every host after success; a failed restore keeps its downloads.Filters go on every command:
tables,partitions,skipTables,skipTableEngines,databaseMapping,rbac.overwrite: truewithouttablesadds--rm, which recreates the databases of the backup as a whole; withtables, or withoutoverwrite, only the tables of the backup are recreated (clickhouse-backupdrops the existing ones) and no database is dropped. A restore of access entities holds the backups and schedules of its own clusters only; restores of different clusters run at the same time.Reruns:
spec.taskIDon all three kinds, withstatus.taskID,taskIDsStarted,taskIDsCompleted. A completed backup runs again under a new name (the old one instatus.previousBackupNames), an unfinished one under its own name after its earlier copies are deleted. A failed restore runs again:spec.resumeDownload(default true) resumes its earlier downloads, false deletes them and starts over. An aborted schedule is validated again. AtaskIDset while a run is active is ignored with aTaskIDIgnoredwarning.Deletion. Finalizers on
ClickHouseBackup,ClickHouseRestoreandClickHouseBackupSchedule. Deleting an unfinished backup kills only its own running commands (kill "<command>") and deletes its local and remote copies; a completed one keeps its remote backup for retention. A restore and a schedule run are waited for, and a deleted schedule starts no new slot. Unreachable hosts are given up afterunreachableTimeout, with aDeletionLeftoverwarning and the SQL to finish by hand.Validation. Backup enabled without
configSecretRef, a missing or invalid storage Secret, or an invalidbackupblock stops the CHI reconcile: statusAborted, reasonBackupConfigInvalid, Warning eventBackupStorageConfigInvalid.Status and events.
status.clusters[].runof aClickHouseBackup/ClickHouseRestorerecords the step, the hosts and every command sent with its status. PhasesPending,Running,Completed,Failed,Aborted. The operator posts every event itself (Orchestrator*per step and command) on theClickHouseBackup,ClickHouseBackupScheduleandClickHouseRestore.Removed:
backup.modeand pod mode,backup.orchestrator, the bash and Python orchestrator scripts and their ConfigMaps,orchestratorConfigMapRef,backup.pathof the operator configuration,jobName/cronJobName,concurrencyPolicy, backup verification (spec.verify, theVerifiedcondition and its metric), the restore overwrite guard, and the operator RBAC rights for Jobs, CronJobs, Pod writes, ServiceAccounts, Roles and RoleBindings. The operator gainsupdate/patchon its three backup kinds for the finalizers.Manifests are regenerated with the current yq, which writes plain
<<:merge keys in place of!!merge <<:; the documents are the same.Docs:
docs/backup.md(how the operator runs an operation, naming, timeouts, storage paths, migration from the Altinity usual backup workflow, schedule changes, reruns, deletion, config overrides, integration tables),docs/custom_resource_explained.md,docs/operator_configuration.md,docs/chb-examples/.Tests
go build ./... && go test ./...,-raceforpkg/controller/chbackupandpkg/model/chbackup: runs against fake sidecars (command text, polling, timeouts, resume after restart, busy backoff, replica fallback, copy to detached, finalizers, taskID reruns, path uniqueness, per-cluster gates), retention plans, schedule changes and their expiry, naming, slots, incremental base.helm templateof the regenerated chart.test_010087: backup, schedule, retention and restore of two clusters through real sidecars;test_010088: recovery of a new CHI from another one's backup;test_010089: retention across a schedule change: held backups expiring by the old schedule,keepBackupspins withoutuntil, withuntilin the past and in the future.Related, in
clickhouse-backup:/metricson its own address, so the API can stay on127.0.0.1;start/finishofsystem.backup_actionswithout a time zone (worked around here withTZ=UTC);system.backup_actions;DROP ... ON CLUSTERunderRESTORE_SCHEMA_ON_CLUSTERandmax_table_size_to_drop.deploy/operatorhubis not regenerated (done at release).dev/run_code_generator.shdoes not build with the current Go (#2152); deepcopy was generated with deepcopy-gen v0.34.1.🤖 Generated with Claude Code