MediaWiki master
PoolCounterRedis.php
Go to the documentation of this file.
1<?php
8
9use Exception;
11use RedisException;
16
50 protected $ring;
52 protected $pool;
54 protected $serversByLabel;
56 protected $keySha1;
58 protected $lockTTL;
60 protected $conn;
62 protected $slot;
64 protected $onRelease;
66 protected $session;
68 protected $slotTime;
69
70 private const AWAKE_ONE = 1; // wake-up if when a slot can be taken from an existing process
71 private const AWAKE_ALL = 2; // wake-up if an existing process finishes and wake up such others
72
74 protected static $active = null;
75
76 public function __construct( array $conf, string $type, string $key ) {
77 parent::__construct( $conf, $type, $key );
78
79 $this->serversByLabel = $conf['servers'];
80
81 $serverLabels = array_keys( $conf['servers'] );
82 $this->ring = new HashRing( array_fill_keys( $serverLabels, 10 ) );
83
84 $conf['redisConfig']['serializer'] = 'none'; // for use with Lua
85 $this->pool = RedisConnectionPool::singleton( $conf['redisConfig'] );
86
87 $this->keySha1 = sha1( $this->key );
88 $met = ini_get( 'max_execution_time' ); // usually 0 in CLI mode
89 $this->lockTTL = $met ? 2 * (int)$met : 3600;
90
91 if ( self::$active === null ) {
92 self::$active = [];
93 register_shutdown_function( self::releaseAll( ... ) );
94 }
95 }
96
100 protected function getConnection() {
101 if ( !$this->conn ) {
102 $conn = false;
103 $servers = $this->ring->getLocations( $this->key, 3 );
104 ArrayUtils::consistentHashSort( $servers, $this->key );
105 foreach ( $servers as $server ) {
106 $conn = $this->pool->getConnection( $this->serversByLabel[$server], $this->logger );
107 if ( $conn ) {
108 break;
109 }
110 }
111 if ( !$conn ) {
112 return Status::newFatal( 'pool-servererror', implode( ', ', $servers ) );
113 }
114 $this->conn = $conn;
115 }
116 return Status::newGood( $this->conn );
117 }
118
120 public function acquireForMe( $timeout = null ) {
121 $status = $this->precheckAcquire();
122 if ( !$status->isGood() ) {
123 return $status;
124 }
125
126 return $this->waitForSlotOrNotif( self::AWAKE_ONE, $timeout );
127 }
128
130 public function acquireForAnyone( $timeout = null ) {
131 $status = $this->precheckAcquire();
132 if ( !$status->isGood() ) {
133 return $status;
134 }
135
136 return $this->waitForSlotOrNotif( self::AWAKE_ALL, $timeout );
137 }
138
140 public function release() {
141 if ( $this->slot === null ) {
142 return Status::newGood( PoolCounter::NOT_LOCKED ); // not locked
143 }
144
145 $status = $this->getConnection();
146 if ( !$status->isOK() ) {
147 return $status;
148 }
150 $conn = $status->value;
151 '@phan-var RedisConnRef $conn';
152
153 // phpcs:disable Generic.Files.LineLength
154 static $script =
156<<<LUA
157 local kSlots,kSlotsNextRelease,kWakeup,kWaiting = unpack(KEYS)
158 local rMaxWorkers,rExpiry,rSlot,rSlotTime,rAwakeAll,rTime = unpack(ARGV)
159 -- Add the slots back to the list (if rSlot is "w" then it is not a slot).
160 -- Treat the list as expired if the "next release" time sorted-set is missing.
161 if rSlot ~= 'w' and redis.call('exists',kSlotsNextRelease) == 1 then
162 if 1*redis.call('zScore',kSlotsNextRelease,rSlot) ~= (rSlotTime + rExpiry) then
163 -- Slot lock expired and was released already
164 elseif redis.call('lLen',kSlots) >= 1*rMaxWorkers then
165 -- Slots somehow got out of sync; reset the list
166 redis.call('del',kSlots,kSlotsNextRelease)
167 elseif redis.call('lLen',kSlots) == (1*rMaxWorkers - 1) and redis.call('zCard',kWaiting) == 0 then
168 -- Slot list will be made full; clear it to save space (it re-inits as needed)
169 -- since nothing is waiting on being unblocked by a push to the list
170 redis.call('del',kSlots,kSlotsNextRelease)
171 else
172 -- Add slot back to pool and update the "next release" time
173 redis.call('rPush',kSlots,rSlot)
174 redis.call('zAdd',kSlotsNextRelease,rTime + 30,rSlot)
175 -- Always keep renewing the expiry on use
176 redis.call('expireAt',kSlots,math.ceil(rTime + rExpiry))
177 redis.call('expireAt',kSlotsNextRelease,math.ceil(rTime + rExpiry))
178 end
179 end
180 -- Update an ephemeral list to wake up other clients that can
181 -- reuse any cached work from this process. Only do this if no
182 -- slots are currently free (e.g. clients could be waiting).
183 if 1*rAwakeAll == 1 then
184 local count = redis.call('zCard',kWaiting)
185 for i = 1,count do
186 redis.call('rPush',kWakeup,'w')
187 end
188 redis.call('pexpire',kWakeup,1)
189 end
190 return 1
191LUA;
192 // phpcs:enable
193
194 try {
195 $conn->luaEval(
196 $script,
197 [
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 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
230 protected function waitForSlotOrNotif( $doWakeup, $timeout = null ) {
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 }
240 $conn = $status->value;
241 '@phan-var RedisConnRef $conn';
242
243 $now = microtime( true );
245 try {
246 $slot = $this->initAndPopPoolSlotList( $conn, $now );
247 if ( ctype_digit( $slot ) ) {
248 // Pool slot acquired by this process
249 $slotTime = $now;
250 } elseif ( $slot === 'QUEUE_FULL' ) {
251 // Too many processes are waiting for pooled processes to finish
252 return Status::newGood( PoolCounter::QUEUE_FULL );
253 } elseif ( $slot === 'QUEUE_WAIT' ) {
254 // This process is now registered as waiting
255 $keys =
256 ( $doWakeup == self::AWAKE_ALL ) // Wait for an open slot or wake-up signal (preferring the latter)
257 ? [ $this->getWakeupListKey(), $this->getSlotListKey() ] // Just wait for an actual pool slot
258 : [ $this->getSlotListKey() ];
259
260 $res = $conn->blPop( $keys, $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
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
294 protected function initAndPopPoolSlotList( RedisConnRef $conn, $now ) {
295 static $script = <<<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 -- 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)
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
338LUA;
339 return $conn->luaEval(
340 $script,
341 [
342 $this->getSlotListKey(),
343 $this->getSlotRTimeSetKey(),
344 $this->getWaitSetKey(),
345 $this->workers,
346 $this->maxqueue,
347 $this->timeout,
348 $this->lockTTL,
349 $this->session,
350 $now,
351 ],
352 3 # number of first argument(s) that are keys
353 );
354 }
355
362 protected function registerAcquisitionTime( RedisConnRef $conn, $slot, $now ) {
363 static $script = <<<LUA
364 local kSlots,kSlotsNextRelease,kSlotWaits = unpack(KEYS)
365 local rSlot,rExpiry,rSess,rTime = unpack(ARGV)
366 -- If rSlot is 'w' then the client was told to wake up but got no slot
367 if rSlot ~= 'w' then
368 -- Update the slot "next release" time
369 redis.call('zAdd',kSlotsNextRelease,rTime + rExpiry,rSlot)
370 -- Always keep renewing the expiry on use
371 redis.call('expireAt',kSlots,math.ceil(rTime + rExpiry))
372 redis.call('expireAt',kSlotsNextRelease,math.ceil(rTime + rExpiry))
373 end
374 -- Unregister this process as waiting
375 redis.call('zRem',kSlotWaits,rSess)
376 return 1
377LUA;
378 return $conn->luaEval(
379 $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
396 protected function getSlotListKey() {
397 return "poolcounter:l-slots-{$this->keySha1}-{$this->workers}";
398 }
399
403 protected function getSlotRTimeSetKey() {
404 return "poolcounter:z-renewtime-{$this->keySha1}-{$this->workers}";
405 }
406
410 protected function getWaitSetKey() {
411 return "poolcounter:z-wait-{$this->keySha1}-{$this->workers}";
412 }
413
417 protected function getWakeupListKey() {
418 return "poolcounter:l-wakeup-{$this->keySha1}-{$this->workers}";
419 }
420
424 public static function releaseAll() {
425 $e = null;
426 foreach ( self::$active as $poolCounter ) {
427 try {
428 if ( $poolCounter->slot !== null ) {
429 $poolCounter->release();
430 }
431 } catch ( Exception $e ) {
432 }
433 }
434 if ( $e ) {
435 throw $e;
436 }
437 }
438}
439
441class_alias( PoolCounterRedis::class, 'PoolCounterRedis' );
Version of PoolCounter that uses Redis.
string $session
Unique string to identify this process.
initAndPopPoolSlotList(RedisConnRef $conn, $now)
waitForSlotOrNotif( $doWakeup, $timeout=null)
__construct(array $conf, string $type, string $key)
release()
I have successfully finished my task.Lets another one grab the lock, and returns the workers waiting ...
array $serversByLabel
(server label => host) map
int $lockTTL
TTL for locks to expire (work should finish in this time)
acquireForMe( $timeout=null)
I want to do this task and I need to do it myself.Status Value is one of Locked/Error
static releaseAll()
Try to make sure that locks get released (even with exceptions and fatals)
static PoolCounterRedis[] $active
List of active PoolCounterRedis objects in this script.
acquireForAnyone( $timeout=null)
I want to do this task, but if anyone else does it instead, it's also fine for me....
registerAcquisitionTime(RedisConnRef $conn, $slot, $now)
Semaphore semantics to restrict how many workers may concurrently perform a task.
precheckAcquire()
Checks that the lock request is sensible.
onRelease()
Update any lock tracking information when the lock is released.
string $key
All workers with the same key share the lock.
int $timeout
Maximum time in seconds to wait for the lock.
onAcquire()
Update any lock tracking information when the lock is acquired.
Generic operation result class Has warning/error list, boolean status and arbitrary value.
Definition Status.php:44
A collection of static methods to play with arrays.
Convenience class for weighted consistent hash rings.
Definition HashRing.php:36
Wrapper class for Redis connections that automatically reuses connections (via RAII pattern)
luaEval( $script, array $params, $numKeys)
Manage one or more Redis client connection.