locking.py 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  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 modify(self, key, op):
  159. roster = self.load()
  160. try:
  161. elements = set(tuple(e) for e in roster[key])
  162. except KeyError:
  163. elements = set()
  164. if op == ADD:
  165. elements.add(self.id)
  166. elif op == REMOVE:
  167. elements.remove(self.id)
  168. else:
  169. raise ValueError('Unknown LockRoster op %r' % op)
  170. roster[key] = list(list(e) for e in elements)
  171. self.save(roster)
  172. class UpgradableLock:
  173. """
  174. A Lock for a resource that can be accessed in a shared or exclusive way.
  175. Typically, write access to a resource needs an exclusive lock (1 writer,
  176. noone is allowed reading) and read access to a resource needs a shared
  177. lock (multiple readers are allowed).
  178. If possible, try to use the contextmanager here like::
  179. with UpgradableLock(...) as lock:
  180. ...
  181. This makes sure the lock is released again if the block is left, no
  182. matter how (e.g. if an exception occurred).
  183. """
  184. def __init__(self, path, exclusive=False, sleep=None, timeout=None, id=None):
  185. self.path = path
  186. self.is_exclusive = exclusive
  187. self.sleep = sleep
  188. self.timeout = timeout
  189. self.id = id or get_id()
  190. # globally keeping track of shared and exclusive lockers:
  191. self._roster = LockRoster(path + '.roster', id=id)
  192. # an exclusive lock, used for:
  193. # - holding while doing roster queries / updates
  194. # - holding while the UpgradableLock itself is exclusive
  195. self._lock = ExclusiveLock(path + '.exclusive', id=id, timeout=timeout)
  196. def __enter__(self):
  197. return self.acquire()
  198. def __exit__(self, *exc):
  199. self.release()
  200. def __repr__(self):
  201. return "<%s: %r>" % (self.__class__.__name__, self.id)
  202. def acquire(self, exclusive=None, remove=None, sleep=None):
  203. if exclusive is None:
  204. exclusive = self.is_exclusive
  205. sleep = sleep or self.sleep or 0.2
  206. if exclusive:
  207. self._wait_for_readers_finishing(remove, sleep)
  208. self._roster.modify(EXCLUSIVE, ADD)
  209. else:
  210. with self._lock:
  211. if remove is not None:
  212. self._roster.modify(remove, REMOVE)
  213. self._roster.modify(SHARED, ADD)
  214. self.is_exclusive = exclusive
  215. return self
  216. def _wait_for_readers_finishing(self, remove, sleep):
  217. timer = TimeoutTimer(self.timeout, sleep).start()
  218. while True:
  219. self._lock.acquire()
  220. try:
  221. if remove is not None:
  222. self._roster.modify(remove, REMOVE)
  223. if len(self._roster.get(SHARED)) == 0:
  224. return # we are the only one and we keep the lock!
  225. # restore the roster state as before (undo the roster change):
  226. if remove is not None:
  227. self._roster.modify(remove, ADD)
  228. except:
  229. # avoid orphan lock when an exception happens here, e.g. Ctrl-C!
  230. self._lock.release()
  231. raise
  232. else:
  233. self._lock.release()
  234. if timer.timed_out_or_sleep():
  235. raise LockTimeout(self.path)
  236. def release(self):
  237. if self.is_exclusive:
  238. self._roster.modify(EXCLUSIVE, REMOVE)
  239. self._lock.release()
  240. else:
  241. with self._lock:
  242. self._roster.modify(SHARED, REMOVE)
  243. def upgrade(self):
  244. if not self.is_exclusive:
  245. self.acquire(exclusive=True, remove=SHARED)
  246. def downgrade(self):
  247. if self.is_exclusive:
  248. self.acquire(exclusive=False, remove=EXCLUSIVE)
  249. def break_lock(self):
  250. self._roster.remove()
  251. self._lock.break_lock()