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 ( $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
183 isset( $this->connFailureErrors
[$serverIndex] ) &&
184 ( time() - $this->connFailureTimes
[$serverIndex] ) < 60
186 throw $this->connFailureErrors
[$serverIndex];
189 if ( $this->serverInfos
) {
190 if ( !isset( $this->conns
[$serverIndex] ) ) {
191 // Use custom database defined by server connection info
192 $info = $this->serverInfos
[$serverIndex];
193 $type = $info['type'] ??
'mysql';
194 $host = $info['host'] ??
'[unknown]';
195 $this->logger
->debug( __CLASS__
. ": connecting to $host" );
196 $db = Database
::factory( $type, $info );
197 $db->clearFlag( DBO_TRX
); // auto-commit mode
198 $this->conns
[$serverIndex] = $db;
200 $db = $this->conns
[$serverIndex];
202 // Use the main LB database
203 $lb = MediaWikiServices
::getInstance()->getDBLoadBalancer();
204 $index = $this->replicaOnly ? DB_REPLICA
: DB_MASTER
;
205 if ( $lb->getServerType( $lb->getWriterIndex() ) !== 'sqlite' ) {
206 // Keep a separate connection to avoid contention and deadlocks
207 $db = $lb->getConnection( $index, [], false, $lb::CONN_TRX_AUTOCOMMIT
);
209 // However, SQLite has the opposite behavior due to DB-level locking.
210 // Stock sqlite MediaWiki installs use a separate sqlite cache DB instead.
211 $db = $lb->getConnection( $index );
215 $this->logger
->debug( sprintf( "Connection %s will be used for SqlBagOStuff", $db ) );
221 * Get the server index and table name for a given key
223 * @return array Server index and table name
225 protected function getTableByKey( $key ) {
226 if ( $this->shards
> 1 ) {
227 $hash = hexdec( substr( md5( $key ), 0, 8 ) ) & 0x7fffffff;
228 $tableIndex = $hash %
$this->shards
;
232 if ( $this->numServers
> 1 ) {
233 $sortedServers = $this->serverTags
;
234 ArrayUtils
::consistentHashSort( $sortedServers, $key );
235 reset( $sortedServers );
236 $serverIndex = key( $sortedServers );
240 return [ $serverIndex, $this->getTableNameByShard( $tableIndex ) ];
244 * Get the table name for a given shard index
248 protected function getTableNameByShard( $index ) {
249 if ( $this->shards
> 1 ) {
250 $decimals = strlen( $this->shards
- 1 );
251 return $this->tableName
.
252 sprintf( "%0{$decimals}d", $index );
254 return $this->tableName
;
258 protected function doGet( $key, $flags = 0, &$casToken = null ) {
261 $blobs = $this->fetchBlobMulti( [ $key ] );
262 if ( array_key_exists( $key, $blobs ) ) {
263 $blob = $blobs[$key];
264 $value = $this->unserialize( $blob );
266 $casToken = ( $value !== false ) ?
$blob : null;
274 protected function doGetMulti( array $keys, $flags = 0 ) {
277 $blobs = $this->fetchBlobMulti( $keys );
278 foreach ( $blobs as $key => $blob ) {
279 $values[$key] = $this->unserialize( $blob );
285 protected function fetchBlobMulti( array $keys, $flags = 0 ) {
286 $values = []; // array of (key => value)
289 foreach ( $keys as $key ) {
290 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
291 $keysByTable[$serverIndex][$tableName][] = $key;
295 foreach ( $keysByTable as $serverIndex => $serverKeys ) {
297 $db = $this->getDB( $serverIndex );
298 foreach ( $serverKeys as $tableName => $tableKeys ) {
299 $res = $db->select( $tableName,
300 [ 'keyname', 'value', 'exptime' ],
301 [ 'keyname' => $tableKeys ],
303 // Approximate write-on-the-fly BagOStuff API via blocking.
304 // This approximation fails if a ROLLBACK happens (which is rare).
305 // We do not want to flush the TRX as that can break callers.
306 $db->trxLevel() ?
[ 'LOCK IN SHARE MODE' ] : []
308 if ( $res === false ) {
311 foreach ( $res as $row ) {
312 $row->serverIndex
= $serverIndex;
313 $row->tableName
= $tableName;
314 $dataRows[$row->keyname
] = $row;
317 } catch ( DBError
$e ) {
318 $this->handleReadError( $e, $serverIndex );
322 foreach ( $keys as $key ) {
323 if ( isset( $dataRows[$key] ) ) { // HIT?
324 $row = $dataRows[$key];
325 $this->debug( "get: retrieved data; expiry time is " . $row->exptime
);
326 $db = null; // in case of connection failure
328 $db = $this->getDB( $row->serverIndex
);
329 if ( $this->isExpired( $db, $row->exptime
) ) { // MISS
330 $this->debug( "get: key has expired" );
332 $values[$key] = $db->decodeBlob( $row->value
);
334 } catch ( DBQueryError
$e ) {
335 $this->handleWriteError( $e, $db, $row->serverIndex
);
338 $this->debug( 'get: no matching rows' );
345 protected function doSetMulti( array $data, $exptime = 0, $flags = 0 ) {
346 return $this->modifyMulti( $data, $exptime, $flags, self
::$OP_SET );
350 * @param mixed[]|null[] $data Map of (key => new value or null)
351 * @param int $exptime UNIX timestamp, TTL in seconds, or 0 (no expiration)
352 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
353 * @param string $op Cache operation
356 private function modifyMulti( array $data, $exptime, $flags, $op ) {
358 foreach ( $data as $key => $value ) {
359 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
360 $keysByTable[$serverIndex][$tableName][] = $key;
363 $exptime = $this->convertToExpiry( $exptime );
366 /** @noinspection PhpUnusedLocalVariableInspection */
367 $silenceScope = $this->silenceTransactionProfiler();
368 foreach ( $keysByTable as $serverIndex => $serverKeys ) {
369 $db = null; // in case of connection failure
371 $db = $this->getDB( $serverIndex );
372 $this->occasionallyGarbageCollect( $db ); // expire old entries if any
373 $dbExpiry = $exptime ?
$db->timestamp( $exptime ) : $this->getMaxDateTime( $db );
374 } catch ( DBError
$e ) {
375 $this->handleWriteError( $e, $db, $serverIndex );
380 foreach ( $serverKeys as $tableName => $tableKeys ) {
382 $result = $this->updateTableKeys(
390 } catch ( DBError
$e ) {
391 $this->handleWriteError( $e, $db, $serverIndex );
398 if ( ( $flags & self
::WRITE_SYNC
) == self
::WRITE_SYNC
) {
399 $result = $this->waitForReplication() && $result;
407 * @param IDatabase $db
408 * @param string $table
409 * @param string[] $tableKeys Keys in $data to update
410 * @param mixed[]|null[] $data Map of (key => new value or null)
411 * @param string $dbExpiry DB-encoded expiry
414 * @throws InvalidArgumentException
416 private function updateTableKeys( $op, $db, $table, $tableKeys, $data, $dbExpiry ) {
419 if ( $op === self
::$OP_ADD ) {
421 foreach ( $tableKeys as $key ) {
424 'value' => $db->encodeBlob( $this->serialize( $data[$key] ) ),
425 'exptime' => $dbExpiry
431 'keyname' => $tableKeys,
432 'exptime <= ' . $db->addQuotes( $db->timestamp() )
436 $db->insert( $table, $rows, __METHOD__
, [ 'IGNORE' ] );
438 $success = ( $db->affectedRows() == count( $rows ) );
439 } elseif ( $op === self
::$OP_SET ) {
441 foreach ( $tableKeys as $key ) {
444 'value' => $db->encodeBlob( $this->serialize( $data[$key] ) ),
445 'exptime' => $dbExpiry
448 $db->replace( $table, [ 'keyname' ], $rows, __METHOD__
);
449 } elseif ( $op === self
::$OP_DELETE ) {
450 $db->delete( $table, [ 'keyname' => $tableKeys ], __METHOD__
);
451 } elseif ( $op === self
::$OP_TOUCH ) {
454 [ 'exptime' => $dbExpiry ],
456 'keyname' => $tableKeys,
457 'exptime > ' . $db->addQuotes( $db->timestamp() )
462 $success = ( $db->affectedRows() == count( $tableKeys ) );
464 throw new InvalidArgumentException( "Invalid operation '$op'" );
470 protected function doSet( $key, $value, $exptime = 0, $flags = 0 ) {
471 return $this->modifyMulti( [ $key => $value ], $exptime, $flags, self
::$OP_SET );
474 public function add( $key, $value, $exptime = 0, $flags = 0 ) {
475 return $this->modifyMulti( [ $key => $value ], $exptime, $flags, self
::$OP_ADD );
478 protected function cas( $casToken, $key, $value, $exptime = 0, $flags = 0 ) {
479 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
480 $exptime = $this->convertToExpiry( $exptime );
482 /** @noinspection PhpUnusedLocalVariableInspection */
483 $silenceScope = $this->silenceTransactionProfiler();
484 $db = null; // in case of connection failure
486 $db = $this->getDB( $serverIndex );
487 // (T26425) use a replace if the db supports it instead of
488 // delete/insert to avoid clashes with conflicting keynames
493 'value' => $db->encodeBlob( $this->serialize( $value ) ),
494 'exptime' => $exptime
495 ?
$db->timestamp( $exptime )
496 : $this->getMaxDateTime( $db )
500 'value' => $db->encodeBlob( $casToken ),
501 'exptime > ' . $db->addQuotes( $db->timestamp() )
505 } catch ( DBQueryError
$e ) {
506 $this->handleWriteError( $e, $db, $serverIndex );
511 return (bool)$db->affectedRows();
514 protected function doDeleteMulti( array $keys, $flags = 0 ) {
515 return $this->modifyMulti(
516 array_fill_keys( $keys, null ),
523 protected function doDelete( $key, $flags = 0 ) {
524 return $this->modifyMulti( [ $key => null ], 0, $flags, self
::$OP_DELETE );
527 public function incr( $key, $step = 1 ) {
528 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
531 /** @noinspection PhpUnusedLocalVariableInspection */
532 $silenceScope = $this->silenceTransactionProfiler();
533 $db = null; // in case of connection failure
535 $db = $this->getDB( $serverIndex );
536 $encTimestamp = $db->addQuotes( $db->timestamp() );
539 [ 'value = value + ' . (int)$step ],
540 [ 'keyname' => $key, "exptime > $encTimestamp" ],
543 if ( $db->affectedRows() > 0 ) {
544 $newValue = $db->selectField(
547 [ 'keyname' => $key, "exptime > $encTimestamp" ],
550 if ( $this->isInteger( $newValue ) ) {
551 $newCount = (int)$newValue;
554 } catch ( DBError
$e ) {
555 $this->handleWriteError( $e, $db, $serverIndex );
561 public function merge( $key, callable
$callback, $exptime = 0, $attempts = 10, $flags = 0 ) {
562 $ok = $this->mergeViaCas( $key, $callback, $exptime, $attempts, $flags );
563 if ( ( $flags & self
::WRITE_SYNC
) == self
::WRITE_SYNC
) {
564 $ok = $this->waitForReplication() && $ok;
570 protected function doChangeTTLMulti( array $keys, $exptime, $flags = 0 ) {
571 return $this->modifyMulti(
572 array_fill_keys( $keys, null ),
579 protected function doChangeTTL( $key, $exptime, $flags ) {
580 return $this->modifyMulti( [ $key => null ], $exptime, $flags, self
::$OP_TOUCH );
584 * @param IDatabase $db
585 * @param string $exptime
588 protected function isExpired( $db, $exptime ) {
590 $exptime != $this->getMaxDateTime( $db ) &&
591 wfTimestamp( TS_UNIX
, $exptime ) < time()
596 * @param IDatabase $db
599 protected function getMaxDateTime( $db ) {
600 if ( time() > 0x7fffffff ) {
601 return $db->timestamp( 1 << 62 );
603 return $db->timestamp( 0x7fffffff );
608 * @param IDatabase $db
611 protected function occasionallyGarbageCollect( IDatabase
$db ) {
613 // Random purging is enabled
614 $this->purgePeriod
&&
615 // Only purge on one in every $this->purgePeriod writes
616 mt_rand( 0, $this->purgePeriod
- 1 ) == 0 &&
617 // Avoid repeating the delete within a few seconds
618 ( time() - $this->lastGarbageCollect
) > self
::$GARBAGE_COLLECT_DELAY_SEC
620 $garbageCollector = function () use ( $db ) {
621 $this->deleteServerObjectsExpiringBefore( $db, time(), null, $this->purgeLimit
);
622 $this->lastGarbageCollect
= time();
624 if ( $this->asyncHandler
) {
625 $this->lastGarbageCollect
= time(); // avoid duplicate enqueues
626 ( $this->asyncHandler
)( $garbageCollector );
633 public function expireAll() {
634 $this->deleteObjectsExpiringBefore( time() );
637 public function deleteObjectsExpiringBefore(
639 callable
$progress = null,
642 /** @noinspection PhpUnusedLocalVariableInspection */
643 $silenceScope = $this->silenceTransactionProfiler();
645 $serverIndexes = range( 0, $this->numServers
- 1 );
646 shuffle( $serverIndexes );
650 $keysDeletedCount = 0;
651 foreach ( $serverIndexes as $numServersDone => $serverIndex ) {
652 $db = null; // in case of connection failure
654 $db = $this->getDB( $serverIndex );
655 $this->deleteServerObjectsExpiringBefore(
663 } catch ( DBError
$e ) {
664 $this->handleWriteError( $e, $db, $serverIndex );
673 * @param IDatabase $db
674 * @param string|int $timestamp
675 * @param callable|null $progressCallback
677 * @param int $serversDoneCount
678 * @param int &$keysDeletedCount
681 private function deleteServerObjectsExpiringBefore(
686 $serversDoneCount = 0,
687 &$keysDeletedCount = 0
689 $cutoffUnix = wfTimestamp( TS_UNIX
, $timestamp );
690 $shardIndexes = range( 0, $this->shards
- 1 );
691 shuffle( $shardIndexes );
693 foreach ( $shardIndexes as $numShardsDone => $shardIndex ) {
694 $continue = null; // last exptime
695 $lag = null; // purge lag
698 $this->getTableNameByShard( $shardIndex ),
699 [ 'keyname', 'exptime' ],
701 [ 'exptime < ' . $db->addQuotes( $db->timestamp( $cutoffUnix ) ) ],
702 $continue ?
[ 'exptime >= ' . $db->addQuotes( $continue ) ] : []
705 [ 'LIMIT' => min( $limit, 100 ), 'ORDER BY' => 'exptime' ]
708 if ( $res->numRows() ) {
709 $row = $res->current();
710 if ( $lag === null ) {
711 $lag = max( $cutoffUnix - wfTimestamp( TS_UNIX
, $row->exptime
), 1 );
715 foreach ( $res as $row ) {
716 $keys[] = $row->keyname
;
717 $continue = $row->exptime
;
721 $this->getTableNameByShard( $shardIndex ),
723 'exptime < ' . $db->addQuotes( $db->timestamp( $cutoffUnix ) ),
728 $keysDeletedCount +
= $db->affectedRows();
731 if ( is_callable( $progressCallback ) ) {
733 $remainingLag = $cutoffUnix - wfTimestamp( TS_UNIX
, $continue );
734 $processedLag = max( $lag - $remainingLag, 0 );
735 $doneRatio = ( $numShardsDone +
$processedLag / $lag ) / $this->shards
;
740 $overallRatio = ( $doneRatio / $this->numServers
)
741 +
( $serversDoneCount / $this->numServers
);
742 call_user_func( $progressCallback, $overallRatio * 100 );
744 } while ( $res->numRows() && $keysDeletedCount < $limit );
749 * Delete content of shard tables in every server.
750 * Return true if the operation is successful, false otherwise.
753 public function deleteAll() {
754 /** @noinspection PhpUnusedLocalVariableInspection */
755 $silenceScope = $this->silenceTransactionProfiler();
756 for ( $serverIndex = 0; $serverIndex < $this->numServers
; $serverIndex++
) {
757 $db = null; // in case of connection failure
759 $db = $this->getDB( $serverIndex );
760 for ( $i = 0; $i < $this->shards
; $i++
) {
761 $db->delete( $this->getTableNameByShard( $i ), '*', __METHOD__
);
763 } catch ( DBError
$e ) {
764 $this->handleWriteError( $e, $db, $serverIndex );
771 public function lock( $key, $timeout = 6, $expiry = 6, $rclass = '' ) {
772 // Avoid deadlocks and allow lock reentry if specified
773 if ( isset( $this->locks
[$key] ) ) {
774 if ( $rclass != '' && $this->locks
[$key]['class'] === $rclass ) {
775 ++
$this->locks
[$key]['depth'];
782 list( $serverIndex ) = $this->getTableByKey( $key );
784 $db = null; // in case of connection failure
786 $db = $this->getDB( $serverIndex );
787 $ok = $db->lock( $key, __METHOD__
, $timeout );
789 $this->locks
[$key] = [ 'class' => $rclass, 'depth' => 1 ];
792 $this->logger
->warning(
793 __METHOD__
. " failed due to timeout for {key}.",
794 [ 'key' => $key, 'timeout' => $timeout ]
798 } catch ( DBError
$e ) {
799 $this->handleWriteError( $e, $db, $serverIndex );
806 public function unlock( $key ) {
807 if ( !isset( $this->locks
[$key] ) ) {
811 if ( --$this->locks
[$key]['depth'] <= 0 ) {
812 unset( $this->locks
[$key] );
814 list( $serverIndex ) = $this->getTableByKey( $key );
816 $db = null; // in case of connection failure
818 $db = $this->getDB( $serverIndex );
819 $ok = $db->unlock( $key, __METHOD__
);
821 $this->logger
->warning(
822 __METHOD__
. ' failed to release lock for {key}.',
826 } catch ( DBError
$e ) {
827 $this->handleWriteError( $e, $db, $serverIndex );
838 * Serialize an object and, if possible, compress the representation.
839 * On typical message and page data, this can provide a 3X decrease
840 * in storage requirements.
845 protected function serialize( $data ) {
846 if ( is_int( $data ) ) {
850 $serial = serialize( $data );
851 if ( function_exists( 'gzdeflate' ) ) {
852 $serial = gzdeflate( $serial );
859 * Unserialize and, if necessary, decompress an object.
860 * @param string $serial
863 protected function unserialize( $serial ) {
864 if ( $this->isInteger( $serial ) ) {
868 if ( function_exists( 'gzinflate' ) ) {
869 Wikimedia\
suppressWarnings();
870 $decomp = gzinflate( $serial );
871 Wikimedia\restoreWarnings
();
873 if ( $decomp !== false ) {
878 return unserialize( $serial );
882 * Handle a DBError which occurred during a read operation.
884 * @param DBError $exception
885 * @param int $serverIndex
887 protected function handleReadError( DBError
$exception, $serverIndex ) {
888 if ( $exception instanceof DBConnectionError
) {
889 $this->markServerDown( $exception, $serverIndex );
892 $this->setAndLogDBError( $exception );
896 * Handle a DBQueryError which occurred during a write operation.
898 * @param DBError $exception
899 * @param IDatabase|null $db DB handle or null if connection failed
900 * @param int $serverIndex
903 protected function handleWriteError( DBError
$exception, $db, $serverIndex ) {
904 if ( !( $db instanceof IDatabase
) ) {
905 $this->markServerDown( $exception, $serverIndex );
908 $this->setAndLogDBError( $exception );
912 * @param DBError $exception
914 private function setAndLogDBError( DBError
$exception ) {
915 $this->logger
->error( "DBError: {$exception->getMessage()}" );
916 if ( $exception instanceof DBConnectionError
) {
917 $this->setLastError( BagOStuff
::ERR_UNREACHABLE
);
918 $this->logger
->debug( __METHOD__
. ": ignoring connection error" );
920 $this->setLastError( BagOStuff
::ERR_UNEXPECTED
);
921 $this->logger
->debug( __METHOD__
. ": ignoring query error" );
926 * Mark a server down due to a DBConnectionError exception
928 * @param DBError $exception
929 * @param int $serverIndex
931 protected function markServerDown( DBError
$exception, $serverIndex ) {
932 unset( $this->conns
[$serverIndex] ); // bug T103435
934 if ( isset( $this->connFailureTimes
[$serverIndex] ) ) {
935 if ( time() - $this->connFailureTimes
[$serverIndex] >= 60 ) {
936 unset( $this->connFailureTimes
[$serverIndex] );
937 unset( $this->connFailureErrors
[$serverIndex] );
939 $this->logger
->debug( __METHOD__
. ": Server #$serverIndex already down" );
944 $this->logger
->info( __METHOD__
. ": Server #$serverIndex down until " . ( $now +
60 ) );
945 $this->connFailureTimes
[$serverIndex] = $now;
946 $this->connFailureErrors
[$serverIndex] = $exception;
950 * Create shard tables. For use from eval.php.
952 public function createTables() {
953 for ( $serverIndex = 0; $serverIndex < $this->numServers
; $serverIndex++
) {
954 $db = $this->getDB( $serverIndex );
955 if ( $db->getType() !== 'mysql' ) {
956 throw new MWException( __METHOD__
. ' is not supported on this DB server' );
959 for ( $i = 0; $i < $this->shards
; $i++
) {
961 'CREATE TABLE ' . $db->tableName( $this->getTableNameByShard( $i ) ) .
962 ' LIKE ' . $db->tableName( 'objectcache' ),
969 * @return bool Whether the main DB is used, e.g. wfGetDB( DB_MASTER )
971 protected function usesMainDB() {
972 return !$this->serverInfos
;
975 protected function waitForReplication() {
976 if ( !$this->usesMainDB() ) {
977 // Custom DB server list; probably doesn't use replication
981 $lb = MediaWikiServices
::getInstance()->getDBLoadBalancer();
982 if ( $lb->getServerCount() <= 1 ) {
983 return true; // no replica DBs
986 // Main LB is used; wait for any replica DBs to catch up
988 $masterPos = $lb->getMasterPos();
990 return true; // not applicable
993 $loop = new WaitConditionLoop(
994 function () use ( $lb, $masterPos ) {
995 return $lb->waitForAll( $masterPos, 1 );
1001 return ( $loop->invoke() === $loop::CONDITION_REACHED
);
1002 } catch ( DBError
$e ) {
1003 $this->setAndLogDBError( $e );
1010 * Returns a ScopedCallback which resets the silence flag in the transaction profiler when it is
1011 * destroyed on the end of a scope, for example on return or throw
1012 * @return ScopedCallback
1015 protected function silenceTransactionProfiler() {
1016 $trxProfiler = Profiler
::instance()->getTransactionProfiler();
1017 $oldSilenced = $trxProfiler->setSilenced( true );
1018 return new ScopedCallback( function () use ( $trxProfiler, $oldSilenced ) {
1019 $trxProfiler->setSilenced( $oldSilenced );