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