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