1
from __future__ import absolute_import, division
8
from . import (LockBase, LockFailed, NotLocked, NotMyLock, LockTimeout,
12
class MkdirLockFile(LockBase):
13
"""Lock file by creating a directory."""
14
def __init__(self, path, threaded=True, timeout=None):
16
>>> lock = MkdirLockFile('somefile')
17
>>> lock = MkdirLockFile('somefile', threaded=False)
19
LockBase.__init__(self, path, threaded, timeout)
20
# Lock file itself is a directory. Place the unique file name into
22
self.unique_name = os.path.join(self.lock_file,
23
"%s.%s%s" % (self.hostname,
27
def acquire(self, timeout=None):
28
timeout = timeout if timeout is not None else self.timeout
29
end_time = time.time()
30
if timeout is not None and timeout > 0:
36
wait = max(0, timeout / 10)
40
os.mkdir(self.lock_file)
42
err = sys.exc_info()[1]
43
if err.errno == errno.EEXIST:
45
if os.path.exists(self.unique_name):
46
# Already locked by me.
48
if timeout is not None and time.time() > end_time:
50
raise LockTimeout("Timeout waiting to acquire"
54
# Someone else has the lock.
55
raise AlreadyLocked("%s is already locked" %
59
# Couldn't create the lock for some other reason
60
raise LockFailed("failed to create %s" % self.lock_file)
62
open(self.unique_name, "wb").close()
66
if not self.is_locked():
67
raise NotLocked("%s is not locked" % self.path)
68
elif not os.path.exists(self.unique_name):
69
raise NotMyLock("%s is locked, but not by me" % self.path)
70
os.unlink(self.unique_name)
71
os.rmdir(self.lock_file)
74
return os.path.exists(self.lock_file)
76
def i_am_locking(self):
77
return (self.is_locked() and
78
os.path.exists(self.unique_name))
81
if os.path.exists(self.lock_file):
82
for name in os.listdir(self.lock_file):
83
os.unlink(os.path.join(self.lock_file, name))
84
os.rmdir(self.lock_file)