|
| 1 | +package no.nav.dolly.libs.nais; |
| 2 | + |
| 3 | +import lombok.RequiredArgsConstructor; |
| 4 | +import lombok.extern.slf4j.Slf4j; |
| 5 | +import org.springframework.core.env.ConfigurableEnvironment; |
| 6 | + |
| 7 | +import java.io.BufferedReader; |
| 8 | +import java.io.InputStreamReader; |
| 9 | +import java.util.ArrayList; |
| 10 | +import java.util.List; |
| 11 | +import java.util.Map; |
| 12 | +import java.util.Optional; |
| 13 | +import java.util.stream.Collectors; |
| 14 | + |
| 15 | +@RequiredArgsConstructor |
| 16 | +@Slf4j |
| 17 | +class NaisRuntimeEnvironmentConnector { |
| 18 | + |
| 19 | + private final ConfigurableEnvironment environment; |
| 20 | + |
| 21 | + Map<String, String> getEnvironmentVariables() |
| 22 | + throws NaisEnvironmentException { |
| 23 | + |
| 24 | + if (!environment.matchesProfiles("local")) { |
| 25 | + throw new NaisEnvironmentException("Attempted to load environment variables from pod in non-local profile"); |
| 26 | + } |
| 27 | + try { |
| 28 | + var applicationName = resolveApplicationName(); |
| 29 | + var requestedKeys = resolveRequestedKeys(); |
| 30 | + if (applicationName == null || requestedKeys.isEmpty()) { |
| 31 | + log.info("Application is not configured for dynamic environment variables from NAIS"); |
| 32 | + return Map.of(); |
| 33 | + } |
| 34 | + var cluster = resolveCluster(); |
| 35 | + var pod = resolvePod(cluster, applicationName); |
| 36 | + return getVariables(cluster, pod, requestedKeys); |
| 37 | + } catch (NaisEnvironmentException e) { |
| 38 | + throw e; |
| 39 | + } catch (Exception e) { |
| 40 | + throw new NaisEnvironmentException("Unexpected failure", e); |
| 41 | + } |
| 42 | + |
| 43 | + } |
| 44 | + |
| 45 | + private List<String> resolveRequestedKeys() { |
| 46 | + |
| 47 | + var keys = new ArrayList<String>(); |
| 48 | + for (int i = 0; ; i++) { |
| 49 | + var key = "dolly.nais.variables[%d]".formatted(i); |
| 50 | + if (!environment.containsProperty(key)) { |
| 51 | + break; |
| 52 | + } |
| 53 | + keys.add(environment.getProperty(key)); |
| 54 | + } |
| 55 | + return keys; |
| 56 | + |
| 57 | + } |
| 58 | + |
| 59 | + private String resolveApplicationName() { |
| 60 | + |
| 61 | + return Optional |
| 62 | + .ofNullable(environment.getProperty("dolly.nais.name")) |
| 63 | + .map(Object::toString) |
| 64 | + .orElse(null); |
| 65 | + |
| 66 | + } |
| 67 | + |
| 68 | + private String resolveCluster() { |
| 69 | + |
| 70 | + return Optional |
| 71 | + .ofNullable(environment.getProperty("dolly.nais.cluster")) |
| 72 | + .map(Object::toString) |
| 73 | + .orElseGet(() -> { |
| 74 | + log.info("Cannot determine cluster from dolly.nais.cluster, guessing on dev-gcp"); |
| 75 | + return "dev-gcp"; |
| 76 | + }); |
| 77 | + |
| 78 | + } |
| 79 | + |
| 80 | + private String resolvePod(String cluster, String applicationName) |
| 81 | + throws NaisEnvironmentException { |
| 82 | + |
| 83 | + var pods = getAllPodsInClusterWithName(cluster, applicationName); |
| 84 | + if (pods.isEmpty()) { |
| 85 | + throw new NaisEnvironmentException("No pods found for %s in %s".formatted(applicationName, cluster)); |
| 86 | + } |
| 87 | + if (pods.size() > 1) { |
| 88 | + log.warn("Multiple pods found for {} in {}, picking {}", applicationName, cluster, pods.getFirst()); |
| 89 | + } |
| 90 | + return pods.getFirst(); |
| 91 | + |
| 92 | + } |
| 93 | + |
| 94 | + private Map<String, String> getVariables(String cluster, String pod, List<String> requestedKeys) |
| 95 | + throws NaisEnvironmentException { |
| 96 | + |
| 97 | + var command = "kubectl exec --cluster=%s --namespace=dolly %s -- env" |
| 98 | + .formatted(cluster, pod); |
| 99 | + var output = execute(command); |
| 100 | + var variables = output |
| 101 | + .stream() |
| 102 | + .map(line -> line.split("=")) |
| 103 | + .filter(elements -> requestedKeys.contains(elements[0])) |
| 104 | + .collect(Collectors.toMap( |
| 105 | + elements -> elements[0], |
| 106 | + elements -> elements[1], |
| 107 | + (a, b) -> a)); |
| 108 | + log.info("Retrieved {}/{} keys from pod {}:{}", variables.size(), requestedKeys.size(), cluster, pod); |
| 109 | + return variables; |
| 110 | + |
| 111 | + } |
| 112 | + |
| 113 | + private List<String> getAllPodsInClusterWithName(String cluster, String name) |
| 114 | + throws NaisEnvironmentException { |
| 115 | + |
| 116 | + var command = "kubectl get pods --cluster=%s --namespace=dolly -l app=%s -o name" |
| 117 | + .formatted(cluster, name); |
| 118 | + return execute(command) |
| 119 | + .stream() |
| 120 | + .map(pod -> pod.substring(pod.lastIndexOf("/") + 1).trim()) |
| 121 | + .sorted() |
| 122 | + .toList(); |
| 123 | + |
| 124 | + } |
| 125 | + |
| 126 | + private List<String> execute(String command) |
| 127 | + throws NaisEnvironmentException { |
| 128 | + |
| 129 | + var processBuilder = new ProcessBuilder(command.split(" ")); |
| 130 | + try { |
| 131 | + var process = processBuilder.start(); |
| 132 | + var reader = new BufferedReader(new InputStreamReader(process.getInputStream())); |
| 133 | + var output = new ArrayList<String>(); |
| 134 | + String line; |
| 135 | + while ((line = reader.readLine()) != null) { |
| 136 | + output.add(line); |
| 137 | + } |
| 138 | + var status = process.waitFor(); |
| 139 | + if (status != 0) { |
| 140 | + log.warn("Command terminated with status {}: {}", status, command); |
| 141 | + } |
| 142 | + return output; |
| 143 | + } catch (InterruptedException e) { |
| 144 | + log.warn("Interrupted while waiting for command: {}", command, e); |
| 145 | + Thread.currentThread().interrupt(); |
| 146 | + return List.of(); |
| 147 | + } |
| 148 | + catch (Exception e) { |
| 149 | + throw new NaisEnvironmentException("Failed to execute command: " + command, e); |
| 150 | + } |
| 151 | + |
| 152 | + } |
| 153 | + |
| 154 | +} |
0 commit comments