MediaWiki fundraising/REL1_35
SqlBagOStuff.php
Go to the documentation of this file.
1<?php
24use Wikimedia\AtEase\AtEase;
25use Wikimedia\ObjectFactory;
33use Wikimedia\ScopedCallback;
34use Wikimedia\Timestamp\ConvertibleTimestamp;
35use Wikimedia\WaitConditionLoop;
36
44 protected $localKeyLb;
46 protected $globalKeyLb;
47
49 protected $serverInfos = [];
51 protected $serverTags = [];
55 protected $lastGarbageCollect = 0;
57 protected $purgePeriod = 10;
59 protected $purgeLimit = 100;
61 protected $numTableShards = 1;
63 protected $tableName = 'objectcache';
65 protected $replicaOnly;
66
68 protected $conns;
70 protected $connFailureTimes = [];
72 protected $connFailureErrors = [];
73
75 private static $GC_DELAY_SEC = 1;
76
78 private static $OP_SET = 'set';
80 private static $OP_ADD = 'add';
82 private static $OP_TOUCH = 'touch';
84 private static $OP_DELETE = 'delete';
85
87 private const SHARD_LOCAL = 'local';
89 private const SHARD_GLOBAL = 'global';
90
127 public function __construct( $params ) {
128 parent::__construct( $params );
129
130 $this->attrMap[self::ATTR_EMULATION] = self::QOS_EMULATION_SQL;
131
132 if ( isset( $params['servers'] ) || isset( $params['server'] ) ) {
133 $index = 0;
134 foreach ( ( $params['servers'] ?? [ $params['server'] ] ) as $tag => $info ) {
135 $this->serverInfos[$index] = $info;
136 $this->serverTags[$index] = is_string( $tag ) ? $tag : "#$index";
137 ++$index;
138 }
139 // Horizontal partitioning by key hash (if any)
140 $this->numServerShards = count( $this->serverInfos );
141 $this->attrMap[self::ATTR_SYNCWRITES] = self::QOS_SYNCWRITES_NONE;
142 } else {
143 if ( isset( $params['localKeyLB'] ) ) {
144 $this->localKeyLb = ( $params['localKeyLB'] instanceof ILoadBalancer )
145 ? $params['localKeyLB']
146 : ObjectFactory::getObjectFromSpec( $params['localKeyLB'] );
147 }
148 if ( isset( $params['globalKeyLB'] ) ) {
149 $this->globalKeyLb = ( $params['globalKeyLB'] instanceof ILoadBalancer )
150 ? $params['globalKeyLB']
151 : ObjectFactory::getObjectFromSpec( $params['globalKeyLB'] );
152 }
153 $this->localKeyLb = $this->localKeyLb ?: $this->globalKeyLb;
154 if ( !$this->localKeyLb ) {
155 throw new InvalidArgumentException(
156 "Config requires 'server', 'servers', or 'localKeyLB'/'globalKeyLB'"
157 );
158 }
159 // Verticle partitioning by global vs local keys (if any)
160 $this->numServerShards = ( $this->localKeyLb === $this->globalKeyLb ) ? 1 : 2;
161 $this->attrMap[self::ATTR_SYNCWRITES] = self::QOS_SYNCWRITES_BE;
162 }
163 if ( isset( $params['purgePeriod'] ) ) {
164 $this->purgePeriod = intval( $params['purgePeriod'] );
165 }
166 if ( isset( $params['purgeLimit'] ) ) {
167 $this->purgeLimit = intval( $params['purgeLimit'] );
168 }
169 if ( isset( $params['tableName'] ) ) {
170 $this->tableName = $params['tableName'];
171 }
172 if ( isset( $params['shards'] ) ) {
173 $this->numTableShards = intval( $params['shards'] );
174 }
175 $this->replicaOnly = $params['replicaOnly'] ?? false;
176 }
177
186 private function getConnection( $shardIndex ) {
187 // Don't keep timing out trying to connect if the server is down
188 if (
189 isset( $this->connFailureErrors[$shardIndex] ) &&
190 ( $this->getCurrentTime() - $this->connFailureTimes[$shardIndex] ) < 60
191 ) {
192 throw $this->connFailureErrors[$shardIndex];
193 }
194
195 if ( $shardIndex === self::SHARD_LOCAL ) {
196 $conn = $this->getConnectionViaLoadBalancer( $shardIndex );
197 } elseif ( $shardIndex === self::SHARD_GLOBAL ) {
198 $conn = $this->getConnectionViaLoadBalancer( $shardIndex );
199 } elseif ( is_int( $shardIndex ) ) {
200 if ( isset( $this->serverInfos[$shardIndex] ) ) {
201 $server = $this->serverInfos[$shardIndex];
202 $conn = $this->getConnectionFromServerInfo( $shardIndex, $server );
203 } else {
204 throw new UnexpectedValueException( "Invalid server index #$shardIndex" );
205 }
206 } else {
207 throw new UnexpectedValueException( "Invalid server index '$shardIndex'" );
208 }
209
210 return $conn;
211 }
212
218 private function getKeyLocation( $key ) {
219 if ( $this->serverTags ) {
220 // Striped array of database servers
221 if ( count( $this->serverTags ) == 1 ) {
222 $shardIndex = 0; // short-circuit
223 } else {
224 $sortedServers = $this->serverTags;
225 ArrayUtils::consistentHashSort( $sortedServers, $key );
226 reset( $sortedServers );
227 $shardIndex = key( $sortedServers );
228 }
229 } else {
230 // LoadBalancer based configuration
231 $shardIndex = ( strpos( $key, 'global:' ) === 0 && $this->globalKeyLb )
232 ? self::SHARD_GLOBAL
233 : self::SHARD_LOCAL;
234 }
235
236 if ( $this->numTableShards > 1 ) {
237 $hash = hexdec( substr( md5( $key ), 0, 8 ) ) & 0x7fffffff;
238 $tableIndex = $hash % $this->numTableShards;
239 } else {
240 $tableIndex = null;
241 }
242
243 return [ $shardIndex, $this->getTableNameByShard( $tableIndex ) ];
244 }
245
251 private function getTableNameByShard( $index ) {
252 if ( $index !== null && $this->numTableShards > 1 ) {
253 $decimals = strlen( $this->numTableShards - 1 );
254
255 return $this->tableName . sprintf( "%0{$decimals}d", $index );
256 }
257
258 return $this->tableName;
259 }
260
261 protected function doGet( $key, $flags = 0, &$casToken = null ) {
262 $casToken = null;
263
264 $blobs = $this->fetchBlobMulti( [ $key ] );
265 if ( array_key_exists( $key, $blobs ) ) {
266 $blob = $blobs[$key];
267 $value = $this->unserialize( $blob );
268
269 $casToken = ( $value !== false ) ? $blob : null;
270
271 return $value;
272 }
273
274 return false;
275 }
276
277 protected function doGetMulti( array $keys, $flags = 0 ) {
278 $values = [];
279
280 $blobs = $this->fetchBlobMulti( $keys );
281 foreach ( $blobs as $key => $blob ) {
282 $values[$key] = $this->unserialize( $blob );
283 }
284
285 return $values;
286 }
287
288 private function fetchBlobMulti( array $keys ) {
289 $values = []; // array of (key => value)
290
291 $keysByTableByShardIndex = [];
292 foreach ( $keys as $key ) {
293 list( $shardIndex, $tableName ) = $this->getKeyLocation( $key );
294 $keysByTableByShardIndex[$shardIndex][$tableName][] = $key;
295 }
296
297 $dataRows = [];
298 foreach ( $keysByTableByShardIndex as $shardIndex => $serverKeys ) {
299 try {
300 $db = $this->getConnection( $shardIndex );
301 foreach ( $serverKeys as $tableName => $tableKeys ) {
302 $res = $db->select(
304 [ 'keyname', 'value', 'exptime' ],
305 [ 'keyname' => $tableKeys ],
306 __METHOD__,
307 // Approximate write-on-the-fly BagOStuff API via blocking.
308 // This approximation fails if a ROLLBACK happens (which is rare).
309 // We do not want to flush the TRX as that can break callers.
310 $db->trxLevel() ? [ 'LOCK IN SHARE MODE' ] : []
311 );
312 if ( $res === false ) {
313 continue;
314 }
315 foreach ( $res as $row ) {
316 $row->shardIndex = $shardIndex;
317 $row->tableName = $tableName;
318 $dataRows[$row->keyname] = $row;
319 }
320 }
321 } catch ( DBError $e ) {
322 $this->handleReadError( $e, $shardIndex );
323 }
324 }
325
326 foreach ( $keys as $key ) {
327 if ( isset( $dataRows[$key] ) ) { // HIT?
328 $row = $dataRows[$key];
329 $this->debug( "get: retrieved data; expiry time is " . $row->exptime );
330 $db = null; // in case of connection failure
331 try {
332 $db = $this->getConnection( $row->shardIndex );
333 if ( $this->isExpired( $db, $row->exptime ) ) { // MISS
334 $this->debug( "get: key has expired" );
335 } else { // HIT
336 $values[$key] = $db->decodeBlob( $row->value );
337 }
338 } catch ( DBQueryError $e ) {
339 $this->handleWriteError( $e, $db, $row->shardIndex );
340 }
341 } else { // MISS
342 $this->debug( 'get: no matching rows' );
343 }
344 }
345
346 return $values;
347 }
348
349 protected function doSetMulti( array $data, $exptime = 0, $flags = 0 ) {
350 return $this->modifyMulti( $data, $exptime, $flags, self::$OP_SET );
351 }
352
360 private function modifyMulti( array $data, $exptime, $flags, $op ) {
361 $keysByTableByShardIndex = [];
362 foreach ( $data as $key => $value ) {
363 list( $shardIndex, $tableName ) = $this->getKeyLocation( $key );
364 $keysByTableByShardIndex[$shardIndex][$tableName][] = $key;
365 }
366
367 $exptime = $this->getExpirationAsTimestamp( $exptime );
368
369 $result = true;
371 $silenceScope = $this->silenceTransactionProfiler();
372 foreach ( $keysByTableByShardIndex as $shardIndex => $serverKeys ) {
373 $db = null; // in case of connection failure
374 try {
375 $db = $this->getConnection( $shardIndex );
376 $this->occasionallyGarbageCollect( $db ); // expire old entries if any
377 $dbExpiry = $exptime ? $db->timestamp( $exptime ) : $this->getMaxDateTime( $db );
378 } catch ( DBError $e ) {
379 $this->handleWriteError( $e, $db, $shardIndex );
380 $result = false;
381 continue;
382 }
383
384 foreach ( $serverKeys as $tableName => $tableKeys ) {
385 try {
386 $result = $this->updateTable(
387 $op,
388 $db,
390 $tableKeys,
391 $data,
392 $dbExpiry
393 ) && $result;
394 } catch ( DBError $e ) {
395 $this->handleWriteError( $e, $db, $shardIndex );
396 $result = false;
397 }
398
399 }
400 }
401
402 if ( $this->fieldHasFlags( $flags, self::WRITE_SYNC ) ) {
403 foreach ( $keysByTableByShardIndex as $shardIndex => $unused ) {
404 $result = $this->waitForReplication( $shardIndex ) && $result;
405 }
406 }
407
408 return $result;
409 }
410
422 private function updateTable( $op, $db, $table, $tableKeys, $data, $dbExpiry ) {
423 $success = true;
424
425 if ( $op === self::$OP_ADD ) {
426 $rows = [];
427 foreach ( $tableKeys as $key ) {
428 $rows[] = [
429 'keyname' => $key,
430 'value' => $db->encodeBlob( $this->serialize( $data[$key] ) ),
431 'exptime' => $dbExpiry
432 ];
433 }
434 $db->delete(
435 $table,
436 [
437 'keyname' => $tableKeys,
438 'exptime <= ' . $db->addQuotes( $db->timestamp() )
439 ],
440 __METHOD__
441 );
442 $db->insert( $table, $rows, __METHOD__, [ 'IGNORE' ] );
443
444 $success = ( $db->affectedRows() == count( $rows ) );
445 } elseif ( $op === self::$OP_SET ) {
446 $rows = [];
447 foreach ( $tableKeys as $key ) {
448 $rows[] = [
449 'keyname' => $key,
450 'value' => $db->encodeBlob( $this->serialize( $data[$key] ) ),
451 'exptime' => $dbExpiry
452 ];
453 }
454 $db->replace( $table, 'keyname', $rows, __METHOD__ );
455 } elseif ( $op === self::$OP_DELETE ) {
456 $db->delete( $table, [ 'keyname' => $tableKeys ], __METHOD__ );
457 } elseif ( $op === self::$OP_TOUCH ) {
458 $db->update(
459 $table,
460 [ 'exptime' => $dbExpiry ],
461 [
462 'keyname' => $tableKeys,
463 'exptime > ' . $db->addQuotes( $db->timestamp() )
464 ],
465 __METHOD__
466 );
467
468 $success = ( $db->affectedRows() == count( $tableKeys ) );
469 } else {
470 throw new InvalidArgumentException( "Invalid operation '$op'" );
471 }
472
473 return $success;
474 }
475
476 protected function doSet( $key, $value, $exptime = 0, $flags = 0 ) {
477 return $this->modifyMulti( [ $key => $value ], $exptime, $flags, self::$OP_SET );
478 }
479
480 protected function doAdd( $key, $value, $exptime = 0, $flags = 0 ) {
481 return $this->modifyMulti( [ $key => $value ], $exptime, $flags, self::$OP_ADD );
482 }
483
484 protected function doCas( $casToken, $key, $value, $exptime = 0, $flags = 0 ) {
485 list( $shardIndex, $tableName ) = $this->getKeyLocation( $key );
486 $exptime = $this->getExpirationAsTimestamp( $exptime );
487
489 $silenceScope = $this->silenceTransactionProfiler();
490 $db = null; // in case of connection failure
491 try {
492 $db = $this->getConnection( $shardIndex );
493 // (T26425) use a replace if the db supports it instead of
494 // delete/insert to avoid clashes with conflicting keynames
495 $db->update(
497 [
498 'keyname' => $key,
499 'value' => $db->encodeBlob( $this->serialize( $value ) ),
500 'exptime' => $exptime
501 ? $db->timestamp( $exptime )
502 : $this->getMaxDateTime( $db )
503 ],
504 [
505 'keyname' => $key,
506 'value' => $db->encodeBlob( $casToken ),
507 'exptime > ' . $db->addQuotes( $db->timestamp() )
508 ],
509 __METHOD__
510 );
511 } catch ( DBQueryError $e ) {
512 $this->handleWriteError( $e, $db, $shardIndex );
513
514 return false;
515 }
516
517 $success = (bool)$db->affectedRows();
518 if ( $this->fieldHasFlags( $flags, self::WRITE_SYNC ) ) {
519 $success = $this->waitForReplication( $shardIndex ) && $success;
520 }
521
522 return $success;
523 }
524
525 protected function doDeleteMulti( array $keys, $flags = 0 ) {
526 return $this->modifyMulti(
527 array_fill_keys( $keys, null ),
528 0,
529 $flags,
530 self::$OP_DELETE
531 );
532 }
533
534 protected function doDelete( $key, $flags = 0 ) {
535 return $this->modifyMulti( [ $key => null ], 0, $flags, self::$OP_DELETE );
536 }
537
538 public function incr( $key, $step = 1, $flags = 0 ) {
539 list( $shardIndex, $tableName ) = $this->getKeyLocation( $key );
540
541 $newCount = false;
543 $silenceScope = $this->silenceTransactionProfiler();
544 $db = null; // in case of connection failure
545 try {
546 $db = $this->getConnection( $shardIndex );
547 $encTimestamp = $db->addQuotes( $db->timestamp() );
548 $db->update(
550 [ 'value = value + ' . (int)$step ],
551 [ 'keyname' => $key, "exptime > $encTimestamp" ],
552 __METHOD__
553 );
554 if ( $db->affectedRows() > 0 ) {
555 $newValue = $db->selectField(
557 'value',
558 [ 'keyname' => $key, "exptime > $encTimestamp" ],
559 __METHOD__
560 );
561 if ( $this->isInteger( $newValue ) ) {
562 $newCount = (int)$newValue;
563 }
564 }
565 } catch ( DBError $e ) {
566 $this->handleWriteError( $e, $db, $shardIndex );
567 }
568
569 return $newCount;
570 }
571
572 public function decr( $key, $value = 1, $flags = 0 ) {
573 return $this->incr( $key, -$value, $flags );
574 }
575
576 public function changeTTLMulti( array $keys, $exptime, $flags = 0 ) {
577 return $this->modifyMulti(
578 array_fill_keys( $keys, null ),
579 $exptime,
580 $flags,
581 self::$OP_TOUCH
582 );
583 }
584
585 protected function doChangeTTL( $key, $exptime, $flags ) {
586 return $this->modifyMulti( [ $key => null ], $exptime, $flags, self::$OP_TOUCH );
587 }
588
594 private function isExpired( IDatabase $db, $exptime ) {
595 return (
596 $exptime != $this->getMaxDateTime( $db ) &&
597 ConvertibleTimestamp::convert( TS_UNIX, $exptime ) < $this->getCurrentTime()
598 );
599 }
600
605 private function getMaxDateTime( $db ) {
606 if ( (int)$this->getCurrentTime() > 0x7fffffff ) {
607 return $db->timestamp( 1 << 62 );
608 } else {
609 return $db->timestamp( 0x7fffffff );
610 }
611 }
612
617 private function occasionallyGarbageCollect( IDatabase $db ) {
618 if (
619 // Random purging is enabled
620 $this->purgePeriod &&
621 // Only purge on one in every $this->purgePeriod writes
622 mt_rand( 0, $this->purgePeriod - 1 ) == 0 &&
623 // Avoid repeating the delete within a few seconds
624 ( $this->getCurrentTime() - $this->lastGarbageCollect ) > self::$GC_DELAY_SEC
625 ) {
626 $garbageCollector = function () use ( $db ) {
628 $db, $this->getCurrentTime(),
629 null,
630 $this->purgeLimit
631 );
632 $this->lastGarbageCollect = time();
633 };
634 if ( $this->asyncHandler ) {
635 $this->lastGarbageCollect = $this->getCurrentTime(); // avoid duplicate enqueues
636 ( $this->asyncHandler )( $garbageCollector );
637 } else {
638 $garbageCollector();
639 }
640 }
641 }
642
643 public function expireAll() {
645 }
646
648 $timestamp,
649 callable $progress = null,
650 $limit = INF
651 ) {
653 $silenceScope = $this->silenceTransactionProfiler();
654
655 $shardIndexes = $this->getServerShardIndexes();
656 shuffle( $shardIndexes );
657
658 $ok = true;
659
660 $keysDeletedCount = 0;
661 foreach ( $shardIndexes as $numServersDone => $shardIndex ) {
662 $db = null; // in case of connection failure
663 try {
664 $db = $this->getConnection( $shardIndex );
666 $db,
667 $timestamp,
668 $progress,
669 $limit,
670 $numServersDone,
671 $keysDeletedCount
672 );
673 } catch ( DBError $e ) {
674 $this->handleWriteError( $e, $db, $shardIndex );
675 $ok = false;
676 }
677 }
678
679 return $ok;
680 }
681
692 IDatabase $db,
693 $timestamp,
694 $progressCallback,
695 $limit,
696 $serversDoneCount = 0,
697 &$keysDeletedCount = 0
698 ) {
699 $cutoffUnix = ConvertibleTimestamp::convert( TS_UNIX, $timestamp );
700 $tableIndexes = range( 0, $this->numTableShards - 1 );
701 shuffle( $tableIndexes );
702
703 foreach ( $tableIndexes as $numShardsDone => $tableIndex ) {
704 $continue = null; // last exptime
705 $lag = null; // purge lag
706 do {
707 $res = $db->select(
708 $this->getTableNameByShard( $tableIndex ),
709 [ 'keyname', 'exptime' ],
710 array_merge(
711 [ 'exptime < ' . $db->addQuotes( $db->timestamp( $cutoffUnix ) ) ],
712 $continue ? [ 'exptime >= ' . $db->addQuotes( $continue ) ] : []
713 ),
714 __METHOD__,
715 [ 'LIMIT' => min( $limit, 100 ), 'ORDER BY' => 'exptime' ]
716 );
717
718 if ( $res->numRows() ) {
719 $row = $res->current();
720 if ( $lag === null ) {
721 $rowExpUnix = ConvertibleTimestamp::convert( TS_UNIX, $row->exptime );
722 $lag = max( $cutoffUnix - $rowExpUnix, 1 );
723 }
724
725 $keys = [];
726 foreach ( $res as $row ) {
727 $keys[] = $row->keyname;
728 $continue = $row->exptime;
729 }
730
731 $db->delete(
732 $this->getTableNameByShard( $tableIndex ),
733 [
734 'exptime < ' . $db->addQuotes( $db->timestamp( $cutoffUnix ) ),
735 'keyname' => $keys
736 ],
737 __METHOD__
738 );
739 $keysDeletedCount += $db->affectedRows();
740 }
741
742 if ( is_callable( $progressCallback ) ) {
743 if ( $lag ) {
744 $continueUnix = ConvertibleTimestamp::convert( TS_UNIX, $continue );
745 $remainingLag = $cutoffUnix - $continueUnix;
746 $processedLag = max( $lag - $remainingLag, 0 );
747 $doneRatio =
748 ( $numShardsDone + $processedLag / $lag ) / $this->numTableShards;
749 } else {
750 $doneRatio = 1;
751 }
752
753 $overallRatio = ( $doneRatio / $this->numServerShards )
754 + ( $serversDoneCount / $this->numServerShards );
755 call_user_func( $progressCallback, $overallRatio * 100 );
756 }
757 } while ( $res->numRows() && $keysDeletedCount < $limit );
758 }
759 }
760
766 public function deleteAll() {
768 $silenceScope = $this->silenceTransactionProfiler();
769 foreach ( $this->getServerShardIndexes() as $shardIndex ) {
770 $db = null; // in case of connection failure
771 try {
772 $db = $this->getConnection( $shardIndex );
773 for ( $i = 0; $i < $this->numTableShards; $i++ ) {
774 $db->delete( $this->getTableNameByShard( $i ), '*', __METHOD__ );
775 }
776 } catch ( DBError $e ) {
777 $this->handleWriteError( $e, $db, $shardIndex );
778 return false;
779 }
780 }
781 return true;
782 }
783
784 public function lock( $key, $timeout = 6, $expiry = 6, $rclass = '' ) {
785 // Avoid deadlocks and allow lock reentry if specified
786 if ( isset( $this->locks[$key] ) ) {
787 if ( $rclass != '' && $this->locks[$key]['class'] === $rclass ) {
788 ++$this->locks[$key]['depth'];
789 return true;
790 } else {
791 return false;
792 }
793 }
794
795 list( $shardIndex ) = $this->getKeyLocation( $key );
796
797 $db = null; // in case of connection failure
798 try {
799 $db = $this->getConnection( $shardIndex );
800 $ok = $db->lock( $key, __METHOD__, $timeout );
801 if ( $ok ) {
802 $this->locks[$key] = [ 'class' => $rclass, 'depth' => 1 ];
803 }
804
805 $this->logger->warning(
806 __METHOD__ . " failed due to timeout for {key}.",
807 [ 'key' => $key, 'timeout' => $timeout ]
808 );
809
810 return $ok;
811 } catch ( DBError $e ) {
812 $this->handleWriteError( $e, $db, $shardIndex );
813 $ok = false;
814 }
815
816 return $ok;
817 }
818
819 public function unlock( $key ) {
820 if ( !isset( $this->locks[$key] ) ) {
821 return false;
822 }
823
824 if ( --$this->locks[$key]['depth'] <= 0 ) {
825 unset( $this->locks[$key] );
826
827 list( $shardIndex ) = $this->getKeyLocation( $key );
828
829 $db = null; // in case of connection failure
830 try {
831 $db = $this->getConnection( $shardIndex );
832 $ok = $db->unlock( $key, __METHOD__ );
833 if ( !$ok ) {
834 $this->logger->warning(
835 __METHOD__ . ' failed to release lock for {key}.',
836 [ 'key' => $key ]
837 );
838 }
839 } catch ( DBError $e ) {
840 $this->handleWriteError( $e, $db, $shardIndex );
841 $ok = false;
842 }
843
844 return $ok;
845 }
846
847 return true;
848 }
849
858 public function makeKeyInternal( $keyspace, $args ) {
859 // SQL schema for 'objectcache' specifies keys as varchar(255). From that,
860 // subtract the number of characters we need for the keyspace and for
861 // the separator character needed for each argument. To handle some
862 // custom prefixes used by thing like WANObjectCache, limit to 205.
863 $keyspace = strtr( $keyspace, ' ', '_' );
864 $charsLeft = 205 - strlen( $keyspace ) - count( $args );
865 foreach ( $args as &$arg ) {
866 $arg = strtr( $arg, [
867 ' ' => '_', // Avoid unnecessary misses from pre-1.35 code
868 ':' => '%3A',
869 ] );
870
871 // 33 = 32 characters for the MD5 + 1 for the '#' prefix.
872 if ( $charsLeft > 33 && strlen( $arg ) > $charsLeft ) {
873 $arg = '#' . md5( $arg );
874 }
875 $charsLeft -= strlen( $arg );
876 }
877
878 if ( $charsLeft < 0 ) {
879 return $keyspace . ':BagOStuff-long-key:##' . md5( implode( ':', $args ) );
880 }
881 return $keyspace . ':' . implode( ':', $args );
882 }
883
892 protected function serialize( $data ) {
893 if ( is_int( $data ) ) {
894 return $data;
895 }
896
897 $serial = serialize( $data );
898 if ( function_exists( 'gzdeflate' ) ) {
899 $serial = gzdeflate( $serial );
900 }
901
902 return $serial;
903 }
904
910 protected function unserialize( $serial ) {
911 if ( $this->isInteger( $serial ) ) {
912 return (int)$serial;
913 }
914
915 if ( function_exists( 'gzinflate' ) ) {
916 AtEase::suppressWarnings();
917 $decomp = gzinflate( $serial );
918 AtEase::restoreWarnings();
919
920 if ( $decomp !== false ) {
921 $serial = $decomp;
922 }
923 }
924
925 return unserialize( $serial );
926 }
927
933 private function getConnectionViaLoadBalancer( $shardIndex ) {
934 $lb = ( $shardIndex === self::SHARD_LOCAL ) ? $this->localKeyLb : $this->globalKeyLb;
935 if ( $lb->getServerAttributes( $lb->getWriterIndex() )[Database::ATTR_DB_LEVEL_LOCKING] ) {
936 // Use the main connection to avoid transaction deadlocks
938 } else {
939 // If the RDBMs has row/table/page level locking, then use separate auto-commit
940 // connection to avoid needless contention and deadlocks.
941 $conn = $lb->getMaintenanceConnectionRef(
942 $this->replicaOnly ? DB_REPLICA : DB_MASTER, [],
943 false,
944 $lb::CONN_TRX_AUTOCOMMIT
945 );
946 }
947
948 return $conn;
949 }
950
957 private function getConnectionFromServerInfo( $shardIndex, array $server ) {
958 if ( !isset( $this->conns[$shardIndex] ) ) {
960 $conn = Database::factory( $server['type'], array_merge(
961 $server,
962 [
963 'flags' => ( $server['flags'] ?? 0 ) & ~IDatabase::DBO_TRX,
964 'connLogger' => $this->logger,
965 'queryLogger' => $this->logger
966 ]
967 ) );
968 // Automatically create the objectcache table for sqlite as needed
969 if ( $conn->getType() === 'sqlite' && !$conn->tableExists( 'objectcache', __METHOD__ ) ) {
970 $this->initSqliteDatabase( $conn );
971 }
972 $this->conns[$shardIndex] = $conn;
973 }
974
975 return $this->conns[$shardIndex];
976 }
977
984 private function handleReadError( DBError $exception, $shardIndex ) {
985 if ( $exception instanceof DBConnectionError ) {
986 $this->markServerDown( $exception, $shardIndex );
987 }
988
989 $this->setAndLogDBError( $exception );
990 }
991
1000 private function handleWriteError( DBError $exception, $db, $shardIndex ) {
1001 if ( !( $db instanceof IDatabase ) ) {
1002 $this->markServerDown( $exception, $shardIndex );
1003 }
1004
1005 $this->setAndLogDBError( $exception );
1006 }
1007
1011 private function setAndLogDBError( DBError $exception ) {
1012 $this->logger->error( "DBError: {$exception->getMessage()}" );
1013 if ( $exception instanceof DBConnectionError ) {
1014 $this->setLastError( BagOStuff::ERR_UNREACHABLE );
1015 $this->logger->debug( __METHOD__ . ": ignoring connection error" );
1016 } else {
1017 $this->setLastError( BagOStuff::ERR_UNEXPECTED );
1018 $this->logger->debug( __METHOD__ . ": ignoring query error" );
1019 }
1020 }
1021
1028 private function markServerDown( DBError $exception, $shardIndex ) {
1029 unset( $this->conns[$shardIndex] ); // bug T103435
1030
1031 $now = $this->getCurrentTime();
1032 if ( isset( $this->connFailureTimes[$shardIndex] ) ) {
1033 if ( $now - $this->connFailureTimes[$shardIndex] >= 60 ) {
1034 unset( $this->connFailureTimes[$shardIndex] );
1035 unset( $this->connFailureErrors[$shardIndex] );
1036 } else {
1037 $this->logger->debug( __METHOD__ . ": Server #$shardIndex already down" );
1038 return;
1039 }
1040 }
1041 $this->logger->info( __METHOD__ . ": Server #$shardIndex down until " . ( $now + 60 ) );
1042 $this->connFailureTimes[$shardIndex] = $now;
1043 $this->connFailureErrors[$shardIndex] = $exception;
1044 }
1045
1051 if ( $db->tableExists( 'objectcache', __METHOD__ ) ) {
1052 return;
1053 }
1054 // Use one table for SQLite; sharding does not seem to have much benefit
1055 $db->query( "PRAGMA journal_mode=WAL", __METHOD__ ); // this is permanent
1056 $db->startAtomic( __METHOD__ ); // atomic DDL
1057 try {
1058 $encTable = $db->tableName( 'objectcache' );
1059 $encExptimeIndex = $db->addIdentifierQuotes( $db->tablePrefix() . 'exptime' );
1060 $db->query(
1061 "CREATE TABLE $encTable (\n" .
1062 " keyname BLOB NOT NULL default '' PRIMARY KEY,\n" .
1063 " value BLOB,\n" .
1064 " exptime TEXT\n" .
1065 ")",
1066 __METHOD__
1067 );
1068 $db->query( "CREATE INDEX $encExptimeIndex ON $encTable (exptime)", __METHOD__ );
1069 $db->endAtomic( __METHOD__ );
1070 } catch ( DBError $e ) {
1071 $db->rollback( __METHOD__ );
1072 throw $e;
1073 }
1074 }
1075
1079 public function createTables() {
1080 foreach ( $this->getServerShardIndexes() as $shardIndex ) {
1081 $db = $this->getConnection( $shardIndex );
1082 if ( in_array( $db->getType(), [ 'mysql', 'postgres' ], true ) ) {
1083 for ( $i = 0; $i < $this->numTableShards; $i++ ) {
1084 $encBaseTable = $db->tableName( 'objectcache' );
1085 $encShardTable = $db->tableName( $this->getTableNameByShard( $i ) );
1086 $db->query( "CREATE TABLE $encShardTable LIKE $encBaseTable", __METHOD__ );
1087 }
1088 }
1089 }
1090 }
1091
1095 private function getServerShardIndexes() {
1096 if ( $this->serverTags ) {
1097 // Striped array of database servers
1098 $shardIndexes = range( 0, $this->numServerShards - 1 );
1099 } else {
1100 // LoadBalancer based configuration
1101 $shardIndexes = [];
1102 if ( $this->localKeyLb ) {
1103 $shardIndexes[] = self::SHARD_LOCAL;
1104 }
1105 if ( $this->globalKeyLb ) {
1106 $shardIndexes[] = self::SHARD_GLOBAL;
1107 }
1108 }
1109
1110 return $shardIndexes;
1111 }
1112
1119 private function waitForReplication( $shardIndex ) {
1120 if ( is_int( $shardIndex ) ) {
1121 return true; // striped only, no LoadBalancer
1122 }
1123
1124 $lb = ( $shardIndex === self::SHARD_LOCAL ) ? $this->localKeyLb : $this->globalKeyLb;
1125 if ( !$lb->hasStreamingReplicaServers() ) {
1126 return true;
1127 }
1128
1129 try {
1130 // Wait for any replica DBs to catch up
1131 $masterPos = $lb->getMasterPos();
1132 if ( !$masterPos ) {
1133 return true; // not applicable
1134 }
1135
1136 $loop = new WaitConditionLoop(
1137 function () use ( $lb, $masterPos ) {
1138 return $lb->waitForAll( $masterPos, 1 );
1139 },
1142 );
1143
1144 return ( $loop->invoke() === $loop::CONDITION_REACHED );
1145 } catch ( DBError $e ) {
1146 $this->setAndLogDBError( $e );
1147
1148 return false;
1149 }
1150 }
1151
1157 private function silenceTransactionProfiler() {
1158 if ( $this->serverInfos ) {
1159 return null; // no TransactionProfiler injected anyway
1160 }
1161
1162 $trxProfiler = Profiler::instance()->getTransactionProfiler();
1163 $oldSilenced = $trxProfiler->setSilenced( true );
1164 return new ScopedCallback( function () use ( $trxProfiler, $oldSilenced ) {
1165 $trxProfiler->setSilenced( $oldSilenced );
1166 } );
1167 }
1168}
serialize()
fieldHasFlags( $field, $flags)
callable null $asyncHandler
Definition BagOStuff.php:76
Storage medium specific cache for storing items (e.g.
getExpirationAsTimestamp( $exptime)
Convert an optionally relative timestamp to an absolute time.
isInteger( $value)
Check if a value is an integer.
setLastError( $err)
Set the "last error" registry.
Class to store objects in the database.
doDelete( $key, $flags=0)
Delete an item.
handleWriteError(DBError $exception, $db, $shardIndex)
Handle a DBQueryError which occurred during a write operation.
serialize( $data)
Serialize an object and, if possible, compress the representation.
lock( $key, $timeout=6, $expiry=6, $rclass='')
Acquire an advisory lock on a key string.
string[] $serverTags
(server index => tag/host name)
doSetMulti(array $data, $exptime=0, $flags=0)
makeKeyInternal( $keyspace, $args)
Construct a cache key.
createTables()
Create the shard tables on all databases (e.g.
isExpired(IDatabase $db, $exptime)
getConnectionViaLoadBalancer( $shardIndex)
deleteObjectsExpiringBefore( $timestamp, callable $progress=null, $limit=INF)
Delete all objects expiring before a certain date.
doChangeTTL( $key, $exptime, $flags)
modifyMulti(array $data, $exptime, $flags, $op)
static string $OP_ADD
handleReadError(DBError $exception, $shardIndex)
Handle a DBError which occurred during a read operation.
waitForReplication( $shardIndex)
Wait for replica DBs to catch up to the master DB.
array[] $serverInfos
(server index => server config)
deleteAll()
Delete content of shard tables in every server.
doDeleteMulti(array $keys, $flags=0)
getConnectionFromServerInfo( $shardIndex, array $server)
__construct( $params)
Constructor.
int $lastGarbageCollect
UNIX timestamp.
markServerDown(DBError $exception, $shardIndex)
Mark a server down due to a DBConnectionError exception.
static int $GC_DELAY_SEC
static string $OP_TOUCH
doGet( $key, $flags=0, &$casToken=null)
updateTable( $op, $db, $table, $tableKeys, $data, $dbExpiry)
doAdd( $key, $value, $exptime=0, $flags=0)
Insert an item if it does not already exist.
deleteServerObjectsExpiringBefore(IDatabase $db, $timestamp, $progressCallback, $limit, $serversDoneCount=0, &$keysDeletedCount=0)
doSet( $key, $value, $exptime=0, $flags=0)
Set an item.
int $numServerShards
Number of database servers shards (e.g.
decr( $key, $value=1, $flags=0)
Decrease stored value of $key by $value while preserving its TTL.
ILoadBalancer null $localKeyLb
silenceTransactionProfiler()
Silence the transaction profiler until the return value falls out of scope.
unlock( $key)
Release an advisory lock on a key string.
getConnection( $shardIndex)
Get a connection to the specified database.
fetchBlobMulti(array $keys)
ILoadBalancer null $globalKeyLb
Exception[] $connFailureErrors
Map of (shard index => Exception)
changeTTLMulti(array $keys, $exptime, $flags=0)
Change the expiration of multiple keys that exist.
setAndLogDBError(DBError $exception)
IMaintainableDatabase[] $conns
Map of (shard index => DB handle)
unserialize( $serial)
Unserialize and, if necessary, decompress an object.
string $tableName
getKeyLocation( $key)
Get the server index and table name for a given key.
getTableNameByShard( $index)
Get the table name for a given shard index.
initSqliteDatabase(IMaintainableDatabase $db)
static string $OP_SET
static string $OP_DELETE
doGetMulti(array $keys, $flags=0)
Get an associative array containing the item for each of the keys that have items.
doCas( $casToken, $key, $value, $exptime=0, $flags=0)
Check and set an item.
occasionallyGarbageCollect(IDatabase $db)
float[] $connFailureTimes
Map of (shard index => UNIX timestamps)
incr( $key, $step=1, $flags=0)
Increase stored value of $key by $value while preserving its TTL.
Database error base class @newable Stable to extend.
Definition DBError.php:32
@newable Stable to extend
Relational database abstraction object.
Definition Database.php:50
Basic database interface for live and lazy-loaded relation database handles.
Definition IDatabase.php:38
rollback( $fname=__METHOD__, $flush=self::FLUSHING_ONE)
Rollback a transaction previously started using begin()
addIdentifierQuotes( $s)
Escape a SQL identifier (e.g.
endAtomic( $fname=__METHOD__)
Ends an atomic section of SQL statements.
select( $table, $vars, $conds='', $fname=__METHOD__, $options=[], $join_conds=[])
Execute a SELECT query constructed using the various parameters provided.
tableExists( $table, $fname=__METHOD__)
Query whether a given table exists.
affectedRows()
Get the number of rows affected by the last write query.
delete( $table, $conds, $fname=__METHOD__)
Delete all rows in a table that match a condition.
addQuotes( $s)
Escape and quote a raw value string for use in a SQL query.
timestamp( $ts=0)
Convert a timestamp in one of the formats accepted by ConvertibleTimestamp to the format used for ins...
getType()
Get the type of the DBMS (e.g.
tablePrefix( $prefix=null)
Get/set the table prefix.
query( $sql, $fname=__METHOD__, $flags=0)
Run an SQL query and return the result.
startAtomic( $fname=__METHOD__, $cancelable=self::ATOMIC_NOT_CANCELABLE)
Begin an atomic section of SQL statements.
Database cluster connection, tracking, load balancing, and transaction manager interface.
getMasterPos()
Get the current master replication position.
getMaintenanceConnectionRef( $i, $groups=[], $domain=false, $flags=0)
Get a live database handle for a real or virtual (DB_MASTER/DB_REPLICA) server index that can be used...
Advanced database interface for IDatabase handles that include maintenance methods.
tableName( $name, $format='quoted')
Format a table name ready for use in constructing an SQL query.
if( $line===false) $args
Definition mcc.php:124
const DB_REPLICA
Definition defines.php:25
const DB_MASTER
Definition defines.php:29