3 * Object caching using a SQL database.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
24 use MediaWiki\MediaWikiServices
;
25 use Wikimedia\Rdbms\Database
;
26 use Wikimedia\Rdbms\IDatabase
;
27 use Wikimedia\Rdbms\DBError
;
28 use Wikimedia\Rdbms\DBQueryError
;
29 use Wikimedia\Rdbms\DBConnectionError
;
30 use Wikimedia\Rdbms\LoadBalancer
;
31 use Wikimedia\ScopedCallback
;
32 use Wikimedia\WaitConditionLoop
;
35 * Class to store objects in the database
39 class SqlBagOStuff
extends BagOStuff
{
40 /** @var array[] (server index => server config) */
41 protected $serverInfos;
42 /** @var string[] (server index => tag/host name) */
43 protected $serverTags;
45 protected $numServers;
46 /** @var int UNIX timestamp */
47 protected $lastGarbageCollect = 0;
49 protected $purgePeriod = 10;
51 protected $purgeLimit = 100;
53 protected $shards = 1;
55 protected $tableName = 'objectcache';
57 protected $replicaOnly = false;
59 protected $syncTimeout = 3;
61 /** @var LoadBalancer|null */
62 protected $separateMainLB;
65 /** @var array UNIX timestamps */
66 protected $connFailureTimes = [];
67 /** @var array Exceptions */
68 protected $connFailureErrors = [];
71 private static $GARBAGE_COLLECT_DELAY_SEC = 1;
74 private static $OP_SET = 'set';
76 private static $OP_ADD = 'add';
78 private static $OP_TOUCH = 'touch';
80 private static $OP_DELETE = 'delete';
83 * Constructor. Parameters are:
84 * - server: A server info structure in the format required by each
85 * element in $wgDBServers.
87 * - servers: An array of server info structures describing a set of database servers
88 * to distribute keys to. If this is specified, the "server" option will be
89 * ignored. If string keys are used, then they will be used for consistent
90 * hashing *instead* of the host name (from the server config). This is useful
91 * when a cluster is replicated to another site (with different host names)
92 * but each server has a corresponding replica in the other cluster.
94 * - purgePeriod: The average number of object cache writes in between
95 * garbage collection operations, where expired entries
96 * are removed from the database. Or in other words, the
97 * reciprocal of the probability of purging on any given
98 * write. If this is set to zero, purging will never be done.
100 * - purgeLimit: Maximum number of rows to purge at once.
102 * - tableName: The table name to use, default is "objectcache".
104 * - shards: The number of tables to use for data storage on each server.
105 * If this is more than 1, table names will be formed in the style
106 * objectcacheNNN where NNN is the shard index, between 0 and
107 * shards-1. The number of digits will be the minimum number
108 * required to hold the largest shard index. Data will be
109 * distributed across all tables by key hash. This is for
110 * MySQL bugs 61735 <https://bugs.mysql.com/bug.php?id=61735>
111 * and 61736 <https://bugs.mysql.com/bug.php?id=61736>.
113 * - replicaOnly: Whether to only use replica DBs and avoid triggering
114 * garbage collection logic of expired items. This only
115 * makes sense if the primary DB is used and only if get()
116 * calls will be used. This is used by ReplicatedBagOStuff.
117 * - syncTimeout: Max seconds to wait for replica DBs to catch up for WRITE_SYNC.
119 * @param array $params
121 public function __construct( $params ) {
122 parent
::__construct( $params );
124 $this->attrMap
[self
::ATTR_EMULATION
] = self
::QOS_EMULATION_SQL
;
125 $this->attrMap
[self
::ATTR_SYNCWRITES
] = self
::QOS_SYNCWRITES_NONE
;
127 if ( isset( $params['servers'] ) ) {
128 $this->serverInfos
= [];
129 $this->serverTags
= [];
130 $this->numServers
= count( $params['servers'] );
132 foreach ( $params['servers'] as $tag => $info ) {
133 $this->serverInfos
[$index] = $info;
134 if ( is_string( $tag ) ) {
135 $this->serverTags
[$index] = $tag;
137 $this->serverTags
[$index] = $info['host'] ??
"#$index";
141 } elseif ( isset( $params['server'] ) ) {
142 $this->serverInfos
= [ $params['server'] ];
143 $this->numServers
= count( $this->serverInfos
);
145 // Default to using the main wiki's database servers
146 $this->serverInfos
= false;
147 $this->numServers
= 1;
148 $this->attrMap
[self
::ATTR_SYNCWRITES
] = self
::QOS_SYNCWRITES_BE
;
150 if ( isset( $params['purgePeriod'] ) ) {
151 $this->purgePeriod
= intval( $params['purgePeriod'] );
153 if ( isset( $params['purgeLimit'] ) ) {
154 $this->purgeLimit
= intval( $params['purgeLimit'] );
156 if ( isset( $params['tableName'] ) ) {
157 $this->tableName
= $params['tableName'];
159 if ( isset( $params['shards'] ) ) {
160 $this->shards
= intval( $params['shards'] );
162 if ( isset( $params['syncTimeout'] ) ) {
163 $this->syncTimeout
= $params['syncTimeout'];
165 // Backwards-compatibility for < 1.34
166 $this->replicaOnly
= $params['replicaOnly'] ??
( $params['slaveOnly'] ??
false );
170 * Get a connection to the specified database
172 * @param int $serverIndex
174 * @throws MWException
176 protected function getDB( $serverIndex ) {
177 if ( !isset( $this->conns
[$serverIndex] ) ) {
178 if ( $serverIndex >= $this->numServers
) {
179 throw new MWException( __METHOD__
. ": Invalid server index \"$serverIndex\"" );
182 # Don't keep timing out trying to connect for each call if the DB is down
183 if ( isset( $this->connFailureErrors
[$serverIndex] )
184 && ( time() - $this->connFailureTimes
[$serverIndex] ) < 60
186 throw $this->connFailureErrors
[$serverIndex];
189 if ( $this->serverInfos
) {
190 // Use custom database defined by server connection info
191 $info = $this->serverInfos
[$serverIndex];
192 $type = $info['type'] ??
'mysql';
193 $host = $info['host'] ??
'[unknown]';
194 $this->logger
->debug( __CLASS__
. ": connecting to $host" );
195 $db = Database
::factory( $type, $info );
196 $db->clearFlag( DBO_TRX
); // auto-commit mode
198 // Use the main LB database
199 $lb = MediaWikiServices
::getInstance()->getDBLoadBalancer();
200 $index = $this->replicaOnly ? DB_REPLICA
: DB_MASTER
;
201 if ( $lb->getServerType( $lb->getWriterIndex() ) !== 'sqlite' ) {
202 // Keep a separate connection to avoid contention and deadlocks
203 $db = $lb->getConnection( $index, [], false, $lb::CONN_TRX_AUTOCOMMIT
);
205 // However, SQLite has the opposite behavior due to DB-level locking.
206 // Stock sqlite MediaWiki installs use a separate sqlite cache DB instead.
207 $db = $lb->getConnection( $index );
211 $this->logger
->debug( sprintf( "Connection %s will be used for SqlBagOStuff", $db ) );
212 $this->conns
[$serverIndex] = $db;
215 return $this->conns
[$serverIndex];
219 * Get the server index and table name for a given key
221 * @return array Server index and table name
223 protected function getTableByKey( $key ) {
224 if ( $this->shards
> 1 ) {
225 $hash = hexdec( substr( md5( $key ), 0, 8 ) ) & 0x7fffffff;
226 $tableIndex = $hash %
$this->shards
;
230 if ( $this->numServers
> 1 ) {
231 $sortedServers = $this->serverTags
;
232 ArrayUtils
::consistentHashSort( $sortedServers, $key );
233 reset( $sortedServers );
234 $serverIndex = key( $sortedServers );
238 return [ $serverIndex, $this->getTableNameByShard( $tableIndex ) ];
242 * Get the table name for a given shard index
246 protected function getTableNameByShard( $index ) {
247 if ( $this->shards
> 1 ) {
248 $decimals = strlen( $this->shards
- 1 );
249 return $this->tableName
.
250 sprintf( "%0{$decimals}d", $index );
252 return $this->tableName
;
256 protected function doGet( $key, $flags = 0, &$casToken = null ) {
259 $blobs = $this->fetchBlobMulti( [ $key ] );
260 if ( array_key_exists( $key, $blobs ) ) {
261 $blob = $blobs[$key];
262 $value = $this->unserialize( $blob );
264 $casToken = ( $value !== false ) ?
$blob : null;
272 protected function doGetMulti( array $keys, $flags = 0 ) {
275 $blobs = $this->fetchBlobMulti( $keys );
276 foreach ( $blobs as $key => $blob ) {
277 $values[$key] = $this->unserialize( $blob );
283 protected function fetchBlobMulti( array $keys, $flags = 0 ) {
284 $values = []; // array of (key => value)
287 foreach ( $keys as $key ) {
288 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
289 $keysByTable[$serverIndex][$tableName][] = $key;
293 foreach ( $keysByTable as $serverIndex => $serverKeys ) {
295 $db = $this->getDB( $serverIndex );
296 foreach ( $serverKeys as $tableName => $tableKeys ) {
297 $res = $db->select( $tableName,
298 [ 'keyname', 'value', 'exptime' ],
299 [ 'keyname' => $tableKeys ],
301 // Approximate write-on-the-fly BagOStuff API via blocking.
302 // This approximation fails if a ROLLBACK happens (which is rare).
303 // We do not want to flush the TRX as that can break callers.
304 $db->trxLevel() ?
[ 'LOCK IN SHARE MODE' ] : []
306 if ( $res === false ) {
309 foreach ( $res as $row ) {
310 $row->serverIndex
= $serverIndex;
311 $row->tableName
= $tableName;
312 $dataRows[$row->keyname
] = $row;
315 } catch ( DBError
$e ) {
316 $this->handleReadError( $e, $serverIndex );
320 foreach ( $keys as $key ) {
321 if ( isset( $dataRows[$key] ) ) { // HIT?
322 $row = $dataRows[$key];
323 $this->debug( "get: retrieved data; expiry time is " . $row->exptime
);
324 $db = null; // in case of connection failure
326 $db = $this->getDB( $row->serverIndex
);
327 if ( $this->isExpired( $db, $row->exptime
) ) { // MISS
328 $this->debug( "get: key has expired" );
330 $values[$key] = $db->decodeBlob( $row->value
);
332 } catch ( DBQueryError
$e ) {
333 $this->handleWriteError( $e, $db, $row->serverIndex
);
336 $this->debug( 'get: no matching rows' );
343 protected function doSetMulti( array $data, $exptime = 0, $flags = 0 ) {
344 return $this->modifyMulti( $data, $exptime, $flags, self
::$OP_SET );
348 * @param mixed[]|null[] $data Map of (key => new value or null)
349 * @param int $exptime UNIX timestamp, TTL in seconds, or 0 (no expiration)
350 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
351 * @param string $op Cache operation
354 private function modifyMulti( array $data, $exptime, $flags, $op ) {
356 foreach ( $data as $key => $value ) {
357 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
358 $keysByTable[$serverIndex][$tableName][] = $key;
361 $exptime = $this->convertToExpiry( $exptime );
364 /** @noinspection PhpUnusedLocalVariableInspection */
365 $silenceScope = $this->silenceTransactionProfiler();
366 foreach ( $keysByTable as $serverIndex => $serverKeys ) {
367 $db = null; // in case of connection failure
369 $db = $this->getDB( $serverIndex );
370 $this->occasionallyGarbageCollect( $db ); // expire old entries if any
371 $dbExpiry = $exptime ?
$db->timestamp( $exptime ) : $this->getMaxDateTime( $db );
372 } catch ( DBError
$e ) {
373 $this->handleWriteError( $e, $db, $serverIndex );
378 foreach ( $serverKeys as $tableName => $tableKeys ) {
380 $result = $this->updateTableKeys(
388 } catch ( DBError
$e ) {
389 $this->handleWriteError( $e, $db, $serverIndex );
396 if ( ( $flags & self
::WRITE_SYNC
) == self
::WRITE_SYNC
) {
397 $result = $this->waitForReplication() && $result;
405 * @param IDatabase $db
406 * @param string $table
407 * @param string[] $tableKeys Keys in $data to update
408 * @param mixed[]|null[] $data Map of (key => new value or null)
409 * @param string $dbExpiry DB-encoded expiry
412 * @throws InvalidArgumentException
414 private function updateTableKeys( $op, $db, $table, $tableKeys, $data, $dbExpiry ) {
417 if ( $op === self
::$OP_ADD ) {
419 foreach ( $tableKeys as $key ) {
422 'value' => $db->encodeBlob( $this->serialize( $data[$key] ) ),
423 'exptime' => $dbExpiry
429 'keyname' => $tableKeys,
430 'exptime <= ' . $db->addQuotes( $db->timestamp() )
434 $db->insert( $table, $rows, __METHOD__
, [ 'IGNORE' ] );
436 $success = ( $db->affectedRows() == count( $rows ) );
437 } elseif ( $op === self
::$OP_SET ) {
439 foreach ( $tableKeys as $key ) {
442 'value' => $db->encodeBlob( $this->serialize( $data[$key] ) ),
443 'exptime' => $dbExpiry
446 $db->replace( $table, [ 'keyname' ], $rows, __METHOD__
);
447 } elseif ( $op === self
::$OP_DELETE ) {
448 $db->delete( $table, [ 'keyname' => $tableKeys ], __METHOD__
);
449 } elseif ( $op === self
::$OP_TOUCH ) {
452 [ 'exptime' => $dbExpiry ],
454 'keyname' => $tableKeys,
455 'exptime > ' . $db->addQuotes( $db->timestamp() )
460 $success = ( $db->affectedRows() == count( $tableKeys ) );
462 throw new InvalidArgumentException( "Invalid operation '$op'" );
468 protected function doSet( $key, $value, $exptime = 0, $flags = 0 ) {
469 return $this->modifyMulti( [ $key => $value ], $exptime, $flags, self
::$OP_SET );
472 public function add( $key, $value, $exptime = 0, $flags = 0 ) {
473 return $this->modifyMulti( [ $key => $value ], $exptime, $flags, self
::$OP_ADD );
476 protected function cas( $casToken, $key, $value, $exptime = 0, $flags = 0 ) {
477 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
478 $exptime = $this->convertToExpiry( $exptime );
480 /** @noinspection PhpUnusedLocalVariableInspection */
481 $silenceScope = $this->silenceTransactionProfiler();
482 $db = null; // in case of connection failure
484 $db = $this->getDB( $serverIndex );
485 // (T26425) use a replace if the db supports it instead of
486 // delete/insert to avoid clashes with conflicting keynames
491 'value' => $db->encodeBlob( $this->serialize( $value ) ),
492 'exptime' => $exptime
493 ?
$db->timestamp( $exptime )
494 : $this->getMaxDateTime( $db )
498 'value' => $db->encodeBlob( $casToken ),
499 'exptime > ' . $db->addQuotes( $db->timestamp() )
503 } catch ( DBQueryError
$e ) {
504 $this->handleWriteError( $e, $db, $serverIndex );
509 return (bool)$db->affectedRows();
512 protected function doDeleteMulti( array $keys, $flags = 0 ) {
513 return $this->modifyMulti(
514 array_fill_keys( $keys, null ),
521 protected function doDelete( $key, $flags = 0 ) {
522 return $this->modifyMulti( [ $key => null ], 0, $flags, self
::$OP_DELETE );
525 public function incr( $key, $step = 1 ) {
526 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
529 /** @noinspection PhpUnusedLocalVariableInspection */
530 $silenceScope = $this->silenceTransactionProfiler();
531 $db = null; // in case of connection failure
533 $db = $this->getDB( $serverIndex );
534 $encTimestamp = $db->addQuotes( $db->timestamp() );
537 [ 'value = value + ' . (int)$step ],
538 [ 'keyname' => $key, "exptime > $encTimestamp" ],
541 if ( $db->affectedRows() > 0 ) {
542 $newValue = $db->selectField(
545 [ 'keyname' => $key, "exptime > $encTimestamp" ],
548 if ( $this->isInteger( $newValue ) ) {
549 $newCount = (int)$newValue;
552 } catch ( DBError
$e ) {
553 $this->handleWriteError( $e, $db, $serverIndex );
559 public function merge( $key, callable
$callback, $exptime = 0, $attempts = 10, $flags = 0 ) {
560 $ok = $this->mergeViaCas( $key, $callback, $exptime, $attempts, $flags );
561 if ( ( $flags & self
::WRITE_SYNC
) == self
::WRITE_SYNC
) {
562 $ok = $this->waitForReplication() && $ok;
568 protected function doChangeTTLMulti( array $keys, $exptime, $flags = 0 ) {
569 return $this->modifyMulti(
570 array_fill_keys( $keys, null ),
577 protected function doChangeTTL( $key, $exptime, $flags ) {
578 return $this->modifyMulti( [ $key => null ], $exptime, $flags, self
::$OP_TOUCH );
582 * @param IDatabase $db
583 * @param string $exptime
586 protected function isExpired( $db, $exptime ) {
588 $exptime != $this->getMaxDateTime( $db ) &&
589 wfTimestamp( TS_UNIX
, $exptime ) < time()
594 * @param IDatabase $db
597 protected function getMaxDateTime( $db ) {
598 if ( time() > 0x7fffffff ) {
599 return $db->timestamp( 1 << 62 );
601 return $db->timestamp( 0x7fffffff );
606 * @param IDatabase $db
609 protected function occasionallyGarbageCollect( IDatabase
$db ) {
611 // Random purging is enabled
612 $this->purgePeriod
&&
613 // Only purge on one in every $this->purgePeriod writes
614 mt_rand( 0, $this->purgePeriod
- 1 ) == 0 &&
615 // Avoid repeating the delete within a few seconds
616 ( time() - $this->lastGarbageCollect
) > self
::$GARBAGE_COLLECT_DELAY_SEC
618 $garbageCollector = function () use ( $db ) {
619 $this->deleteServerObjectsExpiringBefore( $db, time(), null, $this->purgeLimit
);
620 $this->lastGarbageCollect
= time();
622 if ( $this->asyncHandler
) {
623 $this->lastGarbageCollect
= time(); // avoid duplicate enqueues
624 ( $this->asyncHandler
)( $garbageCollector );
631 public function expireAll() {
632 $this->deleteObjectsExpiringBefore( time() );
635 public function deleteObjectsExpiringBefore(
637 callable
$progress = null,
640 /** @noinspection PhpUnusedLocalVariableInspection */
641 $silenceScope = $this->silenceTransactionProfiler();
643 $serverIndexes = range( 0, $this->numServers
- 1 );
644 shuffle( $serverIndexes );
648 $keysDeletedCount = 0;
649 foreach ( $serverIndexes as $numServersDone => $serverIndex ) {
650 $db = null; // in case of connection failure
652 $db = $this->getDB( $serverIndex );
653 $this->deleteServerObjectsExpiringBefore(
661 } catch ( DBError
$e ) {
662 $this->handleWriteError( $e, $db, $serverIndex );
671 * @param IDatabase $db
672 * @param string|int $timestamp
673 * @param callable|null $progressCallback
675 * @param int $serversDoneCount
676 * @param int &$keysDeletedCount
679 private function deleteServerObjectsExpiringBefore(
684 $serversDoneCount = 0,
685 &$keysDeletedCount = 0
687 $cutoffUnix = wfTimestamp( TS_UNIX
, $timestamp );
688 $shardIndexes = range( 0, $this->shards
- 1 );
689 shuffle( $shardIndexes );
691 foreach ( $shardIndexes as $numShardsDone => $shardIndex ) {
692 $continue = null; // last exptime
693 $lag = null; // purge lag
696 $this->getTableNameByShard( $shardIndex ),
697 [ 'keyname', 'exptime' ],
699 [ 'exptime < ' . $db->addQuotes( $db->timestamp( $cutoffUnix ) ) ],
700 $continue ?
[ 'exptime >= ' . $db->addQuotes( $continue ) ] : []
703 [ 'LIMIT' => min( $limit, 100 ), 'ORDER BY' => 'exptime' ]
706 if ( $res->numRows() ) {
707 $row = $res->current();
708 if ( $lag === null ) {
709 $lag = max( $cutoffUnix - wfTimestamp( TS_UNIX
, $row->exptime
), 1 );
713 foreach ( $res as $row ) {
714 $keys[] = $row->keyname
;
715 $continue = $row->exptime
;
719 $this->getTableNameByShard( $shardIndex ),
721 'exptime < ' . $db->addQuotes( $db->timestamp( $cutoffUnix ) ),
726 $keysDeletedCount +
= $db->affectedRows();
729 if ( is_callable( $progressCallback ) ) {
731 $remainingLag = $cutoffUnix - wfTimestamp( TS_UNIX
, $continue );
732 $processedLag = max( $lag - $remainingLag, 0 );
733 $doneRatio = ( $numShardsDone +
$processedLag / $lag ) / $this->shards
;
738 $overallRatio = ( $doneRatio / $this->numServers
)
739 +
( $serversDoneCount / $this->numServers
);
740 call_user_func( $progressCallback, $overallRatio * 100 );
742 } while ( $res->numRows() && $keysDeletedCount < $limit );
747 * Delete content of shard tables in every server.
748 * Return true if the operation is successful, false otherwise.
751 public function deleteAll() {
752 /** @noinspection PhpUnusedLocalVariableInspection */
753 $silenceScope = $this->silenceTransactionProfiler();
754 for ( $serverIndex = 0; $serverIndex < $this->numServers
; $serverIndex++
) {
755 $db = null; // in case of connection failure
757 $db = $this->getDB( $serverIndex );
758 for ( $i = 0; $i < $this->shards
; $i++
) {
759 $db->delete( $this->getTableNameByShard( $i ), '*', __METHOD__
);
761 } catch ( DBError
$e ) {
762 $this->handleWriteError( $e, $db, $serverIndex );
769 public function lock( $key, $timeout = 6, $expiry = 6, $rclass = '' ) {
770 // Avoid deadlocks and allow lock reentry if specified
771 if ( isset( $this->locks
[$key] ) ) {
772 if ( $rclass != '' && $this->locks
[$key]['class'] === $rclass ) {
773 ++
$this->locks
[$key]['depth'];
780 list( $serverIndex ) = $this->getTableByKey( $key );
782 $db = null; // in case of connection failure
784 $db = $this->getDB( $serverIndex );
785 $ok = $db->lock( $key, __METHOD__
, $timeout );
787 $this->locks
[$key] = [ 'class' => $rclass, 'depth' => 1 ];
790 $this->logger
->warning(
791 __METHOD__
. " failed due to timeout for {key}.",
792 [ 'key' => $key, 'timeout' => $timeout ]
796 } catch ( DBError
$e ) {
797 $this->handleWriteError( $e, $db, $serverIndex );
804 public function unlock( $key ) {
805 if ( !isset( $this->locks
[$key] ) ) {
809 if ( --$this->locks
[$key]['depth'] <= 0 ) {
810 unset( $this->locks
[$key] );
812 list( $serverIndex ) = $this->getTableByKey( $key );
814 $db = null; // in case of connection failure
816 $db = $this->getDB( $serverIndex );
817 $ok = $db->unlock( $key, __METHOD__
);
819 $this->logger
->warning(
820 __METHOD__
. ' failed to release lock for {key}.',
824 } catch ( DBError
$e ) {
825 $this->handleWriteError( $e, $db, $serverIndex );
836 * Serialize an object and, if possible, compress the representation.
837 * On typical message and page data, this can provide a 3X decrease
838 * in storage requirements.
843 protected function serialize( $data ) {
844 if ( is_int( $data ) ) {
848 $serial = serialize( $data );
849 if ( function_exists( 'gzdeflate' ) ) {
850 $serial = gzdeflate( $serial );
857 * Unserialize and, if necessary, decompress an object.
858 * @param string $serial
861 protected function unserialize( $serial ) {
862 if ( $this->isInteger( $serial ) ) {
866 if ( function_exists( 'gzinflate' ) ) {
867 Wikimedia\
suppressWarnings();
868 $decomp = gzinflate( $serial );
869 Wikimedia\restoreWarnings
();
871 if ( $decomp !== false ) {
876 return unserialize( $serial );
880 * Handle a DBError which occurred during a read operation.
882 * @param DBError $exception
883 * @param int $serverIndex
885 protected function handleReadError( DBError
$exception, $serverIndex ) {
886 if ( $exception instanceof DBConnectionError
) {
887 $this->markServerDown( $exception, $serverIndex );
890 $this->setAndLogDBError( $exception );
894 * Handle a DBQueryError which occurred during a write operation.
896 * @param DBError $exception
897 * @param IDatabase|null $db DB handle or null if connection failed
898 * @param int $serverIndex
901 protected function handleWriteError( DBError
$exception, $db, $serverIndex ) {
902 if ( !( $db instanceof IDatabase
) ) {
903 $this->markServerDown( $exception, $serverIndex );
906 $this->setAndLogDBError( $exception );
910 * @param DBError $exception
912 private function setAndLogDBError( DBError
$exception ) {
913 $this->logger
->error( "DBError: {$exception->getMessage()}" );
914 if ( $exception instanceof DBConnectionError
) {
915 $this->setLastError( BagOStuff
::ERR_UNREACHABLE
);
916 $this->logger
->debug( __METHOD__
. ": ignoring connection error" );
918 $this->setLastError( BagOStuff
::ERR_UNEXPECTED
);
919 $this->logger
->debug( __METHOD__
. ": ignoring query error" );
924 * Mark a server down due to a DBConnectionError exception
926 * @param DBError $exception
927 * @param int $serverIndex
929 protected function markServerDown( DBError
$exception, $serverIndex ) {
930 unset( $this->conns
[$serverIndex] ); // bug T103435
932 if ( isset( $this->connFailureTimes
[$serverIndex] ) ) {
933 if ( time() - $this->connFailureTimes
[$serverIndex] >= 60 ) {
934 unset( $this->connFailureTimes
[$serverIndex] );
935 unset( $this->connFailureErrors
[$serverIndex] );
937 $this->logger
->debug( __METHOD__
. ": Server #$serverIndex already down" );
942 $this->logger
->info( __METHOD__
. ": Server #$serverIndex down until " . ( $now +
60 ) );
943 $this->connFailureTimes
[$serverIndex] = $now;
944 $this->connFailureErrors
[$serverIndex] = $exception;
948 * Create shard tables. For use from eval.php.
950 public function createTables() {
951 for ( $serverIndex = 0; $serverIndex < $this->numServers
; $serverIndex++
) {
952 $db = $this->getDB( $serverIndex );
953 if ( $db->getType() !== 'mysql' ) {
954 throw new MWException( __METHOD__
. ' is not supported on this DB server' );
957 for ( $i = 0; $i < $this->shards
; $i++
) {
959 'CREATE TABLE ' . $db->tableName( $this->getTableNameByShard( $i ) ) .
960 ' LIKE ' . $db->tableName( 'objectcache' ),
967 * @return bool Whether the main DB is used, e.g. wfGetDB( DB_MASTER )
969 protected function usesMainDB() {
970 return !$this->serverInfos
;
973 protected function waitForReplication() {
974 if ( !$this->usesMainDB() ) {
975 // Custom DB server list; probably doesn't use replication
979 $lb = MediaWikiServices
::getInstance()->getDBLoadBalancer();
980 if ( $lb->getServerCount() <= 1 ) {
981 return true; // no replica DBs
984 // Main LB is used; wait for any replica DBs to catch up
986 $masterPos = $lb->getMasterPos();
988 return true; // not applicable
991 $loop = new WaitConditionLoop(
992 function () use ( $lb, $masterPos ) {
993 return $lb->waitForAll( $masterPos, 1 );
999 return ( $loop->invoke() === $loop::CONDITION_REACHED
);
1000 } catch ( DBError
$e ) {
1001 $this->setAndLogDBError( $e );
1008 * Returns a ScopedCallback which resets the silence flag in the transaction profiler when it is
1009 * destroyed on the end of a scope, for example on return or throw
1010 * @return ScopedCallback
1013 protected function silenceTransactionProfiler() {
1014 $trxProfiler = Profiler
::instance()->getTransactionProfiler();
1015 $oldSilenced = $trxProfiler->setSilenced( true );
1016 return new ScopedCallback( function () use ( $trxProfiler, $oldSilenced ) {
1017 $trxProfiler->setSilenced( $oldSilenced );