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