Merge "Tidy up conditions for applying a block from a cookie"
[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 * - slaveOnly: 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 $this->replicaOnly = !empty( $params['slaveOnly'] );
166 }
167
168 /**
169 * Get a connection to the specified database
170 *
171 * @param int $serverIndex
172 * @return Database
173 * @throws MWException
174 */
175 protected function getDB( $serverIndex ) {
176 if ( !isset( $this->conns[$serverIndex] ) ) {
177 if ( $serverIndex >= $this->numServers ) {
178 throw new MWException( __METHOD__ . ": Invalid server index \"$serverIndex\"" );
179 }
180
181 # Don't keep timing out trying to connect for each call if the DB is down
182 if ( isset( $this->connFailureErrors[$serverIndex] )
183 && ( time() - $this->connFailureTimes[$serverIndex] ) < 60
184 ) {
185 throw $this->connFailureErrors[$serverIndex];
186 }
187
188 if ( $this->serverInfos ) {
189 // Use custom database defined by server connection info
190 $info = $this->serverInfos[$serverIndex];
191 $type = $info['type'] ?? 'mysql';
192 $host = $info['host'] ?? '[unknown]';
193 $this->logger->debug( __CLASS__ . ": connecting to $host" );
194 $db = Database::factory( $type, $info );
195 $db->clearFlag( DBO_TRX ); // auto-commit mode
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 $this->conns[$serverIndex] = $db;
212 }
213
214 return $this->conns[$serverIndex];
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 protected function getTableByKey( $key ) {
223 if ( $this->shards > 1 ) {
224 $hash = hexdec( substr( md5( $key ), 0, 8 ) ) & 0x7fffffff;
225 $tableIndex = $hash % $this->shards;
226 } else {
227 $tableIndex = 0;
228 }
229 if ( $this->numServers > 1 ) {
230 $sortedServers = $this->serverTags;
231 ArrayUtils::consistentHashSort( $sortedServers, $key );
232 reset( $sortedServers );
233 $serverIndex = key( $sortedServers );
234 } else {
235 $serverIndex = 0;
236 }
237 return [ $serverIndex, $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 protected function getTableNameByShard( $index ) {
246 if ( $this->shards > 1 ) {
247 $decimals = strlen( $this->shards - 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 protected function fetchBlobMulti( array $keys, $flags = 0 ) {
283 $values = []; // array of (key => value)
284
285 $keysByTable = [];
286 foreach ( $keys as $key ) {
287 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
288 $keysByTable[$serverIndex][$tableName][] = $key;
289 }
290
291 $dataRows = [];
292 foreach ( $keysByTable as $serverIndex => $serverKeys ) {
293 try {
294 $db = $this->getDB( $serverIndex );
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->serverIndex = $serverIndex;
310 $row->tableName = $tableName;
311 $dataRows[$row->keyname] = $row;
312 }
313 }
314 } catch ( DBError $e ) {
315 $this->handleReadError( $e, $serverIndex );
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->getDB( $row->serverIndex );
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->serverIndex );
333 }
334 } else { // MISS
335 $this->debug( 'get: no matching rows' );
336 }
337 }
338
339 return $values;
340 }
341
342 public 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( $serverIndex, $tableName ) = $this->getTableByKey( $key );
357 $keysByTable[$serverIndex][$tableName][] = $key;
358 }
359
360 $exptime = $this->convertToExpiry( $exptime );
361
362 $result = true;
363 /** @noinspection PhpUnusedLocalVariableInspection */
364 $silenceScope = $this->silenceTransactionProfiler();
365 foreach ( $keysByTable as $serverIndex => $serverKeys ) {
366 $db = null; // in case of connection failure
367 try {
368 $db = $this->getDB( $serverIndex );
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, $serverIndex );
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, $serverIndex );
389 $result = false;
390 }
391
392 }
393 }
394
395 if ( ( $flags & self::WRITE_SYNC ) == 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 public function add( $key, $value, $exptime = 0, $flags = 0 ) {
472 return $this->modifyMulti( [ $key => $value ], $exptime, $flags, self::$OP_ADD );
473 }
474
475 protected function cas( $casToken, $key, $value, $exptime = 0, $flags = 0 ) {
476 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
477 $exptime = $this->convertToExpiry( $exptime );
478
479 /** @noinspection PhpUnusedLocalVariableInspection */
480 $silenceScope = $this->silenceTransactionProfiler();
481 $db = null; // in case of connection failure
482 try {
483 $db = $this->getDB( $serverIndex );
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, $serverIndex );
504
505 return false;
506 }
507
508 return (bool)$db->affectedRows();
509 }
510
511 public function doDeleteMulti( array $keys, $flags = 0 ) {
512 return $this->modifyMulti(
513 array_fill_keys( $keys, null ),
514 0,
515 $flags,
516 self::$OP_DELETE
517 );
518 }
519
520 protected function doDelete( $key, $flags = 0 ) {
521 return $this->modifyMulti( [ $key => null ], 0, $flags, self::$OP_DELETE );
522 }
523
524 public function incr( $key, $step = 1 ) {
525 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
526
527 $newCount = false;
528 /** @noinspection PhpUnusedLocalVariableInspection */
529 $silenceScope = $this->silenceTransactionProfiler();
530 $db = null; // in case of connection failure
531 try {
532 $db = $this->getDB( $serverIndex );
533 $encTimestamp = $db->addQuotes( $db->timestamp() );
534 $db->update(
535 $tableName,
536 [ 'value = value + ' . (int)$step ],
537 [ 'keyname' => $key, "exptime > $encTimestamp" ],
538 __METHOD__
539 );
540 if ( $db->affectedRows() > 0 ) {
541 $newValue = $db->selectField(
542 $tableName,
543 'value',
544 [ 'keyname' => $key, "exptime > $encTimestamp" ],
545 __METHOD__
546 );
547 if ( $this->isInteger( $newValue ) ) {
548 $newCount = (int)$newValue;
549 }
550 }
551 } catch ( DBError $e ) {
552 $this->handleWriteError( $e, $db, $serverIndex );
553 }
554
555 return $newCount;
556 }
557
558 public function merge( $key, callable $callback, $exptime = 0, $attempts = 10, $flags = 0 ) {
559 $ok = $this->mergeViaCas( $key, $callback, $exptime, $attempts, $flags );
560 if ( ( $flags & self::WRITE_SYNC ) == self::WRITE_SYNC ) {
561 $ok = $this->waitForReplication() && $ok;
562 }
563
564 return $ok;
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 protected function isExpired( $db, $exptime ) {
586 return (
587 $exptime != $this->getMaxDateTime( $db ) &&
588 wfTimestamp( TS_UNIX, $exptime ) < time()
589 );
590 }
591
592 /**
593 * @param IDatabase $db
594 * @return string
595 */
596 protected function getMaxDateTime( $db ) {
597 if ( time() > 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 protected function occasionallyGarbageCollect( IDatabase $db ) {
609 if (
610 // Random purging is enabled
611 $this->purgePeriod &&
612 // This is not using a replica DB
613 !$this->replicaOnly &&
614 // Only purge on one in every $this->purgePeriod writes
615 mt_rand( 0, $this->purgePeriod - 1 ) == 0 &&
616 // Avoid repeating the delete within a few seconds
617 ( time() - $this->lastGarbageCollect ) > self::$GARBAGE_COLLECT_DELAY_SEC
618 ) {
619 $garbageCollector = function () use ( $db ) {
620 $this->deleteServerObjectsExpiringBefore( $db, time(), null, $this->purgeLimit );
621 $this->lastGarbageCollect = time();
622 };
623 if ( $this->asyncHandler ) {
624 $this->lastGarbageCollect = time(); // avoid duplicate enqueues
625 ( $this->asyncHandler )( $garbageCollector );
626 } else {
627 $garbageCollector();
628 }
629 }
630 }
631
632 public function expireAll() {
633 $this->deleteObjectsExpiringBefore( time() );
634 }
635
636 public function deleteObjectsExpiringBefore(
637 $timestamp,
638 callable $progressCallback = null,
639 $limit = INF
640 ) {
641 /** @noinspection PhpUnusedLocalVariableInspection */
642 $silenceScope = $this->silenceTransactionProfiler();
643
644 $serverIndexes = range( 0, $this->numServers - 1 );
645 shuffle( $serverIndexes );
646
647 $ok = true;
648
649 $keysDeletedCount = 0;
650 foreach ( $serverIndexes as $numServersDone => $serverIndex ) {
651 $db = null; // in case of connection failure
652 try {
653 $db = $this->getDB( $serverIndex );
654 $this->deleteServerObjectsExpiringBefore(
655 $db,
656 $timestamp,
657 $progressCallback,
658 $limit,
659 $numServersDone,
660 $keysDeletedCount
661 );
662 } catch ( DBError $e ) {
663 $this->handleWriteError( $e, $db, $serverIndex );
664 $ok = false;
665 }
666 }
667
668 return $ok;
669 }
670
671 /**
672 * @param IDatabase $db
673 * @param string|int $timestamp
674 * @param callable|null $progressCallback
675 * @param int $limit
676 * @param int $serversDoneCount
677 * @param int &$keysDeletedCount
678 * @throws DBError
679 */
680 private function deleteServerObjectsExpiringBefore(
681 IDatabase $db,
682 $timestamp,
683 $progressCallback,
684 $limit,
685 $serversDoneCount = 0,
686 &$keysDeletedCount = 0
687 ) {
688 $cutoffUnix = wfTimestamp( TS_UNIX, $timestamp );
689 $shardIndexes = range( 0, $this->shards - 1 );
690 shuffle( $shardIndexes );
691
692 foreach ( $shardIndexes as $numShardsDone => $shardIndex ) {
693 $continue = null; // last exptime
694 $lag = null; // purge lag
695 do {
696 $res = $db->select(
697 $this->getTableNameByShard( $shardIndex ),
698 [ 'keyname', 'exptime' ],
699 array_merge(
700 [ 'exptime < ' . $db->addQuotes( $db->timestamp( $cutoffUnix ) ) ],
701 $continue ? [ 'exptime >= ' . $db->addQuotes( $continue ) ] : []
702 ),
703 __METHOD__,
704 [ 'LIMIT' => min( $limit, 100 ), 'ORDER BY' => 'exptime' ]
705 );
706
707 if ( $res->numRows() ) {
708 $row = $res->current();
709 if ( $lag === null ) {
710 $lag = max( $cutoffUnix - wfTimestamp( TS_UNIX, $row->exptime ), 1 );
711 }
712
713 $keys = [];
714 foreach ( $res as $row ) {
715 $keys[] = $row->keyname;
716 $continue = $row->exptime;
717 }
718
719 $db->delete(
720 $this->getTableNameByShard( $shardIndex ),
721 [
722 'exptime < ' . $db->addQuotes( $db->timestamp( $cutoffUnix ) ),
723 'keyname' => $keys
724 ],
725 __METHOD__
726 );
727 $keysDeletedCount += $db->affectedRows();
728 }
729
730 if ( is_callable( $progressCallback ) ) {
731 if ( $lag ) {
732 $remainingLag = $cutoffUnix - wfTimestamp( TS_UNIX, $continue );
733 $processedLag = max( $lag - $remainingLag, 0 );
734 $doneRatio = ( $numShardsDone + $processedLag / $lag ) / $this->shards;
735 } else {
736 $doneRatio = 1;
737 }
738
739 $overallRatio = ( $doneRatio / $this->numServers )
740 + ( $serversDoneCount / $this->numServers );
741 call_user_func( $progressCallback, $overallRatio * 100 );
742 }
743 } while ( $res->numRows() && $keysDeletedCount < $limit );
744 }
745 }
746
747 /**
748 * Delete content of shard tables in every server.
749 * Return true if the operation is successful, false otherwise.
750 * @return bool
751 */
752 public function deleteAll() {
753 /** @noinspection PhpUnusedLocalVariableInspection */
754 $silenceScope = $this->silenceTransactionProfiler();
755 for ( $serverIndex = 0; $serverIndex < $this->numServers; $serverIndex++ ) {
756 $db = null; // in case of connection failure
757 try {
758 $db = $this->getDB( $serverIndex );
759 for ( $i = 0; $i < $this->shards; $i++ ) {
760 $db->delete( $this->getTableNameByShard( $i ), '*', __METHOD__ );
761 }
762 } catch ( DBError $e ) {
763 $this->handleWriteError( $e, $db, $serverIndex );
764 return false;
765 }
766 }
767 return true;
768 }
769
770 public function lock( $key, $timeout = 6, $expiry = 6, $rclass = '' ) {
771 // Avoid deadlocks and allow lock reentry if specified
772 if ( isset( $this->locks[$key] ) ) {
773 if ( $rclass != '' && $this->locks[$key]['class'] === $rclass ) {
774 ++$this->locks[$key]['depth'];
775 return true;
776 } else {
777 return false;
778 }
779 }
780
781 list( $serverIndex ) = $this->getTableByKey( $key );
782
783 $db = null; // in case of connection failure
784 try {
785 $db = $this->getDB( $serverIndex );
786 $ok = $db->lock( $key, __METHOD__, $timeout );
787 if ( $ok ) {
788 $this->locks[$key] = [ 'class' => $rclass, 'depth' => 1 ];
789 }
790
791 $this->logger->warning(
792 __METHOD__ . " failed due to timeout for {key}.",
793 [ 'key' => $key, 'timeout' => $timeout ]
794 );
795
796 return $ok;
797 } catch ( DBError $e ) {
798 $this->handleWriteError( $e, $db, $serverIndex );
799 $ok = false;
800 }
801
802 return $ok;
803 }
804
805 public function unlock( $key ) {
806 if ( !isset( $this->locks[$key] ) ) {
807 return false;
808 }
809
810 if ( --$this->locks[$key]['depth'] <= 0 ) {
811 unset( $this->locks[$key] );
812
813 list( $serverIndex ) = $this->getTableByKey( $key );
814
815 $db = null; // in case of connection failure
816 try {
817 $db = $this->getDB( $serverIndex );
818 $ok = $db->unlock( $key, __METHOD__ );
819 if ( !$ok ) {
820 $this->logger->warning(
821 __METHOD__ . ' failed to release lock for {key}.',
822 [ 'key' => $key ]
823 );
824 }
825 } catch ( DBError $e ) {
826 $this->handleWriteError( $e, $db, $serverIndex );
827 $ok = false;
828 }
829
830 return $ok;
831 }
832
833 return true;
834 }
835
836 /**
837 * Serialize an object and, if possible, compress the representation.
838 * On typical message and page data, this can provide a 3X decrease
839 * in storage requirements.
840 *
841 * @param mixed $data
842 * @return string|int
843 */
844 protected function serialize( $data ) {
845 if ( is_int( $data ) ) {
846 return $data;
847 }
848
849 $serial = serialize( $data );
850 if ( function_exists( 'gzdeflate' ) ) {
851 $serial = gzdeflate( $serial );
852 }
853
854 return $serial;
855 }
856
857 /**
858 * Unserialize and, if necessary, decompress an object.
859 * @param string $serial
860 * @return mixed
861 */
862 protected function unserialize( $serial ) {
863 if ( $this->isInteger( $serial ) ) {
864 return (int)$serial;
865 }
866
867 if ( function_exists( 'gzinflate' ) ) {
868 Wikimedia\suppressWarnings();
869 $decomp = gzinflate( $serial );
870 Wikimedia\restoreWarnings();
871
872 if ( $decomp !== false ) {
873 $serial = $decomp;
874 }
875 }
876
877 return unserialize( $serial );
878 }
879
880 /**
881 * Handle a DBError which occurred during a read operation.
882 *
883 * @param DBError $exception
884 * @param int $serverIndex
885 */
886 protected function handleReadError( DBError $exception, $serverIndex ) {
887 if ( $exception instanceof DBConnectionError ) {
888 $this->markServerDown( $exception, $serverIndex );
889 }
890
891 $this->setAndLogDBError( $exception );
892 }
893
894 /**
895 * Handle a DBQueryError which occurred during a write operation.
896 *
897 * @param DBError $exception
898 * @param IDatabase|null $db DB handle or null if connection failed
899 * @param int $serverIndex
900 * @throws Exception
901 */
902 protected function handleWriteError( DBError $exception, $db, $serverIndex ) {
903 if ( !( $db instanceof IDatabase ) ) {
904 $this->markServerDown( $exception, $serverIndex );
905 }
906
907 $this->setAndLogDBError( $exception );
908 }
909
910 /**
911 * @param DBError $exception
912 */
913 private function setAndLogDBError( DBError $exception ) {
914 $this->logger->error( "DBError: {$exception->getMessage()}" );
915 if ( $exception instanceof DBConnectionError ) {
916 $this->setLastError( BagOStuff::ERR_UNREACHABLE );
917 $this->logger->debug( __METHOD__ . ": ignoring connection error" );
918 } else {
919 $this->setLastError( BagOStuff::ERR_UNEXPECTED );
920 $this->logger->debug( __METHOD__ . ": ignoring query error" );
921 }
922 }
923
924 /**
925 * Mark a server down due to a DBConnectionError exception
926 *
927 * @param DBError $exception
928 * @param int $serverIndex
929 */
930 protected function markServerDown( DBError $exception, $serverIndex ) {
931 unset( $this->conns[$serverIndex] ); // bug T103435
932
933 if ( isset( $this->connFailureTimes[$serverIndex] ) ) {
934 if ( time() - $this->connFailureTimes[$serverIndex] >= 60 ) {
935 unset( $this->connFailureTimes[$serverIndex] );
936 unset( $this->connFailureErrors[$serverIndex] );
937 } else {
938 $this->logger->debug( __METHOD__ . ": Server #$serverIndex already down" );
939 return;
940 }
941 }
942 $now = time();
943 $this->logger->info( __METHOD__ . ": Server #$serverIndex down until " . ( $now + 60 ) );
944 $this->connFailureTimes[$serverIndex] = $now;
945 $this->connFailureErrors[$serverIndex] = $exception;
946 }
947
948 /**
949 * Create shard tables. For use from eval.php.
950 */
951 public function createTables() {
952 for ( $serverIndex = 0; $serverIndex < $this->numServers; $serverIndex++ ) {
953 $db = $this->getDB( $serverIndex );
954 if ( $db->getType() !== 'mysql' ) {
955 throw new MWException( __METHOD__ . ' is not supported on this DB server' );
956 }
957
958 for ( $i = 0; $i < $this->shards; $i++ ) {
959 $db->query(
960 'CREATE TABLE ' . $db->tableName( $this->getTableNameByShard( $i ) ) .
961 ' LIKE ' . $db->tableName( 'objectcache' ),
962 __METHOD__ );
963 }
964 }
965 }
966
967 /**
968 * @return bool Whether the main DB is used, e.g. wfGetDB( DB_MASTER )
969 */
970 protected function usesMainDB() {
971 return !$this->serverInfos;
972 }
973
974 protected function waitForReplication() {
975 if ( !$this->usesMainDB() ) {
976 // Custom DB server list; probably doesn't use replication
977 return true;
978 }
979
980 $lb = MediaWikiServices::getInstance()->getDBLoadBalancer();
981 if ( $lb->getServerCount() <= 1 ) {
982 return true; // no replica DBs
983 }
984
985 // Main LB is used; wait for any replica DBs to catch up
986 try {
987 $masterPos = $lb->getMasterPos();
988 if ( !$masterPos ) {
989 return true; // not applicable
990 }
991
992 $loop = new WaitConditionLoop(
993 function () use ( $lb, $masterPos ) {
994 return $lb->waitForAll( $masterPos, 1 );
995 },
996 $this->syncTimeout,
997 $this->busyCallbacks
998 );
999
1000 return ( $loop->invoke() === $loop::CONDITION_REACHED );
1001 } catch ( DBError $e ) {
1002 $this->setAndLogDBError( $e );
1003
1004 return false;
1005 }
1006 }
1007
1008 /**
1009 * Returns a ScopedCallback which resets the silence flag in the transaction profiler when it is
1010 * destroyed on the end of a scope, for example on return or throw
1011 * @return ScopedCallback
1012 * @since 1.32
1013 */
1014 protected function silenceTransactionProfiler() {
1015 $trxProfiler = Profiler::instance()->getTransactionProfiler();
1016 $oldSilenced = $trxProfiler->setSilenced( true );
1017 return new ScopedCallback( function () use ( $trxProfiler, $oldSilenced ) {
1018 $trxProfiler->setSilenced( $oldSilenced );
1019 } );
1020 }
1021 }