thumb_handler.php doesn't seem to extract path_info correctly
[mediawiki.git] / includes / filebackend / lockmanager / MemcLockManager.php
blob757aeee1fab7beb4deae8263ebf225d9c114e795
1 <?php
2 /**
3 * Version of LockManager based on using memcached servers.
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.
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.
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
20 * @file
21 * @ingroup LockManager
24 /**
25 * Manage locks using memcached servers.
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.
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.
35 * @ingroup LockManager
36 * @since 1.20
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
46 /** @var Array Map server names to MemcachedBagOStuff objects */
47 protected $bagOStuffs = array();
48 /** @var Array */
49 protected $serversUp = array(); // (server name => bool)
51 protected $session = ''; // string; random UUID
53 /**
54 * Construct a new instance from configuration.
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.
63 * @param array $config
64 * @throws MWException
66 public function __construct( array $config ) {
67 parent::__construct( $config );
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
73 $memcConfig = isset( $config['memcConfig'] )
74 ? $config['memcConfig']
75 : array( 'class' => 'MemcachedPhpBagOStuff' );
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.' );
88 $this->session = wfRandomString( 32 );
91 /**
92 * @see QuorumLockManager::getLocksOnServer()
93 * @return Status
95 protected function getLocksOnServer( $lockSrv, array $paths, $type ) {
96 $status = Status::newGood();
98 $memc = $this->getCache( $lockSrv );
99 $keys = array_map( array( $this, 'recordKeyForPath' ), $paths ); // lock records
101 // Lock all of the active lock record keys...
102 if ( !$this->acquireMutexes( $memc, $keys ) ) {
103 foreach ( $paths as $path ) {
104 $status->fatal( 'lockmanager-fail-acquirelock', $path );
106 return $status;
109 // Fetch all the existing lock records...
110 $lockRecords = $memc->getMulti( $keys );
112 $now = time();
113 // Check if the requested locks conflict with existing ones...
114 foreach ( $paths as $path ) {
115 $locksKey = $this->recordKeyForPath( $path );
116 $locksHeld = isset( $lockRecords[$locksKey] )
117 ? self::sanitizeLockArray( $lockRecords[$locksKey] )
118 : self::newLockArray(); // init
119 foreach ( $locksHeld[self::LOCK_EX] as $session => $expiry ) {
120 if ( $expiry < $now ) { // stale?
121 unset( $locksHeld[self::LOCK_EX][$session] );
122 } elseif ( $session !== $this->session ) {
123 $status->fatal( 'lockmanager-fail-acquirelock', $path );
126 if ( $type === self::LOCK_EX ) {
127 foreach ( $locksHeld[self::LOCK_SH] as $session => $expiry ) {
128 if ( $expiry < $now ) { // stale?
129 unset( $locksHeld[self::LOCK_SH][$session] );
130 } elseif ( $session !== $this->session ) {
131 $status->fatal( 'lockmanager-fail-acquirelock', $path );
135 if ( $status->isOK() ) {
136 // Register the session in the lock record array
137 $locksHeld[$type][$this->session] = $now + $this->lockTTL;
138 // We will update this record if none of the other locks conflict
139 $lockRecords[$locksKey] = $locksHeld;
143 // If there were no lock conflicts, update all the lock records...
144 if ( $status->isOK() ) {
145 foreach ( $paths as $path ) {
146 $locksKey = $this->recordKeyForPath( $path );
147 $locksHeld = $lockRecords[$locksKey];
148 $ok = $memc->set( $locksKey, $locksHeld, 7 * 86400 );
149 if ( !$ok ) {
150 $status->fatal( 'lockmanager-fail-acquirelock', $path );
151 } else {
152 wfDebug( __METHOD__ . ": acquired lock on key $locksKey.\n" );
157 // Unlock all of the active lock record keys...
158 $this->releaseMutexes( $memc, $keys );
160 return $status;
164 * @see QuorumLockManager::freeLocksOnServer()
165 * @return Status
167 protected function freeLocksOnServer( $lockSrv, array $paths, $type ) {
168 $status = Status::newGood();
170 $memc = $this->getCache( $lockSrv );
171 $keys = array_map( array( $this, 'recordKeyForPath' ), $paths ); // lock records
173 // Lock all of the active lock record keys...
174 if ( !$this->acquireMutexes( $memc, $keys ) ) {
175 foreach ( $paths as $path ) {
176 $status->fatal( 'lockmanager-fail-releaselock', $path );
178 return;
181 // Fetch all the existing lock records...
182 $lockRecords = $memc->getMulti( $keys );
184 // Remove the requested locks from all records...
185 foreach ( $paths as $path ) {
186 $locksKey = $this->recordKeyForPath( $path ); // lock record
187 if ( !isset( $lockRecords[$locksKey] ) ) {
188 $status->warning( 'lockmanager-fail-releaselock', $path );
189 continue; // nothing to do
191 $locksHeld = self::sanitizeLockArray( $lockRecords[$locksKey] );
192 if ( isset( $locksHeld[$type][$this->session] ) ) {
193 unset( $locksHeld[$type][$this->session] ); // unregister this session
194 if ( $locksHeld === self::newLockArray() ) {
195 $ok = $memc->delete( $locksKey );
196 } else {
197 $ok = $memc->set( $locksKey, $locksHeld );
199 if ( !$ok ) {
200 $status->fatal( 'lockmanager-fail-releaselock', $path );
202 } else {
203 $status->warning( 'lockmanager-fail-releaselock', $path );
205 wfDebug( __METHOD__ . ": released lock on key $locksKey.\n" );
208 // Unlock all of the active lock record keys...
209 $this->releaseMutexes( $memc, $keys );
211 return $status;
215 * @see QuorumLockManager::releaseAllLocks()
216 * @return Status
218 protected function releaseAllLocks() {
219 return Status::newGood(); // not supported
223 * @see QuorumLockManager::isServerUp()
224 * @return bool
226 protected function isServerUp( $lockSrv ) {
227 return (bool)$this->getCache( $lockSrv );
231 * Get the MemcachedBagOStuff object for a $lockSrv
233 * @param string $lockSrv Server name
234 * @return MemcachedBagOStuff|null
236 protected function getCache( $lockSrv ) {
237 $memc = null;
238 if ( isset( $this->bagOStuffs[$lockSrv] ) ) {
239 $memc = $this->bagOStuffs[$lockSrv];
240 if ( !isset( $this->serversUp[$lockSrv] ) ) {
241 $this->serversUp[$lockSrv] = $memc->set( __CLASS__ . ':ping', 1, 1 );
242 if ( !$this->serversUp[$lockSrv] ) {
243 trigger_error( __METHOD__ . ": Could not contact $lockSrv.", E_USER_WARNING );
246 if ( !$this->serversUp[$lockSrv] ) {
247 return null; // server appears to be down
250 return $memc;
254 * @param $path string
255 * @return string
257 protected function recordKeyForPath( $path ) {
258 return implode( ':', array( __CLASS__, 'locks', $this->sha1Base36Absolute( $path ) ) );
262 * @return Array An empty lock structure for a key
264 protected static function newLockArray() {
265 return array( self::LOCK_SH => array(), self::LOCK_EX => array() );
269 * @param $a array
270 * @return Array An empty lock structure for a key
272 protected static function sanitizeLockArray( $a ) {
273 if ( is_array( $a ) && isset( $a[self::LOCK_EX] ) && isset( $a[self::LOCK_SH] ) ) {
274 return $a;
275 } else {
276 trigger_error( __METHOD__ . ": reset invalid lock array.", E_USER_WARNING );
277 return self::newLockArray();
282 * @param $memc MemcachedBagOStuff
283 * @param array $keys List of keys to acquire
284 * @return bool
286 protected function acquireMutexes( MemcachedBagOStuff $memc, array $keys ) {
287 $lockedKeys = array();
289 // Acquire the keys in lexicographical order, to avoid deadlock problems.
290 // If P1 is waiting to acquire a key P2 has, P2 can't also be waiting for a key P1 has.
291 sort( $keys );
293 // Try to quickly loop to acquire the keys, but back off after a few rounds.
294 // This reduces memcached spam, especially in the rare case where a server acquires
295 // some lock keys and dies without releasing them. Lock keys expire after a few minutes.
296 $rounds = 0;
297 $start = microtime( true );
298 do {
299 if ( ( ++$rounds % 4 ) == 0 ) {
300 usleep( 1000 * 50 ); // 50 ms
302 foreach ( array_diff( $keys, $lockedKeys ) as $key ) {
303 if ( $memc->add( "$key:mutex", 1, 180 ) ) { // lock record
304 $lockedKeys[] = $key;
305 } else {
306 continue; // acquire in order
309 } while ( count( $lockedKeys ) < count( $keys ) && ( microtime( true ) - $start ) <= 3 );
311 if ( count( $lockedKeys ) != count( $keys ) ) {
312 $this->releaseMutexes( $memc, $lockedKeys ); // failed; release what was locked
313 return false;
316 return true;
320 * @param $memc MemcachedBagOStuff
321 * @param array $keys List of acquired keys
322 * @return void
324 protected function releaseMutexes( MemcachedBagOStuff $memc, array $keys ) {
325 foreach ( $keys as $key ) {
326 $memc->delete( "$key:mutex" );
331 * Make sure remaining locks get cleared for sanity
333 function __destruct() {
334 while ( count( $this->locksHeld ) ) {
335 foreach ( $this->locksHeld as $path => $locks ) {
336 $this->doUnlock( array( $path ), self::LOCK_EX );
337 $this->doUnlock( array( $path ), self::LOCK_SH );