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