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