|
| 1 | +// Copyright (c) Microsoft Corporation. All rights reserved. |
| 2 | +// Licensed under the MIT License. |
| 3 | + |
| 4 | +package com.azure.spring.cloud.autoconfigure.monitor.implementation.selfdiagnostics; |
| 5 | + |
| 6 | +import org.slf4j.Logger; |
| 7 | +import org.springframework.boot.CommandLineRunner; |
| 8 | +import org.springframework.core.env.ConfigurableEnvironment; |
| 9 | +import org.springframework.core.env.Environment; |
| 10 | +import org.springframework.core.env.PropertySource; |
| 11 | + |
| 12 | +import java.util.AbstractMap.SimpleEntry; |
| 13 | +import java.util.Locale; |
| 14 | +import java.util.Map; |
| 15 | +import java.util.stream.Collectors; |
| 16 | +import java.util.stream.StreamSupport; |
| 17 | + |
| 18 | +class SpringEnvSelfDiag implements CommandLineRunner { |
| 19 | + |
| 20 | + private final Environment environment; |
| 21 | + |
| 22 | + private final Logger selfDiagnosticsLogger; |
| 23 | + |
| 24 | + SpringEnvSelfDiag(Environment environment, Logger selfDiagnosticsLogger) { |
| 25 | + this.environment = environment; |
| 26 | + this.selfDiagnosticsLogger = selfDiagnosticsLogger; |
| 27 | + } |
| 28 | + |
| 29 | + @Override |
| 30 | + public void run(String... args) { |
| 31 | + if (!selfDiagnosticsLogger.isTraceEnabled()) { |
| 32 | + return; |
| 33 | + } |
| 34 | + |
| 35 | + try { |
| 36 | + executeSpringEnvSelfDiag(); |
| 37 | + } catch (Exception e) { |
| 38 | + selfDiagnosticsLogger.warn("An unexpected issue has happened during Spring env self-diagnostics.", e); |
| 39 | + } |
| 40 | + } |
| 41 | + |
| 42 | + private void executeSpringEnvSelfDiag() { |
| 43 | + if (environment instanceof ConfigurableEnvironment) { |
| 44 | + ConfigurableEnvironment configurableEnvironment = (ConfigurableEnvironment) environment; |
| 45 | + String env = buildEnvAsString(configurableEnvironment); |
| 46 | + selfDiagnosticsLogger.trace("Env: " + env); |
| 47 | + } |
| 48 | + } |
| 49 | + |
| 50 | + private static String buildEnvAsString(ConfigurableEnvironment configurableEnvironment) { |
| 51 | + return StreamSupport.stream(configurableEnvironment.getPropertySources().spliterator(), false) |
| 52 | + .map(PropertySource::getSource) |
| 53 | + .filter(source -> source instanceof Map) |
| 54 | + .flatMap(source -> ((Map<?, ?>) source).entrySet().stream()) |
| 55 | + .map(entry -> { |
| 56 | + String value = isSensitive(entry) ? "***" : entry.getValue().toString(); |
| 57 | + return new SimpleEntry<>(entry.getKey().toString(), value); |
| 58 | + }) |
| 59 | + .map(SimpleEntry::toString) |
| 60 | + .collect(Collectors.joining(", ")); |
| 61 | + } |
| 62 | + |
| 63 | + private static boolean isSensitive(Map.Entry<?, ?> entry) { |
| 64 | + String key = entry.getKey().toString().toLowerCase(Locale.ROOT); |
| 65 | + return key.contains("password") || key.contains("pwd") || key.contains("secret"); |
| 66 | + } |
| 67 | +} |
0 commit comments