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 namespace Wikimedia\Rdbms
;
24 use Psr\Log\LoggerInterface
;
25 use Psr\Log\NullLogger
;
26 use Wikimedia\ScopedCallback
;
31 * Basic DB load monitor with no external dependencies
32 * Uses memcached to cache the replication lag for a short time
36 class LoadMonitor
implements ILoadMonitor
{
37 /** @var ILoadBalancer */
43 /** @var LoggerInterface */
44 protected $replLogger;
46 /** @var float Moving average ratio (e.g. 0.1 for 10% weight to new weight) */
47 private $movingAveRatio;
49 const VERSION
= 1; // cache key version
51 public function __construct(
52 ILoadBalancer
$lb, BagOStuff
$srvCache, BagOStuff
$cache, array $options = []
55 $this->srvCache
= $srvCache;
56 $this->mainCache
= $cache;
57 $this->replLogger
= new NullLogger();
59 $this->movingAveRatio
= isset( $options['movingAveRatio'] )
60 ?
$options['movingAveRatio']
64 public function setLogger( LoggerInterface
$logger ) {
65 $this->replLogger
= $logger;
68 public function scaleLoads( array &$weightByServer, $domain ) {
69 $serverIndexes = array_keys( $weightByServer );
70 $states = $this->getServerStates( $serverIndexes, $domain );
71 $coefficientsByServer = $states['weightScales'];
72 foreach ( $weightByServer as $i => $weight ) {
73 if ( isset( $coefficientsByServer[$i] ) ) {
74 $weightByServer[$i] = $weight * $coefficientsByServer[$i];
75 } else { // server recently added to config?
76 $host = $this->parent
->getServerName( $i );
77 $this->replLogger
->error( __METHOD__
. ": host $host not in cache" );
82 public function getLagTimes( array $serverIndexes, $domain ) {
83 $states = $this->getServerStates( $serverIndexes, $domain );
85 return $states['lagTimes'];
88 protected function getServerStates( array $serverIndexes, $domain ) {
89 $writerIndex = $this->parent
->getWriterIndex();
90 if ( count( $serverIndexes ) == 1 && reset( $serverIndexes ) == $writerIndex ) {
91 # Single server only, just return zero without caching
93 'lagTimes' => [ $writerIndex => 0 ],
94 'weightScales' => [ $writerIndex => 1.0 ]
98 $key = $this->getCacheKey( $serverIndexes );
99 # Randomize TTLs to reduce stampedes (4.0 - 5.0 sec)
100 $ttl = mt_rand( 4e6
, 5e6
) / 1e6
;
101 # Keep keys around longer as fallbacks
104 # (a) Check the local APC cache
105 $value = $this->srvCache
->get( $key );
106 if ( $value && $value['timestamp'] > ( microtime( true ) - $ttl ) ) {
107 $this->replLogger
->debug( __METHOD__
. ": got lag times ($key) from local cache" );
108 return $value; // cache hit
110 $staleValue = $value ?
: false;
112 # (b) Check the shared cache and backfill APC
113 $value = $this->mainCache
->get( $key );
114 if ( $value && $value['timestamp'] > ( microtime( true ) - $ttl ) ) {
115 $this->srvCache
->set( $key, $value, $staleTTL );
116 $this->replLogger
->debug( __METHOD__
. ": got lag times ($key) from main cache" );
118 return $value; // cache hit
120 $staleValue = $value ?
: $staleValue;
122 # (c) Cache key missing or expired; regenerate and backfill
123 if ( $this->mainCache
->lock( $key, 0, 10 ) ) {
124 # Let this process alone update the cache value
125 $cache = $this->mainCache
;
126 /** @noinspection PhpUnusedLocalVariableInspection */
127 $unlocker = new ScopedCallback( function () use ( $cache, $key ) {
128 $cache->unlock( $key );
130 } elseif ( $staleValue ) {
131 # Could not acquire lock but an old cache exists, so use it
137 $movAveRatio = $this->movingAveRatio
;
138 foreach ( $serverIndexes as $i ) {
139 if ( $i == $this->parent
->getWriterIndex() ) {
140 $lagTimes[$i] = 0; // master always has no lag
141 $weightScales[$i] = 1.0; // nominal weight
145 $conn = $this->parent
->getAnyOpenConnection( $i );
147 $close = false; // already open
149 $conn = $this->parent
->openConnection( $i, $domain );
150 $close = true; // new connection
153 $lastWeight = isset( $staleValue['weightScales'][$i] )
154 ?
$staleValue['weightScales'][$i]
156 $coefficient = $this->getWeightScale( $i, $conn ?
: null );
157 $newWeight = $movAveRatio * $coefficient +
( 1 - $movAveRatio ) * $lastWeight;
159 // Scale from 10% to 100% of nominal weight
160 $weightScales[$i] = max( $newWeight, .10 );
163 $lagTimes[$i] = false;
164 $host = $this->parent
->getServerName( $i );
165 $this->replLogger
->error( __METHOD__
. ": host $host is unreachable" );
169 if ( $conn->getLBInfo( 'is static' ) ) {
172 $lagTimes[$i] = $conn->getLag();
173 if ( $lagTimes[$i] === false ) {
174 $host = $this->parent
->getServerName( $i );
175 $this->replLogger
->error( __METHOD__
. ": host $host is not replicating?" );
180 # Close the connection to avoid sleeper connections piling up.
181 # Note that the caller will pick one of these DBs and reconnect,
182 # which is slightly inefficient, but this only matters for the lag
183 # time cache miss cache, which is far less common that cache hits.
184 $this->parent
->closeConnection( $conn );
188 # Add a timestamp key so we know when it was cached
190 'lagTimes' => $lagTimes,
191 'weightScales' => $weightScales,
192 'timestamp' => microtime( true )
194 $this->mainCache
->set( $key, $value, $staleTTL );
195 $this->srvCache
->set( $key, $value, $staleTTL );
196 $this->replLogger
->info( __METHOD__
. ": re-calculated lag times ($key)" );
202 * @param integer $index Server index
203 * @param IDatabase|null $conn Connection handle or null on connection failure
206 protected function getWeightScale( $index, IDatabase
$conn = null ) {
207 return $conn ?
1.0 : 0.0;
210 private function getCacheKey( array $serverIndexes ) {
211 sort( $serverIndexes );
212 // Lag is per-server, not per-DB, so key on the master DB name
213 return $this->srvCache
->makeGlobalKey(
216 $this->parent
->getServerName( $this->parent
->getWriterIndex() ),
217 implode( '-', $serverIndexes )