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