MediaWiki  1.29.1
EtcdConfig.php
Go to the documentation of this file.
1 <?php
24 use Psr\Log\LoggerAwareInterface;
25 use Psr\Log\LoggerInterface;
26 use Wikimedia\WaitConditionLoop;
27 
33 class EtcdConfig implements Config, LoggerAwareInterface {
35  private $http;
37  private $srvCache;
39  private $procCache;
41  private $logger;
42 
44  private $host;
46  private $protocol;
48  private $directory;
50  private $encoding;
52  private $baseCacheTTL;
54  private $skewCacheTTL;
56  private $timeout;
58  private $directoryHash;
59 
72  public function __construct( array $params ) {
73  $params += [
74  'protocol' => 'http',
75  'encoding' => 'JSON',
76  'cacheTTL' => 10,
77  'skewTTL' => 1,
78  'timeout' => 10
79  ];
80 
81  $this->host = $params['host'];
82  $this->protocol = $params['protocol'];
83  $this->directory = trim( $params['directory'], '/' );
84  $this->directoryHash = sha1( $this->directory );
85  $this->encoding = $params['encoding'];
86  $this->skewCacheTTL = $params['skewTTL'];
87  $this->baseCacheTTL = max( $params['cacheTTL'] - $this->skewCacheTTL, 0 );
88  $this->timeout = $params['timeout'];
89 
90  if ( !isset( $params['cache'] ) ) {
91  $this->srvCache = new HashBagOStuff( [] );
92  } elseif ( $params['cache'] instanceof BagOStuff ) {
93  $this->srvCache = $params['cache'];
94  } else {
95  $this->srvCache = ObjectFactory::getObjectFromSpec( $params['cache'] );
96  }
97 
98  $this->logger = new Psr\Log\NullLogger();
99  $this->http = new MultiHttpClient( [
100  'connTimeout' => $this->timeout,
101  'reqTimeout' => $this->timeout
102  ] );
103  }
104 
105  public function setLogger( LoggerInterface $logger ) {
106  $this->logger = $logger;
107  }
108 
109  public function has( $name ) {
110  $this->load();
111 
112  return array_key_exists( $name, $this->procCache['config'] );
113  }
114 
115  public function get( $name ) {
116  $this->load();
117 
118  if ( !array_key_exists( $name, $this->procCache['config'] ) ) {
119  throw new ConfigException( "No entry found for '$name'." );
120  }
121 
122  return $this->procCache['config'][$name];
123  }
124 
125  private function load() {
126  if ( $this->procCache !== null ) {
127  return; // already loaded
128  }
129 
130  $now = microtime( true );
131  $key = $this->srvCache->makeKey( 'variable', $this->directoryHash );
132 
133  // Get the cached value or block until it is regenerated (by this or another thread)...
134  $data = null; // latest config info
135  $error = null; // last error message
136  $loop = new WaitConditionLoop(
137  function () use ( $key, $now, &$data, &$error ) {
138  // Check if the values are in cache yet...
139  $data = $this->srvCache->get( $key );
140  if ( is_array( $data ) && $data['expires'] > $now ) {
141  $this->logger->debug( "Found up-to-date etcd configuration cache." );
142 
143  return WaitConditionLoop::CONDITION_REACHED;
144  }
145 
146  // Cache is either empty or stale;
147  // refresh the cache from etcd, using a mutex to reduce stampedes...
148  if ( $this->srvCache->lock( $key, 0, $this->baseCacheTTL ) ) {
149  try {
150  list( $config, $error, $retry ) = $this->fetchAllFromEtcd();
151  if ( $config === null ) {
152  $this->logger->error( "Failed to fetch configuration: $error" );
153  // Fail fast if the error is likely to just keep happening
154  return $retry
155  ? WaitConditionLoop::CONDITION_CONTINUE
156  : WaitConditionLoop::CONDITION_FAILED;
157  }
158 
159  // Avoid having all servers expire cache keys at the same time
160  $expiry = microtime( true ) + $this->baseCacheTTL;
161  $expiry += mt_rand( 0, 1e6 ) / 1e6 * $this->skewCacheTTL;
162 
163  $data = [ 'config' => $config, 'expires' => $expiry ];
164  $this->srvCache->set( $key, $data, BagOStuff::TTL_INDEFINITE );
165 
166  $this->logger->info( "Refreshed stale etcd configuration cache." );
167 
168  return WaitConditionLoop::CONDITION_REACHED;
169  } finally {
170  $this->srvCache->unlock( $key ); // release mutex
171  }
172  }
173 
174  if ( is_array( $data ) ) {
175  $this->logger->info( "Using stale etcd configuration cache." );
176 
177  return WaitConditionLoop::CONDITION_REACHED;
178  }
179 
180  return WaitConditionLoop::CONDITION_CONTINUE;
181  },
183  );
184 
185  if ( $loop->invoke() !== WaitConditionLoop::CONDITION_REACHED ) {
186  // No cached value exists and etcd query failed; throw an error
187  throw new ConfigException( "Failed to load configuration from etcd: $error" );
188  }
189 
190  $this->procCache = $data;
191  }
192 
196  public function fetchAllFromEtcd() {
197  $dsd = new DnsSrvDiscoverer( $this->host );
198  $servers = $dsd->getServers();
199  if ( !$servers ) {
200  return $this->fetchAllFromEtcdServer( $this->host );
201  }
202 
203  do {
204  // Pick a random etcd server from dns
205  $server = $dsd->pickServer( $servers );
206  $host = IP::combineHostAndPort( $server['target'], $server['port'] );
207  // Try to load the config from this particular server
208  list( $config, $error, $retry ) = $this->fetchAllFromEtcdServer( $host );
209  if ( is_array( $config ) || !$retry ) {
210  break;
211  }
212 
213  // Avoid the server next time if that failed
214  $dsd->removeServer( $server, $servers );
215  } while ( $servers );
216 
217  return [ $config, $error, $retry ];
218  }
219 
224  protected function fetchAllFromEtcdServer( $address ) {
225  // Retrieve all the values under the MediaWiki config directory
226  list( $rcode, $rdesc, /* $rhdrs */, $rbody, $rerr ) = $this->http->run( [
227  'method' => 'GET',
228  'url' => "{$this->protocol}://{$address}/v2/keys/{$this->directory}/",
229  'headers' => [ 'content-type' => 'application/json' ]
230  ] );
231 
232  static $terminalCodes = [ 404 => true ];
233  if ( $rcode < 200 || $rcode > 399 ) {
234  return [
235  null,
236  strlen( $rerr ) ? $rerr : "HTTP $rcode ($rdesc)",
237  empty( $terminalCodes[$rcode] )
238  ];
239  }
240 
241  $info = json_decode( $rbody, true );
242  if ( $info === null || !isset( $info['node']['nodes'] ) ) {
243  return [ null, $rcode, "Unexpected JSON response; missing 'nodes' list.", false ];
244  }
245 
246  $config = [];
247  foreach ( $info['node']['nodes'] as $node ) {
248  if ( !empty( $node['dir'] ) ) {
249  continue; // skip directories
250  }
251 
252  $name = basename( $node['key'] );
253  $value = $this->unserialize( $node['value'] );
254  if ( !is_array( $value ) || !isset( $value['val'] ) ) {
255  return [ null, "Failed to parse value for '$name'.", false ];
256  }
257 
258  $config[$name] = $value['val'];
259  }
260 
261  return [ $config, null, false ];
262  }
263 
268  private function unserialize( $string ) {
269  if ( $this->encoding === 'YAML' ) {
270  return yaml_parse( $string );
271  } else { // JSON
272  return json_decode( $string, true );
273  }
274  }
275 }
DnsSrvDiscoverer
Definition: DnsSrvDiscoverer.php:26
EtcdConfig\$http
MultiHttpClient $http
Definition: EtcdConfig.php:35
MultiHttpClient
Class to handle concurrent HTTP requests.
Definition: MultiHttpClient.php:45
false
processing should stop and the error should be shown to the user * false
Definition: hooks.txt:189
directory
The most up to date schema for the tables in the database will always be tables sql in the maintenance directory
Definition: schema.txt:2
HashBagOStuff
Simple store for keeping values in an associative array for the current process.
Definition: HashBagOStuff.php:31
EtcdConfig\__construct
__construct(array $params)
Definition: EtcdConfig.php:72
IP\combineHostAndPort
static combineHostAndPort( $host, $port, $defaultPort=false)
Given a host name and a port, combine them into host/port string like you might find in a URL.
Definition: IP.php:303
EtcdConfig\fetchAllFromEtcd
fetchAllFromEtcd()
Definition: EtcdConfig.php:196
EtcdConfig\fetchAllFromEtcdServer
fetchAllFromEtcdServer( $address)
Definition: EtcdConfig.php:224
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
EtcdConfig
Interface for configuration instances.
Definition: EtcdConfig.php:33
$params
$params
Definition: styleTest.css.php:40
BagOStuff
interface is intended to be more or less compatible with the PHP memcached client.
Definition: BagOStuff.php:47
$name
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:304
http
Apache License January http
Definition: APACHE-LICENSE-2.0.txt:3
EtcdConfig\$timeout
integer $timeout
Definition: EtcdConfig.php:56
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
EtcdConfig\load
load()
Definition: EtcdConfig.php:125
EtcdConfig\$directory
string $directory
Definition: EtcdConfig.php:48
EtcdConfig\setLogger
setLogger(LoggerInterface $logger)
Definition: EtcdConfig.php:105
IExpiringStore\TTL_INDEFINITE
const TTL_INDEFINITE
Definition: IExpiringStore.php:44
ConfigException
Exceptions for config failures.
Definition: ConfigException.php:28
EtcdConfig\$logger
LoggerInterface $logger
Definition: EtcdConfig.php:41
EtcdConfig\unserialize
unserialize( $string)
Definition: EtcdConfig.php:268
list
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global list
Definition: deferred.txt:11
EtcdConfig\$procCache
array $procCache
Definition: EtcdConfig.php:39
$value
$value
Definition: styleTest.css.php:45
ObjectFactory\getObjectFromSpec
static getObjectFromSpec( $spec)
Instantiate an object based on a specification array.
Definition: ObjectFactory.php:59
EtcdConfig\$baseCacheTTL
integer $baseCacheTTL
Definition: EtcdConfig.php:52
EtcdConfig\$srvCache
BagOStuff $srvCache
Definition: EtcdConfig.php:37
EtcdConfig\$host
string $host
Definition: EtcdConfig.php:44
EtcdConfig\$skewCacheTTL
integer $skewCacheTTL
Definition: EtcdConfig.php:54
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
EtcdConfig\$protocol
string $protocol
Definition: EtcdConfig.php:46
EtcdConfig\$directoryHash
string $directoryHash
Definition: EtcdConfig.php:58
EtcdConfig\has
has( $name)
Definition: EtcdConfig.php:109
true
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 noclasses just before the function returns a value If you return true
Definition: hooks.txt:1956
EtcdConfig\$encoding
string $encoding
Definition: EtcdConfig.php:50
array
the array() calling protocol came about after MediaWiki 1.4rc1.