Merge "Cache page content language in Title object"
[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 = array(
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 /** @var Array Map server names to hostname/IP and port numbers */
51 protected $lockServers = array();
52
53 protected $session = ''; // string; random UUID
54
55 /**
56 * Construct a new instance from configuration.
57 *
58 * $config paramaters include:
59 * - lockServers : Associative array of server names to "<IP>:<port>" strings.
60 * - srvsByBucket : Array of 1-16 consecutive integer keys, starting from 0,
61 * each having an odd-numbered list of server names (peers) as values.
62 * - redisConfig : Configuration for RedisConnectionPool::__construct().
63 *
64 * @param Array $config
65 * @throws MWException
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 // @TODO: change this code to work in one batch
82 protected function getLocksOnServer( $lockSrv, array $pathsByType ) {
83 $status = Status::newGood();
84
85 $lockedPaths = array();
86 foreach ( $pathsByType as $type => $paths ) {
87 $status->merge( $this->doGetLocksOnServer( $lockSrv, $paths, $type ) );
88 if ( $status->isOK() ) {
89 $lockedPaths[$type] = isset( $lockedPaths[$type] )
90 ? array_merge( $lockedPaths[$type], $paths )
91 : $paths;
92 } else {
93 foreach ( $lockedPaths as $type => $paths ) {
94 $status->merge( $this->doFreeLocksOnServer( $lockSrv, $paths, $type ) );
95 }
96 break;
97 }
98 }
99
100 return $status;
101 }
102
103 // @TODO: change this code to work in one batch
104 protected function freeLocksOnServer( $lockSrv, array $pathsByType ) {
105 $status = Status::newGood();
106
107 foreach ( $pathsByType as $type => $paths ) {
108 $status->merge( $this->doFreeLocksOnServer( $lockSrv, $paths, $type ) );
109 }
110
111 return $status;
112 }
113
114 protected function doGetLocksOnServer( $lockSrv, array $paths, $type ) {
115 $status = Status::newGood();
116
117 $server = $this->lockServers[$lockSrv];
118 $conn = $this->redisPool->getConnection( $server );
119 if ( !$conn ) {
120 foreach ( $paths as $path ) {
121 $status->fatal( 'lockmanager-fail-acquirelock', $path );
122 }
123 return $status;
124 }
125
126 $keys = array_map( array( $this, 'recordKeyForPath' ), $paths ); // lock records
127
128 try {
129 static $script =
130 <<<LUA
131 if ARGV[1] ~= 'EX' and ARGV[1] ~= 'SH' then
132 return redis.error_reply('Unrecognized lock type given (must be EX or SH)')
133 end
134 local failed = {}
135 -- Check that all the locks can be acquired
136 for i,resourceKey in ipairs(KEYS) do
137 local keyIsFree = true
138 local currentLocks = redis.call('hKeys',resourceKey)
139 for i,lockKey in ipairs(currentLocks) do
140 local _, _, type, session = string.find(lockKey,"(%w+):(%w+)")
141 -- Check any locks that are not owned by this session
142 if session ~= ARGV[2] then
143 local lockTimestamp = redis.call('hGet',resourceKey,lockKey)
144 if 1*lockTimestamp < ( ARGV[4] - ARGV[3] ) then
145 -- Lock is stale, so just prune it out
146 redis.call('hDel',resourceKey,lockKey)
147 elseif ARGV[1] == 'EX' or type == 'EX' then
148 keyIsFree = false
149 break
150 end
151 end
152 end
153 if not keyIsFree then
154 failed[#failed+1] = resourceKey
155 end
156 end
157 -- If all locks could be acquired, then do so
158 if #failed == 0 then
159 for i,resourceKey in ipairs(KEYS) do
160 redis.call('hSet',resourceKey,ARGV[1] .. ':' .. ARGV[2],ARGV[4])
161 -- In addition to invalidation logic, be sure to garbage collect
162 redis.call('expire',resourceKey,ARGV[3])
163 end
164 end
165 return failed
166 LUA;
167 $res = $conn->luaEval( $script,
168 array_merge(
169 $keys, // KEYS[0], KEYS[1],...KEYS[N]
170 array(
171 $type === self::LOCK_SH ? 'SH' : 'EX', // ARGV[1]
172 $this->session, // ARGV[2]
173 $this->lockTTL, // ARGV[3]
174 time() // ARGV[4]
175 )
176 ),
177 count( $keys ) # number of first argument(s) that are keys
178 );
179 } catch ( RedisException $e ) {
180 $res = false;
181 $this->redisPool->handleException( $server, $conn, $e );
182 }
183
184 if ( $res === false ) {
185 foreach ( $paths as $path ) {
186 $status->fatal( 'lockmanager-fail-acquirelock', $path );
187 }
188 } else {
189 $pathsByKey = array_combine( $keys, $paths );
190 foreach ( $res as $key ) {
191 $status->fatal( 'lockmanager-fail-acquirelock', $pathsByKey[$key] );
192 }
193 }
194
195 return $status;
196 }
197
198 protected function doFreeLocksOnServer( $lockSrv, array $paths, $type ) {
199 $status = Status::newGood();
200
201 $server = $this->lockServers[$lockSrv];
202 $conn = $this->redisPool->getConnection( $server );
203 if ( !$conn ) {
204 foreach ( $paths as $path ) {
205 $status->fatal( 'lockmanager-fail-releaselock', $path );
206 }
207 return $status;
208 }
209
210 $keys = array_map( array( $this, 'recordKeyForPath' ), $paths ); // lock records
211
212 try {
213 static $script =
214 <<<LUA
215 if ARGV[1] ~= 'EX' and ARGV[1] ~= 'SH' then
216 return redis.error_reply('Unrecognized lock type given (must be EX or SH)')
217 end
218 local failed = {}
219 for i,resourceKey in ipairs(KEYS) do
220 local released = redis.call('hDel',resourceKey,ARGV[1] .. ':' .. ARGV[2])
221 if released > 0 then
222 -- Remove the whole structure if it is now empty
223 if redis.call('hLen',resourceKey) == 0 then
224 redis.call('del',resourceKey)
225 end
226 else
227 failed[#failed+1] = resourceKey
228 end
229 end
230 return failed
231 LUA;
232 $res = $conn->luaEval( $script,
233 array_merge(
234 $keys, // KEYS[0], KEYS[1],...KEYS[N]
235 array(
236 $type === self::LOCK_SH ? 'SH' : 'EX', // ARGV[1]
237 $this->session // ARGV[2]
238 )
239 ),
240 count( $keys ) # number of first argument(s) that are keys
241 );
242 } catch ( RedisException $e ) {
243 $res = false;
244 $this->redisPool->handleException( $server, $conn, $e );
245 }
246
247 if ( $res === false ) {
248 foreach ( $paths as $path ) {
249 $status->fatal( 'lockmanager-fail-releaselock', $path );
250 }
251 } else {
252 $pathsByKey = array_combine( $keys, $paths );
253 foreach ( $res as $key ) {
254 $status->fatal( 'lockmanager-fail-releaselock', $pathsByKey[$key] );
255 }
256 }
257
258 return $status;
259 }
260
261 protected function releaseAllLocks() {
262 return Status::newGood(); // not supported
263 }
264
265 protected function isServerUp( $lockSrv ) {
266 return (bool)$this->redisPool->getConnection( $this->lockServers[$lockSrv] );
267 }
268
269 /**
270 * @param $path string
271 * @return string
272 */
273 protected function recordKeyForPath( $path ) {
274 return implode( ':', array( __CLASS__, 'locks', $this->sha1Base36Absolute( $path ) ) );
275 }
276
277 /**
278 * Make sure remaining locks get cleared for sanity
279 */
280 function __destruct() {
281 while ( count( $this->locksHeld ) ) {
282 foreach ( $this->locksHeld as $path => $locks ) {
283 $this->doUnlock( array( $path ), self::LOCK_EX );
284 $this->doUnlock( array( $path ), self::LOCK_SH );
285 }
286 }
287 }
288 }