From 2be9fc21db96ce63e8b2532de4e79fca46eb372b Mon Sep 17 00:00:00 2001 From: James Maes Date: Tue, 24 Nov 2026 05:19:03 -0600 Subject: [PATCH] fix(schedule): the daily prune prunes, and plans run on their schedule without a scheduled jobs table 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 --- CHANGELOG.md | 3 + README.md | 11 + .../qbits/backups/alerts/BackupAlerts.java | 5 +- .../backups/processes/LifecycleProcesses.java | 2 + .../qbits/backups/processes/PruneProcess.java | 14 +- .../schedule/BackupDuePlansProcess.java | 198 ++++++++++++++++ .../schedule/BackupScheduledPruneProcess.java | 143 ++++++++++++ src/main/resources/help/qbit-backups.yaml | 8 + .../alerts/AlertsQBitAlertSinkTest.java | 4 +- .../backups/alerts/BackupAlertsTest.java | 2 +- .../processes/LifecycleProcessesTest.java | 87 ++++++++ .../schedule/BackupDuePlansProcessTest.java | 211 ++++++++++++++++++ 12 files changed, 673 insertions(+), 15 deletions(-) create mode 100644 src/main/java/com/kingsrook/qbits/backups/schedule/BackupDuePlansProcess.java create mode 100644 src/main/java/com/kingsrook/qbits/backups/schedule/BackupScheduledPruneProcess.java create mode 100644 src/test/java/com/kingsrook/qbits/backups/schedule/BackupDuePlansProcessTest.java diff --git a/CHANGELOG.md b/CHANGELOG.md index 405d5da..b33f8df 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,8 @@ 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:<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.` 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. @@ -17,6 +19,7 @@ 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 +- **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". diff --git a/README.md b/README.md index ffdc771..24e3adc 100644 --- a/README.md +++ b/README.md @@ -62,6 +62,17 @@ 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: diff --git a/src/main/java/com/kingsrook/qbits/backups/alerts/BackupAlerts.java b/src/main/java/com/kingsrook/qbits/backups/alerts/BackupAlerts.java index 4f0fc31..34b3845 100644 --- a/src/main/java/com/kingsrook/qbits/backups/alerts/BackupAlerts.java +++ b/src/main/java/com/kingsrook/qbits/backups/alerts/BackupAlerts.java @@ -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."))); } diff --git a/src/main/java/com/kingsrook/qbits/backups/processes/LifecycleProcesses.java b/src/main/java/com/kingsrook/qbits/backups/processes/LifecycleProcesses.java index c4d17c3..65f9d99 100644 --- a/src/main/java/com/kingsrook/qbits/backups/processes/LifecycleProcesses.java +++ b/src/main/java/com/kingsrook/qbits/backups/processes/LifecycleProcesses.java @@ -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 diff --git a/src/main/java/com/kingsrook/qbits/backups/processes/PruneProcess.java b/src/main/java/com/kingsrook/qbits/backups/processes/PruneProcess.java index 7e4020e..db4d344 100644 --- a/src/main/java/com/kingsrook/qbits/backups/processes/PruneProcess.java +++ b/src/main/java/com/kingsrook/qbits/backups/processes/PruneProcess.java @@ -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)); diff --git a/src/main/java/com/kingsrook/qbits/backups/schedule/BackupDuePlansProcess.java b/src/main/java/com/kingsrook/qbits/backups/schedule/BackupDuePlansProcess.java new file mode 100644 index 0000000..e7df839 --- /dev/null +++ b/src/main/java/com/kingsrook/qbits/backups/schedule/BackupDuePlansProcess.java @@ -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 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)); + } +} diff --git a/src/main/java/com/kingsrook/qbits/backups/schedule/BackupScheduledPruneProcess.java b/src/main/java/com/kingsrook/qbits/backups/schedule/BackupScheduledPruneProcess.java new file mode 100644 index 0000000..dde5a7b --- /dev/null +++ b/src/main/java/com/kingsrook/qbits/backups/schedule/BackupScheduledPruneProcess.java @@ -0,0 +1,143 @@ +/* + * 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 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++; + 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); + } +} diff --git a/src/main/resources/help/qbit-backups.yaml b/src/main/resources/help/qbit-backups.yaml index d7f1594..7849498 100644 --- a/src/main/resources/help/qbit-backups.yaml +++ b/src/main/resources/help/qbit-backups.yaml @@ -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: | diff --git a/src/test/java/com/kingsrook/qbits/backups/alerts/AlertsQBitAlertSinkTest.java b/src/test/java/com/kingsrook/qbits/backups/alerts/AlertsQBitAlertSinkTest.java index 6717bc3..b8f7f73 100644 --- a/src/test/java/com/kingsrook/qbits/backups/alerts/AlertsQBitAlertSinkTest.java +++ b/src/test/java/com/kingsrook/qbits/backups/alerts/AlertsQBitAlertSinkTest.java @@ -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"); diff --git a/src/test/java/com/kingsrook/qbits/backups/alerts/BackupAlertsTest.java b/src/test/java/com/kingsrook/qbits/backups/alerts/BackupAlertsTest.java index 005cca5..a84dd58 100644 --- a/src/test/java/com/kingsrook/qbits/backups/alerts/BackupAlertsTest.java +++ b/src/test/java/com/kingsrook/qbits/backups/alerts/BackupAlertsTest.java @@ -71,7 +71,7 @@ class BackupAlertsTest { Set 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); diff --git a/src/test/java/com/kingsrook/qbits/backups/processes/LifecycleProcessesTest.java b/src/test/java/com/kingsrook/qbits/backups/processes/LifecycleProcessesTest.java index cc69be2..2a71f73 100644 --- a/src/test/java/com/kingsrook/qbits/backups/processes/LifecycleProcessesTest.java +++ b/src/test/java/com/kingsrook/qbits/backups/processes/LifecycleProcessesTest.java @@ -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. *******************************************************************************/ diff --git a/src/test/java/com/kingsrook/qbits/backups/schedule/BackupDuePlansProcessTest.java b/src/test/java/com/kingsrook/qbits/backups/schedule/BackupDuePlansProcessTest.java new file mode 100644 index 0000000..8842f0c --- /dev/null +++ b/src/test/java/com/kingsrook/qbits/backups/schedule/BackupDuePlansProcessTest.java @@ -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 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 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(); + } +} -- 2.54.0