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