LoadBalancerTest.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  1. <?php
  2. /**
  3. * Holds tests for LoadBalancer 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. */
  22. use Wikimedia\Rdbms\DBError;
  23. use Wikimedia\Rdbms\DatabaseDomain;
  24. use Wikimedia\Rdbms\Database;
  25. use Wikimedia\Rdbms\LoadBalancer;
  26. use Wikimedia\Rdbms\LoadMonitorNull;
  27. /**
  28. * @group Database
  29. * @covers \Wikimedia\Rdbms\LoadBalancer
  30. */
  31. class LoadBalancerTest extends MediaWikiTestCase {
  32. private function makeServerConfig() {
  33. global $wgDBserver, $wgDBname, $wgDBuser, $wgDBpassword, $wgDBtype, $wgSQLiteDataDir;
  34. return [
  35. 'host' => $wgDBserver,
  36. 'dbname' => $wgDBname,
  37. 'tablePrefix' => $this->dbPrefix(),
  38. 'user' => $wgDBuser,
  39. 'password' => $wgDBpassword,
  40. 'type' => $wgDBtype,
  41. 'dbDirectory' => $wgSQLiteDataDir,
  42. 'load' => 0,
  43. 'flags' => DBO_TRX // REPEATABLE-READ for consistency
  44. ];
  45. }
  46. /**
  47. * @covers LoadBalancer::getLocalDomainID()
  48. * @covers LoadBalancer::resolveDomainID()
  49. */
  50. public function testWithoutReplica() {
  51. global $wgDBname;
  52. $called = false;
  53. $lb = new LoadBalancer( [
  54. 'servers' => [ $this->makeServerConfig() ],
  55. 'queryLogger' => MediaWiki\Logger\LoggerFactory::getInstance( 'DBQuery' ),
  56. 'localDomain' => new DatabaseDomain( $wgDBname, null, $this->dbPrefix() ),
  57. 'chronologyCallback' => function () use ( &$called ) {
  58. $called = true;
  59. }
  60. ] );
  61. $ld = DatabaseDomain::newFromId( $lb->getLocalDomainID() );
  62. $this->assertEquals( $wgDBname, $ld->getDatabase(), 'local domain DB set' );
  63. $this->assertEquals( $this->dbPrefix(), $ld->getTablePrefix(), 'local domain prefix set' );
  64. $this->assertSame( 'my_test_wiki', $lb->resolveDomainID( 'my_test_wiki' ) );
  65. $this->assertSame( $ld->getId(), $lb->resolveDomainID( false ) );
  66. $this->assertSame( $ld->getId(), $lb->resolveDomainID( $ld ) );
  67. $this->assertFalse( $called );
  68. $dbw = $lb->getConnection( DB_MASTER );
  69. $this->assertTrue( $called );
  70. $this->assertTrue( $dbw->getLBInfo( 'master' ), 'master shows as master' );
  71. $this->assertTrue( $dbw->getFlag( $dbw::DBO_TRX ), "DBO_TRX set on master" );
  72. $this->assertWriteAllowed( $dbw );
  73. $dbr = $lb->getConnection( DB_REPLICA );
  74. $this->assertTrue( $dbr->getLBInfo( 'master' ), 'DB_REPLICA also gets the master' );
  75. $this->assertTrue( $dbr->getFlag( $dbw::DBO_TRX ), "DBO_TRX set on replica" );
  76. if ( !$lb->getServerAttributes( $lb->getWriterIndex() )[$dbw::ATTR_DB_LEVEL_LOCKING] ) {
  77. $dbwAuto = $lb->getConnection( DB_MASTER, [], false, $lb::CONN_TRX_AUTOCOMMIT );
  78. $this->assertFalse(
  79. $dbwAuto->getFlag( $dbw::DBO_TRX ), "No DBO_TRX with CONN_TRX_AUTOCOMMIT" );
  80. $this->assertTrue( $dbw->getFlag( $dbw::DBO_TRX ), "DBO_TRX still set on master" );
  81. $this->assertNotEquals(
  82. $dbw, $dbwAuto, "CONN_TRX_AUTOCOMMIT uses separate connection" );
  83. $dbrAuto = $lb->getConnection( DB_REPLICA, [], false, $lb::CONN_TRX_AUTOCOMMIT );
  84. $this->assertFalse(
  85. $dbrAuto->getFlag( $dbw::DBO_TRX ), "No DBO_TRX with CONN_TRX_AUTOCOMMIT" );
  86. $this->assertTrue( $dbr->getFlag( $dbw::DBO_TRX ), "DBO_TRX still set on replica" );
  87. $this->assertNotEquals(
  88. $dbr, $dbrAuto, "CONN_TRX_AUTOCOMMIT uses separate connection" );
  89. $dbwAuto2 = $lb->getConnection( DB_MASTER, [], false, $lb::CONN_TRX_AUTOCOMMIT );
  90. $this->assertEquals( $dbwAuto2, $dbwAuto, "CONN_TRX_AUTOCOMMIT reuses connections" );
  91. }
  92. $lb->closeAll();
  93. }
  94. public function testWithReplica() {
  95. global $wgDBserver, $wgDBname, $wgDBuser, $wgDBpassword, $wgDBtype, $wgSQLiteDataDir;
  96. $servers = [
  97. [ // master
  98. 'host' => $wgDBserver,
  99. 'dbname' => $wgDBname,
  100. 'tablePrefix' => $this->dbPrefix(),
  101. 'user' => $wgDBuser,
  102. 'password' => $wgDBpassword,
  103. 'type' => $wgDBtype,
  104. 'dbDirectory' => $wgSQLiteDataDir,
  105. 'load' => 0,
  106. 'flags' => DBO_TRX // REPEATABLE-READ for consistency
  107. ],
  108. [ // emulated replica
  109. 'host' => $wgDBserver,
  110. 'dbname' => $wgDBname,
  111. 'tablePrefix' => $this->dbPrefix(),
  112. 'user' => $wgDBuser,
  113. 'password' => $wgDBpassword,
  114. 'type' => $wgDBtype,
  115. 'dbDirectory' => $wgSQLiteDataDir,
  116. 'load' => 100,
  117. 'flags' => DBO_TRX // REPEATABLE-READ for consistency
  118. ]
  119. ];
  120. $lb = new LoadBalancer( [
  121. 'servers' => $servers,
  122. 'localDomain' => new DatabaseDomain( $wgDBname, null, $this->dbPrefix() ),
  123. 'queryLogger' => MediaWiki\Logger\LoggerFactory::getInstance( 'DBQuery' ),
  124. 'loadMonitorClass' => LoadMonitorNull::class
  125. ] );
  126. $dbw = $lb->getConnection( DB_MASTER );
  127. $this->assertTrue( $dbw->getLBInfo( 'master' ), 'master shows as master' );
  128. $this->assertEquals(
  129. ( $wgDBserver != '' ) ? $wgDBserver : 'localhost',
  130. $dbw->getLBInfo( 'clusterMasterHost' ),
  131. 'cluster master set' );
  132. $this->assertTrue( $dbw->getFlag( $dbw::DBO_TRX ), "DBO_TRX set on master" );
  133. $this->assertWriteAllowed( $dbw );
  134. $dbr = $lb->getConnection( DB_REPLICA );
  135. $this->assertTrue( $dbr->getLBInfo( 'replica' ), 'replica shows as replica' );
  136. $this->assertEquals(
  137. ( $wgDBserver != '' ) ? $wgDBserver : 'localhost',
  138. $dbr->getLBInfo( 'clusterMasterHost' ),
  139. 'cluster master set' );
  140. $this->assertTrue( $dbr->getFlag( $dbw::DBO_TRX ), "DBO_TRX set on replica" );
  141. $this->assertWriteForbidden( $dbr );
  142. if ( !$lb->getServerAttributes( $lb->getWriterIndex() )[$dbw::ATTR_DB_LEVEL_LOCKING] ) {
  143. $dbwAuto = $lb->getConnection( DB_MASTER, [], false, $lb::CONN_TRX_AUTOCOMMIT );
  144. $this->assertFalse(
  145. $dbwAuto->getFlag( $dbw::DBO_TRX ), "No DBO_TRX with CONN_TRX_AUTOCOMMIT" );
  146. $this->assertTrue( $dbw->getFlag( $dbw::DBO_TRX ), "DBO_TRX still set on master" );
  147. $this->assertNotEquals(
  148. $dbw, $dbwAuto, "CONN_TRX_AUTOCOMMIT uses separate connection" );
  149. $dbrAuto = $lb->getConnection( DB_REPLICA, [], false, $lb::CONN_TRX_AUTOCOMMIT );
  150. $this->assertFalse(
  151. $dbrAuto->getFlag( $dbw::DBO_TRX ), "No DBO_TRX with CONN_TRX_AUTOCOMMIT" );
  152. $this->assertTrue( $dbr->getFlag( $dbw::DBO_TRX ), "DBO_TRX still set on replica" );
  153. $this->assertNotEquals(
  154. $dbr, $dbrAuto, "CONN_TRX_AUTOCOMMIT uses separate connection" );
  155. $dbwAuto2 = $lb->getConnection( DB_MASTER, [], false, $lb::CONN_TRX_AUTOCOMMIT );
  156. $this->assertEquals( $dbwAuto2, $dbwAuto, "CONN_TRX_AUTOCOMMIT reuses connections" );
  157. }
  158. $lb->closeAll();
  159. }
  160. private function assertWriteForbidden( Database $db ) {
  161. try {
  162. $db->delete( 'some_table', [ 'id' => 57634126 ], __METHOD__ );
  163. $this->fail( 'Write operation should have failed!' );
  164. } catch ( DBError $ex ) {
  165. // check that the exception message contains "Write operation"
  166. $constraint = new PHPUnit_Framework_Constraint_StringContains( 'Write operation' );
  167. if ( !$constraint->evaluate( $ex->getMessage(), '', true ) ) {
  168. // re-throw original error, to preserve stack trace
  169. throw $ex;
  170. }
  171. }
  172. }
  173. private function assertWriteAllowed( Database $db ) {
  174. $table = $db->tableName( 'some_table' );
  175. // Trigger a transaction so that rollback() will remove all the tables.
  176. // Don't do this for MySQL/Oracle as they auto-commit transactions for DDL
  177. // statements such as CREATE TABLE.
  178. $useAtomicSection = in_array( $db->getType(), [ 'sqlite', 'postgres', 'mssql' ], true );
  179. try {
  180. $db->dropTable( 'some_table' ); // clear for sanity
  181. $this->assertNotEquals( $db::STATUS_TRX_ERROR, $db->trxStatus() );
  182. if ( $useAtomicSection ) {
  183. $db->startAtomic( __METHOD__ );
  184. }
  185. // Use only basic SQL and trivial types for these queries for compatibility
  186. $this->assertNotSame(
  187. false,
  188. $db->query( "CREATE TABLE $table (id INT, time INT)", __METHOD__ ),
  189. "table created"
  190. );
  191. $this->assertNotEquals( $db::STATUS_TRX_ERROR, $db->trxStatus() );
  192. $this->assertNotSame(
  193. false,
  194. $db->query( "DELETE FROM $table WHERE id=57634126", __METHOD__ ),
  195. "delete query"
  196. );
  197. $this->assertNotEquals( $db::STATUS_TRX_ERROR, $db->trxStatus() );
  198. } finally {
  199. if ( !$useAtomicSection ) {
  200. // Drop the table to clean up, ignoring any error.
  201. $db->dropTable( 'some_table' );
  202. }
  203. // Rollback the atomic section for sqlite's benefit.
  204. $db->rollback( __METHOD__, 'flush' );
  205. $this->assertNotEquals( $db::STATUS_TRX_ERROR, $db->trxStatus() );
  206. }
  207. }
  208. public function testServerAttributes() {
  209. $servers = [
  210. [ // master
  211. 'dbname' => 'my_unittest_wiki',
  212. 'tablePrefix' => 'unittest_',
  213. 'type' => 'sqlite',
  214. 'dbDirectory' => "some_directory",
  215. 'load' => 0
  216. ]
  217. ];
  218. $lb = new LoadBalancer( [
  219. 'servers' => $servers,
  220. 'localDomain' => new DatabaseDomain( 'my_unittest_wiki', null, 'unittest_' ),
  221. 'loadMonitorClass' => LoadMonitorNull::class
  222. ] );
  223. $this->assertTrue( $lb->getServerAttributes( 0 )[Database::ATTR_DB_LEVEL_LOCKING] );
  224. $servers = [
  225. [ // master
  226. 'host' => 'db1001',
  227. 'user' => 'wikiuser',
  228. 'password' => 'none',
  229. 'dbname' => 'my_unittest_wiki',
  230. 'tablePrefix' => 'unittest_',
  231. 'type' => 'mysql',
  232. 'load' => 100
  233. ],
  234. [ // emulated replica
  235. 'host' => 'db1002',
  236. 'user' => 'wikiuser',
  237. 'password' => 'none',
  238. 'dbname' => 'my_unittest_wiki',
  239. 'tablePrefix' => 'unittest_',
  240. 'type' => 'mysql',
  241. 'load' => 100
  242. ]
  243. ];
  244. $lb = new LoadBalancer( [
  245. 'servers' => $servers,
  246. 'localDomain' => new DatabaseDomain( 'my_unittest_wiki', null, 'unittest_' ),
  247. 'loadMonitorClass' => LoadMonitorNull::class
  248. ] );
  249. $this->assertFalse( $lb->getServerAttributes( 1 )[Database::ATTR_DB_LEVEL_LOCKING] );
  250. }
  251. /**
  252. * @covers LoadBalancer::openConnection()
  253. * @covers LoadBalancer::getAnyOpenConnection()
  254. */
  255. function testOpenConnection() {
  256. global $wgDBname;
  257. $lb = new LoadBalancer( [
  258. 'servers' => [ $this->makeServerConfig() ],
  259. 'localDomain' => new DatabaseDomain( $wgDBname, null, $this->dbPrefix() )
  260. ] );
  261. $i = $lb->getWriterIndex();
  262. $this->assertEquals( null, $lb->getAnyOpenConnection( $i ) );
  263. $conn1 = $lb->getConnection( $i );
  264. $this->assertNotEquals( null, $conn1 );
  265. $this->assertEquals( $conn1, $lb->getAnyOpenConnection( $i ) );
  266. $conn2 = $lb->getConnection( $i, [], false, $lb::CONN_TRX_AUTOCOMMIT );
  267. $this->assertNotEquals( null, $conn2 );
  268. if ( $lb->getServerAttributes( $i )[Database::ATTR_DB_LEVEL_LOCKING] ) {
  269. $this->assertEquals( null,
  270. $lb->getAnyOpenConnection( $i, $lb::CONN_TRX_AUTOCOMMIT ) );
  271. $this->assertEquals( $conn1,
  272. $lb->getConnection(
  273. $i, [], false, $lb::CONN_TRX_AUTOCOMMIT ), $lb::CONN_TRX_AUTOCOMMIT );
  274. } else {
  275. $this->assertEquals( $conn2,
  276. $lb->getAnyOpenConnection( $i, $lb::CONN_TRX_AUTOCOMMIT ) );
  277. $this->assertEquals( $conn2,
  278. $lb->getConnection( $i, [], false, $lb::CONN_TRX_AUTOCOMMIT ) );
  279. $conn2->startAtomic( __METHOD__ );
  280. try {
  281. $lb->getConnection( $i, [], false, $lb::CONN_TRX_AUTOCOMMIT );
  282. $conn2->endAtomic( __METHOD__ );
  283. $this->fail( "No exception thrown." );
  284. } catch ( DBUnexpectedError $e ) {
  285. $this->assertEquals(
  286. 'Wikimedia\Rdbms\LoadBalancer::openConnection: ' .
  287. 'CONN_TRX_AUTOCOMMIT handle has a transaction.',
  288. $e->getMessage()
  289. );
  290. }
  291. $conn2->endAtomic( __METHOD__ );
  292. }
  293. $lb->closeAll();
  294. }
  295. public function testTransactionCallbackChains() {
  296. global $wgDBserver, $wgDBname, $wgDBuser, $wgDBpassword, $wgDBtype, $wgSQLiteDataDir;
  297. $servers = [
  298. [
  299. 'host' => $wgDBserver,
  300. 'dbname' => $wgDBname,
  301. 'tablePrefix' => $this->dbPrefix(),
  302. 'user' => $wgDBuser,
  303. 'password' => $wgDBpassword,
  304. 'type' => $wgDBtype,
  305. 'dbDirectory' => $wgSQLiteDataDir,
  306. 'load' => 0,
  307. 'flags' => DBO_TRX // REPEATABLE-READ for consistency
  308. ],
  309. ];
  310. $lb = new LoadBalancer( [
  311. 'servers' => $servers,
  312. 'localDomain' => new DatabaseDomain( $wgDBname, null, $this->dbPrefix() )
  313. ] );
  314. $conn1 = $lb->openConnection( $lb->getWriterIndex(), false );
  315. $conn2 = $lb->openConnection( $lb->getWriterIndex(), '' );
  316. $count = 0;
  317. $lb->forEachOpenMasterConnection( function () use ( &$count ) {
  318. ++$count;
  319. } );
  320. $this->assertEquals( 2, $count, 'Connection handle count' );
  321. $tlCalls = 0;
  322. $lb->setTransactionListener( 'test-listener', function () use ( &$tlCalls ) {
  323. ++$tlCalls;
  324. } );
  325. $lb->beginMasterChanges( __METHOD__ );
  326. $bc = array_fill_keys( [ 'a', 'b', 'c', 'd' ], 0 );
  327. $conn1->onTransactionPreCommitOrIdle( function () use ( &$bc, $conn1, $conn2 ) {
  328. $bc['a'] = 1;
  329. $conn2->onTransactionPreCommitOrIdle( function () use ( &$bc, $conn1, $conn2 ) {
  330. $bc['b'] = 1;
  331. $conn1->onTransactionPreCommitOrIdle( function () use ( &$bc, $conn1, $conn2 ) {
  332. $bc['c'] = 1;
  333. $conn1->onTransactionPreCommitOrIdle( function () use ( &$bc, $conn1, $conn2 ) {
  334. $bc['d'] = 1;
  335. } );
  336. } );
  337. } );
  338. } );
  339. $lb->finalizeMasterChanges();
  340. $lb->approveMasterChanges( [] );
  341. $lb->commitMasterChanges( __METHOD__ );
  342. $lb->runMasterTransactionIdleCallbacks();
  343. $lb->runMasterTransactionListenerCallbacks();
  344. $this->assertEquals( array_fill_keys( [ 'a', 'b', 'c', 'd' ], 1 ), $bc );
  345. $this->assertEquals( 2, $tlCalls );
  346. $tlCalls = 0;
  347. $lb->beginMasterChanges( __METHOD__ );
  348. $ac = array_fill_keys( [ 'a', 'b', 'c', 'd' ], 0 );
  349. $conn1->onTransactionCommitOrIdle( function () use ( &$ac, $conn1, $conn2 ) {
  350. $ac['a'] = 1;
  351. $conn2->onTransactionCommitOrIdle( function () use ( &$ac, $conn1, $conn2 ) {
  352. $ac['b'] = 1;
  353. $conn1->onTransactionCommitOrIdle( function () use ( &$ac, $conn1, $conn2 ) {
  354. $ac['c'] = 1;
  355. $conn1->onTransactionCommitOrIdle( function () use ( &$ac, $conn1, $conn2 ) {
  356. $ac['d'] = 1;
  357. } );
  358. } );
  359. } );
  360. } );
  361. $lb->finalizeMasterChanges();
  362. $lb->approveMasterChanges( [] );
  363. $lb->commitMasterChanges( __METHOD__ );
  364. $lb->runMasterTransactionIdleCallbacks();
  365. $lb->runMasterTransactionListenerCallbacks();
  366. $this->assertEquals( array_fill_keys( [ 'a', 'b', 'c', 'd' ], 1 ), $ac );
  367. $this->assertEquals( 2, $tlCalls );
  368. $conn1->close();
  369. $conn2->close();
  370. }
  371. }