Merge "Move MediaHandler defaults out of global scope"
[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 /**
475 * @param IDatabase $db
476 * @param string $exptime
477 * @return bool
478 */
479 protected function isExpired( $db, $exptime ) {
480 return $exptime != $this->getMaxDateTime( $db ) && wfTimestamp( TS_UNIX, $exptime ) < time();
481 }
482
483 /**
484 * @param IDatabase $db
485 * @return string
486 */
487 protected function getMaxDateTime( $db ) {
488 if ( time() > 0x7fffffff ) {
489 return $db->timestamp( 1 << 62 );
490 } else {
491 return $db->timestamp( 0x7fffffff );
492 }
493 }
494
495 protected function garbageCollect() {
496 if ( !$this->purgePeriod || $this->slaveOnly ) {
497 // Disabled
498 return;
499 }
500 // Only purge on one in every $this->purgePeriod requests.
501 if ( $this->purgePeriod !== 1 && mt_rand( 0, $this->purgePeriod - 1 ) ) {
502 return;
503 }
504 $now = time();
505 // Avoid repeating the delete within a few seconds
506 if ( $now > ( $this->lastExpireAll + 1 ) ) {
507 $this->lastExpireAll = $now;
508 $this->expireAll();
509 }
510 }
511
512 public function expireAll() {
513 $this->deleteObjectsExpiringBefore( wfTimestampNow() );
514 }
515
516 /**
517 * Delete objects from the database which expire before a certain date.
518 * @param string $timestamp
519 * @param bool|callable $progressCallback
520 * @return bool
521 */
522 public function deleteObjectsExpiringBefore( $timestamp, $progressCallback = false ) {
523 for ( $serverIndex = 0; $serverIndex < $this->numServers; $serverIndex++ ) {
524 try {
525 $db = $this->getDB( $serverIndex );
526 $dbTimestamp = $db->timestamp( $timestamp );
527 $totalSeconds = false;
528 $baseConds = [ 'exptime < ' . $db->addQuotes( $dbTimestamp ) ];
529 for ( $i = 0; $i < $this->shards; $i++ ) {
530 $maxExpTime = false;
531 while ( true ) {
532 $conds = $baseConds;
533 if ( $maxExpTime !== false ) {
534 $conds[] = 'exptime > ' . $db->addQuotes( $maxExpTime );
535 }
536 $rows = $db->select(
537 $this->getTableNameByShard( $i ),
538 [ 'keyname', 'exptime' ],
539 $conds,
540 __METHOD__,
541 [ 'LIMIT' => 100, 'ORDER BY' => 'exptime' ] );
542 if ( $rows === false || !$rows->numRows() ) {
543 break;
544 }
545 $keys = [];
546 $row = $rows->current();
547 $minExpTime = $row->exptime;
548 if ( $totalSeconds === false ) {
549 $totalSeconds = wfTimestamp( TS_UNIX, $timestamp )
550 - wfTimestamp( TS_UNIX, $minExpTime );
551 }
552 foreach ( $rows as $row ) {
553 $keys[] = $row->keyname;
554 $maxExpTime = $row->exptime;
555 }
556
557 $db->delete(
558 $this->getTableNameByShard( $i ),
559 [
560 'exptime >= ' . $db->addQuotes( $minExpTime ),
561 'exptime < ' . $db->addQuotes( $dbTimestamp ),
562 'keyname' => $keys
563 ],
564 __METHOD__ );
565
566 if ( $progressCallback ) {
567 if ( intval( $totalSeconds ) === 0 ) {
568 $percent = 0;
569 } else {
570 $remainingSeconds = wfTimestamp( TS_UNIX, $timestamp )
571 - wfTimestamp( TS_UNIX, $maxExpTime );
572 if ( $remainingSeconds > $totalSeconds ) {
573 $totalSeconds = $remainingSeconds;
574 }
575 $processedSeconds = $totalSeconds - $remainingSeconds;
576 $percent = ( $i + $processedSeconds / $totalSeconds )
577 / $this->shards * 100;
578 }
579 $percent = ( $percent / $this->numServers )
580 + ( $serverIndex / $this->numServers * 100 );
581 call_user_func( $progressCallback, $percent );
582 }
583 }
584 }
585 } catch ( DBError $e ) {
586 $this->handleWriteError( $e, $serverIndex );
587 return false;
588 }
589 }
590 return true;
591 }
592
593 /**
594 * Delete content of shard tables in every server.
595 * Return true if the operation is successful, false otherwise.
596 * @return bool
597 */
598 public function deleteAll() {
599 for ( $serverIndex = 0; $serverIndex < $this->numServers; $serverIndex++ ) {
600 try {
601 $db = $this->getDB( $serverIndex );
602 for ( $i = 0; $i < $this->shards; $i++ ) {
603 $db->delete( $this->getTableNameByShard( $i ), '*', __METHOD__ );
604 }
605 } catch ( DBError $e ) {
606 $this->handleWriteError( $e, $serverIndex );
607 return false;
608 }
609 }
610 return true;
611 }
612
613 /**
614 * Serialize an object and, if possible, compress the representation.
615 * On typical message and page data, this can provide a 3X decrease
616 * in storage requirements.
617 *
618 * @param mixed $data
619 * @return string
620 */
621 protected function serialize( &$data ) {
622 $serial = serialize( $data );
623
624 if ( function_exists( 'gzdeflate' ) ) {
625 return gzdeflate( $serial );
626 } else {
627 return $serial;
628 }
629 }
630
631 /**
632 * Unserialize and, if necessary, decompress an object.
633 * @param string $serial
634 * @return mixed
635 */
636 protected function unserialize( $serial ) {
637 if ( function_exists( 'gzinflate' ) ) {
638 MediaWiki\suppressWarnings();
639 $decomp = gzinflate( $serial );
640 MediaWiki\restoreWarnings();
641
642 if ( false !== $decomp ) {
643 $serial = $decomp;
644 }
645 }
646
647 $ret = unserialize( $serial );
648
649 return $ret;
650 }
651
652 /**
653 * Handle a DBError which occurred during a read operation.
654 *
655 * @param DBError $exception
656 * @param int $serverIndex
657 */
658 protected function handleReadError( DBError $exception, $serverIndex ) {
659 if ( $exception instanceof DBConnectionError ) {
660 $this->markServerDown( $exception, $serverIndex );
661 }
662 $this->logger->error( "DBError: {$exception->getMessage()}" );
663 if ( $exception instanceof DBConnectionError ) {
664 $this->setLastError( BagOStuff::ERR_UNREACHABLE );
665 $this->logger->debug( __METHOD__ . ": ignoring connection error" );
666 } else {
667 $this->setLastError( BagOStuff::ERR_UNEXPECTED );
668 $this->logger->debug( __METHOD__ . ": ignoring query error" );
669 }
670 }
671
672 /**
673 * Handle a DBQueryError which occurred during a write operation.
674 *
675 * @param DBError $exception
676 * @param int $serverIndex
677 */
678 protected function handleWriteError( DBError $exception, $serverIndex ) {
679 if ( $exception instanceof DBConnectionError ) {
680 $this->markServerDown( $exception, $serverIndex );
681 }
682 if ( $exception->db && $exception->db->wasReadOnlyError() ) {
683 if ( $exception->db->trxLevel() ) {
684 try {
685 $exception->db->rollback( __METHOD__ );
686 } catch ( DBError $e ) {
687 }
688 }
689 }
690
691 $this->logger->error( "DBError: {$exception->getMessage()}" );
692 if ( $exception instanceof DBConnectionError ) {
693 $this->setLastError( BagOStuff::ERR_UNREACHABLE );
694 $this->logger->debug( __METHOD__ . ": ignoring connection error" );
695 } else {
696 $this->setLastError( BagOStuff::ERR_UNEXPECTED );
697 $this->logger->debug( __METHOD__ . ": ignoring query error" );
698 }
699 }
700
701 /**
702 * Mark a server down due to a DBConnectionError exception
703 *
704 * @param DBError $exception
705 * @param int $serverIndex
706 */
707 protected function markServerDown( $exception, $serverIndex ) {
708 unset( $this->conns[$serverIndex] ); // bug T103435
709
710 if ( isset( $this->connFailureTimes[$serverIndex] ) ) {
711 if ( time() - $this->connFailureTimes[$serverIndex] >= 60 ) {
712 unset( $this->connFailureTimes[$serverIndex] );
713 unset( $this->connFailureErrors[$serverIndex] );
714 } else {
715 $this->logger->debug( __METHOD__ . ": Server #$serverIndex already down" );
716 return;
717 }
718 }
719 $now = time();
720 $this->logger->info( __METHOD__ . ": Server #$serverIndex down until " . ( $now + 60 ) );
721 $this->connFailureTimes[$serverIndex] = $now;
722 $this->connFailureErrors[$serverIndex] = $exception;
723 }
724
725 /**
726 * Create shard tables. For use from eval.php.
727 */
728 public function createTables() {
729 for ( $serverIndex = 0; $serverIndex < $this->numServers; $serverIndex++ ) {
730 $db = $this->getDB( $serverIndex );
731 if ( $db->getType() !== 'mysql' ) {
732 throw new MWException( __METHOD__ . ' is not supported on this DB server' );
733 }
734
735 for ( $i = 0; $i < $this->shards; $i++ ) {
736 $db->query(
737 'CREATE TABLE ' . $db->tableName( $this->getTableNameByShard( $i ) ) .
738 ' LIKE ' . $db->tableName( 'objectcache' ),
739 __METHOD__ );
740 }
741 }
742 }
743
744 protected function waitForSlaves() {
745 if ( !$this->serverInfos ) {
746 // Main LB is used; wait for any slaves to catch up
747 try {
748 wfGetLBFactory()->waitForReplication( [ 'wiki' => wfWikiID() ] );
749 return true;
750 } catch ( DBReplicationWaitError $e ) {
751 return false;
752 }
753 } else {
754 // Custom DB server list; probably doesn't use replication
755 return true;
756 }
757 }
758 }