MediaWiki  REL1_24
PoolCounterRedis.php
Go to the documentation of this file.
00001 <?php
00053 class PoolCounterRedis extends PoolCounter {
00055     protected $ring;
00057     protected $pool;
00059     protected $serversByLabel;
00061     protected $keySha1;
00063     protected $lockTTL;
00064 
00066     protected $conn;
00068     protected $slot;
00070     protected $onRelease;
00072     protected $session;
00074     protected $slotTime;
00075 
00076     const AWAKE_ONE = 1; // wake-up if when a slot can be taken from an existing process
00077     const AWAKE_ALL = 2; // wake-up if an existing process finishes and wake up such others
00078 
00080     protected static $active = null;
00081 
00082     function __construct( $conf, $type, $key ) {
00083         parent::__construct( $conf, $type, $key );
00084 
00085         $this->serversByLabel = $conf['servers'];
00086         $this->ring = new HashRing( array_fill_keys( array_keys( $conf['servers'] ), 100 ) );
00087 
00088         $conf['redisConfig']['serializer'] = 'none'; // for use with Lua
00089         $this->pool = RedisConnectionPool::singleton( $conf['redisConfig'] );
00090 
00091         $this->keySha1 = sha1( $this->key );
00092         $met = ini_get( 'max_execution_time' ); // usually 0 in CLI mode
00093         $this->lockTTL = $met ? 2 * $met : 3600;
00094 
00095         if ( self::$active === null ) {
00096             self::$active = array();
00097             register_shutdown_function( array( __CLASS__, 'releaseAll' ) );
00098         }
00099     }
00100 
00104     protected function getConnection() {
00105         if ( !isset( $this->conn ) ) {
00106             $conn = false;
00107             $servers = $this->ring->getLocations( $this->key, 3 );
00108             ArrayUtils::consistentHashSort( $servers, $this->key );
00109             foreach ( $servers as $server ) {
00110                 $conn = $this->pool->getConnection( $this->serversByLabel[$server] );
00111                 if ( $conn ) {
00112                     break;
00113                 }
00114             }
00115             if ( !$conn ) {
00116                 return Status::newFatal( 'pool-servererror', implode( ', ', $servers ) );
00117             }
00118             $this->conn = $conn;
00119         }
00120         return Status::newGood( $this->conn );
00121     }
00122 
00123     function acquireForMe() {
00124         $section = new ProfileSection( __METHOD__ );
00125 
00126         return $this->waitForSlotOrNotif( self::AWAKE_ONE );
00127     }
00128 
00129     function acquireForAnyone() {
00130         $section = new ProfileSection( __METHOD__ );
00131 
00132         return $this->waitForSlotOrNotif( self::AWAKE_ALL );
00133     }
00134 
00135     function release() {
00136         $section = new ProfileSection( __METHOD__ );
00137 
00138         if ( $this->slot === null ) {
00139             return Status::newGood( PoolCounter::NOT_LOCKED ); // not locked
00140         }
00141 
00142         $status = $this->getConnection();
00143         if ( !$status->isOK() ) {
00144             return $status;
00145         }
00146         $conn = $status->value;
00147 
00148         static $script =
00149 <<<LUA
00150         local kSlots,kSlotsNextRelease,kWakeup,kWaiting = unpack(KEYS)
00151         local rMaxWorkers,rExpiry,rSlot,rSlotTime,rAwakeAll,rTime = unpack(ARGV)
00152         -- Add the slots back to the list (if rSlot is "w" then it is not a slot).
00153         -- Treat the list as expired if the "next release" time sorted-set is missing.
00154         if rSlot ~= 'w' and redis.call('exists',kSlotsNextRelease) == 1 then
00155             if 1*redis.call('zScore',kSlotsNextRelease,rSlot) ~= (rSlotTime + rExpiry) then
00156                 -- Slot lock expired and was released already
00157             elseif redis.call('lLen',kSlots) >= 1*rMaxWorkers then
00158                 -- Slots somehow got out of sync; reset the list for sanity
00159                 redis.call('del',kSlots,kSlotsNextRelease)
00160             elseif redis.call('lLen',kSlots) == (1*rMaxWorkers - 1) and redis.call('zCard',kWaiting) == 0 then
00161                 -- Slot list will be made full; clear it to save space (it re-inits as needed)
00162                 -- since nothing is waiting on being unblocked by a push to the list
00163                 redis.call('del',kSlots,kSlotsNextRelease)
00164             else
00165                 -- Add slot back to pool and update the "next release" time
00166                 redis.call('rPush',kSlots,rSlot)
00167                 redis.call('zAdd',kSlotsNextRelease,rTime + 30,rSlot)
00168                 -- Always keep renewing the expiry on use
00169                 redis.call('expireAt',kSlots,math.ceil(rTime + rExpiry))
00170                 redis.call('expireAt',kSlotsNextRelease,math.ceil(rTime + rExpiry))
00171             end
00172         end
00173         -- Update an ephemeral list to wake up other clients that can
00174         -- reuse any cached work from this process. Only do this if no
00175         -- slots are currently free (e.g. clients could be waiting).
00176         if 1*rAwakeAll == 1 then
00177             local count = redis.call('zCard',kWaiting)
00178             for i = 1,count do
00179                 redis.call('rPush',kWakeup,'w')
00180             end
00181             redis.call('pexpire',kWakeup,1)
00182         end
00183         return 1
00184 LUA;
00185         try {
00186             $res = $conn->luaEval( $script,
00187                 array(
00188                     $this->getSlotListKey(),
00189                     $this->getSlotRTimeSetKey(),
00190                     $this->getWakeupListKey(),
00191                     $this->getWaitSetKey(),
00192                     $this->workers,
00193                     $this->lockTTL,
00194                     $this->slot,
00195                     $this->slotTime, // used for CAS-style sanity check
00196                     ( $this->onRelease === self::AWAKE_ALL ) ? 1 : 0,
00197                     microtime( true )
00198                 ),
00199                 4 # number of first argument(s) that are keys
00200             );
00201         } catch ( RedisException $e ) {
00202             return Status::newFatal( 'pool-error-unknown', $e->getMessage() );
00203         }
00204 
00205         $this->slot = null;
00206         $this->slotTime = null;
00207         $this->onRelease = null;
00208         unset( self::$active[$this->session] );
00209 
00210         return Status::newGood( PoolCounter::RELEASED );
00211     }
00212 
00217     protected function waitForSlotOrNotif( $doWakeup ) {
00218         if ( $this->slot !== null ) {
00219             return Status::newGood( PoolCounter::LOCK_HELD ); // already acquired
00220         }
00221 
00222         $status = $this->getConnection();
00223         if ( !$status->isOK() ) {
00224             return $status;
00225         }
00226         $conn = $status->value;
00227 
00228         $now = microtime( true );
00229         try {
00230             $slot = $this->initAndPopPoolSlotList( $conn, $now );
00231             if ( ctype_digit( $slot ) ) {
00232                 // Pool slot acquired by this process
00233                 $slotTime = $now;
00234             } elseif ( $slot === 'QUEUE_FULL' ) {
00235                 // Too many processes are waiting for pooled processes to finish
00236                 return Status::newGood( PoolCounter::QUEUE_FULL );
00237             } elseif ( $slot === 'QUEUE_WAIT' ) {
00238                 // This process is now registered as waiting
00239                 $keys = ( $doWakeup == self::AWAKE_ALL )
00240                     // Wait for an open slot or wake-up signal (preferring the later)
00241                     ? array( $this->getWakeupListKey(), $this->getSlotListKey() )
00242                     // Just wait for an actual pool slot
00243                     : array( $this->getSlotListKey() );
00244 
00245                 $res = $conn->blPop( $keys, $this->timeout );
00246                 if ( $res === array() ) {
00247                     $conn->zRem( $this->getWaitSetKey(), $this->session ); // no longer waiting
00248                     return Status::newGood( PoolCounter::TIMEOUT );
00249                 }
00250 
00251                 $slot = $res[1]; // pool slot or "w" for wake-up notifications
00252                 $slotTime = microtime( true ); // last microtime() was a few RTTs ago
00253                 // Unregister this process as waiting and bump slot "next release" time
00254                 $this->registerAcquisitionTime( $conn, $slot, $slotTime );
00255             } else {
00256                 return Status::newFatal( 'pool-error-unknown', "Server gave slot '$slot'." );
00257             }
00258         } catch ( RedisException $e ) {
00259             return Status::newFatal( 'pool-error-unknown', $e->getMessage() );
00260         }
00261 
00262         if ( $slot !== 'w' ) {
00263             $this->slot = $slot;
00264             $this->slotTime = $slotTime;
00265             $this->onRelease = $doWakeup;
00266             self::$active[$this->session] = $this;
00267         }
00268 
00269         return Status::newGood( $slot === 'w' ? PoolCounter::DONE : PoolCounter::LOCKED );
00270     }
00271 
00277     protected function initAndPopPoolSlotList( RedisConnRef $conn, $now ) {
00278         static $script =
00279 <<<LUA
00280         local kSlots,kSlotsNextRelease,kSlotWaits = unpack(KEYS)
00281         local rMaxWorkers,rMaxQueue,rTimeout,rExpiry,rSess,rTime = unpack(ARGV)
00282         -- Initialize if the "next release" time sorted-set is empty. The slot key
00283         -- itself is empty if all slots are busy or when nothing is initialized.
00284         -- If the list is empty but the set is not, then it is the later case.
00285         -- For sanity, if the list exists but not the set, then reset everything.
00286         if redis.call('exists',kSlotsNextRelease) == 0 then
00287             redis.call('del',kSlots)
00288             for i = 1,1*rMaxWorkers do
00289                 redis.call('rPush',kSlots,i)
00290                 redis.call('zAdd',kSlotsNextRelease,-1,i)
00291             end
00292         -- Otherwise do maintenance to clean up after network partitions
00293         else
00294             -- Find stale slot locks and add free them (avoid duplicates for sanity)
00295             local staleLocks = redis.call('zRangeByScore',kSlotsNextRelease,0,rTime)
00296             for k,slot in ipairs(staleLocks) do
00297                 redis.call('lRem',kSlots,0,slot)
00298                 redis.call('rPush',kSlots,slot)
00299                 redis.call('zAdd',kSlotsNextRelease,rTime + 30,slot)
00300             end
00301             -- Find stale wait slot entries and remove them
00302             redis.call('zRemRangeByScore',kSlotWaits,0,rTime - 2*rTimeout)
00303         end
00304         local slot
00305         -- Try to acquire a slot if possible now
00306         if redis.call('lLen',kSlots) > 0 then
00307             slot = redis.call('lPop',kSlots)
00308             -- Update the slot "next release" time
00309             redis.call('zAdd',kSlotsNextRelease,rTime + rExpiry,slot)
00310         elseif redis.call('zCard',kSlotWaits) >= 1*rMaxQueue then
00311             slot = 'QUEUE_FULL'
00312         else
00313             slot = 'QUEUE_WAIT'
00314             -- Register this process as waiting
00315             redis.call('zAdd',kSlotWaits,rTime,rSess)
00316             redis.call('expireAt',kSlotWaits,math.ceil(rTime + 2*rTimeout))
00317         end
00318         -- Always keep renewing the expiry on use
00319         redis.call('expireAt',kSlots,math.ceil(rTime + rExpiry))
00320         redis.call('expireAt',kSlotsNextRelease,math.ceil(rTime + rExpiry))
00321         return slot
00322 LUA;
00323         return $conn->luaEval( $script,
00324             array(
00325                 $this->getSlotListKey(),
00326                 $this->getSlotRTimeSetKey(),
00327                 $this->getWaitSetKey(),
00328                 $this->workers,
00329                 $this->maxqueue,
00330                 $this->timeout,
00331                 $this->lockTTL,
00332                 $this->session,
00333                 $now
00334             ),
00335             3 # number of first argument(s) that are keys
00336         );
00337     }
00338 
00345     protected function registerAcquisitionTime( RedisConnRef $conn, $slot, $now ) {
00346         static $script =
00347 <<<LUA
00348         local kSlots,kSlotsNextRelease,kSlotWaits = unpack(KEYS)
00349         local rSlot,rExpiry,rSess,rTime = unpack(ARGV)
00350         -- If rSlot is 'w' then the client was told to wake up but got no slot
00351         if rSlot ~= 'w' then
00352             -- Update the slot "next release" time
00353             redis.call('zAdd',kSlotsNextRelease,rTime + rExpiry,rSlot)
00354             -- Always keep renewing the expiry on use
00355             redis.call('expireAt',kSlots,math.ceil(rTime + rExpiry))
00356             redis.call('expireAt',kSlotsNextRelease,math.ceil(rTime + rExpiry))
00357         end
00358         -- Unregister this process as waiting
00359         redis.call('zRem',kSlotWaits,rSess)
00360         return 1
00361 LUA;
00362         return $conn->luaEval( $script,
00363             array(
00364                 $this->getSlotListKey(),
00365                 $this->getSlotRTimeSetKey(),
00366                 $this->getWaitSetKey(),
00367                 $slot,
00368                 $this->lockTTL,
00369                 $this->session,
00370                 $now
00371             ),
00372             3 # number of first argument(s) that are keys
00373         );
00374     }
00375 
00379     protected function getSlotListKey() {
00380         return "poolcounter:l-slots-{$this->keySha1}-{$this->workers}";
00381     }
00382 
00386     protected function getSlotRTimeSetKey() {
00387         return "poolcounter:z-renewtime-{$this->keySha1}-{$this->workers}";
00388     }
00389 
00393     protected function getWaitSetKey() {
00394         return "poolcounter:z-wait-{$this->keySha1}-{$this->workers}";
00395     }
00396 
00400     protected function getWakeupListKey() {
00401         return "poolcounter:l-wakeup-{$this->keySha1}-{$this->workers}";
00402     }
00403 
00407     public static function releaseAll() {
00408         foreach ( self::$active as $poolCounter ) {
00409             try {
00410                 if ( $poolCounter->slot !== null ) {
00411                     $poolCounter->release();
00412                 }
00413             } catch ( Exception $e ) {
00414             }
00415         }
00416     }
00417 }