Now it is straightforward to fix bug 89, subst: template parameters.
[lhc/web/wiklou.git] / includes / LoadBalancer.php
1 <?php
2 /**
3 *
4 * @package MediaWiki
5 */
6
7 /**
8 * Depends on the database object
9 */
10 require_once( 'Database.php' );
11
12 # Valid database indexes
13 # Operation-based indexes
14 define( 'DB_SLAVE', -1 ); # Read from the slave (or only server)
15 define( 'DB_MASTER', -2 ); # Write to master (or only server)
16 define( 'DB_LAST', -3 ); # Whatever database was used last
17
18 # Obsolete aliases
19 define( 'DB_READ', -1 );
20 define( 'DB_WRITE', -2 );
21
22 # Task-based indexes
23 # ***NOT USED YET, EXPERIMENTAL***
24 # These may be defined in $wgDBservers. If they aren't, the default reader or writer will be used
25 # Even numbers are always readers, odd numbers are writers
26 define( 'DB_TASK_FIRST', 1000 ); # First in list
27 define( 'DB_SEARCH_R', 1000 ); # Search read
28 define( 'DB_SEARCH_W', 1001 ); # Search write
29 define( 'DB_ASKSQL_R', 1002 ); # Special:Asksql read
30 define( 'DB_WATCHLIST_R', 1004 ); # Watchlist read
31 define( 'DB_TASK_LAST', 1004) ; # Last in list
32
33 define( 'MASTER_WAIT_TIMEOUT', 15 ); # Time to wait for a slave to synchronise
34
35 /**
36 * Database load balancing object
37 *
38 * @todo document
39 * @package MediaWiki
40 */
41 class LoadBalancer {
42 /* private */ var $mServers, $mConnections, $mLoads;
43 /* private */ var $mFailFunction;
44 /* private */ var $mForce, $mReadIndex, $mLastIndex;
45 /* private */ var $mWaitForFile, $mWaitForPos;
46
47 function LoadBalancer()
48 {
49 $this->mServers = array();
50 $this->mConnections = array();
51 $this->mFailFunction = false;
52 $this->mReadIndex = -1;
53 $this->mForce = -1;
54 $this->mLastIndex = -1;
55 }
56
57 function newFromParams( $servers, $failFunction = false )
58 {
59 $lb = new LoadBalancer;
60 $lb->initialise( $servers, $failFunction = false );
61 return $lb;
62 }
63
64 function initialise( $servers, $failFunction = false )
65 {
66 $this->mServers = $servers;
67 $this->mFailFunction = $failFunction;
68 $this->mReadIndex = -1;
69 $this->mWriteIndex = -1;
70 $this->mForce = -1;
71 $this->mConnections = array();
72 $this->mLastIndex = 1;
73 $this->mLoads = array();
74 $this->mWaitForFile = false;
75 $this->mWaitForPos = false;
76
77 foreach( $servers as $i => $server ) {
78 $this->mLoads[$i] = $server['load'];
79 }
80 }
81
82 /**
83 * Given an array of non-normalised probabilities, this function will select
84 * an element and return the appropriate key
85 */
86 function pickRandom( $weights )
87 {
88 if ( !is_array( $weights ) || count( $weights ) == 0 ) {
89 return false;
90 }
91
92 $sum = 0;
93 foreach ( $weights as $w ) {
94 $sum += $w;
95 }
96 $max = mt_getrandmax();
97 $rand = mt_rand(0, $max) / $max * $sum;
98
99 $sum = 0;
100 foreach ( $weights as $i => $w ) {
101 $sum += $w;
102 if ( $sum >= $rand ) {
103 break;
104 }
105 }
106 return $i;
107 }
108
109 function getReaderIndex()
110 {
111 $fname = 'LoadBalancer::getReaderIndex';
112 wfProfileIn( $fname );
113
114 $i = false;
115 if ( $this->mForce >= 0 ) {
116 $i = $this->mForce;
117 } else {
118 if ( $this->mReadIndex >= 0 ) {
119 $i = $this->mReadIndex;
120 } else {
121 # $loads is $this->mLoads except with elements knocked out if they
122 # don't work
123 $loads = $this->mLoads;
124 do {
125 $i = $this->pickRandom( $loads );
126 if ( $i !== false ) {
127 wfDebug( "Using reader #$i: {$this->mServers[$i]['host']}\n" );
128
129 $this->openConnection( $i );
130
131 if ( !$this->isOpen( $i ) ) {
132 unset( $loads[$i] );
133 }
134 }
135 } while ( $i !== false && !$this->isOpen( $i ) );
136
137 if ( $this->isOpen( $i ) ) {
138 $this->mReadIndex = $i;
139 } else {
140 $i = false;
141 }
142 }
143 }
144 wfProfileOut( $fname );
145 return $i;
146 }
147
148 /**
149 * Set the master wait position
150 * If a DB_SLAVE connection has been opened already, waits
151 * Otherwise sets a variable telling it to wait if such a connection is opened
152 */
153 function waitFor( $file, $pos ) {
154 $fname = 'LoadBalancer::waitFor';
155 wfProfileIn( $fname );
156
157 wfDebug( "User master pos: $file $pos\n" );
158 $this->mWaitForFile = false;
159 $this->mWaitForPos = false;
160
161 if ( count( $this->mServers ) > 1 ) {
162 $this->mWaitForFile = $file;
163 $this->mWaitForPos = $pos;
164
165 if ( $this->mReadIndex > 0 ) {
166 if ( !$this->doWait( $this->mReadIndex ) ) {
167 # Use master instead
168 $this->mReadIndex = 0;
169 }
170 }
171 }
172 wfProfileOut( $fname );
173 }
174
175 /**
176 * Wait for a given slave to catch up to the master pos stored in $this
177 */
178 function doWait( $index ) {
179 global $wgMemc;
180
181 $retVal = false;
182
183 $key = 'masterpos:' . $index;
184 $memcPos = $wgMemc->get( $key );
185 if ( $memcPos ) {
186 list( $file, $pos ) = explode( ' ', $memcPos );
187 # If the saved position is later than the requested position, return now
188 if ( $file == $this->mWaitForFile && $this->mWaitForPos <= $pos ) {
189 $retVal = true;
190 }
191 }
192
193 if ( !$retVal && $this->isOpen( $index ) ) {
194 $conn =& $this->mConnections( $index );
195 wfDebug( "Waiting for slave #$index to catch up...\n" );
196 $result = $conn->masterPosWait( $this->mWaitForFile, $this->mWaitForPos, MASTER_WAIT_TIMEOUT );
197
198 if ( $result == -1 || is_null( $result ) ) {
199 # Timed out waiting for slave, use master instead
200 wfDebug( "Timed out waiting for slave #$index pos {$this->mWaitForFile} {$this->mWaitForPos}\n" );
201 $retVal = false;
202 } else {
203 $retVal = true;
204 wfDebug( "Done\n" );
205 }
206 }
207 return $retVal;
208 }
209
210 /**
211 * Get a connection by index
212 */
213 function &getConnection( $i, $fail = true )
214 {
215 $fname = 'LoadBalancer::getConnection';
216 wfProfileIn( $fname );
217 /*
218 # Task-based index
219 if ( $i >= DB_TASK_FIRST && $i < DB_TASK_LAST ) {
220 if ( $i % 2 ) {
221 # Odd index use writer
222 $i = DB_MASTER;
223 } else {
224 # Even index use reader
225 $i = DB_SLAVE;
226 }
227 }*/
228
229 # Operation-based index
230 if ( $i == DB_SLAVE ) {
231 $i = $this->getReaderIndex();
232 } elseif ( $i == DB_MASTER ) {
233 $i = $this->getWriterIndex();
234 } elseif ( $i == DB_LAST ) {
235 # Just use $this->mLastIndex, which should already be set
236 $i = $this->mLastIndex;
237 if ( $i === -1 ) {
238 # Oh dear, not set, best to use the writer for safety
239 wfDebug( "Warning: DB_LAST used when there was no previous index\n" );
240 $i = $this->getWriterIndex();
241 }
242 }
243 # Now we have an explicit index into the servers array
244 $this->openConnection( $i, $fail );
245 wfProfileOut( $fname );
246 return $this->mConnections[$i];
247 }
248
249 /**
250 * Open a connection to the server given by the specified index
251 * Index must be an actual index into the array
252 * @private
253 */
254 function openConnection( $i, $fail = false ) {
255 $fname = 'LoadBalancer::openConnection';
256 wfProfileIn( $fname );
257
258 if ( !$this->isOpen( $i ) ) {
259 $this->mConnections[$i] = $this->reallyOpenConnection( $this->mServers[$i] );
260
261 if ( $i != 0 && $this->mWaitForFile ) {
262 if ( !$this->doWait( $i ) ) {
263 # Error waiting for this slave, use master instead
264 $this->mReadIndex = 0;
265 $i = 0;
266 if ( !$this->isOpen( 0 ) ) {
267 $this->mConnections[0] = $this->reallyOpenConnection( $this->mServers[0] );
268 }
269 wfDebug( "Failed over to {$this->mConnections[0]->mServer}\n" );
270 }
271 }
272 }
273 if ( !$this->isOpen( $i ) ) {
274 wfDebug( "Failed to connect to database $i at {$this->mServers[$i]['host']}\n" );
275 if ( $fail ) {
276 $this->reportConnectionError( $this->mConnections[$i] );
277 }
278 $this->mConnections[$i] = false;
279 }
280 $this->mLastIndex = $i;
281 wfProfileOut( $fname );
282 }
283
284 /**
285 * Test if the specified index represents an open connection
286 * @private
287 */
288 function isOpen( $index ) {
289 if( !is_integer( $index ) ) {
290 return false;
291 }
292 if ( array_key_exists( $index, $this->mConnections ) && is_object( $this->mConnections[$index] ) &&
293 $this->mConnections[$index]->isOpen() )
294 {
295 return true;
296 } else {
297 return false;
298 }
299 }
300
301 /**
302 * Really opens a connection
303 * @private
304 */
305 function reallyOpenConnection( &$server ) {
306 extract( $server );
307 # Get class for this database type
308 $class = 'Database' . ucfirst( $type );
309 if ( !class_exists( $class ) ) {
310 require_once( "$class.php" );
311 }
312
313 # Create object
314 return new $class( $host, $user, $password, $dbname, 1, $flags );
315 }
316
317 function reportConnectionError( &$conn )
318 {
319 $fname = 'LoadBalancer::reportConnectionError';
320 wfProfileIn( $fname );
321 # Prevent infinite recursion
322
323 static $reporting = false;
324 if ( !$reporting ) {
325 $reporting = true;
326 if ( !is_object( $conn ) ) {
327 $conn = new Database;
328 }
329 if ( $this->mFailFunction ) {
330 $conn->failFunction( $this->mFailFunction );
331 } else {
332 $conn->failFunction( 'wfEmergencyAbort' );
333 }
334 $conn->reportConnectionError();
335 $reporting = false;
336 }
337 wfProfileOut( $fname );
338 }
339
340 function getWriterIndex()
341 {
342 return 0;
343 }
344
345 function force( $i )
346 {
347 $this->mForce = $i;
348 }
349
350 function haveIndex( $i )
351 {
352 return array_key_exists( $i, $this->mServers );
353 }
354
355 /**
356 * Get the number of defined servers (not the number of open connections)
357 */
358 function getServerCount() {
359 return count( $this->mServers );
360 }
361
362 /**
363 * Save master pos to the session and to memcached, if the session exists
364 */
365 function saveMasterPos() {
366 global $wgSessionStarted;
367 if ( $wgSessionStarted && count( $this->mServers ) > 1 ) {
368 # If this entire request was served from a slave without opening a connection to the
369 # master (however unlikely that may be), then we can fetch the position from the slave.
370 if ( empty( $this->mConnections[0] ) ) {
371 $conn =& $this->getConnection( DB_SLAVE );
372 list( $file, $pos ) = $conn->getSlavePos();
373 wfDebug( "Saving master pos fetched from slave: $file $pos\n" );
374 } else {
375 $conn =& $this->getConnection( 0 );
376 list( $file, $pos ) = $conn->getMasterPos();
377 wfDebug( "Saving master pos: $file $pos\n" );
378 }
379 if ( $file !== false ) {
380 $_SESSION['master_log_file'] = $file;
381 $_SESSION['master_pos'] = $pos;
382 }
383 }
384 }
385
386 /**
387 * Loads the master pos from the session, waits for it if necessary
388 */
389 function loadMasterPos() {
390 if ( isset( $_SESSION['master_log_file'] ) && isset( $_SESSION['master_pos'] ) ) {
391 $this->waitFor( $_SESSION['master_log_file'], $_SESSION['master_pos'] );
392 }
393 }
394
395 /**
396 * Close all open connections
397 */
398 function closeAll() {
399 foreach( $this->mConnections as $i => $conn ) {
400 if ( $this->isOpen( $i ) ) {
401 $conn->close();
402 }
403 }
404 }
405
406 function commitAll() {
407 foreach( $this->mConnections as $i => $conn ) {
408 if ( $this->isOpen( $i ) ) {
409 $conn->immediateCommit();
410 }
411 }
412 }
413 }