Don't fallback from uk to ru
[lhc/web/wiklou.git] / includes / filebackend / 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 /** @var string Random UUID */
55 protected $session = '';
56
57 /**
58 * Construct a new instance from configuration.
59 *
60 * @param array $config Parameters include:
61 * - lockServers : Associative array of server names to "<IP>:<port>" strings.
62 * - srvsByBucket : Array of 1-16 consecutive integer keys, starting from 0,
63 * each having an odd-numbered list of server names (peers) as values.
64 * - redisConfig : Configuration for RedisConnectionPool::__construct().
65 * @throws Exception
66 */
67 public function __construct( array $config ) {
68 parent::__construct( $config );
69
70 $this->lockServers = $config['lockServers'];
71 // Sanitize srvsByBucket config to prevent PHP errors
72 $this->srvsByBucket = array_filter( $config['srvsByBucket'], 'is_array' );
73 $this->srvsByBucket = array_values( $this->srvsByBucket ); // consecutive
74
75 $config['redisConfig']['serializer'] = 'none';
76 $this->redisPool = RedisConnectionPool::singleton( $config['redisConfig'] );
77
78 $this->session = wfRandomString( 32 );
79 }
80
81 protected function getLocksOnServer( $lockSrv, array $pathsByType ) {
82 $status = Status::newGood();
83
84 $pathList = call_user_func_array( 'array_merge', array_values( $pathsByType ) );
85
86 $server = $this->lockServers[$lockSrv];
87 $conn = $this->redisPool->getConnection( $server );
88 if ( !$conn ) {
89 foreach ( $pathList as $path ) {
90 $status->fatal( 'lockmanager-fail-acquirelock', $path );
91 }
92
93 return $status;
94 }
95
96 $pathsByKey = []; // (type:hash => path) map
97 foreach ( $pathsByType as $type => $paths ) {
98 $typeString = ( $type == LockManager::LOCK_SH ) ? 'SH' : 'EX';
99 foreach ( $paths as $path ) {
100 $pathsByKey[$this->recordKeyForPath( $path, $typeString )] = $path;
101 }
102 }
103
104 try {
105 static $script =
106 <<<LUA
107 local failed = {}
108 -- Load input params (e.g. session, ttl, time of request)
109 local rSession, rTTL, rTime = unpack(ARGV)
110 -- Check that all the locks can be acquired
111 for i,requestKey in ipairs(KEYS) do
112 local _, _, rType, resourceKey = string.find(requestKey,"(%w+):(%w+)$")
113 local keyIsFree = true
114 local currentLocks = redis.call('hKeys',resourceKey)
115 for i,lockKey in ipairs(currentLocks) do
116 -- Get the type and session of this lock
117 local _, _, type, session = string.find(lockKey,"(%w+):(%w+)")
118 -- Check any locks that are not owned by this session
119 if session ~= rSession then
120 local lockExpiry = redis.call('hGet',resourceKey,lockKey)
121 if 1*lockExpiry < 1*rTime then
122 -- Lock is stale, so just prune it out
123 redis.call('hDel',resourceKey,lockKey)
124 elseif rType == 'EX' or type == 'EX' then
125 keyIsFree = false
126 break
127 end
128 end
129 end
130 if not keyIsFree then
131 failed[#failed+1] = requestKey
132 end
133 end
134 -- If all locks could be acquired, then do so
135 if #failed == 0 then
136 for i,requestKey in ipairs(KEYS) do
137 local _, _, rType, resourceKey = string.find(requestKey,"(%w+):(%w+)$")
138 redis.call('hSet',resourceKey,rType .. ':' .. rSession,rTime + rTTL)
139 -- In addition to invalidation logic, be sure to garbage collect
140 redis.call('expire',resourceKey,rTTL)
141 end
142 end
143 return failed
144 LUA;
145 $res = $conn->luaEval( $script,
146 array_merge(
147 array_keys( $pathsByKey ), // KEYS[0], KEYS[1],...,KEYS[N]
148 [
149 $this->session, // ARGV[1]
150 $this->lockTTL, // ARGV[2]
151 time() // ARGV[3]
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 } else {
166 foreach ( $res as $key ) {
167 $status->fatal( 'lockmanager-fail-acquirelock', $pathsByKey[$key] );
168 }
169 }
170
171 return $status;
172 }
173
174 protected function freeLocksOnServer( $lockSrv, array $pathsByType ) {
175 $status = Status::newGood();
176
177 $pathList = call_user_func_array( 'array_merge', array_values( $pathsByType ) );
178
179 $server = $this->lockServers[$lockSrv];
180 $conn = $this->redisPool->getConnection( $server );
181 if ( !$conn ) {
182 foreach ( $pathList as $path ) {
183 $status->fatal( 'lockmanager-fail-releaselock', $path );
184 }
185
186 return $status;
187 }
188
189 $pathsByKey = []; // (type:hash => path) map
190 foreach ( $pathsByType as $type => $paths ) {
191 $typeString = ( $type == LockManager::LOCK_SH ) ? 'SH' : 'EX';
192 foreach ( $paths as $path ) {
193 $pathsByKey[$this->recordKeyForPath( $path, $typeString )] = $path;
194 }
195 }
196
197 try {
198 static $script =
199 <<<LUA
200 local failed = {}
201 -- Load input params (e.g. session)
202 local rSession = unpack(ARGV)
203 for i,requestKey in ipairs(KEYS) do
204 local _, _, rType, resourceKey = string.find(requestKey,"(%w+):(%w+)$")
205 local released = redis.call('hDel',resourceKey,rType .. ':' .. rSession)
206 if released > 0 then
207 -- Remove the whole structure if it is now empty
208 if redis.call('hLen',resourceKey) == 0 then
209 redis.call('del',resourceKey)
210 end
211 else
212 failed[#failed+1] = requestKey
213 end
214 end
215 return failed
216 LUA;
217 $res = $conn->luaEval( $script,
218 array_merge(
219 array_keys( $pathsByKey ), // KEYS[0], KEYS[1],...,KEYS[N]
220 [
221 $this->session, // ARGV[1]
222 ]
223 ),
224 count( $pathsByKey ) # number of first argument(s) that are keys
225 );
226 } catch ( RedisException $e ) {
227 $res = false;
228 $this->redisPool->handleError( $conn, $e );
229 }
230
231 if ( $res === false ) {
232 foreach ( $pathList as $path ) {
233 $status->fatal( 'lockmanager-fail-releaselock', $path );
234 }
235 } else {
236 foreach ( $res as $key ) {
237 $status->fatal( 'lockmanager-fail-releaselock', $pathsByKey[$key] );
238 }
239 }
240
241 return $status;
242 }
243
244 protected function releaseAllLocks() {
245 return Status::newGood(); // not supported
246 }
247
248 protected function isServerUp( $lockSrv ) {
249 return (bool)$this->redisPool->getConnection( $this->lockServers[$lockSrv] );
250 }
251
252 /**
253 * @param string $path
254 * @param string $type One of (EX,SH)
255 * @return string
256 */
257 protected function recordKeyForPath( $path, $type ) {
258 return implode( ':',
259 [ __CLASS__, 'locks', "$type:" . $this->sha1Base36Absolute( $path ) ] );
260 }
261
262 /**
263 * Make sure remaining locks get cleared for sanity
264 */
265 function __destruct() {
266 while ( count( $this->locksHeld ) ) {
267 $pathsByType = [];
268 foreach ( $this->locksHeld as $path => $locks ) {
269 foreach ( $locks as $type => $count ) {
270 $pathsByType[$type][] = $path;
271 }
272 }
273 $this->unlockByType( $pathsByType );
274 }
275 }
276 }