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;
47 protected $lastExpireAll = 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 * Constructor. Parameters are:
72 * - server: A server info structure in the format required by each
73 * element in $wgDBServers.
75 * - servers: An array of server info structures describing a set of database servers
76 * to distribute keys to. If this is specified, the "server" option will be
77 * ignored. If string keys are used, then they will be used for consistent
78 * hashing *instead* of the host name (from the server config). This is useful
79 * when a cluster is replicated to another site (with different host names)
80 * but each server has a corresponding replica in the other cluster.
82 * - purgePeriod: The average number of object cache writes in between
83 * garbage collection operations, where expired entries
84 * are removed from the database. Or in other words, the
85 * reciprocal of the probability of purging on any given
86 * write. If this is set to zero, purging will never be done.
88 * - purgeLimit: Maximum number of rows to purge at once.
90 * - tableName: The table name to use, default is "objectcache".
92 * - shards: The number of tables to use for data storage on each server.
93 * If this is more than 1, table names will be formed in the style
94 * objectcacheNNN where NNN is the shard index, between 0 and
95 * shards-1. The number of digits will be the minimum number
96 * required to hold the largest shard index. Data will be
97 * distributed across all tables by key hash. This is for
98 * MySQL bugs 61735 <https://bugs.mysql.com/bug.php?id=61735>
99 * and 61736 <https://bugs.mysql.com/bug.php?id=61736>.
101 * - slaveOnly: Whether to only use replica DBs and avoid triggering
102 * garbage collection logic of expired items. This only
103 * makes sense if the primary DB is used and only if get()
104 * calls will be used. This is used by ReplicatedBagOStuff.
105 * - syncTimeout: Max seconds to wait for replica DBs to catch up for WRITE_SYNC.
107 * @param array $params
109 public function __construct( $params ) {
110 parent
::__construct( $params );
112 $this->attrMap
[self
::ATTR_EMULATION
] = self
::QOS_EMULATION_SQL
;
113 $this->attrMap
[self
::ATTR_SYNCWRITES
] = self
::QOS_SYNCWRITES_NONE
;
115 if ( isset( $params['servers'] ) ) {
116 $this->serverInfos
= [];
117 $this->serverTags
= [];
118 $this->numServers
= count( $params['servers'] );
120 foreach ( $params['servers'] as $tag => $info ) {
121 $this->serverInfos
[$index] = $info;
122 if ( is_string( $tag ) ) {
123 $this->serverTags
[$index] = $tag;
125 $this->serverTags
[$index] = $info['host'] ??
"#$index";
129 } elseif ( isset( $params['server'] ) ) {
130 $this->serverInfos
= [ $params['server'] ];
131 $this->numServers
= count( $this->serverInfos
);
133 // Default to using the main wiki's database servers
134 $this->serverInfos
= false;
135 $this->numServers
= 1;
136 $this->attrMap
[self
::ATTR_SYNCWRITES
] = self
::QOS_SYNCWRITES_BE
;
138 if ( isset( $params['purgePeriod'] ) ) {
139 $this->purgePeriod
= intval( $params['purgePeriod'] );
141 if ( isset( $params['purgeLimit'] ) ) {
142 $this->purgeLimit
= intval( $params['purgeLimit'] );
144 if ( isset( $params['tableName'] ) ) {
145 $this->tableName
= $params['tableName'];
147 if ( isset( $params['shards'] ) ) {
148 $this->shards
= intval( $params['shards'] );
150 if ( isset( $params['syncTimeout'] ) ) {
151 $this->syncTimeout
= $params['syncTimeout'];
153 $this->replicaOnly
= !empty( $params['slaveOnly'] );
157 * Get a connection to the specified database
159 * @param int $serverIndex
161 * @throws MWException
163 protected function getDB( $serverIndex ) {
164 if ( !isset( $this->conns
[$serverIndex] ) ) {
165 if ( $serverIndex >= $this->numServers
) {
166 throw new MWException( __METHOD__
. ": Invalid server index \"$serverIndex\"" );
169 # Don't keep timing out trying to connect for each call if the DB is down
170 if ( isset( $this->connFailureErrors
[$serverIndex] )
171 && ( time() - $this->connFailureTimes
[$serverIndex] ) < 60
173 throw $this->connFailureErrors
[$serverIndex];
176 if ( $this->serverInfos
) {
177 // Use custom database defined by server connection info
178 $info = $this->serverInfos
[$serverIndex];
179 $type = $info['type'] ??
'mysql';
180 $host = $info['host'] ??
'[unknown]';
181 $this->logger
->debug( __CLASS__
. ": connecting to $host" );
182 $db = Database
::factory( $type, $info );
183 $db->clearFlag( DBO_TRX
); // auto-commit mode
185 // Use the main LB database
186 $lb = MediaWikiServices
::getInstance()->getDBLoadBalancer();
187 $index = $this->replicaOnly ? DB_REPLICA
: DB_MASTER
;
188 if ( $lb->getServerType( $lb->getWriterIndex() ) !== 'sqlite' ) {
189 // Keep a separate connection to avoid contention and deadlocks
190 $db = $lb->getConnection( $index, [], false, $lb::CONN_TRX_AUTOCOMMIT
);
192 // However, SQLite has the opposite behavior due to DB-level locking.
193 // Stock sqlite MediaWiki installs use a separate sqlite cache DB instead.
194 $db = $lb->getConnection( $index );
198 $this->logger
->debug( sprintf( "Connection %s will be used for SqlBagOStuff", $db ) );
199 $this->conns
[$serverIndex] = $db;
202 return $this->conns
[$serverIndex];
206 * Get the server index and table name for a given key
208 * @return array Server index and table name
210 protected function getTableByKey( $key ) {
211 if ( $this->shards
> 1 ) {
212 $hash = hexdec( substr( md5( $key ), 0, 8 ) ) & 0x7fffffff;
213 $tableIndex = $hash %
$this->shards
;
217 if ( $this->numServers
> 1 ) {
218 $sortedServers = $this->serverTags
;
219 ArrayUtils
::consistentHashSort( $sortedServers, $key );
220 reset( $sortedServers );
221 $serverIndex = key( $sortedServers );
225 return [ $serverIndex, $this->getTableNameByShard( $tableIndex ) ];
229 * Get the table name for a given shard index
233 protected function getTableNameByShard( $index ) {
234 if ( $this->shards
> 1 ) {
235 $decimals = strlen( $this->shards
- 1 );
236 return $this->tableName
.
237 sprintf( "%0{$decimals}d", $index );
239 return $this->tableName
;
243 protected function doGet( $key, $flags = 0, &$casToken = null ) {
246 $blobs = $this->fetchBlobMulti( [ $key ] );
247 if ( array_key_exists( $key, $blobs ) ) {
248 $blob = $blobs[$key];
249 $value = $this->unserialize( $blob );
251 $casToken = ( $value !== false ) ?
$blob : null;
259 protected function doGetMulti( array $keys, $flags = 0 ) {
262 $blobs = $this->fetchBlobMulti( $keys );
263 foreach ( $blobs as $key => $blob ) {
264 $values[$key] = $this->unserialize( $blob );
270 protected function fetchBlobMulti( array $keys, $flags = 0 ) {
271 $values = []; // array of (key => value)
274 foreach ( $keys as $key ) {
275 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
276 $keysByTable[$serverIndex][$tableName][] = $key;
280 foreach ( $keysByTable as $serverIndex => $serverKeys ) {
282 $db = $this->getDB( $serverIndex );
283 foreach ( $serverKeys as $tableName => $tableKeys ) {
284 $res = $db->select( $tableName,
285 [ 'keyname', 'value', 'exptime' ],
286 [ 'keyname' => $tableKeys ],
288 // Approximate write-on-the-fly BagOStuff API via blocking.
289 // This approximation fails if a ROLLBACK happens (which is rare).
290 // We do not want to flush the TRX as that can break callers.
291 $db->trxLevel() ?
[ 'LOCK IN SHARE MODE' ] : []
293 if ( $res === false ) {
296 foreach ( $res as $row ) {
297 $row->serverIndex
= $serverIndex;
298 $row->tableName
= $tableName;
299 $dataRows[$row->keyname
] = $row;
302 } catch ( DBError
$e ) {
303 $this->handleReadError( $e, $serverIndex );
307 foreach ( $keys as $key ) {
308 if ( isset( $dataRows[$key] ) ) { // HIT?
309 $row = $dataRows[$key];
310 $this->debug( "get: retrieved data; expiry time is " . $row->exptime
);
313 $db = $this->getDB( $row->serverIndex
);
314 if ( $this->isExpired( $db, $row->exptime
) ) { // MISS
315 $this->debug( "get: key has expired" );
317 $values[$key] = $db->decodeBlob( $row->value
);
319 } catch ( DBQueryError
$e ) {
320 $this->handleWriteError( $e, $db, $row->serverIndex
);
323 $this->debug( 'get: no matching rows' );
330 public function setMulti( array $data, $expiry = 0, $flags = 0 ) {
331 return $this->insertMulti( $data, $expiry, $flags, true );
334 private function insertMulti( array $data, $expiry, $flags, $replace ) {
336 foreach ( $data as $key => $value ) {
337 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
338 $keysByTable[$serverIndex][$tableName][] = $key;
341 $this->garbageCollect(); // expire old entries if any
344 $exptime = (int)$expiry;
345 /** @noinspection PhpUnusedLocalVariableInspection */
346 $silenceScope = $this->silenceTransactionProfiler();
347 foreach ( $keysByTable as $serverIndex => $serverKeys ) {
350 $db = $this->getDB( $serverIndex );
351 } catch ( DBError
$e ) {
352 $this->handleWriteError( $e, $db, $serverIndex );
357 if ( $exptime < 0 ) {
361 if ( $exptime == 0 ) {
362 $encExpiry = $this->getMaxDateTime( $db );
364 $exptime = $this->convertToExpiry( $exptime );
365 $encExpiry = $db->timestamp( $exptime );
367 foreach ( $serverKeys as $tableName => $tableKeys ) {
369 foreach ( $tableKeys as $key ) {
372 'value' => $db->encodeBlob( $this->serialize( $data[$key] ) ),
373 'exptime' => $encExpiry,
379 $db->replace( $tableName, [ 'keyname' ], $rows, __METHOD__
);
381 $db->insert( $tableName, $rows, __METHOD__
, [ 'IGNORE' ] );
382 $result = ( $db->affectedRows() > 0 && $result );
384 } catch ( DBError
$e ) {
385 $this->handleWriteError( $e, $db, $serverIndex );
392 if ( ( $flags & self
::WRITE_SYNC
) == self
::WRITE_SYNC
) {
393 $result = $this->waitForReplication() && $result;
399 protected function doSet( $key, $value, $exptime = 0, $flags = 0 ) {
400 $ok = $this->insertMulti( [ $key => $value ], $exptime, $flags, true );
405 public function add( $key, $value, $exptime = 0, $flags = 0 ) {
406 $added = $this->insertMulti( [ $key => $value ], $exptime, $flags, false );
411 protected function cas( $casToken, $key, $value, $exptime = 0, $flags = 0 ) {
412 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
414 /** @noinspection PhpUnusedLocalVariableInspection */
415 $silenceScope = $this->silenceTransactionProfiler();
417 $db = $this->getDB( $serverIndex );
418 $exptime = intval( $exptime );
420 if ( $exptime < 0 ) {
424 if ( $exptime == 0 ) {
425 $encExpiry = $this->getMaxDateTime( $db );
427 $exptime = $this->convertToExpiry( $exptime );
428 $encExpiry = $db->timestamp( $exptime );
430 // (T26425) use a replace if the db supports it instead of
431 // delete/insert to avoid clashes with conflicting keynames
436 'value' => $db->encodeBlob( $this->serialize( $value ) ),
437 'exptime' => $encExpiry
441 'value' => $db->encodeBlob( $casToken )
445 } catch ( DBQueryError
$e ) {
446 $this->handleWriteError( $e, $db, $serverIndex );
451 return (bool)$db->affectedRows();
454 public function deleteMulti( array $keys, $flags = 0 ) {
455 return $this->purgeMulti( $keys, $flags );
458 public function purgeMulti( array $keys, $flags = 0 ) {
460 foreach ( $keys as $key ) {
461 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
462 $keysByTable[$serverIndex][$tableName][] = $key;
466 /** @noinspection PhpUnusedLocalVariableInspection */
467 $silenceScope = $this->silenceTransactionProfiler();
468 foreach ( $keysByTable as $serverIndex => $serverKeys ) {
471 $db = $this->getDB( $serverIndex );
472 } catch ( DBError
$e ) {
473 $this->handleWriteError( $e, $db, $serverIndex );
478 foreach ( $serverKeys as $tableName => $tableKeys ) {
480 $db->delete( $tableName, [ 'keyname' => $tableKeys ], __METHOD__
);
481 } catch ( DBError
$e ) {
482 $this->handleWriteError( $e, $db, $serverIndex );
489 if ( ( $flags & self
::WRITE_SYNC
) == self
::WRITE_SYNC
) {
490 $result = $this->waitForReplication() && $result;
496 protected function doDelete( $key, $flags = 0 ) {
497 $ok = $this->purgeMulti( [ $key ], $flags );
502 public function incr( $key, $step = 1 ) {
503 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
505 /** @noinspection PhpUnusedLocalVariableInspection */
506 $silenceScope = $this->silenceTransactionProfiler();
508 $db = $this->getDB( $serverIndex );
509 $step = intval( $step );
510 $row = $db->selectRow(
512 [ 'value', 'exptime' ],
513 [ 'keyname' => $key ],
517 if ( $row === false ) {
521 $db->delete( $tableName, [ 'keyname' => $key ], __METHOD__
);
522 if ( $this->isExpired( $db, $row->exptime
) ) {
523 // Expired, do not reinsert
527 $oldValue = intval( $this->unserialize( $db->decodeBlob( $row->value
) ) );
528 $newValue = $oldValue +
$step;
533 'value' => $db->encodeBlob( $this->serialize( $newValue ) ),
534 'exptime' => $row->exptime
540 if ( $db->affectedRows() == 0 ) {
541 // Race condition. See T30611
544 } catch ( DBError
$e ) {
545 $this->handleWriteError( $e, $db, $serverIndex );
552 public function merge( $key, callable
$callback, $exptime = 0, $attempts = 10, $flags = 0 ) {
553 $ok = $this->mergeViaCas( $key, $callback, $exptime, $attempts, $flags );
554 if ( ( $flags & self
::WRITE_SYNC
) == self
::WRITE_SYNC
) {
555 $ok = $this->waitForReplication() && $ok;
561 public function changeTTL( $key, $exptime = 0, $flags = 0 ) {
562 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
564 /** @noinspection PhpUnusedLocalVariableInspection */
565 $silenceScope = $this->silenceTransactionProfiler();
567 $db = $this->getDB( $serverIndex );
568 if ( $exptime == 0 ) {
569 $timestamp = $this->getMaxDateTime( $db );
571 $timestamp = $db->timestamp( $this->convertToExpiry( $exptime ) );
575 [ 'exptime' => $timestamp ],
576 [ 'keyname' => $key, 'exptime > ' . $db->addQuotes( $db->timestamp( time() ) ) ],
579 if ( $db->affectedRows() == 0 ) {
580 $exists = (bool)$db->selectField(
583 [ 'keyname' => $key, 'exptime' => $timestamp ],
590 } catch ( DBError
$e ) {
591 $this->handleWriteError( $e, $db, $serverIndex );
599 * @param IDatabase $db
600 * @param string $exptime
603 protected function isExpired( $db, $exptime ) {
604 return $exptime != $this->getMaxDateTime( $db ) && wfTimestamp( TS_UNIX
, $exptime ) < time();
608 * @param IDatabase $db
611 protected function getMaxDateTime( $db ) {
612 if ( time() > 0x7fffffff ) {
613 return $db->timestamp( 1 << 62 );
615 return $db->timestamp( 0x7fffffff );
619 protected function garbageCollect() {
620 if ( !$this->purgePeriod ||
$this->replicaOnly
) {
624 // Only purge on one in every $this->purgePeriod writes
625 if ( $this->purgePeriod
!== 1 && mt_rand( 0, $this->purgePeriod
- 1 ) ) {
629 // Avoid repeating the delete within a few seconds
630 if ( $now > ( $this->lastExpireAll +
1 ) ) {
631 $this->lastExpireAll
= $now;
632 $this->deleteObjectsExpiringBefore(
633 wfTimestamp( TS_MW
, $now ),
640 public function expireAll() {
641 $this->deleteObjectsExpiringBefore( wfTimestampNow() );
644 public function deleteObjectsExpiringBefore(
646 $progressCallback = false,
649 /** @noinspection PhpUnusedLocalVariableInspection */
650 $silenceScope = $this->silenceTransactionProfiler();
653 for ( $serverIndex = 0; $serverIndex < $this->numServers
; $serverIndex++
) {
656 $db = $this->getDB( $serverIndex );
657 $dbTimestamp = $db->timestamp( $timestamp );
658 $totalSeconds = false;
659 $baseConds = [ 'exptime < ' . $db->addQuotes( $dbTimestamp ) ];
660 for ( $i = 0; $i < $this->shards
; $i++
) {
664 if ( $maxExpTime !== false ) {
665 $conds[] = 'exptime >= ' . $db->addQuotes( $maxExpTime );
668 $this->getTableNameByShard( $i ),
669 [ 'keyname', 'exptime' ],
672 [ 'LIMIT' => 100, 'ORDER BY' => 'exptime' ]
674 if ( $rows === false ||
!$rows->numRows() ) {
678 $row = $rows->current();
679 $minExpTime = $row->exptime
;
680 if ( $totalSeconds === false ) {
681 $totalSeconds = wfTimestamp( TS_UNIX
, $timestamp )
682 - wfTimestamp( TS_UNIX
, $minExpTime );
684 foreach ( $rows as $row ) {
685 $keys[] = $row->keyname
;
686 $maxExpTime = $row->exptime
;
690 $this->getTableNameByShard( $i ),
692 'exptime >= ' . $db->addQuotes( $minExpTime ),
693 'exptime < ' . $db->addQuotes( $dbTimestamp ),
698 $count +
= $db->affectedRows();
699 if ( $count >= $limit ) {
703 if ( is_callable( $progressCallback ) ) {
704 if ( intval( $totalSeconds ) === 0 ) {
707 $remainingSeconds = wfTimestamp( TS_UNIX
, $timestamp )
708 - wfTimestamp( TS_UNIX
, $maxExpTime );
709 if ( $remainingSeconds > $totalSeconds ) {
710 $totalSeconds = $remainingSeconds;
712 $processedSeconds = $totalSeconds - $remainingSeconds;
713 $percent = ( $i +
$processedSeconds / $totalSeconds )
714 / $this->shards
* 100;
716 $percent = ( $percent / $this->numServers
)
717 +
( $serverIndex / $this->numServers
* 100 );
718 call_user_func( $progressCallback, $percent );
722 } catch ( DBError
$e ) {
723 $this->handleWriteError( $e, $db, $serverIndex );
732 * Delete content of shard tables in every server.
733 * Return true if the operation is successful, false otherwise.
736 public function deleteAll() {
737 /** @noinspection PhpUnusedLocalVariableInspection */
738 $silenceScope = $this->silenceTransactionProfiler();
739 for ( $serverIndex = 0; $serverIndex < $this->numServers
; $serverIndex++
) {
742 $db = $this->getDB( $serverIndex );
743 for ( $i = 0; $i < $this->shards
; $i++
) {
744 $db->delete( $this->getTableNameByShard( $i ), '*', __METHOD__
);
746 } catch ( DBError
$e ) {
747 $this->handleWriteError( $e, $db, $serverIndex );
754 public function lock( $key, $timeout = 6, $expiry = 6, $rclass = '' ) {
755 // Avoid deadlocks and allow lock reentry if specified
756 if ( isset( $this->locks
[$key] ) ) {
757 if ( $rclass != '' && $this->locks
[$key]['class'] === $rclass ) {
758 ++
$this->locks
[$key]['depth'];
765 list( $serverIndex ) = $this->getTableByKey( $key );
767 $db = $this->getDB( $serverIndex );
768 $ok = $db->lock( $key, __METHOD__
, $timeout );
770 $this->locks
[$key] = [ 'class' => $rclass, 'depth' => 1 ];
773 $this->logger
->warning(
774 __METHOD__
. " failed due to timeout for {key}.",
775 [ 'key' => $key, 'timeout' => $timeout ]
779 } catch ( DBError
$e ) {
780 $this->handleWriteError( $e, $db, $serverIndex );
787 public function unlock( $key ) {
788 if ( !isset( $this->locks
[$key] ) ) {
792 if ( --$this->locks
[$key]['depth'] <= 0 ) {
793 unset( $this->locks
[$key] );
795 list( $serverIndex ) = $this->getTableByKey( $key );
797 $db = $this->getDB( $serverIndex );
798 $ok = $db->unlock( $key, __METHOD__
);
800 $this->logger
->warning(
801 __METHOD__
. ' failed to release lock for {key}.',
805 } catch ( DBError
$e ) {
806 $this->handleWriteError( $e, $db, $serverIndex );
817 * Serialize an object and, if possible, compress the representation.
818 * On typical message and page data, this can provide a 3X decrease
819 * in storage requirements.
824 protected function serialize( $data ) {
825 $serial = serialize( $data );
827 if ( function_exists( 'gzdeflate' ) ) {
828 return gzdeflate( $serial );
835 * Unserialize and, if necessary, decompress an object.
836 * @param string $serial
839 protected function unserialize( $serial ) {
840 if ( function_exists( 'gzinflate' ) ) {
841 Wikimedia\
suppressWarnings();
842 $decomp = gzinflate( $serial );
843 Wikimedia\restoreWarnings
();
845 if ( $decomp !== false ) {
850 $ret = unserialize( $serial );
856 * Handle a DBError which occurred during a read operation.
858 * @param DBError $exception
859 * @param int $serverIndex
861 protected function handleReadError( DBError
$exception, $serverIndex ) {
862 if ( $exception instanceof DBConnectionError
) {
863 $this->markServerDown( $exception, $serverIndex );
866 $this->setAndLogDBError( $exception );
870 * Handle a DBQueryError which occurred during a write operation.
872 * @param DBError $exception
873 * @param IDatabase|null $db DB handle or null if connection failed
874 * @param int $serverIndex
877 protected function handleWriteError( DBError
$exception, $db, $serverIndex ) {
878 if ( !( $db instanceof IDatabase
) ) {
879 $this->markServerDown( $exception, $serverIndex );
882 $this->setAndLogDBError( $exception );
886 * @param DBError $exception
888 private function setAndLogDBError( DBError
$exception ) {
889 $this->logger
->error( "DBError: {$exception->getMessage()}" );
890 if ( $exception instanceof DBConnectionError
) {
891 $this->setLastError( BagOStuff
::ERR_UNREACHABLE
);
892 $this->logger
->debug( __METHOD__
. ": ignoring connection error" );
894 $this->setLastError( BagOStuff
::ERR_UNEXPECTED
);
895 $this->logger
->debug( __METHOD__
. ": ignoring query error" );
900 * Mark a server down due to a DBConnectionError exception
902 * @param DBError $exception
903 * @param int $serverIndex
905 protected function markServerDown( DBError
$exception, $serverIndex ) {
906 unset( $this->conns
[$serverIndex] ); // bug T103435
908 if ( isset( $this->connFailureTimes
[$serverIndex] ) ) {
909 if ( time() - $this->connFailureTimes
[$serverIndex] >= 60 ) {
910 unset( $this->connFailureTimes
[$serverIndex] );
911 unset( $this->connFailureErrors
[$serverIndex] );
913 $this->logger
->debug( __METHOD__
. ": Server #$serverIndex already down" );
918 $this->logger
->info( __METHOD__
. ": Server #$serverIndex down until " . ( $now +
60 ) );
919 $this->connFailureTimes
[$serverIndex] = $now;
920 $this->connFailureErrors
[$serverIndex] = $exception;
924 * Create shard tables. For use from eval.php.
926 public function createTables() {
927 for ( $serverIndex = 0; $serverIndex < $this->numServers
; $serverIndex++
) {
928 $db = $this->getDB( $serverIndex );
929 if ( $db->getType() !== 'mysql' ) {
930 throw new MWException( __METHOD__
. ' is not supported on this DB server' );
933 for ( $i = 0; $i < $this->shards
; $i++
) {
935 'CREATE TABLE ' . $db->tableName( $this->getTableNameByShard( $i ) ) .
936 ' LIKE ' . $db->tableName( 'objectcache' ),
943 * @return bool Whether the main DB is used, e.g. wfGetDB( DB_MASTER )
945 protected function usesMainDB() {
946 return !$this->serverInfos
;
949 protected function waitForReplication() {
950 if ( !$this->usesMainDB() ) {
951 // Custom DB server list; probably doesn't use replication
955 $lb = MediaWikiServices
::getInstance()->getDBLoadBalancer();
956 if ( $lb->getServerCount() <= 1 ) {
957 return true; // no replica DBs
960 // Main LB is used; wait for any replica DBs to catch up
962 $masterPos = $lb->getMasterPos();
964 return true; // not applicable
967 $loop = new WaitConditionLoop(
968 function () use ( $lb, $masterPos ) {
969 return $lb->waitForAll( $masterPos, 1 );
975 return ( $loop->invoke() === $loop::CONDITION_REACHED
);
976 } catch ( DBError
$e ) {
977 $this->setAndLogDBError( $e );
984 * Returns a ScopedCallback which resets the silence flag in the transaction profiler when it is
985 * destroyed on the end of a scope, for example on return or throw
986 * @return ScopedCallback
989 protected function silenceTransactionProfiler() {
990 $trxProfiler = Profiler
::instance()->getTransactionProfiler();
991 $oldSilenced = $trxProfiler->setSilenced( true );
992 return new ScopedCallback( function () use ( $trxProfiler, $oldSilenced ) {
993 $trxProfiler->setSilenced( $oldSilenced );