MediaWiki  1.30.0
LoadBalancer.php
Go to the documentation of this file.
1 <?php
23 namespace Wikimedia\Rdbms;
24 
25 use Psr\Log\LoggerInterface;
26 use Psr\Log\NullLogger;
27 use Wikimedia\ScopedCallback;
32 use InvalidArgumentException;
33 use RuntimeException;
34 use Exception;
35 
41 class LoadBalancer implements ILoadBalancer {
43  private $mServers;
45  private $mConns;
47  private $mLoads;
49  private $mGroupLoads;
51  private $mAllowLagged;
53  private $mWaitTimeout;
57  private $tableAliases = [];
58 
60  private $loadMonitor;
62  private $chronProt;
64  private $srvCache;
66  private $wanCache;
68  protected $profiler;
70  protected $trxProfiler;
72  protected $replLogger;
74  protected $connLogger;
76  protected $queryLogger;
78  protected $perfLogger;
79 
83  private $mReadIndex;
85  private $mWaitForPos;
87  private $laggedReplicaMode = false;
89  private $allReplicasDownMode = false;
91  private $mLastError = 'Unknown error';
93  private $readOnlyReason = false;
95  private $connsOpened = 0;
97  private $trxRoundId = false;
99  private $trxRecurringCallbacks = [];
101  private $localDomain;
105  private $host;
107  protected $cliMode;
109  protected $agent;
110 
112  private $errorLogger;
113 
115  private $disabled = false;
117  private $chronProtInitialized = false;
118 
120  const CONN_HELD_WARN_THRESHOLD = 10;
121 
123  const MAX_LAG_DEFAULT = 10;
125  const TTL_CACHE_READONLY = 5;
126 
127  const KEY_LOCAL = 'local';
128  const KEY_FOREIGN_FREE = 'foreignFree';
129  const KEY_FOREIGN_INUSE = 'foreignInUse';
130 
131  const KEY_LOCAL_NOROUND = 'localAutoCommit';
132  const KEY_FOREIGN_FREE_NOROUND = 'foreignFreeAutoCommit';
133  const KEY_FOREIGN_INUSE_NOROUND = 'foreignInUseAutoCommit';
134 
135  public function __construct( array $params ) {
136  if ( !isset( $params['servers'] ) ) {
137  throw new InvalidArgumentException( __CLASS__ . ': missing servers parameter' );
138  }
139  $this->mServers = $params['servers'];
140  foreach ( $this->mServers as $i => $server ) {
141  if ( $i == 0 ) {
142  $this->mServers[$i]['master'] = true;
143  } else {
144  $this->mServers[$i]['replica'] = true;
145  }
146  }
147 
148  $this->localDomain = isset( $params['localDomain'] )
149  ? DatabaseDomain::newFromId( $params['localDomain'] )
151  // In case a caller assumes that the domain ID is simply <db>-<prefix>, which is almost
152  // always true, gracefully handle the case when they fail to account for escaping.
153  if ( $this->localDomain->getTablePrefix() != '' ) {
154  $this->localDomainIdAlias =
155  $this->localDomain->getDatabase() . '-' . $this->localDomain->getTablePrefix();
156  } else {
157  $this->localDomainIdAlias = $this->localDomain->getDatabase();
158  }
159 
160  $this->mWaitTimeout = isset( $params['waitTimeout'] ) ? $params['waitTimeout'] : 10;
161 
162  $this->mReadIndex = -1;
163  $this->mConns = [
164  // Connection were transaction rounds may be applied
165  self::KEY_LOCAL => [],
166  self::KEY_FOREIGN_INUSE => [],
167  self::KEY_FOREIGN_FREE => [],
168  // Auto-committing counterpart connections that ignore transaction rounds
169  self::KEY_LOCAL_NOROUND => [],
170  self::KEY_FOREIGN_INUSE_NOROUND => [],
171  self::KEY_FOREIGN_FREE_NOROUND => []
172  ];
173  $this->mLoads = [];
174  $this->mWaitForPos = false;
175  $this->mAllowLagged = false;
176 
177  if ( isset( $params['readOnlyReason'] ) && is_string( $params['readOnlyReason'] ) ) {
178  $this->readOnlyReason = $params['readOnlyReason'];
179  }
180 
181  if ( isset( $params['loadMonitor'] ) ) {
182  $this->loadMonitorConfig = $params['loadMonitor'];
183  } else {
184  $this->loadMonitorConfig = [ 'class' => 'LoadMonitorNull' ];
185  }
186 
187  foreach ( $params['servers'] as $i => $server ) {
188  $this->mLoads[$i] = $server['load'];
189  if ( isset( $server['groupLoads'] ) ) {
190  foreach ( $server['groupLoads'] as $group => $ratio ) {
191  if ( !isset( $this->mGroupLoads[$group] ) ) {
192  $this->mGroupLoads[$group] = [];
193  }
194  $this->mGroupLoads[$group][$i] = $ratio;
195  }
196  }
197  }
198 
199  if ( isset( $params['srvCache'] ) ) {
200  $this->srvCache = $params['srvCache'];
201  } else {
202  $this->srvCache = new EmptyBagOStuff();
203  }
204  if ( isset( $params['wanCache'] ) ) {
205  $this->wanCache = $params['wanCache'];
206  } else {
207  $this->wanCache = WANObjectCache::newEmpty();
208  }
209  $this->profiler = isset( $params['profiler'] ) ? $params['profiler'] : null;
210  if ( isset( $params['trxProfiler'] ) ) {
211  $this->trxProfiler = $params['trxProfiler'];
212  } else {
213  $this->trxProfiler = new TransactionProfiler();
214  }
215 
216  $this->errorLogger = isset( $params['errorLogger'] )
217  ? $params['errorLogger']
218  : function ( Exception $e ) {
219  trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_USER_WARNING );
220  };
221 
222  foreach ( [ 'replLogger', 'connLogger', 'queryLogger', 'perfLogger' ] as $key ) {
223  $this->$key = isset( $params[$key] ) ? $params[$key] : new NullLogger();
224  }
225 
226  $this->host = isset( $params['hostname'] )
227  ? $params['hostname']
228  : ( gethostname() ?: 'unknown' );
229  $this->cliMode = isset( $params['cliMode'] ) ? $params['cliMode'] : PHP_SAPI === 'cli';
230  $this->agent = isset( $params['agent'] ) ? $params['agent'] : '';
231 
232  if ( isset( $params['chronologyProtector'] ) ) {
233  $this->chronProt = $params['chronologyProtector'];
234  }
235  }
236 
242  private function getLoadMonitor() {
243  if ( !isset( $this->loadMonitor ) ) {
244  $compat = [
245  'LoadMonitor' => LoadMonitor::class,
246  'LoadMonitorNull' => LoadMonitorNull::class,
247  'LoadMonitorMySQL' => LoadMonitorMySQL::class,
248  ];
249 
250  $class = $this->loadMonitorConfig['class'];
251  if ( isset( $compat[$class] ) ) {
252  $class = $compat[$class];
253  }
254 
255  $this->loadMonitor = new $class(
256  $this, $this->srvCache, $this->wanCache, $this->loadMonitorConfig );
257  $this->loadMonitor->setLogger( $this->replLogger );
258  }
259 
260  return $this->loadMonitor;
261  }
262 
269  private function getRandomNonLagged( array $loads, $domain = false, $maxLag = INF ) {
270  $lags = $this->getLagTimes( $domain );
271 
272  # Unset excessively lagged servers
273  foreach ( $lags as $i => $lag ) {
274  if ( $i != 0 ) {
275  # How much lag this server nominally is allowed to have
276  $maxServerLag = isset( $this->mServers[$i]['max lag'] )
277  ? $this->mServers[$i]['max lag']
278  : self::MAX_LAG_DEFAULT; // default
279  # Constrain that futher by $maxLag argument
280  $maxServerLag = min( $maxServerLag, $maxLag );
281 
282  $host = $this->getServerName( $i );
283  if ( $lag === false && !is_infinite( $maxServerLag ) ) {
284  $this->replLogger->error(
285  "Server {host} is not replicating?", [ 'host' => $host ] );
286  unset( $loads[$i] );
287  } elseif ( $lag > $maxServerLag ) {
288  $this->replLogger->warning(
289  "Server {host} has {lag} seconds of lag (>= {maxlag})",
290  [ 'host' => $host, 'lag' => $lag, 'maxlag' => $maxServerLag ]
291  );
292  unset( $loads[$i] );
293  }
294  }
295  }
296 
297  # Find out if all the replica DBs with non-zero load are lagged
298  $sum = 0;
299  foreach ( $loads as $load ) {
300  $sum += $load;
301  }
302  if ( $sum == 0 ) {
303  # No appropriate DB servers except maybe the master and some replica DBs with zero load
304  # Do NOT use the master
305  # Instead, this function will return false, triggering read-only mode,
306  # and a lagged replica DB will be used instead.
307  return false;
308  }
309 
310  if ( count( $loads ) == 0 ) {
311  return false;
312  }
313 
314  # Return a random representative of the remainder
315  return ArrayUtils::pickRandom( $loads );
316  }
317 
318  public function getReaderIndex( $group = false, $domain = false ) {
319  if ( count( $this->mServers ) == 1 ) {
320  // Skip the load balancing if there's only one server
321  return $this->getWriterIndex();
322  } elseif ( $group === false && $this->mReadIndex >= 0 ) {
323  // Shortcut if the generic reader index was already cached
324  return $this->mReadIndex;
325  }
326 
327  if ( $group !== false ) {
328  // Use the server weight array for this load group
329  if ( isset( $this->mGroupLoads[$group] ) ) {
330  $loads = $this->mGroupLoads[$group];
331  } else {
332  // No loads for this group, return false and the caller can use some other group
333  $this->connLogger->info( __METHOD__ . ": no loads for group $group" );
334 
335  return false;
336  }
337  } else {
338  // Use the generic load group
339  $loads = $this->mLoads;
340  }
341 
342  // Scale the configured load ratios according to each server's load and state
343  $this->getLoadMonitor()->scaleLoads( $loads, $domain );
344 
345  // Pick a server to use, accounting for weights, load, lag, and mWaitForPos
346  list( $i, $laggedReplicaMode ) = $this->pickReaderIndex( $loads, $domain );
347  if ( $i === false ) {
348  // Replica DB connection unsuccessful
349  return false;
350  }
351 
352  if ( $this->mWaitForPos && $i != $this->getWriterIndex() ) {
353  // Before any data queries are run, wait for the server to catch up to the
354  // specified position. This is used to improve session consistency. Note that
355  // when LoadBalancer::waitFor() sets mWaitForPos, the waiting triggers here,
356  // so update laggedReplicaMode as needed for consistency.
357  if ( !$this->doWait( $i ) ) {
358  $laggedReplicaMode = true;
359  }
360  }
361 
362  if ( $this->mReadIndex <= 0 && $this->mLoads[$i] > 0 && $group === false ) {
363  // Cache the generic reader index for future ungrouped DB_REPLICA handles
364  $this->mReadIndex = $i;
365  // Record if the generic reader index is in "lagged replica DB" mode
366  if ( $laggedReplicaMode ) {
367  $this->laggedReplicaMode = true;
368  }
369  }
370 
371  $serverName = $this->getServerName( $i );
372  $this->connLogger->debug( __METHOD__ . ": using server $serverName for group '$group'" );
373 
374  return $i;
375  }
376 
382  private function pickReaderIndex( array $loads, $domain = false ) {
383  if ( !count( $loads ) ) {
384  throw new InvalidArgumentException( "Empty server array given to LoadBalancer" );
385  }
386 
388  $i = false;
390  $laggedReplicaMode = false;
391 
392  // Quickly look through the available servers for a server that meets criteria...
393  $currentLoads = $loads;
394  while ( count( $currentLoads ) ) {
395  if ( $this->mAllowLagged || $laggedReplicaMode ) {
396  $i = ArrayUtils::pickRandom( $currentLoads );
397  } else {
398  $i = false;
399  if ( $this->mWaitForPos && $this->mWaitForPos->asOfTime() ) {
400  // ChronologyProtecter sets mWaitForPos for session consistency.
401  // This triggers doWait() after connect, so it's especially good to
402  // avoid lagged servers so as to avoid excessive delay in that method.
403  $ago = microtime( true ) - $this->mWaitForPos->asOfTime();
404  // Aim for <= 1 second of waiting (being too picky can backfire)
405  $i = $this->getRandomNonLagged( $currentLoads, $domain, $ago + 1 );
406  }
407  if ( $i === false ) {
408  // Any server with less lag than it's 'max lag' param is preferable
409  $i = $this->getRandomNonLagged( $currentLoads, $domain );
410  }
411  if ( $i === false && count( $currentLoads ) != 0 ) {
412  // All replica DBs lagged. Switch to read-only mode
413  $this->replLogger->error( "All replica DBs lagged. Switch to read-only mode" );
414  $i = ArrayUtils::pickRandom( $currentLoads );
415  $laggedReplicaMode = true;
416  }
417  }
418 
419  if ( $i === false ) {
420  // pickRandom() returned false.
421  // This is permanent and means the configuration or the load monitor
422  // wants us to return false.
423  $this->connLogger->debug( __METHOD__ . ": pickRandom() returned false" );
424 
425  return [ false, false ];
426  }
427 
428  $serverName = $this->getServerName( $i );
429  $this->connLogger->debug( __METHOD__ . ": Using reader #$i: $serverName..." );
430 
431  $conn = $this->openConnection( $i, $domain );
432  if ( !$conn ) {
433  $this->connLogger->warning( __METHOD__ . ": Failed connecting to $i/$domain" );
434  unset( $currentLoads[$i] ); // avoid this server next iteration
435  $i = false;
436  continue;
437  }
438 
439  // Decrement reference counter, we are finished with this connection.
440  // It will be incremented for the caller later.
441  if ( $domain !== false ) {
442  $this->reuseConnection( $conn );
443  }
444 
445  // Return this server
446  break;
447  }
448 
449  // If all servers were down, quit now
450  if ( !count( $currentLoads ) ) {
451  $this->connLogger->error( "All servers down" );
452  }
453 
454  return [ $i, $laggedReplicaMode ];
455  }
456 
457  public function waitFor( $pos ) {
458  $oldPos = $this->mWaitForPos;
459  try {
460  $this->mWaitForPos = $pos;
461  // If a generic reader connection was already established, then wait now
462  $i = $this->mReadIndex;
463  if ( $i > 0 ) {
464  if ( !$this->doWait( $i ) ) {
465  $this->laggedReplicaMode = true;
466  }
467  }
468  } finally {
469  // Restore the older position if it was higher since this is used for lag-protection
470  $this->setWaitForPositionIfHigher( $oldPos );
471  }
472  }
473 
474  public function waitForOne( $pos, $timeout = null ) {
475  $oldPos = $this->mWaitForPos;
476  try {
477  $this->mWaitForPos = $pos;
478 
479  $i = $this->mReadIndex;
480  if ( $i <= 0 ) {
481  // Pick a generic replica DB if there isn't one yet
482  $readLoads = $this->mLoads;
483  unset( $readLoads[$this->getWriterIndex()] ); // replica DBs only
484  $readLoads = array_filter( $readLoads ); // with non-zero load
485  $i = ArrayUtils::pickRandom( $readLoads );
486  }
487 
488  if ( $i > 0 ) {
489  $ok = $this->doWait( $i, true, $timeout );
490  } else {
491  $ok = true; // no applicable loads
492  }
493  } finally {
494  # Restore the old position, as this is not used for lag-protection but for throttling
495  $this->mWaitForPos = $oldPos;
496  }
497 
498  return $ok;
499  }
500 
501  public function waitForAll( $pos, $timeout = null ) {
502  $oldPos = $this->mWaitForPos;
503  try {
504  $this->mWaitForPos = $pos;
505  $serverCount = count( $this->mServers );
506 
507  $ok = true;
508  for ( $i = 1; $i < $serverCount; $i++ ) {
509  if ( $this->mLoads[$i] > 0 ) {
510  $ok = $this->doWait( $i, true, $timeout ) && $ok;
511  }
512  }
513  } finally {
514  # Restore the old position, as this is not used for lag-protection but for throttling
515  $this->mWaitForPos = $oldPos;
516  }
517 
518  return $ok;
519  }
520 
524  private function setWaitForPositionIfHigher( $pos ) {
525  if ( !$pos ) {
526  return;
527  }
528 
529  if ( !$this->mWaitForPos || $pos->hasReached( $this->mWaitForPos ) ) {
530  $this->mWaitForPos = $pos;
531  }
532  }
533 
538  public function getAnyOpenConnection( $i ) {
539  foreach ( $this->mConns as $connsByServer ) {
540  if ( !empty( $connsByServer[$i] ) ) {
542  $serverConns = $connsByServer[$i];
543 
544  return reset( $serverConns );
545  }
546  }
547 
548  return false;
549  }
550 
558  protected function doWait( $index, $open = false, $timeout = null ) {
559  $close = false; // close the connection afterwards
560 
561  // Check if we already know that the DB has reached this point
562  $server = $this->getServerName( $index );
563  $key = $this->srvCache->makeGlobalKey( __CLASS__, 'last-known-pos', $server, 'v1' );
565  $knownReachedPos = $this->srvCache->get( $key );
566  if (
567  $knownReachedPos instanceof DBMasterPos &&
568  $knownReachedPos->hasReached( $this->mWaitForPos )
569  ) {
570  $this->replLogger->debug( __METHOD__ .
571  ": replica DB $server known to be caught up (pos >= $knownReachedPos)." );
572  return true;
573  }
574 
575  // Find a connection to wait on, creating one if needed and allowed
576  $conn = $this->getAnyOpenConnection( $index );
577  if ( !$conn ) {
578  if ( !$open ) {
579  $this->replLogger->debug( __METHOD__ . ": no connection open for $server" );
580 
581  return false;
582  } else {
583  $conn = $this->openConnection( $index, self::DOMAIN_ANY );
584  if ( !$conn ) {
585  $this->replLogger->warning( __METHOD__ . ": failed to connect to $server" );
586 
587  return false;
588  }
589  // Avoid connection spam in waitForAll() when connections
590  // are made just for the sake of doing this lag check.
591  $close = true;
592  }
593  }
594 
595  $this->replLogger->info( __METHOD__ . ": Waiting for replica DB $server to catch up..." );
596  $timeout = $timeout ?: $this->mWaitTimeout;
597  $result = $conn->masterPosWait( $this->mWaitForPos, $timeout );
598 
599  if ( $result == -1 || is_null( $result ) ) {
600  // Timed out waiting for replica DB, use master instead
601  $this->replLogger->warning(
602  __METHOD__ . ": Timed out waiting on {host} pos {$this->mWaitForPos}",
603  [ 'host' => $server ]
604  );
605  $ok = false;
606  } else {
607  $this->replLogger->info( __METHOD__ . ": Done" );
608  $ok = true;
609  // Remember that the DB reached this point
610  $this->srvCache->set( $key, $this->mWaitForPos, BagOStuff::TTL_DAY );
611  }
612 
613  if ( $close ) {
614  $this->closeConnection( $conn );
615  }
616 
617  return $ok;
618  }
619 
620  public function getConnection( $i, $groups = [], $domain = false, $flags = 0 ) {
621  if ( $i === null || $i === false ) {
622  throw new InvalidArgumentException( 'Attempt to call ' . __METHOD__ .
623  ' with invalid server index' );
624  }
625 
626  if ( $this->localDomain->equals( $domain ) || $domain === $this->localDomainIdAlias ) {
627  $domain = false; // local connection requested
628  }
629 
630  $groups = ( $groups === false || $groups === [] )
631  ? [ false ] // check one "group": the generic pool
632  : (array)$groups;
633 
634  $masterOnly = ( $i == self::DB_MASTER || $i == $this->getWriterIndex() );
635  $oldConnsOpened = $this->connsOpened; // connections open now
636 
637  if ( $i == self::DB_MASTER ) {
638  $i = $this->getWriterIndex();
639  } else {
640  # Try to find an available server in any the query groups (in order)
641  foreach ( $groups as $group ) {
642  $groupIndex = $this->getReaderIndex( $group, $domain );
643  if ( $groupIndex !== false ) {
644  $i = $groupIndex;
645  break;
646  }
647  }
648  }
649 
650  # Operation-based index
651  if ( $i == self::DB_REPLICA ) {
652  $this->mLastError = 'Unknown error'; // reset error string
653  # Try the general server pool if $groups are unavailable.
654  $i = ( $groups === [ false ] )
655  ? false // don't bother with this if that is what was tried above
656  : $this->getReaderIndex( false, $domain );
657  # Couldn't find a working server in getReaderIndex()?
658  if ( $i === false ) {
659  $this->mLastError = 'No working replica DB server: ' . $this->mLastError;
660  // Throw an exception
661  $this->reportConnectionError();
662  return null; // not reached
663  }
664  }
665 
666  # Now we have an explicit index into the servers array
667  $conn = $this->openConnection( $i, $domain, $flags );
668  if ( !$conn ) {
669  // Throw an exception
670  $this->reportConnectionError();
671  return null; // not reached
672  }
673 
674  # Profile any new connections that happen
675  if ( $this->connsOpened > $oldConnsOpened ) {
676  $host = $conn->getServer();
677  $dbname = $conn->getDBname();
678  $this->trxProfiler->recordConnection( $host, $dbname, $masterOnly );
679  }
680 
681  if ( $masterOnly ) {
682  # Make master-requested DB handles inherit any read-only mode setting
683  $conn->setLBInfo( 'readOnlyReason', $this->getReadOnlyReason( $domain, $conn ) );
684  }
685 
686  return $conn;
687  }
688 
689  public function reuseConnection( $conn ) {
690  $serverIndex = $conn->getLBInfo( 'serverIndex' );
691  $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
692  if ( $serverIndex === null || $refCount === null ) {
703  return;
704  } elseif ( $conn instanceof DBConnRef ) {
705  // DBConnRef already handles calling reuseConnection() and only passes the live
706  // Database instance to this method. Any caller passing in a DBConnRef is broken.
707  $this->connLogger->error( __METHOD__ . ": got DBConnRef instance.\n" .
708  ( new RuntimeException() )->getTraceAsString() );
709 
710  return;
711  }
712 
713  if ( $this->disabled ) {
714  return; // DBConnRef handle probably survived longer than the LoadBalancer
715  }
716 
717  if ( $conn->getLBInfo( 'autoCommitOnly' ) ) {
718  $connFreeKey = self::KEY_FOREIGN_FREE_NOROUND;
719  $connInUseKey = self::KEY_FOREIGN_INUSE_NOROUND;
720  } else {
721  $connFreeKey = self::KEY_FOREIGN_FREE;
722  $connInUseKey = self::KEY_FOREIGN_INUSE;
723  }
724 
725  $domain = $conn->getDomainID();
726  if ( !isset( $this->mConns[$connInUseKey][$serverIndex][$domain] ) ) {
727  throw new InvalidArgumentException( __METHOD__ .
728  ": connection $serverIndex/$domain not found; it may have already been freed." );
729  } elseif ( $this->mConns[$connInUseKey][$serverIndex][$domain] !== $conn ) {
730  throw new InvalidArgumentException( __METHOD__ .
731  ": connection $serverIndex/$domain mismatched; it may have already been freed." );
732  }
733 
734  $conn->setLBInfo( 'foreignPoolRefCount', --$refCount );
735  if ( $refCount <= 0 ) {
736  $this->mConns[$connFreeKey][$serverIndex][$domain] = $conn;
737  unset( $this->mConns[$connInUseKey][$serverIndex][$domain] );
738  if ( !$this->mConns[$connInUseKey][$serverIndex] ) {
739  unset( $this->mConns[$connInUseKey][$serverIndex] ); // clean up
740  }
741  $this->connLogger->debug( __METHOD__ . ": freed connection $serverIndex/$domain" );
742  } else {
743  $this->connLogger->debug( __METHOD__ .
744  ": reference count for $serverIndex/$domain reduced to $refCount" );
745  }
746  }
747 
748  public function getConnectionRef( $db, $groups = [], $domain = false, $flags = 0 ) {
749  $domain = ( $domain !== false ) ? $domain : $this->localDomain;
750 
751  return new DBConnRef( $this, $this->getConnection( $db, $groups, $domain, $flags ) );
752  }
753 
754  public function getLazyConnectionRef( $db, $groups = [], $domain = false, $flags = 0 ) {
755  $domain = ( $domain !== false ) ? $domain : $this->localDomain;
756 
757  return new DBConnRef( $this, [ $db, $groups, $domain, $flags ] );
758  }
759 
760  public function getMaintenanceConnectionRef( $db, $groups = [], $domain = false, $flags = 0 ) {
761  $domain = ( $domain !== false ) ? $domain : $this->localDomain;
762 
763  return new MaintainableDBConnRef(
764  $this, $this->getConnection( $db, $groups, $domain, $flags ) );
765  }
766 
767  public function openConnection( $i, $domain = false, $flags = 0 ) {
768  if ( $this->localDomain->equals( $domain ) || $domain === $this->localDomainIdAlias ) {
769  $domain = false; // local connection requested
770  }
771 
772  if ( !$this->chronProtInitialized && $this->chronProt ) {
773  $this->connLogger->debug( __METHOD__ . ': calling initLB() before first connection.' );
774  // Load CP positions before connecting so that doWait() triggers later if needed
775  $this->chronProtInitialized = true;
776  $this->chronProt->initLB( $this );
777  }
778 
779  // Check if an auto-commit connection is being requested. If so, it will not reuse the
780  // main set of DB connections but rather its own pool since:
781  // a) those are usually set to implicitly use transaction rounds via DBO_TRX
782  // b) those must support the use of explicit transaction rounds via beginMasterChanges()
783  $autoCommit = ( ( $flags & self::CONN_TRX_AUTO ) == self::CONN_TRX_AUTO );
784 
785  if ( $domain !== false ) {
786  // Connection is to a foreign domain
787  $conn = $this->openForeignConnection( $i, $domain, $flags );
788  } else {
789  // Connection is to the local domain
790  $connKey = $autoCommit ? self::KEY_LOCAL_NOROUND : self::KEY_LOCAL;
791  if ( isset( $this->mConns[$connKey][$i][0] ) ) {
792  $conn = $this->mConns[$connKey][$i][0];
793  } else {
794  if ( !isset( $this->mServers[$i] ) || !is_array( $this->mServers[$i] ) ) {
795  throw new InvalidArgumentException( "No server with index '$i'." );
796  }
797  // Open a new connection
798  $server = $this->mServers[$i];
799  $server['serverIndex'] = $i;
800  $server['autoCommitOnly'] = $autoCommit;
801  $conn = $this->reallyOpenConnection( $server, false );
802  $host = $this->getServerName( $i );
803  if ( $conn->isOpen() ) {
804  $this->connLogger->debug( "Connected to database $i at '$host'." );
805  $this->mConns[$connKey][$i][0] = $conn;
806  } else {
807  $this->connLogger->warning( "Failed to connect to database $i at '$host'." );
808  $this->errorConnection = $conn;
809  $conn = false;
810  }
811  }
812  }
813 
814  if ( $conn instanceof IDatabase && !$conn->isOpen() ) {
815  // Connection was made but later unrecoverably lost for some reason.
816  // Do not return a handle that will just throw exceptions on use,
817  // but let the calling code (e.g. getReaderIndex) try another server.
818  // See DatabaseMyslBase::ping() for how this can happen.
819  $this->errorConnection = $conn;
820  $conn = false;
821  }
822 
823  if ( $autoCommit && $conn instanceof IDatabase ) {
824  $conn->clearFlag( $conn::DBO_TRX ); // auto-commit mode
825  }
826 
827  return $conn;
828  }
829 
851  private function openForeignConnection( $i, $domain, $flags = 0 ) {
852  $domainInstance = DatabaseDomain::newFromId( $domain );
853  $dbName = $domainInstance->getDatabase();
854  $prefix = $domainInstance->getTablePrefix();
855  $autoCommit = ( ( $flags & self::CONN_TRX_AUTO ) == self::CONN_TRX_AUTO );
856 
857  if ( $autoCommit ) {
858  $connFreeKey = self::KEY_FOREIGN_FREE_NOROUND;
859  $connInUseKey = self::KEY_FOREIGN_INUSE_NOROUND;
860  } else {
861  $connFreeKey = self::KEY_FOREIGN_FREE;
862  $connInUseKey = self::KEY_FOREIGN_INUSE;
863  }
864 
865  if ( isset( $this->mConns[$connInUseKey][$i][$domain] ) ) {
866  // Reuse an in-use connection for the same domain
867  $conn = $this->mConns[$connInUseKey][$i][$domain];
868  $this->connLogger->debug( __METHOD__ . ": reusing connection $i/$domain" );
869  } elseif ( isset( $this->mConns[$connFreeKey][$i][$domain] ) ) {
870  // Reuse a free connection for the same domain
871  $conn = $this->mConns[$connFreeKey][$i][$domain];
872  unset( $this->mConns[$connFreeKey][$i][$domain] );
873  $this->mConns[$connInUseKey][$i][$domain] = $conn;
874  $this->connLogger->debug( __METHOD__ . ": reusing free connection $i/$domain" );
875  } elseif ( !empty( $this->mConns[$connFreeKey][$i] ) ) {
876  // Reuse a free connection from another domain
877  $conn = reset( $this->mConns[$connFreeKey][$i] );
878  $oldDomain = key( $this->mConns[$connFreeKey][$i] );
879  // The empty string as a DB name means "don't care".
880  // DatabaseMysqlBase::open() already handle this on connection.
881  if ( strlen( $dbName ) && !$conn->selectDB( $dbName ) ) {
882  $this->mLastError = "Error selecting database '$dbName' on server " .
883  $conn->getServer() . " from client host {$this->host}";
884  $this->errorConnection = $conn;
885  $conn = false;
886  } else {
887  $conn->tablePrefix( $prefix );
888  unset( $this->mConns[$connFreeKey][$i][$oldDomain] );
889  $this->mConns[$connInUseKey][$i][$domain] = $conn;
890  $this->connLogger->debug( __METHOD__ .
891  ": reusing free connection from $oldDomain for $domain" );
892  }
893  } else {
894  if ( !isset( $this->mServers[$i] ) || !is_array( $this->mServers[$i] ) ) {
895  throw new InvalidArgumentException( "No server with index '$i'." );
896  }
897  // Open a new connection
898  $server = $this->mServers[$i];
899  $server['serverIndex'] = $i;
900  $server['foreignPoolRefCount'] = 0;
901  $server['foreign'] = true;
902  $server['autoCommitOnly'] = $autoCommit;
903  $conn = $this->reallyOpenConnection( $server, $dbName );
904  if ( !$conn->isOpen() ) {
905  $this->connLogger->warning( __METHOD__ . ": connection error for $i/$domain" );
906  $this->errorConnection = $conn;
907  $conn = false;
908  } else {
909  $conn->tablePrefix( $prefix );
910  $this->mConns[$connInUseKey][$i][$domain] = $conn;
911  $this->connLogger->debug( __METHOD__ . ": opened new connection for $i/$domain" );
912  }
913  }
914 
915  // Increment reference count
916  if ( $conn instanceof IDatabase ) {
917  $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
918  $conn->setLBInfo( 'foreignPoolRefCount', $refCount + 1 );
919  }
920 
921  return $conn;
922  }
923 
931  private function isOpen( $index ) {
932  if ( !is_integer( $index ) ) {
933  return false;
934  }
935 
936  return (bool)$this->getAnyOpenConnection( $index );
937  }
938 
950  protected function reallyOpenConnection( array $server, $dbNameOverride = false ) {
951  if ( $this->disabled ) {
952  throw new DBAccessError();
953  }
954 
955  if ( $dbNameOverride !== false ) {
956  $server['dbname'] = $dbNameOverride;
957  }
958 
959  // Let the handle know what the cluster master is (e.g. "db1052")
960  $masterName = $this->getServerName( $this->getWriterIndex() );
961  $server['clusterMasterHost'] = $masterName;
962 
963  // Log when many connection are made on requests
964  if ( ++$this->connsOpened >= self::CONN_HELD_WARN_THRESHOLD ) {
965  $this->perfLogger->warning( __METHOD__ . ": " .
966  "{$this->connsOpened}+ connections made (master=$masterName)" );
967  }
968 
969  $server['srvCache'] = $this->srvCache;
970  // Set loggers and profilers
971  $server['connLogger'] = $this->connLogger;
972  $server['queryLogger'] = $this->queryLogger;
973  $server['errorLogger'] = $this->errorLogger;
974  $server['profiler'] = $this->profiler;
975  $server['trxProfiler'] = $this->trxProfiler;
976  // Use the same agent and PHP mode for all DB handles
977  $server['cliMode'] = $this->cliMode;
978  $server['agent'] = $this->agent;
979  // Use DBO_DEFAULT flags by default for LoadBalancer managed databases. Assume that the
980  // application calls LoadBalancer::commitMasterChanges() before the PHP script completes.
981  $server['flags'] = isset( $server['flags'] ) ? $server['flags'] : IDatabase::DBO_DEFAULT;
982 
983  // Create a live connection object
984  try {
985  $db = Database::factory( $server['type'], $server );
986  } catch ( DBConnectionError $e ) {
987  // FIXME: This is probably the ugliest thing I have ever done to
988  // PHP. I'm half-expecting it to segfault, just out of disgust. -- TS
989  $db = $e->db;
990  }
991 
992  $db->setLBInfo( $server );
993  $db->setLazyMasterHandle(
994  $this->getLazyConnectionRef( self::DB_MASTER, [], $db->getDomainID() )
995  );
996  $db->setTableAliases( $this->tableAliases );
997 
998  if ( $server['serverIndex'] === $this->getWriterIndex() ) {
999  if ( $this->trxRoundId !== false ) {
1000  $this->applyTransactionRoundFlags( $db );
1001  }
1002  foreach ( $this->trxRecurringCallbacks as $name => $callback ) {
1003  $db->setTransactionListener( $name, $callback );
1004  }
1005  }
1006 
1007  return $db;
1008  }
1009 
1013  private function reportConnectionError() {
1014  $conn = $this->errorConnection; // the connection which caused the error
1015  $context = [
1016  'method' => __METHOD__,
1017  'last_error' => $this->mLastError,
1018  ];
1019 
1020  if ( $conn instanceof IDatabase ) {
1021  $context['db_server'] = $conn->getServer();
1022  $this->connLogger->warning(
1023  "Connection error: {last_error} ({db_server})",
1024  $context
1025  );
1026 
1027  // throws DBConnectionError
1028  $conn->reportConnectionError( "{$this->mLastError} ({$context['db_server']})" );
1029  } else {
1030  // No last connection, probably due to all servers being too busy
1031  $this->connLogger->error(
1032  "LB failure with no last connection. Connection error: {last_error}",
1033  $context
1034  );
1035 
1036  // If all servers were busy, mLastError will contain something sensible
1037  throw new DBConnectionError( null, $this->mLastError );
1038  }
1039  }
1040 
1041  public function getWriterIndex() {
1042  return 0;
1043  }
1044 
1045  public function haveIndex( $i ) {
1046  return array_key_exists( $i, $this->mServers );
1047  }
1048 
1049  public function isNonZeroLoad( $i ) {
1050  return array_key_exists( $i, $this->mServers ) && $this->mLoads[$i] != 0;
1051  }
1052 
1053  public function getServerCount() {
1054  return count( $this->mServers );
1055  }
1056 
1057  public function getServerName( $i ) {
1058  if ( isset( $this->mServers[$i]['hostName'] ) ) {
1059  $name = $this->mServers[$i]['hostName'];
1060  } elseif ( isset( $this->mServers[$i]['host'] ) ) {
1061  $name = $this->mServers[$i]['host'];
1062  } else {
1063  $name = '';
1064  }
1065 
1066  return ( $name != '' ) ? $name : 'localhost';
1067  }
1068 
1069  public function getServerType( $i ) {
1070  return isset( $this->mServers[$i]['type'] ) ? $this->mServers[$i]['type'] : 'unknown';
1071  }
1072 
1076  public function getServerInfo( $i ) {
1077  wfDeprecated( __METHOD__, '1.30' );
1078  if ( isset( $this->mServers[$i] ) ) {
1079  return $this->mServers[$i];
1080  } else {
1081  return false;
1082  }
1083  }
1084 
1088  public function setServerInfo( $i, array $serverInfo ) {
1089  wfDeprecated( __METHOD__, '1.30' );
1090  $this->mServers[$i] = $serverInfo;
1091  }
1092 
1093  public function getMasterPos() {
1094  # If this entire request was served from a replica DB without opening a connection to the
1095  # master (however unlikely that may be), then we can fetch the position from the replica DB.
1096  $masterConn = $this->getAnyOpenConnection( $this->getWriterIndex() );
1097  if ( !$masterConn ) {
1098  $serverCount = count( $this->mServers );
1099  for ( $i = 1; $i < $serverCount; $i++ ) {
1100  $conn = $this->getAnyOpenConnection( $i );
1101  if ( $conn ) {
1102  return $conn->getReplicaPos();
1103  }
1104  }
1105  } else {
1106  return $masterConn->getMasterPos();
1107  }
1108 
1109  return false;
1110  }
1111 
1112  public function disable() {
1113  $this->closeAll();
1114  $this->disabled = true;
1115  }
1116 
1117  public function closeAll() {
1118  $this->forEachOpenConnection( function ( IDatabase $conn ) {
1119  $host = $conn->getServer();
1120  $this->connLogger->debug( "Closing connection to database '$host'." );
1121  $conn->close();
1122  } );
1123 
1124  $this->mConns = [
1125  self::KEY_LOCAL => [],
1126  self::KEY_FOREIGN_INUSE => [],
1127  self::KEY_FOREIGN_FREE => [],
1128  self::KEY_LOCAL_NOROUND => [],
1129  self::KEY_FOREIGN_INUSE_NOROUND => [],
1130  self::KEY_FOREIGN_FREE_NOROUND => []
1131  ];
1132  $this->connsOpened = 0;
1133  }
1134 
1135  public function closeConnection( IDatabase $conn ) {
1136  $serverIndex = $conn->getLBInfo( 'serverIndex' ); // second index level of mConns
1137  foreach ( $this->mConns as $type => $connsByServer ) {
1138  if ( !isset( $connsByServer[$serverIndex] ) ) {
1139  continue;
1140  }
1141 
1142  foreach ( $connsByServer[$serverIndex] as $i => $trackedConn ) {
1143  if ( $conn === $trackedConn ) {
1144  $host = $this->getServerName( $i );
1145  $this->connLogger->debug( "Closing connection to database $i at '$host'." );
1146  unset( $this->mConns[$type][$serverIndex][$i] );
1148  break 2;
1149  }
1150  }
1151  }
1152 
1153  $conn->close();
1154  }
1155 
1156  public function commitAll( $fname = __METHOD__ ) {
1157  $failures = [];
1158 
1159  $restore = ( $this->trxRoundId !== false );
1160  $this->trxRoundId = false;
1161  $this->forEachOpenConnection(
1162  function ( IDatabase $conn ) use ( $fname, $restore, &$failures ) {
1163  try {
1164  $conn->commit( $fname, $conn::FLUSHING_ALL_PEERS );
1165  } catch ( DBError $e ) {
1166  call_user_func( $this->errorLogger, $e );
1167  $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
1168  }
1169  if ( $restore && $conn->getLBInfo( 'master' ) ) {
1170  $this->undoTransactionRoundFlags( $conn );
1171  }
1172  }
1173  );
1174 
1175  if ( $failures ) {
1176  throw new DBExpectedError(
1177  null,
1178  "Commit failed on server(s) " . implode( "\n", array_unique( $failures ) )
1179  );
1180  }
1181  }
1182 
1183  public function finalizeMasterChanges() {
1184  $this->forEachOpenMasterConnection( function ( Database $conn ) {
1185  // Any error should cause all DB transactions to be rolled back together
1186  $conn->setTrxEndCallbackSuppression( false );
1188  // Defer post-commit callbacks until COMMIT finishes for all DBs
1189  $conn->setTrxEndCallbackSuppression( true );
1190  } );
1191  }
1192 
1193  public function approveMasterChanges( array $options ) {
1194  $limit = isset( $options['maxWriteDuration'] ) ? $options['maxWriteDuration'] : 0;
1195  $this->forEachOpenMasterConnection( function ( IDatabase $conn ) use ( $limit ) {
1196  // If atomic sections or explicit transactions are still open, some caller must have
1197  // caught an exception but failed to properly rollback any changes. Detect that and
1198  // throw and error (causing rollback).
1199  if ( $conn->explicitTrxActive() ) {
1200  throw new DBTransactionError(
1201  $conn,
1202  "Explicit transaction still active. A caller may have caught an error."
1203  );
1204  }
1205  // Assert that the time to replicate the transaction will be sane.
1206  // If this fails, then all DB transactions will be rollback back together.
1207  $time = $conn->pendingWriteQueryDuration( $conn::ESTIMATE_DB_APPLY );
1208  if ( $limit > 0 && $time > $limit ) {
1209  throw new DBTransactionSizeError(
1210  $conn,
1211  "Transaction spent $time second(s) in writes, exceeding the limit of $limit.",
1212  [ $time, $limit ]
1213  );
1214  }
1215  // If a connection sits idle while slow queries execute on another, that connection
1216  // may end up dropped before the commit round is reached. Ping servers to detect this.
1217  if ( $conn->writesOrCallbacksPending() && !$conn->ping() ) {
1218  throw new DBTransactionError(
1219  $conn,
1220  "A connection to the {$conn->getDBname()} database was lost before commit."
1221  );
1222  }
1223  } );
1224  }
1225 
1226  public function beginMasterChanges( $fname = __METHOD__ ) {
1227  if ( $this->trxRoundId !== false ) {
1228  throw new DBTransactionError(
1229  null,
1230  "$fname: Transaction round '{$this->trxRoundId}' already started."
1231  );
1232  }
1233  $this->trxRoundId = $fname;
1234 
1235  $failures = [];
1237  function ( Database $conn ) use ( $fname, &$failures ) {
1238  $conn->setTrxEndCallbackSuppression( true );
1239  try {
1240  $conn->flushSnapshot( $fname );
1241  } catch ( DBError $e ) {
1242  call_user_func( $this->errorLogger, $e );
1243  $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
1244  }
1245  $conn->setTrxEndCallbackSuppression( false );
1246  $this->applyTransactionRoundFlags( $conn );
1247  }
1248  );
1249 
1250  if ( $failures ) {
1251  throw new DBExpectedError(
1252  null,
1253  "$fname: Flush failed on server(s) " . implode( "\n", array_unique( $failures ) )
1254  );
1255  }
1256  }
1257 
1258  public function commitMasterChanges( $fname = __METHOD__ ) {
1259  $failures = [];
1260 
1262  $scope = $this->getScopedPHPBehaviorForCommit(); // try to ignore client aborts
1263 
1264  $restore = ( $this->trxRoundId !== false );
1265  $this->trxRoundId = false;
1267  function ( IDatabase $conn ) use ( $fname, $restore, &$failures ) {
1268  try {
1269  if ( $conn->writesOrCallbacksPending() ) {
1270  $conn->commit( $fname, $conn::FLUSHING_ALL_PEERS );
1271  } elseif ( $restore ) {
1272  $conn->flushSnapshot( $fname );
1273  }
1274  } catch ( DBError $e ) {
1275  call_user_func( $this->errorLogger, $e );
1276  $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
1277  }
1278  if ( $restore ) {
1279  $this->undoTransactionRoundFlags( $conn );
1280  }
1281  }
1282  );
1283 
1284  if ( $failures ) {
1285  throw new DBExpectedError(
1286  null,
1287  "$fname: Commit failed on server(s) " . implode( "\n", array_unique( $failures ) )
1288  );
1289  }
1290  }
1291 
1292  public function runMasterPostTrxCallbacks( $type ) {
1293  $e = null; // first exception
1294  $this->forEachOpenMasterConnection( function ( Database $conn ) use ( $type, &$e ) {
1295  $conn->setTrxEndCallbackSuppression( false );
1296  if ( $conn->writesOrCallbacksPending() ) {
1297  // This happens if onTransactionIdle() callbacks leave callbacks on *another* DB
1298  // (which finished its callbacks already). Warn and recover in this case. Let the
1299  // callbacks run in the final commitMasterChanges() in LBFactory::shutdown().
1300  $this->queryLogger->info( __METHOD__ . ": found writes/callbacks pending." );
1301  return;
1302  } elseif ( $conn->trxLevel() ) {
1303  // This happens for single-DB setups where DB_REPLICA uses the master DB,
1304  // thus leaving an implicit read-only transaction open at this point. It
1305  // also happens if onTransactionIdle() callbacks leave implicit transactions
1306  // open on *other* DBs (which is slightly improper). Let these COMMIT on the
1307  // next call to commitMasterChanges(), possibly in LBFactory::shutdown().
1308  return;
1309  }
1310  try {
1312  } catch ( Exception $ex ) {
1313  $e = $e ?: $ex;
1314  }
1315  try {
1317  } catch ( Exception $ex ) {
1318  $e = $e ?: $ex;
1319  }
1320  } );
1321 
1322  return $e;
1323  }
1324 
1325  public function rollbackMasterChanges( $fname = __METHOD__ ) {
1326  $restore = ( $this->trxRoundId !== false );
1327  $this->trxRoundId = false;
1329  function ( IDatabase $conn ) use ( $fname, $restore ) {
1330  if ( $conn->writesOrCallbacksPending() ) {
1331  $conn->rollback( $fname, $conn::FLUSHING_ALL_PEERS );
1332  }
1333  if ( $restore ) {
1334  $this->undoTransactionRoundFlags( $conn );
1335  }
1336  }
1337  );
1338  }
1339 
1341  $this->forEachOpenMasterConnection( function ( Database $conn ) {
1342  $conn->setTrxEndCallbackSuppression( true );
1343  } );
1344  }
1345 
1349  private function applyTransactionRoundFlags( IDatabase $conn ) {
1350  if ( $conn->getLBInfo( 'autoCommitOnly' ) ) {
1351  return; // transaction rounds do not apply to these connections
1352  }
1353 
1354  if ( $conn->getFlag( $conn::DBO_DEFAULT ) ) {
1355  // DBO_TRX is controlled entirely by CLI mode presence with DBO_DEFAULT.
1356  // Force DBO_TRX even in CLI mode since a commit round is expected soon.
1357  $conn->setFlag( $conn::DBO_TRX, $conn::REMEMBER_PRIOR );
1358  // If config has explicitly requested DBO_TRX be either on or off by not
1359  // setting DBO_DEFAULT, then respect that. Forcing no transactions is useful
1360  // for things like blob stores (ExternalStore) which want auto-commit mode.
1361  }
1362  }
1363 
1367  private function undoTransactionRoundFlags( IDatabase $conn ) {
1368  if ( $conn->getLBInfo( 'autoCommitOnly' ) ) {
1369  return; // transaction rounds do not apply to these connections
1370  }
1371 
1372  if ( $conn->getFlag( $conn::DBO_DEFAULT ) ) {
1373  $conn->restoreFlags( $conn::RESTORE_PRIOR );
1374  }
1375  }
1376 
1377  public function flushReplicaSnapshots( $fname = __METHOD__ ) {
1378  $this->forEachOpenReplicaConnection( function ( IDatabase $conn ) {
1379  $conn->flushSnapshot( __METHOD__ );
1380  } );
1381  }
1382 
1383  public function hasMasterConnection() {
1384  return $this->isOpen( $this->getWriterIndex() );
1385  }
1386 
1387  public function hasMasterChanges() {
1388  $pending = 0;
1389  $this->forEachOpenMasterConnection( function ( IDatabase $conn ) use ( &$pending ) {
1390  $pending |= $conn->writesOrCallbacksPending();
1391  } );
1392 
1393  return (bool)$pending;
1394  }
1395 
1396  public function lastMasterChangeTimestamp() {
1397  $lastTime = false;
1398  $this->forEachOpenMasterConnection( function ( IDatabase $conn ) use ( &$lastTime ) {
1399  $lastTime = max( $lastTime, $conn->lastDoneWrites() );
1400  } );
1401 
1402  return $lastTime;
1403  }
1404 
1405  public function hasOrMadeRecentMasterChanges( $age = null ) {
1406  $age = ( $age === null ) ? $this->mWaitTimeout : $age;
1407 
1408  return ( $this->hasMasterChanges()
1409  || $this->lastMasterChangeTimestamp() > microtime( true ) - $age );
1410  }
1411 
1412  public function pendingMasterChangeCallers() {
1413  $fnames = [];
1414  $this->forEachOpenMasterConnection( function ( IDatabase $conn ) use ( &$fnames ) {
1415  $fnames = array_merge( $fnames, $conn->pendingWriteCallers() );
1416  } );
1417 
1418  return $fnames;
1419  }
1420 
1421  public function getLaggedReplicaMode( $domain = false ) {
1422  // No-op if there is only one DB (also avoids recursion)
1423  if ( !$this->laggedReplicaMode && $this->getServerCount() > 1 ) {
1424  try {
1425  // See if laggedReplicaMode gets set
1426  $conn = $this->getConnection( self::DB_REPLICA, false, $domain );
1427  $this->reuseConnection( $conn );
1428  } catch ( DBConnectionError $e ) {
1429  // Avoid expensive re-connect attempts and failures
1430  $this->allReplicasDownMode = true;
1431  $this->laggedReplicaMode = true;
1432  }
1433  }
1434 
1435  return $this->laggedReplicaMode;
1436  }
1437 
1443  public function getLaggedSlaveMode( $domain = false ) {
1444  return $this->getLaggedReplicaMode( $domain );
1445  }
1446 
1447  public function laggedReplicaUsed() {
1448  return $this->laggedReplicaMode;
1449  }
1450 
1456  public function laggedSlaveUsed() {
1457  return $this->laggedReplicaUsed();
1458  }
1459 
1460  public function getReadOnlyReason( $domain = false, IDatabase $conn = null ) {
1461  if ( $this->readOnlyReason !== false ) {
1462  return $this->readOnlyReason;
1463  } elseif ( $this->getLaggedReplicaMode( $domain ) ) {
1464  if ( $this->allReplicasDownMode ) {
1465  return 'The database has been automatically locked ' .
1466  'until the replica database servers become available';
1467  } else {
1468  return 'The database has been automatically locked ' .
1469  'while the replica database servers catch up to the master.';
1470  }
1471  } elseif ( $this->masterRunningReadOnly( $domain, $conn ) ) {
1472  return 'The database master is running in read-only mode.';
1473  }
1474 
1475  return false;
1476  }
1477 
1483  private function masterRunningReadOnly( $domain, IDatabase $conn = null ) {
1485  $masterServer = $this->getServerName( $this->getWriterIndex() );
1486 
1487  return (bool)$cache->getWithSetCallback(
1488  $cache->makeGlobalKey( __CLASS__, 'server-read-only', $masterServer ),
1489  self::TTL_CACHE_READONLY,
1490  function () use ( $domain, $conn ) {
1491  $old = $this->trxProfiler->setSilenced( true );
1492  try {
1493  $dbw = $conn ?: $this->getConnection( self::DB_MASTER, [], $domain );
1494  $readOnly = (int)$dbw->serverIsReadOnly();
1495  if ( !$conn ) {
1496  $this->reuseConnection( $dbw );
1497  }
1498  } catch ( DBError $e ) {
1499  $readOnly = 0;
1500  }
1501  $this->trxProfiler->setSilenced( $old );
1502  return $readOnly;
1503  },
1504  [ 'pcTTL' => $cache::TTL_PROC_LONG, 'busyValue' => 0 ]
1505  );
1506  }
1507 
1508  public function allowLagged( $mode = null ) {
1509  if ( $mode === null ) {
1510  return $this->mAllowLagged;
1511  }
1512  $this->mAllowLagged = $mode;
1513 
1514  return $this->mAllowLagged;
1515  }
1516 
1517  public function pingAll() {
1518  $success = true;
1519  $this->forEachOpenConnection( function ( IDatabase $conn ) use ( &$success ) {
1520  if ( !$conn->ping() ) {
1521  $success = false;
1522  }
1523  } );
1524 
1525  return $success;
1526  }
1527 
1528  public function forEachOpenConnection( $callback, array $params = [] ) {
1529  foreach ( $this->mConns as $connsByServer ) {
1530  foreach ( $connsByServer as $serverConns ) {
1531  foreach ( $serverConns as $conn ) {
1532  $mergedParams = array_merge( [ $conn ], $params );
1533  call_user_func_array( $callback, $mergedParams );
1534  }
1535  }
1536  }
1537  }
1538 
1539  public function forEachOpenMasterConnection( $callback, array $params = [] ) {
1540  $masterIndex = $this->getWriterIndex();
1541  foreach ( $this->mConns as $connsByServer ) {
1542  if ( isset( $connsByServer[$masterIndex] ) ) {
1544  foreach ( $connsByServer[$masterIndex] as $conn ) {
1545  $mergedParams = array_merge( [ $conn ], $params );
1546  call_user_func_array( $callback, $mergedParams );
1547  }
1548  }
1549  }
1550  }
1551 
1552  public function forEachOpenReplicaConnection( $callback, array $params = [] ) {
1553  foreach ( $this->mConns as $connsByServer ) {
1554  foreach ( $connsByServer as $i => $serverConns ) {
1555  if ( $i === $this->getWriterIndex() ) {
1556  continue; // skip master
1557  }
1558  foreach ( $serverConns as $conn ) {
1559  $mergedParams = array_merge( [ $conn ], $params );
1560  call_user_func_array( $callback, $mergedParams );
1561  }
1562  }
1563  }
1564  }
1565 
1566  public function getMaxLag( $domain = false ) {
1567  $maxLag = -1;
1568  $host = '';
1569  $maxIndex = 0;
1570 
1571  if ( $this->getServerCount() <= 1 ) {
1572  return [ $host, $maxLag, $maxIndex ]; // no replication = no lag
1573  }
1574 
1575  $lagTimes = $this->getLagTimes( $domain );
1576  foreach ( $lagTimes as $i => $lag ) {
1577  if ( $this->mLoads[$i] > 0 && $lag > $maxLag ) {
1578  $maxLag = $lag;
1579  $host = $this->mServers[$i]['host'];
1580  $maxIndex = $i;
1581  }
1582  }
1583 
1584  return [ $host, $maxLag, $maxIndex ];
1585  }
1586 
1587  public function getLagTimes( $domain = false ) {
1588  if ( $this->getServerCount() <= 1 ) {
1589  return [ $this->getWriterIndex() => 0 ]; // no replication = no lag
1590  }
1591 
1592  $knownLagTimes = []; // map of (server index => 0 seconds)
1593  $indexesWithLag = [];
1594  foreach ( $this->mServers as $i => $server ) {
1595  if ( empty( $server['is static'] ) ) {
1596  $indexesWithLag[] = $i; // DB server might have replication lag
1597  } else {
1598  $knownLagTimes[$i] = 0; // DB server is a non-replicating and read-only archive
1599  }
1600  }
1601 
1602  return $this->getLoadMonitor()->getLagTimes( $indexesWithLag, $domain ) + $knownLagTimes;
1603  }
1604 
1605  public function safeGetLag( IDatabase $conn ) {
1606  if ( $this->getServerCount() <= 1 ) {
1607  return 0;
1608  } else {
1609  return $conn->getLag();
1610  }
1611  }
1612 
1619  public function safeWaitForMasterPos( IDatabase $conn, $pos = false, $timeout = 10 ) {
1620  if ( $this->getServerCount() <= 1 || !$conn->getLBInfo( 'replica' ) ) {
1621  return true; // server is not a replica DB
1622  }
1623 
1624  if ( !$pos ) {
1625  // Get the current master position, opening a connection if needed
1626  $masterConn = $this->getAnyOpenConnection( $this->getWriterIndex() );
1627  if ( $masterConn ) {
1628  $pos = $masterConn->getMasterPos();
1629  } else {
1630  $masterConn = $this->openConnection( $this->getWriterIndex(), self::DOMAIN_ANY );
1631  $pos = $masterConn->getMasterPos();
1632  $this->closeConnection( $masterConn );
1633  }
1634  }
1635 
1636  if ( $pos instanceof DBMasterPos ) {
1637  $result = $conn->masterPosWait( $pos, $timeout );
1638  if ( $result == -1 || is_null( $result ) ) {
1639  $msg = __METHOD__ . ": Timed out waiting on {$conn->getServer()} pos {$pos}";
1640  $this->replLogger->warning( "$msg" );
1641  $ok = false;
1642  } else {
1643  $this->replLogger->info( __METHOD__ . ": Done" );
1644  $ok = true;
1645  }
1646  } else {
1647  $ok = false; // something is misconfigured
1648  $this->replLogger->error( "Could not get master pos for {$conn->getServer()}." );
1649  }
1650 
1651  return $ok;
1652  }
1653 
1654  public function setTransactionListener( $name, callable $callback = null ) {
1655  if ( $callback ) {
1656  $this->trxRecurringCallbacks[$name] = $callback;
1657  } else {
1658  unset( $this->trxRecurringCallbacks[$name] );
1659  }
1661  function ( IDatabase $conn ) use ( $name, $callback ) {
1662  $conn->setTransactionListener( $name, $callback );
1663  }
1664  );
1665  }
1666 
1667  public function setTableAliases( array $aliases ) {
1668  $this->tableAliases = $aliases;
1669  }
1670 
1671  public function setDomainPrefix( $prefix ) {
1672  // Find connections to explicit foreign domains still marked as in-use...
1673  $domainsInUse = [];
1674  $this->forEachOpenConnection( function ( IDatabase $conn ) use ( &$domainsInUse ) {
1675  // Once reuseConnection() is called on a handle, its reference count goes from 1 to 0.
1676  // Until then, it is still in use by the caller (explicitly or via DBConnRef scope).
1677  if ( $conn->getLBInfo( 'foreignPoolRefCount' ) > 0 ) {
1678  $domainsInUse[] = $conn->getDomainID();
1679  }
1680  } );
1681 
1682  // Do not switch connections to explicit foreign domains unless marked as safe
1683  if ( $domainsInUse ) {
1684  $domains = implode( ', ', $domainsInUse );
1685  throw new DBUnexpectedError( null,
1686  "Foreign domain connections are still in use ($domains)." );
1687  }
1688 
1689  $this->localDomain = new DatabaseDomain(
1690  $this->localDomain->getDatabase(),
1691  null,
1692  $prefix
1693  );
1694 
1695  $this->forEachOpenConnection( function ( IDatabase $db ) use ( $prefix ) {
1696  $db->tablePrefix( $prefix );
1697  } );
1698  }
1699 
1706  final protected function getScopedPHPBehaviorForCommit() {
1707  if ( PHP_SAPI != 'cli' ) { // https://bugs.php.net/bug.php?id=47540
1708  $old = ignore_user_abort( true ); // avoid half-finished operations
1709  return new ScopedCallback( function () use ( $old ) {
1710  ignore_user_abort( $old );
1711  } );
1712  }
1713 
1714  return null;
1715  }
1716 
1717  function __destruct() {
1718  // Avoid connection leaks for sanity
1719  $this->disable();
1720  }
1721 }
1722 
1723 class_alias( LoadBalancer::class, 'LoadBalancer' );
Wikimedia\Rdbms\LoadBalancer\getServerType
getServerType( $i)
Get DB type of the server with the specified index.
Definition: LoadBalancer.php:1069
Wikimedia\Rdbms\LoadBalancer\setWaitForPositionIfHigher
setWaitForPositionIfHigher( $pos)
Definition: LoadBalancer.php:524
Wikimedia\Rdbms\DBTransactionSizeError
Definition: DBTransactionSizeError.php:27
Wikimedia\Rdbms\IDatabase\flushSnapshot
flushSnapshot( $fname=__METHOD__)
Commit any transaction but error out if writes or callbacks are pending.
Wikimedia\Rdbms\LoadBalancer\setDomainPrefix
setDomainPrefix( $prefix)
Set a new table prefix for the existing local domain ID for testing.
Definition: LoadBalancer.php:1671
Wikimedia\Rdbms\Database
Relational database abstraction object.
Definition: Database.php:45
Wikimedia\Rdbms\IDatabase\isOpen
isOpen()
Is a connection to the database open?
Wikimedia\Rdbms\LoadBalancer\getServerInfo
getServerInfo( $i)
Definition: LoadBalancer.php:1076
Wikimedia\Rdbms\LoadBalancer\getLazyConnectionRef
getLazyConnectionRef( $db, $groups=[], $domain=false, $flags=0)
Get a database connection handle reference without connecting yet.
Definition: LoadBalancer.php:754
Wikimedia\Rdbms\LoadBalancer\$trxProfiler
TransactionProfiler $trxProfiler
Definition: LoadBalancer.php:70
Wikimedia\Rdbms\LoadBalancer\isOpen
isOpen( $index)
Test if the specified index represents an open connection.
Definition: LoadBalancer.php:931
Wikimedia\Rdbms\LoadBalancer\$trxRoundId
string bool $trxRoundId
String if a requested DBO_TRX transaction round is active.
Definition: LoadBalancer.php:97
false
processing should stop and the error should be shown to the user * false
Definition: hooks.txt:187
Wikimedia\Rdbms\IDatabase\getServer
getServer()
Get the server hostname or IP address.
Wikimedia\Rdbms\LoadBalancer\hasOrMadeRecentMasterChanges
hasOrMadeRecentMasterChanges( $age=null)
Check if this load balancer object had any recent or still pending writes issued against it by this P...
Definition: LoadBalancer.php:1405
$context
do that in ParserLimitReportFormat instead use this to modify the parameters of the image all existing parser cache entries will be invalid To avoid you ll need to handle that somehow(e.g. with the RejectParserCacheValue hook) because MediaWiki won 't do it for you. & $defaults also a ContextSource after deleting those rows but within the same transaction you ll probably need to make sure the header is varied on and they can depend only on the ResourceLoaderContext $context
Definition: hooks.txt:2581
Wikimedia\Rdbms\IDatabase\pendingWriteQueryDuration
pendingWriteQueryDuration( $type=self::ESTIMATE_TOTAL)
Get the time spend running write queries for this transaction.
Wikimedia\Rdbms\DatabaseDomain\newFromId
static newFromId( $domain)
Definition: DatabaseDomain.php:63
Wikimedia\Rdbms\IDatabase\tablePrefix
tablePrefix( $prefix=null)
Get/set the table prefix.
Wikimedia\Rdbms\LoadBalancer\getWriterIndex
getWriterIndex()
Definition: LoadBalancer.php:1041
EmptyBagOStuff
A BagOStuff object with no objects in it.
Definition: EmptyBagOStuff.php:29
Wikimedia\Rdbms\DBAccessError
Exception class for attempted DB access.
Definition: DBAccessError.php:28
Wikimedia\Rdbms\LoadBalancer\undoTransactionRoundFlags
undoTransactionRoundFlags(IDatabase $conn)
Definition: LoadBalancer.php:1367
Wikimedia\Rdbms\ILoadMonitor
An interface for database load monitoring.
Definition: ILoadMonitor.php:35
captcha-old.count
count
Definition: captcha-old.py:249
Wikimedia\Rdbms\LoadBalancer\disable
disable()
Disable this load balancer.
Definition: LoadBalancer.php:1112
Wikimedia\Rdbms\LoadBalancer\getMasterPos
getMasterPos()
Get the current master position for chronology control purposes.
Definition: LoadBalancer.php:1093
Wikimedia\Rdbms\IDatabase\ping
ping(&$rtt=null)
Ping the server and try to reconnect if it there is no connection.
Wikimedia\Rdbms\LoadBalancer\$host
string $host
Current server name.
Definition: LoadBalancer.php:105
$result
The index of the header message $result[1]=The index of the body text message $result[2 through n]=Parameters passed to body text message. Please note the header message cannot receive/use parameters. 'ImportHandleLogItemXMLTag':When parsing a XML tag in a log item. Return false to stop further processing of the tag $reader:XMLReader object $logInfo:Array of information 'ImportHandlePageXMLTag':When parsing a XML tag in a page. Return false to stop further processing of the tag $reader:XMLReader object & $pageInfo:Array of information 'ImportHandleRevisionXMLTag':When parsing a XML tag in a page revision. Return false to stop further processing of the tag $reader:XMLReader object $pageInfo:Array of page information $revisionInfo:Array of revision information 'ImportHandleToplevelXMLTag':When parsing a top level XML tag. Return false to stop further processing of the tag $reader:XMLReader object 'ImportHandleUploadXMLTag':When parsing a XML tag in a file upload. Return false to stop further processing of the tag $reader:XMLReader object $revisionInfo:Array of information 'ImportLogInterwikiLink':Hook to change the interwiki link used in log entries and edit summaries for transwiki imports. & $fullInterwikiPrefix:Interwiki prefix, may contain colons. & $pageTitle:String that contains page title. 'ImportSources':Called when reading from the $wgImportSources configuration variable. Can be used to lazy-load the import sources list. & $importSources:The value of $wgImportSources. Modify as necessary. See the comment in DefaultSettings.php for the detail of how to structure this array. 'InfoAction':When building information to display on the action=info page. $context:IContextSource object & $pageInfo:Array of information 'InitializeArticleMaybeRedirect':MediaWiki check to see if title is a redirect. & $title:Title object for the current page & $request:WebRequest & $ignoreRedirect:boolean to skip redirect check & $target:Title/string of redirect target & $article:Article object 'InternalParseBeforeLinks':during Parser 's internalParse method before links but after nowiki/noinclude/includeonly/onlyinclude and other processings. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InternalParseBeforeSanitize':during Parser 's internalParse method just before the parser removes unwanted/dangerous HTML tags and after nowiki/noinclude/includeonly/onlyinclude and other processings. Ideal for syntax-extensions after template/parser function execution which respect nowiki and HTML-comments. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InterwikiLoadPrefix':When resolving if a given prefix is an interwiki or not. Return true without providing an interwiki to continue interwiki search. $prefix:interwiki prefix we are looking for. & $iwData:output array describing the interwiki with keys iw_url, iw_local, iw_trans and optionally iw_api and iw_wikiid. 'InvalidateEmailComplete':Called after a user 's email has been invalidated successfully. $user:user(object) whose email is being invalidated 'IRCLineURL':When constructing the URL to use in an IRC notification. Callee may modify $url and $query, URL will be constructed as $url . $query & $url:URL to index.php & $query:Query string $rc:RecentChange object that triggered url generation 'IsFileCacheable':Override the result of Article::isFileCacheable()(if true) & $article:article(object) being checked 'IsTrustedProxy':Override the result of IP::isTrustedProxy() & $ip:IP being check & $result:Change this value to override the result of IP::isTrustedProxy() 'IsUploadAllowedFromUrl':Override the result of UploadFromUrl::isAllowedUrl() $url:URL used to upload from & $allowed:Boolean indicating if uploading is allowed for given URL 'isValidEmailAddr':Override the result of Sanitizer::validateEmail(), for instance to return false if the domain name doesn 't match your organization. $addr:The e-mail address entered by the user & $result:Set this and return false to override the internal checks 'isValidPassword':Override the result of User::isValidPassword() $password:The password entered by the user & $result:Set this and return false to override the internal checks $user:User the password is being validated for 'Language::getMessagesFileName':$code:The language code or the language we 're looking for a messages file for & $file:The messages file path, you can override this to change the location. 'LanguageGetMagic':DEPRECATED! Use $magicWords in a file listed in $wgExtensionMessagesFiles instead. Use this to define synonyms of magic words depending of the language & $magicExtensions:associative array of magic words synonyms $lang:language code(string) 'LanguageGetNamespaces':Provide custom ordering for namespaces or remove namespaces. Do not use this hook to add namespaces. Use CanonicalNamespaces for that. & $namespaces:Array of namespaces indexed by their numbers 'LanguageGetSpecialPageAliases':DEPRECATED! Use $specialPageAliases in a file listed in $wgExtensionMessagesFiles instead. Use to define aliases of special pages names depending of the language & $specialPageAliases:associative array of magic words synonyms $lang:language code(string) 'LanguageGetTranslatedLanguageNames':Provide translated language names. & $names:array of language code=> language name $code:language of the preferred translations 'LanguageLinks':Manipulate a page 's language links. This is called in various places to allow extensions to define the effective language links for a page. $title:The page 's Title. & $links:Array with elements of the form "language:title" in the order that they will be output. & $linkFlags:Associative array mapping prefixed links to arrays of flags. Currently unused, but planned to provide support for marking individual language links in the UI, e.g. for featured articles. 'LanguageSelector':Hook to change the language selector available on a page. $out:The output page. $cssClassName:CSS class name of the language selector. 'LinkBegin':DEPRECATED! Use HtmlPageLinkRendererBegin instead. Used when generating internal and interwiki links in Linker::link(), before processing starts. Return false to skip default processing and return $ret. See documentation for Linker::link() for details on the expected meanings of parameters. $skin:the Skin object $target:the Title that the link is pointing to & $html:the contents that the< a > tag should have(raw HTML) $result
Definition: hooks.txt:1963
Wikimedia\Rdbms\LoadBalancer\safeGetLag
safeGetLag(IDatabase $conn)
Get the lag in seconds for a given connection, or zero if this load balancer does not have replicatio...
Definition: LoadBalancer.php:1605
use
as see the revision history and available at free of to any person obtaining a copy of this software and associated documentation to deal in the Software without including without limitation the rights to use
Definition: MIT-LICENSE.txt:10
Wikimedia\Rdbms\IDatabase\close
close()
Closes a database connection.
Wikimedia\Rdbms\LoadBalancer\getAnyOpenConnection
getAnyOpenConnection( $i)
Definition: LoadBalancer.php:538
Wikimedia\Rdbms
Definition: ChronologyProtector.php:24
$fname
if(!defined( 'MEDIAWIKI')) $fname
This file is not a valid entry point, perform no further processing unless MEDIAWIKI is defined.
Definition: Setup.php:36
Wikimedia\Rdbms\LoadBalancer\$loadMonitorConfig
array $loadMonitorConfig
The LoadMonitor configuration.
Definition: LoadBalancer.php:55
Wikimedia\Rdbms\LoadBalancer\getServerName
getServerName( $i)
Get the host name or IP address of the server with the specified index.
Definition: LoadBalancer.php:1057
Wikimedia\Rdbms\DBMasterPos
An object representing a master or replica DB position in a replicated setup.
Definition: DBMasterPos.php:10
$params
$params
Definition: styleTest.css.php:40
Wikimedia\Rdbms\LoadBalancer\forEachOpenMasterConnection
forEachOpenMasterConnection( $callback, array $params=[])
Call a function with each open connection object to a master.
Definition: LoadBalancer.php:1539
BagOStuff
interface is intended to be more or less compatible with the PHP memcached client.
Definition: BagOStuff.php:47
Wikimedia\Rdbms\LoadBalancer\getConnection
getConnection( $i, $groups=[], $domain=false, $flags=0)
Get a connection by index.
Definition: LoadBalancer.php:620
$name
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:302
Wikimedia\Rdbms\LoadBalancer\runMasterPostTrxCallbacks
runMasterPostTrxCallbacks( $type)
Issue all pending post-COMMIT/ROLLBACK callbacks.
Definition: LoadBalancer.php:1292
Wikimedia\Rdbms\LoadBalancer\getLagTimes
getLagTimes( $domain=false)
Get an estimate of replication lag (in seconds) for each server.
Definition: LoadBalancer.php:1587
$success
$success
Definition: NoLocalSettings.php:44
Wikimedia\Rdbms\IDatabase\getLag
getLag()
Get replica DB lag.
Wikimedia\Rdbms\LoadBalancer\flushReplicaSnapshots
flushReplicaSnapshots( $fname=__METHOD__)
Commit all replica DB transactions so as to flush any REPEATABLE-READ or SSI snapshot.
Definition: LoadBalancer.php:1377
Wikimedia\Rdbms\LoadBalancer\$perfLogger
LoggerInterface $perfLogger
Definition: LoadBalancer.php:78
Wikimedia\Rdbms\LoadBalancer\KEY_FOREIGN_INUSE
const KEY_FOREIGN_INUSE
Definition: LoadBalancer.php:129
Wikimedia\Rdbms\LoadBalancer\$replLogger
LoggerInterface $replLogger
Definition: LoadBalancer.php:72
Wikimedia\Rdbms\LoadBalancer\doWait
doWait( $index, $open=false, $timeout=null)
Wait for a given replica DB to catch up to the master pos stored in $this.
Definition: LoadBalancer.php:558
Wikimedia\Rdbms\DBError
Database error base class.
Definition: DBError.php:30
Wikimedia\Rdbms\LoadBalancer\hasMasterChanges
hasMasterChanges()
Determine if there are pending changes in a transaction by this thread.
Definition: LoadBalancer.php:1387
DBO_TRX
const DBO_TRX
Definition: defines.php:12
Wikimedia\Rdbms\LoadBalancer\KEY_FOREIGN_INUSE_NOROUND
const KEY_FOREIGN_INUSE_NOROUND
Definition: LoadBalancer.php:133
Wikimedia\Rdbms\LoadBalancer\getMaxLag
getMaxLag( $domain=false)
Get the hostname and lag time of the most-lagged replica DB.
Definition: LoadBalancer.php:1566
php
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
Wikimedia\Rdbms\IDatabase
Basic database interface for live and lazy-loaded relation database handles.
Definition: IDatabase.php:40
Wikimedia\Rdbms\LoadBalancer\$mWaitForPos
bool DBMasterPos $mWaitForPos
False if not set.
Definition: LoadBalancer.php:85
Wikimedia\Rdbms\IDatabase\lastDoneWrites
lastDoneWrites()
Returns the last time the connection may have been used for write queries.
Wikimedia\Rdbms\LoadBalancer\safeWaitForMasterPos
safeWaitForMasterPos(IDatabase $conn, $pos=false, $timeout=10)
Definition: LoadBalancer.php:1619
Wikimedia\Rdbms\LoadBalancer\$mAllowLagged
bool $mAllowLagged
Whether to disregard replica DB lag as a factor in replica DB selection.
Definition: LoadBalancer.php:51
Wikimedia\Rdbms\IDatabase\commit
commit( $fname=__METHOD__, $flush='')
Commits a transaction previously started using begin().
Wikimedia\Rdbms\DatabaseDomain\newUnspecified
static newUnspecified()
Definition: DatabaseDomain.php:93
Wikimedia\Rdbms\LoadBalancer\allowLagged
allowLagged( $mode=null)
Disables/enables lag checks.
Definition: LoadBalancer.php:1508
key
design txt This is a brief overview of the new design More thorough and up to date information is available on the documentation wiki at etc Handles the details of getting and saving to the user table of the and dealing with sessions and cookies OutputPage Encapsulates the entire HTML page that will be sent in response to any server request It is used by calling its functions to add in any and then calling but I prefer the flexibility This should also do the output encoding The system allocates a global one in $wgOut Title Represents the title of an and does all the work of translating among various forms such as plain database key
Definition: design.txt:25
WANObjectCache\newEmpty
static newEmpty()
Get an instance that wraps EmptyBagOStuff.
Definition: WANObjectCache.php:201
Wikimedia\Rdbms\Database\runOnTransactionIdleCallbacks
runOnTransactionIdleCallbacks( $trigger)
Actually run and consume any "on transaction idle/resolution" callbacks.
Definition: Database.php:2728
Wikimedia\Rdbms\MaintainableDBConnRef
Helper class to handle automatically marking connections as reusable (via RAII pattern) as well handl...
Definition: MaintainableDBConnRef.php:13
Wikimedia\Rdbms\LoadBalancer\$mConns
Database[][][] $mConns
Map of (connection category => server index => IDatabase[])
Definition: LoadBalancer.php:45
Wikimedia\Rdbms\LoadBalancer\getReaderIndex
getReaderIndex( $group=false, $domain=false)
Get the index of the reader connection, which may be a replica DB.
Definition: LoadBalancer.php:318
Wikimedia\Rdbms\LoadBalancer\$trxRecurringCallbacks
array[] $trxRecurringCallbacks
Map of (name => callable)
Definition: LoadBalancer.php:99
Wikimedia\Rdbms\LoadBalancer\KEY_LOCAL_NOROUND
const KEY_LOCAL_NOROUND
Definition: LoadBalancer.php:131
Wikimedia\Rdbms\Database\runOnTransactionPreCommitCallbacks
runOnTransactionPreCommitCallbacks()
Actually run and consume any "on transaction pre-commit" callbacks.
Definition: Database.php:2778
Wikimedia\Rdbms\LoadBalancer\KEY_LOCAL
const KEY_LOCAL
Definition: LoadBalancer.php:127
Wikimedia\Rdbms\LoadBalancer\KEY_FOREIGN_FREE
const KEY_FOREIGN_FREE
Definition: LoadBalancer.php:128
Wikimedia\Rdbms\LoadBalancer\getRandomNonLagged
getRandomNonLagged(array $loads, $domain=false, $maxLag=INF)
Definition: LoadBalancer.php:269
wfDeprecated
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Throws a warning that $function is deprecated.
Definition: GlobalFunctions.php:1176
Wikimedia\Rdbms\LoadBalancer\getReadOnlyReason
getReadOnlyReason( $domain=false, IDatabase $conn=null)
Definition: LoadBalancer.php:1460
Wikimedia\Rdbms\LoadBalancer\pickReaderIndex
pickReaderIndex(array $loads, $domain=false)
Definition: LoadBalancer.php:382
Wikimedia\Rdbms\LoadBalancer\reuseConnection
reuseConnection( $conn)
Mark a foreign connection as being available for reuse under a different DB domain.
Definition: LoadBalancer.php:689
Wikimedia\Rdbms\LoadBalancer\pendingMasterChangeCallers
pendingMasterChangeCallers()
Get the list of callers that have pending master changes.
Definition: LoadBalancer.php:1412
Wikimedia\Rdbms\Database\trxLevel
trxLevel()
Gets the current transaction level.
Definition: Database.php:472
Wikimedia\Rdbms\LoadBalancer\__destruct
__destruct()
Definition: LoadBalancer.php:1717
Wikimedia\Rdbms\LoadBalancer\$mServers
array[] $mServers
Map of (server index => server config array)
Definition: LoadBalancer.php:43
IExpiringStore\TTL_DAY
const TTL_DAY
Definition: IExpiringStore.php:35
Wikimedia\Rdbms\LoadBalancer\hasMasterConnection
hasMasterConnection()
Definition: LoadBalancer.php:1383
Wikimedia\Rdbms\Database\writesOrCallbacksPending
writesOrCallbacksPending()
Returns true if there is a transaction open with possible write queries or transaction pre-commit/idl...
Definition: Database.php:558
Wikimedia\Rdbms\LoadBalancer\suppressTransactionEndCallbacks
suppressTransactionEndCallbacks()
Suppress all pending post-COMMIT/ROLLBACK callbacks.
Definition: LoadBalancer.php:1340
Wikimedia\Rdbms\LoadBalancer\commitMasterChanges
commitMasterChanges( $fname=__METHOD__)
Issue COMMIT on all master connections where writes where done.
Definition: LoadBalancer.php:1258
Wikimedia\Rdbms\LoadBalancer\forEachOpenConnection
forEachOpenConnection( $callback, array $params=[])
Call a function with each open connection object.
Definition: LoadBalancer.php:1528
Wikimedia\Rdbms\LoadBalancer\$srvCache
BagOStuff $srvCache
Definition: LoadBalancer.php:64
Wikimedia\Rdbms\LoadBalancer\isNonZeroLoad
isNonZeroLoad( $i)
Returns true if the specified index is valid and has non-zero load.
Definition: LoadBalancer.php:1049
Wikimedia\Rdbms\LoadBalancer\__construct
__construct(array $params)
Construct a manager of IDatabase connection objects.
Definition: LoadBalancer.php:135
Wikimedia\Rdbms\LoadBalancer\applyTransactionRoundFlags
applyTransactionRoundFlags(IDatabase $conn)
Definition: LoadBalancer.php:1349
Wikimedia\Rdbms\LoadBalancer\waitForOne
waitForOne( $pos, $timeout=null)
Set the master wait position and wait for a "generic" replica DB to catch up to it.
Definition: LoadBalancer.php:474
$time
see documentation in includes Linker php for Linker::makeImageLink & $time
Definition: hooks.txt:1778
Wikimedia\Rdbms\LoadBalancer\$errorLogger
callable $errorLogger
Exception logger.
Definition: LoadBalancer.php:112
Wikimedia\Rdbms\LoadBalancer\pingAll
pingAll()
Definition: LoadBalancer.php:1517
DB_REPLICA
const DB_REPLICA
Definition: defines.php:25
Wikimedia\Rdbms\LoadBalancer\$localDomainIdAlias
string $localDomainIdAlias
Alternate ID string for the domain instead of DatabaseDomain::getId()
Definition: LoadBalancer.php:103
Wikimedia\Rdbms\LoadBalancer\$tableAliases
$tableAliases
Definition: LoadBalancer.php:57
Wikimedia\Rdbms\LoadBalancer\forEachOpenReplicaConnection
forEachOpenReplicaConnection( $callback, array $params=[])
Call a function with each open replica DB connection object.
Definition: LoadBalancer.php:1552
Wikimedia\Rdbms\LoadBalancer\beginMasterChanges
beginMasterChanges( $fname=__METHOD__)
Flush any master transaction snapshots and set DBO_TRX (if DBO_DEFAULT is set)
Definition: LoadBalancer.php:1226
DB_MASTER
const DB_MASTER
Definition: defines.php:26
Wikimedia\Rdbms\LoadBalancer\$connsOpened
int $connsOpened
Total connections opened.
Definition: LoadBalancer.php:95
list
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global list
Definition: deferred.txt:11
Wikimedia\Rdbms\LoadBalancer\commitAll
commitAll( $fname=__METHOD__)
Commit transactions on all open connections.
Definition: LoadBalancer.php:1156
Wikimedia\Rdbms\LoadBalancer
Database connection, tracking, load balancing, and transaction manager for a cluster.
Definition: LoadBalancer.php:41
Wikimedia\Rdbms\LoadBalancer\$mReadIndex
int $mReadIndex
The generic (not query grouped) replica DB index (of $mServers)
Definition: LoadBalancer.php:83
Wikimedia\Rdbms\LoadBalancer\getScopedPHPBehaviorForCommit
getScopedPHPBehaviorForCommit()
Make PHP ignore user aborts/disconnects until the returned value leaves scope.
Definition: LoadBalancer.php:1706
$e
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException' returning false will NOT prevent logging $e
Definition: hooks.txt:2141
Wikimedia\Rdbms\LoadBalancer\getLoadMonitor
getLoadMonitor()
Get a LoadMonitor instance.
Definition: LoadBalancer.php:242
Wikimedia\Rdbms\LoadBalancer\setTransactionListener
setTransactionListener( $name, callable $callback=null)
Set a callback via IDatabase::setTransactionListener() on all current and future master connections o...
Definition: LoadBalancer.php:1654
Wikimedia\Rdbms\LoadBalancer\$chronProtInitialized
bool $chronProtInitialized
Definition: LoadBalancer.php:117
Wikimedia\Rdbms\IDatabase\explicitTrxActive
explicitTrxActive()
Wikimedia\Rdbms\LoadBalancer\laggedSlaveUsed
laggedSlaveUsed()
Definition: LoadBalancer.php:1456
Wikimedia\Rdbms\IDatabase\getDomainID
getDomainID()
Wikimedia\Rdbms\LoadBalancer\setServerInfo
setServerInfo( $i, array $serverInfo)
Definition: LoadBalancer.php:1088
Wikimedia\Rdbms\IDatabase\setTransactionListener
setTransactionListener( $name, callable $callback=null)
Run a callback each time any transaction commits or rolls back.
Wikimedia\Rdbms\LoadBalancer\$mLoads
float[] $mLoads
Map of (server index => weight)
Definition: LoadBalancer.php:47
WANObjectCache
Multi-datacenter aware caching interface.
Definition: WANObjectCache.php:80
Wikimedia\Rdbms\IDatabase\rollback
rollback( $fname=__METHOD__, $flush='')
Rollback a transaction previously started using begin().
Wikimedia\Rdbms\Database\setTrxEndCallbackSuppression
setTrxEndCallbackSuppression( $suppress)
Whether to disable running of post-COMMIT/ROLLBACK callbacks.
Definition: Database.php:2715
Wikimedia\Rdbms\IDatabase\pendingWriteCallers
pendingWriteCallers()
Get the list of method names that did write queries for this transaction.
Wikimedia\Rdbms\LoadBalancer\$allReplicasDownMode
bool $allReplicasDownMode
Whether the generic reader fell back to a lagged replica DB.
Definition: LoadBalancer.php:89
Wikimedia\Rdbms\LoadBalancer\rollbackMasterChanges
rollbackMasterChanges( $fname=__METHOD__)
Issue ROLLBACK only on master, only if queries were done on connection.
Definition: LoadBalancer.php:1325
Wikimedia\Rdbms\LoadBalancer\$profiler
object string $profiler
Class name or object With profileIn/profileOut methods.
Definition: LoadBalancer.php:68
Wikimedia\Rdbms\IDatabase\getFlag
getFlag( $flag)
Returns a boolean whether the flag $flag is set for this connection.
Wikimedia\Rdbms\LoadBalancer\getMaintenanceConnectionRef
getMaintenanceConnectionRef( $db, $groups=[], $domain=false, $flags=0)
Get a maintenance database connection handle reference for migrations and schema changes.
Definition: LoadBalancer.php:760
Wikimedia\Rdbms\DBUnexpectedError
Definition: DBUnexpectedError.php:27
Wikimedia\Rdbms\IDatabase\masterPosWait
masterPosWait(DBMasterPos $pos, $timeout)
Wait for the replica DB to catch up to a given master position.
Wikimedia\Rdbms\LoadBalancer\approveMasterChanges
approveMasterChanges(array $options)
Perform all pre-commit checks for things like replication safety.
Definition: LoadBalancer.php:1193
Wikimedia\Rdbms\LoadBalancer\$chronProt
ChronologyProtector null $chronProt
Definition: LoadBalancer.php:62
Wikimedia\Rdbms\LoadBalancer\$readOnlyReason
string bool $readOnlyReason
Reason the LB is read-only or false if not.
Definition: LoadBalancer.php:93
Wikimedia\Rdbms\LoadBalancer\getConnectionRef
getConnectionRef( $db, $groups=[], $domain=false, $flags=0)
Get a database connection handle reference.
Definition: LoadBalancer.php:748
Wikimedia\Rdbms\DBConnRef
Helper class to handle automatically marking connections as reusable (via RAII pattern) as well handl...
Definition: DBConnRef.php:15
Wikimedia\Rdbms\LoadBalancer\masterRunningReadOnly
masterRunningReadOnly( $domain, IDatabase $conn=null)
Definition: LoadBalancer.php:1483
Wikimedia\Rdbms\LoadBalancer\setTableAliases
setTableAliases(array $aliases)
Make certain table names use their own database, schema, and table prefix when passed into SQL querie...
Definition: LoadBalancer.php:1667
Wikimedia\Rdbms\DBTransactionError
Definition: DBTransactionError.php:27
Wikimedia\Rdbms\LoadBalancer\$localDomain
DatabaseDomain $localDomain
Local Domain ID and default for selectDB() calls.
Definition: LoadBalancer.php:101
$cache
$cache
Definition: mcc.php:33
$options
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped & $options
Definition: hooks.txt:1965
Wikimedia\Rdbms\DBExpectedError
Base class for the more common types of database errors.
Definition: DBExpectedError.php:35
Wikimedia\Rdbms\Database\factory
static factory( $dbType, $p=[])
Construct a Database subclass instance given a database type and parameters.
Definition: Database.php:338
ArrayUtils\pickRandom
static pickRandom( $weights)
Given an array of non-normalised probabilities, this function will select an element and return the a...
Definition: ArrayUtils.php:66
ArrayUtils
A collection of static methods to play with arrays.
Definition: ArrayUtils.php:28
Wikimedia\Rdbms\ChronologyProtector
Class for ensuring a consistent ordering of events as seen by the user, despite replication.
Definition: ChronologyProtector.php:36
Wikimedia\Rdbms\LoadBalancer\$disabled
bool $disabled
Definition: LoadBalancer.php:115
Wikimedia\Rdbms\LoadBalancer\getLaggedReplicaMode
getLaggedReplicaMode( $domain=false)
Definition: LoadBalancer.php:1421
Wikimedia\Rdbms\Database\flushSnapshot
flushSnapshot( $fname=__METHOD__)
Commit any transaction but error out if writes or callbacks are pending.
Definition: Database.php:3050
as
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
Definition: distributors.txt:9
Wikimedia\Rdbms\Database\runTransactionListenerCallbacks
runTransactionListenerCallbacks( $trigger)
Actually run any "transaction listener" callbacks.
Definition: Database.php:2808
Wikimedia\Rdbms\LoadBalancer\$errorConnection
Database $errorConnection
DB connection object that caused a problem.
Definition: LoadBalancer.php:81
Wikimedia\Rdbms\DBConnectionError
Definition: DBConnectionError.php:26
Wikimedia\Rdbms\LoadBalancer\finalizeMasterChanges
finalizeMasterChanges()
Perform all pre-commit callbacks that remain part of the atomic transactions and disable any post-com...
Definition: LoadBalancer.php:1183
Wikimedia\Rdbms\IDatabase\getLBInfo
getLBInfo( $name=null)
Get properties passed down from the server info array of the load balancer.
Wikimedia\Rdbms\LoadBalancer\haveIndex
haveIndex( $i)
Returns true if the specified index is a valid server index.
Definition: LoadBalancer.php:1045
Wikimedia\Rdbms\DBMasterPos\hasReached
hasReached(DBMasterPos $pos)
Wikimedia\Rdbms\LoadBalancer\getLaggedSlaveMode
getLaggedSlaveMode( $domain=false)
Definition: LoadBalancer.php:1443
class
you have access to all of the normal MediaWiki so you can get a DB use the etc For full docs on the Maintenance class
Definition: maintenance.txt:52
Wikimedia\Rdbms\LoadBalancer\laggedReplicaUsed
laggedReplicaUsed()
Checks whether the database for generic connections this request was both:
Definition: LoadBalancer.php:1447
Wikimedia\Rdbms\LoadBalancer\$wanCache
WANObjectCache $wanCache
Definition: LoadBalancer.php:66
Wikimedia\Rdbms\LoadBalancer\$mWaitTimeout
int $mWaitTimeout
Seconds to spend waiting on replica DB lag to resolve.
Definition: LoadBalancer.php:53
Wikimedia\Rdbms\LoadBalancer\reallyOpenConnection
reallyOpenConnection(array $server, $dbNameOverride=false)
Really opens a connection.
Definition: LoadBalancer.php:950
Wikimedia\Rdbms\LoadBalancer\$agent
string $agent
Agent name for query profiling.
Definition: LoadBalancer.php:109
Wikimedia\Rdbms\DatabaseDomain
Class to handle database/prefix specification for IDatabase domains.
Definition: DatabaseDomain.php:28
Wikimedia\Rdbms\TransactionProfiler
Helper class that detects high-contention DB queries via profiling calls.
Definition: TransactionProfiler.php:38
Wikimedia\Rdbms\LoadBalancer\$laggedReplicaMode
bool $laggedReplicaMode
Whether the generic reader fell back to a lagged replica DB.
Definition: LoadBalancer.php:87
Wikimedia\Rdbms\LoadBalancer\$queryLogger
LoggerInterface $queryLogger
Definition: LoadBalancer.php:76
Wikimedia\Rdbms\LoadBalancer\$loadMonitor
ILoadMonitor $loadMonitor
Definition: LoadBalancer.php:60
Wikimedia\Rdbms\LoadBalancer\openConnection
openConnection( $i, $domain=false, $flags=0)
Open a connection to the server given by the specified index.
Definition: LoadBalancer.php:767
DBO_DEFAULT
const DBO_DEFAULT
Definition: defines.php:13
Wikimedia\Rdbms\IDatabase\setFlag
setFlag( $flag, $remember=self::REMEMBER_NOTHING)
Set a flag for this connection.
Wikimedia\Rdbms\LoadBalancer\waitForAll
waitForAll( $pos, $timeout=null)
Set the master wait position and wait for ALL replica DBs to catch up to it.
Definition: LoadBalancer.php:501
Wikimedia\Rdbms\LoadBalancer\closeAll
closeAll()
Close all open connections.
Definition: LoadBalancer.php:1117
Wikimedia\Rdbms\LoadBalancer\$connLogger
LoggerInterface $connLogger
Definition: LoadBalancer.php:74
Wikimedia\Rdbms\IDatabase\restoreFlags
restoreFlags( $state=self::RESTORE_PRIOR)
Restore the flags to their prior state before the last setFlag/clearFlag call.
Wikimedia\Rdbms\LoadBalancer\waitFor
waitFor( $pos)
Set the master wait position.
Definition: LoadBalancer.php:457
Wikimedia\Rdbms\LoadBalancer\$mLastError
string $mLastError
The last DB selection or connection error.
Definition: LoadBalancer.php:91
Wikimedia\Rdbms\LoadBalancer\openForeignConnection
openForeignConnection( $i, $domain, $flags=0)
Open a connection to a foreign DB, or return one if it is already open.
Definition: LoadBalancer.php:851
Wikimedia\Rdbms\LoadBalancer\lastMasterChangeTimestamp
lastMasterChangeTimestamp()
Get the timestamp of the latest write query done by this thread.
Definition: LoadBalancer.php:1396
Wikimedia\Rdbms\LoadBalancer\$cliMode
bool $cliMode
Whether this PHP instance is for a CLI script.
Definition: LoadBalancer.php:107
$flags
it s the revision text itself In either if gzip is the revision text is gzipped $flags
Definition: hooks.txt:2801
Wikimedia\Rdbms\ILoadBalancer
Database cluster connection, tracking, load balancing, and transaction manager interface.
Definition: ILoadBalancer.php:78
Wikimedia\Rdbms\LoadBalancer\getServerCount
getServerCount()
Get the number of defined servers (not the number of open connections)
Definition: LoadBalancer.php:1053
Wikimedia\Rdbms\LoadBalancer\closeConnection
closeConnection(IDatabase $conn)
Close a connection.
Definition: LoadBalancer.php:1135
Wikimedia\Rdbms\LoadBalancer\KEY_FOREIGN_FREE_NOROUND
const KEY_FOREIGN_FREE_NOROUND
Definition: LoadBalancer.php:132
Wikimedia\Rdbms\LoadBalancer\reportConnectionError
reportConnectionError()
Definition: LoadBalancer.php:1013
array
the array() calling protocol came about after MediaWiki 1.4rc1.
$type
$type
Definition: testCompression.php:48
Wikimedia\Rdbms\LoadBalancer\$mGroupLoads
array[] $mGroupLoads
Map of (group => server index => weight)
Definition: LoadBalancer.php:49
Wikimedia\Rdbms\IDatabase\writesOrCallbacksPending
writesOrCallbacksPending()
Returns true if there is a transaction open with possible write queries or transaction pre-commit/idl...