89860d792f0518a7969408ef9754e92b587be6be
[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->mLastError = 'All servers busy';
230 }
231
232 if ( $i !== false && $this->isOpen( $i ) ) {
233 # Wait for the session master pos for a short time
234 if ( $this->mWaitForFile ) {
235 if ( !$this->doWait( $i ) ) {
236 $this->mServers[$i]['slave pos'] = $this->mConnections[$i]->getSlavePos();
237 }
238 }
239 if ( $i !== false ) {
240 $this->mReadIndex = $i;
241 }
242 } else {
243 $i = false;
244 }
245 }
246 }
247 wfProfileOut( $fname );
248 return $i;
249 }
250
251 /**
252 * Get a random server to use in a query group
253 */
254 function getGroupIndex( $group ) {
255 if ( isset( $this->mGroupLoads[$group] ) ) {
256 $i = $this->pickRandom( $this->mGroupLoads[$group] );
257 } else {
258 $i = false;
259 }
260 wfDebug( "Query group $group => $i\n" );
261 return $i;
262 }
263
264 /**
265 * Set the master wait position
266 * If a DB_SLAVE connection has been opened already, waits
267 * Otherwise sets a variable telling it to wait if such a connection is opened
268 */
269 function waitFor( $file, $pos ) {
270 $fname = 'LoadBalancer::waitFor';
271 wfProfileIn( $fname );
272
273 wfDebug( "User master pos: $file $pos\n" );
274 $this->mWaitForFile = false;
275 $this->mWaitForPos = false;
276
277 if ( count( $this->mServers ) > 1 ) {
278 $this->mWaitForFile = $file;
279 $this->mWaitForPos = $pos;
280 $i = $this->mReadIndex;
281
282 if ( $i > 0 ) {
283 if ( !$this->doWait( $i ) ) {
284 $this->mServers[$i]['slave pos'] = $this->mConnections[$i]->getSlavePos();
285 $this->mLaggedSlaveMode = true;
286 }
287 }
288 }
289 wfProfileOut( $fname );
290 }
291
292 /**
293 * Wait for a given slave to catch up to the master pos stored in $this
294 */
295 function doWait( $index ) {
296 global $wgMemc;
297
298 $retVal = false;
299
300 # Debugging hacks
301 if ( isset( $this->mServers[$index]['lagged slave'] ) ) {
302 return false;
303 } elseif ( isset( $this->mServers[$index]['fake slave'] ) ) {
304 return true;
305 }
306
307 $key = 'masterpos:' . $index;
308 $memcPos = $wgMemc->get( $key );
309 if ( $memcPos ) {
310 list( $file, $pos ) = explode( ' ', $memcPos );
311 # If the saved position is later than the requested position, return now
312 if ( $file == $this->mWaitForFile && $this->mWaitForPos <= $pos ) {
313 $retVal = true;
314 }
315 }
316
317 if ( !$retVal && $this->isOpen( $index ) ) {
318 $conn =& $this->mConnections[$index];
319 wfDebug( "Waiting for slave #$index to catch up...\n" );
320 $result = $conn->masterPosWait( $this->mWaitForFile, $this->mWaitForPos, $this->mWaitTimeout );
321
322 if ( $result == -1 || is_null( $result ) ) {
323 # Timed out waiting for slave, use master instead
324 wfDebug( "Timed out waiting for slave #$index pos {$this->mWaitForFile} {$this->mWaitForPos}\n" );
325 $retVal = false;
326 } else {
327 $retVal = true;
328 wfDebug( "Done\n" );
329 }
330 }
331 return $retVal;
332 }
333
334 /**
335 * Get a connection by index
336 */
337 function &getConnection( $i, $fail = true, $groups = array() )
338 {
339 $fname = 'LoadBalancer::getConnection';
340 wfProfileIn( $fname );
341
342 # Query groups
343 $groupIndex = false;
344 foreach ( $groups as $group ) {
345 $groupIndex = $this->getGroupIndex( $group );
346 if ( $groupIndex !== false ) {
347 $i = $groupIndex;
348 break;
349 }
350 }
351
352 # Operation-based index
353 if ( $i == DB_SLAVE ) {
354 $i = $this->getReaderIndex();
355 } elseif ( $i == DB_MASTER ) {
356 $i = $this->getWriterIndex();
357 } elseif ( $i == DB_LAST ) {
358 # Just use $this->mLastIndex, which should already be set
359 $i = $this->mLastIndex;
360 if ( $i === -1 ) {
361 # Oh dear, not set, best to use the writer for safety
362 wfDebug( "Warning: DB_LAST used when there was no previous index\n" );
363 $i = $this->getWriterIndex();
364 }
365 }
366 # Couldn't find a working server in getReaderIndex()?
367 if ( $i === false ) {
368 $this->reportConnectionError( $this->mErrorConnection );
369 }
370 # Now we have an explicit index into the servers array
371 $this->openConnection( $i, $fail );
372
373 wfProfileOut( $fname );
374 return $this->mConnections[$i];
375 }
376
377 /**
378 * Open a connection to the server given by the specified index
379 * Index must be an actual index into the array
380 * Returns success
381 * @private
382 */
383 function openConnection( $i, $fail = false ) {
384 $fname = 'LoadBalancer::openConnection';
385 wfProfileIn( $fname );
386 $success = true;
387
388 if ( !$this->isOpen( $i ) ) {
389 $this->mConnections[$i] = $this->reallyOpenConnection( $this->mServers[$i] );
390 }
391
392 if ( !$this->isOpen( $i ) ) {
393 wfDebug( "Failed to connect to database $i at {$this->mServers[$i]['host']}\n" );
394 if ( $fail ) {
395 $this->reportConnectionError( $this->mConnections[$i] );
396 }
397 $this->mErrorConnection = $this->mConnections[$i];
398 $this->mConnections[$i] = false;
399 $success = false;
400 }
401 $this->mLastIndex = $i;
402 wfProfileOut( $fname );
403 return $success;
404 }
405
406 /**
407 * Test if the specified index represents an open connection
408 * @private
409 */
410 function isOpen( $index ) {
411 if( !is_integer( $index ) ) {
412 return false;
413 }
414 if ( array_key_exists( $index, $this->mConnections ) && is_object( $this->mConnections[$index] ) &&
415 $this->mConnections[$index]->isOpen() )
416 {
417 return true;
418 } else {
419 return false;
420 }
421 }
422
423 /**
424 * Really opens a connection
425 * @private
426 */
427 function reallyOpenConnection( &$server ) {
428 if( !is_array( $server ) ) {
429 wfDebugDieBacktrace( 'You must update your load-balancing configuration. See DefaultSettings.php entry for $wgDBservers.' );
430 }
431
432 extract( $server );
433 # Get class for this database type
434 $class = 'Database' . ucfirst( $type );
435 if ( !class_exists( $class ) ) {
436 require_once( "$class.php" );
437 }
438
439 # Create object
440 return new $class( $host, $user, $password, $dbname, 1, $flags );
441 }
442
443 function reportConnectionError( &$conn )
444 {
445 $fname = 'LoadBalancer::reportConnectionError';
446 wfProfileIn( $fname );
447 # Prevent infinite recursion
448
449 static $reporting = false;
450 if ( !$reporting ) {
451 $reporting = true;
452 if ( !is_object( $conn ) ) {
453 // No last connection, probably due to all servers being too busy
454 $conn = new Database;
455 if ( $this->mFailFunction ) {
456 $conn->failFunction( $this->mFailFunction );
457 $conn->reportConnectionError();
458 } else {
459 // If all servers were busy, mLastError will contain something sensible
460 wfEmergencyAbort( $conn, $this->mLastError );
461 }
462 } else {
463 if ( $this->mFailFunction ) {
464 $conn->failFunction( $this->mFailFunction );
465 } else {
466 $conn->failFunction( false );
467 }
468 $conn->reportConnectionError();
469 }
470 $reporting = false;
471 }
472 wfProfileOut( $fname );
473 }
474
475 function getWriterIndex()
476 {
477 return 0;
478 }
479
480 function force( $i )
481 {
482 $this->mForce = $i;
483 }
484
485 function haveIndex( $i )
486 {
487 return array_key_exists( $i, $this->mServers );
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 function pingAll() {
560 $success = true;
561 foreach ( $this->mConnections as $i => $conn ) {
562 if ( $this->isOpen( $i ) ) {
563 if ( !$this->mConnections[$i]->ping() ) {
564 $success = false;
565 }
566 }
567 }
568 return $success;
569 }
570
571 /**
572 * Get the hostname and lag time of the most-lagged slave
573 * This is useful for maintenance scripts that need to throttle their updates
574 */
575 function getMaxLag() {
576 $maxLag = -1;
577 $host = '';
578 foreach ( $this->mServers as $i => $conn ) {
579 if ( $this->openConnection( $i ) ) {
580 $lag = $this->mConnections[$i]->getLag();
581 if ( $lag > $maxLag ) {
582 $maxLag = $lag;
583 $host = $this->mServers[$i]['host'];
584 }
585 }
586 }
587 return array( $host, $maxLag );
588 }
589
590 /**
591 * Get lag time for each DB
592 * Results are cached for a short time in memcached
593 */
594 function getLagTimes() {
595 global $wgDBname;
596
597 $expiry = 5;
598 $requestRate = 10;
599
600 global $wgMemc;
601 $times = $wgMemc->get( "$wgDBname:lag_times" );
602 if ( $times ) {
603 # Randomly recache with probability rising over $expiry
604 $elapsed = time() - $times['timestamp'];
605 $chance = max( 0, ( $expiry - $elapsed ) * $requestRate );
606 if ( mt_rand( 0, $chance ) != 0 ) {
607 unset( $times['timestamp'] );
608 return $times;
609 }
610 }
611
612 # Cache key missing or expired
613
614 $times = array();
615 foreach ( $this->mServers as $i => $conn ) {
616 if ( $this->openConnection( $i ) ) {
617 $times[$i] = $this->mConnections[$i]->getLag();
618 }
619 }
620
621 # Add a timestamp key so we know when it was cached
622 $times['timestamp'] = time();
623 $wgMemc->set( "$wgDBname:lag_times", $times, $expiry );
624
625 # But don't give the timestamp to the caller
626 unset($times['timestamp']);
627 return $times;
628 }
629 }
630
631 ?>