8131f81782cca3386a6b8487580a8765443e4095
[lhc/web/wiklou.git] / includes / filebackend / lockmanager / MemcLockManager.php
1 <?php
2 /**
3 * Version of LockManager based on using memcached servers.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 * @ingroup LockManager
22 */
23
24 /**
25 * Manage locks using memcached servers.
26 *
27 * Version of LockManager based on using memcached servers.
28 * This is meant for multi-wiki systems that may share files.
29 * All locks are non-blocking, which avoids deadlocks.
30 *
31 * All lock requests for a resource, identified by a hash string, will map to one
32 * bucket. Each bucket maps to one or several peer servers, each running memcached.
33 * A majority of peers must agree for a lock to be acquired.
34 *
35 * @ingroup LockManager
36 * @since 1.20
37 */
38 class MemcLockManager extends QuorumLockManager {
39 /** @var Array Mapping of lock types to the type actually used */
40 protected $lockTypeMap = array(
41 self::LOCK_SH => self::LOCK_SH,
42 self::LOCK_UW => self::LOCK_SH,
43 self::LOCK_EX => self::LOCK_EX
44 );
45
46 /** @var Array Map server names to MemcachedBagOStuff objects */
47 protected $bagOStuffs = array();
48 /** @var Array */
49 protected $serversUp = array(); // (server name => bool)
50
51 protected $lockExpiry; // integer; maximum time locks can be held
52 protected $session = ''; // string; random UUID
53
54 /**
55 * Construct a new instance from configuration.
56 *
57 * $config paramaters include:
58 * - lockServers : Associative array of server names to "<IP>:<port>" strings.
59 * - srvsByBucket : Array of 1-16 consecutive integer keys, starting from 0,
60 * each having an odd-numbered list of server names (peers) as values.
61 * - memcConfig : Configuration array for ObjectCache::newFromParams. [optional]
62 * If set, this must use one of the memcached classes.
63 *
64 * @param array $config
65 * @throws MWException
66 */
67 public function __construct( array $config ) {
68 parent::__construct( $config );
69
70 // Sanitize srvsByBucket config to prevent PHP errors
71 $this->srvsByBucket = array_filter( $config['srvsByBucket'], 'is_array' );
72 $this->srvsByBucket = array_values( $this->srvsByBucket ); // consecutive
73
74 $memcConfig = isset( $config['memcConfig'] )
75 ? $config['memcConfig']
76 : array( 'class' => 'MemcachedPhpBagOStuff' );
77
78 foreach ( $config['lockServers'] as $name => $address ) {
79 $params = array( 'servers' => array( $address ) ) + $memcConfig;
80 $cache = ObjectCache::newFromParams( $params );
81 if ( $cache instanceof MemcachedBagOStuff ) {
82 $this->bagOStuffs[$name] = $cache;
83 } else {
84 throw new MWException(
85 'Only MemcachedBagOStuff classes are supported by MemcLockManager.' );
86 }
87 }
88
89 $met = ini_get( 'max_execution_time' ); // this is 0 in CLI mode
90 $this->lockExpiry = $met ? 2*(int)$met : 2*3600;
91
92 $this->session = wfRandomString( 32 );
93 }
94
95 /**
96 * @see QuorumLockManager::getLocksOnServer()
97 * @return Status
98 */
99 protected function getLocksOnServer( $lockSrv, array $paths, $type ) {
100 $status = Status::newGood();
101
102 $memc = $this->getCache( $lockSrv );
103 $keys = array_map( array( $this, 'recordKeyForPath' ), $paths ); // lock records
104
105 // Lock all of the active lock record keys...
106 if ( !$this->acquireMutexes( $memc, $keys ) ) {
107 foreach ( $paths as $path ) {
108 $status->fatal( 'lockmanager-fail-acquirelock', $path );
109 }
110 return $status;
111 }
112
113 // Fetch all the existing lock records...
114 $lockRecords = $memc->getMulti( $keys );
115
116 $now = time();
117 // Check if the requested locks conflict with existing ones...
118 foreach ( $paths as $path ) {
119 $locksKey = $this->recordKeyForPath( $path );
120 $locksHeld = isset( $lockRecords[$locksKey] )
121 ? self::sanitizeLockArray( $lockRecords[$locksKey] )
122 : self::newLockArray(); // init
123 foreach ( $locksHeld[self::LOCK_EX] as $session => $expiry ) {
124 if ( $expiry < $now ) { // stale?
125 unset( $locksHeld[self::LOCK_EX][$session] );
126 } elseif ( $session !== $this->session ) {
127 $status->fatal( 'lockmanager-fail-acquirelock', $path );
128 }
129 }
130 if ( $type === self::LOCK_EX ) {
131 foreach ( $locksHeld[self::LOCK_SH] as $session => $expiry ) {
132 if ( $expiry < $now ) { // stale?
133 unset( $locksHeld[self::LOCK_SH][$session] );
134 } elseif ( $session !== $this->session ) {
135 $status->fatal( 'lockmanager-fail-acquirelock', $path );
136 }
137 }
138 }
139 if ( $status->isOK() ) {
140 // Register the session in the lock record array
141 $locksHeld[$type][$this->session] = $now + $this->lockExpiry;
142 // We will update this record if none of the other locks conflict
143 $lockRecords[$locksKey] = $locksHeld;
144 }
145 }
146
147 // If there were no lock conflicts, update all the lock records...
148 if ( $status->isOK() ) {
149 foreach ( $paths as $path ) {
150 $locksKey = $this->recordKeyForPath( $path );
151 $locksHeld = $lockRecords[$locksKey];
152 $ok = $memc->set( $locksKey, $locksHeld, 7*86400 );
153 if ( !$ok ) {
154 $status->fatal( 'lockmanager-fail-acquirelock', $path );
155 } else {
156 wfDebug( __METHOD__ . ": acquired lock on key $locksKey.\n" );
157 }
158 }
159 }
160
161 // Unlock all of the active lock record keys...
162 $this->releaseMutexes( $memc, $keys );
163
164 return $status;
165 }
166
167 /**
168 * @see QuorumLockManager::freeLocksOnServer()
169 * @return Status
170 */
171 protected function freeLocksOnServer( $lockSrv, array $paths, $type ) {
172 $status = Status::newGood();
173
174 $memc = $this->getCache( $lockSrv );
175 $keys = array_map( array( $this, 'recordKeyForPath' ), $paths ); // lock records
176
177 // Lock all of the active lock record keys...
178 if ( !$this->acquireMutexes( $memc, $keys ) ) {
179 foreach ( $paths as $path ) {
180 $status->fatal( 'lockmanager-fail-releaselock', $path );
181 }
182 return;
183 }
184
185 // Fetch all the existing lock records...
186 $lockRecords = $memc->getMulti( $keys );
187
188 // Remove the requested locks from all records...
189 foreach ( $paths as $path ) {
190 $locksKey = $this->recordKeyForPath( $path ); // lock record
191 if ( !isset( $lockRecords[$locksKey] ) ) {
192 $status->warning( 'lockmanager-fail-releaselock', $path );
193 continue; // nothing to do
194 }
195 $locksHeld = self::sanitizeLockArray( $lockRecords[$locksKey] );
196 if ( isset( $locksHeld[$type][$this->session] ) ) {
197 unset( $locksHeld[$type][$this->session] ); // unregister this session
198 if ( $locksHeld === self::newLockArray() ) {
199 $ok = $memc->delete( $locksKey );
200 } else {
201 $ok = $memc->set( $locksKey, $locksHeld );
202 }
203 if ( !$ok ) {
204 $status->fatal( 'lockmanager-fail-releaselock', $path );
205 }
206 } else {
207 $status->warning( 'lockmanager-fail-releaselock', $path );
208 }
209 wfDebug( __METHOD__ . ": released lock on key $locksKey.\n" );
210 }
211
212 // Unlock all of the active lock record keys...
213 $this->releaseMutexes( $memc, $keys );
214
215 return $status;
216 }
217
218 /**
219 * @see QuorumLockManager::releaseAllLocks()
220 * @return Status
221 */
222 protected function releaseAllLocks() {
223 return Status::newGood(); // not supported
224 }
225
226 /**
227 * @see QuorumLockManager::isServerUp()
228 * @return bool
229 */
230 protected function isServerUp( $lockSrv ) {
231 return (bool)$this->getCache( $lockSrv );
232 }
233
234 /**
235 * Get the MemcachedBagOStuff object for a $lockSrv
236 *
237 * @param string $lockSrv Server name
238 * @return MemcachedBagOStuff|null
239 */
240 protected function getCache( $lockSrv ) {
241 $memc = null;
242 if ( isset( $this->bagOStuffs[$lockSrv] ) ) {
243 $memc = $this->bagOStuffs[$lockSrv];
244 if ( !isset( $this->serversUp[$lockSrv] ) ) {
245 $this->serversUp[$lockSrv] = $memc->set( 'MemcLockManager:ping', 1, 1 );
246 if ( !$this->serversUp[$lockSrv] ) {
247 trigger_error( __METHOD__ . ": Could not contact $lockSrv.", E_USER_WARNING );
248 }
249 }
250 if ( !$this->serversUp[$lockSrv] ) {
251 return null; // server appears to be down
252 }
253 }
254 return $memc;
255 }
256
257 /**
258 * @param $path string
259 * @return string
260 */
261 protected function recordKeyForPath( $path ) {
262 return implode( ':', array( __CLASS__, 'locks', $this->sha1Base36Absolute( $path ) ) );
263 }
264
265 /**
266 * @return Array An empty lock structure for a key
267 */
268 protected static function newLockArray() {
269 return array( self::LOCK_SH => array(), self::LOCK_EX => array() );
270 }
271
272 /**
273 * @param $a array
274 * @return Array An empty lock structure for a key
275 */
276 protected static function sanitizeLockArray( $a ) {
277 if ( is_array( $a ) && isset( $a[self::LOCK_EX] ) && isset( $a[self::LOCK_SH] ) ) {
278 return $a;
279 } else {
280 trigger_error( __METHOD__ . ": reset invalid lock array.", E_USER_WARNING );
281 return self::newLockArray();
282 }
283 }
284
285 /**
286 * @param $memc MemcachedBagOStuff
287 * @param array $keys List of keys to acquire
288 * @return bool
289 */
290 protected function acquireMutexes( MemcachedBagOStuff $memc, array $keys ) {
291 $lockedKeys = array();
292
293 // Acquire the keys in lexicographical order, to avoid deadlock problems.
294 // If P1 is waiting to acquire a key P2 has, P2 can't also be waiting for a key P1 has.
295 sort( $keys );
296
297 // Try to quickly loop to acquire the keys, but back off after a few rounds.
298 // This reduces memcached spam, especially in the rare case where a server acquires
299 // some lock keys and dies without releasing them. Lock keys expire after a few minutes.
300 $rounds = 0;
301 $start = microtime( true );
302 do {
303 if ( ( ++$rounds % 4 ) == 0 ) {
304 usleep( 1000*50 ); // 50 ms
305 }
306 foreach ( array_diff( $keys, $lockedKeys ) as $key ) {
307 if ( $memc->add( "$key:mutex", 1, 180 ) ) { // lock record
308 $lockedKeys[] = $key;
309 } else {
310 continue; // acquire in order
311 }
312 }
313 } while ( count( $lockedKeys ) < count( $keys ) && ( microtime( true ) - $start ) <= 3 );
314
315 if ( count( $lockedKeys ) != count( $keys ) ) {
316 $this->releaseMutexes( $memc, $lockedKeys ); // failed; release what was locked
317 return false;
318 }
319
320 return true;
321 }
322
323 /**
324 * @param $memc MemcachedBagOStuff
325 * @param array $keys List of acquired keys
326 * @return void
327 */
328 protected function releaseMutexes( MemcachedBagOStuff $memc, array $keys ) {
329 foreach ( $keys as $key ) {
330 $memc->delete( "$key:mutex" );
331 }
332 }
333
334 /**
335 * Make sure remaining locks get cleared for sanity
336 */
337 function __destruct() {
338 while ( count( $this->locksHeld ) ) {
339 foreach ( $this->locksHeld as $path => $locks ) {
340 $this->doUnlock( array( $path ), self::LOCK_EX );
341 $this->doUnlock( array( $path ), self::LOCK_SH );
342 }
343 }
344 }
345 }