Merge "Use getHtmlCode() instead of getCode() to set the lang attribute"
[lhc/web/wiklou.git] / includes / poolcounter / PoolCounterRedis.php
1 <?php
2 /**
3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
17 *
18 * @file
19 * @author Aaron Schulz
20 */
21
22 /**
23 * Version of PoolCounter that uses Redis
24 *
25 * There are four main redis keys used to track each pool counter key:
26 * - poolcounter:l-slots-* : A list of available slot IDs for a pool.
27 * - poolcounter:z-renewtime-* : A sorted set of (slot ID, UNIX timestamp as score)
28 * used for tracking the next time a slot should be
29 * released. This is -1 when a slot is created, and is
30 * set when released (expired), locked, and unlocked.
31 * - poolcounter:z-wait-* : A sorted set of (slot ID, UNIX timestamp as score)
32 * used for tracking waiting processes (and wait time).
33 * - poolcounter:l-wakeup-* : A list pushed to for the sake of waking up processes
34 * when a any process in the pool finishes (lasts for 1ms).
35 * For a given pool key, all the redis keys start off non-existing and are deleted if not
36 * used for a while to prevent garbage from building up on the server. They are atomically
37 * re-initialized as needed. The "z-renewtime" key is used for detecting sessions which got
38 * slots but then disappeared. Stale entries from there have their timestamp updated and the
39 * corresponding slots freed up. The "z-wait" key is used for detecting processes registered
40 * as waiting but that disappeared. Stale entries from there are deleted and the corresponding
41 * slots are freed up. The worker count is included in all the redis key names as it does not
42 * vary within each $wgPoolCounterConf type and doing so handles configuration changes.
43 *
44 * This class requires Redis 2.6 as it makes use Lua scripts for fast atomic operations.
45 * Also this should be on a server plenty of RAM for the working set to avoid evictions.
46 * Evictions could temporarily allow wait queues to double in size or temporarily cause
47 * pools to appear as full when they are not. Using volatile-ttl and bumping memory-samples
48 * in redis.conf can be helpful otherwise.
49 *
50 * @ingroup Redis
51 * @since 1.23
52 */
53 class PoolCounterRedis extends PoolCounter {
54 /** @var HashRing */
55 protected $ring;
56 /** @var RedisConnectionPool */
57 protected $pool;
58 /** @var array (server label => host) map */
59 protected $serversByLabel;
60 /** @var string SHA-1 of the key */
61 protected $keySha1;
62 /** @var int TTL for locks to expire (work should finish in this time) */
63 protected $lockTTL;
64
65 /** @var RedisConnRef */
66 protected $conn;
67 /** @var string Pool slot value */
68 protected $slot;
69 /** @var int AWAKE_* constant */
70 protected $onRelease;
71 /** @var string Unique string to identify this process */
72 protected $session;
73 /** @var int UNIX timestamp */
74 protected $slotTime;
75
76 const AWAKE_ONE = 1; // wake-up if when a slot can be taken from an existing process
77 const AWAKE_ALL = 2; // wake-up if an existing process finishes and wake up such others
78
79 /** @var array List of active PoolCounterRedis objects in this script */
80 protected static $active = null;
81
82 function __construct( $conf, $type, $key ) {
83 parent::__construct( $conf, $type, $key );
84
85 $this->serversByLabel = $conf['servers'];
86 $this->ring = new HashRing( array_fill_keys( array_keys( $conf['servers'] ), 100 ) );
87
88 $conf['redisConfig']['serializer'] = 'none'; // for use with Lua
89 $this->pool = RedisConnectionPool::singleton( $conf['redisConfig'] );
90
91 $this->keySha1 = sha1( $this->key );
92 $met = ini_get( 'max_execution_time' ); // usually 0 in CLI mode
93 $this->lockTTL = $met ? 2 * $met : 3600;
94
95 if ( self::$active === null ) {
96 self::$active = array();
97 register_shutdown_function( array( __CLASS__, 'releaseAll' ) );
98 }
99 }
100
101 /**
102 * @return Status Uses RediConnRef as value on success
103 */
104 protected function getConnection() {
105 if ( !isset( $this->conn ) ) {
106 $conn = false;
107 $servers = $this->ring->getLocations( $this->key, 3 );
108 ArrayUtils::consistentHashSort( $servers, $this->key );
109 foreach ( $servers as $server ) {
110 $conn = $this->pool->getConnection( $this->serversByLabel[$server] );
111 if ( $conn ) {
112 break;
113 }
114 }
115 if ( !$conn ) {
116 return Status::newFatal( 'pool-servererror', implode( ', ', $servers ) );
117 }
118 $this->conn = $conn;
119 }
120 return Status::newGood( $this->conn );
121 }
122
123 function acquireForMe() {
124 $section = new ProfileSection( __METHOD__ );
125
126 $status = $this->precheckAcquire();
127 if ( !$status->isGood() ) {
128 return $status;
129 }
130
131 return $this->waitForSlotOrNotif( self::AWAKE_ONE );
132 }
133
134 function acquireForAnyone() {
135 $section = new ProfileSection( __METHOD__ );
136
137 $status = $this->precheckAcquire();
138 if ( !$status->isGood() ) {
139 return $status;
140 }
141
142 return $this->waitForSlotOrNotif( self::AWAKE_ALL );
143 }
144
145 function release() {
146 $section = new ProfileSection( __METHOD__ );
147
148 if ( $this->slot === null ) {
149 return Status::newGood( PoolCounter::NOT_LOCKED ); // not locked
150 }
151
152 $status = $this->getConnection();
153 if ( !$status->isOK() ) {
154 return $status;
155 }
156 $conn = $status->value;
157
158 static $script =
159 <<<LUA
160 local kSlots,kSlotsNextRelease,kWakeup,kWaiting = unpack(KEYS)
161 local rMaxWorkers,rExpiry,rSlot,rSlotTime,rAwakeAll,rTime = unpack(ARGV)
162 -- Add the slots back to the list (if rSlot is "w" then it is not a slot).
163 -- Treat the list as expired if the "next release" time sorted-set is missing.
164 if rSlot ~= 'w' and redis.call('exists',kSlotsNextRelease) == 1 then
165 if 1*redis.call('zScore',kSlotsNextRelease,rSlot) ~= (rSlotTime + rExpiry) then
166 -- Slot lock expired and was released already
167 elseif redis.call('lLen',kSlots) >= 1*rMaxWorkers then
168 -- Slots somehow got out of sync; reset the list for sanity
169 redis.call('del',kSlots,kSlotsNextRelease)
170 elseif redis.call('lLen',kSlots) == (1*rMaxWorkers - 1) and redis.call('zCard',kWaiting) == 0 then
171 -- Slot list will be made full; clear it to save space (it re-inits as needed)
172 -- since nothing is waiting on being unblocked by a push to the list
173 redis.call('del',kSlots,kSlotsNextRelease)
174 else
175 -- Add slot back to pool and update the "next release" time
176 redis.call('rPush',kSlots,rSlot)
177 redis.call('zAdd',kSlotsNextRelease,rTime + 30,rSlot)
178 -- Always keep renewing the expiry on use
179 redis.call('expireAt',kSlots,math.ceil(rTime + rExpiry))
180 redis.call('expireAt',kSlotsNextRelease,math.ceil(rTime + rExpiry))
181 end
182 end
183 -- Update an ephemeral list to wake up other clients that can
184 -- reuse any cached work from this process. Only do this if no
185 -- slots are currently free (e.g. clients could be waiting).
186 if 1*rAwakeAll == 1 then
187 local count = redis.call('zCard',kWaiting)
188 for i = 1,count do
189 redis.call('rPush',kWakeup,'w')
190 end
191 redis.call('pexpire',kWakeup,1)
192 end
193 return 1
194 LUA;
195 try {
196 $res = $conn->luaEval( $script,
197 array(
198 $this->getSlotListKey(),
199 $this->getSlotRTimeSetKey(),
200 $this->getWakeupListKey(),
201 $this->getWaitSetKey(),
202 $this->workers,
203 $this->lockTTL,
204 $this->slot,
205 $this->slotTime, // used for CAS-style sanity check
206 ( $this->onRelease === self::AWAKE_ALL ) ? 1 : 0,
207 microtime( true )
208 ),
209 4 # number of first argument(s) that are keys
210 );
211 } catch ( RedisException $e ) {
212 return Status::newFatal( 'pool-error-unknown', $e->getMessage() );
213 }
214
215 $this->slot = null;
216 $this->slotTime = null;
217 $this->onRelease = null;
218 unset( self::$active[$this->session] );
219
220 $this->onRelease();
221
222 return Status::newGood( PoolCounter::RELEASED );
223 }
224
225 /**
226 * @param int $doWakeup AWAKE_* constant
227 * @return Status
228 */
229 protected function waitForSlotOrNotif( $doWakeup ) {
230 if ( $this->slot !== null ) {
231 return Status::newGood( PoolCounter::LOCK_HELD ); // already acquired
232 }
233
234 $status = $this->getConnection();
235 if ( !$status->isOK() ) {
236 return $status;
237 }
238 $conn = $status->value;
239
240 $now = microtime( true );
241 try {
242 $slot = $this->initAndPopPoolSlotList( $conn, $now );
243 if ( ctype_digit( $slot ) ) {
244 // Pool slot acquired by this process
245 $slotTime = $now;
246 } elseif ( $slot === 'QUEUE_FULL' ) {
247 // Too many processes are waiting for pooled processes to finish
248 return Status::newGood( PoolCounter::QUEUE_FULL );
249 } elseif ( $slot === 'QUEUE_WAIT' ) {
250 // This process is now registered as waiting
251 $keys = ( $doWakeup == self::AWAKE_ALL )
252 // Wait for an open slot or wake-up signal (preferring the later)
253 ? array( $this->getWakeupListKey(), $this->getSlotListKey() )
254 // Just wait for an actual pool slot
255 : array( $this->getSlotListKey() );
256
257 $res = $conn->blPop( $keys, $this->timeout );
258 if ( $res === array() ) {
259 $conn->zRem( $this->getWaitSetKey(), $this->session ); // no longer waiting
260 return Status::newGood( PoolCounter::TIMEOUT );
261 }
262
263 $slot = $res[1]; // pool slot or "w" for wake-up notifications
264 $slotTime = microtime( true ); // last microtime() was a few RTTs ago
265 // Unregister this process as waiting and bump slot "next release" time
266 $this->registerAcquisitionTime( $conn, $slot, $slotTime );
267 } else {
268 return Status::newFatal( 'pool-error-unknown', "Server gave slot '$slot'." );
269 }
270 } catch ( RedisException $e ) {
271 return Status::newFatal( 'pool-error-unknown', $e->getMessage() );
272 }
273
274 if ( $slot !== 'w' ) {
275 $this->slot = $slot;
276 $this->slotTime = $slotTime;
277 $this->onRelease = $doWakeup;
278 self::$active[$this->session] = $this;
279 }
280
281 $this->onAcquire();
282
283 return Status::newGood( $slot === 'w' ? PoolCounter::DONE : PoolCounter::LOCKED );
284 }
285
286 /**
287 * @param RedisConnRef $conn
288 * @param float $now UNIX timestamp
289 * @return string|bool False on failure
290 */
291 protected function initAndPopPoolSlotList( RedisConnRef $conn, $now ) {
292 static $script =
293 <<<LUA
294 local kSlots,kSlotsNextRelease,kSlotWaits = unpack(KEYS)
295 local rMaxWorkers,rMaxQueue,rTimeout,rExpiry,rSess,rTime = unpack(ARGV)
296 -- Initialize if the "next release" time sorted-set is empty. The slot key
297 -- itself is empty if all slots are busy or when nothing is initialized.
298 -- If the list is empty but the set is not, then it is the later case.
299 -- For sanity, if the list exists but not the set, then reset everything.
300 if redis.call('exists',kSlotsNextRelease) == 0 then
301 redis.call('del',kSlots)
302 for i = 1,1*rMaxWorkers do
303 redis.call('rPush',kSlots,i)
304 redis.call('zAdd',kSlotsNextRelease,-1,i)
305 end
306 -- Otherwise do maintenance to clean up after network partitions
307 else
308 -- Find stale slot locks and add free them (avoid duplicates for sanity)
309 local staleLocks = redis.call('zRangeByScore',kSlotsNextRelease,0,rTime)
310 for k,slot in ipairs(staleLocks) do
311 redis.call('lRem',kSlots,0,slot)
312 redis.call('rPush',kSlots,slot)
313 redis.call('zAdd',kSlotsNextRelease,rTime + 30,slot)
314 end
315 -- Find stale wait slot entries and remove them
316 redis.call('zRemRangeByScore',kSlotWaits,0,rTime - 2*rTimeout)
317 end
318 local slot
319 -- Try to acquire a slot if possible now
320 if redis.call('lLen',kSlots) > 0 then
321 slot = redis.call('lPop',kSlots)
322 -- Update the slot "next release" time
323 redis.call('zAdd',kSlotsNextRelease,rTime + rExpiry,slot)
324 elseif redis.call('zCard',kSlotWaits) >= 1*rMaxQueue then
325 slot = 'QUEUE_FULL'
326 else
327 slot = 'QUEUE_WAIT'
328 -- Register this process as waiting
329 redis.call('zAdd',kSlotWaits,rTime,rSess)
330 redis.call('expireAt',kSlotWaits,math.ceil(rTime + 2*rTimeout))
331 end
332 -- Always keep renewing the expiry on use
333 redis.call('expireAt',kSlots,math.ceil(rTime + rExpiry))
334 redis.call('expireAt',kSlotsNextRelease,math.ceil(rTime + rExpiry))
335 return slot
336 LUA;
337 return $conn->luaEval( $script,
338 array(
339 $this->getSlotListKey(),
340 $this->getSlotRTimeSetKey(),
341 $this->getWaitSetKey(),
342 $this->workers,
343 $this->maxqueue,
344 $this->timeout,
345 $this->lockTTL,
346 $this->session,
347 $now
348 ),
349 3 # number of first argument(s) that are keys
350 );
351 }
352
353 /**
354 * @param RedisConnRef $conn
355 * @param string $slot
356 * @param float $now
357 * @return int|bool False on failure
358 */
359 protected function registerAcquisitionTime( RedisConnRef $conn, $slot, $now ) {
360 static $script =
361 <<<LUA
362 local kSlots,kSlotsNextRelease,kSlotWaits = unpack(KEYS)
363 local rSlot,rExpiry,rSess,rTime = unpack(ARGV)
364 -- If rSlot is 'w' then the client was told to wake up but got no slot
365 if rSlot ~= 'w' then
366 -- Update the slot "next release" time
367 redis.call('zAdd',kSlotsNextRelease,rTime + rExpiry,rSlot)
368 -- Always keep renewing the expiry on use
369 redis.call('expireAt',kSlots,math.ceil(rTime + rExpiry))
370 redis.call('expireAt',kSlotsNextRelease,math.ceil(rTime + rExpiry))
371 end
372 -- Unregister this process as waiting
373 redis.call('zRem',kSlotWaits,rSess)
374 return 1
375 LUA;
376 return $conn->luaEval( $script,
377 array(
378 $this->getSlotListKey(),
379 $this->getSlotRTimeSetKey(),
380 $this->getWaitSetKey(),
381 $slot,
382 $this->lockTTL,
383 $this->session,
384 $now
385 ),
386 3 # number of first argument(s) that are keys
387 );
388 }
389
390 /**
391 * @return string
392 */
393 protected function getSlotListKey() {
394 return "poolcounter:l-slots-{$this->keySha1}-{$this->workers}";
395 }
396
397 /**
398 * @return string
399 */
400 protected function getSlotRTimeSetKey() {
401 return "poolcounter:z-renewtime-{$this->keySha1}-{$this->workers}";
402 }
403
404 /**
405 * @return string
406 */
407 protected function getWaitSetKey() {
408 return "poolcounter:z-wait-{$this->keySha1}-{$this->workers}";
409 }
410
411 /**
412 * @return string
413 */
414 protected function getWakeupListKey() {
415 return "poolcounter:l-wakeup-{$this->keySha1}-{$this->workers}";
416 }
417
418 /**
419 * Try to make sure that locks get released (even with exceptions and fatals)
420 */
421 public static function releaseAll() {
422 foreach ( self::$active as $poolCounter ) {
423 try {
424 if ( $poolCounter->slot !== null ) {
425 $poolCounter->release();
426 }
427 } catch ( Exception $e ) {
428 }
429 }
430 }
431 }