Merge "objectcache: move lag waiting to SqlBagOStuff::doCas() instead of overriding...
[lhc/web/wiklou.git] / includes / objectcache / SqlBagOStuff.php
1 <?php
2 /**
3 * Object caching using a SQL database.
4 *
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.
9 *
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.
14 *
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
19 *
20 * @file
21 * @ingroup Cache
22 */
23
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\IMaintainableDatabase;
31 use Wikimedia\Rdbms\LoadBalancer;
32 use Wikimedia\ScopedCallback;
33 use Wikimedia\WaitConditionLoop;
34
35 /**
36 * Class to store objects in the database
37 *
38 * @ingroup Cache
39 */
40 class SqlBagOStuff extends MediumSpecificBagOStuff {
41 /** @var array[] (server index => server config) */
42 protected $serverInfos;
43 /** @var string[] (server index => tag/host name) */
44 protected $serverTags;
45 /** @var int */
46 protected $numServerShards;
47 /** @var int UNIX timestamp */
48 protected $lastGarbageCollect = 0;
49 /** @var int */
50 protected $purgePeriod = 10;
51 /** @var int */
52 protected $purgeLimit = 100;
53 /** @var int */
54 protected $numTableShards = 1;
55 /** @var string */
56 protected $tableName = 'objectcache';
57 /** @var bool */
58 protected $replicaOnly = false;
59
60 /** @var LoadBalancer|null */
61 protected $separateMainLB;
62 /** @var array */
63 protected $conns;
64 /** @var array UNIX timestamps */
65 protected $connFailureTimes = [];
66 /** @var array Exceptions */
67 protected $connFailureErrors = [];
68
69 /** @var int */
70 private static $GC_DELAY_SEC = 1;
71
72 /** @var string */
73 private static $OP_SET = 'set';
74 /** @var string */
75 private static $OP_ADD = 'add';
76 /** @var string */
77 private static $OP_TOUCH = 'touch';
78 /** @var string */
79 private static $OP_DELETE = 'delete';
80
81 /**
82 * Constructor. Parameters are:
83 * - server: A server info structure in the format required by each
84 * element in $wgDBServers.
85 *
86 * - servers: An array of server info structures describing a set of database servers
87 * to distribute keys to. If this is specified, the "server" option will be
88 * ignored. If string keys are used, then they will be used for consistent
89 * hashing *instead* of the host name (from the server config). This is useful
90 * when a cluster is replicated to another site (with different host names)
91 * but each server has a corresponding replica in the other cluster.
92 *
93 * - purgePeriod: The average number of object cache writes in between
94 * garbage collection operations, where expired entries
95 * are removed from the database. Or in other words, the
96 * reciprocal of the probability of purging on any given
97 * write. If this is set to zero, purging will never be done.
98 *
99 * - purgeLimit: Maximum number of rows to purge at once.
100 *
101 * - tableName: The table name to use, default is "objectcache".
102 *
103 * - shards: The number of tables to use for data storage on each server.
104 * If this is more than 1, table names will be formed in the style
105 * objectcacheNNN where NNN is the shard index, between 0 and
106 * shards-1. The number of digits will be the minimum number
107 * required to hold the largest shard index. Data will be
108 * distributed across all tables by key hash. This is for
109 * MySQL bugs 61735 <https://bugs.mysql.com/bug.php?id=61735>
110 * and 61736 <https://bugs.mysql.com/bug.php?id=61736>.
111 *
112 * - replicaOnly: Whether to only use replica DBs and avoid triggering
113 * garbage collection logic of expired items. This only
114 * makes sense if the primary DB is used and only if get()
115 * calls will be used. This is used by ReplicatedBagOStuff.
116 * - syncTimeout: Max seconds to wait for replica DBs to catch up for WRITE_SYNC.
117 *
118 * @param array $params
119 */
120 public function __construct( $params ) {
121 parent::__construct( $params );
122
123 $this->attrMap[self::ATTR_EMULATION] = self::QOS_EMULATION_SQL;
124 $this->attrMap[self::ATTR_SYNCWRITES] = self::QOS_SYNCWRITES_NONE;
125
126 if ( isset( $params['servers'] ) ) {
127 $this->serverInfos = [];
128 $this->serverTags = [];
129 $this->numServerShards = count( $params['servers'] );
130 $index = 0;
131 foreach ( $params['servers'] as $tag => $info ) {
132 $this->serverInfos[$index] = $info;
133 if ( is_string( $tag ) ) {
134 $this->serverTags[$index] = $tag;
135 } else {
136 $this->serverTags[$index] = $info['host'] ?? "#$index";
137 }
138 ++$index;
139 }
140 } elseif ( isset( $params['server'] ) ) {
141 $this->serverInfos = [ $params['server'] ];
142 $this->numServerShards = count( $this->serverInfos );
143 } else {
144 // Default to using the main wiki's database servers
145 $this->serverInfos = false;
146 $this->numServerShards = 1;
147 $this->attrMap[self::ATTR_SYNCWRITES] = self::QOS_SYNCWRITES_BE;
148 }
149 if ( isset( $params['purgePeriod'] ) ) {
150 $this->purgePeriod = intval( $params['purgePeriod'] );
151 }
152 if ( isset( $params['purgeLimit'] ) ) {
153 $this->purgeLimit = intval( $params['purgeLimit'] );
154 }
155 if ( isset( $params['tableName'] ) ) {
156 $this->tableName = $params['tableName'];
157 }
158 if ( isset( $params['shards'] ) ) {
159 $this->numTableShards = intval( $params['shards'] );
160 }
161 // Backwards-compatibility for < 1.34
162 $this->replicaOnly = $params['replicaOnly'] ?? ( $params['slaveOnly'] ?? false );
163 }
164
165 /**
166 * Get a connection to the specified database
167 *
168 * @param int $shardIndex
169 * @return IMaintainableDatabase
170 * @throws MWException
171 */
172 private function getDB( $shardIndex ) {
173 if ( $shardIndex >= $this->numServerShards ) {
174 throw new MWException( __METHOD__ . ": Invalid server index \"$shardIndex\"" );
175 }
176
177 # Don't keep timing out trying to connect for each call if the DB is down
178 if (
179 isset( $this->connFailureErrors[$shardIndex] ) &&
180 ( $this->getCurrentTime() - $this->connFailureTimes[$shardIndex] ) < 60
181 ) {
182 throw $this->connFailureErrors[$shardIndex];
183 }
184
185 if ( $this->serverInfos ) {
186 if ( !isset( $this->conns[$shardIndex] ) ) {
187 // Use custom database defined by server connection info
188 $info = $this->serverInfos[$shardIndex];
189 $type = $info['type'] ?? 'mysql';
190 $host = $info['host'] ?? '[unknown]';
191 $this->logger->debug( __CLASS__ . ": connecting to $host" );
192 $db = Database::factory( $type, $info );
193 $db->clearFlag( DBO_TRX ); // auto-commit mode
194 $this->conns[$shardIndex] = $db;
195 }
196 $db = $this->conns[$shardIndex];
197 } else {
198 // Use the main LB database
199 $lb = MediaWikiServices::getInstance()->getDBLoadBalancer();
200 $index = $this->replicaOnly ? DB_REPLICA : DB_MASTER;
201 if ( $lb->getServerType( $lb->getWriterIndex() ) !== 'sqlite' ) {
202 // Keep a separate connection to avoid contention and deadlocks
203 $db = $lb->getConnectionRef( $index, [], false, $lb::CONN_TRX_AUTOCOMMIT );
204 } else {
205 // However, SQLite has the opposite behavior due to DB-level locking.
206 // Stock sqlite MediaWiki installs use a separate sqlite cache DB instead.
207 $db = $lb->getConnectionRef( $index );
208 }
209 }
210
211 $this->logger->debug( sprintf( "Connection %s will be used for SqlBagOStuff", $db ) );
212
213 return $db;
214 }
215
216 /**
217 * Get the server index and table name for a given key
218 * @param string $key
219 * @return array Server index and table name
220 */
221 private function getTableByKey( $key ) {
222 if ( $this->numTableShards > 1 ) {
223 $hash = hexdec( substr( md5( $key ), 0, 8 ) ) & 0x7fffffff;
224 $tableIndex = $hash % $this->numTableShards;
225 } else {
226 $tableIndex = 0;
227 }
228 if ( $this->numServerShards > 1 ) {
229 $sortedServers = $this->serverTags;
230 ArrayUtils::consistentHashSort( $sortedServers, $key );
231 reset( $sortedServers );
232 $shardIndex = key( $sortedServers );
233 } else {
234 $shardIndex = 0;
235 }
236 return [ $shardIndex, $this->getTableNameByShard( $tableIndex ) ];
237 }
238
239 /**
240 * Get the table name for a given shard index
241 * @param int $index
242 * @return string
243 */
244 private function getTableNameByShard( $index ) {
245 if ( $this->numTableShards > 1 ) {
246 $decimals = strlen( $this->numTableShards - 1 );
247 return $this->tableName .
248 sprintf( "%0{$decimals}d", $index );
249 } else {
250 return $this->tableName;
251 }
252 }
253
254 protected function doGet( $key, $flags = 0, &$casToken = null ) {
255 $casToken = null;
256
257 $blobs = $this->fetchBlobMulti( [ $key ] );
258 if ( array_key_exists( $key, $blobs ) ) {
259 $blob = $blobs[$key];
260 $value = $this->unserialize( $blob );
261
262 $casToken = ( $value !== false ) ? $blob : null;
263
264 return $value;
265 }
266
267 return false;
268 }
269
270 protected function doGetMulti( array $keys, $flags = 0 ) {
271 $values = [];
272
273 $blobs = $this->fetchBlobMulti( $keys );
274 foreach ( $blobs as $key => $blob ) {
275 $values[$key] = $this->unserialize( $blob );
276 }
277
278 return $values;
279 }
280
281 private function fetchBlobMulti( array $keys, $flags = 0 ) {
282 $values = []; // array of (key => value)
283
284 $keysByTable = [];
285 foreach ( $keys as $key ) {
286 list( $shardIndex, $tableName ) = $this->getTableByKey( $key );
287 $keysByTable[$shardIndex][$tableName][] = $key;
288 }
289
290 $dataRows = [];
291 foreach ( $keysByTable as $shardIndex => $serverKeys ) {
292 try {
293 $db = $this->getDB( $shardIndex );
294 foreach ( $serverKeys as $tableName => $tableKeys ) {
295 $res = $db->select( $tableName,
296 [ 'keyname', 'value', 'exptime' ],
297 [ 'keyname' => $tableKeys ],
298 __METHOD__,
299 // Approximate write-on-the-fly BagOStuff API via blocking.
300 // This approximation fails if a ROLLBACK happens (which is rare).
301 // We do not want to flush the TRX as that can break callers.
302 $db->trxLevel() ? [ 'LOCK IN SHARE MODE' ] : []
303 );
304 if ( $res === false ) {
305 continue;
306 }
307 foreach ( $res as $row ) {
308 $row->shardIndex = $shardIndex;
309 $row->tableName = $tableName;
310 $dataRows[$row->keyname] = $row;
311 }
312 }
313 } catch ( DBError $e ) {
314 $this->handleReadError( $e, $shardIndex );
315 }
316 }
317
318 foreach ( $keys as $key ) {
319 if ( isset( $dataRows[$key] ) ) { // HIT?
320 $row = $dataRows[$key];
321 $this->debug( "get: retrieved data; expiry time is " . $row->exptime );
322 $db = null; // in case of connection failure
323 try {
324 $db = $this->getDB( $row->shardIndex );
325 if ( $this->isExpired( $db, $row->exptime ) ) { // MISS
326 $this->debug( "get: key has expired" );
327 } else { // HIT
328 $values[$key] = $db->decodeBlob( $row->value );
329 }
330 } catch ( DBQueryError $e ) {
331 $this->handleWriteError( $e, $db, $row->shardIndex );
332 }
333 } else { // MISS
334 $this->debug( 'get: no matching rows' );
335 }
336 }
337
338 return $values;
339 }
340
341 protected function doSetMulti( array $data, $exptime = 0, $flags = 0 ) {
342 return $this->modifyMulti( $data, $exptime, $flags, self::$OP_SET );
343 }
344
345 /**
346 * @param mixed[]|null[] $data Map of (key => new value or null)
347 * @param int $exptime UNIX timestamp, TTL in seconds, or 0 (no expiration)
348 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
349 * @param string $op Cache operation
350 * @return bool
351 */
352 private function modifyMulti( array $data, $exptime, $flags, $op ) {
353 $keysByTable = [];
354 foreach ( $data as $key => $value ) {
355 list( $shardIndex, $tableName ) = $this->getTableByKey( $key );
356 $keysByTable[$shardIndex][$tableName][] = $key;
357 }
358
359 $exptime = $this->getExpirationAsTimestamp( $exptime );
360
361 $result = true;
362 /** @noinspection PhpUnusedLocalVariableInspection */
363 $silenceScope = $this->silenceTransactionProfiler();
364 foreach ( $keysByTable as $shardIndex => $serverKeys ) {
365 $db = null; // in case of connection failure
366 try {
367 $db = $this->getDB( $shardIndex );
368 $this->occasionallyGarbageCollect( $db ); // expire old entries if any
369 $dbExpiry = $exptime ? $db->timestamp( $exptime ) : $this->getMaxDateTime( $db );
370 } catch ( DBError $e ) {
371 $this->handleWriteError( $e, $db, $shardIndex );
372 $result = false;
373 continue;
374 }
375
376 foreach ( $serverKeys as $tableName => $tableKeys ) {
377 try {
378 $result = $this->updateTableKeys(
379 $op,
380 $db,
381 $tableName,
382 $tableKeys,
383 $data,
384 $dbExpiry
385 ) && $result;
386 } catch ( DBError $e ) {
387 $this->handleWriteError( $e, $db, $shardIndex );
388 $result = false;
389 }
390
391 }
392 }
393
394 if ( $this->fieldHasFlags( $flags, self::WRITE_SYNC ) ) {
395 $result = $this->waitForReplication() && $result;
396 }
397
398 return $result;
399 }
400
401 /**
402 * @param string $op
403 * @param IDatabase $db
404 * @param string $table
405 * @param string[] $tableKeys Keys in $data to update
406 * @param mixed[]|null[] $data Map of (key => new value or null)
407 * @param string $dbExpiry DB-encoded expiry
408 * @return bool
409 * @throws DBError
410 * @throws InvalidArgumentException
411 */
412 private function updateTableKeys( $op, $db, $table, $tableKeys, $data, $dbExpiry ) {
413 $success = true;
414
415 if ( $op === self::$OP_ADD ) {
416 $rows = [];
417 foreach ( $tableKeys as $key ) {
418 $rows[] = [
419 'keyname' => $key,
420 'value' => $db->encodeBlob( $this->serialize( $data[$key] ) ),
421 'exptime' => $dbExpiry
422 ];
423 }
424 $db->delete(
425 $table,
426 [
427 'keyname' => $tableKeys,
428 'exptime <= ' . $db->addQuotes( $db->timestamp() )
429 ],
430 __METHOD__
431 );
432 $db->insert( $table, $rows, __METHOD__, [ 'IGNORE' ] );
433
434 $success = ( $db->affectedRows() == count( $rows ) );
435 } elseif ( $op === self::$OP_SET ) {
436 $rows = [];
437 foreach ( $tableKeys as $key ) {
438 $rows[] = [
439 'keyname' => $key,
440 'value' => $db->encodeBlob( $this->serialize( $data[$key] ) ),
441 'exptime' => $dbExpiry
442 ];
443 }
444 $db->replace( $table, [ 'keyname' ], $rows, __METHOD__ );
445 } elseif ( $op === self::$OP_DELETE ) {
446 $db->delete( $table, [ 'keyname' => $tableKeys ], __METHOD__ );
447 } elseif ( $op === self::$OP_TOUCH ) {
448 $db->update(
449 $table,
450 [ 'exptime' => $dbExpiry ],
451 [
452 'keyname' => $tableKeys,
453 'exptime > ' . $db->addQuotes( $db->timestamp() )
454 ],
455 __METHOD__
456 );
457
458 $success = ( $db->affectedRows() == count( $tableKeys ) );
459 } else {
460 throw new InvalidArgumentException( "Invalid operation '$op'" );
461 }
462
463 return $success;
464 }
465
466 protected function doSet( $key, $value, $exptime = 0, $flags = 0 ) {
467 return $this->modifyMulti( [ $key => $value ], $exptime, $flags, self::$OP_SET );
468 }
469
470 protected function doAdd( $key, $value, $exptime = 0, $flags = 0 ) {
471 return $this->modifyMulti( [ $key => $value ], $exptime, $flags, self::$OP_ADD );
472 }
473
474 protected function doCas( $casToken, $key, $value, $exptime = 0, $flags = 0 ) {
475 list( $shardIndex, $tableName ) = $this->getTableByKey( $key );
476 $exptime = $this->getExpirationAsTimestamp( $exptime );
477
478 /** @noinspection PhpUnusedLocalVariableInspection */
479 $silenceScope = $this->silenceTransactionProfiler();
480 $db = null; // in case of connection failure
481 try {
482 $db = $this->getDB( $shardIndex );
483 // (T26425) use a replace if the db supports it instead of
484 // delete/insert to avoid clashes with conflicting keynames
485 $db->update(
486 $tableName,
487 [
488 'keyname' => $key,
489 'value' => $db->encodeBlob( $this->serialize( $value ) ),
490 'exptime' => $exptime
491 ? $db->timestamp( $exptime )
492 : $this->getMaxDateTime( $db )
493 ],
494 [
495 'keyname' => $key,
496 'value' => $db->encodeBlob( $casToken ),
497 'exptime > ' . $db->addQuotes( $db->timestamp() )
498 ],
499 __METHOD__
500 );
501 } catch ( DBQueryError $e ) {
502 $this->handleWriteError( $e, $db, $shardIndex );
503
504 return false;
505 }
506
507 $success = (bool)$db->affectedRows();
508 if ( $this->fieldHasFlags( $flags, self::WRITE_SYNC ) ) {
509 $success = $this->waitForReplication() && $success;
510 }
511
512 return $success;
513 }
514
515 protected function doDeleteMulti( array $keys, $flags = 0 ) {
516 return $this->modifyMulti(
517 array_fill_keys( $keys, null ),
518 0,
519 $flags,
520 self::$OP_DELETE
521 );
522 }
523
524 protected function doDelete( $key, $flags = 0 ) {
525 return $this->modifyMulti( [ $key => null ], 0, $flags, self::$OP_DELETE );
526 }
527
528 public function incr( $key, $step = 1 ) {
529 list( $shardIndex, $tableName ) = $this->getTableByKey( $key );
530
531 $newCount = false;
532 /** @noinspection PhpUnusedLocalVariableInspection */
533 $silenceScope = $this->silenceTransactionProfiler();
534 $db = null; // in case of connection failure
535 try {
536 $db = $this->getDB( $shardIndex );
537 $encTimestamp = $db->addQuotes( $db->timestamp() );
538 $db->update(
539 $tableName,
540 [ 'value = value + ' . (int)$step ],
541 [ 'keyname' => $key, "exptime > $encTimestamp" ],
542 __METHOD__
543 );
544 if ( $db->affectedRows() > 0 ) {
545 $newValue = $db->selectField(
546 $tableName,
547 'value',
548 [ 'keyname' => $key, "exptime > $encTimestamp" ],
549 __METHOD__
550 );
551 if ( $this->isInteger( $newValue ) ) {
552 $newCount = (int)$newValue;
553 }
554 }
555 } catch ( DBError $e ) {
556 $this->handleWriteError( $e, $db, $shardIndex );
557 }
558
559 return $newCount;
560 }
561
562 public function changeTTLMulti( array $keys, $exptime, $flags = 0 ) {
563 return $this->modifyMulti(
564 array_fill_keys( $keys, null ),
565 $exptime,
566 $flags,
567 self::$OP_TOUCH
568 );
569 }
570
571 protected function doChangeTTL( $key, $exptime, $flags ) {
572 return $this->modifyMulti( [ $key => null ], $exptime, $flags, self::$OP_TOUCH );
573 }
574
575 /**
576 * @param IDatabase $db
577 * @param string $exptime
578 * @return bool
579 */
580 private function isExpired( $db, $exptime ) {
581 return (
582 $exptime != $this->getMaxDateTime( $db ) &&
583 wfTimestamp( TS_UNIX, $exptime ) < $this->getCurrentTime()
584 );
585 }
586
587 /**
588 * @param IDatabase $db
589 * @return string
590 */
591 private function getMaxDateTime( $db ) {
592 if ( (int)$this->getCurrentTime() > 0x7fffffff ) {
593 return $db->timestamp( 1 << 62 );
594 } else {
595 return $db->timestamp( 0x7fffffff );
596 }
597 }
598
599 /**
600 * @param IDatabase $db
601 * @throws DBError
602 */
603 private function occasionallyGarbageCollect( IDatabase $db ) {
604 if (
605 // Random purging is enabled
606 $this->purgePeriod &&
607 // Only purge on one in every $this->purgePeriod writes
608 mt_rand( 0, $this->purgePeriod - 1 ) == 0 &&
609 // Avoid repeating the delete within a few seconds
610 ( $this->getCurrentTime() - $this->lastGarbageCollect ) > self::$GC_DELAY_SEC
611 ) {
612 $garbageCollector = function () use ( $db ) {
613 $this->deleteServerObjectsExpiringBefore(
614 $db, $this->getCurrentTime(),
615 null,
616 $this->purgeLimit
617 );
618 $this->lastGarbageCollect = time();
619 };
620 if ( $this->asyncHandler ) {
621 $this->lastGarbageCollect = $this->getCurrentTime(); // avoid duplicate enqueues
622 ( $this->asyncHandler )( $garbageCollector );
623 } else {
624 $garbageCollector();
625 }
626 }
627 }
628
629 public function expireAll() {
630 $this->deleteObjectsExpiringBefore( $this->getCurrentTime() );
631 }
632
633 public function deleteObjectsExpiringBefore(
634 $timestamp,
635 callable $progress = null,
636 $limit = INF
637 ) {
638 /** @noinspection PhpUnusedLocalVariableInspection */
639 $silenceScope = $this->silenceTransactionProfiler();
640
641 $shardIndexes = range( 0, $this->numServerShards - 1 );
642 shuffle( $shardIndexes );
643
644 $ok = true;
645
646 $keysDeletedCount = 0;
647 foreach ( $shardIndexes as $numServersDone => $shardIndex ) {
648 $db = null; // in case of connection failure
649 try {
650 $db = $this->getDB( $shardIndex );
651 $this->deleteServerObjectsExpiringBefore(
652 $db,
653 $timestamp,
654 $progress,
655 $limit,
656 $numServersDone,
657 $keysDeletedCount
658 );
659 } catch ( DBError $e ) {
660 $this->handleWriteError( $e, $db, $shardIndex );
661 $ok = false;
662 }
663 }
664
665 return $ok;
666 }
667
668 /**
669 * @param IDatabase $db
670 * @param string|int $timestamp
671 * @param callable|null $progressCallback
672 * @param int $limit
673 * @param int $serversDoneCount
674 * @param int &$keysDeletedCount
675 * @throws DBError
676 */
677 private function deleteServerObjectsExpiringBefore(
678 IDatabase $db,
679 $timestamp,
680 $progressCallback,
681 $limit,
682 $serversDoneCount = 0,
683 &$keysDeletedCount = 0
684 ) {
685 $cutoffUnix = wfTimestamp( TS_UNIX, $timestamp );
686 $shardIndexes = range( 0, $this->numTableShards - 1 );
687 shuffle( $shardIndexes );
688
689 foreach ( $shardIndexes as $numShardsDone => $shardIndex ) {
690 $continue = null; // last exptime
691 $lag = null; // purge lag
692 do {
693 $res = $db->select(
694 $this->getTableNameByShard( $shardIndex ),
695 [ 'keyname', 'exptime' ],
696 array_merge(
697 [ 'exptime < ' . $db->addQuotes( $db->timestamp( $cutoffUnix ) ) ],
698 $continue ? [ 'exptime >= ' . $db->addQuotes( $continue ) ] : []
699 ),
700 __METHOD__,
701 [ 'LIMIT' => min( $limit, 100 ), 'ORDER BY' => 'exptime' ]
702 );
703
704 if ( $res->numRows() ) {
705 $row = $res->current();
706 if ( $lag === null ) {
707 $lag = max( $cutoffUnix - wfTimestamp( TS_UNIX, $row->exptime ), 1 );
708 }
709
710 $keys = [];
711 foreach ( $res as $row ) {
712 $keys[] = $row->keyname;
713 $continue = $row->exptime;
714 }
715
716 $db->delete(
717 $this->getTableNameByShard( $shardIndex ),
718 [
719 'exptime < ' . $db->addQuotes( $db->timestamp( $cutoffUnix ) ),
720 'keyname' => $keys
721 ],
722 __METHOD__
723 );
724 $keysDeletedCount += $db->affectedRows();
725 }
726
727 if ( is_callable( $progressCallback ) ) {
728 if ( $lag ) {
729 $remainingLag = $cutoffUnix - wfTimestamp( TS_UNIX, $continue );
730 $processedLag = max( $lag - $remainingLag, 0 );
731 $doneRatio = ( $numShardsDone + $processedLag / $lag ) / $this->numTableShards;
732 } else {
733 $doneRatio = 1;
734 }
735
736 $overallRatio = ( $doneRatio / $this->numServerShards )
737 + ( $serversDoneCount / $this->numServerShards );
738 call_user_func( $progressCallback, $overallRatio * 100 );
739 }
740 } while ( $res->numRows() && $keysDeletedCount < $limit );
741 }
742 }
743
744 /**
745 * Delete content of shard tables in every server.
746 * Return true if the operation is successful, false otherwise.
747 * @return bool
748 */
749 public function deleteAll() {
750 /** @noinspection PhpUnusedLocalVariableInspection */
751 $silenceScope = $this->silenceTransactionProfiler();
752 for ( $shardIndex = 0; $shardIndex < $this->numServerShards; $shardIndex++ ) {
753 $db = null; // in case of connection failure
754 try {
755 $db = $this->getDB( $shardIndex );
756 for ( $i = 0; $i < $this->numTableShards; $i++ ) {
757 $db->delete( $this->getTableNameByShard( $i ), '*', __METHOD__ );
758 }
759 } catch ( DBError $e ) {
760 $this->handleWriteError( $e, $db, $shardIndex );
761 return false;
762 }
763 }
764 return true;
765 }
766
767 public function lock( $key, $timeout = 6, $expiry = 6, $rclass = '' ) {
768 // Avoid deadlocks and allow lock reentry if specified
769 if ( isset( $this->locks[$key] ) ) {
770 if ( $rclass != '' && $this->locks[$key]['class'] === $rclass ) {
771 ++$this->locks[$key]['depth'];
772 return true;
773 } else {
774 return false;
775 }
776 }
777
778 list( $shardIndex ) = $this->getTableByKey( $key );
779
780 $db = null; // in case of connection failure
781 try {
782 $db = $this->getDB( $shardIndex );
783 $ok = $db->lock( $key, __METHOD__, $timeout );
784 if ( $ok ) {
785 $this->locks[$key] = [ 'class' => $rclass, 'depth' => 1 ];
786 }
787
788 $this->logger->warning(
789 __METHOD__ . " failed due to timeout for {key}.",
790 [ 'key' => $key, 'timeout' => $timeout ]
791 );
792
793 return $ok;
794 } catch ( DBError $e ) {
795 $this->handleWriteError( $e, $db, $shardIndex );
796 $ok = false;
797 }
798
799 return $ok;
800 }
801
802 public function unlock( $key ) {
803 if ( !isset( $this->locks[$key] ) ) {
804 return false;
805 }
806
807 if ( --$this->locks[$key]['depth'] <= 0 ) {
808 unset( $this->locks[$key] );
809
810 list( $shardIndex ) = $this->getTableByKey( $key );
811
812 $db = null; // in case of connection failure
813 try {
814 $db = $this->getDB( $shardIndex );
815 $ok = $db->unlock( $key, __METHOD__ );
816 if ( !$ok ) {
817 $this->logger->warning(
818 __METHOD__ . ' failed to release lock for {key}.',
819 [ 'key' => $key ]
820 );
821 }
822 } catch ( DBError $e ) {
823 $this->handleWriteError( $e, $db, $shardIndex );
824 $ok = false;
825 }
826
827 return $ok;
828 }
829
830 return true;
831 }
832
833 /**
834 * Serialize an object and, if possible, compress the representation.
835 * On typical message and page data, this can provide a 3X decrease
836 * in storage requirements.
837 *
838 * @param mixed $data
839 * @return string|int
840 */
841 protected function serialize( $data ) {
842 if ( is_int( $data ) ) {
843 return $data;
844 }
845
846 $serial = serialize( $data );
847 if ( function_exists( 'gzdeflate' ) ) {
848 $serial = gzdeflate( $serial );
849 }
850
851 return $serial;
852 }
853
854 /**
855 * Unserialize and, if necessary, decompress an object.
856 * @param string $serial
857 * @return mixed
858 */
859 protected function unserialize( $serial ) {
860 if ( $this->isInteger( $serial ) ) {
861 return (int)$serial;
862 }
863
864 if ( function_exists( 'gzinflate' ) ) {
865 Wikimedia\suppressWarnings();
866 $decomp = gzinflate( $serial );
867 Wikimedia\restoreWarnings();
868
869 if ( $decomp !== false ) {
870 $serial = $decomp;
871 }
872 }
873
874 return unserialize( $serial );
875 }
876
877 /**
878 * Handle a DBError which occurred during a read operation.
879 *
880 * @param DBError $exception
881 * @param int $shardIndex
882 */
883 private function handleReadError( DBError $exception, $shardIndex ) {
884 if ( $exception instanceof DBConnectionError ) {
885 $this->markServerDown( $exception, $shardIndex );
886 }
887
888 $this->setAndLogDBError( $exception );
889 }
890
891 /**
892 * Handle a DBQueryError which occurred during a write operation.
893 *
894 * @param DBError $exception
895 * @param IDatabase|null $db DB handle or null if connection failed
896 * @param int $shardIndex
897 * @throws Exception
898 */
899 private function handleWriteError( DBError $exception, $db, $shardIndex ) {
900 if ( !( $db instanceof IDatabase ) ) {
901 $this->markServerDown( $exception, $shardIndex );
902 }
903
904 $this->setAndLogDBError( $exception );
905 }
906
907 /**
908 * @param DBError $exception
909 */
910 private function setAndLogDBError( DBError $exception ) {
911 $this->logger->error( "DBError: {$exception->getMessage()}" );
912 if ( $exception instanceof DBConnectionError ) {
913 $this->setLastError( BagOStuff::ERR_UNREACHABLE );
914 $this->logger->debug( __METHOD__ . ": ignoring connection error" );
915 } else {
916 $this->setLastError( BagOStuff::ERR_UNEXPECTED );
917 $this->logger->debug( __METHOD__ . ": ignoring query error" );
918 }
919 }
920
921 /**
922 * Mark a server down due to a DBConnectionError exception
923 *
924 * @param DBError $exception
925 * @param int $shardIndex
926 */
927 private function markServerDown( DBError $exception, $shardIndex ) {
928 unset( $this->conns[$shardIndex] ); // bug T103435
929
930 $now = $this->getCurrentTime();
931 if ( isset( $this->connFailureTimes[$shardIndex] ) ) {
932 if ( $now - $this->connFailureTimes[$shardIndex] >= 60 ) {
933 unset( $this->connFailureTimes[$shardIndex] );
934 unset( $this->connFailureErrors[$shardIndex] );
935 } else {
936 $this->logger->debug( __METHOD__ . ": Server #$shardIndex already down" );
937 return;
938 }
939 }
940 $this->logger->info( __METHOD__ . ": Server #$shardIndex down until " . ( $now + 60 ) );
941 $this->connFailureTimes[$shardIndex] = $now;
942 $this->connFailureErrors[$shardIndex] = $exception;
943 }
944
945 /**
946 * Create shard tables. For use from eval.php.
947 */
948 public function createTables() {
949 for ( $shardIndex = 0; $shardIndex < $this->numServerShards; $shardIndex++ ) {
950 $db = $this->getDB( $shardIndex );
951 if ( $db->getType() !== 'mysql' ) {
952 throw new MWException( __METHOD__ . ' is not supported on this DB server' );
953 }
954
955 for ( $i = 0; $i < $this->numTableShards; $i++ ) {
956 $db->query(
957 'CREATE TABLE ' . $db->tableName( $this->getTableNameByShard( $i ) ) .
958 ' LIKE ' . $db->tableName( 'objectcache' ),
959 __METHOD__ );
960 }
961 }
962 }
963
964 /**
965 * @return bool Whether the main DB is used, e.g. wfGetDB( DB_MASTER )
966 */
967 private function usesMainDB() {
968 return !$this->serverInfos;
969 }
970
971 private function waitForReplication() {
972 if ( !$this->usesMainDB() ) {
973 // Custom DB server list; probably doesn't use replication
974 return true;
975 }
976
977 $lb = MediaWikiServices::getInstance()->getDBLoadBalancer();
978 if ( $lb->getServerCount() <= 1 ) {
979 return true; // no replica DBs
980 }
981
982 // Main LB is used; wait for any replica DBs to catch up
983 try {
984 $masterPos = $lb->getMasterPos();
985 if ( !$masterPos ) {
986 return true; // not applicable
987 }
988
989 $loop = new WaitConditionLoop(
990 function () use ( $lb, $masterPos ) {
991 return $lb->waitForAll( $masterPos, 1 );
992 },
993 $this->syncTimeout,
994 $this->busyCallbacks
995 );
996
997 return ( $loop->invoke() === $loop::CONDITION_REACHED );
998 } catch ( DBError $e ) {
999 $this->setAndLogDBError( $e );
1000
1001 return false;
1002 }
1003 }
1004
1005 /**
1006 * Silence the transaction profiler until the return value falls out of scope
1007 *
1008 * @return ScopedCallback|null
1009 */
1010 private function silenceTransactionProfiler() {
1011 if ( !$this->usesMainDB() ) {
1012 // Custom DB is configured which either has no TransactionProfiler injected,
1013 // or has one specific for cache use, which we shouldn't silence
1014 return null;
1015 }
1016
1017 $trxProfiler = Profiler::instance()->getTransactionProfiler();
1018 $oldSilenced = $trxProfiler->setSilenced( true );
1019 return new ScopedCallback( function () use ( $trxProfiler, $oldSilenced ) {
1020 $trxProfiler->setSilenced( $oldSilenced );
1021 } );
1022 }
1023 }