Update ApiBase::PARAM_* comments
[mediawiki.git] / includes / db / loadbalancer / LBFactory.php
blobeeeca6283c1bc1a3898ec906823a00483d939b7b
1 <?php
2 /**
3 * Generator of database load balancing objects.
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.
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.
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
20 * @file
21 * @ingroup Database
24 /**
25 * An interface for generating database load balancers
26 * @ingroup Database
28 abstract class LBFactory {
29 /** @var ChronologyProtector */
30 protected $chronProt;
32 /** @var LBFactory */
33 private static $instance;
35 /** @var string|bool Reason all LBs are read-only or false if not */
36 protected $readOnlyReason = false;
38 const SHUTDOWN_NO_CHRONPROT = 1; // don't save ChronologyProtector positions (for async code)
40 /**
41 * Construct a factory based on a configuration array (typically from $wgLBFactoryConf)
42 * @param array $conf
44 public function __construct( array $conf ) {
45 if ( isset( $conf['readOnlyReason'] ) && is_string( $conf['readOnlyReason'] ) ) {
46 $this->readOnlyReason = $conf['readOnlyReason'];
49 $this->chronProt = $this->newChronologyProtector();
52 /**
53 * Disables all access to the load balancer, will cause all database access
54 * to throw a DBAccessError
56 public static function disableBackend() {
57 global $wgLBFactoryConf;
58 self::$instance = new LBFactoryFake( $wgLBFactoryConf );
61 /**
62 * Get an LBFactory instance
64 * @return LBFactory
66 public static function singleton() {
67 global $wgLBFactoryConf;
69 if ( is_null( self::$instance ) ) {
70 $class = self::getLBFactoryClass( $wgLBFactoryConf );
71 $config = $wgLBFactoryConf;
72 if ( !isset( $config['readOnlyReason'] ) ) {
73 $config['readOnlyReason'] = wfConfiguredReadOnlyReason();
75 self::$instance = new $class( $config );
78 return self::$instance;
81 /**
82 * Returns the LBFactory class to use and the load balancer configuration.
84 * @param array $config (e.g. $wgLBFactoryConf)
85 * @return string Class name
87 public static function getLBFactoryClass( array $config ) {
88 // For configuration backward compatibility after removing
89 // underscores from class names in MediaWiki 1.23.
90 $bcClasses = array(
91 'LBFactory_Simple' => 'LBFactorySimple',
92 'LBFactory_Single' => 'LBFactorySingle',
93 'LBFactory_Multi' => 'LBFactoryMulti',
94 'LBFactory_Fake' => 'LBFactoryFake',
97 $class = $config['class'];
99 if ( isset( $bcClasses[$class] ) ) {
100 $class = $bcClasses[$class];
101 wfDeprecated(
102 '$wgLBFactoryConf must be updated. See RELEASE-NOTES for details',
103 '1.23'
107 return $class;
111 * Shut down, close connections and destroy the cached instance.
113 public static function destroyInstance() {
114 if ( self::$instance ) {
115 self::$instance->shutdown();
116 self::$instance->forEachLBCallMethod( 'closeAll' );
117 self::$instance = null;
122 * Set the instance to be the given object
124 * @param LBFactory $instance
126 public static function setInstance( $instance ) {
127 self::destroyInstance();
128 self::$instance = $instance;
132 * Create a new load balancer object. The resulting object will be untracked,
133 * not chronology-protected, and the caller is responsible for cleaning it up.
135 * @param bool|string $wiki Wiki ID, or false for the current wiki
136 * @return LoadBalancer
138 abstract public function newMainLB( $wiki = false );
141 * Get a cached (tracked) load balancer object.
143 * @param bool|string $wiki Wiki ID, or false for the current wiki
144 * @return LoadBalancer
146 abstract public function getMainLB( $wiki = false );
149 * Create a new load balancer for external storage. The resulting object will be
150 * untracked, not chronology-protected, and the caller is responsible for
151 * cleaning it up.
153 * @param string $cluster External storage cluster, or false for core
154 * @param bool|string $wiki Wiki ID, or false for the current wiki
155 * @return LoadBalancer
157 abstract protected function newExternalLB( $cluster, $wiki = false );
160 * Get a cached (tracked) load balancer for external storage
162 * @param string $cluster External storage cluster, or false for core
163 * @param bool|string $wiki Wiki ID, or false for the current wiki
164 * @return LoadBalancer
166 abstract public function &getExternalLB( $cluster, $wiki = false );
169 * Execute a function for each tracked load balancer
170 * The callback is called with the load balancer as the first parameter,
171 * and $params passed as the subsequent parameters.
173 * @param callable $callback
174 * @param array $params
176 abstract public function forEachLB( $callback, array $params = array() );
179 * Prepare all tracked load balancers for shutdown
180 * @param integer $flags Supports SHUTDOWN_* flags
181 * STUB
183 public function shutdown( $flags = 0 ) {
187 * Call a method of each tracked load balancer
189 * @param string $methodName
190 * @param array $args
192 private function forEachLBCallMethod( $methodName, array $args = array() ) {
193 $this->forEachLB( function ( LoadBalancer $loadBalancer, $methodName, array $args ) {
194 call_user_func_array( array( $loadBalancer, $methodName ), $args );
195 }, array( $methodName, $args ) );
199 * Commit on all connections. Done for two reasons:
200 * 1. To commit changes to the masters.
201 * 2. To release the snapshot on all connections, master and slave.
203 public function commitAll() {
204 $this->forEachLBCallMethod( 'commitAll' );
208 * Commit changes on all master connections
210 public function commitMasterChanges() {
211 $start = microtime( true );
212 $this->forEachLBCallMethod( 'commitMasterChanges' );
213 $timeMs = 1000 * ( microtime( true ) - $start );
214 RequestContext::getMain()->getStats()->timing( "db.commit-masters", $timeMs );
218 * Rollback changes on all master connections
219 * @since 1.23
221 public function rollbackMasterChanges() {
222 $this->forEachLBCallMethod( 'rollbackMasterChanges' );
226 * Determine if any master connection has pending changes
227 * @return bool
228 * @since 1.23
230 public function hasMasterChanges() {
231 $ret = false;
232 $this->forEachLB( function ( LoadBalancer $lb ) use ( &$ret ) {
233 $ret = $ret || $lb->hasMasterChanges();
234 } );
236 return $ret;
240 * Detemine if any lagged slave connection was used
241 * @since 1.27
242 * @return bool
244 public function laggedSlaveUsed() {
245 $ret = false;
246 $this->forEachLB( function ( LoadBalancer $lb ) use ( &$ret ) {
247 $ret = $ret || $lb->laggedSlaveUsed();
248 } );
250 return $ret;
254 * Determine if any master connection has pending/written changes from this request
255 * @return bool
256 * @since 1.27
258 public function hasOrMadeRecentMasterChanges() {
259 $ret = false;
260 $this->forEachLB( function ( LoadBalancer $lb ) use ( &$ret ) {
261 $ret = $ret || $lb->hasOrMadeRecentMasterChanges();
262 } );
263 return $ret;
267 * Disable the ChronologyProtector for all load balancers
269 * This can be called at the start of special API entry points
271 * @since 1.27
273 public function disableChronologyProtection() {
274 $this->chronProt->setEnabled( false );
278 * @return ChronologyProtector
280 protected function newChronologyProtector() {
281 $request = RequestContext::getMain()->getRequest();
282 $chronProt = new ChronologyProtector(
283 ObjectCache::getMainStashInstance(),
284 array(
285 'ip' => $request->getIP(),
286 'agent' => $request->getHeader( 'User-Agent' )
289 if ( PHP_SAPI === 'cli' ) {
290 $chronProt->setEnabled( false );
291 } elseif ( $request->getHeader( 'ChronologyProtection' ) === 'false' ) {
292 // Request opted out of using position wait logic. This is useful for requests
293 // done by the job queue or background ETL that do not have a meaningful session.
294 $chronProt->setWaitEnabled( false );
297 return $chronProt;
301 * @param ChronologyProtector $cp
303 protected function shutdownChronologyProtector( ChronologyProtector $cp ) {
304 // Get all the master positions needed
305 $this->forEachLB( function ( LoadBalancer $lb ) use ( $cp ) {
306 $cp->shutdownLB( $lb );
307 } );
308 // Write them to the stash
309 $unsavedPositions = $cp->shutdown();
310 // If the positions failed to write to the stash, at least wait on local datacenter
311 // slaves to catch up before responding. Even if there are several DCs, this increases
312 // the chance that the user will see their own changes immediately afterwards. As long
313 // as the sticky DC cookie applies (same domain), this is not even an issue.
314 $this->forEachLB( function ( LoadBalancer $lb ) use ( $unsavedPositions ) {
315 $masterName = $lb->getServerName( $lb->getWriterIndex() );
316 if ( isset( $unsavedPositions[$masterName] ) ) {
317 $lb->waitForAll( $unsavedPositions[$masterName] );
319 } );
324 * Exception class for attempted DB access
326 class DBAccessError extends MWException {
327 public function __construct() {
328 parent::__construct( "Mediawiki tried to access the database via wfGetDB(). " .
329 "This is not allowed." );