MediaWiki REL1_28
LBFactoryTest.php
Go to the documentation of this file.
1<?php
27
31 public function testGetLBFactoryClass( $expected, $deprecated ) {
32 $mockDB = $this->getMockBuilder( 'DatabaseMysql' )
33 ->disableOriginalConstructor()
34 ->getMock();
35
36 $config = [
37 'class' => $deprecated,
38 'connection' => $mockDB,
39 # Various other parameters required:
40 'sectionsByDB' => [],
41 'sectionLoads' => [],
42 'serverTemplate' => [],
43 ];
44
45 $this->hideDeprecated( '$wgLBFactoryConf must be updated. See RELEASE-NOTES for details' );
47
48 $this->assertEquals( $expected, $result );
49 }
50
51 public function getLBFactoryClassProvider() {
52 return [
53 # Format: new class, old class
54 [ 'LBFactorySimple', 'LBFactory_Simple' ],
55 [ 'LBFactorySingle', 'LBFactory_Single' ],
56 [ 'LBFactoryMulti', 'LBFactory_Multi' ],
57 ];
58 }
59
60 public function testLBFactorySimpleServer() {
62
63 $servers = [
64 [
65 'host' => $wgDBserver,
66 'dbname' => $wgDBname,
67 'user' => $wgDBuser,
68 'password' => $wgDBpassword,
69 'type' => $wgDBtype,
70 'load' => 0,
71 'flags' => DBO_TRX // REPEATABLE-READ for consistency
72 ],
73 ];
74
75 $factory = new LBFactorySimple( [ 'servers' => $servers ] );
76 $lb = $factory->getMainLB();
77
78 $dbw = $lb->getConnection( DB_MASTER );
79 $this->assertTrue( $dbw->getLBInfo( 'master' ), 'master shows as master' );
80
81 $dbr = $lb->getConnection( DB_SLAVE );
82 $this->assertTrue( $dbr->getLBInfo( 'master' ), 'DB_SLAVE also gets the master' );
83
84 $factory->shutdown();
85 $lb->closeAll();
86 }
87
88 public function testLBFactorySimpleServers() {
90
91 $servers = [
92 [ // master
93 'host' => $wgDBserver,
94 'dbname' => $wgDBname,
95 'user' => $wgDBuser,
96 'password' => $wgDBpassword,
97 'type' => $wgDBtype,
98 'load' => 0,
99 'flags' => DBO_TRX // REPEATABLE-READ for consistency
100 ],
101 [ // emulated slave
102 'host' => $wgDBserver,
103 'dbname' => $wgDBname,
104 'user' => $wgDBuser,
105 'password' => $wgDBpassword,
106 'type' => $wgDBtype,
107 'load' => 100,
108 'flags' => DBO_TRX // REPEATABLE-READ for consistency
109 ]
110 ];
111
112 $factory = new LBFactorySimple( [
113 'servers' => $servers,
114 'loadMonitorClass' => 'LoadMonitorNull'
115 ] );
116 $lb = $factory->getMainLB();
117
118 $dbw = $lb->getConnection( DB_MASTER );
119 $this->assertTrue( $dbw->getLBInfo( 'master' ), 'master shows as master' );
120 $this->assertEquals(
121 $wgDBserver, $dbw->getLBInfo( 'clusterMasterHost' ), 'cluster master set' );
122
123 $dbr = $lb->getConnection( DB_SLAVE );
124 $this->assertTrue( $dbr->getLBInfo( 'replica' ), 'slave shows as slave' );
125 $this->assertEquals(
126 $wgDBserver, $dbr->getLBInfo( 'clusterMasterHost' ), 'cluster master set' );
127
128 $factory->shutdown();
129 $lb->closeAll();
130 }
131
132 public function testLBFactoryMulti() {
134
135 $factory = new LBFactoryMulti( [
136 'sectionsByDB' => [],
137 'sectionLoads' => [
138 'DEFAULT' => [
139 'test-db1' => 0,
140 'test-db2' => 100,
141 ],
142 ],
143 'serverTemplate' => [
144 'dbname' => $wgDBname,
145 'user' => $wgDBuser,
146 'password' => $wgDBpassword,
147 'type' => $wgDBtype,
148 'flags' => DBO_DEFAULT
149 ],
150 'hostsByName' => [
151 'test-db1' => $wgDBserver,
152 'test-db2' => $wgDBserver
153 ],
154 'loadMonitorClass' => 'LoadMonitorNull'
155 ] );
156 $lb = $factory->getMainLB();
157
158 $dbw = $lb->getConnection( DB_MASTER );
159 $this->assertTrue( $dbw->getLBInfo( 'master' ), 'master shows as master' );
160
161 $dbr = $lb->getConnection( DB_SLAVE );
162 $this->assertTrue( $dbr->getLBInfo( 'replica' ), 'slave shows as slave' );
163
164 $factory->shutdown();
165 $lb->closeAll();
166 }
167
168 public function testChronologyProtector() {
169 // (a) First HTTP request
170 $mPos = new MySQLMasterPos( 'db1034-bin.000976', '843431247' );
171
172 $now = microtime( true );
173 $mockDB = $this->getMockBuilder( 'DatabaseMysql' )
174 ->disableOriginalConstructor()
175 ->getMock();
176 $mockDB->method( 'writesOrCallbacksPending' )->willReturn( true );
177 $mockDB->method( 'lastDoneWrites' )->willReturn( $now );
178 $mockDB->method( 'getMasterPos' )->willReturn( $mPos );
179
180 $lb = $this->getMockBuilder( 'LoadBalancer' )
181 ->disableOriginalConstructor()
182 ->getMock();
183 $lb->method( 'getConnection' )->willReturn( $mockDB );
184 $lb->method( 'getServerCount' )->willReturn( 2 );
185 $lb->method( 'parentInfo' )->willReturn( [ 'id' => "main-DEFAULT" ] );
186 $lb->method( 'getAnyOpenConnection' )->willReturn( $mockDB );
187 $lb->method( 'hasOrMadeRecentMasterChanges' )->will( $this->returnCallback(
188 function () use ( $mockDB ) {
189 $p = 0;
190 $p |= call_user_func( [ $mockDB, 'writesOrCallbacksPending' ] );
191 $p |= call_user_func( [ $mockDB, 'lastDoneWrites' ] );
192
193 return (bool)$p;
194 }
195 ) );
196 $lb->method( 'getMasterPos' )->willReturn( $mPos );
197
198 $bag = new HashBagOStuff();
199 $cp = new ChronologyProtector(
200 $bag,
201 [
202 'ip' => '127.0.0.1',
203 'agent' => "Totally-Not-FireFox"
204 ]
205 );
206
207 $mockDB->expects( $this->exactly( 2 ) )->method( 'writesOrCallbacksPending' );
208 $mockDB->expects( $this->exactly( 2 ) )->method( 'lastDoneWrites' );
209
210 // Nothing to wait for
211 $cp->initLB( $lb );
212 // Record in stash
213 $cp->shutdownLB( $lb );
214 $cp->shutdown();
215
216 // (b) Second HTTP request
217 $cp = new ChronologyProtector(
218 $bag,
219 [
220 'ip' => '127.0.0.1',
221 'agent' => "Totally-Not-FireFox"
222 ]
223 );
224
225 $lb->expects( $this->once() )
226 ->method( 'waitFor' )->with( $this->equalTo( $mPos ) );
227
228 // Wait
229 $cp->initLB( $lb );
230 // Record in stash
231 $cp->shutdownLB( $lb );
232 $cp->shutdown();
233 }
234
235 private function newLBFactoryMulti( array $baseOverride = [], array $serverOverride = [] ) {
237
238 return new LBFactoryMulti( $baseOverride + [
239 'sectionsByDB' => [],
240 'sectionLoads' => [
241 'DEFAULT' => [
242 'test-db1' => 1,
243 ],
244 ],
245 'serverTemplate' => $serverOverride + [
246 'dbname' => $wgDBname,
247 'user' => $wgDBuser,
248 'password' => $wgDBpassword,
249 'type' => $wgDBtype,
250 'flags' => DBO_DEFAULT
251 ],
252 'hostsByName' => [
253 'test-db1' => $wgDBserver,
254 ],
255 'loadMonitorClass' => 'LoadMonitorNull',
256 'localDomain' => wfWikiID()
257 ] );
258 }
259
260 public function testNiceDomains() {
262
263 $factory = $this->newLBFactoryMulti();
264 $lb = $factory->getMainLB();
265
266 $db = $lb->getConnectionRef( DB_MASTER );
267 $this->assertEquals(
268 $wgDBname,
270 );
271 unset( $db );
272
274 $db = $lb->getConnection( DB_MASTER, [], '' );
275 $lb->reuseConnection( $db ); // don't care
276
277 $this->assertEquals(
278 '',
280 );
281
282 $this->assertEquals(
283 $db->addIdentifierQuotes( 'page' ),
284 $db->tableName( 'page' ),
285 "Correct full table name"
286 );
287
288 $this->assertEquals(
290 $db->tableName( "$wgDBname.page" ),
291 "Correct full table name"
292 );
293
294 $this->assertEquals(
295 $db->addIdentifierQuotes( 'nice_db' ) . '.' . $db->addIdentifierQuotes( 'page' ),
296 $db->tableName( 'nice_db.page' ),
297 "Correct full table name"
298 );
299
300 $factory->setDomainPrefix( 'my_' );
301 $this->assertEquals(
302 '',
304 );
305 $this->assertEquals(
306 $db->addIdentifierQuotes( 'my_page' ),
307 $db->tableName( 'page' ),
308 "Correct full table name"
309 );
310 $this->assertEquals(
311 $db->addIdentifierQuotes( 'other_nice_db' ) . '.' . $db->addIdentifierQuotes( 'page' ),
312 $db->tableName( 'other_nice_db.page' ),
313 "Correct full table name"
314 );
315
316 $factory->closeAll();
317 $factory->destroy();
318 }
319
320 public function testTrickyDomain() {
321 $dbname = 'unittest-domain';
322 $factory = $this->newLBFactoryMulti(
323 [ 'localDomain' => $dbname ], [ 'dbname' => $dbname ] );
324 $lb = $factory->getMainLB();
326 $db = $lb->getConnection( DB_MASTER, [], '' );
327 $lb->reuseConnection( $db ); // don't care
328
329 $this->assertEquals(
330 '',
332 );
333
334 $this->assertEquals(
335 $db->addIdentifierQuotes( 'page' ),
336 $db->tableName( 'page' ),
337 "Correct full table name"
338 );
339
340 $this->assertEquals(
341 $db->addIdentifierQuotes( $dbname ) . '.' . $db->addIdentifierQuotes( 'page' ),
342 $db->tableName( "$dbname.page" ),
343 "Correct full table name"
344 );
345
346 $this->assertEquals(
347 $db->addIdentifierQuotes( 'nice_db' ) . '.' . $db->addIdentifierQuotes( 'page' ),
348 $db->tableName( 'nice_db.page' ),
349 "Correct full table name"
350 );
351
352 $factory->setDomainPrefix( 'my_' );
353
354 $this->assertEquals(
355 $db->addIdentifierQuotes( 'my_page' ),
356 $db->tableName( 'page' ),
357 "Correct full table name"
358 );
359 $this->assertEquals(
360 $db->addIdentifierQuotes( 'other_nice_db' ) . '.' . $db->addIdentifierQuotes( 'page' ),
361 $db->tableName( 'other_nice_db.page' ),
362 "Correct full table name"
363 );
364
365 \MediaWiki\suppressWarnings();
366 $this->assertFalse( $db->selectDB( 'garbage-db' ) );
367 \MediaWiki\restoreWarnings();
368
369 $this->assertEquals(
370 $db->addIdentifierQuotes( 'garbage-db' ) . '.' . $db->addIdentifierQuotes( 'page' ),
371 $db->tableName( 'garbage-db.page' ),
372 "Correct full table name"
373 );
374
375 $factory->closeAll();
376 $factory->destroy();
377 }
378}
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
$wgDBuser
Database username.
$wgDBtype
Database type.
$wgDBserver
Database host name or IP address.
$wgDBpassword
Database user's password.
const DB_SLAVE
Definition Defines.php:28
wfWikiID()
Get an ASCII string identifying this wiki This is used as a prefix in memcached keys.
Class for ensuring a consistent ordering of events as seen by the user, despite replication.
getDomainID()
Definition Database.php:621
addIdentifierQuotes( $s)
Quotes an identifier using backticks or "double quotes" depending on the database type.
selectDB( $db)
Change the current database.
tableName( $name, $format='quoted')
Format a table name ready for use in constructing an SQL query.
Simple store for keeping values in an associative array for the current process.
A multi-database, multi-master factory for Wikimedia and similar installations.
A simple single-master LBFactory that gets its configuration from the b/c globals.
newLBFactoryMulti(array $baseOverride=[], array $serverOverride=[])
testGetLBFactoryClass( $expected, $deprecated)
getLBFactoryClassProvider
static getLBFactoryClass(array $config)
Returns the LBFactory class to use and the load balancer configuration.
Database $db
Primary database.
hideDeprecated( $function)
Don't throw a warning if $function is deprecated and called later.
DBMasterPos class for MySQL/MariaDB.
when a variable name is used in a it is silently declared as a new local masking the global
Definition design.txt:95
the array() calling protocol came about after MediaWiki 1.4rc1.
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
Definition hooks.txt:1937
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition injection.txt:37
controlled by $wgMainCacheType controlled by $wgParserCacheType controlled by $wgMessageCacheType If you set CACHE_NONE to one of the three control default value for MediaWiki still create a but requests to it are no ops and we always fall through to the database If the cache daemon can t be it should also disable itself fairly smoothly By $wgMemc is used but when it is $parserMemc or $messageMemc this is mentioned $wgDBname
const DB_MASTER
Definition defines.php:23
const DBO_DEFAULT
Definition defines.php:10
const DBO_TRX
Definition defines.php:9