ba9bb37fb35f08be722d52b4da5dae78f4dc5d8a
[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 connection, tracking, load balancing, and transaction manager for a cluster
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 and profilers
805 $server['connLogger'] = $this->connLogger;
806 $server['queryLogger'] = $this->queryLogger;
807 $server['errorLogger'] = $this->errorLogger;
808 $server['profiler'] = $this->profiler;
809 $server['trxProfiler'] = $this->trxProfiler;
810 // Use the same agent and PHP mode for all DB handles
811 $server['cliMode'] = $this->cliMode;
812 $server['agent'] = $this->agent;
813 // Use DBO_DEFAULT flags by default for LoadBalancer managed databases. Assume that the
814 // application calls LoadBalancer::commitMasterChanges() before the PHP script completes.
815 $server['flags'] = isset( $server['flags'] ) ? $server['flags'] : DBO_DEFAULT;
816
817 // Create a live connection object
818 try {
819 $db = Database::factory( $server['type'], $server );
820 } catch ( DBConnectionError $e ) {
821 // FIXME: This is probably the ugliest thing I have ever done to
822 // PHP. I'm half-expecting it to segfault, just out of disgust. -- TS
823 $db = $e->db;
824 }
825
826 $db->setLBInfo( $server );
827 $db->setLazyMasterHandle(
828 $this->getLazyConnectionRef( DB_MASTER, [], $db->getDomainID() )
829 );
830 $db->setTableAliases( $this->tableAliases );
831
832 if ( $server['serverIndex'] === $this->getWriterIndex() ) {
833 if ( $this->trxRoundId !== false ) {
834 $this->applyTransactionRoundFlags( $db );
835 }
836 foreach ( $this->trxRecurringCallbacks as $name => $callback ) {
837 $db->setTransactionListener( $name, $callback );
838 }
839 }
840
841 return $db;
842 }
843
844 /**
845 * @throws DBConnectionError
846 * @return bool
847 */
848 private function reportConnectionError() {
849 $conn = $this->mErrorConnection; // The connection which caused the error
850 $context = [
851 'method' => __METHOD__,
852 'last_error' => $this->mLastError,
853 ];
854
855 if ( !is_object( $conn ) ) {
856 // No last connection, probably due to all servers being too busy
857 $this->connLogger->error(
858 "LB failure with no last connection. Connection error: {last_error}",
859 $context
860 );
861
862 // If all servers were busy, mLastError will contain something sensible
863 throw new DBConnectionError( null, $this->mLastError );
864 } else {
865 $context['db_server'] = $conn->getProperty( 'mServer' );
866 $this->connLogger->warning(
867 "Connection error: {last_error} ({db_server})",
868 $context
869 );
870
871 // throws DBConnectionError
872 $conn->reportConnectionError( "{$this->mLastError} ({$context['db_server']})" );
873 }
874
875 return false; /* not reached */
876 }
877
878 public function getWriterIndex() {
879 return 0;
880 }
881
882 public function haveIndex( $i ) {
883 return array_key_exists( $i, $this->mServers );
884 }
885
886 public function isNonZeroLoad( $i ) {
887 return array_key_exists( $i, $this->mServers ) && $this->mLoads[$i] != 0;
888 }
889
890 public function getServerCount() {
891 return count( $this->mServers );
892 }
893
894 public function getServerName( $i ) {
895 if ( isset( $this->mServers[$i]['hostName'] ) ) {
896 $name = $this->mServers[$i]['hostName'];
897 } elseif ( isset( $this->mServers[$i]['host'] ) ) {
898 $name = $this->mServers[$i]['host'];
899 } else {
900 $name = '';
901 }
902
903 return ( $name != '' ) ? $name : 'localhost';
904 }
905
906 public function getServerInfo( $i ) {
907 if ( isset( $this->mServers[$i] ) ) {
908 return $this->mServers[$i];
909 } else {
910 return false;
911 }
912 }
913
914 public function setServerInfo( $i, array $serverInfo ) {
915 $this->mServers[$i] = $serverInfo;
916 }
917
918 public function getMasterPos() {
919 # If this entire request was served from a replica DB without opening a connection to the
920 # master (however unlikely that may be), then we can fetch the position from the replica DB.
921 $masterConn = $this->getAnyOpenConnection( $this->getWriterIndex() );
922 if ( !$masterConn ) {
923 $serverCount = count( $this->mServers );
924 for ( $i = 1; $i < $serverCount; $i++ ) {
925 $conn = $this->getAnyOpenConnection( $i );
926 if ( $conn ) {
927 return $conn->getSlavePos();
928 }
929 }
930 } else {
931 return $masterConn->getMasterPos();
932 }
933
934 return false;
935 }
936
937 public function disable() {
938 $this->closeAll();
939 $this->disabled = true;
940 }
941
942 public function closeAll() {
943 $this->forEachOpenConnection( function ( IDatabase $conn ) {
944 $conn->close();
945 } );
946
947 $this->mConns = [
948 'local' => [],
949 'foreignFree' => [],
950 'foreignUsed' => [],
951 ];
952 $this->connsOpened = 0;
953 }
954
955 public function closeConnection( IDatabase $conn ) {
956 $serverIndex = $conn->getLBInfo( 'serverIndex' ); // second index level of mConns
957 foreach ( $this->mConns as $type => $connsByServer ) {
958 if ( !isset( $connsByServer[$serverIndex] ) ) {
959 continue;
960 }
961
962 foreach ( $connsByServer[$serverIndex] as $i => $trackedConn ) {
963 if ( $conn === $trackedConn ) {
964 unset( $this->mConns[$type][$serverIndex][$i] );
965 --$this->connsOpened;
966 break 2;
967 }
968 }
969 }
970
971 $conn->close();
972 }
973
974 public function commitAll( $fname = __METHOD__ ) {
975 $failures = [];
976
977 $restore = ( $this->trxRoundId !== false );
978 $this->trxRoundId = false;
979 $this->forEachOpenConnection(
980 function ( IDatabase $conn ) use ( $fname, $restore, &$failures ) {
981 try {
982 $conn->commit( $fname, $conn::FLUSHING_ALL_PEERS );
983 } catch ( DBError $e ) {
984 call_user_func( $this->errorLogger, $e );
985 $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
986 }
987 if ( $restore && $conn->getLBInfo( 'master' ) ) {
988 $this->undoTransactionRoundFlags( $conn );
989 }
990 }
991 );
992
993 if ( $failures ) {
994 throw new DBExpectedError(
995 null,
996 "Commit failed on server(s) " . implode( "\n", array_unique( $failures ) )
997 );
998 }
999 }
1000
1001 public function finalizeMasterChanges() {
1002 $this->forEachOpenMasterConnection( function ( DatabaseBase $conn ) {
1003 // Any error should cause all DB transactions to be rolled back together
1004 $conn->setTrxEndCallbackSuppression( false );
1005 $conn->runOnTransactionPreCommitCallbacks();
1006 // Defer post-commit callbacks until COMMIT finishes for all DBs
1007 $conn->setTrxEndCallbackSuppression( true );
1008 } );
1009 }
1010
1011 public function approveMasterChanges( array $options ) {
1012 $limit = isset( $options['maxWriteDuration'] ) ? $options['maxWriteDuration'] : 0;
1013 $this->forEachOpenMasterConnection( function ( IDatabase $conn ) use ( $limit ) {
1014 // If atomic sections or explicit transactions are still open, some caller must have
1015 // caught an exception but failed to properly rollback any changes. Detect that and
1016 // throw and error (causing rollback).
1017 if ( $conn->explicitTrxActive() ) {
1018 throw new DBTransactionError(
1019 $conn,
1020 "Explicit transaction still active. A caller may have caught an error."
1021 );
1022 }
1023 // Assert that the time to replicate the transaction will be sane.
1024 // If this fails, then all DB transactions will be rollback back together.
1025 $time = $conn->pendingWriteQueryDuration( $conn::ESTIMATE_DB_APPLY );
1026 if ( $limit > 0 && $time > $limit ) {
1027 throw new DBTransactionSizeError(
1028 $conn,
1029 "Transaction spent $time second(s) in writes, exceeding the $limit limit.",
1030 [ $time, $limit ]
1031 );
1032 }
1033 // If a connection sits idle while slow queries execute on another, that connection
1034 // may end up dropped before the commit round is reached. Ping servers to detect this.
1035 if ( $conn->writesOrCallbacksPending() && !$conn->ping() ) {
1036 throw new DBTransactionError(
1037 $conn,
1038 "A connection to the {$conn->getDBname()} database was lost before commit."
1039 );
1040 }
1041 } );
1042 }
1043
1044 public function beginMasterChanges( $fname = __METHOD__ ) {
1045 if ( $this->trxRoundId !== false ) {
1046 throw new DBTransactionError(
1047 null,
1048 "$fname: Transaction round '{$this->trxRoundId}' already started."
1049 );
1050 }
1051 $this->trxRoundId = $fname;
1052
1053 $failures = [];
1054 $this->forEachOpenMasterConnection(
1055 function ( DatabaseBase $conn ) use ( $fname, &$failures ) {
1056 $conn->setTrxEndCallbackSuppression( true );
1057 try {
1058 $conn->flushSnapshot( $fname );
1059 } catch ( DBError $e ) {
1060 call_user_func( $this->errorLogger, $e );
1061 $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
1062 }
1063 $conn->setTrxEndCallbackSuppression( false );
1064 $this->applyTransactionRoundFlags( $conn );
1065 }
1066 );
1067
1068 if ( $failures ) {
1069 throw new DBExpectedError(
1070 null,
1071 "$fname: Flush failed on server(s) " . implode( "\n", array_unique( $failures ) )
1072 );
1073 }
1074 }
1075
1076 public function commitMasterChanges( $fname = __METHOD__ ) {
1077 $failures = [];
1078
1079 $restore = ( $this->trxRoundId !== false );
1080 $this->trxRoundId = false;
1081 $this->forEachOpenMasterConnection(
1082 function ( IDatabase $conn ) use ( $fname, $restore, &$failures ) {
1083 try {
1084 if ( $conn->writesOrCallbacksPending() ) {
1085 $conn->commit( $fname, $conn::FLUSHING_ALL_PEERS );
1086 } elseif ( $restore ) {
1087 $conn->flushSnapshot( $fname );
1088 }
1089 } catch ( DBError $e ) {
1090 call_user_func( $this->errorLogger, $e );
1091 $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
1092 }
1093 if ( $restore ) {
1094 $this->undoTransactionRoundFlags( $conn );
1095 }
1096 }
1097 );
1098
1099 if ( $failures ) {
1100 throw new DBExpectedError(
1101 null,
1102 "$fname: Commit failed on server(s) " . implode( "\n", array_unique( $failures ) )
1103 );
1104 }
1105 }
1106
1107 public function runMasterPostTrxCallbacks( $type ) {
1108 $e = null; // first exception
1109 $this->forEachOpenMasterConnection( function ( DatabaseBase $conn ) use ( $type, &$e ) {
1110 $conn->setTrxEndCallbackSuppression( false );
1111 if ( $conn->writesOrCallbacksPending() ) {
1112 // This happens if onTransactionIdle() callbacks leave callbacks on *another* DB
1113 // (which finished its callbacks already). Warn and recover in this case. Let the
1114 // callbacks run in the final commitMasterChanges() in LBFactory::shutdown().
1115 $this->queryLogger->error( __METHOD__ . ": found writes/callbacks pending." );
1116 return;
1117 } elseif ( $conn->trxLevel() ) {
1118 // This happens for single-DB setups where DB_REPLICA uses the master DB,
1119 // thus leaving an implicit read-only transaction open at this point. It
1120 // also happens if onTransactionIdle() callbacks leave implicit transactions
1121 // open on *other* DBs (which is slightly improper). Let these COMMIT on the
1122 // next call to commitMasterChanges(), possibly in LBFactory::shutdown().
1123 return;
1124 }
1125 try {
1126 $conn->runOnTransactionIdleCallbacks( $type );
1127 } catch ( Exception $ex ) {
1128 $e = $e ?: $ex;
1129 }
1130 try {
1131 $conn->runTransactionListenerCallbacks( $type );
1132 } catch ( Exception $ex ) {
1133 $e = $e ?: $ex;
1134 }
1135 } );
1136
1137 return $e;
1138 }
1139
1140 public function rollbackMasterChanges( $fname = __METHOD__ ) {
1141 $restore = ( $this->trxRoundId !== false );
1142 $this->trxRoundId = false;
1143 $this->forEachOpenMasterConnection(
1144 function ( IDatabase $conn ) use ( $fname, $restore ) {
1145 if ( $conn->writesOrCallbacksPending() ) {
1146 $conn->rollback( $fname, $conn::FLUSHING_ALL_PEERS );
1147 }
1148 if ( $restore ) {
1149 $this->undoTransactionRoundFlags( $conn );
1150 }
1151 }
1152 );
1153 }
1154
1155 public function suppressTransactionEndCallbacks() {
1156 $this->forEachOpenMasterConnection( function ( DatabaseBase $conn ) {
1157 $conn->setTrxEndCallbackSuppression( true );
1158 } );
1159 }
1160
1161 /**
1162 * @param IDatabase $conn
1163 */
1164 private function applyTransactionRoundFlags( IDatabase $conn ) {
1165 if ( $conn->getFlag( DBO_DEFAULT ) ) {
1166 // DBO_TRX is controlled entirely by CLI mode presence with DBO_DEFAULT.
1167 // Force DBO_TRX even in CLI mode since a commit round is expected soon.
1168 $conn->setFlag( DBO_TRX, $conn::REMEMBER_PRIOR );
1169 // If config has explicitly requested DBO_TRX be either on or off by not
1170 // setting DBO_DEFAULT, then respect that. Forcing no transactions is useful
1171 // for things like blob stores (ExternalStore) which want auto-commit mode.
1172 }
1173 }
1174
1175 /**
1176 * @param IDatabase $conn
1177 */
1178 private function undoTransactionRoundFlags( IDatabase $conn ) {
1179 if ( $conn->getFlag( DBO_DEFAULT ) ) {
1180 $conn->restoreFlags( $conn::RESTORE_PRIOR );
1181 }
1182 }
1183
1184 public function flushReplicaSnapshots( $fname = __METHOD__ ) {
1185 $this->forEachOpenReplicaConnection( function ( IDatabase $conn ) {
1186 $conn->flushSnapshot( __METHOD__ );
1187 } );
1188 }
1189
1190 public function hasMasterConnection() {
1191 return $this->isOpen( $this->getWriterIndex() );
1192 }
1193
1194 public function hasMasterChanges() {
1195 $pending = 0;
1196 $this->forEachOpenMasterConnection( function ( IDatabase $conn ) use ( &$pending ) {
1197 $pending |= $conn->writesOrCallbacksPending();
1198 } );
1199
1200 return (bool)$pending;
1201 }
1202
1203 public function lastMasterChangeTimestamp() {
1204 $lastTime = false;
1205 $this->forEachOpenMasterConnection( function ( IDatabase $conn ) use ( &$lastTime ) {
1206 $lastTime = max( $lastTime, $conn->lastDoneWrites() );
1207 } );
1208
1209 return $lastTime;
1210 }
1211
1212 public function hasOrMadeRecentMasterChanges( $age = null ) {
1213 $age = ( $age === null ) ? $this->mWaitTimeout : $age;
1214
1215 return ( $this->hasMasterChanges()
1216 || $this->lastMasterChangeTimestamp() > microtime( true ) - $age );
1217 }
1218
1219 public function pendingMasterChangeCallers() {
1220 $fnames = [];
1221 $this->forEachOpenMasterConnection( function ( IDatabase $conn ) use ( &$fnames ) {
1222 $fnames = array_merge( $fnames, $conn->pendingWriteCallers() );
1223 } );
1224
1225 return $fnames;
1226 }
1227
1228 public function getLaggedReplicaMode( $domain = false ) {
1229 // No-op if there is only one DB (also avoids recursion)
1230 if ( !$this->laggedReplicaMode && $this->getServerCount() > 1 ) {
1231 try {
1232 // See if laggedReplicaMode gets set
1233 $conn = $this->getConnection( DB_REPLICA, false, $domain );
1234 $this->reuseConnection( $conn );
1235 } catch ( DBConnectionError $e ) {
1236 // Avoid expensive re-connect attempts and failures
1237 $this->allReplicasDownMode = true;
1238 $this->laggedReplicaMode = true;
1239 }
1240 }
1241
1242 return $this->laggedReplicaMode;
1243 }
1244
1245 /**
1246 * @param bool $domain
1247 * @return bool
1248 * @deprecated 1.28; use getLaggedReplicaMode()
1249 */
1250 public function getLaggedSlaveMode( $domain = false ) {
1251 return $this->getLaggedReplicaMode( $domain );
1252 }
1253
1254 public function laggedReplicaUsed() {
1255 return $this->laggedReplicaMode;
1256 }
1257
1258 /**
1259 * @return bool
1260 * @since 1.27
1261 * @deprecated Since 1.28; use laggedReplicaUsed()
1262 */
1263 public function laggedSlaveUsed() {
1264 return $this->laggedReplicaUsed();
1265 }
1266
1267 public function getReadOnlyReason( $domain = false, IDatabase $conn = null ) {
1268 if ( $this->readOnlyReason !== false ) {
1269 return $this->readOnlyReason;
1270 } elseif ( $this->getLaggedReplicaMode( $domain ) ) {
1271 if ( $this->allReplicasDownMode ) {
1272 return 'The database has been automatically locked ' .
1273 'until the replica database servers become available';
1274 } else {
1275 return 'The database has been automatically locked ' .
1276 'while the replica database servers catch up to the master.';
1277 }
1278 } elseif ( $this->masterRunningReadOnly( $domain, $conn ) ) {
1279 return 'The database master is running in read-only mode.';
1280 }
1281
1282 return false;
1283 }
1284
1285 /**
1286 * @param string $domain Domain ID, or false for the current domain
1287 * @param IDatabase|null DB master connectionl used to avoid loops [optional]
1288 * @return bool
1289 */
1290 private function masterRunningReadOnly( $domain, IDatabase $conn = null ) {
1291 $cache = $this->wanCache;
1292 $masterServer = $this->getServerName( $this->getWriterIndex() );
1293
1294 return (bool)$cache->getWithSetCallback(
1295 $cache->makeGlobalKey( __CLASS__, 'server-read-only', $masterServer ),
1296 self::TTL_CACHE_READONLY,
1297 function () use ( $domain, $conn ) {
1298 $this->trxProfiler->setSilenced( true );
1299 try {
1300 $dbw = $conn ?: $this->getConnection( DB_MASTER, [], $domain );
1301 $readOnly = (int)$dbw->serverIsReadOnly();
1302 } catch ( DBError $e ) {
1303 $readOnly = 0;
1304 }
1305 $this->trxProfiler->setSilenced( false );
1306 return $readOnly;
1307 },
1308 [ 'pcTTL' => $cache::TTL_PROC_LONG, 'busyValue' => 0 ]
1309 );
1310 }
1311
1312 public function allowLagged( $mode = null ) {
1313 if ( $mode === null ) {
1314 return $this->mAllowLagged;
1315 }
1316 $this->mAllowLagged = $mode;
1317
1318 return $this->mAllowLagged;
1319 }
1320
1321 public function pingAll() {
1322 $success = true;
1323 $this->forEachOpenConnection( function ( IDatabase $conn ) use ( &$success ) {
1324 if ( !$conn->ping() ) {
1325 $success = false;
1326 }
1327 } );
1328
1329 return $success;
1330 }
1331
1332 public function forEachOpenConnection( $callback, array $params = [] ) {
1333 foreach ( $this->mConns as $connsByServer ) {
1334 foreach ( $connsByServer as $serverConns ) {
1335 foreach ( $serverConns as $conn ) {
1336 $mergedParams = array_merge( [ $conn ], $params );
1337 call_user_func_array( $callback, $mergedParams );
1338 }
1339 }
1340 }
1341 }
1342
1343 public function forEachOpenMasterConnection( $callback, array $params = [] ) {
1344 $masterIndex = $this->getWriterIndex();
1345 foreach ( $this->mConns as $connsByServer ) {
1346 if ( isset( $connsByServer[$masterIndex] ) ) {
1347 /** @var IDatabase $conn */
1348 foreach ( $connsByServer[$masterIndex] as $conn ) {
1349 $mergedParams = array_merge( [ $conn ], $params );
1350 call_user_func_array( $callback, $mergedParams );
1351 }
1352 }
1353 }
1354 }
1355
1356 public function forEachOpenReplicaConnection( $callback, array $params = [] ) {
1357 foreach ( $this->mConns as $connsByServer ) {
1358 foreach ( $connsByServer as $i => $serverConns ) {
1359 if ( $i === $this->getWriterIndex() ) {
1360 continue; // skip master
1361 }
1362 foreach ( $serverConns as $conn ) {
1363 $mergedParams = array_merge( [ $conn ], $params );
1364 call_user_func_array( $callback, $mergedParams );
1365 }
1366 }
1367 }
1368 }
1369
1370 public function getMaxLag( $domain = false ) {
1371 $maxLag = -1;
1372 $host = '';
1373 $maxIndex = 0;
1374
1375 if ( $this->getServerCount() <= 1 ) {
1376 return [ $host, $maxLag, $maxIndex ]; // no replication = no lag
1377 }
1378
1379 $lagTimes = $this->getLagTimes( $domain );
1380 foreach ( $lagTimes as $i => $lag ) {
1381 if ( $this->mLoads[$i] > 0 && $lag > $maxLag ) {
1382 $maxLag = $lag;
1383 $host = $this->mServers[$i]['host'];
1384 $maxIndex = $i;
1385 }
1386 }
1387
1388 return [ $host, $maxLag, $maxIndex ];
1389 }
1390
1391 public function getLagTimes( $domain = false ) {
1392 if ( $this->getServerCount() <= 1 ) {
1393 return [ $this->getWriterIndex() => 0 ]; // no replication = no lag
1394 }
1395
1396 $knownLagTimes = []; // map of (server index => 0 seconds)
1397 $indexesWithLag = [];
1398 foreach ( $this->mServers as $i => $server ) {
1399 if ( empty( $server['is static'] ) ) {
1400 $indexesWithLag[] = $i; // DB server might have replication lag
1401 } else {
1402 $knownLagTimes[$i] = 0; // DB server is a non-replicating and read-only archive
1403 }
1404 }
1405
1406 return $this->getLoadMonitor()->getLagTimes( $indexesWithLag, $domain ) + $knownLagTimes;
1407 }
1408
1409 public function safeGetLag( IDatabase $conn ) {
1410 if ( $this->getServerCount() == 1 ) {
1411 return 0;
1412 } else {
1413 return $conn->getLag();
1414 }
1415 }
1416
1417 public function safeWaitForMasterPos( IDatabase $conn, $pos = false, $timeout = 10 ) {
1418 if ( $this->getServerCount() == 1 || !$conn->getLBInfo( 'replica' ) ) {
1419 return true; // server is not a replica DB
1420 }
1421
1422 $pos = $pos ?: $this->getConnection( DB_MASTER )->getMasterPos();
1423 if ( !( $pos instanceof DBMasterPos ) ) {
1424 return false; // something is misconfigured
1425 }
1426
1427 $result = $conn->masterPosWait( $pos, $timeout );
1428 if ( $result == -1 || is_null( $result ) ) {
1429 $msg = __METHOD__ . ": Timed out waiting on {$conn->getServer()} pos {$pos}";
1430 $this->replLogger->warning( "$msg" );
1431 $ok = false;
1432 } else {
1433 $this->replLogger->info( __METHOD__ . ": Done" );
1434 $ok = true;
1435 }
1436
1437 return $ok;
1438 }
1439
1440 public function clearLagTimeCache() {
1441 $this->getLoadMonitor()->clearCaches();
1442 }
1443
1444 public function setTransactionListener( $name, callable $callback = null ) {
1445 if ( $callback ) {
1446 $this->trxRecurringCallbacks[$name] = $callback;
1447 } else {
1448 unset( $this->trxRecurringCallbacks[$name] );
1449 }
1450 $this->forEachOpenMasterConnection(
1451 function ( IDatabase $conn ) use ( $name, $callback ) {
1452 $conn->setTransactionListener( $name, $callback );
1453 }
1454 );
1455 }
1456
1457 public function setTableAliases( array $aliases ) {
1458 $this->tableAliases = $aliases;
1459 }
1460
1461 public function setDomainPrefix( $prefix ) {
1462 $this->localDomain = new DatabaseDomain(
1463 $this->localDomain->getDatabase(),
1464 null,
1465 $prefix
1466 );
1467
1468 $this->forEachOpenConnection( function ( IDatabase $db ) use ( $prefix ) {
1469 $db->tablePrefix( $prefix );
1470 } );
1471 }
1472 }