Merge "Upgrade justinrainbow/json-schema to ~3.0"
[lhc/web/wiklou.git] / includes / db / loadbalancer / LoadBalancer.php
1 <?php
2 /**
3 * Database load balancing.
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 Database
22 */
23
24 /**
25 * Database load balancing object
26 *
27 * @todo document
28 * @ingroup Database
29 */
30 class LoadBalancer {
31 /** @var array[] Map of (server index => server config array) */
32 private $mServers;
33 /** @var array[] Map of (local/foreignUsed/foreignFree => server index => DatabaseBase array) */
34 private $mConns;
35 /** @var array Map of (server index => weight) */
36 private $mLoads;
37 /** @var array[] Map of (group => server index => weight) */
38 private $mGroupLoads;
39 /** @var bool Whether to disregard slave lag as a factor in slave selection */
40 private $mAllowLagged;
41 /** @var integer Seconds to spend waiting on slave lag to resolve */
42 private $mWaitTimeout;
43 /** @var array LBFactory information */
44 private $mParentInfo;
45
46 /** @var string The LoadMonitor subclass name */
47 private $mLoadMonitorClass;
48 /** @var LoadMonitor */
49 private $mLoadMonitor;
50 /** @var BagOStuff */
51 private $srvCache;
52 /** @var WANObjectCache */
53 private $wanCache;
54
55 /** @var bool|DatabaseBase Database connection that caused a problem */
56 private $mErrorConnection;
57 /** @var integer The generic (not query grouped) slave index (of $mServers) */
58 private $mReadIndex;
59 /** @var bool|DBMasterPos False if not set */
60 private $mWaitForPos;
61 /** @var bool Whether the generic reader fell back to a lagged slave */
62 private $laggedSlaveMode = false;
63 /** @var bool Whether the generic reader fell back to a lagged slave */
64 private $slavesDownMode = false;
65 /** @var string The last DB selection or connection error */
66 private $mLastError = 'Unknown error';
67 /** @var string|bool Reason the LB is read-only or false if not */
68 private $readOnlyReason = false;
69 /** @var integer Total connections opened */
70 private $connsOpened = 0;
71
72 /** @var TransactionProfiler */
73 protected $trxProfiler;
74
75 /** @var integer Warn when this many connection are held */
76 const CONN_HELD_WARN_THRESHOLD = 10;
77 /** @var integer Default 'max lag' when unspecified */
78 const MAX_LAG = 10;
79 /** @var integer Max time to wait for a slave to catch up (e.g. ChronologyProtector) */
80 const POS_WAIT_TIMEOUT = 10;
81 /** @var integer Seconds to cache master server read-only status */
82 const TTL_CACHE_READONLY = 5;
83
84 /**
85 * @var boolean
86 */
87 private $disabled = false;
88
89 /**
90 * @param array $params Array with keys:
91 * - servers : Required. Array of server info structures.
92 * - loadMonitor : Name of a class used to fetch server lag and load.
93 * - readOnlyReason : Reason the master DB is read-only if so [optional]
94 * - srvCache : BagOStuff object [optional]
95 * - wanCache : WANObjectCache object [optional]
96 * @throws MWException
97 */
98 public function __construct( array $params ) {
99 if ( !isset( $params['servers'] ) ) {
100 throw new MWException( __CLASS__ . ': missing servers parameter' );
101 }
102 $this->mServers = $params['servers'];
103 $this->mWaitTimeout = self::POS_WAIT_TIMEOUT;
104
105 $this->mReadIndex = -1;
106 $this->mWriteIndex = -1;
107 $this->mConns = [
108 'local' => [],
109 'foreignUsed' => [],
110 'foreignFree' => [] ];
111 $this->mLoads = [];
112 $this->mWaitForPos = false;
113 $this->mErrorConnection = false;
114 $this->mAllowLagged = false;
115
116 if ( isset( $params['readOnlyReason'] ) && is_string( $params['readOnlyReason'] ) ) {
117 $this->readOnlyReason = $params['readOnlyReason'];
118 }
119
120 if ( isset( $params['loadMonitor'] ) ) {
121 $this->mLoadMonitorClass = $params['loadMonitor'];
122 } else {
123 $master = reset( $params['servers'] );
124 if ( isset( $master['type'] ) && $master['type'] === 'mysql' ) {
125 $this->mLoadMonitorClass = 'LoadMonitorMySQL';
126 } else {
127 $this->mLoadMonitorClass = 'LoadMonitorNull';
128 }
129 }
130
131 foreach ( $params['servers'] as $i => $server ) {
132 $this->mLoads[$i] = $server['load'];
133 if ( isset( $server['groupLoads'] ) ) {
134 foreach ( $server['groupLoads'] as $group => $ratio ) {
135 if ( !isset( $this->mGroupLoads[$group] ) ) {
136 $this->mGroupLoads[$group] = [];
137 }
138 $this->mGroupLoads[$group][$i] = $ratio;
139 }
140 }
141 }
142
143 if ( isset( $params['srvCache'] ) ) {
144 $this->srvCache = $params['srvCache'];
145 } else {
146 $this->srvCache = new EmptyBagOStuff();
147 }
148 if ( isset( $params['wanCache'] ) ) {
149 $this->wanCache = $params['wanCache'];
150 } else {
151 $this->wanCache = WANObjectCache::newEmpty();
152 }
153 if ( isset( $params['trxProfiler'] ) ) {
154 $this->trxProfiler = $params['trxProfiler'];
155 } else {
156 $this->trxProfiler = new TransactionProfiler();
157 }
158 }
159
160 /**
161 * Get a LoadMonitor instance
162 *
163 * @return LoadMonitor
164 */
165 private function getLoadMonitor() {
166 if ( !isset( $this->mLoadMonitor ) ) {
167 $class = $this->mLoadMonitorClass;
168 $this->mLoadMonitor = new $class( $this );
169 }
170
171 return $this->mLoadMonitor;
172 }
173
174 /**
175 * Get or set arbitrary data used by the parent object, usually an LBFactory
176 * @param mixed $x
177 * @return mixed
178 */
179 public function parentInfo( $x = null ) {
180 return wfSetVar( $this->mParentInfo, $x );
181 }
182
183 /**
184 * @param array $loads
185 * @param bool|string $wiki Wiki to get non-lagged for
186 * @param int $maxLag Restrict the maximum allowed lag to this many seconds
187 * @return bool|int|string
188 */
189 private function getRandomNonLagged( array $loads, $wiki = false, $maxLag = self::MAX_LAG ) {
190 $lags = $this->getLagTimes( $wiki );
191
192 # Unset excessively lagged servers
193 foreach ( $lags as $i => $lag ) {
194 if ( $i != 0 ) {
195 $maxServerLag = $maxLag;
196 if ( isset( $this->mServers[$i]['max lag'] ) ) {
197 $maxServerLag = min( $maxServerLag, $this->mServers[$i]['max lag'] );
198 }
199
200 $host = $this->getServerName( $i );
201 if ( $lag === false ) {
202 wfDebugLog( 'replication', "Server $host (#$i) is not replicating?" );
203 unset( $loads[$i] );
204 } elseif ( $lag > $maxServerLag ) {
205 wfDebugLog( 'replication', "Server $host (#$i) has >= $lag seconds of lag" );
206 unset( $loads[$i] );
207 }
208 }
209 }
210
211 # Find out if all the slaves with non-zero load are lagged
212 $sum = 0;
213 foreach ( $loads as $load ) {
214 $sum += $load;
215 }
216 if ( $sum == 0 ) {
217 # No appropriate DB servers except maybe the master and some slaves with zero load
218 # Do NOT use the master
219 # Instead, this function will return false, triggering read-only mode,
220 # and a lagged slave will be used instead.
221 return false;
222 }
223
224 if ( count( $loads ) == 0 ) {
225 return false;
226 }
227
228 # Return a random representative of the remainder
229 return ArrayUtils::pickRandom( $loads );
230 }
231
232 /**
233 * Get the index of the reader connection, which may be a slave
234 * This takes into account load ratios and lag times. It should
235 * always return a consistent index during a given invocation
236 *
237 * Side effect: opens connections to databases
238 * @param string|bool $group Query group, or false for the generic reader
239 * @param string|bool $wiki Wiki ID, or false for the current wiki
240 * @throws MWException
241 * @return bool|int|string
242 */
243 public function getReaderIndex( $group = false, $wiki = false ) {
244 global $wgDBtype;
245
246 # @todo FIXME: For now, only go through all this for mysql databases
247 if ( $wgDBtype != 'mysql' ) {
248 return $this->getWriterIndex();
249 }
250
251 if ( count( $this->mServers ) == 1 ) {
252 # Skip the load balancing if there's only one server
253 return 0;
254 } elseif ( $group === false && $this->mReadIndex >= 0 ) {
255 # Shortcut if generic reader exists already
256 return $this->mReadIndex;
257 }
258
259 # Find the relevant load array
260 if ( $group !== false ) {
261 if ( isset( $this->mGroupLoads[$group] ) ) {
262 $nonErrorLoads = $this->mGroupLoads[$group];
263 } else {
264 # No loads for this group, return false and the caller can use some other group
265 wfDebugLog( 'connect', __METHOD__ . ": no loads for group $group\n" );
266
267 return false;
268 }
269 } else {
270 $nonErrorLoads = $this->mLoads;
271 }
272
273 if ( !count( $nonErrorLoads ) ) {
274 throw new MWException( "Empty server array given to LoadBalancer" );
275 }
276
277 # Scale the configured load ratios according to the dynamic load (if the load monitor supports it)
278 $this->getLoadMonitor()->scaleLoads( $nonErrorLoads, $group, $wiki );
279
280 $laggedSlaveMode = false;
281
282 # No server found yet
283 $i = false;
284 $conn = false;
285 # First try quickly looking through the available servers for a server that
286 # meets our criteria
287 $currentLoads = $nonErrorLoads;
288 while ( count( $currentLoads ) ) {
289 if ( $this->mAllowLagged || $laggedSlaveMode ) {
290 $i = ArrayUtils::pickRandom( $currentLoads );
291 } else {
292 $i = false;
293 if ( $this->mWaitForPos && $this->mWaitForPos->asOfTime() ) {
294 # ChronologyProtecter causes mWaitForPos to be set via sessions.
295 # This triggers doWait() after connect, so it's especially good to
296 # avoid lagged servers so as to avoid just blocking in that method.
297 $ago = microtime( true ) - $this->mWaitForPos->asOfTime();
298 # Aim for <= 1 second of waiting (being too picky can backfire)
299 $i = $this->getRandomNonLagged( $currentLoads, $wiki, $ago + 1 );
300 }
301 if ( $i === false ) {
302 # Any server with less lag than it's 'max lag' param is preferable
303 $i = $this->getRandomNonLagged( $currentLoads, $wiki );
304 }
305 if ( $i === false && count( $currentLoads ) != 0 ) {
306 # All slaves lagged. Switch to read-only mode
307 wfDebugLog( 'replication', "All slaves lagged. Switch to read-only mode" );
308 $i = ArrayUtils::pickRandom( $currentLoads );
309 $laggedSlaveMode = true;
310 }
311 }
312
313 if ( $i === false ) {
314 # pickRandom() returned false
315 # This is permanent and means the configuration or the load monitor
316 # wants us to return false.
317 wfDebugLog( 'connect', __METHOD__ . ": pickRandom() returned false" );
318
319 return false;
320 }
321
322 $serverName = $this->getServerName( $i );
323 wfDebugLog( 'connect', __METHOD__ . ": Using reader #$i: $serverName..." );
324
325 $conn = $this->openConnection( $i, $wiki );
326 if ( !$conn ) {
327 wfDebugLog( 'connect', __METHOD__ . ": Failed connecting to $i/$wiki" );
328 unset( $nonErrorLoads[$i] );
329 unset( $currentLoads[$i] );
330 $i = false;
331 continue;
332 }
333
334 // Decrement reference counter, we are finished with this connection.
335 // It will be incremented for the caller later.
336 if ( $wiki !== false ) {
337 $this->reuseConnection( $conn );
338 }
339
340 # Return this server
341 break;
342 }
343
344 # If all servers were down, quit now
345 if ( !count( $nonErrorLoads ) ) {
346 wfDebugLog( 'connect', "All servers down" );
347 }
348
349 if ( $i !== false ) {
350 # Slave connection successful
351 # Wait for the session master pos for a short time
352 if ( $this->mWaitForPos && $i > 0 ) {
353 if ( !$this->doWait( $i ) ) {
354 $this->mServers[$i]['slave pos'] = $conn->getSlavePos();
355 }
356 }
357 if ( $this->mReadIndex <= 0 && $this->mLoads[$i] > 0 && $group === false ) {
358 $this->mReadIndex = $i;
359 # Record if the generic reader index is in "lagged slave" mode
360 if ( $laggedSlaveMode ) {
361 $this->laggedSlaveMode = true;
362 }
363 }
364 $serverName = $this->getServerName( $i );
365 wfDebugLog( 'connect', __METHOD__ .
366 ": using server $serverName for group '$group'\n" );
367 }
368
369 return $i;
370 }
371
372 /**
373 * Set the master wait position
374 * If a DB_SLAVE connection has been opened already, waits
375 * Otherwise sets a variable telling it to wait if such a connection is opened
376 * @param DBMasterPos $pos
377 */
378 public function waitFor( $pos ) {
379 $this->mWaitForPos = $pos;
380 $i = $this->mReadIndex;
381
382 if ( $i > 0 ) {
383 if ( !$this->doWait( $i ) ) {
384 $this->mServers[$i]['slave pos'] = $this->getAnyOpenConnection( $i )->getSlavePos();
385 $this->laggedSlaveMode = true;
386 }
387 }
388 }
389
390 /**
391 * Set the master wait position and wait for a "generic" slave to catch up to it
392 *
393 * This can be used a faster proxy for waitForAll()
394 *
395 * @param DBMasterPos $pos
396 * @param int $timeout Max seconds to wait; default is mWaitTimeout
397 * @return bool Success (able to connect and no timeouts reached)
398 * @since 1.26
399 */
400 public function waitForOne( $pos, $timeout = null ) {
401 $this->mWaitForPos = $pos;
402
403 $i = $this->mReadIndex;
404 if ( $i <= 0 ) {
405 // Pick a generic slave if there isn't one yet
406 $readLoads = $this->mLoads;
407 unset( $readLoads[$this->getWriterIndex()] ); // slaves only
408 $readLoads = array_filter( $readLoads ); // with non-zero load
409 $i = ArrayUtils::pickRandom( $readLoads );
410 }
411
412 if ( $i > 0 ) {
413 $ok = $this->doWait( $i, true, $timeout );
414 } else {
415 $ok = true; // no applicable loads
416 }
417
418 return $ok;
419 }
420
421 /**
422 * Set the master wait position and wait for ALL slaves to catch up to it
423 * @param DBMasterPos $pos
424 * @param int $timeout Max seconds to wait; default is mWaitTimeout
425 * @return bool Success (able to connect and no timeouts reached)
426 */
427 public function waitForAll( $pos, $timeout = null ) {
428 $this->mWaitForPos = $pos;
429 $serverCount = count( $this->mServers );
430
431 $ok = true;
432 for ( $i = 1; $i < $serverCount; $i++ ) {
433 if ( $this->mLoads[$i] > 0 ) {
434 $ok = $this->doWait( $i, true, $timeout ) && $ok;
435 }
436 }
437
438 return $ok;
439 }
440
441 /**
442 * Get any open connection to a given server index, local or foreign
443 * Returns false if there is no connection open
444 *
445 * @param int $i
446 * @return DatabaseBase|bool False on failure
447 */
448 public function getAnyOpenConnection( $i ) {
449 foreach ( $this->mConns as $conns ) {
450 if ( !empty( $conns[$i] ) ) {
451 return reset( $conns[$i] );
452 }
453 }
454
455 return false;
456 }
457
458 /**
459 * Wait for a given slave to catch up to the master pos stored in $this
460 * @param int $index Server index
461 * @param bool $open Check the server even if a new connection has to be made
462 * @param int $timeout Max seconds to wait; default is mWaitTimeout
463 * @return bool
464 */
465 protected function doWait( $index, $open = false, $timeout = null ) {
466 $close = false; // close the connection afterwards
467
468 // Check if we already know that the DB has reached this point
469 $server = $this->getServerName( $index );
470 $key = $this->srvCache->makeGlobalKey( __CLASS__, 'last-known-pos', $server );
471 /** @var DBMasterPos $knownReachedPos */
472 $knownReachedPos = $this->srvCache->get( $key );
473 if ( $knownReachedPos && $knownReachedPos->hasReached( $this->mWaitForPos ) ) {
474 wfDebugLog( 'replication', __METHOD__ .
475 ": slave $server known to be caught up (pos >= $knownReachedPos).\n" );
476 return true;
477 }
478
479 // Find a connection to wait on, creating one if needed and allowed
480 $conn = $this->getAnyOpenConnection( $index );
481 if ( !$conn ) {
482 if ( !$open ) {
483 wfDebugLog( 'replication', __METHOD__ . ": no connection open for $server\n" );
484
485 return false;
486 } else {
487 $conn = $this->openConnection( $index, '' );
488 if ( !$conn ) {
489 wfDebugLog( 'replication', __METHOD__ . ": failed to connect to $server\n" );
490
491 return false;
492 }
493 // Avoid connection spam in waitForAll() when connections
494 // are made just for the sake of doing this lag check.
495 $close = true;
496 }
497 }
498
499 wfDebugLog( 'replication', __METHOD__ . ": Waiting for slave $server to catch up...\n" );
500 $timeout = $timeout ?: $this->mWaitTimeout;
501 $result = $conn->masterPosWait( $this->mWaitForPos, $timeout );
502
503 if ( $result == -1 || is_null( $result ) ) {
504 // Timed out waiting for slave, use master instead
505 $msg = __METHOD__ . ": Timed out waiting on $server pos {$this->mWaitForPos}";
506 wfDebugLog( 'replication', "$msg\n" );
507 wfDebugLog( 'DBPerformance', "$msg:\n" . wfBacktrace( true ) );
508 $ok = false;
509 } else {
510 wfDebugLog( 'replication', __METHOD__ . ": Done\n" );
511 $ok = true;
512 // Remember that the DB reached this point
513 $this->srvCache->set( $key, $this->mWaitForPos, BagOStuff::TTL_DAY );
514 }
515
516 if ( $close ) {
517 $this->closeConnection( $conn );
518 }
519
520 return $ok;
521 }
522
523 /**
524 * Get a connection by index
525 * This is the main entry point for this class.
526 *
527 * @param int $i Server index
528 * @param array|string|bool $groups Query group(s), or false for the generic reader
529 * @param string|bool $wiki Wiki ID, or false for the current wiki
530 *
531 * @throws MWException
532 * @return DatabaseBase
533 */
534 public function getConnection( $i, $groups = [], $wiki = false ) {
535 if ( $i === null || $i === false ) {
536 throw new MWException( 'Attempt to call ' . __METHOD__ .
537 ' with invalid server index' );
538 }
539
540 if ( $wiki === wfWikiID() ) {
541 $wiki = false;
542 }
543
544 $groups = ( $groups === false || $groups === [] )
545 ? [ false ] // check one "group": the generic pool
546 : (array)$groups;
547
548 $masterOnly = ( $i == DB_MASTER || $i == $this->getWriterIndex() );
549 $oldConnsOpened = $this->connsOpened; // connections open now
550
551 if ( $i == DB_MASTER ) {
552 $i = $this->getWriterIndex();
553 } else {
554 # Try to find an available server in any the query groups (in order)
555 foreach ( $groups as $group ) {
556 $groupIndex = $this->getReaderIndex( $group, $wiki );
557 if ( $groupIndex !== false ) {
558 $i = $groupIndex;
559 break;
560 }
561 }
562 }
563
564 # Operation-based index
565 if ( $i == DB_SLAVE ) {
566 $this->mLastError = 'Unknown error'; // reset error string
567 # Try the general server pool if $groups are unavailable.
568 $i = in_array( false, $groups, true )
569 ? false // don't bother with this if that is what was tried above
570 : $this->getReaderIndex( false, $wiki );
571 # Couldn't find a working server in getReaderIndex()?
572 if ( $i === false ) {
573 $this->mLastError = 'No working slave server: ' . $this->mLastError;
574
575 return $this->reportConnectionError();
576 }
577 }
578
579 # Now we have an explicit index into the servers array
580 $conn = $this->openConnection( $i, $wiki );
581 if ( !$conn ) {
582 return $this->reportConnectionError();
583 }
584
585 # Profile any new connections that happen
586 if ( $this->connsOpened > $oldConnsOpened ) {
587 $host = $conn->getServer();
588 $dbname = $conn->getDBname();
589 $trxProf = Profiler::instance()->getTransactionProfiler();
590 $trxProf->recordConnection( $host, $dbname, $masterOnly );
591 }
592
593 if ( $masterOnly ) {
594 # Make master-requested DB handles inherit any read-only mode setting
595 $conn->setLBInfo( 'readOnlyReason', $this->getReadOnlyReason( $wiki, $conn ) );
596 }
597
598 return $conn;
599 }
600
601 /**
602 * Mark a foreign connection as being available for reuse under a different
603 * DB name or prefix. This mechanism is reference-counted, and must be called
604 * the same number of times as getConnection() to work.
605 *
606 * @param DatabaseBase $conn
607 * @throws MWException
608 */
609 public function reuseConnection( $conn ) {
610 $serverIndex = $conn->getLBInfo( 'serverIndex' );
611 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
612 if ( $serverIndex === null || $refCount === null ) {
613 wfDebug( __METHOD__ . ": this connection was not opened as a foreign connection\n" );
614 /**
615 * This can happen in code like:
616 * foreach ( $dbs as $db ) {
617 * $conn = $lb->getConnection( DB_SLAVE, [], $db );
618 * ...
619 * $lb->reuseConnection( $conn );
620 * }
621 * When a connection to the local DB is opened in this way, reuseConnection()
622 * should be ignored
623 */
624 return;
625 }
626
627 $dbName = $conn->getDBname();
628 $prefix = $conn->tablePrefix();
629 if ( strval( $prefix ) !== '' ) {
630 $wiki = "$dbName-$prefix";
631 } else {
632 $wiki = $dbName;
633 }
634 if ( $this->mConns['foreignUsed'][$serverIndex][$wiki] !== $conn ) {
635 throw new MWException( __METHOD__ . ": connection not found, has " .
636 "the connection been freed already?" );
637 }
638 $conn->setLBInfo( 'foreignPoolRefCount', --$refCount );
639 if ( $refCount <= 0 ) {
640 $this->mConns['foreignFree'][$serverIndex][$wiki] = $conn;
641 unset( $this->mConns['foreignUsed'][$serverIndex][$wiki] );
642 wfDebug( __METHOD__ . ": freed connection $serverIndex/$wiki\n" );
643 } else {
644 wfDebug( __METHOD__ . ": reference count for $serverIndex/$wiki reduced to $refCount\n" );
645 }
646 }
647
648 /**
649 * Get a database connection handle reference
650 *
651 * The handle's methods wrap simply wrap those of a DatabaseBase handle
652 *
653 * @see LoadBalancer::getConnection() for parameter information
654 *
655 * @param int $db
656 * @param array|string|bool $groups Query group(s), or false for the generic reader
657 * @param string|bool $wiki Wiki ID, or false for the current wiki
658 * @return DBConnRef
659 */
660 public function getConnectionRef( $db, $groups = [], $wiki = false ) {
661 return new DBConnRef( $this, $this->getConnection( $db, $groups, $wiki ) );
662 }
663
664 /**
665 * Get a database connection handle reference without connecting yet
666 *
667 * The handle's methods wrap simply wrap those of a DatabaseBase handle
668 *
669 * @see LoadBalancer::getConnection() for parameter information
670 *
671 * @param int $db
672 * @param array|string|bool $groups Query group(s), or false for the generic reader
673 * @param string|bool $wiki Wiki ID, or false for the current wiki
674 * @return DBConnRef
675 */
676 public function getLazyConnectionRef( $db, $groups = [], $wiki = false ) {
677 return new DBConnRef( $this, [ $db, $groups, $wiki ] );
678 }
679
680 /**
681 * Open a connection to the server given by the specified index
682 * Index must be an actual index into the array.
683 * If the server is already open, returns it.
684 *
685 * On error, returns false, and the connection which caused the
686 * error will be available via $this->mErrorConnection.
687 *
688 * @note If disable() was called on this LoadBalancer, this method will throw a DBAccessError.
689 *
690 * @param int $i Server index
691 * @param string|bool $wiki Wiki ID, or false for the current wiki
692 * @return DatabaseBase|bool Returns false on errors
693 */
694 public function openConnection( $i, $wiki = false ) {
695 if ( $wiki !== false ) {
696 $conn = $this->openForeignConnection( $i, $wiki );
697 } elseif ( isset( $this->mConns['local'][$i][0] ) ) {
698 $conn = $this->mConns['local'][$i][0];
699 } else {
700 $server = $this->mServers[$i];
701 $server['serverIndex'] = $i;
702 $conn = $this->reallyOpenConnection( $server, false );
703 $serverName = $this->getServerName( $i );
704 if ( $conn->isOpen() ) {
705 wfDebugLog( 'connect', "Connected to database $i at $serverName\n" );
706 $this->mConns['local'][$i][0] = $conn;
707 } else {
708 wfDebugLog( 'connect', "Failed to connect to database $i at $serverName\n" );
709 $this->mErrorConnection = $conn;
710 $conn = false;
711 }
712 }
713
714 if ( $conn && !$conn->isOpen() ) {
715 // Connection was made but later unrecoverably lost for some reason.
716 // Do not return a handle that will just throw exceptions on use,
717 // but let the calling code (e.g. getReaderIndex) try another server.
718 // See DatabaseMyslBase::ping() for how this can happen.
719 $this->mErrorConnection = $conn;
720 $conn = false;
721 }
722
723 return $conn;
724 }
725
726 /**
727 * Open a connection to a foreign DB, or return one if it is already open.
728 *
729 * Increments a reference count on the returned connection which locks the
730 * connection to the requested wiki. This reference count can be
731 * decremented by calling reuseConnection().
732 *
733 * If a connection is open to the appropriate server already, but with the wrong
734 * database, it will be switched to the right database and returned, as long as
735 * it has been freed first with reuseConnection().
736 *
737 * On error, returns false, and the connection which caused the
738 * error will be available via $this->mErrorConnection.
739 *
740 * @note If disable() was called on this LoadBalancer, this method will throw a DBAccessError.
741 *
742 * @param int $i Server index
743 * @param string $wiki Wiki ID to open
744 * @return DatabaseBase
745 */
746 private function openForeignConnection( $i, $wiki ) {
747 list( $dbName, $prefix ) = wfSplitWikiID( $wiki );
748 if ( isset( $this->mConns['foreignUsed'][$i][$wiki] ) ) {
749 // Reuse an already-used connection
750 $conn = $this->mConns['foreignUsed'][$i][$wiki];
751 wfDebug( __METHOD__ . ": reusing connection $i/$wiki\n" );
752 } elseif ( isset( $this->mConns['foreignFree'][$i][$wiki] ) ) {
753 // Reuse a free connection for the same wiki
754 $conn = $this->mConns['foreignFree'][$i][$wiki];
755 unset( $this->mConns['foreignFree'][$i][$wiki] );
756 $this->mConns['foreignUsed'][$i][$wiki] = $conn;
757 wfDebug( __METHOD__ . ": reusing free connection $i/$wiki\n" );
758 } elseif ( !empty( $this->mConns['foreignFree'][$i] ) ) {
759 // Reuse a connection from another wiki
760 $conn = reset( $this->mConns['foreignFree'][$i] );
761 $oldWiki = key( $this->mConns['foreignFree'][$i] );
762
763 // The empty string as a DB name means "don't care".
764 // DatabaseMysqlBase::open() already handle this on connection.
765 if ( $dbName !== '' && !$conn->selectDB( $dbName ) ) {
766 $this->mLastError = "Error selecting database $dbName on server " .
767 $conn->getServer() . " from client host " . wfHostname() . "\n";
768 $this->mErrorConnection = $conn;
769 $conn = false;
770 } else {
771 $conn->tablePrefix( $prefix );
772 unset( $this->mConns['foreignFree'][$i][$oldWiki] );
773 $this->mConns['foreignUsed'][$i][$wiki] = $conn;
774 wfDebug( __METHOD__ . ": reusing free connection from $oldWiki for $wiki\n" );
775 }
776 } else {
777 // Open a new connection
778 $server = $this->mServers[$i];
779 $server['serverIndex'] = $i;
780 $server['foreignPoolRefCount'] = 0;
781 $server['foreign'] = true;
782 $conn = $this->reallyOpenConnection( $server, $dbName );
783 if ( !$conn->isOpen() ) {
784 wfDebug( __METHOD__ . ": error opening connection for $i/$wiki\n" );
785 $this->mErrorConnection = $conn;
786 $conn = false;
787 } else {
788 $conn->tablePrefix( $prefix );
789 $this->mConns['foreignUsed'][$i][$wiki] = $conn;
790 wfDebug( __METHOD__ . ": opened new connection for $i/$wiki\n" );
791 }
792 }
793
794 // Increment reference count
795 if ( $conn ) {
796 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
797 $conn->setLBInfo( 'foreignPoolRefCount', $refCount + 1 );
798 }
799
800 return $conn;
801 }
802
803 /**
804 * Test if the specified index represents an open connection
805 *
806 * @param int $index Server index
807 * @access private
808 * @return bool
809 */
810 private function isOpen( $index ) {
811 if ( !is_integer( $index ) ) {
812 return false;
813 }
814
815 return (bool)$this->getAnyOpenConnection( $index );
816 }
817
818 /**
819 * Really opens a connection. Uncached.
820 * Returns a Database object whether or not the connection was successful.
821 * @access private
822 *
823 * @param array $server
824 * @param bool $dbNameOverride
825 * @throws MWException
826 * @return DatabaseBase
827 */
828 protected function reallyOpenConnection( $server, $dbNameOverride = false ) {
829 if ( $this->disabled ) {
830 throw new DBAccessError();
831 }
832
833 if ( !is_array( $server ) ) {
834 throw new MWException( 'You must update your load-balancing configuration. ' .
835 'See DefaultSettings.php entry for $wgDBservers.' );
836 }
837
838 if ( $dbNameOverride !== false ) {
839 $server['dbname'] = $dbNameOverride;
840 }
841
842 // Let the handle know what the cluster master is (e.g. "db1052")
843 $masterName = $this->getServerName( 0 );
844 $server['clusterMasterHost'] = $masterName;
845
846 // Log when many connection are made on requests
847 if ( ++$this->connsOpened >= self::CONN_HELD_WARN_THRESHOLD ) {
848 wfDebugLog( 'DBPerformance', __METHOD__ . ": " .
849 "{$this->connsOpened}+ connections made (master=$masterName)\n" .
850 wfBacktrace( true ) );
851 }
852
853 # Create object
854 try {
855 $db = DatabaseBase::factory( $server['type'], $server );
856 } catch ( DBConnectionError $e ) {
857 // FIXME: This is probably the ugliest thing I have ever done to
858 // PHP. I'm half-expecting it to segfault, just out of disgust. -- TS
859 $db = $e->db;
860 }
861
862 $db->setLBInfo( $server );
863 $db->setLazyMasterHandle(
864 $this->getLazyConnectionRef( DB_MASTER, [], $db->getWikiID() )
865 );
866 $db->setTransactionProfiler( $this->trxProfiler );
867
868 return $db;
869 }
870
871 /**
872 * @throws DBConnectionError
873 * @return bool
874 */
875 private function reportConnectionError() {
876 $conn = $this->mErrorConnection; // The connection which caused the error
877 $context = [
878 'method' => __METHOD__,
879 'last_error' => $this->mLastError,
880 ];
881
882 if ( !is_object( $conn ) ) {
883 // No last connection, probably due to all servers being too busy
884 wfLogDBError(
885 "LB failure with no last connection. Connection error: {last_error}",
886 $context
887 );
888
889 // If all servers were busy, mLastError will contain something sensible
890 throw new DBConnectionError( null, $this->mLastError );
891 } else {
892 $context['db_server'] = $conn->getProperty( 'mServer' );
893 wfLogDBError(
894 "Connection error: {last_error} ({db_server})",
895 $context
896 );
897
898 // throws DBConnectionError
899 $conn->reportConnectionError( "{$this->mLastError} ({$context['db_server']})" );
900 }
901
902 return false; /* not reached */
903 }
904
905 /**
906 * @return int
907 * @since 1.26
908 */
909 public function getWriterIndex() {
910 return 0;
911 }
912
913 /**
914 * Returns true if the specified index is a valid server index
915 *
916 * @param string $i
917 * @return bool
918 */
919 public function haveIndex( $i ) {
920 return array_key_exists( $i, $this->mServers );
921 }
922
923 /**
924 * Returns true if the specified index is valid and has non-zero load
925 *
926 * @param string $i
927 * @return bool
928 */
929 public function isNonZeroLoad( $i ) {
930 return array_key_exists( $i, $this->mServers ) && $this->mLoads[$i] != 0;
931 }
932
933 /**
934 * Get the number of defined servers (not the number of open connections)
935 *
936 * @return int
937 */
938 public function getServerCount() {
939 return count( $this->mServers );
940 }
941
942 /**
943 * Get the host name or IP address of the server with the specified index
944 * Prefer a readable name if available.
945 * @param string $i
946 * @return string
947 */
948 public function getServerName( $i ) {
949 if ( isset( $this->mServers[$i]['hostName'] ) ) {
950 $name = $this->mServers[$i]['hostName'];
951 } elseif ( isset( $this->mServers[$i]['host'] ) ) {
952 $name = $this->mServers[$i]['host'];
953 } else {
954 $name = '';
955 }
956
957 return ( $name != '' ) ? $name : 'localhost';
958 }
959
960 /**
961 * Return the server info structure for a given index, or false if the index is invalid.
962 * @param int $i
963 * @return array|bool
964 */
965 public function getServerInfo( $i ) {
966 if ( isset( $this->mServers[$i] ) ) {
967 return $this->mServers[$i];
968 } else {
969 return false;
970 }
971 }
972
973 /**
974 * Sets the server info structure for the given index. Entry at index $i
975 * is created if it doesn't exist
976 * @param int $i
977 * @param array $serverInfo
978 */
979 public function setServerInfo( $i, array $serverInfo ) {
980 $this->mServers[$i] = $serverInfo;
981 }
982
983 /**
984 * Get the current master position for chronology control purposes
985 * @return mixed
986 */
987 public function getMasterPos() {
988 # If this entire request was served from a slave without opening a connection to the
989 # master (however unlikely that may be), then we can fetch the position from the slave.
990 $masterConn = $this->getAnyOpenConnection( 0 );
991 if ( !$masterConn ) {
992 $serverCount = count( $this->mServers );
993 for ( $i = 1; $i < $serverCount; $i++ ) {
994 $conn = $this->getAnyOpenConnection( $i );
995 if ( $conn ) {
996 return $conn->getSlavePos();
997 }
998 }
999 } else {
1000 return $masterConn->getMasterPos();
1001 }
1002
1003 return false;
1004 }
1005
1006 /**
1007 * Disable this load balancer. All connections are closed, and any attempt to
1008 * open a new connection will result in a DBAccessError.
1009 *
1010 * @since 1.27
1011 */
1012 public function disable() {
1013 $this->closeAll();
1014 $this->disabled = true;
1015 }
1016
1017 /**
1018 * Close all open connections
1019 */
1020 public function closeAll() {
1021 $this->forEachOpenConnection( function ( DatabaseBase $conn ) {
1022 $conn->close();
1023 } );
1024
1025 $this->mConns = [
1026 'local' => [],
1027 'foreignFree' => [],
1028 'foreignUsed' => [],
1029 ];
1030 $this->connsOpened = 0;
1031 }
1032
1033 /**
1034 * Close a connection
1035 * Using this function makes sure the LoadBalancer knows the connection is closed.
1036 * If you use $conn->close() directly, the load balancer won't update its state.
1037 * @param DatabaseBase $conn
1038 */
1039 public function closeConnection( $conn ) {
1040 $done = false;
1041 foreach ( $this->mConns as $i1 => $conns2 ) {
1042 foreach ( $conns2 as $i2 => $conns3 ) {
1043 foreach ( $conns3 as $i3 => $candidateConn ) {
1044 if ( $conn === $candidateConn ) {
1045 $conn->close();
1046 unset( $this->mConns[$i1][$i2][$i3] );
1047 --$this->connsOpened;
1048 $done = true;
1049 break;
1050 }
1051 }
1052 }
1053 }
1054 if ( !$done ) {
1055 $conn->close();
1056 }
1057 }
1058
1059 /**
1060 * Commit transactions on all open connections
1061 * @param string $fname Caller name
1062 */
1063 public function commitAll( $fname = __METHOD__ ) {
1064 $this->forEachOpenConnection( function ( DatabaseBase $conn ) use ( $fname ) {
1065 $conn->commit( $fname, IDatabase::FLUSHING_ALL_PEERS );
1066 } );
1067 }
1068
1069 /**
1070 * Perform all pre-commit callbacks that remain part of the atomic transactions
1071 * and disable any post-commit callbacks until runMasterPostCommitCallbacks()
1072 * @since 1.28
1073 */
1074 public function runMasterPreCommitCallbacks() {
1075 $this->forEachOpenMasterConnection( function ( DatabaseBase $conn ) {
1076 // Any error will cause all DB transactions to be rolled back together.
1077 $conn->runOnTransactionPreCommitCallbacks();
1078 // Defer post-commit callbacks until COMMIT finishes for all DBs.
1079 $conn->setPostCommitCallbackSupression( true );
1080 } );
1081 }
1082
1083 /**
1084 * Perform all pre-commit checks for things like replication safety
1085 * @param array $options Includes:
1086 * - maxWriteDuration : max write query duration time in seconds
1087 * @throws DBTransactionError
1088 * @since 1.28
1089 */
1090 public function approveMasterChanges( array $options ) {
1091 $limit = isset( $options['maxWriteDuration'] ) ? $options['maxWriteDuration'] : 0;
1092 $this->forEachOpenMasterConnection( function ( DatabaseBase $conn ) use ( $limit ) {
1093 // If atomic sections or explicit transactions are still open, some caller must have
1094 // caught an exception but failed to properly rollback any changes. Detect that and
1095 // throw and error (causing rollback).
1096 if ( $conn->explicitTrxActive() ) {
1097 throw new DBTransactionError(
1098 $conn,
1099 "Explicit transaction still active. A caller may have caught an error."
1100 );
1101 }
1102 // Assert that the time to replicate the transaction will be sane.
1103 // If this fails, then all DB transactions will be rollback back together.
1104 $time = $conn->pendingWriteQueryDuration();
1105 if ( $limit > 0 && $time > $limit ) {
1106 throw new DBTransactionError(
1107 $conn,
1108 wfMessage( 'transaction-duration-limit-exceeded', $time, $limit )->text()
1109 );
1110 }
1111 // If a connection sits idle while slow queries execute on another, that connection
1112 // may end up dropped before the commit round is reached. Ping servers to detect this.
1113 if ( $conn->writesOrCallbacksPending() && !$conn->ping() ) {
1114 throw new DBTransactionError(
1115 $conn,
1116 "A connection to the {$conn->getDBname()} database was lost before commit."
1117 );
1118 }
1119 } );
1120 }
1121
1122 /**
1123 * Issue COMMIT on all master connections where writes where done
1124 * @param string $fname Caller name
1125 */
1126 public function commitMasterChanges( $fname = __METHOD__ ) {
1127 $this->forEachOpenMasterConnection( function ( DatabaseBase $conn ) use ( $fname ) {
1128 if ( $conn->writesOrCallbacksPending() ) {
1129 $conn->commit( $fname, IDatabase::FLUSHING_ALL_PEERS );
1130 }
1131 } );
1132 }
1133
1134 /**
1135 * Issue all pending post-commit callbacks
1136 * @return Exception|null The first exception or null if there were none
1137 * @since 1.28
1138 */
1139 public function runMasterPostCommitCallbacks() {
1140 $e = null; // first exception
1141 $this->forEachOpenMasterConnection( function ( DatabaseBase $db ) use ( &$e ) {
1142 $db->setPostCommitCallbackSupression( false );
1143 try {
1144 $db->runOnTransactionIdleCallbacks( IDatabase::TRIGGER_COMMIT );
1145 } catch ( Exception $ex ) {
1146 $e = $e ?: $ex;
1147 }
1148 } );
1149
1150 return $e;
1151 }
1152
1153 /**
1154 * Issue ROLLBACK only on master, only if queries were done on connection
1155 * @param string $fname Caller name
1156 * @throws DBExpectedError
1157 * @since 1.23
1158 */
1159 public function rollbackMasterChanges( $fname = __METHOD__ ) {
1160 $failedServers = [];
1161
1162 $masterIndex = $this->getWriterIndex();
1163 foreach ( $this->mConns as $conns2 ) {
1164 if ( empty( $conns2[$masterIndex] ) ) {
1165 continue;
1166 }
1167 /** @var DatabaseBase $conn */
1168 foreach ( $conns2[$masterIndex] as $conn ) {
1169 if ( $conn->trxLevel() && $conn->writesOrCallbacksPending() ) {
1170 try {
1171 $conn->rollback( $fname, IDatabase::FLUSHING_ALL_PEERS );
1172 } catch ( DBError $e ) {
1173 MWExceptionHandler::logException( $e );
1174 $failedServers[] = $conn->getServer();
1175 }
1176 }
1177 }
1178 }
1179
1180 if ( $failedServers ) {
1181 throw new DBExpectedError( null, "Rollback failed on server(s) " .
1182 implode( ', ', array_unique( $failedServers ) ) );
1183 }
1184 }
1185
1186 /**
1187 * @return bool Whether a master connection is already open
1188 * @since 1.24
1189 */
1190 public function hasMasterConnection() {
1191 return $this->isOpen( $this->getWriterIndex() );
1192 }
1193
1194 /**
1195 * Determine if there are pending changes in a transaction by this thread
1196 * @since 1.23
1197 * @return bool
1198 */
1199 public function hasMasterChanges() {
1200 $masterIndex = $this->getWriterIndex();
1201 foreach ( $this->mConns as $conns2 ) {
1202 if ( empty( $conns2[$masterIndex] ) ) {
1203 continue;
1204 }
1205 /** @var DatabaseBase $conn */
1206 foreach ( $conns2[$masterIndex] as $conn ) {
1207 if ( $conn->trxLevel() && $conn->writesOrCallbacksPending() ) {
1208 return true;
1209 }
1210 }
1211 }
1212 return false;
1213 }
1214
1215 /**
1216 * Get the timestamp of the latest write query done by this thread
1217 * @since 1.25
1218 * @return float|bool UNIX timestamp or false
1219 */
1220 public function lastMasterChangeTimestamp() {
1221 $lastTime = false;
1222 $masterIndex = $this->getWriterIndex();
1223 foreach ( $this->mConns as $conns2 ) {
1224 if ( empty( $conns2[$masterIndex] ) ) {
1225 continue;
1226 }
1227 /** @var DatabaseBase $conn */
1228 foreach ( $conns2[$masterIndex] as $conn ) {
1229 $lastTime = max( $lastTime, $conn->lastDoneWrites() );
1230 }
1231 }
1232 return $lastTime;
1233 }
1234
1235 /**
1236 * Check if this load balancer object had any recent or still
1237 * pending writes issued against it by this PHP thread
1238 *
1239 * @param float $age How many seconds ago is "recent" [defaults to mWaitTimeout]
1240 * @return bool
1241 * @since 1.25
1242 */
1243 public function hasOrMadeRecentMasterChanges( $age = null ) {
1244 $age = ( $age === null ) ? $this->mWaitTimeout : $age;
1245
1246 return ( $this->hasMasterChanges()
1247 || $this->lastMasterChangeTimestamp() > microtime( true ) - $age );
1248 }
1249
1250 /**
1251 * Get the list of callers that have pending master changes
1252 *
1253 * @return array
1254 * @since 1.27
1255 */
1256 public function pendingMasterChangeCallers() {
1257 $fnames = [];
1258
1259 $masterIndex = $this->getWriterIndex();
1260 foreach ( $this->mConns as $conns2 ) {
1261 if ( empty( $conns2[$masterIndex] ) ) {
1262 continue;
1263 }
1264 /** @var DatabaseBase $conn */
1265 foreach ( $conns2[$masterIndex] as $conn ) {
1266 $fnames = array_merge( $fnames, $conn->pendingWriteCallers() );
1267 }
1268 }
1269
1270 return $fnames;
1271 }
1272
1273 /**
1274 * @param mixed $value
1275 * @return mixed
1276 */
1277 public function waitTimeout( $value = null ) {
1278 return wfSetVar( $this->mWaitTimeout, $value );
1279 }
1280
1281 /**
1282 * @note This method will trigger a DB connection if not yet done
1283 *
1284 * @param string|bool $wiki Wiki ID, or false for the current wiki
1285 * @return bool Whether the generic connection for reads is highly "lagged"
1286 */
1287 public function getLaggedSlaveMode( $wiki = false ) {
1288 // No-op if there is only one DB (also avoids recursion)
1289 if ( !$this->laggedSlaveMode && $this->getServerCount() > 1 ) {
1290 try {
1291 // See if laggedSlaveMode gets set
1292 $conn = $this->getConnection( DB_SLAVE, false, $wiki );
1293 $this->reuseConnection( $conn );
1294 } catch ( DBConnectionError $e ) {
1295 // Avoid expensive re-connect attempts and failures
1296 $this->slavesDownMode = true;
1297 $this->laggedSlaveMode = true;
1298 }
1299 }
1300
1301 return $this->laggedSlaveMode;
1302 }
1303
1304 /**
1305 * @note This method will never cause a new DB connection
1306 * @return bool Whether any generic connection used for reads was highly "lagged"
1307 * @since 1.27
1308 */
1309 public function laggedSlaveUsed() {
1310 return $this->laggedSlaveMode;
1311 }
1312
1313 /**
1314 * @note This method may trigger a DB connection if not yet done
1315 * @param string|bool $wiki Wiki ID, or false for the current wiki
1316 * @param DatabaseBase|null DB master connection; used to avoid loops [optional]
1317 * @return string|bool Reason the master is read-only or false if it is not
1318 * @since 1.27
1319 */
1320 public function getReadOnlyReason( $wiki = false, DatabaseBase $conn = null ) {
1321 if ( $this->readOnlyReason !== false ) {
1322 return $this->readOnlyReason;
1323 } elseif ( $this->getLaggedSlaveMode( $wiki ) ) {
1324 if ( $this->slavesDownMode ) {
1325 return 'The database has been automatically locked ' .
1326 'until the slave database servers become available';
1327 } else {
1328 return 'The database has been automatically locked ' .
1329 'while the slave database servers catch up to the master.';
1330 }
1331 } elseif ( $this->masterRunningReadOnly( $wiki, $conn ) ) {
1332 return 'The database master is running in read-only mode.';
1333 }
1334
1335 return false;
1336 }
1337
1338 /**
1339 * @param string $wiki Wiki ID, or false for the current wiki
1340 * @param DatabaseBase|null DB master connectionl used to avoid loops [optional]
1341 * @return bool
1342 */
1343 private function masterRunningReadOnly( $wiki, DatabaseBase $conn = null ) {
1344 $cache = $this->wanCache;
1345 $masterServer = $this->getServerName( $this->getWriterIndex() );
1346
1347 return (bool)$cache->getWithSetCallback(
1348 $cache->makeGlobalKey( __CLASS__, 'server-read-only', $masterServer ),
1349 self::TTL_CACHE_READONLY,
1350 function () use ( $wiki, $conn ) {
1351 $this->trxProfiler->setSilenced( true );
1352 try {
1353 $dbw = $conn ?: $this->getConnection( DB_MASTER, [], $wiki );
1354 $readOnly = (int)$dbw->serverIsReadOnly();
1355 } catch ( DBError $e ) {
1356 $readOnly = 0;
1357 }
1358 $this->trxProfiler->setSilenced( false );
1359 return $readOnly;
1360 },
1361 [ 'pcTTL' => $cache::TTL_PROC_LONG, 'busyValue' => 0 ]
1362 );
1363 }
1364
1365 /**
1366 * Disables/enables lag checks
1367 * @param null|bool $mode
1368 * @return bool
1369 */
1370 public function allowLagged( $mode = null ) {
1371 if ( $mode === null ) {
1372 return $this->mAllowLagged;
1373 }
1374 $this->mAllowLagged = $mode;
1375
1376 return $this->mAllowLagged;
1377 }
1378
1379 /**
1380 * @return bool
1381 */
1382 public function pingAll() {
1383 $success = true;
1384 $this->forEachOpenConnection( function ( DatabaseBase $conn ) use ( &$success ) {
1385 if ( !$conn->ping() ) {
1386 $success = false;
1387 }
1388 } );
1389
1390 return $success;
1391 }
1392
1393 /**
1394 * Call a function with each open connection object
1395 * @param callable $callback
1396 * @param array $params
1397 */
1398 public function forEachOpenConnection( $callback, array $params = [] ) {
1399 foreach ( $this->mConns as $connsByServer ) {
1400 foreach ( $connsByServer as $serverConns ) {
1401 foreach ( $serverConns as $conn ) {
1402 $mergedParams = array_merge( [ $conn ], $params );
1403 call_user_func_array( $callback, $mergedParams );
1404 }
1405 }
1406 }
1407 }
1408
1409 /**
1410 * Call a function with each open connection object to a master
1411 * @param callable $callback
1412 * @param array $params
1413 * @since 1.28
1414 */
1415 public function forEachOpenMasterConnection( $callback, array $params = [] ) {
1416 $masterIndex = $this->getWriterIndex();
1417 foreach ( $this->mConns as $connsByServer ) {
1418 if ( isset( $connsByServer[$masterIndex] ) ) {
1419 /** @var DatabaseBase $conn */
1420 foreach ( $connsByServer[$masterIndex] as $conn ) {
1421 $mergedParams = array_merge( [ $conn ], $params );
1422 call_user_func_array( $callback, $mergedParams );
1423 }
1424 }
1425 }
1426 }
1427
1428 /**
1429 * Get the hostname and lag time of the most-lagged slave
1430 *
1431 * This is useful for maintenance scripts that need to throttle their updates.
1432 * May attempt to open connections to slaves on the default DB. If there is
1433 * no lag, the maximum lag will be reported as -1.
1434 *
1435 * @param bool|string $wiki Wiki ID, or false for the default database
1436 * @return array ( host, max lag, index of max lagged host )
1437 */
1438 public function getMaxLag( $wiki = false ) {
1439 $maxLag = -1;
1440 $host = '';
1441 $maxIndex = 0;
1442
1443 if ( $this->getServerCount() <= 1 ) {
1444 return [ $host, $maxLag, $maxIndex ]; // no replication = no lag
1445 }
1446
1447 $lagTimes = $this->getLagTimes( $wiki );
1448 foreach ( $lagTimes as $i => $lag ) {
1449 if ( $this->mLoads[$i] > 0 && $lag > $maxLag ) {
1450 $maxLag = $lag;
1451 $host = $this->mServers[$i]['host'];
1452 $maxIndex = $i;
1453 }
1454 }
1455
1456 return [ $host, $maxLag, $maxIndex ];
1457 }
1458
1459 /**
1460 * Get an estimate of replication lag (in seconds) for each server
1461 *
1462 * Results are cached for a short time in memcached/process cache
1463 *
1464 * Values may be "false" if replication is too broken to estimate
1465 *
1466 * @param string|bool $wiki
1467 * @return int[] Map of (server index => float|int|bool)
1468 */
1469 public function getLagTimes( $wiki = false ) {
1470 if ( $this->getServerCount() <= 1 ) {
1471 return [ 0 => 0 ]; // no replication = no lag
1472 }
1473
1474 # Send the request to the load monitor
1475 return $this->getLoadMonitor()->getLagTimes( array_keys( $this->mServers ), $wiki );
1476 }
1477
1478 /**
1479 * Get the lag in seconds for a given connection, or zero if this load
1480 * balancer does not have replication enabled.
1481 *
1482 * This should be used in preference to Database::getLag() in cases where
1483 * replication may not be in use, since there is no way to determine if
1484 * replication is in use at the connection level without running
1485 * potentially restricted queries such as SHOW SLAVE STATUS. Using this
1486 * function instead of Database::getLag() avoids a fatal error in this
1487 * case on many installations.
1488 *
1489 * @param IDatabase $conn
1490 * @return int|bool Returns false on error
1491 */
1492 public function safeGetLag( IDatabase $conn ) {
1493 if ( $this->getServerCount() == 1 ) {
1494 return 0;
1495 } else {
1496 return $conn->getLag();
1497 }
1498 }
1499
1500 /**
1501 * Wait for a slave DB to reach a specified master position
1502 *
1503 * This will connect to the master to get an accurate position if $pos is not given
1504 *
1505 * @param IDatabase $conn Slave DB
1506 * @param DBMasterPos|bool $pos Master position; default: current position
1507 * @param integer $timeout Timeout in seconds
1508 * @return bool Success
1509 * @since 1.27
1510 */
1511 public function safeWaitForMasterPos( IDatabase $conn, $pos = false, $timeout = 10 ) {
1512 if ( $this->getServerCount() == 1 || !$conn->getLBInfo( 'slave' ) ) {
1513 return true; // server is not a slave DB
1514 }
1515
1516 $pos = $pos ?: $this->getConnection( DB_MASTER )->getMasterPos();
1517 if ( !( $pos instanceof DBMasterPos ) ) {
1518 return false; // something is misconfigured
1519 }
1520
1521 $result = $conn->masterPosWait( $pos, $timeout );
1522 if ( $result == -1 || is_null( $result ) ) {
1523 $msg = __METHOD__ . ": Timed out waiting on {$conn->getServer()} pos {$pos}";
1524 wfDebugLog( 'replication', "$msg\n" );
1525 wfDebugLog( 'DBPerformance', "$msg:\n" . wfBacktrace( true ) );
1526 $ok = false;
1527 } else {
1528 wfDebugLog( 'replication', __METHOD__ . ": Done\n" );
1529 $ok = true;
1530 }
1531
1532 return $ok;
1533 }
1534
1535 /**
1536 * Clear the cache for slag lag delay times
1537 *
1538 * This is only used for testing
1539 */
1540 public function clearLagTimeCache() {
1541 $this->getLoadMonitor()->clearCaches();
1542 }
1543 }