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