a9f5ca364c1deafc6c05148b8d42cedc5307bc0f
[lhc/web/wiklou.git] / includes / libs / lockmanager / RedisLockManager.php
1 <?php
2 /**
3 * Version of LockManager based on using redis servers.
4 *
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.
9 *
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.
14 *
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
19 *
20 * @file
21 * @ingroup LockManager
22 */
23
24 /**
25 * Manage locks using redis servers.
26 *
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.
30 *
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.
34 *
35 * This class requires Redis 2.6 as it makes use Lua scripts for fast atomic operations.
36 *
37 * @ingroup LockManager
38 * @since 1.22
39 */
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
46 ];
47
48 /** @var RedisConnectionPool */
49 protected $redisPool;
50
51 /** @var array Map server names to hostname/IP and port numbers */
52 protected $lockServers = [];
53
54 /**
55 * Construct a new instance from configuration.
56 *
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().
62 * @throws Exception
63 */
64 public function __construct( array $config ) {
65 parent::__construct( $config );
66
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
71
72 $config['redisConfig']['serializer'] = 'none';
73 $this->redisPool = RedisConnectionPool::singleton( $config['redisConfig'] );
74 }
75
76 protected function getLocksOnServer( $lockSrv, array $pathsByType ) {
77 $status = StatusValue::newGood();
78
79 $pathList = call_user_func_array( 'array_merge', array_values( $pathsByType ) );
80
81 $server = $this->lockServers[$lockSrv];
82 $conn = $this->redisPool->getConnection( $server, $this->logger );
83 if ( !$conn ) {
84 foreach ( $pathList as $path ) {
85 $status->fatal( 'lockmanager-fail-acquirelock', $path );
86 }
87
88 return $status;
89 }
90
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;
96 }
97 }
98
99 try {
100 static $script =
101 <<<LUA
102 local failed = {}
103 -- Load input params (e.g. session, ttl, time of request)
104 local rSession, rTTL, rTime = unpack(ARGV)
105 -- Check that all the locks can be acquired
106 for i,requestKey in ipairs(KEYS) do
107 local _, _, rType, resourceKey = string.find(requestKey,"(%w+):(%w+)$")
108 local keyIsFree = true
109 local currentLocks = redis.call('hKeys',resourceKey)
110 for i,lockKey in ipairs(currentLocks) do
111 -- Get the type and session of this lock
112 local _, _, type, session = string.find(lockKey,"(%w+):(%w+)")
113 -- Check any locks that are not owned by this session
114 if session ~= rSession then
115 local lockExpiry = redis.call('hGet',resourceKey,lockKey)
116 if 1*lockExpiry < 1*rTime then
117 -- Lock is stale, so just prune it out
118 redis.call('hDel',resourceKey,lockKey)
119 elseif rType == 'EX' or type == 'EX' then
120 keyIsFree = false
121 break
122 end
123 end
124 end
125 if not keyIsFree then
126 failed[#failed+1] = requestKey
127 end
128 end
129 -- If all locks could be acquired, then do so
130 if #failed == 0 then
131 for i,requestKey in ipairs(KEYS) do
132 local _, _, rType, resourceKey = string.find(requestKey,"(%w+):(%w+)$")
133 redis.call('hSet',resourceKey,rType .. ':' .. rSession,rTime + rTTL)
134 -- In addition to invalidation logic, be sure to garbage collect
135 redis.call('expire',resourceKey,rTTL)
136 end
137 end
138 return failed
139 LUA;
140 $res = $conn->luaEval( $script,
141 array_merge(
142 array_keys( $pathsByKey ), // KEYS[0], KEYS[1],...,KEYS[N]
143 [
144 $this->session, // ARGV[1]
145 $this->lockTTL, // ARGV[2]
146 time() // ARGV[3]
147 ]
148 ),
149 count( $pathsByKey ) # number of first argument(s) that are keys
150 );
151 } catch ( RedisException $e ) {
152 $res = false;
153 $this->redisPool->handleError( $conn, $e );
154 }
155
156 if ( $res === false ) {
157 foreach ( $pathList as $path ) {
158 $status->fatal( 'lockmanager-fail-acquirelock', $path );
159 }
160 } else {
161 foreach ( $res as $key ) {
162 $status->fatal( 'lockmanager-fail-acquirelock', $pathsByKey[$key] );
163 }
164 }
165
166 return $status;
167 }
168
169 protected function freeLocksOnServer( $lockSrv, array $pathsByType ) {
170 $status = StatusValue::newGood();
171
172 $pathList = call_user_func_array( 'array_merge', array_values( $pathsByType ) );
173
174 $server = $this->lockServers[$lockSrv];
175 $conn = $this->redisPool->getConnection( $server, $this->logger );
176 if ( !$conn ) {
177 foreach ( $pathList as $path ) {
178 $status->fatal( 'lockmanager-fail-releaselock', $path );
179 }
180
181 return $status;
182 }
183
184 $pathsByKey = []; // (type:hash => path) map
185 foreach ( $pathsByType as $type => $paths ) {
186 $typeString = ( $type == LockManager::LOCK_SH ) ? 'SH' : 'EX';
187 foreach ( $paths as $path ) {
188 $pathsByKey[$this->recordKeyForPath( $path, $typeString )] = $path;
189 }
190 }
191
192 try {
193 static $script =
194 <<<LUA
195 local failed = {}
196 -- Load input params (e.g. session)
197 local rSession = unpack(ARGV)
198 for i,requestKey in ipairs(KEYS) do
199 local _, _, rType, resourceKey = string.find(requestKey,"(%w+):(%w+)$")
200 local released = redis.call('hDel',resourceKey,rType .. ':' .. rSession)
201 if released > 0 then
202 -- Remove the whole structure if it is now empty
203 if redis.call('hLen',resourceKey) == 0 then
204 redis.call('del',resourceKey)
205 end
206 else
207 failed[#failed+1] = requestKey
208 end
209 end
210 return failed
211 LUA;
212 $res = $conn->luaEval( $script,
213 array_merge(
214 array_keys( $pathsByKey ), // KEYS[0], KEYS[1],...,KEYS[N]
215 [
216 $this->session, // ARGV[1]
217 ]
218 ),
219 count( $pathsByKey ) # number of first argument(s) that are keys
220 );
221 } catch ( RedisException $e ) {
222 $res = false;
223 $this->redisPool->handleError( $conn, $e );
224 }
225
226 if ( $res === false ) {
227 foreach ( $pathList as $path ) {
228 $status->fatal( 'lockmanager-fail-releaselock', $path );
229 }
230 } else {
231 foreach ( $res as $key ) {
232 $status->fatal( 'lockmanager-fail-releaselock', $pathsByKey[$key] );
233 }
234 }
235
236 return $status;
237 }
238
239 protected function releaseAllLocks() {
240 return StatusValue::newGood(); // not supported
241 }
242
243 protected function isServerUp( $lockSrv ) {
244 $conn = $this->redisPool->getConnection( $this->lockServers[$lockSrv], $this->logger );
245
246 return (bool)$conn;
247 }
248
249 /**
250 * @param string $path
251 * @param string $type One of (EX,SH)
252 * @return string
253 */
254 protected function recordKeyForPath( $path, $type ) {
255 return implode( ':',
256 [ __CLASS__, 'locks', "$type:" . $this->sha1Base36Absolute( $path ) ] );
257 }
258
259 /**
260 * Make sure remaining locks get cleared for sanity
261 */
262 function __destruct() {
263 while ( count( $this->locksHeld ) ) {
264 $pathsByType = [];
265 foreach ( $this->locksHeld as $path => $locks ) {
266 foreach ( $locks as $type => $count ) {
267 $pathsByType[$type][] = $path;
268 }
269 }
270 $this->unlockByType( $pathsByType );
271 }
272 }
273 }