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\AtEase\AtEase
;
26 use Wikimedia\Rdbms\Database
;
27 use Wikimedia\Rdbms\IDatabase
;
28 use Wikimedia\Rdbms\DBError
;
29 use Wikimedia\Rdbms\DBQueryError
;
30 use Wikimedia\Rdbms\DBConnectionError
;
31 use Wikimedia\Rdbms\IMaintainableDatabase
;
32 use Wikimedia\Rdbms\LoadBalancer
;
33 use Wikimedia\ScopedCallback
;
34 use Wikimedia\WaitConditionLoop
;
37 * Class to store objects in the database
41 class SqlBagOStuff
extends MediumSpecificBagOStuff
{
42 /** @var array[] (server index => server config) */
43 protected $serverInfos;
44 /** @var string[] (server index => tag/host name) */
45 protected $serverTags;
47 protected $numServerShards;
48 /** @var int UNIX timestamp */
49 protected $lastGarbageCollect = 0;
51 protected $purgePeriod = 10;
53 protected $purgeLimit = 100;
55 protected $numTableShards = 1;
57 protected $tableName = 'objectcache';
59 protected $replicaOnly = false;
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 $GC_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->numServerShards
= 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->numServerShards
= count( $this->serverInfos
);
145 // Default to using the main wiki's database servers
146 $this->serverInfos
= false;
147 $this->numServerShards
= 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->numTableShards
= intval( $params['shards'] );
162 // Backwards-compatibility for < 1.34
163 $this->replicaOnly
= $params['replicaOnly'] ??
( $params['slaveOnly'] ??
false );
167 * Get a connection to the specified database
169 * @param int $shardIndex
170 * @return IMaintainableDatabase
171 * @throws MWException
173 private function getConnection( $shardIndex ) {
174 if ( $shardIndex >= $this->numServerShards
) {
175 throw new MWException( __METHOD__
. ": Invalid server index \"$shardIndex\"" );
178 # Don't keep timing out trying to connect for each call if the DB is down
180 isset( $this->connFailureErrors
[$shardIndex] ) &&
181 ( $this->getCurrentTime() - $this->connFailureTimes
[$shardIndex] ) < 60
183 throw $this->connFailureErrors
[$shardIndex];
186 if ( $this->serverInfos
) {
187 if ( !isset( $this->conns
[$shardIndex] ) ) {
188 // Use custom database defined by server connection info
189 $info = $this->serverInfos
[$shardIndex];
190 $type = $info['type'] ??
'mysql';
191 $host = $info['host'] ??
'[unknown]';
192 $this->logger
->debug( __CLASS__
. ": connecting to $host" );
193 $db = Database
::factory( $type, $info );
194 $db->clearFlag( DBO_TRX
); // auto-commit mode
195 $this->conns
[$shardIndex] = $db;
197 $db = $this->conns
[$shardIndex];
199 // Use the main LB database
200 $lb = MediaWikiServices
::getInstance()->getDBLoadBalancer();
201 $index = $this->replicaOnly ? DB_REPLICA
: DB_MASTER
;
202 if ( $lb->getServerType( $lb->getWriterIndex() ) !== 'sqlite' ) {
203 // Keep a separate connection to avoid contention and deadlocks
204 $db = $lb->getConnectionRef( $index, [], false, $lb::CONN_TRX_AUTOCOMMIT
);
206 // However, SQLite has the opposite behavior due to DB-level locking.
207 // Stock sqlite MediaWiki installs use a separate sqlite cache DB instead.
208 $db = $lb->getConnectionRef( $index );
212 $this->logger
->debug( sprintf( "Connection %s will be used for SqlBagOStuff", $db ) );
218 * Get the server index and table name for a given key
220 * @return array Server index and table name
222 private function getTableByKey( $key ) {
223 if ( $this->numTableShards
> 1 ) {
224 $hash = hexdec( substr( md5( $key ), 0, 8 ) ) & 0x7fffffff;
225 $tableIndex = $hash %
$this->numTableShards
;
229 if ( $this->numServerShards
> 1 ) {
230 $sortedServers = $this->serverTags
;
231 ArrayUtils
::consistentHashSort( $sortedServers, $key );
232 reset( $sortedServers );
233 $shardIndex = key( $sortedServers );
237 return [ $shardIndex, $this->getTableNameByShard( $tableIndex ) ];
241 * Get the table name for a given shard index
245 private function getTableNameByShard( $index ) {
246 if ( $this->numTableShards
> 1 ) {
247 $decimals = strlen( $this->numTableShards
- 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 private function fetchBlobMulti( array $keys, $flags = 0 ) {
283 $values = []; // array of (key => value)
286 foreach ( $keys as $key ) {
287 list( $shardIndex, $tableName ) = $this->getTableByKey( $key );
288 $keysByTable[$shardIndex][$tableName][] = $key;
292 foreach ( $keysByTable as $shardIndex => $serverKeys ) {
294 $db = $this->getConnection( $shardIndex );
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->shardIndex
= $shardIndex;
310 $row->tableName
= $tableName;
311 $dataRows[$row->keyname
] = $row;
314 } catch ( DBError
$e ) {
315 $this->handleReadError( $e, $shardIndex );
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->getConnection( $row->shardIndex
);
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->shardIndex
);
335 $this->debug( 'get: no matching rows' );
342 protected 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( $shardIndex, $tableName ) = $this->getTableByKey( $key );
357 $keysByTable[$shardIndex][$tableName][] = $key;
360 $exptime = $this->getExpirationAsTimestamp( $exptime );
363 /** @noinspection PhpUnusedLocalVariableInspection */
364 $silenceScope = $this->silenceTransactionProfiler();
365 foreach ( $keysByTable as $shardIndex => $serverKeys ) {
366 $db = null; // in case of connection failure
368 $db = $this->getConnection( $shardIndex );
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, $shardIndex );
377 foreach ( $serverKeys as $tableName => $tableKeys ) {
379 $result = $this->updateTableKeys(
387 } catch ( DBError
$e ) {
388 $this->handleWriteError( $e, $db, $shardIndex );
395 if ( $this->fieldHasFlags( $flags, 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 protected function doAdd( $key, $value, $exptime = 0, $flags = 0 ) {
472 return $this->modifyMulti( [ $key => $value ], $exptime, $flags, self
::$OP_ADD );
475 protected function doCas( $casToken, $key, $value, $exptime = 0, $flags = 0 ) {
476 list( $shardIndex, $tableName ) = $this->getTableByKey( $key );
477 $exptime = $this->getExpirationAsTimestamp( $exptime );
479 /** @noinspection PhpUnusedLocalVariableInspection */
480 $silenceScope = $this->silenceTransactionProfiler();
481 $db = null; // in case of connection failure
483 $db = $this->getConnection( $shardIndex );
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, $shardIndex );
508 $success = (bool)$db->affectedRows();
509 if ( $this->fieldHasFlags( $flags, self
::WRITE_SYNC
) ) {
510 $success = $this->waitForReplication() && $success;
516 protected function doDeleteMulti( array $keys, $flags = 0 ) {
517 return $this->modifyMulti(
518 array_fill_keys( $keys, null ),
525 protected function doDelete( $key, $flags = 0 ) {
526 return $this->modifyMulti( [ $key => null ], 0, $flags, self
::$OP_DELETE );
529 public function incr( $key, $step = 1, $flags = 0 ) {
530 list( $shardIndex, $tableName ) = $this->getTableByKey( $key );
533 /** @noinspection PhpUnusedLocalVariableInspection */
534 $silenceScope = $this->silenceTransactionProfiler();
535 $db = null; // in case of connection failure
537 $db = $this->getConnection( $shardIndex );
538 $encTimestamp = $db->addQuotes( $db->timestamp() );
541 [ 'value = value + ' . (int)$step ],
542 [ 'keyname' => $key, "exptime > $encTimestamp" ],
545 if ( $db->affectedRows() > 0 ) {
546 $newValue = $db->selectField(
549 [ 'keyname' => $key, "exptime > $encTimestamp" ],
552 if ( $this->isInteger( $newValue ) ) {
553 $newCount = (int)$newValue;
556 } catch ( DBError
$e ) {
557 $this->handleWriteError( $e, $db, $shardIndex );
563 public function decr( $key, $value = 1, $flags = 0 ) {
564 return $this->incr( $key, -$value, $flags );
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 private function isExpired( $db, $exptime ) {
587 $exptime != $this->getMaxDateTime( $db ) &&
588 wfTimestamp( TS_UNIX
, $exptime ) < $this->getCurrentTime()
593 * @param IDatabase $db
596 private function getMaxDateTime( $db ) {
597 if ( (int)$this->getCurrentTime() > 0x7fffffff ) {
598 return $db->timestamp( 1 << 62 );
600 return $db->timestamp( 0x7fffffff );
605 * @param IDatabase $db
608 private function occasionallyGarbageCollect( IDatabase
$db ) {
610 // Random purging is enabled
611 $this->purgePeriod
&&
612 // Only purge on one in every $this->purgePeriod writes
613 mt_rand( 0, $this->purgePeriod
- 1 ) == 0 &&
614 // Avoid repeating the delete within a few seconds
615 ( $this->getCurrentTime() - $this->lastGarbageCollect
) > self
::$GC_DELAY_SEC
617 $garbageCollector = function () use ( $db ) {
618 $this->deleteServerObjectsExpiringBefore(
619 $db, $this->getCurrentTime(),
623 $this->lastGarbageCollect
= time();
625 if ( $this->asyncHandler
) {
626 $this->lastGarbageCollect
= $this->getCurrentTime(); // avoid duplicate enqueues
627 ( $this->asyncHandler
)( $garbageCollector );
634 public function expireAll() {
635 $this->deleteObjectsExpiringBefore( $this->getCurrentTime() );
638 public function deleteObjectsExpiringBefore(
640 callable
$progress = null,
643 /** @noinspection PhpUnusedLocalVariableInspection */
644 $silenceScope = $this->silenceTransactionProfiler();
646 $shardIndexes = range( 0, $this->numServerShards
- 1 );
647 shuffle( $shardIndexes );
651 $keysDeletedCount = 0;
652 foreach ( $shardIndexes as $numServersDone => $shardIndex ) {
653 $db = null; // in case of connection failure
655 $db = $this->getConnection( $shardIndex );
656 $this->deleteServerObjectsExpiringBefore(
664 } catch ( DBError
$e ) {
665 $this->handleWriteError( $e, $db, $shardIndex );
674 * @param IDatabase $db
675 * @param string|int $timestamp
676 * @param callable|null $progressCallback
678 * @param int $serversDoneCount
679 * @param int &$keysDeletedCount
682 private function deleteServerObjectsExpiringBefore(
687 $serversDoneCount = 0,
688 &$keysDeletedCount = 0
690 $cutoffUnix = wfTimestamp( TS_UNIX
, $timestamp );
691 $shardIndexes = range( 0, $this->numTableShards
- 1 );
692 shuffle( $shardIndexes );
694 foreach ( $shardIndexes as $numShardsDone => $shardIndex ) {
695 $continue = null; // last exptime
696 $lag = null; // purge lag
699 $this->getTableNameByShard( $shardIndex ),
700 [ 'keyname', 'exptime' ],
702 [ 'exptime < ' . $db->addQuotes( $db->timestamp( $cutoffUnix ) ) ],
703 $continue ?
[ 'exptime >= ' . $db->addQuotes( $continue ) ] : []
706 [ 'LIMIT' => min( $limit, 100 ), 'ORDER BY' => 'exptime' ]
709 if ( $res->numRows() ) {
710 $row = $res->current();
711 if ( $lag === null ) {
712 $lag = max( $cutoffUnix - wfTimestamp( TS_UNIX
, $row->exptime
), 1 );
716 foreach ( $res as $row ) {
717 $keys[] = $row->keyname
;
718 $continue = $row->exptime
;
722 $this->getTableNameByShard( $shardIndex ),
724 'exptime < ' . $db->addQuotes( $db->timestamp( $cutoffUnix ) ),
729 $keysDeletedCount +
= $db->affectedRows();
732 if ( is_callable( $progressCallback ) ) {
734 $remainingLag = $cutoffUnix - wfTimestamp( TS_UNIX
, $continue );
735 $processedLag = max( $lag - $remainingLag, 0 );
736 $doneRatio = ( $numShardsDone +
$processedLag / $lag ) / $this->numTableShards
;
741 $overallRatio = ( $doneRatio / $this->numServerShards
)
742 +
( $serversDoneCount / $this->numServerShards
);
743 call_user_func( $progressCallback, $overallRatio * 100 );
745 } while ( $res->numRows() && $keysDeletedCount < $limit );
750 * Delete content of shard tables in every server.
751 * Return true if the operation is successful, false otherwise.
754 public function deleteAll() {
755 /** @noinspection PhpUnusedLocalVariableInspection */
756 $silenceScope = $this->silenceTransactionProfiler();
757 for ( $shardIndex = 0; $shardIndex < $this->numServerShards
; $shardIndex++
) {
758 $db = null; // in case of connection failure
760 $db = $this->getConnection( $shardIndex );
761 for ( $i = 0; $i < $this->numTableShards
; $i++
) {
762 $db->delete( $this->getTableNameByShard( $i ), '*', __METHOD__
);
764 } catch ( DBError
$e ) {
765 $this->handleWriteError( $e, $db, $shardIndex );
772 public function lock( $key, $timeout = 6, $expiry = 6, $rclass = '' ) {
773 // Avoid deadlocks and allow lock reentry if specified
774 if ( isset( $this->locks
[$key] ) ) {
775 if ( $rclass != '' && $this->locks
[$key]['class'] === $rclass ) {
776 ++
$this->locks
[$key]['depth'];
783 list( $shardIndex ) = $this->getTableByKey( $key );
785 $db = null; // in case of connection failure
787 $db = $this->getConnection( $shardIndex );
788 $ok = $db->lock( $key, __METHOD__
, $timeout );
790 $this->locks
[$key] = [ 'class' => $rclass, 'depth' => 1 ];
793 $this->logger
->warning(
794 __METHOD__
. " failed due to timeout for {key}.",
795 [ 'key' => $key, 'timeout' => $timeout ]
799 } catch ( DBError
$e ) {
800 $this->handleWriteError( $e, $db, $shardIndex );
807 public function unlock( $key ) {
808 if ( !isset( $this->locks
[$key] ) ) {
812 if ( --$this->locks
[$key]['depth'] <= 0 ) {
813 unset( $this->locks
[$key] );
815 list( $shardIndex ) = $this->getTableByKey( $key );
817 $db = null; // in case of connection failure
819 $db = $this->getConnection( $shardIndex );
820 $ok = $db->unlock( $key, __METHOD__
);
822 $this->logger
->warning(
823 __METHOD__
. ' failed to release lock for {key}.',
827 } catch ( DBError
$e ) {
828 $this->handleWriteError( $e, $db, $shardIndex );
839 * Serialize an object and, if possible, compress the representation.
840 * On typical message and page data, this can provide a 3X decrease
841 * in storage requirements.
846 protected function serialize( $data ) {
847 if ( is_int( $data ) ) {
851 $serial = serialize( $data );
852 if ( function_exists( 'gzdeflate' ) ) {
853 $serial = gzdeflate( $serial );
860 * Unserialize and, if necessary, decompress an object.
861 * @param string $serial
864 protected function unserialize( $serial ) {
865 if ( $this->isInteger( $serial ) ) {
869 if ( function_exists( 'gzinflate' ) ) {
870 AtEase
::suppressWarnings();
871 $decomp = gzinflate( $serial );
872 AtEase
::restoreWarnings();
874 if ( $decomp !== false ) {
879 return unserialize( $serial );
883 * Handle a DBError which occurred during a read operation.
885 * @param DBError $exception
886 * @param int $shardIndex
888 private function handleReadError( DBError
$exception, $shardIndex ) {
889 if ( $exception instanceof DBConnectionError
) {
890 $this->markServerDown( $exception, $shardIndex );
893 $this->setAndLogDBError( $exception );
897 * Handle a DBQueryError which occurred during a write operation.
899 * @param DBError $exception
900 * @param IDatabase|null $db DB handle or null if connection failed
901 * @param int $shardIndex
904 private function handleWriteError( DBError
$exception, $db, $shardIndex ) {
905 if ( !( $db instanceof IDatabase
) ) {
906 $this->markServerDown( $exception, $shardIndex );
909 $this->setAndLogDBError( $exception );
913 * @param DBError $exception
915 private function setAndLogDBError( DBError
$exception ) {
916 $this->logger
->error( "DBError: {$exception->getMessage()}" );
917 if ( $exception instanceof DBConnectionError
) {
918 $this->setLastError( BagOStuff
::ERR_UNREACHABLE
);
919 $this->logger
->debug( __METHOD__
. ": ignoring connection error" );
921 $this->setLastError( BagOStuff
::ERR_UNEXPECTED
);
922 $this->logger
->debug( __METHOD__
. ": ignoring query error" );
927 * Mark a server down due to a DBConnectionError exception
929 * @param DBError $exception
930 * @param int $shardIndex
932 private function markServerDown( DBError
$exception, $shardIndex ) {
933 unset( $this->conns
[$shardIndex] ); // bug T103435
935 $now = $this->getCurrentTime();
936 if ( isset( $this->connFailureTimes
[$shardIndex] ) ) {
937 if ( $now - $this->connFailureTimes
[$shardIndex] >= 60 ) {
938 unset( $this->connFailureTimes
[$shardIndex] );
939 unset( $this->connFailureErrors
[$shardIndex] );
941 $this->logger
->debug( __METHOD__
. ": Server #$shardIndex already down" );
945 $this->logger
->info( __METHOD__
. ": Server #$shardIndex down until " . ( $now +
60 ) );
946 $this->connFailureTimes
[$shardIndex] = $now;
947 $this->connFailureErrors
[$shardIndex] = $exception;
951 * Create shard tables. For use from eval.php.
953 public function createTables() {
954 for ( $shardIndex = 0; $shardIndex < $this->numServerShards
; $shardIndex++
) {
955 $db = $this->getConnection( $shardIndex );
956 if ( $db->getType() !== 'mysql' ) {
957 throw new MWException( __METHOD__
. ' is not supported on this DB server' );
960 for ( $i = 0; $i < $this->numTableShards
; $i++
) {
962 'CREATE TABLE ' . $db->tableName( $this->getTableNameByShard( $i ) ) .
963 ' LIKE ' . $db->tableName( 'objectcache' ),
970 * @return bool Whether the main DB is used, e.g. wfGetDB( DB_MASTER )
972 private function usesMainDB() {
973 return !$this->serverInfos
;
976 private function waitForReplication() {
977 if ( !$this->usesMainDB() ) {
978 // Custom DB server list; probably doesn't use replication
982 $lb = MediaWikiServices
::getInstance()->getDBLoadBalancer();
983 if ( $lb->getServerCount() <= 1 ) {
984 return true; // no replica DBs
987 // Main LB is used; wait for any replica DBs to catch up
989 $masterPos = $lb->getMasterPos();
991 return true; // not applicable
994 $loop = new WaitConditionLoop(
995 function () use ( $lb, $masterPos ) {
996 return $lb->waitForAll( $masterPos, 1 );
1002 return ( $loop->invoke() === $loop::CONDITION_REACHED
);
1003 } catch ( DBError
$e ) {
1004 $this->setAndLogDBError( $e );
1011 * Silence the transaction profiler until the return value falls out of scope
1013 * @return ScopedCallback|null
1015 private function silenceTransactionProfiler() {
1016 if ( !$this->usesMainDB() ) {
1017 // Custom DB is configured which either has no TransactionProfiler injected,
1018 // or has one specific for cache use, which we shouldn't silence
1022 $trxProfiler = Profiler
::instance()->getTransactionProfiler();
1023 $oldSilenced = $trxProfiler->setSilenced( true );
1024 return new ScopedCallback( function () use ( $trxProfiler, $oldSilenced ) {
1025 $trxProfiler->setSilenced( $oldSilenced );