Fix use of GenderCache in ApiPageSet::processTitlesArray
[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 */
20 use Psr\Log\LoggerInterface;
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 LoggerInterface */
59 protected $logger;
60 /** @var array (server label => host) map */
61 protected $serversByLabel;
62 /** @var string SHA-1 of the key */
63 protected $keySha1;
64 /** @var int TTL for locks to expire (work should finish in this time) */
65 protected $lockTTL;
66
67 /** @var RedisConnRef */
68 protected $conn;
69 /** @var string Pool slot value */
70 protected $slot;
71 /** @var int AWAKE_* constant */
72 protected $onRelease;
73 /** @var string Unique string to identify this process */
74 protected $session;
75 /** @var int UNIX timestamp */
76 protected $slotTime;
77
78 const AWAKE_ONE = 1; // wake-up if when a slot can be taken from an existing process
79 const AWAKE_ALL = 2; // wake-up if an existing process finishes and wake up such others
80
81 /** @var PoolCounterRedis[] List of active PoolCounterRedis objects in this script */
82 protected static $active = null;
83
84 function __construct( $conf, $type, $key ) {
85 parent::__construct( $conf, $type, $key );
86
87 $this->serversByLabel = $conf['servers'];
88
89 $serverLabels = array_keys( $conf['servers'] );
90 $this->ring = new HashRing( array_fill_keys( $serverLabels, 10 ) );
91
92 $conf['redisConfig']['serializer'] = 'none'; // for use with Lua
93 $this->pool = RedisConnectionPool::singleton( $conf['redisConfig'] );
94 $this->logger = \MediaWiki\Logger\LoggerFactory::getInstance( 'redis' );
95
96 $this->keySha1 = sha1( $this->key );
97 $met = ini_get( 'max_execution_time' ); // usually 0 in CLI mode
98 $this->lockTTL = $met ? 2 * $met : 3600;
99
100 if ( self::$active === null ) {
101 self::$active = [];
102 register_shutdown_function( [ __CLASS__, 'releaseAll' ] );
103 }
104 }
105
106 /**
107 * @return Status Uses RediConnRef as value on success
108 */
109 protected function getConnection() {
110 if ( !isset( $this->conn ) ) {
111 $conn = false;
112 $servers = $this->ring->getLocations( $this->key, 3 );
113 ArrayUtils::consistentHashSort( $servers, $this->key );
114 foreach ( $servers as $server ) {
115 $conn = $this->pool->getConnection( $this->serversByLabel[$server], $this->logger );
116 if ( $conn ) {
117 break;
118 }
119 }
120 if ( !$conn ) {
121 return Status::newFatal( 'pool-servererror', implode( ', ', $servers ) );
122 }
123 $this->conn = $conn;
124 }
125 return Status::newGood( $this->conn );
126 }
127
128 function acquireForMe() {
129 $status = $this->precheckAcquire();
130 if ( !$status->isGood() ) {
131 return $status;
132 }
133
134 return $this->waitForSlotOrNotif( self::AWAKE_ONE );
135 }
136
137 function acquireForAnyone() {
138 $status = $this->precheckAcquire();
139 if ( !$status->isGood() ) {
140 return $status;
141 }
142
143 return $this->waitForSlotOrNotif( self::AWAKE_ALL );
144 }
145
146 function release() {
147 if ( $this->slot === null ) {
148 return Status::newGood( PoolCounter::NOT_LOCKED ); // not locked
149 }
150
151 $status = $this->getConnection();
152 if ( !$status->isOK() ) {
153 return $status;
154 }
155 $conn = $status->value;
156
157 // phpcs:disable Generic.Files.LineLength
158 static $script =
159 /** @lang Lua */
160 <<<LUA
161 local kSlots,kSlotsNextRelease,kWakeup,kWaiting = unpack(KEYS)
162 local rMaxWorkers,rExpiry,rSlot,rSlotTime,rAwakeAll,rTime = unpack(ARGV)
163 -- Add the slots back to the list (if rSlot is "w" then it is not a slot).
164 -- Treat the list as expired if the "next release" time sorted-set is missing.
165 if rSlot ~= 'w' and redis.call('exists',kSlotsNextRelease) == 1 then
166 if 1*redis.call('zScore',kSlotsNextRelease,rSlot) ~= (rSlotTime + rExpiry) then
167 -- Slot lock expired and was released already
168 elseif redis.call('lLen',kSlots) >= 1*rMaxWorkers then
169 -- Slots somehow got out of sync; reset the list for sanity
170 redis.call('del',kSlots,kSlotsNextRelease)
171 elseif redis.call('lLen',kSlots) == (1*rMaxWorkers - 1) and redis.call('zCard',kWaiting) == 0 then
172 -- Slot list will be made full; clear it to save space (it re-inits as needed)
173 -- since nothing is waiting on being unblocked by a push to the list
174 redis.call('del',kSlots,kSlotsNextRelease)
175 else
176 -- Add slot back to pool and update the "next release" time
177 redis.call('rPush',kSlots,rSlot)
178 redis.call('zAdd',kSlotsNextRelease,rTime + 30,rSlot)
179 -- Always keep renewing the expiry on use
180 redis.call('expireAt',kSlots,math.ceil(rTime + rExpiry))
181 redis.call('expireAt',kSlotsNextRelease,math.ceil(rTime + rExpiry))
182 end
183 end
184 -- Update an ephemeral list to wake up other clients that can
185 -- reuse any cached work from this process. Only do this if no
186 -- slots are currently free (e.g. clients could be waiting).
187 if 1*rAwakeAll == 1 then
188 local count = redis.call('zCard',kWaiting)
189 for i = 1,count do
190 redis.call('rPush',kWakeup,'w')
191 end
192 redis.call('pexpire',kWakeup,1)
193 end
194 return 1
195 LUA;
196 // phpcs:enable
197
198 try {
199 $conn->luaEval( $script,
200 [
201 $this->getSlotListKey(),
202 $this->getSlotRTimeSetKey(),
203 $this->getWakeupListKey(),
204 $this->getWaitSetKey(),
205 $this->workers,
206 $this->lockTTL,
207 $this->slot,
208 $this->slotTime, // used for CAS-style sanity check
209 ( $this->onRelease === self::AWAKE_ALL ) ? 1 : 0,
210 microtime( true )
211 ],
212 4 # number of first argument(s) that are keys
213 );
214 } catch ( RedisException $e ) {
215 return Status::newFatal( 'pool-error-unknown', $e->getMessage() );
216 }
217
218 $this->slot = null;
219 $this->slotTime = null;
220 $this->onRelease = null;
221 unset( self::$active[$this->session] );
222
223 $this->onRelease();
224
225 return Status::newGood( PoolCounter::RELEASED );
226 }
227
228 /**
229 * @param int $doWakeup AWAKE_* constant
230 * @return Status
231 */
232 protected function waitForSlotOrNotif( $doWakeup ) {
233 if ( $this->slot !== null ) {
234 return Status::newGood( PoolCounter::LOCK_HELD ); // already acquired
235 }
236
237 $status = $this->getConnection();
238 if ( !$status->isOK() ) {
239 return $status;
240 }
241 $conn = $status->value;
242
243 $now = microtime( true );
244 try {
245 $slot = $this->initAndPopPoolSlotList( $conn, $now );
246 if ( ctype_digit( $slot ) ) {
247 // Pool slot acquired by this process
248 $slotTime = $now;
249 } elseif ( $slot === 'QUEUE_FULL' ) {
250 // Too many processes are waiting for pooled processes to finish
251 return Status::newGood( PoolCounter::QUEUE_FULL );
252 } elseif ( $slot === 'QUEUE_WAIT' ) {
253 // This process is now registered as waiting
254 $keys = ( $doWakeup == self::AWAKE_ALL )
255 // Wait for an open slot or wake-up signal (preferring the latter)
256 ? [ $this->getWakeupListKey(), $this->getSlotListKey() ]
257 // Just wait for an actual pool slot
258 : [ $this->getSlotListKey() ];
259
260 $res = $conn->blPop( $keys, $this->timeout );
261 if ( $res === [] ) {
262 $conn->zRem( $this->getWaitSetKey(), $this->session ); // no longer waiting
263 return Status::newGood( PoolCounter::TIMEOUT );
264 }
265
266 $slot = $res[1]; // pool slot or "w" for wake-up notifications
267 $slotTime = microtime( true ); // last microtime() was a few RTTs ago
268 // Unregister this process as waiting and bump slot "next release" time
269 $this->registerAcquisitionTime( $conn, $slot, $slotTime );
270 } else {
271 return Status::newFatal( 'pool-error-unknown', "Server gave slot '$slot'." );
272 }
273 } catch ( RedisException $e ) {
274 return Status::newFatal( 'pool-error-unknown', $e->getMessage() );
275 }
276
277 if ( $slot !== 'w' ) {
278 $this->slot = $slot;
279 $this->slotTime = $slotTime;
280 $this->onRelease = $doWakeup;
281 self::$active[$this->session] = $this;
282 }
283
284 $this->onAcquire();
285
286 return Status::newGood( $slot === 'w' ? PoolCounter::DONE : PoolCounter::LOCKED );
287 }
288
289 /**
290 * @param RedisConnRef $conn
291 * @param float $now UNIX timestamp
292 * @return string|bool False on failure
293 */
294 protected function initAndPopPoolSlotList( RedisConnRef $conn, $now ) {
295 static $script =
296 /** @lang Lua */
297 <<<LUA
298 local kSlots,kSlotsNextRelease,kSlotWaits = unpack(KEYS)
299 local rMaxWorkers,rMaxQueue,rTimeout,rExpiry,rSess,rTime = unpack(ARGV)
300 -- Initialize if the "next release" time sorted-set is empty. The slot key
301 -- itself is empty if all slots are busy or when nothing is initialized.
302 -- If the list is empty but the set is not, then it is the latter case.
303 -- For sanity, if the list exists but not the set, then reset everything.
304 if redis.call('exists',kSlotsNextRelease) == 0 then
305 redis.call('del',kSlots)
306 for i = 1,1*rMaxWorkers do
307 redis.call('rPush',kSlots,i)
308 redis.call('zAdd',kSlotsNextRelease,-1,i)
309 end
310 -- Otherwise do maintenance to clean up after network partitions
311 else
312 -- Find stale slot locks and add free them (avoid duplicates for sanity)
313 local staleLocks = redis.call('zRangeByScore',kSlotsNextRelease,0,rTime)
314 for k,slot in ipairs(staleLocks) do
315 redis.call('lRem',kSlots,0,slot)
316 redis.call('rPush',kSlots,slot)
317 redis.call('zAdd',kSlotsNextRelease,rTime + 30,slot)
318 end
319 -- Find stale wait slot entries and remove them
320 redis.call('zRemRangeByScore',kSlotWaits,0,rTime - 2*rTimeout)
321 end
322 local slot
323 -- Try to acquire a slot if possible now
324 if redis.call('lLen',kSlots) > 0 then
325 slot = redis.call('lPop',kSlots)
326 -- Update the slot "next release" time
327 redis.call('zAdd',kSlotsNextRelease,rTime + rExpiry,slot)
328 elseif redis.call('zCard',kSlotWaits) >= 1*rMaxQueue then
329 slot = 'QUEUE_FULL'
330 else
331 slot = 'QUEUE_WAIT'
332 -- Register this process as waiting
333 redis.call('zAdd',kSlotWaits,rTime,rSess)
334 redis.call('expireAt',kSlotWaits,math.ceil(rTime + 2*rTimeout))
335 end
336 -- Always keep renewing the expiry on use
337 redis.call('expireAt',kSlots,math.ceil(rTime + rExpiry))
338 redis.call('expireAt',kSlotsNextRelease,math.ceil(rTime + rExpiry))
339 return slot
340 LUA;
341 return $conn->luaEval( $script,
342 [
343 $this->getSlotListKey(),
344 $this->getSlotRTimeSetKey(),
345 $this->getWaitSetKey(),
346 $this->workers,
347 $this->maxqueue,
348 $this->timeout,
349 $this->lockTTL,
350 $this->session,
351 $now
352 ],
353 3 # number of first argument(s) that are keys
354 );
355 }
356
357 /**
358 * @param RedisConnRef $conn
359 * @param string $slot
360 * @param float $now
361 * @return int|bool False on failure
362 */
363 protected function registerAcquisitionTime( RedisConnRef $conn, $slot, $now ) {
364 static $script =
365 /** @lang Lua */
366 <<<LUA
367 local kSlots,kSlotsNextRelease,kSlotWaits = unpack(KEYS)
368 local rSlot,rExpiry,rSess,rTime = unpack(ARGV)
369 -- If rSlot is 'w' then the client was told to wake up but got no slot
370 if rSlot ~= 'w' then
371 -- Update the slot "next release" time
372 redis.call('zAdd',kSlotsNextRelease,rTime + rExpiry,rSlot)
373 -- Always keep renewing the expiry on use
374 redis.call('expireAt',kSlots,math.ceil(rTime + rExpiry))
375 redis.call('expireAt',kSlotsNextRelease,math.ceil(rTime + rExpiry))
376 end
377 -- Unregister this process as waiting
378 redis.call('zRem',kSlotWaits,rSess)
379 return 1
380 LUA;
381 return $conn->luaEval( $script,
382 [
383 $this->getSlotListKey(),
384 $this->getSlotRTimeSetKey(),
385 $this->getWaitSetKey(),
386 $slot,
387 $this->lockTTL,
388 $this->session,
389 $now
390 ],
391 3 # number of first argument(s) that are keys
392 );
393 }
394
395 /**
396 * @return string
397 */
398 protected function getSlotListKey() {
399 return "poolcounter:l-slots-{$this->keySha1}-{$this->workers}";
400 }
401
402 /**
403 * @return string
404 */
405 protected function getSlotRTimeSetKey() {
406 return "poolcounter:z-renewtime-{$this->keySha1}-{$this->workers}";
407 }
408
409 /**
410 * @return string
411 */
412 protected function getWaitSetKey() {
413 return "poolcounter:z-wait-{$this->keySha1}-{$this->workers}";
414 }
415
416 /**
417 * @return string
418 */
419 protected function getWakeupListKey() {
420 return "poolcounter:l-wakeup-{$this->keySha1}-{$this->workers}";
421 }
422
423 /**
424 * Try to make sure that locks get released (even with exceptions and fatals)
425 */
426 public static function releaseAll() {
427 foreach ( self::$active as $poolCounter ) {
428 try {
429 if ( $poolCounter->slot !== null ) {
430 $poolCounter->release();
431 }
432 } catch ( Exception $e ) {
433 }
434 }
435 }
436 }