id: velero-backup-schedule-gap-and-restore-check
namespace: company.team
description: |
Velero schedules keep reporting Enabled while their backups quietly stop completing, and restore drills nobody runs leave the archives unproven until an incident needs them. A keyed webhook accepts the latest backup and restore drill report, a Python pass ages every schedule's newest Completed backup against its own cadence and checks the newest successful restore drill, and a Loop walks each schedule posting the gapped ones to Slack. The gate fails the execution when a schedule is past its tolerance, when the drill evidence is stale, or when the report cannot be parsed, a healthy run logs the all clear, the gap counts and ages are published as outputs, and any unexpected failure escalates to Slack.
triggers:
- id: post_backup_report
type: io.kestra.plugin.core.trigger.Webhook
description: POST the Velero backup and restore drill report here after each
backup window, for example from a cluster cron job collecting velero
backup get output and the drill results.
key: "{{ secret('VELERO_REPORT_WEBHOOK_KEY') }}"
- id: daily_gap_safety_net
type: io.kestra.plugin.core.trigger.Schedule
description: Daily 05:00 UTC safety net, shipped disabled so no gap alert fires
until an operator reviews the cadence inputs and switches it on.
cron: "0 5 * * *"
disabled: true
inputs:
- id: expected_cadence_hours
type: INT
defaults: 24
description: Default hours between completed backups for any schedule that does
not carry its own cadenceHours field in the posted report.
- id: gap_tolerance_hours
type: INT
defaults: 6
description: Extra hours a schedule may run past its cadence before the run
counts it as a gap.
- id: restore_drill_max_age_days
type: INT
defaults: 30
description: Maximum age in days of the newest successful restore drill before
the drill half of the check blocks the run.
tasks:
# --- 1. report analysis ---
- id: analyze_backup_report
type: io.kestra.plugin.scripts.python.Script
description: Read the posted Velero report, age each schedule's newest Completed
backup against its cadence plus tolerance, check the newest successful
restore drill, and emit the gate verdict through the outputs protocol.
taskRunner:
type: io.kestra.plugin.scripts.runner.docker.Docker
containerImage: python:3.12-slim
inputFiles:
velero_report.json: "{{ (trigger.body ?? {}) | toJson }}"
env:
EXPECTED_CADENCE_HOURS: "{{ inputs.expected_cadence_hours }}"
GAP_TOLERANCE_HOURS: "{{ inputs.gap_tolerance_hours }}"
RESTORE_DRILL_MAX_AGE_DAYS: "{{ inputs.restore_drill_max_age_days }}"
script: |
import json
import os
from datetime import datetime, timezone
REPORT_FILE = "velero_report.json"
def env_float(name, default):
try:
return float(os.environ.get(name, default))
except (TypeError, ValueError):
return float(default)
EXPECTED_CADENCE_HOURS = env_float("EXPECTED_CADENCE_HOURS", 24)
GAP_TOLERANCE_HOURS = env_float("GAP_TOLERANCE_HOURS", 6)
DRILL_MAX_AGE_DAYS = env_float("RESTORE_DRILL_MAX_AGE_DAYS", 30)
def parse_timestamp(value):
if not value:
return None
text = str(value).strip()
if text.endswith("Z"):
text = text[:-1] + "+00:00"
try:
stamp = datetime.fromisoformat(text)
except ValueError:
return None
if stamp.tzinfo is None:
stamp = stamp.replace(tzinfo=timezone.utc)
return stamp.astimezone(timezone.utc)
def load_report(path):
try:
if not os.path.exists(path) or os.path.getsize(path) == 0:
return None, "report file is missing or empty"
with open(path, "r", encoding="utf-8") as handle:
document = json.load(handle)
document = json.loads(document) if isinstance(document, str) else document
if not isinstance(document, dict):
return None, "report is not a JSON object"
return document, ""
except ValueError:
return None, "report is not valid JSON"
report, problem = load_report(REPORT_FILE)
now = parse_timestamp(report.get("observedAt")) if report else None
now = now or datetime.now(timezone.utc)
verdict, detail, drill_ok = "HEALTHY", "", False
drills_stale, schedule_entries, gapped_names = [], [], []
oldest_age_hours = 0.0
if report is None:
verdict = "UNREADABLE_REPORT"
detail = problem
else:
schedules = [row for row in (report.get("schedules") or []) if isinstance(row, dict)]
backups = [row for row in (report.get("backups") or []) if isinstance(row, dict)]
latest = {}
for backup in backups:
status = backup.get("status") or {}
meta = backup.get("metadata") or {}
labels = meta.get("labels") or {}
spec = backup.get("spec") or {}
schedule_name = labels.get("velero.io/schedule-name") or spec.get("schedule")
start = parse_timestamp(status.get("startTimestamp")) or parse_timestamp(meta.get("creationTimestamp"))
if str(status.get("phase") or "") != "Completed" or not schedule_name or start is None:
continue
if schedule_name not in latest or start > latest[schedule_name]:
latest[schedule_name] = start
for schedule in schedules:
name = str(schedule.get("name") or "unnamed-schedule")
try:
cadence = float(schedule.get("cadenceHours") or EXPECTED_CADENCE_HOURS)
except (TypeError, ValueError):
cadence = EXPECTED_CADENCE_HOURS
window = cadence + GAP_TOLERANCE_HOURS
last = latest.get(name)
if last is None:
age_hours = 0.0
gapped = True
last_text = "never"
reason = "no Completed backup on record for this schedule"
else:
age_hours = round((now - last).total_seconds() / 3600.0, 1)
gapped = age_hours > window
last_text = last.strftime("%Y-%m-%dT%H:%M:%SZ")
reason = "%.1fh since the last Completed backup, %s the %.0fh window" % (
age_hours, "past" if gapped else "inside", window)
oldest_age_hours = max(oldest_age_hours, age_hours)
entry = {"name": name, "gapped": gapped, "gap_hours": age_hours,
"expected_hours": cadence, "window_hours": window,
"last_backup": last_text, "reason": reason}
schedule_entries.append(entry)
if gapped:
gapped_names.append(name)
drills = [row for row in (report.get("restoreDrills") or []) if isinstance(row, dict)]
if not drills:
drills_stale.append("no restore drill recorded in the report")
for drill in drills:
drill_name = str(drill.get("name") or "unnamed-drill")
last_ok = parse_timestamp(drill.get("lastSuccess"))
if last_ok is None:
drills_stale.append("%s has no recorded success" % drill_name)
continue
age_days = (now - last_ok).total_seconds() / 86400.0
if age_days > DRILL_MAX_AGE_DAYS:
drills_stale.append("%s last succeeded %.0fd ago, past the %.0fd limit" % (
drill_name, age_days, DRILL_MAX_AGE_DAYS))
drill_ok = not drills_stale
blockers = []
if gapped_names:
blockers.append("%d schedule(s) past their cadence window" % len(gapped_names))
if not drill_ok:
blockers.append("restore drill " + "; ".join(drills_stale))
if not schedule_entries:
verdict = "NO_DATA"
detail = "report contained no schedule entries"
elif blockers:
verdict = "BLOCKED"
detail = " and ".join(blockers)
else:
verdict = "HEALTHY"
detail = "%d schedule(s) inside their cadence window and the restore drill is current" % len(schedule_entries)
gate_blocked = verdict != "HEALTHY"
print("verdict=%s schedules=%d gaps=%d oldest_hours=%.1f drill_ok=%s" % (
verdict, len(schedule_entries), len(gapped_names), oldest_age_hours, drill_ok))
print("::" + json.dumps({"outputs": {
"verdict": verdict,
"report_valid": report is not None,
"gate_blocked": gate_blocked,
"schedules_checked": len(schedule_entries),
"gaps_detected": len(gapped_names),
"gapped_schedule_names": gapped_names,
"oldest_backup_age_hours": round(oldest_age_hours, 1),
"restore_drill_ok": drill_ok,
"stale_drills": drills_stale,
"schedules": schedule_entries,
"detail": detail,
}}) + "::")
# --- 2. schedule walk ---
- id: walk_schedules
type: io.kestra.plugin.core.flow.Loop
description: Walk every schedule in the report one at a time so each gap is
announced with its own cadence and age instead of one lumped alert.
values: "{{ outputs.analyze_backup_report.vars.schedules }}"
concurrencyLimit: 1
tasks:
- id: gap_check
type: io.kestra.plugin.core.flow.If
description: Announce only the schedules that are past their cadence window and
record the on cadence ones without paging anyone.
condition: "{{ item.value.gapped }}"
then:
- id: alert_schedule_gap
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
description: Post the gapped schedule with its reason, its last Completed backup
and the execution id to the ops channel.
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
payload: |
{"text": "Velero schedule {{ item.value.name }} is behind. {{ item.value.reason }}. Last Completed backup {{ item.value.last_backup }}, expected every {{ item.value.expected_hours }}h. Execution {{ execution.id }}."}
else:
- id: log_on_cadence
type: io.kestra.plugin.core.log.Log
description: Record that this schedule is inside its window so the execution
history still proves what was checked.
message: "{{ item.value.name }} on cadence - {{ item.value.reason }}."
# --- 3. gate verdict ---
- id: restore_drill_gate
type: io.kestra.plugin.core.flow.If
description: Fail the execution when any schedule is past its window or the
restore drill evidence is stale, and log the all clear otherwise.
condition: "{{ outputs.analyze_backup_report.vars.gate_blocked }}"
then:
- id: alert_gate_blocked
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
description: Summarize the blocked gate with the gap count, the oldest backup
age and the drill finding before the execution fails.
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
payload: |
{"text": "Velero backup gate BLOCKED for {{ flow.id }}. {{ outputs.analyze_backup_report.vars.detail }}. Schedules checked {{ outputs.analyze_backup_report.vars.schedules_checked }}, gaps {{ outputs.analyze_backup_report.vars.gaps_detected }}, oldest backup age {{ outputs.analyze_backup_report.vars.oldest_backup_age_hours }}h, restore drill ok {{ outputs.analyze_backup_report.vars.restore_drill_ok }}. Execution {{ execution.id }}."}
- id: fail_gate
type: io.kestra.plugin.core.execution.Fail
description: Fail the execution so a release pipeline waiting on this check
stops instead of proceeding on an unproven backup position.
errorMessage: "Backup gate blocked - {{ outputs.analyze_backup_report.vars.detail }}"
else:
- id: log_all_clear
type: io.kestra.plugin.core.log.Log
description: Record the healthy position with the schedule count and the oldest
backup age so the execution history proves the check ran.
message: "Velero backup gate clear - {{
outputs.analyze_backup_report.vars.schedules_checked }} schedule(s)
inside their cadence window, oldest backup {{
outputs.analyze_backup_report.vars.oldest_backup_age_hours }}h old,
restore drill current."
errors:
- id: notify_failure
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
description: Escalate any failure to the ops channel with the execution url.
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
payload: |
{"text": "FAILED: {{ flow.id }} {{ execution.id }}"}
outputs:
- id: verdict
type: STRING
value: "{{ outputs.analyze_backup_report.vars.verdict }}"
- id: gate_blocked
type: BOOL
value: "{{ outputs.analyze_backup_report.vars.gate_blocked }}"
- id: gaps_detected
type: INT
value: "{{ outputs.analyze_backup_report.vars.gaps_detected }}"
- id: schedules_checked
type: INT
value: "{{ outputs.analyze_backup_report.vars.schedules_checked }}"
- id: oldest_backup_age_hours
type: FLOAT
value: "{{ outputs.analyze_backup_report.vars.oldest_backup_age_hours }}"
- id: restore_drill_ok
type: BOOL
value: "{{ outputs.analyze_backup_report.vars.restore_drill_ok }}"
- id: gapped_schedules
type: ARRAY
value: "{{ outputs.analyze_backup_report.vars.gapped_schedule_names | toJson }}"
- id: detail
type: STRING
value: "{{ outputs.analyze_backup_report.vars.detail }}"