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