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