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