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