Sub topic 12
Scheduling backups with systemd
This chapter assumes you have a working backup command from the earlier chapters: an initialized repository, a password file or passphrase command, and a retention policy you have tested by hand. Here you wrap that command in a script, run it from a systemd service, and trigger it with a timer. You should be comfortable writing unit files and reading journalctl output.
Why a timer instead of cron
Cron works, but a systemd timer gives you several things that suit backups:
- Output goes to the journal with no mail setup, and you can read it with
journalctl -u. Persistent=trueruns a job that was missed while the machine was off.RandomizedDelaySecspreads start times, so many servers do not hit one backup host at the same moment.- The service can declare dependencies, such as waiting for the network, and resource limits such as CPU and I/O priority.
systemctl statusandsystemctl list-timersshow the last run, the result and the next run.
A timer never runs your command directly. A timer unit activates a service unit of the same name, and the service runs the script.
The backup script
Keep the logic in a script and keep the unit files thin. You can then run the script by hand to test it, and the service runs the same code. Save this as /usr/local/bin/restic-backup.sh and make it executable with chmod 700:
#!/bin/bash
set -euo pipefail
export RESTIC_REPOSITORY=sftp:[email protected]:/srv/restic/myserver
export RESTIC_PASSWORD_FILE=/etc/restic/password
restic backup --exclude-file=/etc/restic/excludes.txt /etc /home /var/www
restic forget --keep-daily 7 --keep-weekly 4 --keep-monthly 6 --pruneset -euo pipefail makes the script stop at the first failing command, treat unset variables as errors, and fail when any command in a pipeline fails. This matters. Without it, a failed restic backup would be followed by a forget --prune that still deletes old snapshots, and the run would look successful if the last command passed.
Use chmod 600 on /etc/restic/password and make sure only root can read it. The service runs as root here because it needs to read /etc and other users' home directories.
Exit codes you will meet
set -e treats any non-zero exit as a failure, but the tools use non-zero codes with different meanings:
| Tool | Exit code | Meaning |
|---|---|---|
| restic | 0 | Snapshot created, all files read |
| restic | 1 | Fatal error, no snapshot created |
| restic | 3 | Snapshot created, but some source files could not be read (restic 0.13 and later) |
| Borg | 0 | Success |
| Borg | 1 | Warning, for example a file changed while being read |
| Borg | 2 or higher | Error |
With set -e, restic's exit code 3 aborts the script before forget runs, and the service is marked failed. That is usually what you want, because it tells you something is unreadable. If you decide a known warning is acceptable, handle it explicitly rather than turning set -e off:
#!/bin/bash
set -euo pipefail
export BORG_REPO=ssh://[email protected]/./borg/myserver
export BORG_PASSCOMMAND='cat /etc/borg/passphrase'
rc=0
borg create --stats --compression zstd '::{hostname}-{now:%Y-%m-%dT%H:%M:%S}' /etc /home /var/www || rc=$?
if [ "$rc" -ge 2 ]; then
echo "borg create failed with exit code $rc" >&2
exit "$rc"
fi
borg prune --keep-daily 7 --keep-weekly 4 --keep-monthly 6
borg compactHere a Borg warning (code 1) lets the run continue, and a real error stops it. Decide this on purpose. A warning such as "file changed while reading" on a busy log directory is normal, but a warning that hides a permissions problem is not.
The service unit
Create /etc/systemd/system/restic-backup.service:
[Unit]
Description=restic backup
Wants=network-online.target
After=network-online.target
[Service]
Type=oneshot
ExecStart=/usr/local/bin/restic-backup.sh
Nice=10
IOSchedulingClass=idleThe settings that matter:
Type=oneshottells systemd the unit is finished when the process exits. The unit staysinactivebetween runs, which is correct for a job.Wants=andAfter=network-online.targetmake the job wait until the network is configured. Without both lines, a run shortly after boot can start before the network is up and fail to reach the repository.Nice=10andIOSchedulingClass=idlelower the backup's CPU and disk priority, so it does not slow down your services during the run.- There is no
[Install]section. The timer starts this service, so you never enable the service itself.
The timer unit
Create /etc/systemd/system/restic-backup.timer:
[Unit]
Description=Run restic backup daily
[Timer]
OnCalendar=*-*-* 02:00:00
RandomizedDelaySec=30min
Persistent=true
[Install]
WantedBy=timers.targetOnCalendarsets when the job fires. The shorthanddailymeans midnight, which is when many other jobs run. An explicit*-*-* 02:00:00is clearer and easier to move.RandomizedDelaySec=30minadds a random delay of up to 30 minutes. Each machine picks its own delay, which spreads load on shared storage.Persistent=truestores the last trigger time on disk. If the server was off at 02:00, the timer fires the job right after the next boot. This option only has an effect withOnCalendar=.WantedBy=timers.targetis whatenableuses to start the timer at boot.
Check a calendar expression before you rely on it:
systemd-analyze calendar '*-*-* 02:00:00'The output shows the normalized form and the next time the expression fires.
Enabling and testing
Reload systemd so it sees the new files, then enable the timer. Export the Borg key before you rely on a Borg schedule, because a repository you cannot unlock is useless:
borg key export :: /root/borg-key-backup.txt
systemctl daemon-reload
systemctl enable --now restic-backup.timer
systemctl list-timers restic-backup.timerlist-timers shows the NEXT and LAST columns and which service the timer triggers. If NEXT is empty, the timer is not active.
Do not wait until 02:00 to find out whether the service works. Start it manually and watch the output:
systemctl start restic-backup.service
journalctl -u restic-backup.service -e
systemctl status restic-backup.servicesystemctl start blocks until a oneshot service finishes, so the command returns only when the backup is done. A first run on a large server can take a long time, so run it in a terminal multiplexer or use --no-block and follow with journalctl -fu restic-backup.service.
Overlapping runs and long backups
A timer will not start a second copy of a oneshot service that is still running. If a backup takes longer than the interval, the next trigger does nothing while the unit is active. That protects the repository from two concurrent writers in the same service.
Locks still matter across services. Restic takes locks in the repository, and Borg does too. If a run is killed, for example by a power loss, a stale lock can block later runs. Check the repository for stale locks before you remove one, and do not delete a lock while a backup may still be running.
Common errors
- The timer shows no
NEXTtime. You enabled the service instead of the timer, or you forgotdaemon-reload. Runsystemctl enable --now restic-backup.timer. - The run fails with
Permission deniedon the script. The script is not executable, orExecStarthas a wrong path. Runls -l /usr/local/bin/restic-backup.sh. - The run works by hand but fails from the timer. Compare environments. Set every variable the tool needs inside the script, as above, rather than relying on your shell profile.
- The backup is skipped after a reboot.
Persistent=trueis missing, or the clock is wrong. Checktimedatectl. - A real failure goes unnoticed. The unit failed, but nobody looked. Failure alerts are covered in a later chapter. For now, check
systemctl --failedand the journal by hand.
Exercise
A server is powered off from 01:30 to 06:00. Its timer has OnCalendar=--* 02:00:00 and RandomizedDelaySec=30min. Which setting makes the backup run after the server boots, and what happens if you remove it?
Show answer
Persistent=true makes the timer remember its last trigger. After boot, systemd sees that the 02:00 trigger was missed and starts the service shortly afterwards. If you remove it, the missed run is simply skipped, and the next backup happens at the following 02:00 (plus the random delay), so the recovery point is about a day older than you planned.
Exercise
Your script uses set -euo pipefail and runs restic backup followed by restic forget --prune. One file is unreadable, so restic backup exits with code 3. What does the service do, and why is this useful?
Show answer
The script stops at the failing command because of set -e. restic forget --prune does not run, and systemd marks the service as failed. This is useful because the failure is visible in systemctl status and the journal, and old snapshots are not pruned after an incomplete run.