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