MediaWiki  1.29.1
LoadMonitor.php
Go to the documentation of this file.
1 <?php
22 namespace Wikimedia\Rdbms;
23 
24 use Psr\Log\LoggerInterface;
25 use Psr\Log\NullLogger;
26 use Wikimedia\ScopedCallback;
28 
35 class LoadMonitor implements ILoadMonitor {
37  protected $parent;
39  protected $srvCache;
41  protected $mainCache;
43  protected $replLogger;
44 
46  private $movingAveRatio;
47 
48  const VERSION = 1; // cache key version
49 
50  public function __construct(
52  ) {
53  $this->parent = $lb;
54  $this->srvCache = $srvCache;
55  $this->mainCache = $cache;
56  $this->replLogger = new NullLogger();
57 
58  $this->movingAveRatio = isset( $options['movingAveRatio'] )
59  ? $options['movingAveRatio']
60  : 0.1;
61  }
62 
63  public function setLogger( LoggerInterface $logger ) {
64  $this->replLogger = $logger;
65  }
66 
67  public function scaleLoads( array &$weightByServer, $domain ) {
68  $serverIndexes = array_keys( $weightByServer );
69  $states = $this->getServerStates( $serverIndexes, $domain );
70  $coefficientsByServer = $states['weightScales'];
71  foreach ( $weightByServer as $i => $weight ) {
72  if ( isset( $coefficientsByServer[$i] ) ) {
73  $weightByServer[$i] = $weight * $coefficientsByServer[$i];
74  } else { // server recently added to config?
75  $host = $this->parent->getServerName( $i );
76  $this->replLogger->error( __METHOD__ . ": host $host not in cache" );
77  }
78  }
79  }
80 
81  public function getLagTimes( array $serverIndexes, $domain ) {
82  $states = $this->getServerStates( $serverIndexes, $domain );
83 
84  return $states['lagTimes'];
85  }
86 
87  protected function getServerStates( array $serverIndexes, $domain ) {
88  $writerIndex = $this->parent->getWriterIndex();
89  if ( count( $serverIndexes ) == 1 && reset( $serverIndexes ) == $writerIndex ) {
90  # Single server only, just return zero without caching
91  return [
92  'lagTimes' => [ $writerIndex => 0 ],
93  'weightScales' => [ $writerIndex => 1.0 ]
94  ];
95  }
96 
97  $key = $this->getCacheKey( $serverIndexes );
98  # Randomize TTLs to reduce stampedes (4.0 - 5.0 sec)
99  $ttl = mt_rand( 4e6, 5e6 ) / 1e6;
100  # Keep keys around longer as fallbacks
101  $staleTTL = 60;
102 
103  # (a) Check the local APC cache
104  $value = $this->srvCache->get( $key );
105  if ( $value && $value['timestamp'] > ( microtime( true ) - $ttl ) ) {
106  $this->replLogger->debug( __METHOD__ . ": got lag times ($key) from local cache" );
107  return $value; // cache hit
108  }
109  $staleValue = $value ?: false;
110 
111  # (b) Check the shared cache and backfill APC
112  $value = $this->mainCache->get( $key );
113  if ( $value && $value['timestamp'] > ( microtime( true ) - $ttl ) ) {
114  $this->srvCache->set( $key, $value, $staleTTL );
115  $this->replLogger->debug( __METHOD__ . ": got lag times ($key) from main cache" );
116 
117  return $value; // cache hit
118  }
119  $staleValue = $value ?: $staleValue;
120 
121  # (c) Cache key missing or expired; regenerate and backfill
122  if ( $this->mainCache->lock( $key, 0, 10 ) ) {
123  # Let this process alone update the cache value
126  $unlocker = new ScopedCallback( function () use ( $cache, $key ) {
127  $cache->unlock( $key );
128  } );
129  } elseif ( $staleValue ) {
130  # Could not acquire lock but an old cache exists, so use it
131  return $staleValue;
132  }
133 
134  $lagTimes = [];
135  $weightScales = [];
136  $movAveRatio = $this->movingAveRatio;
137  foreach ( $serverIndexes as $i ) {
138  if ( $i == $this->parent->getWriterIndex() ) {
139  $lagTimes[$i] = 0; // master always has no lag
140  $weightScales[$i] = 1.0; // nominal weight
141  continue;
142  }
143 
144  $conn = $this->parent->getAnyOpenConnection( $i );
145  if ( $conn ) {
146  $close = false; // already open
147  } else {
148  $conn = $this->parent->openConnection( $i, $domain );
149  $close = true; // new connection
150  }
151 
152  $lastWeight = isset( $staleValue['weightScales'][$i] )
153  ? $staleValue['weightScales'][$i]
154  : 1.0;
155  $coefficient = $this->getWeightScale( $i, $conn ?: null );
156  $newWeight = $movAveRatio * $coefficient + ( 1 - $movAveRatio ) * $lastWeight;
157 
158  // Scale from 10% to 100% of nominal weight
159  $weightScales[$i] = max( $newWeight, .10 );
160 
161  if ( !$conn ) {
162  $lagTimes[$i] = false;
163  $host = $this->parent->getServerName( $i );
164  $this->replLogger->error( __METHOD__ . ": host $host is unreachable" );
165  continue;
166  }
167 
168  if ( $conn->getLBInfo( 'is static' ) ) {
169  $lagTimes[$i] = 0;
170  } else {
171  $lagTimes[$i] = $conn->getLag();
172  if ( $lagTimes[$i] === false ) {
173  $host = $this->parent->getServerName( $i );
174  $this->replLogger->error( __METHOD__ . ": host $host is not replicating?" );
175  }
176  }
177 
178  if ( $close ) {
179  # Close the connection to avoid sleeper connections piling up.
180  # Note that the caller will pick one of these DBs and reconnect,
181  # which is slightly inefficient, but this only matters for the lag
182  # time cache miss cache, which is far less common that cache hits.
183  $this->parent->closeConnection( $conn );
184  }
185  }
186 
187  # Add a timestamp key so we know when it was cached
188  $value = [
189  'lagTimes' => $lagTimes,
190  'weightScales' => $weightScales,
191  'timestamp' => microtime( true )
192  ];
193  $this->mainCache->set( $key, $value, $staleTTL );
194  $this->srvCache->set( $key, $value, $staleTTL );
195  $this->replLogger->info( __METHOD__ . ": re-calculated lag times ($key)" );
196 
197  return $value;
198  }
199 
205  protected function getWeightScale( $index, IDatabase $conn = null ) {
206  return $conn ? 1.0 : 0.0;
207  }
208 
209  private function getCacheKey( array $serverIndexes ) {
210  sort( $serverIndexes );
211  // Lag is per-server, not per-DB, so key on the master DB name
212  return $this->srvCache->makeGlobalKey(
213  'lag-times',
214  self::VERSION,
215  $this->parent->getServerName( $this->parent->getWriterIndex() ),
216  implode( '-', $serverIndexes )
217  );
218  }
219 }
Wikimedia\Rdbms\LoadMonitor\$replLogger
LoggerInterface $replLogger
Definition: LoadMonitor.php:43
Wikimedia\Rdbms\LoadMonitor
Basic DB load monitor with no external dependencies Uses memcached to cache the replication lag for a...
Definition: LoadMonitor.php:35
Wikimedia\Rdbms\LoadMonitor\$srvCache
BagOStuff $srvCache
Definition: LoadMonitor.php:39
Wikimedia\Rdbms\ILoadMonitor
An interface for database load monitoring.
Definition: ILoadMonitor.php:34
captcha-old.count
count
Definition: captcha-old.py:225
Wikimedia\Rdbms\LoadMonitor\$parent
ILoadBalancer $parent
Definition: LoadMonitor.php:37
use
as see the revision history and available at free of to any person obtaining a copy of this software and associated documentation to deal in the Software without including without limitation the rights to use
Definition: MIT-LICENSE.txt:10
Wikimedia\Rdbms
Definition: ChronologyProtector.php:24
Wikimedia\Rdbms\LoadMonitor\getCacheKey
getCacheKey(array $serverIndexes)
Definition: LoadMonitor.php:209
BagOStuff
interface is intended to be more or less compatible with the PHP memcached client.
Definition: BagOStuff.php:47
Wikimedia\Rdbms\LoadMonitor\getWeightScale
getWeightScale( $index, IDatabase $conn=null)
Definition: LoadMonitor.php:205
php
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
Wikimedia\Rdbms\IDatabase
Basic database interface for live and lazy-loaded relation database handles.
Definition: IDatabase.php:40
Wikimedia\Rdbms\LoadMonitor\$movingAveRatio
float $movingAveRatio
Moving average ratio (e.g.
Definition: LoadMonitor.php:46
Wikimedia\Rdbms\LoadMonitor\scaleLoads
scaleLoads(array &$weightByServer, $domain)
Perform load ratio adjustment before deciding which server to use.
Definition: LoadMonitor.php:67
Wikimedia\Rdbms\LoadMonitor\getServerStates
getServerStates(array $serverIndexes, $domain)
Definition: LoadMonitor.php:87
$value
$value
Definition: styleTest.css.php:45
Wikimedia\Rdbms\LoadMonitor\setLogger
setLogger(LoggerInterface $logger)
Definition: LoadMonitor.php:63
Wikimedia\Rdbms\LoadMonitor\__construct
__construct(ILoadBalancer $lb, BagOStuff $srvCache, BagOStuff $cache, array $options=[])
Construct a new LoadMonitor with a given LoadBalancer parent.
Definition: LoadMonitor.php:50
Wikimedia\Rdbms\LoadMonitor\$mainCache
BagOStuff $mainCache
Definition: LoadMonitor.php:41
Wikimedia\Rdbms\LoadMonitor\getLagTimes
getLagTimes(array $serverIndexes, $domain)
Get an estimate of replication lag (in seconds) for each server.
Definition: LoadMonitor.php:81
$cache
$cache
Definition: mcc.php:33
as
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
Definition: distributors.txt:9
$options
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist Do not use this to implement individual filters if they are compatible with the ChangesListFilter and ChangesListFilterGroup structure use sub classes of those in conjunction with the ChangesListSpecialPageStructuredFilters hook This hook can be used to implement filters that do not implement that or custom behavior that is not an individual filter e g Watchlist and Watchlist you will want to construct new ChangesListBooleanFilter or ChangesListStringOptionsFilter objects When constructing you specify which group they belong to You can reuse existing or create your you must register them with $special registerFilterGroup removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set and then return false from the hook function Ensure you consume the ChangeTagAfterDelete hook to carry out custom deletion actions as context called by AbstractContent::getParserOutput May be used to override the normal model specific rendering of page content as context as context $options
Definition: hooks.txt:1049
Wikimedia\Rdbms\ILoadBalancer
Database cluster connection, tracking, load balancing, and transaction manager interface.
Definition: ILoadBalancer.php:79
array
the array() calling protocol came about after MediaWiki 1.4rc1.
Wikimedia\Rdbms\LoadMonitor\VERSION
const VERSION
Definition: LoadMonitor.php:48