ILoadBalancer.php 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796
  1. <?php
  2. /**
  3. * Database load balancing interface
  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. namespace Wikimedia\Rdbms;
  24. use Exception;
  25. use LogicException;
  26. use InvalidArgumentException;
  27. /**
  28. * Database cluster connection, tracking, load balancing, and transaction manager interface
  29. *
  30. * A "cluster" is considered to be one master database and zero or more replica databases.
  31. * Typically, the replica DBs replicate from the master asynchronously. The first node in the
  32. * "servers" configuration array is always considered the "master". However, this class can still
  33. * be used when all or some of the "replica" DBs are multi-master peers of the master or even
  34. * when all the DBs are non-replicating clones of each other holding read-only data. Thus, the
  35. * role of "master" is in some cases merely nominal.
  36. *
  37. * By default, each DB server uses DBO_DEFAULT for its 'flags' setting, unless explicitly set
  38. * otherwise in configuration. DBO_DEFAULT behavior depends on whether 'cliMode' is set:
  39. * - In CLI mode, the flag has no effect with regards to LoadBalancer.
  40. * - In non-CLI mode, the flag causes implicit transactions to be used; the first query on
  41. * a database starts a transaction on that database. The transactions are meant to remain
  42. * pending until either commitMasterChanges() or rollbackMasterChanges() is called. The
  43. * application must have some point where it calls commitMasterChanges() near the end of
  44. * the PHP request.
  45. * Every iteration of beginMasterChanges()/commitMasterChanges() is called a "transaction round".
  46. * Rounds are useful on the master DB connections because they make single-DB (and by and large
  47. * multi-DB) updates in web requests all-or-nothing. Also, transactions on replica DBs are useful
  48. * when REPEATABLE-READ or SERIALIZABLE isolation is used because all foriegn keys and constraints
  49. * hold across separate queries in the DB transaction since the data appears within a consistent
  50. * point-in-time snapshot.
  51. *
  52. * The typical caller will use LoadBalancer::getConnection( DB_* ) to yield a live database
  53. * connection handle. The choice of which DB server to use is based on pre-defined loads for
  54. * weighted random selection, adjustments thereof by LoadMonitor, and the amount of replication
  55. * lag on each DB server. Lag checks might cause problems in certain setups, so they should be
  56. * tuned in the server configuration maps as follows:
  57. * - Master + N Replica(s): set 'max lag' to an appropriate threshold for avoiding any database
  58. * lagged by this much or more. If all DBs are this lagged, then the load balancer considers
  59. * the cluster to be read-only.
  60. * - Galera Cluster: Seconds_Behind_Master will be 0, so there probably is nothing to tune.
  61. * Note that lag is still possible depending on how wsrep-sync-wait is set server-side.
  62. * - Read-only archive clones: set 'is static' in the server configuration maps. This will
  63. * treat all such DBs as having 0 lag.
  64. * - Externally updated dataset clones: set 'is static' in the server configuration maps.
  65. * This will treat all such DBs as having 0 lag.
  66. * - SQL load balancing proxy: any proxy should handle lag checks on its own, so the 'max lag'
  67. * parameter should probably be set to INF in the server configuration maps. This will make
  68. * the load balancer ignore whatever it detects as the lag of the logical replica is (which
  69. * would probably just randomly bounce around).
  70. *
  71. * If using a SQL proxy service, it would probably be best to have two proxy hosts for the
  72. * load balancer to talk to. One would be the 'host' of the master server entry and another for
  73. * the (logical) replica server entry. The proxy could map the load balancer's "replica" DB to
  74. * any number of physical replica DBs.
  75. *
  76. * @since 1.28
  77. * @ingroup Database
  78. */
  79. interface ILoadBalancer {
  80. /** @var int Request a replica DB connection */
  81. const DB_REPLICA = -1;
  82. /** @var int Request a master DB connection */
  83. const DB_MASTER = -2;
  84. /** @var string Domain specifier when no specific database needs to be selected */
  85. const DOMAIN_ANY = '';
  86. /** @var string The generic query group */
  87. const GROUP_GENERIC = '';
  88. /** @var int DB handle should have DBO_TRX disabled and the caller will leave it as such */
  89. const CONN_TRX_AUTOCOMMIT = 1;
  90. /** @var int Return null on connection failure instead of throwing an exception */
  91. const CONN_SILENCE_ERRORS = 2;
  92. /** @var int Caller is requesting the master DB server for possibly writes */
  93. const CONN_INTENT_WRITABLE = 4;
  94. /** @var int Bypass and update any server-side read-only mode state cache */
  95. const CONN_REFRESH_READ_ONLY = 8;
  96. /** @var string Manager of ILoadBalancer instances is running post-commit callbacks */
  97. const STAGE_POSTCOMMIT_CALLBACKS = 'stage-postcommit-callbacks';
  98. /** @var string Manager of ILoadBalancer instances is running post-rollback callbacks */
  99. const STAGE_POSTROLLBACK_CALLBACKS = 'stage-postrollback-callbacks';
  100. /**
  101. * Construct a manager of IDatabase connection objects
  102. *
  103. * @param array $params Parameter map with keys:
  104. * - servers : List of server info structures
  105. * - localDomain: A DatabaseDomain or domain ID string
  106. * - loadMonitor : Name of a class used to fetch server lag and load
  107. * - readOnlyReason : Reason the master DB is read-only if so [optional]
  108. * - waitTimeout : Maximum time to wait for replicas for consistency [optional]
  109. * - maxLag: Try to avoid DB replicas with lag above this many seconds [optional]
  110. * - srvCache : BagOStuff object for server cache [optional]
  111. * - wanCache : WANObjectCache object [optional]
  112. * - chronologyCallback: Callback to run before the first connection attempt [optional]
  113. * - defaultGroup: Default query group; the generic group if not specified [optional]
  114. * - hostname : The name of the current server [optional]
  115. * - cliMode: Whether the execution context is a CLI script [optional]
  116. * - profiler : Class name or instance with profileIn()/profileOut() methods [optional]
  117. * - trxProfiler: TransactionProfiler instance [optional]
  118. * - replLogger: PSR-3 logger instance [optional]
  119. * - connLogger: PSR-3 logger instance [optional]
  120. * - queryLogger: PSR-3 logger instance [optional]
  121. * - perfLogger: PSR-3 logger instance [optional]
  122. * - errorLogger : Callback that takes an Exception and logs it [optional]
  123. * - deprecationLogger: Callback to log a deprecation warning [optional]
  124. * - roundStage: STAGE_POSTCOMMIT_* class constant; for internal use [optional]
  125. * - ownerId: integer ID of an LBFactory instance that manages this instance [optional]
  126. * @throws InvalidArgumentException
  127. */
  128. public function __construct( array $params );
  129. /**
  130. * Get the local (and default) database domain ID of connection handles
  131. *
  132. * @see DatabaseDomain
  133. * @return string Database domain ID; this specifies DB name, schema, and table prefix
  134. * @since 1.31
  135. */
  136. public function getLocalDomainID();
  137. /**
  138. * @param DatabaseDomain|string|bool $domain Database domain
  139. * @return string Value of $domain if it is foreign or the local domain otherwise
  140. * @since 1.32
  141. */
  142. public function resolveDomainID( $domain );
  143. /**
  144. * Close all connection and redefine the local domain for testing or schema creation
  145. *
  146. * @param DatabaseDomain|string $domain
  147. * @since 1.33
  148. */
  149. public function redefineLocalDomain( $domain );
  150. /**
  151. * Indicate whether the tables on this domain are only temporary tables for testing
  152. *
  153. * In "temporary tables mode", the ILoadBalancer::CONN_TRX_AUTOCOMMIT flag is ignored
  154. *
  155. * @param bool $value
  156. * @param string $domain
  157. * @return bool Whether "temporary tables mode" was active
  158. * @since 1.34
  159. */
  160. public function setTempTablesOnlyMode( $value, $domain );
  161. /**
  162. * Get the server index of the reader connection for a given group
  163. *
  164. * This takes into account load ratios and lag times. It should return a consistent
  165. * index during the life time of the load balancer. This initially checks replica DBs
  166. * for connectivity to avoid returning an unusable server. This means that connections
  167. * might be attempted by calling this method (usally one at the most but possibly more).
  168. * Subsequent calls with the same $group will not need to make new connection attempts
  169. * since the acquired connection for each group is preserved.
  170. *
  171. * @param string|bool $group Query group or false for the generic group
  172. * @param string|bool $domain DB domain ID or false for the local domain
  173. * @return int|bool Returns false if no live handle can be obtained
  174. */
  175. public function getReaderIndex( $group = false, $domain = false );
  176. /**
  177. * Set the master position to reach before the next generic group DB handle query
  178. *
  179. * If a generic replica DB connection is already open then this immediately waits
  180. * for that DB to catch up to the specified replication position. Otherwise, it will
  181. * do so once such a connection is opened.
  182. *
  183. * If a timeout happens when waiting, then getLaggedReplicaMode()/laggedReplicaUsed()
  184. * will return true.
  185. *
  186. * @param DBMasterPos|bool $pos Master position or false
  187. */
  188. public function waitFor( $pos );
  189. /**
  190. * Set the master wait position and wait for a generic replica DB to catch up to it
  191. *
  192. * This can be used a faster proxy for waitForAll()
  193. *
  194. * @param DBMasterPos|bool $pos Master position or false
  195. * @param int|null $timeout Max seconds to wait; default is mWaitTimeout
  196. * @return bool Success (able to connect and no timeouts reached)
  197. */
  198. public function waitForOne( $pos, $timeout = null );
  199. /**
  200. * Set the master wait position and wait for ALL replica DBs to catch up to it
  201. *
  202. * @param DBMasterPos|bool $pos Master position or false
  203. * @param int|null $timeout Max seconds to wait; default is mWaitTimeout
  204. * @return bool Success (able to connect and no timeouts reached)
  205. */
  206. public function waitForAll( $pos, $timeout = null );
  207. /**
  208. * Get any open connection to a given server index, local or foreign
  209. *
  210. * Use CONN_TRX_AUTOCOMMIT to only look for connections opened with that flag.
  211. * Avoid the use of transaction methods like IDatabase::begin() or IDatabase::startAtomic()
  212. * on any such connections.
  213. *
  214. * @param int $i Server index or DB_MASTER/DB_REPLICA
  215. * @param int $flags Bitfield of CONN_* class constants
  216. * @return Database|bool False if no such connection is open
  217. */
  218. public function getAnyOpenConnection( $i, $flags = 0 );
  219. /**
  220. * Get a live handle for a real or virtual (DB_MASTER/DB_REPLICA) server index
  221. *
  222. * The server index, $i, can be one of the following:
  223. * - DB_REPLICA: a server index will be selected by the load balancer based on read
  224. * weight, connectivity, and replication lag. Note that the master server might be
  225. * configured with read weight. If $groups is empty then it means "the generic group",
  226. * in which case all servers defined with read weight will be considered. Additional
  227. * query groups can be configured, having their own list of server indexes and read
  228. * weights. If a query group list is provided in $groups, then each recognized group
  229. * will be tried, left-to-right, until server index selection succeeds or all groups
  230. * have been tried, in which case the generic group will be tried.
  231. * - DB_MASTER: the master server index will be used; the same as getWriterIndex().
  232. * The value of $groups should be [] when using this server index.
  233. * - Specific server index: a positive integer can be provided to use the server with
  234. * that index. An error will be thrown in no such server index is recognized. This
  235. * server selection method is usually only useful for internal load balancing logic.
  236. * The value of $groups should be [] when using a specific server index.
  237. *
  238. * Handles acquired by this method, getConnectionRef(), getLazyConnectionRef(), and
  239. * getMaintenanceConnectionRef() use the same set of shared connection pools. Callers that
  240. * get a *local* DB domain handle for the same server will share one handle for all of those
  241. * callers using CONN_TRX_AUTOCOMMIT (via $flags) and one handle for all of those callers not
  242. * using CONN_TRX_AUTOCOMMIT. Callers that get a *foreign* DB domain handle (via $domain) will
  243. * share any handle that has the right CONN_TRX_AUTOCOMMIT mode and is already on the right
  244. * DB domain. Otherwise, one of the "free for reuse" handles will be claimed or a new handle
  245. * will be made if there are none.
  246. *
  247. * Handle sharing is particularly useful when callers get local DB domain (the default),
  248. * transaction round aware (the default), DB_MASTER handles. All such callers will operate
  249. * within a single database transaction as a consequence. Handle sharing is also useful when
  250. * callers get local DB domain (the default), transaction round aware (the default), samely
  251. * query grouped (the default), DB_REPLICA handles. All such callers will operate within a
  252. * single database transaction as a consequence.
  253. *
  254. * Calling functions that use $domain must call reuseConnection() once the last query of the
  255. * function is executed. This lets the load balancer share this handle with other callers
  256. * requesting connections on different database domains.
  257. *
  258. * Use CONN_TRX_AUTOCOMMIT to use a separate pool of only auto-commit handles. This flag
  259. * is ignored for databases with ATTR_DB_LEVEL_LOCKING (e.g. sqlite) in order to avoid
  260. * deadlocks. getServerAttributes() can be used to check such attributes beforehand. Avoid
  261. * using IDatabase::begin() and IDatabase::commit() on such handles. If it is not possible
  262. * to avoid using methods like IDatabase::startAtomic() and IDatabase::endAtomic(), callers
  263. * should at least make sure that the atomic sections are closed on failure via try/catch
  264. * and IDatabase::cancelAtomic().
  265. *
  266. * @see ILoadBalancer::reuseConnection()
  267. * @see ILoadBalancer::getServerAttributes()
  268. *
  269. * @param int $i Server index (overrides $groups) or DB_MASTER/DB_REPLICA
  270. * @param string[]|string $groups Query group(s) in preference order; [] for the default group
  271. * @param string|bool $domain DB domain ID or false for the local domain
  272. * @param int $flags Bitfield of CONN_* class constants
  273. *
  274. * @note This method throws DBAccessError if ILoadBalancer::disable() was called
  275. *
  276. * @return IDatabase|bool This returns false on failure if CONN_SILENCE_ERRORS is set
  277. * @throws DBError If no live handle can be obtained and CONN_SILENCE_ERRORS is not set
  278. * @throws DBAccessError If disable() was previously called
  279. * @throws InvalidArgumentException
  280. */
  281. public function getConnection( $i, $groups = [], $domain = false, $flags = 0 );
  282. /**
  283. * Get a live handle for a server index
  284. *
  285. * This is a simpler version of getConnection() that does not accept virtual server
  286. * indexes (e.g. DB_MASTER/DB_REPLICA), does not assure that master DB handles have
  287. * read-only mode when there is high replication lag, and can only trigger attempts
  288. * to connect to a single server (the one with the specified server index).
  289. *
  290. * @see ILoadBalancer::getConnection()
  291. *
  292. * @param int $i Specific server index
  293. * @param string $domain Resolved DB domain
  294. * @param int $flags Bitfield of class CONN_* constants
  295. * @return IDatabase|bool
  296. */
  297. public function getServerConnection( $i, $domain, $flags = 0 );
  298. /**
  299. * Mark a live handle as being available for reuse under a different database domain
  300. *
  301. * This mechanism is reference-counted, and must be called the same number of times as
  302. * getConnection() to work. Never call this on handles acquired via getConnectionRef(),
  303. * getLazyConnectionRef(), and getMaintenanceConnectionRef(), as they already manage
  304. * the logic of calling this method when they fall out of scope in PHP.
  305. *
  306. * @see ILoadBalancer::getConnection()
  307. *
  308. * @param IDatabase $conn
  309. * @throws LogicException
  310. */
  311. public function reuseConnection( IDatabase $conn );
  312. /**
  313. * Get a live database handle reference for a real or virtual (DB_MASTER/DB_REPLICA) server index
  314. *
  315. * The CONN_TRX_AUTOCOMMIT flag is ignored for databases with ATTR_DB_LEVEL_LOCKING
  316. * (e.g. sqlite) in order to avoid deadlocks. getServerAttributes()
  317. * can be used to check such flags beforehand. Avoid the use of begin() or startAtomic()
  318. * on any CONN_TRX_AUTOCOMMIT connections.
  319. *
  320. * @see ILoadBalancer::getConnection() for parameter information
  321. *
  322. * @param int $i Server index or DB_MASTER/DB_REPLICA
  323. * @param string[]|string $groups Query group(s) in preference order; [] for the default group
  324. * @param string|bool $domain DB domain ID or false for the local domain
  325. * @param int $flags Bitfield of CONN_* class constants (e.g. CONN_TRX_AUTOCOMMIT)
  326. * @return DBConnRef
  327. */
  328. public function getConnectionRef( $i, $groups = [], $domain = false, $flags = 0 );
  329. /**
  330. * Get a database handle reference for a real or virtual (DB_MASTER/DB_REPLICA) server index
  331. *
  332. * The handle's methods simply proxy to those of an underlying IDatabase handle which
  333. * takes care of the actual connection and query logic.
  334. *
  335. * The CONN_TRX_AUTOCOMMIT flag is ignored for databases with ATTR_DB_LEVEL_LOCKING
  336. * (e.g. sqlite) in order to avoid deadlocks. getServerAttributes()
  337. * can be used to check such flags beforehand. Avoid the use of begin() or startAtomic()
  338. * on any CONN_TRX_AUTOCOMMIT connections.
  339. *
  340. * @see ILoadBalancer::getConnection() for parameter information
  341. *
  342. * @param int $i Server index or DB_MASTER/DB_REPLICA
  343. * @param string[]|string $groups Query group(s) in preference order; [] for the default group
  344. * @param string|bool $domain DB domain ID or false for the local domain
  345. * @param int $flags Bitfield of CONN_* class constants (e.g. CONN_TRX_AUTOCOMMIT)
  346. * @return DBConnRef
  347. */
  348. public function getLazyConnectionRef( $i, $groups = [], $domain = false, $flags = 0 );
  349. /**
  350. * Get a live database handle for a real or virtual (DB_MASTER/DB_REPLICA) server index
  351. * that can be used for data migrations and schema changes
  352. *
  353. * The handle's methods simply proxy to those of an underlying IDatabase handle which
  354. * takes care of the actual connection and query logic.
  355. *
  356. * The CONN_TRX_AUTOCOMMIT flag is ignored for databases with ATTR_DB_LEVEL_LOCKING
  357. * (e.g. sqlite) in order to avoid deadlocks. getServerAttributes()
  358. * can be used to check such flags beforehand. Avoid the use of begin() or startAtomic()
  359. * on any CONN_TRX_AUTOCOMMIT connections.
  360. *
  361. * @see ILoadBalancer::getConnection() for parameter information
  362. *
  363. * @param int $i Server index or DB_MASTER/DB_REPLICA
  364. * @param string[]|string $groups Query group(s) in preference order; [] for the default group
  365. * @param string|bool $domain DB domain ID or false for the local domain
  366. * @param int $flags Bitfield of CONN_* class constants (e.g. CONN_TRX_AUTOCOMMIT)
  367. * @return MaintainableDBConnRef
  368. */
  369. public function getMaintenanceConnectionRef( $i, $groups = [], $domain = false, $flags = 0 );
  370. /**
  371. * Get the server index of the master server
  372. *
  373. * @return int
  374. */
  375. public function getWriterIndex();
  376. /**
  377. * Get the number of servers defined in configuration
  378. *
  379. * @return int
  380. */
  381. public function getServerCount();
  382. /**
  383. * Whether there are any replica servers configured
  384. *
  385. * This counts both servers using streaming replication from the master server and
  386. * servers that just have a clone of the static dataset found on the master server
  387. *
  388. * @return int
  389. * @since 1.34
  390. */
  391. public function hasReplicaServers();
  392. /**
  393. * Whether any replica servers use streaming replication from the master server
  394. *
  395. * Generally this is one less than getServerCount(), though it might otherwise
  396. * return a lower number if some of the servers are configured with "is static".
  397. * That flag is used when both the server has no active replication setup and the
  398. * dataset is either read-only or occasionally updated out-of-band. For example,
  399. * a script might import a new geographic information dataset each week by writing
  400. * it to each server and later directing the application to use the new version.
  401. *
  402. * It is possible for some replicas to be configured with "is static" but not
  403. * others, though it generally should either be set for all or none of the replicas.
  404. *
  405. * If this returns zero, this means that there is generally no reason to execute
  406. * replication wait logic for session consistency and lag reduction.
  407. *
  408. * @return int
  409. * @since 1.34
  410. */
  411. public function hasStreamingReplicaServers();
  412. /**
  413. * Get the host name or IP address of the server with the specified index
  414. *
  415. * @param int $i
  416. * @return string Readable name if available or IP/host otherwise
  417. */
  418. public function getServerName( $i );
  419. /**
  420. * Return the server info structure for a given index or false if the index is invalid.
  421. * @param int $i
  422. * @return array|bool
  423. * @since 1.31
  424. */
  425. public function getServerInfo( $i );
  426. /**
  427. * Get DB type of the server with the specified index
  428. *
  429. * @param int $i
  430. * @return string One of (mysql,postgres,sqlite,...) or "unknown" for bad indexes
  431. * @since 1.30
  432. */
  433. public function getServerType( $i );
  434. /**
  435. * @param int $i Server index
  436. * @return array (Database::ATTRIBUTE_* constant => value) for all such constants
  437. * @since 1.31
  438. */
  439. public function getServerAttributes( $i );
  440. /**
  441. * Get the current master replication position
  442. *
  443. * @return DBMasterPos|bool Returns false if not applicable
  444. * @throws DBError
  445. */
  446. public function getMasterPos();
  447. /**
  448. * Get the highest DB replication position for chronology control purposes
  449. *
  450. * If there is only a master server then this returns false. If replication is present
  451. * and correctly configured, then this returns the highest replication position of any
  452. * server with an open connection. That position can later be passed to waitFor() on a
  453. * new load balancer instance to make sure that queries on the new connections see data
  454. * at least as up-to-date as queries (prior to this method call) on the old connections.
  455. *
  456. * This can be useful for implementing session consistency, where the session
  457. * will be resumed accross multiple HTTP requests or CLI script instances.
  458. *
  459. * @return DBMasterPos|bool Replication position or false if not applicable
  460. * @since 1.34
  461. */
  462. public function getReplicaResumePos();
  463. /**
  464. * Close all connections and disable this load balancer
  465. *
  466. * Any attempt to open a new connection will result in a DBAccessError.
  467. *
  468. * @param string $fname Caller name
  469. * @param int|null $owner ID of the calling instance (e.g. the LBFactory ID)
  470. */
  471. public function disable( $fname = __METHOD__, $owner = null );
  472. /**
  473. * Close all open connections
  474. *
  475. * @param string $fname Caller name
  476. * @param int|null $owner ID of the calling instance (e.g. the LBFactory ID)
  477. */
  478. public function closeAll( $fname = __METHOD__, $owner = null );
  479. /**
  480. * Close a connection
  481. *
  482. * Using this function makes sure the LoadBalancer knows the connection is closed.
  483. * If you use $conn->close() directly, the load balancer won't update its state.
  484. *
  485. * @param IDatabase $conn
  486. */
  487. public function closeConnection( IDatabase $conn );
  488. /**
  489. * Commit transactions on all open connections
  490. * @param string $fname Caller name
  491. * @param int|null $owner ID of the calling instance (e.g. the LBFactory ID)
  492. * @throws DBExpectedError
  493. */
  494. public function commitAll( $fname = __METHOD__, $owner = null );
  495. /**
  496. * Run pre-commit callbacks and defer execution of post-commit callbacks
  497. *
  498. * Use this only for mutli-database commits
  499. *
  500. * @param string $fname Caller name
  501. * @param int|null $owner ID of the calling instance (e.g. the LBFactory ID)
  502. * @return int Number of pre-commit callbacks run (since 1.32)
  503. */
  504. public function finalizeMasterChanges( $fname = __METHOD__, $owner = null );
  505. /**
  506. * Perform all pre-commit checks for things like replication safety
  507. *
  508. * Use this only for mutli-database commits
  509. *
  510. * @param array $options Includes:
  511. * - maxWriteDuration : max write query duration time in seconds
  512. * @param string $fname Caller name
  513. * @param int|null $owner ID of the calling instance (e.g. the LBFactory ID)
  514. * @throws DBTransactionError
  515. */
  516. public function approveMasterChanges( array $options, $fname, $owner = null );
  517. /**
  518. * Flush any master transaction snapshots and set DBO_TRX (if DBO_DEFAULT is set)
  519. *
  520. * The DBO_TRX setting will be reverted to the default in each of these methods:
  521. * - commitMasterChanges()
  522. * - rollbackMasterChanges()
  523. * - commitAll()
  524. * This allows for custom transaction rounds from any outer transaction scope.
  525. *
  526. * @param string $fname Caller name
  527. * @param int|null $owner ID of the calling instance (e.g. the LBFactory ID)
  528. * @throws DBExpectedError
  529. */
  530. public function beginMasterChanges( $fname = __METHOD__, $owner = null );
  531. /**
  532. * Issue COMMIT on all open master connections to flush changes and view snapshots
  533. * @param string $fname Caller name
  534. * @param int|null $owner ID of the calling instance (e.g. the LBFactory ID)
  535. * @throws DBExpectedError
  536. */
  537. public function commitMasterChanges( $fname = __METHOD__, $owner = null );
  538. /**
  539. * Consume and run all pending post-COMMIT/ROLLBACK callbacks and commit dangling transactions
  540. *
  541. * @param string $fname Caller name
  542. * @param int|null $owner ID of the calling instance (e.g. the LBFactory ID)
  543. * @return Exception|null The first exception or null if there were none
  544. */
  545. public function runMasterTransactionIdleCallbacks( $fname = __METHOD__, $owner = null );
  546. /**
  547. * Run all recurring post-COMMIT/ROLLBACK listener callbacks
  548. *
  549. * @param string $fname Caller name
  550. * @param int|null $owner ID of the calling instance (e.g. the LBFactory ID)
  551. * @return Exception|null The first exception or null if there were none
  552. */
  553. public function runMasterTransactionListenerCallbacks( $fname = __METHOD__, $owner = null );
  554. /**
  555. * Issue ROLLBACK only on master, only if queries were done on connection
  556. * @param string $fname Caller name
  557. * @param int|null $owner ID of the calling instance (e.g. the LBFactory ID)
  558. * @throws DBExpectedError
  559. */
  560. public function rollbackMasterChanges( $fname = __METHOD__, $owner = null );
  561. /**
  562. * Commit all replica DB transactions so as to flush any REPEATABLE-READ or SSI snapshots
  563. *
  564. * @param string $fname Caller name
  565. * @param int|null $owner ID of the calling instance (e.g. the LBFactory ID)
  566. */
  567. public function flushReplicaSnapshots( $fname = __METHOD__, $owner = null );
  568. /**
  569. * Commit all master DB transactions so as to flush any REPEATABLE-READ or SSI snapshots
  570. *
  571. * An error will be thrown if a connection has pending writes or callbacks
  572. *
  573. * @param string $fname Caller name
  574. * @param int|null $owner ID of the calling instance (e.g. the LBFactory ID)
  575. */
  576. public function flushMasterSnapshots( $fname = __METHOD__, $owner = null );
  577. /**
  578. * @return bool Whether a master connection is already open
  579. */
  580. public function hasMasterConnection();
  581. /**
  582. * Whether there are pending changes or callbacks in a transaction by this thread
  583. * @return bool
  584. */
  585. public function hasMasterChanges();
  586. /**
  587. * Get the timestamp of the latest write query done by this thread
  588. * @return float|bool UNIX timestamp or false
  589. */
  590. public function lastMasterChangeTimestamp();
  591. /**
  592. * Check if this load balancer object had any recent or still
  593. * pending writes issued against it by this PHP thread
  594. *
  595. * @param float|null $age How many seconds ago is "recent" [defaults to mWaitTimeout]
  596. * @return bool
  597. */
  598. public function hasOrMadeRecentMasterChanges( $age = null );
  599. /**
  600. * Get the list of callers that have pending master changes
  601. *
  602. * @return string[] List of method names
  603. */
  604. public function pendingMasterChangeCallers();
  605. /**
  606. * @note This method will trigger a DB connection if not yet done
  607. * @param string|bool $domain DB domain ID or false for the local domain
  608. * @return bool Whether the database for generic connections this request is highly "lagged"
  609. */
  610. public function getLaggedReplicaMode( $domain = false );
  611. /**
  612. * Checks whether the database for generic connections this request was both:
  613. * - a) Already choosen due to a prior connection attempt
  614. * - b) Considered highly "lagged"
  615. *
  616. * @note This method will never cause a new DB connection
  617. * @return bool
  618. */
  619. public function laggedReplicaUsed();
  620. /**
  621. * @note This method may trigger a DB connection if not yet done
  622. * @param string|bool $domain DB domain ID or false for the local domain
  623. * @return string|bool Reason the master is read-only or false if it is not
  624. */
  625. public function getReadOnlyReason( $domain = false );
  626. /**
  627. * Disables/enables lag checks
  628. * @param null|bool $mode
  629. * @return bool
  630. */
  631. public function allowLagged( $mode = null );
  632. /**
  633. * @return bool
  634. */
  635. public function pingAll();
  636. /**
  637. * Call a function with each open connection object
  638. * @param callable $callback
  639. * @param array $params
  640. */
  641. public function forEachOpenConnection( $callback, array $params = [] );
  642. /**
  643. * Call a function with each open connection object to a master
  644. * @param callable $callback
  645. * @param array $params
  646. */
  647. public function forEachOpenMasterConnection( $callback, array $params = [] );
  648. /**
  649. * Call a function with each open replica DB connection object
  650. * @param callable $callback
  651. * @param array $params
  652. */
  653. public function forEachOpenReplicaConnection( $callback, array $params = [] );
  654. /**
  655. * Get the hostname and lag time of the most-lagged replica server
  656. *
  657. * This is useful for maintenance scripts that need to throttle their updates.
  658. * May attempt to open connections to replica DBs on the default DB. If there is
  659. * no lag, the maximum lag will be reported as -1.
  660. *
  661. * @param bool|string $domain Domain ID or false for the default database
  662. * @return array ( host, max lag, index of max lagged host )
  663. */
  664. public function getMaxLag( $domain = false );
  665. /**
  666. * Get an estimate of replication lag (in seconds) for each server
  667. *
  668. * Results are cached for a short time in memcached/process cache
  669. *
  670. * Values may be "false" if replication is too broken to estimate
  671. *
  672. * @param string|bool $domain
  673. * @return int[] Map of (server index => float|int|bool)
  674. */
  675. public function getLagTimes( $domain = false );
  676. /**
  677. * Wait for a replica DB to reach a specified master position
  678. *
  679. * If $conn is not a replica server connection, then this will return true.
  680. * Otherwise, if $pos is not provided, this will connect to the master server
  681. * to get an accurate position.
  682. *
  683. * @param IDatabase $conn Replica DB
  684. * @param DBMasterPos|bool $pos Master position; default: current position
  685. * @param int $timeout Timeout in seconds [optional]
  686. * @return bool Success
  687. * @since 1.34
  688. */
  689. public function waitForMasterPos( IDatabase $conn, $pos = false, $timeout = 10 );
  690. /**
  691. * Set a callback via IDatabase::setTransactionListener() on
  692. * all current and future master connections of this load balancer
  693. *
  694. * @param string $name Callback name
  695. * @param callable|null $callback
  696. */
  697. public function setTransactionListener( $name, callable $callback = null );
  698. /**
  699. * Set a new table prefix for the existing local domain ID for testing
  700. *
  701. * @param string $prefix
  702. * @since 1.33
  703. */
  704. public function setLocalDomainPrefix( $prefix );
  705. /**
  706. * Make certain table names use their own database, schema, and table prefix
  707. * when passed into SQL queries pre-escaped and without a qualified database name
  708. *
  709. * For example, "user" can be converted to "myschema.mydbname.user" for convenience.
  710. * Appearances like `user`, somedb.user, somedb.someschema.user will used literally.
  711. *
  712. * Calling this twice will completely clear any old table aliases. Also, note that
  713. * callers are responsible for making sure the schemas and databases actually exist.
  714. *
  715. * @param array[] $aliases Map of (table => (dbname, schema, prefix) map)
  716. */
  717. public function setTableAliases( array $aliases );
  718. /**
  719. * Convert certain index names to alternative names before querying the DB
  720. *
  721. * Note that this applies to indexes regardless of the table they belong to.
  722. *
  723. * This can be employed when an index was renamed X => Y in code, but the new Y-named
  724. * indexes were not yet built on all DBs. After all the Y-named ones are added by the DBA,
  725. * the aliases can be removed, and then the old X-named indexes dropped.
  726. *
  727. * @param string[] $aliases
  728. * @since 1.31
  729. */
  730. public function setIndexAliases( array $aliases );
  731. }