mirror of
https://github.com/floci-io/floci.git
synced 2026-11-23 22:11:36 -05:00
feat(eks): expose IMDS on 169.254.169.254 inside cluster containers (#3693)
* feat(eks): expose IMDS on 169.254.169.254 inside cluster containers When applications or agents run on Kubernetes nodes or use hostNetwork: true, they expect the AWS Instance Metadata Service (IMDS) at the standard link-local address 169.254.169.254:80. In Floci, EKS k3s cluster containers lacked access to IMDS at this link-local address, preventing workloads from discovering instance identities, node IAM roles, or dynamic cluster credentials without custom endpoint overrides. This change exposes IMDS on 169.254.169.254:80 inside EKS cluster containers when floci.services.eks.imds is enabled. It configures a background TCP relay via socat pointing to the host's EC2 metadata port, registers a synthesized EC2 node instance with the cluster's IAM role and container IP in Ec2MetadataServer, extracts reusable metadata proxy logic into Ec2MetadataProxy, and documents node network namespace reachability and hop limit handling. * fix(eks): address review feedback on lifecycle check, default flag, and instance seed * fix(eks): synthesize distinct node instance profile and import CompletableFuture * test(eks): enable IMDS profile and provide curl in docker test fixture
This commit is contained in:
1 parent
f48bc2aa40
commit
a2fddaf08d
13 files changed
+838
-72
No files matched your search
@@ -2727,6 +2727,13 @@ public interface EmulatorConfig {
|
||||
*/
|
||||
@WithDefault("false")
|
||||
boolean disableCni();
|
||||
|
||||
/**
|
||||
* When true, exposes an IMDS link-local proxy (169.254.169.254:80) inside the cluster container's
|
||||
* network namespace that relays to Floci's EC2 metadata service.
|
||||
*/
|
||||
@WithDefault("false")
|
||||
boolean imds();
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -215,7 +215,7 @@ public class EmulatorLifecycle {
|
||||
elbClassicService.restorePersistedRuntime();
|
||||
}
|
||||
|
||||
if (config.services().ec2().enabled() && !config.services().ec2().mock()) {
|
||||
if (isMetadataServerNeeded()) {
|
||||
ec2MetadataServer.start().exceptionally(ex -> {
|
||||
LOG.warnv("EC2 IMDS server failed to start: {0}", ex.getMessage());
|
||||
return null;
|
||||
@@ -304,7 +304,7 @@ public class EmulatorLifecycle {
|
||||
// still runs at the end to stop the flush schedulers and capture any shutdown-time writes.
|
||||
runCleanup("storage flush", storageFactory::flushAll);
|
||||
runCleanup("EC2 metadata server", () -> {
|
||||
if (config.services().ec2().enabled() && !config.services().ec2().mock()) {
|
||||
if (isMetadataServerNeeded()) {
|
||||
ec2MetadataServer.stop();
|
||||
}
|
||||
});
|
||||
@@ -345,4 +345,16 @@ public class EmulatorLifecycle {
|
||||
LOG.warnv(e, "Shutdown cleanup failed for {0}; continuing with the remaining steps", resource);
|
||||
}
|
||||
}
|
||||
|
||||
private boolean isMetadataServerNeeded() {
|
||||
if (config == null || config.services() == null) {
|
||||
return false;
|
||||
}
|
||||
EmulatorConfig.Ec2ServiceConfig ec2 = config.services().ec2();
|
||||
if (ec2 != null && ec2.enabled() && !ec2.mock()) {
|
||||
return true;
|
||||
}
|
||||
EmulatorConfig.EksServiceConfig eks = config.services().eks();
|
||||
return eks != null && eks.enabled() && !eks.mock() && eks.imds();
|
||||
}
|
||||
}
|
||||
@@ -1788,50 +1788,14 @@ public class Ec2ContainerManager {
|
||||
}
|
||||
|
||||
static String[] metadataProxyInstallCommand() {
|
||||
return new String[]{"sh", "-c", String.join("\n",
|
||||
"set -eu",
|
||||
"if command -v ip >/dev/null 2>&1 && command -v socat >/dev/null 2>&1 && command -v curl >/dev/null 2>&1; then exit 0; fi",
|
||||
"if command -v apt-get >/dev/null 2>&1; then",
|
||||
" apt-get update -qq >/dev/null",
|
||||
" DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends iproute2 socat curl ca-certificates >/dev/null",
|
||||
"elif command -v dnf >/dev/null 2>&1; then",
|
||||
// --allowerasing lets dnf swap the curl-minimal that
|
||||
// public.ecr.aws/amazonlinux/amazonlinux:2023 ships by default for the full
|
||||
// curl package this proxy needs. Without it, dnf aborts the whole transaction
|
||||
// on a curl/curl-minimal conflict and iproute+socat never install either, even
|
||||
// though neither of them conflicts with anything.
|
||||
" dnf install -y --allowerasing iproute socat curl ca-certificates >/dev/null",
|
||||
// Same gap as the sshd probe: Amazon Linux 2 has only yum, so on an instance
|
||||
// launched from ami-amazonlinux2 this chain reached its else branch and exited 1
|
||||
// with "No supported package manager found for IMDS proxy dependencies" --
|
||||
// leaving the instance without a link-local IMDS endpoint.
|
||||
"elif command -v yum >/dev/null 2>&1; then",
|
||||
" yum install -y iproute socat curl ca-certificates >/dev/null",
|
||||
"elif command -v apk >/dev/null 2>&1; then",
|
||||
" apk add --no-cache iproute2 socat curl ca-certificates >/dev/null",
|
||||
"else",
|
||||
" echo 'No supported package manager found for IMDS proxy dependencies' >&2",
|
||||
" exit 1",
|
||||
"fi")};
|
||||
return Ec2MetadataProxy.installCommand();
|
||||
}
|
||||
|
||||
static String[] metadataProxyStartCommand(String flociHost, int imdsPort) {
|
||||
return new String[]{"sh", "-c", String.join("\n",
|
||||
"set -eu",
|
||||
"ip addr show dev lo | grep -q '169.254.169.254/32' || ip addr add 169.254.169.254/32 dev lo",
|
||||
"if [ -f /tmp/floci-imds-proxy.pid ] && kill -0 \"$(cat /tmp/floci-imds-proxy.pid)\" 2>/dev/null; then",
|
||||
" exit 0",
|
||||
"fi",
|
||||
"nohup socat TCP-LISTEN:80,bind=169.254.169.254,fork,reuseaddr TCP:" + flociHost + ":" + imdsPort + " >/tmp/floci-imds-proxy.log 2>&1 &",
|
||||
"echo $! > /tmp/floci-imds-proxy.pid",
|
||||
"for i in 1 2 3 4 5 6 7 8 9 10 11 12; do",
|
||||
" curl -fsS --max-time 1 http://169.254.169.254/latest/meta-data/instance-id >/dev/null && exit 0",
|
||||
" sleep 1",
|
||||
"done",
|
||||
"cat /tmp/floci-imds-proxy.log >&2 || true",
|
||||
"exit 1")};
|
||||
return Ec2MetadataProxy.startCommand(flociHost, imdsPort);
|
||||
}
|
||||
|
||||
|
||||
static List<String> localAwsEnvironment(String region, String serviceEndpoint, String imdsEndpoint) {
|
||||
return List.of(
|
||||
"AWS_EC2_METADATA_SERVICE_ENDPOINT=" + imdsEndpoint,
|
||||
@@ -2054,26 +2018,7 @@ public class Ec2ContainerManager {
|
||||
}
|
||||
|
||||
static Optional<String> preferredMetadataSourceIp(Map<String, ContainerNetwork> networks) {
|
||||
if (networks == null || networks.isEmpty()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
Optional<String> configuredNetworkIp = networks.entrySet().stream()
|
||||
.filter(entry -> !"bridge".equals(entry.getKey()))
|
||||
.map(Map.Entry::getValue)
|
||||
.map(ContainerNetwork::getIpAddress)
|
||||
.filter(ip -> ip != null && !ip.isBlank())
|
||||
.findFirst();
|
||||
if (configuredNetworkIp.isPresent()) {
|
||||
return configuredNetworkIp;
|
||||
}
|
||||
ContainerNetwork bridge = networks.get("bridge");
|
||||
if (bridge != null && bridge.getIpAddress() != null && !bridge.getIpAddress().isBlank()) {
|
||||
return Optional.of(bridge.getIpAddress());
|
||||
}
|
||||
return networks.values().stream()
|
||||
.map(ContainerNetwork::getIpAddress)
|
||||
.filter(ip -> ip != null && !ip.isBlank())
|
||||
.findFirst();
|
||||
return Ec2MetadataProxy.preferredMetadataSourceIp(networks);
|
||||
}
|
||||
|
||||
private byte[] buildSingleFileTar(String filename, byte[] content, int mode) throws IOException {
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
package io.github.hectorvent.floci.services.ec2;
|
||||
|
||||
import com.github.dockerjava.api.model.ContainerNetwork;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* Shared commands and network resolution helpers for installing and starting
|
||||
* the link-local IMDS proxy (169.254.169.254:80) inside containers.
|
||||
*/
|
||||
public final class Ec2MetadataProxy {
|
||||
|
||||
private Ec2MetadataProxy() {}
|
||||
|
||||
public static String[] installCommand() {
|
||||
return new String[]{"sh", "-c", String.join("\n",
|
||||
"set -eu",
|
||||
"if command -v ip >/dev/null 2>&1 && command -v socat >/dev/null 2>&1 && command -v curl >/dev/null 2>&1; then exit 0; fi",
|
||||
"if command -v apt-get >/dev/null 2>&1; then",
|
||||
" apt-get update -qq >/dev/null",
|
||||
" DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends iproute2 socat curl ca-certificates >/dev/null",
|
||||
"elif command -v dnf >/dev/null 2>&1; then",
|
||||
// --allowerasing lets dnf swap the curl-minimal that
|
||||
// public.ecr.aws/amazonlinux/amazonlinux:2023 ships by default for the full
|
||||
// curl package this proxy needs. Without it, dnf aborts the whole transaction
|
||||
// on a curl/curl-minimal conflict and iproute+socat never install either, even
|
||||
// though neither of them conflicts with anything.
|
||||
" dnf install -y --allowerasing iproute socat curl ca-certificates >/dev/null",
|
||||
// Same gap as the sshd probe: Amazon Linux 2 has only yum, so on an instance
|
||||
// launched from ami-amazonlinux2 this chain reached its else branch and exited 1
|
||||
// with "No supported package manager found for IMDS proxy dependencies",
|
||||
// leaving the instance without a link-local IMDS endpoint.
|
||||
"elif command -v yum >/dev/null 2>&1; then",
|
||||
" yum install -y iproute socat curl ca-certificates >/dev/null",
|
||||
"elif command -v apk >/dev/null 2>&1; then",
|
||||
" apk add --no-cache iproute2 socat curl ca-certificates >/dev/null",
|
||||
"else",
|
||||
" echo 'No supported package manager found for IMDS proxy dependencies' >&2",
|
||||
" exit 1",
|
||||
"fi")};
|
||||
}
|
||||
|
||||
public static String[] startCommand(String flociHost, int imdsPort) {
|
||||
return new String[]{"sh", "-c", String.join("\n",
|
||||
"set -eu",
|
||||
"ip addr show dev lo | grep -q '169.254.169.254/32' || ip addr add 169.254.169.254/32 dev lo",
|
||||
"if [ -f /tmp/floci-imds-proxy.pid ] && kill -0 \"$(cat /tmp/floci-imds-proxy.pid)\" 2>/dev/null; then",
|
||||
" exit 0",
|
||||
"fi",
|
||||
"nohup socat TCP-LISTEN:80,bind=169.254.169.254,fork,reuseaddr TCP:" + flociHost + ":" + imdsPort + " >/tmp/floci-imds-proxy.log 2>&1 &",
|
||||
"echo $! > /tmp/floci-imds-proxy.pid",
|
||||
"for i in 1 2 3 4 5 6 7 8 9 10 11 12; do",
|
||||
" curl -fsS --max-time 1 http://169.254.169.254/latest/meta-data/instance-id >/dev/null && exit 0",
|
||||
" sleep 1",
|
||||
"done",
|
||||
"cat /tmp/floci-imds-proxy.log >&2 || true",
|
||||
"exit 1")};
|
||||
}
|
||||
|
||||
public static Optional<String> preferredMetadataSourceIp(Map<String, ContainerNetwork> networks) {
|
||||
if (networks == null || networks.isEmpty()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
Optional<String> configuredNetworkIp = networks.entrySet().stream()
|
||||
.filter(entry -> !"bridge".equals(entry.getKey()))
|
||||
.map(Map.Entry::getValue)
|
||||
.map(ContainerNetwork::getIpAddress)
|
||||
.filter(ip -> ip != null && !ip.isBlank())
|
||||
.findFirst();
|
||||
if (configuredNetworkIp.isPresent()) {
|
||||
return configuredNetworkIp;
|
||||
}
|
||||
ContainerNetwork bridge = networks.get("bridge");
|
||||
if (bridge != null && bridge.getIpAddress() != null && !bridge.getIpAddress().isBlank()) {
|
||||
return Optional.of(bridge.getIpAddress());
|
||||
}
|
||||
return networks.values().stream()
|
||||
.map(ContainerNetwork::getIpAddress)
|
||||
.filter(ip -> ip != null && !ip.isBlank())
|
||||
.findFirst();
|
||||
}
|
||||
}
|
||||
@@ -75,7 +75,7 @@ public class Ec2MetadataServer {
|
||||
}
|
||||
|
||||
/** Reconcile every Docker attachment without retaining stale addresses after restart. */
|
||||
void reconcileContainerAddresses(Set<String> addresses, Instance instance) {
|
||||
public void reconcileContainerAddresses(Set<String> addresses, Instance instance) {
|
||||
for (String address : addresses) {
|
||||
registerContainer(address, instance.getInstanceId(), instance);
|
||||
}
|
||||
@@ -83,15 +83,20 @@ public class Ec2MetadataServer {
|
||||
entry.getValue() == instance && !addresses.contains(entry.getKey()));
|
||||
}
|
||||
|
||||
void unregisterInstance(Instance instance) {
|
||||
containerIpToInstance.entrySet().removeIf(entry -> entry.getValue() == instance);
|
||||
public void unregisterInstance(Instance instance) {
|
||||
if (instance != null) {
|
||||
containerIpToInstance.entrySet().removeIf(entry -> entry.getValue() == instance);
|
||||
}
|
||||
}
|
||||
|
||||
Optional<Instance> registeredContainer(String containerIp) {
|
||||
return Optional.ofNullable(containerIpToInstance.get(containerIp));
|
||||
}
|
||||
|
||||
public CompletableFuture<Void> start() {
|
||||
public synchronized CompletableFuture<Void> start() {
|
||||
if (httpServer != null) {
|
||||
return CompletableFuture.completedFuture(null);
|
||||
}
|
||||
CompletableFuture<Void> future = new CompletableFuture<>();
|
||||
int port = config.services().ec2().imdsPort();
|
||||
|
||||
@@ -137,9 +142,10 @@ public class Ec2MetadataServer {
|
||||
return future;
|
||||
}
|
||||
|
||||
public void stop() {
|
||||
public synchronized void stop() {
|
||||
if (httpServer != null) {
|
||||
httpServer.close();
|
||||
httpServer = null;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -14,9 +14,17 @@ import io.github.hectorvent.floci.core.common.docker.PortAllocator;
|
||||
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;
|
||||
import com.github.dockerjava.api.DockerClient;
|
||||
import com.github.dockerjava.api.async.ResultCallback;
|
||||
import com.github.dockerjava.api.command.ExecCreateCmdResponse;
|
||||
import com.github.dockerjava.api.command.InspectContainerResponse;
|
||||
import com.github.dockerjava.api.model.ContainerNetwork;
|
||||
import com.github.dockerjava.api.model.Frame;
|
||||
import io.github.hectorvent.floci.services.ec2.Ec2MetadataProxy;
|
||||
import io.github.hectorvent.floci.services.ec2.Ec2MetadataServer;
|
||||
import io.github.hectorvent.floci.services.ec2.model.Instance;
|
||||
import io.github.hectorvent.floci.services.ec2.model.InstanceState;
|
||||
import io.github.hectorvent.floci.services.ec2.model.Placement;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
|
||||
@@ -33,7 +41,13 @@ import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
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.TimeUnit;
|
||||
|
||||
/**
|
||||
@@ -62,6 +76,20 @@ public class EksClusterManager {
|
||||
private final EcrRegistryManager ecrRegistryManager;
|
||||
private final EmulatorConfig config;
|
||||
private final RegionResolver regionResolver;
|
||||
private final Ec2MetadataServer metadataServer;
|
||||
private final Map<String, Instance> clusterNodeInstances = new ConcurrentHashMap<>();
|
||||
|
||||
public EksClusterManager(ContainerBuilder containerBuilder,
|
||||
ContainerLifecycleManager lifecycleManager,
|
||||
ContainerDetector containerDetector,
|
||||
PortAllocator portAllocator,
|
||||
DockerHostResolver dockerHostResolver,
|
||||
EcrRegistryManager ecrRegistryManager,
|
||||
EmulatorConfig config,
|
||||
RegionResolver regionResolver) {
|
||||
this(containerBuilder, lifecycleManager, containerDetector, portAllocator,
|
||||
dockerHostResolver, ecrRegistryManager, config, regionResolver, null);
|
||||
}
|
||||
|
||||
@Inject
|
||||
public EksClusterManager(ContainerBuilder containerBuilder,
|
||||
@@ -71,7 +99,8 @@ public class EksClusterManager {
|
||||
DockerHostResolver dockerHostResolver,
|
||||
EcrRegistryManager ecrRegistryManager,
|
||||
EmulatorConfig config,
|
||||
RegionResolver regionResolver) {
|
||||
RegionResolver regionResolver,
|
||||
Ec2MetadataServer metadataServer) {
|
||||
this.containerBuilder = containerBuilder;
|
||||
this.lifecycleManager = lifecycleManager;
|
||||
this.containerDetector = containerDetector;
|
||||
@@ -80,6 +109,7 @@ public class EksClusterManager {
|
||||
this.ecrRegistryManager = ecrRegistryManager;
|
||||
this.config = config;
|
||||
this.regionResolver = regionResolver;
|
||||
this.metadataServer = metadataServer;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -222,6 +252,7 @@ public class EksClusterManager {
|
||||
ContainerInfo info = lifecycleManager.startCreated(containerId, spec);
|
||||
|
||||
applyEndpoints(cluster, containerName, hostPort, info);
|
||||
configureLinkLocalMetadataEndpoint(cluster, containerId);
|
||||
|
||||
LOG.infov("k3s container {0} started for cluster {1} on port {2} (internal: {3})",
|
||||
containerId, cluster.getName(), String.valueOf(hostPort), cluster.getInternalEndpoint());
|
||||
@@ -272,6 +303,7 @@ public class EksClusterManager {
|
||||
cluster.setContainerId(info.containerId());
|
||||
cluster.setHostPort(hostPort);
|
||||
applyEndpoints(cluster, containerName, hostPort, info);
|
||||
configureLinkLocalMetadataEndpoint(cluster, info.containerId());
|
||||
|
||||
LOG.infov("Adopted surviving k3s container {0} for EKS cluster {1} on port {2} (internal: {3})",
|
||||
info.containerId(), cluster.getName(), String.valueOf(hostPort), cluster.getInternalEndpoint());
|
||||
@@ -365,6 +397,7 @@ public class EksClusterManager {
|
||||
* cluster's workloads survive a Floci restart and are re-latched by {@link #restoreCluster}.
|
||||
*/
|
||||
public void stopCluster(Cluster cluster) {
|
||||
unregisterMetadataEndpoint(cluster);
|
||||
if (cluster.getContainerId() == null) {
|
||||
return;
|
||||
}
|
||||
@@ -691,8 +724,133 @@ public class EksClusterManager {
|
||||
""".formatted(serverUrl);
|
||||
}
|
||||
|
||||
private String execInContainer(String containerId, String[] cmd) throws Exception {
|
||||
var dockerClient = lifecycleManager.getDockerClient();
|
||||
void configureLinkLocalMetadataEndpoint(Cluster cluster, String containerId) {
|
||||
if (!config.services().eks().imds()) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
String accountId = cluster.getAccountId() != null
|
||||
? cluster.getAccountId()
|
||||
: regionResolver.getAccountId();
|
||||
String region = clusterRegion(cluster);
|
||||
|
||||
ContainerIps containerIps = resolveContainerIps(containerId);
|
||||
Instance nodeInstance = synthesizeClusterNodeInstance(cluster, containerIps.primaryIp(), region, accountId);
|
||||
clusterNodeInstances.put(clusterResourceName(cluster), nodeInstance);
|
||||
|
||||
if (metadataServer != null) {
|
||||
metadataServer.reconcileContainerAddresses(containerIps.allIps(), nodeInstance);
|
||||
}
|
||||
|
||||
ContainerExecResult install = execInContainerForResult(containerId,
|
||||
Ec2MetadataProxy.installCommand(), 180);
|
||||
if (install.exitCode() != 0) {
|
||||
LOG.warnv("Could not install IMDS proxy dependencies for EKS cluster {0}: {1}",
|
||||
cluster.getName(), install.summary());
|
||||
return;
|
||||
}
|
||||
|
||||
String flociHost = dockerHostResolver.resolve();
|
||||
int imdsPort = config.services().ec2().imdsPort();
|
||||
|
||||
ContainerExecResult start = execInContainerForResult(containerId,
|
||||
Ec2MetadataProxy.startCommand(flociHost, imdsPort), 30);
|
||||
if (start.exitCode() != 0) {
|
||||
LOG.warnv("Could not start link-local IMDS proxy for EKS cluster {0}: {1}",
|
||||
cluster.getName(), start.summary());
|
||||
return;
|
||||
}
|
||||
|
||||
LOG.infov("Configured link-local IMDS endpoint for EKS cluster {0}", cluster.getName());
|
||||
} catch (Exception e) {
|
||||
LOG.warnv("Could not configure link-local IMDS endpoint for EKS cluster {0}: {1}",
|
||||
cluster.getName(), e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
void unregisterMetadataEndpoint(Cluster cluster) {
|
||||
Instance nodeInstance = clusterNodeInstances.remove(clusterResourceName(cluster));
|
||||
if (metadataServer != null && nodeInstance != null) {
|
||||
metadataServer.unregisterInstance(nodeInstance);
|
||||
}
|
||||
}
|
||||
|
||||
private String clusterRegion(Cluster cluster) {
|
||||
if (cluster != null && cluster.getArn() != null) {
|
||||
String[] parts = cluster.getArn().split(":");
|
||||
if (parts.length > 3 && !parts[3].isBlank()) {
|
||||
return parts[3];
|
||||
}
|
||||
}
|
||||
return regionResolver.getDefaultRegion();
|
||||
}
|
||||
|
||||
Instance synthesizeClusterNodeInstance(Cluster cluster, String containerIp, String region, String accountId) {
|
||||
Instance inst = new Instance();
|
||||
String safeClusterName = cluster.getName() != null ? cluster.getName() : "eks-cluster";
|
||||
String safeAccountId = accountId != null ? accountId : config.defaultAccountId();
|
||||
String safeRegion = region != null ? region : clusterRegion(cluster);
|
||||
|
||||
String seed = safeClusterName + "-" + safeAccountId + "-" + safeRegion;
|
||||
String hex = UUID.nameUUIDFromBytes(seed.getBytes(StandardCharsets.UTF_8)).toString().replace("-", "");
|
||||
String instanceId = "i-" + (hex.length() >= 17 ? hex.substring(0, 17) : (hex + "00000000000000000").substring(0, 17));
|
||||
|
||||
inst.setInstanceId(instanceId);
|
||||
inst.setImageId("ami-eks-k3s");
|
||||
inst.setInstanceType("m5.large");
|
||||
inst.setPlacement(new Placement(safeRegion + "a"));
|
||||
inst.setRegion(safeRegion);
|
||||
inst.setState(InstanceState.running());
|
||||
|
||||
String ip = (containerIp != null && !containerIp.isBlank()) ? containerIp : "10.0.0.1";
|
||||
inst.setPrivateIpAddress(ip);
|
||||
inst.setPrivateDnsName("ip-" + ip.replace('.', '-') + "." + safeRegion + ".compute.internal");
|
||||
|
||||
// AWS EKS nodes receive credentials from a node IAM role through an EC2 instance profile,
|
||||
// never from the cluster control-plane role (cluster.getRoleArn()). Synthesize a distinct
|
||||
// node instance profile identity so /latest/meta-data/iam/info returns a valid profile ARN.
|
||||
String nodeProfileName = safeClusterName + "-node-profile";
|
||||
inst.setIamInstanceProfileArn("arn:aws:iam::" + safeAccountId + ":instance-profile/" + nodeProfileName);
|
||||
return inst;
|
||||
}
|
||||
|
||||
record ContainerIps(String primaryIp, Set<String> allIps) {}
|
||||
|
||||
ContainerIps resolveContainerIps(String containerId) {
|
||||
Set<String> ips = new LinkedHashSet<>();
|
||||
String preferred = null;
|
||||
try {
|
||||
InspectContainerResponse inspect = lifecycleManager.getDockerClient().inspectContainerCmd(containerId).exec();
|
||||
if (inspect.getNetworkSettings() != null) {
|
||||
Map<String, ContainerNetwork> networks = inspect.getNetworkSettings().getNetworks();
|
||||
if (networks != null) {
|
||||
preferred = Ec2MetadataProxy.preferredMetadataSourceIp(networks).orElse(null);
|
||||
for (ContainerNetwork network : networks.values()) {
|
||||
if (network != null && network.getIpAddress() != null && !network.getIpAddress().isBlank()) {
|
||||
ips.add(network.getIpAddress());
|
||||
}
|
||||
}
|
||||
}
|
||||
String ip = inspect.getNetworkSettings().getIpAddress();
|
||||
if (ip != null && !ip.isBlank()) {
|
||||
ips.add(ip);
|
||||
if (preferred == null) {
|
||||
preferred = ip;
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
LOG.warnv("Could not inspect container {0} for IPs: {1}", containerId, e.getMessage());
|
||||
}
|
||||
return new ContainerIps(preferred != null ? preferred : "10.0.0.1", ips);
|
||||
}
|
||||
|
||||
Instance getRegisteredClusterNodeInstance(Cluster cluster) {
|
||||
return clusterNodeInstances.get(clusterResourceName(cluster));
|
||||
}
|
||||
|
||||
ContainerExecResult execInContainerForResult(String containerId, String[] cmd, int timeoutSeconds) throws Exception {
|
||||
DockerClient dockerClient = lifecycleManager.getDockerClient();
|
||||
ExecCreateCmdResponse exec = dockerClient
|
||||
.execCreateCmd(containerId)
|
||||
.withCmd(cmd)
|
||||
@@ -705,15 +863,32 @@ public class EksClusterManager {
|
||||
.exec(new ResultCallback.Adapter<Frame>() {
|
||||
@Override
|
||||
public void onNext(Frame frame) {
|
||||
output.append(new String(frame.getPayload(), StandardCharsets.UTF_8));
|
||||
if (frame != null && frame.getPayload() != null) {
|
||||
output.append(new String(frame.getPayload(), StandardCharsets.UTF_8));
|
||||
}
|
||||
}
|
||||
})
|
||||
.awaitCompletion(10, TimeUnit.SECONDS);
|
||||
.awaitCompletion(timeoutSeconds, TimeUnit.SECONDS);
|
||||
|
||||
if (!completed) {
|
||||
return new ContainerExecResult(-1, "Timed out after " + timeoutSeconds + "s");
|
||||
}
|
||||
Long exitCode = dockerClient.inspectExecCmd(exec.getId()).exec().getExitCodeLong();
|
||||
return new ContainerExecResult(exitCode != null ? exitCode : -1, output.toString());
|
||||
}
|
||||
|
||||
record ContainerExecResult(long exitCode, String output) {
|
||||
String summary() {
|
||||
return output == null || output.isBlank() ? "(no output)" : output.trim();
|
||||
}
|
||||
}
|
||||
|
||||
private String execInContainer(String containerId, String[] cmd) throws Exception {
|
||||
ContainerExecResult result = execInContainerForResult(containerId, cmd, 10);
|
||||
if (result.exitCode() == -1 && result.output().startsWith("Timed out")) {
|
||||
throw new RuntimeException("exec timed out in container " + containerId);
|
||||
}
|
||||
return output.toString();
|
||||
return result.output();
|
||||
}
|
||||
|
||||
private String extractYamlField(String yaml, String fieldName) {
|
||||
|
||||
Reference in new issue
Block a user