lock.inc

  1. 7.x drupal-7.x/includes/lock.inc
  2. 6.x drupal-6.x/includes/lock.inc

A database-mediated implementation of a locking mechanism.

File

drupal-6.x/includes/lock.inc
View source
  1. <?php
  2. /**
  3. * @file
  4. * A database-mediated implementation of a locking mechanism.
  5. */
  6. /**
  7. * @defgroup lock Functions to coordinate long-running operations across requests.
  8. * @{
  9. * In most environments, multiple Drupal page requests (a.k.a. threads or
  10. * processes) will execute in parallel. This leads to potential conflicts or
  11. * race conditions when two requests execute the same code at the same time. A
  12. * common example of this is a rebuild like menu_rebuild() where we invoke many
  13. * hook implementations to get and process data from all active modules, and
  14. * then delete the current data in the database to insert the new afterwards.
  15. *
  16. * This is a cooperative, advisory lock system. Any long-running operation
  17. * that could potentially be attempted in parallel by multiple requests should
  18. * try to acquire a lock before proceeding. By obtaining a lock, one request
  19. * notifies any other requests that a specific opertation is in progress which
  20. * must not be executed in parallel.
  21. *
  22. * To use this API, pick a unique name for the lock. A sensible choice is the
  23. * name of the function performing the operation. A very simple example use of
  24. * this API:
  25. * @code
  26. * function mymodule_long_operation() {
  27. * if (lock_acquire('mymodule_long_operation')) {
  28. * // Do the long operation here.
  29. * // ...
  30. * lock_release('mymodule_long_operation');
  31. * }
  32. * }
  33. * @endcode
  34. *
  35. * If a function acquires a lock it should always release it when the
  36. * operation is complete by calling lock_release(), as in the example.
  37. *
  38. * A function that has acquired a lock may attempt to renew a lock (extend the
  39. * duration of the lock) by calling lock_acquire() again during the operation.
  40. * Failure to renew a lock is indicative that another request has acquired
  41. * the lock, and that the current operation may need to be aborted.
  42. *
  43. * If a function fails to acquire a lock it may either immediately return, or
  44. * it may call lock_wait() if the rest of the current page request requires
  45. * that the operation in question be complete. After lock_wait() returns,
  46. * the function may again attempt to acquire the lock, or may simply allow the
  47. * page request to proceed on the assumption that a parallel request completed
  48. * the operation.
  49. *
  50. * lock_acquire() and lock_wait() will automatically break (delete) a lock
  51. * whose duration has exceeded the timeout specified when it was acquired.
  52. *
  53. * Alternative implementations of this API (such as APC) may be substituted
  54. * by setting the 'lock_inc' variable to an alternate include filepath. Since
  55. * this is an API intended to support alternative implementations, code using
  56. * this API should never rely upon specific implementation details (for example
  57. * no code should look for or directly modify a lock in the {semaphore} table).
  58. */
  59. /**
  60. * Initialize the locking system.
  61. */
  62. function lock_init() {
  63. global $locks;
  64. $locks = array();
  65. }
  66. /**
  67. * Helper function to get this request's unique id.
  68. */
  69. function _lock_id() {
  70. static $lock_id;
  71. if (!isset($lock_id)) {
  72. // Assign a unique id.
  73. $lock_id = uniqid(mt_rand(), TRUE);
  74. // We only register a shutdown function if a lock is used.
  75. register_shutdown_function('lock_release_all', $lock_id);
  76. }
  77. return $lock_id;
  78. }
  79. /**
  80. * Acquire (or renew) a lock, but do not block if it fails.
  81. *
  82. * @param $name
  83. * The name of the lock.
  84. * @param $timeout
  85. * A number of seconds (float) before the lock expires.
  86. * @return
  87. * TRUE if the lock was acquired, FALSE if it failed.
  88. */
  89. function lock_acquire($name, $timeout = 30.0) {
  90. global $locks;
  91. // Insure that the timeout is at least 1 ms.
  92. $timeout = max($timeout, 0.001);
  93. list($usec, $sec) = explode(' ', microtime());
  94. $expire = (float)$usec + (float)$sec + $timeout;
  95. if (isset($locks[$name])) {
  96. // Try to extend the expiration of a lock we already acquired.
  97. db_query("UPDATE {semaphore} SET expire = %f WHERE name = '%s' AND value = '%s'", $expire, $name, _lock_id());
  98. if (!db_affected_rows()) {
  99. // The lock was broken.
  100. unset($locks[$name]);
  101. }
  102. }
  103. else {
  104. // Optimistically try to acquire the lock, then retry once if it fails.
  105. // The first time through the loop cannot be a retry.
  106. $retry = FALSE;
  107. // We always want to do this code at least once.
  108. do {
  109. if (@db_query("INSERT INTO {semaphore} (name, value, expire) VALUES ('%s', '%s', %f)", $name, _lock_id(), $expire)) {
  110. // We track all acquired locks in the global variable.
  111. $locks[$name] = TRUE;
  112. // We never need to try again.
  113. $retry = FALSE;
  114. }
  115. else {
  116. // Suppress the error. If this is our first pass through the loop,
  117. // then $retry is FALSE. In this case, the insert must have failed
  118. // meaning some other request acquired the lock but did not release it.
  119. // We decide whether to retry by checking lock_may_be_available()
  120. // Since this will break the lock in case it is expired.
  121. $retry = $retry ? FALSE : lock_may_be_available($name);
  122. }
  123. // We only retry in case the first attempt failed, but we then broke
  124. // an expired lock.
  125. } while ($retry);
  126. }
  127. return isset($locks[$name]);
  128. }
  129. /**
  130. * Check if lock acquired by a different process may be available.
  131. *
  132. * If an existing lock has expired, it is removed.
  133. *
  134. * @param $name
  135. * The name of the lock.
  136. * @return
  137. * TRUE if there is no lock or it was removed, FALSE otherwise.
  138. */
  139. function lock_may_be_available($name) {
  140. $lock = db_fetch_array(db_query("SELECT expire, value FROM {semaphore} WHERE name = '%s'", $name));
  141. if (!$lock) {
  142. return TRUE;
  143. }
  144. $expire = (float) $lock['expire'];
  145. list($usec, $sec) = explode(' ', microtime());
  146. $now = (float)$usec + (float)$sec;
  147. if ($now > $lock['expire']) {
  148. // We check two conditions to prevent a race condition where another
  149. // request acquired the lock and set a new expire time. We add a small
  150. // number to $expire to avoid errors with float to string conversion.
  151. db_query("DELETE FROM {semaphore} WHERE name = '%s' AND value = '%s' AND expire <= %f", $name, $lock['value'], 0.0001 + $expire);
  152. return (bool)db_affected_rows();
  153. }
  154. return FALSE;
  155. }
  156. /**
  157. * Wait for a lock to be available.
  158. *
  159. * This function may be called in a request that fails to acquire a desired
  160. * lock. This will block further execution until the lock is available or the
  161. * specified delay in seconds is reached. This should not be used with locks
  162. * that are acquired very frequently, since the lock is likely to be acquired
  163. * again by a different request during the sleep().
  164. *
  165. * @param $name
  166. * The name of the lock.
  167. * @param $delay
  168. * The maximum number of seconds to wait, as an integer.
  169. * @return
  170. * TRUE if the lock holds, FALSE if it is available.
  171. */
  172. function lock_wait($name, $delay = 30) {
  173. while ($delay--) {
  174. // This function should only be called by a request that failed to get a
  175. // lock, so we sleep first to give the parallel request a chance to finish
  176. // and release the lock.
  177. sleep(1);
  178. if (lock_may_be_available($name)) {
  179. // No longer need to wait.
  180. return FALSE;
  181. }
  182. }
  183. // The caller must still wait longer to get the lock.
  184. return TRUE;
  185. }
  186. /**
  187. * Release a lock previously acquired by lock_acquire().
  188. *
  189. * This will release the named lock if it is still held by the current request.
  190. *
  191. * @param $name
  192. * The name of the lock.
  193. */
  194. function lock_release($name) {
  195. global $locks;
  196. unset($locks[$name]);
  197. db_query("DELETE FROM {semaphore} WHERE name = '%s' AND value = '%s'", $name, _lock_id());
  198. }
  199. /**
  200. * Release all previously acquired locks.
  201. */
  202. function lock_release_all($lock_id = NULL) {
  203. global $locks;
  204. $locks = array();
  205. if (empty($lock_id)) {
  206. $lock_id = _lock_id();
  207. }
  208. db_query("DELETE FROM {semaphore} WHERE value = '%s'", _lock_id());
  209. }
  210. /**
  211. * @} End of "defgroup locks".
  212. */