Merge "Use 'pagetitle' in content language"
[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
51 /** @var array Map server names to hostname/IP and port numbers */
52 protected $lockServers = array();
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 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 $lType => $lPaths ) {
94 $status->merge( $this->doFreeLocksOnServer( $lockSrv, $lPaths, $lType ) );
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
124 return $status;
125 }
126
127 $keys = array_map( array( $this, 'recordKeyForPath' ), $paths ); // lock records
128
129 try {
130 static $script =
131 <<<LUA
132 if ARGV[1] ~= 'EX' and ARGV[1] ~= 'SH' then
133 return redis.error_reply('Unrecognized lock type given (must be EX or SH)')
134 end
135 local failed = {}
136 -- Check that all the locks can be acquired
137 for i,resourceKey in ipairs(KEYS) do
138 local keyIsFree = true
139 local currentLocks = redis.call('hKeys',resourceKey)
140 for i,lockKey in ipairs(currentLocks) do
141 local _, _, type, session = string.find(lockKey,"(%w+):(%w+)")
142 -- Check any locks that are not owned by this session
143 if session ~= ARGV[2] then
144 local lockTimestamp = redis.call('hGet',resourceKey,lockKey)
145 if 1*lockTimestamp < ( ARGV[4] - ARGV[3] ) then
146 -- Lock is stale, so just prune it out
147 redis.call('hDel',resourceKey,lockKey)
148 elseif ARGV[1] == 'EX' or type == 'EX' then
149 keyIsFree = false
150 break
151 end
152 end
153 end
154 if not keyIsFree then
155 failed[#failed+1] = resourceKey
156 end
157 end
158 -- If all locks could be acquired, then do so
159 if #failed == 0 then
160 for i,resourceKey in ipairs(KEYS) do
161 redis.call('hSet',resourceKey,ARGV[1] .. ':' .. ARGV[2],ARGV[4])
162 -- In addition to invalidation logic, be sure to garbage collect
163 redis.call('expire',resourceKey,ARGV[3])
164 end
165 end
166 return failed
167 LUA;
168 $res = $conn->luaEval( $script,
169 array_merge(
170 $keys, // KEYS[0], KEYS[1],...KEYS[N]
171 array(
172 $type === self::LOCK_SH ? 'SH' : 'EX', // ARGV[1]
173 $this->session, // ARGV[2]
174 $this->lockTTL, // ARGV[3]
175 time() // ARGV[4]
176 )
177 ),
178 count( $keys ) # number of first argument(s) that are keys
179 );
180 } catch ( RedisException $e ) {
181 $res = false;
182 $this->redisPool->handleException( $server, $conn, $e );
183 }
184
185 if ( $res === false ) {
186 foreach ( $paths as $path ) {
187 $status->fatal( 'lockmanager-fail-acquirelock', $path );
188 }
189 } else {
190 $pathsByKey = array_combine( $keys, $paths );
191 foreach ( $res as $key ) {
192 $status->fatal( 'lockmanager-fail-acquirelock', $pathsByKey[$key] );
193 }
194 }
195
196 return $status;
197 }
198
199 protected function doFreeLocksOnServer( $lockSrv, array $paths, $type ) {
200 $status = Status::newGood();
201
202 $server = $this->lockServers[$lockSrv];
203 $conn = $this->redisPool->getConnection( $server );
204 if ( !$conn ) {
205 foreach ( $paths as $path ) {
206 $status->fatal( 'lockmanager-fail-releaselock', $path );
207 }
208
209 return $status;
210 }
211
212 $keys = array_map( array( $this, 'recordKeyForPath' ), $paths ); // lock records
213
214 try {
215 static $script =
216 <<<LUA
217 if ARGV[1] ~= 'EX' and ARGV[1] ~= 'SH' then
218 return redis.error_reply('Unrecognized lock type given (must be EX or SH)')
219 end
220 local failed = {}
221 for i,resourceKey in ipairs(KEYS) do
222 local released = redis.call('hDel',resourceKey,ARGV[1] .. ':' .. ARGV[2])
223 if released > 0 then
224 -- Remove the whole structure if it is now empty
225 if redis.call('hLen',resourceKey) == 0 then
226 redis.call('del',resourceKey)
227 end
228 else
229 failed[#failed+1] = resourceKey
230 end
231 end
232 return failed
233 LUA;
234 $res = $conn->luaEval( $script,
235 array_merge(
236 $keys, // KEYS[0], KEYS[1],...KEYS[N]
237 array(
238 $type === self::LOCK_SH ? 'SH' : 'EX', // ARGV[1]
239 $this->session // ARGV[2]
240 )
241 ),
242 count( $keys ) # number of first argument(s) that are keys
243 );
244 } catch ( RedisException $e ) {
245 $res = false;
246 $this->redisPool->handleException( $server, $conn, $e );
247 }
248
249 if ( $res === false ) {
250 foreach ( $paths as $path ) {
251 $status->fatal( 'lockmanager-fail-releaselock', $path );
252 }
253 } else {
254 $pathsByKey = array_combine( $keys, $paths );
255 foreach ( $res as $key ) {
256 $status->fatal( 'lockmanager-fail-releaselock', $pathsByKey[$key] );
257 }
258 }
259
260 return $status;
261 }
262
263 protected function releaseAllLocks() {
264 return Status::newGood(); // not supported
265 }
266
267 protected function isServerUp( $lockSrv ) {
268 return (bool)$this->redisPool->getConnection( $this->lockServers[$lockSrv] );
269 }
270
271 /**
272 * @param string $path
273 * @return string
274 */
275 protected function recordKeyForPath( $path ) {
276 return implode( ':', array( __CLASS__, 'locks', $this->sha1Base36Absolute( $path ) ) );
277 }
278
279 /**
280 * Make sure remaining locks get cleared for sanity
281 */
282 function __destruct() {
283 while ( count( $this->locksHeld ) ) {
284 foreach ( $this->locksHeld as $path => $locks ) {
285 $this->doUnlock( array( $path ), self::LOCK_EX );
286 $this->doUnlock( array( $path ), self::LOCK_SH );
287 }
288 }
289 }
290 }