108 const CONN_HELD_WARN_THRESHOLD = 10;
111 const MAX_LAG_DEFAULT = 10;
113 const TTL_CACHE_READONLY = 5;
116 if ( !isset( $params[
'servers'] ) ) {
119 $this->mServers = $params[
'servers'];
121 $this->localDomain = isset( $params[
'localDomain'] )
126 if ( $this->localDomain->getTablePrefix() !=
'' ) {
127 $this->localDomainIdAlias =
128 $this->localDomain->getDatabase() .
'-' . $this->localDomain->getTablePrefix();
130 $this->localDomainIdAlias = $this->localDomain->getDatabase();
133 $this->mWaitTimeout = isset( $params[
'waitTimeout'] ) ? $params[
'waitTimeout'] : 10;
135 $this->mReadIndex = -1;
142 $this->mWaitForPos =
false;
143 $this->mErrorConnection =
false;
144 $this->mAllowLagged =
false;
146 if ( isset( $params[
'readOnlyReason'] ) && is_string( $params[
'readOnlyReason'] ) ) {
147 $this->readOnlyReason = $params[
'readOnlyReason'];
150 if ( isset( $params[
'loadMonitor'] ) ) {
151 $this->loadMonitorConfig = $params[
'loadMonitor'];
153 $this->loadMonitorConfig = [
'class' =>
'LoadMonitorNull' ];
156 foreach ( $params[
'servers']
as $i => $server ) {
157 $this->mLoads[$i] = $server[
'load'];
158 if ( isset( $server[
'groupLoads'] ) ) {
159 foreach ( $server[
'groupLoads']
as $group => $ratio ) {
160 if ( !isset( $this->mGroupLoads[$group] ) ) {
161 $this->mGroupLoads[$group] = [];
163 $this->mGroupLoads[$group][$i] = $ratio;
168 if ( isset( $params[
'srvCache'] ) ) {
169 $this->srvCache = $params[
'srvCache'];
173 if ( isset( $params[
'memCache'] ) ) {
174 $this->memCache = $params[
'memCache'];
178 if ( isset( $params[
'wanCache'] ) ) {
179 $this->wanCache = $params[
'wanCache'];
183 $this->profiler = isset( $params[
'profiler'] ) ? $params[
'profiler'] : null;
184 if ( isset( $params[
'trxProfiler'] ) ) {
185 $this->trxProfiler = $params[
'trxProfiler'];
190 $this->errorLogger = isset( $params[
'errorLogger'] )
191 ? $params[
'errorLogger']
193 trigger_error( get_class(
$e ) .
': ' .
$e->getMessage(), E_USER_WARNING );
196 foreach ( [
'replLogger',
'connLogger',
'queryLogger',
'perfLogger' ]
as $key ) {
197 $this->$key = isset( $params[$key] ) ? $params[$key] : new \Psr\Log\NullLogger();
200 $this->host = isset( $params[
'hostname'] )
201 ? $params[
'hostname']
202 : ( gethostname() ?:
'unknown' );
203 $this->cliMode = isset( $params[
'cliMode'] ) ? $params[
'cliMode'] : PHP_SAPI ===
'cli';
204 $this->agent = isset( $params[
'agent'] ) ? $params[
'agent'] :
'';
213 if ( !isset( $this->loadMonitor ) ) {
214 $class = $this->loadMonitorConfig[
'class'];
215 $this->loadMonitor =
new $class(
216 $this, $this->srvCache, $this->memCache, $this->loadMonitorConfig );
217 $this->loadMonitor->setLogger( $this->replLogger );
232 # Unset excessively lagged servers
233 foreach ( $lags
as $i => $lag ) {
235 # How much lag this server nominally is allowed to have
236 $maxServerLag = isset( $this->mServers[$i][
'max lag'] )
237 ? $this->mServers[$i][
'max lag']
238 : self::MAX_LAG_DEFAULT;
239 # Constrain that futher by $maxLag argument
240 $maxServerLag = min( $maxServerLag, $maxLag );
243 if ( $lag ===
false && !is_infinite( $maxServerLag ) ) {
244 $this->replLogger->error(
"Server $host (#$i) is not replicating?" );
246 } elseif ( $lag > $maxServerLag ) {
247 $this->replLogger->warning(
"Server $host (#$i) has >= $lag seconds of lag" );
253 # Find out if all the replica DBs with non-zero load are lagged
255 foreach ( $loads
as $load ) {
259 # No appropriate DB servers except maybe the master and some replica DBs with zero load
260 # Do NOT use the master
261 # Instead, this function will return false, triggering read-only mode,
262 # and a lagged replica DB will be used instead.
266 if ( count( $loads ) == 0 ) {
270 # Return a random representative of the remainder
275 if ( count( $this->mServers ) == 1 ) {
276 # Skip the load balancing if there's only one server
278 } elseif ( $group ===
false && $this->mReadIndex >= 0 ) {
279 # Shortcut if generic reader exists already
283 # Find the relevant load array
284 if ( $group !==
false ) {
285 if ( isset( $this->mGroupLoads[$group] ) ) {
286 $nonErrorLoads = $this->mGroupLoads[$group];
288 # No loads for this group, return false and the caller can use some other group
289 $this->connLogger->info( __METHOD__ .
": no loads for group $group" );
297 if ( !count( $nonErrorLoads ) ) {
301 # Scale the configured load ratios according to the dynamic load if supported
306 # No server found yet
308 # First try quickly looking through the available servers for a server that
310 $currentLoads = $nonErrorLoads;
311 while ( count( $currentLoads ) ) {
316 if ( $this->mWaitForPos && $this->mWaitForPos->asOfTime() ) {
317 # ChronologyProtecter causes mWaitForPos to be set via sessions.
318 # This triggers doWait() after connect, so it's especially good to
319 # avoid lagged servers so as to avoid just blocking in that method.
320 $ago = microtime(
true ) - $this->mWaitForPos->asOfTime();
321 # Aim for <= 1 second of waiting (being too picky can backfire)
324 if ( $i ===
false ) {
325 # Any server with less lag than it's 'max lag' param is preferable
328 if ( $i ===
false && count( $currentLoads ) != 0 ) {
329 # All replica DBs lagged. Switch to read-only mode
330 $this->replLogger->error(
"All replica DBs lagged. Switch to read-only mode" );
336 if ( $i ===
false ) {
337 # pickRandom() returned false
338 # This is permanent and means the configuration or the load monitor
339 # wants us to return false.
340 $this->connLogger->debug( __METHOD__ .
": pickRandom() returned false" );
346 $this->connLogger->debug( __METHOD__ .
": Using reader #$i: $serverName..." );
350 $this->connLogger->warning( __METHOD__ .
": Failed connecting to $i/$domain" );
351 unset( $nonErrorLoads[$i] );
352 unset( $currentLoads[$i] );
359 if ( $domain !==
false ) {
367 # If all servers were down, quit now
368 if ( !count( $nonErrorLoads ) ) {
369 $this->connLogger->error(
"All servers down" );
372 if ( $i !==
false ) {
373 # Replica DB connection successful.
374 # Wait for the session master pos for a short time.
375 if ( $this->mWaitForPos && $i > 0 ) {
378 if ( $this->mReadIndex <= 0 && $this->mLoads[$i] > 0 && $group ===
false ) {
379 $this->mReadIndex = $i;
380 # Record if the generic reader index is in "lagged replica DB" mode
382 $this->laggedReplicaMode =
true;
386 $this->connLogger->debug(
387 __METHOD__ .
": using server $serverName for group '$group'" );
394 $this->mWaitForPos = $pos;
398 if ( !$this->
doWait( $i ) ) {
399 $this->laggedReplicaMode =
true;
405 $this->mWaitForPos = $pos;
412 $readLoads = array_filter( $readLoads );
417 $ok = $this->
doWait( $i,
true, $timeout );
426 $this->mWaitForPos = $pos;
427 $serverCount = count( $this->mServers );
430 for ( $i = 1; $i < $serverCount; $i++ ) {
431 if ( $this->mLoads[$i] > 0 ) {
432 $ok = $this->
doWait( $i,
true, $timeout ) && $ok;
440 foreach ( $this->mConns
as $connsByServer ) {
441 if ( !empty( $connsByServer[$i] ) ) {
442 return reset( $connsByServer[$i] );
456 protected function doWait( $index, $open =
false, $timeout = null ) {
461 $key = $this->srvCache->makeGlobalKey( __CLASS__,
'last-known-pos', $server );
463 $knownReachedPos = $this->srvCache->get( $key );
464 if ( $knownReachedPos && $knownReachedPos->hasReached( $this->mWaitForPos ) ) {
465 $this->replLogger->debug( __METHOD__ .
466 ": replica DB $server known to be caught up (pos >= $knownReachedPos)." );
474 $this->replLogger->debug( __METHOD__ .
": no connection open for $server" );
480 $this->replLogger->warning( __METHOD__ .
": failed to connect to $server" );
490 $this->replLogger->info( __METHOD__ .
": Waiting for replica DB $server to catch up..." );
492 $result = $conn->masterPosWait( $this->mWaitForPos, $timeout );
496 $msg = __METHOD__ .
": Timed out waiting on $server pos {$this->mWaitForPos}";
497 $this->replLogger->warning(
"$msg" );
500 $this->replLogger->info( __METHOD__ .
": Done" );
523 if ( $i === null || $i ===
false ) {
525 ' with invalid server index' );
532 $groups = ( $groups ===
false || $groups === [] )
542 # Try to find an available server in any the query groups (in order)
543 foreach ( $groups
as $group ) {
545 if ( $groupIndex !==
false ) {
552 # Operation-based index
554 $this->mLastError =
'Unknown error';
555 # Try the general server pool if $groups are unavailable.
556 $i = ( $groups === [
false ] )
559 # Couldn't find a working server in getReaderIndex()?
560 if ( $i ===
false ) {
568 # Now we have an explicit index into the servers array
576 # Profile any new connections that happen
577 if ( $this->connsOpened > $oldConnsOpened ) {
578 $host = $conn->getServer();
579 $dbname = $conn->getDBname();
580 $this->trxProfiler->recordConnection(
$host, $dbname, $masterOnly );
584 # Make master-requested DB handles inherit any read-only mode setting
585 $conn->setLBInfo(
'readOnlyReason', $this->
getReadOnlyReason( $domain, $conn ) );
592 $serverIndex = $conn->getLBInfo(
'serverIndex' );
593 $refCount = $conn->getLBInfo(
'foreignPoolRefCount' );
594 if ( $serverIndex === null || $refCount === null ) {
606 } elseif ( $conn instanceof
DBConnRef ) {
609 $this->connLogger->error( __METHOD__ .
": got DBConnRef instance.\n" .
615 if ( $this->disabled ) {
619 $domain = $conn->getDomainID();
620 if ( !isset( $this->mConns[
'foreignUsed'][$serverIndex][$domain] ) ) {
622 ": connection $serverIndex/$domain not found; it may have already been freed." );
623 } elseif ( $this->mConns[
'foreignUsed'][$serverIndex][$domain] !== $conn ) {
625 ": connection $serverIndex/$domain mismatched; it may have already been freed." );
627 $conn->setLBInfo(
'foreignPoolRefCount', --$refCount );
628 if ( $refCount <= 0 ) {
629 $this->mConns[
'foreignFree'][$serverIndex][$domain] = $conn;
630 unset( $this->mConns[
'foreignUsed'][$serverIndex][$domain] );
631 if ( !$this->mConns[
'foreignUsed'][$serverIndex] ) {
632 unset( $this->mConns[
'foreignUsed' ][$serverIndex] );
634 $this->connLogger->debug( __METHOD__ .
": freed connection $serverIndex/$domain" );
636 $this->connLogger->debug( __METHOD__ .
637 ": reference count for $serverIndex/$domain reduced to $refCount" );
642 $domain = ( $domain !==
false ) ? $domain : $this->localDomain;
648 $domain = ( $domain !==
false ) ? $domain : $this->localDomain;
650 return new DBConnRef( $this, [ $db, $groups, $domain ] );
666 if ( $domain !==
false ) {
668 } elseif ( isset( $this->mConns[
'local'][$i][0] ) ) {
669 $conn = $this->mConns[
'local'][$i][0];
671 if ( !isset( $this->mServers[$i] ) || !is_array( $this->mServers[$i] ) ) {
675 $server = $this->mServers[$i];
676 $server[
'serverIndex'] = $i;
679 if ( $conn->isOpen() ) {
680 $this->connLogger->debug(
"Connected to database $i at '$serverName'." );
681 $this->mConns[
'local'][$i][0] = $conn;
683 $this->connLogger->warning(
"Failed to connect to database $i at '$serverName'." );
684 $this->mErrorConnection = $conn;
689 if ( $conn && !$conn->isOpen() ) {
694 $this->mErrorConnection = $conn;
723 $dbName = $domainInstance->getDatabase();
724 $prefix = $domainInstance->getTablePrefix();
726 if ( isset( $this->mConns[
'foreignUsed'][$i][$domain] ) ) {
728 $conn = $this->mConns[
'foreignUsed'][$i][$domain];
729 $this->connLogger->debug( __METHOD__ .
": reusing connection $i/$domain" );
730 } elseif ( isset( $this->mConns[
'foreignFree'][$i][$domain] ) ) {
732 $conn = $this->mConns[
'foreignFree'][$i][$domain];
733 unset( $this->mConns[
'foreignFree'][$i][$domain] );
734 $this->mConns[
'foreignUsed'][$i][$domain] = $conn;
735 $this->connLogger->debug( __METHOD__ .
": reusing free connection $i/$domain" );
736 } elseif ( !empty( $this->mConns[
'foreignFree'][$i] ) ) {
738 $conn = reset( $this->mConns[
'foreignFree'][$i] );
739 $oldDomain =
key( $this->mConns[
'foreignFree'][$i] );
742 if ( strlen( $dbName ) && !$conn->selectDB( $dbName ) ) {
743 $this->mLastError =
"Error selecting database '$dbName' on server " .
744 $conn->getServer() .
" from client host {$this->host}";
745 $this->mErrorConnection = $conn;
748 $conn->tablePrefix( $prefix );
749 unset( $this->mConns[
'foreignFree'][$i][$oldDomain] );
750 $this->mConns[
'foreignUsed'][$i][$domain] = $conn;
751 $this->connLogger->debug( __METHOD__ .
752 ": reusing free connection from $oldDomain for $domain" );
755 if ( !isset( $this->mServers[$i] ) || !is_array( $this->mServers[$i] ) ) {
759 $server = $this->mServers[$i];
760 $server[
'serverIndex'] = $i;
761 $server[
'foreignPoolRefCount'] = 0;
762 $server[
'foreign'] =
true;
764 if ( !$conn->isOpen() ) {
765 $this->connLogger->warning( __METHOD__ .
": connection error for $i/$domain" );
766 $this->mErrorConnection = $conn;
769 $conn->tablePrefix( $prefix );
770 $this->mConns[
'foreignUsed'][$i][$domain] = $conn;
771 $this->connLogger->debug( __METHOD__ .
": opened new connection for $i/$domain" );
777 $refCount = $conn->getLBInfo(
'foreignPoolRefCount' );
778 $conn->setLBInfo(
'foreignPoolRefCount', $refCount + 1 );
792 if ( !is_integer( $index ) ) {
811 if ( $this->disabled ) {
815 if ( $dbNameOverride !==
false ) {
816 $server[
'dbname'] = $dbNameOverride;
821 $server[
'clusterMasterHost'] = $masterName;
824 if ( ++$this->connsOpened >= self::CONN_HELD_WARN_THRESHOLD ) {
825 $this->perfLogger->warning( __METHOD__ .
": " .
826 "{$this->connsOpened}+ connections made (master=$masterName)" );
852 $db->setLBInfo( $server );
853 $db->setLazyMasterHandle(
856 $db->setTableAliases( $this->tableAliases );
859 if ( $this->trxRoundId !==
false ) {
862 foreach ( $this->trxRecurringCallbacks
as $name => $callback ) {
863 $db->setTransactionListener(
$name, $callback );
876 'method' => __METHOD__,
880 if ( !is_object( $conn ) ) {
882 $this->connLogger->error(
883 "LB failure with no last connection. Connection error: {last_error}",
890 $context[
'db_server'] = $conn->getServer();
891 $this->connLogger->warning(
892 "Connection error: {last_error} ({db_server})",
897 $conn->reportConnectionError(
"{$this->mLastError} ({$context['db_server']})" );
906 return array_key_exists( $i, $this->mServers );
910 return array_key_exists( $i, $this->mServers ) && $this->mLoads[$i] != 0;
914 return count( $this->mServers );
918 if ( isset( $this->mServers[$i][
'hostName'] ) ) {
919 $name = $this->mServers[$i][
'hostName'];
920 } elseif ( isset( $this->mServers[$i][
'host'] ) ) {
921 $name = $this->mServers[$i][
'host'];
930 if ( isset( $this->mServers[$i] ) ) {
931 return $this->mServers[$i];
938 $this->mServers[$i] = $serverInfo;
942 # If this entire request was served from a replica DB without opening a connection to the
943 # master (however unlikely that may be), then we can fetch the position from the replica DB.
945 if ( !$masterConn ) {
946 $serverCount = count( $this->mServers );
947 for ( $i = 1; $i < $serverCount; $i++ ) {
950 return $conn->getReplicaPos();
954 return $masterConn->getMasterPos();
962 $this->disabled =
true;
968 $this->connLogger->debug(
"Closing connection to database '$host'." );
977 $this->connsOpened = 0;
981 $serverIndex = $conn->
getLBInfo(
'serverIndex' );
982 foreach ( $this->mConns
as $type => $connsByServer ) {
983 if ( !isset( $connsByServer[$serverIndex] ) ) {
987 foreach ( $connsByServer[$serverIndex]
as $i => $trackedConn ) {
988 if ( $conn === $trackedConn ) {
990 $this->connLogger->debug(
"Closing connection to database $i at '$host'." );
991 unset( $this->mConns[
$type][$serverIndex][$i] );
1004 $restore = ( $this->trxRoundId !==
false );
1005 $this->trxRoundId =
false;
1011 call_user_func( $this->errorLogger, $e );
1012 $failures[] =
"{$conn->getServer()}: {$e->getMessage()}";
1014 if ( $restore && $conn->
getLBInfo(
'master' ) ) {
1023 "Commit failed on server(s) " . implode(
"\n", array_unique( $failures ) )
1039 $limit = isset( $options[
'maxWriteDuration'] ) ? $options[
'maxWriteDuration'] : 0;
1047 "Explicit transaction still active. A caller may have caught an error."
1056 "Transaction spent $time second(s) in writes, exceeding the $limit limit.",
1065 "A connection to the {$conn->getDBname()} database was lost before commit."
1072 if ( $this->trxRoundId !==
false ) {
1075 "$fname: Transaction round '{$this->trxRoundId}' already started."
1078 $this->trxRoundId =
$fname;
1087 call_user_func( $this->errorLogger, $e );
1088 $failures[] =
"{$conn->getServer()}: {$e->getMessage()}";
1098 "$fname: Flush failed on server(s) " . implode(
"\n", array_unique( $failures ) )
1109 $restore = ( $this->trxRoundId !==
false );
1110 $this->trxRoundId =
false;
1116 } elseif ( $restore ) {
1120 call_user_func( $this->errorLogger, $e );
1121 $failures[] =
"{$conn->getServer()}: {$e->getMessage()}";
1132 "$fname: Commit failed on server(s) " . implode(
"\n", array_unique( $failures ) )
1145 $this->queryLogger->error( __METHOD__ .
": found writes/callbacks pending." );
1171 $restore = ( $this->trxRoundId !==
false );
1172 $this->trxRoundId =
false;
1230 return (
bool)$pending;
1243 $age = ( $age === null ) ? $this->mWaitTimeout : $age;
1260 if ( !$this->laggedReplicaMode && $this->
getServerCount() > 1 ) {
1267 $this->allReplicasDownMode =
true;
1268 $this->laggedReplicaMode =
true;
1298 if ( $this->readOnlyReason !==
false ) {
1301 if ( $this->allReplicasDownMode ) {
1302 return 'The database has been automatically locked ' .
1303 'until the replica database servers become available';
1305 return 'The database has been automatically locked ' .
1306 'while the replica database servers catch up to the master.';
1309 return 'The database master is running in read-only mode.';
1324 return (
bool)
$cache->getWithSetCallback(
1325 $cache->makeGlobalKey( __CLASS__,
'server-read-only', $masterServer ),
1326 self::TTL_CACHE_READONLY,
1327 function ()
use ( $domain, $conn ) {
1328 $old = $this->trxProfiler->setSilenced(
true );
1331 $readOnly = (int)$dbw->serverIsReadOnly();
1338 $this->trxProfiler->setSilenced( $old );
1341 [
'pcTTL' => $cache::TTL_PROC_LONG,
'busyValue' => 0 ]
1346 if ( $mode === null ) {
1349 $this->mAllowLagged = $mode;
1357 if ( !$conn->
ping() ) {
1366 foreach ( $this->mConns
as $connsByServer ) {
1367 foreach ( $connsByServer
as $serverConns ) {
1368 foreach ( $serverConns
as $conn ) {
1369 $mergedParams = array_merge( [ $conn ],
$params );
1370 call_user_func_array( $callback, $mergedParams );
1378 foreach ( $this->mConns
as $connsByServer ) {
1379 if ( isset( $connsByServer[$masterIndex] ) ) {
1381 foreach ( $connsByServer[$masterIndex]
as $conn ) {
1382 $mergedParams = array_merge( [ $conn ],
$params );
1383 call_user_func_array( $callback, $mergedParams );
1390 foreach ( $this->mConns
as $connsByServer ) {
1391 foreach ( $connsByServer
as $i => $serverConns ) {
1395 foreach ( $serverConns
as $conn ) {
1396 $mergedParams = array_merge( [ $conn ],
$params );
1397 call_user_func_array( $callback, $mergedParams );
1409 return [
$host, $maxLag, $maxIndex ];
1413 foreach ( $lagTimes
as $i => $lag ) {
1414 if ( $this->mLoads[$i] > 0 && $lag > $maxLag ) {
1416 $host = $this->mServers[$i][
'host'];
1421 return [
$host, $maxLag, $maxIndex ];
1429 $knownLagTimes = [];
1430 $indexesWithLag = [];
1431 foreach ( $this->mServers
as $i => $server ) {
1432 if ( empty( $server[
'is static'] ) ) {
1433 $indexesWithLag[] = $i;
1435 $knownLagTimes[$i] = 0;
1439 return $this->
getLoadMonitor()->getLagTimes( $indexesWithLag, $domain ) + $knownLagTimes;
1458 if ( $masterConn ) {
1459 $pos = $masterConn->getMasterPos();
1462 $pos = $masterConn->getMasterPos();
1470 $msg = __METHOD__ .
": Timed out waiting on {$conn->getServer()} pos {$pos}";
1471 $this->replLogger->warning(
"$msg" );
1474 $this->replLogger->info( __METHOD__ .
": Done" );
1479 $this->replLogger->error(
"Could not get master pos for {$conn->getServer()}." );
1487 $this->trxRecurringCallbacks[
$name] = $callback;
1489 unset( $this->trxRecurringCallbacks[
$name] );
1499 $this->tableAliases = $aliases;
1503 if ( $this->mConns[
'foreignUsed'] ) {
1506 foreach ( $this->mConns[
'foreignUsed']
as $i => $connsByDomain ) {
1507 $domains = array_merge( $domains, array_keys( $connsByDomain ) );
1509 $domains = implode(
', ', $domains );
1511 "Foreign domain connections are still in use ($domains)." );
1515 $this->localDomain->getDatabase(),
1532 if ( PHP_SAPI !=
'cli' ) {
1533 $old = ignore_user_abort(
true );
1534 return new ScopedCallback(
function ()
use ( $old ) {
1535 ignore_user_abort( $old );
lastDoneWrites()
Returns the last time the connection may have been used for write queries.
commitAll($fname=__METHOD__)
Commit transactions on all open connections.
array[] $trxRecurringCallbacks
Map of (name => callable)
Database error base class.
the array() calling protocol came about after MediaWiki 1.4rc1.
safeGetLag(IDatabase $conn)
Get the lag in seconds for a given connection, or zero if this load balancer does not have replicatio...
integer $mWaitTimeout
Seconds to spend waiting on replica DB lag to resolve.
getAnyOpenConnection($i)
Get any open connection to a given server index, local or foreign Returns false if there is no connec...
writesOrCallbacksPending()
Returns true if there is a transaction open with possible write queries or transaction pre-commit/idl...
bool IDatabase $mErrorConnection
Database connection that caused a problem.
static factory($dbType, $p=[])
Construct a Database subclass instance given a database type and parameters.
trxLevel()
Gets the current transaction level.
reuseConnection($conn)
Mark a foreign connection as being available for reuse under a different DB name or prefix...
processing should stop and the error should be shown to the user * false
ILoadMonitor $loadMonitor
getServerCount()
Get the number of defined servers (not the number of open connections)
array[] $mServers
Map of (server index => server config array)
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
getLoadMonitor()
Get a LoadMonitor instance.
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException'returning false will NOT prevent logging $e
rollbackMasterChanges($fname=__METHOD__)
Issue ROLLBACK only on master, only if queries were done on connection.
LoggerInterface $replLogger
runTransactionListenerCallbacks($trigger)
Actually run any "transaction listener" callbacks.
close()
Closes a database connection.
finalizeMasterChanges()
Perform all pre-commit callbacks that remain part of the atomic transactions and disable any post-com...
object string $profiler
Class name or object With profileIn/profileOut methods.
setTableAliases(array $aliases)
Make certain table names use their own database, schema, and table prefix when passed into SQL querie...
reallyOpenConnection(array $server, $dbNameOverride=false)
Really opens a connection.
An object representing a master or replica DB position in a replicated setup.
bool $cliMode
Whether this PHP instance is for a CLI script.
getReaderIndex($group=false, $domain=false)
Get the index of the reader connection, which may be a replica DB This takes into account load ratios...
openConnection($i, $domain=false)
array[] $mGroupLoads
Map of (group => server index => weight)
float[] $mLoads
Map of (server index => weight)
bool $allReplicasDownMode
Whether the generic reader fell back to a lagged replica DB.
forEachOpenConnection($callback, array $params=[])
Call a function with each open connection object.
getLazyConnectionRef($db, $groups=[], $domain=false)
Get a database connection handle reference without connecting yet.
masterPosWait(DBMasterPos $pos, $timeout)
Wait for the replica DB to catch up to a given master position.
__construct(array $params)
Construct a manager of IDatabase connection objects.
array[] $mConns
Map of (local/foreignUsed/foreignFree => server index => IDatabase array)
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:Associative array mapping language codes to prefixed links of the form"language:title".&$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
doWait($index, $open=false, $timeout=null)
Wait for a given replica DB to catch up to the master pos stored in $this.
getLagTimes($domain=false)
Get an estimate of replication lag (in seconds) for each server.
Class to handle database/prefix specification for IDatabase domains.
static newEmpty()
Get an instance that wraps EmptyBagOStuff.
getRandomNonLagged(array $loads, $domain=false, $maxLag=INF)
getServerInfo($i)
Return the server info structure for a given index, or false if the index is invalid.
array $loadMonitorConfig
The LoadMonitor configuration.
string $mLastError
The last DB selection or connection error.
setServerInfo($i, array $serverInfo)
Sets the server info structure for the given index.
Base class for the more common types of database errors.
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
setFlag($flag, $remember=self::REMEMBER_NOTHING)
Set a flag for this connection.
getReadOnlyReason($domain=false, IDatabase $conn=null)
getLag()
Get replica DB lag.
Database cluster connection, tracking, load balancing, and transaction manager interface.
Helper class that detects high-contention DB queries via profiling calls.
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set and then return false from the hook function Ensure you consume the ChangeTagAfterDelete hook to carry out custom deletion actions as context called by AbstractContent::getParserOutput May be used to override the normal model specific rendering of page content as context as context $options
waitForOne($pos, $timeout=null)
Set the master wait position and wait for a "generic" replica DB to catch up to it.
allowLagged($mode=null)
Disables/enables lag checks.
hasMasterChanges()
Determine if there are pending changes in a transaction by this thread.
getScopedPHPBehaviorForCommit()
Make PHP ignore user aborts/disconnects until the returned value leaves scope.
Exception class for attempted DB access.
integer $connsOpened
Total connections opened.
setDomainPrefix($prefix)
Set a new table prefix for the existing local domain ID for testing.
writesOrCallbacksPending()
Returns true if there is a transaction open with possible write queries or transaction pre-commit/idl...
flushReplicaSnapshots($fname=__METHOD__)
Commit all replica DB transactions so as to flush any REPEATABLE-READ or SSI snapshot.
Helper class to handle automatically marking connections as reusable (via RAII pattern) as well handl...
getMaxLag($domain=false)
Get the hostname and lag time of the most-lagged replica DB.
A BagOStuff object with no objects in it.
LoggerInterface $connLogger
disable()
Disable this load balancer.
getFlag($flag)
Returns a boolean whether the flag $flag is set for this connection.
beginMasterChanges($fname=__METHOD__)
Flush any master transaction snapshots and set DBO_TRX (if DBO_DEFAULT is set)
string $agent
Agent name for query profiling.
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
approveMasterChanges(array $options)
Perform all pre-commit checks for things like replication safety.
hasOrMadeRecentMasterChanges($age=null)
Check if this load balancer object had any recent or still pending writes issued against it by this P...
pendingWriteQueryDuration($type=self::ESTIMATE_TOTAL)
Get the time spend running write queries for this transaction.
forEachOpenMasterConnection($callback, array $params=[])
Call a function with each open connection object to a master.
commit($fname=__METHOD__, $flush= '')
Commits a transaction previously started using begin().
runOnTransactionIdleCallbacks($trigger)
Actually run and consume any "on transaction idle/resolution" callbacks.
flushSnapshot($fname=__METHOD__)
Commit any transaction but error out if writes or callbacks are pending.
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
restoreFlags($state=self::RESTORE_PRIOR)
Restore the flags to their prior state before the last setFlag/clearFlag call.
suppressTransactionEndCallbacks()
Suppress all pending post-COMMIT/ROLLBACK callbacks.
if(!defined( 'MEDIAWIKI')) $fname
This file is not a valid entry point, perform no further processing unless MEDIAWIKI is defined...
setTransactionListener($name, callable $callback=null)
Set a callback via IDatabase::setTransactionListener() on all current and future master connections o...
getLaggedReplicaMode($domain=false)
closeAll()
Close all open connections.
pendingWriteCallers()
Get the list of method names that did write queries for this transaction.
string $localDomainIdAlias
Alternate ID string for the domain instead of DatabaseDomain::getId()
masterRunningReadOnly($domain, IDatabase $conn=null)
getServer()
Get the server hostname or IP address.
getConnection($i, $groups=[], $domain=false)
static newFromId($domain)
LoggerInterface $perfLogger
tablePrefix($prefix=null)
Get/set the table prefix.
closeConnection(IDatabase $conn)
Close a connection.
haveIndex($i)
Returns true if the specified index is a valid server index.
getLBInfo($name=null)
Get properties passed down from the server info array of the load balancer.
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set and then return false from the hook function Ensure you consume the ChangeTagAfterDelete hook to carry out custom deletion actions as context called by AbstractContent::getParserOutput May be used to override the normal model specific rendering of page content as context as context the output can only depend on parameters provided to this hook not on global state indicating whether full HTML should be generated If generation of HTML may be but other information should still be present in the ParserOutput object to manipulate or replace but no entry for that model exists in $wgContentHandlers if desired whether it is OK to use $contentModel on $title Handler functions that modify $ok should generally return false to prevent further hooks from further modifying $ok inclusive $limit
setTrxEndCallbackSuppression($suppress)
Whether to disable running of post-COMMIT/ROLLBACK callbacks.
isOpen($index)
Test if the specified index represents an open connection.
string $host
Current server name.
string bool $trxRoundId
String if a requested DBO_TRX transaction round is active.
static pickRandom($weights)
Given an array of non-normalised probabilities, this function will select an element and return the a...
pendingMasterChangeCallers()
Get the list of callers that have pending master changes.
bool $laggedReplicaMode
Whether the generic reader fell back to a lagged replica DB.
isNonZeroLoad($i)
Returns true if the specified index is valid and has non-zero load.
waitFor($pos)
Set the master wait position If a DB_REPLICA connection has been opened already, waits Otherwise sets...
integer $mReadIndex
The generic (not query grouped) replica DB index (of $mServers)
callable $errorLogger
Exception logger.
getMasterPos()
Get the current master position for chronology control purposes.
openForeignConnection($i, $domain)
Open a connection to a foreign DB, or return one if it is already open.
DatabaseDomain $localDomain
Local Domain ID and default for selectDB() calls.
runOnTransactionPreCommitCallbacks()
Actually run and consume any "on transaction pre-commit" callbacks.
string bool $readOnlyReason
Reason the LB is read-only or false if not.
bool $mAllowLagged
Whether to disregard replica DB lag as a factor in replica DB selection.
commitMasterChanges($fname=__METHOD__)
Issue COMMIT on all master connections where writes where done.
rollback($fname=__METHOD__, $flush= '')
Rollback a transaction previously started using begin().
bool DBMasterPos $mWaitForPos
False if not set.
getServerName($i)
Get the host name or IP address of the server with the specified index Prefer a readable name if avai...
ping(&$rtt=null)
Ping the server and try to reconnect if it there is no connection.
getConnectionRef($db, $groups=[], $domain=false)
Get a database connection handle reference.
forEachOpenReplicaConnection($callback, array $params=[])
Call a function with each open replica DB connection object.
getLaggedSlaveMode($domain=false)
undoTransactionRoundFlags(IDatabase $conn)
waitForAll($pos, $timeout=null)
Set the master wait position and wait for ALL replica DBs to catch up to it.
setTransactionListener($name, callable $callback=null)
Run a callback each time any transaction commits or rolls back.
do that in ParserLimitReportFormat instead use this to modify the parameters of the image and a DIV can begin in one section and end in another Make sure your code can handle that case gracefully See the EditSectionClearerLink extension for an example zero but section is usually empty its values are the globals values before the output is cached one of or reset my talk my contributions etc etc otherwise the built in rate limiting checks are if enabled allows for interception of redirect as a string mapping parameter names to values & $type
TransactionProfiler $trxProfiler
see documentation in includes Linker php for Linker::makeImageLink & $time
Basic database interface for live and lazy-loaded relation database handles.
applyTransactionRoundFlags(IDatabase $conn)
LoggerInterface $queryLogger
runMasterPostTrxCallbacks($type)
Issue all pending post-COMMIT/ROLLBACK callbacks.
safeWaitForMasterPos(IDatabase $conn, $pos=false, $timeout=10)
Wait for a replica DB to reach a specified master position.
lastMasterChangeTimestamp()
Get the timestamp of the latest write query done by this thread.
flushSnapshot($fname=__METHOD__)
Commit any transaction but error out if writes or callbacks are pending.
Allows to change the fields on the form that will be generated $name