Merge "Add Special:Login and Special:Logout as aliases."
[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 /**
92 * @see QuorumLockManager::getLocksOnServer()
93 * @return Status
94 */
95 protected function getLocksOnServer( $lockSrv, array $paths, $type ) {
96 $status = Status::newGood();
97
98 $memc = $this->getCache( $lockSrv );
99 $keys = array_map( array( $this, 'recordKeyForPath' ), $paths ); // lock records
100
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 );
105 }
106 return $status;
107 }
108
109 // Fetch all the existing lock records...
110 $lockRecords = $memc->getMulti( $keys );
111
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 );
124 }
125 }
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 );
132 }
133 }
134 }
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;
140 }
141 }
142
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" );
153 }
154 }
155 }
156
157 // Unlock all of the active lock record keys...
158 $this->releaseMutexes( $memc, $keys );
159
160 return $status;
161 }
162
163 /**
164 * @see QuorumLockManager::freeLocksOnServer()
165 * @return Status
166 */
167 protected function freeLocksOnServer( $lockSrv, array $paths, $type ) {
168 $status = Status::newGood();
169
170 $memc = $this->getCache( $lockSrv );
171 $keys = array_map( array( $this, 'recordKeyForPath' ), $paths ); // lock records
172
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 );
177 }
178 return;
179 }
180
181 // Fetch all the existing lock records...
182 $lockRecords = $memc->getMulti( $keys );
183
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
190 }
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 );
198 }
199 if ( !$ok ) {
200 $status->fatal( 'lockmanager-fail-releaselock', $path );
201 }
202 } else {
203 $status->warning( 'lockmanager-fail-releaselock', $path );
204 }
205 wfDebug( __METHOD__ . ": released lock on key $locksKey.\n" );
206 }
207
208 // Unlock all of the active lock record keys...
209 $this->releaseMutexes( $memc, $keys );
210
211 return $status;
212 }
213
214 /**
215 * @see QuorumLockManager::releaseAllLocks()
216 * @return Status
217 */
218 protected function releaseAllLocks() {
219 return Status::newGood(); // not supported
220 }
221
222 /**
223 * @see QuorumLockManager::isServerUp()
224 * @return bool
225 */
226 protected function isServerUp( $lockSrv ) {
227 return (bool)$this->getCache( $lockSrv );
228 }
229
230 /**
231 * Get the MemcachedBagOStuff object for a $lockSrv
232 *
233 * @param string $lockSrv Server name
234 * @return MemcachedBagOStuff|null
235 */
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 );
244 }
245 }
246 if ( !$this->serversUp[$lockSrv] ) {
247 return null; // server appears to be down
248 }
249 }
250 return $memc;
251 }
252
253 /**
254 * @param $path string
255 * @return string
256 */
257 protected function recordKeyForPath( $path ) {
258 return implode( ':', array( __CLASS__, 'locks', $this->sha1Base36Absolute( $path ) ) );
259 }
260
261 /**
262 * @return Array An empty lock structure for a key
263 */
264 protected static function newLockArray() {
265 return array( self::LOCK_SH => array(), self::LOCK_EX => array() );
266 }
267
268 /**
269 * @param $a array
270 * @return Array An empty lock structure for a key
271 */
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();
278 }
279 }
280
281 /**
282 * @param $memc MemcachedBagOStuff
283 * @param array $keys List of keys to acquire
284 * @return bool
285 */
286 protected function acquireMutexes( MemcachedBagOStuff $memc, array $keys ) {
287 $lockedKeys = array();
288
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 );
292
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
301 }
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
307 }
308 }
309 } while ( count( $lockedKeys ) < count( $keys ) && ( microtime( true ) - $start ) <= 3 );
310
311 if ( count( $lockedKeys ) != count( $keys ) ) {
312 $this->releaseMutexes( $memc, $lockedKeys ); // failed; release what was locked
313 return false;
314 }
315
316 return true;
317 }
318
319 /**
320 * @param $memc MemcachedBagOStuff
321 * @param array $keys List of acquired keys
322 * @return void
323 */
324 protected function releaseMutexes( MemcachedBagOStuff $memc, array $keys ) {
325 foreach ( $keys as $key ) {
326 $memc->delete( "$key:mutex" );
327 }
328 }
329
330 /**
331 * Make sure remaining locks get cleared for sanity
332 */
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 );
338 }
339 }
340 }
341 }