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