31use Wikimedia\ScopedCallback;
32use Wikimedia\WaitConditionLoop;
105 parent::__construct(
$params );
110 if ( isset(
$params[
'servers'] ) ) {
111 $this->serverInfos = [];
112 $this->serverTags = [];
113 $this->numServers = count(
$params[
'servers'] );
115 foreach (
$params[
'servers']
as $tag => $info ) {
116 $this->serverInfos[$index] = $info;
117 if ( is_string( $tag ) ) {
118 $this->serverTags[$index] = $tag;
120 $this->serverTags[$index] = $info[
'host'] ??
"#$index";
124 } elseif ( isset(
$params[
'server'] ) ) {
125 $this->serverInfos = [
$params[
'server'] ];
126 $this->numServers = count( $this->serverInfos );
129 $this->serverInfos =
false;
130 $this->numServers = 1;
133 if ( isset(
$params[
'purgePeriod'] ) ) {
134 $this->purgePeriod = intval(
$params[
'purgePeriod'] );
136 if ( isset(
$params[
'tableName'] ) ) {
139 if ( isset(
$params[
'shards'] ) ) {
140 $this->shards = intval(
$params[
'shards'] );
142 if ( isset(
$params[
'syncTimeout'] ) ) {
143 $this->syncTimeout =
$params[
'syncTimeout'];
145 $this->replicaOnly = !empty(
$params[
'slaveOnly'] );
155 protected function getDB( $serverIndex ) {
156 if ( !isset( $this->conns[$serverIndex] ) ) {
157 if ( $serverIndex >= $this->numServers ) {
158 throw new MWException( __METHOD__ .
": Invalid server index \"$serverIndex\"" );
161 # Don't keep timing out trying to connect for each call if the DB is down
162 if ( isset( $this->connFailureErrors[$serverIndex] )
163 && ( time() - $this->connFailureTimes[$serverIndex] ) < 60
165 throw $this->connFailureErrors[$serverIndex];
168 if ( $this->serverInfos ) {
170 $info = $this->serverInfos[$serverIndex];
171 $type = $info[
'type'] ??
'mysql';
172 $host = $info[
'host'] ??
'[unknown]';
173 $this->logger->debug( __CLASS__ .
": connecting to $host" );
174 $db = Database::factory(
$type, $info );
178 $lb = MediaWikiServices::getInstance()->getDBLoadBalancer();
180 if ( $lb->getServerType( $lb->getWriterIndex() ) !==
'sqlite' ) {
182 $db = $lb->getConnection( $index, [],
false, $lb::CONN_TRX_AUTOCOMMIT );
186 $db = $lb->getConnection( $index );
190 $this->logger->debug( sprintf(
"Connection %s will be used for SqlBagOStuff", $db ) );
191 $this->conns[$serverIndex] = $db;
194 return $this->conns[$serverIndex];
203 if ( $this->shards > 1 ) {
204 $hash = hexdec( substr( md5( $key ), 0, 8 ) ) & 0x7fffffff;
209 if ( $this->numServers > 1 ) {
211 ArrayUtils::consistentHashSort( $sortedServers, $key );
212 reset( $sortedServers );
213 $serverIndex =
key( $sortedServers );
226 if ( $this->shards > 1 ) {
227 $decimals = strlen( $this->shards - 1 );
229 sprintf(
"%0{$decimals}d", $index );
235 protected function doGet( $key, $flags = 0 ) {
242 $values = $this->
getMulti( [ $key ] );
243 if ( array_key_exists( $key, $values ) ) {
244 $casToken = $values[$key];
245 return $values[$key];
256 $keysByTable[$serverIndex][
$tableName][] = $key;
262 foreach ( $keysByTable
as $serverIndex => $serverKeys ) {
264 $db = $this->
getDB( $serverIndex );
267 [
'keyname',
'value',
'exptime' ],
268 [
'keyname' => $tableKeys ],
273 $db->trxLevel() ? [
'LOCK IN SHARE MODE' ] : []
275 if (
$res ===
false ) {
278 foreach (
$res as $row ) {
279 $row->serverIndex = $serverIndex;
281 $dataRows[$row->keyname] = $row;
290 if ( isset( $dataRows[$key] ) ) {
291 $row = $dataRows[$key];
292 $this->
debug(
"get: retrieved data; expiry time is " . $row->exptime );
295 $db = $this->
getDB( $row->serverIndex );
296 if ( $this->
isExpired( $db, $row->exptime ) ) {
297 $this->
debug(
"get: key has expired" );
299 $values[$key] = $this->
unserialize( $db->decodeBlob( $row->value ) );
305 $this->
debug(
'get: no matching rows' );
314 foreach ( $data
as $key =>
$value ) {
316 $keysByTable[$serverIndex][
$tableName][] = $key;
322 $exptime = (int)$expiry;
324 foreach ( $keysByTable
as $serverIndex => $serverKeys ) {
327 $db = $this->
getDB( $serverIndex );
334 if ( $exptime < 0 ) {
338 if ( $exptime == 0 ) {
342 $encExpiry = $db->timestamp( $exptime );
346 foreach ( $tableKeys
as $key ) {
349 'value' => $db->encodeBlob( $this->
serialize( $data[$key] ) ),
350 'exptime' => $encExpiry,
373 public function set( $key,
$value, $exptime = 0, $flags = 0 ) {
375 if ( ( $flags & self::WRITE_SYNC ) == self::WRITE_SYNC ) {
382 protected function cas( $casToken, $key,
$value, $exptime = 0 ) {
387 $db = $this->
getDB( $serverIndex );
388 $exptime = intval( $exptime );
390 if ( $exptime < 0 ) {
394 if ( $exptime == 0 ) {
398 $encExpiry = $db->timestamp( $exptime );
406 'value' => $db->encodeBlob( $this->serialize(
$value ) ),
407 'exptime' => $encExpiry
411 'value' => $db->encodeBlob( $this->serialize( $casToken ) )
421 return (
bool)$db->affectedRows();
424 public function delete( $key ) {
429 $db = $this->
getDB( $serverIndex );
432 [
'keyname' => $key ],
442 public function incr( $key, $step = 1 ) {
447 $db = $this->
getDB( $serverIndex );
448 $step = intval( $step );
449 $row = $db->selectRow(
451 [
'value',
'exptime' ],
452 [
'keyname' => $key ],
455 if ( $row ===
false ) {
460 $db->delete(
$tableName, [
'keyname' => $key ], __METHOD__ );
461 if ( $this->
isExpired( $db, $row->exptime ) ) {
467 $oldValue = intval( $this->
unserialize( $db->decodeBlob( $row->value ) ) );
468 $newValue = $oldValue + $step;
472 'value' => $db->encodeBlob( $this->serialize( $newValue ) ),
473 'exptime' => $row->exptime
474 ], __METHOD__,
'IGNORE' );
476 if ( $db->affectedRows() == 0 ) {
488 public function merge( $key, callable $callback, $exptime = 0, $attempts = 10, $flags = 0 ) {
489 $ok = $this->
mergeViaCas( $key, $callback, $exptime, $attempts );
490 if ( ( $flags & self::WRITE_SYNC ) == self::WRITE_SYNC ) {
502 $db = $this->
getDB( $serverIndex );
505 [
'exptime' => $db->timestamp( $this->convertExpiry( $expiry ) ) ],
506 [
'keyname' => $key,
'exptime > ' . $db->addQuotes( $db->timestamp( time() ) ) ],
509 if ( $db->affectedRows() == 0 ) {
534 if ( time() > 0x7fffffff ) {
535 return $db->timestamp( 1 << 62 );
537 return $db->timestamp( 0x7fffffff );
542 if ( !$this->purgePeriod || $this->replicaOnly ) {
547 if ( $this->purgePeriod !== 1 && mt_rand( 0, $this->purgePeriod - 1 ) ) {
552 if ( $now > ( $this->lastExpireAll + 1 ) ) {
553 $this->lastExpireAll = $now;
573 $db = $this->
getDB( $serverIndex );
574 $dbTimestamp = $db->timestamp( $timestamp );
575 $totalSeconds =
false;
576 $baseConds = [
'exptime < ' . $db->addQuotes( $dbTimestamp ) ];
581 if ( $maxExpTime !==
false ) {
582 $conds[] =
'exptime >= ' . $db->addQuotes( $maxExpTime );
586 [
'keyname',
'exptime' ],
589 [
'LIMIT' => 100,
'ORDER BY' =>
'exptime' ] );
594 $row =
$rows->current();
595 $minExpTime = $row->exptime;
596 if ( $totalSeconds ===
false ) {
601 $keys[] = $row->keyname;
602 $maxExpTime = $row->exptime;
608 'exptime >= ' . $db->addQuotes( $minExpTime ),
609 'exptime < ' . $db->addQuotes( $dbTimestamp ),
614 if ( $progressCallback ) {
615 if ( intval( $totalSeconds ) === 0 ) {
618 $remainingSeconds =
wfTimestamp( TS_UNIX, $timestamp )
620 if ( $remainingSeconds > $totalSeconds ) {
621 $totalSeconds = $remainingSeconds;
623 $processedSeconds = $totalSeconds - $remainingSeconds;
624 $percent = ( $i + $processedSeconds / $totalSeconds )
625 / $this->shards * 100;
628 + ( $serverIndex / $this->numServers * 100 );
629 call_user_func( $progressCallback, $percent );
651 $db = $this->
getDB( $serverIndex );
674 if ( function_exists(
'gzdeflate' ) ) {
675 return gzdeflate( $serial );
687 if ( function_exists(
'gzinflate' ) ) {
688 Wikimedia\suppressWarnings();
689 $decomp = gzinflate( $serial );
690 Wikimedia\restoreWarnings();
692 if (
false !== $decomp ) {
712 $this->logger->error(
"DBError: {$exception->getMessage()}" );
715 $this->logger->debug( __METHOD__ .
": ignoring connection error" );
718 $this->logger->debug( __METHOD__ .
": ignoring query error" );
733 } elseif ( $db->wasReadOnlyError() ) {
734 if ( $db->trxLevel() && $this->usesMainDB() ) {
742 $this->logger->error(
"DBError: {$exception->getMessage()}" );
745 $this->logger->debug( __METHOD__ .
": ignoring connection error" );
748 $this->logger->debug( __METHOD__ .
": ignoring query error" );
759 unset( $this->conns[$serverIndex] );
761 if ( isset( $this->connFailureTimes[$serverIndex] ) ) {
762 if ( time() - $this->connFailureTimes[$serverIndex] >= 60 ) {
763 unset( $this->connFailureTimes[$serverIndex] );
764 unset( $this->connFailureErrors[$serverIndex] );
766 $this->logger->debug( __METHOD__ .
": Server #$serverIndex already down" );
771 $this->logger->info( __METHOD__ .
": Server #$serverIndex down until " . ( $now + 60 ) );
772 $this->connFailureTimes[$serverIndex] = $now;
773 $this->connFailureErrors[$serverIndex] = $exception;
781 $db = $this->
getDB( $serverIndex );
782 if ( $db->getType() !==
'mysql' ) {
783 throw new MWException( __METHOD__ .
' is not supported on this DB server' );
788 'CREATE TABLE ' . $db->tableName( $this->getTableNameByShard( $i ) ) .
789 ' LIKE ' . $db->tableName(
'objectcache' ),
808 $lb = MediaWikiServices::getInstance()->getDBLoadBalancer();
809 if ( $lb->getServerCount() <= 1 ) {
814 $masterPos = $lb->getMasterPos();
819 $loop =
new WaitConditionLoop(
820 function ()
use ( $lb, $masterPos ) {
821 return $lb->waitForAll( $masterPos, 1 );
827 return ( $loop->invoke() === $loop::CONDITION_REACHED );
837 $trxProfiler = Profiler::instance()->getTransactionProfiler();
838 $oldSilenced = $trxProfiler->setSilenced(
true );
839 return new ScopedCallback(
function ()
use ( $trxProfiler, $oldSilenced ) {
840 $trxProfiler->setSilenced( $oldSilenced );
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
wfTimestampNow()
Convenience function; returns MediaWiki timestamp for the present time.
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
Class representing a cache/ephemeral data store.
convertExpiry( $exptime)
Convert an optionally relative time to an absolute time.
callable[] $busyCallbacks
setLastError( $err)
Set the "last error" registry.
mergeViaCas( $key, $callback, $exptime=0, $attempts=10)
Class to store objects in the database.
getDB( $serverIndex)
Get a connection to the specified database.
string[] $serverTags
(server index => tag/host name)
LoadBalancer null $separateMainLB
createTables()
Create shard tables.
getTableByKey( $key)
Get the server index and table name for a given key.
getMulti(array $keys, $flags=0)
Get an associative array containing the item for each of the keys that have items.
array[] $serverInfos
(server index => server config)
deleteAll()
Delete content of shard tables in every server.
__construct( $params)
Constructor.
getWithToken( $key, &$casToken, $flags=0)
isExpired( $db, $exptime)
changeTTL( $key, $expiry=0)
Reset the TTL on a key if it exists.
handleWriteError(DBError $exception, IDatabase $db=null, $serverIndex)
Handle a DBQueryError which occurred during a write operation.
silenceTransactionProfiler()
Returns a ScopedCallback which resets the silence flag in the transaction profiler when it is destroy...
array $connFailureTimes
UNIX timestamps.
array $connFailureErrors
Exceptions.
deleteObjectsExpiringBefore( $timestamp, $progressCallback=false)
Delete objects from the database which expire before a certain date.
cas( $casToken, $key, $value, $exptime=0)
Check and set an item.
merge( $key, callable $callback, $exptime=0, $attempts=10, $flags=0)
Merge changes into the existing cache value (possibly creating a new one)
serialize(&$data)
Serialize an object and, if possible, compress the representation.
markServerDown(DBError $exception, $serverIndex)
Mark a server down due to a DBConnectionError exception.
unserialize( $serial)
Unserialize and, if necessary, decompress an object.
getTableNameByShard( $index)
Get the table name for a given shard index.
incr( $key, $step=1)
Increase stored value of $key by $value while preserving its TTL.
handleReadError(DBError $exception, $serverIndex)
Handle a DBError which occurred during a read operation.
setMulti(array $data, $expiry=0)
Batch insertion.
We use the convention $dbr for read and $dbw for write to help you keep track of whether the database object is a the world will explode Or to be a subsequent write query which succeeded on the master may fail when replicated to the slave due to a unique key collision Replication on the slave will stop and it may take hours to repair the database and get it back online Setting read_only in my cnf on the slave will avoid this but given the dire we prefer to have as many checks as possible We provide a but the wrapper functions like please read the documentation for tableName() and addQuotes(). You will need both of them. ------------------------------------------------------------------------ Basic query optimisation ------------------------------------------------------------------------ MediaWiki developers who need to write DB queries should have some understanding of databases and the performance issues associated with them. Patches containing unacceptably slow features will not be accepted. Unindexed queries are generally not welcome in MediaWiki
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
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
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 $rows
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. 'ImgAuthModifyHeaders':Executed just before a file is streamed to a user via img_auth.php, allowing headers to be modified beforehand. $title:LinkTarget object & $headers:HTTP headers(name=> value, names are case insensitive). Two headers get special handling:If-Modified-Since(value must be a valid HTTP date) and Range(must be of the form "bytes=(\d*-\d*)") will be honored when streaming the file. '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 'ImportHandleUnknownUser':When a user doesn 't exist locally, this hook is called to give extensions an opportunity to auto-create it. If the auto-creation is successful, return false. $name:User name '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 since 1.16! 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 since 1.28! 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
either a unescaped string or a HtmlArmor object after in associative array form externallinks including delete and has completed for all link tables whether this was an auto creation use $formDescriptor instead 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 key
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 noclasses & $ret
returning false will NOT prevent logging $e
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
const QOS_SYNCWRITES_NONE
The wiki should then use memcached to cache various data To use multiple just add more items to the array To increase the weight of a make its entry a array("192.168.0.1:11211", 2))