various load balancing tweaks
[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, $wgDBClusterTimeout;
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 < $wgDBClusterTimeout );
210
211 if ( $i !== false && $this->isOpen( $i ) ) {
212 # Wait for the session master pos for a short time
213 if ( $this->mWaitForFile ) {
214 if ( !$this->doWait( $i ) ) {
215 $this->mServers[$i]['slave pos'] = $this->mConnections[$i]->getSlavePos();
216 }
217 }
218 if ( $i != false ) {
219 $this->mReadIndex = $i;
220 }
221 } else {
222 $i = false;
223 }
224 }
225 }
226 wfProfileOut( $fname );
227 return $i;
228 }
229
230 /**
231 * Get a random server to use in a query group
232 */
233 function getGroupIndex( $group ) {
234 if ( isset( $this->mGroupLoads[$group] ) ) {
235 $i = $this->pickRandom( $this->mGroupLoads[$group] );
236 } else {
237 $i = false;
238 }
239 wfDebug( "Query group $group => $i\n" );
240 return $i;
241 }
242
243 /**
244 * Set the master wait position
245 * If a DB_SLAVE connection has been opened already, waits
246 * Otherwise sets a variable telling it to wait if such a connection is opened
247 */
248 function waitFor( $file, $pos ) {
249 $fname = 'LoadBalancer::waitFor';
250 wfProfileIn( $fname );
251
252 wfDebug( "User master pos: $file $pos\n" );
253 $this->mWaitForFile = false;
254 $this->mWaitForPos = false;
255
256 if ( count( $this->mServers ) > 1 ) {
257 $this->mWaitForFile = $file;
258 $this->mWaitForPos = $pos;
259 $i = $this->mReadIndex;
260
261 if ( $i > 0 ) {
262 if ( !$this->doWait( $i ) ) {
263 $this->mServers[$i]['slave pos'] = $this->mConnections[$i]->getSlavePos();
264 $this->mLaggedSlaveMode = true;
265 }
266 }
267 }
268 wfProfileOut( $fname );
269 }
270
271 /**
272 * Wait for a given slave to catch up to the master pos stored in $this
273 */
274 function doWait( $index ) {
275 global $wgMemc;
276
277 $retVal = false;
278
279 # Debugging hacks
280 if ( isset( $this->mServers[$index]['lagged slave'] ) ) {
281 return false;
282 } elseif ( isset( $this->mServers[$index]['fake slave'] ) ) {
283 return true;
284 }
285
286 $key = 'masterpos:' . $index;
287 $memcPos = $wgMemc->get( $key );
288 if ( $memcPos ) {
289 list( $file, $pos ) = explode( ' ', $memcPos );
290 # If the saved position is later than the requested position, return now
291 if ( $file == $this->mWaitForFile && $this->mWaitForPos <= $pos ) {
292 $retVal = true;
293 }
294 }
295
296 if ( !$retVal && $this->isOpen( $index ) ) {
297 $conn =& $this->mConnections[$index];
298 wfDebug( "Waiting for slave #$index to catch up...\n" );
299 $result = $conn->masterPosWait( $this->mWaitForFile, $this->mWaitForPos, $this->mWaitTimeout );
300
301 if ( $result == -1 || is_null( $result ) ) {
302 # Timed out waiting for slave, use master instead
303 wfDebug( "Timed out waiting for slave #$index pos {$this->mWaitForFile} {$this->mWaitForPos}\n" );
304 $retVal = false;
305 } else {
306 $retVal = true;
307 wfDebug( "Done\n" );
308 }
309 }
310 return $retVal;
311 }
312
313 /**
314 * Get a connection by index
315 */
316 function &getConnection( $i, $fail = true, $groups = array() )
317 {
318 $fname = 'LoadBalancer::getConnection';
319 wfProfileIn( $fname );
320
321 # Query groups
322 $groupIndex = false;
323 foreach ( $groups as $group ) {
324 $groupIndex = $this->getGroupIndex( $group );
325 if ( $groupIndex !== false ) {
326 $i = $groupIndex;
327 break;
328 }
329 }
330
331 # Operation-based index
332 if ( $i == DB_SLAVE ) {
333 $i = $this->getReaderIndex();
334 } elseif ( $i == DB_MASTER ) {
335 $i = $this->getWriterIndex();
336 } elseif ( $i == DB_LAST ) {
337 # Just use $this->mLastIndex, which should already be set
338 $i = $this->mLastIndex;
339 if ( $i === -1 ) {
340 # Oh dear, not set, best to use the writer for safety
341 wfDebug( "Warning: DB_LAST used when there was no previous index\n" );
342 $i = $this->getWriterIndex();
343 }
344 }
345 # Now we have an explicit index into the servers array
346 $this->openConnection( $i, $fail );
347
348 wfProfileOut( $fname );
349 return $this->mConnections[$i];
350 }
351
352 /**
353 * Open a connection to the server given by the specified index
354 * Index must be an actual index into the array
355 * Returns success
356 * @private
357 */
358 function openConnection( $i, $fail = false ) {
359 $fname = 'LoadBalancer::openConnection';
360 wfProfileIn( $fname );
361 $success = true;
362
363 if ( !$this->isOpen( $i ) ) {
364 $this->mConnections[$i] = $this->reallyOpenConnection( $this->mServers[$i] );
365 }
366 if ( !$this->isOpen( $i ) ) {
367 wfDebug( "Failed to connect to database $i at {$this->mServers[$i]['host']}\n" );
368 if ( $fail ) {
369 $this->reportConnectionError( $this->mConnections[$i] );
370 }
371 $this->mConnections[$i] = false;
372 $success = false;
373 }
374 $this->mLastIndex = $i;
375 wfProfileOut( $fname );
376 return $success;
377 }
378
379 /**
380 * Test if the specified index represents an open connection
381 * @private
382 */
383 function isOpen( $index ) {
384 if( !is_integer( $index ) ) {
385 return false;
386 }
387 if ( array_key_exists( $index, $this->mConnections ) && is_object( $this->mConnections[$index] ) &&
388 $this->mConnections[$index]->isOpen() )
389 {
390 return true;
391 } else {
392 return false;
393 }
394 }
395
396 /**
397 * Really opens a connection
398 * @private
399 */
400 function reallyOpenConnection( &$server ) {
401 if( !is_array( $server ) ) {
402 wfDebugDieBacktrace( 'You must update your load-balancing configuration. See DefaultSettings.php entry for $wgDBservers.' );
403 }
404
405 extract( $server );
406 # Get class for this database type
407 $class = 'Database' . ucfirst( $type );
408 if ( !class_exists( $class ) ) {
409 require_once( "$class.php" );
410 }
411
412 # Create object
413 return new $class( $host, $user, $password, $dbname, 1, $flags );
414 }
415
416 function reportConnectionError( &$conn )
417 {
418 $fname = 'LoadBalancer::reportConnectionError';
419 wfProfileIn( $fname );
420 # Prevent infinite recursion
421
422 static $reporting = false;
423 if ( !$reporting ) {
424 $reporting = true;
425 if ( !is_object( $conn ) ) {
426 $conn = new Database;
427 }
428 if ( $this->mFailFunction ) {
429 $conn->failFunction( $this->mFailFunction );
430 } else {
431 $conn->failFunction( 'wfEmergencyAbort' );
432 }
433 $conn->reportConnectionError();
434 $reporting = false;
435 }
436 wfProfileOut( $fname );
437 }
438
439 function getWriterIndex()
440 {
441 return 0;
442 }
443
444 function force( $i )
445 {
446 $this->mForce = $i;
447 }
448
449 function haveIndex( $i )
450 {
451 return array_key_exists( $i, $this->mServers );
452 }
453
454 /**
455 * Get the number of defined servers (not the number of open connections)
456 */
457 function getServerCount() {
458 return count( $this->mServers );
459 }
460
461 /**
462 * Save master pos to the session and to memcached, if the session exists
463 */
464 function saveMasterPos() {
465 global $wgSessionStarted;
466 if ( $wgSessionStarted && count( $this->mServers ) > 1 ) {
467 # If this entire request was served from a slave without opening a connection to the
468 # master (however unlikely that may be), then we can fetch the position from the slave.
469 if ( empty( $this->mConnections[0] ) ) {
470 $conn =& $this->getConnection( DB_SLAVE );
471 list( $file, $pos ) = $conn->getSlavePos();
472 wfDebug( "Saving master pos fetched from slave: $file $pos\n" );
473 } else {
474 $conn =& $this->getConnection( 0 );
475 list( $file, $pos ) = $conn->getMasterPos();
476 wfDebug( "Saving master pos: $file $pos\n" );
477 }
478 if ( $file !== false ) {
479 $_SESSION['master_log_file'] = $file;
480 $_SESSION['master_pos'] = $pos;
481 }
482 }
483 }
484
485 /**
486 * Loads the master pos from the session, waits for it if necessary
487 */
488 function loadMasterPos() {
489 if ( isset( $_SESSION['master_log_file'] ) && isset( $_SESSION['master_pos'] ) ) {
490 $this->waitFor( $_SESSION['master_log_file'], $_SESSION['master_pos'] );
491 }
492 }
493
494 /**
495 * Close all open connections
496 */
497 function closeAll() {
498 foreach( $this->mConnections as $i => $conn ) {
499 if ( $this->isOpen( $i ) ) {
500 // Need to use this syntax because $conn is a copy not a reference
501 $this->mConnections[$i]->close();
502 }
503 }
504 }
505
506 function commitAll() {
507 foreach( $this->mConnections as $i => $conn ) {
508 if ( $this->isOpen( $i ) ) {
509 // Need to use this syntax because $conn is a copy not a reference
510 $this->mConnections[$i]->immediateCommit();
511 }
512 }
513 }
514
515 function waitTimeout( $value = NULL ) {
516 return wfSetVar( $this->mWaitTimeout, $value );
517 }
518
519 function getLaggedSlaveMode() {
520 return $this->mLaggedSlaveMode;
521 }
522
523 function pingAll() {
524 $success = true;
525 foreach ( $this->mConnections as $i => $conn ) {
526 if ( $this->isOpen( $i ) ) {
527 if ( !$this->mConnections[$i]->ping() ) {
528 $success = false;
529 }
530 }
531 }
532 return $success;
533 }
534
535 /**
536 * Get the hostname and lag time of the most-lagged slave
537 * This is useful for maintenance scripts that need to throttle their updates
538 */
539 function getMaxLag() {
540 $maxLag = -1;
541 $host = '';
542 foreach ( $this->mServers as $i => $conn ) {
543 if ( $this->openConnection( $i ) ) {
544 $lag = $this->mConnections[$i]->getLag();
545 if ( $lag > $maxLag ) {
546 $maxLag = $lag;
547 $host = $this->mServers[$i]['host'];
548 }
549 }
550 }
551 return array( $host, $maxLag );
552 }
553
554 /**
555 * Get lag time for each DB
556 * Results are cached for a short time in memcached
557 */
558 function getLagTimes() {
559 $expiry = 5;
560 $requestRate = 10;
561
562 global $wgMemc;
563 $times = $wgMemc->get( 'lag_times' );
564 if ( $times ) {
565 # Randomly recache with probability rising over $expiry
566 $elapsed = time() - $times['timestamp'];
567 $chance = max( 0, ( $expiry - $elapsed ) * $requestRate );
568 if ( mt_rand( 0, $chance ) != 0 ) {
569 unset( $times['timestamp'] );
570 return $times;
571 }
572 }
573
574 # Cache key missing or expired
575
576 $times = array();
577 foreach ( $this->mServers as $i => $conn ) {
578 if ( $this->openConnection( $i ) ) {
579 $times[$i] = $this->mConnections[$i]->getLag();
580 }
581 }
582
583 # Add a timestamp key so we know when it was cached
584 $times['timestamp'] = time();
585 $wgMemc->set( 'lag_times', $times, $expiry );
586
587 # But don't give the timestamp to the caller
588 unset($times['timestamp']);
589 return $times;
590 }
591 }
592
593 ?>