Sub topic 14
Knowing when a backup fails
A backup that fails silently is worse than no backup, because you keep trusting it. This chapter covers how to find out quickly when a restic or Borg job breaks, stalls, or stops running. It assumes you have the systemd service and timer from the scheduling chapter, a working restic-backup.sh script, and a way to send mail or HTTP requests from the server.
Three ways a backup goes wrong
Monitoring has to cover three separate situations. Each needs a different detector.
| Failure | Example | Detected by |
|---|---|---|
| The job ran and failed | Repository unreachable, wrong password, disk full | Exit code, systemd `OnFailure=` |
| The job ran with problems | Some files unreadable, backup completed anyway | Specific exit codes, log review |
| The job never ran | Host down, timer disabled, cron or unit file broken | A dead man's switch or a freshness check |
The third case is the dangerous one. A failure alert sent by the failing machine cannot fire if the machine is off. For that you need an external service that alerts when it hears nothing.
Exit codes are your first signal
Both tools report their result through the process exit code, and a script must not hide it.
For restic, the codes you will meet most often are:
0: the command succeeded.1: the command failed. Forrestic backup, no snapshot was created.3: the backup completed, but some source files could not be read.10,11,12: the repository does not exist, could not be locked, or the password was wrong. These codes exist only in recent restic versions, so checkrestic helpor the manual for yours.
For Borg 1.x, the codes are:
0: success.1: warning. The archive was created, but something such as a file changing during the read needs attention.2: error. The operation failed.- Higher values: the process was killed by a signal.
Newer Borg releases add more specific codes, but the rule holds: 0 is clean, anything else needs a look.
The set -euo pipefail script from the scheduling chapter already makes any non-zero exit stop the script. That is good for failures. It is too blunt for restic's exit 3, because an unreadable temp file would skip the forget step and leave your repository growing. A better script records the code and decides what to do.
A script that reports its own result
This version of /usr/local/bin/restic-backup.sh pings a monitoring service at the start and end of each run. It uses a Healthchecks-style URL. Replace the placeholder with the address your monitor gives you for this job.
#!/bin/bash
set -uo pipefail
export RESTIC_REPOSITORY=sftp:[email protected]:/srv/restic/myserver
export RESTIC_PASSWORD_FILE=/etc/restic/password
HC_URL="https://hc-ping.com/your-check-uuid"
ping_monitor() {
curl -fsS -m 10 --retry 3 -o /dev/null "$1" || true
}
ping_monitor "$HC_URL/start"
restic backup --exclude-file=/etc/restic/excludes.txt /etc /home /var/www
rc=$?
# Run retention after a clean or partial backup, but not after a hard failure.
if [ "$rc" -eq 0 ] || [ "$rc" -eq 3 ]; then
restic forget --keep-daily 7 --keep-weekly 4 --keep-monthly 6 --prune || rc=$?
fi
if [ "$rc" -eq 0 ]; then
ping_monitor "$HC_URL"
else
ping_monitor "$HC_URL/fail"
fi
exit "$rc"Three details matter here.
- The
|| trueinsideping_monitorstops a monitoring outage from failing the backup itself. - The script still ends with
exit "$rc". systemd sees the original result, so theOnFailure=hook in the next section works. - The
/startping lets the monitor measure run time. It also flags a job that starts and never finishes, for example one hung on a dead network connection.
The same pattern works for Borg. Run borg create, store $?, and treat 1 as a warning you may want to report with /fail or a separate message. Run borg prune and borg compact only when the create step did not return 2 or higher.
Alerting from systemd with OnFailure
A oneshot service that exits non-zero enters the failed state. You can attach a second unit that systemd starts when this happens. This works without changes to the script, so it also catches crashes, a missing script, or a permissions error before the script even starts.
First create a template unit. The %i is the instance name, which will be the name of the failing unit.
# /etc/systemd/system/[email protected]
[Unit]
Description=Failure notification for %i
[Service]
Type=oneshot
ExecStart=/usr/local/bin/notify-failure.sh %iThen create the script it calls. It sends the last 30 journal lines for the failed unit, which usually contain the restic or Borg error text. It assumes a working mail command on the server, such as from msmtp or Postfix. Replace the address with your own.
#!/bin/bash
set -u
unit="$1"
host=$(hostname -f)
log=$(journalctl -u "$unit" -n 30 --no-pager)
printf 'Backup unit %s failed on %s\n\n%s\n' "$unit" "$host" "$log" \
| mail -s "BACKUP FAILED: $unit on $host" [email protected]Make it executable with chmod 755 /usr/local/bin/notify-failure.sh. Finally, attach it to the backup service with a drop-in file. Running systemctl edit restic-backup.service opens an editor for it. Add:
[Unit]
OnFailure=backup-failure@%n.serviceHere %n expands to the full unit name, restic-backup.service, which becomes the instance name %i in the template. Reload and test the whole path before you rely on it:
systemctl daemon-reload
systemctl start [email protected]
journalctl -u [email protected] -n 5 --no-pagerStarting the notification unit by hand proves that mail delivery works. A notification path you have never tested is a guess.
Catching jobs that never run
OnFailure= only reports failures of a unit that started. It says nothing if the timer was disabled, the machine lost power, or the unit file has a syntax error. The two defenses are an external dead man's switch and a freshness check.
A dead man's switch is the ping pattern above. The monitor knows the expected schedule, for example once a day with a grace period of a few hours. If no success ping arrives in that window, it alerts you. Because the monitor lives outside your server, it keeps working when the server is down. Services such as Healthchecks.io, Uptime Kuma, or Cronitor offer this. You can also self-host one on a different machine.
A freshness check asks the repository directly how old the newest snapshot is. This catches a case the exit code cannot: the job reports success but backed up the wrong thing, or a different job is writing to the repository. Run it from a machine other than the one being backed up if you can.
#!/bin/bash
set -euo pipefail
export RESTIC_REPOSITORY=sftp:[email protected]:/srv/restic/myserver
export RESTIC_PASSWORD_FILE=/etc/restic/password
MAX_AGE_HOURS=30
latest=$(restic snapshots --host "$(hostname)" --latest 1 --json | jq -r 'map(.time) | max')
if [ -z "$latest" ] || [ "$latest" = "null" ]; then
echo "CRITICAL: no snapshots found for $(hostname)"
exit 2
fi
age_hours=$(( ( $(date +%s) - $(date -d "$latest" +%s) ) / 3600 ))
if [ "$age_hours" -gt "$MAX_AGE_HOURS" ]; then
echo "CRITICAL: newest snapshot is ${age_hours}h old (limit ${MAX_AGE_HOURS}h)"
exit 1
fi
echo "OK: newest snapshot is ${age_hours}h old"The limit is 30 hours for a daily job. That allows for the RandomizedDelaySec spread and a slow run, without waiting two full days to notice a missed night. The exit codes follow the Nagios plugin convention, so a monitoring system can run the script directly. For Borg, borg list --last 1 --json returns the newest archive with a time field you can parse the same way.
Reading the logs when an alert arrives
When an alert fires, start with systemd, which keeps the output of every run:
systemctl status restic-backup.service
journalctl -u restic-backup.service --since "yesterday" --no-pager
systemctl list-timers restic-backup.timerThe list-timers output shows the last and next trigger time. If LAST is days old, the problem is scheduling, not restic. Common causes of an actual failure are:
- Stale lock. A previous run was killed and left a lock. Restic reports exit
11or a "repository is already locked" message. After you confirm no other backup is running,restic unlockremoves stale locks. - Network or SSH problem. The SFTP or SSH connection timed out or the host key changed.
- Full disk on the repository host. Writes fail partway through.
- Rotated password file or passphrase. Restic exit
12, or a Borg passphrase error.
Exercise
Your backup script ends with exit "$rc", and restic-backup.service has OnFailure=backup-failure@%n.service. One night the server loses power at 01:00 and stays off until 09:00, so the 02:00 timer never fires. Which of your alert paths notifies you, and which does not? What change would make you hear about it on a day the server is off?
Show answer
Neither the exit-code check nor OnFailure= notifies you. No unit ran, so none failed, and the server was off and could not send anything. Only an external dead man's switch helps: the monitor expects a success ping every day, receives none before the grace period ends, and alerts you. A freshness check run from another machine would also report that the newest snapshot is too old. Because the timer uses Persistent=true, the missed run will start shortly after boot, but you still learn about the gap only through one of those external detectors.
Exercise
restic backup returns exit code 3, and your script uses set -e. What happens to restic forget --prune, and how does the script in this chapter change that?
Show answer
With set -e, the script exits at the failed command, so forget --prune never runs and old snapshots pile up. The chapter's script turns off set -e, stores the code in rc, and runs forget --prune when rc is 0 or 3. It then sends a /fail ping and exits with the non-zero code, so you still get an alert about the unreadable files.