Merge "Put the HTML attribute whitelist closer to HTML5"
[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 $session = ''; // string; random UUID
52
53 /**
54 * Construct a new instance from configuration.
55 *
56 * $config paramaters include:
57 * - lockServers : Associative array of server names to "<IP>:<port>" strings.
58 * - srvsByBucket : Array of 1-16 consecutive integer keys, starting from 0,
59 * each having an odd-numbered list of server names (peers) as values.
60 * - memcConfig : Configuration array for ObjectCache::newFromParams. [optional]
61 * If set, this must use one of the memcached classes.
62 *
63 * @param array $config
64 * @throws MWException
65 */
66 public function __construct( array $config ) {
67 parent::__construct( $config );
68
69 // Sanitize srvsByBucket config to prevent PHP errors
70 $this->srvsByBucket = array_filter( $config['srvsByBucket'], 'is_array' );
71 $this->srvsByBucket = array_values( $this->srvsByBucket ); // consecutive
72
73 $memcConfig = isset( $config['memcConfig'] )
74 ? $config['memcConfig']
75 : array( 'class' => 'MemcachedPhpBagOStuff' );
76
77 foreach ( $config['lockServers'] as $name => $address ) {
78 $params = array( 'servers' => array( $address ) ) + $memcConfig;
79 $cache = ObjectCache::newFromParams( $params );
80 if ( $cache instanceof MemcachedBagOStuff ) {
81 $this->bagOStuffs[$name] = $cache;
82 } else {
83 throw new MWException(
84 'Only MemcachedBagOStuff classes are supported by MemcLockManager.' );
85 }
86 }
87
88 $this->session = wfRandomString( 32 );
89 }
90
91 // @TODO: change this code to work in one batch
92 protected function getLocksOnServer( $lockSrv, array $pathsByType ) {
93 $status = Status::newGood();
94
95 $lockedPaths = array();
96 foreach ( $pathsByType as $type => $paths ) {
97 $status->merge( $this->doGetLocksOnServer( $lockSrv, $paths, $type ) );
98 if ( $status->isOK() ) {
99 $lockedPaths[$type] = isset( $lockedPaths[$type] )
100 ? array_merge( $lockedPaths[$type], $paths )
101 : $paths;
102 } else {
103 foreach ( $lockedPaths as $type => $paths ) {
104 $status->merge( $this->doFreeLocksOnServer( $lockSrv, $paths, $type ) );
105 }
106 break;
107 }
108 }
109
110 return $status;
111 }
112
113 // @TODO: change this code to work in one batch
114 protected function freeLocksOnServer( $lockSrv, array $pathsByType ) {
115 $status = Status::newGood();
116
117 foreach ( $pathsByType as $type => $paths ) {
118 $status->merge( $this->doFreeLocksOnServer( $lockSrv, $paths, $type ) );
119 }
120
121 return $status;
122 }
123
124 /**
125 * @see QuorumLockManager::getLocksOnServer()
126 * @return Status
127 */
128 protected function doGetLocksOnServer( $lockSrv, array $paths, $type ) {
129 $status = Status::newGood();
130
131 $memc = $this->getCache( $lockSrv );
132 $keys = array_map( array( $this, 'recordKeyForPath' ), $paths ); // lock records
133
134 // Lock all of the active lock record keys...
135 if ( !$this->acquireMutexes( $memc, $keys ) ) {
136 foreach ( $paths as $path ) {
137 $status->fatal( 'lockmanager-fail-acquirelock', $path );
138 }
139 return $status;
140 }
141
142 // Fetch all the existing lock records...
143 $lockRecords = $memc->getMulti( $keys );
144
145 $now = time();
146 // Check if the requested locks conflict with existing ones...
147 foreach ( $paths as $path ) {
148 $locksKey = $this->recordKeyForPath( $path );
149 $locksHeld = isset( $lockRecords[$locksKey] )
150 ? self::sanitizeLockArray( $lockRecords[$locksKey] )
151 : self::newLockArray(); // init
152 foreach ( $locksHeld[self::LOCK_EX] as $session => $expiry ) {
153 if ( $expiry < $now ) { // stale?
154 unset( $locksHeld[self::LOCK_EX][$session] );
155 } elseif ( $session !== $this->session ) {
156 $status->fatal( 'lockmanager-fail-acquirelock', $path );
157 }
158 }
159 if ( $type === self::LOCK_EX ) {
160 foreach ( $locksHeld[self::LOCK_SH] as $session => $expiry ) {
161 if ( $expiry < $now ) { // stale?
162 unset( $locksHeld[self::LOCK_SH][$session] );
163 } elseif ( $session !== $this->session ) {
164 $status->fatal( 'lockmanager-fail-acquirelock', $path );
165 }
166 }
167 }
168 if ( $status->isOK() ) {
169 // Register the session in the lock record array
170 $locksHeld[$type][$this->session] = $now + $this->lockTTL;
171 // We will update this record if none of the other locks conflict
172 $lockRecords[$locksKey] = $locksHeld;
173 }
174 }
175
176 // If there were no lock conflicts, update all the lock records...
177 if ( $status->isOK() ) {
178 foreach ( $paths as $path ) {
179 $locksKey = $this->recordKeyForPath( $path );
180 $locksHeld = $lockRecords[$locksKey];
181 $ok = $memc->set( $locksKey, $locksHeld, 7 * 86400 );
182 if ( !$ok ) {
183 $status->fatal( 'lockmanager-fail-acquirelock', $path );
184 } else {
185 wfDebug( __METHOD__ . ": acquired lock on key $locksKey.\n" );
186 }
187 }
188 }
189
190 // Unlock all of the active lock record keys...
191 $this->releaseMutexes( $memc, $keys );
192
193 return $status;
194 }
195
196 /**
197 * @see QuorumLockManager::freeLocksOnServer()
198 * @return Status
199 */
200 protected function doFreeLocksOnServer( $lockSrv, array $paths, $type ) {
201 $status = Status::newGood();
202
203 $memc = $this->getCache( $lockSrv );
204 $keys = array_map( array( $this, 'recordKeyForPath' ), $paths ); // lock records
205
206 // Lock all of the active lock record keys...
207 if ( !$this->acquireMutexes( $memc, $keys ) ) {
208 foreach ( $paths as $path ) {
209 $status->fatal( 'lockmanager-fail-releaselock', $path );
210 }
211 return;
212 }
213
214 // Fetch all the existing lock records...
215 $lockRecords = $memc->getMulti( $keys );
216
217 // Remove the requested locks from all records...
218 foreach ( $paths as $path ) {
219 $locksKey = $this->recordKeyForPath( $path ); // lock record
220 if ( !isset( $lockRecords[$locksKey] ) ) {
221 $status->warning( 'lockmanager-fail-releaselock', $path );
222 continue; // nothing to do
223 }
224 $locksHeld = self::sanitizeLockArray( $lockRecords[$locksKey] );
225 if ( isset( $locksHeld[$type][$this->session] ) ) {
226 unset( $locksHeld[$type][$this->session] ); // unregister this session
227 if ( $locksHeld === self::newLockArray() ) {
228 $ok = $memc->delete( $locksKey );
229 } else {
230 $ok = $memc->set( $locksKey, $locksHeld );
231 }
232 if ( !$ok ) {
233 $status->fatal( 'lockmanager-fail-releaselock', $path );
234 }
235 } else {
236 $status->warning( 'lockmanager-fail-releaselock', $path );
237 }
238 wfDebug( __METHOD__ . ": released lock on key $locksKey.\n" );
239 }
240
241 // Unlock all of the active lock record keys...
242 $this->releaseMutexes( $memc, $keys );
243
244 return $status;
245 }
246
247 /**
248 * @see QuorumLockManager::releaseAllLocks()
249 * @return Status
250 */
251 protected function releaseAllLocks() {
252 return Status::newGood(); // not supported
253 }
254
255 /**
256 * @see QuorumLockManager::isServerUp()
257 * @return bool
258 */
259 protected function isServerUp( $lockSrv ) {
260 return (bool)$this->getCache( $lockSrv );
261 }
262
263 /**
264 * Get the MemcachedBagOStuff object for a $lockSrv
265 *
266 * @param string $lockSrv Server name
267 * @return MemcachedBagOStuff|null
268 */
269 protected function getCache( $lockSrv ) {
270 $memc = null;
271 if ( isset( $this->bagOStuffs[$lockSrv] ) ) {
272 $memc = $this->bagOStuffs[$lockSrv];
273 if ( !isset( $this->serversUp[$lockSrv] ) ) {
274 $this->serversUp[$lockSrv] = $memc->set( __CLASS__ . ':ping', 1, 1 );
275 if ( !$this->serversUp[$lockSrv] ) {
276 trigger_error( __METHOD__ . ": Could not contact $lockSrv.", E_USER_WARNING );
277 }
278 }
279 if ( !$this->serversUp[$lockSrv] ) {
280 return null; // server appears to be down
281 }
282 }
283 return $memc;
284 }
285
286 /**
287 * @param $path string
288 * @return string
289 */
290 protected function recordKeyForPath( $path ) {
291 return implode( ':', array( __CLASS__, 'locks', $this->sha1Base36Absolute( $path ) ) );
292 }
293
294 /**
295 * @return Array An empty lock structure for a key
296 */
297 protected static function newLockArray() {
298 return array( self::LOCK_SH => array(), self::LOCK_EX => array() );
299 }
300
301 /**
302 * @param $a array
303 * @return Array An empty lock structure for a key
304 */
305 protected static function sanitizeLockArray( $a ) {
306 if ( is_array( $a ) && isset( $a[self::LOCK_EX] ) && isset( $a[self::LOCK_SH] ) ) {
307 return $a;
308 } else {
309 trigger_error( __METHOD__ . ": reset invalid lock array.", E_USER_WARNING );
310 return self::newLockArray();
311 }
312 }
313
314 /**
315 * @param $memc MemcachedBagOStuff
316 * @param array $keys List of keys to acquire
317 * @return bool
318 */
319 protected function acquireMutexes( MemcachedBagOStuff $memc, array $keys ) {
320 $lockedKeys = array();
321
322 // Acquire the keys in lexicographical order, to avoid deadlock problems.
323 // If P1 is waiting to acquire a key P2 has, P2 can't also be waiting for a key P1 has.
324 sort( $keys );
325
326 // Try to quickly loop to acquire the keys, but back off after a few rounds.
327 // This reduces memcached spam, especially in the rare case where a server acquires
328 // some lock keys and dies without releasing them. Lock keys expire after a few minutes.
329 $rounds = 0;
330 $start = microtime( true );
331 do {
332 if ( ( ++$rounds % 4 ) == 0 ) {
333 usleep( 1000 * 50 ); // 50 ms
334 }
335 foreach ( array_diff( $keys, $lockedKeys ) as $key ) {
336 if ( $memc->add( "$key:mutex", 1, 180 ) ) { // lock record
337 $lockedKeys[] = $key;
338 } else {
339 continue; // acquire in order
340 }
341 }
342 } while ( count( $lockedKeys ) < count( $keys ) && ( microtime( true ) - $start ) <= 3 );
343
344 if ( count( $lockedKeys ) != count( $keys ) ) {
345 $this->releaseMutexes( $memc, $lockedKeys ); // failed; release what was locked
346 return false;
347 }
348
349 return true;
350 }
351
352 /**
353 * @param $memc MemcachedBagOStuff
354 * @param array $keys List of acquired keys
355 * @return void
356 */
357 protected function releaseMutexes( MemcachedBagOStuff $memc, array $keys ) {
358 foreach ( $keys as $key ) {
359 $memc->delete( "$key:mutex" );
360 }
361 }
362
363 /**
364 * Make sure remaining locks get cleared for sanity
365 */
366 function __destruct() {
367 while ( count( $this->locksHeld ) ) {
368 foreach ( $this->locksHeld as $path => $locks ) {
369 $this->doUnlock( array( $path ), self::LOCK_EX );
370 $this->doUnlock( array( $path ), self::LOCK_SH );
371 }
372 }
373 }
374 }