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