config: Use less generic cache key, and not fragmented by wiki
[lhc/web/wiklou.git] / includes / config / EtcdConfig.php
1 <?php
2 /**
3 * Copyright 2017
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 * @author Aaron Schulz
22 */
23
24 use Psr\Log\LoggerAwareInterface;
25 use Psr\Log\LoggerInterface;
26 use Wikimedia\WaitConditionLoop;
27
28 /**
29 * Interface for configuration instances
30 *
31 * @since 1.29
32 */
33 class EtcdConfig implements Config, LoggerAwareInterface {
34 /** @var MultiHttpClient */
35 private $http;
36 /** @var BagOStuff */
37 private $srvCache;
38 /** @var array */
39 private $procCache;
40 /** @var LoggerInterface */
41 private $logger;
42
43 /** @var string */
44 private $host;
45 /** @var string */
46 private $protocol;
47 /** @var string */
48 private $directory;
49 /** @var string */
50 private $encoding;
51 /** @var integer */
52 private $baseCacheTTL;
53 /** @var integer */
54 private $skewCacheTTL;
55 /** @var integer */
56 private $timeout;
57
58 /**
59 * @param array $params Parameter map:
60 * - host: the host address and port
61 * - protocol: either http or https
62 * - directory: the etc "directory" were MediaWiki specific variables are located
63 * - encoding: one of ("JSON", "YAML"). Defaults to JSON. [optional]
64 * - cache: BagOStuff instance or ObjectFactory spec thereof for a server cache.
65 * The cache will also be used as a fallback if etcd is down. [optional]
66 * - cacheTTL: logical cache TTL in seconds [optional]
67 * - skewTTL: maximum seconds to randomly lower the assigned TTL on cache save [optional]
68 * - timeout: seconds to wait for etcd before throwing an error [optional]
69 */
70 public function __construct( array $params ) {
71 $params += [
72 'protocol' => 'http',
73 'encoding' => 'JSON',
74 'cacheTTL' => 10,
75 'skewTTL' => 1,
76 'timeout' => 10
77 ];
78
79 $this->host = $params['host'];
80 $this->protocol = $params['protocol'];
81 $this->directory = trim( $params['directory'], '/' );
82 $this->encoding = $params['encoding'];
83 $this->skewCacheTTL = $params['skewTTL'];
84 $this->baseCacheTTL = max( $params['cacheTTL'] - $this->skewCacheTTL, 0 );
85 $this->timeout = $params['timeout'];
86
87 if ( !isset( $params['cache'] ) ) {
88 $this->srvCache = new HashBagOStuff();
89 } elseif ( $params['cache'] instanceof BagOStuff ) {
90 $this->srvCache = $params['cache'];
91 } else {
92 $this->srvCache = ObjectFactory::getObjectFromSpec( $params['cache'] );
93 }
94
95 $this->logger = new Psr\Log\NullLogger();
96 $this->http = new MultiHttpClient( [
97 'connTimeout' => $this->timeout,
98 'reqTimeout' => $this->timeout
99 ] );
100 }
101
102 public function setLogger( LoggerInterface $logger ) {
103 $this->logger = $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 $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}/",
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
245 $info = json_decode( $rbody, true );
246 if ( $info === null || !isset( $info['node']['nodes'] ) ) {
247 return [ null, $rcode, "Unexpected JSON response; missing 'nodes' list.", false ];
248 }
249
250 $config = [];
251 foreach ( $info['node']['nodes'] as $node ) {
252 if ( !empty( $node['dir'] ) ) {
253 continue; // skip directories
254 }
255
256 $name = basename( $node['key'] );
257 $value = $this->unserialize( $node['value'] );
258 if ( !is_array( $value ) || !array_key_exists( 'val', $value ) ) {
259 return [ null, "Failed to parse value for '$name'.", false ];
260 }
261
262 $config[$name] = $value['val'];
263 }
264
265 return [ $config, null, false ];
266 }
267
268 /**
269 * @param string $string
270 * @return mixed
271 */
272 private function unserialize( $string ) {
273 if ( $this->encoding === 'YAML' ) {
274 return yaml_parse( $string );
275 } else { // JSON
276 return json_decode( $string, true );
277 }
278 }
279 }