14 '''Class to handle creating and removing lockfiles'''
22 addr =
lambda self:
'%d@%s' % (self.
pid, self.
host)
23 fddr =
lambda self:
'<%s %s>' % (self.
path, self.
addr())
24 pddr =
lambda self, lock:
'<%s %s@%s>' %\
25 (self.
path, lock[
'pid'], lock[
'host'])
27 def __init__(self, path, debug=None, blocking = False):
28 self.
pid = os.getpid()
29 self.
host = socket.gethostname()
37 '''Acquire a lock, returning self if successful, False otherwise'''
41 print(
'Previous lock detected: %s' % self.
pddr(lock))
44 fd = os.open(self.
path, os.O_RDWR | os.O_CREAT, 0o777)
45 fh = os.fdopen(fd,
'r+')
49 fcntlflag = fcntl.LOCK_EX
51 fcntlflag |= fcntl.LOCK_NB
52 fcntl.lockf(fh, fcntlflag)
55 print(
'Unable to acquire lock on %s: existing lock %s' % (self.
path, fh.read()))
63 modtime = os.stat(self.
path)
64 outstring =
'Acquired lock: '+ self.
fddr() +
' at time '+ time.ctime(modtime.st_mtime)
66 except Exception
as e:
67 if os.path.isfile(self.
path):
75 'Error acquiring lock: %s, reason %s' % (self.
fddr(), e))
79 '''Release lock, returning self'''
83 fcntl.lockf(fh, fcntl.LOCK_UN)
91 outstring =
'Released lock: ' + self.
fddr() +
' at time ' + time.ctime()
93 except Exception
as e:
96 'Error releasing lock: %s, reason %s' % (self.
fddr(), e))
100 '''Internal method to read lock info'''
104 data = fh.read().rstrip().
split(
'@')
106 lock[
'pid'], lock[
'host'] = data
109 return {
'pid': 8**10,
'host':
''}
112 '''Check if we already have a lock'''
116 '''Check if we own the lock'''
120 '''Magic method to clean up lock when program exits'''