31 use Wikimedia\ScopedCallback;
32 use Wikimedia\WaitConditionLoop;
105 parent::__construct(
$params );
110 if ( isset(
$params[
'servers'] ) ) {
111 $this->serverInfos = [];
112 $this->serverTags = [];
115 foreach (
$params[
'servers']
as $tag => $info ) {
116 $this->serverInfos[$index] = $info;
117 if ( is_string( $tag ) ) {
118 $this->serverTags[$index] = $tag;
120 $this->serverTags[$index] = $info[
'host'] ??
"#$index";
124 } elseif ( isset(
$params[
'server'] ) ) {
125 $this->serverInfos = [
$params[
'server'] ];
126 $this->numServers =
count( $this->serverInfos );
129 $this->serverInfos =
false;
130 $this->numServers = 1;
133 if ( isset(
$params[
'purgePeriod'] ) ) {
134 $this->purgePeriod = intval(
$params[
'purgePeriod'] );
136 if ( isset(
$params[
'tableName'] ) ) {
139 if ( isset(
$params[
'shards'] ) ) {
140 $this->shards = intval(
$params[
'shards'] );
142 if ( isset(
$params[
'syncTimeout'] ) ) {
143 $this->syncTimeout =
$params[
'syncTimeout'];
145 $this->replicaOnly = !empty(
$params[
'slaveOnly'] );
155 protected function getDB( $serverIndex ) {
156 if ( !isset( $this->conns[$serverIndex] ) ) {
157 if ( $serverIndex >= $this->numServers ) {
158 throw new MWException( __METHOD__ .
": Invalid server index \"$serverIndex\"" );
161 # Don't keep timing out trying to connect for each call if the DB is down
162 if ( isset( $this->connFailureErrors[$serverIndex] )
163 && ( time() - $this->connFailureTimes[$serverIndex] ) < 60
165 throw $this->connFailureErrors[$serverIndex];
168 if ( $this->serverInfos ) {
170 $info = $this->serverInfos[$serverIndex];
171 $type = $info[
'type'] ??
'mysql';
172 $host = $info[
'host'] ??
'[unknown]';
173 $this->logger->debug( __CLASS__ .
": connecting to $host" );
174 $db = Database::factory(
$type, $info );
178 $lb = MediaWikiServices::getInstance()->getDBLoadBalancer();
180 if ( $lb->getServerType( $lb->getWriterIndex() ) !==
'sqlite' ) {
182 $db = $lb->getConnection( $index, [],
false, $lb::CONN_TRX_AUTOCOMMIT );
186 $db = $lb->getConnection( $index );
190 $this->logger->debug( sprintf(
"Connection %s will be used for SqlBagOStuff", $db ) );
191 $this->conns[$serverIndex] = $db;
194 return $this->conns[$serverIndex];
203 if ( $this->shards > 1 ) {
204 $hash = hexdec( substr( md5( $key ), 0, 8 ) ) & 0x7fffffff;
209 if ( $this->numServers > 1 ) {
212 reset( $sortedServers );
213 $serverIndex =
key( $sortedServers );
226 if ( $this->shards > 1 ) {
227 $decimals = strlen( $this->shards - 1 );
229 sprintf(
"%0{$decimals}d", $index );
235 protected function doGet( $key, $flags = 0 ) {
242 $values = $this->
getMulti( [ $key ] );
243 if ( array_key_exists( $key, $values ) ) {
244 $casToken = $values[$key];
245 return $values[$key];
256 $keysByTable[$serverIndex][
$tableName][] = $key;
262 foreach ( $keysByTable
as $serverIndex => $serverKeys ) {
264 $db = $this->
getDB( $serverIndex );
267 [
'keyname',
'value',
'exptime' ],
268 [
'keyname' => $tableKeys ],
273 $db->trxLevel() ? [
'LOCK IN SHARE MODE' ] : []
275 if (
$res ===
false ) {
278 foreach (
$res as $row ) {
279 $row->serverIndex = $serverIndex;
281 $dataRows[$row->keyname] = $row;
290 if ( isset( $dataRows[$key] ) ) {
291 $row = $dataRows[$key];
292 $this->
debug(
"get: retrieved data; expiry time is " . $row->exptime );
295 $db = $this->
getDB( $row->serverIndex );
296 if ( $this->
isExpired( $db, $row->exptime ) ) {
297 $this->
debug(
"get: key has expired" );
299 $values[$key] = $this->
unserialize( $db->decodeBlob( $row->value ) );
305 $this->
debug(
'get: no matching rows' );
314 foreach ( $data
as $key =>
$value ) {
316 $keysByTable[$serverIndex][
$tableName][] = $key;
322 $exptime = (int)$expiry;
324 foreach ( $keysByTable
as $serverIndex => $serverKeys ) {
327 $db = $this->
getDB( $serverIndex );
334 if ( $exptime < 0 ) {
338 if ( $exptime == 0 ) {
342 $encExpiry = $db->timestamp( $exptime );
346 foreach ( $tableKeys
as $key ) {
349 'value' => $db->encodeBlob( $this->
serialize( $data[$key] ) ),
350 'exptime' => $encExpiry,
373 public function set( $key,
$value, $exptime = 0, $flags = 0 ) {
375 if ( ( $flags & self::WRITE_SYNC ) == self::WRITE_SYNC ) {
382 protected function cas( $casToken, $key,
$value, $exptime = 0 ) {
387 $db = $this->
getDB( $serverIndex );
388 $exptime = intval( $exptime );
390 if ( $exptime < 0 ) {
394 if ( $exptime == 0 ) {
398 $encExpiry = $db->timestamp( $exptime );
406 'value' => $db->encodeBlob( $this->serialize(
$value ) ),
407 'exptime' => $encExpiry
411 'value' => $db->encodeBlob( $this->serialize( $casToken ) )
421 return (
bool)$db->affectedRows();
424 public function delete( $key ) {
429 $db = $this->
getDB( $serverIndex );
432 [
'keyname' => $key ],
442 public function incr( $key, $step = 1 ) {
447 $db = $this->
getDB( $serverIndex );
448 $step = intval( $step );
449 $row = $db->selectRow(
451 [
'value',
'exptime' ],
452 [
'keyname' => $key ],
455 if ( $row ===
false ) {
460 $db->delete(
$tableName, [
'keyname' => $key ], __METHOD__ );
461 if ( $this->
isExpired( $db, $row->exptime ) ) {
467 $oldValue = intval( $this->
unserialize( $db->decodeBlob( $row->value ) ) );
468 $newValue = $oldValue + $step;
472 'value' => $db->encodeBlob( $this->serialize( $newValue ) ),
473 'exptime' => $row->exptime
474 ], __METHOD__,
'IGNORE' );
476 if ( $db->affectedRows() == 0 ) {
488 public function merge( $key, callable $callback, $exptime = 0, $attempts = 10, $flags = 0 ) {
489 $ok = $this->
mergeViaCas( $key, $callback, $exptime, $attempts );
490 if ( ( $flags & self::WRITE_SYNC ) == self::WRITE_SYNC ) {
502 $db = $this->
getDB( $serverIndex );
505 [
'exptime' => $db->timestamp( $this->convertExpiry( $expiry ) ) ],
506 [
'keyname' => $key,
'exptime > ' . $db->addQuotes( $db->timestamp( time() ) ) ],
509 if ( $db->affectedRows() == 0 ) {
534 if ( time() > 0x7fffffff ) {
535 return $db->timestamp( 1 << 62 );
537 return $db->timestamp( 0x7fffffff );
542 if ( !$this->purgePeriod || $this->replicaOnly ) {
547 if ( $this->purgePeriod !== 1 && mt_rand( 0, $this->purgePeriod - 1 ) ) {
552 if ( $now > ( $this->lastExpireAll + 1 ) ) {
553 $this->lastExpireAll = $now;
573 $db = $this->
getDB( $serverIndex );
574 $dbTimestamp = $db->timestamp( $timestamp );
575 $totalSeconds =
false;
576 $baseConds = [
'exptime < ' . $db->addQuotes( $dbTimestamp ) ];
581 if ( $maxExpTime !==
false ) {
582 $conds[] =
'exptime >= ' . $db->addQuotes( $maxExpTime );
586 [
'keyname',
'exptime' ],
589 [
'LIMIT' => 100,
'ORDER BY' =>
'exptime' ] );
594 $row =
$rows->current();
595 $minExpTime = $row->exptime;
596 if ( $totalSeconds ===
false ) {
601 $keys[] = $row->keyname;
602 $maxExpTime = $row->exptime;
608 'exptime >= ' . $db->addQuotes( $minExpTime ),
609 'exptime < ' . $db->addQuotes( $dbTimestamp ),
614 if ( $progressCallback ) {
615 if ( intval( $totalSeconds ) === 0 ) {
618 $remainingSeconds =
wfTimestamp( TS_UNIX, $timestamp )
620 if ( $remainingSeconds > $totalSeconds ) {
621 $totalSeconds = $remainingSeconds;
623 $processedSeconds = $totalSeconds - $remainingSeconds;
624 $percent = ( $i + $processedSeconds / $totalSeconds )
625 / $this->shards * 100;
628 + ( $serverIndex / $this->numServers * 100 );
629 call_user_func( $progressCallback, $percent );
651 $db = $this->
getDB( $serverIndex );
674 if ( function_exists(
'gzdeflate' ) ) {
675 return gzdeflate( $serial );
687 if ( function_exists(
'gzinflate' ) ) {
688 Wikimedia\suppressWarnings();
689 $decomp = gzinflate( $serial );
690 Wikimedia\restoreWarnings();
692 if (
false !== $decomp ) {
712 $this->logger->error(
"DBError: {$exception->getMessage()}" );
715 $this->logger->debug( __METHOD__ .
": ignoring connection error" );
718 $this->logger->debug( __METHOD__ .
": ignoring query error" );
733 } elseif ( $db->wasReadOnlyError() ) {
734 if ( $db->trxLevel() && $this->
usesMainDB() ) {
742 $this->logger->error(
"DBError: {$exception->getMessage()}" );
745 $this->logger->debug( __METHOD__ .
": ignoring connection error" );
748 $this->logger->debug( __METHOD__ .
": ignoring query error" );
759 unset( $this->conns[$serverIndex] );
761 if ( isset( $this->connFailureTimes[$serverIndex] ) ) {
762 if ( time() - $this->connFailureTimes[$serverIndex] >= 60 ) {
763 unset( $this->connFailureTimes[$serverIndex] );
764 unset( $this->connFailureErrors[$serverIndex] );
766 $this->logger->debug( __METHOD__ .
": Server #$serverIndex already down" );
771 $this->logger->info( __METHOD__ .
": Server #$serverIndex down until " . ( $now + 60 ) );
772 $this->connFailureTimes[$serverIndex] = $now;
773 $this->connFailureErrors[$serverIndex] = $exception;
781 $db = $this->
getDB( $serverIndex );
782 if ( $db->getType() !==
'mysql' ) {
783 throw new MWException( __METHOD__ .
' is not supported on this DB server' );
788 'CREATE TABLE ' . $db->tableName( $this->getTableNameByShard( $i ) ) .
789 ' LIKE ' . $db->tableName(
'objectcache' ),
808 $lb = MediaWikiServices::getInstance()->getDBLoadBalancer();
809 if ( $lb->getServerCount() <= 1 ) {
814 $masterPos = $lb->getMasterPos();
819 $loop =
new WaitConditionLoop(
820 function ()
use ( $lb, $masterPos ) {
821 return $lb->waitForAll( $masterPos, 1 );
827 return ( $loop->invoke() === $loop::CONDITION_REACHED );
838 $oldSilenced = $trxProfiler->setSilenced(
true );
839 return new ScopedCallback(
function ()
use ( $trxProfiler, $oldSilenced ) {
840 $trxProfiler->setSilenced( $oldSilenced );