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