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