mirror of
https://github.com/floci-io/floci.git
synced 2026-11-23 22:11:36 -05:00
feat(eks): run node group launch template user data in cluster containers (#4149)
This commit is contained in:
1 parent
76c103fd8c
commit
b7a66d4aaf
9 files changed
+1196
-427
No files matched your search
@@ -0,0 +1,559 @@
|
||||
package io.github.hectorvent.floci.core.common.docker;
|
||||
|
||||
import com.github.dockerjava.api.DockerClient;
|
||||
import com.github.dockerjava.api.async.ResultCallback;
|
||||
import com.github.dockerjava.api.model.Frame;
|
||||
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
|
||||
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.Closeable;
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Base64;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.Semaphore;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.zip.GZIPInputStream;
|
||||
|
||||
/**
|
||||
* Shared pipeline for parsing, decoding, decompressing, and executing EC2 and EKS user data
|
||||
* payloads in Docker containers.
|
||||
*/
|
||||
public final class UserDataPipeline {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(UserDataPipeline.class);
|
||||
|
||||
public static final String USER_DATA_SCRIPT_PATH = "/var/lib/user-data.sh";
|
||||
private static final Pattern MIME_BOUNDARY = Pattern.compile(
|
||||
"(?im)^content-type:\\s*multipart/[^;]+;\\s*boundary=\"?([^\";\\n\\r]+)\"?.*$");
|
||||
private static final Pattern BASE64_BODY = Pattern.compile("[A-Za-z0-9+/\\s]+={0,2}");
|
||||
public static final int MAX_USER_DATA_DECODE_ROUNDS = 3;
|
||||
public static final int MAX_DECOMPRESSED_USER_DATA_BYTES = 10 * 1024 * 1024;
|
||||
public static final int MAX_EXEC_OUTPUT_BYTES = 2048;
|
||||
public static final int MAX_CONCURRENT_USER_DATA_DECOMPRESSIONS = 4;
|
||||
public static final Duration DEFAULT_EXECUTION_TIMEOUT = Duration.ofMinutes(30);
|
||||
|
||||
private static final Semaphore USER_DATA_DECOMPRESSION_BUDGET =
|
||||
new Semaphore(MAX_CONCURRENT_USER_DATA_DECOMPRESSIONS);
|
||||
|
||||
public static volatile Runnable userDataDecompressionTestHook;
|
||||
|
||||
private UserDataPipeline() {
|
||||
}
|
||||
|
||||
public static List<String> extractShellScripts(String userData) {
|
||||
String decoded = decodeUserDataPayload(userData);
|
||||
if (decoded == null || decoded.isBlank()) {
|
||||
return List.of();
|
||||
}
|
||||
|
||||
String normalized = decoded.replace("\r\n", "\n").replace('\r', '\n');
|
||||
String trimmed = normalized.stripLeading();
|
||||
if (trimmed.startsWith("#!")) {
|
||||
return List.of(normalized);
|
||||
}
|
||||
|
||||
Matcher matcher = MIME_BOUNDARY.matcher(normalized);
|
||||
if (!matcher.find()) {
|
||||
return List.of();
|
||||
}
|
||||
|
||||
String boundary = matcher.group(1).trim();
|
||||
if (boundary.isEmpty()) {
|
||||
return List.of();
|
||||
}
|
||||
|
||||
List<String> scripts = new ArrayList<>();
|
||||
String marker = "--" + boundary;
|
||||
for (String segment : normalized.split(Pattern.quote(marker))) {
|
||||
String part = segment.stripLeading();
|
||||
if (part.isBlank() || part.startsWith("--")) {
|
||||
continue;
|
||||
}
|
||||
int headerEnd = part.indexOf("\n\n");
|
||||
if (headerEnd < 0) {
|
||||
continue;
|
||||
}
|
||||
String headers = part.substring(0, headerEnd);
|
||||
String body = part.substring(headerEnd + 2);
|
||||
if (hasShellscriptContentType(headers)) {
|
||||
scripts.add(body.stripTrailing() + "\n");
|
||||
}
|
||||
}
|
||||
return List.copyOf(scripts);
|
||||
}
|
||||
|
||||
public static String decodeUserDataPayload(String userData) {
|
||||
if (userData == null || userData.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
byte[] payload = userData.getBytes(StandardCharsets.UTF_8);
|
||||
// Bounded so a crafted payload cannot make this loop forever; two rounds already
|
||||
// covers base64(gzip(document)), the deepest form in practice.
|
||||
for (int round = 0; round < MAX_USER_DATA_DECODE_ROUNDS; round++) {
|
||||
byte[] next = gunzip(payload);
|
||||
if (next == null) {
|
||||
next = base64Decode(payload);
|
||||
}
|
||||
if (next == null) {
|
||||
break;
|
||||
}
|
||||
payload = next;
|
||||
}
|
||||
return new String(payload, StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
private static byte[] gunzip(byte[] payload) {
|
||||
if (payload.length < 2 || (payload[0] & 0xff) != 0x1f || (payload[1] & 0xff) != 0x8b) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
USER_DATA_DECOMPRESSION_BUDGET.acquire();
|
||||
} catch (InterruptedException ie) {
|
||||
Thread.currentThread().interrupt();
|
||||
LOG.warnv("Interrupted while waiting for UserData decompression budget; discarding payload");
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
Runnable hook = userDataDecompressionTestHook;
|
||||
if (hook != null) {
|
||||
hook.run();
|
||||
}
|
||||
|
||||
// Bounded the same way AwsJsonCborController.decodeBody is: a crafted payload can
|
||||
// otherwise expand to gigabytes of image-heap while the launch worker holds it, since
|
||||
// UserData is caller-controlled and this runs in the shared emulator JVM.
|
||||
byte[] buffer = new byte[64 * 1024];
|
||||
int totalRead = 0;
|
||||
ByteArrayOutputStream decompressed = new ByteArrayOutputStream();
|
||||
try (GZIPInputStream gzip = new GZIPInputStream(new ByteArrayInputStream(payload))) {
|
||||
int read;
|
||||
while ((read = gzip.read(buffer)) != -1) {
|
||||
totalRead += read;
|
||||
if (totalRead > MAX_DECOMPRESSED_USER_DATA_BYTES) {
|
||||
LOG.warnv("UserData decompressed past {0} bytes; discarding as oversized",
|
||||
MAX_DECOMPRESSED_USER_DATA_BYTES);
|
||||
return null;
|
||||
}
|
||||
decompressed.write(buffer, 0, read);
|
||||
}
|
||||
return decompressed.toByteArray();
|
||||
} catch (IOException e) {
|
||||
LOG.warnv("UserData starts with the gzip magic bytes but could not be decompressed: {0}", e.getMessage());
|
||||
return null;
|
||||
}
|
||||
} finally {
|
||||
USER_DATA_DECOMPRESSION_BUDGET.release();
|
||||
}
|
||||
}
|
||||
|
||||
private static byte[] base64Decode(byte[] payload) {
|
||||
String text = new String(payload, StandardCharsets.UTF_8).strip();
|
||||
if (text.isEmpty() || !BASE64_BODY.matcher(text).matches()) {
|
||||
return null;
|
||||
}
|
||||
byte[] decoded;
|
||||
try {
|
||||
decoded = Base64.getMimeDecoder().decode(text);
|
||||
} catch (IllegalArgumentException e) {
|
||||
return null;
|
||||
}
|
||||
if (decoded.length < 2) {
|
||||
return null;
|
||||
}
|
||||
if ((decoded[0] & 0xff) == 0x1f && (decoded[1] & 0xff) == 0x8b) {
|
||||
return decoded;
|
||||
}
|
||||
String head = new String(decoded, 0, Math.min(decoded.length, 512), StandardCharsets.UTF_8).stripLeading();
|
||||
return head.startsWith("#!") || head.toLowerCase(Locale.ROOT).startsWith("content-type:")
|
||||
|| head.toLowerCase(Locale.ROOT).startsWith("mime-version:") || head.startsWith("#cloud-config")
|
||||
? decoded
|
||||
: null;
|
||||
}
|
||||
|
||||
private static boolean hasShellscriptContentType(String headers) {
|
||||
for (String line : headers.split("\n")) {
|
||||
String lower = line.toLowerCase(Locale.ROOT).strip();
|
||||
if (lower.startsWith("content-type:") && lower.contains("text/x-shellscript")) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public static byte[] buildSingleFileTar(String filename, byte[] content, int mode) throws IOException {
|
||||
ByteArrayOutputStream bos = new ByteArrayOutputStream();
|
||||
try (TarArchiveOutputStream tar = new TarArchiveOutputStream(bos)) {
|
||||
tar.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU);
|
||||
TarArchiveEntry entry = new TarArchiveEntry(filename);
|
||||
entry.setSize(content.length);
|
||||
entry.setMode(mode);
|
||||
tar.putArchiveEntry(entry);
|
||||
tar.write(content);
|
||||
tar.closeArchiveEntry();
|
||||
}
|
||||
return bos.toByteArray();
|
||||
}
|
||||
|
||||
public static String summarizeUserDataOutput(BoundedOutput output) {
|
||||
if (output == null) {
|
||||
return "(no output)";
|
||||
}
|
||||
String text = output.utf8Tail().stripTrailing();
|
||||
if (text.isBlank()) {
|
||||
text = "(no output)";
|
||||
}
|
||||
if (output.truncated()) {
|
||||
return "(output truncated; showing last " + output.capacity() + " bytes)\n" + text;
|
||||
}
|
||||
return text;
|
||||
}
|
||||
|
||||
public static ExecutionResult executeUserData(
|
||||
DockerClient dockerClient,
|
||||
String containerId,
|
||||
String contextDescription,
|
||||
String userData,
|
||||
Duration timeout,
|
||||
Consumer<String> outputLineConsumer,
|
||||
Set<ResultCallback<Frame>> activeCallbacks
|
||||
) {
|
||||
if (dockerClient == null || containerId == null || containerId.isBlank()) {
|
||||
return ExecutionResult.skipped("No container available");
|
||||
}
|
||||
List<String> shellScripts = extractShellScripts(userData);
|
||||
if (shellScripts.isEmpty()) {
|
||||
return ExecutionResult.noScripts();
|
||||
}
|
||||
Duration effectiveTimeout = timeout != null ? timeout : DEFAULT_EXECUTION_TIMEOUT;
|
||||
|
||||
for (int i = 0; i < shellScripts.size(); i++) {
|
||||
int partNumber = i + 1;
|
||||
int partCount = shellScripts.size();
|
||||
String scriptContent = shellScripts.get(i);
|
||||
ExecutionResult partResult = executeSingleScript(
|
||||
dockerClient, containerId, contextDescription, scriptContent, partNumber, partCount,
|
||||
effectiveTimeout, outputLineConsumer, activeCallbacks);
|
||||
if (!partResult.isSuccess()) {
|
||||
return partResult;
|
||||
}
|
||||
}
|
||||
return ExecutionResult.success(0L, "UserData execution completed successfully");
|
||||
}
|
||||
|
||||
private static ExecutionResult executeSingleScript(
|
||||
DockerClient dockerClient,
|
||||
String containerId,
|
||||
String contextDescription,
|
||||
String scriptContent,
|
||||
int partNumber,
|
||||
int partCount,
|
||||
Duration timeout,
|
||||
Consumer<String> outputLineConsumer,
|
||||
Set<ResultCallback<Frame>> activeCallbacks
|
||||
) {
|
||||
byte[] script = scriptContent.getBytes(StandardCharsets.UTF_8);
|
||||
try {
|
||||
byte[] tar = buildSingleFileTar("user-data.sh", script, 0755);
|
||||
dockerClient.copyArchiveToContainerCmd(containerId)
|
||||
.withRemotePath("/var/lib")
|
||||
.withTarInputStream(new ByteArrayInputStream(tar))
|
||||
.exec();
|
||||
|
||||
String execId = dockerClient.execCreateCmd(containerId)
|
||||
.withCmd(USER_DATA_SCRIPT_PATH)
|
||||
.withAttachStdout(true)
|
||||
.withAttachStderr(true)
|
||||
.exec()
|
||||
.getId();
|
||||
|
||||
BoundedOutput output = new BoundedOutput(MAX_EXEC_OUTPUT_BYTES);
|
||||
CountDownLatch latch = new CountDownLatch(1);
|
||||
AtomicBoolean cancelled = new AtomicBoolean();
|
||||
|
||||
ResultCallback.Adapter<Frame> callback = new ResultCallback.Adapter<>() {
|
||||
@Override
|
||||
public void onStart(Closeable stream) {
|
||||
if (cancelled.get()) {
|
||||
closeSilently(stream);
|
||||
return;
|
||||
}
|
||||
super.onStart(stream);
|
||||
if (cancelled.get()) {
|
||||
closeSilently(stream);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onNext(Frame frame) {
|
||||
if (cancelled.get()) {
|
||||
return;
|
||||
}
|
||||
byte[] payload = frame.getPayload();
|
||||
if (payload == null) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
output.write(payload);
|
||||
} catch (IOException ignored) {
|
||||
}
|
||||
if (outputLineConsumer != null) {
|
||||
String line = new String(payload, StandardCharsets.UTF_8).stripTrailing();
|
||||
if (!line.isEmpty()) {
|
||||
outputLineConsumer.accept(line);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onComplete() {
|
||||
latch.countDown();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onError(Throwable t) {
|
||||
latch.countDown();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() throws IOException {
|
||||
cancelled.set(true);
|
||||
super.close();
|
||||
}
|
||||
};
|
||||
|
||||
if (activeCallbacks != null) {
|
||||
activeCallbacks.add(callback);
|
||||
}
|
||||
|
||||
try {
|
||||
dockerClient.execStartCmd(execId).exec(callback);
|
||||
|
||||
boolean completed = latch.await(timeout.toMillis(), TimeUnit.MILLISECONDS);
|
||||
if (!completed) {
|
||||
LOG.warnv("UserData shellscript part {0}/{1} timed out for {2}",
|
||||
partNumber, partCount, contextDescription);
|
||||
return ExecutionResult.timedOut(partNumber, partCount, timeout.toMinutes(),
|
||||
summarizeUserDataOutput(output));
|
||||
}
|
||||
|
||||
Long exitCode = dockerClient.inspectExecCmd(execId).exec().getExitCodeLong();
|
||||
if (exitCode != null && exitCode != 0) {
|
||||
LOG.warnv("UserData shellscript part {0}/{1} failed for {2} with exit code {3}: {4}",
|
||||
partNumber, partCount, contextDescription, exitCode, summarizeUserDataOutput(output));
|
||||
return ExecutionResult.failed(exitCode, partNumber, partCount,
|
||||
summarizeUserDataOutput(output));
|
||||
}
|
||||
|
||||
LOG.infov("UserData shellscript part {0}/{1} completed for {2}: {3}",
|
||||
partNumber, partCount, contextDescription, summarizeUserDataOutput(output));
|
||||
return ExecutionResult.success(exitCode, summarizeUserDataOutput(output));
|
||||
} finally {
|
||||
if (activeCallbacks != null) {
|
||||
activeCallbacks.remove(callback);
|
||||
}
|
||||
closeSilently(callback);
|
||||
}
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
LOG.warnv("UserData execution interrupted for {0}", contextDescription);
|
||||
return ExecutionResult.error("UserData execution interrupted for " + contextDescription);
|
||||
} catch (Exception e) {
|
||||
LOG.warnv("UserData execution failed for {0}: {1}", contextDescription, e.getMessage());
|
||||
return ExecutionResult.error("UserData execution failed for " + contextDescription + ": " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private static void closeSilently(Closeable closeable) {
|
||||
if (closeable != null) {
|
||||
try {
|
||||
closeable.close();
|
||||
} catch (IOException ignored) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static class BoundedOutput extends OutputStream {
|
||||
private final byte[] buffer;
|
||||
private int size;
|
||||
private long totalBytes;
|
||||
|
||||
public BoundedOutput(int capacity) {
|
||||
if (capacity <= 0) {
|
||||
throw new IllegalArgumentException("capacity must be positive");
|
||||
}
|
||||
this.buffer = new byte[capacity];
|
||||
}
|
||||
|
||||
@Override
|
||||
public void write(int value) {
|
||||
write(new byte[]{(byte) value}, 0, 1);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void write(byte[] source, int offset, int length) {
|
||||
Objects.checkFromIndexSize(offset, length, source.length);
|
||||
if (length == 0) {
|
||||
return;
|
||||
}
|
||||
totalBytes += length;
|
||||
if (length >= buffer.length) {
|
||||
System.arraycopy(source, offset + length - buffer.length, buffer, 0, buffer.length);
|
||||
size = buffer.length;
|
||||
return;
|
||||
}
|
||||
int overflow = Math.max(0, size + length - buffer.length);
|
||||
if (overflow > 0) {
|
||||
System.arraycopy(buffer, overflow, buffer, 0, size - overflow);
|
||||
size -= overflow;
|
||||
}
|
||||
System.arraycopy(source, offset, buffer, size, length);
|
||||
size += length;
|
||||
}
|
||||
|
||||
public byte[] toByteArray() {
|
||||
byte[] copy = new byte[size];
|
||||
System.arraycopy(buffer, 0, copy, 0, size);
|
||||
return copy;
|
||||
}
|
||||
|
||||
public String utf8Tail() {
|
||||
int start = 0;
|
||||
while (start < size) {
|
||||
int sequenceLength = utf8SequenceLength(buffer[start]);
|
||||
if (sequenceLength == 0) {
|
||||
start++;
|
||||
continue;
|
||||
}
|
||||
if (sequenceLength == 1) {
|
||||
break;
|
||||
}
|
||||
if (sequenceLength <= size - start && hasContinuationBytes(start, sequenceLength)) {
|
||||
break;
|
||||
}
|
||||
start++;
|
||||
}
|
||||
return new String(buffer, start, size - start, StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
private boolean hasContinuationBytes(int start, int sequenceLength) {
|
||||
for (int i = 1; i < sequenceLength; i++) {
|
||||
if ((buffer[start + i] & 0xC0) != 0x80) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private static int utf8SequenceLength(byte value) {
|
||||
int unsigned = value & 0xFF;
|
||||
if (unsigned < 0x80) {
|
||||
return 1;
|
||||
}
|
||||
if ((unsigned & 0xC0) == 0x80) {
|
||||
return 0;
|
||||
}
|
||||
if ((unsigned & 0xE0) == 0xC0) {
|
||||
return 2;
|
||||
}
|
||||
if ((unsigned & 0xF0) == 0xE0) {
|
||||
return 3;
|
||||
}
|
||||
if ((unsigned & 0xF8) == 0xF0) {
|
||||
return 4;
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
public boolean truncated() {
|
||||
return totalBytes > buffer.length;
|
||||
}
|
||||
|
||||
public int capacity() {
|
||||
return buffer.length;
|
||||
}
|
||||
|
||||
public long totalBytes() {
|
||||
return totalBytes;
|
||||
}
|
||||
}
|
||||
|
||||
public static final class ExecutionResult {
|
||||
private final boolean success;
|
||||
private final Long exitCode;
|
||||
private final boolean timedOut;
|
||||
private final String outputSummary;
|
||||
private final String failureMessage;
|
||||
|
||||
private ExecutionResult(boolean success, Long exitCode, boolean timedOut,
|
||||
String outputSummary, String failureMessage) {
|
||||
this.success = success;
|
||||
this.exitCode = exitCode;
|
||||
this.timedOut = timedOut;
|
||||
this.outputSummary = outputSummary;
|
||||
this.failureMessage = failureMessage;
|
||||
}
|
||||
|
||||
public static ExecutionResult success(Long exitCode, String outputSummary) {
|
||||
return new ExecutionResult(true, exitCode, false, outputSummary, null);
|
||||
}
|
||||
|
||||
public static ExecutionResult noScripts() {
|
||||
return new ExecutionResult(true, 0L, false, "(no scripts)", null);
|
||||
}
|
||||
|
||||
public static ExecutionResult skipped(String reason) {
|
||||
return new ExecutionResult(true, 0L, false, reason, null);
|
||||
}
|
||||
|
||||
public static ExecutionResult failed(Long exitCode, int partNumber, int partCount, String outputSummary) {
|
||||
String msg = "UserData shellscript part " + partNumber + "/" + partCount
|
||||
+ " failed with exit code " + exitCode + ": " + outputSummary;
|
||||
return new ExecutionResult(false, exitCode, false, outputSummary, msg);
|
||||
}
|
||||
|
||||
public static ExecutionResult timedOut(int partNumber, int partCount, long timeoutMinutes, String outputSummary) {
|
||||
String msg = "UserData shellscript part " + partNumber + "/" + partCount
|
||||
+ " timed out after " + timeoutMinutes + " minutes: " + outputSummary;
|
||||
return new ExecutionResult(false, null, true, outputSummary, msg);
|
||||
}
|
||||
|
||||
public static ExecutionResult error(String message) {
|
||||
return new ExecutionResult(false, null, false, message, message);
|
||||
}
|
||||
|
||||
public boolean isSuccess() {
|
||||
return success;
|
||||
}
|
||||
|
||||
public Long getExitCode() {
|
||||
return exitCode;
|
||||
}
|
||||
|
||||
public boolean isTimedOut() {
|
||||
return timedOut;
|
||||
}
|
||||
|
||||
public String getOutputSummary() {
|
||||
return outputSummary;
|
||||
}
|
||||
|
||||
public String getFailureMessage() {
|
||||
return failureMessage;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,7 @@ import io.github.hectorvent.floci.core.common.docker.ContainerSpec;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerStorageHelper;
|
||||
import io.github.hectorvent.floci.core.common.docker.DockerHostResolver;
|
||||
import io.github.hectorvent.floci.core.common.docker.PortAllocator;
|
||||
import io.github.hectorvent.floci.core.common.docker.UserDataPipeline;
|
||||
import io.github.hectorvent.floci.services.ec2.model.Instance;
|
||||
import io.github.hectorvent.floci.services.ec2.model.InstanceNetworkInterface;
|
||||
import io.github.hectorvent.floci.services.ec2.model.InstanceState;
|
||||
@@ -49,6 +50,7 @@ import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.function.Consumer;
|
||||
import io.github.hectorvent.floci.services.ec2.model.SecurityGroup;
|
||||
import java.util.concurrent.ArrayBlockingQueue;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
@@ -78,33 +80,10 @@ public class Ec2ContainerManager {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(Ec2ContainerManager.class);
|
||||
// Guest-created /tmp mounts hide files copied through Docker's archive API.
|
||||
private static final String USER_DATA_SCRIPT_PATH = "/var/lib/user-data.sh";
|
||||
private static final Pattern MIME_BOUNDARY = Pattern.compile("(?im)^content-type:\\s*multipart/[^;]+;\\s*boundary=\"?([^\";\\n\\r]+)\"?.*$");
|
||||
private static final String USER_DATA_SCRIPT_PATH = UserDataPipeline.USER_DATA_SCRIPT_PATH;
|
||||
private static final List<String> ALLOWED_SSHD_PATHS = List.of("/usr/sbin/sshd", "/usr/local/sbin/sshd", "/sbin/sshd");
|
||||
/** Exit code the sshd install probe uses for "sshd is present but scp is not". See startSshd. */
|
||||
static final int SSH_CLIENT_MISSING_EXIT_CODE = 2;
|
||||
/** Base64 alphabet plus the line breaks base64-encoded UserData is commonly wrapped at. */
|
||||
private static final Pattern BASE64_BODY = Pattern.compile("[A-Za-z0-9+/\\s]+={0,2}");
|
||||
private static final int MAX_USER_DATA_DECODE_ROUNDS = 3;
|
||||
/** Mirrors AwsJsonCborController.decodeBody's cap: no AWS service should need more than
|
||||
* 10 MB decompressed, and it bounds how much a caller-controlled gzip stream can expand
|
||||
* to in the shared emulator JVM. */
|
||||
private static final int MAX_DECOMPRESSED_USER_DATA_BYTES = 10 * 1024 * 1024;
|
||||
private static final int MAX_EXEC_OUTPUT_BYTES = 2048;
|
||||
/** Caps concurrent UserData gzip decompressions across ALL instance launches, not just one.
|
||||
* Launches run independently on {@link #executor}, so the
|
||||
* per-payload cap above only bounds a single launch's allocation: without this, N concurrent
|
||||
* RunInstances/CreateLaunchConfiguration calls, each smuggling a near-cap gzip payload, could
|
||||
* together decompress N * 10 MB at once in the shared emulator JVM with no aggregate ceiling.
|
||||
* 4 permits budgets ~40 MB of decompressed UserData in flight at a time - a few multiples of
|
||||
* the per-payload cap rather than 1, so an ordinary burst of legitimate concurrent launches
|
||||
* (e.g. an Auto Scaling group launching a handful of instances together) is not serialized
|
||||
* down to one decompression at a time, while a launch storm still cannot grow memory usage
|
||||
* without bound. */
|
||||
private static final int MAX_CONCURRENT_USER_DATA_DECOMPRESSIONS = 4;
|
||||
/** Gates entry to {@link #gunzip}; see {@link #MAX_CONCURRENT_USER_DATA_DECOMPRESSIONS}. */
|
||||
private static final Semaphore USER_DATA_DECOMPRESSION_BUDGET =
|
||||
new Semaphore(MAX_CONCURRENT_USER_DATA_DECOMPRESSIONS);
|
||||
private static final int LAUNCH_CORE_THREADS = 4;
|
||||
private static final int LAUNCH_MAX_THREADS = 8;
|
||||
private static final int LAUNCH_QUEUE_CAPACITY = 64;
|
||||
@@ -125,10 +104,6 @@ public class Ec2ContainerManager {
|
||||
throw new RejectedExecutionException("Interrupted while waiting for EC2 launch capacity", e);
|
||||
}
|
||||
};
|
||||
/** Test seam: when non-null, invoked by {@link #gunzip} right after it acquires a
|
||||
* decompression-budget permit and before it starts decompressing, so tests can observe and
|
||||
* serialize concurrent decompressions deterministically. Always null in production. */
|
||||
static volatile Runnable userDataDecompressionTestHook;
|
||||
|
||||
/**
|
||||
* Label identifying the Floci process that created an EC2 instance container, by its API
|
||||
@@ -1438,119 +1413,18 @@ public class Ec2ContainerManager {
|
||||
}
|
||||
|
||||
private void executeUserData(String containerId, String instanceId, String userData, String region) {
|
||||
try {
|
||||
String logGroup = "/aws/ec2/" + instanceId;
|
||||
String logStream = logStreamer.generateLogStreamName("user-data");
|
||||
String logGroup = "/aws/ec2/" + instanceId;
|
||||
String logStream = logStreamer != null ? logStreamer.generateLogStreamName("user-data") : null;
|
||||
|
||||
List<String> shellScripts = userDataShellScripts(userData);
|
||||
if (shellScripts.isEmpty()) {
|
||||
LOG.warnv("UserData for EC2 instance {0} did not contain executable shellscript parts, "
|
||||
+ "so nothing it was meant to install has run. Floci executes cloud-init "
|
||||
+ "text/x-shellscript parts and bare '#!' scripts only.", instanceId);
|
||||
return;
|
||||
}
|
||||
|
||||
// Execute the script and stream output to CloudWatch
|
||||
for (int i = 0; i < shellScripts.size(); i++) {
|
||||
executeUserDataShellScript(
|
||||
containerId, instanceId, shellScripts.get(i), i + 1, shellScripts.size(),
|
||||
logGroup, logStream, region
|
||||
);
|
||||
}
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
LOG.warnv("UserData execution interrupted for EC2 instance {0}", instanceId);
|
||||
} catch (Exception e) {
|
||||
LOG.warnv("UserData execution failed for EC2 instance {0}: {1}", instanceId, e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private void executeUserDataShellScript(
|
||||
String containerId, String instanceId, String scriptContent, int partNumber, int partCount,
|
||||
String logGroup, String logStream, String region
|
||||
) throws Exception {
|
||||
byte[] script = scriptContent.getBytes(StandardCharsets.UTF_8);
|
||||
byte[] tar = buildSingleFileTar("user-data.sh", script, 0755);
|
||||
dockerClient.copyArchiveToContainerCmd(containerId)
|
||||
.withRemotePath("/var/lib")
|
||||
.withTarInputStream(new ByteArrayInputStream(tar))
|
||||
.exec();
|
||||
|
||||
// Execute the script directly so Docker honors its shebang, matching cloud-init shellscript behavior.
|
||||
String execId = dockerClient.execCreateCmd(containerId)
|
||||
.withCmd(userDataExecutionCommand())
|
||||
.withAttachStdout(true)
|
||||
.withAttachStderr(true)
|
||||
.exec()
|
||||
.getId();
|
||||
|
||||
BoundedOutput output = new BoundedOutput(MAX_EXEC_OUTPUT_BYTES);
|
||||
CountDownLatch latch = new CountDownLatch(1);
|
||||
|
||||
AtomicBoolean cancelled = new AtomicBoolean();
|
||||
ResultCallback.Adapter<Frame> callback = new ResultCallback.Adapter<>() {
|
||||
@Override
|
||||
public void onStart(Closeable stream) {
|
||||
if (cancelled.get()) {
|
||||
closeUserDataStream(stream, instanceId);
|
||||
return;
|
||||
}
|
||||
super.onStart(stream);
|
||||
if (cancelled.get()) {
|
||||
closeUserDataStream(stream, instanceId);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onNext(Frame frame) {
|
||||
if (cancelled.get()) {
|
||||
return;
|
||||
}
|
||||
byte[] payload = frame.getPayload();
|
||||
if (payload == null) {
|
||||
return;
|
||||
}
|
||||
try { output.write(payload); } catch (IOException ignored) {}
|
||||
String line = new String(payload, StandardCharsets.UTF_8).stripTrailing();
|
||||
if (!line.isEmpty()) {
|
||||
logStreamer.streamToCloudWatchLogs(logGroup, logStream, region, line);
|
||||
}
|
||||
}
|
||||
@Override
|
||||
public void onComplete() { latch.countDown(); }
|
||||
@Override
|
||||
public void onError(Throwable t) { latch.countDown(); }
|
||||
@Override
|
||||
public void close() throws IOException {
|
||||
cancelled.set(true);
|
||||
super.close();
|
||||
Consumer<String> lineConsumer = line -> {
|
||||
if (logStreamer != null && logGroup != null && logStream != null && region != null) {
|
||||
logStreamer.streamToCloudWatchLogs(logGroup, logStream, region, line);
|
||||
}
|
||||
};
|
||||
activeUserDataCallbacks.add(callback);
|
||||
|
||||
try {
|
||||
dockerClient.execStartCmd(execId).exec(callback);
|
||||
|
||||
boolean completed = latch.await(userDataExecutionTimeout.toMillis(), TimeUnit.MILLISECONDS);
|
||||
if (!completed) {
|
||||
LOG.warnv("UserData shellscript part {0}/{1} timed out for EC2 instance {2}",
|
||||
partNumber, partCount, instanceId);
|
||||
return;
|
||||
}
|
||||
|
||||
Long exitCode = dockerClient.inspectExecCmd(execId).exec().getExitCodeLong();
|
||||
if (exitCode != null && exitCode != 0) {
|
||||
LOG.warnv("UserData shellscript part {0}/{1} failed for EC2 instance {2} with exit code {3}: {4}",
|
||||
partNumber, partCount, instanceId, exitCode, summarizeUserDataOutput(output));
|
||||
return;
|
||||
}
|
||||
|
||||
LOG.infov("UserData shellscript part {0}/{1} completed for EC2 instance {2}: {3}",
|
||||
partNumber, partCount, instanceId, summarizeUserDataOutput(output));
|
||||
} finally {
|
||||
activeUserDataCallbacks.remove(callback);
|
||||
closeUserDataCallback(callback, instanceId);
|
||||
}
|
||||
UserDataPipeline.executeUserData(
|
||||
dockerClient, containerId, "EC2 instance " + instanceId, userData,
|
||||
userDataExecutionTimeout, lineConsumer, activeUserDataCallbacks);
|
||||
}
|
||||
|
||||
private void closeActiveUserDataCallbacks() {
|
||||
@@ -1565,179 +1439,12 @@ public class Ec2ContainerManager {
|
||||
}
|
||||
}
|
||||
|
||||
private void closeUserDataStream(Closeable stream, String instanceId) {
|
||||
try {
|
||||
stream.close();
|
||||
} catch (IOException e) {
|
||||
LOG.warnv("Could not close Docker UserData stream for EC2 instance {0}: {1}",
|
||||
instanceId, e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
static List<String> userDataShellScripts(String userData) {
|
||||
String decoded = decodeUserDataPayload(userData);
|
||||
if (decoded == null || decoded.isBlank()) {
|
||||
return List.of();
|
||||
}
|
||||
|
||||
String normalized = decoded.replace("\r\n", "\n").replace('\r', '\n');
|
||||
String trimmed = normalized.stripLeading();
|
||||
if (trimmed.startsWith("#!")) {
|
||||
return List.of(normalized);
|
||||
}
|
||||
|
||||
Matcher matcher = MIME_BOUNDARY.matcher(normalized);
|
||||
if (!matcher.find()) {
|
||||
return List.of();
|
||||
}
|
||||
|
||||
String boundary = matcher.group(1).trim();
|
||||
if (boundary.isEmpty()) {
|
||||
return List.of();
|
||||
}
|
||||
|
||||
List<String> scripts = new ArrayList<>();
|
||||
String marker = "--" + boundary;
|
||||
for (String segment : normalized.split(Pattern.quote(marker))) {
|
||||
String part = segment.stripLeading();
|
||||
if (part.isBlank() || part.startsWith("--")) {
|
||||
continue;
|
||||
}
|
||||
int headerEnd = part.indexOf("\n\n");
|
||||
if (headerEnd < 0) {
|
||||
continue;
|
||||
}
|
||||
String headers = part.substring(0, headerEnd);
|
||||
String body = part.substring(headerEnd + 2);
|
||||
if (hasShellscriptContentType(headers)) {
|
||||
scripts.add(body.stripTrailing() + "\n");
|
||||
}
|
||||
}
|
||||
return List.copyOf(scripts);
|
||||
return UserDataPipeline.extractShellScripts(userData);
|
||||
}
|
||||
|
||||
/**
|
||||
* Unwraps whatever encoding the UserData arrived in until a cloud-init document is
|
||||
* visible: gzip, base64, and base64-of-gzip, in any nesting the callers produce.
|
||||
*
|
||||
* <p>RunInstances decodes the wire-level base64 (and its gzip) before Floci ever stores
|
||||
* the value, but not every path does — CreateLaunchConfiguration stores what the client
|
||||
* sent, still base64 — and {@code data.cloudinit_config { gzip = true }}, the documented
|
||||
* way to pass a multipart cloud-init, produces a payload that survives one decode still
|
||||
* compressed. Left unwrapped it matches neither the {@code #!} nor the MIME test below and
|
||||
* the whole document is silently dropped, so the instance boots without anything its
|
||||
* user-data was supposed to install.
|
||||
*
|
||||
* @return the decoded document, or the input unchanged when it is not encoded
|
||||
*/
|
||||
static String decodeUserDataPayload(String userData) {
|
||||
if (userData == null || userData.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
byte[] payload = userData.getBytes(StandardCharsets.UTF_8);
|
||||
// Bounded so a crafted payload cannot make this loop forever; two rounds already
|
||||
// covers base64(gzip(document)), the deepest form in practice.
|
||||
for (int round = 0; round < MAX_USER_DATA_DECODE_ROUNDS; round++) {
|
||||
byte[] next = gunzip(payload);
|
||||
if (next == null) {
|
||||
next = base64Decode(payload);
|
||||
}
|
||||
if (next == null) {
|
||||
break;
|
||||
}
|
||||
payload = next;
|
||||
}
|
||||
return new String(payload, StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
/** @return the decompressed bytes, or null when the input does not start with the gzip magic */
|
||||
private static byte[] gunzip(byte[] payload) {
|
||||
if (payload.length < 2 || (payload[0] & 0xff) != 0x1f || (payload[1] & 0xff) != 0x8b) {
|
||||
return null;
|
||||
}
|
||||
// Aggregate bound (see MAX_CONCURRENT_USER_DATA_DECOMPRESSIONS): this call runs on
|
||||
// whichever launch worker submitted it to the unbounded #executor, independently of every
|
||||
// other concurrent launch, so the per-payload cap below is not enough on its own - it only
|
||||
// stops one caller from expanding past 10 MB, not many callers doing so at once. Blocking
|
||||
// here (rather than failing the launch) mirrors ContainerLauncher's POPULATE_SEMAPHORE: a
|
||||
// burst of legitimate concurrent launches queues briefly instead of being rejected.
|
||||
try {
|
||||
USER_DATA_DECOMPRESSION_BUDGET.acquire();
|
||||
} catch (InterruptedException ie) {
|
||||
Thread.currentThread().interrupt();
|
||||
LOG.warnv("Interrupted while waiting for UserData decompression budget; discarding payload");
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
Runnable hook = userDataDecompressionTestHook;
|
||||
if (hook != null) {
|
||||
hook.run();
|
||||
}
|
||||
// Bounded the same way AwsJsonCborController.decodeBody is: a crafted payload can
|
||||
// otherwise expand to gigabytes of image-heap while the launch worker holds it, since
|
||||
// UserData is caller-controlled and this runs in the shared emulator JVM.
|
||||
byte[] buffer = new byte[64 * 1024];
|
||||
int totalRead = 0;
|
||||
ByteArrayOutputStream decompressed = new ByteArrayOutputStream();
|
||||
try (GZIPInputStream gzip = new GZIPInputStream(new ByteArrayInputStream(payload))) {
|
||||
int read;
|
||||
while ((read = gzip.read(buffer)) != -1) {
|
||||
totalRead += read;
|
||||
if (totalRead > MAX_DECOMPRESSED_USER_DATA_BYTES) {
|
||||
LOG.warnv("UserData decompressed past {0} bytes; discarding as oversized",
|
||||
MAX_DECOMPRESSED_USER_DATA_BYTES);
|
||||
return null;
|
||||
}
|
||||
decompressed.write(buffer, 0, read);
|
||||
}
|
||||
return decompressed.toByteArray();
|
||||
} catch (IOException e) {
|
||||
LOG.warnv("UserData starts with the gzip magic bytes but could not be decompressed: {0}", e.getMessage());
|
||||
return null;
|
||||
}
|
||||
} finally {
|
||||
USER_DATA_DECOMPRESSION_BUDGET.release();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return the decoded bytes when the input is base64 that unwraps to something recognisable
|
||||
* (gzip, a shebang, or MIME headers), null otherwise. The recognisability test is
|
||||
* what keeps a plain shell script — which can be accidentally valid base64 — from
|
||||
* being mangled into binary noise.
|
||||
*/
|
||||
private static byte[] base64Decode(byte[] payload) {
|
||||
String text = new String(payload, StandardCharsets.UTF_8).strip();
|
||||
if (text.isEmpty() || !BASE64_BODY.matcher(text).matches()) {
|
||||
return null;
|
||||
}
|
||||
byte[] decoded;
|
||||
try {
|
||||
decoded = Base64.getMimeDecoder().decode(text);
|
||||
} catch (IllegalArgumentException e) {
|
||||
return null;
|
||||
}
|
||||
if (decoded.length < 2) {
|
||||
return null;
|
||||
}
|
||||
if ((decoded[0] & 0xff) == 0x1f && (decoded[1] & 0xff) == 0x8b) {
|
||||
return decoded;
|
||||
}
|
||||
String head = new String(decoded, 0, Math.min(decoded.length, 512), StandardCharsets.UTF_8).stripLeading();
|
||||
return head.startsWith("#!") || head.toLowerCase(Locale.ROOT).startsWith("content-type:")
|
||||
|| head.toLowerCase(Locale.ROOT).startsWith("mime-version:") || head.startsWith("#cloud-config")
|
||||
? decoded
|
||||
: null;
|
||||
}
|
||||
|
||||
private static boolean hasShellscriptContentType(String headers) {
|
||||
for (String line : headers.split("\n")) {
|
||||
String lower = line.toLowerCase(Locale.ROOT).strip();
|
||||
if (lower.startsWith("content-type:") && lower.contains("text/x-shellscript")) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
return UserDataPipeline.decodeUserDataPayload(userData);
|
||||
}
|
||||
|
||||
static String[] userDataExecutionCommand() {
|
||||
@@ -1817,109 +1524,13 @@ public class Ec2ContainerManager {
|
||||
return environment;
|
||||
}
|
||||
|
||||
static String summarizeUserDataOutput(BoundedOutput output) {
|
||||
String text = output.utf8Tail().stripTrailing();
|
||||
if (text.isBlank()) {
|
||||
text = "(no output)";
|
||||
}
|
||||
if (output.truncated()) {
|
||||
return "(output truncated; showing last " + output.capacity() + " bytes)\n" + text;
|
||||
}
|
||||
return text;
|
||||
static String summarizeUserDataOutput(UserDataPipeline.BoundedOutput output) {
|
||||
return UserDataPipeline.summarizeUserDataOutput(output);
|
||||
}
|
||||
|
||||
static final class BoundedOutput extends OutputStream {
|
||||
private final byte[] buffer;
|
||||
private int size;
|
||||
private long totalBytes;
|
||||
|
||||
static class BoundedOutput extends UserDataPipeline.BoundedOutput {
|
||||
BoundedOutput(int capacity) {
|
||||
if (capacity <= 0) {
|
||||
throw new IllegalArgumentException("capacity must be positive");
|
||||
}
|
||||
buffer = new byte[capacity];
|
||||
}
|
||||
|
||||
@Override
|
||||
public void write(int value) {
|
||||
write(new byte[]{(byte) value}, 0, 1);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void write(byte[] source, int offset, int length) {
|
||||
Objects.checkFromIndexSize(offset, length, source.length);
|
||||
if (length == 0) {
|
||||
return;
|
||||
}
|
||||
totalBytes += length;
|
||||
if (length >= buffer.length) {
|
||||
System.arraycopy(source, offset + length - buffer.length, buffer, 0, buffer.length);
|
||||
size = buffer.length;
|
||||
return;
|
||||
}
|
||||
int overflow = Math.max(0, size + length - buffer.length);
|
||||
if (overflow > 0) {
|
||||
System.arraycopy(buffer, overflow, buffer, 0, size - overflow);
|
||||
size -= overflow;
|
||||
}
|
||||
System.arraycopy(source, offset, buffer, size, length);
|
||||
size += length;
|
||||
}
|
||||
|
||||
String utf8Tail() {
|
||||
int start = 0;
|
||||
while (start < size) {
|
||||
int sequenceLength = utf8SequenceLength(buffer[start]);
|
||||
if (sequenceLength == 0) {
|
||||
start++;
|
||||
continue;
|
||||
}
|
||||
if (sequenceLength == 1) {
|
||||
break;
|
||||
}
|
||||
if (sequenceLength <= size - start && hasContinuationBytes(start, sequenceLength)) {
|
||||
break;
|
||||
}
|
||||
start++;
|
||||
}
|
||||
return new String(buffer, start, size - start, StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
boolean truncated() {
|
||||
return totalBytes > buffer.length;
|
||||
}
|
||||
|
||||
int capacity() {
|
||||
return buffer.length;
|
||||
}
|
||||
|
||||
private boolean hasContinuationBytes(int start, int sequenceLength) {
|
||||
for (int i = 1; i < sequenceLength; i++) {
|
||||
if ((buffer[start + i] & 0xC0) != 0x80) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private static int utf8SequenceLength(byte value) {
|
||||
int unsigned = value & 0xFF;
|
||||
if (unsigned < 0x80) {
|
||||
return 1;
|
||||
}
|
||||
if ((unsigned & 0xC0) == 0x80) {
|
||||
return 0;
|
||||
}
|
||||
if ((unsigned & 0xE0) == 0xC0) {
|
||||
return 2;
|
||||
}
|
||||
if ((unsigned & 0xF0) == 0xE0) {
|
||||
return 3;
|
||||
}
|
||||
if ((unsigned & 0xF8) == 0xF0) {
|
||||
return 4;
|
||||
}
|
||||
return 1;
|
||||
super(capacity);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1958,7 +1569,7 @@ public class Ec2ContainerManager {
|
||||
.getId();
|
||||
|
||||
CountDownLatch latch = new CountDownLatch(1);
|
||||
BoundedOutput output = new BoundedOutput(MAX_EXEC_OUTPUT_BYTES);
|
||||
BoundedOutput output = new BoundedOutput(UserDataPipeline.MAX_EXEC_OUTPUT_BYTES);
|
||||
dockerClient.execStartCmd(execId).exec(new ResultCallback.Adapter<Frame>() {
|
||||
@Override
|
||||
public void onNext(Frame frame) {
|
||||
@@ -2032,16 +1643,6 @@ public class Ec2ContainerManager {
|
||||
}
|
||||
|
||||
private byte[] buildSingleFileTar(String filename, byte[] content, int mode) throws IOException {
|
||||
ByteArrayOutputStream bos = new ByteArrayOutputStream();
|
||||
try (TarArchiveOutputStream tar = new TarArchiveOutputStream(bos)) {
|
||||
tar.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU);
|
||||
TarArchiveEntry entry = new TarArchiveEntry(filename);
|
||||
entry.setSize(content.length);
|
||||
entry.setMode(mode);
|
||||
tar.putArchiveEntry(entry);
|
||||
tar.write(content);
|
||||
tar.closeArchiveEntry();
|
||||
}
|
||||
return bos.toByteArray();
|
||||
return UserDataPipeline.buildSingleFileTar(filename, content, mode);
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,7 @@ import io.github.hectorvent.floci.core.common.docker.ContainerSpec;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerStorageHelper;
|
||||
import io.github.hectorvent.floci.core.common.docker.DockerHostResolver;
|
||||
import io.github.hectorvent.floci.core.common.docker.PortAllocator;
|
||||
import io.github.hectorvent.floci.core.common.docker.UserDataPipeline;
|
||||
import io.github.hectorvent.floci.services.ecr.registry.EcrRegistryManager;
|
||||
import io.github.hectorvent.floci.services.eks.model.CertificateAuthority;
|
||||
import io.github.hectorvent.floci.services.eks.model.Cluster;
|
||||
@@ -51,6 +52,7 @@ import java.nio.file.Paths;
|
||||
import java.nio.file.attribute.PosixFileAttributeView;
|
||||
import java.nio.file.attribute.PosixFilePermission;
|
||||
import java.nio.file.attribute.PosixFilePermissions;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Base64;
|
||||
@@ -1794,6 +1796,38 @@ public class EksClusterManager {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Executes launch template UserData script(s) inside the running cluster container.
|
||||
*
|
||||
* @param cluster the cluster whose container will execute the user data
|
||||
* @param nodegroupName the name of the nodegroup requesting execution
|
||||
* @param userData raw UserData payload from the launch template
|
||||
* @return result indicating success, failure, or skipped
|
||||
*/
|
||||
public UserDataPipeline.ExecutionResult executeUserData(
|
||||
Cluster cluster,
|
||||
String nodegroupName,
|
||||
String userData) {
|
||||
if (cluster == null || cluster.getContainerId() == null || cluster.getContainerId().isBlank()) {
|
||||
return UserDataPipeline.ExecutionResult.skipped("Cluster has no running container");
|
||||
}
|
||||
DockerClient dockerClient = lifecycleManager.getDockerClient();
|
||||
if (dockerClient == null) {
|
||||
return UserDataPipeline.ExecutionResult.skipped("No Docker daemon reachable");
|
||||
}
|
||||
String context = "EKS cluster " + cluster.getName() + " (nodegroup " + nodegroupName + ")";
|
||||
return UserDataPipeline.executeUserData(
|
||||
dockerClient,
|
||||
cluster.getContainerId(),
|
||||
context,
|
||||
userData,
|
||||
Duration.ofMinutes(30),
|
||||
null,
|
||||
null
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
private String execInContainer(String containerId, String[] cmd) throws Exception {
|
||||
ContainerExecResult result = execInContainerForResult(containerId, cmd, 10);
|
||||
if (result.exitCode() == -1 && result.output().startsWith("Timed out")) {
|
||||
|
||||
@@ -6,6 +6,7 @@ import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.common.RequestScopes;
|
||||
import io.github.hectorvent.floci.core.common.TagHandler;
|
||||
import io.github.hectorvent.floci.core.common.docker.UserDataPipeline;
|
||||
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
@@ -13,6 +14,7 @@ import io.github.hectorvent.floci.services.ec2.Ec2Service;
|
||||
import io.github.hectorvent.floci.services.ec2.Ipv4Cidrs;
|
||||
import io.github.hectorvent.floci.services.ec2.SecurityGroupPolicy;
|
||||
import io.github.hectorvent.floci.services.ec2.model.IpPermission;
|
||||
import io.github.hectorvent.floci.services.ec2.model.LaunchTemplateData;
|
||||
import io.github.hectorvent.floci.services.ec2.model.SecurityGroup;
|
||||
import io.github.hectorvent.floci.services.ec2.model.Tag;
|
||||
import io.github.hectorvent.floci.services.ec2.model.UserIdGroupPair;
|
||||
@@ -56,6 +58,7 @@ import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
@@ -95,6 +98,7 @@ public class EksService implements TagHandler, ResourceProvider {
|
||||
private final EksPodIdentityAssociationService podIdentityAssociations;
|
||||
private final EksAddonService addons;
|
||||
private final ScheduledExecutorService poller = Executors.newSingleThreadScheduledExecutor();
|
||||
private final Map<String, String> appliedClusterUserData = new ConcurrentHashMap<>();
|
||||
|
||||
@Inject
|
||||
public EksService(StorageFactory storageFactory, EmulatorConfig config,
|
||||
@@ -259,6 +263,15 @@ public class EksService implements TagHandler, ResourceProvider {
|
||||
}
|
||||
|
||||
void deleteClusterForAccount(String accountId, String clusterName) {
|
||||
Cluster cluster = (storage instanceof AccountAwareStorageBackend<Cluster> aware)
|
||||
? aware.getForAccount(accountId, clusterName).orElse(null)
|
||||
: storage.get(clusterName).orElse(null);
|
||||
clearAppliedClusterUserData(cluster, clusterName);
|
||||
if (cluster == null || cluster.getArn() == null) {
|
||||
String fallbackArn = AwsArnUtils.Arn.of("eks", config.defaultRegion(), accountId,
|
||||
"cluster/" + clusterName).toString();
|
||||
appliedClusterUserData.remove(fallbackArn);
|
||||
}
|
||||
if (storage instanceof AccountAwareStorageBackend<Cluster> aware) {
|
||||
aware.deleteForAccount(accountId, clusterName);
|
||||
return;
|
||||
@@ -266,6 +279,20 @@ public class EksService implements TagHandler, ResourceProvider {
|
||||
storage.delete(clusterName);
|
||||
}
|
||||
|
||||
private void clearAppliedClusterUserData(Cluster cluster, String fallbackName) {
|
||||
if (cluster != null) {
|
||||
if (cluster.getArn() != null) {
|
||||
appliedClusterUserData.remove(cluster.getArn());
|
||||
}
|
||||
if (cluster.getName() != null) {
|
||||
appliedClusterUserData.remove(cluster.getName());
|
||||
}
|
||||
}
|
||||
if (fallbackName != null) {
|
||||
appliedClusterUserData.remove(fallbackName);
|
||||
}
|
||||
}
|
||||
|
||||
private SecurityGroup createClusterSecurityGroup(String region, String clusterName, String vpcId) {
|
||||
String suffix = randomHex(8);
|
||||
String groupName = "eks-cluster-sg-" + clusterName + "-" + suffix;
|
||||
@@ -579,6 +606,7 @@ public class EksService implements TagHandler, ResourceProvider {
|
||||
addons.deleteClusterAddons(cluster);
|
||||
}
|
||||
storage.delete(name);
|
||||
clearAppliedClusterUserData(cluster, name);
|
||||
oidcService.deleteKey(name);
|
||||
return cluster;
|
||||
}
|
||||
@@ -628,7 +656,7 @@ public class EksService implements TagHandler, ResourceProvider {
|
||||
}
|
||||
|
||||
String region = resolveClusterRegion(cluster);
|
||||
validateLaunchTemplate(region, request.getLaunchTemplate());
|
||||
LaunchTemplateData launchTemplateData = validateLaunchTemplate(region, request.getLaunchTemplate());
|
||||
|
||||
String accountId = regionResolver.getAccountId();
|
||||
String id = UUID.randomUUID().toString();
|
||||
@@ -668,13 +696,18 @@ public class EksService implements TagHandler, ResourceProvider {
|
||||
nodeGroup.setLabels(request.getLabels() != null ? new HashMap<>(request.getLabels()) : null);
|
||||
nodeGroup.setTags(request.getTags() != null ? new HashMap<>(request.getTags()) : new HashMap<>());
|
||||
|
||||
if (launchTemplateData != null && launchTemplateData.getUserData() != null
|
||||
&& !launchTemplateData.getUserData().isBlank()) {
|
||||
applyNodeGroupUserData(cluster, nodegroupName, launchTemplateData.getUserData(), nodeGroup);
|
||||
}
|
||||
|
||||
nodeGroupStorage.put(storageKey, nodeGroup);
|
||||
return nodeGroup;
|
||||
}
|
||||
|
||||
private void validateLaunchTemplate(String region, Object launchTemplateObj) {
|
||||
private LaunchTemplateData validateLaunchTemplate(String region, Object launchTemplateObj) {
|
||||
if (!(launchTemplateObj instanceof Map<?, ?> map)) {
|
||||
return;
|
||||
return null;
|
||||
}
|
||||
|
||||
String id = asNonBlankString(map.get("id"));
|
||||
@@ -688,7 +721,7 @@ public class EksService implements TagHandler, ResourceProvider {
|
||||
}
|
||||
|
||||
try {
|
||||
ec2Service.resolveLaunchTemplateData(region, id, name, version);
|
||||
return ec2Service.resolveLaunchTemplateData(region, id, name, version);
|
||||
} catch (AwsException e) {
|
||||
switch (e.getErrorCode()) {
|
||||
case "InvalidLaunchTemplateId.NotFound", "InvalidLaunchTemplateName.NotFoundException" ->
|
||||
@@ -1093,6 +1126,49 @@ public class EksService implements TagHandler, ResourceProvider {
|
||||
return health;
|
||||
}
|
||||
|
||||
private Map<String, List<Object>> failedNodeGroupHealth(String nodegroupName, String message) {
|
||||
Map<String, List<Object>> health = new LinkedHashMap<>();
|
||||
Map<String, Object> issue = new LinkedHashMap<>();
|
||||
issue.put("code", "NodeCreationFailure");
|
||||
issue.put("message", message);
|
||||
issue.put("resourceIds", List.of(nodegroupName));
|
||||
health.put("issues", List.of(issue));
|
||||
return health;
|
||||
}
|
||||
|
||||
private void applyNodeGroupUserData(Cluster cluster, String nodegroupName, String userData, Nodegroup nodeGroup) {
|
||||
String clusterKey = cluster.getArn() != null ? cluster.getArn() : cluster.getName();
|
||||
String previouslyApplied = appliedClusterUserData.get(clusterKey);
|
||||
if (previouslyApplied != null) {
|
||||
if (previouslyApplied.equals(userData)) {
|
||||
LOG.infov("Nodegroup {0} specifies identical launch template user data already applied to cluster {1}; skipping",
|
||||
nodegroupName, cluster.getName());
|
||||
} else {
|
||||
LOG.warnv("Nodegroup {0} specifies launch template user data that differs from previously applied user data for cluster {1}; skipping execution because Floci runs a single shared container per cluster",
|
||||
nodegroupName, cluster.getName());
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (clusterManager == null) {
|
||||
appliedClusterUserData.put(clusterKey, userData);
|
||||
return;
|
||||
}
|
||||
|
||||
UserDataPipeline.ExecutionResult result = clusterManager.executeUserData(cluster, nodegroupName, userData);
|
||||
if (result != null && !result.isSuccess()) {
|
||||
nodeGroup.setStatus(NodegroupStatus.CREATE_FAILED);
|
||||
String failureDetail = result.getFailureMessage() != null
|
||||
? result.getFailureMessage()
|
||||
: "UserData execution failed for EKS cluster " + cluster.getName();
|
||||
nodeGroup.setHealth(failedNodeGroupHealth(nodegroupName, failureDetail));
|
||||
LOG.warnv("Nodegroup {0} failed to execute launch template user data: {1}",
|
||||
nodegroupName, failureDetail);
|
||||
} else {
|
||||
appliedClusterUserData.put(clusterKey, userData);
|
||||
}
|
||||
}
|
||||
|
||||
private FargateProfile.Health defaultFargateProfileHealth() {
|
||||
FargateProfile.Health health = new FargateProfile.Health();
|
||||
health.setIssues(List.of());
|
||||
|
||||
Reference in new issue
Block a user