3 * Database load monitoring
10 * An interface for database load monitoring
14 interface LoadMonitor
{
16 * Construct a new LoadMonitor with a given LoadBalancer parent
18 function __construct( $parent );
21 * Perform pre-connection load ratio adjustment.
23 * @param $group String: the selected query group
26 function scaleLoads( &$loads, $group = false, $wiki = false );
29 * Perform post-connection backoff.
31 * If the connection is in overload, this should return a backoff factor
32 * which will be used to control polling time. The number of threads
33 * connected is a good measure.
35 * If there is no overload, zero can be returned.
37 * A threshold thread count is given, the concrete class may compare this
38 * to the running thread count. The threshold may be false, which indicates
39 * that the sysadmin has not configured this feature.
41 * @param $conn DatabaseBase
42 * @param $threshold Float
44 function postConnectionBackoff( $conn, $threshold );
47 * Return an estimate of replication lag for each server
49 function getLagTimes( $serverIndexes, $wiki );
54 * Basic MySQL load monitor with no external dependencies
55 * Uses memcached to cache the replication lag for a short time
59 class LoadMonitor_MySQL
implements LoadMonitor
{
60 var $parent; // LoadBalancer
62 function __construct( $parent ) {
63 $this->parent
= $parent;
66 function scaleLoads( &$loads, $group = false, $wiki = false ) {
69 function getLagTimes( $serverIndexes, $wiki ) {
70 wfProfileIn( __METHOD__
);
75 if ( empty( $wgMemc ) )
76 $wgMemc = wfGetMainCache();
78 $masterName = $this->parent
->getServerName( 0 );
79 $memcKey = wfMemcKey( 'lag_times', $masterName );
80 $times = $wgMemc->get( $memcKey );
82 # Randomly recache with probability rising over $expiry
83 $elapsed = time() - $times['timestamp'];
84 $chance = max( 0, ( $expiry - $elapsed ) * $requestRate );
85 if ( mt_rand( 0, $chance ) != 0 ) {
86 unset( $times['timestamp'] );
87 wfProfileOut( __METHOD__
);
90 wfIncrStats( 'lag_cache_miss_expired' );
92 wfIncrStats( 'lag_cache_miss_absent' );
95 # Cache key missing or expired
98 foreach ( $serverIndexes as $i ) {
99 if ($i == 0) { # Master
101 } elseif ( false !== ( $conn = $this->parent
->getAnyOpenConnection( $i ) ) ) {
102 $times[$i] = $conn->getLag();
103 } elseif ( false !== ( $conn = $this->parent
->openConnection( $i, $wiki ) ) ) {
104 $times[$i] = $conn->getLag();
108 # Add a timestamp key so we know when it was cached
109 $times['timestamp'] = time();
110 $wgMemc->set( $memcKey, $times, $expiry );
112 # But don't give the timestamp to the caller
113 unset($times['timestamp']);
116 wfProfileOut( __METHOD__
);
120 function postConnectionBackoff( $conn, $threshold ) {
124 $status = $conn->getStatus("Thread%");
125 if ( $status['Threads_running'] > $threshold ) {
126 return $status['Threads_connected'];