Automation will be the death of me

Automation will be the death of me.
I’m a 20-year Linux end-user running KDE-Neon (Ubuntu LTS) desktop in a home-office environment.
I’ve been trying to have systemd handle backups on a Desktop before poweroff. This is easy on a local drive with Rdiff-Backup. But the remote Restic backup (to B2) almost always fails, and rarely tells me why.

Abandoned locks remain a common problem.
I also get: unable to open cache: unable to locate cache directory (XDG_CACHE_HOME and HOME unset) I have no idea what “XDG_CACHE_HOME and HOME unset” means. Does this have something to do with who owns the script, or it’s file location?

Here’s the latest status after running:
sudo systemctl stop restic-backup-script to simulate what happens at shutdown.

● restic-backup-script.service - Run restic-backup script at shutdown
Loaded: loaded (/etc/systemd/system/restic-backup-script.service; enabled; vendor preset: enabled)
Active: failed (Result: exit-code) since Sat 2019-11-02 00:08:50 MDT; 49min ago
Process: 14854 ExecStop=/home/lance/restic/restic-backup.sh (code=exited, status=1/FAILURE)
Main PID: 1135 (code=exited, status=0/SUCCESS)

Nov 02 00:08:46 Lance-Desktop restic-backup.sh[14854]: [1:46:42] 100.00% 223.063 GiB / 223.063 GiB 141578 / 141578 items 0 errors ETA 0:00
Nov 02 00:08:46 Lance-Desktop restic-backup.sh[14854]: duration: 1:46:42
Nov 02 00:08:46 Lance-Desktop restic-backup.sh[14854]: snapshot 6fe54f85 saved
Nov 02 00:08:49 Lance-Desktop restic-backup.sh[14854]: unable to open cache: unable to locate cache directory (XDG_CACHE_HOME and HOME unset)
Nov 02 00:08:50 Lance-Desktop restic-backup.sh[14854]: Fatal: unable to create lock in backend: repository is already locked by PID 2229 on Lance-Desktop by root (UID 0, GID 0)
Nov 02 00:08:50 Lance-Desktop restic-backup.sh[14854]: lock was created at 2019-11-01 13:01:27 (11h7m23.123314417s ago)
Nov 02 00:08:50 Lance-Desktop restic-backup.sh[14854]: storage ID xxxxxxxx
Nov 02 00:08:50 Lance-Desktop systemd[1]: restic-backup-script.service: Control process exited, code=exited status=1
Nov 02 00:08:50 Lance-Desktop systemd[1]: restic-backup-script.service: Failed with result ‘exit-code’.
Nov 02 00:08:50 Lance-Desktop systemd[1]: Stopped Run restic-backup script at shutdown.

The cache warning happens because systemd doesn’t set either of those environment variables by default. There’s a few possible solutions:

  • Do nothing and let restic operate without a cache.
  • Pass --cache-dir to restic.
  • Set either of those environment variables in the unit file.

The real problem is that there is a stale lock. This can be solved by running restic unlock before restic backup.

As @cdhowie said, you can “pass” restic environment config to your systemd unit:

[Service]
...
EnvironmentFile=/etc/sysconfig/restic_env
...

@LanceHaverkamp Please let us know the status of things after the replies you got, so that we can hopefully mark this as resolved.