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