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\Timestamp\ConvertibleTimestamp
;
35 use Wikimedia\WaitConditionLoop
;
38 * Class to store objects in the database
42 class SqlBagOStuff
extends MediumSpecificBagOStuff
{
43 /** @var array[] (server index => server config) */
44 protected $serverInfos;
45 /** @var string[] (server index => tag/host name) */
46 protected $serverTags;
48 protected $numServerShards;
49 /** @var int UNIX timestamp */
50 protected $lastGarbageCollect = 0;
52 protected $purgePeriod = 10;
54 protected $purgeLimit = 100;
56 protected $numTableShards = 1;
58 protected $tableName = 'objectcache';
60 protected $replicaOnly = false;
62 /** @var LoadBalancer|null */
63 protected $separateMainLB;
66 /** @var array UNIX timestamps */
67 protected $connFailureTimes = [];
68 /** @var array Exceptions */
69 protected $connFailureErrors = [];
72 private static $GC_DELAY_SEC = 1;
75 private static $OP_SET = 'set';
77 private static $OP_ADD = 'add';
79 private static $OP_TOUCH = 'touch';
81 private static $OP_DELETE = 'delete';
84 * Constructor. Parameters are:
85 * - server: A server info structure in the format required by each
86 * element in $wgDBServers.
88 * - servers: An array of server info structures describing a set of database servers
89 * to distribute keys to. If this is specified, the "server" option will be
90 * ignored. If string keys are used, then they will be used for consistent
91 * hashing *instead* of the host name (from the server config). This is useful
92 * when a cluster is replicated to another site (with different host names)
93 * but each server has a corresponding replica in the other cluster.
95 * - purgePeriod: The average number of object cache writes in between
96 * garbage collection operations, where expired entries
97 * are removed from the database. Or in other words, the
98 * reciprocal of the probability of purging on any given
99 * write. If this is set to zero, purging will never be done.
101 * - purgeLimit: Maximum number of rows to purge at once.
103 * - tableName: The table name to use, default is "objectcache".
105 * - shards: The number of tables to use for data storage on each server.
106 * If this is more than 1, table names will be formed in the style
107 * objectcacheNNN where NNN is the shard index, between 0 and
108 * shards-1. The number of digits will be the minimum number
109 * required to hold the largest shard index. Data will be
110 * distributed across all tables by key hash. This is for
111 * MySQL bugs 61735 <https://bugs.mysql.com/bug.php?id=61735>
112 * and 61736 <https://bugs.mysql.com/bug.php?id=61736>.
114 * - replicaOnly: Whether to only use replica DBs and avoid triggering
115 * garbage collection logic of expired items. This only
116 * makes sense if the primary DB is used and only if get()
117 * calls will be used. This is used by ReplicatedBagOStuff.
118 * - syncTimeout: Max seconds to wait for replica DBs to catch up for WRITE_SYNC.
120 * @param array $params
122 public function __construct( $params ) {
123 parent
::__construct( $params );
125 $this->attrMap
[self
::ATTR_EMULATION
] = self
::QOS_EMULATION_SQL
;
126 $this->attrMap
[self
::ATTR_SYNCWRITES
] = self
::QOS_SYNCWRITES_NONE
;
128 if ( isset( $params['servers'] ) ) {
129 $this->serverInfos
= [];
130 $this->serverTags
= [];
131 $this->numServerShards
= count( $params['servers'] );
133 foreach ( $params['servers'] as $tag => $info ) {
134 $this->serverInfos
[$index] = $info;
135 if ( is_string( $tag ) ) {
136 $this->serverTags
[$index] = $tag;
138 $this->serverTags
[$index] = $info['host'] ??
"#$index";
142 } elseif ( isset( $params['server'] ) ) {
143 $this->serverInfos
= [ $params['server'] ];
144 $this->numServerShards
= count( $this->serverInfos
);
146 // Default to using the main wiki's database servers
147 $this->serverInfos
= false;
148 $this->numServerShards
= 1;
149 $this->attrMap
[self
::ATTR_SYNCWRITES
] = self
::QOS_SYNCWRITES_BE
;
151 if ( isset( $params['purgePeriod'] ) ) {
152 $this->purgePeriod
= intval( $params['purgePeriod'] );
154 if ( isset( $params['purgeLimit'] ) ) {
155 $this->purgeLimit
= intval( $params['purgeLimit'] );
157 if ( isset( $params['tableName'] ) ) {
158 $this->tableName
= $params['tableName'];
160 if ( isset( $params['shards'] ) ) {
161 $this->numTableShards
= intval( $params['shards'] );
163 // Backwards-compatibility for < 1.34
164 $this->replicaOnly
= $params['replicaOnly'] ??
( $params['slaveOnly'] ??
false );
168 * Get a connection to the specified database
170 * @param int $shardIndex
171 * @return IMaintainableDatabase
172 * @throws MWException
174 private function getConnection( $shardIndex ) {
175 if ( $shardIndex >= $this->numServerShards
) {
176 throw new MWException( __METHOD__
. ": Invalid server index \"$shardIndex\"" );
179 # Don't keep timing out trying to connect for each call if the DB is down
181 isset( $this->connFailureErrors
[$shardIndex] ) &&
182 ( $this->getCurrentTime() - $this->connFailureTimes
[$shardIndex] ) < 60
184 throw $this->connFailureErrors
[$shardIndex];
187 if ( $this->serverInfos
) {
188 if ( !isset( $this->conns
[$shardIndex] ) ) {
189 // Use custom database defined by server connection info
190 $info = $this->serverInfos
[$shardIndex];
191 $type = $info['type'] ??
'mysql';
192 $host = $info['host'] ??
'[unknown]';
193 $this->logger
->debug( __CLASS__
. ": connecting to $host" );
194 $conn = Database
::factory( $type, $info );
195 $conn->clearFlag( DBO_TRX
); // auto-commit mode
196 $this->conns
[$shardIndex] = $conn;
198 $conn = $this->conns
[$shardIndex];
200 // Use the main LB database
201 $lb = MediaWikiServices
::getInstance()->getDBLoadBalancer();
202 $index = $this->replicaOnly ? DB_REPLICA
: DB_MASTER
;
203 // If the RDBMS has row-level locking, use the autocommit connection to avoid
204 // contention and deadlocks. Do not do this if it only has DB-level locking since
205 // that would just cause deadlocks.
206 $attribs = $lb->getServerAttributes( $lb->getWriterIndex() );
207 $flags = $attribs[Database
::ATTR_DB_LEVEL_LOCKING
] ?
0 : $lb::CONN_TRX_AUTOCOMMIT
;
208 $conn = $lb->getMaintenanceConnectionRef( $index, [], false, $flags );
209 // Automatically create the objectcache table for sqlite as needed
210 if ( $conn->getType() === 'sqlite' ) {
211 $this->initSqliteDatabase( $conn );
215 $this->logger
->debug( sprintf( "Connection %s will be used for SqlBagOStuff", $conn ) );
221 * Get the server index and table name for a given key
223 * @return array Server index and table name
225 private function getTableByKey( $key ) {
226 if ( $this->numTableShards
> 1 ) {
227 $hash = hexdec( substr( md5( $key ), 0, 8 ) ) & 0x7fffffff;
228 $tableIndex = $hash %
$this->numTableShards
;
232 if ( $this->numServerShards
> 1 ) {
233 $sortedServers = $this->serverTags
;
234 ArrayUtils
::consistentHashSort( $sortedServers, $key );
235 reset( $sortedServers );
236 $shardIndex = key( $sortedServers );
240 return [ $shardIndex, $this->getTableNameByShard( $tableIndex ) ];
244 * Get the table name for a given shard index
248 private function getTableNameByShard( $index ) {
249 if ( $this->numTableShards
> 1 ) {
250 $decimals = strlen( $this->numTableShards
- 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 private function fetchBlobMulti( array $keys, $flags = 0 ) {
286 $values = []; // array of (key => value)
289 foreach ( $keys as $key ) {
290 list( $shardIndex, $tableName ) = $this->getTableByKey( $key );
291 $keysByTable[$shardIndex][$tableName][] = $key;
295 foreach ( $keysByTable as $shardIndex => $serverKeys ) {
297 $db = $this->getConnection( $shardIndex );
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->shardIndex
= $shardIndex;
313 $row->tableName
= $tableName;
314 $dataRows[$row->keyname
] = $row;
317 } catch ( DBError
$e ) {
318 $this->handleReadError( $e, $shardIndex );
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->getConnection( $row->shardIndex
);
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->shardIndex
);
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( $shardIndex, $tableName ) = $this->getTableByKey( $key );
360 $keysByTable[$shardIndex][$tableName][] = $key;
363 $exptime = $this->getExpirationAsTimestamp( $exptime );
366 /** @noinspection PhpUnusedLocalVariableInspection */
367 $silenceScope = $this->silenceTransactionProfiler();
368 foreach ( $keysByTable as $shardIndex => $serverKeys ) {
369 $db = null; // in case of connection failure
371 $db = $this->getConnection( $shardIndex );
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, $shardIndex );
380 foreach ( $serverKeys as $tableName => $tableKeys ) {
382 $result = $this->updateTableKeys(
390 } catch ( DBError
$e ) {
391 $this->handleWriteError( $e, $db, $shardIndex );
398 if ( $this->fieldHasFlags( $flags, 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 protected function doAdd( $key, $value, $exptime = 0, $flags = 0 ) {
475 return $this->modifyMulti( [ $key => $value ], $exptime, $flags, self
::$OP_ADD );
478 protected function doCas( $casToken, $key, $value, $exptime = 0, $flags = 0 ) {
479 list( $shardIndex, $tableName ) = $this->getTableByKey( $key );
480 $exptime = $this->getExpirationAsTimestamp( $exptime );
482 /** @noinspection PhpUnusedLocalVariableInspection */
483 $silenceScope = $this->silenceTransactionProfiler();
484 $db = null; // in case of connection failure
486 $db = $this->getConnection( $shardIndex );
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, $shardIndex );
511 $success = (bool)$db->affectedRows();
512 if ( $this->fieldHasFlags( $flags, self
::WRITE_SYNC
) ) {
513 $success = $this->waitForReplication() && $success;
519 protected function doDeleteMulti( array $keys, $flags = 0 ) {
520 return $this->modifyMulti(
521 array_fill_keys( $keys, null ),
528 protected function doDelete( $key, $flags = 0 ) {
529 return $this->modifyMulti( [ $key => null ], 0, $flags, self
::$OP_DELETE );
532 public function incr( $key, $step = 1, $flags = 0 ) {
533 list( $shardIndex, $tableName ) = $this->getTableByKey( $key );
536 /** @noinspection PhpUnusedLocalVariableInspection */
537 $silenceScope = $this->silenceTransactionProfiler();
538 $db = null; // in case of connection failure
540 $db = $this->getConnection( $shardIndex );
541 $encTimestamp = $db->addQuotes( $db->timestamp() );
544 [ 'value = value + ' . (int)$step ],
545 [ 'keyname' => $key, "exptime > $encTimestamp" ],
548 if ( $db->affectedRows() > 0 ) {
549 $newValue = $db->selectField(
552 [ 'keyname' => $key, "exptime > $encTimestamp" ],
555 if ( $this->isInteger( $newValue ) ) {
556 $newCount = (int)$newValue;
559 } catch ( DBError
$e ) {
560 $this->handleWriteError( $e, $db, $shardIndex );
566 public function decr( $key, $value = 1, $flags = 0 ) {
567 return $this->incr( $key, -$value, $flags );
570 public function changeTTLMulti( 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 private function isExpired( IDatabase
$db, $exptime ) {
590 $exptime != $this->getMaxDateTime( $db ) &&
591 ConvertibleTimestamp
::convert( TS_UNIX
, $exptime ) < $this->getCurrentTime()
596 * @param IDatabase $db
599 private function getMaxDateTime( $db ) {
600 if ( (int)$this->getCurrentTime() > 0x7fffffff ) {
601 return $db->timestamp( 1 << 62 );
603 return $db->timestamp( 0x7fffffff );
608 * @param IDatabase $db
611 private 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 ( $this->getCurrentTime() - $this->lastGarbageCollect
) > self
::$GC_DELAY_SEC
620 $garbageCollector = function () use ( $db ) {
621 $this->deleteServerObjectsExpiringBefore(
622 $db, $this->getCurrentTime(),
626 $this->lastGarbageCollect
= time();
628 if ( $this->asyncHandler
) {
629 $this->lastGarbageCollect
= $this->getCurrentTime(); // avoid duplicate enqueues
630 ( $this->asyncHandler
)( $garbageCollector );
637 public function expireAll() {
638 $this->deleteObjectsExpiringBefore( $this->getCurrentTime() );
641 public function deleteObjectsExpiringBefore(
643 callable
$progress = null,
646 /** @noinspection PhpUnusedLocalVariableInspection */
647 $silenceScope = $this->silenceTransactionProfiler();
649 $shardIndexes = range( 0, $this->numServerShards
- 1 );
650 shuffle( $shardIndexes );
654 $keysDeletedCount = 0;
655 foreach ( $shardIndexes as $numServersDone => $shardIndex ) {
656 $db = null; // in case of connection failure
658 $db = $this->getConnection( $shardIndex );
659 $this->deleteServerObjectsExpiringBefore(
667 } catch ( DBError
$e ) {
668 $this->handleWriteError( $e, $db, $shardIndex );
677 * @param IDatabase $db
678 * @param string|int $timestamp
679 * @param callable|null $progressCallback
681 * @param int $serversDoneCount
682 * @param int &$keysDeletedCount
685 private function deleteServerObjectsExpiringBefore(
690 $serversDoneCount = 0,
691 &$keysDeletedCount = 0
693 $cutoffUnix = ConvertibleTimestamp
::convert( TS_UNIX
, $timestamp );
694 $shardIndexes = range( 0, $this->numTableShards
- 1 );
695 shuffle( $shardIndexes );
697 foreach ( $shardIndexes as $numShardsDone => $shardIndex ) {
698 $continue = null; // last exptime
699 $lag = null; // purge lag
702 $this->getTableNameByShard( $shardIndex ),
703 [ 'keyname', 'exptime' ],
705 [ 'exptime < ' . $db->addQuotes( $db->timestamp( $cutoffUnix ) ) ],
706 $continue ?
[ 'exptime >= ' . $db->addQuotes( $continue ) ] : []
709 [ 'LIMIT' => min( $limit, 100 ), 'ORDER BY' => 'exptime' ]
712 if ( $res->numRows() ) {
713 $row = $res->current();
714 if ( $lag === null ) {
715 $rowExpUnix = ConvertibleTimestamp
::convert( TS_UNIX
, $row->exptime
);
716 $lag = max( $cutoffUnix - $rowExpUnix, 1 );
720 foreach ( $res as $row ) {
721 $keys[] = $row->keyname
;
722 $continue = $row->exptime
;
726 $this->getTableNameByShard( $shardIndex ),
728 'exptime < ' . $db->addQuotes( $db->timestamp( $cutoffUnix ) ),
733 $keysDeletedCount +
= $db->affectedRows();
736 if ( is_callable( $progressCallback ) ) {
738 $continueUnix = ConvertibleTimestamp
::convert( TS_UNIX
, $continue );
739 $remainingLag = $cutoffUnix - $continueUnix;
740 $processedLag = max( $lag - $remainingLag, 0 );
741 $doneRatio = ( $numShardsDone +
$processedLag / $lag ) / $this->numTableShards
;
746 $overallRatio = ( $doneRatio / $this->numServerShards
)
747 +
( $serversDoneCount / $this->numServerShards
);
748 call_user_func( $progressCallback, $overallRatio * 100 );
750 } while ( $res->numRows() && $keysDeletedCount < $limit );
755 * Delete content of shard tables in every server.
756 * Return true if the operation is successful, false otherwise.
759 public function deleteAll() {
760 /** @noinspection PhpUnusedLocalVariableInspection */
761 $silenceScope = $this->silenceTransactionProfiler();
762 for ( $shardIndex = 0; $shardIndex < $this->numServerShards
; $shardIndex++
) {
763 $db = null; // in case of connection failure
765 $db = $this->getConnection( $shardIndex );
766 for ( $i = 0; $i < $this->numTableShards
; $i++
) {
767 $db->delete( $this->getTableNameByShard( $i ), '*', __METHOD__
);
769 } catch ( DBError
$e ) {
770 $this->handleWriteError( $e, $db, $shardIndex );
777 public function lock( $key, $timeout = 6, $expiry = 6, $rclass = '' ) {
778 // Avoid deadlocks and allow lock reentry if specified
779 if ( isset( $this->locks
[$key] ) ) {
780 if ( $rclass != '' && $this->locks
[$key]['class'] === $rclass ) {
781 ++
$this->locks
[$key]['depth'];
788 list( $shardIndex ) = $this->getTableByKey( $key );
790 $db = null; // in case of connection failure
792 $db = $this->getConnection( $shardIndex );
793 $ok = $db->lock( $key, __METHOD__
, $timeout );
795 $this->locks
[$key] = [ 'class' => $rclass, 'depth' => 1 ];
798 $this->logger
->warning(
799 __METHOD__
. " failed due to timeout for {key}.",
800 [ 'key' => $key, 'timeout' => $timeout ]
804 } catch ( DBError
$e ) {
805 $this->handleWriteError( $e, $db, $shardIndex );
812 public function unlock( $key ) {
813 if ( !isset( $this->locks
[$key] ) ) {
817 if ( --$this->locks
[$key]['depth'] <= 0 ) {
818 unset( $this->locks
[$key] );
820 list( $shardIndex ) = $this->getTableByKey( $key );
822 $db = null; // in case of connection failure
824 $db = $this->getConnection( $shardIndex );
825 $ok = $db->unlock( $key, __METHOD__
);
827 $this->logger
->warning(
828 __METHOD__
. ' failed to release lock for {key}.',
832 } catch ( DBError
$e ) {
833 $this->handleWriteError( $e, $db, $shardIndex );
844 * Serialize an object and, if possible, compress the representation.
845 * On typical message and page data, this can provide a 3X decrease
846 * in storage requirements.
851 protected function serialize( $data ) {
852 if ( is_int( $data ) ) {
856 $serial = serialize( $data );
857 if ( function_exists( 'gzdeflate' ) ) {
858 $serial = gzdeflate( $serial );
865 * Unserialize and, if necessary, decompress an object.
866 * @param string $serial
869 protected function unserialize( $serial ) {
870 if ( $this->isInteger( $serial ) ) {
874 if ( function_exists( 'gzinflate' ) ) {
875 AtEase
::suppressWarnings();
876 $decomp = gzinflate( $serial );
877 AtEase
::restoreWarnings();
879 if ( $decomp !== false ) {
884 return unserialize( $serial );
888 * Handle a DBError which occurred during a read operation.
890 * @param DBError $exception
891 * @param int $shardIndex
893 private function handleReadError( DBError
$exception, $shardIndex ) {
894 if ( $exception instanceof DBConnectionError
) {
895 $this->markServerDown( $exception, $shardIndex );
898 $this->setAndLogDBError( $exception );
902 * Handle a DBQueryError which occurred during a write operation.
904 * @param DBError $exception
905 * @param IDatabase|null $db DB handle or null if connection failed
906 * @param int $shardIndex
909 private function handleWriteError( DBError
$exception, $db, $shardIndex ) {
910 if ( !( $db instanceof IDatabase
) ) {
911 $this->markServerDown( $exception, $shardIndex );
914 $this->setAndLogDBError( $exception );
918 * @param DBError $exception
920 private function setAndLogDBError( DBError
$exception ) {
921 $this->logger
->error( "DBError: {$exception->getMessage()}" );
922 if ( $exception instanceof DBConnectionError
) {
923 $this->setLastError( BagOStuff
::ERR_UNREACHABLE
);
924 $this->logger
->debug( __METHOD__
. ": ignoring connection error" );
926 $this->setLastError( BagOStuff
::ERR_UNEXPECTED
);
927 $this->logger
->debug( __METHOD__
. ": ignoring query error" );
932 * Mark a server down due to a DBConnectionError exception
934 * @param DBError $exception
935 * @param int $shardIndex
937 private function markServerDown( DBError
$exception, $shardIndex ) {
938 unset( $this->conns
[$shardIndex] ); // bug T103435
940 $now = $this->getCurrentTime();
941 if ( isset( $this->connFailureTimes
[$shardIndex] ) ) {
942 if ( $now - $this->connFailureTimes
[$shardIndex] >= 60 ) {
943 unset( $this->connFailureTimes
[$shardIndex] );
944 unset( $this->connFailureErrors
[$shardIndex] );
946 $this->logger
->debug( __METHOD__
. ": Server #$shardIndex already down" );
950 $this->logger
->info( __METHOD__
. ": Server #$shardIndex down until " . ( $now +
60 ) );
951 $this->connFailureTimes
[$shardIndex] = $now;
952 $this->connFailureErrors
[$shardIndex] = $exception;
956 * @param IMaintainableDatabase $db
959 private function initSqliteDatabase( IMaintainableDatabase
$db ) {
960 if ( $db->tableExists( 'objectcache' ) ) {
963 // Use one table for SQLite; sharding does not seem to have much benefit
964 $db->query( "PRAGMA journal_mode=WAL" ); // this is permanent
965 $db->startAtomic( __METHOD__
); // atomic DDL
967 $encTable = $db->tableName( 'objectcache' );
968 $encExptimeIndex = $db->addIdentifierQuotes( $db->tablePrefix() . 'exptime' );
970 "CREATE TABLE $encTable (\n" .
971 " keyname BLOB NOT NULL default '' PRIMARY KEY,\n" .
977 $db->query( "CREATE INDEX $encExptimeIndex ON $encTable (exptime)" );
978 $db->endAtomic( __METHOD__
);
979 } catch ( DBError
$e ) {
980 $db->rollback( __METHOD__
);
986 * Create the shard tables on all databases (e.g. via eval.php/shell.php)
988 public function createTables() {
989 for ( $shardIndex = 0; $shardIndex < $this->numServerShards
; $shardIndex++
) {
990 $db = $this->getConnection( $shardIndex );
991 if ( in_array( $db->getType(), [ 'mysql', 'postgres' ], true ) ) {
992 for ( $i = 0; $i < $this->numTableShards
; $i++
) {
993 $encBaseTable = $db->tableName( 'objectcache' );
994 $encShardTable = $db->tableName( $this->getTableNameByShard( $i ) );
995 $db->query( "CREATE TABLE $encShardTable LIKE $encBaseTable" );
1002 * @return bool Whether the main DB is used, e.g. wfGetDB( DB_MASTER )
1004 private function usesMainDB() {
1005 return !$this->serverInfos
;
1008 private function waitForReplication() {
1009 if ( !$this->usesMainDB() ) {
1010 // Custom DB server list; probably doesn't use replication
1014 $lb = MediaWikiServices
::getInstance()->getDBLoadBalancer();
1015 if ( $lb->getServerCount() <= 1 ) {
1016 return true; // no replica DBs
1019 // Main LB is used; wait for any replica DBs to catch up
1021 $masterPos = $lb->getMasterPos();
1022 if ( !$masterPos ) {
1023 return true; // not applicable
1026 $loop = new WaitConditionLoop(
1027 function () use ( $lb, $masterPos ) {
1028 return $lb->waitForAll( $masterPos, 1 );
1031 $this->busyCallbacks
1034 return ( $loop->invoke() === $loop::CONDITION_REACHED
);
1035 } catch ( DBError
$e ) {
1036 $this->setAndLogDBError( $e );
1043 * Silence the transaction profiler until the return value falls out of scope
1045 * @return ScopedCallback|null
1047 private function silenceTransactionProfiler() {
1048 if ( !$this->usesMainDB() ) {
1049 // Custom DB is configured which either has no TransactionProfiler injected,
1050 // or has one specific for cache use, which we shouldn't silence
1054 $trxProfiler = Profiler
::instance()->getTransactionProfiler();
1055 $oldSilenced = $trxProfiler->setSilenced( true );
1056 return new ScopedCallback( function () use ( $trxProfiler, $oldSilenced ) {
1057 $trxProfiler->setSilenced( $oldSilenced );