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 $status->fatal( 'lockmanager-fail-acquirelocks', implode( ', ', $paths ) );
92 $status->merge( $this->doUnlock( $lockedPaths, $type ) );
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 ) );
101 // Record these locks as active
102 foreach ( $paths as $path ) {
103 $this->locksHeld
[$path][$type] = 1; // locked
105 // Keep track of what locks were made in this attempt
106 $lockedPaths = array_merge( $lockedPaths, $paths );
112 protected function doUnlock( array $paths, $type ) {
113 $status = Status
::newGood();
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 );
121 --$this->locksHeld
[$path][$type];
122 if ( $this->locksHeld
[$path][$type] <= 0 ) {
123 unset( $this->locksHeld
[$path][$type] );
125 if ( !count( $this->locksHeld
[$path] ) ) {
126 unset( $this->locksHeld
[$path] ); // no SH or EX locks left for key
131 // Reference count the locks held and release locks when zero
132 if ( !count( $this->locksHeld
) ) {
133 $status->merge( $this->releaseLocks() );
140 * Get a connection to a lock server and acquire locks on $paths
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
147 protected function doLockingRequest( $lockSrv, array $paths, $type ) {
148 if ( $type == self
::LOCK_SH
) { // reader locks
150 } elseif ( $type == self
::LOCK_EX
) { // writer locks
153 return true; // ok...
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 );
160 return ( $response === 'ACQUIRED' );
164 * Send a command and get back the response
166 * @param $lockSrv string
167 * @param $action string
168 * @param $type string
169 * @param $values Array
170 * @return string|false
172 protected function sendCommand( $lockSrv, $action, $type, $values ) {
173 $conn = $this->getConnection( $lockSrv );
175 return false; // no connection
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 ) {
185 // Get the response...
186 $response = fgets( $conn );
187 if ( $response === false ) {
190 return trim( $response );
194 * Attempt to acquire locks with the peers for a bucket
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')
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
211 ++
$yesVotes; // success for this peer
212 if ( $yesVotes >= $quorum ) {
213 return true; // lock obtained
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
222 // At this point, we must not have meet the quorum
223 return 'srverrors'; // not enough votes to ensure correctness
227 * Get (or reuse) a connection to a lock server
229 * @param $lockSrv string
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
);
239 if ( $conn === false ) {
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;
247 return $this->conns
[$lockSrv];
251 * Release all locks that this session is holding
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 );
267 * Get the bucket for resource path.
268 * This should avoid throwing any exceptions.
270 * @param $path string
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
);
279 * Make sure remaining locks get cleared for sanity
281 function __destruct() {
282 $this->releaseLocks();
283 foreach ( $this->conns
as $lockSrv => $conn ) {