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