4 * An interface for database load monitoring
7 interface LoadMonitor
{
9 * Construct a new LoadMonitor with a given LoadBalancer parent
11 function __construct( $parent );
14 * Perform pre-connection load ratio adjustment.
16 * @param $group String: the selected query group
19 function scaleLoads( &$loads, $group = false, $wiki = false );
22 * Perform post-connection backoff.
24 * If the connection is in overload, this should return a backoff factor
25 * which will be used to control polling time. The number of threads
26 * connected is a good measure.
28 * If there is no overload, zero can be returned.
30 * A threshold thread count is given, the concrete class may compare this
31 * to the running thread count. The threshold may be false, which indicates
32 * that the sysadmin has not configured this feature.
34 * @param $conn DatabaseBase
35 * @param $threshold Float
37 function postConnectionBackoff( $conn, $threshold );
40 * Return an estimate of replication lag for each server
42 function getLagTimes( $serverIndexes, $wiki );
47 * Basic MySQL load monitor with no external dependencies
48 * Uses memcached to cache the replication lag for a short time
51 class LoadMonitor_MySQL
implements LoadMonitor
{
52 var $parent; // LoadBalancer
54 function __construct( $parent ) {
55 $this->parent
= $parent;
58 function scaleLoads( &$loads, $group = false, $wiki = false ) {
61 function getLagTimes( $serverIndexes, $wiki ) {
62 wfProfileIn( __METHOD__
);
67 if ( empty( $wgMemc ) )
68 $wgMemc = wfGetMainCache();
70 $masterName = $this->parent
->getServerName( 0 );
71 $memcKey = wfMemcKey( 'lag_times', $masterName );
72 $times = $wgMemc->get( $memcKey );
74 # Randomly recache with probability rising over $expiry
75 $elapsed = time() - $times['timestamp'];
76 $chance = max( 0, ( $expiry - $elapsed ) * $requestRate );
77 if ( mt_rand( 0, $chance ) != 0 ) {
78 unset( $times['timestamp'] );
79 wfProfileOut( __METHOD__
);
82 wfIncrStats( 'lag_cache_miss_expired' );
84 wfIncrStats( 'lag_cache_miss_absent' );
87 # Cache key missing or expired
90 foreach ( $serverIndexes as $i ) {
91 if ($i == 0) { # Master
93 } elseif ( false !== ( $conn = $this->parent
->getAnyOpenConnection( $i ) ) ) {
94 $times[$i] = $conn->getLag();
95 } elseif ( false !== ( $conn = $this->parent
->openConnection( $i, $wiki ) ) ) {
96 $times[$i] = $conn->getLag();
100 # Add a timestamp key so we know when it was cached
101 $times['timestamp'] = time();
102 $wgMemc->set( $memcKey, $times, $expiry );
104 # But don't give the timestamp to the caller
105 unset($times['timestamp']);
108 wfProfileOut( __METHOD__
);
112 function postConnectionBackoff( $conn, $threshold ) {
116 $status = $conn->getStatus("Thread%");
117 if ( $status['Threads_running'] > $threshold ) {
118 return $status['Threads_connected'];