Development of an internal social media platform with personalised dashboards for students
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

pidlockfile.py 5.9KB

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