76 const CONN_HELD_WARN_THRESHOLD = 10;
80 const POS_WAIT_TIMEOUT = 10;
82 const TTL_CACHE_READONLY = 5;
97 if ( !isset( $params[
'servers'] ) ) {
98 throw new MWException( __CLASS__ .
': missing servers parameter' );
100 $this->mServers = $params[
'servers'];
101 $this->mWaitTimeout = self::POS_WAIT_TIMEOUT;
103 $this->mReadIndex = -1;
104 $this->mWriteIndex = -1;
108 'foreignFree' => [] ];
110 $this->mWaitForPos =
false;
111 $this->mErrorConnection =
false;
112 $this->mAllowLagged =
false;
114 if ( isset( $params[
'readOnlyReason'] ) && is_string( $params[
'readOnlyReason'] ) ) {
115 $this->readOnlyReason = $params[
'readOnlyReason'];
118 if ( isset( $params[
'loadMonitor'] ) ) {
119 $this->mLoadMonitorClass = $params[
'loadMonitor'];
121 $master = reset( $params[
'servers'] );
122 if ( isset( $master[
'type'] ) && $master[
'type'] ===
'mysql' ) {
123 $this->mLoadMonitorClass =
'LoadMonitorMySQL';
125 $this->mLoadMonitorClass =
'LoadMonitorNull';
129 foreach ( $params[
'servers']
as $i => $server ) {
130 $this->mLoads[$i] = $server[
'load'];
131 if ( isset( $server[
'groupLoads'] ) ) {
132 foreach ( $server[
'groupLoads']
as $group => $ratio ) {
133 if ( !isset( $this->mGroupLoads[$group] ) ) {
134 $this->mGroupLoads[$group] = [];
136 $this->mGroupLoads[$group][$i] = $ratio;
144 if ( isset( $params[
'trxProfiler'] ) ) {
145 $this->trxProfiler = $params[
'trxProfiler'];
157 if ( !isset( $this->mLoadMonitor ) ) {
159 $this->mLoadMonitor =
new $class( $this );
171 return wfSetVar( $this->mParentInfo, $x );
183 # Unset excessively lagged servers
184 foreach ( $lags
as $i => $lag ) {
186 $maxServerLag = $maxLag;
187 if ( isset( $this->mServers[$i][
'max lag'] ) ) {
188 $maxServerLag = min( $maxServerLag, $this->mServers[$i][
'max lag'] );
192 if ( $lag ===
false ) {
193 wfDebugLog(
'replication',
"Server $host (#$i) is not replicating?" );
195 } elseif ( $lag > $maxServerLag ) {
196 wfDebugLog(
'replication',
"Server $host (#$i) has >= $lag seconds of lag" );
202 # Find out if all the slaves with non-zero load are lagged
204 foreach ( $loads
as $load ) {
208 # No appropriate DB servers except maybe the master and some slaves with zero load
209 # Do NOT use the master
210 # Instead, this function will return false, triggering read-only mode,
211 # and a lagged slave will be used instead.
215 if ( count( $loads ) == 0 ) {
219 # Return a random representative of the remainder
237 # @todo FIXME: For now, only go through all this for mysql databases
238 if ( $wgDBtype !=
'mysql' ) {
242 if ( count( $this->mServers ) == 1 ) {
243 # Skip the load balancing if there's only one server
245 } elseif ( $group ===
false && $this->mReadIndex >= 0 ) {
246 # Shortcut if generic reader exists already
250 # Find the relevant load array
251 if ( $group !==
false ) {
252 if ( isset( $this->mGroupLoads[$group] ) ) {
253 $nonErrorLoads = $this->mGroupLoads[$group];
255 # No loads for this group, return false and the caller can use some other group
256 wfDebugLog(
'connect', __METHOD__ .
": no loads for group $group\n" );
264 if ( !count( $nonErrorLoads ) ) {
265 throw new MWException(
"Empty server array given to LoadBalancer" );
268 # Scale the configured load ratios according to the dynamic load (if the load monitor supports it)
269 $this->
getLoadMonitor()->scaleLoads( $nonErrorLoads, $group, $wiki );
273 # No server found yet
276 # First try quickly looking through the available servers for a server that
278 $currentLoads = $nonErrorLoads;
279 while ( count( $currentLoads ) ) {
284 if ( $this->mWaitForPos && $this->mWaitForPos->asOfTime() ) {
285 # ChronologyProtecter causes mWaitForPos to be set via sessions.
286 # This triggers doWait() after connect, so it's especially good to
287 # avoid lagged servers so as to avoid just blocking in that method.
288 $ago = microtime(
true ) - $this->mWaitForPos->asOfTime();
289 # Aim for <= 1 second of waiting (being too picky can backfire)
292 if ( $i ===
false ) {
293 # Any server with less lag than it's 'max lag' param is preferable
296 if ( $i ===
false && count( $currentLoads ) != 0 ) {
297 # All slaves lagged. Switch to read-only mode
298 wfDebugLog(
'replication',
"All slaves lagged. Switch to read-only mode" );
304 if ( $i ===
false ) {
305 # pickRandom() returned false
306 # This is permanent and means the configuration or the load monitor
307 # wants us to return false.
308 wfDebugLog(
'connect', __METHOD__ .
": pickRandom() returned false" );
314 wfDebugLog(
'connect', __METHOD__ .
": Using reader #$i: $serverName..." );
318 wfDebugLog(
'connect', __METHOD__ .
": Failed connecting to $i/$wiki" );
319 unset( $nonErrorLoads[$i] );
320 unset( $currentLoads[$i] );
327 if ( $wiki !==
false ) {
335 # If all servers were down, quit now
336 if ( !count( $nonErrorLoads ) ) {
340 if ( $i !==
false ) {
341 # Slave connection successful
342 # Wait for the session master pos for a short time
343 if ( $this->mWaitForPos && $i > 0 ) {
344 if ( !$this->
doWait( $i ) ) {
345 $this->mServers[$i][
'slave pos'] = $conn->getSlavePos();
348 if ( $this->mReadIndex <= 0 && $this->mLoads[$i] > 0 && $group ===
false ) {
349 $this->mReadIndex = $i;
350 # Record if the generic reader index is in "lagged slave" mode
352 $this->laggedSlaveMode =
true;
357 ": using server $serverName for group '$group'\n" );
370 $this->mWaitForPos = $pos;
374 if ( !$this->
doWait( $i ) ) {
376 $this->laggedSlaveMode =
true;
392 $this->mWaitForPos = $pos;
399 $readLoads = array_filter( $readLoads );
404 $ok = $this->
doWait( $i,
true, $timeout );
419 $this->mWaitForPos = $pos;
420 $serverCount = count( $this->mServers );
423 for ( $i = 1; $i < $serverCount; $i++ ) {
424 if ( $this->mLoads[$i] > 0 ) {
425 $ok = $this->
doWait( $i,
true, $timeout ) && $ok;
440 foreach ( $this->mConns
as $conns ) {
441 if ( !empty( $conns[$i] ) ) {
442 return reset( $conns[$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 ) ) {
466 ": slave $server known to be caught up (pos >= $knownReachedPos).\n" );
474 wfDebugLog(
'replication', __METHOD__ .
": no connection open for $server\n" );
480 wfDebugLog(
'replication', __METHOD__ .
": failed to connect to $server\n" );
490 wfDebugLog(
'replication', __METHOD__ .
": Waiting for slave $server to catch up...\n" );
492 $result = $conn->masterPosWait( $this->mWaitForPos, $timeout );
496 $msg = __METHOD__ .
": Timed out waiting on $server pos {$this->mWaitForPos}";
501 wfDebugLog(
'replication', __METHOD__ .
": Done\n" );
526 if ( $i === null || $i ===
false ) {
527 throw new MWException(
'Attempt to call ' . __METHOD__ .
528 ' with invalid server index' );
535 $groups = ( $groups ===
false || $groups === [] )
545 # Try to find an available server in any the query groups (in order)
546 foreach ( $groups
as $group ) {
548 if ( $groupIndex !==
false ) {
555 # Operation-based index
557 $this->mLastError =
'Unknown error';
558 # Try the general server pool if $groups are unavailable.
559 $i = in_array(
false, $groups,
true )
562 # Couldn't find a working server in getReaderIndex()?
563 if ( $i ===
false ) {
570 # 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();
581 $trxProf->recordConnection( $host, $dbname, $masterOnly );
585 # Make master-requested DB handles inherit any read-only mode setting
601 $serverIndex = $conn->getLBInfo(
'serverIndex' );
602 $refCount = $conn->getLBInfo(
'foreignPoolRefCount' );
603 if ( $serverIndex === null || $refCount === null ) {
604 wfDebug( __METHOD__ .
": this connection was not opened as a foreign connection\n" );
618 $dbName = $conn->getDBname();
619 $prefix = $conn->tablePrefix();
620 if ( strval( $prefix ) !==
'' ) {
621 $wiki =
"$dbName-$prefix";
625 if ( $this->mConns[
'foreignUsed'][$serverIndex][$wiki] !== $conn ) {
626 throw new MWException( __METHOD__ .
": connection not found, has " .
627 "the connection been freed already?" );
629 $conn->setLBInfo(
'foreignPoolRefCount', --$refCount );
630 if ( $refCount <= 0 ) {
631 $this->mConns[
'foreignFree'][$serverIndex][$wiki] = $conn;
632 unset( $this->mConns[
'foreignUsed'][$serverIndex][$wiki] );
633 wfDebug( __METHOD__ .
": freed connection $serverIndex/$wiki\n" );
635 wfDebug( __METHOD__ .
": reference count for $serverIndex/$wiki reduced to $refCount\n" );
668 return new DBConnRef( $this, [ $db, $groups, $wiki ] );
686 if ( $wiki !==
false ) {
688 } elseif ( isset( $this->mConns[
'local'][$i][0] ) ) {
689 $conn = $this->mConns[
'local'][$i][0];
691 $server = $this->mServers[$i];
692 $server[
'serverIndex'] = $i;
695 if ( $conn->isOpen() ) {
696 wfDebugLog(
'connect',
"Connected to database $i at $serverName\n" );
697 $this->mConns[
'local'][$i][0] = $conn;
699 wfDebugLog(
'connect',
"Failed to connect to database $i at $serverName\n" );
700 $this->mErrorConnection = $conn;
705 if ( $conn && !$conn->isOpen() ) {
710 $this->mErrorConnection = $conn;
739 if ( isset( $this->mConns[
'foreignUsed'][$i][$wiki] ) ) {
741 $conn = $this->mConns[
'foreignUsed'][$i][$wiki];
742 wfDebug( __METHOD__ .
": reusing connection $i/$wiki\n" );
743 } elseif ( isset( $this->mConns[
'foreignFree'][$i][$wiki] ) ) {
745 $conn = $this->mConns[
'foreignFree'][$i][$wiki];
746 unset( $this->mConns[
'foreignFree'][$i][$wiki] );
747 $this->mConns[
'foreignUsed'][$i][$wiki] = $conn;
748 wfDebug( __METHOD__ .
": reusing free connection $i/$wiki\n" );
749 } elseif ( !empty( $this->mConns[
'foreignFree'][$i] ) ) {
751 $conn = reset( $this->mConns[
'foreignFree'][$i] );
752 $oldWiki =
key( $this->mConns[
'foreignFree'][$i] );
756 if ( $dbName !==
'' && !$conn->selectDB( $dbName ) ) {
757 $this->mLastError =
"Error selecting database $dbName on server " .
758 $conn->getServer() .
" from client host " .
wfHostname() .
"\n";
759 $this->mErrorConnection = $conn;
762 $conn->tablePrefix( $prefix );
763 unset( $this->mConns[
'foreignFree'][$i][$oldWiki] );
764 $this->mConns[
'foreignUsed'][$i][$wiki] = $conn;
765 wfDebug( __METHOD__ .
": reusing free connection from $oldWiki for $wiki\n" );
769 $server = $this->mServers[$i];
770 $server[
'serverIndex'] = $i;
771 $server[
'foreignPoolRefCount'] = 0;
772 $server[
'foreign'] =
true;
774 if ( !$conn->isOpen() ) {
775 wfDebug( __METHOD__ .
": error opening connection for $i/$wiki\n" );
776 $this->mErrorConnection = $conn;
779 $conn->tablePrefix( $prefix );
780 $this->mConns[
'foreignUsed'][$i][$wiki] = $conn;
781 wfDebug( __METHOD__ .
": opened new connection for $i/$wiki\n" );
787 $refCount = $conn->getLBInfo(
'foreignPoolRefCount' );
788 $conn->setLBInfo(
'foreignPoolRefCount', $refCount + 1 );
802 if ( !is_integer( $index ) ) {
820 if ( $this->disabled ) {
824 if ( !is_array( $server ) ) {
825 throw new MWException(
'You must update your load-balancing configuration. ' .
826 'See DefaultSettings.php entry for $wgDBservers.' );
829 if ( $dbNameOverride !==
false ) {
830 $server[
'dbname'] = $dbNameOverride;
835 $server[
'clusterMasterHost'] = $masterName;
838 if ( ++$this->connsOpened >= self::CONN_HELD_WARN_THRESHOLD ) {
839 wfDebugLog(
'DBPerformance', __METHOD__ .
": " .
840 "{$this->connsOpened}+ connections made (master=$masterName)\n" .
853 $db->setLBInfo( $server );
854 $db->setLazyMasterHandle(
857 $db->setTransactionProfiler( $this->trxProfiler );
869 'method' => __METHOD__,
873 if ( !is_object( $conn ) ) {
876 "LB failure with no last connection. Connection error: {last_error}",
883 $context[
'db_server'] = $conn->getProperty(
'mServer' );
885 "Connection error: {last_error} ({db_server})",
890 $conn->reportConnectionError(
"{$this->mLastError} ({$context['db_server']})" );
911 return array_key_exists( $i, $this->mServers );
921 return array_key_exists( $i, $this->mServers ) && $this->mLoads[$i] != 0;
930 return count( $this->mServers );
940 if ( isset( $this->mServers[$i][
'hostName'] ) ) {
941 $name = $this->mServers[$i][
'hostName'];
942 } elseif ( isset( $this->mServers[$i][
'host'] ) ) {
943 $name = $this->mServers[$i][
'host'];
957 if ( isset( $this->mServers[$i] ) ) {
958 return $this->mServers[$i];
971 $this->mServers[$i] = $serverInfo;
979 # If this entire request was served from a slave without opening a connection to the
980 # master (however unlikely that may be), then we can fetch the position from the slave.
982 if ( !$masterConn ) {
983 $serverCount = count( $this->mServers );
984 for ( $i = 1; $i < $serverCount; $i++ ) {
987 return $conn->getSlavePos();
991 return $masterConn->getMasterPos();
1005 $this->disabled =
true;
1018 'foreignFree' => [],
1019 'foreignUsed' => [],
1021 $this->connsOpened = 0;
1032 foreach ( $this->mConns
as $i1 => $conns2 ) {
1033 foreach ( $conns2
as $i2 => $conns3 ) {
1034 foreach ( $conns3
as $i3 => $candidateConn ) {
1035 if ( $conn === $candidateConn ) {
1037 unset( $this->mConns[$i1][$i2][$i3] );
1082 $limit = isset( $options[
'maxWriteDuration'] ) ? $options[
'maxWriteDuration'] : 0;
1126 $failedServers = [];
1129 foreach ( $this->mConns
as $conns2 ) {
1130 if ( empty( $conns2[$masterIndex] ) ) {
1134 foreach ( $conns2[$masterIndex]
as $conn ) {
1135 if ( $conn->trxLevel() && $conn->writesOrCallbacksPending() ) {
1137 $conn->rollback(
$fname,
'flush' );
1140 $failedServers[] = $conn->getServer();
1146 if ( $failedServers ) {
1148 implode(
', ', array_unique( $failedServers ) ) );
1167 foreach ( $this->mConns
as $conns2 ) {
1168 if ( empty( $conns2[$masterIndex] ) ) {
1172 foreach ( $conns2[$masterIndex]
as $conn ) {
1173 if ( $conn->trxLevel() && $conn->writesOrCallbacksPending() ) {
1189 foreach ( $this->mConns
as $conns2 ) {
1190 if ( empty( $conns2[$masterIndex] ) ) {
1194 foreach ( $conns2[$masterIndex]
as $conn ) {
1195 $lastTime = max( $lastTime, $conn->lastDoneWrites() );
1210 $age = ( $age === null ) ? $this->mWaitTimeout : $age;
1226 foreach ( $this->mConns
as $conns2 ) {
1227 if ( empty( $conns2[$masterIndex] ) ) {
1231 foreach ( $conns2[$masterIndex]
as $conn ) {
1232 $fnames = array_merge( $fnames, $conn->pendingWriteCallers() );
1262 $this->slavesDownMode =
true;
1263 $this->laggedSlaveMode =
true;
1287 if ( $this->readOnlyReason !==
false ) {
1290 if ( $this->slavesDownMode ) {
1291 return 'The database has been automatically locked ' .
1292 'until the slave database servers become available';
1294 return 'The database has been automatically locked ' .
1295 'while the slave database servers catch up to the master.';
1298 return 'The database master is running in read-only mode.';
1313 return (
bool)
$cache->getWithSetCallback(
1314 $cache->makeGlobalKey( __CLASS__,
'server-read-only', $masterServer ),
1315 self::TTL_CACHE_READONLY,
1316 function ()
use ( $wiki, $conn ) {
1319 return (
int)$dbw->serverIsReadOnly();
1324 [
'pcTTL' => $cache::TTL_PROC_LONG,
'busyValue' => 0 ]
1334 if ( $mode === null ) {
1337 $this->mAllowLagged = $mode;
1348 if ( !$conn->
ping() ) {
1362 foreach ( $this->mConns
as $connsByServer ) {
1363 foreach ( $connsByServer
as $serverConns ) {
1364 foreach ( $serverConns
as $conn ) {
1365 $mergedParams = array_merge( [ $conn ],
$params );
1366 call_user_func_array( $callback, $mergedParams );
1380 foreach ( $this->mConns
as $connsByServer ) {
1381 if ( isset( $connsByServer[$masterIndex] ) ) {
1383 foreach ( $connsByServer[$masterIndex]
as $conn ) {
1384 $mergedParams = array_merge( [ $conn ],
$params );
1385 call_user_func_array( $callback, $mergedParams );
1407 return [ $host, $maxLag, $maxIndex ];
1411 foreach ( $lagTimes
as $i => $lag ) {
1412 if ( $this->mLoads[$i] > 0 && $lag > $maxLag ) {
1414 $host = $this->mServers[$i][
'host'];
1419 return [ $host, $maxLag, $maxIndex ];
1437 # Send the request to the load monitor
1438 return $this->
getLoadMonitor()->getLagTimes( array_keys( $this->mServers ), $wiki );
1486 $msg = __METHOD__ .
": Timed out waiting on {$conn->getServer()} pos {$pos}";
1491 wfDebugLog(
'replication', __METHOD__ .
": Done\n" );
ping()
Ping the server and try to reconnect if it there is no connection.
getLaggedSlaveMode($wiki=false)
static getMainWANInstance()
Get the main WAN cache object.
commitAll($fname=__METHOD__)
Commit transactions on all open connections.
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
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...
masterRunningReadOnly($wiki, DatabaseBase $conn=null)
integer $mWaitTimeout
Seconds to spend waiting on slave lag to resolve.
getAnyOpenConnection($i)
Get any open connection to a given server index, local or foreign Returns false if there is no connec...
reuseConnection($conn)
Mark a foreign connection as being available for reuse under a different DB name or prefix...
getServerCount()
Get the number of defined servers (not the number of open connections)
array[] $mServers
Map of (server index => server config array)
bool $slavesDownMode
Whether the generic reader fell back to a lagged slave.
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
array $mParentInfo
LBFactory information.
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
static instance()
Singleton.
rollbackMasterChanges($fname=__METHOD__)
Issue ROLLBACK only on master, only if queries were done on connection.
array $mLoads
Map of (server index => weight)
wfHostname()
Fetch server name for use in error reporting etc.
getLazyConnectionRef($db, $groups=[], $wiki=false)
Get a database connection handle reference without connecting yet.
wfBacktrace($raw=null)
Get a debug backtrace as a string.
runOnTransactionIdleCallbacks($trigger)
Actually run and consume any "on transaction idle/resolution" callbacks.
wfLogDBError($text, array $context=[])
Log for database errors.
An object representing a master or slave position in a replicated setup.
getMaxLag($wiki=false)
Get the hostname and lag time of the most-lagged slave.
when a variable name is used in a it is silently declared as a new local masking the global
array[] $mGroupLoads
Map of (group => server index => weight)
forEachOpenConnection($callback, array $params=[])
Call a function with each open connection object.
masterPosWait(DBMasterPos $pos, $timeout)
Wait for the slave to catch up to a given master position.
see documentation in includes Linker php for Linker::makeImageLink & $time
close()
Closes a database connection.
__construct(array $params)
wfDebug($text, $dest= 'all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
array[] $mConns
Map of (local/foreignUsed/foreignFree => server index => DatabaseBase array)
runOnTransactionPreCommitCallbacks()
Actually run and consume any "on transaction pre-commit" callbacks.
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
getConnection($i, $groups=[], $wiki=false)
Get a connection by index This is the main entry point for this class.
doWait($index, $open=false, $timeout=null)
Wait for a given slave to catch up to the master pos stored in $this.
LoadMonitor $mLoadMonitor
getRandomNonLagged(array $loads, $wiki=false, $maxLag=self::MAX_LAG)
Database load balancing object.
wfDebugLog($logGroup, $text, $dest= 'all', array $context=[])
Send a line to a supplementary debug log file, if configured, or main debug log if not...
getServerInfo($i)
Return the server info structure for a given index, or false if the index is invalid.
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
bool DatabaseBase $mErrorConnection
Database connection that caused a problem.
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" slave to catch up to it.
allowLagged($mode=null)
Disables/enables lag checks.
openForeignConnection($i, $wiki)
Open a connection to a foreign DB, or return one if it is already open.
getReadOnlyReason($wiki=false, DatabaseBase $conn=null)
hasMasterChanges()
Determine if there are pending changes in a transaction by this thread.
Exception class for attempted DB access.
integer $connsOpened
Total connections opened.
openConnection($i, $wiki=false)
Open a connection to the server given by the specified index Index must be an actual index into the a...
parentInfo($x=null)
Get or set arbitrary data used by the parent object, usually an LBFactory.
Helper class to handle automatically marking connections as reusable (via RAII pattern) as well handl...
static factory($dbType, $p=[])
Given a DB type, construct the name of the appropriate child class of DatabaseBase.
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 just before the function returns a value If you return an< a > element with HTML attributes $attribs and contents $html will be returned If you return $ret will be returned after processing after in associative array form externallinks including delete and has completed for all link tables whether this was an auto creation default is conds Array Extra conditions for the No matching items in log is displayed if loglist is empty msgKey Array If you want a nice box with a set this to the key of the message First element is the message additional optional elements are parameters for the key that are processed with wfMessage() -> params() ->parseAsBlock()-offset Set to overwrite offset parameter in $wgRequest set to ''to unsetoffset-wrap String Wrap the message in html(usually something like"<
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 text
clearLagTimeCache()
Clear the cache for slag lag delay times.
disable()
Disable this load balancer.
wfWikiID()
Get an ASCII string identifying this wiki This is used as a prefix in memcached keys.
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...
forEachOpenMasterConnection($callback, array $params=[])
Call a function with each open connection object to a master.
pendingWriteQueryDuration()
Get the time spend running write queries for this transaction.
getLagTimes($wiki=false)
Get an estimate of replication lag (in seconds) for each server.
Database abstraction object.
getConnectionRef($db, $groups=[], $wiki=false)
Get a database connection handle reference.
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
wfSetVar(&$dest, $source, $force=false)
Sets dest to source and returns the original value of dest If source is NULL, it just returns the val...
if(!defined( 'MEDIAWIKI')) $fname
This file is not a valid entry point, perform no further processing unless MEDIAWIKI is defined...
runMasterPreCommitCallbacks()
Perform all pre-commit callbacks that remain part of the atomic transactions and disable any post-com...
closeAll()
Close all open connections.
static getLocalServerInstance($fallback=CACHE_NONE)
Factory function for CACHE_ACCEL (referenced from DefaultSettings.php)
setPostCommitCallbackSupression($suppress)
Whether to disable running of post-commit callbacks.
closeConnection($conn)
Close a connection Using this function makes sure the LoadBalancer knows the connection is closed...
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
commit($fname=__METHOD__, $flush= '')
Commits a transaction previously started using begin().
isOpen($index)
Test if the specified index represents an open connection.
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.
getReaderIndex($group=false, $wiki=false)
Get the index of the reader connection, which may be a slave This takes into account load ratios and ...
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_SLAVE connection has been opened already, waits Otherwise sets a...
integer $mReadIndex
The generic (not query grouped) slave index (of $mServers)
getMasterPos()
Get the current master position for chronology control purposes.
string bool $readOnlyReason
Reason the LB is read-only or false if not.
wfSplitWikiID($wiki)
Split a wiki ID into DB name and table prefix.
bool $mAllowLagged
Whether to disregard slave lag as a factor in slave selection.
commitMasterChanges($fname=__METHOD__)
Issue COMMIT on all master connections where writes where done.
writesOrCallbacksPending()
Returns true if there is a transaction open with possible write queries or transaction pre-commit/idl...
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...
static logException($e)
Log an exception to the exception log (if enabled).
reallyOpenConnection($server, $dbNameOverride=false)
Really opens a connection.
string $mLoadMonitorClass
The LoadMonitor subclass name.
waitForAll($pos, $timeout=null)
Set the master wait position and wait for ALL slaves to catch up to it.
bool $laggedSlaveMode
Whether the generic reader fell back to a lagged slave.
TransactionProfiler $trxProfiler
Basic database interface for live and lazy-loaded DB handles.
runMasterPostCommitCallbacks()
Issue all pending post-commit callbacks.
safeWaitForMasterPos(IDatabase $conn, $pos=false, $timeout=10)
Wait for a slave DB to reach a specified master position.
lastMasterChangeTimestamp()
Get the timestamp of the latest write query done by this thread.
Allows to change the fields on the form that will be generated $name