-
Notifications
You must be signed in to change notification settings - Fork 1k
/
DefaultEnvironment.java
1016 lines (908 loc) · 39.8 KB
/
DefaultEnvironment.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
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* 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.context.env;
import io.micronaut.context.ApplicationContextConfiguration;
import io.micronaut.context.exceptions.ConfigurationException;
import io.micronaut.core.annotation.NonNull;
import io.micronaut.core.annotation.Nullable;
import io.micronaut.core.convert.ConversionContext;
import io.micronaut.core.convert.TypeConverter;
import io.micronaut.core.io.ResourceLoader;
import io.micronaut.core.io.ResourceResolver;
import io.micronaut.core.io.file.DefaultFileSystemResourceLoader;
import io.micronaut.core.io.file.FileSystemResourceLoader;
import io.micronaut.core.io.scan.BeanIntrospectionScanner;
import io.micronaut.core.io.scan.ClassPathResourceLoader;
import io.micronaut.core.io.service.SoftServiceLoader;
import io.micronaut.core.naming.NameUtils;
import io.micronaut.core.optim.StaticOptimizations;
import io.micronaut.core.order.OrderUtil;
import io.micronaut.core.reflect.ClassUtils;
import io.micronaut.core.util.StringUtils;
import io.micronaut.inject.BeanConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.annotation.Annotation;
import java.net.InetAddress;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* <p>The default implementation of the {@link Environment} interface. Configures a named environment.</p>
*
* @author Graeme Rocher
* @author rvanderwerf
* @since 1.0
*/
public class DefaultEnvironment extends PropertySourcePropertyResolver implements Environment {
private static final List<PropertySource> CONSTANT_PROPERTY_SOURCES = StaticOptimizations.get(ConstantPropertySources.class)
.map(ConstantPropertySources::getSources)
.orElse(Collections.emptyList());
private static final String EC2_LINUX_HYPERVISOR_FILE = "/sys/hypervisor/uuid";
private static final String EC2_LINUX_BIOS_VENDOR_FILE = "/sys/devices/virtual/dmi/id/bios_vendor";
private static final String EC2_WINDOWS_HYPERVISOR_CMD = "wmic path win32_computersystemproduct get uuid";
private static final String FILE_SEPARATOR = ",";
private static final Logger LOG = LoggerFactory.getLogger(DefaultEnvironment.class);
private static final String AWS_LAMBDA_FUNCTION_NAME_ENV = "AWS_LAMBDA_FUNCTION_NAME";
private static final String K8S_ENV = "KUBERNETES_SERVICE_HOST";
private static final String PCF_ENV = "VCAP_SERVICES";
private static final String HEROKU_DYNO = "DYNO";
private static final String GOOGLE_APPENGINE_ENVIRONMENT = "GAE_ENV";
private static final int DEFAULT_READ_TIMEOUT = 500;
private static final int DEFAULT_CONNECT_TIMEOUT = 500;
// CHECKSTYLE:OFF
private static final String GOOGLE_COMPUTE_METADATA = "metadata.google.internal";
// CHECKSTYLE:ON
private static final String ORACLE_CLOUD_ASSET_TAG_FILE = "/sys/devices/virtual/dmi/id/chassis_asset_tag";
private static final String ORACLE_CLOUD_WINDOWS_ASSET_TAG_CMD = "wmic systemenclosure get smbiosassettag";
private static final String DO_SYS_VENDOR_FILE = "/sys/devices/virtual/dmi/id/sys_vendor";
private static final Boolean DEDUCE_ENVIRONMENT_DEFAULT = true;
private static final List<String> DEFAULT_CONFIG_LOCATIONS = Arrays.asList("classpath:/", "file:config/");
protected final ClassPathResourceLoader resourceLoader;
protected final List<PropertySource> refreshablePropertySources = new ArrayList<>(10);
private EnvironmentsAndPackage environmentsAndPackage;
private final Set<String> names;
private final ClassLoader classLoader;
private final Collection<String> packages = new ConcurrentLinkedQueue<>();
private final BeanIntrospectionScanner annotationScanner;
private Collection<String> configurationIncludes = new HashSet<>(3);
private Collection<String> configurationExcludes = new HashSet<>(3);
private final AtomicBoolean running = new AtomicBoolean(false);
private Collection<PropertySourceLoader> propertySourceLoaderList;
private final Map<String, PropertySourceLoader> loaderByFormatMap = new ConcurrentHashMap<>();
private final Map<String, Boolean> presenceCache = new ConcurrentHashMap<>();
private final AtomicBoolean reading = new AtomicBoolean(false);
private final Boolean deduceEnvironments;
private final ApplicationContextConfiguration configuration;
private final Collection<String> configLocations;
/**
* Construct a new environment for the given configuration.
*
* @param configuration The configuration
*/
public DefaultEnvironment(@NonNull ApplicationContextConfiguration configuration) {
super(configuration.getConversionService());
this.configuration = configuration;
this.resourceLoader = configuration.getResourceLoader();
Set<String> environments = new LinkedHashSet<>(3);
List<String> specifiedNames = new ArrayList<>(configuration.getEnvironments());
specifiedNames.addAll(0, Stream.of(CachedEnvironment.getProperty(ENVIRONMENTS_PROPERTY),
CachedEnvironment.getenv(ENVIRONMENTS_ENV))
.filter(StringUtils::isNotEmpty)
.flatMap(s -> Arrays.stream(s.split(",")))
.map(String::trim)
.collect(Collectors.toList()));
this.deduceEnvironments = configuration.getDeduceEnvironments().orElse(null);
EnvironmentsAndPackage environmentsAndPackage = getEnvironmentsAndPackage(specifiedNames);
if (environmentsAndPackage.enviroments.isEmpty() && specifiedNames.isEmpty()) {
specifiedNames = configuration.getDefaultEnvironments();
}
environments.addAll(environmentsAndPackage.enviroments);
String aPackage = environmentsAndPackage.aPackage;
if (aPackage != null) {
packages.add(aPackage);
}
environments.removeAll(specifiedNames);
environments.addAll(specifiedNames);
this.classLoader = configuration.getClassLoader();
this.annotationScanner = createAnnotationScanner(classLoader);
this.names = environments;
if (LOG.isInfoEnabled() && !environments.isEmpty()) {
LOG.info("Established active environments: {}", environments);
}
List<String> configLocations = configuration.getOverrideConfigLocations() == null ?
new ArrayList<>(DEFAULT_CONFIG_LOCATIONS) : configuration.getOverrideConfigLocations();
// Search config locations in reverse order
Collections.reverse(configLocations);
this.configLocations = configLocations;
}
@Override
public boolean isPresent(String className) {
return presenceCache.computeIfAbsent(className, s -> ClassUtils.isPresent(className, getClassLoader()));
}
@Override
public PropertyPlaceholderResolver getPlaceholderResolver() {
return this.propertyPlaceholderResolver;
}
@Override
public Stream<Class<?>> scan(Class<? extends Annotation> annotation) {
return annotationScanner.scan(annotation, getPackages());
}
@Override
public Stream<Class<?>> scan(Class<? extends Annotation> annotation, String... packages) {
return annotationScanner.scan(annotation, packages);
}
@Override
public ClassLoader getClassLoader() {
return classLoader;
}
@Override
public boolean isActive(BeanConfiguration configuration) {
String name = configuration.getName();
return !configurationExcludes.contains(name) && (configurationIncludes.isEmpty() || configurationIncludes.contains(name));
}
@Override
public DefaultEnvironment addPropertySource(PropertySource propertySource) {
propertySources.put(propertySource.getName(), propertySource);
if (isRunning() && !reading.get()) {
resetCaches();
processPropertySource(propertySource, PropertySource.PropertyConvention.JAVA_PROPERTIES);
}
return this;
}
@Override
public Environment removePropertySource(PropertySource propertySource) {
propertySources.remove(propertySource.getName());
if (isRunning() && !reading.get()) {
resetCaches();
}
return this;
}
@Override
public DefaultEnvironment addPropertySource(String name, Map<String, ? super Object> values) {
return (DefaultEnvironment) super.addPropertySource(name, values);
}
@Override
public Environment addPackage(String pkg) {
if (!this.packages.contains(pkg)) {
this.packages.add(pkg);
}
return this;
}
@Override
public Environment addConfigurationExcludes(@Nullable String... names) {
if (names != null) {
configurationExcludes.addAll(Arrays.asList(names));
}
return this;
}
@Override
public Environment addConfigurationIncludes(String... names) {
if (names != null) {
configurationIncludes.addAll(Arrays.asList(names));
}
return this;
}
@Override
public Collection<String> getPackages() {
return Collections.unmodifiableCollection(packages);
}
@Override
public Set<String> getActiveNames() {
return this.names;
}
@Override
public Collection<PropertySource> getPropertySources() {
return Collections.unmodifiableCollection(this.propertySources.values());
}
@Override
public Environment start() {
if (running.compareAndSet(false, true)) {
if (LOG.isDebugEnabled()) {
LOG.debug("Starting environment {} for active names {}", this, getActiveNames());
}
if (reading.compareAndSet(false, true)) {
readPropertySources(getPropertySourceRootName());
reading.set(false);
}
}
return this;
}
@Override
public boolean isRunning() {
return running.get();
}
@Override
public Environment stop() {
running.set(false);
reading.set(false);
this.propertySources.values().removeAll(refreshablePropertySources);
synchronized (catalog) {
for (int i = 0; i < catalog.length; i++) {
catalog[i] = null;
}
resetCaches();
}
return this;
}
@Override
public Map<String, Object> refreshAndDiff() {
Map<String, Object>[] copiedCatalog = copyCatalog();
refresh();
return diffCatalog(copiedCatalog, catalog);
}
@Override
public <T> Optional<T> convert(Object object, Class<T> targetType, ConversionContext context) {
return conversionService.convert(object, targetType, context);
}
@Override
public <S, T> boolean canConvert(Class<S> sourceType, Class<T> targetType) {
return conversionService.canConvert(sourceType, targetType);
}
@Override
public <S, T> Environment addConverter(Class<S> sourceType, Class<T> targetType, TypeConverter<S, T> typeConverter) {
conversionService.addConverter(sourceType, targetType, typeConverter);
return this;
}
@Override
public <S, T> Environment addConverter(Class<S> sourceType, Class<T> targetType, Function<S, T> typeConverter) {
conversionService.addConverter(sourceType, targetType, typeConverter);
return this;
}
@Override
public Optional<InputStream> getResourceAsStream(String path) {
return resourceLoader.getResourceAsStream(path);
}
@Override
public Optional<URL> getResource(String path) {
return resourceLoader.getResource(path);
}
@Override
public Stream<URL> getResources(String path) {
return resourceLoader.getResources(path);
}
@Override
public boolean supportsPrefix(String path) {
return resourceLoader.supportsPrefix(path);
}
@Override
public ResourceLoader forBase(String basePath) {
return resourceLoader.forBase(basePath);
}
/**
* @return Whether environment names and packages should be deduced
*/
protected boolean shouldDeduceEnvironments() {
if (deduceEnvironments != null) {
if (LOG.isDebugEnabled()) {
LOG.debug("Environment deduction was set explicitly via builder to: " + deduceEnvironments);
}
return deduceEnvironments;
} else {
String deduceProperty = CachedEnvironment.getProperty(Environment.DEDUCE_ENVIRONMENT_PROPERTY);
String deduceEnv = CachedEnvironment.getenv(Environment.DEDUCE_ENVIRONMENT_ENV);
if (StringUtils.isNotEmpty(deduceEnv)) {
boolean deduce = Boolean.parseBoolean(deduceEnv);
if (LOG.isDebugEnabled()) {
LOG.debug("Environment deduction was set via environment variable to: " + deduce);
}
return deduce;
} else if (StringUtils.isNotEmpty(deduceProperty)) {
boolean deduce = Boolean.parseBoolean(deduceProperty);
if (LOG.isDebugEnabled()) {
LOG.debug("Environment deduction was set via system property to: " + deduce);
}
return deduce;
} else {
boolean deduceDefault = DEDUCE_ENVIRONMENT_DEFAULT;
if (LOG.isDebugEnabled()) {
LOG.debug("Environment deduction is using the default of: " + deduceDefault);
}
return deduceDefault;
}
}
}
/**
* Creates the default annotation scanner.
*
* @param classLoader The class loader
* @return The scanner
*/
protected BeanIntrospectionScanner createAnnotationScanner(ClassLoader classLoader) {
return new BeanIntrospectionScanner();
}
/**
* @return The property source root name
*/
protected String getPropertySourceRootName() {
return DEFAULT_NAME;
}
/**
* @param name The name to read property sources
*/
protected void readPropertySources(String name) {
refreshablePropertySources.clear();
List<PropertySource> propertySources = readPropertySourceList(name);
addDefaultPropertySources(propertySources);
String propertySourcesSystemProperty = CachedEnvironment.getProperty(Environment.PROPERTY_SOURCES_KEY);
if (propertySourcesSystemProperty != null) {
propertySources.addAll(readPropertySourceListFromFiles(propertySourcesSystemProperty));
}
String propertySourcesEnv = readPropertySourceListKeyFromEnvironment();
if (propertySourcesEnv != null) {
propertySources.addAll(readPropertySourceListFromFiles(propertySourcesEnv));
}
refreshablePropertySources.addAll(propertySources);
readConstantPropertySources(name, propertySources);
propertySources.addAll(this.propertySources.values());
OrderUtil.sort(propertySources);
for (PropertySource propertySource : propertySources) {
if (LOG.isDebugEnabled()) {
LOG.debug("Processing property source: {}", propertySource.getName());
}
processPropertySource(propertySource, propertySource.getConvention());
}
}
private void readConstantPropertySources(String name, List<PropertySource> propertySources) {
Set<String> propertySourceNames = Stream.concat(Stream.of(name), getActiveNames().stream().map(env -> name + "-" + env))
.collect(Collectors.toSet());
getConstantPropertySources().stream()
.filter(p -> propertySourceNames.contains(p.getName()))
.forEach(propertySources::add);
}
/**
* @return Property sources created at build time
*/
protected List<PropertySource> getConstantPropertySources() {
return CONSTANT_PROPERTY_SOURCES;
}
/**
* Reads the value of MICRONAUT_CONFIG_FILES environment variable.
*
* @return The comma-separated list of files
*/
protected String readPropertySourceListKeyFromEnvironment() {
return CachedEnvironment.getenv(StringUtils.convertDotToUnderscore(Environment.PROPERTY_SOURCES_KEY));
}
/**
* Resolve the property sources for files passed via system property and system env.
*
* @param files The comma separated list of files
* @return The list of property sources for each file
*/
protected List<PropertySource> readPropertySourceListFromFiles(String files) {
List<PropertySource> propertySources = new ArrayList<>();
Collection<PropertySourceLoader> propertySourceLoaders = getPropertySourceLoaders();
Optional<Collection<String>> filePathList = Optional.ofNullable(files)
.filter(value -> !value.isEmpty())
.map(value -> value.split(FILE_SEPARATOR))
.map(Arrays::asList)
.map(Collections::unmodifiableList);
filePathList.ifPresent(list -> {
if (!list.isEmpty()) {
int order = AbstractPropertySourceLoader.DEFAULT_POSITION + 50;
for (String filePath: list) {
if (!propertySourceLoaders.isEmpty()) {
String extension = NameUtils.extension(filePath);
String fileName = NameUtils.filename(filePath);
Optional<PropertySourceLoader> propertySourceLoader = Optional.ofNullable(loaderByFormatMap.get(extension));
if (propertySourceLoader.isPresent()) {
if (LOG.isDebugEnabled()) {
LOG.debug("Reading property sources from loader: {}", propertySourceLoader);
}
Optional<Map<String, Object>> properties = readPropertiesFromLoader(fileName, filePath, propertySourceLoader.get());
if (properties.isPresent()) {
propertySources.add(PropertySource.of(filePath, properties.get(), order));
}
order++;
} else {
throw new ConfigurationException("Unsupported properties file format while reading " + fileName + "." + extension + " from " + filePath);
}
}
}
}
});
return propertySources;
}
/**
* @param name The name to resolver property sources
* @return The list of property sources
*/
protected List<PropertySource> readPropertySourceList(String name) {
List<PropertySource> propertySources = new ArrayList<>();
for (String configLocation : configLocations) {
ResourceLoader resourceLoader;
if (configLocation.equals("classpath:/")) {
resourceLoader = this;
} else if (configLocation.startsWith("classpath:")) {
resourceLoader = this.forBase(configLocation);
} else if (configLocation.startsWith("file:")) {
configLocation = configLocation.substring(5);
Path configLocationPath = Paths.get(configLocation);
if (Files.exists(configLocationPath) && Files.isDirectory(configLocationPath) && Files.isReadable(configLocationPath)) {
resourceLoader = new DefaultFileSystemResourceLoader(configLocationPath);
} else {
continue; // Skip not existing config location
}
} else {
throw new ConfigurationException("Unsupported config location format: " + configLocation);
}
readPropertySourceList(name, resourceLoader, propertySources);
}
return propertySources;
}
private void readPropertySourceList(String name, ResourceLoader resourceLoader, List<PropertySource> propertySources) {
Collection<PropertySourceLoader> propertySourceLoaders = getPropertySourceLoaders();
if (propertySourceLoaders.isEmpty()) {
loadPropertySourceFromLoader(name, new PropertiesPropertySourceLoader(), propertySources, resourceLoader);
} else {
for (PropertySourceLoader propertySourceLoader : propertySourceLoaders) {
if (LOG.isDebugEnabled()) {
LOG.debug("Reading property sources from loader: {}", propertySourceLoader);
}
loadPropertySourceFromLoader(name, propertySourceLoader, propertySources, resourceLoader);
}
}
}
/**
* Adds default property sources.
*
* @param propertySources The list of property sources
*/
protected void addDefaultPropertySources(List<PropertySource> propertySources) {
if (!this.propertySources.containsKey(SystemPropertiesPropertySource.NAME)) {
propertySources.add(new SystemPropertiesPropertySource());
}
if (!this.propertySources.containsKey(EnvironmentPropertySource.NAME) && configuration.isEnvironmentPropertySource()) {
List<String> includes = configuration.getEnvironmentVariableIncludes();
List<String> excludes = configuration.getEnvironmentVariableExcludes();
if (this.names.contains(Environment.KUBERNETES)) {
propertySources.add(new KubernetesEnvironmentPropertySource(includes, excludes));
} else {
propertySources.add(new EnvironmentPropertySource(includes, excludes));
}
}
}
/**
* @return Loaded properties as a {@link SoftServiceLoader}
*/
protected SoftServiceLoader<PropertySourceLoader> readPropertySourceLoaders() {
return SoftServiceLoader.load(PropertySourceLoader.class, getClassLoader());
}
/**
* Obtains the {@link PropertySourceLoader} instances.
*
* @return A collection of {@link PropertySourceLoader}
*/
@Override
public Collection<PropertySourceLoader> getPropertySourceLoaders() {
Collection<PropertySourceLoader> propertySourceLoaderList = this.propertySourceLoaderList;
if (propertySourceLoaderList == null) {
synchronized (this) { // double check
propertySourceLoaderList = this.propertySourceLoaderList;
if (propertySourceLoaderList == null) {
propertySourceLoaderList = evaluatePropertySourceLoaders();
this.propertySourceLoaderList = propertySourceLoaderList;
}
}
}
return propertySourceLoaderList;
}
@SuppressWarnings("MagicNumber")
private Collection<PropertySourceLoader> evaluatePropertySourceLoaders() {
SoftServiceLoader<PropertySourceLoader> definitions = readPropertySourceLoaders();
Collection<PropertySourceLoader> allLoaders = definitions.collectAll();
for (PropertySourceLoader propertySourceLoader : allLoaders) {
Set<String> extensions = propertySourceLoader.getExtensions();
for (String extension : extensions) {
loaderByFormatMap.put(extension, propertySourceLoader);
}
}
return allLoaders;
}
private void loadPropertySourceFromLoader(String name, PropertySourceLoader propertySourceLoader, List<PropertySource> propertySources, ResourceLoader resourceLoader) {
Optional<PropertySource> defaultPropertySource = propertySourceLoader.load(name, resourceLoader);
defaultPropertySource.ifPresent(propertySources::add);
Set<String> activeNames = getActiveNames();
int i = 0;
for (String activeName: activeNames) {
Optional<PropertySource> propertySource = propertySourceLoader.loadEnv(name, resourceLoader, ActiveEnvironment.of(activeName, i));
propertySource.ifPresent(propertySources::add);
i++;
}
}
/**
* Read the property source.
*
* @param fileName Name of the file to be used as property source name
* @param filePath Absolute file path
* @param propertySourceLoader The appropriate property source loader
* @throws ConfigurationException If unable to find the appropriate property source loader for the given file
*/
private Optional<Map<String, Object>> readPropertiesFromLoader(String fileName, String filePath, PropertySourceLoader propertySourceLoader) throws ConfigurationException {
ResourceLoader loader = new ResourceResolver().getSupportingLoader(filePath)
.orElse(FileSystemResourceLoader.defaultLoader());
try {
Optional<InputStream> inputStream = loader.getResourceAsStream(filePath);
if (inputStream.isPresent()) {
return Optional.of(propertySourceLoader.read(fileName, inputStream.get()));
} else {
throw new ConfigurationException("Failed to read configuration file: " + filePath);
}
} catch (IOException e) {
throw new ConfigurationException("Unsupported properties file: " + fileName);
}
}
private EnvironmentsAndPackage getEnvironmentsAndPackage(List<String> specifiedNames) {
EnvironmentsAndPackage environmentsAndPackage = this.environmentsAndPackage;
final boolean extendedDeduction = !specifiedNames.contains(Environment.FUNCTION);
if (environmentsAndPackage == null) {
synchronized (EnvironmentsAndPackage.class) { // double check
environmentsAndPackage = this.environmentsAndPackage;
if (environmentsAndPackage == null) {
environmentsAndPackage = deduceEnvironmentsAndPackage(
shouldDeduceEnvironments(),
extendedDeduction,
extendedDeduction,
!extendedDeduction
);
this.environmentsAndPackage = environmentsAndPackage;
}
}
}
return environmentsAndPackage;
}
private static EnvironmentsAndPackage deduceEnvironmentsAndPackage(
boolean deduceEnvironments,
boolean deduceComputePlatform,
boolean inspectTrace,
boolean deduceFunctionPlatform
) {
EnvironmentsAndPackage environmentsAndPackage = new EnvironmentsAndPackage();
Set<String> environments = environmentsAndPackage.enviroments;
if (inspectTrace) {
performStackTraceInspection(deduceEnvironments, environmentsAndPackage, environments);
}
if (deduceEnvironments && !environments.contains(ANDROID)) {
performEnvironmentDeduction(deduceComputePlatform, environments);
}
if (deduceFunctionPlatform) {
performFunctionDeduction(environments);
}
return environmentsAndPackage;
}
private static void performFunctionDeduction(Set<String> environments) {
// deduce AWS Lambda
if (StringUtils.isNotEmpty(CachedEnvironment.getenv(AWS_LAMBDA_FUNCTION_NAME_ENV))) {
environments.add(Environment.AMAZON_EC2);
environments.add(Environment.CLOUD);
}
}
private static void performEnvironmentDeduction(boolean deduceComputePlatform, Set<String> environments) {
// deduce k8s
if (StringUtils.isNotEmpty(CachedEnvironment.getenv(K8S_ENV))) {
environments.add(Environment.KUBERNETES);
environments.add(Environment.CLOUD);
}
// deduce CF
if (StringUtils.isNotEmpty(CachedEnvironment.getenv(PCF_ENV))) {
environments.add(Environment.CLOUD_FOUNDRY);
environments.add(Environment.CLOUD);
}
// deduce heroku
if (StringUtils.isNotEmpty(CachedEnvironment.getenv(HEROKU_DYNO))) {
environments.add(Environment.HEROKU);
environments.add(Environment.CLOUD);
deduceComputePlatform = false;
}
// deduce GAE
if (StringUtils.isNotEmpty(CachedEnvironment.getenv(GOOGLE_APPENGINE_ENVIRONMENT))) {
environments.add(Environment.GAE);
environments.add(Environment.GOOGLE_COMPUTE);
deduceComputePlatform = false;
}
if (deduceComputePlatform) {
performComputePlatformDeduction(environments);
}
}
private static void performComputePlatformDeduction(Set<String> environments) {
ComputePlatform computePlatform = determineCloudProvider();
if (computePlatform != null) {
switch (computePlatform) {
case GOOGLE_COMPUTE:
//instantiate bean for GC metadata discovery
environments.add(GOOGLE_COMPUTE);
environments.add(Environment.CLOUD);
break;
case AMAZON_EC2:
//instantiate bean for ec2 metadata discovery
environments.add(AMAZON_EC2);
environments.add(Environment.CLOUD);
break;
case ORACLE_CLOUD:
environments.add(ORACLE_CLOUD);
environments.add(Environment.CLOUD);
break;
case AZURE:
// not yet implemented
environments.add(AZURE);
environments.add(Environment.CLOUD);
break;
case IBM:
// not yet implemented
environments.add(IBM);
environments.add(Environment.CLOUD);
break;
case DIGITAL_OCEAN:
environments.add(DIGITAL_OCEAN);
environments.add(Environment.CLOUD);
break;
case OTHER:
// do nothing here
break;
default:
// no-op
}
}
}
private static void performStackTraceInspection(boolean deduceEnvironments, EnvironmentsAndPackage environmentsAndPackage, Set<String> environments) {
StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
int len = stackTrace.length;
for (int i = 0; i < len; i++) {
StackTraceElement stackTraceElement = stackTrace[i];
String className = stackTraceElement.getClassName();
analyzeStackTraceElement(deduceEnvironments, environmentsAndPackage, environments, stackTrace, len, i, stackTraceElement, className);
}
}
private static void analyzeStackTraceElement(boolean deduceEnvironments, EnvironmentsAndPackage environmentsAndPackage, Set<String> environments, StackTraceElement[] stackTrace, int len, int i, StackTraceElement stackTraceElement, String className) {
if (className.startsWith("io.micronaut")) {
int nextIndex = i + 1;
if (nextIndex < len) {
StackTraceElement next = stackTrace[nextIndex];
if (!next.getClassName().startsWith("io.micronaut")) {
environmentsAndPackage.aPackage = NameUtils.getPackageName(next.getClassName());
}
}
}
if (stackTraceElement.getMethodName().contains("$spock_")) {
environmentsAndPackage.aPackage = NameUtils.getPackageName(className);
}
if (deduceEnvironments) {
if (Stream.of("org.spockframework", "org.junit", "io.kotlintest", "io.kotest").anyMatch(className::startsWith)) {
environments.add(TEST);
}
if (className.startsWith("com.android")) {
environments.add(ANDROID);
}
}
}
private Map<String, Object> diffCatalog(Map<String, Object>[] original, Map<String, Object>[] newCatalog) {
Map<String, Object> changes = new LinkedHashMap<>();
for (int i = 0; i < original.length; i++) {
Map<String, Object> map = original[i];
Map<String, Object> newMap = newCatalog[i];
boolean hasNew = newMap != null;
boolean hasOld = map != null;
if (!hasOld && hasNew) {
changes.putAll(newMap);
} else {
if (!hasNew && hasOld) {
changes.putAll(map);
} else if (hasOld && hasNew) {
diffMap(map, newMap, changes);
}
}
}
return changes;
}
private void diffMap(Map<String, Object> map, Map<String, Object> newMap, Map<String, Object> changes) {
for (Map.Entry<String, Object> entry : newMap.entrySet()) {
String key = entry.getKey();
Object newValue = entry.getValue();
if (!map.containsKey(key)) {
changes.put(key, newValue);
} else {
Object oldValue = map.get(key);
boolean hasNew = newValue != null;
boolean hasOld = oldValue != null;
if (hasNew && !hasOld) {
changes.put(key, null);
} else if (hasOld && !hasNew) {
changes.put(key, oldValue);
} else if (hasNew && hasOld && !newValue.equals(oldValue)) {
changes.put(key, oldValue);
}
}
}
}
private Map<String, Object>[] copyCatalog() {
Map<String, Object>[] newCatalog = new Map[catalog.length];
for (int i = 0; i < catalog.length; i++) {
Map<String, Object> entry = catalog[i];
if (entry != null) {
newCatalog[i] = new LinkedHashMap<>(entry);
}
}
return newCatalog;
}
private static ComputePlatform determineCloudProvider() {
String computePlatform = CachedEnvironment.getProperty(CLOUD_PLATFORM_PROPERTY);
if (computePlatform != null) {
try {
return ComputePlatform.valueOf(computePlatform);
} catch (IllegalArgumentException e) {
throw new ConfigurationException("Illegal value specified for [" + CLOUD_PLATFORM_PROPERTY + "]: " + computePlatform);
}
}
boolean isWindows = CachedEnvironment.getProperty("os.name")
.toLowerCase().startsWith("windows");
if (isWindows ? isEC2Windows() : isEC2Linux()) {
return ComputePlatform.AMAZON_EC2;
}
if (isGoogleCompute()) {
return ComputePlatform.GOOGLE_COMPUTE;
}
if (isWindows ? isOracleCloudWindows() : isOracleCloudLinux()) {
return ComputePlatform.ORACLE_CLOUD;
}
if (isDigitalOcean()) {
return ComputePlatform.DIGITAL_OCEAN;
}
//TODO check for azure and IBM
//Azure - see https://blog.mszcool.com/index.php/2015/04/detecting-if-a-virtual-machine-runs-in-microsoft-azure-linux-windows-to-protect-your-software-when-distributed-via-the-azure-marketplace/
//IBM - uses cloudfoundry, will have to use that to probe
// if all else fails not a cloud server that we can tell
return ComputePlatform.BARE_METAL;
}
@SuppressWarnings("MagicNumber")
private static boolean isGoogleCompute() {
try {
InetAddress.getByName(GOOGLE_COMPUTE_METADATA);
return true;
} catch (Exception e) {
// well not google then
}
return false;
}
@SuppressWarnings("MagicNumber")
private static boolean isOracleCloudLinux() {
return readFile(ORACLE_CLOUD_ASSET_TAG_FILE).toLowerCase().contains("oraclecloud");
}
private static Optional<Process> runWindowsCmd(String cmd) {
try {
ProcessBuilder builder = new ProcessBuilder();
builder.command("cmd.exe", "/c", cmd);
builder.redirectErrorStream(true);
builder.directory(new File(CachedEnvironment.getProperty("user.home")));
Process process = builder.start();
return Optional.of(process);
} catch (IOException e) {
}
return Optional.empty();
}
private static StringBuilder readProcessStream(Process process) {
StringBuilder stdout = new StringBuilder();
try {
//Read out dir output
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
while ((line = br.readLine()) != null) {
stdout.append(line);
}
} catch (IOException e) {
}
return stdout;
}
private static boolean isOracleCloudWindows() {
Optional<Process> optionalProcess = runWindowsCmd(ORACLE_CLOUD_WINDOWS_ASSET_TAG_CMD);
if (!optionalProcess.isPresent()) {
return false;
}
Process process = optionalProcess.get();
StringBuilder stdout = readProcessStream(process);
//Wait to get exit value
try {
int exitValue = process.waitFor();
if (exitValue == 0 && stdout.toString().toLowerCase().contains("oraclecloud")) {
return true;
}
} catch (InterruptedException e) {
// test negative
}
return false;
}
private static boolean isEC2Linux() {
if (readFile(EC2_LINUX_HYPERVISOR_FILE).startsWith("ec2")) {
return true;
} else if (readFile(EC2_LINUX_BIOS_VENDOR_FILE).toLowerCase().startsWith("amazon ec2")) {
return true;
}
return false;
}
private static String readFile(String path) {
try {
Path pathPath = Paths.get(path);
if (!Files.exists(pathPath)) {
return "";
}
return new String(Files.readAllBytes(pathPath)).trim();
} catch (IOException e) {
return "";
}
}
private static boolean isEC2Windows() {
Optional<Process> optionalProcess = runWindowsCmd(EC2_WINDOWS_HYPERVISOR_CMD);
if (!optionalProcess.isPresent()) {
return false;
}
Process process = optionalProcess.get();
StringBuilder stdout = readProcessStream(process);
//Wait to get exit value
try {
int exitValue = process.waitFor();
if (exitValue == 0 && stdout.toString().startsWith("EC2")) {
return true;
}
} catch (InterruptedException e) {
// test negative
}
return false;
}
private static boolean isDigitalOcean() {
return "digitalocean".equalsIgnoreCase(readFile(DO_SYS_VENDOR_FILE));
}
@Override
public void close() {