What I’m trying to do and why
I’ve got pre/post backup scripts that run which do some things like take snapshots of filesystems/vms. Currently they are set up in a way where if two instances of borgmatic run simultaneously they will fight each other and then an inconsistent backup would be taken. My current solution to this is to create a script which wraps borgmatic and uses flock to take a lock on the filesystem which prevents a second borgmatic instance from running. The script is shown below. I renamed borgmatic to _borgmatic so that I don’t accidentally run it. (It would be cleaner to just named the script something else and just use a non default config file, but this works fine for now)
#!/bin/sh lockpath=/.backups flock -xn -E201 $lockpath /root/.local/bin/_borgmatic "$@" if [ $? -eq 201 ]; then echo "Failed to acquire lock for $lockpath" exit 201 fi
It would be cleaner if you borgmatic could just grab a lock itself for the length of its execution.
Other notes / implementation ideas
Python does have a flock module for filesystem locking. The nice thing about locks created with that mechanism is they disappear when the program closes. I believe its as simple as doing something like this.
pidfile = open("/etc/borgmatic/config.yaml", "r") try: fcntl.flock(self.pidfile.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB) except IOError: self.pidfile = None raise SystemExit("Already running according to " + self.path)
I’m not sure if you’d want to use the config file as the file to lock. The one thing I remember was that when the handle to the file gets garbage collected (
pidfile in this case) the lock get dropped, so it needs to be to a file handle that is open for the length of the program.
If Windows needs to be supported, I’d imagine there is something similar, but I’m not sure what