3 * Version of LockManager based on using lock daemon servers.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
21 * @ingroup LockManager
25 * Manage locks using a lock daemon server.
27 * Version of LockManager based on using lock daemon servers.
28 * This is meant for multi-wiki systems that may share files.
29 * All locks are non-blocking, which avoids deadlocks.
31 * All lock requests for a resource, identified by a hash string, will map
32 * to one bucket. Each bucket maps to one or several peer servers, each
33 * running LockServerDaemon.php, listening on a designated TCP port.
34 * A majority of peers must agree for a lock to be acquired.
36 * @ingroup LockManager
39 class LSLockManager
extends LockManager
{
40 /** @var Array Mapping of lock types to the type actually used */
41 protected $lockTypeMap = array(
42 self
::LOCK_SH
=> self
::LOCK_SH
,
43 self
::LOCK_UW
=> self
::LOCK_SH
,
44 self
::LOCK_EX
=> self
::LOCK_EX
47 /** @var Array Map of server names to server config */
48 protected $lockServers; // (server name => server config array)
49 /** @var Array Map of bucket indexes to peer server lists */
50 protected $srvsByBucket; // (bucket index => (lsrv1, lsrv2, ...))
52 /** @var Array Map Server connections (server name => resource) */
53 protected $conns = array();
55 protected $connTimeout; // float number of seconds
56 protected $session = ''; // random SHA-1 string
59 * Construct a new instance from configuration.
61 * $config paramaters include:
62 * 'lockServers' : Associative array of server names to configuration.
63 * Configuration is an associative array that includes:
64 * 'host' - IP address/hostname
66 * 'authKey' - Secret string the lock server uses
67 * 'srvsByBucket' : Array of 1-16 consecutive integer keys, starting from 0,
68 * each having an odd-numbered list of server names (peers) as values.
69 * 'connTimeout' : Lock server connection attempt timeout. [optional]
71 * @param Array $config
73 public function __construct( array $config ) {
74 parent
::__construct( $config );
76 $this->lockServers
= $config['lockServers'];
77 // Sanitize srvsByBucket config to prevent PHP errors
78 $this->srvsByBucket
= array_filter( $config['srvsByBucket'], 'is_array' );
79 $this->srvsByBucket
= array_values( $this->srvsByBucket
); // consecutive
81 if ( isset( $config['connTimeout'] ) ) {
82 $this->connTimeout
= $config['connTimeout'];
84 $this->connTimeout
= 3; // use some sane amount
88 for ( $i = 0; $i < 5; $i++
) {
89 $this->session
.= mt_rand( 0, 2147483647 );
91 $this->session
= wfBaseConvert( sha1( $this->session
), 16, 36, 31 );
95 * @see LockManager::doLock()
98 protected function doLock( array $paths, $type ) {
99 $status = Status
::newGood();
101 $pathsToLock = array();
102 // Get locks that need to be acquired (buckets => locks)...
103 foreach ( $paths as $path ) {
104 if ( isset( $this->locksHeld
[$path][$type] ) ) {
105 ++
$this->locksHeld
[$path][$type];
106 } elseif ( isset( $this->locksHeld
[$path][self
::LOCK_EX
] ) ) {
107 $this->locksHeld
[$path][$type] = 1;
109 $bucket = $this->getBucketFromKey( $path );
110 $pathsToLock[$bucket][] = $path;
114 $lockedPaths = array(); // files locked in this attempt
115 // Attempt to acquire these locks...
116 foreach ( $pathsToLock as $bucket => $paths ) {
117 // Try to acquire the locks for this bucket
118 $res = $this->doLockingRequestAll( $bucket, $paths, $type );
119 if ( $res === 'cantacquire' ) {
120 // Resources already locked by another process.
121 // Abort and unlock everything we just locked.
122 foreach ( $paths as $path ) {
123 $status->fatal( 'lockmanager-fail-acquirelock', $path );
125 $status->merge( $this->doUnlock( $lockedPaths, $type ) );
127 } elseif ( $res !== true ) {
128 // Couldn't contact any servers for this bucket.
129 // Abort and unlock everything we just locked.
130 foreach ( $paths as $path ) {
131 $status->fatal( 'lockmanager-fail-acquirelock', $path );
133 $status->merge( $this->doUnlock( $lockedPaths, $type ) );
136 // Record these locks as active
137 foreach ( $paths as $path ) {
138 $this->locksHeld
[$path][$type] = 1; // locked
140 // Keep track of what locks were made in this attempt
141 $lockedPaths = array_merge( $lockedPaths, $paths );
148 * @see LockManager::doUnlock()
151 protected function doUnlock( array $paths, $type ) {
152 $status = Status
::newGood();
154 foreach ( $paths as $path ) {
155 if ( !isset( $this->locksHeld
[$path] ) ) {
156 $status->warning( 'lockmanager-notlocked', $path );
157 } elseif ( !isset( $this->locksHeld
[$path][$type] ) ) {
158 $status->warning( 'lockmanager-notlocked', $path );
160 --$this->locksHeld
[$path][$type];
161 if ( $this->locksHeld
[$path][$type] <= 0 ) {
162 unset( $this->locksHeld
[$path][$type] );
164 if ( !count( $this->locksHeld
[$path] ) ) {
165 unset( $this->locksHeld
[$path] ); // no SH or EX locks left for key
170 // Reference count the locks held and release locks when zero
171 if ( !count( $this->locksHeld
) ) {
172 $status->merge( $this->releaseLocks() );
179 * Get a connection to a lock server and acquire locks on $paths
181 * @param $lockSrv string
182 * @param $paths Array
183 * @param $type integer LockManager::LOCK_EX or LockManager::LOCK_SH
184 * @return bool Resources able to be locked
186 protected function doLockingRequest( $lockSrv, array $paths, $type ) {
187 if ( $type == self
::LOCK_SH
) { // reader locks
189 } elseif ( $type == self
::LOCK_EX
) { // writer locks
192 return true; // ok...
195 // Send out the command and get the response...
196 $keys = array_unique( array_map( 'LockManager::sha1Base36', $paths ) );
197 $response = $this->sendCommand( $lockSrv, 'ACQUIRE', $type, $keys );
199 return ( $response === 'ACQUIRED' );
203 * Send a command and get back the response
205 * @param $lockSrv string
206 * @param $action string
207 * @param $type string
208 * @param $values Array
209 * @return string|bool
211 protected function sendCommand( $lockSrv, $action, $type, $values ) {
212 $conn = $this->getConnection( $lockSrv );
214 return false; // no connection
216 $authKey = $this->lockServers
[$lockSrv]['authKey'];
217 // Build of the command as a flat string...
218 $values = implode( '|', $values );
219 $key = sha1( $this->session
. $action . $type . $values . $authKey );
220 // Send out the command...
221 if ( fwrite( $conn, "{$this->session}:$key:$action:$type:$values\n" ) === false ) {
224 // Get the response...
225 $response = fgets( $conn );
226 if ( $response === false ) {
229 return trim( $response );
233 * Attempt to acquire locks with the peers for a bucket
235 * @param $bucket integer
236 * @param $paths Array List of resource keys to lock
237 * @param $type integer LockManager::LOCK_EX or LockManager::LOCK_SH
238 * @return bool|string One of (true, 'cantacquire', 'srverrors')
240 protected function doLockingRequestAll( $bucket, array $paths, $type ) {
241 $yesVotes = 0; // locks made on trustable servers
242 $votesLeft = count( $this->srvsByBucket
[$bucket] ); // remaining peers
243 $quorum = floor( $votesLeft/2 +
1 ); // simple majority
244 // Get votes for each peer, in order, until we have enough...
245 foreach ( $this->srvsByBucket
[$bucket] as $lockSrv ) {
246 // Attempt to acquire the lock on this peer
247 if ( !$this->doLockingRequest( $lockSrv, $paths, $type ) ) {
248 return 'cantacquire'; // vetoed; resource locked
250 ++
$yesVotes; // success for this peer
251 if ( $yesVotes >= $quorum ) {
252 return true; // lock obtained
255 $votesNeeded = $quorum - $yesVotes;
256 if ( $votesNeeded > $votesLeft ) {
257 // In "trust cache" mode we don't have to meet the quorum
258 break; // short-circuit
261 // At this point, we must not have meet the quorum
262 return 'srverrors'; // not enough votes to ensure correctness
266 * Get (or reuse) a connection to a lock server
268 * @param $lockSrv string
271 protected function getConnection( $lockSrv ) {
272 if ( !isset( $this->conns
[$lockSrv] ) ) {
273 $cfg = $this->lockServers
[$lockSrv];
274 wfSuppressWarnings();
275 $errno = $errstr = '';
276 $conn = fsockopen( $cfg['host'], $cfg['port'], $errno, $errstr, $this->connTimeout
);
278 if ( $conn === false ) {
281 $sec = floor( $this->connTimeout
);
282 $usec = floor( ( $this->connTimeout
- floor( $this->connTimeout
) ) * 1e6
);
283 stream_set_timeout( $conn, $sec, $usec );
284 $this->conns
[$lockSrv] = $conn;
286 return $this->conns
[$lockSrv];
290 * Release all locks that this session is holding
294 protected function releaseLocks() {
295 $status = Status
::newGood();
296 foreach ( $this->conns
as $lockSrv => $conn ) {
297 $response = $this->sendCommand( $lockSrv, 'RELEASE_ALL', '', array() );
298 if ( $response !== 'RELEASED_ALL' ) {
299 $status->fatal( 'lockmanager-fail-svr-release', $lockSrv );
306 * Get the bucket for resource path.
307 * This should avoid throwing any exceptions.
309 * @param $path string
312 protected function getBucketFromKey( $path ) {
313 $prefix = substr( sha1( $path ), 0, 2 ); // first 2 hex chars (8 bits)
314 return intval( base_convert( $prefix, 16, 10 ) ) %
count( $this->srvsByBucket
);
318 * Make sure remaining locks get cleared for sanity
320 function __destruct() {
321 $this->releaseLocks();
322 foreach ( $this->conns
as $conn ) {