ea9dde7f2a09ae5023d246c465792197ff448116
3 * Version of LockManager based on using redis 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 redis servers.
27 * Version of LockManager based on using redis 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 to one
32 * bucket. Each bucket maps to one or several peer servers, each running redis.
33 * A majority of peers must agree for a lock to be acquired.
35 * This class requires Redis 2.6 as it makes use Lua scripts for fast atomic operations.
37 * @ingroup LockManager
40 class RedisLockManager
extends QuorumLockManager
{
41 /** @var array Mapping of lock types to the type actually used */
42 protected $lockTypeMap = [
43 self
::LOCK_SH
=> self
::LOCK_SH
,
44 self
::LOCK_UW
=> self
::LOCK_SH
,
45 self
::LOCK_EX
=> self
::LOCK_EX
48 /** @var RedisConnectionPool */
51 /** @var array Map server names to hostname/IP and port numbers */
52 protected $lockServers = [];
55 * Construct a new instance from configuration.
57 * @param array $config Parameters include:
58 * - lockServers : Associative array of server names to "<IP>:<port>" strings.
59 * - srvsByBucket : Array of 1-16 consecutive integer keys, starting from 0,
60 * each having an odd-numbered list of server names (peers) as values.
61 * - redisConfig : Configuration for RedisConnectionPool::__construct().
64 public function __construct( array $config ) {
65 parent
::__construct( $config );
67 $this->lockServers
= $config['lockServers'];
68 // Sanitize srvsByBucket config to prevent PHP errors
69 $this->srvsByBucket
= array_filter( $config['srvsByBucket'], 'is_array' );
70 $this->srvsByBucket
= array_values( $this->srvsByBucket
); // consecutive
72 $config['redisConfig']['serializer'] = 'none';
73 $this->redisPool
= RedisConnectionPool
::singleton( $config['redisConfig'] );
76 protected function getLocksOnServer( $lockSrv, array $pathsByType ) {
77 $status = StatusValue
::newGood();
79 $pathList = call_user_func_array( 'array_merge', array_values( $pathsByType ) );
81 $server = $this->lockServers
[$lockSrv];
82 $conn = $this->redisPool
->getConnection( $server, $this->logger
);
84 foreach ( $pathList as $path ) {
85 $status->fatal( 'lockmanager-fail-acquirelock', $path );
91 $pathsByKey = []; // (type:hash => path) map
92 foreach ( $pathsByType as $type => $paths ) {
93 $typeString = ( $type == LockManager
::LOCK_SH
) ?
'SH' : 'EX';
94 foreach ( $paths as $path ) {
95 $pathsByKey[$this->recordKeyForPath( $path, $typeString )] = $path;
104 -- Load input params (e.g. session, ttl, time of request)
105 local rSession, rTTL, rMaxTTL, rTime = unpack(ARGV)
106 -- Check that all the locks can be acquired
107 for i,requestKey in ipairs(KEYS) do
108 local _, _, rType, resourceKey = string.find(requestKey,"(%w+):(%w+)$")
109 local keyIsFree = true
110 local currentLocks = redis.call('hKeys',resourceKey)
111 for i,lockKey in ipairs(currentLocks) do
112 -- Get the type and session of this lock
113 local _, _, type, session = string.find(lockKey,"(%w+):(%w+)")
114 -- Check any locks that are not owned by this session
115 if session ~= rSession then
116 local lockExpiry = redis.call('hGet',resourceKey,lockKey)
117 if 1*lockExpiry < 1*rTime then
118 -- Lock is stale, so just prune it out
119 redis.call('hDel',resourceKey,lockKey)
120 elseif rType == 'EX' or type == 'EX' then
126 if not keyIsFree then
127 failed[#failed+1] = requestKey
130 -- If all locks could be acquired, then do so
132 for i,requestKey in ipairs(KEYS) do
133 local _, _, rType, resourceKey = string.find(requestKey,"(%w+):(%w+)$")
134 redis.call('hSet',resourceKey,rType .. ':' .. rSession,rTime + rTTL)
135 -- In addition to invalidation logic, be sure to garbage collect
136 redis.call('expire',resourceKey,rMaxTTL)
141 $res = $conn->luaEval( $script,
143 array_keys( $pathsByKey ), // KEYS[0], KEYS[1],...,KEYS[N]
145 $this->session
, // ARGV[1]
146 $this->lockTTL
, // ARGV[2]
147 self
::MAX_LOCK_TTL
, // ARGV[3]
151 count( $pathsByKey ) # number of first argument(s) that are keys
153 } catch ( RedisException
$e ) {
155 $this->redisPool
->handleError( $conn, $e );
158 if ( $res === false ) {
159 foreach ( $pathList as $path ) {
160 $status->fatal( 'lockmanager-fail-acquirelock', $path );
163 foreach ( $res as $key ) {
164 $status->fatal( 'lockmanager-fail-acquirelock', $pathsByKey[$key] );
171 protected function freeLocksOnServer( $lockSrv, array $pathsByType ) {
172 $status = StatusValue
::newGood();
174 $pathList = call_user_func_array( 'array_merge', array_values( $pathsByType ) );
176 $server = $this->lockServers
[$lockSrv];
177 $conn = $this->redisPool
->getConnection( $server, $this->logger
);
179 foreach ( $pathList as $path ) {
180 $status->fatal( 'lockmanager-fail-releaselock', $path );
186 $pathsByKey = []; // (type:hash => path) map
187 foreach ( $pathsByType as $type => $paths ) {
188 $typeString = ( $type == LockManager
::LOCK_SH
) ?
'SH' : 'EX';
189 foreach ( $paths as $path ) {
190 $pathsByKey[$this->recordKeyForPath( $path, $typeString )] = $path;
199 -- Load input params (e.g. session)
200 local rSession = unpack(ARGV)
201 for i,requestKey in ipairs(KEYS) do
202 local _, _, rType, resourceKey = string.find(requestKey,"(%w+):(%w+)$")
203 local released = redis.call('hDel',resourceKey,rType .. ':' .. rSession)
205 -- Remove the whole structure if it is now empty
206 if redis.call('hLen',resourceKey) == 0 then
207 redis.call('del',resourceKey)
210 failed[#failed+1] = requestKey
215 $res = $conn->luaEval( $script,
217 array_keys( $pathsByKey ), // KEYS[0], KEYS[1],...,KEYS[N]
219 $this->session
, // ARGV[1]
222 count( $pathsByKey ) # number of first argument(s) that are keys
224 } catch ( RedisException
$e ) {
226 $this->redisPool
->handleError( $conn, $e );
229 if ( $res === false ) {
230 foreach ( $pathList as $path ) {
231 $status->fatal( 'lockmanager-fail-releaselock', $path );
234 foreach ( $res as $key ) {
235 $status->fatal( 'lockmanager-fail-releaselock', $pathsByKey[$key] );
242 protected function releaseAllLocks() {
243 return StatusValue
::newGood(); // not supported
246 protected function isServerUp( $lockSrv ) {
247 $conn = $this->redisPool
->getConnection( $this->lockServers
[$lockSrv], $this->logger
);
253 * @param string $path
254 * @param string $type One of (EX,SH)
257 protected function recordKeyForPath( $path, $type ) {
259 [ __CLASS__
, 'locks', "$type:" . $this->sha1Base36Absolute( $path ) ] );
263 * Make sure remaining locks get cleared for sanity
265 function __destruct() {
266 while ( count( $this->locksHeld
) ) {
268 foreach ( $this->locksHeld
as $path => $locks ) {
269 foreach ( $locks as $type => $count ) {
270 $pathsByType[$type][] = $path;
273 $this->unlockByType( $pathsByType );