rdbms: fix finalization stage errors in LBFactory::commitMasterChanges
[lhc/web/wiklou.git] / tests / phpunit / includes / db / LBFactoryTest.php
1 <?php
2 /**
3 * Holds tests for LBFactory abstract MediaWiki class.
4 *
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.
9 *
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.
14 *
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
19 *
20 * @file
21 * @author Antoine Musso
22 * @copyright © 2013 Antoine Musso
23 * @copyright © 2013 Wikimedia Foundation Inc.
24 */
25
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;
33
34 /**
35 * @group Database
36 * @covers \Wikimedia\Rdbms\LBFactorySimple
37 * @covers \Wikimedia\Rdbms\LBFactoryMulti
38 */
39 class LBFactoryTest extends MediaWikiTestCase {
40
41 /**
42 * @covers MWLBFactory::getLBFactoryClass
43 * @dataProvider getLBFactoryClassProvider
44 */
45 public function testGetLBFactoryClass( $expected, $deprecated ) {
46 $mockDB = $this->getMockBuilder( DatabaseMysqli::class )
47 ->disableOriginalConstructor()
48 ->getMock();
49
50 $config = [
51 'class' => $deprecated,
52 'connection' => $mockDB,
53 # Various other parameters required:
54 'sectionsByDB' => [],
55 'sectionLoads' => [],
56 'serverTemplate' => [],
57 ];
58
59 $this->hideDeprecated( '$wgLBFactoryConf must be updated. See RELEASE-NOTES for details' );
60 $result = MWLBFactory::getLBFactoryClass( $config );
61
62 $this->assertEquals( $expected, $result );
63 }
64
65 public function getLBFactoryClassProvider() {
66 return [
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' ],
74 ];
75 }
76
77 public function testLBFactorySimpleServer() {
78 global $wgDBserver, $wgDBname, $wgDBuser, $wgDBpassword, $wgDBtype, $wgSQLiteDataDir;
79
80 $servers = [
81 [
82 'host' => $wgDBserver,
83 'dbname' => $wgDBname,
84 'user' => $wgDBuser,
85 'password' => $wgDBpassword,
86 'type' => $wgDBtype,
87 'dbDirectory' => $wgSQLiteDataDir,
88 'load' => 0,
89 'flags' => DBO_TRX // REPEATABLE-READ for consistency
90 ],
91 ];
92
93 $factory = new LBFactorySimple( [ 'servers' => $servers ] );
94 $lb = $factory->getMainLB();
95
96 $dbw = $lb->getConnection( DB_MASTER );
97 $this->assertTrue( $dbw->getLBInfo( 'master' ), 'master shows as master' );
98
99 $dbr = $lb->getConnection( DB_REPLICA );
100 $this->assertTrue( $dbr->getLBInfo( 'master' ), 'DB_REPLICA also gets the master' );
101
102 $factory->shutdown();
103 $lb->closeAll();
104 }
105
106 public function testLBFactorySimpleServers() {
107 global $wgDBserver, $wgDBname, $wgDBuser, $wgDBpassword, $wgDBtype, $wgSQLiteDataDir;
108
109 $servers = [
110 [ // master
111 'host' => $wgDBserver,
112 'dbname' => $wgDBname,
113 'user' => $wgDBuser,
114 'password' => $wgDBpassword,
115 'type' => $wgDBtype,
116 'dbDirectory' => $wgSQLiteDataDir,
117 'load' => 0,
118 'flags' => DBO_TRX // REPEATABLE-READ for consistency
119 ],
120 [ // emulated slave
121 'host' => $wgDBserver,
122 'dbname' => $wgDBname,
123 'user' => $wgDBuser,
124 'password' => $wgDBpassword,
125 'type' => $wgDBtype,
126 'dbDirectory' => $wgSQLiteDataDir,
127 'load' => 100,
128 'flags' => DBO_TRX // REPEATABLE-READ for consistency
129 ]
130 ];
131
132 $factory = new LBFactorySimple( [
133 'servers' => $servers,
134 'loadMonitorClass' => LoadMonitorNull::class
135 ] );
136 $lb = $factory->getMainLB();
137
138 $dbw = $lb->getConnection( DB_MASTER );
139 $this->assertTrue( $dbw->getLBInfo( 'master' ), 'master shows as master' );
140 $this->assertEquals(
141 ( $wgDBserver != '' ) ? $wgDBserver : 'localhost',
142 $dbw->getLBInfo( 'clusterMasterHost' ),
143 'cluster master set' );
144
145 $dbr = $lb->getConnection( DB_REPLICA );
146 $this->assertTrue( $dbr->getLBInfo( 'replica' ), 'slave shows as slave' );
147 $this->assertEquals(
148 ( $wgDBserver != '' ) ? $wgDBserver : 'localhost',
149 $dbr->getLBInfo( 'clusterMasterHost' ),
150 'cluster master set' );
151
152 $factory->shutdown();
153 $lb->closeAll();
154 }
155
156 public function testLBFactoryMulti() {
157 global $wgDBserver, $wgDBname, $wgDBuser, $wgDBpassword, $wgDBtype, $wgSQLiteDataDir;
158
159 $factory = new LBFactoryMulti( [
160 'sectionsByDB' => [
161 's1wiki' => 's1',
162 ],
163 'sectionLoads' => [
164 's1' => [
165 'test-db3' => 0,
166 'test-db4' => 100,
167 ],
168 'DEFAULT' => [
169 'test-db1' => 0,
170 'test-db2' => 100,
171 ]
172 ],
173 'serverTemplate' => [
174 'dbname' => $wgDBname,
175 'user' => $wgDBuser,
176 'password' => $wgDBpassword,
177 'type' => $wgDBtype,
178 'dbDirectory' => $wgSQLiteDataDir,
179 'flags' => DBO_DEFAULT
180 ],
181 'hostsByName' => [
182 'test-db1' => $wgDBserver,
183 'test-db2' => $wgDBserver,
184 'test-db3' => $wgDBserver,
185 'test-db4' => $wgDBserver
186 ],
187 'loadMonitorClass' => LoadMonitorNull::class
188 ] );
189 $lb = $factory->getMainLB();
190
191 $dbw = $lb->getConnection( DB_MASTER );
192 $this->assertTrue( $dbw->getLBInfo( 'master' ), 'master shows as master' );
193
194 $dbr = $lb->getConnection( DB_REPLICA );
195 $this->assertTrue( $dbr->getLBInfo( 'replica' ), 'slave shows as slave' );
196
197 // Test that LoadBalancer instances made during commitMasterChanges() do not throw
198 // DBTransactionError due to transaction ROUND_* stages being mismatched.
199 $factory->beginMasterChanges( __METHOD__ );
200 $dbw->onTransactionPreCommitOrIdle( function () use ( $factory ) {
201 // Trigger s1 LoadBalancer instantiation during "finalize" stage.
202 // There is no s1wiki DB to select so it is not in getConnection(),
203 // but this fools getMainLB() at least.
204 $factory->getMainLB( 's1wiki' )->getConnection( DB_MASTER );
205 } );
206 $factory->commitMasterChanges( __METHOD__ );
207
208 $count = 0;
209 $factory->forEachLB( function () use ( &$count ) {
210 ++$count;
211 } );
212 $this->assertEquals( 2, $count );
213
214 $factory->shutdown();
215 $factory->closeAll();
216 }
217
218 /**
219 * @covers \Wikimedia\Rdbms\ChronologyProtector
220 */
221 public function testChronologyProtector() {
222 $now = microtime( true );
223
224 // (a) First HTTP request
225 $m1Pos = new MySQLMasterPos( 'db1034-bin.000976/843431247', $now );
226 $m2Pos = new MySQLMasterPos( 'db1064-bin.002400/794074907', $now );
227
228 // Master DB 1
229 $mockDB1 = $this->getMockBuilder( DatabaseMysqli::class )
230 ->disableOriginalConstructor()
231 ->getMock();
232 $mockDB1->method( 'writesOrCallbacksPending' )->willReturn( true );
233 $mockDB1->method( 'lastDoneWrites' )->willReturn( $now );
234 $mockDB1->method( 'getMasterPos' )->willReturn( $m1Pos );
235 // Load balancer for master DB 1
236 $lb1 = $this->getMockBuilder( LoadBalancer::class )
237 ->disableOriginalConstructor()
238 ->getMock();
239 $lb1->method( 'getConnection' )->willReturn( $mockDB1 );
240 $lb1->method( 'getServerCount' )->willReturn( 2 );
241 $lb1->method( 'getAnyOpenConnection' )->willReturn( $mockDB1 );
242 $lb1->method( 'hasOrMadeRecentMasterChanges' )->will( $this->returnCallback(
243 function () use ( $mockDB1 ) {
244 $p = 0;
245 $p |= call_user_func( [ $mockDB1, 'writesOrCallbacksPending' ] );
246 $p |= call_user_func( [ $mockDB1, 'lastDoneWrites' ] );
247
248 return (bool)$p;
249 }
250 ) );
251 $lb1->method( 'getMasterPos' )->willReturn( $m1Pos );
252 $lb1->method( 'getServerName' )->with( 0 )->willReturn( 'master1' );
253 // Master DB 2
254 $mockDB2 = $this->getMockBuilder( DatabaseMysqli::class )
255 ->disableOriginalConstructor()
256 ->getMock();
257 $mockDB2->method( 'writesOrCallbacksPending' )->willReturn( true );
258 $mockDB2->method( 'lastDoneWrites' )->willReturn( $now );
259 $mockDB2->method( 'getMasterPos' )->willReturn( $m2Pos );
260 // Load balancer for master DB 2
261 $lb2 = $this->getMockBuilder( LoadBalancer::class )
262 ->disableOriginalConstructor()
263 ->getMock();
264 $lb2->method( 'getConnection' )->willReturn( $mockDB2 );
265 $lb2->method( 'getServerCount' )->willReturn( 2 );
266 $lb2->method( 'getAnyOpenConnection' )->willReturn( $mockDB2 );
267 $lb2->method( 'hasOrMadeRecentMasterChanges' )->will( $this->returnCallback(
268 function () use ( $mockDB2 ) {
269 $p = 0;
270 $p |= call_user_func( [ $mockDB2, 'writesOrCallbacksPending' ] );
271 $p |= call_user_func( [ $mockDB2, 'lastDoneWrites' ] );
272
273 return (bool)$p;
274 }
275 ) );
276 $lb2->method( 'getMasterPos' )->willReturn( $m2Pos );
277 $lb2->method( 'getServerName' )->with( 0 )->willReturn( 'master2' );
278
279 $bag = new HashBagOStuff();
280 $cp = new ChronologyProtector(
281 $bag,
282 [
283 'ip' => '127.0.0.1',
284 'agent' => "Totally-Not-FireFox"
285 ]
286 );
287
288 $mockDB1->expects( $this->exactly( 1 ) )->method( 'writesOrCallbacksPending' );
289 $mockDB1->expects( $this->exactly( 1 ) )->method( 'lastDoneWrites' );
290 $mockDB2->expects( $this->exactly( 1 ) )->method( 'writesOrCallbacksPending' );
291 $mockDB2->expects( $this->exactly( 1 ) )->method( 'lastDoneWrites' );
292
293 // Nothing to wait for on first HTTP request start
294 $cp->initLB( $lb1 );
295 $cp->initLB( $lb2 );
296 // Record positions in stash on first HTTP request end
297 $cp->shutdownLB( $lb1 );
298 $cp->shutdownLB( $lb2 );
299 $cpIndex = null;
300 $cp->shutdown( null, 'sync', $cpIndex );
301
302 $this->assertEquals( 1, $cpIndex, "CP write index set" );
303
304 // (b) Second HTTP request
305
306 // Load balancer for master DB 1
307 $lb1 = $this->getMockBuilder( LoadBalancer::class )
308 ->disableOriginalConstructor()
309 ->getMock();
310 $lb1->method( 'getServerCount' )->willReturn( 2 );
311 $lb1->method( 'getServerName' )->with( 0 )->willReturn( 'master1' );
312 $lb1->expects( $this->once() )
313 ->method( 'waitFor' )->with( $this->equalTo( $m1Pos ) );
314 // Load balancer for master DB 2
315 $lb2 = $this->getMockBuilder( LoadBalancer::class )
316 ->disableOriginalConstructor()
317 ->getMock();
318 $lb2->method( 'getServerCount' )->willReturn( 2 );
319 $lb2->method( 'getServerName' )->with( 0 )->willReturn( 'master2' );
320 $lb2->expects( $this->once() )
321 ->method( 'waitFor' )->with( $this->equalTo( $m2Pos ) );
322
323 $cp = new ChronologyProtector(
324 $bag,
325 [
326 'ip' => '127.0.0.1',
327 'agent' => "Totally-Not-FireFox"
328 ],
329 $cpIndex
330 );
331
332 // Wait for last positions to be reached on second HTTP request start
333 $cp->initLB( $lb1 );
334 $cp->initLB( $lb2 );
335 // Shutdown (nothing to record)
336 $cp->shutdownLB( $lb1 );
337 $cp->shutdownLB( $lb2 );
338 $cpIndex = null;
339 $cp->shutdown( null, 'sync', $cpIndex );
340
341 $this->assertEquals( null, $cpIndex, "CP write index retained" );
342 }
343
344 private function newLBFactoryMulti( array $baseOverride = [], array $serverOverride = [] ) {
345 global $wgDBserver, $wgDBuser, $wgDBpassword, $wgDBname, $wgDBprefix, $wgDBtype;
346 global $wgSQLiteDataDir;
347
348 return new LBFactoryMulti( $baseOverride + [
349 'sectionsByDB' => [],
350 'sectionLoads' => [
351 'DEFAULT' => [
352 'test-db1' => 1,
353 ],
354 ],
355 'serverTemplate' => $serverOverride + [
356 'dbname' => $wgDBname,
357 'tablePrefix' => $wgDBprefix,
358 'user' => $wgDBuser,
359 'password' => $wgDBpassword,
360 'type' => $wgDBtype,
361 'dbDirectory' => $wgSQLiteDataDir,
362 'flags' => DBO_DEFAULT
363 ],
364 'hostsByName' => [
365 'test-db1' => $wgDBserver,
366 ],
367 'loadMonitorClass' => LoadMonitorNull::class,
368 'localDomain' => new DatabaseDomain( $wgDBname, null, $wgDBprefix )
369 ] );
370 }
371
372 public function testNiceDomains() {
373 global $wgDBname;
374
375 if ( wfGetDB( DB_MASTER )->databasesAreIndependent() ) {
376 self::markTestSkipped( "Skipping tests about selecting DBs: not applicable" );
377 return;
378 }
379
380 $factory = $this->newLBFactoryMulti(
381 [],
382 []
383 );
384 $lb = $factory->getMainLB();
385
386 $db = $lb->getConnectionRef( DB_MASTER );
387 $this->assertEquals(
388 wfWikiID(),
389 $db->getDomainID()
390 );
391 unset( $db );
392
393 /** @var Database $db */
394 $db = $lb->getConnection( DB_MASTER, [], '' );
395
396 $this->assertEquals(
397 '',
398 $db->getDomainId(),
399 'Null domain ID handle used'
400 );
401 $this->assertEquals(
402 '',
403 $db->getDBname(),
404 'Null domain ID handle used'
405 );
406 $this->assertEquals(
407 '',
408 $db->tablePrefix(),
409 'Main domain ID handle used; prefix is empty though'
410 );
411 $this->assertEquals(
412 $this->quoteTable( $db, 'page' ),
413 $db->tableName( 'page' ),
414 "Correct full table name"
415 );
416 $this->assertEquals(
417 $this->quoteTable( $db, $wgDBname ) . '.' . $this->quoteTable( $db, 'page' ),
418 $db->tableName( "$wgDBname.page" ),
419 "Correct full table name"
420 );
421 $this->assertEquals(
422 $this->quoteTable( $db, 'nice_db' ) . '.' . $this->quoteTable( $db, 'page' ),
423 $db->tableName( 'nice_db.page' ),
424 "Correct full table name"
425 );
426
427 $lb->reuseConnection( $db ); // don't care
428
429 $db = $lb->getConnection( DB_MASTER ); // local domain connection
430 $factory->setDomainPrefix( 'my_' );
431
432 $this->assertEquals( $wgDBname, $db->getDBname() );
433 $this->assertEquals(
434 "$wgDBname-my_",
435 $db->getDomainID()
436 );
437 $this->assertEquals(
438 $this->quoteTable( $db, 'my_page' ),
439 $db->tableName( 'page' ),
440 "Correct full table name"
441 );
442 $this->assertEquals(
443 $this->quoteTable( $db, 'other_nice_db' ) . '.' . $this->quoteTable( $db, 'page' ),
444 $db->tableName( 'other_nice_db.page' ),
445 "Correct full table name"
446 );
447
448 $factory->closeAll();
449 $factory->destroy();
450 }
451
452 public function testTrickyDomain() {
453 global $wgDBname;
454
455 if ( wfGetDB( DB_MASTER )->databasesAreIndependent() ) {
456 self::markTestSkipped( "Skipping tests about selecting DBs: not applicable" );
457 return;
458 }
459
460 $dbname = 'unittest-domain'; // explodes if DB is selected
461 $factory = $this->newLBFactoryMulti(
462 [ 'localDomain' => ( new DatabaseDomain( $dbname, null, '' ) )->getId() ],
463 [
464 'dbName' => 'do_not_select_me' // explodes if DB is selected
465 ]
466 );
467 $lb = $factory->getMainLB();
468 /** @var Database $db */
469 $db = $lb->getConnection( DB_MASTER, [], '' );
470
471 $this->assertEquals( '', $db->getDomainID(), "Null domain used" );
472
473 $this->assertEquals(
474 $this->quoteTable( $db, 'page' ),
475 $db->tableName( 'page' ),
476 "Correct full table name"
477 );
478
479 $this->assertEquals(
480 $this->quoteTable( $db, $dbname ) . '.' . $this->quoteTable( $db, 'page' ),
481 $db->tableName( "$dbname.page" ),
482 "Correct full table name"
483 );
484
485 $this->assertEquals(
486 $this->quoteTable( $db, 'nice_db' ) . '.' . $this->quoteTable( $db, 'page' ),
487 $db->tableName( 'nice_db.page' ),
488 "Correct full table name"
489 );
490
491 $lb->reuseConnection( $db ); // don't care
492
493 $factory->setDomainPrefix( 'my_' );
494 $db = $lb->getConnection( DB_MASTER, [], "$wgDBname-my_" );
495
496 $this->assertEquals(
497 $this->quoteTable( $db, 'my_page' ),
498 $db->tableName( 'page' ),
499 "Correct full table name"
500 );
501 $this->assertEquals(
502 $this->quoteTable( $db, 'other_nice_db' ) . '.' . $this->quoteTable( $db, 'page' ),
503 $db->tableName( 'other_nice_db.page' ),
504 "Correct full table name"
505 );
506 $this->assertEquals(
507 $this->quoteTable( $db, 'garbage-db' ) . '.' . $this->quoteTable( $db, 'page' ),
508 $db->tableName( 'garbage-db.page' ),
509 "Correct full table name"
510 );
511
512 $lb->reuseConnection( $db ); // don't care
513
514 $factory->closeAll();
515 $factory->destroy();
516 }
517
518 public function testInvalidSelectDB() {
519 $dbname = 'unittest-domain'; // explodes if DB is selected
520 $factory = $this->newLBFactoryMulti(
521 [ 'localDomain' => ( new DatabaseDomain( $dbname, null, '' ) )->getId() ],
522 [
523 'dbName' => 'do_not_select_me' // explodes if DB is selected
524 ]
525 );
526 $lb = $factory->getMainLB();
527 /** @var Database $db */
528 $db = $lb->getConnection( DB_MASTER, [], '' );
529
530 if ( $db->getType() === 'sqlite' ) {
531 $this->assertFalse( $db->selectDB( 'garbage-db' ) );
532 } elseif ( $db->databasesAreIndependent() ) {
533 try {
534 $e = null;
535 $db->selectDB( 'garbage-db' );
536 } catch ( \Wikimedia\Rdbms\DBConnectionError $e ) {
537 // expected
538 }
539 $this->assertInstanceOf( \Wikimedia\Rdbms\DBConnectionError::class, $e );
540 $this->assertFalse( $db->isOpen() );
541 } else {
542 \Wikimedia\suppressWarnings();
543 $this->assertFalse( $db->selectDB( 'garbage-db' ) );
544 \Wikimedia\restoreWarnings();
545 }
546 }
547
548 private function quoteTable( Database $db, $table ) {
549 if ( $db->getType() === 'sqlite' ) {
550 return $table;
551 } else {
552 return $db->addIdentifierQuotes( $table );
553 }
554 }
555 }