|
| 1 | +package io.github.easy4j.opencli.capability; |
| 2 | + |
| 3 | +import io.github.easy4j.opencli.OpenCliExecutionTarget; |
| 4 | +import io.github.easy4j.opencli.OpenCliProperties; |
| 5 | +import io.github.easy4j.opencli.capability.OpenCliCapabilitySnapshot.Status; |
| 6 | +import io.github.easy4j.opencli.core.OpenCliExecutionDetails.TerminationReason; |
| 7 | +import io.github.easy4j.opencli.core.OpenCliExecutor; |
| 8 | +import io.github.easy4j.opencli.core.OpenCliResult; |
| 9 | +import io.github.easy4j.opencli.exception.OpenCliException; |
| 10 | +import io.github.easy4j.opencli.exception.OpenCliTimeoutException; |
| 11 | +import io.github.easy4j.opencli.parser.OpenCliHelpParser; |
| 12 | +import io.github.easy4j.opencli.parser.OpenCliHelpResult; |
| 13 | +import io.github.easy4j.opencli.util.OpenCliStrings; |
| 14 | +import java.io.IOException; |
| 15 | +import java.nio.ByteBuffer; |
| 16 | +import java.nio.charset.StandardCharsets; |
| 17 | +import java.nio.file.Files; |
| 18 | +import java.nio.file.InvalidPathException; |
| 19 | +import java.nio.file.Path; |
| 20 | +import java.nio.file.Paths; |
| 21 | +import java.security.MessageDigest; |
| 22 | +import java.security.NoSuchAlgorithmException; |
| 23 | +import java.time.Instant; |
| 24 | +import java.util.Arrays; |
| 25 | +import java.util.Collections; |
| 26 | +import java.util.Map; |
| 27 | +import java.util.Objects; |
| 28 | +import java.util.TreeMap; |
| 29 | +import java.util.regex.Pattern; |
| 30 | + |
| 31 | +/** Fixed, bounded metadata probes through the existing local subprocess runtime. */ |
| 32 | +public final class OpenCliCapabilityDiscovery { |
| 33 | + private static final int MAX_PROBE_OUTPUT_BYTES = 1024 * 1024; |
| 34 | + private static final long MAX_PROBE_MILLIS = 10_000; |
| 35 | + private static final long MAX_CLEANUP_MILLIS = 1_000; |
| 36 | + private static final Pattern VERSION = Pattern.compile( |
| 37 | + "[0-9]+\\.[0-9]+\\.[0-9]+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?"); |
| 38 | + |
| 39 | + private OpenCliCapabilityDiscovery() { |
| 40 | + } |
| 41 | + |
| 42 | + /** |
| 43 | + * Observes version and root help on a configured, trusted absolute executable. |
| 44 | + * Installation, launcher arguments and environment are supplied by the trusted caller. |
| 45 | + * |
| 46 | + * @param executor client executor whose local process capacity is shared |
| 47 | + * @return the root observation or an explicit reason it could not be made |
| 48 | + */ |
| 49 | + public static OpenCliCapabilitySnapshot discover(OpenCliExecutor executor) { |
| 50 | + OpenCliProperties configured = executor.getProperties(); |
| 51 | + OpenCliCapabilitySnapshot.OpenCliCapabilitySnapshotBuilder snapshot = |
| 52 | + OpenCliCapabilitySnapshot.builder().observedAt(Instant.now()); |
| 53 | + if (configured.getExecutionTarget() != OpenCliExecutionTarget.LOCAL_PROCESS) { |
| 54 | + return snapshot.status(Status.UNSUPPORTED).reason("LOCAL_DISCOVERY_ONLY").build(); |
| 55 | + } |
| 56 | + if (OpenCliStrings.isBlank(configured.getExecutable())) { |
| 57 | + return snapshot.status(Status.UNSUPPORTED).reason("ABSOLUTE_EXECUTABLE_REQUIRED").build(); |
| 58 | + } |
| 59 | + |
| 60 | + OpenCliProperties probe = configured.copyForLocalCliExecution(); |
| 61 | + Path executable; |
| 62 | + try { |
| 63 | + Path configuredPath = Paths.get(probe.getExecutable().trim()); |
| 64 | + if (!configuredPath.isAbsolute()) { |
| 65 | + return snapshot.status(Status.UNSUPPORTED).reason("ABSOLUTE_EXECUTABLE_REQUIRED").build(); |
| 66 | + } |
| 67 | + executable = configuredPath.toRealPath(); |
| 68 | + if (!Files.isRegularFile(executable) || !Files.isExecutable(executable)) { |
| 69 | + return snapshot.status(Status.UNKNOWN).reason("EXECUTABLE_UNAVAILABLE").build(); |
| 70 | + } |
| 71 | + } catch (IOException | InvalidPathException | SecurityException ex) { |
| 72 | + return snapshot.status(Status.UNKNOWN).reason("EXECUTABLE_UNAVAILABLE").build(); |
| 73 | + } |
| 74 | + |
| 75 | + probe.setExecutable(executable.toString()); |
| 76 | + probe.setCommandTimeoutMillis(Math.min(MAX_PROBE_MILLIS, |
| 77 | + Math.min(probe.getStartupProbeTimeoutMillis(), probe.getCommandTimeoutMillis()))); |
| 78 | + probe.setCleanupGraceMillis(Math.min(MAX_CLEANUP_MILLIS, probe.getCleanupGraceMillis())); |
| 79 | + probe.setMaxStdoutBytes(Math.min(MAX_PROBE_OUTPUT_BYTES, probe.getMaxStdoutBytes())); |
| 80 | + probe.setMaxStderrBytes(Math.min(MAX_PROBE_OUTPUT_BYTES, probe.getMaxStderrBytes())); |
| 81 | + snapshot.executable(probe.getExecutable()).configurationSha256(configurationDigest(probe)); |
| 82 | + try (OpenCliExecutor local = new OpenCliExecutor(probe, executor.getProcessRuntime())) { |
| 83 | + String phase = "VERSION"; |
| 84 | + try { |
| 85 | + OpenCliResult versionResult = local.invokeLocalOnly(Collections.singletonList("--version")); |
| 86 | + String version = versionResult.getStdout().trim(); |
| 87 | + if (versionResult.getExecutionDetails().isStdoutTruncated() || !VERSION.matcher(version).matches()) { |
| 88 | + return snapshot.status(Status.UNKNOWN).reason("INVALID_VERSION_OUTPUT").build(); |
| 89 | + } |
| 90 | + snapshot.observedVersion(version); |
| 91 | + phase = "HELP"; |
| 92 | + OpenCliResult helpResult = local.invokeLocalOnly(Arrays.asList("--help", "-f", "json")); |
| 93 | + if (helpResult.getExecutionDetails().isStdoutTruncated()) { |
| 94 | + return snapshot.status(Status.UNKNOWN).reason("HELP_TRUNCATED").build(); |
| 95 | + } |
| 96 | + String stdout = helpResult.getStdout(); |
| 97 | + OpenCliHelpResult help = OpenCliHelpParser.parse(stdout); |
| 98 | + snapshot.help(help).helpSha256(hex(sha256().digest(stdout.getBytes(StandardCharsets.UTF_8)))); |
| 99 | + if (help.getStatus() == OpenCliHelpResult.Status.AVAILABLE) { |
| 100 | + return snapshot.status(Status.AVAILABLE).build(); |
| 101 | + } |
| 102 | + return snapshot.status(Status.UNKNOWN).reason(help.getReason().name()).build(); |
| 103 | + } catch (OpenCliTimeoutException ex) { |
| 104 | + return snapshot.status(Status.UNKNOWN).reason(phase + "_TIMEOUT").build(); |
| 105 | + } catch (OpenCliException ex) { |
| 106 | + OpenCliResult partial = ex.getPartialResult(); |
| 107 | + if (Objects.nonNull(partial) && partial.getExecutionDetails().getTerminationReason() == TerminationReason.OUTPUT_LIMIT) { |
| 108 | + return snapshot.status(Status.UNKNOWN).reason(phase + "_TRUNCATED").build(); |
| 109 | + } |
| 110 | + return snapshot.status(Status.UNKNOWN).reason(phase + "_PROBE_FAILED").build(); |
| 111 | + } catch (IllegalArgumentException | IllegalStateException | UnsupportedOperationException ex) { |
| 112 | + return snapshot.status(Status.UNKNOWN).reason(phase + "_PROBE_FAILED").build(); |
| 113 | + } |
| 114 | + } |
| 115 | + } |
| 116 | + |
| 117 | + private static String configurationDigest(OpenCliProperties probe) { |
| 118 | + MessageDigest digest = sha256(); |
| 119 | + add(digest, probe.getExecutable()); |
| 120 | + String directory = probe.getWorkingDirectory(); |
| 121 | + add(digest, OpenCliStrings.isBlank(directory) ? System.getProperty("user.dir") : directory.trim()); |
| 122 | + add(digest, Integer.toString(probe.getLeadingArguments().size())); |
| 123 | + for (String argument : probe.getLeadingArguments()) { |
| 124 | + add(digest, argument); |
| 125 | + } |
| 126 | + Map<String, String> environment = new TreeMap<>(System.getenv()); |
| 127 | + probe.getEnvironment().forEach((key, value) -> { |
| 128 | + if (Objects.nonNull(key) && Objects.nonNull(value)) { |
| 129 | + environment.put(key, value); |
| 130 | + } |
| 131 | + }); |
| 132 | + environment.forEach((key, value) -> { |
| 133 | + add(digest, key); |
| 134 | + add(digest, value); |
| 135 | + }); |
| 136 | + return hex(digest.digest()); |
| 137 | + } |
| 138 | + |
| 139 | + private static void add(MessageDigest digest, String value) { |
| 140 | + if (Objects.isNull(value)) { |
| 141 | + digest.update(ByteBuffer.allocate(Integer.BYTES).putInt(-1).array()); |
| 142 | + return; |
| 143 | + } |
| 144 | + byte[] bytes = value.getBytes(StandardCharsets.UTF_8); |
| 145 | + digest.update(ByteBuffer.allocate(Integer.BYTES).putInt(bytes.length).array()); |
| 146 | + digest.update(bytes); |
| 147 | + } |
| 148 | + |
| 149 | + private static MessageDigest sha256() { |
| 150 | + try { |
| 151 | + return MessageDigest.getInstance("SHA-256"); |
| 152 | + } catch (NoSuchAlgorithmException ex) { |
| 153 | + throw new IllegalStateException("The Java runtime must provide SHA-256", ex); |
| 154 | + } |
| 155 | + } |
| 156 | + |
| 157 | + private static String hex(byte[] digest) { |
| 158 | + char[] digits = "0123456789abcdef".toCharArray(); |
| 159 | + char[] result = new char[digest.length * 2]; |
| 160 | + for (int index = 0; index < digest.length; index++) { |
| 161 | + int value = digest[index] & 0xff; |
| 162 | + result[index * 2] = digits[value >>> 4]; |
| 163 | + result[index * 2 + 1] = digits[value & 0xf]; |
| 164 | + } |
| 165 | + return new String(result); |
| 166 | + } |
| 167 | +} |
0 commit comments