1
from __future__ import absolute_import, division
8
from . import (LockBase, LockFailed, NotLocked, NotMyLock, LockTimeout,
11
class MkdirLockFile(LockBase):
12
"""Lock file by creating a directory."""
13
def __init__(self, path, threaded=True):
15
>>> lock = MkdirLockFile('somefile')
16
>>> lock = MkdirLockFile('somefile', threaded=False)
18
LockBase.__init__(self, path, threaded)
19
# Lock file itself is a directory. Place the unique file name into
21
self.unique_name = os.path.join(self.lock_file,
22
"%s.%s%s" % (self.hostname,
26
def acquire(self, timeout=None):
27
end_time = time.time()
28
if timeout is not None and timeout > 0:
34
wait = max(0, timeout / 10)
38
os.mkdir(self.lock_file)
40
err = sys.exc_info()[1]
41
if err.errno == errno.EEXIST:
43
if os.path.exists(self.unique_name):
44
# Already locked by me.
46
if timeout is not None and time.time() > end_time:
50
# Someone else has the lock.
54
# Couldn't create the lock for some other reason
55
raise LockFailed("failed to create %s" % self.lock_file)
57
open(self.unique_name, "wb").close()
61
if not self.is_locked():
63
elif not os.path.exists(self.unique_name):
65
os.unlink(self.unique_name)
66
os.rmdir(self.lock_file)
69
return os.path.exists(self.lock_file)
71
def i_am_locking(self):
72
return (self.is_locked() and
73
os.path.exists(self.unique_name))
76
if os.path.exists(self.lock_file):
77
for name in os.listdir(self.lock_file):
78
os.unlink(os.path.join(self.lock_file, name))
79
os.rmdir(self.lock_file)