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