4 * Manage locks using a lock daemon server.
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.
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.
15 * @ingroup LockManager
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
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, ...))
31 /** @var Array Map Server connections (server name => resource) */
32 protected $conns = array();
34 protected $connTimeout; // float number of seconds
35 protected $session = ''; // random SHA-1 string
38 * Construct a new instance from configuration.
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
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]
50 * @param Array $config
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
58 if ( isset( $config['connTimeout'] ) ) {
59 $this->connTimeout
= $config['connTimeout'];
61 $this->connTimeout
= 3; // use some sane amount
65 for ( $i = 0; $i < 5; $i++
) {
66 $this->session
.= mt_rand( 0, 2147483647 );
68 $this->session
= wfBaseConvert( sha1( $this->session
), 16, 36, 31 );
72 * @see LockManager::doLock()
75 protected function doLock( array $paths, $type ) {
76 $status = Status
::newGood();
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;
86 $bucket = $this->getBucketFromKey( $path );
87 $pathsToLock[$bucket][] = $path;
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 );
102 $status->merge( $this->doUnlock( $lockedPaths, $type ) );
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 );
110 $status->merge( $this->doUnlock( $lockedPaths, $type ) );
113 // Record these locks as active
114 foreach ( $paths as $path ) {
115 $this->locksHeld
[$path][$type] = 1; // locked
117 // Keep track of what locks were made in this attempt
118 $lockedPaths = array_merge( $lockedPaths, $paths );
125 * @see LockManager::doUnlock()
128 protected function doUnlock( array $paths, $type ) {
129 $status = Status
::newGood();
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 );
137 --$this->locksHeld
[$path][$type];
138 if ( $this->locksHeld
[$path][$type] <= 0 ) {
139 unset( $this->locksHeld
[$path][$type] );
141 if ( !count( $this->locksHeld
[$path] ) ) {
142 unset( $this->locksHeld
[$path] ); // no SH or EX locks left for key
147 // Reference count the locks held and release locks when zero
148 if ( !count( $this->locksHeld
) ) {
149 $status->merge( $this->releaseLocks() );
156 * Get a connection to a lock server and acquire locks on $paths
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
163 protected function doLockingRequest( $lockSrv, array $paths, $type ) {
164 if ( $type == self
::LOCK_SH
) { // reader locks
166 } elseif ( $type == self
::LOCK_EX
) { // writer locks
169 return true; // ok...
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 );
176 return ( $response === 'ACQUIRED' );
180 * Send a command and get back the response
182 * @param $lockSrv string
183 * @param $action string
184 * @param $type string
185 * @param $values Array
186 * @return string|bool
188 protected function sendCommand( $lockSrv, $action, $type, $values ) {
189 $conn = $this->getConnection( $lockSrv );
191 return false; // no connection
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 ) {
201 // Get the response...
202 $response = fgets( $conn );
203 if ( $response === false ) {
206 return trim( $response );
210 * Attempt to acquire locks with the peers for a bucket
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')
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
227 ++
$yesVotes; // success for this peer
228 if ( $yesVotes >= $quorum ) {
229 return true; // lock obtained
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
238 // At this point, we must not have meet the quorum
239 return 'srverrors'; // not enough votes to ensure correctness
243 * Get (or reuse) a connection to a lock server
245 * @param $lockSrv string
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
);
255 if ( $conn === false ) {
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;
263 return $this->conns
[$lockSrv];
267 * Release all locks that this session is holding
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 );
283 * Get the bucket for resource path.
284 * This should avoid throwing any exceptions.
286 * @param $path string
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
);
295 * Make sure remaining locks get cleared for sanity
297 function __destruct() {
298 $this->releaseLocks();
299 foreach ( $this->conns
as $conn ) {