Revert "Adding sanity check to Title::isRedirect()."
[lhc/web/wiklou.git] / includes / filerepo / backend / lockmanager / LSLockManager.php
1 <?php
2 /**
3 * Version of LockManager based on using lock daemon 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 a lock daemon server.
26 *
27 * Version of LockManager based on using lock daemon 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
32 * to one bucket. Each bucket maps to one or several peer servers, each
33 * running LockServerDaemon.php, listening on a designated TCP port.
34 * A majority of peers must agree for a lock to be acquired.
35 *
36 * @ingroup LockManager
37 * @since 1.19
38 */
39 class LSLockManager extends LockManager {
40 /** @var Array Mapping of lock types to the type actually used */
41 protected $lockTypeMap = array(
42 self::LOCK_SH => self::LOCK_SH,
43 self::LOCK_UW => self::LOCK_SH,
44 self::LOCK_EX => self::LOCK_EX
45 );
46
47 /** @var Array Map of server names to server config */
48 protected $lockServers; // (server name => server config array)
49 /** @var Array Map of bucket indexes to peer server lists */
50 protected $srvsByBucket; // (bucket index => (lsrv1, lsrv2, ...))
51
52 /** @var Array Map Server connections (server name => resource) */
53 protected $conns = array();
54
55 protected $connTimeout; // float number of seconds
56 protected $session = ''; // random SHA-1 string
57
58 /**
59 * Construct a new instance from configuration.
60 *
61 * $config paramaters include:
62 * 'lockServers' : Associative array of server names to configuration.
63 * Configuration is an associative array that includes:
64 * 'host' - IP address/hostname
65 * 'port' - TCP port
66 * 'authKey' - Secret string the lock server uses
67 * 'srvsByBucket' : Array of 1-16 consecutive integer keys, starting from 0,
68 * each having an odd-numbered list of server names (peers) as values.
69 * 'connTimeout' : Lock server connection attempt timeout. [optional]
70 *
71 * @param Array $config
72 */
73 public function __construct( array $config ) {
74 parent::__construct( $config );
75
76 $this->lockServers = $config['lockServers'];
77 // Sanitize srvsByBucket config to prevent PHP errors
78 $this->srvsByBucket = array_filter( $config['srvsByBucket'], 'is_array' );
79 $this->srvsByBucket = array_values( $this->srvsByBucket ); // consecutive
80
81 if ( isset( $config['connTimeout'] ) ) {
82 $this->connTimeout = $config['connTimeout'];
83 } else {
84 $this->connTimeout = 3; // use some sane amount
85 }
86
87 $this->session = '';
88 for ( $i = 0; $i < 5; $i++ ) {
89 $this->session .= mt_rand( 0, 2147483647 );
90 }
91 $this->session = wfBaseConvert( sha1( $this->session ), 16, 36, 31 );
92 }
93
94 /**
95 * @see LockManager::doLock()
96 * @return Status
97 */
98 protected function doLock( array $paths, $type ) {
99 $status = Status::newGood();
100
101 $pathsToLock = array();
102 // Get locks that need to be acquired (buckets => locks)...
103 foreach ( $paths as $path ) {
104 if ( isset( $this->locksHeld[$path][$type] ) ) {
105 ++$this->locksHeld[$path][$type];
106 } elseif ( isset( $this->locksHeld[$path][self::LOCK_EX] ) ) {
107 $this->locksHeld[$path][$type] = 1;
108 } else {
109 $bucket = $this->getBucketFromKey( $path );
110 $pathsToLock[$bucket][] = $path;
111 }
112 }
113
114 $lockedPaths = array(); // files locked in this attempt
115 // Attempt to acquire these locks...
116 foreach ( $pathsToLock as $bucket => $paths ) {
117 // Try to acquire the locks for this bucket
118 $res = $this->doLockingRequestAll( $bucket, $paths, $type );
119 if ( $res === 'cantacquire' ) {
120 // Resources already locked by another process.
121 // Abort and unlock everything we just locked.
122 foreach ( $paths as $path ) {
123 $status->fatal( 'lockmanager-fail-acquirelock', $path );
124 }
125 $status->merge( $this->doUnlock( $lockedPaths, $type ) );
126 return $status;
127 } elseif ( $res !== true ) {
128 // Couldn't contact any servers for this bucket.
129 // Abort and unlock everything we just locked.
130 foreach ( $paths as $path ) {
131 $status->fatal( 'lockmanager-fail-acquirelock', $path );
132 }
133 $status->merge( $this->doUnlock( $lockedPaths, $type ) );
134 return $status;
135 }
136 // Record these locks as active
137 foreach ( $paths as $path ) {
138 $this->locksHeld[$path][$type] = 1; // locked
139 }
140 // Keep track of what locks were made in this attempt
141 $lockedPaths = array_merge( $lockedPaths, $paths );
142 }
143
144 return $status;
145 }
146
147 /**
148 * @see LockManager::doUnlock()
149 * @return Status
150 */
151 protected function doUnlock( array $paths, $type ) {
152 $status = Status::newGood();
153
154 foreach ( $paths as $path ) {
155 if ( !isset( $this->locksHeld[$path] ) ) {
156 $status->warning( 'lockmanager-notlocked', $path );
157 } elseif ( !isset( $this->locksHeld[$path][$type] ) ) {
158 $status->warning( 'lockmanager-notlocked', $path );
159 } else {
160 --$this->locksHeld[$path][$type];
161 if ( $this->locksHeld[$path][$type] <= 0 ) {
162 unset( $this->locksHeld[$path][$type] );
163 }
164 if ( !count( $this->locksHeld[$path] ) ) {
165 unset( $this->locksHeld[$path] ); // no SH or EX locks left for key
166 }
167 }
168 }
169
170 // Reference count the locks held and release locks when zero
171 if ( !count( $this->locksHeld ) ) {
172 $status->merge( $this->releaseLocks() );
173 }
174
175 return $status;
176 }
177
178 /**
179 * Get a connection to a lock server and acquire locks on $paths
180 *
181 * @param $lockSrv string
182 * @param $paths Array
183 * @param $type integer LockManager::LOCK_EX or LockManager::LOCK_SH
184 * @return bool Resources able to be locked
185 */
186 protected function doLockingRequest( $lockSrv, array $paths, $type ) {
187 if ( $type == self::LOCK_SH ) { // reader locks
188 $type = 'SH';
189 } elseif ( $type == self::LOCK_EX ) { // writer locks
190 $type = 'EX';
191 } else {
192 return true; // ok...
193 }
194
195 // Send out the command and get the response...
196 $keys = array_unique( array_map( 'LockManager::sha1Base36', $paths ) );
197 $response = $this->sendCommand( $lockSrv, 'ACQUIRE', $type, $keys );
198
199 return ( $response === 'ACQUIRED' );
200 }
201
202 /**
203 * Send a command and get back the response
204 *
205 * @param $lockSrv string
206 * @param $action string
207 * @param $type string
208 * @param $values Array
209 * @return string|bool
210 */
211 protected function sendCommand( $lockSrv, $action, $type, $values ) {
212 $conn = $this->getConnection( $lockSrv );
213 if ( !$conn ) {
214 return false; // no connection
215 }
216 $authKey = $this->lockServers[$lockSrv]['authKey'];
217 // Build of the command as a flat string...
218 $values = implode( '|', $values );
219 $key = sha1( $this->session . $action . $type . $values . $authKey );
220 // Send out the command...
221 if ( fwrite( $conn, "{$this->session}:$key:$action:$type:$values\n" ) === false ) {
222 return false;
223 }
224 // Get the response...
225 $response = fgets( $conn );
226 if ( $response === false ) {
227 return false;
228 }
229 return trim( $response );
230 }
231
232 /**
233 * Attempt to acquire locks with the peers for a bucket
234 *
235 * @param $bucket integer
236 * @param $paths Array List of resource keys to lock
237 * @param $type integer LockManager::LOCK_EX or LockManager::LOCK_SH
238 * @return bool|string One of (true, 'cantacquire', 'srverrors')
239 */
240 protected function doLockingRequestAll( $bucket, array $paths, $type ) {
241 $yesVotes = 0; // locks made on trustable servers
242 $votesLeft = count( $this->srvsByBucket[$bucket] ); // remaining peers
243 $quorum = floor( $votesLeft/2 + 1 ); // simple majority
244 // Get votes for each peer, in order, until we have enough...
245 foreach ( $this->srvsByBucket[$bucket] as $lockSrv ) {
246 // Attempt to acquire the lock on this peer
247 if ( !$this->doLockingRequest( $lockSrv, $paths, $type ) ) {
248 return 'cantacquire'; // vetoed; resource locked
249 }
250 ++$yesVotes; // success for this peer
251 if ( $yesVotes >= $quorum ) {
252 return true; // lock obtained
253 }
254 --$votesLeft;
255 $votesNeeded = $quorum - $yesVotes;
256 if ( $votesNeeded > $votesLeft ) {
257 // In "trust cache" mode we don't have to meet the quorum
258 break; // short-circuit
259 }
260 }
261 // At this point, we must not have meet the quorum
262 return 'srverrors'; // not enough votes to ensure correctness
263 }
264
265 /**
266 * Get (or reuse) a connection to a lock server
267 *
268 * @param $lockSrv string
269 * @return resource
270 */
271 protected function getConnection( $lockSrv ) {
272 if ( !isset( $this->conns[$lockSrv] ) ) {
273 $cfg = $this->lockServers[$lockSrv];
274 wfSuppressWarnings();
275 $errno = $errstr = '';
276 $conn = fsockopen( $cfg['host'], $cfg['port'], $errno, $errstr, $this->connTimeout );
277 wfRestoreWarnings();
278 if ( $conn === false ) {
279 return null;
280 }
281 $sec = floor( $this->connTimeout );
282 $usec = floor( ( $this->connTimeout - floor( $this->connTimeout ) ) * 1e6 );
283 stream_set_timeout( $conn, $sec, $usec );
284 $this->conns[$lockSrv] = $conn;
285 }
286 return $this->conns[$lockSrv];
287 }
288
289 /**
290 * Release all locks that this session is holding
291 *
292 * @return Status
293 */
294 protected function releaseLocks() {
295 $status = Status::newGood();
296 foreach ( $this->conns as $lockSrv => $conn ) {
297 $response = $this->sendCommand( $lockSrv, 'RELEASE_ALL', '', array() );
298 if ( $response !== 'RELEASED_ALL' ) {
299 $status->fatal( 'lockmanager-fail-svr-release', $lockSrv );
300 }
301 }
302 return $status;
303 }
304
305 /**
306 * Get the bucket for resource path.
307 * This should avoid throwing any exceptions.
308 *
309 * @param $path string
310 * @return integer
311 */
312 protected function getBucketFromKey( $path ) {
313 $prefix = substr( sha1( $path ), 0, 2 ); // first 2 hex chars (8 bits)
314 return intval( base_convert( $prefix, 16, 10 ) ) % count( $this->srvsByBucket );
315 }
316
317 /**
318 * Make sure remaining locks get cleared for sanity
319 */
320 function __destruct() {
321 $this->releaseLocks();
322 foreach ( $this->conns as $conn ) {
323 fclose( $conn );
324 }
325 }
326 }