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 MediumSpecificBagOStuff
{
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 /** @var LoadBalancer|null */
60 protected $separateMainLB;
63 /** @var array UNIX timestamps */
64 protected $connFailureTimes = [];
65 /** @var array Exceptions */
66 protected $connFailureErrors = [];
69 private static $GARBAGE_COLLECT_DELAY_SEC = 1;
72 private static $OP_SET = 'set';
74 private static $OP_ADD = 'add';
76 private static $OP_TOUCH = 'touch';
78 private static $OP_DELETE = 'delete';
81 * Constructor. Parameters are:
82 * - server: A server info structure in the format required by each
83 * element in $wgDBServers.
85 * - servers: An array of server info structures describing a set of database servers
86 * to distribute keys to. If this is specified, the "server" option will be
87 * ignored. If string keys are used, then they will be used for consistent
88 * hashing *instead* of the host name (from the server config). This is useful
89 * when a cluster is replicated to another site (with different host names)
90 * but each server has a corresponding replica in the other cluster.
92 * - purgePeriod: The average number of object cache writes in between
93 * garbage collection operations, where expired entries
94 * are removed from the database. Or in other words, the
95 * reciprocal of the probability of purging on any given
96 * write. If this is set to zero, purging will never be done.
98 * - purgeLimit: Maximum number of rows to purge at once.
100 * - tableName: The table name to use, default is "objectcache".
102 * - shards: The number of tables to use for data storage on each server.
103 * If this is more than 1, table names will be formed in the style
104 * objectcacheNNN where NNN is the shard index, between 0 and
105 * shards-1. The number of digits will be the minimum number
106 * required to hold the largest shard index. Data will be
107 * distributed across all tables by key hash. This is for
108 * MySQL bugs 61735 <https://bugs.mysql.com/bug.php?id=61735>
109 * and 61736 <https://bugs.mysql.com/bug.php?id=61736>.
111 * - replicaOnly: Whether to only use replica DBs and avoid triggering
112 * garbage collection logic of expired items. This only
113 * makes sense if the primary DB is used and only if get()
114 * calls will be used. This is used by ReplicatedBagOStuff.
115 * - syncTimeout: Max seconds to wait for replica DBs to catch up for WRITE_SYNC.
117 * @param array $params
119 public function __construct( $params ) {
120 parent
::__construct( $params );
122 $this->attrMap
[self
::ATTR_EMULATION
] = self
::QOS_EMULATION_SQL
;
123 $this->attrMap
[self
::ATTR_SYNCWRITES
] = self
::QOS_SYNCWRITES_NONE
;
125 if ( isset( $params['servers'] ) ) {
126 $this->serverInfos
= [];
127 $this->serverTags
= [];
128 $this->numServers
= count( $params['servers'] );
130 foreach ( $params['servers'] as $tag => $info ) {
131 $this->serverInfos
[$index] = $info;
132 if ( is_string( $tag ) ) {
133 $this->serverTags
[$index] = $tag;
135 $this->serverTags
[$index] = $info['host'] ??
"#$index";
139 } elseif ( isset( $params['server'] ) ) {
140 $this->serverInfos
= [ $params['server'] ];
141 $this->numServers
= count( $this->serverInfos
);
143 // Default to using the main wiki's database servers
144 $this->serverInfos
= false;
145 $this->numServers
= 1;
146 $this->attrMap
[self
::ATTR_SYNCWRITES
] = self
::QOS_SYNCWRITES_BE
;
148 if ( isset( $params['purgePeriod'] ) ) {
149 $this->purgePeriod
= intval( $params['purgePeriod'] );
151 if ( isset( $params['purgeLimit'] ) ) {
152 $this->purgeLimit
= intval( $params['purgeLimit'] );
154 if ( isset( $params['tableName'] ) ) {
155 $this->tableName
= $params['tableName'];
157 if ( isset( $params['shards'] ) ) {
158 $this->shards
= intval( $params['shards'] );
160 // Backwards-compatibility for < 1.34
161 $this->replicaOnly
= $params['replicaOnly'] ??
( $params['slaveOnly'] ??
false );
165 * Get a connection to the specified database
167 * @param int $serverIndex
169 * @throws MWException
171 protected function getDB( $serverIndex ) {
172 if ( $serverIndex >= $this->numServers
) {
173 throw new MWException( __METHOD__
. ": Invalid server index \"$serverIndex\"" );
176 # Don't keep timing out trying to connect for each call if the DB is down
178 isset( $this->connFailureErrors
[$serverIndex] ) &&
179 ( time() - $this->connFailureTimes
[$serverIndex] ) < 60
181 throw $this->connFailureErrors
[$serverIndex];
184 if ( $this->serverInfos
) {
185 if ( !isset( $this->conns
[$serverIndex] ) ) {
186 // Use custom database defined by server connection info
187 $info = $this->serverInfos
[$serverIndex];
188 $type = $info['type'] ??
'mysql';
189 $host = $info['host'] ??
'[unknown]';
190 $this->logger
->debug( __CLASS__
. ": connecting to $host" );
191 $db = Database
::factory( $type, $info );
192 $db->clearFlag( DBO_TRX
); // auto-commit mode
193 $this->conns
[$serverIndex] = $db;
195 $db = $this->conns
[$serverIndex];
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 ) );
216 * Get the server index and table name for a given key
218 * @return array Server index and table name
220 protected function getTableByKey( $key ) {
221 if ( $this->shards
> 1 ) {
222 $hash = hexdec( substr( md5( $key ), 0, 8 ) ) & 0x7fffffff;
223 $tableIndex = $hash %
$this->shards
;
227 if ( $this->numServers
> 1 ) {
228 $sortedServers = $this->serverTags
;
229 ArrayUtils
::consistentHashSort( $sortedServers, $key );
230 reset( $sortedServers );
231 $serverIndex = key( $sortedServers );
235 return [ $serverIndex, $this->getTableNameByShard( $tableIndex ) ];
239 * Get the table name for a given shard index
243 protected function getTableNameByShard( $index ) {
244 if ( $this->shards
> 1 ) {
245 $decimals = strlen( $this->shards
- 1 );
246 return $this->tableName
.
247 sprintf( "%0{$decimals}d", $index );
249 return $this->tableName
;
253 protected function doGet( $key, $flags = 0, &$casToken = null ) {
256 $blobs = $this->fetchBlobMulti( [ $key ] );
257 if ( array_key_exists( $key, $blobs ) ) {
258 $blob = $blobs[$key];
259 $value = $this->unserialize( $blob );
261 $casToken = ( $value !== false ) ?
$blob : null;
269 protected function doGetMulti( array $keys, $flags = 0 ) {
272 $blobs = $this->fetchBlobMulti( $keys );
273 foreach ( $blobs as $key => $blob ) {
274 $values[$key] = $this->unserialize( $blob );
280 protected function fetchBlobMulti( array $keys, $flags = 0 ) {
281 $values = []; // array of (key => value)
284 foreach ( $keys as $key ) {
285 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
286 $keysByTable[$serverIndex][$tableName][] = $key;
290 foreach ( $keysByTable as $serverIndex => $serverKeys ) {
292 $db = $this->getDB( $serverIndex );
293 foreach ( $serverKeys as $tableName => $tableKeys ) {
294 $res = $db->select( $tableName,
295 [ 'keyname', 'value', 'exptime' ],
296 [ 'keyname' => $tableKeys ],
298 // Approximate write-on-the-fly BagOStuff API via blocking.
299 // This approximation fails if a ROLLBACK happens (which is rare).
300 // We do not want to flush the TRX as that can break callers.
301 $db->trxLevel() ?
[ 'LOCK IN SHARE MODE' ] : []
303 if ( $res === false ) {
306 foreach ( $res as $row ) {
307 $row->serverIndex
= $serverIndex;
308 $row->tableName
= $tableName;
309 $dataRows[$row->keyname
] = $row;
312 } catch ( DBError
$e ) {
313 $this->handleReadError( $e, $serverIndex );
317 foreach ( $keys as $key ) {
318 if ( isset( $dataRows[$key] ) ) { // HIT?
319 $row = $dataRows[$key];
320 $this->debug( "get: retrieved data; expiry time is " . $row->exptime
);
321 $db = null; // in case of connection failure
323 $db = $this->getDB( $row->serverIndex
);
324 if ( $this->isExpired( $db, $row->exptime
) ) { // MISS
325 $this->debug( "get: key has expired" );
327 $values[$key] = $db->decodeBlob( $row->value
);
329 } catch ( DBQueryError
$e ) {
330 $this->handleWriteError( $e, $db, $row->serverIndex
);
333 $this->debug( 'get: no matching rows' );
340 protected function doSetMulti( array $data, $exptime = 0, $flags = 0 ) {
341 return $this->modifyMulti( $data, $exptime, $flags, self
::$OP_SET );
345 * @param mixed[]|null[] $data Map of (key => new value or null)
346 * @param int $exptime UNIX timestamp, TTL in seconds, or 0 (no expiration)
347 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
348 * @param string $op Cache operation
351 private function modifyMulti( array $data, $exptime, $flags, $op ) {
353 foreach ( $data as $key => $value ) {
354 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
355 $keysByTable[$serverIndex][$tableName][] = $key;
358 $exptime = $this->convertToExpiry( $exptime );
361 /** @noinspection PhpUnusedLocalVariableInspection */
362 $silenceScope = $this->silenceTransactionProfiler();
363 foreach ( $keysByTable as $serverIndex => $serverKeys ) {
364 $db = null; // in case of connection failure
366 $db = $this->getDB( $serverIndex );
367 $this->occasionallyGarbageCollect( $db ); // expire old entries if any
368 $dbExpiry = $exptime ?
$db->timestamp( $exptime ) : $this->getMaxDateTime( $db );
369 } catch ( DBError
$e ) {
370 $this->handleWriteError( $e, $db, $serverIndex );
375 foreach ( $serverKeys as $tableName => $tableKeys ) {
377 $result = $this->updateTableKeys(
385 } catch ( DBError
$e ) {
386 $this->handleWriteError( $e, $db, $serverIndex );
393 if ( ( $flags & self
::WRITE_SYNC
) == self
::WRITE_SYNC
) {
394 $result = $this->waitForReplication() && $result;
402 * @param IDatabase $db
403 * @param string $table
404 * @param string[] $tableKeys Keys in $data to update
405 * @param mixed[]|null[] $data Map of (key => new value or null)
406 * @param string $dbExpiry DB-encoded expiry
409 * @throws InvalidArgumentException
411 private function updateTableKeys( $op, $db, $table, $tableKeys, $data, $dbExpiry ) {
414 if ( $op === self
::$OP_ADD ) {
416 foreach ( $tableKeys as $key ) {
419 'value' => $db->encodeBlob( $this->serialize( $data[$key] ) ),
420 'exptime' => $dbExpiry
426 'keyname' => $tableKeys,
427 'exptime <= ' . $db->addQuotes( $db->timestamp() )
431 $db->insert( $table, $rows, __METHOD__
, [ 'IGNORE' ] );
433 $success = ( $db->affectedRows() == count( $rows ) );
434 } elseif ( $op === self
::$OP_SET ) {
436 foreach ( $tableKeys as $key ) {
439 'value' => $db->encodeBlob( $this->serialize( $data[$key] ) ),
440 'exptime' => $dbExpiry
443 $db->replace( $table, [ 'keyname' ], $rows, __METHOD__
);
444 } elseif ( $op === self
::$OP_DELETE ) {
445 $db->delete( $table, [ 'keyname' => $tableKeys ], __METHOD__
);
446 } elseif ( $op === self
::$OP_TOUCH ) {
449 [ 'exptime' => $dbExpiry ],
451 'keyname' => $tableKeys,
452 'exptime > ' . $db->addQuotes( $db->timestamp() )
457 $success = ( $db->affectedRows() == count( $tableKeys ) );
459 throw new InvalidArgumentException( "Invalid operation '$op'" );
465 protected function doSet( $key, $value, $exptime = 0, $flags = 0 ) {
466 return $this->modifyMulti( [ $key => $value ], $exptime, $flags, self
::$OP_SET );
469 public function add( $key, $value, $exptime = 0, $flags = 0 ) {
470 return $this->modifyMulti( [ $key => $value ], $exptime, $flags, self
::$OP_ADD );
473 protected function cas( $casToken, $key, $value, $exptime = 0, $flags = 0 ) {
474 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
475 $exptime = $this->convertToExpiry( $exptime );
477 /** @noinspection PhpUnusedLocalVariableInspection */
478 $silenceScope = $this->silenceTransactionProfiler();
479 $db = null; // in case of connection failure
481 $db = $this->getDB( $serverIndex );
482 // (T26425) use a replace if the db supports it instead of
483 // delete/insert to avoid clashes with conflicting keynames
488 'value' => $db->encodeBlob( $this->serialize( $value ) ),
489 'exptime' => $exptime
490 ?
$db->timestamp( $exptime )
491 : $this->getMaxDateTime( $db )
495 'value' => $db->encodeBlob( $casToken ),
496 'exptime > ' . $db->addQuotes( $db->timestamp() )
500 } catch ( DBQueryError
$e ) {
501 $this->handleWriteError( $e, $db, $serverIndex );
506 return (bool)$db->affectedRows();
509 protected function doDeleteMulti( array $keys, $flags = 0 ) {
510 return $this->modifyMulti(
511 array_fill_keys( $keys, null ),
518 protected function doDelete( $key, $flags = 0 ) {
519 return $this->modifyMulti( [ $key => null ], 0, $flags, self
::$OP_DELETE );
522 public function incr( $key, $step = 1 ) {
523 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
526 /** @noinspection PhpUnusedLocalVariableInspection */
527 $silenceScope = $this->silenceTransactionProfiler();
528 $db = null; // in case of connection failure
530 $db = $this->getDB( $serverIndex );
531 $encTimestamp = $db->addQuotes( $db->timestamp() );
534 [ 'value = value + ' . (int)$step ],
535 [ 'keyname' => $key, "exptime > $encTimestamp" ],
538 if ( $db->affectedRows() > 0 ) {
539 $newValue = $db->selectField(
542 [ 'keyname' => $key, "exptime > $encTimestamp" ],
545 if ( $this->isInteger( $newValue ) ) {
546 $newCount = (int)$newValue;
549 } catch ( DBError
$e ) {
550 $this->handleWriteError( $e, $db, $serverIndex );
556 public function merge( $key, callable
$callback, $exptime = 0, $attempts = 10, $flags = 0 ) {
557 $ok = $this->mergeViaCas( $key, $callback, $exptime, $attempts, $flags );
558 if ( ( $flags & self
::WRITE_SYNC
) == self
::WRITE_SYNC
) {
559 $ok = $this->waitForReplication() && $ok;
565 protected function doChangeTTLMulti( array $keys, $exptime, $flags = 0 ) {
566 return $this->modifyMulti(
567 array_fill_keys( $keys, null ),
574 protected function doChangeTTL( $key, $exptime, $flags ) {
575 return $this->modifyMulti( [ $key => null ], $exptime, $flags, self
::$OP_TOUCH );
579 * @param IDatabase $db
580 * @param string $exptime
583 protected function isExpired( $db, $exptime ) {
585 $exptime != $this->getMaxDateTime( $db ) &&
586 wfTimestamp( TS_UNIX
, $exptime ) < time()
591 * @param IDatabase $db
594 protected function getMaxDateTime( $db ) {
595 if ( time() > 0x7fffffff ) {
596 return $db->timestamp( 1 << 62 );
598 return $db->timestamp( 0x7fffffff );
603 * @param IDatabase $db
606 protected function occasionallyGarbageCollect( IDatabase
$db ) {
608 // Random purging is enabled
609 $this->purgePeriod
&&
610 // Only purge on one in every $this->purgePeriod writes
611 mt_rand( 0, $this->purgePeriod
- 1 ) == 0 &&
612 // Avoid repeating the delete within a few seconds
613 ( time() - $this->lastGarbageCollect
) > self
::$GARBAGE_COLLECT_DELAY_SEC
615 $garbageCollector = function () use ( $db ) {
616 $this->deleteServerObjectsExpiringBefore( $db, time(), null, $this->purgeLimit
);
617 $this->lastGarbageCollect
= time();
619 if ( $this->asyncHandler
) {
620 $this->lastGarbageCollect
= time(); // avoid duplicate enqueues
621 ( $this->asyncHandler
)( $garbageCollector );
628 public function expireAll() {
629 $this->deleteObjectsExpiringBefore( time() );
632 public function deleteObjectsExpiringBefore(
634 callable
$progress = null,
637 /** @noinspection PhpUnusedLocalVariableInspection */
638 $silenceScope = $this->silenceTransactionProfiler();
640 $serverIndexes = range( 0, $this->numServers
- 1 );
641 shuffle( $serverIndexes );
645 $keysDeletedCount = 0;
646 foreach ( $serverIndexes as $numServersDone => $serverIndex ) {
647 $db = null; // in case of connection failure
649 $db = $this->getDB( $serverIndex );
650 $this->deleteServerObjectsExpiringBefore(
658 } catch ( DBError
$e ) {
659 $this->handleWriteError( $e, $db, $serverIndex );
668 * @param IDatabase $db
669 * @param string|int $timestamp
670 * @param callable|null $progressCallback
672 * @param int $serversDoneCount
673 * @param int &$keysDeletedCount
676 private function deleteServerObjectsExpiringBefore(
681 $serversDoneCount = 0,
682 &$keysDeletedCount = 0
684 $cutoffUnix = wfTimestamp( TS_UNIX
, $timestamp );
685 $shardIndexes = range( 0, $this->shards
- 1 );
686 shuffle( $shardIndexes );
688 foreach ( $shardIndexes as $numShardsDone => $shardIndex ) {
689 $continue = null; // last exptime
690 $lag = null; // purge lag
693 $this->getTableNameByShard( $shardIndex ),
694 [ 'keyname', 'exptime' ],
696 [ 'exptime < ' . $db->addQuotes( $db->timestamp( $cutoffUnix ) ) ],
697 $continue ?
[ 'exptime >= ' . $db->addQuotes( $continue ) ] : []
700 [ 'LIMIT' => min( $limit, 100 ), 'ORDER BY' => 'exptime' ]
703 if ( $res->numRows() ) {
704 $row = $res->current();
705 if ( $lag === null ) {
706 $lag = max( $cutoffUnix - wfTimestamp( TS_UNIX
, $row->exptime
), 1 );
710 foreach ( $res as $row ) {
711 $keys[] = $row->keyname
;
712 $continue = $row->exptime
;
716 $this->getTableNameByShard( $shardIndex ),
718 'exptime < ' . $db->addQuotes( $db->timestamp( $cutoffUnix ) ),
723 $keysDeletedCount +
= $db->affectedRows();
726 if ( is_callable( $progressCallback ) ) {
728 $remainingLag = $cutoffUnix - wfTimestamp( TS_UNIX
, $continue );
729 $processedLag = max( $lag - $remainingLag, 0 );
730 $doneRatio = ( $numShardsDone +
$processedLag / $lag ) / $this->shards
;
735 $overallRatio = ( $doneRatio / $this->numServers
)
736 +
( $serversDoneCount / $this->numServers
);
737 call_user_func( $progressCallback, $overallRatio * 100 );
739 } while ( $res->numRows() && $keysDeletedCount < $limit );
744 * Delete content of shard tables in every server.
745 * Return true if the operation is successful, false otherwise.
748 public function deleteAll() {
749 /** @noinspection PhpUnusedLocalVariableInspection */
750 $silenceScope = $this->silenceTransactionProfiler();
751 for ( $serverIndex = 0; $serverIndex < $this->numServers
; $serverIndex++
) {
752 $db = null; // in case of connection failure
754 $db = $this->getDB( $serverIndex );
755 for ( $i = 0; $i < $this->shards
; $i++
) {
756 $db->delete( $this->getTableNameByShard( $i ), '*', __METHOD__
);
758 } catch ( DBError
$e ) {
759 $this->handleWriteError( $e, $db, $serverIndex );
766 public function lock( $key, $timeout = 6, $expiry = 6, $rclass = '' ) {
767 // Avoid deadlocks and allow lock reentry if specified
768 if ( isset( $this->locks
[$key] ) ) {
769 if ( $rclass != '' && $this->locks
[$key]['class'] === $rclass ) {
770 ++
$this->locks
[$key]['depth'];
777 list( $serverIndex ) = $this->getTableByKey( $key );
779 $db = null; // in case of connection failure
781 $db = $this->getDB( $serverIndex );
782 $ok = $db->lock( $key, __METHOD__
, $timeout );
784 $this->locks
[$key] = [ 'class' => $rclass, 'depth' => 1 ];
787 $this->logger
->warning(
788 __METHOD__
. " failed due to timeout for {key}.",
789 [ 'key' => $key, 'timeout' => $timeout ]
793 } catch ( DBError
$e ) {
794 $this->handleWriteError( $e, $db, $serverIndex );
801 public function unlock( $key ) {
802 if ( !isset( $this->locks
[$key] ) ) {
806 if ( --$this->locks
[$key]['depth'] <= 0 ) {
807 unset( $this->locks
[$key] );
809 list( $serverIndex ) = $this->getTableByKey( $key );
811 $db = null; // in case of connection failure
813 $db = $this->getDB( $serverIndex );
814 $ok = $db->unlock( $key, __METHOD__
);
816 $this->logger
->warning(
817 __METHOD__
. ' failed to release lock for {key}.',
821 } catch ( DBError
$e ) {
822 $this->handleWriteError( $e, $db, $serverIndex );
833 * Serialize an object and, if possible, compress the representation.
834 * On typical message and page data, this can provide a 3X decrease
835 * in storage requirements.
840 protected function serialize( $data ) {
841 if ( is_int( $data ) ) {
845 $serial = serialize( $data );
846 if ( function_exists( 'gzdeflate' ) ) {
847 $serial = gzdeflate( $serial );
854 * Unserialize and, if necessary, decompress an object.
855 * @param string $serial
858 protected function unserialize( $serial ) {
859 if ( $this->isInteger( $serial ) ) {
863 if ( function_exists( 'gzinflate' ) ) {
864 Wikimedia\
suppressWarnings();
865 $decomp = gzinflate( $serial );
866 Wikimedia\restoreWarnings
();
868 if ( $decomp !== false ) {
873 return unserialize( $serial );
877 * Handle a DBError which occurred during a read operation.
879 * @param DBError $exception
880 * @param int $serverIndex
882 protected function handleReadError( DBError
$exception, $serverIndex ) {
883 if ( $exception instanceof DBConnectionError
) {
884 $this->markServerDown( $exception, $serverIndex );
887 $this->setAndLogDBError( $exception );
891 * Handle a DBQueryError which occurred during a write operation.
893 * @param DBError $exception
894 * @param IDatabase|null $db DB handle or null if connection failed
895 * @param int $serverIndex
898 protected function handleWriteError( DBError
$exception, $db, $serverIndex ) {
899 if ( !( $db instanceof IDatabase
) ) {
900 $this->markServerDown( $exception, $serverIndex );
903 $this->setAndLogDBError( $exception );
907 * @param DBError $exception
909 private function setAndLogDBError( DBError
$exception ) {
910 $this->logger
->error( "DBError: {$exception->getMessage()}" );
911 if ( $exception instanceof DBConnectionError
) {
912 $this->setLastError( BagOStuff
::ERR_UNREACHABLE
);
913 $this->logger
->debug( __METHOD__
. ": ignoring connection error" );
915 $this->setLastError( BagOStuff
::ERR_UNEXPECTED
);
916 $this->logger
->debug( __METHOD__
. ": ignoring query error" );
921 * Mark a server down due to a DBConnectionError exception
923 * @param DBError $exception
924 * @param int $serverIndex
926 protected function markServerDown( DBError
$exception, $serverIndex ) {
927 unset( $this->conns
[$serverIndex] ); // bug T103435
929 if ( isset( $this->connFailureTimes
[$serverIndex] ) ) {
930 if ( time() - $this->connFailureTimes
[$serverIndex] >= 60 ) {
931 unset( $this->connFailureTimes
[$serverIndex] );
932 unset( $this->connFailureErrors
[$serverIndex] );
934 $this->logger
->debug( __METHOD__
. ": Server #$serverIndex already down" );
939 $this->logger
->info( __METHOD__
. ": Server #$serverIndex down until " . ( $now +
60 ) );
940 $this->connFailureTimes
[$serverIndex] = $now;
941 $this->connFailureErrors
[$serverIndex] = $exception;
945 * Create shard tables. For use from eval.php.
947 public function createTables() {
948 for ( $serverIndex = 0; $serverIndex < $this->numServers
; $serverIndex++
) {
949 $db = $this->getDB( $serverIndex );
950 if ( $db->getType() !== 'mysql' ) {
951 throw new MWException( __METHOD__
. ' is not supported on this DB server' );
954 for ( $i = 0; $i < $this->shards
; $i++
) {
956 'CREATE TABLE ' . $db->tableName( $this->getTableNameByShard( $i ) ) .
957 ' LIKE ' . $db->tableName( 'objectcache' ),
964 * @return bool Whether the main DB is used, e.g. wfGetDB( DB_MASTER )
966 protected function usesMainDB() {
967 return !$this->serverInfos
;
970 protected function waitForReplication() {
971 if ( !$this->usesMainDB() ) {
972 // Custom DB server list; probably doesn't use replication
976 $lb = MediaWikiServices
::getInstance()->getDBLoadBalancer();
977 if ( $lb->getServerCount() <= 1 ) {
978 return true; // no replica DBs
981 // Main LB is used; wait for any replica DBs to catch up
983 $masterPos = $lb->getMasterPos();
985 return true; // not applicable
988 $loop = new WaitConditionLoop(
989 function () use ( $lb, $masterPos ) {
990 return $lb->waitForAll( $masterPos, 1 );
996 return ( $loop->invoke() === $loop::CONDITION_REACHED
);
997 } catch ( DBError
$e ) {
998 $this->setAndLogDBError( $e );
1005 * Returns a ScopedCallback which resets the silence flag in the transaction profiler when it is
1006 * destroyed on the end of a scope, for example on return or throw
1007 * @return ScopedCallback
1010 protected function silenceTransactionProfiler() {
1011 $trxProfiler = Profiler
::instance()->getTransactionProfiler();
1012 $oldSilenced = $trxProfiler->setSilenced( true );
1013 return new ScopedCallback( function () use ( $trxProfiler, $oldSilenced ) {
1014 $trxProfiler->setSilenced( $oldSilenced );