In LockManager classes:
[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 $status->fatal( 'lockmanager-fail-acquirelocks', implode( ', ', $paths ) );
92 $status->merge( $this->doUnlock( $lockedPaths, $type ) );
93 return $status;
94 } elseif ( $res !== true ) {
95 // Couldn't contact any servers for this bucket.
96 // Abort and unlock everything we just locked.
97 $status->fatal( 'lockmanager-fail-acquirelocks', implode( ', ', $paths ) );
98 $status->merge( $this->doUnlock( $lockedPaths, $type ) );
99 return $status;
100 }
101 // Record these locks as active
102 foreach ( $paths as $path ) {
103 $this->locksHeld[$path][$type] = 1; // locked
104 }
105 // Keep track of what locks were made in this attempt
106 $lockedPaths = array_merge( $lockedPaths, $paths );
107 }
108
109 return $status;
110 }
111
112 protected function doUnlock( array $paths, $type ) {
113 $status = Status::newGood();
114
115 foreach ( $paths as $path ) {
116 if ( !isset( $this->locksHeld[$path] ) ) {
117 $status->warning( 'lockmanager-notlocked', $path );
118 } elseif ( !isset( $this->locksHeld[$path][$type] ) ) {
119 $status->warning( 'lockmanager-notlocked', $path );
120 } else {
121 --$this->locksHeld[$path][$type];
122 if ( $this->locksHeld[$path][$type] <= 0 ) {
123 unset( $this->locksHeld[$path][$type] );
124 }
125 if ( !count( $this->locksHeld[$path] ) ) {
126 unset( $this->locksHeld[$path] ); // no SH or EX locks left for key
127 }
128 }
129 }
130
131 // Reference count the locks held and release locks when zero
132 if ( !count( $this->locksHeld ) ) {
133 $status->merge( $this->releaseLocks() );
134 }
135
136 return $status;
137 }
138
139 /**
140 * Get a connection to a lock server and acquire locks on $paths
141 *
142 * @param $lockSrv string
143 * @param $paths Array
144 * @param $type integer LockManager::LOCK_EX or LockManager::LOCK_SH
145 * @return bool Resources able to be locked
146 */
147 protected function doLockingRequest( $lockSrv, array $paths, $type ) {
148 if ( $type == self::LOCK_SH ) { // reader locks
149 $type = 'SH';
150 } elseif ( $type == self::LOCK_EX ) { // writer locks
151 $type = 'EX';
152 } else {
153 return true; // ok...
154 }
155
156 // Send out the command and get the response...
157 $keys = array_unique( array_map( 'LockManager::sha1Base36', $paths ) );
158 $response = $this->sendCommand( $lockSrv, 'ACQUIRE', $type, $keys );
159
160 return ( $response === 'ACQUIRED' );
161 }
162
163 /**
164 * Send a command and get back the response
165 *
166 * @param $lockSrv string
167 * @param $action string
168 * @param $type string
169 * @param $values Array
170 * @return string|false
171 */
172 protected function sendCommand( $lockSrv, $action, $type, $values ) {
173 $conn = $this->getConnection( $lockSrv );
174 if ( !$conn ) {
175 return false; // no connection
176 }
177 $authKey = $this->lockServers[$lockSrv]['authKey'];
178 // Build of the command as a flat string...
179 $values = implode( '|', $values );
180 $key = sha1( $this->session . $action . $type . $values . $authKey );
181 // Send out the command...
182 if ( fwrite( $conn, "{$this->session}:$key:$action:$type:$values\n" ) === false ) {
183 return false;
184 }
185 // Get the response...
186 $response = fgets( $conn );
187 if ( $response === false ) {
188 return false;
189 }
190 return trim( $response );
191 }
192
193 /**
194 * Attempt to acquire locks with the peers for a bucket
195 *
196 * @param $bucket integer
197 * @param $paths Array List of resource keys to lock
198 * @param $type integer LockManager::LOCK_EX or LockManager::LOCK_SH
199 * @return bool|string One of (true, 'cantacquire', 'srverrors')
200 */
201 protected function doLockingRequestAll( $bucket, array $paths, $type ) {
202 $yesVotes = 0; // locks made on trustable servers
203 $votesLeft = count( $this->srvsByBucket[$bucket] ); // remaining peers
204 $quorum = floor( $votesLeft/2 + 1 ); // simple majority
205 // Get votes for each peer, in order, until we have enough...
206 foreach ( $this->srvsByBucket[$bucket] as $index => $lockSrv ) {
207 // Attempt to acquire the lock on this peer
208 if ( !$this->doLockingRequest( $lockSrv, $paths, $type ) ) {
209 return 'cantacquire'; // vetoed; resource locked
210 }
211 ++$yesVotes; // success for this peer
212 if ( $yesVotes >= $quorum ) {
213 return true; // lock obtained
214 }
215 --$votesLeft;
216 $votesNeeded = $quorum - $yesVotes;
217 if ( $votesNeeded > $votesLeft ) {
218 // In "trust cache" mode we don't have to meet the quorum
219 break; // short-circuit
220 }
221 }
222 // At this point, we must not have meet the quorum
223 return 'srverrors'; // not enough votes to ensure correctness
224 }
225
226 /**
227 * Get (or reuse) a connection to a lock server
228 *
229 * @param $lockSrv string
230 * @return resource
231 */
232 protected function getConnection( $lockSrv ) {
233 if ( !isset( $this->conns[$lockSrv] ) ) {
234 $cfg = $this->lockServers[$lockSrv];
235 wfSuppressWarnings();
236 $errno = $errstr = '';
237 $conn = fsockopen( $cfg['host'], $cfg['port'], $errno, $errstr, $this->connTimeout );
238 wfRestoreWarnings();
239 if ( $conn === false ) {
240 return null;
241 }
242 $sec = floor( $this->connTimeout );
243 $usec = floor( ( $this->connTimeout - floor( $this->connTimeout ) ) * 1e6 );
244 stream_set_timeout( $conn, $sec, $usec );
245 $this->conns[$lockSrv] = $conn;
246 }
247 return $this->conns[$lockSrv];
248 }
249
250 /**
251 * Release all locks that this session is holding
252 *
253 * @return Status
254 */
255 protected function releaseLocks() {
256 $status = Status::newGood();
257 foreach ( $this->conns as $lockSrv => $conn ) {
258 $response = $this->sendCommand( $lockSrv, 'RELEASE_ALL', '', array() );
259 if ( $response !== 'RELEASED_ALL' ) {
260 $status->fatal( 'lockmanager-fail-svr-release', $lockSrv );
261 }
262 }
263 return $status;
264 }
265
266 /**
267 * Get the bucket for resource path.
268 * This should avoid throwing any exceptions.
269 *
270 * @param $path string
271 * @return integer
272 */
273 protected function getBucketFromKey( $path ) {
274 $prefix = substr( sha1( $path ), 0, 2 ); // first 2 hex chars (8 bits)
275 return intval( base_convert( $prefix, 16, 10 ) ) % count( $this->dbsByBucket );
276 }
277
278 /**
279 * Make sure remaining locks get cleared for sanity
280 */
281 function __destruct() {
282 $this->releaseLocks();
283 foreach ( $this->conns as $lockSrv => $conn ) {
284 fclose( $conn );
285 }
286 }
287 }