MediaWiki  REL1_22
SqlBagOStuff.php
Go to the documentation of this file.
00001 <?php
00029 class SqlBagOStuff extends BagOStuff {
00033     var $lb;
00034 
00035     var $serverInfos;
00036     var $serverNames;
00037     var $numServers;
00038     var $conns;
00039     var $lastExpireAll = 0;
00040     var $purgePeriod = 100;
00041     var $shards = 1;
00042     var $tableName = 'objectcache';
00043 
00044     protected $connFailureTimes = array(); // UNIX timestamps
00045     protected $connFailureErrors = array(); // exceptions
00046 
00075     public function __construct( $params ) {
00076         if ( isset( $params['servers'] ) ) {
00077             $this->serverInfos = $params['servers'];
00078             $this->numServers = count( $this->serverInfos );
00079             $this->serverNames = array();
00080             foreach ( $this->serverInfos as $i => $info ) {
00081                 $this->serverNames[$i] = isset( $info['host'] ) ? $info['host'] : "#$i";
00082             }
00083         } elseif ( isset( $params['server'] ) ) {
00084             $this->serverInfos = array( $params['server'] );
00085             $this->numServers = count( $this->serverInfos );
00086         } else {
00087             $this->serverInfos = false;
00088             $this->numServers = 1;
00089         }
00090         if ( isset( $params['purgePeriod'] ) ) {
00091             $this->purgePeriod = intval( $params['purgePeriod'] );
00092         }
00093         if ( isset( $params['tableName'] ) ) {
00094             $this->tableName = $params['tableName'];
00095         }
00096         if ( isset( $params['shards'] ) ) {
00097             $this->shards = intval( $params['shards'] );
00098         }
00099     }
00100 
00107     protected function getDB( $serverIndex ) {
00108         global $wgDebugDBTransactions;
00109 
00110         if ( !isset( $this->conns[$serverIndex] ) ) {
00111             if ( $serverIndex >= $this->numServers ) {
00112                 throw new MWException( __METHOD__ . ": Invalid server index \"$serverIndex\"" );
00113             }
00114 
00115             # Don't keep timing out trying to connect for each call if the DB is down
00116             if ( isset( $this->connFailureErrors[$serverIndex] )
00117                 && ( time() - $this->connFailureTimes[$serverIndex] ) < 60 )
00118             {
00119                 throw $this->connFailureErrors[$serverIndex];
00120             }
00121 
00122             # If server connection info was given, use that
00123             if ( $this->serverInfos ) {
00124                 if ( $wgDebugDBTransactions ) {
00125                     wfDebug( "Using provided serverInfo for SqlBagOStuff\n" );
00126                 }
00127                 $info = $this->serverInfos[$serverIndex];
00128                 $type = isset( $info['type'] ) ? $info['type'] : 'mysql';
00129                 $host = isset( $info['host'] ) ? $info['host'] : '[unknown]';
00130                 wfDebug( __CLASS__ . ": connecting to $host\n" );
00131                 $db = DatabaseBase::factory( $type, $info );
00132                 $db->clearFlag( DBO_TRX );
00133             } else {
00134                 /*
00135                  * We must keep a separate connection to MySQL in order to avoid deadlocks
00136                  * However, SQLite has an opposite behavior. And PostgreSQL needs to know
00137                  * if we are in transaction or no
00138                  */
00139                 if ( wfGetDB( DB_MASTER )->getType() == 'mysql' ) {
00140                     $this->lb = wfGetLBFactory()->newMainLB();
00141                     $db = $this->lb->getConnection( DB_MASTER );
00142                     $db->clearFlag( DBO_TRX ); // auto-commit mode
00143                 } else {
00144                     $db = wfGetDB( DB_MASTER );
00145                 }
00146             }
00147             if ( $wgDebugDBTransactions ) {
00148                 wfDebug( sprintf( "Connection %s will be used for SqlBagOStuff\n", $db ) );
00149             }
00150             $this->conns[$serverIndex] = $db;
00151         }
00152 
00153         return $this->conns[$serverIndex];
00154     }
00155 
00161     protected function getTableByKey( $key ) {
00162         if ( $this->shards > 1 ) {
00163             $hash = hexdec( substr( md5( $key ), 0, 8 ) ) & 0x7fffffff;
00164             $tableIndex = $hash % $this->shards;
00165         } else {
00166             $tableIndex = 0;
00167         }
00168         if ( $this->numServers > 1 ) {
00169             $sortedServers = $this->serverNames;
00170             ArrayUtils::consistentHashSort( $sortedServers, $key );
00171             reset( $sortedServers );
00172             $serverIndex = key( $sortedServers );
00173         } else {
00174             $serverIndex = 0;
00175         }
00176         return array( $serverIndex, $this->getTableNameByShard( $tableIndex ) );
00177     }
00178 
00184     protected function getTableNameByShard( $index ) {
00185         if ( $this->shards > 1 ) {
00186             $decimals = strlen( $this->shards - 1 );
00187             return $this->tableName .
00188                 sprintf( "%0{$decimals}d", $index );
00189         } else {
00190             return $this->tableName;
00191         }
00192     }
00193 
00199     public function get( $key, &$casToken = null ) {
00200         $values = $this->getMulti( array( $key ) );
00201         if ( array_key_exists( $key, $values ) ) {
00202             $casToken = $values[$key];
00203             return $values[$key];
00204         }
00205         return false;
00206     }
00207 
00212     public function getMulti( array $keys ) {
00213         $values = array(); // array of (key => value)
00214 
00215         $keysByTable = array();
00216         foreach ( $keys as $key ) {
00217             list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
00218             $keysByTable[$serverIndex][$tableName][] = $key;
00219         }
00220 
00221         $this->garbageCollect(); // expire old entries if any
00222 
00223         $dataRows = array();
00224         foreach ( $keysByTable as $serverIndex => $serverKeys ) {
00225             try {
00226                 $db = $this->getDB( $serverIndex );
00227                 foreach ( $serverKeys as $tableName => $tableKeys ) {
00228                     $res = $db->select( $tableName,
00229                         array( 'keyname', 'value', 'exptime' ),
00230                         array( 'keyname' => $tableKeys ),
00231                         __METHOD__ );
00232                     foreach ( $res as $row ) {
00233                         $row->serverIndex = $serverIndex;
00234                         $row->tableName = $tableName;
00235                         $dataRows[$row->keyname] = $row;
00236                     }
00237                 }
00238             } catch ( DBError $e ) {
00239                 $this->handleReadError( $e, $serverIndex );
00240             }
00241         }
00242 
00243         foreach ( $keys as $key ) {
00244             if ( isset( $dataRows[$key] ) ) { // HIT?
00245                 $row = $dataRows[$key];
00246                 $this->debug( "get: retrieved data; expiry time is " . $row->exptime );
00247                 try {
00248                     $db = $this->getDB( $row->serverIndex );
00249                     if ( $this->isExpired( $db, $row->exptime ) ) { // MISS
00250                         $this->debug( "get: key has expired, deleting" );
00251                         $db->begin( __METHOD__ );
00252                         # Put the expiry time in the WHERE condition to avoid deleting a
00253                         # newly-inserted value
00254                         $db->delete( $row->tableName,
00255                             array( 'keyname' => $key, 'exptime' => $row->exptime ),
00256                             __METHOD__ );
00257                         $db->commit( __METHOD__ );
00258                         $values[$key] = false;
00259                     } else { // HIT
00260                         $values[$key] = $this->unserialize( $db->decodeBlob( $row->value ) );
00261                     }
00262                 } catch ( DBQueryError $e ) {
00263                     $this->handleWriteError( $e, $row->serverIndex );
00264                 }
00265             } else { // MISS
00266                 $values[$key] = false;
00267                 $this->debug( 'get: no matching rows' );
00268             }
00269         }
00270 
00271         return $values;
00272     }
00273 
00280     public function set( $key, $value, $exptime = 0 ) {
00281         list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
00282         try {
00283             $db = $this->getDB( $serverIndex );
00284             $exptime = intval( $exptime );
00285 
00286             if ( $exptime < 0 ) {
00287                 $exptime = 0;
00288             }
00289 
00290             if ( $exptime == 0 ) {
00291                 $encExpiry = $this->getMaxDateTime( $db );
00292             } else {
00293                 if ( $exptime < 3.16e8 ) { # ~10 years
00294                     $exptime += time();
00295                 }
00296 
00297                 $encExpiry = $db->timestamp( $exptime );
00298             }
00299             $db->begin( __METHOD__ );
00300             // (bug 24425) use a replace if the db supports it instead of
00301             // delete/insert to avoid clashes with conflicting keynames
00302             $db->replace(
00303                 $tableName,
00304                 array( 'keyname' ),
00305                 array(
00306                     'keyname' => $key,
00307                     'value' => $db->encodeBlob( $this->serialize( $value ) ),
00308                     'exptime' => $encExpiry
00309                 ), __METHOD__ );
00310             $db->commit( __METHOD__ );
00311         } catch ( DBError $e ) {
00312             $this->handleWriteError( $e, $serverIndex );
00313             return false;
00314         }
00315 
00316         return true;
00317     }
00318 
00326     public function cas( $casToken, $key, $value, $exptime = 0 ) {
00327         list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
00328         try {
00329             $db = $this->getDB( $serverIndex );
00330             $exptime = intval( $exptime );
00331 
00332             if ( $exptime < 0 ) {
00333                 $exptime = 0;
00334             }
00335 
00336             if ( $exptime == 0 ) {
00337                 $encExpiry = $this->getMaxDateTime( $db );
00338             } else {
00339                 if ( $exptime < 3.16e8 ) { # ~10 years
00340                     $exptime += time();
00341                 }
00342                 $encExpiry = $db->timestamp( $exptime );
00343             }
00344             $db->begin( __METHOD__ );
00345             // (bug 24425) use a replace if the db supports it instead of
00346             // delete/insert to avoid clashes with conflicting keynames
00347             $db->update(
00348                 $tableName,
00349                 array(
00350                     'keyname' => $key,
00351                     'value' => $db->encodeBlob( $this->serialize( $value ) ),
00352                     'exptime' => $encExpiry
00353                 ),
00354                 array(
00355                     'keyname' => $key,
00356                     'value' => $db->encodeBlob( $this->serialize( $casToken ) )
00357                 ),
00358                 __METHOD__
00359             );
00360             $db->commit( __METHOD__ );
00361         } catch ( DBQueryError $e ) {
00362             $this->handleWriteError( $e, $serverIndex );
00363 
00364             return false;
00365         }
00366 
00367         return (bool)$db->affectedRows();
00368     }
00369 
00375     public function delete( $key, $time = 0 ) {
00376         list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
00377         try {
00378             $db = $this->getDB( $serverIndex );
00379             $db->begin( __METHOD__ );
00380             $db->delete(
00381                 $tableName,
00382                 array( 'keyname' => $key ),
00383                 __METHOD__ );
00384             $db->commit( __METHOD__ );
00385         } catch ( DBError $e ) {
00386             $this->handleWriteError( $e, $serverIndex );
00387             return false;
00388         }
00389 
00390         return true;
00391     }
00392 
00398     public function incr( $key, $step = 1 ) {
00399         list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
00400         try {
00401             $db = $this->getDB( $serverIndex );
00402             $step = intval( $step );
00403             $db->begin( __METHOD__ );
00404             $row = $db->selectRow(
00405                 $tableName,
00406                 array( 'value', 'exptime' ),
00407                 array( 'keyname' => $key ),
00408                 __METHOD__,
00409                 array( 'FOR UPDATE' ) );
00410             if ( $row === false ) {
00411                 // Missing
00412                 $db->commit( __METHOD__ );
00413 
00414                 return null;
00415             }
00416             $db->delete( $tableName, array( 'keyname' => $key ), __METHOD__ );
00417             if ( $this->isExpired( $db, $row->exptime ) ) {
00418                 // Expired, do not reinsert
00419                 $db->commit( __METHOD__ );
00420 
00421                 return null;
00422             }
00423 
00424             $oldValue = intval( $this->unserialize( $db->decodeBlob( $row->value ) ) );
00425             $newValue = $oldValue + $step;
00426             $db->insert( $tableName,
00427                 array(
00428                     'keyname' => $key,
00429                     'value' => $db->encodeBlob( $this->serialize( $newValue ) ),
00430                     'exptime' => $row->exptime
00431                 ), __METHOD__, 'IGNORE' );
00432 
00433             if ( $db->affectedRows() == 0 ) {
00434                 // Race condition. See bug 28611
00435                 $newValue = null;
00436             }
00437             $db->commit( __METHOD__ );
00438         } catch ( DBError $e ) {
00439             $this->handleWriteError( $e, $serverIndex );
00440             return null;
00441         }
00442 
00443         return $newValue;
00444     }
00445 
00450     protected function isExpired( $db, $exptime ) {
00451         return $exptime != $this->getMaxDateTime( $db ) && wfTimestamp( TS_UNIX, $exptime ) < time();
00452     }
00453 
00457     protected function getMaxDateTime( $db ) {
00458         if ( time() > 0x7fffffff ) {
00459             return $db->timestamp( 1 << 62 );
00460         } else {
00461             return $db->timestamp( 0x7fffffff );
00462         }
00463     }
00464 
00465     protected function garbageCollect() {
00466         if ( !$this->purgePeriod ) {
00467             // Disabled
00468             return;
00469         }
00470         // Only purge on one in every $this->purgePeriod requests.
00471         if ( $this->purgePeriod !== 1 && mt_rand( 0, $this->purgePeriod - 1 ) ) {
00472             return;
00473         }
00474         $now = time();
00475         // Avoid repeating the delete within a few seconds
00476         if ( $now > ( $this->lastExpireAll + 1 ) ) {
00477             $this->lastExpireAll = $now;
00478             $this->expireAll();
00479         }
00480     }
00481 
00482     public function expireAll() {
00483         $this->deleteObjectsExpiringBefore( wfTimestampNow() );
00484     }
00485 
00492     public function deleteObjectsExpiringBefore( $timestamp, $progressCallback = false ) {
00493         for ( $serverIndex = 0; $serverIndex < $this->numServers; $serverIndex++ ) {
00494             try {
00495                 $db = $this->getDB( $serverIndex );
00496                 $dbTimestamp = $db->timestamp( $timestamp );
00497                 $totalSeconds = false;
00498                 $baseConds = array( 'exptime < ' . $db->addQuotes( $dbTimestamp ) );
00499                 for ( $i = 0; $i < $this->shards; $i++ ) {
00500                     $maxExpTime = false;
00501                     while ( true ) {
00502                         $conds = $baseConds;
00503                         if ( $maxExpTime !== false ) {
00504                             $conds[] = 'exptime > ' . $db->addQuotes( $maxExpTime );
00505                         }
00506                         $rows = $db->select(
00507                             $this->getTableNameByShard( $i ),
00508                             array( 'keyname', 'exptime' ),
00509                             $conds,
00510                             __METHOD__,
00511                             array( 'LIMIT' => 100, 'ORDER BY' => 'exptime' ) );
00512                         if ( !$rows->numRows() ) {
00513                             break;
00514                         }
00515                         $keys = array();
00516                         $row = $rows->current();
00517                         $minExpTime = $row->exptime;
00518                         if ( $totalSeconds === false ) {
00519                             $totalSeconds = wfTimestamp( TS_UNIX, $timestamp )
00520                                 - wfTimestamp( TS_UNIX, $minExpTime );
00521                         }
00522                         foreach ( $rows as $row ) {
00523                             $keys[] = $row->keyname;
00524                             $maxExpTime = $row->exptime;
00525                         }
00526 
00527                         $db->begin( __METHOD__ );
00528                         $db->delete(
00529                             $this->getTableNameByShard( $i ),
00530                             array(
00531                                 'exptime >= ' . $db->addQuotes( $minExpTime ),
00532                                 'exptime < ' . $db->addQuotes( $dbTimestamp ),
00533                                 'keyname' => $keys
00534                             ),
00535                             __METHOD__ );
00536                         $db->commit( __METHOD__ );
00537 
00538                         if ( $progressCallback ) {
00539                             if ( intval( $totalSeconds ) === 0 ) {
00540                                 $percent = 0;
00541                             } else {
00542                                 $remainingSeconds = wfTimestamp( TS_UNIX, $timestamp )
00543                                     - wfTimestamp( TS_UNIX, $maxExpTime );
00544                                 if ( $remainingSeconds > $totalSeconds ) {
00545                                     $totalSeconds = $remainingSeconds;
00546                                 }
00547                                 $percent = ( $i + $remainingSeconds / $totalSeconds )
00548                                     / $this->shards * 100;
00549                             }
00550                             $percent = ( $percent / $this->numServers )
00551                                 + ( $serverIndex / $this->numServers * 100 );
00552                             call_user_func( $progressCallback, $percent );
00553                         }
00554                     }
00555                 }
00556             } catch ( DBError $e ) {
00557                 $this->handleWriteError( $e, $serverIndex );
00558                 return false;
00559             }
00560         }
00561         return true;
00562     }
00563 
00564     public function deleteAll() {
00565         for ( $serverIndex = 0; $serverIndex < $this->numServers; $serverIndex++ ) {
00566             try {
00567                 $db = $this->getDB( $serverIndex );
00568                 for ( $i = 0; $i < $this->shards; $i++ ) {
00569                     $db->begin( __METHOD__ );
00570                     $db->delete( $this->getTableNameByShard( $i ), '*', __METHOD__ );
00571                     $db->commit( __METHOD__ );
00572                 }
00573             } catch ( DBError $e ) {
00574                 $this->handleWriteError( $e, $serverIndex );
00575                 return false;
00576             }
00577         }
00578         return true;
00579     }
00580 
00589     protected function serialize( &$data ) {
00590         $serial = serialize( $data );
00591 
00592         if ( function_exists( 'gzdeflate' ) ) {
00593             return gzdeflate( $serial );
00594         } else {
00595             return $serial;
00596         }
00597     }
00598 
00604     protected function unserialize( $serial ) {
00605         if ( function_exists( 'gzinflate' ) ) {
00606             wfSuppressWarnings();
00607             $decomp = gzinflate( $serial );
00608             wfRestoreWarnings();
00609 
00610             if ( false !== $decomp ) {
00611                 $serial = $decomp;
00612             }
00613         }
00614 
00615         $ret = unserialize( $serial );
00616 
00617         return $ret;
00618     }
00619 
00623     protected function handleReadError( DBError $exception, $serverIndex ) {
00624         if ( $exception instanceof DBConnectionError ) {
00625             $this->markServerDown( $exception, $serverIndex );
00626         }
00627         wfDebugLog( 'SQLBagOStuff', "DBError: {$exception->getMessage()}" );
00628         if ( $exception instanceof DBConnectionError ) {
00629             wfDebug( __METHOD__ . ": ignoring connection error\n" );
00630         } else {
00631             wfDebug( __METHOD__ . ": ignoring query error\n" );
00632         }
00633     }
00634 
00638     protected function handleWriteError( DBError $exception, $serverIndex ) {
00639         if ( $exception instanceof DBConnectionError ) {
00640             $this->markServerDown( $exception, $serverIndex );
00641         }
00642         if ( $exception->db && $exception->db->wasReadOnlyError() ) {
00643             try {
00644                 $exception->db->rollback( __METHOD__ );
00645             } catch ( DBError $e ) {}
00646         }
00647         wfDebugLog( 'SQLBagOStuff', "DBError: {$exception->getMessage()}" );
00648         if ( $exception instanceof DBConnectionError ) {
00649             wfDebug( __METHOD__ . ": ignoring connection error\n" );
00650         } else {
00651             wfDebug( __METHOD__ . ": ignoring query error\n" );
00652         }
00653     }
00654 
00658     protected function markServerDown( $exception, $serverIndex ) {
00659         if ( isset( $this->connFailureTimes[$serverIndex] ) ) {
00660             if ( time() - $this->connFailureTimes[$serverIndex] >= 60 ) {
00661                 unset( $this->connFailureTimes[$serverIndex] );
00662                 unset( $this->connFailureErrors[$serverIndex] );
00663             } else {
00664                 wfDebug( __METHOD__ . ": Server #$serverIndex already down\n" );
00665                 return;
00666             }
00667         }
00668         $now = time();
00669         wfDebug( __METHOD__ . ": Server #$serverIndex down until " . ( $now + 60 ) . "\n" );
00670         $this->connFailureTimes[$serverIndex] = $now;
00671         $this->connFailureErrors[$serverIndex] = $exception;
00672     }
00673 
00677     public function createTables() {
00678         for ( $serverIndex = 0; $serverIndex < $this->numServers; $serverIndex++ ) {
00679             $db = $this->getDB( $serverIndex );
00680             if ( $db->getType() !== 'mysql'
00681                 || version_compare( $db->getServerVersion(), '4.1.0', '<' ) )
00682             {
00683                 throw new MWException( __METHOD__ . ' is not supported on this DB server' );
00684             }
00685 
00686             for ( $i = 0; $i < $this->shards; $i++ ) {
00687                 $db->begin( __METHOD__ );
00688                 $db->query(
00689                     'CREATE TABLE ' . $db->tableName( $this->getTableNameByShard( $i ) ) .
00690                     ' LIKE ' . $db->tableName( 'objectcache' ),
00691                     __METHOD__ );
00692                 $db->commit( __METHOD__ );
00693             }
00694         }
00695     }
00696 }
00697 
00701 class MediaWikiBagOStuff extends SqlBagOStuff { }