Merge new-installer branch to trunk
[lhc/web/wiklou.git] / includes / db / LBFactory.php
1 <?php
2 /**
3 * @file
4 * @ingroup Database
5 */
6
7 /**
8 * An interface for generating database load balancers
9 * @ingroup Database
10 */
11 abstract class LBFactory {
12 static $instance;
13
14 /**
15 * Disables all access to the load balancer, will cause all database access
16 * to throw a DBAccessError
17 */
18 public static function disableBackend() {
19 global $wgLBFactoryConf;
20 self::$instance = new LBFactory_Fake( $wgLBFactoryConf );
21 }
22
23 /**
24 * Resets the singleton for use if it's been disabled. Does nothing otherwise
25 */
26 public static function enableBackend() {
27 if( self::$instance instanceof LBFactory_Fake )
28 self::$instance = null;
29 }
30
31 /**
32 * Get an LBFactory instance
33 */
34 static function &singleton() {
35 if ( is_null( self::$instance ) ) {
36 global $wgLBFactoryConf;
37 $class = $wgLBFactoryConf['class'];
38 self::$instance = new $class( $wgLBFactoryConf );
39 }
40 return self::$instance;
41 }
42
43 /**
44 * Shut down, close connections and destroy the cached instance.
45 *
46 */
47 static function destroyInstance() {
48 if ( self::$instance ) {
49 self::$instance->shutdown();
50 self::$instance->forEachLBCallMethod( 'closeAll' );
51 self::$instance = null;
52 }
53 }
54
55 /**
56 * Construct a factory based on a configuration array (typically from $wgLBFactoryConf)
57 */
58 abstract function __construct( $conf );
59
60 /**
61 * Create a new load balancer object. The resulting object will be untracked,
62 * not chronology-protected, and the caller is responsible for cleaning it up.
63 *
64 * @param $wiki String: wiki ID, or false for the current wiki
65 * @return LoadBalancer
66 */
67 abstract function newMainLB( $wiki = false );
68
69 /**
70 * Get a cached (tracked) load balancer object.
71 *
72 * @param $wiki String: wiki ID, or false for the current wiki
73 * @return LoadBalancer
74 */
75 abstract function getMainLB( $wiki = false );
76
77 /*
78 * Create a new load balancer for external storage. The resulting object will be
79 * untracked, not chronology-protected, and the caller is responsible for
80 * cleaning it up.
81 *
82 * @param $cluster String: external storage cluster, or false for core
83 * @param $wiki String: wiki ID, or false for the current wiki
84 */
85 abstract function newExternalLB( $cluster, $wiki = false );
86
87 /*
88 * Get a cached (tracked) load balancer for external storage
89 *
90 * @param $cluster String: external storage cluster, or false for core
91 * @param $wiki String: wiki ID, or false for the current wiki
92 */
93 abstract function &getExternalLB( $cluster, $wiki = false );
94
95 /**
96 * Execute a function for each tracked load balancer
97 * The callback is called with the load balancer as the first parameter,
98 * and $params passed as the subsequent parameters.
99 */
100 abstract function forEachLB( $callback, $params = array() );
101
102 /**
103 * Prepare all tracked load balancers for shutdown
104 * STUB
105 */
106 function shutdown() {}
107
108 /**
109 * Call a method of each tracked load balancer
110 */
111 function forEachLBCallMethod( $methodName, $args = array() ) {
112 $this->forEachLB( array( $this, 'callMethod' ), array( $methodName, $args ) );
113 }
114
115 /**
116 * Private helper for forEachLBCallMethod
117 */
118 function callMethod( $loadBalancer, $methodName, $args ) {
119 call_user_func_array( array( $loadBalancer, $methodName ), $args );
120 }
121
122 /**
123 * Commit changes on all master connections
124 */
125 function commitMasterChanges() {
126 $this->forEachLBCallMethod( 'commitMasterChanges' );
127 }
128 }
129
130 /**
131 * A simple single-master LBFactory that gets its configuration from the b/c globals
132 */
133 class LBFactory_Simple extends LBFactory {
134 var $mainLB;
135 var $extLBs = array();
136
137 # Chronology protector
138 var $chronProt;
139
140 function __construct( $conf ) {
141 $this->chronProt = new ChronologyProtector;
142 }
143
144 function newMainLB( $wiki = false ) {
145 global $wgDBservers, $wgMasterWaitTimeout;
146 if ( $wgDBservers ) {
147 $servers = $wgDBservers;
148 } else {
149 global $wgDBserver, $wgDBuser, $wgDBpassword, $wgDBname, $wgDBtype, $wgDebugDumpSql;
150 $servers = array(array(
151 'host' => $wgDBserver,
152 'user' => $wgDBuser,
153 'password' => $wgDBpassword,
154 'dbname' => $wgDBname,
155 'type' => $wgDBtype,
156 'load' => 1,
157 'flags' => ($wgDebugDumpSql ? DBO_DEBUG : 0) | DBO_DEFAULT
158 ));
159 }
160
161 return new LoadBalancer( array(
162 'servers' => $servers,
163 'masterWaitTimeout' => $wgMasterWaitTimeout
164 ));
165 }
166
167 function getMainLB( $wiki = false ) {
168 if ( !isset( $this->mainLB ) ) {
169 $this->mainLB = $this->newMainLB( $wiki );
170 $this->mainLB->parentInfo( array( 'id' => 'main' ) );
171 $this->chronProt->initLB( $this->mainLB );
172 }
173 return $this->mainLB;
174 }
175
176 function newExternalLB( $cluster, $wiki = false ) {
177 global $wgExternalServers;
178 if ( !isset( $wgExternalServers[$cluster] ) ) {
179 throw new MWException( __METHOD__.": Unknown cluster \"$cluster\"" );
180 }
181 return new LoadBalancer( array(
182 'servers' => $wgExternalServers[$cluster]
183 ));
184 }
185
186 function &getExternalLB( $cluster, $wiki = false ) {
187 if ( !isset( $this->extLBs[$cluster] ) ) {
188 $this->extLBs[$cluster] = $this->newExternalLB( $cluster, $wiki );
189 $this->extLBs[$cluster]->parentInfo( array( 'id' => "ext-$cluster" ) );
190 }
191 return $this->extLBs[$cluster];
192 }
193
194 /**
195 * Execute a function for each tracked load balancer
196 * The callback is called with the load balancer as the first parameter,
197 * and $params passed as the subsequent parameters.
198 */
199 function forEachLB( $callback, $params = array() ) {
200 if ( isset( $this->mainLB ) ) {
201 call_user_func_array( $callback, array_merge( array( $this->mainLB ), $params ) );
202 }
203 foreach ( $this->extLBs as $lb ) {
204 call_user_func_array( $callback, array_merge( array( $lb ), $params ) );
205 }
206 }
207
208 function shutdown() {
209 if ( $this->mainLB ) {
210 $this->chronProt->shutdownLB( $this->mainLB );
211 }
212 $this->chronProt->shutdown();
213 $this->commitMasterChanges();
214 }
215 }
216
217 /**
218 * LBFactory class that throws an error on any attempt to use it.
219 * This will typically be done via wfGetDB().
220 * Call LBFactory::disable() to start using this, and LBFactory::enable() to
221 * return to normal behavior
222 */
223 class LBFactory_Fake extends LBFactory {
224 function __construct( $conf ) {}
225
226 function newMainLB( $wiki = false) {
227 throw new DBAccessError;
228 }
229 function getMainLB( $wiki = false ) {
230 throw new DBAccessError;
231 }
232 function newExternalLB( $cluster, $wiki = false ) {
233 throw new DBAccessError;
234 }
235 function &getExternalLB( $cluster, $wiki = false ) {
236 throw new DBAccessError;
237 }
238 function forEachLB( $callback, $params = array() ) {}
239 }
240
241 /**
242 * Exception class for attempted DB access
243 */
244 class DBAccessError extends MWException {
245 function __construct() {
246 parent::__construct( "Mediawiki tried to access the database via wfGetDB(). This is not allowed." );
247 }
248 }
249
250 /**
251 * Class for ensuring a consistent ordering of events as seen by the user, despite replication.
252 * Kind of like Hawking's [[Chronology Protection Agency]].
253 */
254 class ChronologyProtector {
255 var $startupPos;
256 var $shutdownPos = array();
257
258 /**
259 * Initialise a LoadBalancer to give it appropriate chronology protection.
260 *
261 * @param $lb LoadBalancer
262 */
263 function initLB( $lb ) {
264 if ( $this->startupPos === null ) {
265 if ( !empty( $_SESSION[__CLASS__] ) ) {
266 $this->startupPos = $_SESSION[__CLASS__];
267 }
268 }
269 if ( !$this->startupPos ) {
270 return;
271 }
272 $masterName = $lb->getServerName( 0 );
273
274 if ( $lb->getServerCount() > 1 && !empty( $this->startupPos[$masterName] ) ) {
275 $info = $lb->parentInfo();
276 $pos = $this->startupPos[$masterName];
277 wfDebug( __METHOD__.": LB " . $info['id'] . " waiting for master pos $pos\n" );
278 $lb->waitFor( $this->startupPos[$masterName] );
279 }
280 }
281
282 /**
283 * Notify the ChronologyProtector that the LoadBalancer is about to shut
284 * down. Saves replication positions.
285 *
286 * @param $lb LoadBalancer
287 */
288 function shutdownLB( $lb ) {
289 // Don't start a session, don't bother with non-replicated setups
290 if ( strval( session_id() ) == '' || $lb->getServerCount() <= 1 ) {
291 return;
292 }
293 $masterName = $lb->getServerName( 0 );
294 if ( isset( $this->shutdownPos[$masterName] ) ) {
295 // Already done
296 return;
297 }
298 // Only save the position if writes have been done on the connection
299 $db = $lb->getAnyOpenConnection( 0 );
300 $info = $lb->parentInfo();
301 if ( !$db || !$db->doneWrites() ) {
302 wfDebug( __METHOD__.": LB {$info['id']}, no writes done\n" );
303 return;
304 }
305 $pos = $db->getMasterPos();
306 wfDebug( __METHOD__.": LB {$info['id']} has master pos $pos\n" );
307 $this->shutdownPos[$masterName] = $pos;
308 }
309
310 /**
311 * Notify the ChronologyProtector that the LBFactory is done calling shutdownLB() for now.
312 * May commit chronology data to persistent storage.
313 */
314 function shutdown() {
315 if ( session_id() != '' && count( $this->shutdownPos ) ) {
316 wfDebug( __METHOD__.": saving master pos for " .
317 count( $this->shutdownPos ) . " master(s)\n" );
318 $_SESSION[__CLASS__] = $this->shutdownPos;
319 }
320 }
321 }