Use wikimedia/object-factory 1.0.0
[lhc/web/wiklou.git] / includes / config / EtcdConfig.php
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 use Psr\Log\LoggerAwareInterface;
22 use Psr\Log\LoggerInterface;
23 use Wikimedia\ObjectFactory;
24 use Wikimedia\WaitConditionLoop;
25
26 /**
27 * Interface for configuration instances
28 *
29 * @since 1.29
30 */
31 class EtcdConfig implements Config, LoggerAwareInterface {
32 /** @var MultiHttpClient */
33 private $http;
34 /** @var BagOStuff */
35 private $srvCache;
36 /** @var array */
37 private $procCache;
38 /** @var LoggerInterface */
39 private $logger;
40
41 /** @var string */
42 private $host;
43 /** @var string */
44 private $protocol;
45 /** @var string */
46 private $directory;
47 /** @var string */
48 private $encoding;
49 /** @var int */
50 private $baseCacheTTL;
51 /** @var int */
52 private $skewCacheTTL;
53 /** @var int */
54 private $timeout;
55
56 /**
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]
67 */
68 public function __construct( array $params ) {
69 $params += [
70 'protocol' => 'http',
71 'encoding' => 'JSON',
72 'cacheTTL' => 10,
73 'skewTTL' => 1,
74 'timeout' => 2
75 ];
76
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'];
84
85 if ( !isset( $params['cache'] ) ) {
86 $this->srvCache = new HashBagOStuff();
87 } elseif ( $params['cache'] instanceof BagOStuff ) {
88 $this->srvCache = $params['cache'];
89 } else {
90 $this->srvCache = ObjectFactory::getObjectFromSpec( $params['cache'] );
91 }
92
93 $this->logger = new Psr\Log\NullLogger();
94 $this->http = new MultiHttpClient( [
95 'connTimeout' => $this->timeout,
96 'reqTimeout' => $this->timeout,
97 'logger' => $this->logger
98 ] );
99 }
100
101 public function setLogger( LoggerInterface $logger ) {
102 $this->logger = $logger;
103 $this->http->setLogger( $logger );
104 }
105
106 public function has( $name ) {
107 $this->load();
108
109 return array_key_exists( $name, $this->procCache['config'] );
110 }
111
112 public function get( $name ) {
113 $this->load();
114
115 if ( !array_key_exists( $name, $this->procCache['config'] ) ) {
116 throw new ConfigException( "No entry found for '$name'." );
117 }
118
119 return $this->procCache['config'][$name];
120 }
121
122 /**
123 * @throws ConfigException
124 */
125 private function load() {
126 if ( $this->procCache !== null ) {
127 return; // already loaded
128 }
129
130 $now = microtime( true );
131 $key = $this->srvCache->makeGlobalKey(
132 __CLASS__,
133 $this->host,
134 $this->directory
135 );
136
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." );
146
147 return WaitConditionLoop::CONDITION_REACHED;
148 }
149
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 ) ) {
153 try {
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;
159
160 $data = [ 'config' => $config, 'expires' => $expiry ];
161 $this->srvCache->set( $key, $data, BagOStuff::TTL_INDEFINITE );
162
163 $this->logger->info( "Refreshed stale etcd configuration cache." );
164
165 return WaitConditionLoop::CONDITION_REACHED;
166 } else {
167 $this->logger->error( "Failed to fetch configuration: $error" );
168 if ( !$retry ) {
169 // Fail fast since the error is likely to keep happening
170 return WaitConditionLoop::CONDITION_FAILED;
171 }
172 }
173 } finally {
174 $this->srvCache->unlock( $key ); // release mutex
175 }
176 }
177
178 if ( is_array( $data ) ) {
179 $this->logger->info( "Using stale etcd configuration cache." );
180
181 return WaitConditionLoop::CONDITION_REACHED;
182 }
183
184 return WaitConditionLoop::CONDITION_CONTINUE;
185 },
186 $this->timeout
187 );
188
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" );
192 }
193
194 $this->procCache = $data;
195 }
196
197 /**
198 * @return array (config array or null, error string, allow retries)
199 */
200 public function fetchAllFromEtcd() {
201 $dsd = new DnsSrvDiscoverer( $this->host );
202 $servers = $dsd->getServers();
203 if ( !$servers ) {
204 return $this->fetchAllFromEtcdServer( $this->host );
205 }
206
207 do {
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 ) {
214 break;
215 }
216
217 // Avoid the server next time if that failed
218 $servers = $dsd->removeServer( $server, $servers );
219 } while ( $servers );
220
221 return [ $config, $error, $retry ];
222 }
223
224 /**
225 * @param string $address Host and port
226 * @return array (config array or null, error string, whether to allow retries)
227 */
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( [
231 'method' => 'GET',
232 'url' => "{$this->protocol}://{$address}/v2/keys/{$this->directory}/?recursive=true",
233 'headers' => [ 'content-type' => 'application/json' ]
234 ] );
235
236 static $terminalCodes = [ 404 => true ];
237 if ( $rcode < 200 || $rcode > 399 ) {
238 return [
239 null,
240 strlen( $rerr ) ? $rerr : "HTTP $rcode ($rdesc)",
241 empty( $terminalCodes[$rcode] )
242 ];
243 }
244 try {
245 return [ $this->parseResponse( $rbody ), null, false ];
246 } catch ( EtcdConfigParseError $e ) {
247 return [ null, $e->getMessage(), false ];
248 }
249 }
250
251 /**
252 * Parse a response body, throwing EtcdConfigParseError if there is a validation error
253 *
254 * @param string $rbody
255 * @return array
256 */
257 protected function parseResponse( $rbody ) {
258 $info = json_decode( $rbody, true );
259 if ( $info === null ) {
260 throw new EtcdConfigParseError( "Error unserializing JSON response." );
261 }
262 if ( !isset( $info['node'] ) || !is_array( $info['node'] ) ) {
263 throw new EtcdConfigParseError(
264 "Unexpected JSON response: Missing or invalid node at top level." );
265 }
266 $config = [];
267 $this->parseDirectory( '', $info['node'], $config );
268 return $config;
269 }
270
271 /**
272 * Recursively parse a directory node and populate the array passed by
273 * reference, throwing EtcdConfigParseError if there is a validation error
274 *
275 * @param string $dirName The relative directory name
276 * @param array $dirNode The decoded directory node
277 * @param array &$config The output array
278 */
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." );
283 }
284 if ( !is_array( $dirNode['nodes'] ) ) {
285 throw new EtcdConfigParseError(
286 "Unexpected JSON response in dir '$dirName'; 'nodes' is not an array." );
287 }
288
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 );
294 } else {
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'." );
298 }
299
300 $config[$fullName] = $value['val'];
301 }
302 }
303 }
304
305 /**
306 * @param string $string
307 * @return mixed
308 */
309 private function unserialize( $string ) {
310 if ( $this->encoding === 'YAML' ) {
311 return yaml_parse( $string );
312 } else { // JSON
313 return json_decode( $string, true );
314 }
315 }
316 }