PageRenderTime 57ms CodeModel.GetById 27ms RepoModel.GetById 0ms app.codeStats 0ms

/includes/db/loadbalancer/LBFactory.php

https://gitlab.com/link233/bootmw
PHP | 481 lines | 228 code | 51 blank | 202 comment | 24 complexity | 742794129010404271a071a1ffd7c26e MD5 | raw file
  1. <?php
  2. /**
  3. * Generator of database load balancing objects.
  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. * @ingroup Database
  22. */
  23. use Psr\Log\LoggerInterface;
  24. use MediaWiki\Logger\LoggerFactory;
  25. /**
  26. * An interface for generating database load balancers
  27. * @ingroup Database
  28. */
  29. abstract class LBFactory {
  30. /** @var ChronologyProtector */
  31. protected $chronProt;
  32. /** @var TransactionProfiler */
  33. protected $trxProfiler;
  34. /** @var LoggerInterface */
  35. protected $logger;
  36. /** @var LBFactory */
  37. private static $instance;
  38. /** @var string|bool Reason all LBs are read-only or false if not */
  39. protected $readOnlyReason = false;
  40. const SHUTDOWN_NO_CHRONPROT = 1; // don't save ChronologyProtector positions (for async code)
  41. /**
  42. * Construct a factory based on a configuration array (typically from $wgLBFactoryConf)
  43. * @param array $conf
  44. */
  45. public function __construct( array $conf ) {
  46. if ( isset( $conf['readOnlyReason'] ) && is_string( $conf['readOnlyReason'] ) ) {
  47. $this->readOnlyReason = $conf['readOnlyReason'];
  48. }
  49. $this->chronProt = $this->newChronologyProtector();
  50. $this->trxProfiler = Profiler::instance()->getTransactionProfiler();
  51. $this->logger = LoggerFactory::getInstance( 'DBTransaction' );
  52. }
  53. /**
  54. * Disables all access to the load balancer, will cause all database access
  55. * to throw a DBAccessError
  56. */
  57. public static function disableBackend() {
  58. global $wgLBFactoryConf;
  59. self::$instance = new LBFactoryFake( $wgLBFactoryConf );
  60. }
  61. /**
  62. * Get an LBFactory instance
  63. *
  64. * @return LBFactory
  65. */
  66. public static function singleton() {
  67. global $wgLBFactoryConf;
  68. if ( is_null( self::$instance ) ) {
  69. $class = self::getLBFactoryClass( $wgLBFactoryConf );
  70. $config = $wgLBFactoryConf;
  71. if ( !isset( $config['readOnlyReason'] ) ) {
  72. $config['readOnlyReason'] = wfConfiguredReadOnlyReason();
  73. }
  74. self::$instance = new $class( $config );
  75. }
  76. return self::$instance;
  77. }
  78. /**
  79. * Returns the LBFactory class to use and the load balancer configuration.
  80. *
  81. * @param array $config (e.g. $wgLBFactoryConf)
  82. * @return string Class name
  83. */
  84. public static function getLBFactoryClass( array $config ) {
  85. // For configuration backward compatibility after removing
  86. // underscores from class names in MediaWiki 1.23.
  87. $bcClasses = [
  88. 'LBFactory_Simple' => 'LBFactorySimple',
  89. 'LBFactory_Single' => 'LBFactorySingle',
  90. 'LBFactory_Multi' => 'LBFactoryMulti',
  91. 'LBFactory_Fake' => 'LBFactoryFake',
  92. ];
  93. $class = $config['class'];
  94. if ( isset( $bcClasses[$class] ) ) {
  95. $class = $bcClasses[$class];
  96. wfDeprecated(
  97. '$wgLBFactoryConf must be updated. See RELEASE-NOTES for details',
  98. '1.23'
  99. );
  100. }
  101. return $class;
  102. }
  103. /**
  104. * Shut down, close connections and destroy the cached instance.
  105. */
  106. public static function destroyInstance() {
  107. if ( self::$instance ) {
  108. self::$instance->shutdown();
  109. self::$instance->forEachLBCallMethod( 'closeAll' );
  110. self::$instance = null;
  111. }
  112. }
  113. /**
  114. * Set the instance to be the given object
  115. *
  116. * @param LBFactory $instance
  117. */
  118. public static function setInstance( $instance ) {
  119. self::destroyInstance();
  120. self::$instance = $instance;
  121. }
  122. /**
  123. * Create a new load balancer object. The resulting object will be untracked,
  124. * not chronology-protected, and the caller is responsible for cleaning it up.
  125. *
  126. * @param bool|string $wiki Wiki ID, or false for the current wiki
  127. * @return LoadBalancer
  128. */
  129. abstract public function newMainLB( $wiki = false );
  130. /**
  131. * Get a cached (tracked) load balancer object.
  132. *
  133. * @param bool|string $wiki Wiki ID, or false for the current wiki
  134. * @return LoadBalancer
  135. */
  136. abstract public function getMainLB( $wiki = false );
  137. /**
  138. * Create a new load balancer for external storage. The resulting object will be
  139. * untracked, not chronology-protected, and the caller is responsible for
  140. * cleaning it up.
  141. *
  142. * @param string $cluster External storage cluster, or false for core
  143. * @param bool|string $wiki Wiki ID, or false for the current wiki
  144. * @return LoadBalancer
  145. */
  146. abstract protected function newExternalLB( $cluster, $wiki = false );
  147. /**
  148. * Get a cached (tracked) load balancer for external storage
  149. *
  150. * @param string $cluster External storage cluster, or false for core
  151. * @param bool|string $wiki Wiki ID, or false for the current wiki
  152. * @return LoadBalancer
  153. */
  154. abstract public function &getExternalLB( $cluster, $wiki = false );
  155. /**
  156. * Execute a function for each tracked load balancer
  157. * The callback is called with the load balancer as the first parameter,
  158. * and $params passed as the subsequent parameters.
  159. *
  160. * @param callable $callback
  161. * @param array $params
  162. */
  163. abstract public function forEachLB( $callback, array $params = [] );
  164. /**
  165. * Prepare all tracked load balancers for shutdown
  166. * @param integer $flags Supports SHUTDOWN_* flags
  167. * STUB
  168. */
  169. public function shutdown( $flags = 0 ) {
  170. }
  171. /**
  172. * Call a method of each tracked load balancer
  173. *
  174. * @param string $methodName
  175. * @param array $args
  176. */
  177. private function forEachLBCallMethod( $methodName, array $args = [] ) {
  178. $this->forEachLB(
  179. function ( LoadBalancer $loadBalancer, $methodName, array $args ) {
  180. call_user_func_array( [ $loadBalancer, $methodName ], $args );
  181. },
  182. [ $methodName, $args ]
  183. );
  184. }
  185. /**
  186. * Commit on all connections. Done for two reasons:
  187. * 1. To commit changes to the masters.
  188. * 2. To release the snapshot on all connections, master and slave.
  189. * @param string $fname Caller name
  190. */
  191. public function commitAll( $fname = __METHOD__ ) {
  192. $this->logMultiDbTransaction();
  193. $start = microtime( true );
  194. $this->forEachLBCallMethod( 'commitAll', [ $fname ] );
  195. $timeMs = 1000 * ( microtime( true ) - $start );
  196. RequestContext::getMain()->getStats()->timing( "db.commit-all", $timeMs );
  197. }
  198. /**
  199. * Commit changes on all master connections
  200. * @param string $fname Caller name
  201. * @param array $options Options map:
  202. * - maxWriteDuration: abort if more than this much time was spent in write queries
  203. */
  204. public function commitMasterChanges( $fname = __METHOD__, array $options = [] ) {
  205. $limit = isset( $options['maxWriteDuration'] ) ? $options['maxWriteDuration'] : 0;
  206. $this->logMultiDbTransaction();
  207. $this->forEachLB( function ( LoadBalancer $lb ) use ( $limit ) {
  208. $lb->forEachOpenConnection( function ( IDatabase $db ) use ( $limit ) {
  209. $time = $db->pendingWriteQueryDuration();
  210. if ( $limit > 0 && $time > $limit ) {
  211. throw new DBTransactionError(
  212. $db,
  213. wfMessage( 'transaction-duration-limit-exceeded', $time, $limit )->text()
  214. );
  215. }
  216. } );
  217. } );
  218. $this->forEachLBCallMethod( 'commitMasterChanges', [ $fname ] );
  219. }
  220. /**
  221. * Rollback changes on all master connections
  222. * @param string $fname Caller name
  223. * @since 1.23
  224. */
  225. public function rollbackMasterChanges( $fname = __METHOD__ ) {
  226. $this->forEachLBCallMethod( 'rollbackMasterChanges', [ $fname ] );
  227. }
  228. /**
  229. * Log query info if multi DB transactions are going to be committed now
  230. */
  231. private function logMultiDbTransaction() {
  232. $callersByDB = [];
  233. $this->forEachLB( function ( LoadBalancer $lb ) use ( &$callersByDB ) {
  234. $masterName = $lb->getServerName( $lb->getWriterIndex() );
  235. $callers = $lb->pendingMasterChangeCallers();
  236. if ( $callers ) {
  237. $callersByDB[$masterName] = $callers;
  238. }
  239. } );
  240. if ( count( $callersByDB ) >= 2 ) {
  241. $dbs = implode( ', ', array_keys( $callersByDB ) );
  242. $msg = "Multi-DB transaction [{$dbs}]:\n";
  243. foreach ( $callersByDB as $db => $callers ) {
  244. $msg .= "$db: " . implode( '; ', $callers ) . "\n";
  245. }
  246. $this->logger->info( $msg );
  247. }
  248. }
  249. /**
  250. * Determine if any master connection has pending changes
  251. * @return bool
  252. * @since 1.23
  253. */
  254. public function hasMasterChanges() {
  255. $ret = false;
  256. $this->forEachLB( function ( LoadBalancer $lb ) use ( &$ret ) {
  257. $ret = $ret || $lb->hasMasterChanges();
  258. } );
  259. return $ret;
  260. }
  261. /**
  262. * Detemine if any lagged slave connection was used
  263. * @since 1.27
  264. * @return bool
  265. */
  266. public function laggedSlaveUsed() {
  267. $ret = false;
  268. $this->forEachLB( function ( LoadBalancer $lb ) use ( &$ret ) {
  269. $ret = $ret || $lb->laggedSlaveUsed();
  270. } );
  271. return $ret;
  272. }
  273. /**
  274. * Determine if any master connection has pending/written changes from this request
  275. * @return bool
  276. * @since 1.27
  277. */
  278. public function hasOrMadeRecentMasterChanges() {
  279. $ret = false;
  280. $this->forEachLB( function ( LoadBalancer $lb ) use ( &$ret ) {
  281. $ret = $ret || $lb->hasOrMadeRecentMasterChanges();
  282. } );
  283. return $ret;
  284. }
  285. /**
  286. * Waits for the slave DBs to catch up to the current master position
  287. *
  288. * Use this when updating very large numbers of rows, as in maintenance scripts,
  289. * to avoid causing too much lag. Of course, this is a no-op if there are no slaves.
  290. *
  291. * By default this waits on all DB clusters actually used in this request.
  292. * This makes sense when lag being waiting on is caused by the code that does this check.
  293. * In that case, setting "ifWritesSince" can avoid the overhead of waiting for clusters
  294. * that were not changed since the last wait check. To forcefully wait on a specific cluster
  295. * for a given wiki, use the 'wiki' parameter. To forcefully wait on an "external" cluster,
  296. * use the "cluster" parameter.
  297. *
  298. * Never call this function after a large DB write that is *still* in a transaction.
  299. * It only makes sense to call this after the possible lag inducing changes were committed.
  300. *
  301. * @param array $opts Optional fields that include:
  302. * - wiki : wait on the load balancer DBs that handles the given wiki
  303. * - cluster : wait on the given external load balancer DBs
  304. * - timeout : Max wait time. Default: ~60 seconds
  305. * - ifWritesSince: Only wait if writes were done since this UNIX timestamp
  306. * @throws DBReplicationWaitError If a timeout or error occured waiting on a DB cluster
  307. * @since 1.27
  308. */
  309. public function waitForReplication( array $opts = [] ) {
  310. $opts += [
  311. 'wiki' => false,
  312. 'cluster' => false,
  313. 'timeout' => 60,
  314. 'ifWritesSince' => null
  315. ];
  316. // Figure out which clusters need to be checked
  317. /** @var LoadBalancer[] $lbs */
  318. $lbs = [];
  319. if ( $opts['cluster'] !== false ) {
  320. $lbs[] = $this->getExternalLB( $opts['cluster'] );
  321. } elseif ( $opts['wiki'] !== false ) {
  322. $lbs[] = $this->getMainLB( $opts['wiki'] );
  323. } else {
  324. $this->forEachLB( function ( LoadBalancer $lb ) use ( &$lbs ) {
  325. $lbs[] = $lb;
  326. } );
  327. if ( !$lbs ) {
  328. return; // nothing actually used
  329. }
  330. }
  331. // Get all the master positions of applicable DBs right now.
  332. // This can be faster since waiting on one cluster reduces the
  333. // time needed to wait on the next clusters.
  334. $masterPositions = array_fill( 0, count( $lbs ), false );
  335. foreach ( $lbs as $i => $lb ) {
  336. if ( $lb->getServerCount() <= 1 ) {
  337. // Bug 27975 - Don't try to wait for slaves if there are none
  338. // Prevents permission error when getting master position
  339. continue;
  340. } elseif ( $opts['ifWritesSince']
  341. && $lb->lastMasterChangeTimestamp() < $opts['ifWritesSince']
  342. ) {
  343. continue; // no writes since the last wait
  344. }
  345. $masterPositions[$i] = $lb->getMasterPos();
  346. }
  347. $failed = [];
  348. foreach ( $lbs as $i => $lb ) {
  349. if ( $masterPositions[$i] ) {
  350. // The DBMS may not support getMasterPos() or the whole
  351. // load balancer might be fake (e.g. $wgAllDBsAreLocalhost).
  352. if ( !$lb->waitForAll( $masterPositions[$i], $opts['timeout'] ) ) {
  353. $failed[] = $lb->getServerName( $lb->getWriterIndex() );
  354. }
  355. }
  356. }
  357. if ( $failed ) {
  358. throw new DBReplicationWaitError(
  359. "Could not wait for slaves to catch up to " .
  360. implode( ', ', $failed )
  361. );
  362. }
  363. }
  364. /**
  365. * Disable the ChronologyProtector for all load balancers
  366. *
  367. * This can be called at the start of special API entry points
  368. *
  369. * @since 1.27
  370. */
  371. public function disableChronologyProtection() {
  372. $this->chronProt->setEnabled( false );
  373. }
  374. /**
  375. * @return ChronologyProtector
  376. */
  377. protected function newChronologyProtector() {
  378. $request = RequestContext::getMain()->getRequest();
  379. $chronProt = new ChronologyProtector(
  380. ObjectCache::getMainStashInstance(),
  381. [
  382. 'ip' => $request->getIP(),
  383. 'agent' => $request->getHeader( 'User-Agent' )
  384. ]
  385. );
  386. if ( PHP_SAPI === 'cli' ) {
  387. $chronProt->setEnabled( false );
  388. } elseif ( $request->getHeader( 'ChronologyProtection' ) === 'false' ) {
  389. // Request opted out of using position wait logic. This is useful for requests
  390. // done by the job queue or background ETL that do not have a meaningful session.
  391. $chronProt->setWaitEnabled( false );
  392. }
  393. return $chronProt;
  394. }
  395. /**
  396. * @param ChronologyProtector $cp
  397. */
  398. protected function shutdownChronologyProtector( ChronologyProtector $cp ) {
  399. // Get all the master positions needed
  400. $this->forEachLB( function ( LoadBalancer $lb ) use ( $cp ) {
  401. $cp->shutdownLB( $lb );
  402. } );
  403. // Write them to the stash
  404. $unsavedPositions = $cp->shutdown();
  405. // If the positions failed to write to the stash, at least wait on local datacenter
  406. // slaves to catch up before responding. Even if there are several DCs, this increases
  407. // the chance that the user will see their own changes immediately afterwards. As long
  408. // as the sticky DC cookie applies (same domain), this is not even an issue.
  409. $this->forEachLB( function ( LoadBalancer $lb ) use ( $unsavedPositions ) {
  410. $masterName = $lb->getServerName( $lb->getWriterIndex() );
  411. if ( isset( $unsavedPositions[$masterName] ) ) {
  412. $lb->waitForAll( $unsavedPositions[$masterName] );
  413. }
  414. } );
  415. }
  416. }
  417. /**
  418. * Exception class for attempted DB access
  419. */
  420. class DBAccessError extends MWException {
  421. public function __construct() {
  422. parent::__construct( "Mediawiki tried to access the database via wfGetDB(). " .
  423. "This is not allowed." );
  424. }
  425. }
  426. /**
  427. * Exception class for replica DB wait timeouts
  428. */
  429. class DBReplicationWaitError extends Exception {
  430. }