14f596a780b3108805ca6c57e8e2d4daf69ca79c
[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 $silenceScope = $this->silenceTransactionProfiler();
342 foreach ( $keysByTable as $serverIndex => $serverKeys ) {
343 $db = null;
344 try {
345 $db = $this->getDB( $serverIndex );
346 } catch ( DBError $e ) {
347 $this->handleWriteError( $e, $db, $serverIndex );
348 $result = false;
349 continue;
350 }
351
352 if ( $exptime < 0 ) {
353 $exptime = 0;
354 }
355
356 if ( $exptime == 0 ) {
357 $encExpiry = $this->getMaxDateTime( $db );
358 } else {
359 $exptime = $this->convertToExpiry( $exptime );
360 $encExpiry = $db->timestamp( $exptime );
361 }
362 foreach ( $serverKeys as $tableName => $tableKeys ) {
363 $rows = [];
364 foreach ( $tableKeys as $key ) {
365 $rows[] = [
366 'keyname' => $key,
367 'value' => $db->encodeBlob( $this->serialize( $data[$key] ) ),
368 'exptime' => $encExpiry,
369 ];
370 }
371
372 try {
373 if ( $replace ) {
374 $db->replace( $tableName, [ 'keyname' ], $rows, __METHOD__ );
375 } else {
376 $db->insert( $tableName, $rows, __METHOD__, [ 'IGNORE' ] );
377 $result = ( $db->affectedRows() > 0 && $result );
378 }
379 } catch ( DBError $e ) {
380 $this->handleWriteError( $e, $db, $serverIndex );
381 $result = false;
382 }
383
384 }
385 }
386
387 if ( ( $flags & self::WRITE_SYNC ) == self::WRITE_SYNC ) {
388 $result = $this->waitForReplication() && $result;
389 }
390
391 return $result;
392 }
393
394 protected function doSet( $key, $value, $exptime = 0, $flags = 0 ) {
395 $ok = $this->insertMulti( [ $key => $value ], $exptime, $flags, true );
396
397 return $ok;
398 }
399
400 public function add( $key, $value, $exptime = 0, $flags = 0 ) {
401 $added = $this->insertMulti( [ $key => $value ], $exptime, $flags, false );
402
403 return $added;
404 }
405
406 protected function cas( $casToken, $key, $value, $exptime = 0, $flags = 0 ) {
407 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
408 $db = null;
409 $silenceScope = $this->silenceTransactionProfiler();
410 try {
411 $db = $this->getDB( $serverIndex );
412 $exptime = intval( $exptime );
413
414 if ( $exptime < 0 ) {
415 $exptime = 0;
416 }
417
418 if ( $exptime == 0 ) {
419 $encExpiry = $this->getMaxDateTime( $db );
420 } else {
421 $exptime = $this->convertToExpiry( $exptime );
422 $encExpiry = $db->timestamp( $exptime );
423 }
424 // (T26425) use a replace if the db supports it instead of
425 // delete/insert to avoid clashes with conflicting keynames
426 $db->update(
427 $tableName,
428 [
429 'keyname' => $key,
430 'value' => $db->encodeBlob( $this->serialize( $value ) ),
431 'exptime' => $encExpiry
432 ],
433 [
434 'keyname' => $key,
435 'value' => $db->encodeBlob( $casToken )
436 ],
437 __METHOD__
438 );
439 } catch ( DBQueryError $e ) {
440 $this->handleWriteError( $e, $db, $serverIndex );
441
442 return false;
443 }
444
445 return (bool)$db->affectedRows();
446 }
447
448 public function deleteMulti( array $keys, $flags = 0 ) {
449 return $this->purgeMulti( $keys, $flags );
450 }
451
452 public function purgeMulti( array $keys, $flags = 0 ) {
453 $keysByTable = [];
454 foreach ( $keys as $key ) {
455 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
456 $keysByTable[$serverIndex][$tableName][] = $key;
457 }
458
459 $result = true;
460 $silenceScope = $this->silenceTransactionProfiler();
461 foreach ( $keysByTable as $serverIndex => $serverKeys ) {
462 $db = null;
463 try {
464 $db = $this->getDB( $serverIndex );
465 } catch ( DBError $e ) {
466 $this->handleWriteError( $e, $db, $serverIndex );
467 $result = false;
468 continue;
469 }
470
471 foreach ( $serverKeys as $tableName => $tableKeys ) {
472 try {
473 $db->delete( $tableName, [ 'keyname' => $tableKeys ], __METHOD__ );
474 } catch ( DBError $e ) {
475 $this->handleWriteError( $e, $db, $serverIndex );
476 $result = false;
477 }
478
479 }
480 }
481
482 if ( ( $flags & self::WRITE_SYNC ) == self::WRITE_SYNC ) {
483 $result = $this->waitForReplication() && $result;
484 }
485
486 return $result;
487 }
488
489 protected function doDelete( $key, $flags = 0 ) {
490 $ok = $this->purgeMulti( [ $key ], $flags );
491
492 return $ok;
493 }
494
495 public function incr( $key, $step = 1 ) {
496 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
497 $db = null;
498 $silenceScope = $this->silenceTransactionProfiler();
499 try {
500 $db = $this->getDB( $serverIndex );
501 $step = intval( $step );
502 $row = $db->selectRow(
503 $tableName,
504 [ 'value', 'exptime' ],
505 [ 'keyname' => $key ],
506 __METHOD__,
507 [ 'FOR UPDATE' ]
508 );
509 if ( $row === false ) {
510 // Missing
511 return false;
512 }
513 $db->delete( $tableName, [ 'keyname' => $key ], __METHOD__ );
514 if ( $this->isExpired( $db, $row->exptime ) ) {
515 // Expired, do not reinsert
516 return false;
517 }
518
519 $oldValue = intval( $this->unserialize( $db->decodeBlob( $row->value ) ) );
520 $newValue = $oldValue + $step;
521 $db->insert(
522 $tableName,
523 [
524 'keyname' => $key,
525 'value' => $db->encodeBlob( $this->serialize( $newValue ) ),
526 'exptime' => $row->exptime
527 ],
528 __METHOD__,
529 'IGNORE'
530 );
531
532 if ( $db->affectedRows() == 0 ) {
533 // Race condition. See T30611
534 $newValue = false;
535 }
536 } catch ( DBError $e ) {
537 $this->handleWriteError( $e, $db, $serverIndex );
538 return false;
539 }
540
541 return $newValue;
542 }
543
544 public function merge( $key, callable $callback, $exptime = 0, $attempts = 10, $flags = 0 ) {
545 $ok = $this->mergeViaCas( $key, $callback, $exptime, $attempts, $flags );
546 if ( ( $flags & self::WRITE_SYNC ) == self::WRITE_SYNC ) {
547 $ok = $this->waitForReplication() && $ok;
548 }
549
550 return $ok;
551 }
552
553 public function changeTTL( $key, $exptime = 0, $flags = 0 ) {
554 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
555 $db = null;
556 $silenceScope = $this->silenceTransactionProfiler();
557 try {
558 $db = $this->getDB( $serverIndex );
559 if ( $exptime == 0 ) {
560 $timestamp = $this->getMaxDateTime( $db );
561 } else {
562 $timestamp = $db->timestamp( $this->convertToExpiry( $exptime ) );
563 }
564 $db->update(
565 $tableName,
566 [ 'exptime' => $timestamp ],
567 [ 'keyname' => $key, 'exptime > ' . $db->addQuotes( $db->timestamp( time() ) ) ],
568 __METHOD__
569 );
570 if ( $db->affectedRows() == 0 ) {
571 $exists = (bool)$db->selectField(
572 $tableName,
573 1,
574 [ 'keyname' => $key, 'exptime' => $timestamp ],
575 __METHOD__,
576 [ 'FOR UPDATE' ]
577 );
578
579 return $exists;
580 }
581 } catch ( DBError $e ) {
582 $this->handleWriteError( $e, $db, $serverIndex );
583 return false;
584 }
585
586 return true;
587 }
588
589 /**
590 * @param IDatabase $db
591 * @param string $exptime
592 * @return bool
593 */
594 protected function isExpired( $db, $exptime ) {
595 return $exptime != $this->getMaxDateTime( $db ) && wfTimestamp( TS_UNIX, $exptime ) < time();
596 }
597
598 /**
599 * @param IDatabase $db
600 * @return string
601 */
602 protected function getMaxDateTime( $db ) {
603 if ( time() > 0x7fffffff ) {
604 return $db->timestamp( 1 << 62 );
605 } else {
606 return $db->timestamp( 0x7fffffff );
607 }
608 }
609
610 protected function garbageCollect() {
611 if ( !$this->purgePeriod || $this->replicaOnly ) {
612 // Disabled
613 return;
614 }
615 // Only purge on one in every $this->purgePeriod requests.
616 if ( $this->purgePeriod !== 1 && mt_rand( 0, $this->purgePeriod - 1 ) ) {
617 return;
618 }
619 $now = time();
620 // Avoid repeating the delete within a few seconds
621 if ( $now > ( $this->lastExpireAll + 1 ) ) {
622 $this->lastExpireAll = $now;
623 $this->expireAll();
624 }
625 }
626
627 public function expireAll() {
628 $this->deleteObjectsExpiringBefore( wfTimestampNow() );
629 }
630
631 /**
632 * Delete objects from the database which expire before a certain date.
633 * @param string $timestamp
634 * @param bool|callable $progressCallback
635 * @return bool
636 */
637 public function deleteObjectsExpiringBefore( $timestamp, $progressCallback = false ) {
638 $silenceScope = $this->silenceTransactionProfiler();
639 for ( $serverIndex = 0; $serverIndex < $this->numServers; $serverIndex++ ) {
640 $db = null;
641 try {
642 $db = $this->getDB( $serverIndex );
643 $dbTimestamp = $db->timestamp( $timestamp );
644 $totalSeconds = false;
645 $baseConds = [ 'exptime < ' . $db->addQuotes( $dbTimestamp ) ];
646 for ( $i = 0; $i < $this->shards; $i++ ) {
647 $maxExpTime = false;
648 while ( true ) {
649 $conds = $baseConds;
650 if ( $maxExpTime !== false ) {
651 $conds[] = 'exptime >= ' . $db->addQuotes( $maxExpTime );
652 }
653 $rows = $db->select(
654 $this->getTableNameByShard( $i ),
655 [ 'keyname', 'exptime' ],
656 $conds,
657 __METHOD__,
658 [ 'LIMIT' => 100, 'ORDER BY' => 'exptime' ] );
659 if ( $rows === false || !$rows->numRows() ) {
660 break;
661 }
662 $keys = [];
663 $row = $rows->current();
664 $minExpTime = $row->exptime;
665 if ( $totalSeconds === false ) {
666 $totalSeconds = wfTimestamp( TS_UNIX, $timestamp )
667 - wfTimestamp( TS_UNIX, $minExpTime );
668 }
669 foreach ( $rows as $row ) {
670 $keys[] = $row->keyname;
671 $maxExpTime = $row->exptime;
672 }
673
674 $db->delete(
675 $this->getTableNameByShard( $i ),
676 [
677 'exptime >= ' . $db->addQuotes( $minExpTime ),
678 'exptime < ' . $db->addQuotes( $dbTimestamp ),
679 'keyname' => $keys
680 ],
681 __METHOD__ );
682
683 if ( $progressCallback ) {
684 if ( intval( $totalSeconds ) === 0 ) {
685 $percent = 0;
686 } else {
687 $remainingSeconds = wfTimestamp( TS_UNIX, $timestamp )
688 - wfTimestamp( TS_UNIX, $maxExpTime );
689 if ( $remainingSeconds > $totalSeconds ) {
690 $totalSeconds = $remainingSeconds;
691 }
692 $processedSeconds = $totalSeconds - $remainingSeconds;
693 $percent = ( $i + $processedSeconds / $totalSeconds )
694 / $this->shards * 100;
695 }
696 $percent = ( $percent / $this->numServers )
697 + ( $serverIndex / $this->numServers * 100 );
698 call_user_func( $progressCallback, $percent );
699 }
700 }
701 }
702 } catch ( DBError $e ) {
703 $this->handleWriteError( $e, $db, $serverIndex );
704 return false;
705 }
706 }
707 return true;
708 }
709
710 /**
711 * Delete content of shard tables in every server.
712 * Return true if the operation is successful, false otherwise.
713 * @return bool
714 */
715 public function deleteAll() {
716 $silenceScope = $this->silenceTransactionProfiler();
717 for ( $serverIndex = 0; $serverIndex < $this->numServers; $serverIndex++ ) {
718 $db = null;
719 try {
720 $db = $this->getDB( $serverIndex );
721 for ( $i = 0; $i < $this->shards; $i++ ) {
722 $db->delete( $this->getTableNameByShard( $i ), '*', __METHOD__ );
723 }
724 } catch ( DBError $e ) {
725 $this->handleWriteError( $e, $db, $serverIndex );
726 return false;
727 }
728 }
729 return true;
730 }
731
732 /**
733 * Serialize an object and, if possible, compress the representation.
734 * On typical message and page data, this can provide a 3X decrease
735 * in storage requirements.
736 *
737 * @param mixed $data
738 * @return string
739 */
740 protected function serialize( $data ) {
741 $serial = serialize( $data );
742
743 if ( function_exists( 'gzdeflate' ) ) {
744 return gzdeflate( $serial );
745 } else {
746 return $serial;
747 }
748 }
749
750 /**
751 * Unserialize and, if necessary, decompress an object.
752 * @param string $serial
753 * @return mixed
754 */
755 protected function unserialize( $serial ) {
756 if ( function_exists( 'gzinflate' ) ) {
757 Wikimedia\suppressWarnings();
758 $decomp = gzinflate( $serial );
759 Wikimedia\restoreWarnings();
760
761 if ( $decomp !== false ) {
762 $serial = $decomp;
763 }
764 }
765
766 $ret = unserialize( $serial );
767
768 return $ret;
769 }
770
771 /**
772 * Handle a DBError which occurred during a read operation.
773 *
774 * @param DBError $exception
775 * @param int $serverIndex
776 */
777 protected function handleReadError( DBError $exception, $serverIndex ) {
778 if ( $exception instanceof DBConnectionError ) {
779 $this->markServerDown( $exception, $serverIndex );
780 }
781
782 $this->setAndLogDBError( $exception );
783 }
784
785 /**
786 * Handle a DBQueryError which occurred during a write operation.
787 *
788 * @param DBError $exception
789 * @param IDatabase|null $db DB handle or null if connection failed
790 * @param int $serverIndex
791 * @throws Exception
792 */
793 protected function handleWriteError( DBError $exception, IDatabase $db = null, $serverIndex ) {
794 if ( !$db ) {
795 $this->markServerDown( $exception, $serverIndex );
796 }
797
798 $this->setAndLogDBError( $exception );
799 }
800
801 /**
802 * @param DBError $exception
803 */
804 private function setAndLogDBError( DBError $exception ) {
805 $this->logger->error( "DBError: {$exception->getMessage()}" );
806 if ( $exception instanceof DBConnectionError ) {
807 $this->setLastError( BagOStuff::ERR_UNREACHABLE );
808 $this->logger->debug( __METHOD__ . ": ignoring connection error" );
809 } else {
810 $this->setLastError( BagOStuff::ERR_UNEXPECTED );
811 $this->logger->debug( __METHOD__ . ": ignoring query error" );
812 }
813 }
814
815 /**
816 * Mark a server down due to a DBConnectionError exception
817 *
818 * @param DBError $exception
819 * @param int $serverIndex
820 */
821 protected function markServerDown( DBError $exception, $serverIndex ) {
822 unset( $this->conns[$serverIndex] ); // bug T103435
823
824 if ( isset( $this->connFailureTimes[$serverIndex] ) ) {
825 if ( time() - $this->connFailureTimes[$serverIndex] >= 60 ) {
826 unset( $this->connFailureTimes[$serverIndex] );
827 unset( $this->connFailureErrors[$serverIndex] );
828 } else {
829 $this->logger->debug( __METHOD__ . ": Server #$serverIndex already down" );
830 return;
831 }
832 }
833 $now = time();
834 $this->logger->info( __METHOD__ . ": Server #$serverIndex down until " . ( $now + 60 ) );
835 $this->connFailureTimes[$serverIndex] = $now;
836 $this->connFailureErrors[$serverIndex] = $exception;
837 }
838
839 /**
840 * Create shard tables. For use from eval.php.
841 */
842 public function createTables() {
843 for ( $serverIndex = 0; $serverIndex < $this->numServers; $serverIndex++ ) {
844 $db = $this->getDB( $serverIndex );
845 if ( $db->getType() !== 'mysql' ) {
846 throw new MWException( __METHOD__ . ' is not supported on this DB server' );
847 }
848
849 for ( $i = 0; $i < $this->shards; $i++ ) {
850 $db->query(
851 'CREATE TABLE ' . $db->tableName( $this->getTableNameByShard( $i ) ) .
852 ' LIKE ' . $db->tableName( 'objectcache' ),
853 __METHOD__ );
854 }
855 }
856 }
857
858 /**
859 * @return bool Whether the main DB is used, e.g. wfGetDB( DB_MASTER )
860 */
861 protected function usesMainDB() {
862 return !$this->serverInfos;
863 }
864
865 protected function waitForReplication() {
866 if ( !$this->usesMainDB() ) {
867 // Custom DB server list; probably doesn't use replication
868 return true;
869 }
870
871 $lb = MediaWikiServices::getInstance()->getDBLoadBalancer();
872 if ( $lb->getServerCount() <= 1 ) {
873 return true; // no replica DBs
874 }
875
876 // Main LB is used; wait for any replica DBs to catch up
877 try {
878 $masterPos = $lb->getMasterPos();
879 if ( !$masterPos ) {
880 return true; // not applicable
881 }
882
883 $loop = new WaitConditionLoop(
884 function () use ( $lb, $masterPos ) {
885 return $lb->waitForAll( $masterPos, 1 );
886 },
887 $this->syncTimeout,
888 $this->busyCallbacks
889 );
890
891 return ( $loop->invoke() === $loop::CONDITION_REACHED );
892 } catch ( DBError $e ) {
893 $this->setAndLogDBError( $e );
894
895 return false;
896 }
897 }
898
899 /**
900 * Returns a ScopedCallback which resets the silence flag in the transaction profiler when it is
901 * destroyed on the end of a scope, for example on return or throw
902 * @return ScopedCallback
903 * @since 1.32
904 */
905 protected function silenceTransactionProfiler() {
906 $trxProfiler = Profiler::instance()->getTransactionProfiler();
907 $oldSilenced = $trxProfiler->setSilenced( true );
908 return new ScopedCallback( function () use ( $trxProfiler, $oldSilenced ) {
909 $trxProfiler->setSilenced( $oldSilenced );
910 } );
911 }
912 }