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