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