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