generated from micronaut-projects/micronaut-project-template
-
Notifications
You must be signed in to change notification settings - Fork 17
/
ConsulConfigurationClient.java
353 lines (316 loc) · 16.8 KB
/
ConsulConfigurationClient.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
/*
* Copyright 2017-2020 original authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.micronaut.discovery.consul.config;
import io.micronaut.context.annotation.BootstrapContextCompatible;
import io.micronaut.context.annotation.Requires;
import io.micronaut.context.env.Environment;
import io.micronaut.context.env.EnvironmentPropertySource;
import io.micronaut.context.env.PropertiesPropertySourceLoader;
import io.micronaut.context.env.PropertySource;
import io.micronaut.context.env.PropertySourceLoader;
import io.micronaut.context.env.yaml.YamlPropertySourceLoader;
import io.micronaut.context.exceptions.ConfigurationException;
import io.micronaut.core.annotation.Nullable;
import io.micronaut.core.util.CollectionUtils;
import io.micronaut.core.util.StringUtils;
import io.micronaut.discovery.client.ClientUtil;
import io.micronaut.discovery.config.ConfigDiscoveryConfiguration;
import io.micronaut.discovery.config.ConfigurationClient;
import io.micronaut.discovery.consul.ConsulConfiguration;
import io.micronaut.discovery.consul.client.v1.ConsulClient;
import io.micronaut.discovery.consul.client.v1.KeyValue;
import io.micronaut.discovery.consul.condition.RequiresConsul;
import io.micronaut.http.HttpStatus;
import io.micronaut.http.client.exceptions.HttpClientResponseException;
import io.micronaut.jackson.env.JsonPropertySourceLoader;
import io.micronaut.scheduling.TaskExecutors;
import jakarta.inject.Inject;
import jakarta.inject.Named;
import jakarta.inject.Singleton;
import org.reactivestreams.Publisher;
import reactor.core.publisher.Flux;
import reactor.core.publisher.FluxSink;
import reactor.core.scheduler.Scheduler;
import reactor.core.scheduler.Schedulers;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.function.Function;
/**
* A {@link ConfigurationClient} for Consul.
*/
@Singleton
@RequiresConsul
@Requires(beans = ConsulClient.class)
@Requires(property = ConfigurationClient.ENABLED, value = StringUtils.TRUE, defaultValue = StringUtils.FALSE)
@BootstrapContextCompatible
public class ConsulConfigurationClient implements ConfigurationClient {
private final ConsulClient consulClient;
private final ConsulConfiguration consulConfiguration;
private final Map<String, PropertySourceLoader> loaderByFormatMap = new ConcurrentHashMap<>();
private ExecutorService executionService;
/**
* @param consulClient The consul client
* @param consulConfiguration The consul configuration
* @param environment The environment
*/
public ConsulConfigurationClient(ConsulClient consulClient, ConsulConfiguration consulConfiguration, Environment environment) {
this.consulClient = consulClient;
this.consulConfiguration = consulConfiguration;
if (environment != null) {
Collection<PropertySourceLoader> loaders = environment.getPropertySourceLoaders();
for (PropertySourceLoader loader : loaders) {
Set<String> extensions = loader.getExtensions();
for (String extension : extensions) {
loaderByFormatMap.put(extension, loader);
}
}
}
}
@Override
public String getDescription() {
return consulClient.getDescription();
}
@SuppressWarnings("MagicNumber")
@Override
public Publisher<PropertySource> getPropertySources(Environment environment) {
if (!consulConfiguration.getConfiguration().isEnabled()) {
return Flux.empty();
}
List<String> activeNames = new ArrayList<>(environment.getActiveNames());
Optional<String> serviceId = consulConfiguration.getServiceId();
ConsulConfiguration.ConsulConfigDiscoveryConfiguration configDiscoveryConfiguration = consulConfiguration.getConfiguration();
ConfigDiscoveryConfiguration.Format format = configDiscoveryConfiguration.getFormat();
String path = configDiscoveryConfiguration.getPath().orElse(ConfigDiscoveryConfiguration.DEFAULT_PATH);
if (!path.endsWith("/")) {
path += "/";
}
String pathPrefix = path;
String commonConfigPath = path + Environment.DEFAULT_NAME;
final boolean hasApplicationSpecificConfig = serviceId.isPresent();
String applicationSpecificPath = hasApplicationSpecificConfig ? path + serviceId.get() : null;
String dc = configDiscoveryConfiguration.getDatacenter().orElse(null);
Scheduler scheduler = null;
if (executionService != null) {
scheduler = Schedulers.fromExecutor(executionService);
}
List<Flux<List<KeyValue>>> keyValueFlowables = new ArrayList<>();
Function<Throwable, Publisher<? extends List<KeyValue>>> errorHandler = throwable -> {
if (throwable instanceof HttpClientResponseException hcre && hcre.getStatus() == HttpStatus.NOT_FOUND) {
return Flux.empty();
}
return Flux.error(new ConfigurationException("Error reading distributed configuration from Consul: " + throwable.getMessage(), throwable));
};
Flux<List<KeyValue>> applicationConfig = Flux.from(
consulClient.readValues(commonConfigPath, dc, null, null))
.onErrorResume(errorHandler);
if (scheduler != null) {
applicationConfig = applicationConfig.subscribeOn(scheduler);
}
keyValueFlowables.add(applicationConfig);
if (hasApplicationSpecificConfig) {
Flux<List<KeyValue>> appSpecificConfig = Flux.from(
consulClient.readValues(applicationSpecificPath, dc, null, null))
.onErrorResume(errorHandler);
if (scheduler != null) {
appSpecificConfig = appSpecificConfig.subscribeOn(scheduler);
}
keyValueFlowables.add(appSpecificConfig);
}
int basePriority = EnvironmentPropertySource.POSITION + 100;
int envBasePriority = basePriority + 50;
return Flux.merge(keyValueFlowables).flatMap(keyValues -> Flux.create(emitter -> {
if (CollectionUtils.isEmpty(keyValues)) {
emitter.complete();
} else {
Map<String, LocalSource> propertySources = new HashMap<>();
Base64.Decoder base64Decoder = Base64.getDecoder();
for (KeyValue keyValue : keyValues) {
String key = keyValue.getKey();
String value = keyValue.getValue();
boolean isFolder = key.endsWith("/") && value == null;
boolean isCommonConfigKey = key.startsWith(commonConfigPath);
boolean isApplicationSpecificConfigKey = hasApplicationSpecificConfig && key.startsWith(applicationSpecificPath);
boolean validKey = isCommonConfigKey || isApplicationSpecificConfigKey;
if (!isFolder && validKey) {
switch (format) {
case FILE:
String fileName = key.substring(pathPrefix.length());
int i = fileName.lastIndexOf('.');
if (i > -1) {
String ext = fileName.substring(i + 1);
fileName = fileName.substring(0, i);
PropertySourceLoader propertySourceLoader = resolveLoader(ext);
if (propertySourceLoader != null) {
String propertySourceName = resolvePropertySourceName(Environment.DEFAULT_NAME, fileName, activeNames);
if (hasApplicationSpecificConfig && propertySourceName == null) {
propertySourceName = resolvePropertySourceName(serviceId.get(), fileName, activeNames);
}
if (propertySourceName != null) {
String finalName = propertySourceName;
byte[] decoded = base64Decoder.decode(value);
Map<String, Object> properties = propertySourceLoader.read(propertySourceName, decoded);
String envName = ClientUtil.resolveEnvironment(fileName, activeNames);
LocalSource localSource = propertySources.computeIfAbsent(propertySourceName, s -> new LocalSource(isApplicationSpecificConfigKey, envName, finalName));
localSource.putAll(properties);
}
}
}
break;
case NATIVE:
String property = null;
Set<String> propertySourceNames = null;
if (isCommonConfigKey) {
property = resolvePropertyName(commonConfigPath, key);
propertySourceNames = resolvePropertySourceNames(pathPrefix, key, activeNames);
} else if (isApplicationSpecificConfigKey) {
property = resolvePropertyName(applicationSpecificPath, key);
propertySourceNames = resolvePropertySourceNames(pathPrefix, key, activeNames);
}
if (property != null && propertySourceNames != null) {
for (String propertySourceName : propertySourceNames) {
String envName = ClientUtil.resolveEnvironment(propertySourceName, activeNames);
LocalSource localSource = propertySources.computeIfAbsent(propertySourceName, s -> new LocalSource(isApplicationSpecificConfigKey, envName, propertySourceName));
byte[] decoded = base64Decoder.decode(value);
localSource.put(property, new String(decoded));
}
}
break;
case JSON, YAML, PROPERTIES:
String fullName = key.substring(pathPrefix.length());
if (!fullName.contains("/")) {
propertySourceNames = ClientUtil.calcPropertySourceNames(fullName, activeNames, ",");
String formatName = format.name().toLowerCase(Locale.ENGLISH);
PropertySourceLoader propertySourceLoader = resolveLoader(formatName);
if (propertySourceLoader == null) {
emitter.error(new ConfigurationException("No PropertySourceLoader found for format [" + format + "]. Ensure ConfigurationClient is running within Micronaut container."));
return;
} else {
if (propertySourceLoader.isEnabled()) {
byte[] decoded = base64Decoder.decode(value);
Map<String, Object> properties = propertySourceLoader.read(fullName, decoded);
for (String propertySourceName : propertySourceNames) {
String envName = ClientUtil.resolveEnvironment(propertySourceName, activeNames);
LocalSource localSource = propertySources.computeIfAbsent(propertySourceName, s -> new LocalSource(isApplicationSpecificConfigKey, envName, propertySourceName));
localSource.putAll(properties);
}
}
}
}
break;
default:
// no-op
}
}
}
for (LocalSource localSource: propertySources.values()) {
int priority;
if (localSource.environment != null) {
priority = envBasePriority + (activeNames.indexOf(localSource.environment) * 2);
} else {
priority = basePriority + 1;
}
if (localSource.appSpecific) {
priority++;
}
emitter.next(PropertySource.of(ConsulClient.SERVICE_ID + '-' + localSource.name, localSource.values, priority));
}
emitter.complete();
}
}, FluxSink.OverflowStrategy.ERROR));
}
private String resolvePropertySourceName(String rootName, String fileName, List<String> activeNames) {
String propertySourceName = null;
if (fileName.startsWith(rootName)) {
String envString = fileName.substring(rootName.length());
if (StringUtils.isEmpty(envString)) {
propertySourceName = rootName;
} else if (envString.startsWith("-")) {
String env = envString.substring(1);
if (activeNames.contains(env)) {
propertySourceName = rootName + '[' + env + ']';
}
}
}
return propertySourceName;
}
private PropertySourceLoader resolveLoader(String formatName) {
return loaderByFormatMap.computeIfAbsent(formatName, f -> defaultLoader(formatName));
}
private PropertySourceLoader defaultLoader(String format) {
return switch (format) {
case "json" -> new JsonPropertySourceLoader();
case "properties" -> new PropertiesPropertySourceLoader();
case "yml", "yaml" -> new YamlPropertySourceLoader();
default -> throw new ConfigurationException("Unsupported properties file format: " + format);
};
}
/**
* @param executionService The execution service
*/
@Inject
void setExecutionService(@Named(TaskExecutors.IO) @Nullable ExecutorService executionService) {
if (executionService != null) {
this.executionService = executionService;
}
}
private Set<String> resolvePropertySourceNames(String finalPath, String key, List<String> activeNames) {
Set<String> propertySourceNames = null;
String prefix = key.substring(finalPath.length());
int i = prefix.indexOf('/');
if (i > -1) {
prefix = prefix.substring(0, i);
propertySourceNames = ClientUtil.calcPropertySourceNames(prefix, activeNames, ",");
}
return propertySourceNames;
}
private String resolvePropertyName(String commonConfigPath, String key) {
String property = key.substring(commonConfigPath.length());
if (StringUtils.isNotEmpty(property)) {
if (property.charAt(0) == '/') {
property = property.substring(1);
} else if (property.lastIndexOf('/') > -1) {
property = property.substring(property.lastIndexOf('/') + 1);
}
}
if (property.indexOf('/') == -1) {
return property;
}
return null;
}
/**
* A local property source.
*/
private static class LocalSource {
private final boolean appSpecific;
private final String environment;
private final String name;
private final Map<String, Object> values = new LinkedHashMap<>();
LocalSource(boolean appSpecific,
String environment,
String name) {
this.appSpecific = appSpecific;
this.environment = environment;
this.name = name;
}
void put(String key, Object value) {
this.values.put(key, value);
}
void putAll(Map<String, Object> values) {
this.values.putAll(values);
}
}
}