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