locking.py 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  1. import json
  2. import os
  3. import socket
  4. import time
  5. from borg.helpers import Error, ErrorWithTraceback
  6. ADD, REMOVE = 'add', 'remove'
  7. SHARED, EXCLUSIVE = 'shared', 'exclusive'
  8. # only determine the PID and hostname once.
  9. # for FUSE mounts, we fork a child process that needs to release
  10. # the lock made by the parent, so it needs to use the same PID for that.
  11. _pid = os.getpid()
  12. _hostname = socket.gethostname()
  13. def get_id():
  14. """Get identification tuple for 'us'"""
  15. thread_id = 0
  16. return _hostname, _pid, thread_id
  17. class TimeoutTimer:
  18. """
  19. A timer for timeout checks (can also deal with no timeout, give timeout=None [default]).
  20. It can also compute and optionally execute a reasonable sleep time (e.g. to avoid
  21. polling too often or to support thread/process rescheduling).
  22. """
  23. def __init__(self, timeout=None, sleep=None):
  24. """
  25. Initialize a timer.
  26. :param timeout: time out interval [s] or None (no timeout)
  27. :param sleep: sleep interval [s] (>= 0: do sleep call, <0: don't call sleep)
  28. or None (autocompute: use 10% of timeout [but not more than 60s],
  29. or 1s for no timeout)
  30. """
  31. if timeout is not None and timeout < 0:
  32. raise ValueError("timeout must be >= 0")
  33. self.timeout_interval = timeout
  34. if sleep is None:
  35. if timeout is None:
  36. sleep = 1.0
  37. else:
  38. sleep = min(60.0, timeout / 10.0)
  39. self.sleep_interval = sleep
  40. self.start_time = None
  41. self.end_time = None
  42. def __repr__(self):
  43. return "<%s: start=%r end=%r timeout=%r sleep=%r>" % (
  44. self.__class__.__name__, self.start_time, self.end_time,
  45. self.timeout_interval, self.sleep_interval)
  46. def start(self):
  47. self.start_time = time.time()
  48. if self.timeout_interval is not None:
  49. self.end_time = self.start_time + self.timeout_interval
  50. return self
  51. def sleep(self):
  52. if self.sleep_interval >= 0:
  53. time.sleep(self.sleep_interval)
  54. def timed_out(self):
  55. return self.end_time is not None and time.time() >= self.end_time
  56. def timed_out_or_sleep(self):
  57. if self.timed_out():
  58. return True
  59. else:
  60. self.sleep()
  61. return False
  62. class LockError(Error):
  63. """Failed to acquire the lock {}."""
  64. class LockErrorT(ErrorWithTraceback):
  65. """Failed to acquire the lock {}."""
  66. class LockTimeout(LockError):
  67. """Failed to create/acquire the lock {} (timeout)."""
  68. class LockFailed(LockErrorT):
  69. """Failed to create/acquire the lock {} ({})."""
  70. class NotLocked(LockErrorT):
  71. """Failed to release the lock {} (was not locked)."""
  72. class NotMyLock(LockErrorT):
  73. """Failed to release the lock {} (was/is locked, but not by me)."""
  74. class ExclusiveLock:
  75. """An exclusive Lock based on mkdir fs operation being atomic.
  76. If possible, try to use the contextmanager here like::
  77. with ExclusiveLock(...) as lock:
  78. ...
  79. This makes sure the lock is released again if the block is left, no
  80. matter how (e.g. if an exception occurred).
  81. """
  82. def __init__(self, path, timeout=None, sleep=None, id=None):
  83. self.timeout = timeout
  84. self.sleep = sleep
  85. self.path = os.path.abspath(path)
  86. self.id = id or get_id()
  87. self.unique_name = os.path.join(self.path, "%s.%d-%x" % self.id)
  88. def __enter__(self):
  89. return self.acquire()
  90. def __exit__(self, *exc):
  91. self.release()
  92. def __repr__(self):
  93. return "<%s: %r>" % (self.__class__.__name__, self.unique_name)
  94. def acquire(self, timeout=None, sleep=None):
  95. if timeout is None:
  96. timeout = self.timeout
  97. if sleep is None:
  98. sleep = self.sleep
  99. timer = TimeoutTimer(timeout, sleep).start()
  100. while True:
  101. try:
  102. os.mkdir(self.path)
  103. except FileExistsError: # already locked
  104. if self.by_me():
  105. return self
  106. if timer.timed_out_or_sleep():
  107. raise LockTimeout(self.path)
  108. except OSError as err:
  109. raise LockFailed(self.path, str(err)) from None
  110. else:
  111. with open(self.unique_name, "wb"):
  112. pass
  113. return self
  114. def release(self):
  115. if not self.is_locked():
  116. raise NotLocked(self.path)
  117. if not self.by_me():
  118. raise NotMyLock(self.path)
  119. os.unlink(self.unique_name)
  120. os.rmdir(self.path)
  121. def is_locked(self):
  122. return os.path.exists(self.path)
  123. def by_me(self):
  124. return os.path.exists(self.unique_name)
  125. def break_lock(self):
  126. if self.is_locked():
  127. for name in os.listdir(self.path):
  128. os.unlink(os.path.join(self.path, name))
  129. os.rmdir(self.path)
  130. class LockRoster:
  131. """
  132. A Lock Roster to track shared/exclusive lockers.
  133. Note: you usually should call the methods with an exclusive lock held,
  134. to avoid conflicting access by multiple threads/processes/machines.
  135. """
  136. def __init__(self, path, id=None):
  137. self.path = path
  138. self.id = id or get_id()
  139. def load(self):
  140. try:
  141. with open(self.path) as f:
  142. data = json.load(f)
  143. except (FileNotFoundError, ValueError):
  144. # no or corrupt/empty roster file?
  145. data = {}
  146. return data
  147. def save(self, data):
  148. with open(self.path, "w") as f:
  149. json.dump(data, f)
  150. def remove(self):
  151. try:
  152. os.unlink(self.path)
  153. except FileNotFoundError:
  154. pass
  155. def get(self, key):
  156. roster = self.load()
  157. return set(tuple(e) for e in roster.get(key, []))
  158. def empty(self, *keys):
  159. return all(not self.get(key) for key in keys)
  160. def modify(self, key, op):
  161. roster = self.load()
  162. try:
  163. elements = set(tuple(e) for e in roster[key])
  164. except KeyError:
  165. elements = set()
  166. if op == ADD:
  167. elements.add(self.id)
  168. elif op == REMOVE:
  169. elements.remove(self.id)
  170. else:
  171. raise ValueError('Unknown LockRoster op %r' % op)
  172. roster[key] = list(list(e) for e in elements)
  173. self.save(roster)
  174. class Lock:
  175. """
  176. A Lock for a resource that can be accessed in a shared or exclusive way.
  177. Typically, write access to a resource needs an exclusive lock (1 writer,
  178. noone is allowed reading) and read access to a resource needs a shared
  179. lock (multiple readers are allowed).
  180. If possible, try to use the contextmanager here like::
  181. with Lock(...) as lock:
  182. ...
  183. This makes sure the lock is released again if the block is left, no
  184. matter how (e.g. if an exception occurred).
  185. """
  186. def __init__(self, path, exclusive=False, sleep=None, timeout=None, id=None):
  187. self.path = path
  188. self.is_exclusive = exclusive
  189. self.sleep = sleep
  190. self.timeout = timeout
  191. self.id = id or get_id()
  192. # globally keeping track of shared and exclusive lockers:
  193. self._roster = LockRoster(path + '.roster', id=id)
  194. # an exclusive lock, used for:
  195. # - holding while doing roster queries / updates
  196. # - holding while the Lock instance itself is exclusive
  197. self._lock = ExclusiveLock(path + '.exclusive', id=id, timeout=timeout)
  198. def __enter__(self):
  199. return self.acquire()
  200. def __exit__(self, *exc):
  201. self.release()
  202. def __repr__(self):
  203. return "<%s: %r>" % (self.__class__.__name__, self.id)
  204. def acquire(self, exclusive=None, remove=None, sleep=None):
  205. if exclusive is None:
  206. exclusive = self.is_exclusive
  207. sleep = sleep or self.sleep or 0.2
  208. if exclusive:
  209. self._wait_for_readers_finishing(remove, sleep)
  210. self._roster.modify(EXCLUSIVE, ADD)
  211. else:
  212. with self._lock:
  213. if remove is not None:
  214. self._roster.modify(remove, REMOVE)
  215. self._roster.modify(SHARED, ADD)
  216. self.is_exclusive = exclusive
  217. return self
  218. def _wait_for_readers_finishing(self, remove, sleep):
  219. timer = TimeoutTimer(self.timeout, sleep).start()
  220. while True:
  221. self._lock.acquire()
  222. try:
  223. if remove is not None:
  224. self._roster.modify(remove, REMOVE)
  225. if len(self._roster.get(SHARED)) == 0:
  226. return # we are the only one and we keep the lock!
  227. # restore the roster state as before (undo the roster change):
  228. if remove is not None:
  229. self._roster.modify(remove, ADD)
  230. except:
  231. # avoid orphan lock when an exception happens here, e.g. Ctrl-C!
  232. self._lock.release()
  233. raise
  234. else:
  235. self._lock.release()
  236. if timer.timed_out_or_sleep():
  237. raise LockTimeout(self.path)
  238. def release(self):
  239. if self.is_exclusive:
  240. self._roster.modify(EXCLUSIVE, REMOVE)
  241. if self._roster.empty(EXCLUSIVE, SHARED):
  242. self._roster.remove()
  243. self._lock.release()
  244. else:
  245. with self._lock:
  246. self._roster.modify(SHARED, REMOVE)
  247. if self._roster.empty(EXCLUSIVE, SHARED):
  248. self._roster.remove()
  249. def upgrade(self):
  250. # WARNING: if multiple read-lockers want to upgrade, it will deadlock because they
  251. # all will wait until the other read locks go away - and that won't happen.
  252. if not self.is_exclusive:
  253. self.acquire(exclusive=True, remove=SHARED)
  254. def downgrade(self):
  255. if self.is_exclusive:
  256. self.acquire(exclusive=False, remove=EXCLUSIVE)
  257. def got_exclusive_lock(self):
  258. return self.is_exclusive and self._lock.is_locked() and self._lock.by_me()
  259. def break_lock(self):
  260. self._roster.remove()
  261. self._lock.break_lock()