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 * - slaveOnly: 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 $this->replicaOnly
= !empty( $params['slaveOnly'] );
169 * Get a connection to the specified database
171 * @param int $serverIndex
173 * @throws MWException
175 protected function getDB( $serverIndex ) {
176 if ( !isset( $this->conns
[$serverIndex] ) ) {
177 if ( $serverIndex >= $this->numServers
) {
178 throw new MWException( __METHOD__
. ": Invalid server index \"$serverIndex\"" );
181 # Don't keep timing out trying to connect for each call if the DB is down
182 if ( isset( $this->connFailureErrors
[$serverIndex] )
183 && ( time() - $this->connFailureTimes
[$serverIndex] ) < 60
185 throw $this->connFailureErrors
[$serverIndex];
188 if ( $this->serverInfos
) {
189 // Use custom database defined by server connection info
190 $info = $this->serverInfos
[$serverIndex];
191 $type = $info['type'] ??
'mysql';
192 $host = $info['host'] ??
'[unknown]';
193 $this->logger
->debug( __CLASS__
. ": connecting to $host" );
194 $db = Database
::factory( $type, $info );
195 $db->clearFlag( DBO_TRX
); // auto-commit mode
197 // Use the main LB database
198 $lb = MediaWikiServices
::getInstance()->getDBLoadBalancer();
199 $index = $this->replicaOnly ? DB_REPLICA
: DB_MASTER
;
200 if ( $lb->getServerType( $lb->getWriterIndex() ) !== 'sqlite' ) {
201 // Keep a separate connection to avoid contention and deadlocks
202 $db = $lb->getConnection( $index, [], false, $lb::CONN_TRX_AUTOCOMMIT
);
204 // However, SQLite has the opposite behavior due to DB-level locking.
205 // Stock sqlite MediaWiki installs use a separate sqlite cache DB instead.
206 $db = $lb->getConnection( $index );
210 $this->logger
->debug( sprintf( "Connection %s will be used for SqlBagOStuff", $db ) );
211 $this->conns
[$serverIndex] = $db;
214 return $this->conns
[$serverIndex];
218 * Get the server index and table name for a given key
220 * @return array Server index and table name
222 protected function getTableByKey( $key ) {
223 if ( $this->shards
> 1 ) {
224 $hash = hexdec( substr( md5( $key ), 0, 8 ) ) & 0x7fffffff;
225 $tableIndex = $hash %
$this->shards
;
229 if ( $this->numServers
> 1 ) {
230 $sortedServers = $this->serverTags
;
231 ArrayUtils
::consistentHashSort( $sortedServers, $key );
232 reset( $sortedServers );
233 $serverIndex = key( $sortedServers );
237 return [ $serverIndex, $this->getTableNameByShard( $tableIndex ) ];
241 * Get the table name for a given shard index
245 protected function getTableNameByShard( $index ) {
246 if ( $this->shards
> 1 ) {
247 $decimals = strlen( $this->shards
- 1 );
248 return $this->tableName
.
249 sprintf( "%0{$decimals}d", $index );
251 return $this->tableName
;
255 protected function doGet( $key, $flags = 0, &$casToken = null ) {
258 $blobs = $this->fetchBlobMulti( [ $key ] );
259 if ( array_key_exists( $key, $blobs ) ) {
260 $blob = $blobs[$key];
261 $value = $this->unserialize( $blob );
263 $casToken = ( $value !== false ) ?
$blob : null;
271 protected function doGetMulti( array $keys, $flags = 0 ) {
274 $blobs = $this->fetchBlobMulti( $keys );
275 foreach ( $blobs as $key => $blob ) {
276 $values[$key] = $this->unserialize( $blob );
282 protected function fetchBlobMulti( array $keys, $flags = 0 ) {
283 $values = []; // array of (key => value)
286 foreach ( $keys as $key ) {
287 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
288 $keysByTable[$serverIndex][$tableName][] = $key;
292 foreach ( $keysByTable as $serverIndex => $serverKeys ) {
294 $db = $this->getDB( $serverIndex );
295 foreach ( $serverKeys as $tableName => $tableKeys ) {
296 $res = $db->select( $tableName,
297 [ 'keyname', 'value', 'exptime' ],
298 [ 'keyname' => $tableKeys ],
300 // Approximate write-on-the-fly BagOStuff API via blocking.
301 // This approximation fails if a ROLLBACK happens (which is rare).
302 // We do not want to flush the TRX as that can break callers.
303 $db->trxLevel() ?
[ 'LOCK IN SHARE MODE' ] : []
305 if ( $res === false ) {
308 foreach ( $res as $row ) {
309 $row->serverIndex
= $serverIndex;
310 $row->tableName
= $tableName;
311 $dataRows[$row->keyname
] = $row;
314 } catch ( DBError
$e ) {
315 $this->handleReadError( $e, $serverIndex );
319 foreach ( $keys as $key ) {
320 if ( isset( $dataRows[$key] ) ) { // HIT?
321 $row = $dataRows[$key];
322 $this->debug( "get: retrieved data; expiry time is " . $row->exptime
);
323 $db = null; // in case of connection failure
325 $db = $this->getDB( $row->serverIndex
);
326 if ( $this->isExpired( $db, $row->exptime
) ) { // MISS
327 $this->debug( "get: key has expired" );
329 $values[$key] = $db->decodeBlob( $row->value
);
331 } catch ( DBQueryError
$e ) {
332 $this->handleWriteError( $e, $db, $row->serverIndex
);
335 $this->debug( 'get: no matching rows' );
342 public function doSetMulti( array $data, $exptime = 0, $flags = 0 ) {
343 return $this->modifyMulti( $data, $exptime, $flags, self
::$OP_SET );
347 * @param mixed[]|null[] $data Map of (key => new value or null)
348 * @param int $exptime UNIX timestamp, TTL in seconds, or 0 (no expiration)
349 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
350 * @param string $op Cache operation
353 private function modifyMulti( array $data, $exptime, $flags, $op ) {
355 foreach ( $data as $key => $value ) {
356 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
357 $keysByTable[$serverIndex][$tableName][] = $key;
360 $exptime = $this->convertToExpiry( $exptime );
363 /** @noinspection PhpUnusedLocalVariableInspection */
364 $silenceScope = $this->silenceTransactionProfiler();
365 foreach ( $keysByTable as $serverIndex => $serverKeys ) {
366 $db = null; // in case of connection failure
368 $db = $this->getDB( $serverIndex );
369 $this->occasionallyGarbageCollect( $db ); // expire old entries if any
370 $dbExpiry = $exptime ?
$db->timestamp( $exptime ) : $this->getMaxDateTime( $db );
371 } catch ( DBError
$e ) {
372 $this->handleWriteError( $e, $db, $serverIndex );
377 foreach ( $serverKeys as $tableName => $tableKeys ) {
379 $result = $this->updateTableKeys(
387 } catch ( DBError
$e ) {
388 $this->handleWriteError( $e, $db, $serverIndex );
395 if ( ( $flags & self
::WRITE_SYNC
) == self
::WRITE_SYNC
) {
396 $result = $this->waitForReplication() && $result;
404 * @param IDatabase $db
405 * @param string $table
406 * @param string[] $tableKeys Keys in $data to update
407 * @param mixed[]|null[] $data Map of (key => new value or null)
408 * @param string $dbExpiry DB-encoded expiry
411 * @throws InvalidArgumentException
413 private function updateTableKeys( $op, $db, $table, $tableKeys, $data, $dbExpiry ) {
416 if ( $op === self
::$OP_ADD ) {
418 foreach ( $tableKeys as $key ) {
421 'value' => $db->encodeBlob( $this->serialize( $data[$key] ) ),
422 'exptime' => $dbExpiry
428 'keyname' => $tableKeys,
429 'exptime <= ' . $db->addQuotes( $db->timestamp() )
433 $db->insert( $table, $rows, __METHOD__
, [ 'IGNORE' ] );
435 $success = ( $db->affectedRows() == count( $rows ) );
436 } elseif ( $op === self
::$OP_SET ) {
438 foreach ( $tableKeys as $key ) {
441 'value' => $db->encodeBlob( $this->serialize( $data[$key] ) ),
442 'exptime' => $dbExpiry
445 $db->replace( $table, [ 'keyname' ], $rows, __METHOD__
);
446 } elseif ( $op === self
::$OP_DELETE ) {
447 $db->delete( $table, [ 'keyname' => $tableKeys ], __METHOD__
);
448 } elseif ( $op === self
::$OP_TOUCH ) {
451 [ 'exptime' => $dbExpiry ],
453 'keyname' => $tableKeys,
454 'exptime > ' . $db->addQuotes( $db->timestamp() )
459 $success = ( $db->affectedRows() == count( $tableKeys ) );
461 throw new InvalidArgumentException( "Invalid operation '$op'" );
467 protected function doSet( $key, $value, $exptime = 0, $flags = 0 ) {
468 return $this->modifyMulti( [ $key => $value ], $exptime, $flags, self
::$OP_SET );
471 public function add( $key, $value, $exptime = 0, $flags = 0 ) {
472 return $this->modifyMulti( [ $key => $value ], $exptime, $flags, self
::$OP_ADD );
475 protected function cas( $casToken, $key, $value, $exptime = 0, $flags = 0 ) {
476 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
477 $exptime = $this->convertToExpiry( $exptime );
479 /** @noinspection PhpUnusedLocalVariableInspection */
480 $silenceScope = $this->silenceTransactionProfiler();
481 $db = null; // in case of connection failure
483 $db = $this->getDB( $serverIndex );
484 // (T26425) use a replace if the db supports it instead of
485 // delete/insert to avoid clashes with conflicting keynames
490 'value' => $db->encodeBlob( $this->serialize( $value ) ),
491 'exptime' => $exptime
492 ?
$db->timestamp( $exptime )
493 : $this->getMaxDateTime( $db )
497 'value' => $db->encodeBlob( $casToken ),
498 'exptime > ' . $db->addQuotes( $db->timestamp() )
502 } catch ( DBQueryError
$e ) {
503 $this->handleWriteError( $e, $db, $serverIndex );
508 return (bool)$db->affectedRows();
511 public function doDeleteMulti( array $keys, $flags = 0 ) {
512 return $this->modifyMulti(
513 array_fill_keys( $keys, null ),
520 protected function doDelete( $key, $flags = 0 ) {
521 return $this->modifyMulti( [ $key => null ], 0, $flags, self
::$OP_DELETE );
524 public function incr( $key, $step = 1 ) {
525 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
528 /** @noinspection PhpUnusedLocalVariableInspection */
529 $silenceScope = $this->silenceTransactionProfiler();
530 $db = null; // in case of connection failure
532 $db = $this->getDB( $serverIndex );
533 $encTimestamp = $db->addQuotes( $db->timestamp() );
536 [ 'value = value + ' . (int)$step ],
537 [ 'keyname' => $key, "exptime > $encTimestamp" ],
540 if ( $db->affectedRows() > 0 ) {
541 $newValue = $db->selectField(
544 [ 'keyname' => $key, "exptime > $encTimestamp" ],
547 if ( $this->isInteger( $newValue ) ) {
548 $newCount = (int)$newValue;
551 } catch ( DBError
$e ) {
552 $this->handleWriteError( $e, $db, $serverIndex );
558 public function merge( $key, callable
$callback, $exptime = 0, $attempts = 10, $flags = 0 ) {
559 $ok = $this->mergeViaCas( $key, $callback, $exptime, $attempts, $flags );
560 if ( ( $flags & self
::WRITE_SYNC
) == self
::WRITE_SYNC
) {
561 $ok = $this->waitForReplication() && $ok;
567 public function changeTTLMulti( array $keys, $exptime, $flags = 0 ) {
568 return $this->modifyMulti(
569 array_fill_keys( $keys, null ),
576 protected function doChangeTTL( $key, $exptime, $flags ) {
577 return $this->modifyMulti( [ $key => null ], $exptime, $flags, self
::$OP_TOUCH );
581 * @param IDatabase $db
582 * @param string $exptime
585 protected function isExpired( $db, $exptime ) {
587 $exptime != $this->getMaxDateTime( $db ) &&
588 wfTimestamp( TS_UNIX
, $exptime ) < time()
593 * @param IDatabase $db
596 protected function getMaxDateTime( $db ) {
597 if ( time() > 0x7fffffff ) {
598 return $db->timestamp( 1 << 62 );
600 return $db->timestamp( 0x7fffffff );
605 * @param IDatabase $db
608 protected function occasionallyGarbageCollect( IDatabase
$db ) {
610 // Random purging is enabled
611 $this->purgePeriod
&&
612 // This is not using a replica DB
613 !$this->replicaOnly
&&
614 // Only purge on one in every $this->purgePeriod writes
615 mt_rand( 0, $this->purgePeriod
- 1 ) == 0 &&
616 // Avoid repeating the delete within a few seconds
617 ( time() - $this->lastGarbageCollect
) > self
::$GARBAGE_COLLECT_DELAY_SEC
619 $garbageCollector = function () use ( $db ) {
620 $this->deleteServerObjectsExpiringBefore( $db, time(), null, $this->purgeLimit
);
621 $this->lastGarbageCollect
= time();
623 if ( $this->asyncHandler
) {
624 $this->lastGarbageCollect
= time(); // avoid duplicate enqueues
625 ( $this->asyncHandler
)( $garbageCollector );
632 public function expireAll() {
633 $this->deleteObjectsExpiringBefore( time() );
636 public function deleteObjectsExpiringBefore(
638 callable
$progressCallback = null,
641 /** @noinspection PhpUnusedLocalVariableInspection */
642 $silenceScope = $this->silenceTransactionProfiler();
644 $serverIndexes = range( 0, $this->numServers
- 1 );
645 shuffle( $serverIndexes );
649 $keysDeletedCount = 0;
650 foreach ( $serverIndexes as $numServersDone => $serverIndex ) {
651 $db = null; // in case of connection failure
653 $db = $this->getDB( $serverIndex );
654 $this->deleteServerObjectsExpiringBefore(
662 } catch ( DBError
$e ) {
663 $this->handleWriteError( $e, $db, $serverIndex );
672 * @param IDatabase $db
673 * @param string|int $timestamp
674 * @param callable|null $progressCallback
676 * @param int $serversDoneCount
677 * @param int &$keysDeletedCount
680 private function deleteServerObjectsExpiringBefore(
685 $serversDoneCount = 0,
686 &$keysDeletedCount = 0
688 $cutoffUnix = wfTimestamp( TS_UNIX
, $timestamp );
689 $shardIndexes = range( 0, $this->shards
- 1 );
690 shuffle( $shardIndexes );
692 foreach ( $shardIndexes as $numShardsDone => $shardIndex ) {
693 $continue = null; // last exptime
694 $lag = null; // purge lag
697 $this->getTableNameByShard( $shardIndex ),
698 [ 'keyname', 'exptime' ],
700 [ 'exptime < ' . $db->addQuotes( $db->timestamp( $cutoffUnix ) ) ],
701 $continue ?
[ 'exptime >= ' . $db->addQuotes( $continue ) ] : []
704 [ 'LIMIT' => min( $limit, 100 ), 'ORDER BY' => 'exptime' ]
707 if ( $res->numRows() ) {
708 $row = $res->current();
709 if ( $lag === null ) {
710 $lag = max( $cutoffUnix - wfTimestamp( TS_UNIX
, $row->exptime
), 1 );
714 foreach ( $res as $row ) {
715 $keys[] = $row->keyname
;
716 $continue = $row->exptime
;
720 $this->getTableNameByShard( $shardIndex ),
722 'exptime < ' . $db->addQuotes( $db->timestamp( $cutoffUnix ) ),
727 $keysDeletedCount +
= $db->affectedRows();
730 if ( is_callable( $progressCallback ) ) {
732 $remainingLag = $cutoffUnix - wfTimestamp( TS_UNIX
, $continue );
733 $processedLag = max( $lag - $remainingLag, 0 );
734 $doneRatio = ( $numShardsDone +
$processedLag / $lag ) / $this->shards
;
739 $overallRatio = ( $doneRatio / $this->numServers
)
740 +
( $serversDoneCount / $this->numServers
);
741 call_user_func( $progressCallback, $overallRatio * 100 );
743 } while ( $res->numRows() && $keysDeletedCount < $limit );
748 * Delete content of shard tables in every server.
749 * Return true if the operation is successful, false otherwise.
752 public function deleteAll() {
753 /** @noinspection PhpUnusedLocalVariableInspection */
754 $silenceScope = $this->silenceTransactionProfiler();
755 for ( $serverIndex = 0; $serverIndex < $this->numServers
; $serverIndex++
) {
756 $db = null; // in case of connection failure
758 $db = $this->getDB( $serverIndex );
759 for ( $i = 0; $i < $this->shards
; $i++
) {
760 $db->delete( $this->getTableNameByShard( $i ), '*', __METHOD__
);
762 } catch ( DBError
$e ) {
763 $this->handleWriteError( $e, $db, $serverIndex );
770 public function lock( $key, $timeout = 6, $expiry = 6, $rclass = '' ) {
771 // Avoid deadlocks and allow lock reentry if specified
772 if ( isset( $this->locks
[$key] ) ) {
773 if ( $rclass != '' && $this->locks
[$key]['class'] === $rclass ) {
774 ++
$this->locks
[$key]['depth'];
781 list( $serverIndex ) = $this->getTableByKey( $key );
783 $db = null; // in case of connection failure
785 $db = $this->getDB( $serverIndex );
786 $ok = $db->lock( $key, __METHOD__
, $timeout );
788 $this->locks
[$key] = [ 'class' => $rclass, 'depth' => 1 ];
791 $this->logger
->warning(
792 __METHOD__
. " failed due to timeout for {key}.",
793 [ 'key' => $key, 'timeout' => $timeout ]
797 } catch ( DBError
$e ) {
798 $this->handleWriteError( $e, $db, $serverIndex );
805 public function unlock( $key ) {
806 if ( !isset( $this->locks
[$key] ) ) {
810 if ( --$this->locks
[$key]['depth'] <= 0 ) {
811 unset( $this->locks
[$key] );
813 list( $serverIndex ) = $this->getTableByKey( $key );
815 $db = null; // in case of connection failure
817 $db = $this->getDB( $serverIndex );
818 $ok = $db->unlock( $key, __METHOD__
);
820 $this->logger
->warning(
821 __METHOD__
. ' failed to release lock for {key}.',
825 } catch ( DBError
$e ) {
826 $this->handleWriteError( $e, $db, $serverIndex );
837 * Serialize an object and, if possible, compress the representation.
838 * On typical message and page data, this can provide a 3X decrease
839 * in storage requirements.
844 protected function serialize( $data ) {
845 if ( is_int( $data ) ) {
849 $serial = serialize( $data );
850 if ( function_exists( 'gzdeflate' ) ) {
851 $serial = gzdeflate( $serial );
858 * Unserialize and, if necessary, decompress an object.
859 * @param string $serial
862 protected function unserialize( $serial ) {
863 if ( $this->isInteger( $serial ) ) {
867 if ( function_exists( 'gzinflate' ) ) {
868 Wikimedia\
suppressWarnings();
869 $decomp = gzinflate( $serial );
870 Wikimedia\restoreWarnings
();
872 if ( $decomp !== false ) {
877 return unserialize( $serial );
881 * Handle a DBError which occurred during a read operation.
883 * @param DBError $exception
884 * @param int $serverIndex
886 protected function handleReadError( DBError
$exception, $serverIndex ) {
887 if ( $exception instanceof DBConnectionError
) {
888 $this->markServerDown( $exception, $serverIndex );
891 $this->setAndLogDBError( $exception );
895 * Handle a DBQueryError which occurred during a write operation.
897 * @param DBError $exception
898 * @param IDatabase|null $db DB handle or null if connection failed
899 * @param int $serverIndex
902 protected function handleWriteError( DBError
$exception, $db, $serverIndex ) {
903 if ( !( $db instanceof IDatabase
) ) {
904 $this->markServerDown( $exception, $serverIndex );
907 $this->setAndLogDBError( $exception );
911 * @param DBError $exception
913 private function setAndLogDBError( DBError
$exception ) {
914 $this->logger
->error( "DBError: {$exception->getMessage()}" );
915 if ( $exception instanceof DBConnectionError
) {
916 $this->setLastError( BagOStuff
::ERR_UNREACHABLE
);
917 $this->logger
->debug( __METHOD__
. ": ignoring connection error" );
919 $this->setLastError( BagOStuff
::ERR_UNEXPECTED
);
920 $this->logger
->debug( __METHOD__
. ": ignoring query error" );
925 * Mark a server down due to a DBConnectionError exception
927 * @param DBError $exception
928 * @param int $serverIndex
930 protected function markServerDown( DBError
$exception, $serverIndex ) {
931 unset( $this->conns
[$serverIndex] ); // bug T103435
933 if ( isset( $this->connFailureTimes
[$serverIndex] ) ) {
934 if ( time() - $this->connFailureTimes
[$serverIndex] >= 60 ) {
935 unset( $this->connFailureTimes
[$serverIndex] );
936 unset( $this->connFailureErrors
[$serverIndex] );
938 $this->logger
->debug( __METHOD__
. ": Server #$serverIndex already down" );
943 $this->logger
->info( __METHOD__
. ": Server #$serverIndex down until " . ( $now +
60 ) );
944 $this->connFailureTimes
[$serverIndex] = $now;
945 $this->connFailureErrors
[$serverIndex] = $exception;
949 * Create shard tables. For use from eval.php.
951 public function createTables() {
952 for ( $serverIndex = 0; $serverIndex < $this->numServers
; $serverIndex++
) {
953 $db = $this->getDB( $serverIndex );
954 if ( $db->getType() !== 'mysql' ) {
955 throw new MWException( __METHOD__
. ' is not supported on this DB server' );
958 for ( $i = 0; $i < $this->shards
; $i++
) {
960 'CREATE TABLE ' . $db->tableName( $this->getTableNameByShard( $i ) ) .
961 ' LIKE ' . $db->tableName( 'objectcache' ),
968 * @return bool Whether the main DB is used, e.g. wfGetDB( DB_MASTER )
970 protected function usesMainDB() {
971 return !$this->serverInfos
;
974 protected function waitForReplication() {
975 if ( !$this->usesMainDB() ) {
976 // Custom DB server list; probably doesn't use replication
980 $lb = MediaWikiServices
::getInstance()->getDBLoadBalancer();
981 if ( $lb->getServerCount() <= 1 ) {
982 return true; // no replica DBs
985 // Main LB is used; wait for any replica DBs to catch up
987 $masterPos = $lb->getMasterPos();
989 return true; // not applicable
992 $loop = new WaitConditionLoop(
993 function () use ( $lb, $masterPos ) {
994 return $lb->waitForAll( $masterPos, 1 );
1000 return ( $loop->invoke() === $loop::CONDITION_REACHED
);
1001 } catch ( DBError
$e ) {
1002 $this->setAndLogDBError( $e );
1009 * Returns a ScopedCallback which resets the silence flag in the transaction profiler when it is
1010 * destroyed on the end of a scope, for example on return or throw
1011 * @return ScopedCallback
1014 protected function silenceTransactionProfiler() {
1015 $trxProfiler = Profiler
::instance()->getTransactionProfiler();
1016 $oldSilenced = $trxProfiler->setSilenced( true );
1017 return new ScopedCallback( function () use ( $trxProfiler, $oldSilenced ) {
1018 $trxProfiler->setSilenced( $oldSilenced );