MediaWiki  master
LBFactoryTest.php
Go to the documentation of this file.
1 <?php
35 
43 
48  public function testGetLBFactoryClass( $expected, $deprecated ) {
49  $mockDB = $this->getMockBuilder( IDatabase::class )
50  ->disableOriginalConstructor()
51  ->getMock();
52 
53  $config = [
54  'class' => $deprecated,
55  'connection' => $mockDB,
56  # Various other parameters required:
57  'sectionsByDB' => [],
58  'sectionLoads' => [],
59  'serverTemplate' => [],
60  ];
61 
62  $this->hideDeprecated( '$wgLBFactoryConf must be updated. See RELEASE-NOTES for details' );
64 
65  $this->assertEquals( $expected, $result );
66  }
67 
68  public function getLBFactoryClassProvider() {
69  return [
70  # Format: new class, old class
71  [ Wikimedia\Rdbms\LBFactorySimple::class, 'LBFactory_Simple' ],
72  [ Wikimedia\Rdbms\LBFactorySingle::class, 'LBFactory_Single' ],
73  [ Wikimedia\Rdbms\LBFactoryMulti::class, 'LBFactory_Multi' ],
74  [ Wikimedia\Rdbms\LBFactorySimple::class, 'LBFactorySimple' ],
75  [ Wikimedia\Rdbms\LBFactorySingle::class, 'LBFactorySingle' ],
76  [ Wikimedia\Rdbms\LBFactoryMulti::class, 'LBFactoryMulti' ],
77  ];
78  }
79 
84  public function testLBFactorySimpleServer() {
86 
87  $servers = [
88  [
89  'host' => $wgDBserver,
90  'dbname' => $wgDBname,
91  'user' => $wgDBuser,
92  'password' => $wgDBpassword,
93  'type' => $wgDBtype,
94  'dbDirectory' => $wgSQLiteDataDir,
95  'load' => 0,
96  'flags' => DBO_TRX // REPEATABLE-READ for consistency
97  ],
98  ];
99 
100  $factory = new LBFactorySimple( [ 'servers' => $servers ] );
101  $lb = $factory->getMainLB();
102 
103  $dbw = $lb->getConnection( DB_MASTER );
104  $this->assertTrue( $dbw->getLBInfo( 'master' ), 'master shows as master' );
105 
106  $dbr = $lb->getConnection( DB_REPLICA );
107  $this->assertTrue( $dbr->getLBInfo( 'master' ), 'DB_REPLICA also gets the master' );
108 
109  $this->assertSame( 'my_test_wiki', $factory->resolveDomainID( 'my_test_wiki' ) );
110  $this->assertSame( $factory->getLocalDomainID(), $factory->resolveDomainID( false ) );
111 
112  $factory->shutdown();
113  $lb->closeAll();
114  }
115 
116  public function testLBFactorySimpleServers() {
118 
119  $servers = [
120  [ // master
121  'host' => $wgDBserver,
122  'dbname' => $wgDBname,
123  'user' => $wgDBuser,
124  'password' => $wgDBpassword,
125  'type' => $wgDBtype,
126  'dbDirectory' => $wgSQLiteDataDir,
127  'load' => 0,
128  'flags' => DBO_TRX // REPEATABLE-READ for consistency
129  ],
130  [ // emulated replica
131  'host' => $wgDBserver,
132  'dbname' => $wgDBname,
133  'user' => $wgDBuser,
134  'password' => $wgDBpassword,
135  'type' => $wgDBtype,
136  'dbDirectory' => $wgSQLiteDataDir,
137  'load' => 100,
138  'flags' => DBO_TRX // REPEATABLE-READ for consistency
139  ]
140  ];
141 
142  $factory = new LBFactorySimple( [
143  'servers' => $servers,
144  'loadMonitorClass' => LoadMonitorNull::class
145  ] );
146  $lb = $factory->getMainLB();
147 
148  $dbw = $lb->getConnection( DB_MASTER );
149  $this->assertTrue( $dbw->getLBInfo( 'master' ), 'master shows as master' );
150  $this->assertEquals(
151  ( $wgDBserver != '' ) ? $wgDBserver : 'localhost',
152  $dbw->getLBInfo( 'clusterMasterHost' ),
153  'cluster master set' );
154 
155  $dbr = $lb->getConnection( DB_REPLICA );
156  $this->assertTrue( $dbr->getLBInfo( 'replica' ), 'replica shows as replica' );
157  $this->assertEquals(
158  ( $wgDBserver != '' ) ? $wgDBserver : 'localhost',
159  $dbr->getLBInfo( 'clusterMasterHost' ),
160  'cluster master set' );
161 
162  $factory->shutdown();
163  $lb->closeAll();
164  }
165 
166  public function testLBFactoryMultiConns() {
167  $factory = $this->newLBFactoryMultiLBs();
168 
169  $dbw = $factory->getMainLB()->getConnection( DB_MASTER );
170  $this->assertTrue( $dbw->getLBInfo( 'master' ), 'master shows as master' );
171 
172  $dbr = $factory->getMainLB()->getConnection( DB_REPLICA );
173  $this->assertTrue( $dbr->getLBInfo( 'replica' ), 'replica shows as replica' );
174 
175  // Destructor should trigger without round stage errors
176  unset( $factory );
177  }
178 
180  $called = 0;
181  $countLBsFunc = function ( LBFactoryMulti $factory ) {
182  $count = 0;
183  $factory->forEachLB( function () use ( &$count ) {
184  ++$count;
185  } );
186 
187  return $count;
188  };
189 
190  $factory = $this->newLBFactoryMultiLBs();
191  $this->assertEquals( 0, $countLBsFunc( $factory ) );
192  $dbw = $factory->getMainLB()->getConnection( DB_MASTER );
193  $this->assertEquals( 1, $countLBsFunc( $factory ) );
194  // Test that LoadBalancer instances made during pre-commit callbacks in do not
195  // throw DBTransactionError due to transaction ROUND_* stages being mismatched.
196  $factory->beginMasterChanges( __METHOD__ );
197  $dbw->onTransactionPreCommitOrIdle( function () use ( $factory, &$called ) {
198  ++$called;
199  // Trigger s1 LoadBalancer instantiation during "finalize" stage.
200  // There is no s1wiki DB to select so it is not in getConnection(),
201  // but this fools getMainLB() at least.
202  $factory->getMainLB( 's1wiki' )->getConnection( DB_MASTER );
203  } );
204  $factory->commitMasterChanges( __METHOD__ );
205  $this->assertEquals( 1, $called );
206  $this->assertEquals( 2, $countLBsFunc( $factory ) );
207  $factory->shutdown();
208  $factory->closeAll();
209 
210  $called = 0;
211  $factory = $this->newLBFactoryMultiLBs();
212  $this->assertEquals( 0, $countLBsFunc( $factory ) );
213  $dbw = $factory->getMainLB()->getConnection( DB_MASTER );
214  $this->assertEquals( 1, $countLBsFunc( $factory ) );
215  // Test that LoadBalancer instances made during pre-commit callbacks in do not
216  // throw DBTransactionError due to transaction ROUND_* stages being mismatched.hrow
217  // DBTransactionError due to transaction ROUND_* stages being mismatched.
218  $factory->beginMasterChanges( __METHOD__ );
219  $dbw->query( "SELECT 1 as t", __METHOD__ );
220  $dbw->onTransactionResolution( function () use ( $factory, &$called ) {
221  ++$called;
222  // Trigger s1 LoadBalancer instantiation during "finalize" stage.
223  // There is no s1wiki DB to select so it is not in getConnection(),
224  // but this fools getMainLB() at least.
225  $factory->getMainLB( 's1wiki' )->getConnection( DB_MASTER );
226  } );
227  $factory->commitMasterChanges( __METHOD__ );
228  $this->assertEquals( 1, $called );
229  $this->assertEquals( 2, $countLBsFunc( $factory ) );
230  $factory->shutdown();
231  $factory->closeAll();
232 
233  $factory = $this->newLBFactoryMultiLBs();
234  $dbw = $factory->getMainLB()->getConnection( DB_MASTER );
235  // DBTransactionError should not be thrown
236  $ran = 0;
237  $dbw->onTransactionPreCommitOrIdle( function () use ( &$ran ) {
238  ++$ran;
239  } );
240  $factory->commitAll( __METHOD__ );
241  $this->assertEquals( 1, $ran );
242 
243  $factory->shutdown();
244  $factory->closeAll();
245  }
246 
247  private function newLBFactoryMultiLBs() {
249 
250  return new LBFactoryMulti( [
251  'sectionsByDB' => [
252  's1wiki' => 's1',
253  ],
254  'sectionLoads' => [
255  's1' => [
256  'test-db3' => 0,
257  'test-db4' => 100,
258  ],
259  'DEFAULT' => [
260  'test-db1' => 0,
261  'test-db2' => 100,
262  ]
263  ],
264  'serverTemplate' => [
265  'dbname' => $wgDBname,
266  'user' => $wgDBuser,
267  'password' => $wgDBpassword,
268  'type' => $wgDBtype,
269  'dbDirectory' => $wgSQLiteDataDir,
270  'flags' => DBO_DEFAULT
271  ],
272  'hostsByName' => [
273  'test-db1' => $wgDBserver,
274  'test-db2' => $wgDBserver,
275  'test-db3' => $wgDBserver,
276  'test-db4' => $wgDBserver
277  ],
278  'loadMonitorClass' => LoadMonitorNull::class
279  ] );
280  }
281 
285  public function testChronologyProtector() {
286  $now = microtime( true );
287 
288  // (a) First HTTP request
289  $m1Pos = new MySQLMasterPos( 'db1034-bin.000976/843431247', $now );
290  $m2Pos = new MySQLMasterPos( 'db1064-bin.002400/794074907', $now );
291 
292  // Master DB 1
293  $mockDB1 = $this->getMockBuilder( IDatabase::class )
294  ->disableOriginalConstructor()
295  ->getMock();
296  $mockDB1->method( 'writesOrCallbacksPending' )->willReturn( true );
297  $mockDB1->method( 'lastDoneWrites' )->willReturn( $now );
298  $mockDB1->method( 'getMasterPos' )->willReturn( $m1Pos );
299  // Load balancer for master DB 1
300  $lb1 = $this->getMockBuilder( LoadBalancer::class )
301  ->disableOriginalConstructor()
302  ->getMock();
303  $lb1->method( 'getConnection' )->willReturn( $mockDB1 );
304  $lb1->method( 'getServerCount' )->willReturn( 2 );
305  $lb1->method( 'hasReplicaServers' )->willReturn( true );
306  $lb1->method( 'hasStreamingReplicaServers' )->willReturn( true );
307  $lb1->method( 'getAnyOpenConnection' )->willReturn( $mockDB1 );
308  $lb1->method( 'hasOrMadeRecentMasterChanges' )->will( $this->returnCallback(
309  function () use ( $mockDB1 ) {
310  $p = 0;
311  $p |= call_user_func( [ $mockDB1, 'writesOrCallbacksPending' ] );
312  $p |= call_user_func( [ $mockDB1, 'lastDoneWrites' ] );
313 
314  return (bool)$p;
315  }
316  ) );
317  $lb1->method( 'getMasterPos' )->willReturn( $m1Pos );
318  $lb1->method( 'getReplicaResumePos' )->willReturn( $m1Pos );
319  $lb1->method( 'getServerName' )->with( 0 )->willReturn( 'master1' );
320  // Master DB 2
321  $mockDB2 = $this->getMockBuilder( IDatabase::class )
322  ->disableOriginalConstructor()
323  ->getMock();
324  $mockDB2->method( 'writesOrCallbacksPending' )->willReturn( true );
325  $mockDB2->method( 'lastDoneWrites' )->willReturn( $now );
326  $mockDB2->method( 'getMasterPos' )->willReturn( $m2Pos );
327  // Load balancer for master DB 2
328  $lb2 = $this->getMockBuilder( LoadBalancer::class )
329  ->disableOriginalConstructor()
330  ->getMock();
331  $lb2->method( 'getConnection' )->willReturn( $mockDB2 );
332  $lb2->method( 'getServerCount' )->willReturn( 2 );
333  $lb2->method( 'hasReplicaServers' )->willReturn( true );
334  $lb2->method( 'hasStreamingReplicaServers' )->willReturn( true );
335  $lb2->method( 'getAnyOpenConnection' )->willReturn( $mockDB2 );
336  $lb2->method( 'hasOrMadeRecentMasterChanges' )->will( $this->returnCallback(
337  function () use ( $mockDB2 ) {
338  $p = 0;
339  $p |= call_user_func( [ $mockDB2, 'writesOrCallbacksPending' ] );
340  $p |= call_user_func( [ $mockDB2, 'lastDoneWrites' ] );
341 
342  return (bool)$p;
343  }
344  ) );
345  $lb2->method( 'getMasterPos' )->willReturn( $m2Pos );
346  $lb2->method( 'getReplicaResumePos' )->willReturn( $m2Pos );
347  $lb2->method( 'getServerName' )->with( 0 )->willReturn( 'master2' );
348 
349  $bag = new HashBagOStuff();
350  $cp = new ChronologyProtector(
351  $bag,
352  [
353  'ip' => '127.0.0.1',
354  'agent' => "Totally-Not-FireFox"
355  ],
356  null
357  );
358 
359  $mockDB1->expects( $this->exactly( 1 ) )->method( 'writesOrCallbacksPending' );
360  $mockDB1->expects( $this->exactly( 1 ) )->method( 'lastDoneWrites' );
361  $mockDB2->expects( $this->exactly( 1 ) )->method( 'writesOrCallbacksPending' );
362  $mockDB2->expects( $this->exactly( 1 ) )->method( 'lastDoneWrites' );
363 
364  // Nothing to wait for on first HTTP request start
365  $cp->applySessionReplicationPosition( $lb1 );
366  $cp->applySessionReplicationPosition( $lb2 );
367  // Record positions in stash on first HTTP request end
368  $cp->storeSessionReplicationPosition( $lb1 );
369  $cp->storeSessionReplicationPosition( $lb2 );
370  $cpIndex = null;
371  $cp->shutdown( null, 'sync', $cpIndex );
372 
373  $this->assertEquals( 1, $cpIndex, "CP write index set" );
374 
375  // (b) Second HTTP request
376 
377  // Load balancer for master DB 1
378  $lb1 = $this->getMockBuilder( LoadBalancer::class )
379  ->disableOriginalConstructor()
380  ->getMock();
381  $lb1->method( 'getServerCount' )->willReturn( 2 );
382  $lb1->method( 'hasReplicaServers' )->willReturn( true );
383  $lb1->method( 'hasStreamingReplicaServers' )->willReturn( true );
384  $lb1->method( 'getServerName' )->with( 0 )->willReturn( 'master1' );
385  $lb1->expects( $this->once() )
386  ->method( 'waitFor' )->with( $this->equalTo( $m1Pos ) );
387  // Load balancer for master DB 2
388  $lb2 = $this->getMockBuilder( LoadBalancer::class )
389  ->disableOriginalConstructor()
390  ->getMock();
391  $lb2->method( 'getServerCount' )->willReturn( 2 );
392  $lb2->method( 'hasReplicaServers' )->willReturn( true );
393  $lb2->method( 'hasStreamingReplicaServers' )->willReturn( true );
394  $lb2->method( 'getServerName' )->with( 0 )->willReturn( 'master2' );
395  $lb2->expects( $this->once() )
396  ->method( 'waitFor' )->with( $this->equalTo( $m2Pos ) );
397 
398  $cp = new ChronologyProtector(
399  $bag,
400  [
401  'ip' => '127.0.0.1',
402  'agent' => "Totally-Not-FireFox"
403  ],
404  $cpIndex
405  );
406 
407  // Wait for last positions to be reached on second HTTP request start
408  $cp->applySessionReplicationPosition( $lb1 );
409  $cp->applySessionReplicationPosition( $lb2 );
410  // Shutdown (nothing to record)
411  $cp->storeSessionReplicationPosition( $lb1 );
412  $cp->storeSessionReplicationPosition( $lb2 );
413  $cpIndex = null;
414  $cp->shutdown( null, 'sync', $cpIndex );
415 
416  $this->assertEquals( null, $cpIndex, "CP write index retained" );
417 
418  $this->assertEquals( '45e93a9c215c031d38b7c42d8e4700ca', $cp->getClientId() );
419  }
420 
421  private function newLBFactoryMulti( array $baseOverride = [], array $serverOverride = [] ) {
423  global $wgSQLiteDataDir;
424 
425  return new LBFactoryMulti( $baseOverride + [
426  'sectionsByDB' => [],
427  'sectionLoads' => [
428  'DEFAULT' => [
429  'test-db1' => 1,
430  ],
431  ],
432  'serverTemplate' => $serverOverride + [
433  'dbname' => $wgDBname,
434  'tablePrefix' => $wgDBprefix,
435  'user' => $wgDBuser,
436  'password' => $wgDBpassword,
437  'type' => $wgDBtype,
438  'dbDirectory' => $wgSQLiteDataDir,
439  'flags' => DBO_DEFAULT
440  ],
441  'hostsByName' => [
442  'test-db1' => $wgDBserver,
443  ],
444  'loadMonitorClass' => LoadMonitorNull::class,
445  'localDomain' => new DatabaseDomain( $wgDBname, null, $wgDBprefix ),
446  'agent' => 'MW-UNIT-TESTS'
447  ] );
448  }
449 
455  public function testNiceDomains() {
456  global $wgDBname;
457 
458  if ( wfGetDB( DB_MASTER )->databasesAreIndependent() ) {
459  self::markTestSkipped( "Skipping tests about selecting DBs: not applicable" );
460  return;
461  }
462 
463  $factory = $this->newLBFactoryMulti(
464  [],
465  []
466  );
467  $lb = $factory->getMainLB();
468 
469  $db = $lb->getConnectionRef( DB_MASTER );
470  $this->assertEquals(
471  wfWikiID(),
472  $db->getDomainID()
473  );
474  unset( $db );
475 
477  $db = $lb->getConnection( DB_MASTER, [], '' );
478 
479  $this->assertEquals(
480  '',
481  $db->getDomainId(),
482  'Null domain ID handle used'
483  );
484  $this->assertEquals(
485  '',
486  $db->getDBname(),
487  'Null domain ID handle used'
488  );
489  $this->assertEquals(
490  '',
491  $db->tablePrefix(),
492  'Main domain ID handle used; prefix is empty though'
493  );
494  $this->assertEquals(
495  $this->quoteTable( $db, 'page' ),
496  $db->tableName( 'page' ),
497  "Correct full table name"
498  );
499  $this->assertEquals(
500  $this->quoteTable( $db, $wgDBname ) . '.' . $this->quoteTable( $db, 'page' ),
501  $db->tableName( "$wgDBname.page" ),
502  "Correct full table name"
503  );
504  $this->assertEquals(
505  $this->quoteTable( $db, 'nice_db' ) . '.' . $this->quoteTable( $db, 'page' ),
506  $db->tableName( 'nice_db.page' ),
507  "Correct full table name"
508  );
509 
510  $lb->reuseConnection( $db ); // don't care
511 
512  $db = $lb->getConnection( DB_MASTER ); // local domain connection
513  $factory->setLocalDomainPrefix( 'my_' );
514 
515  $this->assertEquals( $wgDBname, $db->getDBname() );
516  $this->assertEquals(
517  "$wgDBname-my_",
518  $db->getDomainID()
519  );
520  $this->assertEquals(
521  $this->quoteTable( $db, 'my_page' ),
522  $db->tableName( 'page' ),
523  "Correct full table name"
524  );
525  $this->assertEquals(
526  $this->quoteTable( $db, 'other_nice_db' ) . '.' . $this->quoteTable( $db, 'page' ),
527  $db->tableName( 'other_nice_db.page' ),
528  "Correct full table name"
529  );
530 
531  $factory->closeAll();
532  $factory->destroy();
533  }
534 
540  public function testTrickyDomain() {
541  global $wgDBname;
542 
543  if ( wfGetDB( DB_MASTER )->databasesAreIndependent() ) {
544  self::markTestSkipped( "Skipping tests about selecting DBs: not applicable" );
545  return;
546  }
547 
548  $dbname = 'unittest-domain'; // explodes if DB is selected
549  $factory = $this->newLBFactoryMulti(
550  [ 'localDomain' => ( new DatabaseDomain( $dbname, null, '' ) )->getId() ],
551  [
552  'dbname' => 'do_not_select_me' // explodes if DB is selected
553  ]
554  );
555  $lb = $factory->getMainLB();
557  $db = $lb->getConnection( DB_MASTER, [], '' );
558 
559  $this->assertEquals( '', $db->getDomainID(), "Null domain used" );
560 
561  $this->assertEquals(
562  $this->quoteTable( $db, 'page' ),
563  $db->tableName( 'page' ),
564  "Correct full table name"
565  );
566 
567  $this->assertEquals(
568  $this->quoteTable( $db, $dbname ) . '.' . $this->quoteTable( $db, 'page' ),
569  $db->tableName( "$dbname.page" ),
570  "Correct full table name"
571  );
572 
573  $this->assertEquals(
574  $this->quoteTable( $db, 'nice_db' ) . '.' . $this->quoteTable( $db, 'page' ),
575  $db->tableName( 'nice_db.page' ),
576  "Correct full table name"
577  );
578 
579  $lb->reuseConnection( $db ); // don't care
580 
581  $factory->setLocalDomainPrefix( 'my_' );
582  $db = $lb->getConnection( DB_MASTER, [], "$wgDBname-my_" );
583 
584  $this->assertEquals(
585  $this->quoteTable( $db, 'my_page' ),
586  $db->tableName( 'page' ),
587  "Correct full table name"
588  );
589  $this->assertEquals(
590  $this->quoteTable( $db, 'other_nice_db' ) . '.' . $this->quoteTable( $db, 'page' ),
591  $db->tableName( 'other_nice_db.page' ),
592  "Correct full table name"
593  );
594  $this->assertEquals(
595  $this->quoteTable( $db, 'garbage-db' ) . '.' . $this->quoteTable( $db, 'page' ),
596  $db->tableName( 'garbage-db.page' ),
597  "Correct full table name"
598  );
599 
600  $lb->reuseConnection( $db ); // don't care
601 
602  $factory->closeAll();
603  $factory->destroy();
604  }
605 
611  public function testInvalidSelectDB() {
612  if ( wfGetDB( DB_MASTER )->databasesAreIndependent() ) {
613  $this->markTestSkipped( "Not applicable per databasesAreIndependent()" );
614  }
615 
616  $dbname = 'unittest-domain'; // explodes if DB is selected
617  $factory = $this->newLBFactoryMulti(
618  [ 'localDomain' => ( new DatabaseDomain( $dbname, null, '' ) )->getId() ],
619  [
620  'dbname' => 'do_not_select_me' // explodes if DB is selected
621  ]
622  );
623  $lb = $factory->getMainLB();
625  $db = $lb->getConnection( DB_MASTER, [], '' );
626 
627  \Wikimedia\suppressWarnings();
628  try {
629  $this->assertFalse( $db->selectDB( 'garbage-db' ) );
630  $this->fail( "No error thrown." );
631  } catch ( \Wikimedia\Rdbms\DBQueryError $e ) {
632  $this->assertRegExp( '/[\'"]garbage-db[\'"]/', $e->getMessage() );
633  }
634  \Wikimedia\restoreWarnings();
635  }
636 
642  public function testInvalidSelectDBIndependent() {
643  $dbname = 'unittest-domain'; // explodes if DB is selected
644  $factory = $this->newLBFactoryMulti(
645  [ 'localDomain' => ( new DatabaseDomain( $dbname, null, '' ) )->getId() ],
646  [
647  // Explodes with SQLite and Postgres during open/USE
648  'dbname' => 'bad_dir/do_not_select_me'
649  ]
650  );
651  $lb = $factory->getMainLB();
652 
653  if ( !$lb->getConnection( DB_MASTER )->databasesAreIndependent() ) {
654  $this->markTestSkipped( "Not applicable per databasesAreIndependent()" );
655  }
656 
658  $lb->getConnection( DB_MASTER, [], '' );
659  }
660 
667  $dbname = 'unittest-domain'; // explodes if DB is selected
668  $factory = $this->newLBFactoryMulti(
669  [ 'localDomain' => ( new DatabaseDomain( $dbname, null, '' ) )->getId() ],
670  [
671  // Explodes with SQLite and Postgres during open/USE
672  'dbname' => 'bad_dir/do_not_select_me'
673  ]
674  );
675  $lb = $factory->getMainLB();
676 
677  if ( !$lb->getConnection( DB_MASTER )->databasesAreIndependent() ) {
678  $this->markTestSkipped( "Not applicable per databasesAreIndependent()" );
679  }
680 
681  $db = $lb->getConnection( DB_MASTER );
682  $db->selectDB( 'garbage-db' );
683  }
684 
690  public function testRedefineLocalDomain() {
691  global $wgDBname;
692 
693  if ( wfGetDB( DB_MASTER )->databasesAreIndependent() ) {
694  self::markTestSkipped( "Skipping tests about selecting DBs: not applicable" );
695  return;
696  }
697 
698  $factory = $this->newLBFactoryMulti(
699  [],
700  []
701  );
702  $lb = $factory->getMainLB();
703 
704  $conn1 = $lb->getConnectionRef( DB_MASTER );
705  $this->assertEquals(
706  wfWikiID(),
707  $conn1->getDomainID()
708  );
709  unset( $conn1 );
710 
711  $factory->redefineLocalDomain( 'somedb-prefix_' );
712  $this->assertEquals( 'somedb-prefix_', $factory->getLocalDomainID() );
713 
714  $domain = new DatabaseDomain( $wgDBname, null, 'pref_' );
715  $factory->redefineLocalDomain( $domain );
716 
717  $n = 0;
718  $lb->forEachOpenConnection( function () use ( &$n ) {
719  ++$n;
720  } );
721  $this->assertEquals( 0, $n, "Connections closed" );
722 
723  $conn2 = $lb->getConnectionRef( DB_MASTER );
724  $this->assertEquals(
725  $domain->getId(),
726  $conn2->getDomainID()
727  );
728  unset( $conn2 );
729 
730  $factory->closeAll();
731  $factory->destroy();
732  }
733 
734  private function quoteTable( IDatabase $db, $table ) {
735  if ( $db->getType() === 'sqlite' ) {
736  return $table;
737  } else {
738  return $db->addIdentifierQuotes( $table );
739  }
740  }
741 
746  public function testCPPosIndexCookieValues() {
747  $time = 1526522031;
748  $agentId = md5( 'Ramsey\'s Loyal Presa Canario' );
749 
750  $this->assertEquals(
751  '3@542#c47dcfb0566e7d7bc110a6128a45c93a',
752  LBFactory::makeCookieValueFromCPIndex( 3, 542, $agentId )
753  );
754 
755  $lbFactory = $this->newLBFactoryMulti();
756  $lbFactory->setRequestInfo( [ 'IPAddress' => '10.64.24.52', 'UserAgent' => 'meow' ] );
757  $this->assertEquals(
758  '1@542#c47dcfb0566e7d7bc110a6128a45c93a',
759  LBFactory::makeCookieValueFromCPIndex( 1, 542, $agentId )
760  );
761 
762  $this->assertSame(
763  null,
764  LBFactory::getCPInfoFromCookieValue( "5#$agentId", $time - 10 )['index'],
765  'No time set'
766  );
767  $this->assertSame(
768  null,
769  LBFactory::getCPInfoFromCookieValue( "5@$time", $time - 10 )['index'],
770  'No agent set'
771  );
772  $this->assertSame(
773  null,
774  LBFactory::getCPInfoFromCookieValue( "0@$time#$agentId", $time - 10 )['index'],
775  'Bad index'
776  );
777 
778  $this->assertSame(
779  2,
780  LBFactory::getCPInfoFromCookieValue( "2@$time#$agentId", $time - 10 )['index'],
781  'Fresh'
782  );
783  $this->assertSame(
784  2,
785  LBFactory::getCPInfoFromCookieValue( "2@$time#$agentId", $time + 9 - 10 )['index'],
786  'Almost stale'
787  );
788  $this->assertSame(
789  null,
790  LBFactory::getCPInfoFromCookieValue( "0@$time#$agentId", $time + 9 - 10 )['index'],
791  'Almost stale; bad index'
792  );
793  $this->assertSame(
794  null,
795  LBFactory::getCPInfoFromCookieValue( "2@$time#$agentId", $time + 11 - 10 )['index'],
796  'Stale'
797  );
798 
799  $this->assertSame(
800  $agentId,
801  LBFactory::getCPInfoFromCookieValue( "5@$time#$agentId", $time - 10 )['clientId'],
802  'Live (client ID)'
803  );
804  $this->assertSame(
805  null,
806  LBFactory::getCPInfoFromCookieValue( "5@$time#$agentId", $time + 11 - 10 )['clientId'],
807  'Stale (client ID)'
808  );
809  }
810 }
testRedefineLocalDomain()
\Wikimedia\Rdbms\LoadBalancer::getConnection \Wikimedia\Rdbms\LoadBalancer::redefineLocalDomain \Wiki...
$wgSQLiteDataDir
To override default SQLite data directory ($docroot/../data)
quoteTable(IDatabase $db, $table)
addIdentifierQuotes( $s)
Quotes an identifier, in order to make user controlled input safe.
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException' returning false will NOT prevent logging $e
Definition: hooks.txt:2147
$wgDBpassword
Database user&#39;s password.
testLBFactorySimpleServer()
\Wikimedia\Rdbms\LBFactory::getLocalDomainID() \Wikimedia\Rdbms\LBFactory::resolveDomainID() ...
$wgDBtype
Database type.
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
testCPPosIndexCookieValues()
\Wikimedia\Rdbms\LBFactory::makeCookieValueFromCPIndex() \Wikimedia\Rdbms\LBFactory::getCPInfoFromCoo...
$wgDBserver
Database host name or IP address.
$wgDBuser
Database username.
see documentation in includes Linker php for Linker::makeImageLink & $time
Definition: hooks.txt:1781
testChronologyProtector()
\Wikimedia\Rdbms\ChronologyProtector
const DB_MASTER
Definition: defines.php:26
A multi-database, multi-master factory for Wikimedia and similar installations.
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=(\*-\*)") 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. '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 '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
Definition: hooks.txt:1970
Database \Wikimedia\Rdbms\LBFactory \Wikimedia\Rdbms\LBFactorySimple \Wikimedia\Rdbms\LBFactoryMulti...
This program is free software; you can redistribute it and/or modify it under the terms of the GNU Ge...
Helper class for mitigating DB replication lag in order to provide "session consistency".
testGetLBFactoryClass( $expected, $deprecated)
MWLBFactory::getLBFactoryClass() getLBFactoryClassProvider.
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that When $user is not null
Definition: hooks.txt:767
wfWikiID()
Get an ASCII string identifying this wiki This is used as a prefix in memcached keys.
testInvalidSelectDB()
\Wikimedia\Rdbms\LoadBalancer::getConnection \Wikimedia\Rdbms\DatabaseMysqlBase::doSelectDomain \Wiki...
const DBO_TRX
Definition: defines.php:12
DBMasterPos class for MySQL/MariaDB.
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:35
const DBO_DEFAULT
Definition: defines.php:13
getType()
Get the type of the DBMS, as it appears in $wgDBtype.
Class to handle database/prefix specification for IDatabase domains.
Basic database interface for live and lazy-loaded relation database handles.
Definition: IDatabase.php:38
you have access to all of the normal MediaWiki so you can get a DB use the etc For full docs on the Maintenance class
Definition: maintenance.txt:52
testInvalidSelectDBIndependent()
\Wikimedia\Rdbms\DatabaseSqlite::selectDB \Wikimedia\Rdbms\DatabasePostgres::selectDB \Wikimedia\Rdbm...
static getLBFactoryClass(array $config)
Returns the LBFactory class to use and the load balancer configuration.
testLBFactoryMultiRoundCallbacks()
$wgDBprefix
Table name prefix.
testInvalidSelectDBIndependent2()
\Wikimedia\Rdbms\DatabaseSqlite::selectDB \Wikimedia\Rdbms\DatabasePostgres::selectDB \Wikimedia\Rdbm...
newLBFactoryMulti(array $baseOverride=[], array $serverOverride=[])
const DB_REPLICA
Definition: defines.php:25
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 controlled by the following MediaWiki still creates a BagOStuff but calls it to it are no ops If the cache daemon can t be it should also disable itself fairly $wgDBname
Definition: memcached.txt:93
testTrickyDomain()
\Wikimedia\Rdbms\LoadBalancer::getConnection \Wikimedia\Rdbms\DatabaseMysqlBase::doSelectDomain \Wiki...
A simple single-master LBFactory that gets its configuration from the b/c globals.
testNiceDomains()
\Wikimedia\Rdbms\LoadBalancer::getConnection \Wikimedia\Rdbms\DatabaseMysqlBase::doSelectDomain \Wiki...