id: rclone-offsite-mirror-deletion-guard
namespace: company.team
description: |
Keep an offsite object-storage mirror in step with production without letting the mirror copy a disaster.
Each run plans an `rclone sync`, compares the plan with the last verified mirror kept in Kestra KV, and
applies it by itself only when the change looks like normal traffic. A collapsing source, a mass delete or a
mass rewrite stops at an approval. The approved sync is capped at the reviewed number of deletions, keeps every
deleted or overwritten object in a trash prefix, and is followed by a second comparison before the baseline moves.
concurrency:
limit: 1
behavior: CANCEL
inputs:
- id: source
type: STRING
defaults: "prod:orders-exports"
description: rclone path of production data, as `remote:bucket/prefix`. The
remote is defined in the RCLONE_CONFIG secret.
- id: destination
type: STRING
defaults: "dr:orders-exports-mirror"
description: rclone path of the offsite mirror. Only this path is ever modified.
- id: trash_path
type: STRING
defaults: "dr:orders-exports-trash/mirror"
description: Where deleted and overwritten mirror objects are moved, under a
folder named after the run. Must be on the same remote as the destination
and must not sit inside it.
- id: compare
type: SELECT
values: [ hash, size-only, download ]
defaults: hash
description: How objects are compared. hash uses size and checksum, size-only is
quick and weaker, download reads both sides and is the only option when
the two remotes share no hash type.
- id: max_shrink_pct
type: INT
defaults: 20
description: Review when the source object count or total size is this many
percent below the last verified mirror.
- id: max_delete_pct
type: INT
defaults: 5
description: Review when the sync would delete more than this percent of the
objects in the mirror.
- id: max_rewrite_pct
type: INT
defaults: 30
description: Review when the sync would overwrite more than this percent of the
objects in the mirror. In-place encryption by ransomware or a broken batch
job looks like this.
- id: free_changes
type: INT
defaults: 10
description: Deletes or overwrites up to this many never need review, so small
buckets do not stop on a single object.
- id: verify_tolerance
type: INT
defaults: 0
description: Objects allowed to still differ after the sync because production
kept writing while it ran. Raise it for busy buckets.
- id: dry_run
type: BOOL
defaults: true
description: Plan and report only. Nothing is written and no approval is requested.
- id: approval_timeout
type: DURATION
defaults: PT12H
description: How long a review waits. When it runs out the sync is not applied
and the next run plans again.
- id: rclone_image
type: STRING
defaults: rclone/rclone:1.75.2
variables:
baseline_key: "rclone_mirror_baseline_{{ (inputs.source ~ '_' ~
inputs.destination) | slugify }}"
backup_dir: "{{ inputs.trash_path }}/{{ execution.startDate |
date('yyyyMMdd-HHmmss', timeZone='UTC') }}"
check_flags: "{{ inputs.compare == 'size-only' ? '--size-only' : (inputs.compare
== 'download' ? '--download' : '') }}"
sync_flags: "{{ inputs.compare == 'size-only' ? '--size-only' : '--checksum' }}"
helpers: |
fail() { echo "MIRROR GUARD FAILED: $*" >&2; exit 1; }
num() { case "$1" in ''|*[!0-9]*) fail "unexpected rclone output: $2" ;; esac; }
# size_of REMOTE:PATH must-exist|empty-ok -> "count bytes". Exit code 3 is rclone's "directory not found".
size_of() {
rc=0; rclone size --json "$1" > size.json 2> size.err || rc=$?
if [ "$rc" -eq 3 ] && [ "$2" = empty-ok ]; then echo "0 0"; return 0; fi
[ "$rc" -eq 0 ] || fail "rclone size $1 exited $rc: $(tail -n 1 size.err)"
c=$(sed -E 's/.*"count":([0-9]+).*/\1/' size.json); b=$(sed -E 's/.*"bytes":([0-9]+).*/\1/' size.json)
num "$c" "$(cat size.json)"; num "$b" "$(cat size.json)"
echo "$c $b"
}
# tally SYMBOL -> number of `rclone check --combined` lines that start with SYMBOL
tally() { n=$(grep -c "^$1 " combined.txt) || true; echo "${n:-0}"; }
# run_check -> combined.txt holds one line per object: "= same", "+ only in source", "- only in mirror", "* differs", "! unreadable"
run_check() {
rm -f combined.txt
rc=0; rclone check "$SRC" "$DST" $CHECK_FLAGS --combined combined.txt > check.out 2>&1 || rc=$?
[ "$rc" -le 1 ] && [ -f combined.txt ] || fail "rclone check exited $rc: $(tail -n 2 check.out | tr '\n' ' ')"
[ "$(tally '!')" -eq 0 ] || fail "$(tally '!') objects could not be read or hashed, so the plan cannot be trusted: $(grep '^! ' combined.txt | head -n 3 | tr '\n' ' ')"
}
triggers:
- id: nightly_mirror
type: io.kestra.plugin.core.trigger.Schedule
description: Shipped disabled. Enable it after a manual dry run against your own
remotes.
cron: "30 1 * * *"
disabled: true
- id: after_export
type: io.kestra.plugin.core.trigger.Webhook
description: Call it when the job that writes the source finishes, so the mirror
follows the data instead of the clock.
key: "{{ secret('RCLONE_MIRROR_WEBHOOK_KEY') }}"
tasks:
- id: load_baseline
type: io.kestra.plugin.core.kv.Get
description: Source object count and size recorded by the last mirror that was
applied and verified. Missing on the first run.
key: "{{ render(vars.baseline_key) }}"
errorOnMissing: false
- id: plan
type: io.kestra.plugin.scripts.shell.Commands
description: Measures both sides and asks rclone check what a sync would do,
then applies the review rules. Changes nothing.
taskRunner:
type: io.kestra.plugin.scripts.runner.docker.Docker
containerImage: "{{ inputs.rclone_image }}"
inputFiles:
rclone.conf: "{{ secret('RCLONE_CONFIG') }}"
env:
RCLONE_CONFIG: rclone.conf
SRC: "{{ inputs.source }}"
DST: "{{ inputs.destination }}"
CHECK_FLAGS: "{{ render(vars.check_flags) }}"
BASE_COUNT: "{{ outputs.load_baseline.value.count is defined ?
outputs.load_baseline.value.count : -1 }}"
BASE_BYTES: "{{ outputs.load_baseline.value.bytes is defined ?
outputs.load_baseline.value.bytes : -1 }}"
MAX_SHRINK_PCT: "{{ inputs.max_shrink_pct }}"
MAX_DELETE_PCT: "{{ inputs.max_delete_pct }}"
MAX_REWRITE_PCT: "{{ inputs.max_rewrite_pct }}"
FREE_CHANGES: "{{ inputs.free_changes }}"
commands:
- |
{{ render(vars.helpers) }}
# A missing source is an error, never an empty source: treating it as empty would plan to erase the mirror.
out=$(size_of "$SRC" must-exist) || exit 1; set -- $out; SRC_COUNT=$1; SRC_BYTES=$2
out=$(size_of "$DST" empty-ok) || exit 1; set -- $out; DST_COUNT=$1; DST_BYTES=$2
if [ "$DST_COUNT" -eq 0 ]; then
TO_COPY=$SRC_COUNT; TO_UPDATE=0; TO_DELETE=0; SAME=0
else
run_check
TO_COPY=$(tally '+'); TO_DELETE=$(tally '-'); TO_UPDATE=$(tally '*'); SAME=$(tally '=')
fi
REASONS=""
add() { REASONS="${REASONS}${REASONS:+ | }$1"; }
if [ "$DST_COUNT" -gt 0 ] && [ "$SRC_COUNT" -eq 0 ]; then
add "the source is empty while the mirror holds $DST_COUNT objects"
fi
if [ "$BASE_COUNT" -gt 0 ] && [ $(( (BASE_COUNT - SRC_COUNT) * 100 )) -gt $(( MAX_SHRINK_PCT * BASE_COUNT )) ]; then
add "source object count fell from $BASE_COUNT to $SRC_COUNT since the last verified mirror (limit ${MAX_SHRINK_PCT}%)"
fi
if [ "$BASE_BYTES" -gt 0 ] && [ $(( (BASE_BYTES - SRC_BYTES) * 100 )) -gt $(( MAX_SHRINK_PCT * BASE_BYTES )) ]; then
add "source size fell from $BASE_BYTES to $SRC_BYTES bytes since the last verified mirror (limit ${MAX_SHRINK_PCT}%)"
fi
if [ "$TO_DELETE" -gt "$FREE_CHANGES" ] && [ $(( TO_DELETE * 100 )) -gt $(( MAX_DELETE_PCT * DST_COUNT )) ]; then
add "the sync would delete $TO_DELETE of $DST_COUNT mirrored objects (limit ${MAX_DELETE_PCT}%)"
fi
if [ "$TO_UPDATE" -gt "$FREE_CHANGES" ] && [ $(( TO_UPDATE * 100 )) -gt $(( MAX_REWRITE_PCT * DST_COUNT )) ]; then
add "the sync would overwrite $TO_UPDATE of $DST_COUNT mirrored objects (limit ${MAX_REWRITE_PCT}%), which looks like a mass rewrite and not normal change"
fi
VERDICT=CLEAN; [ -z "$REASONS" ] || VERDICT=REVIEW
echo "plan: copy $TO_COPY, overwrite $TO_UPDATE, delete $TO_DELETE, unchanged $SAME -> $VERDICT"
echo "::{\"outputs\":{\"verdict\":\"$VERDICT\",\"reasons\":\"$REASONS\",\"src_count\":$SRC_COUNT,\"src_bytes\":$SRC_BYTES,\"dst_count\":$DST_COUNT,\"dst_bytes\":$DST_BYTES,\"to_copy\":$TO_COPY,\"to_update\":$TO_UPDATE,\"to_delete\":$TO_DELETE,\"unchanged\":$SAME}}::"
- id: review_gate
type: io.kestra.plugin.core.flow.If
description: Only a plan that tripped a rule, in a run that may write, asks a human.
condition: "{{ outputs.plan.vars.verdict == 'REVIEW' and not inputs.dry_run }}"
then:
- id: request_review
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
messageText: |
rclone mirror `{{ inputs.source }}` -> `{{ inputs.destination }}` is waiting for approval.
Why: {{ outputs.plan.vars.reasons }}
Plan: copy {{ outputs.plan.vars.to_copy }}, overwrite {{ outputs.plan.vars.to_update }}, delete {{ outputs.plan.vars.to_delete }} (mirror holds {{ outputs.plan.vars.dst_count }}, source holds {{ outputs.plan.vars.src_count }}).
If approved, deleted and overwritten objects go to `{{ render(vars.backup_dir) }}` and rclone is capped at {{ outputs.plan.vars.to_delete }} deletions.
Resume execution {{ execution.id }} in Kestra and tick Approve. Without approval within {{ inputs.approval_timeout }} nothing is written.
- id: approve_sync
type: io.kestra.plugin.core.flow.Pause
description: Human gate. The default is false and the timeout resumes with the
default, so silence never applies the sync.
pauseDuration: "{{ inputs.approval_timeout }}"
behavior: RESUME
onResume:
- id: approve
type: BOOL
displayName: Apply this sync?
defaults: false
- id: note
type: STRING
displayName: Why is the change expected?
required: false
- id: apply_gate
type: io.kestra.plugin.core.flow.If
description: Applies the sync for a clean plan, or for a reviewed plan that was
approved. A dry run never gets here.
condition: "{{ not inputs.dry_run and (outputs.plan.vars.verdict == 'CLEAN' or
(outputs.approve_sync.onResume.approve is defined and
outputs.approve_sync.onResume.approve == true)) }}"
then:
- id: apply_sync
type: io.kestra.plugin.scripts.shell.Commands
description: rclone sync into the mirror. --max-delete is the number of
deletions that was planned (and approved), so objects that became
deletable after the plan stop the run instead of being deleted.
taskRunner:
type: io.kestra.plugin.scripts.runner.docker.Docker
containerImage: "{{ inputs.rclone_image }}"
inputFiles:
rclone.conf: "{{ secret('RCLONE_CONFIG') }}"
env:
RCLONE_CONFIG: rclone.conf
SRC: "{{ inputs.source }}"
DST: "{{ inputs.destination }}"
BACKUP: "{{ render(vars.backup_dir) }}"
SYNC_FLAGS: "{{ render(vars.sync_flags) }}"
PLANNED_DELETES: "{{ outputs.plan.vars.to_delete }}"
commands:
- |
{{ render(vars.helpers) }}
rc=0
rclone sync "$SRC" "$DST" --backup-dir "$BACKUP" --max-delete "$PLANNED_DELETES" $SYNC_FLAGS -v > sync.log 2>&1 || rc=$?
tail -n 15 sync.log
if [ "$rc" -ne 0 ]; then
if grep -q 'max-delete threshold reached' sync.log; then
fail "more objects were due for deletion than the $PLANNED_DELETES that were planned, so rclone stopped. Everything already deleted is in $BACKUP. Run again for a fresh plan."
fi
fail "rclone sync exited $rc, see the log above. Anything already deleted or overwritten is in $BACKUP."
fi
- id: verify_mirror
type: io.kestra.plugin.scripts.shell.Commands
description: Compares source and mirror again and checks that the trash prefix
holds the deleted objects. The baseline only moves when this passes.
taskRunner:
type: io.kestra.plugin.scripts.runner.docker.Docker
containerImage: "{{ inputs.rclone_image }}"
inputFiles:
rclone.conf: "{{ secret('RCLONE_CONFIG') }}"
env:
RCLONE_CONFIG: rclone.conf
SRC: "{{ inputs.source }}"
DST: "{{ inputs.destination }}"
BACKUP: "{{ render(vars.backup_dir) }}"
CHECK_FLAGS: "{{ render(vars.check_flags) }}"
PLANNED_DELETES: "{{ outputs.plan.vars.to_delete }}"
TOLERANCE: "{{ inputs.verify_tolerance }}"
commands:
- |
{{ render(vars.helpers) }}
out=$(size_of "$SRC" must-exist) || exit 1; set -- $out; SRC_COUNT=$1; SRC_BYTES=$2
out=$(size_of "$DST" empty-ok) || exit 1; set -- $out; DST_COUNT=$1; DST_BYTES=$2
out=$(size_of "$BACKUP" empty-ok) || exit 1; set -- $out; TRASH_COUNT=$1
if [ "$DST_COUNT" -eq 0 ]; then
EXTRA=0; DRIFT=$SRC_COUNT
else
run_check
EXTRA=$(tally '-'); DRIFT=$(( $(tally '+') + $(tally '*') ))
fi
[ "$EXTRA" -eq 0 ] || fail "$EXTRA objects are still in the mirror that the source does not have"
[ "$DRIFT" -le "$TOLERANCE" ] || fail "$DRIFT objects still differ between source and mirror (tolerance $TOLERANCE)"
[ "$TRASH_COUNT" -ge "$PLANNED_DELETES" ] || fail "only $TRASH_COUNT of the $PLANNED_DELETES deleted objects are in $BACKUP, so they are not recoverable"
echo "verified: source $SRC_COUNT objects, mirror $DST_COUNT, trash $TRASH_COUNT, still differing $DRIFT"
echo "::{\"outputs\":{\"src_count\":$SRC_COUNT,\"src_bytes\":$SRC_BYTES,\"dst_count\":$DST_COUNT,\"trash_count\":$TRASH_COUNT,\"drift\":$DRIFT}}::"
- id: save_baseline
type: io.kestra.plugin.core.kv.Set
description: Records the verified source size as the new reference. A run that
was declined or that failed verification never gets here, so the same
collapse is flagged again on the next run.
key: "{{ render(vars.baseline_key) }}"
kvType: JSON
value: "{{ {'count': outputs.verify_mirror.vars.src_count, 'bytes':
outputs.verify_mirror.vars.src_bytes, 'at': execution.startDate,
'execution': execution.id, 'reviewed': (outputs.plan.vars.verdict ==
'REVIEW'), 'reasons': outputs.plan.vars.reasons, 'approval_note':
(outputs.approve_sync.onResume.note is defined ?
outputs.approve_sync.onResume.note : '')} | toJson }}"
- id: report_applied
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
messageText: "rclone mirror `{{ inputs.source }}` -> `{{ inputs.destination }}`
applied and verified{% if outputs.plan.vars.verdict == 'REVIEW' %}
after approval{% endif %}: copied {{ outputs.plan.vars.to_copy }},
overwrote {{ outputs.plan.vars.to_update }}, deleted {{
outputs.plan.vars.to_delete }}. Mirror holds {{
outputs.verify_mirror.vars.dst_count }} objects, {{
outputs.verify_mirror.vars.trash_count }} recoverable in `{{
render(vars.backup_dir) }}`."
else:
- id: report_not_applied
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
messageText: "rclone mirror `{{ inputs.source }}` -> `{{ inputs.destination }}`
not applied ({% if inputs.dry_run %}dry run{% else %}the review was
not approved{% endif %}). Plan: copy {{ outputs.plan.vars.to_copy }},
overwrite {{ outputs.plan.vars.to_update }}, delete {{
outputs.plan.vars.to_delete }}, verdict {{ outputs.plan.vars.verdict
}}{% if outputs.plan.vars.reasons != '' %}. Why: {{
outputs.plan.vars.reasons }}{% endif %}. The mirror and the baseline
are unchanged."
errors:
- id: alert_failure
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
messageText: "rclone mirror guard FAILED for `{{ inputs.source }}` -> `{{
inputs.destination }}` (execution {{ execution.id }}){% if errorLogs() |
length > 0 %} at `{{ errorLogs()[0]['taskId'] }}`: {{
errorLogs()[0]['message'] | abbreviate(300) }}{% endif %}. The baseline
was not moved. If the failure is at verify_mirror or later the sync
already ran: look in `{{ render(vars.backup_dir) }}` for deleted and
overwritten objects."