Skip to content

Instantly share code, notes, and snippets.

@mcansky
Created June 18, 2015 14:12
Show Gist options
  • Save mcansky/07a86eab5213dcf80e46 to your computer and use it in GitHub Desktop.
Save mcansky/07a86eab5213dcf80e46 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Check that apt lock is off or on. If on, wait up to 60 seconds before trying
again and returning success (if released) or failure.
Author: Thomas R. R. Riboulet <[email protected]>
'''
import logging
import json
import time
import fcntl
# Set up logging
LOG = logging.getLogger(__name__)
def _apt_locked():
'''
Try locking the apt lock
True if locked
False if unlocked
'''
with open('/var/lib/dpkg/lock', 'w') as handle:
try:
fcntl.lockf(handle, fcntl.LOCK_EX | fcntl.LOCK_NB)
return False
except IOError:
return True
def check_lock():
'''
Check lock state and return success if it's free or released under 60 seconds
'''
if _apt_locked():
LOG.info("APT lock ON, waiting 60 seconds")
time.sleep(60)
if _apt_locked():
LOG.info("APT lock still ON, exiting")
return False
LOG.info("APT lock OFF")
return True
if __name__ == "__main__":
print check_lock()
@Reiner030
Copy link

Seems some kernel/other package updates broke something with lslocks so it took very long to check:

# time (lslocks -r -o PATH | grep /var/lib/dpkg/lock)

    real    0m16.080s
    user    0m0.976s
    sys     0m15.104s

A nice solution I found is checking it with lsof instead:

# time (lsof | grep -q /var/lib/dpkg/lock)

    real    0m2.715s
    user    0m1.364s
    sys     0m1.184s

but for this the package has to be installed first.
So I decided to put two different checks before which programs are setup by default:

  • test (from bash/shell) to see if lockfile exists
  • fuser to check if a program is accessing it
jenkins-package:
  module.run:
    - name: apt_lock_wait.check_lock
    - onlyif: test -f /var/lib/dpkg/lock && `fuser /var/lib/dpkg/lock >/dev/null 2>&1` && `lslocks -r -o PATH | grep -q /var/lib/dpkg/lock`
  pkg.installed:
    - name: jenkins

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment