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