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.
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.
13 * @ingroup LockManager
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
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, ...))
28 /** @var Array Map Server connections (server name => resource) */
29 protected $conns = array();
31 protected $connTimeout; // float number of seconds
32 protected $session = ''; // random SHA-1 string
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
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]
46 * @param Array $config
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
54 if ( isset( $config['connTimeout'] ) ) {
55 $this->connTimeout
= $config['connTimeout'];
57 $this->connTimeout
= 3; // use some sane amount
61 for ( $i = 0; $i < 5; $i++
) {
62 $this->session
.= mt_rand( 0, 2147483647 );
64 $this->session
= wfBaseConvert( sha1( $this->session
), 16, 36, 31 );
67 protected function doLock( array $paths, $type ) {
68 $status = Status
::newGood();
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;
78 $bucket = $this->getBucketFromKey( $path );
79 $pathsToLock[$bucket][] = $path;
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 );
94 $status->merge( $this->doUnlock( $lockedPaths, $type ) );
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 );
102 $status->merge( $this->doUnlock( $lockedPaths, $type ) );
105 // Record these locks as active
106 foreach ( $paths as $path ) {
107 $this->locksHeld
[$path][$type] = 1; // locked
109 // Keep track of what locks were made in this attempt
110 $lockedPaths = array_merge( $lockedPaths, $paths );
116 protected function doUnlock( array $paths, $type ) {
117 $status = Status
::newGood();
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 );
125 --$this->locksHeld
[$path][$type];
126 if ( $this->locksHeld
[$path][$type] <= 0 ) {
127 unset( $this->locksHeld
[$path][$type] );
129 if ( !count( $this->locksHeld
[$path] ) ) {
130 unset( $this->locksHeld
[$path] ); // no SH or EX locks left for key
135 // Reference count the locks held and release locks when zero
136 if ( !count( $this->locksHeld
) ) {
137 $status->merge( $this->releaseLocks() );
144 * Get a connection to a lock server and acquire locks on $paths
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
151 protected function doLockingRequest( $lockSrv, array $paths, $type ) {
152 if ( $type == self
::LOCK_SH
) { // reader locks
154 } elseif ( $type == self
::LOCK_EX
) { // writer locks
157 return true; // ok...
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 );
164 return ( $response === 'ACQUIRED' );
168 * Send a command and get back the response
170 * @param $lockSrv string
171 * @param $action string
172 * @param $type string
173 * @param $values Array
174 * @return string|false
176 protected function sendCommand( $lockSrv, $action, $type, $values ) {
177 $conn = $this->getConnection( $lockSrv );
179 return false; // no connection
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 ) {
189 // Get the response...
190 $response = fgets( $conn );
191 if ( $response === false ) {
194 return trim( $response );
198 * Attempt to acquire locks with the peers for a bucket
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')
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
215 ++
$yesVotes; // success for this peer
216 if ( $yesVotes >= $quorum ) {
217 return true; // lock obtained
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
226 // At this point, we must not have meet the quorum
227 return 'srverrors'; // not enough votes to ensure correctness
231 * Get (or reuse) a connection to a lock server
233 * @param $lockSrv string
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
);
243 if ( $conn === false ) {
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;
251 return $this->conns
[$lockSrv];
255 * Release all locks that this session is holding
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 );
271 * Get the bucket for resource path.
272 * This should avoid throwing any exceptions.
274 * @param $path string
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
);
283 * Make sure remaining locks get cleared for sanity
285 function __destruct() {
286 $this->releaseLocks();
287 foreach ( $this->conns
as $conn ) {