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
21 use Psr\Log\LoggerAwareInterface
;
22 use Psr\Log\LoggerInterface
;
23 use Wikimedia\ObjectFactory
;
24 use Wikimedia\WaitConditionLoop
;
27 * Interface for configuration instances
31 class EtcdConfig
implements Config
, LoggerAwareInterface
{
32 /** @var MultiHttpClient */
38 /** @var LoggerInterface */
50 private $baseCacheTTL;
52 private $skewCacheTTL;
57 * @param array $params Parameter map:
58 * - host: the host address and port
59 * - protocol: either http or https
60 * - directory: the etc "directory" were MediaWiki specific variables are located
61 * - encoding: one of ("JSON", "YAML"). Defaults to JSON. [optional]
62 * - cache: BagOStuff instance or ObjectFactory spec thereof for a server cache.
63 * The cache will also be used as a fallback if etcd is down. [optional]
64 * - cacheTTL: logical cache TTL in seconds [optional]
65 * - skewTTL: maximum seconds to randomly lower the assigned TTL on cache save [optional]
66 * - timeout: seconds to wait for etcd before throwing an error [optional]
68 public function __construct( array $params ) {
77 $this->host
= $params['host'];
78 $this->protocol
= $params['protocol'];
79 $this->directory
= trim( $params['directory'], '/' );
80 $this->encoding
= $params['encoding'];
81 $this->skewCacheTTL
= $params['skewTTL'];
82 $this->baseCacheTTL
= max( $params['cacheTTL'] - $this->skewCacheTTL
, 0 );
83 $this->timeout
= $params['timeout'];
85 if ( !isset( $params['cache'] ) ) {
86 $this->srvCache
= new HashBagOStuff();
87 } elseif ( $params['cache'] instanceof BagOStuff
) {
88 $this->srvCache
= $params['cache'];
90 $this->srvCache
= ObjectFactory
::getObjectFromSpec( $params['cache'] );
93 $this->logger
= new Psr\Log\
NullLogger();
94 $this->http
= new MultiHttpClient( [
95 'connTimeout' => $this->timeout
,
96 'reqTimeout' => $this->timeout
,
97 'logger' => $this->logger
101 public function setLogger( LoggerInterface
$logger ) {
102 $this->logger
= $logger;
103 $this->http
->setLogger( $logger );
106 public function has( $name ) {
109 return array_key_exists( $name, $this->procCache
['config'] );
112 public function get( $name ) {
115 if ( !array_key_exists( $name, $this->procCache
['config'] ) ) {
116 throw new ConfigException( "No entry found for '$name'." );
119 return $this->procCache
['config'][$name];
123 * @throws ConfigException
125 private function load() {
126 if ( $this->procCache
!== null ) {
127 return; // already loaded
130 $now = microtime( true );
131 $key = $this->srvCache
->makeGlobalKey(
137 // Get the cached value or block until it is regenerated (by this or another thread)...
138 $data = null; // latest config info
139 $error = null; // last error message
140 $loop = new WaitConditionLoop(
141 function () use ( $key, $now, &$data, &$error ) {
142 // Check if the values are in cache yet...
143 $data = $this->srvCache
->get( $key );
144 if ( is_array( $data ) && $data['expires'] > $now ) {
145 $this->logger
->debug( "Found up-to-date etcd configuration cache." );
147 return WaitConditionLoop
::CONDITION_REACHED
;
150 // Cache is either empty or stale;
151 // refresh the cache from etcd, using a mutex to reduce stampedes...
152 if ( $this->srvCache
->lock( $key, 0, $this->baseCacheTTL
) ) {
154 list( $config, $error, $retry ) = $this->fetchAllFromEtcd();
155 if ( is_array( $config ) ) {
156 // Avoid having all servers expire cache keys at the same time
157 $expiry = microtime( true ) +
$this->baseCacheTTL
;
158 $expiry +
= mt_rand( 0, 1e6
) / 1e6
* $this->skewCacheTTL
;
160 $data = [ 'config' => $config, 'expires' => $expiry ];
161 $this->srvCache
->set( $key, $data, BagOStuff
::TTL_INDEFINITE
);
163 $this->logger
->info( "Refreshed stale etcd configuration cache." );
165 return WaitConditionLoop
::CONDITION_REACHED
;
167 $this->logger
->error( "Failed to fetch configuration: $error" );
169 // Fail fast since the error is likely to keep happening
170 return WaitConditionLoop
::CONDITION_FAILED
;
174 $this->srvCache
->unlock( $key ); // release mutex
178 if ( is_array( $data ) ) {
179 $this->logger
->info( "Using stale etcd configuration cache." );
181 return WaitConditionLoop
::CONDITION_REACHED
;
184 return WaitConditionLoop
::CONDITION_CONTINUE
;
189 if ( $loop->invoke() !== WaitConditionLoop
::CONDITION_REACHED
) {
190 // No cached value exists and etcd query failed; throw an error
191 throw new ConfigException( "Failed to load configuration from etcd: $error" );
194 $this->procCache
= $data;
198 * @return array (config array or null, error string, allow retries)
200 public function fetchAllFromEtcd() {
201 $dsd = new DnsSrvDiscoverer( $this->host
);
202 $servers = $dsd->getServers();
204 return $this->fetchAllFromEtcdServer( $this->host
);
208 // Pick a random etcd server from dns
209 $server = $dsd->pickServer( $servers );
210 $host = IP
::combineHostAndPort( $server['target'], $server['port'] );
211 // Try to load the config from this particular server
212 list( $config, $error, $retry ) = $this->fetchAllFromEtcdServer( $host );
213 if ( is_array( $config ) ||
!$retry ) {
217 // Avoid the server next time if that failed
218 $servers = $dsd->removeServer( $server, $servers );
219 } while ( $servers );
221 return [ $config, $error, $retry ];
225 * @param string $address Host and port
226 * @return array (config array or null, error string, whether to allow retries)
228 protected function fetchAllFromEtcdServer( $address ) {
229 // Retrieve all the values under the MediaWiki config directory
230 list( $rcode, $rdesc, /* $rhdrs */, $rbody, $rerr ) = $this->http
->run( [
232 'url' => "{$this->protocol}://{$address}/v2/keys/{$this->directory}/?recursive=true",
233 'headers' => [ 'content-type' => 'application/json' ]
236 static $terminalCodes = [ 404 => true ];
237 if ( $rcode < 200 ||
$rcode > 399 ) {
240 strlen( $rerr ) ?
$rerr : "HTTP $rcode ($rdesc)",
241 empty( $terminalCodes[$rcode] )
245 return [ $this->parseResponse( $rbody ), null, false ];
246 } catch ( EtcdConfigParseError
$e ) {
247 return [ null, $e->getMessage(), false ];
252 * Parse a response body, throwing EtcdConfigParseError if there is a validation error
254 * @param string $rbody
257 protected function parseResponse( $rbody ) {
258 $info = json_decode( $rbody, true );
259 if ( $info === null ) {
260 throw new EtcdConfigParseError( "Error unserializing JSON response." );
262 if ( !isset( $info['node'] ) ||
!is_array( $info['node'] ) ) {
263 throw new EtcdConfigParseError(
264 "Unexpected JSON response: Missing or invalid node at top level." );
267 $this->parseDirectory( '', $info['node'], $config );
272 * Recursively parse a directory node and populate the array passed by
273 * reference, throwing EtcdConfigParseError if there is a validation error
275 * @param string $dirName The relative directory name
276 * @param array $dirNode The decoded directory node
277 * @param array &$config The output array
279 protected function parseDirectory( $dirName, $dirNode, &$config ) {
280 if ( !isset( $dirNode['nodes'] ) ) {
281 throw new EtcdConfigParseError(
282 "Unexpected JSON response in dir '$dirName'; missing 'nodes' list." );
284 if ( !is_array( $dirNode['nodes'] ) ) {
285 throw new EtcdConfigParseError(
286 "Unexpected JSON response in dir '$dirName'; 'nodes' is not an array." );
289 foreach ( $dirNode['nodes'] as $node ) {
290 $baseName = basename( $node['key'] );
291 $fullName = $dirName === '' ?
$baseName : "$dirName/$baseName";
292 if ( !empty( $node['dir'] ) ) {
293 $this->parseDirectory( $fullName, $node, $config );
295 $value = $this->unserialize( $node['value'] );
296 if ( !is_array( $value ) ||
!array_key_exists( 'val', $value ) ) {
297 throw new EtcdConfigParseError( "Failed to parse value for '$fullName'." );
300 $config[$fullName] = $value['val'];
306 * @param string $string
309 private function unserialize( $string ) {
310 if ( $this->encoding
=== 'YAML' ) {
311 return yaml_parse( $string );
313 return json_decode( $string, true );