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 * @param LoadBalancer $parent
20 function __construct( $parent );
23 * Perform pre-connection load ratio adjustment.
25 * @param $group String: the selected query group
28 function scaleLoads( &$loads, $group = false, $wiki = false );
31 * Perform post-connection backoff.
33 * If the connection is in overload, this should return a backoff factor
34 * which will be used to control polling time. The number of threads
35 * connected is a good measure.
37 * If there is no overload, zero can be returned.
39 * A threshold thread count is given, the concrete class may compare this
40 * to the running thread count. The threshold may be false, which indicates
41 * that the sysadmin has not configured this feature.
43 * @param $conn DatabaseBase
44 * @param $threshold Float
46 function postConnectionBackoff( $conn, $threshold );
49 * Return an estimate of replication lag for each server
51 * @param $serverIndexes
56 function getLagTimes( $serverIndexes, $wiki );
61 * Basic MySQL load monitor with no external dependencies
62 * Uses memcached to cache the replication lag for a short time
66 class LoadMonitor_MySQL
implements LoadMonitor
{
74 * @param LoadBalancer $parent
76 function __construct( $parent ) {
77 $this->parent
= $parent;
85 function scaleLoads( &$loads, $group = false, $wiki = false ) {
89 * @param $serverIndexes
93 function getLagTimes( $serverIndexes, $wiki ) {
94 wfProfileIn( __METHOD__
);
99 if ( empty( $wgMemc ) )
100 $wgMemc = wfGetMainCache();
102 $masterName = $this->parent
->getServerName( 0 );
103 $memcKey = wfMemcKey( 'lag_times', $masterName );
104 $times = $wgMemc->get( $memcKey );
106 # Randomly recache with probability rising over $expiry
107 $elapsed = time() - $times['timestamp'];
108 $chance = max( 0, ( $expiry - $elapsed ) * $requestRate );
109 if ( mt_rand( 0, $chance ) != 0 ) {
110 unset( $times['timestamp'] );
111 wfProfileOut( __METHOD__
);
114 wfIncrStats( 'lag_cache_miss_expired' );
116 wfIncrStats( 'lag_cache_miss_absent' );
119 # Cache key missing or expired
122 foreach ( $serverIndexes as $i ) {
123 if ($i == 0) { # Master
125 } elseif ( false !== ( $conn = $this->parent
->getAnyOpenConnection( $i ) ) ) {
126 $times[$i] = $conn->getLag();
127 } elseif ( false !== ( $conn = $this->parent
->openConnection( $i, $wiki ) ) ) {
128 $times[$i] = $conn->getLag();
132 # Add a timestamp key so we know when it was cached
133 $times['timestamp'] = time();
134 $wgMemc->set( $memcKey, $times, $expiry );
136 # But don't give the timestamp to the caller
137 unset($times['timestamp']);
140 wfProfileOut( __METHOD__
);
145 * @param $conn DatabaseBase
149 function postConnectionBackoff( $conn, $threshold ) {
153 $status = $conn->getStatus("Thread%");
154 if ( $status['Threads_running'] > $threshold ) {
155 return $status['Threads_connected'];