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