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