Debian Codegraph @

includes/config/EtcdConfig.php

raw symbols SCIP
1 <?php
2 /**
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.
7 *
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.
12 *
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
17 *
18 * @file
19 */
20
21 namespace MediaWiki\Config;
22
23 use DnsSrvDiscoverer;
24 use Psr\Log\LoggerAwareInterface;
25 use Psr\Log\LoggerInterface;
26 use Wikimedia\Http\MultiHttpClient;
27 use Wikimedia\IPUtils;
28 use Wikimedia\ObjectCache\BagOStuff;
29 use Wikimedia\ObjectCache\HashBagOStuff;
30 use Wikimedia\ObjectFactory\ObjectFactory;
31 use Wikimedia\WaitConditionLoop;
32 use function array_key_exists;
33
34 /**
35 * Interface for configuration instances
36 *
37 * @since 1.29
38 */
39 class EtcdConfig implements Config, LoggerAwareInterface {
40 /** @var MultiHttpClient */
41 private $http;
42 /** @var BagOStuff */
43 private $srvCache;
44 /** @var array */
45 private $procCache;
46 /** @var DnsSrvDiscoverer */
47 private $dsd;
48
49 /** @var string */
50 private $service;
51 /** @var string */
52 private $host;
53 /** @var ?int */
54 private $port;
55 /** @var string */
56 private $protocol;
57 /** @var string */
58 private $directory;
59 /** @var int */
60 private $baseCacheTTL;
61 /** @var int */
62 private $skewCacheTTL;
63 /** @var int */
64 private $timeout;
65
66 /**
67 * @param array $params Parameter map:
68 * - host: the host address
69 * - directory: the etc "directory" were MediaWiki specific variables are located
70 * - service: service name used in SRV discovery. Defaults to 'etcd'. [optional]
71 * - port: custom host port [optional]
72 * - protocol: one of ("http", "https"). Defaults to http. [optional]
73 * - cache: BagOStuff instance or ObjectFactory spec thereof for a server cache.
74 * The cache will also be used as a fallback if etcd is down. [optional]
75 * - cacheTTL: logical cache TTL in seconds [optional]
76 * - skewTTL: maximum seconds to randomly lower the assigned TTL on cache save [optional]
77 * - timeout: seconds to wait for etcd before throwing an error [optional]
78 */
79 public function __construct( array $params ) {
80 $params += [
81 'service' => 'etcd',
82 'port' => null,
83 'protocol' => 'http',
84 'cacheTTL' => 10,
85 'skewTTL' => 1,
86 'timeout' => 2
87 ];
88
89 $this->service = $params['service'];
90 $this->host = $params['host'];
91 $this->port = $params['port'];
92 $this->protocol = $params['protocol'];
93 $this->directory = trim( $params['directory'], '/' );
94 $this->skewCacheTTL = $params['skewTTL'];
95 $this->baseCacheTTL = max( $params['cacheTTL'] - $this->skewCacheTTL, 0 );
96 $this->timeout = $params['timeout'];
97
98 // For backwards compatibility, check the host for an embedded port
99 $hostAndPort = IPUtils::splitHostAndPort( $this->host );
100
101 if ( $hostAndPort ) {
102 $this->host = $hostAndPort[0];
103
104 if ( $hostAndPort[1] ) {
105 $this->port = $hostAndPort[1];
106 }
107 }
108
109 // Also for backwards compatibility, check for a host in the format of
110 // an SRV record and use the service specified therein
111 if ( preg_match( '/^_([^\.]+)\._tcp\.(.+)$/', $this->host, $m ) ) {
112 $this->service = $m[1];
113 $this->host = $m[2];
114 }
115
116 if ( !isset( $params['cache'] ) ) {
117 $this->srvCache = new HashBagOStuff();
118 } elseif ( $params['cache'] instanceof BagOStuff ) {
119 $this->srvCache = $params['cache'];
120 } else {
121 $this->srvCache = ObjectFactory::getObjectFromSpec( $params['cache'] );
122 }
123
124 $this->http = new MultiHttpClient( [
125 'connTimeout' => $this->timeout,
126 'reqTimeout' => $this->timeout,
127 ] );
128 $this->dsd = new DnsSrvDiscoverer( $this->service, 'tcp', $this->host );
129 }
130
131 /**
132 * @deprecated since 1.41 No longer used and did not work in practice
133 */
134 public function setLogger( LoggerInterface $logger ) {
135 trigger_error( __METHOD__ . ' is deprecated since 1.41', E_USER_DEPRECATED );
136 }
137
138 public function has( $name ) {
139 $this->load();
140
141 return array_key_exists( $name, $this->procCache['config'] );
142 }
143
144 public function get( $name ) {
145 $this->load();
146
147 if ( !array_key_exists( $name, $this->procCache['config'] ) ) {
148 throw new ConfigException( "No entry found for '$name'." );
149 }
150
151 return $this->procCache['config'][$name];
152 }
153
154 public function getModifiedIndex() {
155 $this->load();
156 return $this->procCache['modifiedIndex'];
157 }
158
159 /**
160 * @throws ConfigException
161 */
162 private function load() {
163 if ( $this->procCache !== null ) {
164 return; // already loaded
165 }
166
167 $now = microtime( true );
168 $key = $this->srvCache->makeGlobalKey(
169 __CLASS__,
170 $this->host,
171 $this->directory
172 );
173
174 // Get the cached value or block until it is regenerated (by this or another thread)...
175 $data = null; // latest config info
176 $error = null; // last error message
177 $loop = new WaitConditionLoop(
178 function () use ( $key, $now, &$data, &$error ) {
179 // Check if the values are in cache yet...
180 $data = $this->srvCache->get( $key );
181 if ( is_array( $data ) && $data['expires'] > $now ) {
182 return WaitConditionLoop::CONDITION_REACHED;
183 }
184
185 // Cache is either empty or stale;
186 // refresh the cache from etcd, using a mutex to reduce stampedes...
187 if ( $this->srvCache->lock( $key, 0, $this->baseCacheTTL ) ) {
188 try {
189 $etcdResponse = $this->fetchAllFromEtcd();
190 $error = $etcdResponse['error'];
191 if ( is_array( $etcdResponse['config'] ) ) {
192 // Avoid having all servers expire cache keys at the same time
193 $expiry = microtime( true ) + $this->baseCacheTTL;
194 // @phan-suppress-next-line PhanTypeMismatchArgumentInternal
195 $expiry += mt_rand( 0, 1e6 ) / 1e6 * $this->skewCacheTTL;
196 $data = [
197 'config' => $etcdResponse['config'],
198 'expires' => $expiry,
199 'modifiedIndex' => $etcdResponse['modifiedIndex']
200 ];
201 $this->srvCache->set( $key, $data, BagOStuff::TTL_INDEFINITE );
202
203 return WaitConditionLoop::CONDITION_REACHED;
204 } else {
205 trigger_error( "EtcdConfig failed to fetch data: $error", E_USER_WARNING );
206 if ( !$etcdResponse['retry'] && !is_array( $data ) ) {
207 // Fail fast since the error is likely to keep happening
208 return WaitConditionLoop::CONDITION_FAILED;
209 }
210 }
211 } finally {
212 $this->srvCache->unlock( $key ); // release mutex
213 }
214 } else {
215 $error = 'lost lock';
216 }
217
218 if ( is_array( $data ) ) {
219 trigger_error( "EtcdConfig using stale data: $error", E_USER_NOTICE );
220
221 return WaitConditionLoop::CONDITION_REACHED;
222 }
223
224 return WaitConditionLoop::CONDITION_CONTINUE;
225 },
226 $this->timeout
227 );
228
229 if ( $loop->invoke() !== WaitConditionLoop::CONDITION_REACHED ) {
230 // No cached value exists and etcd query failed; throw an error
231 // @phan-suppress-next-line PhanTypeSuspiciousStringExpression WaitConditionLoop throws or error set
232 throw new ConfigException( "Failed to load configuration from etcd: $error" );
233 }
234
235 // @phan-suppress-next-line PhanTypeMismatchProperty WaitConditionLoop throws ore data set
236 $this->procCache = $data;
237 }
238
239 /**
240 * @return array (containing the keys config, error, retry, modifiedIndex)
241 */
242 public function fetchAllFromEtcd() {
243 $servers = $this->dsd->getServers() ?: [ [ $this->host, $this->port ] ];
244
245 foreach ( $servers as [ $host, $port ] ) {
246 // Try to load the config from this particular server
247 $response = $this->fetchAllFromEtcdServer( $host, $port );
248 if ( is_array( $response['config'] ) || $response['retry'] ) {
249 break;
250 }
251 }
252
253 return $response;
254 }
255
256 /**
257 * @param string $address Host
258 * @param ?int $port Port
259 * @return array (containing the keys config, error, retry, modifiedIndex)
260 */
261 protected function fetchAllFromEtcdServer( string $address, ?int $port = null ) {
262 $host = $address;
263
264 if ( $port !== null ) {
265 $host = IPUtils::combineHostAndPort( $address, $port );
266 }
267
268 // Retrieve all the values under the MediaWiki config directory
269 [ $rcode, $rdesc, /* $rhdrs */, $rbody, $rerr ] = $this->http->run( [
270 'method' => 'GET',
271 'url' => "{$this->protocol}://{$host}/v2/keys/{$this->directory}/?recursive=true",
272 'headers' => [
273 'content-type' => 'application/json',
274 ]
275 ] );
276
277 $response = [ 'config' => null, 'error' => null, 'retry' => false, 'modifiedIndex' => 0 ];
278
279 static $terminalCodes = [ 404 => true ];
280 if ( $rcode < 200 || $rcode > 399 ) {
281 $response['error'] = strlen( $rerr ?? '' ) ? $rerr : "HTTP $rcode ($rdesc)";
282 $response['retry'] = empty( $terminalCodes[$rcode] );
283 return $response;
284 }
285
286 try {
287 $parsedResponse = $this->parseResponse( $rbody );
288 } catch ( EtcdConfigParseError $e ) {
289 $parsedResponse = [ 'error' => $e->getMessage() ];
290 }
291 return array_merge( $response, $parsedResponse );
292 }
293
294 /**
295 * Parse a response body, throwing EtcdConfigParseError if there is a validation error
296 *
297 * @param string $rbody
298 * @return array
299 */
300 protected function parseResponse( $rbody ) {
301 $info = json_decode( $rbody, true );
302 if ( $info === null ) {
303 throw new EtcdConfigParseError( "Error unserializing JSON response." );
304 }
305 if ( !isset( $info['node'] ) || !is_array( $info['node'] ) ) {
306 throw new EtcdConfigParseError(
307 "Unexpected JSON response: Missing or invalid node at top level." );
308 }
309 $config = [];
310 $lastModifiedIndex = $this->parseDirectory( '', $info['node'], $config );
311 return [ 'modifiedIndex' => $lastModifiedIndex, 'config' => $config ];
312 }
313
314 /**
315 * Recursively parse a directory node and populate the array passed by
316 * reference, throwing EtcdConfigParseError if there is a validation error
317 *
318 * @param string $dirName The relative directory name
319 * @param array $dirNode The decoded directory node
320 * @param array &$config The output array
321 * @return int lastModifiedIndex The maximum last modified index across all keys in the directory
322 */
323 protected function parseDirectory( $dirName, $dirNode, &$config ) {
324 $lastModifiedIndex = 0;
325 if ( !isset( $dirNode['nodes'] ) ) {
326 throw new EtcdConfigParseError(
327 "Unexpected JSON response in dir '$dirName'; missing 'nodes' list." );
328 }
329 if ( !is_array( $dirNode['nodes'] ) ) {
330 throw new EtcdConfigParseError(
331 "Unexpected JSON response in dir '$dirName'; 'nodes' is not an array." );
332 }
333
334 foreach ( $dirNode['nodes'] as $node ) {
335 '@phan-var array $node';
336 $baseName = basename( $node['key'] );
337 $fullName = $dirName === '' ? $baseName : "$dirName/$baseName";
338 if ( !empty( $node['dir'] ) ) {
339 $lastModifiedIndex = max(
340 $this->parseDirectory( $fullName, $node, $config ),
341 $lastModifiedIndex );
342 } else {
343 $value = $this->unserialize( $node['value'] );
344 if ( !is_array( $value ) || !array_key_exists( 'val', $value ) ) {
345 throw new EtcdConfigParseError( "Failed to parse value for '$fullName'." );
346 }
347 $lastModifiedIndex = max( $node['modifiedIndex'], $lastModifiedIndex );
348 $config[$fullName] = $value['val'];
349 }
350 }
351 return $lastModifiedIndex;
352 }
353
354 /**
355 * @param string $string
356 * @return mixed
357 */
358 private function unserialize( $string ) {
359 return json_decode( $string, true );
360 }
361 }
362
363 /** @deprecated class alias since 1.41 */
364 class_alias( EtcdConfig::class, 'EtcdConfig' );