mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
fix(eks): lease stable VPC private IP and pass --node-ip to k3s across restarts (#7980)
This commit is contained in:
1 parent
287c44b8f8
commit
7ade98e010
5 files changed
+783
-157
No files matched your search
@@ -457,6 +457,29 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Re-claims a Docker-backed subnet address a persisted container (such as an EKS cluster node)
|
||||
* already holds across a restart.
|
||||
*/
|
||||
public boolean reserveVpcPrivateIp(String region, String subnetId, String address) {
|
||||
if (vpcNetworkManager == null || subnetId == null || address == null) {
|
||||
return false;
|
||||
}
|
||||
synchronized (privateIpAllocationLock) {
|
||||
if (!vpcNetworkManager.reservePrivateIp(region, subnetId, address)) {
|
||||
return false;
|
||||
}
|
||||
containerPrivateIps.computeIfAbsent(key(region, subnetId), ignored -> new HashSet<>()).add(address);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
public void detachContainerFromVpc(String region, String vpcId, String containerId) {
|
||||
if (vpcNetworkManager != null) {
|
||||
vpcNetworkManager.detach(region, vpcId, containerId);
|
||||
}
|
||||
}
|
||||
|
||||
public boolean isVpcNetworkEnabled() {
|
||||
return vpcNetworkManager != null && vpcNetworkManager.enabled();
|
||||
}
|
||||
|
||||
@@ -13,6 +13,7 @@ import io.floci.aws.core.common.AwsArnUtils;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.core.common.AwsRegions;
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
import io.floci.aws.core.common.RequestScopes;
|
||||
import io.floci.aws.core.common.dns.DnsAnswer;
|
||||
import io.floci.aws.core.common.dns.DnsClientVpcSource;
|
||||
import io.floci.aws.core.common.dns.DnsClientVpcSource.ClientVpc;
|
||||
@@ -193,6 +194,9 @@ public class EksClusterManager
|
||||
private final StorageBackend<String, Nodegroup> nodeGroupStorage;
|
||||
private final Map<String, Set<String>> programmedClusterRoutes = new ConcurrentHashMap<>();
|
||||
private final ConcurrentHashMap<String, Object> clusterRouteLocks = new ConcurrentHashMap<>();
|
||||
private record VpcLease(String region, String vpcId, String subnetId, String address) {}
|
||||
private record ClusterVpcSubnet(String vpcId, String subnetId) {}
|
||||
private final Map<String, VpcLease> clusterVpcLeases = new ConcurrentHashMap<>();
|
||||
|
||||
private Object routeLockFor(String clusterKey) {
|
||||
return clusterRouteLocks.computeIfAbsent(clusterKey, k -> new Object());
|
||||
@@ -212,6 +216,98 @@ public class EksClusterManager
|
||||
return null;
|
||||
}
|
||||
|
||||
private static ClusterVpcSubnet resolveClusterSubnet(Cluster cluster) {
|
||||
ResourcesVpcConfig vpcConfig = cluster != null ? cluster.getResourcesVpcConfig() : null;
|
||||
if (vpcConfig == null) {
|
||||
return null;
|
||||
}
|
||||
String vpcId = vpcConfig.getVpcId();
|
||||
List<String> subnetIds = vpcConfig.getSubnetIds();
|
||||
String subnetId = (subnetIds != null && !subnetIds.isEmpty()) ? subnetIds.getFirst() : null;
|
||||
if (vpcId == null || vpcId.isBlank() || subnetId == null || subnetId.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
return new ClusterVpcSubnet(vpcId, subnetId);
|
||||
}
|
||||
|
||||
private VpcLease resolveClusterVpcLease(Cluster cluster) {
|
||||
if (cluster == null) {
|
||||
return null;
|
||||
}
|
||||
VpcLease existing = clusterVpcLeases.get(clusterResourceName(cluster));
|
||||
if (existing != null) {
|
||||
return existing;
|
||||
}
|
||||
String persistedIp = cluster.getNodePrivateIp();
|
||||
ClusterVpcSubnet subnet = resolveClusterSubnet(cluster);
|
||||
if (persistedIp == null || persistedIp.isBlank() || subnet == null) {
|
||||
return null;
|
||||
}
|
||||
return new VpcLease(clusterRegion(cluster), subnet.vpcId(), subnet.subnetId(), persistedIp);
|
||||
}
|
||||
|
||||
// Issue #5501: Lease or re-reserve a stable VPC subnet IP for the k3s node container across restarts.
|
||||
private VpcLease acquireClusterVpcLease(Cluster cluster, String accountId, String region) {
|
||||
return acquireClusterVpcLease(cluster, accountId, region, true);
|
||||
}
|
||||
|
||||
private VpcLease acquireClusterVpcLease(Cluster cluster, String accountId, String region,
|
||||
boolean allocateWhenUnreserved) {
|
||||
ClusterVpcSubnet subnet = resolveClusterSubnet(cluster);
|
||||
if (subnet == null) {
|
||||
return null;
|
||||
}
|
||||
String vpcId = subnet.vpcId();
|
||||
String subnetId = subnet.subnetId();
|
||||
Ec2Service ec2 = ec2Service();
|
||||
if (ec2 == null) {
|
||||
return null;
|
||||
}
|
||||
String resourceName = clusterResourceName(cluster);
|
||||
VpcLease existing = clusterVpcLeases.get(resourceName);
|
||||
if (existing != null) {
|
||||
if (cluster.getNodePrivateIp() == null || cluster.getNodePrivateIp().isBlank()) {
|
||||
cluster.setNodePrivateIp(existing.address());
|
||||
}
|
||||
return existing;
|
||||
}
|
||||
String persistedIp = cluster.getNodePrivateIp();
|
||||
if (persistedIp != null && !persistedIp.isBlank()) {
|
||||
boolean reserved = Boolean.TRUE.equals(RequestScopes.callAs(accountId, region,
|
||||
() -> ec2.reserveVpcPrivateIp(region, subnetId, persistedIp)));
|
||||
if (reserved) {
|
||||
VpcLease lease = new VpcLease(region, vpcId, subnetId, persistedIp);
|
||||
clusterVpcLeases.put(resourceName, lease);
|
||||
return lease;
|
||||
}
|
||||
cluster.setNodePrivateIp(null);
|
||||
if (!allocateWhenUnreserved) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
if (!allocateWhenUnreserved) {
|
||||
return null;
|
||||
}
|
||||
Optional<String> allocated = RequestScopes.callAs(accountId, region,
|
||||
() -> ec2.allocateVpcPrivateIp(region, subnetId));
|
||||
if (allocated == null || allocated.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
String address = allocated.get();
|
||||
cluster.setNodePrivateIp(address);
|
||||
VpcLease lease = new VpcLease(region, vpcId, subnetId, address);
|
||||
clusterVpcLeases.put(resourceName, lease);
|
||||
return lease;
|
||||
}
|
||||
|
||||
private void releaseClusterVpcLease(Cluster cluster, String resourceName) {
|
||||
VpcLease lease = clusterVpcLeases.remove(resourceName);
|
||||
Ec2Service ec2 = ec2Service();
|
||||
if (lease != null && ec2 != null) {
|
||||
ec2.releaseVpcPrivateIp(lease.region(), lease.subnetId(), lease.address());
|
||||
}
|
||||
}
|
||||
|
||||
public void addNodeRegistrationListener(Consumer<Instance> listener) {
|
||||
this.nodeRegistrationListeners.add(listener);
|
||||
}
|
||||
@@ -624,161 +720,216 @@ public class EksClusterManager
|
||||
cluster.setDefaultStorageClass(defaultStorageClass);
|
||||
}
|
||||
|
||||
List<String> serverArgs = buildServerArgs(
|
||||
config.services().eks().disableCni(),
|
||||
defaultStorageClass,
|
||||
serviceCidr,
|
||||
clusterCidr);
|
||||
String endpointHost = endpointHost();
|
||||
if (!"localhost".equals(endpointHost)) {
|
||||
serverArgs.add("--tls-san=" + endpointHost);
|
||||
}
|
||||
|
||||
EksNodeCapacity.Limits nodeLimits = resolveNodeCapacity(cluster);
|
||||
if (nodeLimits != null) {
|
||||
nodeLimits.addKubeletArgs(serverArgs);
|
||||
}
|
||||
|
||||
try {
|
||||
String nodeName = deriveClusterNodePrivateDnsName(cluster);
|
||||
serverArgs.add("--node-name=" + nodeName);
|
||||
} catch (Exception e) {
|
||||
String clusterName = cluster != null ? cluster.getName() : "unknown";
|
||||
LOG.warnv("EKS node name injection disabled for cluster {0}: could not derive node name: {1}",
|
||||
clusterName, e.getMessage());
|
||||
}
|
||||
|
||||
try {
|
||||
String providerId = deriveClusterNodeProviderId(cluster);
|
||||
serverArgs.add("--kubelet-arg=provider-id=" + providerId);
|
||||
} catch (Exception e) {
|
||||
String clusterName = cluster != null ? cluster.getName() : "unknown";
|
||||
LOG.warnv("EKS node provider ID injection disabled for cluster {0}: could not derive provider ID: {1}",
|
||||
clusterName, e.getMessage());
|
||||
}
|
||||
|
||||
try {
|
||||
String region = clusterRegion(cluster);
|
||||
String az = deriveClusterNodeAvailabilityZone(cluster, region);
|
||||
Nodegroup nodegroup = selectFirstNodegroup(cluster);
|
||||
String nodeLabels = buildNodeLabels(cluster, nodegroup, az, region);
|
||||
if (nodeLabels != null && !nodeLabels.isBlank()) {
|
||||
serverArgs.add("--kubelet-arg=node-labels=" + nodeLabels);
|
||||
}
|
||||
String taints = buildRegisterWithTaints(nodegroup);
|
||||
if (taints != null && !taints.isBlank()) {
|
||||
serverArgs.add("--kubelet-arg=register-with-taints=" + taints);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
String clusterName = cluster != null ? cluster.getName() : "unknown";
|
||||
LOG.warnv("EKS node topology labels injection disabled for cluster {0}: could not derive topology labels: {1}",
|
||||
clusterName, e.getMessage());
|
||||
}
|
||||
|
||||
// The account label comes from the cluster record when set (restore runs with no request
|
||||
// context); regionResolver is the fallback for the create path.
|
||||
String labelAccountId = resolveClusterAccountId(cluster);
|
||||
Map<String, String> labels = new LinkedHashMap<>(ContainerStorageHelper.resourceIdentityLabels(
|
||||
"eks", cluster.getName(), labelAccountId, clusterRegion(cluster)));
|
||||
labels.put(NODE_CAPACITY_LABEL, capacityLabel(cluster, nodeLimits));
|
||||
labels.put(DEFAULT_STORAGE_CLASS_LABEL, String.valueOf(defaultStorageClass));
|
||||
labels.put(SHARED_MOUNTS_LABEL, "true");
|
||||
if (!"localhost".equals(endpointHost)) {
|
||||
labels.put(ENDPOINT_HOST_LABEL, endpointHost);
|
||||
}
|
||||
ContainerBuilder.Builder specBuilder = containerBuilder.newContainer(image)
|
||||
.withName(containerName)
|
||||
.withEnv("K3S_KUBECONFIG_MODE", "644")
|
||||
.withPortBinding(K3S_API_SERVER_PORT, hostPort)
|
||||
.withNamedVolume(volumeName, K3S_DATA_DIR)
|
||||
.withDockerNetwork(config.services().eks().dockerNetwork())
|
||||
.withPrivileged(true)
|
||||
.withLogRotation()
|
||||
.withLabels(labels);
|
||||
String clusterRegion = clusterRegion(cluster);
|
||||
String resourceName = clusterResourceName(cluster);
|
||||
boolean hadLeaseBeforeLaunch = clusterVpcLeases.containsKey(resourceName);
|
||||
String previousNodeIp = cluster != null ? cluster.getNodePrivateIp() : null;
|
||||
VpcLease vpcLease = acquireClusterVpcLease(cluster, labelAccountId, clusterRegion);
|
||||
String nodeIp = vpcLease != null ? vpcLease.address() : null;
|
||||
String restoredNodeIp = (previousNodeIp != null && !previousNodeIp.isBlank()
|
||||
&& previousNodeIp.equals(nodeIp)) ? previousNodeIp : null;
|
||||
|
||||
if (nodeLimits != null) {
|
||||
if (nodeLimits.memoryBytes() > 0) {
|
||||
specBuilder.withMemoryBytes(nodeLimits.memoryBytes());
|
||||
}
|
||||
if (nodeLimits.vcpus() > 0) {
|
||||
specBuilder.withCpuUnits(nodeLimits.vcpus() * 1024);
|
||||
}
|
||||
}
|
||||
|
||||
if (config.services().eks().embeddedDns()) {
|
||||
specBuilder.withEmbeddedDns();
|
||||
}
|
||||
|
||||
if (config.services().eks().ecrRegistryMirror() && config.services().ecr().enabled()) {
|
||||
specBuilder.withHostDockerInternalOnLinux();
|
||||
}
|
||||
|
||||
// Wire a token-authentication webhook so `aws eks get-token` bearer tokens are validated by
|
||||
// Floci and mapped to their Kubernetes identity. The k3s API server POSTs a TokenReview to Floci's
|
||||
// _floci/eks/clusters/<cluster-name>/token-webhook endpoint. The kubeconfig is copied into
|
||||
// the container via the Docker API after create and before start (below), not bind-mounted,
|
||||
// so it works the same natively and in Docker-in-Docker, with no host-path /
|
||||
// host-persistent-path requirement.
|
||||
List<String> serverArgs;
|
||||
String endpointHost;
|
||||
ContainerBuilder.Builder specBuilder;
|
||||
String webhookLocalFile = null;
|
||||
if (config.services().eks().iamAuthWebhook()) {
|
||||
webhookLocalFile = writeWebhookKubeconfig(cluster);
|
||||
if (webhookLocalFile != null) {
|
||||
specBuilder.withHostDockerInternalOnLinux();
|
||||
serverArgs.add("--kube-apiserver-arg=authentication-token-webhook-config-file="
|
||||
+ WEBHOOK_CONFIG_PATH);
|
||||
serverArgs.add("--kube-apiserver-arg=authentication-token-webhook-version=v1");
|
||||
serverArgs.add("--kube-apiserver-arg=authentication-token-webhook-cache-ttl=30s");
|
||||
}
|
||||
}
|
||||
|
||||
SigningKeyFiles signingKeyFiles = null;
|
||||
if (config.services().eks().irsaSigningKey() && oidcService != null) {
|
||||
String auditPolicyLocalFile = null;
|
||||
ContainerSpec spec;
|
||||
String containerId;
|
||||
try {
|
||||
serverArgs = buildServerArgs(
|
||||
config.services().eks().disableCni(),
|
||||
defaultStorageClass,
|
||||
serviceCidr,
|
||||
clusterCidr,
|
||||
nodeIp);
|
||||
endpointHost = endpointHost();
|
||||
if (!"localhost".equals(endpointHost)) {
|
||||
serverArgs.add("--tls-san=" + endpointHost);
|
||||
}
|
||||
|
||||
EksNodeCapacity.Limits nodeLimits = resolveNodeCapacity(cluster);
|
||||
if (nodeLimits != null) {
|
||||
nodeLimits.addKubeletArgs(serverArgs);
|
||||
}
|
||||
|
||||
try {
|
||||
String accountId = resolveClusterAccountId(cluster);
|
||||
String issuer = resolveClusterIssuer(cluster);
|
||||
ClusterOidcKey oidcKey = oidcService.ensureKeyForAccount(accountId, oidcKeyName(cluster), issuer);
|
||||
signingKeyFiles = writeSigningKeyFiles(cluster, oidcKey);
|
||||
if (signingKeyFiles != null) {
|
||||
serverArgs.addAll(buildIrsaServerArgs(oidcKey.getIssuer()));
|
||||
String nodeName = deriveClusterNodePrivateDnsName(cluster);
|
||||
serverArgs.add("--node-name=" + nodeName);
|
||||
} catch (Exception e) {
|
||||
String clusterName = cluster != null ? cluster.getName() : "unknown";
|
||||
LOG.warnv("EKS node name injection disabled for cluster {0}: could not derive node name: {1}",
|
||||
clusterName, e.getMessage());
|
||||
}
|
||||
|
||||
try {
|
||||
String providerId = deriveClusterNodeProviderId(cluster);
|
||||
serverArgs.add("--kubelet-arg=provider-id=" + providerId);
|
||||
} catch (Exception e) {
|
||||
String clusterName = cluster != null ? cluster.getName() : "unknown";
|
||||
LOG.warnv("EKS node provider ID injection disabled for cluster {0}: could not derive provider ID: {1}",
|
||||
clusterName, e.getMessage());
|
||||
}
|
||||
|
||||
try {
|
||||
String region = clusterRegion(cluster);
|
||||
String az = deriveClusterNodeAvailabilityZone(cluster, region);
|
||||
Nodegroup nodegroup = selectFirstNodegroup(cluster);
|
||||
String nodeLabels = buildNodeLabels(cluster, nodegroup, az, region);
|
||||
if (nodeLabels != null && !nodeLabels.isBlank()) {
|
||||
serverArgs.add("--kubelet-arg=node-labels=" + nodeLabels);
|
||||
}
|
||||
String taints = buildRegisterWithTaints(nodegroup);
|
||||
if (taints != null && !taints.isBlank()) {
|
||||
serverArgs.add("--kubelet-arg=register-with-taints=" + taints);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
LOG.warnv("EKS IRSA signing key injection disabled for cluster {0}: could not prepare keys: {1}",
|
||||
cluster.getName(), e.getMessage());
|
||||
String clusterName = cluster != null ? cluster.getName() : "unknown";
|
||||
LOG.warnv("EKS node topology labels injection disabled for cluster {0}: could not derive topology labels: {1}",
|
||||
clusterName, e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
String auditPolicyLocalFile = null;
|
||||
if (hasLoggingEnabled(cluster, "audit")) {
|
||||
auditPolicyLocalFile = writeAuditPolicyFile(cluster);
|
||||
if (auditPolicyLocalFile != null) {
|
||||
serverArgs.add("--kube-apiserver-arg=audit-policy-file=" + AUDIT_POLICY_CONTAINER_PATH);
|
||||
serverArgs.add("--kube-apiserver-arg=audit-log-path=" + AUDIT_LOG_CONTAINER_PATH);
|
||||
serverArgs.add("--kube-apiserver-arg=audit-log-maxage=" + AUDIT_LOG_MAXAGE);
|
||||
serverArgs.add("--kube-apiserver-arg=audit-log-maxbackup=" + AUDIT_LOG_MAXBACKUP);
|
||||
serverArgs.add("--kube-apiserver-arg=audit-log-maxsize=" + AUDIT_LOG_MAXSIZE);
|
||||
Map<String, String> labels = new LinkedHashMap<>(ContainerStorageHelper.resourceIdentityLabels(
|
||||
"eks", cluster.getName(), labelAccountId, clusterRegion));
|
||||
labels.put(NODE_CAPACITY_LABEL, capacityLabel(cluster, nodeLimits));
|
||||
labels.put(DEFAULT_STORAGE_CLASS_LABEL, String.valueOf(defaultStorageClass));
|
||||
labels.put(SHARED_MOUNTS_LABEL, "true");
|
||||
if (!"localhost".equals(endpointHost)) {
|
||||
labels.put(ENDPOINT_HOST_LABEL, endpointHost);
|
||||
}
|
||||
specBuilder = containerBuilder.newContainer(image)
|
||||
.withName(containerName)
|
||||
.withEnv("K3S_KUBECONFIG_MODE", "644")
|
||||
.withPortBinding(K3S_API_SERVER_PORT, hostPort)
|
||||
.withNamedVolume(volumeName, K3S_DATA_DIR)
|
||||
.withDockerNetwork(config.services().eks().dockerNetwork())
|
||||
.withPrivileged(true)
|
||||
.withLogRotation()
|
||||
.withLabels(labels);
|
||||
|
||||
if (nodeLimits != null) {
|
||||
if (nodeLimits.memoryBytes() > 0) {
|
||||
specBuilder.withMemoryBytes(nodeLimits.memoryBytes());
|
||||
}
|
||||
if (nodeLimits.vcpus() > 0) {
|
||||
specBuilder.withCpuUnits(nodeLimits.vcpus() * 1024);
|
||||
}
|
||||
}
|
||||
|
||||
if (config.services().eks().embeddedDns()) {
|
||||
specBuilder.withEmbeddedDns();
|
||||
}
|
||||
|
||||
if (config.services().eks().ecrRegistryMirror() && config.services().ecr().enabled()) {
|
||||
specBuilder.withHostDockerInternalOnLinux();
|
||||
}
|
||||
|
||||
// Wire a token-authentication webhook so `aws eks get-token` bearer tokens are validated by
|
||||
// Floci and mapped to their Kubernetes identity. The k3s API server POSTs a TokenReview to Floci's
|
||||
// _floci/eks/clusters/<cluster-name>/token-webhook endpoint. The kubeconfig is copied into
|
||||
// the container via the Docker API after create and before start (below), not bind-mounted,
|
||||
// so it works the same natively and in Docker-in-Docker, with no host-path /
|
||||
// host-persistent-path requirement.
|
||||
if (config.services().eks().iamAuthWebhook()) {
|
||||
webhookLocalFile = writeWebhookKubeconfig(cluster);
|
||||
if (webhookLocalFile != null) {
|
||||
specBuilder.withHostDockerInternalOnLinux();
|
||||
serverArgs.add("--kube-apiserver-arg=authentication-token-webhook-config-file="
|
||||
+ WEBHOOK_CONFIG_PATH);
|
||||
serverArgs.add("--kube-apiserver-arg=authentication-token-webhook-version=v1");
|
||||
serverArgs.add("--kube-apiserver-arg=authentication-token-webhook-cache-ttl=30s");
|
||||
}
|
||||
}
|
||||
|
||||
if (config.services().eks().irsaSigningKey() && oidcService != null) {
|
||||
try {
|
||||
String accountId = resolveClusterAccountId(cluster);
|
||||
String issuer = resolveClusterIssuer(cluster);
|
||||
ClusterOidcKey oidcKey = oidcService.ensureKeyForAccount(accountId, oidcKeyName(cluster), issuer);
|
||||
signingKeyFiles = writeSigningKeyFiles(cluster, oidcKey);
|
||||
if (signingKeyFiles != null) {
|
||||
serverArgs.addAll(buildIrsaServerArgs(oidcKey.getIssuer()));
|
||||
}
|
||||
} catch (Exception e) {
|
||||
LOG.warnv("EKS IRSA signing key injection disabled for cluster {0}: could not prepare keys: {1}",
|
||||
cluster.getName(), e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
if (hasLoggingEnabled(cluster, "audit")) {
|
||||
auditPolicyLocalFile = writeAuditPolicyFile(cluster);
|
||||
if (auditPolicyLocalFile != null) {
|
||||
serverArgs.add("--kube-apiserver-arg=audit-policy-file=" + AUDIT_POLICY_CONTAINER_PATH);
|
||||
serverArgs.add("--kube-apiserver-arg=audit-log-path=" + AUDIT_LOG_CONTAINER_PATH);
|
||||
serverArgs.add("--kube-apiserver-arg=audit-log-maxage=" + AUDIT_LOG_MAXAGE);
|
||||
serverArgs.add("--kube-apiserver-arg=audit-log-maxbackup=" + AUDIT_LOG_MAXBACKUP);
|
||||
serverArgs.add("--kube-apiserver-arg=audit-log-maxsize=" + AUDIT_LOG_MAXSIZE);
|
||||
}
|
||||
}
|
||||
|
||||
List<String> callerArgs = resolveCallerArgs(cluster);
|
||||
if (!callerArgs.isEmpty()) {
|
||||
serverArgs.addAll(callerArgs);
|
||||
}
|
||||
|
||||
// A container's mounts default to private propagation, which a pod asking for mount
|
||||
// propagation cannot start on: a CSI node plugin mounts its volumes under
|
||||
// /var/lib/kubelet/pods with Bidirectional propagation ("is not a shared mount"), a node
|
||||
// exporter reads / with HostToContainer, and Cilium mounts its BPF filesystem on /sys
|
||||
// ("is not a shared or slave mount"). An EKS node is a VM, whose mounts are shared.
|
||||
// `mount --make-rshared /` before k3s starts gives the node the same; kind's own node
|
||||
// image runs the same fix in its entrypoint. RSHARE_ENTRYPOINT is POSIX sh-compatible
|
||||
// (no bashisms): the k3s image has no bash, only busybox sh.
|
||||
specBuilder.withEntrypoint(RSHARE_ENTRYPOINT);
|
||||
specBuilder.withCmd(buildRshareWrappedCmd(serverArgs));
|
||||
spec = specBuilder.build();
|
||||
|
||||
// create -> attach VPC network -> inject webhook kubeconfig -> start, so the interface
|
||||
// and files exist before the k3s API server / network policy controller boots.
|
||||
containerId = lifecycleManager.create(spec);
|
||||
} catch (RuntimeException e) {
|
||||
if (!hadLeaseBeforeLaunch) {
|
||||
releaseClusterVpcLease(cluster, resourceName);
|
||||
if (cluster != null) {
|
||||
cluster.setNodePrivateIp(restoredNodeIp);
|
||||
}
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
|
||||
List<String> callerArgs = resolveCallerArgs(cluster);
|
||||
if (!callerArgs.isEmpty()) {
|
||||
serverArgs.addAll(callerArgs);
|
||||
}
|
||||
|
||||
// A container's mounts default to private propagation, which a pod asking for mount
|
||||
// propagation cannot start on: a CSI node plugin mounts its volumes under
|
||||
// /var/lib/kubelet/pods with Bidirectional propagation ("is not a shared mount"), a node
|
||||
// exporter reads / with HostToContainer, and Cilium mounts its BPF filesystem on /sys
|
||||
// ("is not a shared or slave mount"). An EKS node is a VM, whose mounts are shared.
|
||||
// `mount --make-rshared /` before k3s starts gives the node the same; kind's own node
|
||||
// image runs the same fix in its entrypoint. RSHARE_ENTRYPOINT is POSIX sh-compatible
|
||||
// (no bashisms): the k3s image has no bash, only busybox sh.
|
||||
specBuilder.withEntrypoint(RSHARE_ENTRYPOINT);
|
||||
specBuilder.withCmd(buildRshareWrappedCmd(serverArgs));
|
||||
ContainerSpec spec = specBuilder.build();
|
||||
|
||||
// create -> inject webhook kubeconfig -> start, so the file exists before the API server boots.
|
||||
String containerId = lifecycleManager.create(spec);
|
||||
cluster.setContainerId(containerId);
|
||||
if (vpcLease != null) {
|
||||
Ec2Service ec2 = ec2Service();
|
||||
Optional<String> attachedNetwork = ec2 != null
|
||||
? ec2.attachContainerToVpc(
|
||||
vpcLease.region(), vpcLease.vpcId(), vpcLease.subnetId(),
|
||||
containerId, vpcLease.address())
|
||||
: Optional.empty();
|
||||
if (attachedNetwork == null || attachedNetwork.isEmpty()) {
|
||||
if (hadLeaseBeforeLaunch || (previousNodeIp != null && !previousNodeIp.isBlank())) {
|
||||
// Issue #5501: A restored cluster's k3s data already holds its node IP; fail
|
||||
// the start and retain the address rather than booting on the bridge without it.
|
||||
lifecycleManager.removeIfExistsStrict(containerName, true);
|
||||
cluster.setContainerId(null);
|
||||
throw new IllegalStateException("Failed to attach restored EKS container "
|
||||
+ containerName + " to VPC " + vpcLease.vpcId());
|
||||
}
|
||||
releaseClusterVpcLease(cluster, resourceName);
|
||||
if (cluster != null) {
|
||||
cluster.setNodePrivateIp(null);
|
||||
}
|
||||
vpcLease = null;
|
||||
lifecycleManager.removeIfExistsStrict(containerName, true);
|
||||
serverArgs.remove("--node-ip=" + nodeIp);
|
||||
specBuilder.withCmd(buildRshareWrappedCmd(serverArgs));
|
||||
spec = specBuilder.build();
|
||||
containerId = lifecycleManager.create(spec);
|
||||
cluster.setContainerId(containerId);
|
||||
}
|
||||
}
|
||||
if (webhookLocalFile != null) {
|
||||
copyWebhookIntoContainer(containerId, webhookLocalFile, cluster.getName());
|
||||
}
|
||||
@@ -801,6 +952,18 @@ public class EksClusterManager
|
||||
e.addSuppressed(cleanup);
|
||||
LOG.warnv("Could not remove failed EKS container {0}; retaining it for cleanup retry: {1}",
|
||||
containerName, cleanup.getMessage());
|
||||
if (vpcLease != null) {
|
||||
Ec2Service ec2 = ec2Service();
|
||||
if (ec2 != null) {
|
||||
ec2.detachContainerFromVpc(vpcLease.region(), vpcLease.vpcId(), containerId);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!hadLeaseBeforeLaunch) {
|
||||
releaseClusterVpcLease(cluster, resourceName);
|
||||
if (cluster != null) {
|
||||
cluster.setNodePrivateIp(restoredNodeIp);
|
||||
}
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
@@ -908,6 +1071,9 @@ public class EksClusterManager
|
||||
cluster.setContainerId(info.containerId());
|
||||
cluster.setHostPort(hostPort);
|
||||
applyEndpoints(cluster, cluster.getDockerName(), hostPort, info, certificateHost);
|
||||
if (cluster.getNodePrivateIp() != null && !cluster.getNodePrivateIp().isBlank()) {
|
||||
acquireClusterVpcLease(cluster, resolveClusterAccountId(cluster), clusterRegion(cluster), false);
|
||||
}
|
||||
registerClusterNodeInstance(cluster, info.containerId());
|
||||
configureLinkLocalMetadataEndpoint(cluster, info.containerId());
|
||||
configurePodIdentityRelay(cluster, info.containerId());
|
||||
@@ -938,10 +1104,15 @@ public class EksClusterManager
|
||||
return false;
|
||||
}
|
||||
boolean renamed = false;
|
||||
VpcLease lease = resolveClusterVpcLease(cluster);
|
||||
Ec2Service ec2 = ec2Service();
|
||||
try {
|
||||
docker.renameContainerCmd(oldId).withName(backupName).exec();
|
||||
renamed = true;
|
||||
docker.stopContainerCmd(oldId).exec();
|
||||
if (lease != null && ec2 != null) {
|
||||
ec2.detachContainerFromVpc(lease.region(), lease.vpcId(), oldId);
|
||||
}
|
||||
unregisterMetadataEndpoint(cluster);
|
||||
closeQuietly(clusterLogHandles.remove(clusterResourceName(cluster)));
|
||||
cluster.setContainerId(null);
|
||||
@@ -957,6 +1128,13 @@ public class EksClusterManager
|
||||
try {
|
||||
lifecycleManager.removeIfExistsStrict(containerName, true);
|
||||
docker.renameContainerCmd(oldId).withName(containerName).exec();
|
||||
if (lease != null && ec2 != null) {
|
||||
Optional<String> reattached = ec2.attachContainerToVpc(
|
||||
lease.region(), lease.vpcId(), lease.subnetId(), oldId, lease.address());
|
||||
if (reattached == null || reattached.isEmpty()) {
|
||||
throw new IllegalStateException("Could not reattach previous EKS container " + oldId);
|
||||
}
|
||||
}
|
||||
if (!adoptSurvivingCluster(cluster, oldId, oldCertificateHost)) {
|
||||
throw new IllegalStateException("Could not adopt previous EKS container " + oldId);
|
||||
}
|
||||
@@ -1110,6 +1288,7 @@ public class EksClusterManager
|
||||
public void stopCluster(Cluster cluster) {
|
||||
String resourceName = clusterResourceName(cluster);
|
||||
if (cluster.getContainerId() == null) {
|
||||
releaseClusterVpcLease(cluster, resourceName);
|
||||
unregisterMetadataEndpoint(cluster);
|
||||
closeQuietly(clusterLogHandles.remove(resourceName));
|
||||
return;
|
||||
@@ -1119,6 +1298,7 @@ public class EksClusterManager
|
||||
// port, so the delete fails and keeps the cluster record, its metadata endpoint, log
|
||||
// handle and port reservation; a retried delete releases them once the container is gone.
|
||||
lifecycleManager.stopAndRemoveStrict(cluster.getContainerId(), logStream, 5, true);
|
||||
releaseClusterVpcLease(cluster, resourceName);
|
||||
unregisterMetadataEndpoint(cluster);
|
||||
// Removed by value so an overlapping delete cannot drop a handle it does not own.
|
||||
if (logStream != null) {
|
||||
@@ -1561,7 +1741,7 @@ public class EksClusterManager
|
||||
* config javadoc for why this must happen at startup, not after the fact.
|
||||
*/
|
||||
static List<String> buildServerArgs(boolean disableCni, boolean defaultStorageClass,
|
||||
String serviceCidr, String clusterCidr) {
|
||||
String serviceCidr, String clusterCidr, String nodeIp) {
|
||||
List<String> serverArgs = new ArrayList<>(List.of("server",
|
||||
"--disable=traefik",
|
||||
"--tls-san=localhost"));
|
||||
@@ -1579,9 +1759,17 @@ public class EksClusterManager
|
||||
if (clusterCidr != null && !clusterCidr.isBlank()) {
|
||||
serverArgs.add("--cluster-cidr=" + clusterCidr);
|
||||
}
|
||||
if (nodeIp != null && !nodeIp.isBlank()) {
|
||||
serverArgs.add("--node-ip=" + nodeIp);
|
||||
}
|
||||
return serverArgs;
|
||||
}
|
||||
|
||||
static List<String> buildServerArgs(boolean disableCni, boolean defaultStorageClass,
|
||||
String serviceCidr, String clusterCidr) {
|
||||
return buildServerArgs(disableCni, defaultStorageClass, serviceCidr, clusterCidr, null);
|
||||
}
|
||||
|
||||
static List<String> buildServerArgs(boolean disableCni, String serviceCidr, String clusterCidr) {
|
||||
return buildServerArgs(disableCni, false, serviceCidr, clusterCidr);
|
||||
}
|
||||
@@ -3016,7 +3204,9 @@ public class EksClusterManager
|
||||
inst.setRegion(safeRegion);
|
||||
inst.setState(InstanceState.running());
|
||||
|
||||
String ip = (containerIp != null && !containerIp.isBlank()) ? containerIp : "10.0.0.1";
|
||||
String ip = (cluster != null && cluster.getNodePrivateIp() != null && !cluster.getNodePrivateIp().isBlank())
|
||||
? cluster.getNodePrivateIp()
|
||||
: ((containerIp != null && !containerIp.isBlank()) ? containerIp : "10.0.0.1");
|
||||
inst.setPrivateIpAddress(ip);
|
||||
inst.setPrivateDnsName(privateDnsName);
|
||||
|
||||
|
||||
@@ -109,6 +109,7 @@ public class EksController {
|
||||
*/
|
||||
private Cluster toClusterResponse(Cluster cluster) {
|
||||
if (cluster == null || (!cluster.isExplicitVersion() && cluster.getNodeInstanceType() == null
|
||||
&& cluster.getNodePrivateIp() == null
|
||||
&& cluster.getClusterArgs() == null && cluster.getDefaultStorageClass() == null
|
||||
&& cluster.getJoinedInstanceIds() == null && cluster.getDockerNameRegion() == null)) {
|
||||
return cluster;
|
||||
@@ -117,6 +118,7 @@ public class EksController {
|
||||
response.setDockerNameRegion(null);
|
||||
response.setExplicitVersion(false);
|
||||
response.setNodeInstanceType(null);
|
||||
response.setNodePrivateIp(null);
|
||||
response.setClusterArgs(null);
|
||||
response.setDefaultStorageClass(null);
|
||||
response.setJoinedInstanceIds(null);
|
||||
|
||||
@@ -111,6 +111,11 @@ public class Cluster {
|
||||
@JsonInclude(JsonInclude.Include.NON_NULL)
|
||||
private String nodeInstanceType;
|
||||
|
||||
/** Private IPv4 address leased for the cluster node from its VPC subnet. Internal persisted metadata. */
|
||||
@JsonProperty("nodePrivateIp")
|
||||
@JsonInclude(JsonInclude.Include.NON_NULL)
|
||||
private String nodePrivateIp;
|
||||
|
||||
/**
|
||||
* Caller-supplied k3s arguments passed at creation via reserved floci tags.
|
||||
* Internal persisted metadata omitted from AWS API responses.
|
||||
@@ -215,6 +220,9 @@ public class Cluster {
|
||||
public String getNodeInstanceType() { return nodeInstanceType; }
|
||||
public void setNodeInstanceType(String nodeInstanceType) { this.nodeInstanceType = nodeInstanceType; }
|
||||
|
||||
public String getNodePrivateIp() { return nodePrivateIp; }
|
||||
public void setNodePrivateIp(String nodePrivateIp) { this.nodePrivateIp = nodePrivateIp; }
|
||||
|
||||
public List<String> getClusterArgs() { return clusterArgs; }
|
||||
public void setClusterArgs(List<String> clusterArgs) { this.clusterArgs = clusterArgs; }
|
||||
|
||||
@@ -278,6 +286,7 @@ public class Cluster {
|
||||
c.dockerName = this.dockerName;
|
||||
c.dockerNameRegion = this.dockerNameRegion;
|
||||
c.nodeInstanceType = this.nodeInstanceType;
|
||||
c.nodePrivateIp = this.nodePrivateIp;
|
||||
c.clusterArgs = this.clusterArgs != null ? new ArrayList<>(this.clusterArgs) : null;
|
||||
c.defaultStorageClass = this.defaultStorageClass;
|
||||
c.joinedInstanceIds = this.joinedInstanceIds != null ? new ConcurrentHashMap<>(this.joinedInstanceIds) : null;
|
||||
|
||||
@@ -34,24 +34,33 @@ import io.floci.aws.core.common.docker.ContainerLogStreamer;
|
||||
import io.floci.aws.core.common.docker.ContainerSpec;
|
||||
import io.floci.aws.core.common.docker.DockerHostResolver;
|
||||
import io.floci.aws.core.common.docker.PortAllocator;
|
||||
import io.floci.aws.core.storage.AccountAwareStorageBackend;
|
||||
import io.floci.aws.core.storage.InMemoryStorage;
|
||||
import io.floci.aws.core.storage.StorageBackend;
|
||||
import io.floci.aws.core.storage.StorageFactory;
|
||||
import io.floci.aws.services.ec2.AmiImageResolver;
|
||||
import io.floci.aws.services.ec2.Ec2ContainerManager;
|
||||
import io.floci.aws.services.ec2.Ec2ImageCatalog;
|
||||
import io.floci.aws.services.ec2.Ec2InstanceTypeCatalog;
|
||||
import io.floci.aws.services.ec2.Ec2MetadataServer;
|
||||
import io.floci.aws.services.ec2.Ec2Service;
|
||||
import io.floci.aws.services.ec2.model.Instance;
|
||||
import io.floci.aws.services.ec2.model.Placement;
|
||||
import io.floci.aws.services.ec2.net.VpcNetworkManager;
|
||||
import io.floci.aws.services.ec2.portforward.Ec2PortForwardManager;
|
||||
import io.floci.aws.services.ecr.registry.EcrRegistryManager;
|
||||
import io.floci.aws.services.eks.model.CertificateAuthority;
|
||||
import io.floci.aws.services.eks.model.Cluster;
|
||||
import io.floci.aws.services.eks.model.ClusterIdentity;
|
||||
import io.floci.aws.services.eks.model.ClusterOidcKey;
|
||||
import io.floci.aws.services.eks.model.CreateClusterRequest;
|
||||
import io.floci.aws.services.eks.model.LogSetup;
|
||||
import io.floci.aws.services.eks.model.Logging;
|
||||
import io.floci.aws.services.eks.model.Nodegroup;
|
||||
import io.floci.aws.services.eks.model.OidcIdentity;
|
||||
import io.floci.aws.services.eks.model.ResourcesVpcConfig;
|
||||
import io.floci.aws.testutil.LogCapture;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
|
||||
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
@@ -59,6 +68,7 @@ import org.junit.jupiter.api.Nested;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.NullAndEmptySource;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.InOrder;
|
||||
@@ -563,6 +573,20 @@ class EksClusterManagerTest {
|
||||
}
|
||||
}
|
||||
|
||||
// Container's getters are final, so survivors are built from JSON instead of mocked.
|
||||
private static Container survivingContainer(String id) {
|
||||
return containerFromJson("{\"Id\":\"" + id + "\","
|
||||
+ "\"Labels\":{\"io.floci.eks.node-capacity\":\"m5.large:unbounded\",\"io.floci.eks.shared-mounts\":\"true\"}}");
|
||||
}
|
||||
|
||||
private static Container containerFromJson(String json) {
|
||||
try {
|
||||
return new ObjectMapper().readValue(json, Container.class);
|
||||
} catch (JsonProcessingException e) {
|
||||
throw new IllegalStateException(e);
|
||||
}
|
||||
}
|
||||
|
||||
/** Re-latching persisted clusters after a Floci/Docker restart (#2609), without a Docker daemon. */
|
||||
@Nested
|
||||
class RestoreCluster {
|
||||
@@ -610,26 +634,12 @@ class EksClusterManagerTest {
|
||||
config, Mockito.mock(RegionResolver.class));
|
||||
}
|
||||
|
||||
// Container's getters are final, so survivors are built from JSON instead of mocked.
|
||||
private Container survivingContainer(String id) {
|
||||
return containerFromJson("{\"Id\":\"" + id + "\","
|
||||
+ "\"Labels\":{\"io.floci.eks.node-capacity\":\"m5.large:unbounded\",\"io.floci.eks.shared-mounts\":\"true\"}}");
|
||||
}
|
||||
|
||||
private Container survivingContainerOwnedBy(String id, String accountId) {
|
||||
return containerFromJson("{\"Id\":\"" + id + "\","
|
||||
+ "\"Labels\":{\"io.floci.account\":\"" + accountId + "\","
|
||||
+ "\"io.floci.eks.node-capacity\":\"m5.large:unbounded\",\"io.floci.eks.shared-mounts\":\"true\"}}");
|
||||
}
|
||||
|
||||
private Container containerFromJson(String json) {
|
||||
try {
|
||||
return new ObjectMapper().readValue(json, Container.class);
|
||||
} catch (JsonProcessingException e) {
|
||||
throw new IllegalStateException(e);
|
||||
}
|
||||
}
|
||||
|
||||
private Cluster cluster() {
|
||||
Cluster cluster = new Cluster();
|
||||
cluster.setName("demo");
|
||||
@@ -1759,6 +1769,7 @@ class EksClusterManagerTest {
|
||||
regionResolver = Mockito.mock(RegionResolver.class);
|
||||
when(regionResolver.getAccountId()).thenReturn("000000000000");
|
||||
when(regionResolver.getDefaultRegion()).thenReturn("us-east-1");
|
||||
when(regionResolver.getRegion()).thenReturn("us-east-1");
|
||||
when(regionResolver.buildGlobalArn(anyString(), anyString(), anyString())).thenAnswer(invocation ->
|
||||
"arn:aws:" + invocation.getArgument(0) + "::" + invocation.getArgument(1) + ":" + invocation.getArgument(2));
|
||||
|
||||
@@ -4597,4 +4608,395 @@ class EksClusterManagerTest {
|
||||
return inst;
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class VpcNodePrivateIp {
|
||||
|
||||
private EmulatorConfig config;
|
||||
private ContainerLifecycleManager lifecycleManager;
|
||||
private ContainerBuilder containerBuilder;
|
||||
private ContainerBuilder.Builder builder;
|
||||
private PortAllocator portAllocator;
|
||||
private DockerClient dockerClient;
|
||||
private RegionResolver regionResolver;
|
||||
private Ec2Service ec2Service;
|
||||
private EksClusterManager manager;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
config = Mockito.mock(EmulatorConfig.class);
|
||||
EmulatorConfig.ServicesConfig services = Mockito.mock(EmulatorConfig.ServicesConfig.class);
|
||||
EmulatorConfig.EksServiceConfig eks = Mockito.mock(EmulatorConfig.EksServiceConfig.class);
|
||||
EmulatorConfig.StorageConfig storage = Mockito.mock(EmulatorConfig.StorageConfig.class);
|
||||
when(config.services()).thenReturn(services);
|
||||
when(config.storage()).thenReturn(storage);
|
||||
when(config.defaultAccountId()).thenReturn("000000000000");
|
||||
when(services.eks()).thenReturn(eks);
|
||||
when(eks.defaultImage()).thenReturn("rancher/k3s:v1.30.0-k3s1");
|
||||
when(eks.apiServerBasePort()).thenReturn(6440);
|
||||
when(eks.apiServerMaxPort()).thenReturn(6499);
|
||||
when(eks.dockerNetwork()).thenReturn(Optional.empty());
|
||||
when(eks.endpointMode()).thenReturn("host");
|
||||
when(eks.disableCni()).thenReturn(false);
|
||||
when(eks.iamAuthWebhook()).thenReturn(false);
|
||||
when(eks.ecrRegistryMirror()).thenReturn(false);
|
||||
|
||||
lifecycleManager = Mockito.mock(ContainerLifecycleManager.class);
|
||||
containerBuilder = Mockito.mock(ContainerBuilder.class);
|
||||
builder = Mockito.mock(ContainerBuilder.Builder.class, Mockito.RETURNS_SELF);
|
||||
when(containerBuilder.newContainer(anyString())).thenReturn(builder);
|
||||
when(builder.build()).thenReturn(new ContainerSpec("test-image"));
|
||||
portAllocator = Mockito.mock(PortAllocator.class);
|
||||
dockerClient = Mockito.mock(DockerClient.class, Mockito.RETURNS_DEEP_STUBS);
|
||||
when(lifecycleManager.getDockerClient()).thenReturn(dockerClient);
|
||||
|
||||
regionResolver = Mockito.mock(RegionResolver.class);
|
||||
when(regionResolver.getAccountId()).thenReturn("000000000000");
|
||||
when(regionResolver.getDefaultRegion()).thenReturn("us-east-1");
|
||||
when(regionResolver.buildGlobalArn(anyString(), anyString(), anyString())).thenAnswer(invocation ->
|
||||
"arn:aws:" + invocation.getArgument(0) + "::" + invocation.getArgument(1) + ":" + invocation.getArgument(2));
|
||||
|
||||
ec2Service = Mockito.mock(Ec2Service.class);
|
||||
when(ec2Service.attachContainerToVpc(anyString(), anyString(), anyString(), anyString(), anyString()))
|
||||
.thenReturn(Optional.of("floci-vpc-1"));
|
||||
manager = new EksClusterManager(containerBuilder, lifecycleManager,
|
||||
Mockito.mock(ContainerDetector.class), portAllocator,
|
||||
Mockito.mock(DockerHostResolver.class), Mockito.mock(EcrRegistryManager.class),
|
||||
config, regionResolver);
|
||||
manager.setEc2Service(ec2Service);
|
||||
}
|
||||
|
||||
private Cluster vpcCluster(String name, String vpcId, List<String> subnetIds) {
|
||||
Cluster cluster = new Cluster();
|
||||
cluster.setName(name);
|
||||
cluster.setArn("arn:aws:eks:us-east-1:000000000000:cluster/" + name);
|
||||
ResourcesVpcConfig vpcConfig = new ResourcesVpcConfig();
|
||||
vpcConfig.setVpcId(vpcId);
|
||||
vpcConfig.setSubnetIds(subnetIds);
|
||||
cluster.setResourcesVpcConfig(vpcConfig);
|
||||
return cluster;
|
||||
}
|
||||
|
||||
@Test
|
||||
void buildServerArgsIncludesNodeIpWhenProvided() {
|
||||
List<String> args = EksClusterManager.buildServerArgs(
|
||||
false, false, "10.100.0.0/16", "10.42.0.0/16", "10.0.1.25");
|
||||
|
||||
assertTrue(args.contains("--node-ip=10.0.1.25"));
|
||||
assertTrue(args.contains("--service-cidr=10.100.0.0/16"));
|
||||
assertTrue(args.contains("--cluster-cidr=10.42.0.0/16"));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@NullAndEmptySource
|
||||
@ValueSource(strings = {" "})
|
||||
void buildServerArgsOmitsNodeIpWhenNullOrBlank(String nodeIp) {
|
||||
List<String> args = EksClusterManager.buildServerArgs(
|
||||
false, false, "10.100.0.0/16", "10.42.0.0/16", nodeIp);
|
||||
|
||||
assertTrue(args.stream().noneMatch(a -> a.startsWith("--node-ip")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void startClusterLeasesPrivateIpAttachesBeforeStartPassesNodeIpSynthesizesNodeAndReleasesOnStop() {
|
||||
when(portAllocator.allocate(6440, 6499)).thenReturn(6440);
|
||||
when(lifecycleManager.create(any())).thenReturn("cid-1");
|
||||
when(lifecycleManager.startCreated(eq("cid-1"), any()))
|
||||
.thenReturn(new ContainerInfo("cid-1", Map.of()));
|
||||
when(ec2Service.allocateVpcPrivateIp("us-east-1", "subnet-1"))
|
||||
.thenReturn(Optional.of("10.0.1.25"));
|
||||
when(ec2Service.attachContainerToVpc("us-east-1", "vpc-1", "subnet-1", "cid-1", "10.0.1.25"))
|
||||
.thenReturn(Optional.of("floci-vpc-1"));
|
||||
|
||||
Cluster cluster = vpcCluster("vpc-cluster", "vpc-1", List.of("subnet-1", "subnet-2"));
|
||||
manager.startCluster(cluster);
|
||||
|
||||
assertEquals("10.0.1.25", cluster.getNodePrivateIp());
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
ArgumentCaptor<List<String>> cmdCaptor = ArgumentCaptor.forClass(List.class);
|
||||
verify(builder).withCmd(cmdCaptor.capture());
|
||||
assertTrue(cmdCaptor.getValue().contains("--node-ip=10.0.1.25"));
|
||||
|
||||
InOrder order = Mockito.inOrder(ec2Service, lifecycleManager);
|
||||
order.verify(ec2Service).allocateVpcPrivateIp("us-east-1", "subnet-1");
|
||||
order.verify(lifecycleManager).create(any());
|
||||
order.verify(ec2Service).attachContainerToVpc("us-east-1", "vpc-1", "subnet-1", "cid-1", "10.0.1.25");
|
||||
order.verify(lifecycleManager).startCreated(eq("cid-1"), any());
|
||||
|
||||
Instance nodeInstance = manager.synthesizeClusterNodeInstance(
|
||||
cluster, "172.17.0.2", "us-east-1", "000000000000");
|
||||
assertEquals("10.0.1.25", nodeInstance.getPrivateIpAddress());
|
||||
|
||||
manager.stopCluster(cluster);
|
||||
order.verify(lifecycleManager).stopAndRemoveStrict("cid-1", null, 5, true);
|
||||
order.verify(ec2Service).releaseVpcPrivateIp("us-east-1", "subnet-1", "10.0.1.25");
|
||||
}
|
||||
|
||||
@Test
|
||||
void startClusterWithoutVpcOrWhenNoIpAllocatedOmitsNodeIpAndAttachment() {
|
||||
when(portAllocator.allocate(6440, 6499)).thenReturn(6440);
|
||||
when(lifecycleManager.create(any())).thenReturn("cid-no-ip");
|
||||
when(lifecycleManager.startCreated(eq("cid-no-ip"), any()))
|
||||
.thenReturn(new ContainerInfo("cid-no-ip", Map.of()));
|
||||
when(ec2Service.allocateVpcPrivateIp("us-east-1", "subnet-1"))
|
||||
.thenReturn(Optional.empty());
|
||||
|
||||
Cluster cluster = vpcCluster("unbacked-cluster", "vpc-1", List.of("subnet-1"));
|
||||
manager.startCluster(cluster);
|
||||
|
||||
assertNull(cluster.getNodePrivateIp());
|
||||
@SuppressWarnings("unchecked")
|
||||
ArgumentCaptor<List<String>> cmdCaptor = ArgumentCaptor.forClass(List.class);
|
||||
verify(builder).withCmd(cmdCaptor.capture());
|
||||
assertTrue(cmdCaptor.getValue().stream().noneMatch(a -> a.startsWith("--node-ip")));
|
||||
verify(ec2Service, never()).attachContainerToVpc(anyString(), anyString(), anyString(), anyString(), anyString());
|
||||
|
||||
Instance fallbackNode = manager.synthesizeClusterNodeInstance(
|
||||
cluster, "172.17.0.2", "us-east-1", "000000000000");
|
||||
assertEquals("172.17.0.2", fallbackNode.getPrivateIpAddress());
|
||||
}
|
||||
|
||||
@Test
|
||||
void restoreClusterRecreatingMissingContainerReusesPersistedNodeIpAndReservesIt() {
|
||||
when(lifecycleManager.findByName("floci-eks-recreated")).thenReturn(Optional.empty());
|
||||
when(portAllocator.allocate(6440, 6499)).thenReturn(6440);
|
||||
when(lifecycleManager.create(any())).thenReturn("cid-recreated");
|
||||
when(lifecycleManager.startCreated(eq("cid-recreated"), any()))
|
||||
.thenReturn(new ContainerInfo("cid-recreated", Map.of()));
|
||||
when(ec2Service.reserveVpcPrivateIp("us-east-1", "subnet-1", "10.0.1.25"))
|
||||
.thenReturn(true);
|
||||
|
||||
Cluster cluster = vpcCluster("recreated", "vpc-1", List.of("subnet-1"));
|
||||
cluster.setNodePrivateIp("10.0.1.25");
|
||||
|
||||
manager.restoreCluster(cluster);
|
||||
|
||||
assertEquals("10.0.1.25", cluster.getNodePrivateIp());
|
||||
verify(ec2Service, never()).allocateVpcPrivateIp(anyString(), anyString());
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
ArgumentCaptor<List<String>> cmdCaptor = ArgumentCaptor.forClass(List.class);
|
||||
verify(builder).withCmd(cmdCaptor.capture());
|
||||
assertTrue(cmdCaptor.getValue().contains("--node-ip=10.0.1.25"));
|
||||
|
||||
InOrder order = Mockito.inOrder(ec2Service, lifecycleManager);
|
||||
order.verify(ec2Service).reserveVpcPrivateIp("us-east-1", "subnet-1", "10.0.1.25");
|
||||
order.verify(lifecycleManager).create(any());
|
||||
order.verify(ec2Service).attachContainerToVpc(
|
||||
"us-east-1", "vpc-1", "subnet-1", "cid-recreated", "10.0.1.25");
|
||||
order.verify(lifecycleManager).startCreated(eq("cid-recreated"), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void startClusterFallsBackToBridgeWithoutNodeIpWhenVpcAttachFailsOnFirstLaunch() {
|
||||
when(portAllocator.allocate(6440, 6499)).thenReturn(6440);
|
||||
when(lifecycleManager.create(any())).thenReturn("cid-vpc", "cid-bridge");
|
||||
when(lifecycleManager.startCreated(eq("cid-bridge"), any()))
|
||||
.thenReturn(new ContainerInfo("cid-bridge", Map.of()));
|
||||
when(ec2Service.allocateVpcPrivateIp("us-east-1", "subnet-1"))
|
||||
.thenReturn(Optional.of("10.0.1.25"));
|
||||
when(ec2Service.attachContainerToVpc("us-east-1", "vpc-1", "subnet-1", "cid-vpc", "10.0.1.25"))
|
||||
.thenReturn(Optional.empty());
|
||||
|
||||
Cluster cluster = vpcCluster("first-launch-fallback", "vpc-1", List.of("subnet-1"));
|
||||
manager.startCluster(cluster);
|
||||
|
||||
assertNull(cluster.getNodePrivateIp());
|
||||
assertEquals("cid-bridge", cluster.getContainerId());
|
||||
verify(ec2Service).releaseVpcPrivateIp("us-east-1", "subnet-1", "10.0.1.25");
|
||||
verify(lifecycleManager).removeIfExistsStrict("floci-aws-eks-first-launch-fallback", true);
|
||||
verify(lifecycleManager, Mockito.times(2)).create(any());
|
||||
verify(lifecycleManager).startCreated(eq("cid-bridge"), any());
|
||||
verify(lifecycleManager, never()).startCreated(eq("cid-vpc"), any());
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
ArgumentCaptor<List<String>> cmdCaptor = ArgumentCaptor.forClass(List.class);
|
||||
verify(builder, Mockito.times(2)).withCmd(cmdCaptor.capture());
|
||||
List<String> firstLaunch = cmdCaptor.getAllValues().get(0);
|
||||
assertTrue(firstLaunch.contains("--node-ip=10.0.1.25"));
|
||||
// The bridge container keeps the shared-mounts entrypoint, so its command is wrapped the same way.
|
||||
assertEquals(firstLaunch.stream().filter(a -> !a.startsWith("--node-ip")).toList(), cmdCaptor.getValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
void restoreClusterFailsStartAndRetainsNodeIpWhenVpcAttachFails() {
|
||||
when(lifecycleManager.findByName("floci-eks-restore-attach-fail")).thenReturn(Optional.empty());
|
||||
when(portAllocator.allocate(6440, 6499)).thenReturn(6440);
|
||||
when(lifecycleManager.create(any())).thenReturn("cid-recreated");
|
||||
when(ec2Service.reserveVpcPrivateIp("us-east-1", "subnet-1", "10.0.1.25"))
|
||||
.thenReturn(true);
|
||||
when(ec2Service.attachContainerToVpc(
|
||||
"us-east-1", "vpc-1", "subnet-1", "cid-recreated", "10.0.1.25"))
|
||||
.thenReturn(Optional.empty());
|
||||
|
||||
Cluster cluster = vpcCluster("restore-attach-fail", "vpc-1", List.of("subnet-1"));
|
||||
cluster.setNodePrivateIp("10.0.1.25");
|
||||
|
||||
assertThrows(IllegalStateException.class, () -> manager.restoreCluster(cluster));
|
||||
|
||||
assertEquals("10.0.1.25", cluster.getNodePrivateIp());
|
||||
verify(ec2Service, never()).releaseVpcPrivateIp(anyString(), anyString(), anyString());
|
||||
verify(lifecycleManager).removeIfExistsStrict("floci-aws-eks-restore-attach-fail", true);
|
||||
verify(lifecycleManager, Mockito.times(1)).create(any());
|
||||
verify(lifecycleManager, never()).startCreated(anyString(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void restoreClusterAdoptingSurvivingContainerReservesPersistedNodeIp() {
|
||||
when(lifecycleManager.findByName("floci-eks-survivor"))
|
||||
.thenReturn(Optional.of(survivingContainer("cid-survivor")));
|
||||
when(lifecycleManager.adopt(eq("cid-survivor"), eq(List.of(6443)), any()))
|
||||
.thenReturn(new ContainerInfo("cid-survivor", Map.of(), Map.of(6443, 6440)));
|
||||
|
||||
Cluster cluster = vpcCluster("survivor", "vpc-1", List.of("subnet-1"));
|
||||
cluster.setNodePrivateIp("10.0.1.25");
|
||||
|
||||
manager.restoreCluster(cluster);
|
||||
|
||||
verify(ec2Service).reserveVpcPrivateIp("us-east-1", "subnet-1", "10.0.1.25");
|
||||
verify(lifecycleManager, never()).create(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void replaceClusterContainerDetachesOldContainerReservesIpAndAttachesNewContainerBeforeStart() {
|
||||
when(lifecycleManager.create(any())).thenReturn("cid-new");
|
||||
when(lifecycleManager.startCreated(eq("cid-new"), any()))
|
||||
.thenReturn(new ContainerInfo("cid-new", Map.of()));
|
||||
when(ec2Service.reserveVpcPrivateIp("us-east-1", "subnet-1", "10.0.1.25"))
|
||||
.thenReturn(true);
|
||||
|
||||
Cluster cluster = vpcCluster("replace-cluster", "vpc-1", List.of("subnet-1"));
|
||||
cluster.setDockerName("floci-eks-replace-cluster");
|
||||
cluster.setContainerId("cid-old");
|
||||
cluster.setHostPort(6441);
|
||||
cluster.setNodeInstanceType("t3.medium");
|
||||
cluster.setNodePrivateIp("10.0.1.25");
|
||||
|
||||
assertTrue(manager.restartForNodeCapacity(cluster, "m5.large"));
|
||||
|
||||
assertEquals("cid-new", cluster.getContainerId());
|
||||
assertEquals("10.0.1.25", cluster.getNodePrivateIp());
|
||||
verify(ec2Service, never()).allocateVpcPrivateIp(anyString(), anyString());
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
ArgumentCaptor<List<String>> cmdCaptor = ArgumentCaptor.forClass(List.class);
|
||||
verify(builder).withCmd(cmdCaptor.capture());
|
||||
assertTrue(cmdCaptor.getValue().contains("--node-ip=10.0.1.25"));
|
||||
|
||||
InOrder order = Mockito.inOrder(dockerClient, ec2Service, lifecycleManager);
|
||||
order.verify(dockerClient).stopContainerCmd("cid-old");
|
||||
order.verify(ec2Service).detachContainerFromVpc("us-east-1", "vpc-1", "cid-old");
|
||||
order.verify(ec2Service).reserveVpcPrivateIp("us-east-1", "subnet-1", "10.0.1.25");
|
||||
order.verify(lifecycleManager).create(any());
|
||||
order.verify(ec2Service).attachContainerToVpc("us-east-1", "vpc-1", "subnet-1", "cid-new", "10.0.1.25");
|
||||
order.verify(lifecycleManager).startCreated(eq("cid-new"), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void replaceClusterContainerRollbackReattachesOldContainerWhenReplacementFails() {
|
||||
when(lifecycleManager.create(any())).thenReturn("cid-new");
|
||||
when(lifecycleManager.startCreated(eq("cid-new"), any()))
|
||||
.thenThrow(new RuntimeException("replacement failed"));
|
||||
when(lifecycleManager.adopt(eq("cid-old"), eq(List.of(6443)), any()))
|
||||
.thenReturn(new ContainerInfo("cid-old", Map.of(), Map.of(6443, 6441)));
|
||||
when(ec2Service.reserveVpcPrivateIp("us-east-1", "subnet-1", "10.0.1.25"))
|
||||
.thenReturn(true);
|
||||
|
||||
Cluster cluster = vpcCluster("rollback-cluster", "vpc-1", List.of("subnet-1"));
|
||||
cluster.setDockerName("floci-eks-rollback-cluster");
|
||||
cluster.setContainerId("cid-old");
|
||||
cluster.setHostPort(6441);
|
||||
cluster.setNodeInstanceType("t3.medium");
|
||||
cluster.setNodePrivateIp("10.0.1.25");
|
||||
|
||||
assertFalse(manager.restartForNodeCapacity(cluster, "m5.large"));
|
||||
|
||||
assertEquals("cid-old", cluster.getContainerId());
|
||||
assertEquals("10.0.1.25", cluster.getNodePrivateIp());
|
||||
verify(ec2Service).detachContainerFromVpc("us-east-1", "vpc-1", "cid-old");
|
||||
verify(ec2Service).attachContainerToVpc("us-east-1", "vpc-1", "subnet-1", "cid-old", "10.0.1.25");
|
||||
}
|
||||
|
||||
@Test
|
||||
void clusterCopyPreservesNodePrivateIpAndEksControllerStripsItFromWireResponses() throws Exception {
|
||||
Cluster cluster = vpcCluster("wire-cluster", "vpc-1", List.of("subnet-1"));
|
||||
cluster.setNodePrivateIp("10.0.1.25");
|
||||
|
||||
Cluster copy = cluster.copy();
|
||||
assertEquals("10.0.1.25", copy.getNodePrivateIp());
|
||||
|
||||
ObjectMapper mapper = new ObjectMapper().findAndRegisterModules();
|
||||
String persistedJson = mapper.writeValueAsString(cluster);
|
||||
assertTrue(persistedJson.contains("\"nodePrivateIp\":\"10.0.1.25\""));
|
||||
Cluster deserialized = mapper.readValue(persistedJson, Cluster.class);
|
||||
assertEquals("10.0.1.25", deserialized.getNodePrivateIp());
|
||||
|
||||
EksService eksService = Mockito.mock(EksService.class);
|
||||
when(eksService.createCluster(any())).thenReturn(cluster);
|
||||
when(eksService.requireClusterInRequestRegion("wire-cluster")).thenReturn(cluster);
|
||||
when(eksService.deleteClusterInRequestRegion("wire-cluster")).thenReturn(cluster);
|
||||
|
||||
EksController controller = new EksController(
|
||||
eksService,
|
||||
Mockito.mock(EksAccessEntryService.class),
|
||||
Mockito.mock(EksPodIdentityAssociationService.class),
|
||||
Mockito.mock(EksAddonService.class));
|
||||
|
||||
for (Response response : List.of(
|
||||
controller.createCluster(new CreateClusterRequest()),
|
||||
controller.describeCluster("wire-cluster"),
|
||||
controller.deleteCluster("wire-cluster"))) {
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, Object> body = (Map<String, Object>) response.getEntity();
|
||||
Cluster wireCluster = (Cluster) body.get("cluster");
|
||||
assertNull(wireCluster.getNodePrivateIp());
|
||||
String wireJson = mapper.writeValueAsString(wireCluster);
|
||||
assertFalse(wireJson.contains("nodePrivateIp"));
|
||||
}
|
||||
assertEquals("10.0.1.25", cluster.getNodePrivateIp());
|
||||
}
|
||||
|
||||
@Test
|
||||
void ec2ServiceReserveVpcPrivateIpAndDetachContainerFromVpcDelegateToVpcNetworkManager() {
|
||||
EmulatorConfig.Ec2ServiceConfig ec2Config = Mockito.mock(EmulatorConfig.Ec2ServiceConfig.class);
|
||||
when(config.services().ec2()).thenReturn(ec2Config);
|
||||
StorageFactory storageFactory = Mockito.mock(StorageFactory.class);
|
||||
when(storageFactory.create(anyString(), anyString(), any()))
|
||||
.thenAnswer(inv -> AccountAwareStorageBackend.inMemory("000000000000"));
|
||||
VpcNetworkManager vpcNetworkManager = Mockito.mock(VpcNetworkManager.class);
|
||||
Ec2Service realEc2Service = new Ec2Service(
|
||||
config,
|
||||
Mockito.mock(Ec2ContainerManager.class),
|
||||
Mockito.mock(Ec2PortForwardManager.class),
|
||||
Mockito.mock(AmiImageResolver.class),
|
||||
Mockito.mock(Ec2ImageCatalog.class),
|
||||
new Ec2InstanceTypeCatalog(),
|
||||
storageFactory,
|
||||
null,
|
||||
vpcNetworkManager,
|
||||
null,
|
||||
null,
|
||||
null);
|
||||
|
||||
when(vpcNetworkManager.reservePrivateIp("us-east-1", "subnet-1", "10.0.1.25"))
|
||||
.thenReturn(true);
|
||||
when(vpcNetworkManager.reservePrivateIp("us-east-1", "subnet-1", "10.0.1.99"))
|
||||
.thenReturn(false);
|
||||
|
||||
assertTrue(realEc2Service.reserveVpcPrivateIp("us-east-1", "subnet-1", "10.0.1.25"));
|
||||
assertFalse(realEc2Service.reserveVpcPrivateIp("us-east-1", "subnet-1", "10.0.1.99"));
|
||||
verify(vpcNetworkManager).reservePrivateIp("us-east-1", "subnet-1", "10.0.1.25");
|
||||
verify(vpcNetworkManager).reservePrivateIp("us-east-1", "subnet-1", "10.0.1.99");
|
||||
|
||||
// Reserved IP is recorded in containerPrivateIps so allocateVpcPrivateIp skips it until released.
|
||||
when(vpcNetworkManager.allocatePrivateIp("us-east-1", "subnet-1"))
|
||||
.thenReturn(Optional.of("10.0.1.25"), Optional.of("10.0.1.26"));
|
||||
assertEquals(Optional.of("10.0.1.26"), realEc2Service.allocateVpcPrivateIp("us-east-1", "subnet-1"));
|
||||
verify(vpcNetworkManager).releasePrivateIp("us-east-1", "subnet-1", "10.0.1.25");
|
||||
|
||||
realEc2Service.detachContainerFromVpc("us-east-1", "vpc-1", "cid-1");
|
||||
verify(vpcNetworkManager).detach("us-east-1", "vpc-1", "cid-1");
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user