-Destroy the DB automatically when initting the DB
[mediawiki.git] / includes / db / LBFactory.php
blob89a99d084408730aaa00307946460b66607cfbb2
1 <?php
2 /**
3 * Generator of database load balancing objects
5 * @file
6 * @ingroup Database
7 */
9 /**
10 * An interface for generating database load balancers
11 * @ingroup Database
13 abstract class LBFactory {
14 static $instance;
16 /**
17 * Disables all access to the load balancer, will cause all database access
18 * to throw a DBAccessError
20 public static function disableBackend() {
21 global $wgLBFactoryConf;
22 self::$instance = new LBFactory_Fake( $wgLBFactoryConf );
25 /**
26 * Resets the singleton for use if it's been disabled. Does nothing otherwise
28 public static function enableBackend() {
29 if( self::$instance instanceof LBFactory_Fake )
30 self::$instance = null;
33 /**
34 * Get an LBFactory instance
36 static function &singleton() {
37 if ( is_null( self::$instance ) ) {
38 global $wgLBFactoryConf;
39 $class = $wgLBFactoryConf['class'];
40 self::$instance = new $class( $wgLBFactoryConf );
42 return self::$instance;
45 /**
46 * Shut down, close connections and destroy the cached instance.
49 static function destroyInstance() {
50 if ( self::$instance ) {
51 self::$instance->shutdown();
52 self::$instance->forEachLBCallMethod( 'closeAll' );
53 self::$instance = null;
57 /**
58 * Construct a factory based on a configuration array (typically from $wgLBFactoryConf)
60 abstract function __construct( $conf );
62 /**
63 * Create a new load balancer object. The resulting object will be untracked,
64 * not chronology-protected, and the caller is responsible for cleaning it up.
66 * @param $wiki String: wiki ID, or false for the current wiki
67 * @return LoadBalancer
69 abstract function newMainLB( $wiki = false );
71 /**
72 * Get a cached (tracked) load balancer object.
74 * @param $wiki String: wiki ID, or false for the current wiki
75 * @return LoadBalancer
77 abstract function getMainLB( $wiki = false );
80 * Create a new load balancer for external storage. The resulting object will be
81 * untracked, not chronology-protected, and the caller is responsible for
82 * cleaning it up.
84 * @param $cluster String: external storage cluster, or false for core
85 * @param $wiki String: wiki ID, or false for the current wiki
87 abstract function newExternalLB( $cluster, $wiki = false );
90 * Get a cached (tracked) load balancer for external storage
92 * @param $cluster String: external storage cluster, or false for core
93 * @param $wiki String: wiki ID, or false for the current wiki
95 abstract function &getExternalLB( $cluster, $wiki = false );
97 /**
98 * Execute a function for each tracked load balancer
99 * The callback is called with the load balancer as the first parameter,
100 * and $params passed as the subsequent parameters.
102 abstract function forEachLB( $callback, $params = array() );
105 * Prepare all tracked load balancers for shutdown
106 * STUB
108 function shutdown() {}
111 * Call a method of each tracked load balancer
113 function forEachLBCallMethod( $methodName, $args = array() ) {
114 $this->forEachLB( array( $this, 'callMethod' ), array( $methodName, $args ) );
118 * Private helper for forEachLBCallMethod
120 function callMethod( $loadBalancer, $methodName, $args ) {
121 call_user_func_array( array( $loadBalancer, $methodName ), $args );
125 * Commit changes on all master connections
127 function commitMasterChanges() {
128 $this->forEachLBCallMethod( 'commitMasterChanges' );
133 * A simple single-master LBFactory that gets its configuration from the b/c globals
135 class LBFactory_Simple extends LBFactory {
136 var $mainLB;
137 var $extLBs = array();
139 # Chronology protector
140 var $chronProt;
142 function __construct( $conf ) {
143 $this->chronProt = new ChronologyProtector;
146 function newMainLB( $wiki = false ) {
147 global $wgDBservers, $wgMasterWaitTimeout;
148 if ( $wgDBservers ) {
149 $servers = $wgDBservers;
150 } else {
151 global $wgDBserver, $wgDBuser, $wgDBpassword, $wgDBname, $wgDBtype, $wgDebugDumpSql;
152 $servers = array(array(
153 'host' => $wgDBserver,
154 'user' => $wgDBuser,
155 'password' => $wgDBpassword,
156 'dbname' => $wgDBname,
157 'type' => $wgDBtype,
158 'load' => 1,
159 'flags' => ($wgDebugDumpSql ? DBO_DEBUG : 0) | DBO_DEFAULT
163 return new LoadBalancer( array(
164 'servers' => $servers,
165 'masterWaitTimeout' => $wgMasterWaitTimeout
169 function getMainLB( $wiki = false ) {
170 if ( !isset( $this->mainLB ) ) {
171 $this->mainLB = $this->newMainLB( $wiki );
172 $this->mainLB->parentInfo( array( 'id' => 'main' ) );
173 $this->chronProt->initLB( $this->mainLB );
175 return $this->mainLB;
178 function newExternalLB( $cluster, $wiki = false ) {
179 global $wgExternalServers;
180 if ( !isset( $wgExternalServers[$cluster] ) ) {
181 throw new MWException( __METHOD__.": Unknown cluster \"$cluster\"" );
183 return new LoadBalancer( array(
184 'servers' => $wgExternalServers[$cluster]
188 function &getExternalLB( $cluster, $wiki = false ) {
189 if ( !isset( $this->extLBs[$cluster] ) ) {
190 $this->extLBs[$cluster] = $this->newExternalLB( $cluster, $wiki );
191 $this->extLBs[$cluster]->parentInfo( array( 'id' => "ext-$cluster" ) );
193 return $this->extLBs[$cluster];
197 * Execute a function for each tracked load balancer
198 * The callback is called with the load balancer as the first parameter,
199 * and $params passed as the subsequent parameters.
201 function forEachLB( $callback, $params = array() ) {
202 if ( isset( $this->mainLB ) ) {
203 call_user_func_array( $callback, array_merge( array( $this->mainLB ), $params ) );
205 foreach ( $this->extLBs as $lb ) {
206 call_user_func_array( $callback, array_merge( array( $lb ), $params ) );
210 function shutdown() {
211 if ( $this->mainLB ) {
212 $this->chronProt->shutdownLB( $this->mainLB );
214 $this->chronProt->shutdown();
215 $this->commitMasterChanges();
220 * LBFactory class that throws an error on any attempt to use it.
221 * This will typically be done via wfGetDB().
222 * Call LBFactory::disableBackend() to start using this, and
223 * LBFactory::enableBackend() to return to normal behavior
225 class LBFactory_Fake extends LBFactory {
226 function __construct( $conf ) {}
228 function newMainLB( $wiki = false) {
229 throw new DBAccessError;
231 function getMainLB( $wiki = false ) {
232 throw new DBAccessError;
234 function newExternalLB( $cluster, $wiki = false ) {
235 throw new DBAccessError;
237 function &getExternalLB( $cluster, $wiki = false ) {
238 throw new DBAccessError;
240 function forEachLB( $callback, $params = array() ) {}
244 * Exception class for attempted DB access
246 class DBAccessError extends MWException {
247 function __construct() {
248 parent::__construct( "Mediawiki tried to access the database via wfGetDB(). This is not allowed." );
253 * Class for ensuring a consistent ordering of events as seen by the user, despite replication.
254 * Kind of like Hawking's [[Chronology Protection Agency]].
256 class ChronologyProtector {
257 var $startupPos;
258 var $shutdownPos = array();
261 * Initialise a LoadBalancer to give it appropriate chronology protection.
263 * @param $lb LoadBalancer
265 function initLB( $lb ) {
266 if ( $this->startupPos === null ) {
267 if ( !empty( $_SESSION[__CLASS__] ) ) {
268 $this->startupPos = $_SESSION[__CLASS__];
271 if ( !$this->startupPos ) {
272 return;
274 $masterName = $lb->getServerName( 0 );
276 if ( $lb->getServerCount() > 1 && !empty( $this->startupPos[$masterName] ) ) {
277 $info = $lb->parentInfo();
278 $pos = $this->startupPos[$masterName];
279 wfDebug( __METHOD__.": LB " . $info['id'] . " waiting for master pos $pos\n" );
280 $lb->waitFor( $this->startupPos[$masterName] );
285 * Notify the ChronologyProtector that the LoadBalancer is about to shut
286 * down. Saves replication positions.
288 * @param $lb LoadBalancer
290 function shutdownLB( $lb ) {
291 // Don't start a session, don't bother with non-replicated setups
292 if ( strval( session_id() ) == '' || $lb->getServerCount() <= 1 ) {
293 return;
295 $masterName = $lb->getServerName( 0 );
296 if ( isset( $this->shutdownPos[$masterName] ) ) {
297 // Already done
298 return;
300 // Only save the position if writes have been done on the connection
301 $db = $lb->getAnyOpenConnection( 0 );
302 $info = $lb->parentInfo();
303 if ( !$db || !$db->doneWrites() ) {
304 wfDebug( __METHOD__.": LB {$info['id']}, no writes done\n" );
305 return;
307 $pos = $db->getMasterPos();
308 wfDebug( __METHOD__.": LB {$info['id']} has master pos $pos\n" );
309 $this->shutdownPos[$masterName] = $pos;
313 * Notify the ChronologyProtector that the LBFactory is done calling shutdownLB() for now.
314 * May commit chronology data to persistent storage.
316 function shutdown() {
317 if ( session_id() != '' && count( $this->shutdownPos ) ) {
318 wfDebug( __METHOD__.": saving master pos for " .
319 count( $this->shutdownPos ) . " master(s)\n" );
320 $_SESSION[__CLASS__] = $this->shutdownPos;