pidlockfile.py 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  1. # -*- coding: utf-8 -*-
  2. # pidlockfile.py
  3. #
  4. # Copyright © 2008–2009 Ben Finney <ben+python@benfinney.id.au>
  5. #
  6. # This is free software: you may copy, modify, and/or distribute this work
  7. # under the terms of the Python Software Foundation License, version 2 or
  8. # later as published by the Python Software Foundation.
  9. # No warranty expressed or implied. See the file LICENSE.PSF-2 for details.
  10. """ Lockfile behaviour implemented via Unix PID files.
  11. """
  12. from __future__ import absolute_import
  13. import os
  14. import sys
  15. import errno
  16. import time
  17. from . import (LockBase, AlreadyLocked, LockFailed, NotLocked, NotMyLock,
  18. LockTimeout)
  19. class PIDLockFile(LockBase):
  20. """ Lockfile implemented as a Unix PID file.
  21. The lock file is a normal file named by the attribute `path`.
  22. A lock's PID file contains a single line of text, containing
  23. the process ID (PID) of the process that acquired the lock.
  24. >>> lock = PIDLockFile('somefile')
  25. >>> lock = PIDLockFile('somefile')
  26. """
  27. def __init__(self, path, threaded=False, timeout=None):
  28. # pid lockfiles don't support threaded operation, so always force
  29. # False as the threaded arg.
  30. LockBase.__init__(self, path, False, timeout)
  31. dirname = os.path.dirname(self.lock_file)
  32. basename = os.path.split(self.path)[-1]
  33. self.unique_name = self.path
  34. def read_pid(self):
  35. """ Get the PID from the lock file.
  36. """
  37. return read_pid_from_pidfile(self.path)
  38. def is_locked(self):
  39. """ Test if the lock is currently held.
  40. The lock is held if the PID file for this lock exists.
  41. """
  42. return os.path.exists(self.path)
  43. def i_am_locking(self):
  44. """ Test if the lock is held by the current process.
  45. Returns ``True`` if the current process ID matches the
  46. number stored in the PID file.
  47. """
  48. return self.is_locked() and os.getpid() == self.read_pid()
  49. def acquire(self, timeout=None):
  50. """ Acquire the lock.
  51. Creates the PID file for this lock, or raises an error if
  52. the lock could not be acquired.
  53. """
  54. timeout = timeout is not None and timeout or self.timeout
  55. end_time = time.time()
  56. if timeout is not None and timeout > 0:
  57. end_time += timeout
  58. while True:
  59. try:
  60. write_pid_to_pidfile(self.path)
  61. except OSError as exc:
  62. if exc.errno == errno.EEXIST:
  63. # The lock creation failed. Maybe sleep a bit.
  64. if timeout is not None and time.time() > end_time:
  65. if timeout > 0:
  66. raise LockTimeout("Timeout waiting to acquire"
  67. " lock for %s" %
  68. self.path)
  69. else:
  70. raise AlreadyLocked("%s is already locked" %
  71. self.path)
  72. time.sleep(timeout is not None and timeout/10 or 0.1)
  73. else:
  74. raise LockFailed("failed to create %s" % self.path)
  75. else:
  76. return
  77. def release(self):
  78. """ Release the lock.
  79. Removes the PID file to release the lock, or raises an
  80. error if the current process does not hold the lock.
  81. """
  82. if not self.is_locked():
  83. raise NotLocked("%s is not locked" % self.path)
  84. if not self.i_am_locking():
  85. raise NotMyLock("%s is locked, but not by me" % self.path)
  86. remove_existing_pidfile(self.path)
  87. def break_lock(self):
  88. """ Break an existing lock.
  89. Removes the PID file if it already exists, otherwise does
  90. nothing.
  91. """
  92. remove_existing_pidfile(self.path)
  93. def read_pid_from_pidfile(pidfile_path):
  94. """ Read the PID recorded in the named PID file.
  95. Read and return the numeric PID recorded as text in the named
  96. PID file. If the PID file cannot be read, or if the content is
  97. not a valid PID, return ``None``.
  98. """
  99. pid = None
  100. try:
  101. pidfile = open(pidfile_path, 'r')
  102. except IOError:
  103. pass
  104. else:
  105. # According to the FHS 2.3 section on PID files in /var/run:
  106. #
  107. # The file must consist of the process identifier in
  108. # ASCII-encoded decimal, followed by a newline character.
  109. #
  110. # Programs that read PID files should be somewhat flexible
  111. # in what they accept; i.e., they should ignore extra
  112. # whitespace, leading zeroes, absence of the trailing
  113. # newline, or additional lines in the PID file.
  114. line = pidfile.readline().strip()
  115. try:
  116. pid = int(line)
  117. except ValueError:
  118. pass
  119. pidfile.close()
  120. return pid
  121. def write_pid_to_pidfile(pidfile_path):
  122. """ Write the PID in the named PID file.
  123. Get the numeric process ID (“PID”) of the current process
  124. and write it to the named file as a line of text.
  125. """
  126. open_flags = (os.O_CREAT | os.O_EXCL | os.O_WRONLY)
  127. open_mode = 0o644
  128. pidfile_fd = os.open(pidfile_path, open_flags, open_mode)
  129. pidfile = os.fdopen(pidfile_fd, 'w')
  130. # According to the FHS 2.3 section on PID files in /var/run:
  131. #
  132. # The file must consist of the process identifier in
  133. # ASCII-encoded decimal, followed by a newline character. For
  134. # example, if crond was process number 25, /var/run/crond.pid
  135. # would contain three characters: two, five, and newline.
  136. pid = os.getpid()
  137. line = "%(pid)d\n" % vars()
  138. pidfile.write(line)
  139. pidfile.close()
  140. def remove_existing_pidfile(pidfile_path):
  141. """ Remove the named PID file if it exists.
  142. Removing a PID file that doesn't already exist puts us in the
  143. desired state, so we ignore the condition if the file does not
  144. exist.
  145. """
  146. try:
  147. os.remove(pidfile_path)
  148. except OSError as exc:
  149. if exc.errno == errno.ENOENT:
  150. pass
  151. else:
  152. raise