On a Debian-based system I have a scheduled job (e.g. cron job, or systemd timer/service) which runs every 30 minutes. However, I don’t want that to happen concurrently with packages are being installed or updated.
Package installation can happen manually or on a schedule, but in the latter case there is a considerable randomized delay. I could adapt the schedule for my job to not interfere with a potential package update (whether something is actually installed or not), and remember to disable the job when installing packages manually, and remember to enable it afterwards – but that is not really satisfactory.
So I am looking for a reliable way to tell package installation is in progress, so my job can check for it and exit (or delay execution) if that is the case. If repository information is being updated or packages are being downloaded in the background concurrently with my job, that is not really an issue, but my job should not run while installation is happening (copying of files, configuration, pre/post-install scripts and similar).
On OPNsense (which is FreeBSD based) the system updater acquires a lock on a particular file, so I have wrapped my job inside flock
. If an update is in progress, my job would be skipped. If an upgrade were to be triggered while my job is running, presumably the upgrade would fail with a message indicating another update is in progress.
I am wondering if apt on Debian has something similar, such as a lock file that I can check on. If so – is that mechanism exclusive to a particular package management frontend or would it work with all of the standard tools for .deb packages (e.g. dpkg, apt, aptitude, synaptic and the like)?
I see that when Synaptic is open and I try to run sudo apt-get upgrade
, I get:
E: Could not get lock /var/lib/dpkg/lock-frontend. It is held by process 1234 (synaptic)
N: Be aware that removing the lock file is not a solution and may break your system.
E: Unable to acquire the dpkg frontend lock (/var/lib/dpkg/lock-frontend), is another process using it?
However, sudo flock -n /var/lib/dpkg/lock-frontend sleep 10 || echo File is locked
succeeds (i.e. flock
returns true
, indicating that I have obtained the lock, sleep
executes while echo
does not) even while Synaptic is running (though not currently installing anything). Same behavior with /var/lib/dpkg/lock
.
So how can I obtain a “lock on package installation”?
dpkg
is runningtrue
as intended, even when idle, because APT is waiting for input. If APT shouldn't be running, test for either lock file mentioned. If the test is true, delay the service until the test is false, or test for false and start the service.