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