3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
22 use Psr\Log\LoggerInterface
;
23 use Wikimedia\ScopedCallback
;
26 * Basic DB load monitor with no external dependencies
27 * Uses memcached to cache the replication lag for a short time
31 class LoadMonitor
implements ILoadMonitor
{
32 /** @var ILoadBalancer */
38 /** @var LoggerInterface */
39 protected $replLogger;
41 /** @var float Moving average ratio (e.g. 0.1 for 10% weight to new weight) */
42 private $movingAveRatio;
44 const VERSION
= 1; // cache key version
46 public function __construct(
47 ILoadBalancer
$lb, BagOStuff
$srvCache, BagOStuff
$cache, array $options = []
50 $this->srvCache
= $srvCache;
51 $this->mainCache
= $cache;
52 $this->replLogger
= new \Psr\Log\
NullLogger();
54 $this->movingAveRatio
= isset( $options['movingAveRatio'] )
55 ?
$options['movingAveRatio']
59 public function setLogger( LoggerInterface
$logger ) {
60 $this->replLogger
= $logger;
63 public function scaleLoads( array &$weightByServer, $domain ) {
64 $serverIndexes = array_keys( $weightByServer );
65 $states = $this->getServerStates( $serverIndexes, $domain );
66 $coefficientsByServer = $states['weightScales'];
67 foreach ( $weightByServer as $i => $weight ) {
68 if ( isset( $coefficientsByServer[$i] ) ) {
69 $weightByServer[$i] = $weight * $coefficientsByServer[$i];
70 } else { // server recently added to config?
71 $host = $this->parent
->getServerName( $i );
72 $this->replLogger
->error( __METHOD__
. ": host $host not in cache" );
77 public function getLagTimes( array $serverIndexes, $domain ) {
78 $states = $this->getServerStates( $serverIndexes, $domain );
80 return $states['lagTimes'];
83 protected function getServerStates( array $serverIndexes, $domain ) {
84 $writerIndex = $this->parent
->getWriterIndex();
85 if ( count( $serverIndexes ) == 1 && reset( $serverIndexes ) == $writerIndex ) {
86 # Single server only, just return zero without caching
88 'lagTimes' => [ $writerIndex => 0 ],
89 'weightScales' => [ $writerIndex => 1.0 ]
93 $key = $this->getCacheKey( $serverIndexes );
94 # Randomize TTLs to reduce stampedes (4.0 - 5.0 sec)
95 $ttl = mt_rand( 4e6
, 5e6
) / 1e6
;
96 # Keep keys around longer as fallbacks
99 # (a) Check the local APC cache
100 $value = $this->srvCache
->get( $key );
101 if ( $value && $value['timestamp'] > ( microtime( true ) - $ttl ) ) {
102 $this->replLogger
->debug( __METHOD__
. ": got lag times ($key) from local cache" );
103 return $value; // cache hit
105 $staleValue = $value ?
: false;
107 # (b) Check the shared cache and backfill APC
108 $value = $this->mainCache
->get( $key );
109 if ( $value && $value['timestamp'] > ( microtime( true ) - $ttl ) ) {
110 $this->srvCache
->set( $key, $value, $staleTTL );
111 $this->replLogger
->debug( __METHOD__
. ": got lag times ($key) from main cache" );
113 return $value; // cache hit
115 $staleValue = $value ?
: $staleValue;
117 # (c) Cache key missing or expired; regenerate and backfill
118 if ( $this->mainCache
->lock( $key, 0, 10 ) ) {
119 # Let this process alone update the cache value
120 $cache = $this->mainCache
;
121 /** @noinspection PhpUnusedLocalVariableInspection */
122 $unlocker = new ScopedCallback( function () use ( $cache, $key ) {
123 $cache->unlock( $key );
125 } elseif ( $staleValue ) {
126 # Could not acquire lock but an old cache exists, so use it
132 $movAveRatio = $this->movingAveRatio
;
133 foreach ( $serverIndexes as $i ) {
134 if ( $i == $this->parent
->getWriterIndex() ) {
135 $lagTimes[$i] = 0; // master always has no lag
136 $weightScales[$i] = 1.0; // nominal weight
140 $conn = $this->parent
->getAnyOpenConnection( $i );
142 $close = false; // already open
144 $conn = $this->parent
->openConnection( $i, $domain );
145 $close = true; // new connection
148 $lastWeight = isset( $staleValue['weightScales'][$i] )
149 ?
$staleValue['weightScales'][$i]
151 $coefficient = $this->getWeightScale( $i, $conn ?
: null );
152 $newWeight = $movAveRatio * $coefficient +
( 1 - $movAveRatio ) * $lastWeight;
154 // Scale from 10% to 100% of nominal weight
155 $weightScales[$i] = max( $newWeight, .10 );
158 $lagTimes[$i] = false;
159 $host = $this->parent
->getServerName( $i );
160 $this->replLogger
->error( __METHOD__
. ": host $host is unreachable" );
164 if ( $conn->getLBInfo( 'is static' ) ) {
167 $lagTimes[$i] = $conn->getLag();
168 if ( $lagTimes[$i] === false ) {
169 $host = $this->parent
->getServerName( $i );
170 $this->replLogger
->error( __METHOD__
. ": host $host is not replicating?" );
175 # Close the connection to avoid sleeper connections piling up.
176 # Note that the caller will pick one of these DBs and reconnect,
177 # which is slightly inefficient, but this only matters for the lag
178 # time cache miss cache, which is far less common that cache hits.
179 $this->parent
->closeConnection( $conn );
183 # Add a timestamp key so we know when it was cached
185 'lagTimes' => $lagTimes,
186 'weightScales' => $weightScales,
187 'timestamp' => microtime( true )
189 $this->mainCache
->set( $key, $value, $staleTTL );
190 $this->srvCache
->set( $key, $value, $staleTTL );
191 $this->replLogger
->info( __METHOD__
. ": re-calculated lag times ($key)" );
197 * @param integer $index Server index
198 * @param IDatabase|null $conn Connection handle or null on connection failure
201 protected function getWeightScale( $index, IDatabase
$conn = null ) {
202 return $conn ?
1.0 : 0.0;
205 private function getCacheKey( array $serverIndexes ) {
206 sort( $serverIndexes );
207 // Lag is per-server, not per-DB, so key on the master DB name
208 return $this->srvCache
->makeGlobalKey(
211 $this->parent
->getServerName( $this->parent
->getWriterIndex() ),
212 implode( '-', $serverIndexes )