id: restic-backup-restore-drill
namespace: company.team
description: |
Prove every day that your restic backups can be restored. The drill checks that the newest snapshot is younger
than your RPO, reads a rotating slice of the repository's pack files with `restic check --read-data-subset`,
restores a random sample of files to a temporary directory and compares their sha256 with the source. Stale locks
left by crashed jobs are reported and removed. `forget --prune` runs only after a passing drill and an approval.
Demo mode needs only Docker.
triggers:
- id: daily_drill
type: io.kestra.plugin.core.trigger.Schedule
description: Shipped disabled; enable it once the repository secrets are yours.
cron: "17 6 * * *"
disabled: true
- id: after_backup
type: io.kestra.plugin.core.trigger.Webhook
description: Call it at the end of the backup job to drill the snapshot it just wrote.
key: "{{ secret('RESTIC_DRILL_WEBHOOK_KEY') }}"
concurrency:
limit: 1
behavior: QUEUE
inputs:
- id: mode
type: SELECT
values: [ demo, repository ]
defaults: demo
description: demo backs up generated files to a local repository inside the
drill container. repository drills the repository in the RESTIC_REPOSITORY
secret.
- id: host
type: STRING
required: false
description: Only consider snapshots from this host (restic --host).
- id: tag
type: STRING
required: false
description: Only consider snapshots with this tag (restic --tag).
- id: rpo_hours
type: INT
defaults: 26
description: The newest snapshot must be younger than this.
- id: read_data_subset
type: STRING
defaults: rotate
description: rotate reads one seventh of the pack files each day (1/7 on Mondays
... 7/7 on Sundays), so every pack is read once a week. Or any restic
value such as 5%, 2/10 or 100%.
- id: sample_files
type: INT
defaults: 20
description: Number of random files restored from the snapshot.
- id: source_root
type: STRING
required: false
description: Where the drill container sees the backed-up paths (mount them
read-only with the Docker runner's volumes). Empty skips the comparison
with the source; restore --verify still checks every restored byte against
the repository.
- id: connect_timeout_seconds
type: INT
defaults: 120
description: restic retries an unreachable backend for many minutes; the drill
gives up after this long.
- id: lock_wait
type: STRING
defaults: 10m
description: How long check waits for a lock held by a running backup (restic
--retry-lock).
- id: forget_policy
type: STRING
required: false
validator: ^(--keep-(last|hourly|daily|weekly|monthly|yearly) [0-9]+ ?)*$
description: e.g. "--keep-daily 7 --keep-weekly 5 --keep-monthly 12". After a
passing drill, the snapshots it would remove are listed and pruned only
after approval.
- id: approval_timeout
type: DURATION
defaults: PT8H
- id: restic_image
type: STRING
defaults: restic/restic:0.19.1
variables:
last_good_key: "restic_drill_last_good_{{ inputs.mode }}"
filter: "{% if (inputs.host ?? '') != '' %} --host {{ inputs.host }}{% endif
%}{% if (inputs.tag ?? '') != '' %} --tag {{ inputs.tag }}{% endif %}"
tasks:
- id: drill
type: io.kestra.plugin.scripts.shell.Commands
description: Opens the repository, clears stale locks, checks integrity,
restores a sample and compares it.
taskRunner:
type: io.kestra.plugin.scripts.runner.docker.Docker
containerImage: "{{ inputs.restic_image }}"
env:
RESTIC_REPOSITORY: "{{ inputs.mode == 'demo' ? '/tmp/demo-repo' :
secret('RESTIC_REPOSITORY') }}"
RESTIC_PASSWORD: "{{ inputs.mode == 'demo' ? 'demo-only-password' :
secret('RESTIC_PASSWORD') }}"
SUBSET: "{{ inputs.read_data_subset == 'rotate' ? (now() | date('e')) ~ '/7' :
inputs.read_data_subset }}"
SOURCE_ROOT: "{{ inputs.mode == 'demo' ? '/' : (inputs.source_root ?? '') }}"
commands:
- |
fail() { echo "DRILL FAILED: $*" >&2; exit 1; }
why() { grep -m1 -iE 'fatal|error|wrong password|locked|unable|refused|no such' "$1" | sed -E 's/.*"message":"([^"]*)".*/\1/; s/^(Fatal|fatal|error|Error): *//'; }
if [ "{{ inputs.mode }}" = demo ]; then
mkdir -p /tmp/demo-source/db /tmp/demo-source/uploads
for i in $(seq 1 30); do head -c $((i * 37000)) /dev/urandom > /tmp/demo-source/uploads/file-$i.bin; done
seq 1 200000 > /tmp/demo-source/db/dump.sql
restic init -q >/dev/null && restic backup -q --host demo /tmp/demo-source >/dev/null || fail "demo backup failed"
fi
rc=0; timeout {{ inputs.connect_timeout_seconds }} restic snapshots --no-lock --json{{ render(vars.filter) }} > snaps.json 2> err.txt || rc=$?
case $rc in 124|130|143) fail "the repository did not answer within {{ inputs.connect_timeout_seconds }} s (restic keeps retrying an unreachable backend): $(grep 'returned error' err.txt | tail -n 1 | sed -E 's/.*retrying after [^:]+: //')" ;; esac
[ $rc -eq 0 ] || fail "cannot open the repository: $(why err.txt)"
snap=$(tr -d '\n' < snaps.json | grep -oE '"time":"[^"]+"' | tail -1 | cut -d'"' -f4)
id=$(tr -d '\n' < snaps.json | grep -oE '"id":"[0-9a-f]{64}"' | tail -1 | cut -d'"' -f4)
[ -n "$id" ] || fail "no snapshot matches{{ render(vars.filter) }}"
# Locks: a running restic refreshes its lock every 5 minutes, so one older than 30 minutes belongs to a dead
# process. `restic unlock` removes only those; a live lock is left alone and check waits for it.
locks=""
for l in $(restic list locks --no-lock 2>/dev/null); do
locks="$locks$(restic cat lock "$l" --no-lock 2>/dev/null | tr -d '\n ' | sed 's/"/\\"/g'),"
done
removed=$(restic unlock 2>&1 | grep -oE 'removed [0-9]+ locks?' | grep -oE '[0-9]+' || echo 0)
start=$(date +%s)
restic check --retry-lock {{ inputs.lock_wait }} --read-data-subset="$SUBSET" > check.log 2>&1 || {
tail -n 15 check.log
if grep -q 'already locked' check.log; then
fail "repository still locked after waiting {{ inputs.lock_wait }}: $(grep -m1 'already locked by' check.log | sed 's/^.*already locked/locked/'), $(grep -m1 'lock was created at' check.log). The lock is live (refreshed by a running restic), so it was not removed"
fi
fail "restic check found a problem in subset $SUBSET: $(grep -m1 -iE 'error|invalid|missing|does not match|fail' check.log)"
}
restic ls --no-lock --json "$id" | grep '"type":"file"' | sed -E 's/.*"path":"([^"]*)".*"size":([0-9]+).*/\2 \1/' > files.txt
total=$(wc -l < files.txt)
[ "$total" -gt 0 ] || fail "snapshot $id contains no files"
shuf -n {{ inputs.sample_files }} files.txt > sample.txt
set --; while read -r size path; do set -- "$@" --include "$path"; done < sample.txt
restic restore --no-lock "$id" --target /tmp/restore --verify "$@" > restore.log 2>&1 \
|| { tail -n 10 restore.log; fail "restore of the sample failed: $(why restore.log)"; }
restore_seconds=$(( $(date +%s) - start ))
compared=0; skipped=0; mismatched=""
snap_epoch=$(date -u -D '%Y-%m-%dT%H:%M:%S' -d "$(echo "$snap" | cut -c1-19)" +%s)
off=$(echo "$snap" | grep -oE '[+-][0-9]{2}:[0-9]{2}$' || true)
[ -z "$off" ] || snap_epoch=$(( snap_epoch - ${off%%[0-9]*}1 * ($(echo "$off" | cut -c2-3 | sed 's/^0//') * 3600 + $(echo "$off" | cut -c5-6 | sed 's/^0//') * 60) ))
while read -r size path; do
[ -f "/tmp/restore$path" ] || { mismatched="$mismatched $path(not restored)"; continue; }
[ -n "$SOURCE_ROOT" ] || continue
src="${SOURCE_ROOT%/}$path"
if [ ! -f "$src" ] || [ "$(stat -c %Y "$src")" -gt "$snap_epoch" ]; then skipped=$((skipped + 1)); continue; fi
a=$(sha256sum "/tmp/restore$path" | cut -c1-64); b=$(sha256sum "$src" | cut -c1-64); compared=$((compared + 1))
[ "$a" = "$b" ] || mismatched="$mismatched $path(restored ${a%${a#????????}} source ${b%${b#????????}})"
done < sample.txt
[ -z "$mismatched" ] || fail "restored files differ from the source although unchanged since the snapshot:$mismatched"
echo "::{\"outputs\":{\"snapshot_id\":\"$id\",\"short_id\":\"${id%${id#????????}}\",\"snapshot_time\":\"$snap\",\"files_in_snapshot\":$total,\"subset\":\"$SUBSET\",\"restored\":$(wc -l < sample.txt),\"compared\":$compared,\"skipped_changed\":$skipped,\"restore_seconds\":$restore_seconds,\"stale_locks_removed\":$removed,\"locks_seen\":\"${locks%,}\"}}::"
- id: rpo_check
type: io.kestra.plugin.core.flow.If
condition: "{{ ((now() | timestamp) - (outputs.drill.vars.snapshot_time |
timestamp)) > inputs.rpo_hours * 3600 }}"
then:
- id: snapshot_too_old
type: io.kestra.plugin.core.execution.Fail
errorMessage: "DRILL FAILED: the newest snapshot {{ outputs.drill.vars.short_id
}} is {{ (((now() | timestamp) - (outputs.drill.vars.snapshot_time |
timestamp)) / 3600.0) | numberFormat('0.0') }} h old, over the {{
inputs.rpo_hours }} h RPO. The repository itself is readable; the
backup job is not producing snapshots."
- id: remember_good_drill
type: io.kestra.plugin.core.kv.Set
key: "{{ render(vars.last_good_key) }}"
kvType: JSON
value: "{{ {'at': execution.startDate, 'snapshot': outputs.drill.vars.short_id}
| toJson }}"
- id: report_pass
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
messageText: |
restic restore drill PASSED ({{ inputs.mode }}): snapshot {{ outputs.drill.vars.short_id }} from {{ outputs.drill.vars.snapshot_time | date('yyyy-MM-dd HH:mm', timeZone='UTC') }} UTC ({{ (((now() | timestamp) - (outputs.drill.vars.snapshot_time | timestamp)) / 3600.0) | numberFormat('0.0') }} h old, RPO {{ inputs.rpo_hours }} h).
check read pack subset {{ outputs.drill.vars.subset }}; restored {{ outputs.drill.vars.restored }} of {{ outputs.drill.vars.files_in_snapshot }} files with --verify{% if outputs.drill.vars.compared > 0 %}, {{ outputs.drill.vars.compared }} match the source by sha256{% endif %}{% if outputs.drill.vars.skipped_changed > 0 %} ({{ outputs.drill.vars.skipped_changed }} changed since the snapshot, not compared){% endif %}; {{ outputs.drill.vars.restore_seconds }} s.{% if outputs.drill.vars.stale_locks_removed > 0 %}
restic unlock removed {{ outputs.drill.vars.stale_locks_removed }} stale lock(s) (not refreshed for 30 min, or held by a process that no longer exists on the same host): a backup or prune died there. Locks seen: {{ outputs.drill.vars.locks_seen }}{% endif %}
- id: retention
type: io.kestra.plugin.core.flow.If
condition: "{{ (inputs.forget_policy ?? '') != '' }}"
then:
- id: forget_preview
type: io.kestra.plugin.scripts.shell.Commands
taskRunner:
type: io.kestra.plugin.scripts.runner.docker.Docker
containerImage: "{{ inputs.restic_image }}"
env:
RESTIC_REPOSITORY: "{{ inputs.mode == 'demo' ? '/tmp/demo-repo' :
secret('RESTIC_REPOSITORY') }}"
RESTIC_PASSWORD: "{{ inputs.mode == 'demo' ? 'demo-only-password' :
secret('RESTIC_PASSWORD') }}"
commands:
- |
restic forget --dry-run --no-lock{{ render(vars.filter) }} {{ inputs.forget_policy }} | tee plan.txt
n=$(grep -oE '^remove [0-9]+ snapshot' plan.txt | awk '{s += $2} END {print s + 0}')
keep=$(grep -oE '^keep [0-9]+ snapshot' plan.txt | awk '{s += $2} END {print s + 0}')
echo "::{\"outputs\":{\"remove\":$n,\"keep\":$keep}}::"
- id: anything_to_forget
type: io.kestra.plugin.core.flow.If
condition: "{{ outputs.forget_preview.vars.remove > 0 }}"
then:
- id: request_approval
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
messageText: "restic retention: `forget --prune {{ inputs.forget_policy }}`
would remove {{ outputs.forget_preview.vars.remove }} snapshot(s)
and keep {{ outputs.forget_preview.vars.keep }}. The drill just
passed. Resume execution {{ execution.id }} in Kestra to approve."
- id: approve_prune
type: io.kestra.plugin.core.flow.Pause
pauseDuration: "{{ inputs.approval_timeout }}"
behavior: RESUME
onResume:
- id: prune
type: BOOL
displayName: Forget and prune now?
defaults: false
- id: prune_gate
type: io.kestra.plugin.core.flow.If
condition: "{{ outputs.approve_prune.onResume.prune ?? false }}"
then:
- id: forget_and_prune
type: io.kestra.plugin.scripts.shell.Commands
taskRunner:
type: io.kestra.plugin.scripts.runner.docker.Docker
containerImage: "{{ inputs.restic_image }}"
env:
RESTIC_REPOSITORY: "{{ inputs.mode == 'demo' ? '/tmp/demo-repo' :
secret('RESTIC_REPOSITORY') }}"
RESTIC_PASSWORD: "{{ inputs.mode == 'demo' ? 'demo-only-password' :
secret('RESTIC_PASSWORD') }}"
commands:
- restic forget --retry-lock {{ inputs.lock_wait }} --prune{{
render(vars.filter) }} {{ inputs.forget_policy }} | tail -n
5
- id: report_pruned
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
messageText: "restic retention applied: {{ outputs.forget_preview.vars.remove }}
snapshot(s) forgotten and pruned with {{ inputs.forget_policy
}}."
else:
- id: report_kept
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
messageText: "restic retention not applied ({% if
outputs.approve_prune.onResume.prune is defined %}declined{%
else %}no decision in time{% endif %}): all snapshots kept."
errors:
- id: alert_failure
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
messageText: |
restic restore drill FAILED ({{ inputs.mode }}) in execution {{ execution.id }}{% if errorLogs() | length > 0 %} at `{{ errorLogs()[0]['taskId'] }}`: {{ errorLogs() | jq('([.[] | select(.message | test("DRILL FAILED"))] + .)[0].message | sub("^DRILL FAILED: "; "") | split("\n")[0]') | first }}{% endif %}
No snapshot was forgotten or pruned. Last good drill: {{ (kv(render(vars.last_good_key), errorOnMissing=false) ?? {}).at ?? 'never' }}
outputs:
- id: result
type: JSON
value: "{{ outputs.drill.vars ?? {} }}"