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