1.1 --- a/imiptools/filesys.py Mon Feb 09 15:32:36 2015 +0100
1.2 +++ b/imiptools/filesys.py Mon Feb 09 16:34:24 2015 +0100
1.3 @@ -19,9 +19,11 @@
1.4 this program. If not, see <http://www.gnu.org/licenses/>.
1.5 """
1.6
1.7 +import errno
1.8 from imiptools.config import DEFAULT_PERMISSIONS
1.9 from os.path import abspath, commonprefix, exists, join
1.10 -from os import chmod, makedirs
1.11 +from os import chmod, makedirs, mkdir, rmdir
1.12 +from time import sleep, time
1.13
1.14 def check_dir(base, dir):
1.15 return commonprefix([base, abspath(dir)]) == base
1.16 @@ -36,6 +38,8 @@
1.17
1.18 "Basic filesystem operations."
1.19
1.20 + lock_name = "__lock__"
1.21 +
1.22 def __init__(self, store_dir):
1.23 self.store_dir = store_dir
1.24 if not exists(self.store_dir):
1.25 @@ -66,4 +70,45 @@
1.26
1.27 return filename
1.28
1.29 + # Locking methods.
1.30 + # This uses the directory creation method exploited by MoinMoin.util.lock.
1.31 + # However, a simple single lock type mechanism is employed here.
1.32 +
1.33 + def get_lock_dir(self, *parts):
1.34 + parts = parts and list(parts) or []
1.35 + parts.append(self.lock_name)
1.36 + return self.get_object_in_store(*parts)
1.37 +
1.38 + def acquire_lock(self, timeout=None, *parts):
1.39 +
1.40 + """
1.41 + Acquire an exclusive lock on the directory or a path within it described
1.42 + by 'parts'.
1.43 + """
1.44 +
1.45 + start = now = time()
1.46 +
1.47 + while not timeout or now - start < timeout:
1.48 + try:
1.49 + mkdir(self.get_lock_dir(*parts))
1.50 + break
1.51 + except OSError, exc:
1.52 + if exc.errno != errno.EEXIST:
1.53 + raise
1.54 + sleep(1)
1.55 + now = time()
1.56 +
1.57 + def release_lock(self, *parts):
1.58 +
1.59 + """
1.60 + Release an acquired lock on the directory or a path within it described
1.61 + by 'parts'.
1.62 + """
1.63 +
1.64 + try:
1.65 + rmdir(self.get_lock_dir(*parts))
1.66 + except OSError, exc:
1.67 + if exc.errno != errno.ENOENT:
1.68 + raise
1.69 +
1.70 # vim: tabstop=4 expandtab shiftwidth=4