MediaWiki master
RedisLockManager.php
Go to the documentation of this file.
1<?php
22
40 protected $lockTypeMap = [
41 self::LOCK_SH => self::LOCK_SH,
42 self::LOCK_UW => self::LOCK_SH,
43 self::LOCK_EX => self::LOCK_EX
44 ];
45
47 protected $redisPool;
48
50 protected $lockServers = [];
51
63 public function __construct( array $config ) {
64 parent::__construct( $config );
65
66 $this->lockServers = $config['lockServers'];
67 if ( isset( $config['srvsByBucket'] ) ) {
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
71 } else {
72 $this->srvsByBucket = [ array_keys( $this->lockServers ) ];
73 }
74
75 $config['redisConfig']['serializer'] = 'none';
76 $this->redisPool = RedisConnectionPool::singleton( $config['redisConfig'] );
77 }
78
79 protected function getLocksOnServer( $lockSrv, array $pathsByType ) {
80 $status = StatusValue::newGood();
81
82 $pathList = array_merge( ...array_values( $pathsByType ) );
83
84 $server = $this->lockServers[$lockSrv];
85 $conn = $this->redisPool->getConnection( $server, $this->logger );
86 if ( !$conn ) {
87 foreach ( $pathList as $path ) {
88 $status->fatal( 'lockmanager-fail-acquirelock', $path );
89 }
90
91 return $status;
92 }
93
94 $pathsByKey = []; // (type:hash => path) map
95 foreach ( $pathsByType as $type => $paths ) {
96 $typeString = ( $type == LockManager::LOCK_SH ) ? 'SH' : 'EX';
97 foreach ( $paths as $path ) {
98 $pathsByKey[$this->recordKeyForPath( $path, $typeString )] = $path;
99 }
100 }
101
102 try {
103 static $script =
105<<<LUA
106 local failed = {}
107 -- Load input params (e.g. session, ttl, time of request)
108 local rSession, rTTL, rMaxTTL, rTime = unpack(ARGV)
109 -- Check that all the locks can be acquired
110 for i,requestKey in ipairs(KEYS) do
111 local _, _, rType, resourceKey = string.find(requestKey,"(%w+):(%w+)$")
112 local keyIsFree = true
113 local currentLocks = redis.call('hKeys',resourceKey)
114 for i,lockKey in ipairs(currentLocks) do
115 -- Get the type and session of this lock
116 local _, _, type, session = string.find(lockKey,"(%w+):(%w+)")
117 -- Check any locks that are not owned by this session
118 if session ~= rSession then
119 local lockExpiry = redis.call('hGet',resourceKey,lockKey)
120 if 1*lockExpiry < 1*rTime then
121 -- Lock is stale, so just prune it out
122 redis.call('hDel',resourceKey,lockKey)
123 elseif rType == 'EX' or type == 'EX' then
124 keyIsFree = false
125 break
126 end
127 end
128 end
129 if not keyIsFree then
130 failed[#failed+1] = requestKey
131 end
132 end
133 -- If all locks could be acquired, then do so
134 if #failed == 0 then
135 for i,requestKey in ipairs(KEYS) do
136 local _, _, rType, resourceKey = string.find(requestKey,"(%w+):(%w+)$")
137 redis.call('hSet',resourceKey,rType .. ':' .. rSession,rTime + rTTL)
138 -- In addition to invalidation logic, be sure to garbage collect
139 redis.call('expire',resourceKey,rMaxTTL)
140 end
141 end
142 return failed
143LUA;
144 $res = $conn->luaEval( $script,
145 array_merge(
146 array_keys( $pathsByKey ), // KEYS[0], KEYS[1],...,KEYS[N]
147 [
148 $this->session, // ARGV[1]
149 $this->lockTTL, // ARGV[2]
150 self::MAX_LOCK_TTL, // ARGV[3]
151 time() // ARGV[4]
152 ]
153 ),
154 count( $pathsByKey ) # number of first argument(s) that are keys
155 );
156 } catch ( RedisException $e ) {
157 $res = false;
158 $this->redisPool->handleError( $conn, $e );
159 }
160
161 if ( $res === false ) {
162 foreach ( $pathList as $path ) {
163 $status->fatal( 'lockmanager-fail-acquirelock', $path );
164 }
165 } elseif ( count( $res ) ) {
166 $status->fatal( 'lockmanager-fail-conflict' );
167 }
168
169 return $status;
170 }
171
172 protected function freeLocksOnServer( $lockSrv, array $pathsByType ) {
173 $status = StatusValue::newGood();
174
175 $pathList = array_merge( ...array_values( $pathsByType ) );
176
177 $server = $this->lockServers[$lockSrv];
178 $conn = $this->redisPool->getConnection( $server, $this->logger );
179 if ( !$conn ) {
180 foreach ( $pathList as $path ) {
181 $status->fatal( 'lockmanager-fail-releaselock', $path );
182 }
183
184 return $status;
185 }
186
187 $pathsByKey = []; // (type:hash => path) map
188 foreach ( $pathsByType as $type => $paths ) {
189 $typeString = ( $type == LockManager::LOCK_SH ) ? 'SH' : 'EX';
190 foreach ( $paths as $path ) {
191 $pathsByKey[$this->recordKeyForPath( $path, $typeString )] = $path;
192 }
193 }
194
195 try {
196 static $script =
198<<<LUA
199 local failed = {}
200 -- Load input params (e.g. session)
201 local rSession = unpack(ARGV)
202 for i,requestKey in ipairs(KEYS) do
203 local _, _, rType, resourceKey = string.find(requestKey,"(%w+):(%w+)$")
204 local released = redis.call('hDel',resourceKey,rType .. ':' .. rSession)
205 if released > 0 then
206 -- Remove the whole structure if it is now empty
207 if redis.call('hLen',resourceKey) == 0 then
208 redis.call('del',resourceKey)
209 end
210 else
211 failed[#failed+1] = requestKey
212 end
213 end
214 return failed
215LUA;
216 $res = $conn->luaEval( $script,
217 array_merge(
218 array_keys( $pathsByKey ), // KEYS[0], KEYS[1],...,KEYS[N]
219 [
220 $this->session, // ARGV[1]
221 ]
222 ),
223 count( $pathsByKey ) # number of first argument(s) that are keys
224 );
225 } catch ( RedisException $e ) {
226 $res = false;
227 $this->redisPool->handleError( $conn, $e );
228 }
229
230 if ( $res === false ) {
231 foreach ( $pathList as $path ) {
232 $status->fatal( 'lockmanager-fail-releaselock', $path );
233 }
234 } else {
235 foreach ( $res as $key ) {
236 $status->fatal( 'lockmanager-fail-releaselock', $pathsByKey[$key] );
237 }
238 }
239
240 return $status;
241 }
242
243 protected function releaseAllLocks() {
244 return StatusValue::newGood(); // not supported
245 }
246
247 protected function isServerUp( $lockSrv ) {
248 $conn = $this->redisPool->getConnection( $this->lockServers[$lockSrv], $this->logger );
249
250 return (bool)$conn;
251 }
252
258 protected function recordKeyForPath( $path, $type ) {
259 return implode( ':',
260 [ __CLASS__, 'locks', "$type:" . $this->sha1Base36Absolute( $path ) ] );
261 }
262
266 public function __destruct() {
267 $pathsByType = [];
268 foreach ( $this->locksHeld as $path => $locks ) {
269 foreach ( $locks as $type => $count ) {
270 $pathsByType[$type][] = $path;
271 }
272 }
273 if ( $pathsByType ) {
274 $this->unlockByType( $pathsByType );
275 }
276 }
277}
lock(array $paths, $type=self::LOCK_EX, $timeout=0)
Lock the resources at the given abstract paths.
const LOCK_SH
Lock types; stronger locks have higher values.
sha1Base36Absolute( $path)
Get the base 36 SHA-1 of a string, padded to 31 digits.
unlockByType(array $pathsByType)
Unlock the resources at the given abstract paths.
Base class for lock managers that use a quorum of peer servers for locks.
Manage locks using redis servers.
__construct(array $config)
Construct a new instance from configuration.
recordKeyForPath( $path, $type)
freeLocksOnServer( $lockSrv, array $pathsByType)
Get a connection to a lock server and release locks on $paths.
RedisConnectionPool $redisPool
getLocksOnServer( $lockSrv, array $pathsByType)
Get a connection to a lock server and acquire locks.
array $lockServers
Map server names to hostname/IP and port numbers.
releaseAllLocks()
Release all locks that this session is holding.
__destruct()
Make sure remaining locks get cleared.
array $lockTypeMap
Mapping of lock types to the type actually used.
isServerUp( $lockSrv)
Check if a lock server is up.
Helper class to manage Redis connections.