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