MediaWiki REL1_33
LoadMonitor.php
Go to the documentation of this file.
1<?php
22namespace Wikimedia\Rdbms;
23
27use BagOStuff;
29
36class LoadMonitor implements ILoadMonitor {
38 protected $parent;
40 protected $srvCache;
42 protected $wanCache;
44 protected $replLogger;
45
50
52 const VERSION = 1;
54 const LAG_WARN_THRESHOLD = 10;
55
64 public function __construct(
66 ) {
67 $this->parent = $lb;
68 $this->srvCache = $srvCache;
69 $this->wanCache = $wCache;
70 $this->replLogger = new NullLogger();
71
72 $this->movingAveRatio = $options['movingAveRatio'] ?? 0.1;
73 $this->lagWarnThreshold = $options['lagWarnThreshold'] ?? self::LAG_WARN_THRESHOLD;
74 }
75
76 public function setLogger( LoggerInterface $logger ) {
77 $this->replLogger = $logger;
78 }
79
80 final public function scaleLoads( array &$weightByServer, $domain ) {
81 $serverIndexes = array_keys( $weightByServer );
82 $states = $this->getServerStates( $serverIndexes, $domain );
83 $newScalesByServer = $states['weightScales'];
84 foreach ( $weightByServer as $i => $weight ) {
85 if ( isset( $newScalesByServer[$i] ) ) {
86 $weightByServer[$i] = $weight * $newScalesByServer[$i];
87 } else { // server recently added to config?
88 $host = $this->parent->getServerName( $i );
89 $this->replLogger->error( __METHOD__ . ": host $host not in cache" );
90 }
91 }
92 }
93
94 final public function getLagTimes( array $serverIndexes, $domain ) {
95 return $this->getServerStates( $serverIndexes, $domain )['lagTimes'];
96 }
97
98 protected function getServerStates( array $serverIndexes, $domain ) {
99 $writerIndex = $this->parent->getWriterIndex();
100 if ( count( $serverIndexes ) == 1 && reset( $serverIndexes ) == $writerIndex ) {
101 # Single server only, just return zero without caching
102 return [
103 'lagTimes' => [ $writerIndex => 0 ],
104 'weightScales' => [ $writerIndex => 1.0 ]
105 ];
106 }
107
108 $key = $this->getCacheKey( $serverIndexes );
109 # Randomize TTLs to reduce stampedes (4.0 - 5.0 sec)
110 $ttl = mt_rand( 4e6, 5e6 ) / 1e6;
111 # Keep keys around longer as fallbacks
112 $staleTTL = 60;
113
114 # (a) Check the local APC cache
115 $value = $this->srvCache->get( $key );
116 if ( $value && $value['timestamp'] > ( microtime( true ) - $ttl ) ) {
117 $this->replLogger->debug( __METHOD__ . ": got lag times ($key) from local cache" );
118 return $value; // cache hit
119 }
120 $staleValue = $value ?: false;
121
122 # (b) Check the shared cache and backfill APC
123 $value = $this->wanCache->get( $key );
124 if ( $value && $value['timestamp'] > ( microtime( true ) - $ttl ) ) {
125 $this->srvCache->set( $key, $value, $staleTTL );
126 $this->replLogger->debug( __METHOD__ . ": got lag times ($key) from main cache" );
127
128 return $value; // cache hit
129 }
130 $staleValue = $value ?: $staleValue;
131
132 # (c) Cache key missing or expired; regenerate and backfill
133 if ( $this->srvCache->lock( $key, 0, 10 ) ) {
134 # Let only this process update the cache value on this server
135 $sCache = $this->srvCache;
137 $unlocker = new ScopedCallback( function () use ( $sCache, $key ) {
138 $sCache->unlock( $key );
139 } );
140 } elseif ( $staleValue ) {
141 # Could not acquire lock but an old cache exists, so use it
142 return $staleValue;
143 }
144
145 $lagTimes = [];
146 $weightScales = [];
147 $movAveRatio = $this->movingAveRatio;
148 foreach ( $serverIndexes as $i ) {
149 if ( $i == $this->parent->getWriterIndex() ) {
150 $lagTimes[$i] = 0; // master always has no lag
151 $weightScales[$i] = 1.0; // nominal weight
152 continue;
153 }
154
155 # Handles with open transactions are avoided since they might be subject
156 # to REPEATABLE-READ snapshots, which could affect the lag estimate query.
157 $flags = ILoadBalancer::CONN_TRX_AUTOCOMMIT;
158 $conn = $this->parent->getAnyOpenConnection( $i, $flags );
159 if ( $conn ) {
160 $close = false; // already open
161 } else {
162 $conn = $this->parent->openConnection( $i, ILoadBalancer::DOMAIN_ANY, $flags );
163 $close = true; // new connection
164 }
165
166 $lastWeight = $staleValue['weightScales'][$i] ?? 1.0;
167 $coefficient = $this->getWeightScale( $i, $conn ?: null );
168 $newWeight = $movAveRatio * $coefficient + ( 1 - $movAveRatio ) * $lastWeight;
169
170 // Scale from 10% to 100% of nominal weight
171 $weightScales[$i] = max( $newWeight, 0.10 );
172
173 $host = $this->parent->getServerName( $i );
174
175 if ( !$conn ) {
176 $lagTimes[$i] = false;
177 $this->replLogger->error(
178 __METHOD__ . ": host {db_server} is unreachable",
179 [ 'db_server' => $host ]
180 );
181 continue;
182 }
183
184 if ( $conn->getLBInfo( 'is static' ) ) {
185 $lagTimes[$i] = 0;
186 } else {
187 $lagTimes[$i] = $conn->getLag();
188 if ( $lagTimes[$i] === false ) {
189 $this->replLogger->error(
190 __METHOD__ . ": host {db_server} is not replicating?",
191 [ 'db_server' => $host ]
192 );
193 } elseif ( $lagTimes[$i] > $this->lagWarnThreshold ) {
194 $this->replLogger->warning(
195 "Server {host} has {lag} seconds of lag (>= {maxlag})",
196 [
197 'host' => $host,
198 'lag' => $lagTimes[$i],
199 'maxlag' => $this->lagWarnThreshold
200 ]
201 );
202 }
203 }
204
205 if ( $close ) {
206 # Close the connection to avoid sleeper connections piling up.
207 # Note that the caller will pick one of these DBs and reconnect,
208 # which is slightly inefficient, but this only matters for the lag
209 # time cache miss cache, which is far less common that cache hits.
210 $this->parent->closeConnection( $conn );
211 }
212 }
213
214 # Add a timestamp key so we know when it was cached
215 $value = [
216 'lagTimes' => $lagTimes,
217 'weightScales' => $weightScales,
218 'timestamp' => microtime( true )
219 ];
220 $this->wanCache->set( $key, $value, $staleTTL );
221 $this->srvCache->set( $key, $value, $staleTTL );
222 $this->replLogger->info( __METHOD__ . ": re-calculated lag times ($key)" );
223
224 return $value;
225 }
226
232 protected function getWeightScale( $index, IDatabase $conn = null ) {
233 return $conn ? 1.0 : 0.0;
234 }
235
236 private function getCacheKey( array $serverIndexes ) {
237 sort( $serverIndexes );
238 // Lag is per-server, not per-DB, so key on the master DB name
239 return $this->srvCache->makeGlobalKey(
240 'lag-times',
241 self::VERSION,
242 $this->parent->getServerName( $this->parent->getWriterIndex() ),
243 implode( '-', $serverIndexes )
244 );
245 }
246}
and that you know you can do these things To protect your we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights These restrictions translate to certain responsibilities for you if you distribute copies of the or if you modify it For if you distribute copies of such a whether gratis or for a you must give the recipients all the rights that you have You must make sure that receive or can get the source code And you must show them these terms so they know their rights We protect your rights with two and(2) offer you this license which gives you legal permission to copy
Class representing a cache/ephemeral data store.
Definition BagOStuff.php:58
Multi-datacenter aware caching interface.
Basic DB load monitor with no external dependencies Uses memcached to cache the replication lag for a...
scaleLoads(array &$weightByServer, $domain)
Perform load ratio adjustment before deciding which server to use.
LoggerInterface $replLogger
int $lagWarnThreshold
Amount of replication lag in seconds before warnings are logged.
float $movingAveRatio
Moving average ratio (e.g.
__construct(ILoadBalancer $lb, BagOStuff $srvCache, WANObjectCache $wCache, array $options=[])
getCacheKey(array $serverIndexes)
getLagTimes(array $serverIndexes, $domain)
Get an estimate of replication lag (in seconds) for each server.
getServerStates(array $serverIndexes, $domain)
setLogger(LoggerInterface $logger)
getWeightScale( $index, IDatabase $conn=null)
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped & $options
Definition hooks.txt:1999
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that When $user is not null
Definition hooks.txt:783
Basic database interface for live and lazy-loaded relation database handles.
Definition IDatabase.php:38
Database cluster connection, tracking, load balancing, and transaction manager interface.
An interface for database load monitoring.
The wiki should then use memcached to cache various data To use multiple just add more items to the array To increase the weight of a make its entry a array("192.168.0.1:11211", 2))