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