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 function getLagTimes( $serverIndexes, $wiki );
56 * Basic MySQL load monitor with no external dependencies
57 * Uses memcached to cache the replication lag for a short time
61 class LoadMonitor_MySQL
implements LoadMonitor
{
69 * @param LoadBalancer $parent
71 function __construct( $parent ) {
72 $this->parent
= $parent;
75 function scaleLoads( &$loads, $group = false, $wiki = false ) {
78 function getLagTimes( $serverIndexes, $wiki ) {
79 wfProfileIn( __METHOD__
);
84 if ( empty( $wgMemc ) )
85 $wgMemc = wfGetMainCache();
87 $masterName = $this->parent
->getServerName( 0 );
88 $memcKey = wfMemcKey( 'lag_times', $masterName );
89 $times = $wgMemc->get( $memcKey );
91 # Randomly recache with probability rising over $expiry
92 $elapsed = time() - $times['timestamp'];
93 $chance = max( 0, ( $expiry - $elapsed ) * $requestRate );
94 if ( mt_rand( 0, $chance ) != 0 ) {
95 unset( $times['timestamp'] );
96 wfProfileOut( __METHOD__
);
99 wfIncrStats( 'lag_cache_miss_expired' );
101 wfIncrStats( 'lag_cache_miss_absent' );
104 # Cache key missing or expired
107 foreach ( $serverIndexes as $i ) {
108 if ($i == 0) { # Master
110 } elseif ( false !== ( $conn = $this->parent
->getAnyOpenConnection( $i ) ) ) {
111 $times[$i] = $conn->getLag();
112 } elseif ( false !== ( $conn = $this->parent
->openConnection( $i, $wiki ) ) ) {
113 $times[$i] = $conn->getLag();
117 # Add a timestamp key so we know when it was cached
118 $times['timestamp'] = time();
119 $wgMemc->set( $memcKey, $times, $expiry );
121 # But don't give the timestamp to the caller
122 unset($times['timestamp']);
125 wfProfileOut( __METHOD__
);
130 * @param $conn DatabaseBase
134 function postConnectionBackoff( $conn, $threshold ) {
138 $status = $conn->getStatus("Thread%");
139 if ( $status['Threads_running'] > $threshold ) {
140 return $status['Threads_connected'];