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