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