fixed connection error handling
[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 /**
23 * Database load balancing object
24 *
25 * @todo document
26 * @package MediaWiki
27 */
28 class LoadBalancer {
29 /* private */ var $mServers, $mConnections, $mLoads, $mGroupLoads;
30 /* private */ var $mFailFunction, $mErrorConnection;
31 /* private */ var $mForce, $mReadIndex, $mLastIndex;
32 /* private */ var $mWaitForFile, $mWaitForPos, $mWaitTimeout;
33 /* private */ var $mLaggedSlaveMode;
34
35 function LoadBalancer()
36 {
37 $this->mServers = array();
38 $this->mConnections = array();
39 $this->mFailFunction = false;
40 $this->mReadIndex = -1;
41 $this->mForce = -1;
42 $this->mLastIndex = -1;
43 $this->mErrorConnection = false;
44 }
45
46 function newFromParams( $servers, $failFunction = false, $waitTimeout = 10 )
47 {
48 $lb = new LoadBalancer;
49 $lb->initialise( $servers, $failFunction, $waitTimeout );
50 return $lb;
51 }
52
53 function initialise( $servers, $failFunction = false, $waitTimeout = 10 )
54 {
55 $this->mServers = $servers;
56 $this->mFailFunction = $failFunction;
57 $this->mReadIndex = -1;
58 $this->mWriteIndex = -1;
59 $this->mForce = -1;
60 $this->mConnections = array();
61 $this->mLastIndex = 1;
62 $this->mLoads = array();
63 $this->mWaitForFile = false;
64 $this->mWaitForPos = false;
65 $this->mWaitTimeout = $waitTimeout;
66 $this->mLaggedSlaveMode = false;
67
68 foreach( $servers as $i => $server ) {
69 $this->mLoads[$i] = $server['load'];
70 if ( isset( $server['groupLoads'] ) ) {
71 foreach ( $server['groupLoads'] as $group => $ratio ) {
72 if ( !isset( $this->mGroupLoads[$group] ) ) {
73 $this->mGroupLoads[$group] = array();
74 }
75 $this->mGroupLoads[$group][$i] = $ratio;
76 }
77 }
78 }
79 }
80
81 /**
82 * Given an array of non-normalised probabilities, this function will select
83 * an element and return the appropriate key
84 */
85 function pickRandom( $weights )
86 {
87 if ( !is_array( $weights ) || count( $weights ) == 0 ) {
88 return false;
89 }
90
91 $sum = 0;
92 foreach ( $weights as $w ) {
93 $sum += $w;
94 }
95
96 if ( $sum == 0 ) {
97 # No loads on any of them
98 # Just pick one at random
99 foreach ( $weights as $i => $w ) {
100 $weights[$i] = 1;
101 }
102 }
103 $max = mt_getrandmax();
104 $rand = mt_rand(0, $max) / $max * $sum;
105
106 $sum = 0;
107 foreach ( $weights as $i => $w ) {
108 $sum += $w;
109 if ( $sum >= $rand ) {
110 break;
111 }
112 }
113 return $i;
114 }
115
116 function getRandomNonLagged( $loads ) {
117 # Unset excessively lagged servers
118 $lags = $this->getLagTimes();
119 foreach ( $lags as $i => $lag ) {
120 if ( isset( $this->mServers[$i]['max lag'] ) && $lag > $this->mServers[$i]['max lag'] ) {
121 unset( $loads[$i] );
122 }
123 }
124
125
126 # Find out if all the slaves with non-zero load are lagged
127 $sum = 0;
128 foreach ( $loads as $load ) {
129 $sum += $load;
130 }
131 if ( $sum == 0 ) {
132 # No appropriate DB servers except maybe the master and some slaves with zero load
133 # Do NOT use the master
134 # Instead, this function will return false, triggering read-only mode,
135 # and a lagged slave will be used instead.
136 unset ( $loads[0] );
137 }
138
139 if ( count( $loads ) == 0 ) {
140 return false;
141 }
142
143 #wfDebug( var_export( $loads, true ) );
144
145 # Return a random representative of the remainder
146 return $this->pickRandom( $loads );
147 }
148
149 /**
150 * Get the index of the reader connection, which may be a slave
151 * This takes into account load ratios and lag times. It should
152 * always return a consistent index during a given invocation
153 *
154 * Side effect: opens connections to databases
155 */
156 function getReaderIndex()
157 {
158 global $wgMaxLag, $wgReadOnly, $wgDBClusterTimeout;
159
160 $fname = 'LoadBalancer::getReaderIndex';
161 wfProfileIn( $fname );
162
163 $i = false;
164 if ( $this->mForce >= 0 ) {
165 $i = $this->mForce;
166 } else {
167 if ( $this->mReadIndex >= 0 ) {
168 $i = $this->mReadIndex;
169 } else {
170 # $loads is $this->mLoads except with elements knocked out if they
171 # don't work
172 $loads = $this->mLoads;
173 $done = false;
174 $totalElapsed = 0;
175 do {
176 if ( $wgReadOnly ) {
177 $i = $this->pickRandom( $loads );
178 } else {
179 $i = $this->getRandomNonLagged( $loads );
180 if ( $i === false && count( $loads ) != 0 ) {
181 # All slaves lagged. Switch to read-only mode
182 $wgReadOnly = wfMsgNoDB( 'readonly_lag' );
183 $i = $this->pickRandom( $loads );
184 }
185 }
186 if ( $i !== false ) {
187 wfDebug( "Using reader #$i: {$this->mServers[$i]['host']}...\n" );
188 $this->openConnection( $i );
189
190 if ( !$this->isOpen( $i ) ) {
191 wfDebug( "Failed\n" );
192 unset( $loads[$i] );
193 $sleepTime = 0;
194 } else {
195 $status = $this->mConnections[$i]->getStatus();
196 if ( isset( $this->mServers[$i]['max threads'] ) &&
197 $status['Threads_running'] > $this->mServers[$i]['max threads'] )
198 {
199 # Slave is lagged, wait for a while
200 $sleepTime = 5000 * $status['Threads_connected'];
201
202 # If we reach the timeout and exit the loop, don't use it
203 $i = false;
204 } else {
205 $done = true;
206 $sleepTime = 0;
207 }
208 }
209 } else {
210 $sleepTime = 500000;
211 }
212 if ( $sleepTime ) {
213 $totalElapsed += $sleepTime;
214 usleep( $sleepTime );
215 }
216 } while ( count( $loads ) && !$done && $totalElapsed / 1e6 < $wgDBClusterTimeout );
217
218 if ( $i !== false && $this->isOpen( $i ) ) {
219 # Wait for the session master pos for a short time
220 if ( $this->mWaitForFile ) {
221 if ( !$this->doWait( $i ) ) {
222 $this->mServers[$i]['slave pos'] = $this->mConnections[$i]->getSlavePos();
223 }
224 }
225 if ( $i !== false ) {
226 $this->mReadIndex = $i;
227 }
228 } else {
229 $i = false;
230 }
231 }
232 }
233 wfProfileOut( $fname );
234 return $i;
235 }
236
237 /**
238 * Get a random server to use in a query group
239 */
240 function getGroupIndex( $group ) {
241 if ( isset( $this->mGroupLoads[$group] ) ) {
242 $i = $this->pickRandom( $this->mGroupLoads[$group] );
243 } else {
244 $i = false;
245 }
246 wfDebug( "Query group $group => $i\n" );
247 return $i;
248 }
249
250 /**
251 * Set the master wait position
252 * If a DB_SLAVE connection has been opened already, waits
253 * Otherwise sets a variable telling it to wait if such a connection is opened
254 */
255 function waitFor( $file, $pos ) {
256 $fname = 'LoadBalancer::waitFor';
257 wfProfileIn( $fname );
258
259 wfDebug( "User master pos: $file $pos\n" );
260 $this->mWaitForFile = false;
261 $this->mWaitForPos = false;
262
263 if ( count( $this->mServers ) > 1 ) {
264 $this->mWaitForFile = $file;
265 $this->mWaitForPos = $pos;
266 $i = $this->mReadIndex;
267
268 if ( $i > 0 ) {
269 if ( !$this->doWait( $i ) ) {
270 $this->mServers[$i]['slave pos'] = $this->mConnections[$i]->getSlavePos();
271 $this->mLaggedSlaveMode = true;
272 }
273 }
274 }
275 wfProfileOut( $fname );
276 }
277
278 /**
279 * Wait for a given slave to catch up to the master pos stored in $this
280 */
281 function doWait( $index ) {
282 global $wgMemc;
283
284 $retVal = false;
285
286 # Debugging hacks
287 if ( isset( $this->mServers[$index]['lagged slave'] ) ) {
288 return false;
289 } elseif ( isset( $this->mServers[$index]['fake slave'] ) ) {
290 return true;
291 }
292
293 $key = 'masterpos:' . $index;
294 $memcPos = $wgMemc->get( $key );
295 if ( $memcPos ) {
296 list( $file, $pos ) = explode( ' ', $memcPos );
297 # If the saved position is later than the requested position, return now
298 if ( $file == $this->mWaitForFile && $this->mWaitForPos <= $pos ) {
299 $retVal = true;
300 }
301 }
302
303 if ( !$retVal && $this->isOpen( $index ) ) {
304 $conn =& $this->mConnections[$index];
305 wfDebug( "Waiting for slave #$index to catch up...\n" );
306 $result = $conn->masterPosWait( $this->mWaitForFile, $this->mWaitForPos, $this->mWaitTimeout );
307
308 if ( $result == -1 || is_null( $result ) ) {
309 # Timed out waiting for slave, use master instead
310 wfDebug( "Timed out waiting for slave #$index pos {$this->mWaitForFile} {$this->mWaitForPos}\n" );
311 $retVal = false;
312 } else {
313 $retVal = true;
314 wfDebug( "Done\n" );
315 }
316 }
317 return $retVal;
318 }
319
320 /**
321 * Get a connection by index
322 */
323 function &getConnection( $i, $fail = true, $groups = array() )
324 {
325 $fname = 'LoadBalancer::getConnection';
326 wfProfileIn( $fname );
327
328 # Query groups
329 $groupIndex = false;
330 foreach ( $groups as $group ) {
331 $groupIndex = $this->getGroupIndex( $group );
332 if ( $groupIndex !== false ) {
333 $i = $groupIndex;
334 break;
335 }
336 }
337
338 # Operation-based index
339 if ( $i == DB_SLAVE ) {
340 $i = $this->getReaderIndex();
341 } elseif ( $i == DB_MASTER ) {
342 $i = $this->getWriterIndex();
343 } elseif ( $i == DB_LAST ) {
344 # Just use $this->mLastIndex, which should already be set
345 $i = $this->mLastIndex;
346 if ( $i === -1 ) {
347 # Oh dear, not set, best to use the writer for safety
348 wfDebug( "Warning: DB_LAST used when there was no previous index\n" );
349 $i = $this->getWriterIndex();
350 }
351 }
352 # Couldn't find a working server in getReaderIndex()?
353 if ( $i === false ) {
354 $this->reportConnectionError( $this->mErrorConnection );
355 }
356 # Now we have an explicit index into the servers array
357 $this->openConnection( $i, $fail );
358
359 wfProfileOut( $fname );
360 return $this->mConnections[$i];
361 }
362
363 /**
364 * Open a connection to the server given by the specified index
365 * Index must be an actual index into the array
366 * Returns success
367 * @private
368 */
369 function openConnection( $i, $fail = false ) {
370 $fname = 'LoadBalancer::openConnection';
371 wfProfileIn( $fname );
372 $success = true;
373
374 if ( !$this->isOpen( $i ) ) {
375 $this->mConnections[$i] = $this->reallyOpenConnection( $this->mServers[$i] );
376 }
377
378 if ( !$this->isOpen( $i ) ) {
379 wfDebug( "Failed to connect to database $i at {$this->mServers[$i]['host']}\n" );
380 if ( $fail ) {
381 $this->reportConnectionError( $this->mConnections[$i] );
382 }
383 $this->mErrorConnection = $this->mConnections[$i];
384 $this->mConnections[$i] = false;
385 $success = false;
386 }
387 $this->mLastIndex = $i;
388 wfProfileOut( $fname );
389 return $success;
390 }
391
392 /**
393 * Test if the specified index represents an open connection
394 * @private
395 */
396 function isOpen( $index ) {
397 if( !is_integer( $index ) ) {
398 return false;
399 }
400 if ( array_key_exists( $index, $this->mConnections ) && is_object( $this->mConnections[$index] ) &&
401 $this->mConnections[$index]->isOpen() )
402 {
403 return true;
404 } else {
405 return false;
406 }
407 }
408
409 /**
410 * Really opens a connection
411 * @private
412 */
413 function reallyOpenConnection( &$server ) {
414 if( !is_array( $server ) ) {
415 wfDebugDieBacktrace( 'You must update your load-balancing configuration. See DefaultSettings.php entry for $wgDBservers.' );
416 }
417
418 extract( $server );
419 # Get class for this database type
420 $class = 'Database' . ucfirst( $type );
421 if ( !class_exists( $class ) ) {
422 require_once( "$class.php" );
423 }
424
425 # Create object
426 return new $class( $host, $user, $password, $dbname, 1, $flags );
427 }
428
429 function reportConnectionError( &$conn )
430 {
431 $fname = 'LoadBalancer::reportConnectionError';
432 wfProfileIn( $fname );
433 # Prevent infinite recursion
434
435 static $reporting = false;
436 if ( !$reporting ) {
437 $reporting = true;
438 if ( !is_object( $conn ) ) {
439 $conn = new Database;
440 }
441 if ( $this->mFailFunction ) {
442 $conn->failFunction( $this->mFailFunction );
443 } else {
444 $conn->failFunction( false );
445 }
446 $conn->reportConnectionError();
447 $reporting = false;
448 }
449 wfProfileOut( $fname );
450 }
451
452 function getWriterIndex()
453 {
454 return 0;
455 }
456
457 function force( $i )
458 {
459 $this->mForce = $i;
460 }
461
462 function haveIndex( $i )
463 {
464 return array_key_exists( $i, $this->mServers );
465 }
466
467 /**
468 * Get the number of defined servers (not the number of open connections)
469 */
470 function getServerCount() {
471 return count( $this->mServers );
472 }
473
474 /**
475 * Save master pos to the session and to memcached, if the session exists
476 */
477 function saveMasterPos() {
478 global $wgSessionStarted;
479 if ( $wgSessionStarted && count( $this->mServers ) > 1 ) {
480 # If this entire request was served from a slave without opening a connection to the
481 # master (however unlikely that may be), then we can fetch the position from the slave.
482 if ( empty( $this->mConnections[0] ) ) {
483 $conn =& $this->getConnection( DB_SLAVE );
484 list( $file, $pos ) = $conn->getSlavePos();
485 wfDebug( "Saving master pos fetched from slave: $file $pos\n" );
486 } else {
487 $conn =& $this->getConnection( 0 );
488 list( $file, $pos ) = $conn->getMasterPos();
489 wfDebug( "Saving master pos: $file $pos\n" );
490 }
491 if ( $file !== false ) {
492 $_SESSION['master_log_file'] = $file;
493 $_SESSION['master_pos'] = $pos;
494 }
495 }
496 }
497
498 /**
499 * Loads the master pos from the session, waits for it if necessary
500 */
501 function loadMasterPos() {
502 if ( isset( $_SESSION['master_log_file'] ) && isset( $_SESSION['master_pos'] ) ) {
503 $this->waitFor( $_SESSION['master_log_file'], $_SESSION['master_pos'] );
504 }
505 }
506
507 /**
508 * Close all open connections
509 */
510 function closeAll() {
511 foreach( $this->mConnections as $i => $conn ) {
512 if ( $this->isOpen( $i ) ) {
513 // Need to use this syntax because $conn is a copy not a reference
514 $this->mConnections[$i]->close();
515 }
516 }
517 }
518
519 function commitAll() {
520 foreach( $this->mConnections as $i => $conn ) {
521 if ( $this->isOpen( $i ) ) {
522 // Need to use this syntax because $conn is a copy not a reference
523 $this->mConnections[$i]->immediateCommit();
524 }
525 }
526 }
527
528 function waitTimeout( $value = NULL ) {
529 return wfSetVar( $this->mWaitTimeout, $value );
530 }
531
532 function getLaggedSlaveMode() {
533 return $this->mLaggedSlaveMode;
534 }
535
536 function pingAll() {
537 $success = true;
538 foreach ( $this->mConnections as $i => $conn ) {
539 if ( $this->isOpen( $i ) ) {
540 if ( !$this->mConnections[$i]->ping() ) {
541 $success = false;
542 }
543 }
544 }
545 return $success;
546 }
547
548 /**
549 * Get the hostname and lag time of the most-lagged slave
550 * This is useful for maintenance scripts that need to throttle their updates
551 */
552 function getMaxLag() {
553 $maxLag = -1;
554 $host = '';
555 foreach ( $this->mServers as $i => $conn ) {
556 if ( $this->openConnection( $i ) ) {
557 $lag = $this->mConnections[$i]->getLag();
558 if ( $lag > $maxLag ) {
559 $maxLag = $lag;
560 $host = $this->mServers[$i]['host'];
561 }
562 }
563 }
564 return array( $host, $maxLag );
565 }
566
567 /**
568 * Get lag time for each DB
569 * Results are cached for a short time in memcached
570 */
571 function getLagTimes() {
572 $expiry = 5;
573 $requestRate = 10;
574
575 global $wgMemc;
576 $times = $wgMemc->get( 'lag_times' );
577 if ( $times ) {
578 # Randomly recache with probability rising over $expiry
579 $elapsed = time() - $times['timestamp'];
580 $chance = max( 0, ( $expiry - $elapsed ) * $requestRate );
581 if ( mt_rand( 0, $chance ) != 0 ) {
582 unset( $times['timestamp'] );
583 return $times;
584 }
585 }
586
587 # Cache key missing or expired
588
589 $times = array();
590 foreach ( $this->mServers as $i => $conn ) {
591 if ( $this->openConnection( $i ) ) {
592 $times[$i] = $this->mConnections[$i]->getLag();
593 }
594 }
595
596 # Add a timestamp key so we know when it was cached
597 $times['timestamp'] = time();
598 $wgMemc->set( 'lag_times', $times, $expiry );
599
600 # But don't give the timestamp to the caller
601 unset($times['timestamp']);
602 return $times;
603 }
604 }
605
606 ?>