Add DROP INDEX support to DatabaseSqlite::replaceVars method
[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 protected function getLocksOnServer( $lockSrv, array $paths, $type ) {
82 $status = Status::newGood();
83
84 $server = $this->lockServers[$lockSrv];
85 $conn = $this->redisPool->getConnection( $server );
86 if ( !$conn ) {
87 foreach ( $paths as $path ) {
88 $status->fatal( 'lockmanager-fail-acquirelock', $path );
89 }
90 return $status;
91 }
92
93 $keys = array_map( array( $this, 'recordKeyForPath' ), $paths ); // lock records
94
95 try {
96 static $script =
97 <<<LUA
98 if ARGV[1] ~= 'EX' and ARGV[1] ~= 'SH' then
99 return redis.error_reply('Unrecognized lock type given (must be EX or SH)')
100 end
101 local failed = {}
102 -- Check that all the locks can be acquired
103 for i,resourceKey in ipairs(KEYS) do
104 local keyIsFree = true
105 local currentLocks = redis.call('hKeys',resourceKey)
106 for i,lockKey in ipairs(currentLocks) do
107 local _, _, type, session = string.find(lockKey,"(%w+):(%w+)")
108 -- Check any locks that are not owned by this session
109 if session ~= ARGV[2] then
110 local lockTimestamp = redis.call('hGet',resourceKey,lockKey)
111 if 1*lockTimestamp < ( ARGV[4] - ARGV[3] ) then
112 -- Lock is stale, so just prune it out
113 redis.call('hDel',resourceKey,lockKey)
114 elseif ARGV[1] == 'EX' or type == 'EX' then
115 keyIsFree = false
116 break
117 end
118 end
119 end
120 if not keyIsFree then
121 failed[#failed+1] = resourceKey
122 end
123 end
124 -- If all locks could be acquired, then do so
125 if #failed == 0 then
126 for i,resourceKey in ipairs(KEYS) do
127 redis.call('hSet',resourceKey,ARGV[1] .. ':' .. ARGV[2],ARGV[4])
128 -- In addition to invalidation logic, be sure to garbage collect
129 redis.call('expire',resourceKey,ARGV[3])
130 end
131 end
132 return failed
133 LUA;
134 $res = $conn->luaEval( $script,
135 array_merge(
136 $keys, // KEYS[0], KEYS[1],...KEYS[N]
137 array(
138 $type === self::LOCK_SH ? 'SH' : 'EX', // ARGV[1]
139 $this->session, // ARGV[2]
140 $this->lockTTL, // ARGV[3]
141 time() // ARGV[4]
142 )
143 ),
144 count( $keys ) # number of first argument(s) that are keys
145 );
146 } catch ( RedisException $e ) {
147 $res = false;
148 $this->redisPool->handleException( $server, $conn, $e );
149 }
150
151 if ( $res === false ) {
152 foreach ( $paths as $path ) {
153 $status->fatal( 'lockmanager-fail-acquirelock', $path );
154 }
155 } else {
156 $pathsByKey = array_combine( $keys, $paths );
157 foreach ( $res as $key ) {
158 $status->fatal( 'lockmanager-fail-acquirelock', $pathsByKey[$key] );
159 }
160 }
161
162 return $status;
163 }
164
165 protected function freeLocksOnServer( $lockSrv, array $paths, $type ) {
166 $status = Status::newGood();
167
168 $server = $this->lockServers[$lockSrv];
169 $conn = $this->redisPool->getConnection( $server );
170 if ( !$conn ) {
171 foreach ( $paths as $path ) {
172 $status->fatal( 'lockmanager-fail-releaselock', $path );
173 }
174 return $status;
175 }
176
177 $keys = array_map( array( $this, 'recordKeyForPath' ), $paths ); // lock records
178
179 try {
180 static $script =
181 <<<LUA
182 if ARGV[1] ~= 'EX' and ARGV[1] ~= 'SH' then
183 return redis.error_reply('Unrecognized lock type given (must be EX or SH)')
184 end
185 local failed = {}
186 for i,resourceKey in ipairs(KEYS) do
187 local released = redis.call('hDel',resourceKey,ARGV[1] .. ':' .. ARGV[2])
188 if released > 0 then
189 -- Remove the whole structure if it is now empty
190 if redis.call('hLen',resourceKey) == 0 then
191 redis.call('del',resourceKey)
192 end
193 else
194 failed[#failed+1] = resourceKey
195 end
196 end
197 return failed
198 LUA;
199 $res = $conn->luaEval( $script,
200 array_merge(
201 $keys, // KEYS[0], KEYS[1],...KEYS[N]
202 array(
203 $type === self::LOCK_SH ? 'SH' : 'EX', // ARGV[1]
204 $this->session // ARGV[2]
205 )
206 ),
207 count( $keys ) # number of first argument(s) that are keys
208 );
209 } catch ( RedisException $e ) {
210 $res = false;
211 $this->redisPool->handleException( $server, $conn, $e );
212 }
213
214 if ( $res === false ) {
215 foreach ( $paths as $path ) {
216 $status->fatal( 'lockmanager-fail-releaselock', $path );
217 }
218 } else {
219 $pathsByKey = array_combine( $keys, $paths );
220 foreach ( $res as $key ) {
221 $status->fatal( 'lockmanager-fail-releaselock', $pathsByKey[$key] );
222 }
223 }
224
225 return $status;
226 }
227
228 protected function releaseAllLocks() {
229 return Status::newGood(); // not supported
230 }
231
232 protected function isServerUp( $lockSrv ) {
233 return (bool)$this->redisPool->getConnection( $this->lockServers[$lockSrv] );
234 }
235
236 /**
237 * @param $path string
238 * @return string
239 */
240 protected function recordKeyForPath( $path ) {
241 return implode( ':', array( __CLASS__, 'locks', $this->sha1Base36Absolute( $path ) ) );
242 }
243
244 /**
245 * Make sure remaining locks get cleared for sanity
246 */
247 function __destruct() {
248 while ( count( $this->locksHeld ) ) {
249 foreach ( $this->locksHeld as $path => $locks ) {
250 $this->doUnlock( array( $path ), self::LOCK_EX );
251 $this->doUnlock( array( $path ), self::LOCK_SH );
252 }
253 }
254 }
255 }