Compare commits

..
Author SHA1 Message Date
CI 61f452f9f2 Bump version to 0.1.0-RC.15 [skip ci] 2026-11-24 11:50:09 +00:00
james.maes bad8ec6b1a Merge pull request 'Merge develop into release/0.1 (next release candidate)' (#60) from merge/develop-into-release-0.1-0546 into release/0.1
build / maven (push) Successful in 1m44s
maven / build (push) Successful in 1m44s
2026-11-24 11:48:27 +00:00
James MaesandClaude Fable 5.2 3f72cc0884 Merge develop into release/0.1 (fix(prune): a plan with an unfinished backup is pruned on real storage)
build / maven (push) Successful in 2m2s
maven / build (push) Successful in 2m2s
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-24 05:46:16 -06:00
james.maes 6b2fa27261 Merge pull request 'fix(prune): a plan with an unfinished backup is pruned on real storage' (#59) from fix/prune-undated-debris into develop
build / maven (push) Successful in 2m5s
maven / build (push) Successful in 2m5s
2026-11-24 11:46:07 +00:00
James MaesandClaude Fable 5.2 f972d42403 fix(prune): a plan with an unfinished backup is pruned on real storage
build / maven (push) Successful in 2m59s
maven / build (push) Successful in 2m59s
A listing through the object-storage qbit dropped each object's
modification time, and the pruner compared those times to find backups
that never finished and are older than 7 days. With one failed run under
a plan every prune of that plan threw a NullPointerException, by hand and
on the daily schedule.

- the listing carries the modification time
- the pruner dates an unfinished backup by its run record where a storage
  lists no times, and never deletes as old what it cannot date
- the daily prune logs the stack trace of an unexpected failure

Found by a host's live check on a real bucket; the in-memory storage of
the tests supplies times. Tests: a storage that lists no times, in
BackupPrunerTest; the MinIO adapter test asserts the listing's times.
./mvnw verify: 234 tests, guardrails, help coverage and coverage pass.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-24 05:42:50 -06:00
CI 6f365d4048 Bump version to 0.1.0-RC.14 [skip ci] 2026-11-24 11:26:52 +00:00
james.maes 790de11827 Merge pull request 'Merge develop into release/0.1 (next release candidate)' (#58) from merge/develop-into-release-0.1-0520 into release/0.1
build / maven (push) Successful in 2m49s
maven / build (push) Successful in 2m49s
2026-11-24 11:24:14 +00:00
James MaesandClaude Fable 5.2 8252d4fb14 Merge develop into release/0.1 (fix(schedule): the daily prune prunes, and plans run on their schedule without a scheduled jobs table)
build / maven (push) Successful in 2m52s
maven / build (push) Successful in 2m52s
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-24 05:20:52 -06:00
james.maes 730c93d3e6 Merge pull request 'fix(schedule): the daily prune prunes, and plans run on their schedule without a scheduled jobs table' (#57) from fix/scheduled-prune into develop
build / maven (push) Successful in 2m45s
maven / build (push) Successful in 2m45s
2026-11-24 11:20:42 +00:00
James MaesandClaude Fable 5.2 2be9fc21db fix(schedule): the daily prune prunes, and plans run on their schedule without a scheduled jobs table
build / maven (push) Successful in 1m25s
maven / build (push) Successful in 1m25s
The daily prune never deleted anything. Its schedule was on "Prune per
retention" (backupPrune), an action for a person that needs plans selected
and a review; a scheduler that started it was told "No records were
selected", logged a warning and went on, every day, in every host.

- backupPruneScheduled (BackupScheduledPruneProcess) prunes every active
  plan to its retention with nobody selecting anything, once a day
- a plan that cannot be pruned raises backups.prune.failed, cleared by its
  next good prune, and does not stop the others
- backupPrune has no schedule now

Plans did not run on their schedule in an application with no scheduled
jobs table: the sync to scheduled jobs logged "ScheduledJob table not
found" and did nothing, so such a host had to build a scheduler itself.

- backupRunDuePlans (BackupDuePlansProcess), once a minute on the qbit's
  scheduler, starts every active plan whose cron has come due since it
  last started and every verification that has come due; missed times
  collapse into one run
- where the application has scheduled jobs it starts nothing
- only the scheduler may run it

Tests: the prune started as the scheduler starts it deletes what the
retention no longer keeps (the same call on the old schedule deleted
nothing); one plan's trouble does not stop the others; six tests of the
due-plans process. ./mvnw verify: 233 tests, guardrails, help coverage
and code coverage pass.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-24 05:19:03 -06:00
CI 1f916556a2 Bump version to 0.1.0-RC.13 [skip ci] 2026-11-24 10:45:34 +00:00
james.maes f4de56dd9e Merge pull request 'Merge develop into release/0.1 (next release candidate)' (#56) from merge/develop-into-release-0.1-0441 into release/0.1
build / maven (push) Successful in 2m21s
maven / build (push) Successful in 2m21s
2026-11-24 10:43:22 +00:00
James MaesandClaude Fable 5.2 1f2557e96c Merge develop into release/0.1 (feat(encryption): client-side encryption works, from the plan to the restore)
build / maven (push) Successful in 1m49s
maven / build (push) Successful in 1m49s
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-24 04:41:11 -06:00
james.maes 47ba7b3f9a Merge pull request 'feat(encryption): client-side encryption works, from the plan to the restore' (#55) from feature/client-side-encryption into develop
build / maven (push) Successful in 1m58s
maven / build (push) Successful in 1m58s
2026-11-24 10:41:02 +00:00
James MaesandClaude Fable 5.2 478bd4363b feat(encryption): client-side encryption works, from the plan to the restore
build / maven (push) Successful in 2m2s
maven / build (push) Successful in 2m2s
A plan could ask for CLIENT_AES256_GCM and was refused: the transform
plumbing was there, but nothing installed a cipher and nothing handed one
to a run.

- BackupsQBitConfig.withKeyProvider installs the streaming cipher of the
  QQQ crypto package (StreamingCipherTransform: Tink streaming AEAD, a
  fresh data key per object, wrapped by the referenced key)
- a run of a plan that asks for encryption gets the cipher for the plan's
  key reference; with no key for it the run is refused and nothing is
  written in the clear
- a plan is not saved when the provider has no key for its reference
- verification and restore read through the same provider; a rotated key
  still reads what its older version wrote
- a run records the key reference and a fingerprint (v<version>:<16 hex
  of a labelled hash), never the key

Fixed on the way: the file index of an encrypted run was written in the
clear while the catalog recorded it as encrypted, and a restore from an
encrypted run could not read it. It is encrypted like every other object
of the run. No release could encrypt before this, so no stored run is
affected.

Tests: StreamingCipherTransformTest (6: round trip, tampering and
truncation refused, another key refused, no key gives no transform,
rotation, the fingerprint is not the key); an encrypted run from the plan
(objects are ciphertext, verified by content and by test restore, rotated,
refused without the key with nothing written); a restore from an encrypted
backup, rows and a file, and its refusal without the key; plan validation
with a key provider. ./mvnw verify: 225 tests, guardrails and coverage
pass.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-24 04:38:25 -06:00
CI 5adc79976d Bump version to 0.1.0-RC.12 [skip ci] 2026-11-07 18:26:34 +00:00
james.maes 0eb18a36da Merge pull request 'Merge develop into release/0.1 (Gitea-aligned RC)' (#54) from align/develop-into-release-0.1 into release/0.1
build / maven (push) Successful in 5m8s
maven / build (push) Successful in 5m8s
2026-11-07 18:11:14 +00:00
james.maesandClaude Opus 5.5 4d56012352 Merge develop into release/0.1 (Gitea-aligned RC)
build / maven (push) Canceled after 0s
maven / build (push) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-07 12:10:56 -06:00
james.maes 4ef8a6293f Merge pull request 'build(deps): align with Gitea registry (parent 2.2.1, QQQ 4.1.0-RC.26)' (#53) from deps/align-gitea into develop
build / maven (push) Successful in 1m50s
maven / build (push) Successful in 1m50s
2026-11-07 18:06:38 +00:00
james.maesandClaude Opus 5.5 c58324bccf build(deps): align with Gitea registry (parent 2.2.1, QQQ 4.1.0-RC.26)
build / maven (push) Successful in 3m28s
maven / build (push) Successful in 3m28s
pom.xml: parent -> 2.2.1
pom.xml: qqq.snapshot.version: 4.1.0-RC.14 -> 4.1.0-RC.26
pom.xml: qbit-object-storage: 0.1.0-RC.2 -> 0.1.0-RC.10
pom.xml: qqq-frontend-next: 1.0.0-RC.14 -> 1.0.0-RC.38
pom.xml: added qqq.version=4.1.0-RC.26 (parent BOM import)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-07 17:55:30 +00:00
james.maes 06b766d516 Merge pull request 'ci: pin shared workflow to v1' (#52) from ci/pin-v1-develop into develop
QRun-IO/ci-policy: native / fork-deny (push) Skipped
QRun-IO/ci-policy: native / dotnet-0 (push) Skipped
QRun-IO/ci-policy: ci / Scoped workflow [workflow 1e25bb5a243dfdcd95d4b9a4f780200ff8c8778a] (push) Successful in 20s
QRun-IO/ci-policy: ci / head-profile (push) Skipped
QRun-IO/ci-policy: ci / repository-policy (push) Skipped
QRun-IO/ci-policy: native / native-result (push) Successful in 16s
QRun-IO/ci-policy: ci / java-core-2-head (push) Skipped
QRun-IO/ci-policy: ci / java-docker-3 (push) Skipped
QRun-IO/ci-policy: ci / java-docker-4 (push) Skipped
QRun-IO/ci-policy: ci / java-frontend-browser-5 (push) Skipped
QRun-IO/ci-policy: ci / java-maven-7-head (push) Skipped
QRun-IO/ci-policy: ci / node-8 (push) Skipped
QRun-IO/ci-policy: ci / node-9 (push) Skipped
QRun-IO/ci-policy: ci / node-10 (push) Skipped
QRun-IO/ci-policy: ci / node-playwright-11 (push) Skipped
QRun-IO/ci-policy: ci / repository-policy-12 (push) Skipped
QRun-IO/ci-policy: ci / source-config-13 (push) Skipped
QRun-IO/ci-policy: ci / source-config-14 (push) Skipped
QRun-IO/ci-policy: ci / original-voyage (push) Skipped
QRun-IO/ci-policy: ci / original-cli (push) Skipped
QRun-IO/ci-policy: ci / ci-result (push) Successful in 11s
build / maven (push) Successful in 3m59s
QRun-IO/ci-policy: ci / fork-guard (push) Skipped
QRun-IO/ci-policy: ci / application-template-0 (push) Skipped
QRun-IO/ci-policy: ci / gradle-1 (push) Skipped
QRun-IO/ci-policy: ci / java-docker-3-head (push) Skipped
QRun-IO/ci-policy: ci / java-maven-6 (push) Skipped
QRun-IO/ci-policy: ci / java-maven-6-head (push) Skipped
QRun-IO/ci-policy: ci / java-maven-7 (push) Skipped
QRun-IO/ci-policy: ci / android-0 (push) Skipped
QRun-IO/ci-policy: ci / original-business (push) Skipped
QRun-IO/ci-policy: ci / original-mcp (push) Skipped
QRun-IO/ci-policy: ci / not-enrolled (push) Skipped
QRun-IO/ci-policy: ci / shared-pipeline (push) Skipped
maven / build (push) Successful in 3m59s
2026-11-06 16:03:45 +00:00
james.maesandClaude Opus 5.5 5c32e3c5f3 ci: pin shared workflow to v1
QRun-IO/ci-policy: ci / fork-guard (pull_request) Skipped
QRun-IO/ci-policy: native / fork-deny (pull_request) Skipped
QRun-IO/ci-policy: native / dotnet-0 (pull_request) Skipped
QRun-IO/ci-policy: ci / Scoped workflow [workflow 1e25bb5a243dfdcd95d4b9a4f780200ff8c8778a] (pull_request) Successful in 5s
QRun-IO/ci-policy: ci / head-profile (pull_request) Skipped
QRun-IO/ci-policy: ci / repository-policy (pull_request) Skipped
QRun-IO/ci-policy: ci / application-template-0 (pull_request) Skipped
QRun-IO/ci-policy: ci / java-core-2-head (pull_request) Skipped
QRun-IO/ci-policy: ci / java-maven-6 (pull_request) Skipped
QRun-IO/ci-policy: ci / java-maven-6-head (pull_request) Skipped
QRun-IO/ci-policy: ci / java-maven-7 (pull_request) Skipped
QRun-IO/ci-policy: ci / java-maven-7-head (pull_request) Skipped
QRun-IO/ci-policy: ci / node-8 (pull_request) Skipped
QRun-IO/ci-policy: ci / original-business (pull_request) Skipped
QRun-IO/ci-policy: ci / original-mcp (pull_request) Skipped
QRun-IO/ci-policy: ci / original-voyage (pull_request) Skipped
QRun-IO/ci-policy: ci / original-cli (pull_request) Skipped
QRun-IO/ci-policy: ci / not-enrolled (pull_request) Skipped
QRun-IO/ci-policy: ci / ci-result (pull_request) Waiting to run
build / maven (push) Successful in 3m27s
QRun-IO/ci-policy: native / native-result (pull_request) Successful in 6s
QRun-IO/ci-policy: ci / gradle-1 (pull_request) Skipped
QRun-IO/ci-policy: ci / java-docker-3 (pull_request) Skipped
QRun-IO/ci-policy: ci / java-docker-3-head (pull_request) Skipped
QRun-IO/ci-policy: ci / java-docker-4 (pull_request) Skipped
QRun-IO/ci-policy: ci / java-frontend-browser-5 (pull_request) Skipped
QRun-IO/ci-policy: ci / node-9 (pull_request) Skipped
QRun-IO/ci-policy: ci / node-10 (pull_request) Skipped
QRun-IO/ci-policy: ci / node-playwright-11 (pull_request) Skipped
QRun-IO/ci-policy: ci / repository-policy-12 (pull_request) Skipped
QRun-IO/ci-policy: ci / source-config-13 (pull_request) Skipped
QRun-IO/ci-policy: ci / source-config-14 (pull_request) Skipped
QRun-IO/ci-policy: ci / android-0 (pull_request) Skipped
QRun-IO/ci-policy: ci / shared-pipeline (pull_request) Skipped
maven / build (push) Successful in 3m27s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 14:04:43 +00:00
james.maes 1de785328e Merge pull request 'ci: use shared ci-workflows Maven workflow' (#51) from ci/ci-workflows into develop
QRun-IO/ci-policy: native / fork-deny (push) Skipped
QRun-IO/ci-policy: native / dotnet-0 (push) Skipped
QRun-IO/ci-policy: native / native-result (push) Successful in 6s
QRun-IO/ci-policy: ci / head-profile (push) Skipped
QRun-IO/ci-policy: ci / repository-policy (push) Skipped
QRun-IO/ci-policy: ci / java-core-2-head (push) Skipped
QRun-IO/ci-policy: ci / java-docker-3 (push) Skipped
QRun-IO/ci-policy: ci / java-docker-4 (push) Skipped
QRun-IO/ci-policy: ci / java-frontend-browser-5 (push) Skipped
QRun-IO/ci-policy: ci / java-maven-7-head (push) Skipped
QRun-IO/ci-policy: ci / node-8 (push) Skipped
QRun-IO/ci-policy: ci / node-9 (push) Skipped
QRun-IO/ci-policy: ci / node-10 (push) Skipped
QRun-IO/ci-policy: ci / node-playwright-11 (push) Skipped
QRun-IO/ci-policy: ci / repository-policy-12 (push) Skipped
QRun-IO/ci-policy: ci / source-config-13 (push) Skipped
QRun-IO/ci-policy: ci / source-config-14 (push) Skipped
QRun-IO/ci-policy: ci / original-voyage (push) Skipped
QRun-IO/ci-policy: ci / original-cli (push) Skipped
QRun-IO/ci-policy: ci / ci-result (push) Successful in 7s
build / maven (push) Successful in 2m49s
QRun-IO/ci-policy: ci / fork-guard (push) Skipped
QRun-IO/ci-policy: ci / Scoped workflow [workflow d20a578c7d818bc7ca32a2ac2c675da4e4f27385] (push) Successful in 8s
QRun-IO/ci-policy: ci / application-template-0 (push) Skipped
QRun-IO/ci-policy: ci / gradle-1 (push) Skipped
QRun-IO/ci-policy: ci / java-docker-3-head (push) Skipped
QRun-IO/ci-policy: ci / java-maven-6 (push) Skipped
QRun-IO/ci-policy: ci / java-maven-6-head (push) Skipped
QRun-IO/ci-policy: ci / java-maven-7 (push) Skipped
QRun-IO/ci-policy: ci / android-0 (push) Skipped
QRun-IO/ci-policy: ci / original-business (push) Skipped
QRun-IO/ci-policy: ci / original-mcp (push) Skipped
QRun-IO/ci-policy: ci / not-enrolled (push) Skipped
QRun-IO/ci-policy: ci / shared-pipeline (push) Skipped
maven / build (push) Successful in 2m48s
2026-11-05 23:14:34 +00:00
james.maesandClaude Opus 5.5 dbcfd85da8 ci: use shared ci-workflows Maven workflow
QRun-IO/ci-policy: ci / fork-guard (pull_request) Skipped
QRun-IO/ci-policy: native / fork-deny (pull_request) Skipped
QRun-IO/ci-policy: native / dotnet-0 (pull_request) Skipped
QRun-IO/ci-policy: ci / Scoped workflow [workflow 1b3648d9421543350067e95e54959dfb471b26d5] (pull_request) Successful in 7s
QRun-IO/ci-policy: ci / head-profile (pull_request) Skipped
QRun-IO/ci-policy: ci / repository-policy (pull_request) Skipped
QRun-IO/ci-policy: ci / application-template-0 (pull_request) Skipped
QRun-IO/ci-policy: ci / java-core-2-head (pull_request) Skipped
QRun-IO/ci-policy: ci / java-maven-6 (pull_request) Skipped
QRun-IO/ci-policy: ci / java-maven-6-head (pull_request) Skipped
QRun-IO/ci-policy: ci / java-maven-7 (pull_request) Skipped
QRun-IO/ci-policy: ci / java-maven-7-head (pull_request) Skipped
QRun-IO/ci-policy: ci / node-8 (pull_request) Skipped
QRun-IO/ci-policy: ci / original-business (pull_request) Skipped
QRun-IO/ci-policy: ci / original-mcp (pull_request) Skipped
QRun-IO/ci-policy: ci / original-voyage (pull_request) Skipped
QRun-IO/ci-policy: ci / original-cli (pull_request) Skipped
build / maven (push) Successful in 2m32s
QRun-IO/ci-policy: ci / ci-result (pull_request) Failing after 2s
QRun-IO/ci-policy: ci / gradle-1 (pull_request) Skipped
QRun-IO/ci-policy: ci / java-docker-3-head (pull_request) Skipped
QRun-IO/ci-policy: ci / java-docker-4 (pull_request) Skipped
QRun-IO/ci-policy: ci / java-frontend-browser-5 (pull_request) Skipped
QRun-IO/ci-policy: native / native-result (pull_request) Successful in 5s
QRun-IO/ci-policy: ci / node-9 (pull_request) Skipped
QRun-IO/ci-policy: ci / node-10 (pull_request) Skipped
QRun-IO/ci-policy: ci / node-playwright-11 (pull_request) Skipped
QRun-IO/ci-policy: ci / repository-policy-12 (pull_request) Skipped
QRun-IO/ci-policy: ci / source-config-13 (pull_request) Skipped
QRun-IO/ci-policy: ci / source-config-14 (pull_request) Skipped
QRun-IO/ci-policy: ci / android-0 (pull_request) Skipped
QRun-IO/ci-policy: ci / not-enrolled (pull_request) Skipped
QRun-IO/ci-policy: ci / shared-pipeline (pull_request) Skipped
maven / build (push) Successful in 2m33s
QRun-IO/ci-policy: Shared Java Maven CI with Docker / verify (pull_request) Successful in 2m3s
QRun-IO/ci-policy: Shared Java Maven CI with Docker / secrets (pull_request) Successful in 16s
QRun-IO/ci-policy: Shared Java Maven CI with Docker / gate (pull_request) Failing after 2s
QRun-IO/ci-policy: ci / java-docker-3 (pull_request) Failing after 19m29s
Replace the platform-ci release callers with one caller of
KofTwentyTwo/ci-workflows maven.yaml (qqq-orb port).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 22:02:21 +00:00
forge-recovery ff76412d80 ci: enroll shared Gitea lifecycle
QRun-IO/ci-policy: ci / head-profile (push) Skipped
QRun-IO/ci-policy: ci / java-docker-4 (push) Skipped
QRun-IO/ci-policy: ci / java-frontend-browser-5 (push) Skipped
QRun-IO/ci-policy: ci / node-8 (push) Skipped
QRun-IO/ci-policy: ci / node-9 (push) Skipped
QRun-IO/ci-policy: ci / node-10 (push) Skipped
QRun-IO/ci-policy: ci / node-playwright-11 (push) Skipped
QRun-IO/ci-policy: ci / repository-policy-12 (push) Skipped
QRun-IO/ci-policy: ci / source-config-13 (push) Skipped
QRun-IO/ci-policy: ci / source-config-14 (push) Skipped
QRun-IO/ci-policy: native / fork-deny (push) Skipped
QRun-IO/ci-policy: native / dotnet-0 (push) Skipped
Shared Java Maven CI with Docker / secrets (push) Successful in 27s
QRun-IO/ci-policy: Shared Java Maven CI with Docker / secrets (push) Successful in 24s
QRun-IO/ci-policy: ci / repository-policy (push) Skipped
QRun-IO/ci-policy: ci / java-core-2-head (push) Skipped
QRun-IO/ci-policy: ci / java-maven-7-head (push) Skipped
QRun-IO/ci-policy: native / native-result (push) Successful in 10s
QRun-IO/ci-policy: ci / java-docker-3 (push) Successful in 11m52s
QRun-IO/ci-policy: ci / ci-result (push) Successful in 6s
Shared Java Maven CI with Docker / verify (push) Successful in 2m38s
qrun-release / postpublish (push) Failing after 10m40s
QRun-IO/ci-policy: ci / fork-guard (push) Skipped
QRun-IO/ci-policy: ci / application-template-0 (push) Skipped
QRun-IO/ci-policy: ci / gradle-1 (push) Skipped
QRun-IO/ci-policy: ci / java-maven-6 (push) Skipped
QRun-IO/ci-policy: ci / java-maven-7 (push) Skipped
QRun-IO/ci-policy: ci / android-0 (push) Skipped
QRun-IO/ci-policy: ci / original-mcp (push) Skipped
QRun-IO/ci-policy: ci / not-enrolled (push) Skipped
QRun-IO/ci-policy: ci / java-docker-3-head (push) Skipped
QRun-IO/ci-policy: ci / java-maven-6-head (push) Skipped
QRun-IO/ci-policy: Shared Java Maven CI with Docker / verify (push) Successful in 1m52s
QRun-IO/ci-policy: Shared Java Maven CI with Docker / gate (push) Successful in 13s
Shared Java Maven CI with Docker / gate (push) Successful in 11s
qrun-release / release (push) Successful in 12m25s
Shared QRun source version / version (push) Failing after 10m40s
2026-11-02 22:10:12 +00:00
forge-recovery 76ac13c14f ci: enroll shared Gitea lifecycle
QRun-IO/ci-policy: ci / head-profile (push) Skipped
QRun-IO/ci-policy: ci / java-docker-4 (push) Skipped
QRun-IO/ci-policy: ci / java-frontend-browser-5 (push) Skipped
QRun-IO/ci-policy: ci / node-8 (push) Skipped
QRun-IO/ci-policy: ci / node-9 (push) Skipped
QRun-IO/ci-policy: ci / node-10 (push) Skipped
QRun-IO/ci-policy: ci / node-playwright-11 (push) Skipped
QRun-IO/ci-policy: ci / repository-policy-12 (push) Skipped
QRun-IO/ci-policy: ci / source-config-13 (push) Skipped
QRun-IO/ci-policy: ci / source-config-14 (push) Skipped
QRun-IO/ci-policy: native / fork-deny (push) Skipped
QRun-IO/ci-policy: native / dotnet-0 (push) Skipped
QRun-IO/ci-policy: native / native-result (push) Successful in 7s
QRun-IO/ci-policy: Shared Java Maven CI with Docker / secrets (push) Successful in 22s
QRun-IO/ci-policy: ci / repository-policy (push) Skipped
QRun-IO/ci-policy: ci / java-core-2-head (push) Skipped
QRun-IO/ci-policy: ci / java-maven-7-head (push) Skipped
QRun-IO/ci-policy: ci / java-docker-3 (push) Successful in 7m24s
QRun-IO/ci-policy: ci / ci-result (push) Successful in 11s
QRun-IO/ci-policy: ci / fork-guard (push) Skipped
QRun-IO/ci-policy: ci / application-template-0 (push) Skipped
QRun-IO/ci-policy: ci / gradle-1 (push) Skipped
QRun-IO/ci-policy: ci / java-maven-6 (push) Skipped
QRun-IO/ci-policy: ci / java-maven-7 (push) Skipped
QRun-IO/ci-policy: ci / android-0 (push) Skipped
QRun-IO/ci-policy: ci / original-mcp (push) Skipped
QRun-IO/ci-policy: ci / not-enrolled (push) Skipped
QRun-IO/ci-policy: ci / java-docker-3-head (push) Skipped
QRun-IO/ci-policy: ci / java-maven-6-head (push) Skipped
QRun-IO/ci-policy: Shared Java Maven CI with Docker / verify (push) Successful in 2m6s
QRun-IO/ci-policy: Shared Java Maven CI with Docker / gate (push) Successful in 20s
2026-11-02 21:30:25 +00:00
forge-recoveryandCodex 7ba2740283 ci: enroll shared Gitea release-candidate lifecycle
QRun-IO/ci-policy: ci / fork-guard (pull_request) Skipped
QRun-IO/ci-policy: ci / head-profile (pull_request) Skipped
QRun-IO/ci-policy: ci / application-template-0 (pull_request) Skipped
QRun-IO/ci-policy: ci / java-maven-6 (pull_request) Skipped
QRun-IO/ci-policy: ci / java-maven-7 (pull_request) Skipped
QRun-IO/ci-policy: ci / node-8 (pull_request) Skipped
QRun-IO/ci-policy: ci / not-enrolled (pull_request) Skipped
QRun-IO/ci-policy: native / fork-deny (pull_request) Skipped
QRun-IO/ci-policy: native / dotnet-0 (pull_request) Skipped
QRun-IO/ci-policy: ci / repository-policy (pull_request) Skipped
QRun-IO/ci-policy: ci / java-core-2-head (pull_request) Skipped
QRun-IO/ci-policy: ci / java-maven-6-head (pull_request) Skipped
QRun-IO/ci-policy: ci / java-maven-7-head (pull_request) Skipped
QRun-IO/ci-policy: ci / ci-result (pull_request) Successful in 6s
Release candidate / release-rc (pull_request) Skipped
QRun-IO/ci-policy: ci / gradle-1 (pull_request) Skipped
QRun-IO/ci-policy: ci / java-docker-4 (pull_request) Skipped
QRun-IO/ci-policy: ci / java-frontend-browser-5 (pull_request) Skipped
QRun-IO/ci-policy: ci / node-9 (pull_request) Skipped
QRun-IO/ci-policy: ci / node-10 (pull_request) Skipped
QRun-IO/ci-policy: ci / node-playwright-11 (pull_request) Skipped
QRun-IO/ci-policy: ci / repository-policy-12 (pull_request) Skipped
QRun-IO/ci-policy: ci / source-config-14 (pull_request) Skipped
QRun-IO/ci-policy: ci / android-0 (pull_request) Skipped
QRun-IO/ci-policy: ci / source-config-13 (pull_request) Skipped
QRun-IO/ci-policy: native / native-result (pull_request) Successful in 5s
QRun-IO/ci-policy: Shared Java Maven CI with Docker / secrets (pull_request) Successful in 12s
QRun-IO/ci-policy: ci / java-docker-3-head (pull_request) Skipped
QRun-IO/ci-policy: Shared Java Maven CI with Docker / verify (pull_request) Successful in 2m7s
QRun-IO/ci-policy: Shared Java Maven CI with Docker / gate (pull_request) Successful in 16s
QRun-IO/ci-policy: ci / java-docker-3 (pull_request) Successful in 55m33s
Co-Authored-By: Codex <noreply@openai.com>
2026-11-02 20:13:41 +00:00
c82c847b35 ci: add the isolated postpublish job to the QRun release caller
QRun-IO/ci-policy: ci / fork-guard (pull_request) Skipped
QRun-IO/ci-policy: ci / head-profile (pull_request) Skipped
QRun-IO/ci-policy: ci / application-template-0 (pull_request) Skipped
QRun-IO/ci-policy: ci / java-maven-6 (pull_request) Skipped
QRun-IO/ci-policy: ci / java-maven-7 (pull_request) Skipped
QRun-IO/ci-policy: ci / node-8 (pull_request) Skipped
QRun-IO/ci-policy: native / fork-deny (pull_request) Skipped
QRun-IO/ci-policy: native / dotnet-0 (pull_request) Skipped
Shared Java Maven CI with Docker / secrets (push) Successful in 15s
QRun-IO/ci-policy: ci / repository-policy (pull_request) Skipped
QRun-IO/ci-policy: ci / java-core-2-head (pull_request) Skipped
QRun-IO/ci-policy: ci / java-maven-6-head (pull_request) Skipped
QRun-IO/ci-policy: ci / java-maven-7-head (pull_request) Skipped
Shared Java Maven CI with Docker / verify (push) Successful in 1m35s
qrun-release / postpublish (push) Skipped
QRun-IO/ci-policy: ci / ci-result (pull_request) Successful in 5s
Release candidate / release-rc (pull_request) Skipped
QRun-IO/ci-policy: ci / gradle-1 (pull_request) Skipped
QRun-IO/ci-policy: ci / java-docker-4 (pull_request) Skipped
QRun-IO/ci-policy: ci / java-frontend-browser-5 (pull_request) Skipped
QRun-IO/ci-policy: ci / node-9 (pull_request) Skipped
QRun-IO/ci-policy: ci / node-10 (pull_request) Skipped
QRun-IO/ci-policy: ci / node-playwright-11 (pull_request) Skipped
QRun-IO/ci-policy: ci / repository-policy-12 (pull_request) Skipped
QRun-IO/ci-policy: ci / source-config-13 (pull_request) Skipped
QRun-IO/ci-policy: ci / source-config-14 (pull_request) Skipped
QRun-IO/ci-policy: ci / not-enrolled (pull_request) Skipped
QRun-IO/ci-policy: Shared Java Maven CI with Docker / secrets (pull_request) Successful in 14s
QRun-IO/ci-policy: ci / java-docker-3-head (pull_request) Skipped
QRun-IO/ci-policy: native / native-result (pull_request) Successful in 4s
Shared Java Maven CI with Docker / gate (push) Successful in 10s
qrun-release / release (push) Successful in 2h25m44s
QRun-IO/ci-policy: Shared Java Maven CI with Docker / verify (pull_request) Successful in 1m31s
QRun-IO/ci-policy: Shared Java Maven CI with Docker / gate (pull_request) Successful in 9s
QRun-IO/ci-policy: ci / java-docker-3 (pull_request) Successful in 2h27m8s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-Authored-By: Codex <noreply@openai.com>
2026-11-02 15:45:49 +00:00
dc69ffe245 ci: move the QRun release caller to the thin v2 contract
QRun-IO/ci-policy: ci / java-frontend-browser-3 (pull_request) Skipped
QRun-IO/ci-policy: ci / node-5 (pull_request) Skipped
QRun-IO/ci-policy: ci / node-6 (pull_request) Skipped
QRun-IO/ci-policy: ci / node-playwright-8 (pull_request) Skipped
QRun-IO/ci-policy: ci / source-config-9 (pull_request) Skipped
Shared Java Maven CI with Docker / secrets (push) Failing after 17s
QRun-IO/ci-policy: ci / java-docker-2 (pull_request) Canceled after 1h25m12s
Shared Java Maven CI with Docker / verify (push) Canceled after 0s
QRun-IO/ci-policy: ci / fork-guard (pull_request) Skipped
QRun-IO/ci-policy: ci / head-profile (pull_request) Skipped
QRun-IO/ci-policy: ci / application-template-0 (pull_request) Skipped
QRun-IO/ci-policy: ci / java-maven-6 (pull_request) Skipped
QRun-IO/ci-policy: ci / java-maven-7 (pull_request) Skipped
QRun-IO/ci-policy: ci / node-8 (pull_request) Skipped
QRun-IO/ci-policy: native / fork-deny (pull_request) Skipped
QRun-IO/ci-policy: native / dotnet-0 (pull_request) Skipped
QRun-IO/ci-policy: ci / repository-policy (pull_request) Skipped
QRun-IO/ci-policy: ci / java-core-2-head (pull_request) Skipped
QRun-IO/ci-policy: ci / java-maven-6-head (pull_request) Skipped
QRun-IO/ci-policy: ci / java-maven-7-head (pull_request) Skipped
QRun-IO/ci-policy: ci / ci-result (pull_request) Successful in 5s
QRun-IO/ci-policy: ci / java-maven-4 (pull_request) Skipped
QRun-IO/ci-policy: ci / node-7 (pull_request) Skipped
Shared Java Maven CI with Docker / gate (push) Canceled after 0s
qrun-release / release (push) Canceled after 1h25m16s
QRun-IO/ci-policy: ci / gradle-1 (pull_request) Skipped
QRun-IO/ci-policy: ci / java-docker-4 (pull_request) Skipped
QRun-IO/ci-policy: ci / java-frontend-browser-5 (pull_request) Skipped
QRun-IO/ci-policy: ci / node-9 (pull_request) Skipped
QRun-IO/ci-policy: ci / node-10 (pull_request) Skipped
QRun-IO/ci-policy: ci / node-playwright-11 (pull_request) Skipped
QRun-IO/ci-policy: ci / source-config-12 (pull_request) Skipped
QRun-IO/ci-policy: ci / source-config-13 (pull_request) Skipped
QRun-IO/ci-policy: ci / not-enrolled (pull_request) Skipped
QRun-IO/ci-policy: Shared Java Maven CI with Docker / secrets (pull_request) Successful in 21s
QRun-IO/ci-policy: ci / java-docker-3-head (pull_request) Skipped
QRun-IO/ci-policy: native / native-result (pull_request) Successful in 6s
QRun-IO/ci-policy: Shared Java Maven CI with Docker / verify (pull_request) Successful in 1m39s
QRun-IO/ci-policy: Shared Java Maven CI with Docker / gate (pull_request) Successful in 11s
QRun-IO/ci-policy: ci / java-docker-3 (pull_request) Successful in 1h41m21s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-Authored-By: Codex <noreply@openai.com>
2026-11-02 06:16:09 +00:00
forge-recoveryandCodex 66fd64e1c4 ci: add the identical QRun release caller
QRun-IO/ci-policy: ci / fork-guard (pull_request) Skipped
QRun-IO/ci-policy: ci / java-maven-2 (pull_request) Skipped
QRun-IO/ci-policy: ci / node-3 (pull_request) Skipped
QRun-IO/ci-policy: ci / node-4 (pull_request) Skipped
QRun-IO/ci-policy: ci / source-config-5 (pull_request) Skipped
QRun-IO/ci-policy: ci / not-enrolled (pull_request) Skipped
QRun-IO/ci-policy: ci / java-docker-1 (pull_request) Failing after 14m1s
QRun-IO/ci-policy: ci / ci-result (pull_request) Failing after 5s
QRun-IO/ci-policy: Shared Java Maven CI with Docker / secrets (pull_request) Failing after 16s
QRun-IO/ci-policy: ci / gradle-0 (pull_request) Skipped
QRun-IO/ci-policy: Shared Java Maven CI with Docker / verify (pull_request) Successful in 1m46s
QRun-IO/ci-policy: Shared Java Maven CI with Docker / gate (pull_request) Failing after 15s
Co-Authored-By: Codex <noreply@openai.com>
2026-11-02 03:25:46 +00:00
james.maesandCodex 895727acbb ci: adopt managed orb 0.8 patch track (#45)
Co-authored-by: Codex <noreply@openai.com>
2026-10-21 15:28:38 -05:00
james.maesandCodex 886e76b333 ci: adopt shared orb 0.7.18 (#44)
Co-authored-by: Codex <noreply@openai.com>
2026-10-21 14:48:47 -05:00
james.maesandCodex 603f0c9d82 ci: adopt shared orb 0.7.17 (#43)
Co-authored-by: Codex <noreply@openai.com>
2026-10-21 14:16:17 -05:00
james.maesandCodex a17c6739bb ci: centralize release branch verification and workflows (#42)
Co-authored-by: Codex <noreply@openai.com>
2026-10-21 12:40:15 -05:00
james.maesandCodex bdf79eae09 ci: centralize QBit source scanning (#40)
Co-authored-by: Codex <noreply@openai.com>
2026-10-21 10:43:14 -05:00
james.maesandCodex ec5fef94bc ci: adopt central orb 0.7.12 and stable gates (#39)
Co-authored-by: Codex <noreply@openai.com>
2026-10-21 08:56:47 -05:00
james.maesandCodex b21db17a9f ci: centralize rc release completion in qqq orb (#38)
Co-authored-by: Codex <noreply@openai.com>
2026-10-21 02:25:46 -05:00
james.maesandCodex 7fa71bbaa6 ci: adopt shared orb 0.7.11 (#37)
Co-authored-by: Codex <noreply@openai.com>
2026-10-21 00:59:34 -05:00
james.maes 84f030d048 Merge pull request #36 from QRun-IO/feature/central-ci
ci: adopt shared QQQ orb standard
2026-10-20 18:57:40 -05:00
james.maesandCodex 9cb78190d8 ci: adopt verified central QQQ orb 0.7.3
Co-Authored-By: Codex <noreply@openai.com>
2026-10-20 18:52:23 -05:00
CircleCI 11156c8e8c Bump version to 0.1.0-RC.11 [skip ci] 2026-10-16 16:57:05 +00:00
james.maesandClaude Opus 5.5 0cc273bb52 Merge develop into release/0.1 for 0.1.0-RC.11 (#33 skip non-queryable tables, full error detail)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 11:54:24 -05:00
james.maes 91d86b016a Merge pull request #33 from QRun-IO/feature/backups-error-detail-unqueryable
fix(run): skip unqueryable tables and record sanitized error detail
2026-10-16 11:51:14 -05:00
james.maesandClaude Opus 5.5 0c28ea6263 fix(run): skip unqueryable tables and record sanitized error detail
A table on a backend module with no query interface (a storage-only
module such as qbit-edi's edi_preview_download) was classified DATA,
read by the keyset pager, and failed the whole run with
"IllegalStateException: Query is not implemented in this module".
TableRoles.isQueryable() now resolves the module through
QBackendModuleDispatcher (cached per backend type) and such tables are
EXTERNAL and always excluded by ScopeResolver with reason NOT_QUERYABLE,
even when selected by name or role. The Run backup review lists them,
and no per-table export process is offered for them.

Failed runs now persist "Backup failed: Class: message" in error_message
and the class, cause chain and top root-cause frames (bounded to 8 KB)
in error_detail, both sanitized by the new FailureText (URL user-info,
presigned query parameters, key=value secrets, Authorization/Bearer
values, AWS access key ids, PEM blocks and Postgres row values are
redacted; object keys and bucket names are kept).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 11:41:15 -05:00
CircleCI 036cd45f32 Bump version to 0.1.0-RC.10 [skip ci] 2026-10-16 16:31:49 +00:00
github-actions[bot] eaa6c9b93a Merge develop into release/0.1 for the next 0.1.0 RC 2026-10-16 15:57:53 +00:00
james.maes 825944fab4 Merge pull request #32 from QRun-IO/feature/backups-setup-attention-consistent
fix(app): Backups Setup and Needs attention agree
2026-10-16 10:19:49 -05:00
james.maesandClaude Opus 5.5 b25f4ff244 fix(app): Backups Setup and Needs attention derive from one list
The home said "1 item needs attention" in Setup while Needs attention said
"Nothing needs attention" (unresolved storage aliases). Every Setup item that
needs setup is now also listed under Needs attention, from the same item list.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 09:08:20 -05:00
james.maes b58c0edbd5 Merge pull request #31 from QRun-IO/ci/release-rc-secrets-inherit
ci(release-rc): pass secrets so the shared workflow can sign the RC tag
2026-10-16 08:04:37 -05:00
james.maesandClaude Opus 5.5 17aad52cdf ci(release-rc): pass secrets to the shared workflow so it can sign the RC tag
QRun-IO/.github#2 adds a tag-and-release job that signs vX with the
QRUN_TAG_SIGNING_KEY secret after Maven Central confirms the artifact.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 16:20:00 -05:00
CircleCI 33cb1f7a17 Bump version to 0.1.0-RC.9 [skip ci] 2026-10-15 19:24:05 +00:00
james.maesandClaude Opus 5.5 773629d253 Merge develop into release/0.1 for 0.1.0-RC.9 (cluster caches, QQQ RC.14)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 14:20:21 -05:00
james.maes 1b37582233 Merge pull request #30 from QRun-IO/feature/cluster-caches
Register backups caches with ClusterCaches (multi-node)
2026-10-15 14:11:22 -05:00
james.maesandClaude Opus 5.5 2f1964ddd1 build: QQQ 4.1.0-RC.14 (ships ClusterCaches)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 14:05:06 -05:00
james.maesandClaude Opus 5.5 e57ab62193 feat(cluster): register backups caches with ClusterCaches
The cached Prometheus text is shared as qbit-backups.metrics and
cleared on every node when a run finishes or a plan is saved or
deleted (the plan customizer now also runs post insert/update/delete);
the 60 s TTL stays as the safety net. SlaChecker's manifest-head and
bucket-audit throttles and the process-permission map are node-local.

Builds against QQQ 4.1.0-SNAPSHOT (qqq.snapshot.version) until the QQQ
RC with ClusterCaches is published; a release must pin that RC.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 12:11:11 -05:00
james.maes e263f3bc8b Merge pull request #29 from QRun-IO/fix/producer-version-from-build
fix: qbit metadata version comes from the build
2026-10-15 01:42:56 -05:00
james.maesandClaude Opus 5.5 ab969bf99b fix: the qbit metadata version comes from the build, not a hardcoded constant
The producer read a literal version, so released artifacts reported a stale
or -SNAPSHOT version. qbit-backups.properties (version=${project.version}) is
Maven-filtered and the producer loads it; tests assert producer == bundle ==
artifact version.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 01:27:59 -05:00
james.maes b17664db8c Merge pull request #28 from QRun-IO/fix/help-bundle-version
fix(help): help bundle version comes from the build, not a hardcoded SNAPSHOT
2026-10-14 22:37:20 -05:00
CircleCI 9855521637 Bump version to 0.1.0-RC.8 [skip ci] 2026-10-15 03:36:37 +00:00
james.maesandClaude Opus 5.5 99f74b4b5f Merge develop into release/0.1 for 0.1.0-RC.8 (#23 health checks)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 22:32:35 -05:00
james.maes eb413b6e15 Merge pull request #23 from QRun-IO/feature/health-checks
feat(health): register backups SLA and destination checks with core central health
2026-10-14 22:05:12 -05:00
james.maes 1e17dada29 Merge remote-tracking branch 'origin/develop' into feature/health-checks
# Conflicts:
#	CHANGELOG.md
2026-10-14 22:02:35 -05:00
CircleCI fa9c4c1774 Bump version to 0.1.0-RC.7 [skip ci] 2026-10-15 02:21:57 +00:00
james.maesandClaude Opus 5.5 c8ba79f55b Merge develop into release/0.1 for 0.1.0-RC.7 (#26 QQQ RC.8, #27 help bundle)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 21:18:12 -05:00
james.maesandClaude Opus 5.5 9a2a1dd88e Merge origin/develop into feature/health-checks; pin QQQ 4.1.0-RC.8
RC.8 ships the central health kernel (QRun-IO/qqq#1207).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 21:14:59 -05:00
CircleCI 7830226982 Bump version to 0.1.0-RC.6 [skip ci] 2026-10-14 22:44:27 +00:00
james.maesandClaude Opus 5.5 b1f258a3d5 Merge develop into release/0.1 for 0.1.0-RC.6 (#24)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 17:41:40 -05:00
CircleCI 3df24cda5a Bump version to 0.1.0-RC.5 [skip ci] 2026-10-14 22:22:38 +00:00
james.maesandClaude Opus 5.5 987c20899b Merge develop into release/0.1 for 0.1.0-RC.5 (#25 setup card, default plan, scheduled verify)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 17:19:54 -05:00
james.maesandClaude Opus 5.5 f9767ede83 chore: drop optional qqq-middleware-health dependency; docs for backups health checks
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 14:55:03 -05:00
james.maesandClaude Opus 5.5 8d56613f7d feat(health): register backups SLA and destination checks; drop BackupsHealthIndicator
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 14:55:03 -05:00
james.maesandClaude Opus 5.5 0f9178dc14 feat(health): read-only destination probe mode
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 14:55:02 -05:00
CircleCI 14bb6fa1b4 Bump version to 0.1.0-RC.4 [skip ci] 2026-10-14 12:26:09 +00:00
james.maesandClaude Opus 5.5 b1ff70d7d3 Merge develop into release/0.1 for 0.1.0-RC.4 (#21 schema fingerprint, keyset pager, guardrails)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 07:21:32 -05:00
CircleCI cda334f2fe Bump version to 0.1.0-RC.3 [skip ci] 2026-10-14 00:53:05 +00:00
james.maesandClaude Opus 5.5 590b132fb6 Merge develop into release/0.1 for 0.1.0-RC.3 (core alerts, renamed alert types, #20)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 19:50:34 -05:00
CircleCI f0a8c5000e Bump version to 0.1.0-RC.2 [skip ci] 2026-10-13 16:11:19 +00:00
james.maesandClaude Opus 5.5 8f3f9ec60a Merge develop into release/0.1 for 0.1.0-RC.2
qbit-object-storage 0.1.0-RC.2 (AWS SDK v2 2.41.34, GHSA-443w-3rq3-5m5h; #17).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 11:08:28 -05:00
CircleCI cdaf218201 Bump version to 0.1.0-RC.1 [skip ci] 2026-10-13 00:26:41 +00:00
63 changed files with 3519 additions and 446 deletions

No files matched your search

+11 -57
View File
@@ -1,60 +1,14 @@
version: 2.1
setup: true
orbs:
qqq-orb: kingsrook/qqq-orb@0.6.9
commands:
configure-package-install:
steps:
- run:
name: Keep package installation unattended
command: |
# These build machines are discarded after the job.
sudo install -d /etc/needrestart/conf.d
printf '%s\n' '$nrconf{restart} = "l";' | sudo tee /etc/needrestart/conf.d/99-qqq-ci.conf >/dev/null
qqq-orb: kingsrook/qqq-orb@0.8
workflows:
test_only:
jobs:
- qqq-orb/mvn_test_only:
pre-steps:
- configure-package-install
context: [qqq-maven-registry-credentials]
filters:
branches:
ignore: /(develop|release\/.*)/
publish_snapshot:
jobs:
- qqq-orb/mvn_publish:
pre-steps:
- configure-package-install
context: [qqq-maven-registry-credentials]
branch_type: snapshot
filters:
branches:
only: [develop]
publish_release_candidate:
jobs:
- qqq-orb/mvn_publish:
pre-steps:
- configure-package-install
context: [qqq-maven-registry-credentials]
branch_type: release_candidate
filters:
branches:
only: [/release\/.*/]
publish_release:
jobs:
- qqq-orb/mvn_publish:
pre-steps:
- configure-package-install
context: [qqq-maven-registry-credentials]
branch_type: release
filters:
branches:
ignore: /.*/
tags:
only: [/^v\d+\.\d+\.\d+$/]
setup:
jobs:
- qqq-orb/generate_pipeline:
orb_version: '0.8'
filters:
branches:
ignore: automation/qbit-rc-pending
tags:
only: /^v\d+\.\d+\.\d+$/
+7
View File
@@ -0,0 +1,7 @@
name: build
on:
push:
jobs:
maven:
uses: self:KofTwentyTwo/ci-workflows/.gitea/workflows/maven.yaml@v1
secrets: inherit
+23
View File
@@ -0,0 +1,23 @@
name: CodeQL
'on':
push:
branches:
- main
- develop
- release/**
- hotfix/**
pull_request: {}
schedule:
- cron: 41 16 * * 0
workflow_dispatch: {}
permissions:
contents: read
actions: read
security-events: write
packages: read
concurrency:
group: codeql-${{ github.event.pull_request.number || github.ref }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
jobs:
analyze:
uses: QRun-IO/qqq-orb/.github/workflows/qbit-codeql.yml@c288a8864fe9054f68410e1d78f5863aea4c4d22
+62 -13
View File
@@ -1,25 +1,74 @@
# Cut the next release candidate (QRun-IO/qqq docs/QRUN-QBIT-REPO-STANDARD.md, C6):
# run this workflow by hand, or merge a develop PR labelled `release:rc`. It merges develop into
# the release line and the release/* push runs CircleCI publish_release_candidate.
name: Release candidate
on:
'on':
workflow_dispatch:
inputs:
dry_run:
description: Print the plan without merging or creating branches
description: Plan a cut without changing release state
type: boolean
default: false
finalize:
description: Retry finalization of an existing cut; do not cut another RC
type: boolean
default: false
recover:
description: Recover the same published RC after a deployment timeout; never
reupload
type: boolean
default: false
circle_build:
description: Original Circle publisher build number (recovery only)
type: string
default: ''
merge_sha:
description: Existing cut merge_sha (finalize retry only)
type: string
default: ''
bump_sha:
description: Existing cut bump_sha (finalize retry only)
type: string
default: ''
branch:
description: Existing cut branch (finalize retry only)
type: string
default: ''
version:
description: Existing cut version (finalize retry only)
type: string
default: ''
pull_request:
types: [closed]
branches: [develop]
types:
- closed
branches:
- develop
repository_dispatch:
types:
- qbit-rc-published
permissions:
contents: write
actions: read
checks: read
jobs:
release-rc:
if: github.event_name == 'workflow_dispatch' || (github.event.pull_request.merged == true && contains(github.event.pull_request.labels.*.name, 'release:rc'))
uses: QRun-IO/.github/.github/workflows/qbit-release-rc.yml@main
if: github.event_name == 'workflow_dispatch' || github.event_name == 'repository_dispatch'
|| (github.event_name == 'pull_request' && github.event.pull_request.merged
== true && github.event.pull_request.base.ref == 'develop' && contains(github.event.pull_request.labels.*.name,
'release:rc'))
uses: QRun-IO/qqq-orb/.github/workflows/qbit-release-rc.yml@cc30f599e63c8e41629c99d23395bac1adb8bc44
with:
dry_run: ${{ github.event_name == 'workflow_dispatch' && inputs.dry_run }}
dry_run: ${{ github.event_name == 'workflow_dispatch' && inputs.dry_run || false
}}
finalize: ${{ github.event_name == 'repository_dispatch' || (github.event_name
== 'workflow_dispatch' && inputs.finalize) }}
recover: ${{ github.event_name == 'workflow_dispatch' && inputs.recover || false
}}
circle_build: ${{ github.event_name == 'workflow_dispatch' && inputs.circle_build
|| '' }}
merge_sha: ${{ github.event_name == 'repository_dispatch' && github.event.client_payload.merge_sha
|| inputs.merge_sha || '' }}
bump_sha: ${{ github.event_name == 'repository_dispatch' && github.event.client_payload.bump_sha
|| inputs.bump_sha || '' }}
branch: ${{ github.event_name == 'repository_dispatch' && github.event.client_payload.branch
|| inputs.branch || '' }}
version: ${{ github.event_name == 'repository_dispatch' && github.event.client_payload.version
|| inputs.version || '' }}
secrets: inherit
+16
View File
@@ -0,0 +1,16 @@
profile: qbit
orb_version: '0.8'
default_branch: develop
java_version: '21'
browsers: true
api_checks: false
docs_only: false
release_on_main: false
release_tag_policy: stable
test_branch_policy: non-release
publish:
snapshot: true
release_candidate: true
release: true
asciidoc: false
release_completion: true
+16
View File
@@ -5,6 +5,10 @@ All notable changes to this project are documented here. The format follows Keep
## [0.1.0] - Unreleased
### Added
- Plans run on their schedule in an application with no scheduled jobs table. `backupRunDuePlans` (`BackupDuePlansProcess`), once a minute on the qbit's scheduler, starts every active plan whose cron has come due since it last started and every verification that has come due; missed times collapse into one run. Where the application has scheduled jobs it starts nothing. Before, the sync to scheduled jobs logged "ScheduledJob table not found" and no plan ever ran on its schedule unless the host built a scheduler of its own.
- Alert `backups.prune.failed`: a plan the daily prune could not prune, cleared by its next good prune.
- Client-side encryption (`CLIENT_AES256_GCM`, spec 11.2) works. `BackupsQBitConfig.withKeyProvider(QKeyProviderInterface)` installs the streaming cipher of the QQQ crypto package (`StreamingCipherTransform`: Tink streaming AEAD, a fresh data key per object, wrapped by the referenced key). A plan that asks for encryption is encrypted by its run without the host handing it a cipher, a plan is refused when the provider has no key for its reference, verification and restore read through the same provider, and a rotated key still reads what its older version wrote. A run records the key reference and a fingerprint (`v<version>:<16 hex>`), never the key. Without a key a run is refused and nothing is written in the clear.
- Central `backups.sla` and per-active-plan `backups.destination.<planId>` health checks, with bounded read-only destination diagnostics and secret-free status details.
- Always-durable backup, resume, scheduled backup, restore and verify processes with conservative `NONE` idempotency and stable backup identities on explicit job retry.
- Weighted backup phases, table/file counts, stored bytes, safe per-table/artifact logs, warnings, failures and resume notices through QQQ `JobProgress`.
- Cooperative job cancellation during backup pages, media copying, restore pages and verification scans; local media-reference spooling keeps phase separation from growing heap usage across tables.
@@ -15,6 +19,15 @@ All notable changes to this project are documented here. The format follows Keep
- Repository scaffold: `BackupsQBitConfig` and `BackupsQBitProducer` (table prefix `backups_`, permissions `backups.*`), build, CI and repository standard files.
### Changed
- **A plan with an unfinished backup could not be pruned on real storage.** A listing through the object-storage qbit dropped each object's modification time, and the pruner compared those times to find backups that never finished and are older than 7 days: with one failed run under a plan, every prune of that plan threw. The listing carries the time now, and the pruner dates an unfinished backup by its run record where a storage lists no times (and never deletes as old what it cannot date). The in-memory storage of the tests supplies times, which is why no test saw it; a host's live check did.
- **The daily prune prunes.** It is a process of its own, `backupPruneScheduled` (`BackupScheduledPruneProcess`), which prunes every active plan with nobody selecting anything. The schedule used to be on "Prune per retention" (`backupPrune`), an action for a person that needs plans selected and a review: started by a scheduler it answered "No records were selected", the scheduler logged a warning, and no old backup was ever deleted by the schedule. `backupPrune` has no schedule now. A host that scheduled it itself should stop.
- The file index of an encrypted run (`files/index-00001.jsonl.gz`: tables, record keys and where each file came from) is encrypted like every other object of the run. It was written in the clear while the catalog recorded it as encrypted, and a restore from an encrypted run could not read it. No release could encrypt before this one, so no stored run is affected.
- A plan that asks for encryption without a key provider is refused with "no key provider is configured" (was "not available in this version"); a refused run names the key reference.
- Tables whose backend module has no query interface (storage-only modules such as qbit-edi `edi_preview_download`) are classified EXTERNAL and always left out of a backup with the reason `NOT_QUERYABLE`, even when selected by name or role; the Run backup review lists them. Before, such a table was read as DATA and the whole run FAILED with "Query is not implemented in this module".
- Failed runs persist an actionable `error_message` ("Backup failed: Class: message") and fill `error_detail` with the exception class, the cause chain and the top root-cause frames (bounded to 8 KB). Both go through `FailureText.sanitize`, which redacts URL user-info, presigned query parameters, key=value secrets, Authorization/Bearer values, AWS access key ids, PEM blocks and Postgres row values while keeping object keys and bucket names.
- Multi-node deployments: the cached Prometheus text (`BackupsMetrics`) is registered with QQQ `ClusterCaches` as `qbit-backups.metrics` and cleared on every node when a run finishes or a plan is inserted, updated or deleted; the 60 s TTL remains the safety net. `SlaChecker`'s manifest-head and bucket-audit throttles and `BackupsRuntime`'s process-permission map are registered as node-local, with reasons. `BackupsClusterCachesTest` audits the package for unregistered static caches and covers a remote invalidation.
- Builds against QQQ `4.1.0-SNAPSHOT` (`qqq.snapshot.version`) for `ClusterCaches` until the next QQQ RC ships; a release must pin that RC.
- Read the QBit metadata version from the Maven artifact version so release builds report their released version.
- Target QQQ `4.1.0-RC.8` (job progress).
- Persist controlled backup failure messages instead of untrusted provider exception text.
- Pin QQQ to released 4.1.0-RC.7 and replace the temporary help loader with core HelpBundles registration.
@@ -26,3 +39,6 @@ All notable changes to this project are documented here. The format follows Keep
- New manifests identify `qqq-table-schema-v1` and carry core schema descriptors; restore and content verification still accept pre-RC.6 manifests with the original fingerprint algorithm.
- Preserve primary-key ordering, exclusive resume cursors, bounded pages and caller-owned transactions; reject non-orderable primary keys and scope filters with skip/limit.
- Require the core `backups.restore` permission during Review when using a core restore writer, including anonymous-mode hosts; preserve supplied timestamps through `RestoreWriteFlag`.
### Removed
- The legacy `BackupsHealthIndicator` and its optional `qqq-middleware-health` dependency; central health registration replaces manual indicator configuration.
+52
View File
@@ -43,6 +43,11 @@ Follow the QQQ [adoption checklist](https://github.com/QRun-IO/qqq/blob/develop/
See [the RC.6 migration notes](docs/RC6-MIGRATION.md) for fingerprint compatibility,
paging guarantees and restore permissions.
Health checks use the core health API released in QQQ `4.1.0-RC.8`.
The producer registers `backups.sla` and a read-only destination check for each
active plan (`backups.destination.<planId>`). With dependencies cached locally,
run `./mvnw -o verify`; no enforcer skip flags are required.
## In-app help
The producer registers [help/qbit-backups.yaml](src/main/resources/help/qbit-backups.yaml)
@@ -57,6 +62,33 @@ checks empty-state, widget and possible-value-source coverage. Run it with
Always use the Maven wrapper (Maven 3.9.11); Maven 3.10 cannot read the parent POM.
## Schedules
Give the qbit a scheduler (`BackupsQBitConfig.withSchedulerName`) and it runs by itself:
- **Backups and verifications** run on each plan's cron. In an application with QQQ's scheduled jobs table every plan has a scheduled job of its own, kept in sync as the plan changes. In an application without that table, `backupRunDuePlans` starts what is due, once a minute. Either way a host builds nothing.
- **Pruning** runs once a day (`backupPruneScheduled`): every active plan is pruned to its retention. A plan that cannot be pruned raises `backups.prune.failed`.
- **The SLA check** runs every `slaCheckIntervalSeconds` (`backupCheckSla`).
Without a scheduler nothing is scheduled, and plans run only by hand.
## Encryption
Backup objects are encrypted before they leave the application when a plan's encryption mode is `CLIENT_AES256_GCM` and the host has given the qbit a key provider:
```java
new BackupsQBitProducer().withQBitConfig(config.withKeyProvider(new EnvKeyProvider())).produce(qInstance);
```
- The plan's **encryption key reference** names a key of the provider. For `EnvKeyProvider` it is the name of an environment variable that holds 32 random bytes as base64, which is how a secret manager hands a key to a process. `AwsSecretsManagerKeyProvider` reads the same from AWS Secrets Manager. The key is never in a table, a log, a manifest or a message; a run records the reference and a fingerprint.
- Table parts, the file index and the copies of referenced files are encrypted (Tink streaming AEAD, a fresh data key per object). The manifest and the checksum list stay readable without the key: they hold table names, row counts and checksums (of the stored bytes, and of each part before it was encrypted, which is how a verification knows it read the right content), and no row.
- A plan cannot be saved, and a run does not start, when the provider has no key for the reference. Nothing is written in the clear instead.
- **Rotation** (the convention of the QQQ key providers, for a reference `NAME`): keep the old key as `NAME_V<old version>`, put the new key in `NAME`, set `NAME_VERSION` to the new version. New runs are written under the new version; older runs are read with the version in each object's header for as long as that version is kept.
- **Losing the key loses every backup it wrote.** Keep it where the application's database is not, and keep an old version until every run written under it has been pruned.
- The sensitive field policy `INCLUDE_ENCRYPTED_ONLY` needs this mode.
## Durable jobs and progress
Run backup now, Resume, scheduled backups, both Restore actions, and Verify backup
@@ -95,3 +127,23 @@ The backup SLA checker still owns expected intervals and grace periods.
RC.5 requires hyphenated alert names: `backups.run.missing-in-storage` and
`backups.plan.owner-invalid` replace the former underscore spellings, including
their deduplication keys. Update host routing rules that used those spellings.
## Health checks
The producer registers these central checks under component `backups`, category `STORAGE`:
| Name | Kind | Interval | Timeout |
| --- | --- | --- | --- |
| `backups.sla` | DEPENDENCY | 900s (15 minutes) | 5000ms |
| `backups.destination.<planId>` | DEPENDENCY | 86400s (24 hours) | 30000ms |
The SLA check reads persisted `slaStatus`: critical active plans that are LATE,
FAILING or MISSING_IN_STORAGE yield DOWN; non-critical failures yield DEGRADED.
Only UNVERIFIED/UNKNOWN plans yield UNKNOWN; no active plans yield UP. Details
contain counts per SLA status. The scheduled `backupCheckSla` still computes SLA state.
Destination checks are supplied for active plans and reuse `DestinationProbe` in
read-only list/head mode, including on unlocked buckets. They never write, delete,
or resolve prune credentials. The Test destination action retains its write tests.
Storage calls are bounded by the central runner, with deadline checks between calls.
Override intervals in `health_check` and disable checks through `health_check.enabled`.
+11 -12
View File
@@ -18,9 +18,10 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<properties>
<qqq.version>4.1.0-RC.26</qqq.version> <!-- feeds qbit-build-parent's qqq-bom-pom import -->
<qbit.guardrails.enforce>true</qbit.guardrails.enforce>
<qbit.guardrails.strictUiApiRoutes>true</qbit.guardrails.strictUiApiRoutes>
<revision>0.1.0-SNAPSHOT</revision>
<revision>0.1.0-RC.15</revision>
<maven.compiler.source>21</maven.compiler.source>
<maven.compiler.target>21</maven.compiler.target>
<jacoco.version>0.8.15</jacoco.version>
@@ -29,7 +30,7 @@
<parent>
<groupId>com.kingsrook</groupId>
<artifactId>qbit-build-parent</artifactId>
<version>2.1.0</version>
<version>2.2.1</version>
</parent>
<groupId>com.kingsrook.qbits</groupId>
@@ -74,13 +75,6 @@
<artifactId>qqq-backend-core</artifactId>
</dependency>
<!-- optional: the BackupsHealthIndicator (apps without qqq-middleware-health never load it) -->
<dependency>
<groupId>com.kingsrook.qqq</groupId>
<artifactId>qqq-middleware-health</artifactId>
<optional>true</optional>
</dependency>
<!-- optional: ESB events (apps without qqq-esb never load it) -->
<dependency>
<groupId>com.kingsrook.qqq</groupId>
@@ -93,7 +87,7 @@
<dependency>
<groupId>com.kingsrook.qbits</groupId>
<artifactId>qbit-object-storage</artifactId>
<version>0.1.0-RC.2</version>
<version>0.1.0-RC.10</version>
<optional>true</optional>
</dependency>
@@ -113,7 +107,7 @@
<dependency>
<groupId>com.kingsrook.qqq</groupId>
<artifactId>qqq-frontend-next</artifactId>
<version>1.0.0-RC.14</version>
<version>1.0.0-RC.38</version>
<scope>test</scope>
</dependency>
@@ -138,6 +132,7 @@
<filtering>true</filtering>
<includes>
<include>help/*.yaml</include>
<include>qbit-backups.properties</include>
</includes>
</resource>
<resource>
@@ -145,6 +140,7 @@
<filtering>false</filtering>
<excludes>
<exclude>help/*.yaml</exclude>
<exclude>qbit-backups.properties</exclude>
</excludes>
</resource>
</resources>
@@ -153,6 +149,9 @@
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<systemPropertyVariables combine.children="append">
<qbit.artifactVersion>${project.version}</qbit.artifactVersion>
</systemPropertyVariables>
<!-- the MinIO test container default credentials, resolved through ${env.X} refs like production -->
<environmentVariables>
<STORAGE_TEST_ACCESS_KEY>minioadmin</STORAGE_TEST_ACCESS_KEY>
@@ -218,7 +217,7 @@
<activeByDefault>true</activeByDefault>
</activation>
<properties>
<qqq.snapshot.version>4.1.0-RC.8</qqq.snapshot.version>
<qqq.snapshot.version>4.1.0-RC.26</qqq.snapshot.version>
</properties>
<dependencyManagement>
<dependencies>
@@ -21,8 +21,10 @@ import java.util.List;
import java.util.function.Function;
import java.util.function.Predicate;
import com.kingsrook.qbits.backups.codec.ArtifactTransform;
import com.kingsrook.qbits.backups.codec.StreamingCipherTransform;
import com.kingsrook.qbits.backups.verify.ScratchTarget;
import com.kingsrook.qbits.backups.storage.BackupStorage;
import com.kingsrook.qqq.backend.core.crypto.QKeyProviderInterface;
import com.kingsrook.qqq.backend.core.model.metadata.QInstance;
import com.kingsrook.qqq.backend.core.model.metadata.qbits.QBitConfig;
import com.kingsrook.qqq.backend.core.utils.StringUtils;
@@ -417,7 +419,23 @@ public class BackupsQBitConfig implements QBitConfig
/*******************************************************************************
** Getter for artifactTransformResolver (the decrypt hook for verify)
** Turn client-side encryption on: plans may ask for CLIENT_AES256_GCM with an
** encryption key reference, which names a key of this provider (for the
** environment provider, the variable that holds it). The same provider reads
** what it wrote, for verification and restore. Losing the key loses the
** backups it wrote: the provider's store is what has to be kept safe.
*******************************************************************************/
public BackupsQBitConfig withKeyProvider(QKeyProviderInterface keyProvider)
{
this.artifactTransformResolver = keyProvider == null ? null : keyRef -> StreamingCipherTransform.forKey(keyProvider, keyRef);
return (this);
}
/*******************************************************************************
** Getter for artifactTransformResolver: the cipher for an encryption key
** reference, for writing, verifying and restoring (null: no encryption)
*******************************************************************************/
public Function<String, ArtifactTransform> getArtifactTransformResolver()
{
@@ -428,7 +446,9 @@ public class BackupsQBitConfig implements QBitConfig
/*******************************************************************************
** Fluent setter for artifactTransformResolver: encryption key reference (the name
** of a key in a key provider) to the transform that decrypts what that key wrote.
** of a key in a key provider) to the transform that encrypts with that key and
** decrypts what it wrote, or null when there is no such key. withKeyProvider
** sets the one built on the QQQ crypto package; this is for a host with its own.
*******************************************************************************/
public BackupsQBitConfig withArtifactTransformResolver(Function<String, ArtifactTransform> artifactTransformResolver)
{
@@ -17,6 +17,17 @@
package com.kingsrook.qbits.backups;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import com.kingsrook.qbits.backups.health.BackupsDestinationHealthChecks;
import com.kingsrook.qbits.backups.health.BackupsSlaHealthCheck;
import com.kingsrook.qqq.backend.core.health.HealthCategory;
import com.kingsrook.qqq.backend.core.health.HealthCheckKind;
import com.kingsrook.qqq.backend.core.health.HealthCheckMetaData;
import com.kingsrook.qqq.backend.core.health.HealthCheckSupplierMetaData;
import com.kingsrook.qqq.backend.core.health.HealthChecksMetaData;
import com.kingsrook.qqq.backend.core.model.metadata.code.QCodeReference;
import com.kingsrook.qqq.backend.core.model.metadata.help.bundles.HelpBundles;
import com.kingsrook.qqq.backend.core.model.metadata.qbits.QBitMetaData;
import com.kingsrook.qqq.backend.core.model.metadata.qbits.QBitMetaDataProducer;
@@ -30,13 +41,41 @@ public class BackupsQBitProducer implements QBitMetaDataProducer<BackupsQBitConf
{
public static final String GROUP_ID = "com.kingsrook.qbits";
public static final String ARTIFACT_ID = "qbit-backups";
public static final String VERSION = "0.1.0";
public static final String VERSION = loadVersion();
private BackupsQBitConfig qBitConfig;
private String namespace;
/*******************************************************************************
** Read the artifact version from the Maven-filtered resource.
*******************************************************************************/
private static String loadVersion()
{
try(InputStream inputStream = BackupsQBitProducer.class.getClassLoader().getResourceAsStream("qbit-backups.properties"))
{
if(inputStream == null)
{
throw (new IllegalStateException("Missing qbit-backups.properties; build with Maven to generate the artifact version"));
}
Properties properties = new Properties();
properties.load(inputStream);
String version = properties.getProperty("version");
if(version == null || version.isBlank() || version.contains("${"))
{
throw (new IllegalStateException("Missing or unfiltered version in qbit-backups.properties; build with Maven"));
}
return (version);
}
catch(IOException e)
{
throw (new IllegalStateException("Could not read artifact version from qbit-backups.properties", e));
}
}
/*******************************************************************************
** Fluent setter for the config.
*******************************************************************************/
@@ -164,6 +203,13 @@ public class BackupsQBitProducer implements QBitMetaDataProducer<BackupsQBitConf
// Registration is metadata-only; core guards startup sync when helpContent is absent.
HelpBundles.register(qInstance, "help/qbit-backups.yaml");
HealthChecksMetaData.ofOrWithNew(qInstance)
.withCheck(new HealthCheckMetaData().withName(BackupsSlaHealthCheck.NAME).withLabel("Backup SLA")
.withComponent("backups").withKind(HealthCheckKind.DEPENDENCY).withCategory(HealthCategory.STORAGE)
.withIntervalSeconds(900).withCheck(new QCodeReference(BackupsSlaHealthCheck.class)))
.withSupplier(new HealthCheckSupplierMetaData().withNamePrefix(BackupsDestinationHealthChecks.PREFIX)
.withComponent("backups").withSupplier(new QCodeReference(BackupsDestinationHealthChecks.class)));
// A parent app only lists the apps that are its children, so attach ourselves (for example Admin, then Backups).
com.kingsrook.qqq.backend.core.model.metadata.layout.QAppMetaData parent = qBitConfig.getParentAppName() == null ? null : qInstance.getApp(qBitConfig.getParentAppName());
if(parent != null && (parent.getChildren() == null || parent.getChildren().stream().noneMatch(child -> app.getName().equals(child.getName()))))
@@ -25,6 +25,7 @@ import com.kingsrook.qbits.backups.alerts.BackupAlertSink;
import com.kingsrook.qbits.backups.alerts.NoOpBackupAlertSink;
import com.kingsrook.qbits.backups.storage.BackupStorage;
import com.kingsrook.qbits.backups.storage.BackupStorageException;
import com.kingsrook.qqq.backend.core.cluster.ClusterCaches;
/*******************************************************************************
@@ -34,7 +35,8 @@ import com.kingsrook.qbits.backups.storage.BackupStorageException;
*******************************************************************************/
public final class BackupsRuntime
{
private static final Map<String, String> PROCESS_PERMISSIONS = new ConcurrentHashMap<>();
private static final Map<String, String> PROCESS_PERMISSIONS = ClusterCaches.nodeLocal(new ConcurrentHashMap<>(),
"built from the qbit config at startup, the same on every node");
private static volatile BackupsQBitConfig config;
private static volatile Clock clock = Clock.systemUTC();
@@ -43,6 +43,7 @@ public final class BackupAlerts
public static final String PLAN_OWNER_INVALID = "backups.plan.owner-invalid";
public static final String STORAGE_DEBRIS = "backups.storage.debris";
public static final String RESTORE_COMPLETED = "backups.restore.completed";
public static final String PRUNE_FAILED = "backups.prune.failed";
/** The prefix of the heartbeat monitor key of a plan. */
public static final String HEARTBEAT_PREFIX = "backups.plan:";
@@ -95,7 +96,9 @@ public final class BackupAlerts
new AlertType(STORAGE_DEBRIS, "Backup storage has debris or orphans", BackupAlertSink.Severity.INFO,
"Prune clears debris. Orphan prefixes can be imported into the catalog or deleted."),
new AlertType(RESTORE_COMPLETED, "A restore finished", BackupAlertSink.Severity.INFO,
"Nothing to fix unless the restore failed. Open the restore run.")));
"Nothing to fix unless the restore failed. Open the restore run."),
new AlertType(PRUNE_FAILED, "Old backups could not be deleted", BackupAlertSink.Severity.WARNING,
"The daily prune could not prune this plan, so its backups are kept past the plan's retention and storage grows. Run Prune per retention on the plan to see why.")));
}
@@ -69,10 +69,11 @@ public final class BackupsHomeView
public static String render(BackupsHomeData data, String pathPrefix)
{
StringBuilder html = new StringBuilder("<div class=\"backups-home\" style=\"" + ROOT + "\">");
List<BackupsSetupStatus.Item> setupItems = BackupsSetupStatus.load(data.plans());
planStatus(html, data, pathPrefix);
setup(html, data, pathPrefix);
setup(html, setupItems, pathPrefix);
html.append("<div style=\"").append(GRID).append("\">");
needsAttention(html, data, pathPrefix);
needsAttention(html, data, setupItems, pathPrefix);
latestTestRestore(html, data, pathPrefix);
recentActivity(html, data, pathPrefix);
trend(html, data);
@@ -144,9 +145,8 @@ public final class BackupsHomeView
** The Setup card: what a working backup needs, whether each part is in place,
** and the next step, linked to its table.
*******************************************************************************/
private static void setup(StringBuilder html, BackupsHomeData data, String prefix)
private static void setup(StringBuilder html, List<BackupsSetupStatus.Item> items, String prefix)
{
List<BackupsSetupStatus.Item> items = BackupsSetupStatus.load(data.plans());
open(html, "Setup");
long todo = items.stream().filter(i -> i.state() == BackupsSetupStatus.State.TODO).count();
html.append("<p style=\"margin:0 0 .6rem;font-size:.9rem;\">")
@@ -185,23 +185,27 @@ public final class BackupsHomeView
/*******************************************************************************
** Needs attention.
** Needs attention: every Setup item that needs setup (the same list the Setup
** card counts), plus plans in a problem state and recent failed runs, so the two
** cards never disagree.
*******************************************************************************/
private static void needsAttention(StringBuilder html, BackupsHomeData data, String prefix)
private static void needsAttention(StringBuilder html, BackupsHomeData data, List<BackupsSetupStatus.Item> setupItems, String prefix)
{
open(html, "Needs attention");
List<QRecord> plans = data.plansNeedingAttention();
if(data.plans().isEmpty())
List<BackupsSetupStatus.Item> setupTodo = setupItems.stream().filter(i -> i.state() == BackupsSetupStatus.State.TODO).toList();
List<QRecord> plans = data.plansNeedingAttention();
if(setupTodo.isEmpty() && plans.isEmpty() && data.failedRuns().isEmpty())
{
empty(html, "Nothing to check yet: no plans.");
}
else if(plans.isEmpty() && data.failedRuns().isEmpty())
{
empty(html, "Nothing needs attention.");
empty(html, data.plans().isEmpty() ? "Nothing to check yet: no plans." : "Nothing needs attention.");
}
else
{
html.append("<ul style=\"").append(ITEMS).append("\">");
for(BackupsSetupStatus.Item item : setupTodo)
{
html.append("<li>Setup: <a style=\"").append(LINK).append("\" href=\"").append(esc(prefix + "/" + item.tableName())).append("\">").append(esc(item.label())).append("</a>: ")
.append(esc(item.detail())).append("</li>");
}
for(QRecord plan : plans)
{
html.append("<li>").append(recordLink(prefix, BackupsTables.PLAN, plan.getValue("id"), plan.getValueString("name")))
@@ -83,4 +83,15 @@ public interface ArtifactTransform
{
return ("");
}
/***************************************************************************
** What a run records to say which key wrote its objects (never the key),
** or null for a transform that has no key.
***************************************************************************/
default String keyFingerprint()
{
return (null);
}
}
@@ -0,0 +1,197 @@
/*
* Copyright 2026 Kingsrook, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.backups.codec;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HexFormat;
import com.kingsrook.qqq.backend.core.crypto.QKeyMaterial;
import com.kingsrook.qqq.backend.core.crypto.QKeyProviderInterface;
import com.kingsrook.qqq.backend.core.crypto.StreamingArtifactCipher;
import com.kingsrook.qqq.backend.core.exceptions.QException;
/*******************************************************************************
** Client-side encryption of a backup's objects (the plan's CLIENT_AES256_GCM,
** spec 11.2): the streaming cipher of the QQQ crypto package, keyed by a
** reference into a key provider.
**
** Every object gets a fresh data key, wrapped by the current version of the
** referenced key; the object's own header names the key and the version that
** wrapped it, so an object written before a rotation is read with the version
** it was written under for as long as the provider still has it.
**
** The key never leaves the provider and the cipher: it is in no table, log,
** manifest or message. What is recorded is the reference and a fingerprint.
*******************************************************************************/
public final class StreamingCipherTransform implements ArtifactTransform
{
/** The scheme a manifest records for objects this transform wrote. */
public static final String SCHEME = "tink-streaming-aead-AES256_GCM_HKDF_1MB";
private static final String FINGERPRINT_DOMAIN = "qbit-backups key fingerprint v1";
private static final int FINGERPRINT_HEX = 16;
private final StreamingArtifactCipher cipher;
private final String keyRef;
private final String fingerprint;
/*******************************************************************************
**
*******************************************************************************/
private StreamingCipherTransform(QKeyProviderInterface keyProvider, String keyRef, String fingerprint)
{
this.cipher = new StreamingArtifactCipher(keyProvider);
this.keyRef = keyRef;
this.fingerprint = fingerprint;
}
/*******************************************************************************
** The transform for a key reference, or null when the provider has no usable
** key of that name (so that a plan, a run, a verification and a restore each
** say "no key for this reference" in their own words, and nothing is written
** or read in the clear instead).
*******************************************************************************/
public static StreamingCipherTransform forKey(QKeyProviderInterface keyProvider, String keyRef)
{
if(keyProvider == null || keyRef == null || keyRef.isBlank())
{
return (null);
}
try
{
QKeyMaterial current = keyProvider.getKey(keyRef);
return (current == null ? null : new StreamingCipherTransform(keyProvider, keyRef, fingerprint(current)));
}
catch(QException e)
{
////////////////////////////////////////////////////////////////////////////
// the provider's message names the setting, never the key; the callers //
// say which reference has no key, so nothing of it is carried further //
////////////////////////////////////////////////////////////////////////////
return (null);
}
}
/*******************************************************************************
** What a run records to say which key (and which version of it) wrote its
** objects: the version, and the start of a hash over the key under a label of
** this qbit's own. Two keys do not share one, and the key cannot be had from it.
*******************************************************************************/
static String fingerprint(QKeyMaterial key)
{
try
{
MessageDigest digest = MessageDigest.getInstance("SHA-256");
digest.update(FINGERPRINT_DOMAIN.getBytes(StandardCharsets.UTF_8));
byte[] keyBytes = key.getKeyBytes();
try
{
digest.update(keyBytes);
}
finally
{
java.util.Arrays.fill(keyBytes, (byte) 0);
}
return ("v" + key.getVersion() + ":" + HexFormat.of().formatHex(digest.digest()).substring(0, FINGERPRINT_HEX));
}
catch(NoSuchAlgorithmException e)
{
throw (new IllegalStateException("SHA-256 is not available", e));
}
}
/*******************************************************************************
** {@inheritDoc}
*******************************************************************************/
@Override
public OutputStream wrap(OutputStream out) throws IOException
{
try
{
return (cipher.newEncryptingStream(keyRef, out));
}
catch(QException e)
{
throw (new IOException("An object could not be encrypted with the key " + keyRef + ": the key provider did not supply it"));
}
}
/*******************************************************************************
** {@inheritDoc}
*******************************************************************************/
@Override
public InputStream unwrap(InputStream in) throws IOException
{
try
{
return (cipher.newDecryptingStream(in));
}
catch(QException e)
{
throw (new IOException("An object could not be decrypted: it is not an encrypted backup object, or the key provider has no key of the version that wrote it (key " + keyRef + ")"));
}
}
/*******************************************************************************
** {@inheritDoc}
*******************************************************************************/
@Override
public boolean encrypts()
{
return (true);
}
/*******************************************************************************
** {@inheritDoc}
*******************************************************************************/
@Override
public String keySuffix()
{
return (".tink");
}
/*******************************************************************************
** {@inheritDoc}
*******************************************************************************/
@Override
public String keyFingerprint()
{
return (fingerprint);
}
}
@@ -0,0 +1,95 @@
/*
* Copyright 2026 Kingsrook, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.backups.health;
import com.kingsrook.qbits.backups.model.BackupsTables;
import com.kingsrook.qbits.backups.plan.DestinationProbe;
import com.kingsrook.qbits.backups.run.BackupCatalog;
import com.kingsrook.qqq.backend.core.context.QContext;
import com.kingsrook.qqq.backend.core.exceptions.QException;
import com.kingsrook.qqq.backend.core.health.HealthCheck;
import com.kingsrook.qqq.backend.core.health.HealthCheckInput;
import com.kingsrook.qqq.backend.core.health.HealthCheckOutcome;
import com.kingsrook.qqq.backend.core.health.HealthDetails;
import com.kingsrook.qqq.backend.core.model.data.QRecord;
import com.kingsrook.qqq.backend.core.model.session.QSystemUserSession;
/*******************************************************************************
** Reuse the destination diagnostic in read-only mode; never publish its text.
*******************************************************************************/
public class BackupsDestinationHealthCheck implements HealthCheck
{
private final Integer planId;
/*******************************************************************************
** Retain only the id; destination and active state are read on each run.
*******************************************************************************/
public BackupsDestinationHealthCheck(Integer planId)
{
this.planId = planId;
}
/*******************************************************************************
** A removed or disabled plan can remain registered until supplier refresh.
*******************************************************************************/
@Override
public HealthCheckOutcome run(HealthCheckInput input)
{
boolean ownsContext = QContext.getQInstance() == null;
if(ownsContext)
{
QContext.init(input.getQInstance(), new QSystemUserSession(input.getQInstance()));
}
try
{
if(BackupsSlaHealthCheck.expired(input))
{
return (HealthCheckOutcome.down("Backup destination check timed out"));
}
QRecord plan = new BackupCatalog().get(BackupsTables.PLAN, planId).orElse(null);
if(plan == null || !Boolean.TRUE.equals(plan.getValueBoolean("isActive")))
{
return (HealthCheckOutcome.unknown("Backup plan is no longer active"));
}
DestinationProbe.Report report = DestinationProbe.probeReadOnly(plan, input.getDeadline());
if(BackupsSlaHealthCheck.expired(input))
{
return (HealthCheckOutcome.down("Backup destination check timed out"));
}
return ((report.ok() ? HealthCheckOutcome.up("Backup destination is readable") : HealthCheckOutcome.down("Backup destination probe failed"))
.withDetails(new HealthDetails().withValue("planId", planId).withValue("readOnly", true)
.withValue("checks", report.checks().size()).withValue("failedChecks", report.checks().stream().filter(check -> !check.ok()).count())));
}
catch(QException | RuntimeException e)
{
return (HealthCheckOutcome.down("Backup destination could not be checked"));
}
finally
{
if(ownsContext)
{
QContext.clear();
}
}
}
}
@@ -0,0 +1,77 @@
/*
* Copyright 2026 Kingsrook, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.backups.health;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import com.kingsrook.qbits.backups.model.BackupsTables;
import com.kingsrook.qbits.backups.run.BackupCatalog;
import com.kingsrook.qqq.backend.core.context.QContext;
import com.kingsrook.qqq.backend.core.exceptions.QException;
import com.kingsrook.qqq.backend.core.health.HealthCategory;
import com.kingsrook.qqq.backend.core.health.HealthCheckKind;
import com.kingsrook.qqq.backend.core.health.HealthCheckMetaData;
import com.kingsrook.qqq.backend.core.health.HealthCheckSupplier;
import com.kingsrook.qqq.backend.core.model.data.QRecord;
import com.kingsrook.qqq.backend.core.model.metadata.QInstance;
import com.kingsrook.qqq.backend.core.model.session.QSystemUserSession;
/*******************************************************************************
** Discover one daily, read-only destination check per active backup plan.
*******************************************************************************/
public class BackupsDestinationHealthChecks implements HealthCheckSupplier
{
public static final String PREFIX = "backups.destination";
/*******************************************************************************
** Resolve from current catalog data, without opening any storage connections.
*******************************************************************************/
@Override
public List<HealthCheckMetaData> supply(QInstance qInstance) throws QException
{
boolean ownsContext = QContext.getQInstance() == null;
if(ownsContext)
{
QContext.init(qInstance, new QSystemUserSession(qInstance));
}
try
{
List<HealthCheckMetaData> checks = new ArrayList<>();
for(QRecord plan : new BackupCatalog().where(BackupsTables.PLAN, "isActive", true))
{
Integer planId = plan.getValueInteger("id");
checks.add(new HealthCheckMetaData().withName(PREFIX + "." + planId.toString().toLowerCase(Locale.ROOT))
.withLabel("Backup destination " + planId).withComponent("backups")
.withKind(HealthCheckKind.DEPENDENCY).withCategory(HealthCategory.STORAGE)
.withIntervalSeconds(86400).withTimeoutMs(30000).withCheckInstance(new BackupsDestinationHealthCheck(planId)));
}
return (checks);
}
finally
{
if(ownsContext)
{
QContext.clear();
}
}
}
}
@@ -1,133 +0,0 @@
/*
* Copyright 2026 Kingsrook, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.backups.health;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.kingsrook.qbits.backups.model.BackupsTables;
import com.kingsrook.qbits.backups.run.BackupCatalog;
import com.kingsrook.qqq.backend.core.context.QContext;
import com.kingsrook.qqq.backend.core.exceptions.QException;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QCriteriaOperator;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QFilterCriteria;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QQueryFilter;
import com.kingsrook.qqq.backend.core.model.data.QRecord;
import com.kingsrook.qqq.backend.core.model.metadata.QInstance;
import com.kingsrook.qqq.backend.core.model.session.QSession;
import com.kingsrook.qqq.backend.core.model.session.QSystemUserSession;
import com.kingsrook.qqq.middleware.health.HealthIndicator;
import com.kingsrook.qqq.middleware.health.model.metadata.HealthCheckResult;
import com.kingsrook.qqq.middleware.health.model.metadata.HealthStatus;
/*******************************************************************************
** The Backups health indicator (design spec section 10.4), for
** qqq-middleware-health (an optional dependency: an app that does not have that
** module never loads this class). It reports DOWN if any active plan marked
** critical is LATE, FAILING or MISSING_IN_STORAGE, and UP with details otherwise.
** It reads the slaStatus the SLA checker maintains; it never touches storage, so
** a health call is cheap.
**
** It is OFF the liveness path by design. Add it to the indicators of the
** instance's health check (the readiness and monitoring view), and do not point a
** Kubernetes liveness probe at a check that includes it: a backup problem must
** never restart pods.
*******************************************************************************/
public class BackupsHealthIndicator implements HealthIndicator
{
public static final String NAME = "backups";
private static final Set<String> CRITICAL_STATUSES = Set.of("LATE", "FAILING", "MISSING_IN_STORAGE");
/*******************************************************************************
** {@inheritDoc}
*******************************************************************************/
@Override
public String getName()
{
return (NAME);
}
/*******************************************************************************
** {@inheritDoc}
*******************************************************************************/
@Override
public HealthCheckResult check(QInstance qInstance) throws QException
{
long started = System.currentTimeMillis();
boolean ownsContext = QContext.getQInstance() == null;
if(ownsContext)
{
QContext.init(qInstance, systemSession(qInstance));
}
try
{
List<QRecord> plans = new BackupCatalog().query(BackupsTables.PLAN, new QQueryFilter(new QFilterCriteria("isActive", QCriteriaOperator.EQUALS, true)));
List<String> criticalProblems = new ArrayList<>();
Map<String, Integer> byStatus = new LinkedHashMap<>();
for(QRecord plan : plans)
{
String status = plan.getValueString("slaStatus") == null ? "UNKNOWN" : plan.getValueString("slaStatus");
byStatus.merge(status, 1, Integer::sum);
if(Boolean.TRUE.equals(plan.getValueBoolean("critical")) && CRITICAL_STATUSES.contains(status))
{
criticalProblems.add(plan.getValueString("planKey") + ": " + status);
}
}
Map<String, Object> details = new LinkedHashMap<>();
details.put("activePlans", plans.size());
details.put("plansByStatus", byStatus);
if(!criticalProblems.isEmpty())
{
details.put("criticalPlansWithProblems", criticalProblems);
}
return (new HealthCheckResult()
.withStatus(criticalProblems.isEmpty() ? HealthStatus.UP : HealthStatus.DOWN)
.withDurationMs(System.currentTimeMillis() - started)
.withDetails(details));
}
finally
{
if(ownsContext)
{
QContext.clear();
}
}
}
/*******************************************************************************
** The session for a health request that has no QQQ context. It must be the
** core system user: token-based authentication modules (OAuth2, Auth0)
** reject any other tokenless session, which failed the check on such hosts.
*******************************************************************************/
static QSession systemSession(QInstance qInstance)
{
return (new QSystemUserSession(qInstance));
}
}
@@ -0,0 +1,132 @@
/*
* Copyright 2026 Kingsrook, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.backups.health;
import java.time.Instant;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.kingsrook.qbits.backups.model.BackupsTables;
import com.kingsrook.qbits.backups.run.BackupCatalog;
import com.kingsrook.qqq.backend.core.context.QContext;
import com.kingsrook.qqq.backend.core.exceptions.QException;
import com.kingsrook.qqq.backend.core.health.HealthCheck;
import com.kingsrook.qqq.backend.core.health.HealthCheckInput;
import com.kingsrook.qqq.backend.core.health.HealthCheckOutcome;
import com.kingsrook.qqq.backend.core.health.HealthDetails;
import com.kingsrook.qqq.backend.core.model.data.QRecord;
import com.kingsrook.qqq.backend.core.model.session.QSystemUserSession;
/*******************************************************************************
** Read persisted SLA state using the former indicator's critical-plan rule.
** SLA calculation and storage verification remain the scheduled checker's job.
*******************************************************************************/
public class BackupsSlaHealthCheck implements HealthCheck
{
public static final String NAME = "backups.sla";
private static final Set<String> BAD_STATUSES = Set.of("LATE", "FAILING", "MISSING_IN_STORAGE");
private static final List<String> STATUSES = List.of("OK", "LATE", "FAILING", "MISSING_IN_STORAGE", "UNVERIFIED", "ABANDONED", "OWNER_INVALID", "UNKNOWN");
/*******************************************************************************
** Counts use a fixed vocabulary so stored strings cannot become detail keys.
*******************************************************************************/
@Override
public HealthCheckOutcome run(HealthCheckInput input)
{
boolean ownsContext = QContext.getQInstance() == null;
if(ownsContext)
{
QContext.init(input.getQInstance(), new QSystemUserSession(input.getQInstance()));
}
try
{
if(expired(input))
{
return (HealthCheckOutcome.down("Backup SLA check timed out"));
}
List<QRecord> plans = new BackupCatalog().where(BackupsTables.PLAN, "isActive", true);
Map<String, Integer> counts = new LinkedHashMap<>();
STATUSES.forEach(status -> counts.put(status, 0));
boolean criticalBad = false;
boolean ordinaryBad = false;
for(QRecord plan : plans)
{
String status = plan.getValueString("slaStatus");
status = status != null && STATUSES.contains(status) ? status : "UNKNOWN";
counts.merge(status, 1, Integer::sum);
if(BAD_STATUSES.contains(status))
{
if(Boolean.TRUE.equals(plan.getValueBoolean("critical")))
{
criticalBad = true;
}
else
{
ordinaryBad = true;
}
}
}
if(expired(input))
{
return (HealthCheckOutcome.down("Backup SLA check timed out"));
}
HealthDetails details = new HealthDetails().withValue("activePlans", plans.size());
counts.forEach((status, count) -> details.withValue("slaStatus." + status, count));
HealthCheckOutcome outcome = HealthCheckOutcome.up("Backup SLA has no failures");
if(criticalBad)
{
outcome = HealthCheckOutcome.down("Critical backup plans have SLA failures");
}
else if(ordinaryBad)
{
outcome = HealthCheckOutcome.degraded("Backup plans have SLA failures");
}
else if(!plans.isEmpty() && counts.get("UNVERIFIED") + counts.get("UNKNOWN") == plans.size())
{
outcome = HealthCheckOutcome.unknown("Backup SLA is not verified yet");
}
return (outcome.withDetails(details));
}
catch(QException | RuntimeException e)
{
return (HealthCheckOutcome.down("Backup SLA state could not be read"));
}
finally
{
if(ownsContext)
{
QContext.clear();
}
}
}
/*******************************************************************************
** Stop between catalog operations when the runner's budget is exhausted.
*******************************************************************************/
static boolean expired(HealthCheckInput input)
{
return (Thread.currentThread().isInterrupted() || !Instant.now().isBefore(input.getDeadline()));
}
}
@@ -20,10 +20,12 @@ package com.kingsrook.qbits.backups.metrics;
import java.time.Duration;
import java.time.Instant;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
import com.kingsrook.qbits.backups.BackupsQBitConfig;
import com.kingsrook.qbits.backups.BackupsRuntime;
import com.kingsrook.qbits.backups.model.BackupsTables;
import com.kingsrook.qbits.backups.run.BackupCatalog;
import com.kingsrook.qqq.backend.core.cluster.ClusterCaches;
import com.kingsrook.qqq.backend.core.exceptions.QException;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QCriteriaOperator;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QFilterCriteria;
@@ -56,10 +58,21 @@ public final class BackupsMetrics
{
public static final String ENDPOINT_PATH = "/metrics/backups";
/** Cluster cache name of the rendered text: cleared on every node when a run finishes or a plan changes. */
public static final String CACHE_NAME = "qbit-backups.metrics";
private static final Duration CACHE = Duration.ofSeconds(60);
private static String cachedText;
private static Instant cachedAt;
private static final AtomicReference<Rendered> CACHED = ClusterCaches.shared(CACHE_NAME, new AtomicReference<>(), BackupsMetrics::resetCache, null);
/*******************************************************************************
** The rendered text and when it was rendered.
*******************************************************************************/
private record Rendered(String text, Instant at)
{
}
@@ -84,12 +97,21 @@ public final class BackupsMetrics
/*******************************************************************************
** Forget the cached text (tests).
** Forget the cached text on this node.
*******************************************************************************/
public static synchronized void resetCache()
public static void resetCache()
{
cachedText = null;
cachedAt = null;
CACHED.set(null);
}
/*******************************************************************************
** Forget the cached text on every node (the backup data changed).
*******************************************************************************/
public static void invalidate()
{
ClusterCaches.invalidate(CACHE_NAME);
}
@@ -99,13 +121,14 @@ public final class BackupsMetrics
*******************************************************************************/
public static synchronized String renderCached() throws QException
{
Instant now = BackupsRuntime.getClock().instant();
if(cachedText == null || cachedAt == null || cachedAt.plus(CACHE).isBefore(now))
Instant now = BackupsRuntime.getClock().instant();
Rendered cached = CACHED.get();
if(cached == null || cached.at().plus(CACHE).isBefore(now))
{
cachedText = render();
cachedAt = now;
cached = new Rendered(render(), now);
CACHED.set(cached);
}
return (cachedText);
return (cached.text());
}
@@ -413,15 +413,22 @@ public final class BackupsTables
QCodeReference validation = new QCodeReference(BackupPlanTableCustomizer.class);
table.withCustomizer(TableCustomizers.PRE_INSERT_RECORD, validation);
table.withCustomizer(TableCustomizers.PRE_UPDATE_RECORD, validation);
/////////////////////////////////////////////////////////////////////////////
// after a save or delete, the plan customizer clears the cached metrics on //
// every node //
/////////////////////////////////////////////////////////////////////////////
QCodeReference post = validation;
if(StringUtils.hasContent(config.getSchedulerName()))
{
QCodeReferenceWithProperties sync = MultiCustomizer.of(
post = MultiCustomizer.of(
BaseSyncToScheduledJobTableCustomizer.makeCodeReference(table, new BackupPlanSyncToScheduledJobProcess()),
BaseSyncToScheduledJobTableCustomizer.makeCodeReference(table, new BackupPlanVerifySyncToScheduledJobProcess()));
table.withCustomizer(TableCustomizers.POST_INSERT_RECORD, sync);
table.withCustomizer(TableCustomizers.POST_UPDATE_RECORD, sync);
table.withCustomizer(TableCustomizers.POST_DELETE_RECORD, sync);
BaseSyncToScheduledJobTableCustomizer.makeCodeReference(table, new BackupPlanVerifySyncToScheduledJobProcess()),
validation);
}
table.withCustomizer(TableCustomizers.POST_INSERT_RECORD, post);
table.withCustomizer(TableCustomizers.POST_UPDATE_RECORD, post);
table.withCustomizer(TableCustomizers.POST_DELETE_RECORD, post);
return (table);
}
@@ -22,6 +22,7 @@ import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import com.kingsrook.qbits.backups.metrics.BackupsMetrics;
import com.kingsrook.qbits.backups.model.BackupsTables;
import com.kingsrook.qbits.backups.run.BackupCatalog;
import com.kingsrook.qbits.backups.run.BackupRunFactory;
@@ -31,6 +32,9 @@ import com.kingsrook.qqq.backend.core.actions.customizers.TableCustomizerInterfa
import com.kingsrook.qqq.backend.core.context.QContext;
import com.kingsrook.qqq.backend.core.exceptions.QException;
import com.kingsrook.qqq.backend.core.model.actions.AbstractActionInput;
import com.kingsrook.qqq.backend.core.model.actions.tables.delete.DeleteInput;
import com.kingsrook.qqq.backend.core.model.actions.tables.insert.InsertInput;
import com.kingsrook.qqq.backend.core.model.actions.tables.update.UpdateInput;
import com.kingsrook.qqq.backend.core.model.data.QRecord;
import com.kingsrook.qqq.backend.core.model.session.QSession;
import com.kingsrook.qqq.backend.core.model.statusmessages.BadInputStatusMessage;
@@ -43,7 +47,8 @@ import com.kingsrook.qqq.backend.core.model.statusmessages.QWarningMessage;
** configuration (the processes write the last run and SLA fields) is not
** validated again.
**
** The saving user becomes the plan owner when none is given.
** The saving user becomes the plan owner when none is given. After an insert,
** update or delete, the cached Prometheus text is cleared on every node.
*******************************************************************************/
public class BackupPlanTableCustomizer implements TableCustomizerInterface
{
@@ -122,6 +127,42 @@ public class BackupPlanTableCustomizer implements TableCustomizerInterface
/*******************************************************************************
** A saved plan changes the metrics on every node.
*******************************************************************************/
@Override
public List<QRecord> postInsert(InsertInput insertInput, List<QRecord> records) throws QException
{
BackupsMetrics.invalidate();
return (records);
}
/*******************************************************************************
** A saved plan changes the metrics on every node.
*******************************************************************************/
@Override
public List<QRecord> postUpdate(UpdateInput updateInput, List<QRecord> records, Optional<List<QRecord>> oldRecordList) throws QException
{
BackupsMetrics.invalidate();
return (records);
}
/*******************************************************************************
** A deleted plan changes the metrics on every node.
*******************************************************************************/
@Override
public List<QRecord> postDelete(DeleteInput deleteInput, List<QRecord> records) throws QException
{
BackupsMetrics.invalidate();
return (records);
}
/*******************************************************************************
** The scope rules to resolve: the ones sent with the plan (associated rows), or
** the saved ones.
@@ -54,7 +54,7 @@ public final class BackupPlanValidator
private static final Set<String> COMPRESSIONS = Set.of("GZIP", "NONE");
private static final Set<String> LOCK_MODES = Set.of("NONE", "GOVERNANCE", "COMPLIANCE");
/** Replace with the real check when client-side encryption ships (spec 11.2). */
/** For a host that installs a cipher of its own outside the config; a configured key provider needs no switch. */
private static volatile boolean encryptionAvailable = false;
@@ -69,8 +69,9 @@ public final class BackupPlanValidator
/*******************************************************************************
** Tell the validator that client-side encryption is available (the encryption
** work calls this when it installs a cipher).
** Tell the validator that client-side encryption is available although the
** config has no key provider (a host with a cipher of its own). With a key
** provider on the config it is available, and a plan's key is checked too.
*******************************************************************************/
public static void setEncryptionAvailable(boolean available)
{
@@ -193,14 +194,21 @@ public final class BackupPlanValidator
String policy = settings.string("sensitiveFieldPolicy", "EXCLUDE");
if("CLIENT_AES256_GCM".equals(mode))
{
if(!encryptionAvailable)
var config = BackupsRuntime.getConfig();
var resolver = config == null ? null : config.getArtifactTransformResolver();
String keyRef = settings.string("encryptionKeyRef", null);
if(!encryptionAvailable && resolver == null)
{
errors.add("Client-side encryption is not available in this version. Use NONE (and keep the sensitive field policy at EXCLUDE).");
errors.add("Client-side encryption is not set up for this application: no key provider is configured. Use NONE (and keep the sensitive field policy at EXCLUDE).");
}
else if(settings.string("encryptionKeyRef", null) == null)
else if(keyRef == null)
{
errors.add("Client-side encryption needs an encryption key reference (the name of the key, never the key itself).");
}
else if(resolver != null && resolver.apply(keyRef) == null)
{
errors.add("No key is available for the encryption key reference " + keyRef + ": the key provider has no usable key of that name. Nothing could be encrypted, so the plan was not saved.");
}
}
if("INCLUDE_ENCRYPTED_ONLY".equals(policy) && !"CLIENT_AES256_GCM".equals(mode))
{
@@ -20,6 +20,7 @@ package com.kingsrook.qbits.backups.plan;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
@@ -81,6 +82,28 @@ public final class DestinationProbe
** Probe the destination of a plan.
*******************************************************************************/
public static Report probe(QRecord plan)
{
return (probe(plan, false, null));
}
/*******************************************************************************
** Health monitoring only lists and heads; it never resolves prune credentials
** or probes capabilities. The runner bounds in-flight storage calls; check the
** deadline between calls because BackupStorage has no per-call timeout API.
*******************************************************************************/
public static Report probeReadOnly(QRecord plan, Instant deadline)
{
return (probe(plan, true, deadline));
}
/*******************************************************************************
** Share storage resolution and the existing locked-bucket read path.
*******************************************************************************/
private static Report probe(QRecord plan, boolean readOnly, Instant deadline)
{
List<Check> checks = new ArrayList<>();
List<String> warnings = new ArrayList<>();
@@ -89,15 +112,23 @@ public final class DestinationProbe
BackupStorage storage;
try
{
requireTime(deadline);
storage = BackupsRuntime.storageFor(alias);
requireTime(deadline);
}
catch(RuntimeException e)
{
checks.add(new Check("Open the backup bucket " + alias, false, e.getMessage()));
return (new Report(false, checks, List.of(), warnings));
return (new Report(readOnly, checks, List.of(), warnings));
}
checks.add(new Check("Open the backup bucket " + alias, true, "found"));
if(readOnly)
{
headOnly(plan, storage, BackupPruner.planPrefix(plan), checks, deadline);
return (new Report(true, checks, List.of(), warnings));
}
BackupStorage deleteSide = storage;
String pruneAlias = plan.getValueString("pruneBucketAlias");
if(pruneAlias == null || pruneAlias.isBlank())
@@ -133,7 +164,7 @@ public final class DestinationProbe
String prefix = BackupPruner.planPrefix(plan);
if(locked)
{
headOnly(plan, storage, prefix, checks);
headOnly(plan, storage, prefix, checks, null);
}
else
{
@@ -147,10 +178,11 @@ public final class DestinationProbe
/*******************************************************************************
** The probe for a locked bucket: list the prefix, and head the newest manifest.
*******************************************************************************/
private static void headOnly(QRecord plan, BackupStorage storage, String prefix, List<Check> checks)
private static void headOnly(QRecord plan, BackupStorage storage, String prefix, List<Check> checks, Instant deadline)
{
checks.add(attempt("Write and delete a probe object", () -> "skipped: object lock is on, a probe object could not be deleted again"));
checks.add(attempt("List the plan prefix", () ->
checks.add(new Check("Write and delete a probe object", true,
deadline == null ? "skipped: object lock is on, a probe object could not be deleted again" : "skipped: read-only probe"));
checks.add(attempt("List the plan prefix", deadline, () ->
{
List<StoredObjectInfo> objects = storage.list(prefix);
return (objects.size() + " objects under " + prefix);
@@ -162,10 +194,11 @@ public final class DestinationProbe
checks.add(new Check("Head the newest manifest", true, "there is no successful run yet"));
return;
}
checks.add(attempt("Head the newest manifest", () ->
checks.add(attempt("Head the newest manifest", deadline, () ->
{
QRecord run = new com.kingsrook.qbits.backups.run.BackupCatalog().get(com.kingsrook.qbits.backups.model.BackupsTables.RUN, lastSuccess).orElseThrow();
String key = run.getValueString("manifestKey");
requireTime(deadline);
if(key == null || storage.head(key).isEmpty())
{
throw (new IllegalStateException("the manifest of the newest successful run is not in the bucket"));
@@ -238,6 +271,9 @@ public final class DestinationProbe
@FunctionalInterface
private interface Attempt
{
/*******************************************************************************
** Execute one diagnostic operation.
*******************************************************************************/
String run() throws Exception;
}
@@ -247,14 +283,40 @@ public final class DestinationProbe
**
*******************************************************************************/
private static Check attempt(String name, Attempt attempt)
{
return (attempt(name, null, attempt));
}
/*******************************************************************************
** Never begin another storage operation after the health budget expires.
*******************************************************************************/
private static Check attempt(String name, Instant deadline, Attempt attempt)
{
try
{
return (new Check(name, true, attempt.run()));
requireTime(deadline);
String detail = attempt.run();
requireTime(deadline);
return (new Check(name, true, detail));
}
catch(Exception e)
{
return (new Check(name, false, e.getMessage() == null ? e.getClass().getSimpleName() : e.getMessage()));
}
}
/*******************************************************************************
** Existing on-demand diagnostics have no deadline; health probes always do.
*******************************************************************************/
private static void requireTime(Instant deadline)
{
if(deadline != null && (Thread.currentThread().isInterrupted() || !Instant.now().isBefore(deadline)))
{
throw (new IllegalStateException("Destination probe timed out"));
}
}
}
@@ -22,6 +22,8 @@ import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import com.kingsrook.qbits.backups.BackupsRuntime;
import com.kingsrook.qbits.backups.model.BackupsTables;
import com.kingsrook.qbits.backups.permissions.BackupsPermissions;
@@ -178,6 +180,10 @@ public final class BackupsProcesses
private final ProcessSummaryLine tables = line(Status.INFO, "table will be backed up", "tables will be backed up", "table was backed up", "tables were backed up");
private final ProcessSummaryLine excluded = line(Status.INFO, "table is left out by its role or scope", "tables are left out by their role or scope",
"table was left out by its role or scope", "tables were left out by their role or scope");
private final ProcessSummaryLine unreadable = line(Status.INFO, "table is left out because its backend cannot be queried (storage only)",
"tables are left out because their backend cannot be queried (storage only)", "table was left out because its backend cannot be queried (storage only)",
"tables were left out because their backend cannot be queried (storage only)");
private final Set<String> unreadableNames = new TreeSet<>();
private final ProcessSummaryLine inactive = line(Status.WARNING, "plan is not active (it can still be run by hand)", "plans are not active (they can still be run by hand)",
"plan was not active", "plans were not active");
private final ProcessSummaryLine invalid = line(Status.ERROR, "plan cannot run", "plans cannot run", "plan could not run", "plans could not run");
@@ -205,6 +211,14 @@ public final class BackupsProcesses
plans.incrementCountAndAddPrimaryKey(plan.getValue("id"));
tables.incrementCount(scope.tables().size());
excluded.incrementCount(scope.excluded().size());
for(ScopeResolver.ExcludedTable out : scope.excluded())
{
if(ScopeResolver.NOT_QUERYABLE.equals(out.reason()) && unreadableNames.add(out.name()))
{
unreadable.incrementCount();
unreadable.setMessageSuffix(": " + String.join(", ", unreadableNames));
}
}
if(!Boolean.TRUE.equals(plan.getValueBoolean("isActive")))
{
inactive.incrementCountAndAddPrimaryKey(plan.getValue("id"));
@@ -235,6 +249,7 @@ public final class BackupsProcesses
plans.addSelfToListIfAnyCount(lines);
tables.addSelfToListIfAnyCount(lines);
excluded.addSelfToListIfAnyCount(lines);
unreadable.addSelfToListIfAnyCount(lines);
inactive.addSelfToListIfAnyCount(lines);
invalid.addSelfToListIfAnyCount(lines);
return (lines);
@@ -118,7 +118,7 @@ public final class ExportTableProcess
continue;
}
TableRole role = TableRoles.roleOf(qInstance, table);
if(role == TableRole.DATA || role == TableRole.AUDIT || role == TableRole.DERIVED)
if((role == TableRole.DATA || role == TableRole.AUDIT || role == TableRole.DERIVED) && TableRoles.isQueryable(qInstance, table))
{
processes.add(processFor(table.getName()));
}
@@ -60,6 +60,8 @@ public final class LifecycleProcesses
processes.addAll(PruneProcess.processes());
BackupsQBitConfig config = BackupsRuntime.getConfig();
processes.add(com.kingsrook.qbits.backups.schedule.BackupScheduledPruneProcess.processMetaData(config));
processes.add(com.kingsrook.qbits.backups.schedule.BackupDuePlansProcess.processMetaData(config));
if(config != null && StringUtils.hasContent(config.getSchedulerName()))
{
try
@@ -22,8 +22,6 @@ import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import com.kingsrook.qbits.backups.BackupsQBitConfig;
import com.kingsrook.qbits.backups.BackupsRuntime;
import com.kingsrook.qbits.backups.model.BackupsTables;
import com.kingsrook.qbits.backups.permissions.BackupsPermissions;
import com.kingsrook.qbits.backups.prune.BackupPruner;
@@ -37,7 +35,6 @@ import com.kingsrook.qqq.backend.core.model.actions.processes.RunBackendStepOutp
import com.kingsrook.qqq.backend.core.model.actions.processes.Status;
import com.kingsrook.qqq.backend.core.model.data.QRecord;
import com.kingsrook.qqq.backend.core.model.metadata.processes.QProcessMetaData;
import com.kingsrook.qqq.backend.core.model.metadata.scheduleing.QScheduleMetaData;
import com.kingsrook.qqq.backend.core.processes.implementations.etl.streamedwithfrontend.AbstractLoadStep;
import com.kingsrook.qqq.backend.core.processes.implementations.etl.streamedwithfrontend.AbstractTransformStep;
import com.kingsrook.qqq.backend.core.processes.implementations.etl.streamedwithfrontend.ProcessSummaryProviderInterface;
@@ -46,8 +43,9 @@ import static com.kingsrook.qbits.backups.processes.BackupsProcesses.line;
/*******************************************************************************
** Prune per retention (spec 9, 10.3). A record action on backups_plan, and a
** table action on backups_run (which prunes the plans of the selected runs); the
** plan one also runs daily when the qbit has a scheduler.
** table action on backups_run (which prunes the plans of the selected runs).
** Both are for a person: they show what will be deleted and wait. The daily
** prune of every active plan is BackupScheduledPruneProcess.
**
** Review shows exactly what Result will do: the runs to delete, the runs kept by
** class, the runs kept because an object is still locked (with the date), the
@@ -80,12 +78,6 @@ public final class PruneProcess
QProcessMetaData onPlans = BackupsProcesses.permission(BackupsProcesses.etl(NAME, "Prune per retention", BackupsTables.PLAN, PlanTransform.class, Load.class,
"This is a preview of what Prune will delete. Nothing is deleted until you continue."), BackupsPermissions.ADMIN);
BackupsQBitConfig config = BackupsRuntime.getConfig();
if(config != null && config.getSchedulerName() != null && !config.getSchedulerName().isBlank())
{
onPlans.withSchedule(new QScheduleMetaData().withSchedulerName(config.getSchedulerName()).withRepeatSeconds(24 * 3600).withInitialDelaySeconds(3600));
}
QProcessMetaData onRuns = BackupsProcesses.permission(BackupsProcesses.etl(NAME_RUNS, "Prune per retention", BackupsTables.RUN, RunTransform.class, Load.class,
"This is a preview of what Prune will delete for the plans of the selected runs. Nothing is deleted until you continue."), BackupsPermissions.ADMIN);
return (List.of(onPlans, onRuns));
@@ -425,6 +425,44 @@ public class BackupPruner
/*******************************************************************************
** Prefixes of the plan that never got a manifest and are old enough.
*******************************************************************************/
/*******************************************************************************
** When the newest object of an unfinished backup was written. A storage may
** list objects without their times: then the run's own record dates them (its
** end, else its start), and where there is no run record either the prefix is
** taken as written now, so nothing that cannot be dated is deleted as old.
*******************************************************************************/
static Instant newestOf(List<StoredObjectInfo> objects, QRecord run, Instant now)
{
Instant newest = null;
boolean undated = false;
for(StoredObjectInfo object : objects)
{
if(object.lastModified() == null)
{
undated = true;
}
else if(newest == null || object.lastModified().isAfter(newest))
{
newest = object.lastModified();
}
}
if(!undated && newest != null)
{
return (newest);
}
Instant recorded = run == null ? null : run.getValueInstant("endDate") != null ? run.getValueInstant("endDate") : run.getValueInstant("startDate");
if(recorded == null)
{
return (now);
}
return (newest != null && newest.isAfter(recorded) ? newest : recorded);
}
/*******************************************************************************
** The prefixes of backups that never finished and are old enough to delete.
*******************************************************************************/
private List<DebrisPlan> debris(QRecord plan, List<QRecord> allRuns, BackupStorage deleteSide, Instant now) throws QException
{
String prefix = planPrefix(plan);
@@ -461,7 +499,7 @@ public class BackupPruner
{
continue;
}
Instant newest = objects.stream().map(StoredObjectInfo::lastModified).max(Comparator.naturalOrder()).orElse(now);
Instant newest = newestOf(objects, run, now);
if(newest.isAfter(now.minus(Duration.ofDays(PruneCalculator.DEBRIS_DAYS))))
{
continue;
@@ -153,6 +153,14 @@ public final class BackupSource
}
Function<BackupManifest.EncryptionInfo, ArtifactTransform> resolver = transformResolver;
ArtifactTransform resolved = resolver == null ? null : resolver.apply(encryption);
if(resolver == null && BackupsRuntime.getConfig() != null && BackupsRuntime.getConfig().getArtifactTransformResolver() != null)
{
///////////////////////////////////////////////////////////////////////////
// the configured key provider reads what it wrote; a resolver set here //
// (by a host with a cipher of its own) takes its place //
///////////////////////////////////////////////////////////////////////////
resolved = BackupsRuntime.getConfig().getArtifactTransformResolver().apply(encryption.keyRef());
}
if(resolved == null)
{
throw (new QException("This backup is encrypted (key " + encryption.keyRef() + "), and no key provider is available to restore it"));
@@ -41,12 +41,15 @@ import com.kingsrook.qbits.backups.BackupsRuntime;
import com.kingsrook.qbits.backups.alerts.BackupAlertSink;
import com.kingsrook.qbits.backups.codec.HashingOutputStream;
import com.kingsrook.qbits.backups.codec.TableArtifactWriter;
import com.kingsrook.qbits.backups.codec.ArtifactTransform;
import com.kingsrook.qbits.backups.codec.StreamingCipherTransform;
import com.kingsrook.qbits.backups.events.BackupEvents;
import com.kingsrook.qbits.backups.files.FileCopier;
import com.kingsrook.qbits.backups.files.FileReference;
import com.kingsrook.qbits.backups.files.FileReferenceProvider;
import com.kingsrook.qbits.backups.manifest.BackupManifest;
import com.kingsrook.qbits.backups.manifest.TableFingerprints;
import com.kingsrook.qbits.backups.metrics.BackupsMetrics;
import com.kingsrook.qbits.backups.model.BackupsTables;
import com.kingsrook.qbits.backups.scope.ScopeResolver;
import com.kingsrook.qbits.backups.storage.BackupStorage;
@@ -76,7 +79,7 @@ import static com.kingsrook.qqq.backend.core.logging.LogUtils.logPair;
** content-addressed store; checksums.sha256 is written; and the manifest is
** written LAST, then checked with a head. A run with no manifest did not
** complete. The run row is updated every page (heartbeat), and a failure marks
** the run FAILED with a scrubbed message (never row values).
** the run FAILED with a sanitized message and detail (no secrets, no row values).
*******************************************************************************/
public class BackupEngine
{
@@ -141,6 +144,7 @@ public class BackupEngine
runValues.remove("startDate");
runValues.put("endDate", null);
runValues.put("errorMessage", null);
runValues.put("errorDetail", null);
}
if(request.getExistingRunId() != null)
{
@@ -154,9 +158,12 @@ public class BackupEngine
}
catch(Exception e)
{
LOG.warn("Could not create the backup run record", e, logPair("runKey", runKey));
String message = FailureText.summary("Could not create the run record", e);
result.setStatus("FAILED");
result.setErrorMessage("Could not create the run record (" + e.getClass().getSimpleName() + ")");
failProgress(progress, "Could not create the run record (" + e.getClass().getSimpleName() + ")");
result.setErrorMessage(message);
result.setErrorDetail(FailureText.detail(e));
failProgress(progress, message);
return (result);
}
@@ -173,12 +180,12 @@ public class BackupEngine
}
catch(CancelledException e)
{
finish(request, result, "CANCELLED", "Cancelled", started);
finish(request, result, "CANCELLED", "Cancelled", null, started);
progress.info("Backup cancelled");
}
catch(TimedOutException e)
{
finish(request, result, "TIMED_OUT", e.getMessage(), started);
finish(request, result, "TIMED_OUT", e.getMessage(), null, started);
failProgress(progress, e.getMessage());
}
catch(Exception e)
@@ -188,14 +195,14 @@ public class BackupEngine
{
if(interrupted.getReason() != JobInterruptedException.Reason.LEASE_LOST)
{
finish(request, result, interrupted.getReason() == JobInterruptedException.Reason.CANCEL ? "CANCELLED" : "ABANDONED", "Job interrupted", started);
finish(request, result, interrupted.getReason() == JobInterruptedException.Reason.CANCEL ? "CANCELLED" : "ABANDONED", "Job interrupted", null, started);
}
throw (interrupted);
}
LOG.warn("Backup run failed", e, logPair("runKey", runKey));
// Provider and reader messages can contain credentials or row values.
failProgress(progress, scrub(e));
finish(request, result, "FAILED", scrub(e), started);
String message = scrub(e);
failProgress(progress, message);
finish(request, result, "FAILED", message, FailureText.detail(e), started);
}
finally
{
@@ -449,7 +456,7 @@ public class BackupEngine
checkJob();
if(indexWriter == null)
{
indexWriter = new FileIndexWriter(storage, runPrefix + "files/index-00001.jsonl.gz", result.getRunKey(), fileLockMode, fileRetainUntil);
indexWriter = new FileIndexWriter(storage, runPrefix + "files/index-00001.jsonl.gz", result.getRunKey(), fileLockMode, fileRetainUntil, request.getTransform());
}
FileCopier.IndexEntry entry = copier.process(ref);
indexWriter.write(entry);
@@ -525,7 +532,7 @@ public class BackupEngine
started.toString(), finished.toString(), request.getRequestedBy(), request.getSecurityScope(),
new BackupManifest.ConsistencyInfo(result.getConsistencyAchieved(), List.of()),
request.getTransform().encrypts()
? new BackupManifest.EncryptionInfo("CLIENT_AES256_GCM", "tink-streaming-aead-AES256_GCM_HKDF_1MB", request.getEncryptionKeyRef(), request.getEncryptionKeyFingerprint())
? new BackupManifest.EncryptionInfo("CLIENT_AES256_GCM", StreamingCipherTransform.SCHEME, request.getEncryptionKeyRef(), request.getEncryptionKeyFingerprint())
: new BackupManifest.EncryptionInfo("NONE", null, null, null),
manifestTables, order,
new BackupManifest.FilesInfo(settings.fileObjectPolicy(), indexKeys, copied + deduplicated, fileBytes + fileBytesRef, missing),
@@ -572,7 +579,7 @@ public class BackupEngine
extra.put("bytesRaw", bytesRaw);
extra.put("bytesStored", bytesStored);
extra.put("warningCount", result.getWarnings().size());
finishWith(request, result, result.getWarnings().isEmpty() ? "SUCCEEDED" : "SUCCEEDED_WITH_WARNINGS", null, started, extra);
finishWith(request, result, result.getWarnings().isEmpty() ? "SUCCEEDED" : "SUCCEEDED_WITH_WARNINGS", null, null, started, extra);
}
@@ -740,11 +747,11 @@ public class BackupEngine
/*******************************************************************************
**
*******************************************************************************/
private void finish(BackupRunRequest request, BackupRunResult result, String status, String message, Instant started)
private void finish(BackupRunRequest request, BackupRunResult result, String status, String message, String detail, Instant started)
{
try
{
finishWith(request, result, status, message, started, new LinkedHashMap<>());
finishWith(request, result, status, message, detail, started, new LinkedHashMap<>());
}
catch(Exception e)
{
@@ -752,6 +759,7 @@ public class BackupEngine
request.getProgress().warn("Could not finish the run record");
result.setStatus(status);
result.setErrorMessage(message);
result.setErrorDetail(detail);
}
}
@@ -760,7 +768,7 @@ public class BackupEngine
/*******************************************************************************
**
*******************************************************************************/
private void finishWith(BackupRunRequest request, BackupRunResult result, String status, String message, Instant started, Map<String, Serializable> extra) throws Exception
private void finishWith(BackupRunRequest request, BackupRunResult result, String status, String message, String detail, Instant started, Map<String, Serializable> extra) throws Exception
{
Instant end = request.getClock().instant();
Map<String, Serializable> v = new LinkedHashMap<>(extra);
@@ -769,11 +777,14 @@ public class BackupEngine
v.put("durationMs", end.toEpochMilli() - started.toEpochMilli());
v.put("heartbeatDate", end);
v.put("errorMessage", message);
v.put("errorDetail", detail);
v.put("warningCount", result.getWarnings().size());
catalog.update(BackupsTables.RUN, result.getRunId(), v);
result.setStatus(status);
result.setErrorMessage(message);
result.setErrorDetail(detail);
signal(request, result, status, message);
BackupsMetrics.invalidate();
}
@@ -826,12 +837,17 @@ public class BackupEngine
/*******************************************************************************
** Provider exceptions may contain credentials or row values. Persist only the
** failure type; detailed diagnostics stay in the server log.
** The error_message of a failed run: "Backup failed: SimpleClass: message".
** Provider, driver and reader messages can contain credentials or row values,
** so the message goes through FailureText.sanitize (URL user-info, presigned
** query parameters, key=value secrets, Authorization values, AWS key ids, PEM
** blocks and Postgres row-value fragments are redacted; object keys and bucket
** names are kept). The class, the cause chain and the root cause frames go to
** error_detail (FailureText.detail); the full trace stays in the server log.
*******************************************************************************/
private static String scrub(Exception e)
{
return ("Backup failed (" + e.getClass().getSimpleName() + "); see server logs for details.");
return (FailureText.summary(e));
}
@@ -1071,9 +1087,11 @@ public class BackupEngine
/*******************************************************************************
** Constructor.
** Constructor. The index names tables, record keys and where each file came
** from, so in an encrypted run it is encrypted like the rows are: compressed,
** then through the run's transform, then stored.
*******************************************************************************/
FileIndexWriter(BackupStorage storage, String key, String runKey, String lockMode, Instant retainUntil) throws IOException
FileIndexWriter(BackupStorage storage, String key, String runKey, String lockMode, Instant retainUntil, ArtifactTransform transform) throws IOException
{
WriteOptions options = WriteOptions.create().withMetadata("qqq-backup-run", runKey);
if(lockMode != null)
@@ -1081,7 +1099,7 @@ public class BackupEngine
options.withObjectLock(lockMode, retainUntil);
}
stored = new HashingOutputStream(storage.openWrite(key, options));
raw = new HashingOutputStream(new GZIPOutputStream(stored));
raw = new HashingOutputStream(new GZIPOutputStream((transform == null ? ArtifactTransform.IDENTITY : transform).wrap(stored)));
}
@@ -448,7 +448,8 @@ public class BackupRunCoordinator
String mode = plan.getValueString("encryptionMode");
if(mode != null && !"NONE".equals(mode) && !request.getTransform().encrypts())
{
return ("The plan asks for " + mode + " encryption, but no cipher is available in this version. Nothing was written.");
return ("The plan asks for " + mode + " encryption, but no key is available for its encryption key reference"
+ (plan.getValueString("encryptionKeyRef") == null ? "" : " " + plan.getValueString("encryptionKeyRef")) + " (no key provider is configured, or it has no key of that name). Nothing was written.");
}
return (null);
}
@@ -21,6 +21,7 @@ import java.util.ArrayList;
import java.util.List;
import com.kingsrook.qbits.backups.BackupsQBitConfig;
import com.kingsrook.qbits.backups.BackupsRuntime;
import com.kingsrook.qbits.backups.codec.ArtifactTransform;
import com.kingsrook.qbits.backups.model.BackupsTables;
import com.kingsrook.qbits.backups.scope.PlanSettings;
import com.kingsrook.qbits.backups.scope.ScopeResolver;
@@ -82,7 +83,7 @@ public final class BackupRunFactory
QSession session = QContext.getQSession();
String user = session == null || session.getUser() == null ? "system:scheduler" : session.getUser().getIdReference();
return (new BackupRunRequest()
BackupRunRequest request = new BackupRunRequest()
.withSettings(settings)
.withScope(resolveScope(plan))
.withTrigger(trigger)
@@ -93,6 +94,23 @@ public final class BackupRunFactory
.withSourceResolver(BackupsRuntime::storageFor)
.withInstanceName(config.getInstanceName() != null ? config.getInstanceName() : "qqq")
.withPlanName(plan.getValueString("name"))
.withClock(BackupsRuntime.getClock()));
.withClock(BackupsRuntime.getClock());
////////////////////////////////////////////////////////////////////////////////
// a plan that asks for client-side encryption gets the cipher for its key //
// reference. When there is none (no key provider, or no key of that name), //
// the request stays without one and the coordinator refuses the run: nothing //
// is ever written in the clear for a plan that asked for encryption //
////////////////////////////////////////////////////////////////////////////////
String keyRef = settings.string("encryptionKeyRef", null);
if("CLIENT_AES256_GCM".equals(settings.string("encryptionMode", "NONE")) && keyRef != null && config.getArtifactTransformResolver() != null)
{
ArtifactTransform transform = config.getArtifactTransformResolver().apply(keyRef);
if(transform != null && transform.encrypts())
{
request.withTransform(transform, keyRef, transform.keyFingerprint());
}
}
return (request);
}
}
@@ -43,6 +43,7 @@ public class BackupRunResult
private int filesMissing;
private long fileBytesCopied;
private String errorMessage;
private String errorDetail;
private List<String> warnings = new ArrayList<>();
@@ -397,6 +398,26 @@ public class BackupRunResult
/*******************************************************************************
** Getter for errorDetail (sanitized class, message, cause chain and root frames)
*******************************************************************************/
public String getErrorDetail()
{
return (errorDetail);
}
/*******************************************************************************
** Setter for errorDetail
*******************************************************************************/
public void setErrorDetail(String errorDetail)
{
this.errorDetail = errorDetail;
}
/*******************************************************************************
** Getter for warnings
*******************************************************************************/
@@ -0,0 +1,184 @@
/*
* Copyright 2026 Kingsrook, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.backups.run;
import java.util.Collections;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/*******************************************************************************
** Safe text for a failure: what is persisted on a run row (error_message and
** error_detail) and shown in job output.
**
** Exception messages from storage providers, drivers and readers can carry
** credentials (URL user-info, presigned query strings, key=value secrets,
** Authorization headers, AWS access key ids, PEM blocks) and row values (the
** Postgres "Key (col)=(value)" and "Detail:" fragments). sanitize() redacts
** those and keeps the rest (class names, object keys, bucket names), which is
** what an operator needs to act on a failure without reading the server log.
*******************************************************************************/
public final class FailureText
{
/** Redaction marker. */
public static final String REDACTED = "[REDACTED]";
/** The longest error_detail written. */
public static final int MAX_DETAIL_CHARS = 8192;
/** The longest exception message kept in error_message. */
public static final int MAX_SUMMARY_MESSAGE_CHARS = 500;
/** Stack frames of the root cause kept in error_detail. */
public static final int ROOT_CAUSE_FRAMES = 8;
private static final int MAX_CAUSES = 20;
private static final String SECRET_NAME = "[\\w.-]*(?:password|passwd|pwd|secret|token|credential|signature|api[_-]?key|access[_-]?key|private[_-]?key)[\\w.-]*";
private static final Pattern PEM_BLOCK = Pattern.compile("-----BEGIN [A-Z0-9 ]+-----.*?(?:-----END [A-Z0-9 ]+-----|$)", Pattern.DOTALL);
private static final Pattern URL_USERINFO = Pattern.compile("(?i)\\b([a-z][a-z0-9+.-]*://)[^/\\s@?#]+@");
private static final Pattern QUERY_PARAM = Pattern.compile("(?i)([?&;](?:X-Amz-[\\w-]+|Signature|Credential|AWSAccessKeyId|Policy|sig|key|" + SECRET_NAME + ")=)[^&\\s\"'<>]*");
private static final Pattern PG_KEY_VALUE = Pattern.compile("(?i)\\b(Key \\([^)]*\\)=\\().*?(\\))(?=\\s|$|[.,;:])");
private static final Pattern PG_DETAIL = Pattern.compile("(?i)\\b(Detail:|Failing row contains)[^\\r\\n]*");
private static final Pattern AUTHORIZATION = Pattern.compile("(?i)\\b((?:Proxy-)?Authorization\"?\\s*[:=]\\s*)(\"[^\"]*\"|[^\\r\\n,;]+)");
private static final Pattern BEARER = Pattern.compile("(?i)\\b(Bearer|Basic)\\s+[A-Za-z0-9._~+/=-]{6,}");
private static final Pattern SECRET_JSON = Pattern.compile("(?i)(\"" + SECRET_NAME + "\"\\s*:\\s*)\"[^\"]*\"");
private static final Pattern SECRET_ASSIGN = Pattern.compile("(?i)(?<![\\w.-])((?:" + SECRET_NAME + "|key)\\s*=\\s*)(?!\\[REDACTED)(\"[^\"]*\"|'[^']*'|[^\\s&,;)\\]}]+)");
private static final Pattern AWS_KEY_ID = Pattern.compile("\\b(?:AKIA|ASIA|AGPA|AIDA|AROA|ANPA|ANVA|AIPA)[A-Z0-9]{16}\\b");
private static final String R = Matcher.quoteReplacement(REDACTED);
/*******************************************************************************
** Utility class.
*******************************************************************************/
private FailureText()
{
}
/*******************************************************************************
** Redact secrets and row values from a message. Null stays null.
*******************************************************************************/
public static String sanitize(String text)
{
if(text == null)
{
return (null);
}
String s = PEM_BLOCK.matcher(text).replaceAll(Matcher.quoteReplacement("[REDACTED PEM]"));
s = URL_USERINFO.matcher(s).replaceAll("$1" + R + "@");
s = QUERY_PARAM.matcher(s).replaceAll("$1" + R);
s = PG_KEY_VALUE.matcher(s).replaceAll("$1" + R + "$2");
s = PG_DETAIL.matcher(s).replaceAll("$1 " + R);
s = AUTHORIZATION.matcher(s).replaceAll("$1" + R);
s = BEARER.matcher(s).replaceAll("$1 " + R);
s = SECRET_JSON.matcher(s).replaceAll("$1\"" + R + "\"");
s = SECRET_ASSIGN.matcher(s).replaceAll("$1" + R);
s = AWS_KEY_ID.matcher(s).replaceAll(R);
return (s);
}
/*******************************************************************************
** The short error_message: "Backup failed: SimpleClass: sanitized message".
*******************************************************************************/
public static String summary(Throwable t)
{
return (summary("Backup failed", t));
}
/*******************************************************************************
** A short message: "prefix: SimpleClass: sanitized message" (bounded).
*******************************************************************************/
public static String summary(String prefix, Throwable t)
{
String message = sanitize(t.getMessage());
if(message == null || message.isBlank())
{
return (prefix + ": " + t.getClass().getSimpleName());
}
message = message.strip();
if(message.length() > MAX_SUMMARY_MESSAGE_CHARS)
{
message = message.substring(0, MAX_SUMMARY_MESSAGE_CHARS) + "...";
}
return (prefix + ": " + t.getClass().getSimpleName() + ": " + message);
}
/*******************************************************************************
** The error_detail: the exception class and sanitized message, each cause
** ("Caused by: ..."), then the top stack frames of the root cause, bounded to
** MAX_DETAIL_CHARS. Frames are class, method, file and line only (no values).
*******************************************************************************/
public static String detail(Throwable t)
{
StringBuilder out = new StringBuilder(line(t));
Set<Throwable> seen = Collections.newSetFromMap(new IdentityHashMap<>());
seen.add(t);
Throwable root = t;
Throwable cause = t.getCause();
while(cause != null && seen.size() < MAX_CAUSES && seen.add(cause))
{
out.append("\nCaused by: ").append(line(cause));
root = cause;
cause = cause.getCause();
}
List<StackTraceElement> frames = List.of(root.getStackTrace());
int shown = Math.min(ROOT_CAUSE_FRAMES, frames.size());
if(shown > 0)
{
out.append("\nRoot cause stack (top ").append(shown).append(" of ").append(frames.size()).append(" frames):");
for(StackTraceElement frame : frames.subList(0, shown))
{
out.append("\n\tat ").append(frame);
}
}
if(out.length() > MAX_DETAIL_CHARS)
{
String marker = "\n... (truncated)";
out.setLength(MAX_DETAIL_CHARS - marker.length());
out.append(marker);
}
return (out.toString());
}
/*******************************************************************************
** "fully.qualified.Class: sanitized message".
*******************************************************************************/
private static String line(Throwable t)
{
String message = sanitize(t.getMessage());
return (message == null ? t.getClass().getName() : t.getClass().getName() + ": " + message);
}
}
@@ -0,0 +1,198 @@
/*
* Copyright 2026 Kingsrook, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.backups.schedule;
import java.text.ParseException;
import java.time.Instant;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;
import com.kingsrook.qbits.backups.BackupsQBitConfig;
import com.kingsrook.qbits.backups.BackupsRuntime;
import com.kingsrook.qbits.backups.model.BackupsTables;
import com.kingsrook.qbits.backups.permissions.BackupsPermissions;
import com.kingsrook.qbits.backups.processes.BackupsProcesses;
import com.kingsrook.qbits.backups.run.BackupCatalog;
import com.kingsrook.qqq.backend.core.actions.processes.BackendStep;
import com.kingsrook.qqq.backend.core.context.QContext;
import com.kingsrook.qqq.backend.core.exceptions.QException;
import com.kingsrook.qqq.backend.core.exceptions.QPermissionDeniedException;
import com.kingsrook.qqq.backend.core.logging.QLogger;
import com.kingsrook.qqq.backend.core.model.actions.processes.RunBackendStepInput;
import com.kingsrook.qqq.backend.core.model.actions.processes.RunBackendStepOutput;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QCriteriaOperator;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QFilterCriteria;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QFilterOrderBy;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QQueryFilter;
import com.kingsrook.qqq.backend.core.model.data.QRecord;
import com.kingsrook.qqq.backend.core.model.metadata.code.QCodeReference;
import com.kingsrook.qqq.backend.core.model.metadata.processes.QBackendStepMetaData;
import com.kingsrook.qqq.backend.core.model.metadata.processes.QProcessMetaData;
import com.kingsrook.qqq.backend.core.model.metadata.scheduleing.QScheduleMetaData;
import com.kingsrook.qqq.backend.core.model.scheduledjobs.ScheduledJob;
import com.kingsrook.qqq.backend.core.model.session.QSystemUserSession;
import com.kingsrook.qqq.backend.core.utils.StringUtils;
import org.quartz.CronExpression;
import static com.kingsrook.qqq.backend.core.logging.LogUtils.logPair;
/*******************************************************************************
** Runs the backups and the verifications that are due, in an application that
** has no scheduled-jobs table.
**
** A plan's schedule is its own cron fields. Where the application has QQQ's
** scheduled-jobs table, each plan is kept in sync with a scheduled job of its
** own (BackupPlanSyncToScheduledJobProcess), which is what starts it. Where it
** has none, that sync quietly did nothing and no plan ever ran on its schedule
** unless the host built a scheduler of its own. This process is that scheduler,
** on the qbit's own: once a minute it starts every active plan whose cron has
** come due since the plan last started (or was created), and every
** verification that has come due since the plan was last verified.
**
** Times that were missed (the application was down) collapse into one run. A
** run that fails counts as a start, so an outage is not followed by a retry
** every minute. The run itself is BackupScheduledRunProcess: the owner check,
** the one-run-per-plan lease, the alerts and the SLA are its, unchanged.
**
** Only the scheduler may run it: it starts work with a full view of the
** application, which no request from a browser may ask for.
*******************************************************************************/
public class BackupDuePlansProcess implements BackendStep
{
private static final QLogger LOG = QLogger.getLogger(BackupDuePlansProcess.class);
public static final String NAME = "backupRunDuePlans";
private static final int EVERY_SECONDS = 60;
/*******************************************************************************
** The process metadata: not in the nav; on the qbit's scheduler once a minute
** when it has one.
*******************************************************************************/
public static QProcessMetaData processMetaData(BackupsQBitConfig config)
{
QProcessMetaData process = new QProcessMetaData()
.withName(NAME)
.withLabel("Run due backup plans")
.withIsHidden(true)
.withStep(new QBackendStepMetaData().withName("tick").withCode(new QCodeReference(BackupDuePlansProcess.class)));
process.setPermissionRules(BackupsTables.permissionRules());
if(config != null && StringUtils.hasContent(config.getSchedulerName()))
{
process.setSchedule(new QScheduleMetaData()
.withSchedulerName(config.getSchedulerName())
.withRepeatSeconds(EVERY_SECONDS)
.withInitialDelaySeconds(EVERY_SECONDS)
.withDescription("Start the backups and verifications whose plan schedule has come due"));
}
return (BackupsProcesses.permission(process, BackupsPermissions.ADMIN));
}
/*******************************************************************************
** Start what is due.
*******************************************************************************/
@Override
public void run(RunBackendStepInput input, RunBackendStepOutput output) throws QException
{
if(!(QContext.getQSession() instanceof QSystemUserSession))
{
throw (new QPermissionDeniedException("Backup plans are started by the scheduler."));
}
if(QContext.getQInstance().getTable(ScheduledJob.TABLE_NAME) != null)
{
///////////////////////////////////////////////////////////////////////////
// the application's scheduled jobs start the plans: starting them here //
// too would run every backup twice //
///////////////////////////////////////////////////////////////////////////
output.addValue("startedBy", "scheduledJobs");
return;
}
BackupCatalog catalog = new BackupCatalog();
Instant now = BackupsRuntime.getClock().instant();
int backups = 0;
int verifies = 0;
for(QRecord plan : catalog.where(BackupsTables.PLAN, "isActive", true))
{
try
{
if(isDue(plan.getValueString("cronExpression"), plan.getValueString("cronTimeZoneId"), lastStart(catalog, plan), now))
{
new BackupScheduledRunProcess().run(new RunBackendStepInput().withRecords(List.of(plan)), new RunBackendStepOutput());
backups++;
}
Instant verified = plan.getValueInstant("lastVerifiedDate");
if(isDue(plan.getValueString("verifyCronExpression"), plan.getValueString("cronTimeZoneId"), verified == null ? plan.getValueInstant("createDate") : verified, now)
&& BackupScheduledRunProcess.ownerProblem(plan) == null)
{
new BackupScheduledVerifyProcess().run(new RunBackendStepInput().withRecords(List.of(plan)), new RunBackendStepOutput());
verifies++;
}
}
catch(QException | ParseException | RuntimeException e)
{
///////////////////////////////////////////////////////////////////////////
// the run and the verification record their own failure, with detail, //
// and alert. One plan's trouble must not keep the others from starting //
///////////////////////////////////////////////////////////////////////////
LOG.warn("A scheduled backup plan could not complete", logPair("plan", plan.getValueString("planKey")), logPair("failure", e.getClass().getSimpleName()));
}
}
output.addValue("startedBy", "plans");
output.addValue("backupsStarted", backups);
output.addValue("verificationsStarted", verifies);
}
/*******************************************************************************
** When the plan last started a run, successful or not; for a plan that has
** never run, when it was created.
*******************************************************************************/
private static Instant lastStart(BackupCatalog catalog, QRecord plan) throws QException
{
List<QRecord> runs = catalog.query(BackupsTables.RUN, new QQueryFilter()
.withCriteria(new QFilterCriteria("backupPlanId", QCriteriaOperator.EQUALS, plan.getValueInteger("id")))
.withOrderBy(new QFilterOrderBy("id", false)).withLimit(1));
Instant start = runs.isEmpty() ? null : runs.get(0).getValueInstant("startDate");
return (start == null ? plan.getValueInstant("createDate") : start);
}
/*******************************************************************************
** Whether the cron has a time after "since" that is not after "now". A zone
** that is not a zone fails; it does not quietly become GMT.
*******************************************************************************/
static boolean isDue(String cron, String zone, Instant since, Instant now) throws ParseException
{
if(!StringUtils.hasContent(cron) || since == null)
{
return (false);
}
CronExpression expression = new CronExpression(cron);
expression.setTimeZone(TimeZone.getTimeZone(ZoneId.of(StringUtils.hasContent(zone) ? zone : "UTC")));
Date next = expression.getNextValidTimeAfter(Date.from(since));
return (next != null && !next.toInstant().isAfter(now));
}
}
@@ -0,0 +1,154 @@
/*
* Copyright 2026 Kingsrook, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.backups.schedule;
import java.util.List;
import com.kingsrook.qbits.backups.BackupsQBitConfig;
import com.kingsrook.qbits.backups.alerts.BackupAlertSink;
import com.kingsrook.qbits.backups.alerts.BackupAlerts;
import com.kingsrook.qbits.backups.model.BackupsTables;
import com.kingsrook.qbits.backups.permissions.BackupsPermissions;
import com.kingsrook.qbits.backups.processes.BackupsProcesses;
import com.kingsrook.qbits.backups.prune.BackupPruner;
import com.kingsrook.qbits.backups.run.BackupCatalog;
import com.kingsrook.qqq.backend.core.actions.processes.BackendStep;
import com.kingsrook.qqq.backend.core.context.QContext;
import com.kingsrook.qqq.backend.core.exceptions.QException;
import com.kingsrook.qqq.backend.core.logging.QLogger;
import com.kingsrook.qqq.backend.core.model.actions.processes.RunBackendStepInput;
import com.kingsrook.qqq.backend.core.model.actions.processes.RunBackendStepOutput;
import com.kingsrook.qqq.backend.core.model.data.QRecord;
import com.kingsrook.qqq.backend.core.model.metadata.code.QCodeReference;
import com.kingsrook.qqq.backend.core.model.metadata.processes.QBackendStepMetaData;
import com.kingsrook.qqq.backend.core.model.metadata.processes.QProcessMetaData;
import com.kingsrook.qqq.backend.core.model.metadata.scheduleing.QScheduleMetaData;
import com.kingsrook.qqq.backend.core.model.session.QSession;
import com.kingsrook.qqq.backend.core.utils.StringUtils;
import static com.kingsrook.qqq.backend.core.logging.LogUtils.logPair;
/*******************************************************************************
** The daily prune: every plan that is switched on is pruned to its retention
** (spec 10.3), with nobody there to pick plans or read a review screen.
**
** "Prune per retention" (backupPrune) is the action a person runs on the plans
** they select; it shows what it will delete and waits. It used to carry the
** daily schedule too, and a scheduler that started it selected nothing, was
** told "No records were selected", logged a warning and went on: no old backup
** was ever deleted by the schedule. This process is what the schedule runs.
**
** A plan that cannot be pruned raises backups.prune.failed (resolved by its
** next good prune) and does not stop the others. A plan that is switched off
** is left alone: its backups stay until a person prunes or deletes them.
*******************************************************************************/
public class BackupScheduledPruneProcess implements BackendStep
{
private static final QLogger LOG = QLogger.getLogger(BackupScheduledPruneProcess.class);
public static final String NAME = "backupPruneScheduled";
private static final int EVERY_SECONDS = 24 * 3600;
private static final int FIRST_AFTER = 3600;
private static final long BYTES_PER_MEBI = 1024L * 1024L;
/*******************************************************************************
** The process metadata: not in the nav; on the qbit's scheduler once a day
** when it has one.
*******************************************************************************/
public static QProcessMetaData processMetaData(BackupsQBitConfig config)
{
QProcessMetaData process = new QProcessMetaData()
.withName(NAME)
.withLabel("Prune every backup plan")
.withIsHidden(true)
.withStep(new QBackendStepMetaData().withName("prune").withCode(new QCodeReference(BackupScheduledPruneProcess.class)));
process.setPermissionRules(BackupsTables.permissionRules());
if(config != null && StringUtils.hasContent(config.getSchedulerName()))
{
process.setSchedule(new QScheduleMetaData()
.withSchedulerName(config.getSchedulerName())
.withRepeatSeconds(EVERY_SECONDS)
.withInitialDelaySeconds(FIRST_AFTER)
.withDescription("Prune every active backup plan to its retention"));
}
return (BackupsProcesses.permission(process, BackupsPermissions.ADMIN));
}
/*******************************************************************************
** Prune every active plan; say what was done.
*******************************************************************************/
@Override
public void run(RunBackendStepInput input, RunBackendStepOutput output) throws QException
{
QSession session = QContext.getQSession();
String user = session == null || session.getUser() == null || session.getUser().getIdReference() == null ? "system:scheduler" : session.getUser().getIdReference();
List<QRecord> plans = new BackupCatalog().where(BackupsTables.PLAN, "isActive", true);
int pruned = 0;
int failed = 0;
int runsDeleted = 0;
int filesSwept = 0;
long bytesFreed = 0;
for(QRecord plan : plans)
{
String planKey = plan.getValueString("planKey");
try
{
BackupPruner.Outcome outcome = new BackupPruner().prune(plan, user);
pruned++;
runsDeleted += outcome.runsDeleted() + outcome.debrisPrefixesDeleted();
filesSwept += outcome.filesSwept();
bytesFreed += outcome.bytesFreed();
BackupAlerts.resolve(BackupAlerts.PRUNE_FAILED, planKey);
}
catch(QException | RuntimeException e)
{
///////////////////////////////////////////////////////////////////////////
// one plan's trouble (a bucket that cannot be listed, a locked object) //
// must not leave the others unpruned. The class says what kind of //
// failure it was; a message could carry a key or an endpoint //
///////////////////////////////////////////////////////////////////////////
failed++;
if(e instanceof RuntimeException)
{
//////////////////////////////////////////////////////////////////////////
// a defect, not a condition of the storage: its stack trace says where, //
// and holds no data //
//////////////////////////////////////////////////////////////////////////
LOG.warn("A backup plan could not be pruned", e, logPair("plan", planKey));
}
else
{
LOG.warn("A backup plan could not be pruned", logPair("plan", planKey), logPair("failure", e.getClass().getSimpleName()));
}
BackupAlerts.raise(BackupAlerts.PRUNE_FAILED, planKey, BackupAlertSink.Severity.WARNING, "Old backups of " + plan.getValueString("name") + " could not be deleted",
"plan", planKey, "failure", e.getClass().getSimpleName());
}
}
LOG.info("Scheduled prune finished", logPair("plansPruned", pruned), logPair("plansFailed", failed), logPair("runsDeleted", runsDeleted), logPair("filesSwept", filesSwept));
output.addValue("plansPruned", pruned);
output.addValue("plansFailed", failed);
output.addValue("runsDeleted", runsDeleted);
output.addValue("filesSwept", filesSwept);
output.addValue("mebibytesFreed", bytesFreed / BYTES_PER_MEBI);
}
}
@@ -48,6 +48,9 @@ import com.kingsrook.qqq.backend.core.model.metadata.tables.QTableMetaData;
*******************************************************************************/
public class ScopeResolver
{
/** Exclusion reason of a table whose backend has no query interface (storage-only): it cannot be read, even when selected. */
public static final String NOT_QUERYABLE = "NOT_QUERYABLE";
private final QInstance qInstance;
@@ -205,6 +208,10 @@ public class ScopeResolver
{
excluded.add(new ExcludedTable(name, "BACKUPS"));
}
else if(!TableRoles.isQueryable(qInstance, table))
{
excluded.add(new ExcludedTable(name, NOT_QUERYABLE));
}
else if((role == TableRole.EPHEMERAL || role == TableRole.DERIVED || role == TableRole.EXTERNAL) && !explicit.contains(name) && !roles.contains(role))
{
excluded.add(new ExcludedTable(name, role.name()));
@@ -35,6 +35,6 @@ public enum TableRole
SECRET,
/** The tables of this qbit: the catalog is rebuilt from manifests. */
BACKUPS,
/** Tables backed by another system (API). Excluded by default; selectable. */
/** Tables backed by another system (API), or by a backend that cannot be queried (storage-only: never read, even when selected). Excluded by default. */
EXTERNAL
}
@@ -17,12 +17,20 @@
package com.kingsrook.qbits.backups.scope;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import com.kingsrook.qbits.backups.BackupsQBitConfig;
import com.kingsrook.qqq.backend.core.exceptions.QModuleDispatchException;
import com.kingsrook.qqq.backend.core.logging.QLogger;
import com.kingsrook.qqq.backend.core.model.metadata.QBackendMetaData;
import com.kingsrook.qqq.backend.core.model.metadata.QInstance;
import com.kingsrook.qqq.backend.core.model.metadata.fields.QFieldMetaData;
import com.kingsrook.qqq.backend.core.model.metadata.fields.QFieldType;
import com.kingsrook.qqq.backend.core.model.metadata.tables.QTableMetaData;
import com.kingsrook.qqq.backend.core.modules.backend.QBackendModuleDispatcher;
import com.kingsrook.qqq.backend.core.modules.backend.QBackendModuleInterface;
import static com.kingsrook.qqq.backend.core.logging.LogUtils.logPair;
/*******************************************************************************
@@ -31,6 +39,14 @@ import com.kingsrook.qqq.backend.core.model.metadata.tables.QTableMetaData;
*******************************************************************************/
public final class TableRoles
{
private static final QLogger LOG = QLogger.getLogger(TableRoles.class);
////////////////////////////////////////////////////////////////////////////////
// whether a backend type's module has a query interface: the answer depends //
// only on the module class, so it is cached per backend type (roleOf is hot) //
////////////////////////////////////////////////////////////////////////////////
private static final Map<String, Boolean> QUERYABLE_BY_BACKEND_TYPE = new ConcurrentHashMap<>();
private static final Set<String> AUDIT_TABLES = Set.of("audit", "auditTable", "auditUser", "auditDetail");
private static final String[] SECRET_NAME_HINTS = { "refreshToken", "RefreshToken", "oauthToken", "OAuthToken", "apiKey" };
@@ -76,6 +92,10 @@ public final class TableRoles
{
return (TableRole.SECRET);
}
if(qInstance != null && !isQueryable(qInstance, table))
{
return (TableRole.EXTERNAL);
}
if(AUDIT_TABLES.contains(name))
{
return (TableRole.AUDIT);
@@ -108,6 +128,56 @@ public final class TableRoles
/*******************************************************************************
** Whether the rows of a table can be read: its backend module must have a query
** interface. A storage-only module (for example qbit-edi's preview download
** backend) throws from getQueryInterface(), and reading its table would fail the
** whole run, so such a table is never backed up. A backend whose module cannot
** be resolved cannot be read either (not cached: the module may register later).
*******************************************************************************/
public static boolean isQueryable(QInstance qInstance, QTableMetaData table)
{
if(qInstance == null || table == null || table.getBackendName() == null)
{
return (true);
}
QBackendMetaData backend = qInstance.getBackend(table.getBackendName());
if(backend == null || backend.getBackendType() == null)
{
return (true);
}
Boolean cached = QUERYABLE_BY_BACKEND_TYPE.get(backend.getBackendType());
if(cached != null)
{
return (cached);
}
QBackendModuleInterface module;
try
{
module = new QBackendModuleDispatcher().getQBackendModule(backend);
}
catch(QModuleDispatchException e)
{
LOG.debug("No backend module for a table, so it cannot be backed up", logPair("table", table.getName()), logPair("backendType", backend.getBackendType()));
return (false);
}
boolean queryable;
try
{
queryable = module.getQueryInterface() != null;
}
catch(IllegalStateException | UnsupportedOperationException e)
{
queryable = false;
}
QUERYABLE_BY_BACKEND_TYPE.put(backend.getBackendType(), queryable);
return (queryable);
}
/*******************************************************************************
** A table that is hidden and has a password or sensitive field (other than the
** keys and dates) is treated as a table of secrets.
@@ -35,6 +35,7 @@ import com.kingsrook.qbits.backups.model.BackupsTables;
import com.kingsrook.qbits.backups.run.BackupCatalog;
import com.kingsrook.qbits.backups.storage.BackupStorage;
import com.kingsrook.qbits.backups.storage.StoredObjectInfo;
import com.kingsrook.qqq.backend.core.cluster.ClusterCaches;
import com.kingsrook.qqq.backend.core.exceptions.QException;
import com.kingsrook.qqq.backend.core.logging.QLogger;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QCriteriaOperator;
@@ -95,8 +96,11 @@ public class SlaChecker
private static final Set<String> FAILED_STATUSES = Set.of("FAILED", "TIMED_OUT", "ABANDONED");
private static final Set<String> FINISHED_STATUSES = Set.of("SUCCEEDED", "SUCCEEDED_WITH_WARNINGS", "FAILED", "TIMED_OUT", "ABANDONED");
private static final Map<String, Instant> MANIFEST_OK_AT = new ConcurrentHashMap<>();
private static final Map<String, Instant> LAST_AUDIT_AT = new ConcurrentHashMap<>();
private static final Map<String, Instant> MANIFEST_OK_AT = ClusterCaches.nodeLocal(new ConcurrentHashMap<>(),
"throttles this node's storage HEAD of a manifest to once per MANIFEST_CACHE; it caches storage state, not editable data, "
+ "and a pruned run is skipped by its prunedDate, so each node is as fresh as a single node");
private static final Map<String, Instant> LAST_AUDIT_AT = ClusterCaches.nodeLocal(new ConcurrentHashMap<>(),
"throttles this node's bucket audit to once per BUCKET_AUDIT_INTERVAL; another node auditing again is only repeated work");
private final BackupCatalog catalog = new BackupCatalog();
@@ -323,7 +323,7 @@ public class ObjectStorageBackupStorage implements BackupStorage
Page<ObjectSummary> page = bucket.list(ListRequest.prefix(prefix == null ? "" : prefix).pageSize(1000).after(after));
for(ObjectSummary summary : page.getItems())
{
rs.add(new StoredObjectInfo(summary.getKey(), summary.getSize() == null ? 0 : summary.getSize(), null, new LinkedHashMap<>(), null));
rs.add(new StoredObjectInfo(summary.getKey(), summary.getSize() == null ? 0 : summary.getSize(), summary.getLastModified(), new LinkedHashMap<>(), null));
}
after = page.getNextToken();
}
@@ -609,6 +609,14 @@ entries:
Use **Create default plan** on **Backup plans** and enter a **Storage bucket alias** provided by your application. Review the proposed plan before continuing. The action adds **Nightly full** for data and audit tables with JSONL, gzip and copied files, scheduled at 02:00 UTC with content verification on Sundays at 04:00 UTC.
You can edit the settings afterward. The action creates a plan only when its plan key does not already exist; it does not change an existing plan. Scheduled execution requires your application's scheduler integration.
- key: process:backupPruneScheduled;slot:help
summary: 'Delete, once a day, the backups that every active plan no longer keeps.'
content: |
This background action prunes every **Backup Plan** that is switched on to its retention: the daily, weekly, monthly and yearly copies the plan keeps, and its minimum. Nobody selects plans or reads a review for it. A plan that is switched off is left alone. A plan that cannot be pruned raises the alert **Old backups could not be deleted**, which its next successful prune clears, and does not stop the others. To see what a prune would delete before it happens, use **Prune per retention** on the plan.
- key: process:backupRunDuePlans;slot:help
summary: 'Start the backups and verifications whose plan schedule has come due.'
content: |
This background action is how plans run on their own schedule in an application that has no scheduled jobs table. Once a minute it starts every active **Backup Plan** whose schedule has come due since the plan last started, and every verification that has come due. Times missed while the application was down become one run. Where the application has scheduled jobs, each plan has a scheduled job of its own and this action starts nothing. Only the scheduler can run it.
- key: process:backupVerifyPlan;slot:help
summary: Verify the latest successful backup of a scheduled plan.
content: |
@@ -0,0 +1 @@
version=${project.version}
@@ -0,0 +1,164 @@
/*
* Copyright 2026 Kingsrook, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.backups;
import java.util.EnumSet;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.function.Consumer;
import com.kingsrook.qbits.backups.metrics.BackupsMetrics;
import com.kingsrook.qbits.backups.model.BackupsTables;
import com.kingsrook.qbits.backups.run.BackupCatalog;
import com.kingsrook.qqq.backend.core.cluster.ClusterBus;
import com.kingsrook.qqq.backend.core.cluster.ClusterBusInterface;
import com.kingsrook.qqq.backend.core.cluster.ClusterBusMetaData;
import com.kingsrook.qqq.backend.core.cluster.ClusterCacheAudit;
import com.kingsrook.qqq.backend.core.cluster.ClusterEvent;
import com.kingsrook.qqq.backend.core.cluster.QNodeRoles;
import com.kingsrook.qqq.backend.core.context.QContext;
import com.kingsrook.qqq.backend.core.model.data.QRecord;
import com.kingsrook.qqq.backend.core.model.metadata.QInstance;
import com.kingsrook.qqq.backend.core.model.metadata.code.QCodeReference;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
/*******************************************************************************
** The Backups caches are correct on several nodes: every static cache is
** registered with ClusterCaches, and the cached metrics are cleared on every
** node when a plan changes.
*******************************************************************************/
class BackupsClusterCachesTest
{
/** the "wire": events every node's transport sees */
static final List<Consumer<ClusterEvent>> WIRE = new CopyOnWriteArrayList<>();
/*******************************************************************************
** A transport over the static WIRE, so a "remote" publish reaches us.
*******************************************************************************/
public static class WireBus implements ClusterBusInterface
{
/*******************************************************************************
**
*******************************************************************************/
@Override
public void publish(ClusterEvent event)
{
WIRE.forEach(listener -> listener.accept(event));
}
/*******************************************************************************
**
*******************************************************************************/
@Override
public AutoCloseable subscribe(Consumer<ClusterEvent> listener)
{
WIRE.add(listener);
return (() -> WIRE.remove(listener));
}
}
/*******************************************************************************
** A backed-up test instance, connected to the wire as node-a.
*******************************************************************************/
@BeforeEach
void setUp() throws Exception
{
VerifyTestSupport.setUp(1);
QInstance instance = QContext.getQInstance();
instance.withSupplementalMetaData(new ClusterBusMetaData().withBus(new QCodeReference(WireBus.class)));
QNodeRoles.set(new QNodeRoles.Settings(EnumSet.allOf(QNodeRoles.Role.class), true, true, true, null, "node-a"));
ClusterBus.connect(instance);
}
/*******************************************************************************
**
*******************************************************************************/
@AfterEach
void afterEach()
{
ClusterBus.close(QContext.getQInstance());
WIRE.clear();
QNodeRoles.set(null);
}
/*******************************************************************************
** Every static Memoization in the QBit is registered (shared or node-local).
*******************************************************************************/
@Test
void testNoUnregisteredStaticCaches() throws Exception
{
assertThat(ClusterCacheAudit.unregisteredStaticCaches("com.kingsrook.qbits.backups")).isEmpty();
}
/*******************************************************************************
** Another node's invalidation clears this node's cached metrics.
*******************************************************************************/
@Test
void testRemoteInvalidationClearsMetricsCache() throws Exception
{
String cached = BackupsMetrics.renderCached();
assertThat(BackupsMetrics.renderCached()).isSameAs(cached);
ClusterEvent remote = new ClusterEvent(ClusterEvent.TYPE_MEMO_INVALIDATE, BackupsMetrics.CACHE_NAME, null);
remote.setOriginNodeId("node-b");
WIRE.forEach(listener -> listener.accept(remote));
assertThat(BackupsMetrics.renderCached()).isNotSameAs(cached);
}
/*******************************************************************************
** A plan edit here clears the metrics here and tells the other nodes.
*******************************************************************************/
@Test
void testPlanEditPublishesMetricsInvalidation() throws Exception
{
QRecord plan = VerifyTestSupport.plan(Map.of());
String cached = BackupsMetrics.renderCached();
List<ClusterEvent> sent = new CopyOnWriteArrayList<>();
WIRE.add(sent::add);
new BackupCatalog().update(BackupsTables.PLAN, plan.getValueInteger("id"), Map.of("slaHours", 48));
assertThat(BackupsMetrics.renderCached()).isNotSameAs(cached);
assertThat(sent).anySatisfy(event ->
{
assertThat(event.getType()).isEqualTo(ClusterEvent.TYPE_MEMO_INVALIDATE);
assertThat(event.getName()).isEqualTo(BackupsMetrics.CACHE_NAME);
assertThat(event.getOriginNodeId()).isEqualTo("node-a");
});
}
}
@@ -18,6 +18,7 @@ package com.kingsrook.qbits.backups;
import com.kingsrook.qqq.backend.core.model.metadata.QInstance;
import com.kingsrook.qqq.backend.core.model.metadata.help.bundles.HelpBundles;
import com.kingsrook.qqq.backend.core.model.metadata.qbits.QBitConfigValidationException;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
@@ -40,12 +41,16 @@ class BackupsQBitProducerTest
BackupsQBitConfig config = new BackupsQBitConfig().withBackendName("rdbms");
BackupsQBitProducer producer = new BackupsQBitProducer().withQBitConfig(config).withNamespace("backups");
String artifactVersion = System.getProperty("qbit.artifactVersion");
assertThat(artifactVersion).isNotBlank();
assertThat(producer.getQBitMetaData().getVersion()).isEqualTo(artifactVersion).isEqualTo(BackupsQBitProducer.VERSION);
assertThat(producer.isEnabled()).isTrue();
assertThat(producer.getQBitConfig()).isSameAs(config);
assertThat(producer.getNamespace()).isEqualTo("backups");
assertThat(config.getDefaultBackendNameForTables()).isEqualTo("rdbms");
producer.produce(qInstance);
assertThat(HelpBundles.of(qInstance).getBundles().get(0).getVersion()).isEqualTo(artifactVersion).isEqualTo(BackupsQBitProducer.VERSION);
assertThat(qInstance.getQBits()).hasSize(1);
assertThat(qInstance.getQBits().values().iterator().next().getArtifactId()).isEqualTo("qbit-backups");
}
@@ -191,10 +191,10 @@ class AlertsQBitAlertSinkTest
AlertsQBitAlertSink sink = new AlertsQBitAlertSink();
int added = sink.registerAlertTypes(instance);
var types = new ArrayList<>(AlertsInstanceMetaData.of(instance).getAlertTypes().values());
assertThat(added).isEqualTo(BackupAlerts.alertTypes().size()).isEqualTo(9);
assertThat(added).isEqualTo(BackupAlerts.alertTypes().size()).isEqualTo(10);
assertThat(types).extracting(t -> t.getName()).containsExactly(
"backups.plan.missed", "backups.run.failed", "backups.run.missing-in-storage", "backups.files.missing", "backups.verify.failed",
"backups.verify.overdue", "backups.plan.owner-invalid", "backups.storage.debris", "backups.restore.completed");
"backups.verify.overdue", "backups.plan.owner-invalid", "backups.storage.debris", "backups.restore.completed", "backups.prune.failed");
assertThat(types).allSatisfy(t ->
{
assertThat(t.getGroupName()).isEqualTo("Backups");
@@ -71,7 +71,7 @@ class BackupAlertsTest
{
Set<String> names = BackupAlerts.alertTypes().stream().map(BackupAlerts.AlertType::name).collect(Collectors.toSet());
assertThat(names).containsExactlyInAnyOrder("backups.plan.missed", "backups.run.failed", "backups.run.missing-in-storage", "backups.files.missing",
"backups.verify.failed", "backups.verify.overdue", "backups.plan.owner-invalid", "backups.storage.debris", "backups.restore.completed");
"backups.verify.failed", "backups.verify.overdue", "backups.plan.owner-invalid", "backups.storage.debris", "backups.restore.completed", "backups.prune.failed");
assertThat(BackupAlerts.alertTypes()).allSatisfy(t -> assertThat(t.howToFix()).isNotBlank());
assertThat(BackupAlerts.alertTypes().stream().filter(t -> t.name().equals(BackupAlerts.RUN_MISSING)).findFirst().orElseThrow().defaultSeverity())
.isEqualTo(BackupAlertSink.Severity.CRITICAL);
@@ -88,7 +88,7 @@ class BackupsHomeTest
void testEmptyStates()
{
String html = BackupsHomeView.render(new BackupsHomeData(List.of(), List.of(), List.of(), List.of(), List.of(), Instant.now()), "/app");
assertThat(html).contains("No backup plans yet").contains("Nothing to check yet").contains("No test restore yet")
assertThat(html).contains("No backup plans yet").contains("Setup: <a").contains("No plan: nothing is backed up.").doesNotContain("Nothing needs attention").contains("No test restore yet")
.contains("Nothing has run yet").contains("Trends appear after the first successful run").contains("Retention starts once runs exist");
assertThat(BackupsHomeView.renderHealthCard(new BackupsHomeData(List.of(), List.of(), List.of(), List.of(), List.of(), Instant.now()), "/app")).contains("No backup plans yet");
}
@@ -121,6 +121,45 @@ class BackupsHomeTest
/*******************************************************************************
** The Setup card and the Needs attention card never contradict each other: a plan
** whose storage aliases do not resolve is a Setup fault, and it is listed under
** Needs attention too, with the same count.
*******************************************************************************/
@Test
void testUnresolvedAliasAppearsInSetupAndNeedsAttention() throws Exception
{
BackupsRuntime.getConfig().withStorageResolver(alias -> BackupsTestUtils.BACKUPS);
new BackupCatalog().insert(BackupsTables.PLAN, new LinkedHashMap<>(Map.of("name", "Offsite", "planKey", "offsite", "isActive", true, "scopeType", "INSTANCE",
"storageBucketAlias", "backupsAws", "pruneBucketAlias", "backupsAwsPrune")));
//////////////////////////////////////////////////////////////////////////////
// the aliases resolved when the plan was saved; now the bucket is gone //
//////////////////////////////////////////////////////////////////////////////
BackupsRuntime.getConfig().withStorageResolver(alias -> "backups".equals(alias) ? BackupsTestUtils.BACKUPS : null);
BackupsHomeData data = BackupsHomeData.load();
List<BackupsSetupStatus.Item> setupTodo = BackupsSetupStatus.load(data.plans()).stream().filter(i -> i.state() == BackupsSetupStatus.State.TODO).toList();
assertThat(setupTodo).extracting(BackupsSetupStatus.Item::label).contains("Storage");
String html = BackupsHomeView.render(data, "/app");
String attention = html.substring(html.indexOf(">Needs attention<"));
attention = attention.substring(0, attention.indexOf("All runs"));
assertThat(attention).doesNotContain("Nothing needs attention").contains("backupsAws").contains("backupsAwsPrune");
///////////////////////////////////////////////////////////////////////////////
// every Setup TODO is listed under Needs attention (counts agree: 2 and 2) //
///////////////////////////////////////////////////////////////////////////////
assertThat(html).contains(setupTodo.size() + " items need attention.");
for(BackupsSetupStatus.Item item : setupTodo)
{
assertThat(attention).contains("Setup: <a").contains(item.label());
}
assertThat(attention.split("<li>", -1).length - 1).isEqualTo(setupTodo.size() + data.plansNeedingAttention().size() + data.failedRuns().size());
}
/*******************************************************************************
** The links follow the configured table path prefix.
*******************************************************************************/
@@ -0,0 +1,215 @@
/*
* Copyright 2026 Kingsrook, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.backups.codec;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import com.kingsrook.qqq.backend.core.crypto.EnvKeyProvider;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
/*******************************************************************************
** The transform that encrypts a backup's objects: what it writes can be read
** back with the key and with nothing else, a changed or cut-off object is
** refused, a rotated key still reads what its older version wrote, and what a
** run records about the key is not the key.
**
** Every key here is random and made for the test.
*******************************************************************************/
class StreamingCipherTransformTest
{
private static final String KEY_REF = "BACKUPS_TEST_KEK";
private static final byte[] PLAIN = ("{\"id\":1,\"title\":\"a row of a backup\"}\n".repeat(4000)).getBytes(StandardCharsets.UTF_8);
/*******************************************************************************
** A new random key, as the text an environment variable would hold.
*******************************************************************************/
private static String newKey()
{
byte[] key = new byte[32];
new SecureRandom().nextBytes(key);
return (Base64.getEncoder().encodeToString(key));
}
/*******************************************************************************
**
*******************************************************************************/
private static byte[] encrypt(ArtifactTransform transform, byte[] plain) throws IOException
{
ByteArrayOutputStream stored = new ByteArrayOutputStream();
try(OutputStream out = transform.wrap(stored))
{
out.write(plain);
}
return (stored.toByteArray());
}
/*******************************************************************************
**
*******************************************************************************/
private static byte[] decrypt(ArtifactTransform transform, byte[] stored) throws IOException
{
try(InputStream in = transform.unwrap(new ByteArrayInputStream(stored)))
{
return (in.readAllBytes());
}
}
/*******************************************************************************
** What is stored is not what was written, and the key reads it back exactly.
*******************************************************************************/
@Test
void testWhatIsStoredIsCiphertextAndTheKeyReadsItBack() throws Exception
{
Map<String, String> env = new HashMap<>(Map.of(KEY_REF, newKey()));
ArtifactTransform transform = StreamingCipherTransform.forKey(new EnvKeyProvider(env::get), KEY_REF);
assertThat(transform).isNotNull();
assertThat(transform.encrypts()).isTrue();
assertThat(transform.keySuffix()).isEqualTo(".tink");
byte[] stored = encrypt(transform, PLAIN);
assertThat(new String(stored, StandardCharsets.ISO_8859_1)).doesNotContain("a row of a backup");
assertThat(stored.length).isGreaterThan(PLAIN.length);
assertThat(decrypt(transform, stored)).isEqualTo(PLAIN);
assertThat(encrypt(transform, PLAIN)).as("a fresh data key for every object").isNotEqualTo(stored);
}
/*******************************************************************************
** A flipped byte, and an object cut short, are refused: nothing altered is
** ever handed back as if it were the backup.
*******************************************************************************/
@Test
void testAChangedOrCutOffObjectIsRefused() throws Exception
{
Map<String, String> env = new HashMap<>(Map.of(KEY_REF, newKey()));
ArtifactTransform transform = StreamingCipherTransform.forKey(new EnvKeyProvider(env::get), KEY_REF);
byte[] stored = encrypt(transform, PLAIN);
byte[] flipped = stored.clone();
flipped[flipped.length / 2] ^= 0x01;
assertThatThrownBy(() -> decrypt(transform, flipped)).isInstanceOf(IOException.class);
byte[] cut = java.util.Arrays.copyOf(stored, stored.length - 100);
assertThatThrownBy(() -> decrypt(transform, cut)).isInstanceOf(IOException.class);
assertThatThrownBy(() -> decrypt(transform, PLAIN)).as("an object that was never encrypted").isInstanceOf(IOException.class);
}
/*******************************************************************************
** Another key does not read it, and its message says nothing of either key.
*******************************************************************************/
@Test
void testAnotherKeyDoesNotReadIt() throws Exception
{
String rightKey = newKey();
String wrongKey = newKey();
byte[] stored = encrypt(StreamingCipherTransform.forKey(new EnvKeyProvider(Map.of(KEY_REF, rightKey)::get), KEY_REF), PLAIN);
ArtifactTransform wrong = StreamingCipherTransform.forKey(new EnvKeyProvider(Map.of(KEY_REF, wrongKey)::get), KEY_REF);
assertThatThrownBy(() -> decrypt(wrong, stored)).isInstanceOf(IOException.class)
.satisfies(e -> assertThat(String.valueOf(e.getMessage())).doesNotContain(rightKey).doesNotContain(wrongKey));
}
/*******************************************************************************
** A reference with no key, or a key that is not a key, gives no transform: the
** caller then refuses, and nothing is written in the clear instead.
*******************************************************************************/
@Test
void testNoKeyGivesNoTransform()
{
assertThat(StreamingCipherTransform.forKey(new EnvKeyProvider(Map.<String, String>of()::get), KEY_REF)).isNull();
assertThat(StreamingCipherTransform.forKey(new EnvKeyProvider(Map.of(KEY_REF, "not-a-key")::get), KEY_REF)).isNull();
assertThat(StreamingCipherTransform.forKey(new EnvKeyProvider(Map.of(KEY_REF, newKey())::get), " ")).isNull();
assertThat(StreamingCipherTransform.forKey(null, KEY_REF)).isNull();
}
/*******************************************************************************
** After a rotation the new version writes, and what the old version wrote is
** still read for as long as the provider keeps that version; without it, it is
** refused.
*******************************************************************************/
@Test
void testARotatedKeyStillReadsWhatItsOlderVersionWrote() throws Exception
{
Map<String, String> env = new HashMap<>();
String first = newKey();
env.put(KEY_REF, first);
ArtifactTransform before = StreamingCipherTransform.forKey(new EnvKeyProvider(env::get), KEY_REF);
byte[] oldObject = encrypt(before, PLAIN);
env.put(KEY_REF + "_V1", first);
env.put(KEY_REF, newKey());
env.put(KEY_REF + "_VERSION", "2");
ArtifactTransform after = StreamingCipherTransform.forKey(new EnvKeyProvider(env::get), KEY_REF);
assertThat(after.keyFingerprint()).startsWith("v2:").isNotEqualTo(before.keyFingerprint());
assertThat(decrypt(after, oldObject)).as("written under version 1, read after the rotation").isEqualTo(PLAIN);
assertThat(decrypt(after, encrypt(after, PLAIN))).isEqualTo(PLAIN);
env.remove(KEY_REF + "_V1");
ArtifactTransform withoutTheOldVersion = StreamingCipherTransform.forKey(new EnvKeyProvider(env::get), KEY_REF);
assertThatThrownBy(() -> decrypt(withoutTheOldVersion, oldObject)).isInstanceOf(IOException.class);
}
/*******************************************************************************
** The fingerprint a run records names the version, is the same every time for
** one key, differs between keys, and holds nothing of the key.
*******************************************************************************/
@Test
void testTheFingerprintIsNotTheKey()
{
String keyText = newKey();
String one = StreamingCipherTransform.forKey(new EnvKeyProvider(Map.of(KEY_REF, keyText)::get), KEY_REF).keyFingerprint();
String again = StreamingCipherTransform.forKey(new EnvKeyProvider(Map.of(KEY_REF, keyText)::get), KEY_REF).keyFingerprint();
String another = StreamingCipherTransform.forKey(new EnvKeyProvider(Map.of(KEY_REF, newKey())::get), KEY_REF).keyFingerprint();
String keyAsHex = java.util.HexFormat.of().formatHex(Base64.getDecoder().decode(keyText));
assertThat(one).matches("v1:[0-9a-f]{16}").isEqualTo(again).isNotEqualTo(another);
assertThat(keyAsHex).doesNotContain(one.substring(3));
assertThat(keyText).doesNotContain(one.substring(3));
}
}
@@ -0,0 +1,495 @@
/*
* Copyright 2026 Kingsrook, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.backups.health;
import java.io.InputStream;
import java.io.OutputStream;
import java.time.Instant;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import com.kingsrook.qbits.backups.BackupsRuntime;
import com.kingsrook.qbits.backups.BackupsTestUtils;
import com.kingsrook.qbits.backups.VerifyTestSupport;
import com.kingsrook.qbits.backups.model.BackupsTables;
import com.kingsrook.qbits.backups.plan.DestinationProbe;
import com.kingsrook.qbits.backups.run.BackupCatalog;
import com.kingsrook.qbits.backups.storage.InMemoryBackupStorage;
import com.kingsrook.qbits.backups.storage.StoredObjectInfo;
import com.kingsrook.qbits.backups.storage.WriteOptions;
import com.kingsrook.qqq.backend.core.actions.customizers.QCodeLoader;
import com.kingsrook.qqq.backend.core.context.QContext;
import com.kingsrook.qqq.backend.core.health.HealthCategory;
import com.kingsrook.qqq.backend.core.health.HealthCheck;
import com.kingsrook.qqq.backend.core.health.HealthCheckInput;
import com.kingsrook.qqq.backend.core.health.HealthCheckKind;
import com.kingsrook.qqq.backend.core.health.HealthCheckMetaData;
import com.kingsrook.qqq.backend.core.health.HealthCheckOutcome;
import com.kingsrook.qqq.backend.core.health.HealthChecksMetaData;
import com.kingsrook.qqq.backend.core.health.HealthStatus;
import com.kingsrook.qqq.backend.core.model.data.QRecord;
import com.kingsrook.qqq.backend.core.model.metadata.QInstance;
import com.kingsrook.qqq.backend.core.model.session.QSession;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
/*******************************************************************************
** Central registration, migrated SLA rules, read-only probes and secret safety.
*******************************************************************************/
class BackupsHealthChecksTest
{
private static final String SECRET = "S3NT1NEL-secret";
private final BackupCatalog catalog = new BackupCatalog();
private ReadOnlyStorage storage;
/*******************************************************************************
** All probes use memory storage; the resolver represents credential injection.
*******************************************************************************/
@BeforeEach
void setUp() throws Exception
{
VerifyTestSupport.setUp(3);
storage = new ReadOnlyStorage(SECRET);
BackupsRuntime.getConfig().withStorageResolver(alias ->
{
assertThat(alias).as("never resolve prune credentials").isNotEqualTo("prune");
return (storage);
});
}
/*******************************************************************************
** Use the actual producer registry, including its reflective supplier loading.
*******************************************************************************/
@Test
void testRegistrationAndDynamicPlans() throws Exception
{
HealthChecksMetaData registry = HealthChecksMetaData.ofOrWithNew(QContext.getQInstance());
assertThat(registry.getChecks()).extracting(HealthCheckMetaData::getName).containsExactly("backups.sla");
assertThat(registry.getSuppliers()).singleElement().satisfies(supplier ->
{
assertThat(supplier.getNamePrefix()).isEqualTo("backups.destination");
assertThat(supplier.getComponent()).isEqualTo("backups");
});
QRecord active = VerifyTestSupport.plan(Map.of());
VerifyTestSupport.plan(Map.of("name", "Off", "planKey", "off", "isActive", false));
List<HealthCheckMetaData> checks = registry.resolveAll(QContext.getQInstance());
assertThat(checks).hasSize(2).allSatisfy(check ->
{
assertThat(check.getComponent()).isEqualTo("backups");
assertThat(check.getKind()).isEqualTo(HealthCheckKind.DEPENDENCY);
assertThat(check.getCategory()).isEqualTo(HealthCategory.STORAGE);
assertThat(check.getIncludeInReadiness()).isFalse();
assertThat(check.getName()).matches("[a-z0-9]+([._-][a-z0-9]+)*");
});
assertThat(checks.get(0).getIntervalSeconds()).isEqualTo(900);
assertThat(checks.get(0).getTimeoutMs()).isEqualTo(5000);
assertThat(QCodeLoader.getAdHoc(HealthCheck.class, checks.get(0).getCheck()).run(input()).getStatus()).isEqualTo(HealthStatus.UNKNOWN);
HealthCheckMetaData destination = checks.get(1);
assertThat(destination.getName()).isEqualTo("backups.destination." + active.getValueInteger("id"));
assertThat(destination.getIntervalSeconds()).isEqualTo(86400);
assertThat(destination.getTimeoutMs()).isEqualTo(30000);
assertThat(destination.getCheckInstance().run(input()).getStatus()).isEqualTo(HealthStatus.UP);
catalog.update(BackupsTables.PLAN, active.getValueInteger("id"), Map.of("isActive", false));
assertThat(destination.getCheckInstance().run(input()).getStatus()).isEqualTo(HealthStatus.UNKNOWN);
assertThat(registry.resolveAll(QContext.getQInstance())).hasSize(1);
VerifyTestSupport.plan(Map.of("name", "New", "planKey", "new"));
assertThat(registry.resolveAll(QContext.getQInstance())).hasSize(2);
}
/*******************************************************************************
** Carry over the indicator's empty, critical, ordinary and inactive cases.
*******************************************************************************/
@Test
void testSlaUpDownAndDegraded() throws Exception
{
BackupsSlaHealthCheck check = new BackupsSlaHealthCheck();
HealthCheckOutcome empty = check.run(input());
assertThat(empty.getStatus()).isEqualTo(HealthStatus.UP);
assertThat(empty.getDetails().getValues()).containsEntry("activePlans", 0);
QRecord critical = VerifyTestSupport.plan(Map.of("critical", true));
QRecord ordinary = VerifyTestSupport.plan(Map.of("name", "Other", "planKey", "other"));
QRecord inactive = VerifyTestSupport.plan(Map.of("name", "Off", "planKey", "off", "isActive", false, "critical", true));
setStatus(inactive, "LATE");
setStatus(critical, "OK");
setStatus(ordinary, "OK");
assertThat(check.run(input()).getStatus()).isEqualTo(HealthStatus.UP);
for(String status : List.of("LATE", "FAILING", "MISSING_IN_STORAGE"))
{
setStatus(ordinary, status);
assertThat(check.run(input()).getStatus()).as(status).isEqualTo(HealthStatus.DEGRADED);
setStatus(critical, status);
HealthCheckOutcome down = check.run(input());
assertThat(down.getStatus()).as(status).isEqualTo(HealthStatus.DOWN);
assertThat(down.getDetails().getValues()).containsEntry("activePlans", 2).containsEntry("slaStatus." + status, 2);
assertClean(down);
setStatus(critical, "OK");
}
}
/*******************************************************************************
** Unknown or unverified plans do not become a false UP or a critical DOWN.
*******************************************************************************/
@Test
void testSlaUnknownAndMixedStates() throws Exception
{
QRecord plan = VerifyTestSupport.plan(Map.of("critical", true));
BackupsSlaHealthCheck check = new BackupsSlaHealthCheck();
assertThat(check.run(input()).getStatus()).isEqualTo(HealthStatus.UNKNOWN);
for(String status : List.of("UNVERIFIED", "UNKNOWN"))
{
setStatus(plan, status);
assertThat(check.run(input()).getStatus()).isEqualTo(HealthStatus.UNKNOWN);
}
QRecord other = VerifyTestSupport.plan(Map.of("name", "Other", "planKey", "other"));
setStatus(other, "UNVERIFIED");
assertThat(check.run(input()).getStatus()).isEqualTo(HealthStatus.UNKNOWN);
setStatus(other, "OK");
assertThat(check.run(input()).getStatus()).isEqualTo(HealthStatus.UP);
}
/*******************************************************************************
** Preserve the old indicator's no-context behavior and existing sessions.
*******************************************************************************/
@Test
void testWithoutContext() throws Exception
{
QRecord plan = VerifyTestSupport.plan(Map.of());
QInstance instance = QContext.getQInstance();
QSession session = QContext.getQSession();
new BackupsSlaHealthCheck().run(input());
assertThat(QContext.getQSession()).isSameAs(session);
QContext.clear();
try
{
HealthCheckInput input = new HealthCheckInput().withQInstance(instance).withDeadline(Instant.now().plusSeconds(5));
assertThat(new BackupsSlaHealthCheck().run(input).getStatus()).isEqualTo(HealthStatus.UNKNOWN);
assertThat(QContext.getQInstance()).isNull();
assertThat(new BackupsDestinationHealthChecks().supply(instance)).hasSize(1);
assertThat(QContext.getQInstance()).isNull();
BackupsRuntime.getConfig().withStorageResolver(alias ->
{
assertThat(QContext.getQSession()).isInstanceOf(com.kingsrook.qqq.backend.core.model.session.QSystemUserSession.class);
return (storage);
});
assertThat(destination(plan).run(input).getStatus()).isEqualTo(HealthStatus.UP);
assertThat(QContext.getQInstance()).isNull();
}
finally
{
QContext.init(instance, session);
}
}
/*******************************************************************************
** Locked and unlocked plans only list/head; neither reads object contents.
*******************************************************************************/
@Test
void testDestinationReadOnlyAndMissingManifest() throws Exception
{
for(String lockMode : List.of("NONE", "GOVERNANCE"))
{
BackupsRuntime.getConfig().withStorageResolver(alias -> BackupsTestUtils.BACKUPS);
QRecord plan = VerifyTestSupport.plan(Map.of("name", lockMode, "planKey", lockMode.toLowerCase(), "objectLockMode", lockMode, "objectLockDays", 3, "pruneBucketAlias", "prune"));
BackupsRuntime.getConfig().withStorageResolver(alias ->
{
assertThat(alias).as("never resolve prune credentials").isNotEqualTo("prune");
return (storage);
});
Integer runId = catalog.insert(BackupsTables.RUN, Map.of("manifestKey", "manifest.json"));
catalog.update(BackupsTables.PLAN, plan.getValueInteger("id"), Map.of("lastSuccessRunId", runId));
storage.putBytes("manifest.json", new byte[] { 1 });
assertThat(destination(plan).run(input()).getStatus()).isEqualTo(HealthStatus.UP);
storage.clear();
assertThat(destination(plan).run(input()).getStatus()).isEqualTo(HealthStatus.DOWN);
}
assertThat(storage.lists).isEqualTo(4);
assertThat(storage.heads).isEqualTo(4);
}
/*******************************************************************************
** A deleted plan is UNKNOWN and does not touch storage.
*******************************************************************************/
@Test
void testDeletedPlan() throws Exception
{
QRecord plan = VerifyTestSupport.plan(Map.of());
catalog.deleteByIds(BackupsTables.PLAN, List.of(plan.getValueInteger("id")));
assertThat(destination(plan).run(input()).getStatus()).isEqualTo(HealthStatus.UNKNOWN);
assertThat(storage.lists).isZero();
}
/*******************************************************************************
** No work starts with an expired deadline, including direct probe calls.
*******************************************************************************/
@Test
void testExpiredDeadline() throws Exception
{
QRecord plan = VerifyTestSupport.plan(Map.of());
HealthCheckInput expired = input().withDeadline(Instant.now().minusSeconds(1));
assertThat(new BackupsSlaHealthCheck().run(expired).getStatus()).isEqualTo(HealthStatus.DOWN);
assertThat(destination(plan).run(expired).getStatus()).isEqualTo(HealthStatus.DOWN);
assertThat(DestinationProbe.probeReadOnly(plan, expired.getDeadline()).ok()).isFalse();
assertThat(storage.lists).isZero();
assertThat(storage.heads).isZero();
}
/*******************************************************************************
** Runner cancellation after list prevents the following manifest head.
*******************************************************************************/
@Test
void testCancellationBetweenStorageCalls() throws Exception
{
QRecord plan = VerifyTestSupport.plan(Map.of());
Integer runId = catalog.insert(BackupsTables.RUN, Map.of("manifestKey", "manifest.json"));
catalog.update(BackupsTables.PLAN, plan.getValueInteger("id"), Map.of("lastSuccessRunId", runId));
storage.interruptAfterList = true;
try
{
assertThat(destination(plan).run(input()).getStatus()).isEqualTo(HealthStatus.DOWN);
assertThat(storage.lists).isEqualTo(1);
assertThat(storage.heads).isZero();
}
finally
{
Thread.interrupted();
}
}
/*******************************************************************************
** Poison configuration, persisted state and provider errors. sanitize is
** package-private in core; assert raw outcomes already contain no secrets.
*******************************************************************************/
@Test
void testNoSecretsInSuccessAndFailureOutcomes() throws Exception
{
QRecord plan = VerifyTestSupport.plan(Map.of("name", SECRET, "storageBucketAlias", SECRET, "critical", true));
Integer runId = catalog.insert(BackupsTables.RUN, Map.of("manifestKey", SECRET));
catalog.update(BackupsTables.PLAN, plan.getValueInteger("id"), Map.of("lastSuccessRunId", runId));
storage.putBytes(SECRET, new byte[] { 1 });
for(String status : List.of("OK", "LATE", "UNVERIFIED", SECRET))
{
setStatus(plan, status);
assertClean(new BackupsSlaHealthCheck().run(input()));
assertClean(destination(plan).run(input()));
}
storage.failList = true;
HealthCheckOutcome failure = destination(plan).run(input());
assertThat(failure.getStatus()).isEqualTo(HealthStatus.DOWN);
assertClean(failure);
storage.failList = false;
storage.failHead = true;
failure = destination(plan).run(input());
assertThat(failure.getStatus()).isEqualTo(HealthStatus.DOWN);
assertClean(failure);
BackupsRuntime.getConfig().withStorageResolver(alias ->
{
throw (new IllegalStateException(SECRET));
});
failure = destination(plan).run(input());
assertThat(failure.getStatus()).isEqualTo(HealthStatus.DOWN);
assertClean(failure);
assertClean(new BackupsSlaHealthCheck().run(input()));
}
/*******************************************************************************
** Catalog failures are DOWN with fixed messages, even if metadata is poisoned.
*******************************************************************************/
@Test
void testCatalogFailureDoesNotExposeSecrets()
{
QContext.getQInstance().getTable(BackupsTables.PLAN).setBackendName(SECRET);
HealthCheckOutcome sla = new BackupsSlaHealthCheck().run(input());
HealthCheckOutcome destination = new BackupsDestinationHealthCheck(1).run(input());
assertThat(sla.getStatus()).isEqualTo(HealthStatus.DOWN);
assertThat(destination.getStatus()).isEqualTo(HealthStatus.DOWN);
assertClean(sla);
assertClean(destination);
}
/*******************************************************************************
** Update persisted SLA state without running the scheduled calculator.
*******************************************************************************/
private void setStatus(QRecord plan, String status) throws Exception
{
catalog.update(BackupsTables.PLAN, plan.getValueInteger("id"), Map.of("slaStatus", status));
}
/*******************************************************************************
** Fresh bounded input for each call.
*******************************************************************************/
private HealthCheckInput input()
{
return (new HealthCheckInput().withQInstance(QContext.getQInstance()).withDeadline(Instant.now().plusSeconds(5)));
}
/*******************************************************************************
** Construct the same per-plan check as the supplier.
*******************************************************************************/
private BackupsDestinationHealthCheck destination(QRecord plan)
{
return (new BackupsDestinationHealthCheck(plan.getValueInteger("id")));
}
/*******************************************************************************
** Validate the raw public message and flattened detail representation.
*******************************************************************************/
private void assertClean(HealthCheckOutcome outcome)
{
assertThat(outcome.getMessage()).doesNotContain(SECRET, "\n", "\r");
assertThat(outcome.getDetails().toJson()).doesNotContain(SECRET);
}
/*******************************************************************************
** Existing memory fake with read failures and assertions against side effects.
*******************************************************************************/
private static class ReadOnlyStorage extends InMemoryBackupStorage
{
private final String credential;
private boolean failList;
private boolean failHead;
private boolean interruptAfterList;
private int lists;
private int heads;
/*******************************************************************************
** Mimic the credential held by a host-provided storage adapter.
*******************************************************************************/
ReadOnlyStorage(String credential)
{
this.credential = credential;
}
/*******************************************************************************
** Record list calls and inject credential-bearing failures or cancellation.
*******************************************************************************/
@Override
public List<StoredObjectInfo> list(String prefix)
{
lists++;
if(failList)
{
throw (new IllegalStateException(credential));
}
if(interruptAfterList)
{
Thread.currentThread().interrupt();
}
return (super.list(prefix));
}
/*******************************************************************************
** Record head calls and inject credential-bearing failures.
*******************************************************************************/
@Override
public Optional<StoredObjectInfo> head(String key)
{
heads++;
if(failHead)
{
throw (new IllegalStateException(credential));
}
return (super.head(key));
}
/*******************************************************************************
** Health probes must not write, even to an unlocked bucket.
*******************************************************************************/
@Override
public OutputStream openWrite(String key, WriteOptions options)
{
throw (new AssertionError("Health probe wrote an object"));
}
/*******************************************************************************
** Health probes must not fetch backup contents.
*******************************************************************************/
@Override
public InputStream openRead(String key)
{
throw (new AssertionError("Health probe read object contents"));
}
/*******************************************************************************
** Health probes must not delete.
*******************************************************************************/
@Override
public DeleteResult deletePermanent(String key)
{
throw (new AssertionError("Health probe deleted an object"));
}
/*******************************************************************************
** Capability diagnostics can be active probes; health must not invoke them.
*******************************************************************************/
@Override
public Set<StorageCapability> capabilities()
{
throw (new AssertionError("Health probe requested capabilities"));
}
}
}
@@ -1,132 +0,0 @@
/*
* Copyright 2026 Kingsrook, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.backups.health;
import java.util.Map;
import com.kingsrook.qbits.backups.VerifyTestSupport;
import com.kingsrook.qbits.backups.model.BackupsTables;
import com.kingsrook.qbits.backups.run.BackupCatalog;
import com.kingsrook.qqq.backend.core.context.QContext;
import com.kingsrook.qqq.backend.core.model.metadata.QInstance;
import com.kingsrook.qqq.backend.core.model.data.QRecord;
import com.kingsrook.qqq.middleware.health.model.metadata.HealthCheckResult;
import com.kingsrook.qqq.middleware.health.model.metadata.HealthStatus;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
/*******************************************************************************
** The health indicator: DOWN only when a critical, active plan is LATE, FAILING or
** MISSING_IN_STORAGE.
*******************************************************************************/
class BackupsHealthIndicatorTest
{
/*******************************************************************************
**
*******************************************************************************/
@BeforeEach
void setUp() throws Exception
{
VerifyTestSupport.setUp(3);
}
/*******************************************************************************
**
*******************************************************************************/
private void setStatus(QRecord plan, String status) throws Exception
{
new BackupCatalog().update(BackupsTables.PLAN, plan.getValueInteger("id"), Map.of("slaStatus", status));
}
/*******************************************************************************
** UP with details when nothing critical is wrong, including a non-critical plan
** that is LATE; DOWN when a critical plan is LATE, FAILING or MISSING_IN_STORAGE.
*******************************************************************************/
@Test
void testUpAndDown() throws Exception
{
BackupsHealthIndicator indicator = new BackupsHealthIndicator();
assertThat(indicator.getName()).isEqualTo("backups");
HealthCheckResult empty = indicator.check(QContext.getQInstance());
assertThat(empty.getStatus()).isEqualTo(HealthStatus.UP);
assertThat(empty.getDetails()).containsEntry("activePlans", 0);
QRecord critical = VerifyTestSupport.plan(Map.of("critical", true));
QRecord ordinary = VerifyTestSupport.plan(Map.of("name", "Other", "planKey", "other"));
VerifyTestSupport.plan(Map.of("name", "Off", "planKey", "off", "isActive", false, "critical", true));
setStatus(critical, "OK");
setStatus(ordinary, "LATE");
HealthCheckResult up = indicator.check(QContext.getQInstance());
assertThat(up.getStatus()).isEqualTo(HealthStatus.UP);
assertThat(up.getDetails()).containsEntry("activePlans", 2).doesNotContainKey("criticalPlansWithProblems");
assertThat(up.getDurationMs()).isNotNull();
for(String status : new String[] { "LATE", "FAILING", "MISSING_IN_STORAGE" })
{
setStatus(critical, status);
HealthCheckResult down = indicator.check(QContext.getQInstance());
assertThat(down.getStatus()).as(status).isEqualTo(HealthStatus.DOWN);
assertThat(down.getDetails().get("criticalPlansWithProblems").toString()).contains("nightly: " + status);
}
setStatus(critical, "UNVERIFIED");
assertThat(indicator.check(QContext.getQInstance()).getStatus()).as("not verified is not down").isEqualTo(HealthStatus.UP);
}
/*******************************************************************************
** On a thread with no QQQ context (a health request) the indicator makes its own
** and cleans up.
*******************************************************************************/
@Test
void testWorksWithoutAContext() throws Exception
{
QInstance qInstance = QContext.getQInstance();
QContext.clear();
try
{
assertThat(new BackupsHealthIndicator().check(qInstance).getStatus()).isEqualTo(HealthStatus.UP);
assertThat(QContext.getQInstance()).isNull();
}
finally
{
QContext.init(qInstance, new com.kingsrook.qqq.backend.core.model.session.QSession());
}
}
/*******************************************************************************
** The indicator's own context runs as the core system user, which token-based
** authentication modules accept without a token.
*******************************************************************************/
@Test
void testOwnContextUsesSystemUserSession()
{
assertThat(BackupsHealthIndicator.systemSession(QContext.getQInstance()))
.isInstanceOf(com.kingsrook.qqq.backend.core.model.session.QSystemUserSession.class);
}
}
@@ -87,10 +87,15 @@ class BackupsMetricsTest
String empty = BackupsMetrics.renderCached();
assertThat(empty).doesNotContain("{instance_name");
VerifyTestSupport.backup(VerifyTestSupport.plan(Map.of()));
VerifyTestSupport.clock.advance(Duration.ofSeconds(30));
assertThat(BackupsMetrics.renderCached()).as("cached").isEqualTo(empty);
assertThat(BackupsMetrics.renderCached()).as("cached").isSameAs(empty);
VerifyTestSupport.clock.advance(Duration.ofSeconds(31));
assertThat(BackupsMetrics.renderCached()).as("expired").isNotSameAs(empty);
/////////////////////////////////////////////////////////////
// a saved plan and a finished run clear the cache at once //
/////////////////////////////////////////////////////////////
VerifyTestSupport.backup(VerifyTestSupport.plan(Map.of()));
assertThat(BackupsMetrics.renderCached()).contains("plan=\"nightly\"");
assertThat(BackupsMetrics.escape("a\"b\\c\nd")).isEqualTo("a\\\"b\\\\c\\nd");
@@ -160,17 +160,35 @@ class BackupPlanValidationTest
/*******************************************************************************
** Including sensitive fields only encrypted needs encryption; client-side
** encryption is refused until a cipher is installed, and then needs a key name.
** With a key provider on the config the key must be one the provider has.
*******************************************************************************/
@Test
void testEncryptionRules() throws Exception
{
assertThat(errors(save(Map.of("sensitiveFieldPolicy", "INCLUDE_ENCRYPTED_ONLY")))).singleElement().asString().contains("requires client-side encryption");
assertThat(errors(save(Map.of("encryptionMode", "CLIENT_AES256_GCM", "encryptionKeyRef", "kek")))).singleElement().asString().contains("not available in this version");
assertThat(errors(save(Map.of("encryptionMode", "CLIENT_AES256_GCM", "encryptionKeyRef", "kek")))).singleElement().asString().contains("no key provider is configured");
assertThat(errors(save(Map.of("sensitiveFieldPolicy", "INCLUDE_ENCRYPTED_ONLY", "encryptionMode", "CLIENT_AES256_GCM", "encryptionKeyRef", "kek")))).hasSize(1);
BackupPlanValidator.setEncryptionAvailable(true);
assertThat(errors(save(Map.of("sensitiveFieldPolicy", "INCLUDE_ENCRYPTED_ONLY", "encryptionMode", "CLIENT_AES256_GCM", "encryptionKeyRef", "kek")))).isEmpty();
assertThat(errors(save(Map.of("encryptionMode", "CLIENT_AES256_GCM")))).singleElement().asString().contains("encryption key reference");
BackupPlanValidator.setEncryptionAvailable(false);
byte[] key = new byte[32];
new java.security.SecureRandom().nextBytes(key);
Map<String, String> env = Map.of("PLAN_TEST_KEK", java.util.Base64.getEncoder().encodeToString(key));
com.kingsrook.qbits.backups.BackupsRuntime.getConfig().withKeyProvider(new com.kingsrook.qqq.backend.core.crypto.EnvKeyProvider(env::get));
try
{
assertThat(errors(save(Map.of("planKey", "with-a-key", "sensitiveFieldPolicy", "INCLUDE_ENCRYPTED_ONLY", "encryptionMode", "CLIENT_AES256_GCM", "encryptionKeyRef", "PLAN_TEST_KEK"))))
.as("the provider has this key").isEmpty();
assertThat(errors(save(Map.of("planKey", "without-a-key", "encryptionMode", "CLIENT_AES256_GCM", "encryptionKeyRef", "NO_SUCH_KEK")))).singleElement().asString()
.contains("No key is available for the encryption key reference NO_SUCH_KEK");
}
finally
{
com.kingsrook.qbits.backups.BackupsRuntime.getConfig().withKeyProvider(null);
}
}
@@ -25,6 +25,7 @@ import java.time.Instant;
import java.util.List;
import java.util.Map;
import java.util.zip.GZIPInputStream;
import com.kingsrook.qbits.backups.alerts.BackupAlerts;
import com.kingsrook.qbits.backups.BackupsRuntime;
import com.kingsrook.qbits.backups.BackupsTestUtils;
import com.kingsrook.qbits.backups.LifecycleTestSupport;
@@ -262,6 +263,92 @@ class LifecycleProcessesTest
/*******************************************************************************
** The daily prune, started the way the scheduler starts it: no plan selected,
** nobody at a review screen. Every plan that is switched on is pruned to its
** retention (a plan that is switched off is left alone), so old backups do not
** pile up for ever.
*******************************************************************************/
@Test
void testTheScheduledPrunePrunesEveryActivePlanWithNobodyThere() throws Exception
{
QRecord plan = LifecycleTestSupport.plan(Map.of("retainDaily", 2, "retainWeekly", 0, "retainMonthly", 0, "retainYearly", 0, "retainMinimum", 0));
QRecord off = LifecycleTestSupport.plan(Map.of("name", "Switched off", "planKey", "switched-off", "prefix", "switched-off", "retainDaily", 1, "retainWeekly", 0, "retainMonthly", 0,
"retainYearly", 0, "retainMinimum", 0));
BackupRunResult first = null;
BackupRunResult firstOff = null;
for(int day = 1; day <= 4; day++)
{
clock.set(DAY_1.plus(Duration.ofDays(day - 1)));
BackupRunResult result = new BackupRunCoordinator().runPlan(plan, "SCHEDULED");
first = first == null ? result : first;
BackupRunResult other = new BackupRunCoordinator().runPlan(off, "SCHEDULED");
firstOff = firstOff == null ? other : firstOff;
}
new com.kingsrook.qqq.backend.core.actions.tables.UpdateAction().execute(new com.kingsrook.qqq.backend.core.model.actions.tables.update.UpdateInput(BackupsTables.PLAN)
.withRecord(new QRecord().withValue("id", off.getValueInteger("id")).withValue("isActive", false)));
assertThat(BackupsTestUtils.BACKUPS.list(first.getRunPrefix())).as("the oldest run is there before the prune").isNotEmpty();
var instance = com.kingsrook.qqq.backend.core.context.QContext.getQInstance();
String scheduled = com.kingsrook.qbits.backups.schedule.BackupScheduledPruneProcess.NAME;
assertThat(instance.getProcess(PruneProcess.NAME).getSchedule()).as("the action a person runs is not what the schedule runs: it needs plans selected and a review").isNull();
assertThat(instance.getProcess(scheduled)).as("the process the schedule runs").isNotNull();
assertThat(instance.getProcess(scheduled).getIsHidden()).isTrue();
var session = com.kingsrook.qqq.backend.core.context.QContext.getQSession();
com.kingsrook.qqq.backend.core.scheduler.SchedulerUtils.runProcess(instance, () -> session, instance.getProcess(scheduled), null, new java.util.HashMap<>());
com.kingsrook.qqq.backend.core.context.QContext.init(instance, session);
assertThat(BackupsTestUtils.BACKUPS.list(first.getRunPrefix())).as("the oldest run of the plan that is on was deleted").isEmpty();
assertThat(new BackupCatalog().where(BackupsTables.RUN, "backupPlanId", plan.getValueInteger("id")).stream().filter(run -> !"PRUNED".equals(run.getValueString("status")) && run.getValue("prunedDate") == null))
.as("two daily backups are kept").hasSize(2);
assertThat(BackupsTestUtils.BACKUPS.list(firstOff.getRunPrefix())).as("a plan that is switched off is not pruned by the schedule").isNotEmpty();
}
/*******************************************************************************
** With a scheduler on the config the daily prune is scheduled, once a day, and
** the action a person runs is not. A plan whose storage has gone away does
** not stop the others, and raises an alert that its next good prune resolves.
*******************************************************************************/
@Test
void testTheScheduledPruneIsOnTheSchedulerAndOnePlansTroubleDoesNotStopTheOthers() throws Exception
{
var config = new com.kingsrook.qbits.backups.BackupsQBitConfig().withSchedulerName("testScheduler");
var meta = com.kingsrook.qbits.backups.schedule.BackupScheduledPruneProcess.processMetaData(config);
assertThat(meta.getSchedule()).isNotNull();
assertThat(meta.getSchedule().getRepeatSeconds()).isEqualTo(24 * 3600);
assertThat(meta.getSchedule().getSchedulerName()).isEqualTo("testScheduler");
assertThat(com.kingsrook.qbits.backups.schedule.BackupScheduledPruneProcess.processMetaData(new com.kingsrook.qbits.backups.BackupsQBitConfig()).getSchedule())
.as("no scheduler, no schedule").isNull();
QRecord good = LifecycleTestSupport.plan(Map.of("retainDaily", 1, "retainWeekly", 0, "retainMonthly", 0, "retainYearly", 0, "retainMinimum", 0));
QRecord bad = LifecycleTestSupport.plan(Map.of("name", "Storage gone", "planKey", "storage-gone", "prefix", "storage-gone", "storageBucketAlias", "media"));
BackupRunResult first = null;
for(int day = 1; day <= 3; day++)
{
clock.set(DAY_1.plus(Duration.ofDays(day - 1)));
BackupRunResult result = new BackupRunCoordinator().runPlan(good, "SCHEDULED");
first = first == null ? result : first;
}
BackupsRuntime.getConfig().withStorageResolver(alias -> "backups".equals(alias) ? BackupsTestUtils.BACKUPS : null);
var sink = new com.kingsrook.qbits.backups.RecordingAlertSink();
BackupsRuntime.setAlertSink(sink);
var output = new com.kingsrook.qqq.backend.core.model.actions.processes.RunBackendStepOutput();
new com.kingsrook.qbits.backups.schedule.BackupScheduledPruneProcess().run(new com.kingsrook.qqq.backend.core.model.actions.processes.RunBackendStepInput(), output);
assertThat(output.getValueInteger("plansPruned")).isEqualTo(1);
assertThat(output.getValueInteger("plansFailed")).isEqualTo(1);
assertThat(output.getValueInteger("runsDeleted")).isEqualTo(2);
assertThat(BackupsTestUtils.BACKUPS.list(first.getRunPrefix())).as("the plan that could be pruned was").isEmpty();
assertThat(bad.getValueString("planKey")).isEqualTo("storage-gone");
assertThat(sink.open.values()).as("the plan that could not be pruned says so").anyMatch(alert -> BackupAlerts.PRUNE_FAILED.equals(alert.type()) && alert.dedupeKey().contains("storage-gone"));
assertThat(sink.open.values()).as("and only that plan").noneMatch(alert -> BackupAlerts.PRUNE_FAILED.equals(alert.type()) && alert.dedupeKey().contains("nightly"));
}
/*******************************************************************************
** The run table action prunes the plans of the selected runs, once each.
*******************************************************************************/
@@ -317,6 +317,63 @@ class BackupPrunerTest
/*******************************************************************************
** A storage that lists objects without their modification times (a listing
** through the object-storage qbit did, for every real bucket) used to make the
** pruner throw as soon as a plan had one unfinished backup, so that plan was
** never pruned again. The run's own record dates the debris: it is deleted when
** the run ended more than 7 days ago, kept before, and a prefix with no times
** and no run record is never deleted as old.
*******************************************************************************/
@Test
void testDebrisIsDatedByItsRunWhenTheStorageListsNoTimes() throws Exception
{
QRecord plan = plan(7, Map.of());
BackupsTestUtils.BACKUPS.withFailWritesFor(key -> key.contains("/tables/blogPost/"));
BackupRunResult failed = new BackupRunCoordinator().runPlan(plan, "SCHEDULED");
BackupsTestUtils.BACKUPS.withFailWritesFor(null);
assertThat(failed.getStatus()).isEqualTo("FAILED");
runOnDay(plan, 6);
com.kingsrook.qbits.backups.storage.BackupStorage noTimes = (com.kingsrook.qbits.backups.storage.BackupStorage) java.lang.reflect.Proxy.newProxyInstance(
getClass().getClassLoader(), new Class<?>[] { com.kingsrook.qbits.backups.storage.BackupStorage.class }, (proxy, method, args) ->
{
try
{
Object answer = method.invoke(BackupsTestUtils.BACKUPS, args);
if("list".equals(method.getName()))
{
List<StoredObjectInfo> listed = new java.util.ArrayList<>();
for(Object each : (List<?>) answer)
{
StoredObjectInfo object = (StoredObjectInfo) each;
listed.add(new StoredObjectInfo(object.key(), object.size(), null, object.metadata(), object.lockedUntil()));
}
return (listed);
}
return (answer);
}
catch(java.lang.reflect.InvocationTargetException e)
{
throw (e.getCause());
}
});
BackupsRuntime.getConfig().withStorageResolver(alias -> "backups".equals(alias) ? noTimes : BackupsTestUtils.MEDIA);
clock.set(DAY_1.plus(Duration.ofDays(6)));
assertThat(new BackupPruner().plan(plan).debris()).as("6 days after the run ended it is not debris yet").isEmpty();
clock.set(DAY_1.plus(Duration.ofDays(8)));
BackupPruner.Outcome outcome = new BackupPruner().prune(plan, "tester");
assertThat(outcome.debrisPrefixesDeleted()).isEqualTo(1);
assertThat(BackupsTestUtils.BACKUPS.list(failed.getRunPrefix())).isEmpty();
Instant now = DAY_1.plus(Duration.ofDays(30));
assertThat(BackupPruner.newestOf(List.of(new StoredObjectInfo("orphan/part", 1, null, Map.of(), null)), null, now)).as("no times and no run record: not old").isEqualTo(now);
}
/*******************************************************************************
** The prefix of a run that never got a manifest is debris once its newest object
** is older than 7 days, and not before.
@@ -175,6 +175,47 @@ class RestoreModesTest
/*******************************************************************************
** A restore from an encrypted backup, with the key provider of the config and
** nothing else set up: the edited rows are rolled back, and the file that was
** removed comes back as it was although its copy in the backup is ciphertext.
** Without the key the restore is refused before anything is read or written.
*******************************************************************************/
@Test
void testRestoreFromAnEncryptedBackup() throws Exception
{
java.util.Map<String, String> env = new java.util.HashMap<>();
byte[] key = new byte[32];
new java.security.SecureRandom().nextBytes(key);
env.put("RESTORE_TEST_KEK", java.util.Base64.getEncoder().encodeToString(key));
com.kingsrook.qbits.backups.BackupsRuntime.getConfig().withKeyProvider(new com.kingsrook.qqq.backend.core.crypto.EnvKeyProvider(env::get));
BackupRunResult run = RestoreTestSupport.backup(Map.of("encryptionMode", "CLIENT_AES256_GCM", "encryptionKeyRef", "RESTORE_TEST_KEK", "sensitiveFieldPolicy", "INCLUDE_ENCRYPTED_ONLY"));
assertThat(RestoreTestSupport.manifest(run).encryption().mode()).isEqualTo("CLIENT_AES256_GCM");
assertThat(RestoreTestSupport.manifest(run).encryption().keyFingerprint()).startsWith("v1:");
assertThat(BackupsTestUtils.BACKUPS.list("").stream().filter(o -> o.key().contains("_files/sha256/")).map(o -> new String(BackupsTestUtils.BACKUPS.getBytes(o.key()))))
.as("the copies of the files are ciphertext too").isNotEmpty().noneMatch(content -> content.contains("photo bytes"));
byte[] index = BackupsTestUtils.BACKUPS.list("").stream().filter(o -> o.key().endsWith("files/index-00001.jsonl.gz")).map(o -> BackupsTestUtils.BACKUPS.getBytes(o.key())).findFirst().orElseThrow();
assertThat(new String(index, 0, 4, java.nio.charset.StandardCharsets.US_ASCII)).as("the file index names record keys and where files came from: it is encrypted too").isEqualTo("QSC1");
RestoreTestSupport.mutate();
BackupsTestUtils.MEDIA.removeIgnoringLock("media/photo-1.jpg");
RestoreOutcome outcome = new RestoreEngine().execute(RestoreTestSupport.request(run, RestoreRequest.MODE_UPSERT, "blogPost"));
assertThat(outcome.getErrors()).isEmpty();
assertThat(outcome.getTables().get("blogPost").getUpdated()).isEqualTo(10);
assertThat(outcome.getTables().get("blogPost").getFilesRestored()).isEqualTo(1);
assertThat(RestoreTestSupport.rows("blogPost").stream().filter(r -> r.getValueInteger("id") == 15).findFirst().orElseThrow().getValueString("title")).isEqualTo("Post 15");
assertThat(new String(BackupsTestUtils.MEDIA.getBytes("media/photo-1.jpg"))).isEqualTo("photo bytes 1");
env.clear();
RestoreOutcome refused = new RestoreEngine().review(RestoreTestSupport.request(run, RestoreRequest.MODE_UPSERT, "blogPost"));
assertThat(refused.getErrors()).singleElement().asString().contains("This backup is encrypted (key RESTORE_TEST_KEK), and no key provider is available to restore it");
assertThat(refused.getTables()).as("nothing was read").isEmpty();
}
/*******************************************************************************
** REPLACE needs the typed confirmation, deletes what is not in the backup, takes a
** pre-restore backup first, brings the table back to exactly the backed up rows
@@ -29,6 +29,8 @@ import com.kingsrook.qbits.backups.manifest.BackupManifest;
import com.kingsrook.qbits.backups.model.BackupsTables;
import com.kingsrook.qbits.backups.scope.PlanSettings;
import com.kingsrook.qbits.backups.scope.ScopeResolver;
import com.kingsrook.qbits.backups.scope.TableRole;
import com.kingsrook.qbits.backups.scope.TableRoles;
import com.kingsrook.qqq.backend.core.actions.async.AsyncJobCallback;
import com.kingsrook.qqq.backend.core.context.QContext;
import com.kingsrook.qqq.backend.core.jobs.plans.JobChunkScope;
@@ -37,6 +39,11 @@ import com.kingsrook.qqq.backend.core.jobs.progress.JobLogLevel;
import com.kingsrook.qqq.backend.core.jobs.progress.JobPhase;
import com.kingsrook.qqq.backend.core.jobs.progress.JobProgress;
import com.kingsrook.qqq.backend.core.model.data.QRecord;
import com.kingsrook.qqq.backend.core.model.metadata.QBackendMetaData;
import com.kingsrook.qqq.backend.core.model.metadata.QInstance;
import com.kingsrook.qqq.backend.core.model.metadata.fields.QFieldMetaData;
import com.kingsrook.qqq.backend.core.model.metadata.fields.QFieldType;
import com.kingsrook.qqq.backend.core.model.metadata.tables.QTableMetaData;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
@@ -230,6 +237,38 @@ class BackupEngineTest
/*******************************************************************************
** A table on a backend with no query interface (a storage-only module, like
** qbit-edi's edi_preview_download) is left out of the scope, even when it is
** selected by name, and the run succeeds. Before the fix the reader queried it
** and the run FAILED with "Query is not implemented in this module".
*******************************************************************************/
@Test
void testUnqueryableTableIsExcluded() throws Exception
{
QInstance qInstance = QContext.getQInstance();
qInstance.addBackend(new QBackendMetaData().withName("storageOnly").withBackendType(StorageOnlyBackendModule.class));
qInstance.addTable(new QTableMetaData().withName("previewDownload").withBackendName("storageOnly").withPrimaryKeyField("id")
.withField(new QFieldMetaData("id", QFieldType.INTEGER)));
BackupRunResult result = run(plan(Map.of()));
assertThat(result.getErrorMessage()).isNull();
assertThat(result.getStatus()).isEqualTo("SUCCEEDED_WITH_WARNINGS");
BackupManifest manifest = BackupManifest.read(BackupsTestUtils.BACKUPS.getBytes(result.getManifestKey()));
assertThat(manifest.table("previewDownload")).isNull();
assertThat(manifest.table("blogPost")).isNotNull();
assertThat(TableRoles.roleOf(qInstance, qInstance.getTable("previewDownload"))).isEqualTo(TableRole.EXTERNAL);
assertThat(TableRoles.isQueryable(qInstance, qInstance.getTable("blogPost"))).isTrue();
ScopeResolver.ResolvedScope scope = new ScopeResolver(qInstance).resolve(PlanSettings.adHoc().with("scopeType", "TABLES").with("includeRoles", "DATA,EXTERNAL"),
List.of(new ScopeResolver.ScopeRule(true, "TABLE", "previewDownload", null, false, null), new ScopeResolver.ScopeRule(true, "ROLE", "EXTERNAL", null, false, null)));
assertThat(scope.names()).doesNotContain("previewDownload");
assertThat(scope.excluded()).contains(new ScopeResolver.ExcludedTable("previewDownload", ScopeResolver.NOT_QUERYABLE));
}
/*******************************************************************************
** Required snapshots fail before anything is written (no backend can open one yet).
*******************************************************************************/
@@ -352,13 +391,14 @@ class BackupEngineTest
BackupRunRequest request = BackupRunFactory.forPlan(plan(Map.of()), "MANUAL").withProgress(progress)
.withReader((table, filter, start, size, transaction, sink) ->
{
throw (new com.kingsrook.qqq.backend.core.exceptions.QException("https://storage-user:storage-password@host/?secret=storage-secret accessKey=storage-access row=private-row"));
throw (new com.kingsrook.qqq.backend.core.exceptions.QException("https://storage-user:storage-password@host/?secret=storage-secret accessKey=storage-access Detail: Key (email)=(private-row) already exists."));
});
BackupRunResult result = new BackupEngine().execute(request);
assertThat(result.getStatus()).isEqualTo("FAILED");
assertThat(progress.logs).contains("ERROR:" + result.getErrorMessage());
assertThat(progress.getSnapshot().getPhases()).anyMatch(p -> p.getStatus() == JobPhase.Status.FAILED);
assertThat(String.join("\n", progress.logs) + result.getErrorMessage()).doesNotContain("storage-user", "storage-password", "storage-secret", "storage-access", "private-row", "https://");
assertThat(result.getErrorMessage()).startsWith("Backup failed: QException: https://[REDACTED]@host/");
assertThat(String.join("\n", progress.logs) + result.getErrorMessage() + result.getErrorDetail()).doesNotContain("storage-user", "storage-password", "storage-secret", "storage-access", "private-row");
}
@@ -408,7 +448,52 @@ class BackupEngineTest
BackupRunResult result = new BackupEngine().execute(BackupRunFactory.forPlan(plan(Map.of()), "MANUAL").withProgress(progress).withStorage(storage));
assertThat(result.getStatus()).isEqualTo("FAILED");
assertThat(progress.logs).contains("ERROR:" + result.getErrorMessage());
assertThat(String.join("\n", progress.logs) + result.getErrorMessage()).doesNotContain("endpoint-user", "endpoint-password", "access-secret", "secret-secret", "https://");
assertThat(String.join("\n", progress.logs) + result.getErrorMessage() + result.getErrorDetail()).doesNotContain("endpoint-user", "endpoint-password", "access-secret", "secret-secret");
}
/*******************************************************************************
** A failed put records what an operator needs on the run row, with no secrets:
** error_message is "Backup failed: Class: message" and error_detail has the
** class, the cause chain and the root cause frames; the presigned signature,
** the access key id and the URL user-info are redacted, the object key is kept.
*******************************************************************************/
@Test
void testFailedPutRecordsSanitizedMessageAndDetail() throws Exception
{
var storage = new com.kingsrook.qbits.backups.storage.InMemoryBackupStorage()
{
/*******************************************************************************
** A MinIO-style failure with a presigned URL in the message.
*******************************************************************************/
@Override
public java.io.OutputStream openWrite(String key, com.kingsrook.qbits.backups.storage.WriteOptions options)
{
throw (new com.kingsrook.qbits.backups.storage.BackupStorageException(com.kingsrook.qbits.backups.storage.BackupStorageException.Reason.ACCESS_DENIED,
"AccessDenied on PUT https://minio-user:minio-pass@minio.galaxy.lan/kof22-backups/" + key
+ "?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAIOSFODNN7EXAMPLE%2F20261016%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Signature=deadbeefcafe0123",
new IOException("XMinioStorageFull: Storage backend has reached its minimum free drive threshold. Authorization: AWS4-HMAC-SHA256 Credential=AKIAIOSFODNN7EXAMPLE/x, Signature=feedface")));
}
};
BackupRunResult result = new BackupEngine().execute(BackupRunFactory.forPlan(plan(Map.of()), "MANUAL").withStorage(storage));
assertThat(result.getStatus()).isEqualTo("FAILED");
QRecord run = new BackupCatalog().get(BackupsTables.RUN, result.getRunId()).orElseThrow();
String message = run.getValueString("errorMessage");
String detail = run.getValueString("errorDetail");
assertThat(message).isEqualTo(result.getErrorMessage());
assertThat(detail).isEqualTo(result.getErrorDetail());
assertThat(message).startsWith("Backup failed: BackupStorageException: AccessDenied on PUT https://[REDACTED]@minio.galaxy.lan/kof22-backups/qqq-backups/testapp/nightly/")
.doesNotContain("see server logs");
assertThat(detail).startsWith("com.kingsrook.qbits.backups.storage.BackupStorageException: AccessDenied on PUT")
.contains("\nCaused by: java.io.IOException: XMinioStorageFull: Storage backend has reached its minimum free drive threshold.")
.contains("X-Amz-Signature=[REDACTED]")
.contains("Root cause stack (top ")
.contains("\tat ");
assertThat(detail.length()).isLessThanOrEqualTo(FailureText.MAX_DETAIL_CHARS);
assertThat(message + detail).doesNotContain("deadbeefcafe0123", "AKIAIOSFODNN7EXAMPLE", "minio-user", "minio-pass", "feedface");
}
@@ -0,0 +1,186 @@
/*
* Copyright 2026 Kingsrook, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.backups.run;
import java.io.IOException;
import java.sql.SQLException;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
/*******************************************************************************
** Unit tests of the failure text sanitizer, summary and detail.
*******************************************************************************/
class FailureTextTest
{
/*******************************************************************************
** Null and plain text pass through; object keys and bucket names are kept.
*******************************************************************************/
@Test
void testPlainTextIsKept()
{
assertThat(FailureText.sanitize(null)).isNull();
String plain = "Query is not implemented in this module: PreviewDownloadBackend (bucket kof22-backups, key qqq-backups/kof22/nightly/2026/10/16/run/tables/a/part-00001.jsonl.gz)";
assertThat(FailureText.sanitize(plain)).isEqualTo(plain);
assertThat(FailureText.sanitize("objectKey=qqq-backups/x/y.gz bucket=kof22-backups")).isEqualTo("objectKey=qqq-backups/x/y.gz bucket=kof22-backups");
}
/*******************************************************************************
** URL user-info and presigned query parameters are redacted; host and path kept.
*******************************************************************************/
@Test
void testUrls()
{
assertThat(FailureText.sanitize("PUT https://user:pass@minio.lan/bucket/a/b.gz?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAIOSFODNN7EXAMPLE%2Fx&X-Amz-Signature=abc123&partNumber=2 failed"))
.isEqualTo("PUT https://[REDACTED]@minio.lan/bucket/a/b.gz?X-Amz-Algorithm=[REDACTED]&X-Amz-Credential=[REDACTED]&X-Amz-Signature=[REDACTED]&partNumber=2 failed");
assertThat(FailureText.sanitize("jdbc:postgresql://app:hunter2@db:5432/app")).isEqualTo("jdbc:postgresql://[REDACTED]@db:5432/app");
assertThat(FailureText.sanitize("https://h/p?Signature=s1&Expires=1&AWSAccessKeyId=k&access_token=t&key=v"))
.isEqualTo("https://h/p?Signature=[REDACTED]&Expires=1&AWSAccessKeyId=[REDACTED]&access_token=[REDACTED]&key=[REDACTED]");
}
/*******************************************************************************
** key=value and JSON secrets, Authorization and Bearer values.
*******************************************************************************/
@Test
void testAssignmentsAndHeaders()
{
assertThat(FailureText.sanitize("password=p1 secret=\"s 2\" token='t3' key=k4 accessKey=a5 secretKey=s6 apiKey=x7 db.password = p8, other=ok"))
.isEqualTo("password=[REDACTED] secret=[REDACTED] token=[REDACTED] key=[REDACTED] accessKey=[REDACTED] secretKey=[REDACTED] apiKey=[REDACTED] db.password = [REDACTED], other=ok");
assertThat(FailureText.sanitize("{\"clientSecret\": \"abc\", \"name\": \"keep\"}")).isEqualTo("{\"clientSecret\": \"[REDACTED]\", \"name\": \"keep\"}");
assertThat(FailureText.sanitize("Authorization: Bearer eyJhbGciOi.payload.sig\nnext line")).isEqualTo("Authorization: [REDACTED]\nnext line");
assertThat(FailureText.sanitize("sent Bearer abcdefghijk to the API")).isEqualTo("sent Bearer [REDACTED] to the API");
assertThat(FailureText.sanitize("id AKIAIOSFODNN7EXAMPLE and ASIAIOSFODNN7EXAMPLE")).isEqualTo("id [REDACTED] and [REDACTED]");
}
/*******************************************************************************
** PEM blocks (terminated or not) and Postgres row values.
*******************************************************************************/
@Test
void testPemAndRowValues()
{
assertThat(FailureText.sanitize("bad key -----BEGIN PRIVATE KEY-----\nMIIabc\n-----END PRIVATE KEY----- here")).isEqualTo("bad key [REDACTED PEM] here");
assertThat(FailureText.sanitize("cut -----BEGIN RSA PRIVATE KEY-----\nMIIabc")).isEqualTo("cut [REDACTED PEM]");
assertThat(FailureText.sanitize("duplicate key value violates unique constraint \"u_email\" Key (email)=(ada@example.com) already exists."))
.isEqualTo("duplicate key value violates unique constraint \"u_email\" Key (email)=([REDACTED]) already exists.");
assertThat(FailureText.sanitize("ERROR: null value in column \"x\"\n Detail: Failing row contains (1, ada, secret-row).\n Where: x"))
.isEqualTo("ERROR: null value in column \"x\"\n Detail: [REDACTED]\n Where: x");
}
/*******************************************************************************
** The summary is short, sanitized and bounded; no message falls back to the class.
*******************************************************************************/
@Test
void testSummary()
{
assertThat(FailureText.summary(new IllegalStateException("Query is not implemented in this module: PreviewDownloadBackend")))
.isEqualTo("Backup failed: IllegalStateException: Query is not implemented in this module: PreviewDownloadBackend");
assertThat(FailureText.summary(new NullPointerException())).isEqualTo("Backup failed: NullPointerException");
assertThat(FailureText.summary("Could not create the run record", new IOException(" password=x "))).isEqualTo("Could not create the run record: IOException: password=[REDACTED]");
assertThat(FailureText.summary(new IOException("x".repeat(2000)))).hasSize("Backup failed: IOException: ".length() + FailureText.MAX_SUMMARY_MESSAGE_CHARS + 3);
}
/*******************************************************************************
** The detail has the class, the cause chain and the root cause frames, bounded.
*******************************************************************************/
@Test
void testDetail()
{
SQLException root = new SQLException("Key (id)=(4242xyz) already exists.");
IOException middle = new IOException("write failed password=pwsecret", root);
RuntimeException top = new RuntimeException("Backup of t failed", middle);
String detail = FailureText.detail(top);
assertThat(detail).startsWith("java.lang.RuntimeException: Backup of t failed\nCaused by: java.io.IOException: write failed password=[REDACTED]\nCaused by: java.sql.SQLException: Key (id)=([REDACTED]) already exists.\nRoot cause stack (top ");
assertThat(detail).contains("\tat com.kingsrook.qbits.backups.run.FailureTextTest.testDetail(FailureTextTest.java:");
assertThat(detail.split("\n\tat ")).hasSize(FailureText.ROOT_CAUSE_FRAMES + 1);
assertThat(detail).doesNotContain("4242xyz", "pwsecret");
IOException noFrames = new IOException((String) null);
noFrames.setStackTrace(new StackTraceElement[0]);
assertThat(FailureText.detail(noFrames)).isEqualTo("java.io.IOException");
String huge = FailureText.detail(new IOException("y".repeat(20_000)));
assertThat(huge).hasSize(FailureText.MAX_DETAIL_CHARS).endsWith("... (truncated)");
}
/*******************************************************************************
** A cause cycle does not loop.
*******************************************************************************/
@Test
void testCauseCycle()
{
CyclicException a = new CyclicException("a");
CyclicException b = new CyclicException("b");
a.setCause(b);
b.setCause(a);
assertThat(FailureText.detail(a)).startsWith("com.kingsrook.qbits.backups.run.FailureTextTest$CyclicException: a\nCaused by: com.kingsrook.qbits.backups.run.FailureTextTest$CyclicException: b\nRoot cause stack");
}
/***************************************************************************
** An exception whose cause can be set to form a cycle.
***************************************************************************/
private static class CyclicException extends Exception
{
private Throwable cause;
/*******************************************************************************
** Constructor.
*******************************************************************************/
CyclicException(String message)
{
super(message);
}
/*******************************************************************************
** Set the cause.
*******************************************************************************/
void setCause(Throwable cause)
{
this.cause = cause;
}
/*******************************************************************************
** The cause.
*******************************************************************************/
@Override
public synchronized Throwable getCause()
{
return (cause);
}
}
}
@@ -0,0 +1,86 @@
/*
* Copyright 2026 Kingsrook, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.backups.run;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import com.kingsrook.qqq.backend.core.actions.interfaces.QStorageInterface;
import com.kingsrook.qqq.backend.core.model.actions.tables.storage.StorageInput;
import com.kingsrook.qqq.backend.core.modules.backend.QBackendModuleDispatcher;
import com.kingsrook.qqq.backend.core.modules.backend.QBackendModuleInterface;
/*******************************************************************************
** A storage-only backend module (like qbit-edi's PreviewDownloadBackend): it
** streams objects but has no query interface, so a table on it cannot be read.
*******************************************************************************/
public class StorageOnlyBackendModule implements QBackendModuleInterface, QStorageInterface
{
public static final String TYPE = "test-storage-only";
static
{
QBackendModuleDispatcher.registerBackendModule(new StorageOnlyBackendModule());
}
/*******************************************************************************
** The backend type.
*******************************************************************************/
@Override
public String getBackendType()
{
return (TYPE);
}
/*******************************************************************************
** Storage only.
*******************************************************************************/
@Override
public QStorageInterface getStorageInterface()
{
return (this);
}
/*******************************************************************************
** Nothing is stored.
*******************************************************************************/
@Override
public InputStream getInputStream(StorageInput input)
{
return (new ByteArrayInputStream(new byte[0]));
}
/*******************************************************************************
** Writes are discarded.
*******************************************************************************/
@Override
public OutputStream createOutputStream(StorageInput input)
{
return (new ByteArrayOutputStream());
}
}
@@ -0,0 +1,211 @@
/*
* Copyright 2026 Kingsrook, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.backups.schedule;
import java.time.Duration;
import java.time.Instant;
import java.util.List;
import java.util.Map;
import com.kingsrook.qbits.backups.BackupsQBitConfig;
import com.kingsrook.qbits.backups.BackupsTestUtils;
import com.kingsrook.qbits.backups.VerifyTestSupport;
import com.kingsrook.qbits.backups.model.BackupsTables;
import com.kingsrook.qbits.backups.run.BackupCatalog;
import com.kingsrook.qqq.backend.core.context.QContext;
import com.kingsrook.qqq.backend.core.model.actions.processes.RunBackendStepInput;
import com.kingsrook.qqq.backend.core.model.actions.processes.RunBackendStepOutput;
import com.kingsrook.qqq.backend.core.model.data.QRecord;
import com.kingsrook.qqq.backend.core.model.scheduledjobs.ScheduledJobsMetaDataProvider;
import com.kingsrook.qqq.backend.core.model.session.QSession;
import com.kingsrook.qqq.backend.core.model.session.QSystemUserSession;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
/*******************************************************************************
** Plans run on their own schedule in an application that has no scheduled-jobs
** table: the qbit starts what is due, once, and nothing that is not.
*******************************************************************************/
class BackupDuePlansProcessTest
{
private static final Map<String, java.io.Serializable> NIGHTLY = Map.of("cronExpression", "0 0 2 * * ?", "cronTimeZoneId", "UTC", "ownerUserId", "jmaes");
/*******************************************************************************
** An application with the qbit and no scheduled-jobs table, a clock that can be
** moved, and the scheduler's session.
*******************************************************************************/
@BeforeEach
void setUp() throws Exception
{
VerifyTestSupport.setUp(5);
QContext.setQSession(new QSystemUserSession());
}
/*******************************************************************************
**
*******************************************************************************/
private static RunBackendStepOutput tick() throws Exception
{
RunBackendStepOutput output = new RunBackendStepOutput();
new BackupDuePlansProcess().run(new RunBackendStepInput(), output);
return (output);
}
/*******************************************************************************
**
*******************************************************************************/
private static List<QRecord> runsOf(QRecord plan) throws Exception
{
return (new BackupCatalog().where(BackupsTables.RUN, "backupPlanId", plan.getValueInteger("id")));
}
/*******************************************************************************
** A cron is due when it has a time after the last start that is not after now,
** in the plan's zone. A cron or a zone that is not one fails; it is not guessed.
*******************************************************************************/
@Test
void testDueTimesRespectZonesAndMissedTimesCollapse() throws Exception
{
Instant since = Instant.parse("2026-11-04T00:00:00Z");
assertThat(BackupDuePlansProcess.isDue("0 0 8 * * ?", "America/Chicago", since, Instant.parse("2026-11-04T13:59:59Z"))).isFalse();
assertThat(BackupDuePlansProcess.isDue("0 0 8 * * ?", "America/Chicago", since, Instant.parse("2026-11-04T14:00:00Z"))).isTrue();
assertThat(BackupDuePlansProcess.isDue("0 0 8 * * ?", "UTC", since, since.plusSeconds(172800))).as("two missed nights are one due time").isTrue();
assertThat(BackupDuePlansProcess.isDue("0 0 8 * * ?", null, since, Instant.parse("2026-11-04T08:00:00Z"))).as("no zone is UTC").isTrue();
assertThat(BackupDuePlansProcess.isDue(null, "UTC", since, since.plusSeconds(172800))).as("a plan with no cron is run by hand only").isFalse();
assertThat(BackupDuePlansProcess.isDue("0 * * * * ?", "UTC", since, since)).isFalse();
assertThat(BackupDuePlansProcess.isDue("0 * * * * ?", "UTC", null, since)).isFalse();
assertThatThrownBy(() -> BackupDuePlansProcess.isDue("invalid", "UTC", since, since)).isInstanceOf(java.text.ParseException.class);
assertThatThrownBy(() -> BackupDuePlansProcess.isDue("0 * * * * ?", "Fake/Zone", since, since)).isInstanceOf(java.time.DateTimeException.class);
}
/*******************************************************************************
** Only the scheduler starts plans: a person's request is refused.
*******************************************************************************/
@Test
void testAPersonCannotRunIt() throws Exception
{
QContext.setQSession(new QSession().withPermissions("backups.admin"));
assertThatThrownBy(BackupDuePlansProcessTest::tick).hasMessageContaining("started by the scheduler");
}
/*******************************************************************************
** A plan that is on and has a cron is started when its time has come, once: not
** before, not again in the next minute, and once for several missed nights. A
** plan that is off, and a plan with no cron, are never started.
*******************************************************************************/
@Test
void testADuePlanIsStartedOnceAndOthersAreNot() throws Exception
{
QRecord nightly = VerifyTestSupport.plan(NIGHTLY);
QRecord off = VerifyTestSupport.plan(Map.of("name", "Off", "planKey", "off", "prefix", "off", "isActive", false, "cronExpression", "0 0 2 * * ?", "cronTimeZoneId", "UTC", "ownerUserId", "jmaes"));
QRecord byHand = VerifyTestSupport.plan(Map.of("name", "By hand", "planKey", "by-hand", "prefix", "by-hand", "ownerUserId", "jmaes"));
assertThat(tick().getValueInteger("backupsStarted")).as("created just now: its first time has not come").isZero();
assertThat(runsOf(nightly)).isEmpty();
VerifyTestSupport.clock.advance(Duration.ofDays(1));
RunBackendStepOutput first = tick();
assertThat(first.getValueString("startedBy")).isEqualTo("plans");
assertThat(first.getValueInteger("backupsStarted")).isEqualTo(1);
assertThat(runsOf(nightly)).singleElement().satisfies(run ->
{
assertThat(run.getValueString("trigger")).isEqualTo("SCHEDULED");
assertThat(run.getValueString("requestedByUserId")).isEqualTo("system:scheduler");
assertThat(run.getValueString("status")).startsWith("SUCCEEDED");
});
VerifyTestSupport.clock.advance(Duration.ofMinutes(1));
assertThat(tick().getValueInteger("backupsStarted")).as("a minute later it is not due again").isZero();
VerifyTestSupport.clock.advance(Duration.ofDays(3));
assertThat(tick().getValueInteger("backupsStarted")).as("three missed nights are one run").isEqualTo(1);
assertThat(runsOf(nightly)).hasSize(2);
assertThat(runsOf(off)).as("a plan that is switched off").isEmpty();
assertThat(runsOf(byHand)).as("a plan with no cron").isEmpty();
}
/*******************************************************************************
** The verification cron is started the same way, after the plan has a backup.
*******************************************************************************/
@Test
void testADueVerificationIsStarted() throws Exception
{
QRecord plan = VerifyTestSupport.plan(Map.of("cronExpression", "0 0 2 * * ?", "verifyCronExpression", "0 0 4 * * ?", "cronTimeZoneId", "UTC", "ownerUserId", "jmaes"));
VerifyTestSupport.clock.advance(Duration.ofDays(1));
RunBackendStepOutput output = tick();
assertThat(output.getValueInteger("backupsStarted")).isEqualTo(1);
assertThat(output.getValueInteger("verificationsStarted")).isEqualTo(1);
assertThat(new BackupCatalog().where(BackupsTables.VERIFICATION, "backupRunId", runsOf(plan).get(0).getValueInteger("id"))).as("the run was verified").isNotEmpty();
assertThat(VerifyTestSupport.reload(plan).getValueInstant("lastVerifiedDate")).isNotNull();
VerifyTestSupport.clock.advance(Duration.ofMinutes(1));
assertThat(tick().getValueInteger("verificationsStarted")).as("a minute later it is not due again").isZero();
}
/*******************************************************************************
** Where the application has the scheduled-jobs table, its scheduled jobs start
** the plans, and this process starts nothing: no backup runs twice.
*******************************************************************************/
@Test
void testItStandsAsideWhereScheduledJobsStartThePlans() throws Exception
{
QRecord plan = VerifyTestSupport.plan(NIGHTLY);
new ScheduledJobsMetaDataProvider().defineAll(QContext.getQInstance(), BackupsTestUtils.BACKEND, null);
VerifyTestSupport.clock.advance(Duration.ofDays(1));
RunBackendStepOutput output = tick();
assertThat(output.getValueString("startedBy")).isEqualTo("scheduledJobs");
assertThat(runsOf(plan)).isEmpty();
}
/*******************************************************************************
** With a scheduler on the config it is on that scheduler, once a minute; with
** none it is not scheduled. It is not in the navigation.
*******************************************************************************/
@Test
void testItIsOnTheQbitsScheduler()
{
var scheduled = BackupDuePlansProcess.processMetaData(new BackupsQBitConfig().withSchedulerName("testScheduler"));
assertThat(scheduled.getSchedule().getSchedulerName()).isEqualTo("testScheduler");
assertThat(scheduled.getSchedule().getRepeatSeconds()).isEqualTo(60);
assertThat(scheduled.getIsHidden()).isTrue();
assertThat(BackupDuePlansProcess.processMetaData(new BackupsQBitConfig()).getSchedule()).isNull();
assertThat(QContext.getQInstance().getProcess(BackupDuePlansProcess.NAME)).as("produced with the qbit").isNotNull();
}
}
@@ -142,6 +142,8 @@ class ObjectStorageBackupStorageMinioTest
storage.copy("contract/big.bin", "contract/copy.bin");
assertThat(storage.list("contract/")).extracting(StoredObjectInfo::key).containsExactly("contract/big.bin", "contract/copy.bin");
assertThat(storage.list("contract/")).as("a listing says when each object was written: the pruner dates unfinished backups by it")
.allSatisfy(object -> assertThat(object.lastModified()).isNotNull());
assertThat(storage.presignGet("contract/copy.bin", Duration.ofMinutes(15), "x.bin")).startsWith("http");
assertThat(storage.deletePermanent("contract/copy.bin")).isEqualTo(BackupStorage.DeleteResult.DELETED);
assertThat(storage.deletePermanent("contract/copy.bin")).isEqualTo(BackupStorage.DeleteResult.NOT_FOUND);
@@ -323,6 +323,65 @@ class BackupVerifierTest
/*******************************************************************************
** The real thing, from the plan: a key provider on the config, a plan that asks
** for client-side encryption with a key reference. Its run is encrypted without
** anybody handing it a cipher: the objects are ciphertext, the run and its
** manifest record the reference and a fingerprint (never the key), and it
** passes verification by content and a test restore. After a rotation the old
** run still verifies and a new run is written under the new version. When the
** key is gone the old run cannot be verified, and a new run is refused with
** nothing written.
*******************************************************************************/
@Test
void testAPlanThatAsksForEncryptionIsEncryptedByTheKeyProvider() throws Exception
{
java.util.Map<String, String> env = new java.util.HashMap<>();
byte[] first = new byte[32];
new java.security.SecureRandom().nextBytes(first);
env.put("RUN_TEST_KEK", java.util.Base64.getEncoder().encodeToString(first));
BackupsRuntime.getConfig().withKeyProvider(new com.kingsrook.qqq.backend.core.crypto.EnvKeyProvider(env::get));
QRecord plan = plan(Map.of("encryptionMode", "CLIENT_AES256_GCM", "encryptionKeyRef", "RUN_TEST_KEK", "sensitiveFieldPolicy", "INCLUDE_ENCRYPTED_ONLY"));
BackupRunResult result = new com.kingsrook.qbits.backups.run.BackupRunCoordinator().runPlan(plan, "MANUAL");
assertThat(result.isUsable()).as(String.valueOf(result.getErrorMessage())).isTrue();
QRecord stored = run(result.getRunId());
assertThat(stored.getValueString("encryptionKeyRef")).isEqualTo("RUN_TEST_KEK");
assertThat(stored.getValueString("encryptionKeyFingerprint")).matches("v1:[0-9a-f]{16}");
String key = VerifyTestSupport.firstPartKey(result, "blogPost");
assertThat(key).endsWith(".tink");
byte[] object = BackupsTestUtils.BACKUPS.getBytes(key);
assertThat(new String(object, 0, 4, java.nio.charset.StandardCharsets.US_ASCII)).as("the cipher's header, not a gzip stream").isEqualTo("QSC1");
assertThat(new BackupCatalog().where(BackupsTables.ARTIFACT, "backupRunId", result.getRunId()).stream().filter(a -> "TABLE_DATA".equals(a.getValueString("artifactType"))))
.isNotEmpty().allSatisfy(a -> assertThat(a.getValueBoolean("encrypted")).isTrue());
List<VerificationOutcome> good = new BackupVerifier().verifyThrough(result.getRunId(), BackupVerifier.TEST_RESTORE, "MANUAL", "t");
assertThat(good).extracting(VerificationOutcome::status).containsExactly("PASSED", "PASSED", "PASSED");
env.put("RUN_TEST_KEK_V1", env.get("RUN_TEST_KEK"));
byte[] second = new byte[32];
new java.security.SecureRandom().nextBytes(second);
env.put("RUN_TEST_KEK", java.util.Base64.getEncoder().encodeToString(second));
env.put("RUN_TEST_KEK_VERSION", "2");
assertThat(new BackupVerifier().verify(result.getRunId(), BackupVerifier.CONTENT, "MANUAL", "t").status()).as("written under version 1, verified after the rotation").isEqualTo("PASSED");
VerifyTestSupport.clock.advance(java.time.Duration.ofHours(1));
BackupRunResult rotated = new com.kingsrook.qbits.backups.run.BackupRunCoordinator().runPlan(reload(plan), "MANUAL");
assertThat(rotated.isUsable()).as(String.valueOf(rotated.getErrorMessage())).isTrue();
assertThat(run(rotated.getRunId()).getValueString("encryptionKeyFingerprint")).startsWith("v2:");
env.clear();
assertThat(new BackupVerifier().verify(result.getRunId(), BackupVerifier.CONTENT, "MANUAL", "t").messages()).anyMatch(m -> m.contains("No key is available for the key reference RUN_TEST_KEK"));
int objects = BackupsTestUtils.BACKUPS.list("").size();
BackupRunResult refused = new com.kingsrook.qbits.backups.run.BackupRunCoordinator().runPlan(reload(plan), "MANUAL");
assertThat(refused.getStatus()).isEqualTo("FAILED");
assertThat(refused.getErrorMessage()).contains("no key is available for its encryption key reference RUN_TEST_KEK").contains("Nothing was written");
assertThat(BackupsTestUtils.BACKUPS.list("")).as("nothing was written in the clear instead").hasSize(objects);
}
/*******************************************************************************
** Encrypted runs verify through the decrypt hook; a wrong key fails clearly; no
** hook at all is an ERROR that says what to configure.