3 * Holds tests for LBFactory abstract MediaWiki class.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
21 * @author Antoine Musso
22 * @copyright © 2013 Antoine Musso
23 * @copyright © 2013 Wikimedia Foundation Inc.
26 use Wikimedia\Rdbms\LBFactorySimple
;
27 use Wikimedia\Rdbms\LBFactoryMulti
;
28 use Wikimedia\Rdbms\LoadBalancer
;
29 use Wikimedia\Rdbms\ChronologyProtector
;
30 use Wikimedia\Rdbms\DatabaseMysqli
;
31 use Wikimedia\Rdbms\MySQLMasterPos
;
32 use Wikimedia\Rdbms\DatabaseDomain
;
36 * @covers \Wikimedia\Rdbms\LBFactorySimple
37 * @covers \Wikimedia\Rdbms\LBFactoryMulti
39 class LBFactoryTest
extends MediaWikiTestCase
{
42 * @covers MWLBFactory::getLBFactoryClass
43 * @dataProvider getLBFactoryClassProvider
45 public function testGetLBFactoryClass( $expected, $deprecated ) {
46 $mockDB = $this->getMockBuilder( DatabaseMysqli
::class )
47 ->disableOriginalConstructor()
51 'class' => $deprecated,
52 'connection' => $mockDB,
53 # Various other parameters required:
56 'serverTemplate' => [],
59 $this->hideDeprecated( '$wgLBFactoryConf must be updated. See RELEASE-NOTES for details' );
60 $result = MWLBFactory
::getLBFactoryClass( $config );
62 $this->assertEquals( $expected, $result );
65 public function getLBFactoryClassProvider() {
67 # Format: new class, old class
68 [ Wikimedia\Rdbms\LBFactorySimple
::class, 'LBFactory_Simple' ],
69 [ Wikimedia\Rdbms\LBFactorySingle
::class, 'LBFactory_Single' ],
70 [ Wikimedia\Rdbms\LBFactoryMulti
::class, 'LBFactory_Multi' ],
71 [ Wikimedia\Rdbms\LBFactorySimple
::class, 'LBFactorySimple' ],
72 [ Wikimedia\Rdbms\LBFactorySingle
::class, 'LBFactorySingle' ],
73 [ Wikimedia\Rdbms\LBFactoryMulti
::class, 'LBFactoryMulti' ],
78 * @covers LBFactory::getLocalDomainID()
79 * @covers LBFactory::resolveDomainID()
81 public function testLBFactorySimpleServer() {
82 global $wgDBserver, $wgDBname, $wgDBuser, $wgDBpassword, $wgDBtype, $wgSQLiteDataDir;
86 'host' => $wgDBserver,
87 'dbname' => $wgDBname,
89 'password' => $wgDBpassword,
91 'dbDirectory' => $wgSQLiteDataDir,
93 'flags' => DBO_TRX
// REPEATABLE-READ for consistency
97 $factory = new LBFactorySimple( [ 'servers' => $servers ] );
98 $lb = $factory->getMainLB();
100 $dbw = $lb->getConnection( DB_MASTER
);
101 $this->assertTrue( $dbw->getLBInfo( 'master' ), 'master shows as master' );
103 $dbr = $lb->getConnection( DB_REPLICA
);
104 $this->assertTrue( $dbr->getLBInfo( 'master' ), 'DB_REPLICA also gets the master' );
106 $this->assertSame( 'my_test_wiki', $factory->resolveDomainID( 'my_test_wiki' ) );
107 $this->assertSame( $factory->getLocalDomainID(), $factory->resolveDomainID( false ) );
109 $factory->shutdown();
113 public function testLBFactorySimpleServers() {
114 global $wgDBserver, $wgDBname, $wgDBuser, $wgDBpassword, $wgDBtype, $wgSQLiteDataDir;
118 'host' => $wgDBserver,
119 'dbname' => $wgDBname,
121 'password' => $wgDBpassword,
123 'dbDirectory' => $wgSQLiteDataDir,
125 'flags' => DBO_TRX
// REPEATABLE-READ for consistency
128 'host' => $wgDBserver,
129 'dbname' => $wgDBname,
131 'password' => $wgDBpassword,
133 'dbDirectory' => $wgSQLiteDataDir,
135 'flags' => DBO_TRX
// REPEATABLE-READ for consistency
139 $factory = new LBFactorySimple( [
140 'servers' => $servers,
141 'loadMonitorClass' => LoadMonitorNull
::class
143 $lb = $factory->getMainLB();
145 $dbw = $lb->getConnection( DB_MASTER
);
146 $this->assertTrue( $dbw->getLBInfo( 'master' ), 'master shows as master' );
148 ( $wgDBserver != '' ) ?
$wgDBserver : 'localhost',
149 $dbw->getLBInfo( 'clusterMasterHost' ),
150 'cluster master set' );
152 $dbr = $lb->getConnection( DB_REPLICA
);
153 $this->assertTrue( $dbr->getLBInfo( 'replica' ), 'slave shows as slave' );
155 ( $wgDBserver != '' ) ?
$wgDBserver : 'localhost',
156 $dbr->getLBInfo( 'clusterMasterHost' ),
157 'cluster master set' );
159 $factory->shutdown();
163 public function testLBFactoryMultiConns() {
164 $factory = $this->newLBFactoryMultiLBs();
166 $dbw = $factory->getMainLB()->getConnection( DB_MASTER
);
167 $this->assertTrue( $dbw->getLBInfo( 'master' ), 'master shows as master' );
169 $dbr = $factory->getMainLB()->getConnection( DB_REPLICA
);
170 $this->assertTrue( $dbr->getLBInfo( 'replica' ), 'slave shows as slave' );
172 // Destructor should trigger without round stage errors
176 public function testLBFactoryMultiRoundCallbacks() {
178 $countLBsFunc = function ( LBFactoryMulti
$factory ) {
180 $factory->forEachLB( function () use ( &$count ) {
187 $factory = $this->newLBFactoryMultiLBs();
188 $this->assertEquals( 0, $countLBsFunc( $factory ) );
189 $dbw = $factory->getMainLB()->getConnection( DB_MASTER
);
190 $this->assertEquals( 1, $countLBsFunc( $factory ) );
191 // Test that LoadBalancer instances made during pre-commit callbacks in do not
192 // throw DBTransactionError due to transaction ROUND_* stages being mismatched.
193 $factory->beginMasterChanges( __METHOD__
);
194 $dbw->onTransactionPreCommitOrIdle( function () use ( $factory, &$called ) {
196 // Trigger s1 LoadBalancer instantiation during "finalize" stage.
197 // There is no s1wiki DB to select so it is not in getConnection(),
198 // but this fools getMainLB() at least.
199 $factory->getMainLB( 's1wiki' )->getConnection( DB_MASTER
);
201 $factory->commitMasterChanges( __METHOD__
);
202 $this->assertEquals( 1, $called );
203 $this->assertEquals( 2, $countLBsFunc( $factory ) );
204 $factory->shutdown();
205 $factory->closeAll();
208 $factory = $this->newLBFactoryMultiLBs();
209 $this->assertEquals( 0, $countLBsFunc( $factory ) );
210 $dbw = $factory->getMainLB()->getConnection( DB_MASTER
);
211 $this->assertEquals( 1, $countLBsFunc( $factory ) );
212 // Test that LoadBalancer instances made during pre-commit callbacks in do not
213 // throw DBTransactionError due to transaction ROUND_* stages being mismatched.hrow
214 // DBTransactionError due to transaction ROUND_* stages being mismatched.
215 $factory->beginMasterChanges( __METHOD__
);
216 $dbw->query( "SELECT 1 as t", __METHOD__
);
217 $dbw->onTransactionResolution( function () use ( $factory, &$called ) {
219 // Trigger s1 LoadBalancer instantiation during "finalize" stage.
220 // There is no s1wiki DB to select so it is not in getConnection(),
221 // but this fools getMainLB() at least.
222 $factory->getMainLB( 's1wiki' )->getConnection( DB_MASTER
);
224 $factory->commitMasterChanges( __METHOD__
);
225 $this->assertEquals( 1, $called );
226 $this->assertEquals( 2, $countLBsFunc( $factory ) );
227 $factory->shutdown();
228 $factory->closeAll();
230 $factory = $this->newLBFactoryMultiLBs();
231 $dbw = $factory->getMainLB()->getConnection( DB_MASTER
);
232 // DBTransactionError should not be thrown
234 $dbw->onTransactionPreCommitOrIdle( function () use ( &$ran ) {
237 $factory->commitAll( __METHOD__
);
238 $this->assertEquals( 1, $ran );
240 $factory->shutdown();
241 $factory->closeAll();
244 private function newLBFactoryMultiLBs() {
245 global $wgDBserver, $wgDBname, $wgDBuser, $wgDBpassword, $wgDBtype, $wgSQLiteDataDir;
247 return new LBFactoryMulti( [
261 'serverTemplate' => [
262 'dbname' => $wgDBname,
264 'password' => $wgDBpassword,
266 'dbDirectory' => $wgSQLiteDataDir,
267 'flags' => DBO_DEFAULT
270 'test-db1' => $wgDBserver,
271 'test-db2' => $wgDBserver,
272 'test-db3' => $wgDBserver,
273 'test-db4' => $wgDBserver
275 'loadMonitorClass' => LoadMonitorNull
::class
280 * @covers \Wikimedia\Rdbms\ChronologyProtector
282 public function testChronologyProtector() {
283 $now = microtime( true );
285 // (a) First HTTP request
286 $m1Pos = new MySQLMasterPos( 'db1034-bin.000976/843431247', $now );
287 $m2Pos = new MySQLMasterPos( 'db1064-bin.002400/794074907', $now );
290 $mockDB1 = $this->getMockBuilder( DatabaseMysqli
::class )
291 ->disableOriginalConstructor()
293 $mockDB1->method( 'writesOrCallbacksPending' )->willReturn( true );
294 $mockDB1->method( 'lastDoneWrites' )->willReturn( $now );
295 $mockDB1->method( 'getMasterPos' )->willReturn( $m1Pos );
296 // Load balancer for master DB 1
297 $lb1 = $this->getMockBuilder( LoadBalancer
::class )
298 ->disableOriginalConstructor()
300 $lb1->method( 'getConnection' )->willReturn( $mockDB1 );
301 $lb1->method( 'getServerCount' )->willReturn( 2 );
302 $lb1->method( 'getAnyOpenConnection' )->willReturn( $mockDB1 );
303 $lb1->method( 'hasOrMadeRecentMasterChanges' )->will( $this->returnCallback(
304 function () use ( $mockDB1 ) {
306 $p |
= call_user_func( [ $mockDB1, 'writesOrCallbacksPending' ] );
307 $p |
= call_user_func( [ $mockDB1, 'lastDoneWrites' ] );
312 $lb1->method( 'getMasterPos' )->willReturn( $m1Pos );
313 $lb1->method( 'getServerName' )->with( 0 )->willReturn( 'master1' );
315 $mockDB2 = $this->getMockBuilder( DatabaseMysqli
::class )
316 ->disableOriginalConstructor()
318 $mockDB2->method( 'writesOrCallbacksPending' )->willReturn( true );
319 $mockDB2->method( 'lastDoneWrites' )->willReturn( $now );
320 $mockDB2->method( 'getMasterPos' )->willReturn( $m2Pos );
321 // Load balancer for master DB 2
322 $lb2 = $this->getMockBuilder( LoadBalancer
::class )
323 ->disableOriginalConstructor()
325 $lb2->method( 'getConnection' )->willReturn( $mockDB2 );
326 $lb2->method( 'getServerCount' )->willReturn( 2 );
327 $lb2->method( 'getAnyOpenConnection' )->willReturn( $mockDB2 );
328 $lb2->method( 'hasOrMadeRecentMasterChanges' )->will( $this->returnCallback(
329 function () use ( $mockDB2 ) {
331 $p |
= call_user_func( [ $mockDB2, 'writesOrCallbacksPending' ] );
332 $p |
= call_user_func( [ $mockDB2, 'lastDoneWrites' ] );
337 $lb2->method( 'getMasterPos' )->willReturn( $m2Pos );
338 $lb2->method( 'getServerName' )->with( 0 )->willReturn( 'master2' );
340 $bag = new HashBagOStuff();
341 $cp = new ChronologyProtector(
345 'agent' => "Totally-Not-FireFox"
349 $mockDB1->expects( $this->exactly( 1 ) )->method( 'writesOrCallbacksPending' );
350 $mockDB1->expects( $this->exactly( 1 ) )->method( 'lastDoneWrites' );
351 $mockDB2->expects( $this->exactly( 1 ) )->method( 'writesOrCallbacksPending' );
352 $mockDB2->expects( $this->exactly( 1 ) )->method( 'lastDoneWrites' );
354 // Nothing to wait for on first HTTP request start
357 // Record positions in stash on first HTTP request end
358 $cp->shutdownLB( $lb1 );
359 $cp->shutdownLB( $lb2 );
361 $cp->shutdown( null, 'sync', $cpIndex );
363 $this->assertEquals( 1, $cpIndex, "CP write index set" );
365 // (b) Second HTTP request
367 // Load balancer for master DB 1
368 $lb1 = $this->getMockBuilder( LoadBalancer
::class )
369 ->disableOriginalConstructor()
371 $lb1->method( 'getServerCount' )->willReturn( 2 );
372 $lb1->method( 'getServerName' )->with( 0 )->willReturn( 'master1' );
373 $lb1->expects( $this->once() )
374 ->method( 'waitFor' )->with( $this->equalTo( $m1Pos ) );
375 // Load balancer for master DB 2
376 $lb2 = $this->getMockBuilder( LoadBalancer
::class )
377 ->disableOriginalConstructor()
379 $lb2->method( 'getServerCount' )->willReturn( 2 );
380 $lb2->method( 'getServerName' )->with( 0 )->willReturn( 'master2' );
381 $lb2->expects( $this->once() )
382 ->method( 'waitFor' )->with( $this->equalTo( $m2Pos ) );
384 $cp = new ChronologyProtector(
388 'agent' => "Totally-Not-FireFox"
393 // Wait for last positions to be reached on second HTTP request start
396 // Shutdown (nothing to record)
397 $cp->shutdownLB( $lb1 );
398 $cp->shutdownLB( $lb2 );
400 $cp->shutdown( null, 'sync', $cpIndex );
402 $this->assertEquals( null, $cpIndex, "CP write index retained" );
404 $this->assertEquals( '45e93a9c215c031d38b7c42d8e4700ca', $cp->getClientId() );
407 private function newLBFactoryMulti( array $baseOverride = [], array $serverOverride = [] ) {
408 global $wgDBserver, $wgDBuser, $wgDBpassword, $wgDBname, $wgDBprefix, $wgDBtype;
409 global $wgSQLiteDataDir;
411 return new LBFactoryMulti( $baseOverride +
[
412 'sectionsByDB' => [],
418 'serverTemplate' => $serverOverride +
[
419 'dbname' => $wgDBname,
420 'tablePrefix' => $wgDBprefix,
422 'password' => $wgDBpassword,
424 'dbDirectory' => $wgSQLiteDataDir,
425 'flags' => DBO_DEFAULT
428 'test-db1' => $wgDBserver,
430 'loadMonitorClass' => LoadMonitorNull
::class,
431 'localDomain' => new DatabaseDomain( $wgDBname, null, $wgDBprefix ),
432 'agent' => 'MW-UNIT-TESTS'
436 public function testNiceDomains() {
439 if ( wfGetDB( DB_MASTER
)->databasesAreIndependent() ) {
440 self
::markTestSkipped( "Skipping tests about selecting DBs: not applicable" );
444 $factory = $this->newLBFactoryMulti(
448 $lb = $factory->getMainLB();
450 $db = $lb->getConnectionRef( DB_MASTER
);
457 /** @var Database $db */
458 $db = $lb->getConnection( DB_MASTER
, [], '' );
463 'Null domain ID handle used'
468 'Null domain ID handle used'
473 'Main domain ID handle used; prefix is empty though'
476 $this->quoteTable( $db, 'page' ),
477 $db->tableName( 'page' ),
478 "Correct full table name"
481 $this->quoteTable( $db, $wgDBname ) . '.' . $this->quoteTable( $db, 'page' ),
482 $db->tableName( "$wgDBname.page" ),
483 "Correct full table name"
486 $this->quoteTable( $db, 'nice_db' ) . '.' . $this->quoteTable( $db, 'page' ),
487 $db->tableName( 'nice_db.page' ),
488 "Correct full table name"
491 $lb->reuseConnection( $db ); // don't care
493 $db = $lb->getConnection( DB_MASTER
); // local domain connection
494 $factory->setDomainPrefix( 'my_' );
496 $this->assertEquals( $wgDBname, $db->getDBname() );
502 $this->quoteTable( $db, 'my_page' ),
503 $db->tableName( 'page' ),
504 "Correct full table name"
507 $this->quoteTable( $db, 'other_nice_db' ) . '.' . $this->quoteTable( $db, 'page' ),
508 $db->tableName( 'other_nice_db.page' ),
509 "Correct full table name"
512 $factory->closeAll();
516 public function testTrickyDomain() {
519 if ( wfGetDB( DB_MASTER
)->databasesAreIndependent() ) {
520 self
::markTestSkipped( "Skipping tests about selecting DBs: not applicable" );
524 $dbname = 'unittest-domain'; // explodes if DB is selected
525 $factory = $this->newLBFactoryMulti(
526 [ 'localDomain' => ( new DatabaseDomain( $dbname, null, '' ) )->getId() ],
528 'dbName' => 'do_not_select_me' // explodes if DB is selected
531 $lb = $factory->getMainLB();
532 /** @var Database $db */
533 $db = $lb->getConnection( DB_MASTER
, [], '' );
535 $this->assertEquals( '', $db->getDomainID(), "Null domain used" );
538 $this->quoteTable( $db, 'page' ),
539 $db->tableName( 'page' ),
540 "Correct full table name"
544 $this->quoteTable( $db, $dbname ) . '.' . $this->quoteTable( $db, 'page' ),
545 $db->tableName( "$dbname.page" ),
546 "Correct full table name"
550 $this->quoteTable( $db, 'nice_db' ) . '.' . $this->quoteTable( $db, 'page' ),
551 $db->tableName( 'nice_db.page' ),
552 "Correct full table name"
555 $lb->reuseConnection( $db ); // don't care
557 $factory->setDomainPrefix( 'my_' );
558 $db = $lb->getConnection( DB_MASTER
, [], "$wgDBname-my_" );
561 $this->quoteTable( $db, 'my_page' ),
562 $db->tableName( 'page' ),
563 "Correct full table name"
566 $this->quoteTable( $db, 'other_nice_db' ) . '.' . $this->quoteTable( $db, 'page' ),
567 $db->tableName( 'other_nice_db.page' ),
568 "Correct full table name"
571 $this->quoteTable( $db, 'garbage-db' ) . '.' . $this->quoteTable( $db, 'page' ),
572 $db->tableName( 'garbage-db.page' ),
573 "Correct full table name"
576 $lb->reuseConnection( $db ); // don't care
578 $factory->closeAll();
582 public function testInvalidSelectDB() {
583 // FIXME: fails under sqlite
584 $this->markTestSkippedIfDbType( 'sqlite' );
585 $dbname = 'unittest-domain'; // explodes if DB is selected
586 $factory = $this->newLBFactoryMulti(
587 [ 'localDomain' => ( new DatabaseDomain( $dbname, null, '' ) )->getId() ],
589 'dbName' => 'do_not_select_me' // explodes if DB is selected
592 $lb = $factory->getMainLB();
593 /** @var Database $db */
594 $db = $lb->getConnection( DB_MASTER
, [], '' );
596 if ( $db->getType() === 'sqlite' ) {
597 $this->assertFalse( $db->selectDB( 'garbage-db' ) );
598 } elseif ( $db->databasesAreIndependent() ) {
601 $db->selectDB( 'garbage-db' );
602 } catch ( \Wikimedia\Rdbms\DBConnectionError
$e ) {
605 $this->assertInstanceOf( \Wikimedia\Rdbms\DBConnectionError
::class, $e );
606 $this->assertFalse( $db->isOpen() );
608 \Wikimedia\
suppressWarnings();
609 $this->assertFalse( $db->selectDB( 'garbage-db' ) );
610 \Wikimedia\restoreWarnings
();
614 private function quoteTable( Database
$db, $table ) {
615 if ( $db->getType() === 'sqlite' ) {
618 return $db->addIdentifierQuotes( $table );
623 * @covers \Wikimedia\Rdbms\LBFactory::makeCookieValueFromCPIndex()
624 * @covers \Wikimedia\Rdbms\LBFactory::getCPInfoFromCookieValue()
626 public function testCPPosIndexCookieValues() {
628 $agentId = md5( 'Ramsey\'s Loyal Presa Canario' );
630 $lbFactory = $this->newLBFactoryMulti();
632 '3@542#c47dcfb0566e7d7bc110a6128a45c93a',
633 LBFactory
::makeCookieValueFromCPIndex( 3, 542, $agentId )
636 $lbFactory = $this->newLBFactoryMulti();
637 $lbFactory->setRequestInfo( [ 'IPAddress' => '10.64.24.52', 'UserAgent' => 'meow' ] );
639 '1@542#c47dcfb0566e7d7bc110a6128a45c93a',
640 LBFactory
::makeCookieValueFromCPIndex( 1, 542, $agentId )
645 LBFactory
::getCPInfoFromCookieValue( "5#$agentId", $time - 10 )['index'],
650 LBFactory
::getCPInfoFromCookieValue( "5@$time", $time - 10 )['index'],
655 LBFactory
::getCPInfoFromCookieValue( "0@$time#$agentId", $time - 10 )['index'],
661 LBFactory
::getCPInfoFromCookieValue( "2@$time#$agentId", $time - 10 )['index'],
666 LBFactory
::getCPInfoFromCookieValue( "2@$time#$agentId", $time +
9 - 10 )['index'],
671 LBFactory
::getCPInfoFromCookieValue( "0@$time#$agentId", $time +
9 - 10 )['index'],
672 'Almost stale; bad index'
676 LBFactory
::getCPInfoFromCookieValue( "2@$time#$agentId", $time +
11 - 10 )['index'],
682 LBFactory
::getCPInfoFromCookieValue( "5@$time#$agentId", $time - 10 )['clientId'],
687 LBFactory
::getCPInfoFromCookieValue( "5@$time#$agentId", $time +
11 - 10 )['clientId'],