7 from __future__
import print_function
15 '''Class to handle creating and removing lockfiles'''
23 addr =
lambda self:
'%d@%s' % (self.
pid, self.
host)
24 fddr =
lambda self:
'<%s %s>' % (self.
path, self.
addr())
25 pddr =
lambda self, lock:
'<%s %s@%s>' %\
26 (self.
path, lock[
'pid'], lock[
'host'])
28 def __init__(self, path, debug=None, blocking = False):
29 self.
pid = os.getpid()
30 self.
host = socket.gethostname()
38 '''Acquire a lock, returning self if successful, False otherwise'''
42 print(
'Previous lock detected: %s' % self.
pddr(lock))
45 fd = os.open(self.
path, os.O_RDWR | os.O_CREAT, 0o777)
46 fh = os.fdopen(fd,
'r+')
50 fcntlflag = fcntl.LOCK_EX
52 fcntlflag |= fcntl.LOCK_NB
53 fcntl.lockf(fh, fcntlflag)
56 print(
'Unable to acquire lock on %s: existing lock %s' % (self.
path, fh.read()))
64 modtime = os.stat(self.
path)
65 outstring =
'Acquired lock: '+ self.
fddr() +
' at time '+ time.ctime(modtime.st_mtime)
67 except Exception
as e:
68 if os.path.isfile(self.
path):
76 'Error acquiring lock: %s, reason %s' % (self.
fddr(), e))
80 '''Release lock, returning self'''
84 fcntl.lockf(fh, fcntl.LOCK_UN)
92 outstring =
'Released lock: ' + self.
fddr() +
' at time ' + time.ctime()
94 except Exception
as e:
97 'Error releasing lock: %s, reason %s' % (self.
fddr(), e))
101 '''Internal method to read lock info'''
105 data = fh.read().rstrip().
split(
'@')
107 lock[
'pid'], lock[
'host'] = data
110 return {
'pid': 8**10,
'host':
''}
113 '''Check if we already have a lock'''
117 '''Check if we own the lock'''
121 '''Magic method to clean up lock when program exits'''