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