source: sipes/cord/includes/lock.inc @ b354002

stableversion-3.0
Last change on this file since b354002 was b354002, checked in by José Gregorio Puentes <jpuentes@…>, 8 años ago

se agrego el directorio del cord

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