test_lockfile.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  1. # Copyright (c) 2005 Divmod, Inc.
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. """
  5. Tests for L{twisted.python.lockfile}.
  6. """
  7. from __future__ import absolute_import, division
  8. import errno
  9. import os
  10. from twisted.trial import unittest
  11. from twisted.python import lockfile
  12. from twisted.python.reflect import requireModule
  13. from twisted.python.runtime import platform
  14. skipKill = None
  15. if platform.isWindows():
  16. if(requireModule('win32api.OpenProcess') is None and
  17. requireModule('pywintypes') is None
  18. ):
  19. skipKill = ("On windows, lockfile.kill is not implemented in the "
  20. "absence of win32api and/or pywintypes.")
  21. class UtilTests(unittest.TestCase):
  22. """
  23. Tests for the helper functions used to implement L{FilesystemLock}.
  24. """
  25. def test_symlinkEEXIST(self):
  26. """
  27. L{lockfile.symlink} raises L{OSError} with C{errno} set to L{EEXIST}
  28. when an attempt is made to create a symlink which already exists.
  29. """
  30. name = self.mktemp()
  31. lockfile.symlink('foo', name)
  32. exc = self.assertRaises(OSError, lockfile.symlink, 'foo', name)
  33. self.assertEqual(exc.errno, errno.EEXIST)
  34. def test_symlinkEIOWindows(self):
  35. """
  36. L{lockfile.symlink} raises L{OSError} with C{errno} set to L{EIO} when
  37. the underlying L{rename} call fails with L{EIO}.
  38. Renaming a file on Windows may fail if the target of the rename is in
  39. the process of being deleted (directory deletion appears not to be
  40. atomic).
  41. """
  42. name = self.mktemp()
  43. def fakeRename(src, dst):
  44. raise IOError(errno.EIO, None)
  45. self.patch(lockfile, 'rename', fakeRename)
  46. exc = self.assertRaises(IOError, lockfile.symlink, name, "foo")
  47. self.assertEqual(exc.errno, errno.EIO)
  48. if not platform.isWindows():
  49. test_symlinkEIOWindows.skip = (
  50. "special rename EIO handling only necessary and correct on "
  51. "Windows.")
  52. def test_readlinkENOENT(self):
  53. """
  54. L{lockfile.readlink} raises L{OSError} with C{errno} set to L{ENOENT}
  55. when an attempt is made to read a symlink which does not exist.
  56. """
  57. name = self.mktemp()
  58. exc = self.assertRaises(OSError, lockfile.readlink, name)
  59. self.assertEqual(exc.errno, errno.ENOENT)
  60. def test_readlinkEACCESWindows(self):
  61. """
  62. L{lockfile.readlink} raises L{OSError} with C{errno} set to L{EACCES}
  63. on Windows when the underlying file open attempt fails with C{EACCES}.
  64. Opening a file on Windows may fail if the path is inside a directory
  65. which is in the process of being deleted (directory deletion appears
  66. not to be atomic).
  67. """
  68. name = self.mktemp()
  69. def fakeOpen(path, mode):
  70. raise IOError(errno.EACCES, None)
  71. self.patch(lockfile, '_open', fakeOpen)
  72. exc = self.assertRaises(IOError, lockfile.readlink, name)
  73. self.assertEqual(exc.errno, errno.EACCES)
  74. if not platform.isWindows():
  75. test_readlinkEACCESWindows.skip = (
  76. "special readlink EACCES handling only necessary and correct on "
  77. "Windows.")
  78. def test_kill(self):
  79. """
  80. L{lockfile.kill} returns without error if passed the PID of a
  81. process which exists and signal C{0}.
  82. """
  83. lockfile.kill(os.getpid(), 0)
  84. test_kill.skip = skipKill
  85. def test_killESRCH(self):
  86. """
  87. L{lockfile.kill} raises L{OSError} with errno of L{ESRCH} if
  88. passed a PID which does not correspond to any process.
  89. """
  90. # Hopefully there is no process with PID 2 ** 31 - 1
  91. exc = self.assertRaises(OSError, lockfile.kill, 2 ** 31 - 1, 0)
  92. self.assertEqual(exc.errno, errno.ESRCH)
  93. test_killESRCH.skip = skipKill
  94. def test_noKillCall(self):
  95. """
  96. Verify that when L{lockfile.kill} does end up as None (e.g. on Windows
  97. without pywin32), it doesn't end up being called and raising a
  98. L{TypeError}.
  99. """
  100. self.patch(lockfile, "kill", None)
  101. fl = lockfile.FilesystemLock(self.mktemp())
  102. fl.lock()
  103. self.assertFalse(fl.lock())
  104. class LockingTests(unittest.TestCase):
  105. def _symlinkErrorTest(self, errno):
  106. def fakeSymlink(source, dest):
  107. raise OSError(errno, None)
  108. self.patch(lockfile, 'symlink', fakeSymlink)
  109. lockf = self.mktemp()
  110. lock = lockfile.FilesystemLock(lockf)
  111. exc = self.assertRaises(OSError, lock.lock)
  112. self.assertEqual(exc.errno, errno)
  113. def test_symlinkError(self):
  114. """
  115. An exception raised by C{symlink} other than C{EEXIST} is passed up to
  116. the caller of L{FilesystemLock.lock}.
  117. """
  118. self._symlinkErrorTest(errno.ENOSYS)
  119. def test_symlinkErrorPOSIX(self):
  120. """
  121. An L{OSError} raised by C{symlink} on a POSIX platform with an errno of
  122. C{EACCES} or C{EIO} is passed to the caller of L{FilesystemLock.lock}.
  123. On POSIX, unlike on Windows, these are unexpected errors which cannot
  124. be handled by L{FilesystemLock}.
  125. """
  126. self._symlinkErrorTest(errno.EACCES)
  127. self._symlinkErrorTest(errno.EIO)
  128. if platform.isWindows():
  129. test_symlinkErrorPOSIX.skip = (
  130. "POSIX-specific error propagation not expected on Windows.")
  131. def test_cleanlyAcquire(self):
  132. """
  133. If the lock has never been held, it can be acquired and the C{clean}
  134. and C{locked} attributes are set to C{True}.
  135. """
  136. lockf = self.mktemp()
  137. lock = lockfile.FilesystemLock(lockf)
  138. self.assertTrue(lock.lock())
  139. self.assertTrue(lock.clean)
  140. self.assertTrue(lock.locked)
  141. def test_cleanlyRelease(self):
  142. """
  143. If a lock is released cleanly, it can be re-acquired and the C{clean}
  144. and C{locked} attributes are set to C{True}.
  145. """
  146. lockf = self.mktemp()
  147. lock = lockfile.FilesystemLock(lockf)
  148. self.assertTrue(lock.lock())
  149. lock.unlock()
  150. self.assertFalse(lock.locked)
  151. lock = lockfile.FilesystemLock(lockf)
  152. self.assertTrue(lock.lock())
  153. self.assertTrue(lock.clean)
  154. self.assertTrue(lock.locked)
  155. def test_cannotLockLocked(self):
  156. """
  157. If a lock is currently locked, it cannot be locked again.
  158. """
  159. lockf = self.mktemp()
  160. firstLock = lockfile.FilesystemLock(lockf)
  161. self.assertTrue(firstLock.lock())
  162. secondLock = lockfile.FilesystemLock(lockf)
  163. self.assertFalse(secondLock.lock())
  164. self.assertFalse(secondLock.locked)
  165. def test_uncleanlyAcquire(self):
  166. """
  167. If a lock was held by a process which no longer exists, it can be
  168. acquired, the C{clean} attribute is set to C{False}, and the
  169. C{locked} attribute is set to C{True}.
  170. """
  171. owner = 12345
  172. def fakeKill(pid, signal):
  173. if signal != 0:
  174. raise OSError(errno.EPERM, None)
  175. if pid == owner:
  176. raise OSError(errno.ESRCH, None)
  177. lockf = self.mktemp()
  178. self.patch(lockfile, 'kill', fakeKill)
  179. lockfile.symlink(str(owner), lockf)
  180. lock = lockfile.FilesystemLock(lockf)
  181. self.assertTrue(lock.lock())
  182. self.assertFalse(lock.clean)
  183. self.assertTrue(lock.locked)
  184. self.assertEqual(lockfile.readlink(lockf), str(os.getpid()))
  185. def test_lockReleasedBeforeCheck(self):
  186. """
  187. If the lock is initially held but then released before it can be
  188. examined to determine if the process which held it still exists, it is
  189. acquired and the C{clean} and C{locked} attributes are set to C{True}.
  190. """
  191. def fakeReadlink(name):
  192. # Pretend to be another process releasing the lock.
  193. lockfile.rmlink(lockf)
  194. # Fall back to the real implementation of readlink.
  195. readlinkPatch.restore()
  196. return lockfile.readlink(name)
  197. readlinkPatch = self.patch(lockfile, 'readlink', fakeReadlink)
  198. def fakeKill(pid, signal):
  199. if signal != 0:
  200. raise OSError(errno.EPERM, None)
  201. if pid == 43125:
  202. raise OSError(errno.ESRCH, None)
  203. self.patch(lockfile, 'kill', fakeKill)
  204. lockf = self.mktemp()
  205. lock = lockfile.FilesystemLock(lockf)
  206. lockfile.symlink(str(43125), lockf)
  207. self.assertTrue(lock.lock())
  208. self.assertTrue(lock.clean)
  209. self.assertTrue(lock.locked)
  210. def test_lockReleasedDuringAcquireSymlink(self):
  211. """
  212. If the lock is released while an attempt is made to acquire
  213. it, the lock attempt fails and C{FilesystemLock.lock} returns
  214. C{False}. This can happen on Windows when L{lockfile.symlink}
  215. fails with L{IOError} of C{EIO} because another process is in
  216. the middle of a call to L{os.rmdir} (implemented in terms of
  217. RemoveDirectory) which is not atomic.
  218. """
  219. def fakeSymlink(src, dst):
  220. # While another process id doing os.rmdir which the Windows
  221. # implementation of rmlink does, a rename call will fail with EIO.
  222. raise OSError(errno.EIO, None)
  223. self.patch(lockfile, 'symlink', fakeSymlink)
  224. lockf = self.mktemp()
  225. lock = lockfile.FilesystemLock(lockf)
  226. self.assertFalse(lock.lock())
  227. self.assertFalse(lock.locked)
  228. if not platform.isWindows():
  229. test_lockReleasedDuringAcquireSymlink.skip = (
  230. "special rename EIO handling only necessary and correct on "
  231. "Windows.")
  232. def test_lockReleasedDuringAcquireReadlink(self):
  233. """
  234. If the lock is initially held but is released while an attempt
  235. is made to acquire it, the lock attempt fails and
  236. L{FilesystemLock.lock} returns C{False}.
  237. """
  238. def fakeReadlink(name):
  239. # While another process is doing os.rmdir which the
  240. # Windows implementation of rmlink does, a readlink call
  241. # will fail with EACCES.
  242. raise IOError(errno.EACCES, None)
  243. self.patch(lockfile, 'readlink', fakeReadlink)
  244. lockf = self.mktemp()
  245. lock = lockfile.FilesystemLock(lockf)
  246. lockfile.symlink(str(43125), lockf)
  247. self.assertFalse(lock.lock())
  248. self.assertFalse(lock.locked)
  249. if not platform.isWindows():
  250. test_lockReleasedDuringAcquireReadlink.skip = (
  251. "special readlink EACCES handling only necessary and correct on "
  252. "Windows.")
  253. def _readlinkErrorTest(self, exceptionType, errno):
  254. def fakeReadlink(name):
  255. raise exceptionType(errno, None)
  256. self.patch(lockfile, 'readlink', fakeReadlink)
  257. lockf = self.mktemp()
  258. # Make it appear locked so it has to use readlink
  259. lockfile.symlink(str(43125), lockf)
  260. lock = lockfile.FilesystemLock(lockf)
  261. exc = self.assertRaises(exceptionType, lock.lock)
  262. self.assertEqual(exc.errno, errno)
  263. self.assertFalse(lock.locked)
  264. def test_readlinkError(self):
  265. """
  266. An exception raised by C{readlink} other than C{ENOENT} is passed up to
  267. the caller of L{FilesystemLock.lock}.
  268. """
  269. self._readlinkErrorTest(OSError, errno.ENOSYS)
  270. self._readlinkErrorTest(IOError, errno.ENOSYS)
  271. def test_readlinkErrorPOSIX(self):
  272. """
  273. Any L{IOError} raised by C{readlink} on a POSIX platform passed to the
  274. caller of L{FilesystemLock.lock}.
  275. On POSIX, unlike on Windows, these are unexpected errors which cannot
  276. be handled by L{FilesystemLock}.
  277. """
  278. self._readlinkErrorTest(IOError, errno.ENOSYS)
  279. self._readlinkErrorTest(IOError, errno.EACCES)
  280. if platform.isWindows():
  281. test_readlinkErrorPOSIX.skip = (
  282. "POSIX-specific error propagation not expected on Windows.")
  283. def test_lockCleanedUpConcurrently(self):
  284. """
  285. If a second process cleans up the lock after a first one checks the
  286. lock and finds that no process is holding it, the first process does
  287. not fail when it tries to clean up the lock.
  288. """
  289. def fakeRmlink(name):
  290. rmlinkPatch.restore()
  291. # Pretend to be another process cleaning up the lock.
  292. lockfile.rmlink(lockf)
  293. # Fall back to the real implementation of rmlink.
  294. return lockfile.rmlink(name)
  295. rmlinkPatch = self.patch(lockfile, 'rmlink', fakeRmlink)
  296. def fakeKill(pid, signal):
  297. if signal != 0:
  298. raise OSError(errno.EPERM, None)
  299. if pid == 43125:
  300. raise OSError(errno.ESRCH, None)
  301. self.patch(lockfile, 'kill', fakeKill)
  302. lockf = self.mktemp()
  303. lock = lockfile.FilesystemLock(lockf)
  304. lockfile.symlink(str(43125), lockf)
  305. self.assertTrue(lock.lock())
  306. self.assertTrue(lock.clean)
  307. self.assertTrue(lock.locked)
  308. def test_rmlinkError(self):
  309. """
  310. An exception raised by L{rmlink} other than C{ENOENT} is passed up
  311. to the caller of L{FilesystemLock.lock}.
  312. """
  313. def fakeRmlink(name):
  314. raise OSError(errno.ENOSYS, None)
  315. self.patch(lockfile, 'rmlink', fakeRmlink)
  316. def fakeKill(pid, signal):
  317. if signal != 0:
  318. raise OSError(errno.EPERM, None)
  319. if pid == 43125:
  320. raise OSError(errno.ESRCH, None)
  321. self.patch(lockfile, 'kill', fakeKill)
  322. lockf = self.mktemp()
  323. # Make it appear locked so it has to use readlink
  324. lockfile.symlink(str(43125), lockf)
  325. lock = lockfile.FilesystemLock(lockf)
  326. exc = self.assertRaises(OSError, lock.lock)
  327. self.assertEqual(exc.errno, errno.ENOSYS)
  328. self.assertFalse(lock.locked)
  329. def test_killError(self):
  330. """
  331. If L{kill} raises an exception other than L{OSError} with errno set to
  332. C{ESRCH}, the exception is passed up to the caller of
  333. L{FilesystemLock.lock}.
  334. """
  335. def fakeKill(pid, signal):
  336. raise OSError(errno.EPERM, None)
  337. self.patch(lockfile, 'kill', fakeKill)
  338. lockf = self.mktemp()
  339. # Make it appear locked so it has to use readlink
  340. lockfile.symlink(str(43125), lockf)
  341. lock = lockfile.FilesystemLock(lockf)
  342. exc = self.assertRaises(OSError, lock.lock)
  343. self.assertEqual(exc.errno, errno.EPERM)
  344. self.assertFalse(lock.locked)
  345. def test_unlockOther(self):
  346. """
  347. L{FilesystemLock.unlock} raises L{ValueError} if called for a lock
  348. which is held by a different process.
  349. """
  350. lockf = self.mktemp()
  351. lockfile.symlink(str(os.getpid() + 1), lockf)
  352. lock = lockfile.FilesystemLock(lockf)
  353. self.assertRaises(ValueError, lock.unlock)
  354. def test_isLocked(self):
  355. """
  356. L{isLocked} returns C{True} if the named lock is currently locked,
  357. C{False} otherwise.
  358. """
  359. lockf = self.mktemp()
  360. self.assertFalse(lockfile.isLocked(lockf))
  361. lock = lockfile.FilesystemLock(lockf)
  362. self.assertTrue(lock.lock())
  363. self.assertTrue(lockfile.isLocked(lockf))
  364. lock.unlock()
  365. self.assertFalse(lockfile.isLocked(lockf))