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