mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
feat(eks): join EC2 instances to a cluster as nodes (#5091)
Support joining real EC2 instances to an EKS cluster as Kubernetes nodes. Inspect instance user data during RunInstances for bootstrap scripts or nodeadm YAML targeting an EKS cluster, recording pending joins and reconciling node registration asynchronously via the readiness poller. Ensure RunInstances returns without blocking on kubectl or shared locks, and guard storage mutations under the deletion lock so deleted clusters cannot be resurrected. Scope restoration tracking per account. Support AL2023 MIME multipart nodeadm configurations, and share the in-use IP check and cursor loop between subnet and subnetless launches. Update node metadata derivation to match AWS conventions, using instance private DNS names for node names and aws:///<az>/<instance-id> for provider IDs, with topology and instance-type labels.
This commit is contained in:
1 parent
0d4b8cda74
commit
6fc957a3b4
11 files changed
+1160
-28
No files matched your search
@@ -544,6 +544,31 @@ Callers requiring dynamic volume provisioning can install a driver (such as the
|
||||
|
||||
For local testing workflows that rely on automatic volume binding without a CSI driver, set `floci.services.eks.default-storage-class: true` (or `FLOCI_SERVICES_EKS_DEFAULT_STORAGE_CLASS=true`) to retain k3s's bundled `local-path` provisioner and default StorageClass.
|
||||
|
||||
## Joining EC2 instances as cluster nodes
|
||||
|
||||
Floci allows EC2 instances to join an EKS cluster as Kubernetes worker nodes. Launching an instance via `RunInstances` with user data targeting a cluster automatically registers a matching Kubernetes node.
|
||||
|
||||
### Join mechanisms
|
||||
|
||||
Supported user data formats include:
|
||||
- Amazon Linux 2 `/etc/eks/bootstrap.sh <cluster-name>` commands (plain text, base64, or gzipped base64).
|
||||
- Amazon Linux 2023 `nodeadm` YAML documents or MIME multipart payloads (`NodeConfig` containing `spec.cluster.name`).
|
||||
|
||||
On AWS, EC2 does not fail instance launches if a target cluster is missing. Floci mirrors this: if the target cluster does not exist or node registration fails, Floci logs a warning and allows the launch to proceed.
|
||||
|
||||
### Node metadata and AWS outcome alignment
|
||||
|
||||
When an instance joins a cluster, Floci registers a Kubernetes `Node` matching AWS conventions:
|
||||
- **Node name**: Uses the instance's private DNS name (`privateDnsName`), matching AWS EKS conventions.
|
||||
- **Provider ID**: Set to `spec.providerID: aws:///<availability-zone>/<instance-id>`.
|
||||
- **Labels & Status**: Includes topology and instance-type labels, ready status, internal IP, and catalog capacity.
|
||||
- **EC2 persistence**: The instance remains an authentic EC2 instance reported by `DescribeInstances`.
|
||||
|
||||
### Differences and limitations
|
||||
|
||||
- Floci registers the `Node` directly in the control plane with matching provider ID, labels, and ready status.
|
||||
- Node cleanup on termination is handled in part two; an instance can belong to at most one cluster at a time.
|
||||
|
||||
## Configuration
|
||||
|
||||
| Variable | Default | Description |
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
package io.github.hectorvent.floci.services.ec2;
|
||||
|
||||
import io.github.hectorvent.floci.services.ec2.model.Instance;
|
||||
|
||||
/**
|
||||
* Listener notified when an EC2 instance is launched.
|
||||
*/
|
||||
public interface Ec2InstanceLaunchListener {
|
||||
|
||||
void onInstanceLaunched(String accountId, String region, Instance instance);
|
||||
}
|
||||
@@ -287,6 +287,8 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
|
||||
private final Ec2VolumeBlockDeviceManager volumeBlockDeviceManager;
|
||||
private jakarta.enterprise.inject.Instance<VpcRouteTableListener> routeTableListenersInstance;
|
||||
private final List<VpcRouteTableListener> routeTableListeners = new CopyOnWriteArrayList<>();
|
||||
private jakarta.enterprise.inject.Instance<Ec2InstanceLaunchListener> instanceLaunchListenersInstance;
|
||||
private final List<Ec2InstanceLaunchListener> instanceLaunchListeners = new CopyOnWriteArrayList<>();
|
||||
|
||||
public void addRouteTableListener(VpcRouteTableListener listener) {
|
||||
if (listener != null && !this.routeTableListeners.contains(listener)) {
|
||||
@@ -301,6 +303,27 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
|
||||
}
|
||||
}
|
||||
|
||||
public void addInstanceLaunchListener(Ec2InstanceLaunchListener listener) {
|
||||
if (listener != null && !this.instanceLaunchListeners.contains(listener)) {
|
||||
this.instanceLaunchListeners.add(listener);
|
||||
}
|
||||
}
|
||||
|
||||
private void notifyInstanceLaunched(String accountId, String region, Instance instance) {
|
||||
Set<Ec2InstanceLaunchListener> listeners = new LinkedHashSet<>(instanceLaunchListeners);
|
||||
if (instanceLaunchListenersInstance != null && !instanceLaunchListenersInstance.isUnsatisfied()) {
|
||||
instanceLaunchListenersInstance.forEach(listeners::add);
|
||||
}
|
||||
for (Ec2InstanceLaunchListener listener : listeners) {
|
||||
try {
|
||||
listener.onInstanceLaunched(accountId, region, instance);
|
||||
} catch (Exception e) {
|
||||
LOG.warnv("Error notifying launch listener for instance {0}: {1}",
|
||||
instance.getInstanceId(), e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public boolean attachContainerToVpc(String region, String vpcId, String containerId) {
|
||||
if (vpcNetworkManager != null) {
|
||||
return vpcNetworkManager.attachContainer(region, vpcId, containerId);
|
||||
@@ -395,12 +418,14 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
|
||||
VpcNetworkManager vpcNetworkManager, IamService iamService,
|
||||
jakarta.enterprise.inject.Instance<ClusterNodeInstanceProvider> clusterNodeInstanceProviders,
|
||||
Ec2VolumeBlockDeviceManager volumeBlockDeviceManager,
|
||||
jakarta.enterprise.inject.Instance<VpcRouteTableListener> routeTableListenersInstance) {
|
||||
jakarta.enterprise.inject.Instance<VpcRouteTableListener> routeTableListenersInstance,
|
||||
jakarta.enterprise.inject.Instance<Ec2InstanceLaunchListener> instanceLaunchListenersInstance) {
|
||||
this(config, containerManager, portForwardManager, amiImageResolver, imageCatalog,
|
||||
instanceTypeCatalog, storageFactory, requestContextInstance, iamService, volumeBlockDeviceManager);
|
||||
this.vpcNetworkManager = vpcNetworkManager;
|
||||
this.clusterNodeInstanceProviders = clusterNodeInstanceProviders;
|
||||
this.routeTableListenersInstance = routeTableListenersInstance;
|
||||
this.instanceLaunchListenersInstance = instanceLaunchListenersInstance;
|
||||
}
|
||||
|
||||
public Ec2Service(EmulatorConfig config, Ec2ContainerManager containerManager,
|
||||
@@ -3243,6 +3268,10 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
|
||||
}
|
||||
}
|
||||
|
||||
for (Instance inst : launched) {
|
||||
notifyInstanceLaunched(callerAccountId(), region, inst);
|
||||
}
|
||||
|
||||
return reservation;
|
||||
}
|
||||
|
||||
@@ -3496,10 +3525,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
|
||||
return allocated.get();
|
||||
}
|
||||
}
|
||||
if (subnetId == null) {
|
||||
return "172.31.0." + (10 + new Random().nextInt(200));
|
||||
}
|
||||
Cidr4 cidr = subnets.get(key(region, subnetId))
|
||||
Cidr4 cidr = (subnetId != null ? subnets.get(key(region, subnetId)) : Optional.<Subnet>empty())
|
||||
.flatMap(subnet -> Cidr4.parse(subnet.getCidrBlock()))
|
||||
.or(() -> Cidr4.parse(SYNTHETIC_FALLBACK_CIDR))
|
||||
.orElseThrow();
|
||||
@@ -3509,7 +3535,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
|
||||
if (last < first) {
|
||||
throw insufficientFreeAddresses(subnetId);
|
||||
}
|
||||
String cursorKey = key(region, subnetId);
|
||||
String cursorKey = key(region, subnetId != null ? subnetId : "subnetless");
|
||||
synchronized (privateIpAllocationLock) {
|
||||
// The addresses persisted resources already hold, so a restart, which forgets the
|
||||
// cursor, never hands out an address that is still in use.
|
||||
@@ -3540,7 +3566,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
|
||||
String regionPrefix = region + "::";
|
||||
Set<String> inUse = new HashSet<>();
|
||||
for (NetworkInterface ni : networkInterfaces.scan(k -> k.startsWith(regionPrefix))) {
|
||||
if (!subnetId.equals(ni.getSubnetId())) {
|
||||
if (!Objects.equals(subnetId, ni.getSubnetId())) {
|
||||
continue;
|
||||
}
|
||||
addIfSet(inUse, ni.getPrivateIpAddress());
|
||||
@@ -3553,17 +3579,17 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
|
||||
if ("terminated".equals(state)) {
|
||||
continue;
|
||||
}
|
||||
if (subnetId.equals(instance.getSubnetId())) {
|
||||
if (Objects.equals(subnetId, instance.getSubnetId())) {
|
||||
addIfSet(inUse, instance.getPrivateIpAddress());
|
||||
}
|
||||
for (InstanceNetworkInterface ni : nullToEmpty(instance.getNetworkInterfaces())) {
|
||||
if (subnetId.equals(ni.getSubnetId())) {
|
||||
if (Objects.equals(subnetId, ni.getSubnetId())) {
|
||||
addIfSet(inUse, ni.getPrivateIpAddress());
|
||||
}
|
||||
}
|
||||
}
|
||||
for (NatGateway natGateway : natGateways.scan(k -> k.startsWith(regionPrefix))) {
|
||||
if (!subnetId.equals(natGateway.getSubnetId()) || "deleted".equals(natGateway.getState())) {
|
||||
if (!Objects.equals(subnetId, natGateway.getSubnetId()) || "deleted".equals(natGateway.getState())) {
|
||||
continue;
|
||||
}
|
||||
for (NatGatewayAddress address : nullToEmpty(natGateway.getNatGatewayAddresses())) {
|
||||
@@ -5822,6 +5848,10 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
|
||||
return findExternalInstance(accountId, region, instanceId);
|
||||
}
|
||||
|
||||
public Optional<Instance> getInstance(String region, String instanceId) {
|
||||
return instances.get(key(region, instanceId));
|
||||
}
|
||||
|
||||
public Instance findInstanceById(String instanceId) {
|
||||
return findInstanceById(callerAccountId(), instanceId);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,183 @@
|
||||
package io.github.hectorvent.floci.services.eks;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
|
||||
import org.apache.james.mime4j.dom.Entity;
|
||||
import org.apache.james.mime4j.dom.Message;
|
||||
import org.apache.james.mime4j.dom.Multipart;
|
||||
import org.apache.james.mime4j.dom.SingleBody;
|
||||
import org.apache.james.mime4j.message.DefaultMessageBuilder;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* Parser for detecting EKS cluster join requests from EC2 instance user data payloads.
|
||||
*/
|
||||
public final class EksBootstrapUserData {
|
||||
|
||||
private static final ObjectMapper YAML_MAPPER = new ObjectMapper(new YAMLFactory());
|
||||
|
||||
private static final Set<String> FLAGS_WITH_ARG = Set.of(
|
||||
"--b64-cluster-ca", "--apiserver-endpoint", "--kubelet-extra-args",
|
||||
"--container-runtime", "--dns-cluster-ip", "--ip-family",
|
||||
"--service-ipv6-cidr", "--use-max-pods", "--aws-api-retry-attempts");
|
||||
|
||||
private EksBootstrapUserData() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Extracts an EKS cluster name from an instance user data string if present.
|
||||
* Supports Amazon Linux 2 bootstrap scripts and Amazon Linux 2023 nodeadm NodeConfig YAML or MIME multipart.
|
||||
*
|
||||
* @param userData the decoded user data payload
|
||||
* @return the cluster name if found, or empty otherwise
|
||||
*/
|
||||
public static Optional<String> extractClusterName(String userData) {
|
||||
if (userData == null || userData.isBlank()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
return extractFromBootstrapScript(userData).or(() -> extractFromNodeadm(userData));
|
||||
}
|
||||
|
||||
private static Optional<String> extractFromBootstrapScript(String userData) {
|
||||
for (String line : userData.split("\n")) {
|
||||
String trimmed = line.trim();
|
||||
if (trimmed.startsWith("#") && !trimmed.startsWith("#!")) {
|
||||
continue;
|
||||
}
|
||||
int idx = trimmed.indexOf("bootstrap.sh");
|
||||
if (idx >= 0) {
|
||||
List<String> tokens = tokenize(trimmed.substring(idx + "bootstrap.sh".length()).trim());
|
||||
for (int i = 0; i < tokens.size(); i++) {
|
||||
String tok = tokens.get(i);
|
||||
if (tok.startsWith("--") && !tok.contains("=") && FLAGS_WITH_ARG.contains(tok) && i + 1 < tokens.size()) {
|
||||
i++;
|
||||
} else if (!tok.isEmpty()) {
|
||||
String name = stripQuotes(tok);
|
||||
if (!name.isEmpty() && !name.startsWith("-")) {
|
||||
return Optional.of(name);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
private static Optional<String> extractFromNodeadm(String userData) {
|
||||
if (!userData.contains("NodeConfig") && !userData.contains("node.eks.aws")) {
|
||||
return Optional.empty();
|
||||
}
|
||||
if (userData.contains("Content-Type:") || userData.contains("MIME-Version:") || userData.contains("multipart/")) {
|
||||
Optional<String> mimeExtracted = extractFromMime(userData);
|
||||
if (mimeExtracted.isPresent()) {
|
||||
return mimeExtracted;
|
||||
}
|
||||
}
|
||||
return parseNodeConfigYaml(userData);
|
||||
}
|
||||
|
||||
private static Optional<String> extractFromMime(String userData) {
|
||||
try {
|
||||
Message message = new DefaultMessageBuilder().parseMessage(
|
||||
new ByteArrayInputStream(userData.getBytes(StandardCharsets.UTF_8)));
|
||||
return extractNodeConfigFromEntity(message);
|
||||
} catch (Exception ignored) {
|
||||
// Malformed MIME structure in user data is treated as non-multipart content.
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
|
||||
private static Optional<String> extractNodeConfigFromEntity(Entity entity) {
|
||||
if (entity == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
if (entity.getBody() instanceof Multipart multipart) {
|
||||
for (Entity part : multipart.getBodyParts()) {
|
||||
Optional<String> found = extractNodeConfigFromEntity(part);
|
||||
if (found.isPresent()) {
|
||||
return found;
|
||||
}
|
||||
}
|
||||
} else if (entity.getBody() instanceof SingleBody singleBody) {
|
||||
try {
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
singleBody.writeTo(out);
|
||||
String content = out.toString(StandardCharsets.UTF_8);
|
||||
if (content.contains("NodeConfig") || (entity.getMimeType() != null && entity.getMimeType().contains("node.eks.aws"))) {
|
||||
return parseNodeConfigYaml(content);
|
||||
}
|
||||
} catch (Exception ignored) {
|
||||
// Ignore unreadable or malformed MIME body parts and continue scanning.
|
||||
}
|
||||
}
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
private static Optional<String> parseNodeConfigYaml(String yaml) {
|
||||
try {
|
||||
Iterator<JsonNode> it = YAML_MAPPER.readValues(
|
||||
YAML_MAPPER.getFactory().createParser(yaml), JsonNode.class);
|
||||
while (it.hasNext()) {
|
||||
JsonNode root = it.next();
|
||||
if (root != null && "NodeConfig".equals(root.path("kind").asText())) {
|
||||
String name = root.path("spec").path("cluster").path("name").asText();
|
||||
if (name != null && !name.isBlank()) {
|
||||
return Optional.of(name.strip());
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (Exception ignored) {
|
||||
// Non-YAML or invalid NodeConfig user data is safely ignored.
|
||||
}
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
private static String stripQuotes(String s) {
|
||||
if (s == null) {
|
||||
return "";
|
||||
}
|
||||
String res = s.trim();
|
||||
boolean quoted = (res.startsWith("\"") && res.endsWith("\"")) || (res.startsWith("'") && res.endsWith("'"));
|
||||
return (quoted && res.length() >= 2) ? res.substring(1, res.length() - 1).trim() : res;
|
||||
}
|
||||
|
||||
private static List<String> tokenize(String cmd) {
|
||||
List<String> list = new ArrayList<>();
|
||||
StringBuilder cur = new StringBuilder();
|
||||
boolean inQuotes = false;
|
||||
char q = 0;
|
||||
for (int i = 0; i < cmd.length(); i++) {
|
||||
char c = cmd.charAt(i);
|
||||
if (inQuotes) {
|
||||
if (c == q) {
|
||||
inQuotes = false;
|
||||
} else {
|
||||
cur.append(c);
|
||||
}
|
||||
} else if (c == '\'' || c == '"') {
|
||||
inQuotes = true;
|
||||
q = c;
|
||||
} else if (Character.isWhitespace(c)) {
|
||||
if (!cur.isEmpty()) {
|
||||
list.add(cur.toString());
|
||||
cur.setLength(0);
|
||||
}
|
||||
} else {
|
||||
cur.append(c);
|
||||
}
|
||||
}
|
||||
if (!cur.isEmpty()) {
|
||||
list.add(cur.toString());
|
||||
}
|
||||
return list;
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import com.github.dockerjava.api.model.Info;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.config.FlociCertificateAuthority;
|
||||
import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.AwsRegions;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.common.dns.DnsAnswer;
|
||||
@@ -169,6 +170,7 @@ public class EksClusterManager
|
||||
private final ContainerLogStreamer logStreamer;
|
||||
private final Ec2InstanceTypeCatalog instanceTypeCatalog = new Ec2InstanceTypeCatalog();
|
||||
private final Map<String, ClusterNodeRecord> clusterNodeInstances = new ConcurrentHashMap<>();
|
||||
private final Map<String, Map<String, Instance>> joinedClusterInstances = new ConcurrentHashMap<>();
|
||||
private final Map<String, Closeable> clusterLogHandles = new ConcurrentHashMap<>();
|
||||
private final List<Consumer<Instance>> nodeRegistrationListeners = new CopyOnWriteArrayList<>();
|
||||
private final Map<String, Cluster> activeClusters = new ConcurrentHashMap<>();
|
||||
@@ -243,6 +245,16 @@ public class EksClusterManager
|
||||
}
|
||||
}
|
||||
}
|
||||
for (Map<String, Instance> map : joinedClusterInstances.values()) {
|
||||
for (Instance inst : map.values()) {
|
||||
if (inst != null && inst.getPrivateIpAddress() != null && !inst.getPrivateIpAddress().isBlank()) {
|
||||
String nodeName = deriveInstanceNodeName(inst, inst.getRegion()).toLowerCase(Locale.ROOT);
|
||||
if (name.equals(nodeName)) {
|
||||
return Optional.of(DnsAnswer.records(List.of(inst.getPrivateIpAddress()), DnsAnswer.DEFAULT_TTL_SECONDS));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
@@ -266,6 +278,13 @@ public class EksClusterManager
|
||||
}
|
||||
}
|
||||
}
|
||||
for (Map<String, Instance> map : joinedClusterInstances.values()) {
|
||||
for (Instance inst : map.values()) {
|
||||
if (inst != null && vpcId.equals(inst.getVpcId())) {
|
||||
rules.add(DnsForwardingRule.system(deriveInstanceNodeName(inst, inst.getRegion())));
|
||||
}
|
||||
}
|
||||
}
|
||||
return List.copyOf(rules);
|
||||
}
|
||||
|
||||
@@ -963,6 +982,8 @@ public class EksClusterManager
|
||||
|
||||
pruneLegacyClusterNodes(cluster, containerId);
|
||||
|
||||
registerAllJoinedNodes(cluster, containerId);
|
||||
|
||||
LOG.infov("Finalized EKS cluster {0} with CA data extracted", cluster.getName());
|
||||
} catch (Exception e) {
|
||||
LOG.warnv("Could not extract kubeconfig for cluster {0}: {1}",
|
||||
@@ -982,7 +1003,7 @@ public class EksClusterManager
|
||||
if (parts.length >= 1 && !parts[0].isBlank()) {
|
||||
String node = parts[0];
|
||||
String readyStatus = parts.length > 1 ? parts[1] : "";
|
||||
if (!node.equals(expectedNodeName) && !"True".equalsIgnoreCase(readyStatus)) {
|
||||
if (!node.equals(expectedNodeName) && !isJoinedNode(cluster, node) && !"True".equalsIgnoreCase(readyStatus)) {
|
||||
execInContainerForResult(containerId,
|
||||
new String[]{"kubectl", "delete", "node", node}, 10);
|
||||
LOG.infov("Removed stale legacy node {0} from EKS cluster {1}", node, cluster.getName());
|
||||
@@ -2468,6 +2489,7 @@ public class EksClusterManager
|
||||
programmedClusterRoutes.remove(clusterKey);
|
||||
}
|
||||
forgetClusterNodeVpcs(clusterKey);
|
||||
joinedClusterInstances.remove(clusterKey);
|
||||
ClusterNodeRecord record = clusterNodeInstances.remove(clusterKey);
|
||||
Instance nodeInstance = record != null ? record.instance() : null;
|
||||
if (metadataServer != null && nodeInstance != null) {
|
||||
@@ -2822,6 +2844,192 @@ public class EksClusterManager
|
||||
.toList();
|
||||
}
|
||||
|
||||
private String resolveInstanceRegion(Instance instance, String region) {
|
||||
if (instance != null && instance.getRegion() != null && !instance.getRegion().isBlank()) {
|
||||
return instance.getRegion();
|
||||
}
|
||||
return (region != null && !region.isBlank()) ? region
|
||||
: (regionResolver != null && regionResolver.getDefaultRegion() != null
|
||||
? regionResolver.getDefaultRegion() : "us-east-1"); // partition-literal: fallback for instance region
|
||||
}
|
||||
|
||||
String deriveInstanceNodeProviderId(Instance instance, String region) {
|
||||
String safeRegion = resolveInstanceRegion(instance, region);
|
||||
String az = (instance != null && instance.getPlacement() != null
|
||||
&& instance.getPlacement().getAvailabilityZone() != null)
|
||||
? instance.getPlacement().getAvailabilityZone() : safeRegion + "a";
|
||||
return "aws:///" + az + "/" + (instance != null && instance.getInstanceId() != null ? instance.getInstanceId() : "i-00000000000000000");
|
||||
}
|
||||
|
||||
String deriveInstanceNodeName(Instance instance, String region) {
|
||||
if (instance != null && instance.getPrivateDnsName() != null && !instance.getPrivateDnsName().isBlank()) {
|
||||
return instance.getPrivateDnsName();
|
||||
}
|
||||
String id = instance != null && instance.getInstanceId() != null ? instance.getInstanceId() : "i-00000000000000000";
|
||||
return id + "." + deriveClusterNodePrivateDnsDomain(resolveInstanceRegion(instance, region));
|
||||
}
|
||||
|
||||
void joinInstance(Cluster cluster, Instance instance) {
|
||||
if (cluster == null || instance == null) {
|
||||
return;
|
||||
}
|
||||
String clusterKey = clusterResourceName(cluster);
|
||||
synchronized (joinedClusterInstances) {
|
||||
for (Map.Entry<String, Map<String, Instance>> entry : joinedClusterInstances.entrySet()) {
|
||||
if (!entry.getKey().equals(clusterKey) && entry.getValue().containsKey(instance.getInstanceId())) {
|
||||
throw new AwsException("InvalidParameterException", "Instance " + instance.getInstanceId()
|
||||
+ " is already joined to cluster " + entry.getKey(), 400);
|
||||
}
|
||||
}
|
||||
Map<String, Instance> current = joinedClusterInstances.get(clusterKey);
|
||||
if (current != null && current.containsKey(instance.getInstanceId())) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
String containerId = cluster.getContainerId();
|
||||
if (containerId != null && !containerId.isBlank()) {
|
||||
try {
|
||||
registerNodeInCluster(cluster, containerId, instance);
|
||||
} catch (Exception e) {
|
||||
String region = instance.getRegion() != null ? instance.getRegion() : clusterRegion(cluster);
|
||||
String nodeName = deriveInstanceNodeName(instance, region);
|
||||
try {
|
||||
execInContainerForResult(containerId,
|
||||
new String[]{"kubectl", "delete", "node", nodeName, "--ignore-not-found=true"}, 15);
|
||||
} catch (Exception ignored) {
|
||||
// Node cleanup best effort on join failure
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
synchronized (joinedClusterInstances) {
|
||||
joinedClusterInstances
|
||||
.computeIfAbsent(clusterKey, k -> new ConcurrentHashMap<>())
|
||||
.put(instance.getInstanceId(), instance);
|
||||
}
|
||||
recordJoinedInstanceId(cluster, instance);
|
||||
|
||||
for (Consumer<Instance> listener : nodeRegistrationListeners) {
|
||||
try {
|
||||
listener.accept(instance);
|
||||
} catch (Exception e) {
|
||||
LOG.warnv("Node registration listener failed for joined instance {0} on cluster {1}: {2}",
|
||||
instance.getInstanceId(), cluster.getName(), e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void recordJoinedInstanceId(Cluster cluster, Instance instance) {
|
||||
if (cluster == null || instance == null) {
|
||||
return;
|
||||
}
|
||||
cluster.recordJoinedInstance(instance.getInstanceId(),
|
||||
instance.getRegion() != null ? instance.getRegion() : clusterRegion(cluster));
|
||||
}
|
||||
|
||||
List<Instance> getJoinedInstances(Cluster cluster) {
|
||||
if (cluster == null) {
|
||||
return List.of();
|
||||
}
|
||||
Map<String, Instance> map = joinedClusterInstances.get(clusterResourceName(cluster));
|
||||
return map != null ? new ArrayList<>(map.values()) : List.of();
|
||||
}
|
||||
|
||||
boolean isInstanceJoined(Cluster cluster, String instanceId) {
|
||||
if (cluster == null || instanceId == null) {
|
||||
return false;
|
||||
}
|
||||
Map<String, Instance> map = joinedClusterInstances.get(clusterResourceName(cluster));
|
||||
return map != null && map.containsKey(instanceId);
|
||||
}
|
||||
|
||||
boolean isJoinedNode(Cluster cluster, String nodeName) {
|
||||
if (cluster == null || nodeName == null) {
|
||||
return false;
|
||||
}
|
||||
Map<String, Instance> map = joinedClusterInstances.get(clusterResourceName(cluster));
|
||||
if (map == null) {
|
||||
return false;
|
||||
}
|
||||
for (Instance inst : map.values()) {
|
||||
if (nodeName.equals(deriveInstanceNodeName(inst, inst.getRegion()))) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
void registerAllJoinedNodes(Cluster cluster, String containerId) {
|
||||
Map<String, Instance> map = joinedClusterInstances.get(clusterResourceName(cluster));
|
||||
if (map != null) {
|
||||
for (Instance inst : map.values()) {
|
||||
registerNodeInCluster(cluster, containerId, inst);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void registerNodeInCluster(Cluster cluster, String containerId, Instance instance) {
|
||||
String region = instance.getRegion() != null ? instance.getRegion() : clusterRegion(cluster);
|
||||
String nodeName = deriveInstanceNodeName(instance, region);
|
||||
try {
|
||||
String az = instance.getPlacement() != null && instance.getPlacement().getAvailabilityZone() != null
|
||||
? instance.getPlacement().getAvailabilityZone() : region + "a";
|
||||
String providerId = deriveInstanceNodeProviderId(instance, region);
|
||||
String instanceType = instance.getInstanceType() != null ? instance.getInstanceType() : DEFAULT_NODE_INSTANCE_TYPE;
|
||||
String privateIp = instance.getPrivateIpAddress() != null ? instance.getPrivateIpAddress() : "10.0.0.1";
|
||||
|
||||
CatalogInstanceType catType = instanceTypeCatalog.find(instanceType).orElse(null);
|
||||
String cpu = catType != null ? String.valueOf(catType.vcpu) : "2";
|
||||
String memory = catType != null ? catType.memoryMib + "Mi" : "4Gi";
|
||||
|
||||
String rawArch = instance.getArchitecture();
|
||||
String k8sArch = (rawArch != null && (rawArch.toLowerCase(Locale.ROOT).contains("arm64")
|
||||
|| rawArch.toLowerCase(Locale.ROOT).contains("aarch64"))) ? "arm64" : "amd64";
|
||||
|
||||
String nodeJson = String.format(Locale.ROOT,
|
||||
"{\"apiVersion\":\"v1\",\"kind\":\"Node\",\"metadata\":{\"name\":\"%s\","
|
||||
+ "\"labels\":{\"topology.kubernetes.io/zone\":\"%s\",\"topology.kubernetes.io/region\":\"%s\","
|
||||
+ "\"node.kubernetes.io/instance-type\":\"%s\",\"kubernetes.io/hostname\":\"%s\","
|
||||
+ "\"kubernetes.io/os\":\"linux\",\"kubernetes.io/arch\":\"%s\"}},\"spec\":{\"providerID\":\"%s\"}}",
|
||||
nodeName, az, region, instanceType, nodeName, k8sArch, providerId);
|
||||
|
||||
ContainerExec.Result applyRes = execInContainerForResult(containerId,
|
||||
new String[]{"sh", "-c", "echo '" + nodeJson.replace("'", "'\\''") + "' | kubectl apply -f -"}, 15);
|
||||
if (applyRes.exitCode() != 0) {
|
||||
throw new IllegalStateException("Failed to apply node " + nodeName + " to cluster "
|
||||
+ cluster.getName() + ": " + applyRes.stderr());
|
||||
}
|
||||
|
||||
String statusPatch = String.format(Locale.ROOT,
|
||||
"{\"status\":{\"conditions\":[{\"type\":\"Ready\",\"status\":\"True\","
|
||||
+ "\"reason\":\"KubeletReady\",\"message\":\"kubelet is posting ready status\"}],"
|
||||
+ "\"addresses\":[{\"type\":\"InternalIP\",\"address\":\"%s\"},{\"type\":\"Hostname\",\"address\":\"%s\"}],"
|
||||
+ "\"capacity\":{\"cpu\":\"%s\",\"memory\":\"%s\",\"pods\":\"110\"},"
|
||||
+ "\"allocatable\":{\"cpu\":\"%s\",\"memory\":\"%s\",\"pods\":\"110\"}}}",
|
||||
privateIp, nodeName, cpu, memory, cpu, memory);
|
||||
|
||||
ContainerExec.Result patchRes = execInContainerForResult(containerId,
|
||||
new String[]{"kubectl", "patch", "node", nodeName, "--subresource=status", "--type=merge",
|
||||
"-p", statusPatch}, 15);
|
||||
if (patchRes.exitCode() != 0) {
|
||||
throw new IllegalStateException("Failed to patch status for node " + nodeName + " on cluster "
|
||||
+ cluster.getName() + ": " + patchRes.stderr());
|
||||
}
|
||||
|
||||
LOG.infov("Registered joined instance node {0} ({1}) in cluster {2}",
|
||||
nodeName, providerId, cluster.getName());
|
||||
} catch (Exception e) {
|
||||
LOG.warnv("Failed to register node for instance {0} in cluster {1}: {2}",
|
||||
instance.getInstanceId(), cluster.getName(), e.getMessage());
|
||||
if (e instanceof RuntimeException re) {
|
||||
throw re;
|
||||
}
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
record ContainerIps(String primaryIp, Set<String> allIps) {}
|
||||
|
||||
ContainerIps resolveContainerIps(String containerId) {
|
||||
|
||||
@@ -93,7 +93,8 @@ public class EksController {
|
||||
*/
|
||||
private Cluster toClusterResponse(Cluster cluster) {
|
||||
if (cluster == null || (!cluster.isExplicitVersion() && cluster.getNodeInstanceType() == null
|
||||
&& cluster.getClusterArgs() == null && cluster.getDefaultStorageClass() == null)) {
|
||||
&& cluster.getClusterArgs() == null && cluster.getDefaultStorageClass() == null
|
||||
&& cluster.getJoinedInstanceIds() == null)) {
|
||||
return cluster;
|
||||
}
|
||||
Cluster response = cluster.copy();
|
||||
@@ -101,6 +102,7 @@ public class EksController {
|
||||
response.setNodeInstanceType(null);
|
||||
response.setClusterArgs(null);
|
||||
response.setDefaultStorageClass(null);
|
||||
response.setJoinedInstanceIds(null);
|
||||
return response;
|
||||
}
|
||||
|
||||
|
||||
@@ -11,9 +11,11 @@ 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;
|
||||
import io.github.hectorvent.floci.services.ec2.Ec2InstanceLaunchListener;
|
||||
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.Instance;
|
||||
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;
|
||||
@@ -60,6 +62,7 @@ import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.Executors;
|
||||
@@ -74,7 +77,7 @@ import io.github.hectorvent.floci.core.resource.ResourceProvider;
|
||||
import io.github.hectorvent.floci.core.resource.SupportedResourceType;
|
||||
|
||||
@ApplicationScoped
|
||||
public class EksService implements TagHandler, ResourceProvider {
|
||||
public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaunchListener {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(EksService.class);
|
||||
|
||||
@@ -108,6 +111,7 @@ public class EksService implements TagHandler, ResourceProvider {
|
||||
private final Map<String, CompletableFuture<Boolean>> pendingFirstNodeGroups = new ConcurrentHashMap<>();
|
||||
// Storage hands every caller the same live Cluster, and Cluster keeps identity equality.
|
||||
private final Set<Cluster> clustersBeingDeleted = ConcurrentHashMap.newKeySet();
|
||||
private final Set<String> restoringClusters = ConcurrentHashMap.newKeySet();
|
||||
|
||||
@Inject
|
||||
public EksService(StorageFactory storageFactory, EmulatorConfig config,
|
||||
@@ -165,8 +169,10 @@ public class EksService implements TagHandler, ResourceProvider {
|
||||
}
|
||||
if (!config.services().eks().mock()) {
|
||||
restorePersistedClusters();
|
||||
startReadinessPoller();
|
||||
} else {
|
||||
restoreMockJoinedInstances();
|
||||
}
|
||||
startReadinessPoller();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -215,6 +221,7 @@ public class EksService implements TagHandler, ResourceProvider {
|
||||
cluster.setNodeInstanceType(selectedNodeInstanceType(group)));
|
||||
}
|
||||
clusterManager.restoreCluster(cluster);
|
||||
restoreJoinedInstances(entry.accountId(), cluster);
|
||||
} catch (Exception e) {
|
||||
if (!clusterManager.isDockerReachable()) {
|
||||
// Same degradation as create: a restored cluster is metadata that stands on
|
||||
@@ -234,7 +241,11 @@ public class EksService implements TagHandler, ResourceProvider {
|
||||
|
||||
private List<AccountAwareStorageBackend.AccountEntry<Cluster>> allClusterEntries() {
|
||||
if (storage instanceof AccountAwareStorageBackend<Cluster> aware) {
|
||||
return aware.scanAllAccountEntries(k -> true);
|
||||
return aware.scanAllAccountEntries(k -> true).stream().peek(entry -> {
|
||||
if (entry.value() != null && entry.value().getAccountId() == null) {
|
||||
entry.value().setAccountId(entry.accountId());
|
||||
}
|
||||
}).toList();
|
||||
}
|
||||
return storage.scan(k -> true).stream()
|
||||
.map(cluster -> new AccountAwareStorageBackend.AccountEntry<>(
|
||||
@@ -243,6 +254,71 @@ public class EksService implements TagHandler, ResourceProvider {
|
||||
.toList();
|
||||
}
|
||||
|
||||
private boolean isClusterDeleting(String accountId, Cluster cluster) {
|
||||
return cluster != null && cluster.getName() != null
|
||||
&& (cluster.getStatus() == ClusterStatus.DELETING
|
||||
|| clustersBeingDeleted.stream().anyMatch(c -> cluster.getName().equals(c.getName())
|
||||
&& (accountId == null || c.getAccountId() == null || accountId.equals(c.getAccountId()))));
|
||||
}
|
||||
|
||||
private void saveClusterIfNotDeleting(String accountId, String clusterName, Consumer<Cluster> mutator) {
|
||||
synchronized (clustersBeingDeleted) {
|
||||
Cluster current = findAuthenticationCluster(accountId, clusterName).orElse(null);
|
||||
if (current != null && !isClusterDeleting(accountId, current)) {
|
||||
if (current.getAccountId() == null) {
|
||||
current.setAccountId(accountId);
|
||||
}
|
||||
mutator.accept(current);
|
||||
putClusterForAccount(accountId, current);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void restoreJoinedInstances(String accountId, Cluster cluster) {
|
||||
if (cluster == null || cluster.getJoinedInstanceIds() == null || ec2Service == null
|
||||
|| isClusterDeleting(accountId, cluster) || findAuthenticationCluster(accountId, cluster.getName()).isEmpty()) {
|
||||
return;
|
||||
}
|
||||
if (cluster.getAccountId() == null) {
|
||||
cluster.setAccountId(accountId);
|
||||
}
|
||||
Set<String> prunedInstanceIds = new HashSet<>();
|
||||
for (Map.Entry<String, String> instEntry : new ArrayList<>(cluster.getJoinedInstanceIds().entrySet())) {
|
||||
if (isClusterDeleting(accountId, cluster) || findAuthenticationCluster(accountId, cluster.getName()).isEmpty()) {
|
||||
return;
|
||||
}
|
||||
String instId = instEntry.getKey();
|
||||
String reg = instEntry.getValue();
|
||||
RequestScopes.runAs(accountId, reg, () -> {
|
||||
Instance inst = ec2Service.getInstance(reg, instId).orElse(null);
|
||||
if (inst == null || (inst.getState() != null && "terminated".equals(inst.getState().getName()))) {
|
||||
cluster.getJoinedInstanceIds().remove(instId);
|
||||
prunedInstanceIds.add(instId);
|
||||
} else {
|
||||
try {
|
||||
clusterManager.joinInstance(cluster, inst);
|
||||
} catch (Exception e) {
|
||||
LOG.warnv("Failed to re-join instance {0} on restore of cluster {1}: {2}",
|
||||
instId, cluster.getName(), e.getMessage());
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
if (!prunedInstanceIds.isEmpty()) {
|
||||
saveClusterIfNotDeleting(accountId, cluster.getName(), current -> {
|
||||
if (current.getJoinedInstanceIds() != null) {
|
||||
prunedInstanceIds.forEach(current.getJoinedInstanceIds()::remove);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private void restoreMockJoinedInstances() {
|
||||
for (AccountAwareStorageBackend.AccountEntry<Cluster> entry : allClusterEntries()) {
|
||||
restoreJoinedInstances(entry.accountId(), entry.value());
|
||||
}
|
||||
}
|
||||
|
||||
private Optional<Nodegroup> firstNodeGroup(String clusterName, String accountId) {
|
||||
String prefix = clusterName + "/";
|
||||
List<Nodegroup> groups;
|
||||
@@ -316,17 +392,32 @@ public class EksService implements TagHandler, ResourceProvider {
|
||||
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 (cluster != null) {
|
||||
if (cluster.getAccountId() == null) {
|
||||
cluster.setAccountId(accountId);
|
||||
}
|
||||
clustersBeingDeleted.add(cluster);
|
||||
cluster.setStatus(ClusterStatus.DELETING);
|
||||
}
|
||||
if (storage instanceof AccountAwareStorageBackend<Cluster> aware) {
|
||||
aware.deleteForAccount(accountId, clusterName);
|
||||
return;
|
||||
try {
|
||||
clearAppliedClusterUserData(cluster, clusterName);
|
||||
if (cluster == null || cluster.getArn() == null) {
|
||||
String fallbackArn = AwsArnUtils.Arn.of("eks", config.defaultRegion(), accountId,
|
||||
"cluster/" + clusterName).toString();
|
||||
appliedClusterUserData.remove(fallbackArn);
|
||||
}
|
||||
synchronized (clustersBeingDeleted) {
|
||||
if (storage instanceof AccountAwareStorageBackend<Cluster> aware) {
|
||||
aware.deleteForAccount(accountId, clusterName);
|
||||
return;
|
||||
}
|
||||
storage.delete(clusterName);
|
||||
}
|
||||
} finally {
|
||||
if (cluster != null) {
|
||||
clustersBeingDeleted.remove(cluster);
|
||||
}
|
||||
}
|
||||
storage.delete(clusterName);
|
||||
}
|
||||
|
||||
private void clearAppliedClusterUserData(Cluster cluster, String fallbackName) {
|
||||
@@ -653,6 +744,69 @@ public class EksService implements TagHandler, ResourceProvider {
|
||||
return cluster;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onInstanceLaunched(String accountId, String region, Instance instance) {
|
||||
extractInstanceClusterName(instance).ifPresent(name ->
|
||||
RequestScopes.runAs(accountId, region, () -> {
|
||||
try {
|
||||
Cluster cluster = describeCluster(name);
|
||||
validateInstanceRegion(cluster, instance);
|
||||
saveClusterIfNotDeleting(accountId, name, current ->
|
||||
clusterManager.recordJoinedInstanceId(current, instance));
|
||||
} catch (AwsException e) {
|
||||
LOG.warnv("Cannot join instance {0} to cluster {1}: {2}",
|
||||
instance.getInstanceId(), name, e.getMessage());
|
||||
} catch (Exception e) {
|
||||
LOG.warnv("Failed to join instance {0} to cluster {1}: {2}",
|
||||
instance.getInstanceId(), name, e.getMessage());
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
private Optional<String> extractInstanceClusterName(Instance instance) {
|
||||
return (instance != null && instance.getUserData() != null && !instance.getUserData().isBlank())
|
||||
? EksBootstrapUserData.extractClusterName(instance.getUserData()) : Optional.empty();
|
||||
}
|
||||
|
||||
void joinInstance(String clusterName, Instance instance) {
|
||||
Cluster cluster = describeCluster(clusterName);
|
||||
validateInstanceRegion(cluster, instance);
|
||||
clusterManager.joinInstance(cluster, instance);
|
||||
storage.put(cluster.getName(), cluster);
|
||||
}
|
||||
|
||||
void joinInstance(String clusterName, String instanceId) {
|
||||
String region = resolveClusterRegion(describeCluster(clusterName));
|
||||
Instance instance = ec2Service != null ? ec2Service.getInstance(region, instanceId).orElse(null) : null;
|
||||
if (instance == null) {
|
||||
throw new AwsException("InvalidInstanceID.NotFound", "The instance ID '" + instanceId + "' does not exist", 400);
|
||||
}
|
||||
joinInstance(clusterName, instance);
|
||||
}
|
||||
|
||||
private void validateInstanceRegion(Cluster cluster, Instance instance) {
|
||||
String clusterReg = resolveClusterRegion(cluster);
|
||||
String instReg = instance.getRegion();
|
||||
if (instReg == null && instance.getPlacement() != null && instance.getPlacement().getAvailabilityZone() != null) {
|
||||
String az = instance.getPlacement().getAvailabilityZone();
|
||||
if (az.length() > 1 && Character.isLetter(az.charAt(az.length() - 1))) {
|
||||
instReg = az.substring(0, az.length() - 1);
|
||||
}
|
||||
}
|
||||
if (instReg != null && !instReg.equals(clusterReg)) {
|
||||
throw new AwsException("InvalidParameterException", "Cannot join instance " + instance.getInstanceId()
|
||||
+ " in region " + instReg + " to cluster " + cluster.getName() + " in region " + clusterReg, 400);
|
||||
}
|
||||
}
|
||||
|
||||
List<Instance> getJoinedInstances(String clusterName) {
|
||||
return clusterManager.getJoinedInstances(describeCluster(clusterName));
|
||||
}
|
||||
|
||||
boolean isInstanceJoined(String clusterName, String instanceId) {
|
||||
return clusterManager.isInstanceJoined(describeCluster(clusterName), instanceId);
|
||||
}
|
||||
|
||||
public List<String> listClusters() {
|
||||
return storage.scan(k -> true).stream()
|
||||
.map(Cluster::getName)
|
||||
@@ -663,6 +817,9 @@ public class EksService implements TagHandler, ResourceProvider {
|
||||
Cluster cluster = storage.get(name)
|
||||
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
|
||||
"No cluster found for name: " + name, 404));
|
||||
if (cluster.getAccountId() == null) {
|
||||
cluster.setAccountId(regionResolver.getAccountId());
|
||||
}
|
||||
|
||||
// One delete at a time per cluster, so a delete that fails cannot restore the status or
|
||||
// state of a cluster another delete is tearing down.
|
||||
@@ -690,9 +847,11 @@ public class EksService implements TagHandler, ResourceProvider {
|
||||
if (addons != null) {
|
||||
addons.deleteClusterAddons(cluster);
|
||||
}
|
||||
storage.delete(name);
|
||||
clearAppliedClusterUserData(cluster, name);
|
||||
oidcService.deleteKey(name);
|
||||
synchronized (clustersBeingDeleted) {
|
||||
storage.delete(name);
|
||||
clearAppliedClusterUserData(cluster, name);
|
||||
oidcService.deleteKey(name);
|
||||
}
|
||||
return cluster;
|
||||
} finally {
|
||||
clustersBeingDeleted.remove(cluster);
|
||||
@@ -1446,14 +1605,18 @@ public class EksService implements TagHandler, ResourceProvider {
|
||||
private void startReadinessPoller() {
|
||||
poller.scheduleAtFixedRate(() -> {
|
||||
try {
|
||||
for (Cluster cluster : allClusters()) {
|
||||
for (AccountAwareStorageBackend.AccountEntry<Cluster> entry : allClusterEntries()) {
|
||||
Cluster cluster = entry.value();
|
||||
if (cluster.getStatus() == ClusterStatus.CREATING) {
|
||||
if (clusterManager.isReady(cluster)) {
|
||||
LOG.infov("EKS cluster {0} is now ACTIVE", cluster.getName());
|
||||
clusterManager.finalizeCluster(cluster);
|
||||
cluster.setStatus(ClusterStatus.ACTIVE);
|
||||
putCluster(cluster);
|
||||
restoreJoinedInstancesAsync(entry.accountId(), cluster);
|
||||
}
|
||||
} else if (cluster.getStatus() == ClusterStatus.ACTIVE && hasPendingJoinedInstances(cluster)) {
|
||||
restoreJoinedInstancesAsync(entry.accountId(), cluster);
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
@@ -1462,6 +1625,28 @@ public class EksService implements TagHandler, ResourceProvider {
|
||||
}, 2, 3, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
private void restoreJoinedInstancesAsync(String accountId, Cluster cluster) {
|
||||
if (cluster == null || cluster.getName() == null || isClusterDeleting(accountId, cluster)) {
|
||||
return;
|
||||
}
|
||||
String key = (accountId != null ? accountId : "default") + "/" + cluster.getName();
|
||||
if (!restoringClusters.add(key)) {
|
||||
return;
|
||||
}
|
||||
CompletableFuture.runAsync(() -> {
|
||||
try {
|
||||
restoreJoinedInstances(accountId, cluster);
|
||||
} finally {
|
||||
restoringClusters.remove(key);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private boolean hasPendingJoinedInstances(Cluster cluster) {
|
||||
return cluster != null && cluster.getJoinedInstanceIds() != null
|
||||
&& cluster.getJoinedInstanceIds().keySet().stream().anyMatch(id -> !clusterManager.isInstanceJoined(cluster, id));
|
||||
}
|
||||
|
||||
public Optional<Cluster> findClusterByIssuer(String issuer) {
|
||||
if (issuer == null || issuer.isBlank()) {
|
||||
return Optional.empty();
|
||||
|
||||
@@ -11,6 +11,7 @@ import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
@RegisterForReflection
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
@@ -119,11 +120,34 @@ public class Cluster {
|
||||
@JsonInclude(JsonInclude.Include.NON_NULL)
|
||||
private Boolean defaultStorageClass;
|
||||
|
||||
// Internal persisted map of joined EC2 instance IDs to their region.
|
||||
@JsonProperty("joinedInstanceIds")
|
||||
@JsonInclude(JsonInclude.Include.NON_EMPTY)
|
||||
private Map<String, String> joinedInstanceIds;
|
||||
|
||||
private AccessConfig accessConfig;
|
||||
|
||||
public AccessConfig getAccessConfig() { return accessConfig; }
|
||||
public void setAccessConfig(AccessConfig accessConfig) { this.accessConfig = accessConfig; }
|
||||
|
||||
public Map<String, String> getJoinedInstanceIds() {
|
||||
if (joinedInstanceIds != null && !(joinedInstanceIds instanceof ConcurrentHashMap)) {
|
||||
joinedInstanceIds = new ConcurrentHashMap<>(joinedInstanceIds);
|
||||
}
|
||||
return joinedInstanceIds;
|
||||
}
|
||||
|
||||
public void setJoinedInstanceIds(Map<String, String> joinedInstanceIds) {
|
||||
this.joinedInstanceIds = joinedInstanceIds != null ? new ConcurrentHashMap<>(joinedInstanceIds) : null;
|
||||
}
|
||||
|
||||
public synchronized void recordJoinedInstance(String instanceId, String region) {
|
||||
if (joinedInstanceIds == null) {
|
||||
joinedInstanceIds = new ConcurrentHashMap<>();
|
||||
}
|
||||
joinedInstanceIds.put(instanceId, region);
|
||||
}
|
||||
|
||||
public Cluster() {}
|
||||
|
||||
public String getName() { return name; }
|
||||
@@ -228,6 +252,7 @@ public class Cluster {
|
||||
c.nodeInstanceType = this.nodeInstanceType;
|
||||
c.clusterArgs = this.clusterArgs != null ? new ArrayList<>(this.clusterArgs) : null;
|
||||
c.defaultStorageClass = this.defaultStorageClass;
|
||||
c.joinedInstanceIds = this.joinedInstanceIds != null ? new ConcurrentHashMap<>(this.joinedInstanceIds) : null;
|
||||
c.accessConfig = this.accessConfig;
|
||||
return c;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
package io.github.hectorvent.floci.services.eks;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class EksBootstrapUserDataTest {
|
||||
|
||||
@Test
|
||||
void extractsClusterNameFromBootstrapScripts() {
|
||||
assertEquals("my-cluster",
|
||||
EksBootstrapUserData.extractClusterName("#!/bin/bash\n/etc/eks/bootstrap.sh my-cluster\n").orElse(null));
|
||||
assertEquals("test-cluster", EksBootstrapUserData.extractClusterName(
|
||||
"#!/bin/bash\n/etc/eks/bootstrap.sh --b64-cluster-ca dGVzdA== --apiserver-endpoint https://k8s.example.com test-cluster\n").orElse(null));
|
||||
assertEquals("my-prod-cluster", EksBootstrapUserData.extractClusterName(
|
||||
"#!/bin/bash\n/etc/eks/bootstrap.sh my-prod-cluster --kubelet-extra-args '--node-labels=workload=compute'\n").orElse(null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void extractsClusterNameFromNodeadmConfig() {
|
||||
String yaml = "---\napiVersion: node.eks.aws/v1alpha1\nkind: NodeConfig\nspec:\n cluster:\n name: nodeadm-cluster\n";
|
||||
assertEquals("nodeadm-cluster", EksBootstrapUserData.extractClusterName(yaml).orElse(null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void extractsClusterNameFromMimeMultipartNodeadmConfig() {
|
||||
String mime = "MIME-Version: 1.0\r\nContent-Type: multipart/mixed; boundary=\"//\"\r\n\r\n"
|
||||
+ "--//\r\nContent-Type: application/node.eks.aws\r\n\r\n---\r\n"
|
||||
+ "apiVersion: node.eks.aws/v1alpha1\r\nkind: NodeConfig\r\nspec:\r\n cluster:\r\n name: mime-nodeadm-cluster\r\n--//--\r\n";
|
||||
assertEquals("mime-nodeadm-cluster", EksBootstrapUserData.extractClusterName(mime).orElse(null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void returnsEmptyForUnrelatedUserData() {
|
||||
assertTrue(EksBootstrapUserData.extractClusterName(null).isEmpty());
|
||||
assertTrue(EksBootstrapUserData.extractClusterName("").isEmpty());
|
||||
assertTrue(EksBootstrapUserData.extractClusterName("#!/bin/bash\necho hello world").isEmpty());
|
||||
assertTrue(EksBootstrapUserData.extractClusterName("export CLUSTER_NAME=\"my-cluster\"").isEmpty());
|
||||
assertTrue(EksBootstrapUserData.extractClusterName("--cluster-name my-cluster").isEmpty());
|
||||
String appYaml = "app:\n version: 1.0\ncluster:\n name: redis-cache-cluster\n nodes: 3\n";
|
||||
assertTrue(EksBootstrapUserData.extractClusterName(appYaml).isEmpty());
|
||||
}
|
||||
}
|
||||
@@ -46,9 +46,12 @@ import com.github.dockerjava.api.model.Container;
|
||||
import com.github.dockerjava.api.model.Frame;
|
||||
import com.github.dockerjava.api.model.Info;
|
||||
import com.github.dockerjava.api.model.NetworkSettings;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerExec;
|
||||
import io.github.hectorvent.floci.services.ec2.Ec2InstanceTypeCatalog;
|
||||
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.Placement;
|
||||
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
|
||||
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
@@ -77,6 +80,9 @@ import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.Future;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.LogRecord;
|
||||
|
||||
@@ -89,9 +95,11 @@ import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyInt;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.atLeastOnce;
|
||||
import static org.mockito.Mockito.doReturn;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
@@ -3706,4 +3714,171 @@ class EksClusterManagerTest {
|
||||
assertTrue(cmd.contains("--kubelet-arg=max-pods=250"));
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class JoinedInstancesTest {
|
||||
|
||||
private EksClusterManager manager;
|
||||
private EmulatorConfig config;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
config = Mockito.mock(EmulatorConfig.class);
|
||||
EmulatorConfig.ServicesConfig services = Mockito.mock(EmulatorConfig.ServicesConfig.class);
|
||||
when(config.services()).thenReturn(services);
|
||||
when(services.eks()).thenReturn(Mockito.mock(EmulatorConfig.EksServiceConfig.class));
|
||||
manager = Mockito.spy(new EksClusterManager(Mockito.mock(ContainerBuilder.class),
|
||||
Mockito.mock(ContainerLifecycleManager.class), Mockito.mock(ContainerDetector.class),
|
||||
Mockito.mock(PortAllocator.class), Mockito.mock(DockerHostResolver.class),
|
||||
Mockito.mock(EcrRegistryManager.class), config, new RegionResolver("us-east-1", "000000000000"),
|
||||
Mockito.mock(Ec2MetadataServer.class), Mockito.mock(EksOidcService.class),
|
||||
Mockito.mock(FlociCertificateAuthority.class), Mockito.mock(ContainerLogStreamer.class),
|
||||
new InMemoryStorage<>()));
|
||||
}
|
||||
|
||||
private Cluster clusterNamed(String name, String containerId) {
|
||||
Cluster c = new Cluster();
|
||||
c.setName(name);
|
||||
c.setContainerId(containerId);
|
||||
return c;
|
||||
}
|
||||
|
||||
@Test
|
||||
void deriveInstanceNodeNameAndProviderId() {
|
||||
Instance inst = createInstance("i-0123456789abcdef0", "us-east-1b", null, null, null);
|
||||
inst.setPrivateDnsName("ip-10-0-1-50.ec2.internal");
|
||||
assertEquals("ip-10-0-1-50.ec2.internal", manager.deriveInstanceNodeName(inst, "us-east-1"));
|
||||
assertEquals("aws:///us-east-1b/i-0123456789abcdef0", manager.deriveInstanceNodeProviderId(inst, "us-east-1"));
|
||||
Instance euInst = createInstance("i-0abcdef1234567890", "eu-west-1c", null, null, null);
|
||||
assertEquals("i-0abcdef1234567890.eu-west-1.compute.internal", manager.deriveInstanceNodeName(euInst, "eu-west-1"));
|
||||
assertEquals("aws:///eu-west-1c/i-0abcdef1234567890", manager.deriveInstanceNodeProviderId(euInst, "eu-west-1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void joinAndQueryJoinedInstances() {
|
||||
Cluster cluster = clusterNamed("track-cluster", null);
|
||||
cluster.setEndpoint("https://public:6443");
|
||||
cluster.setInternalEndpoint("https://internal:6443");
|
||||
Instance inst = createInstance("i-0123456789abcdef0", "us-east-1a", null, null, "10.0.1.50");
|
||||
assertFalse(manager.isInstanceJoined(cluster, "i-0123456789abcdef0"));
|
||||
manager.joinInstance(cluster, inst);
|
||||
assertTrue(manager.isInstanceJoined(cluster, "i-0123456789abcdef0"));
|
||||
assertEquals(1, manager.getJoinedInstances(cluster).size());
|
||||
assertEquals("i-0123456789abcdef0", manager.getJoinedInstances(cluster).getFirst().getInstanceId());
|
||||
Optional<DnsAnswer> ans = manager.resolveIpv4("i-0123456789abcdef0.ec2.internal");
|
||||
assertTrue(ans.isPresent() && ans.get().addresses().contains("10.0.1.50"));
|
||||
manager.unregisterMetadataEndpoint(cluster);
|
||||
assertFalse(manager.isInstanceJoined(cluster, "i-0123456789abcdef0"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void joinInstanceRegistersNodeInRunningContainerWithExpectedManifest() {
|
||||
Cluster cluster = clusterNamed("live-cluster", "live-container-123");
|
||||
Instance inst = createInstance("i-0123456789abcdef0", "us-east-1a", "t3.medium", "x86_64", "10.0.1.50");
|
||||
|
||||
ArgumentCaptor<String[]> cmdCaptor = ArgumentCaptor.forClass(String[].class);
|
||||
doReturn(new ContainerExec.Result(0L, "", "", false)).when(manager)
|
||||
.execInContainerForResult(eq("live-container-123"), cmdCaptor.capture(), anyInt());
|
||||
|
||||
manager.joinInstance(cluster, inst);
|
||||
assertTrue(manager.isInstanceJoined(cluster, "i-0123456789abcdef0"));
|
||||
List<String[]> capturedCmds = cmdCaptor.getAllValues();
|
||||
assertEquals(2, capturedCmds.size());
|
||||
|
||||
String applyScript = capturedCmds.getFirst()[2];
|
||||
assertTrue(applyScript.contains("i-0123456789abcdef0.ec2.internal")
|
||||
&& applyScript.contains("aws:///us-east-1a/i-0123456789abcdef0")
|
||||
&& applyScript.contains("\"topology.kubernetes.io/zone\":\"us-east-1a\"")
|
||||
&& applyScript.contains("\"topology.kubernetes.io/region\":\"us-east-1\"")
|
||||
&& applyScript.contains("\"node.kubernetes.io/instance-type\":\"t3.medium\"")
|
||||
&& applyScript.contains("\"kubernetes.io/arch\":\"amd64\""));
|
||||
|
||||
String[] patchCmd = capturedCmds.get(1);
|
||||
assertEquals("node", patchCmd[2]);
|
||||
assertEquals("i-0123456789abcdef0.ec2.internal", patchCmd[3]);
|
||||
assertTrue(patchCmd[7].contains("10.0.1.50") && patchCmd[7].contains("KubeletReady"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void joinArmInstanceRegistersWithArm64Label() {
|
||||
Cluster cluster = clusterNamed("arm-cluster", "arm-container-123");
|
||||
Instance inst = createInstance("i-0arm1234567890abc", "us-east-1b", "t4g.medium", "arm64", "10.0.2.60");
|
||||
|
||||
ArgumentCaptor<String[]> cmdCaptor = ArgumentCaptor.forClass(String[].class);
|
||||
doReturn(new ContainerExec.Result(0L, "", "", false)).when(manager)
|
||||
.execInContainerForResult(eq("arm-container-123"), cmdCaptor.capture(), anyInt());
|
||||
|
||||
manager.joinInstance(cluster, inst);
|
||||
assertTrue(cmdCaptor.getAllValues().getFirst()[2].contains("\"kubernetes.io/arch\":\"arm64\""));
|
||||
}
|
||||
|
||||
@Test
|
||||
void joinInstanceRegistrationFailureCleansUpAndThrows() {
|
||||
Cluster c1 = clusterNamed("fail-apply", "c1");
|
||||
doReturn(new ContainerExec.Result(1L, "", "apply failed", false))
|
||||
.when(manager).execInContainerForResult(eq("c1"), any(), anyInt());
|
||||
assertThrows(IllegalStateException.class, () ->
|
||||
manager.joinInstance(c1, createInstance("i-fail1", "us-east-1a", null, null, null)));
|
||||
assertFalse(manager.isInstanceJoined(c1, "i-fail1"));
|
||||
|
||||
Cluster c2 = clusterNamed("fail-patch", "c2");
|
||||
ArgumentCaptor<String[]> captor = ArgumentCaptor.forClass(String[].class);
|
||||
doReturn(new ContainerExec.Result(0L, "", "", false),
|
||||
new ContainerExec.Result(1L, "", "patch failed", false),
|
||||
new ContainerExec.Result(0L, "", "", false))
|
||||
.when(manager).execInContainerForResult(eq("c2"), captor.capture(), anyInt());
|
||||
assertThrows(IllegalStateException.class, () ->
|
||||
manager.joinInstance(c2, createInstance("i-fail2", "us-east-1a", null, null, null)));
|
||||
assertFalse(manager.isInstanceJoined(c2, "i-fail2"));
|
||||
assertEquals("delete", captor.getAllValues().get(2)[1]);
|
||||
}
|
||||
|
||||
@Test
|
||||
void joinInstanceSameClusterIsIdempotent() {
|
||||
Cluster cluster = clusterNamed("idem-cluster", null);
|
||||
Instance inst = createInstance("i-idem123456789", "us-east-1a", null, null, null);
|
||||
manager.joinInstance(cluster, inst);
|
||||
assertTrue(manager.isInstanceJoined(cluster, "i-idem123456789"));
|
||||
manager.joinInstance(cluster, inst);
|
||||
assertEquals(1, manager.getJoinedInstances(cluster).size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void joinInstanceRejectsInstanceAlreadyJoinedToAnotherCluster() {
|
||||
Cluster c1 = clusterNamed("c1", null), c2 = clusterNamed("c2", null);
|
||||
Instance inst = createInstance("i-shared1234567890", "us-east-1a", null, null, null);
|
||||
manager.joinInstance(c1, inst);
|
||||
assertTrue(manager.isInstanceJoined(c1, "i-shared1234567890"));
|
||||
assertThrows(AwsException.class, () -> manager.joinInstance(c2, inst));
|
||||
assertFalse(manager.isInstanceJoined(c2, "i-shared1234567890"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void recordJoinedInstanceIdConcurrentSafety() throws Exception {
|
||||
Cluster cluster = clusterNamed("concurrent-cluster", null);
|
||||
ExecutorService executor = Executors.newFixedThreadPool(8);
|
||||
List<Future<?>> futures = new ArrayList<>();
|
||||
for (int i = 0; i < 20; i++) {
|
||||
final int idx = i;
|
||||
futures.add(executor.submit(() ->
|
||||
manager.recordJoinedInstanceId(cluster, createInstance("i-c" + idx, "us-east-1a", null, null, null))));
|
||||
}
|
||||
for (Future<?> f : futures) {
|
||||
f.get();
|
||||
}
|
||||
executor.shutdown();
|
||||
assertEquals(20, cluster.getJoinedInstanceIds().size());
|
||||
}
|
||||
|
||||
private Instance createInstance(String id, String zone, String type, String arch, String ip) {
|
||||
Instance inst = new Instance();
|
||||
inst.setInstanceId(id);
|
||||
inst.setRegion(zone.substring(0, zone.length() - 1));
|
||||
inst.setPlacement(new Placement(zone));
|
||||
inst.setInstanceType(type);
|
||||
inst.setArchitecture(arch);
|
||||
inst.setPrivateIpAddress(ip);
|
||||
return inst;
|
||||
}
|
||||
}
|
||||
}
|
||||
+244
@@ -0,0 +1,244 @@
|
||||
package io.github.hectorvent.floci.services.eks;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.RequestScopes;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerExec;
|
||||
import io.github.hectorvent.floci.services.ec2.Ec2Service;
|
||||
import io.github.hectorvent.floci.services.ec2.model.Instance;
|
||||
import io.github.hectorvent.floci.services.eks.model.Cluster;
|
||||
import io.github.hectorvent.floci.services.eks.model.CreateClusterRequest;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.mockito.InjectSpy;
|
||||
import io.restassured.response.ValidatableResponse;
|
||||
import io.restassured.specification.RequestSpecification;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Base64;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.awaitility.Awaitility.await;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.anyInt;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.doReturn;
|
||||
|
||||
@QuarkusTest
|
||||
class EksInstanceJoinIntegrationTest {
|
||||
|
||||
@Inject
|
||||
EksService eksService;
|
||||
|
||||
@InjectSpy
|
||||
EksClusterManager eksClusterManager;
|
||||
|
||||
@Inject
|
||||
Ec2Service ec2Service;
|
||||
|
||||
@Test
|
||||
void instanceJoinsClusterViaUserDataAndExposesNodeMetadata() {
|
||||
String account = "123456789012";
|
||||
String clusterName = "join-cluster-" + UUID.randomUUID().toString().substring(0, 8);
|
||||
|
||||
Cluster cluster = createTestCluster(clusterName, account);
|
||||
cluster.setContainerId("mock-k3s-container");
|
||||
ArgumentCaptor<String[]> cmdCaptor = ArgumentCaptor.forClass(String[].class);
|
||||
doReturn(new ContainerExec.Result(0L, "", "", false)).when(eksClusterManager)
|
||||
.execInContainerForResult(eq("mock-k3s-container"), cmdCaptor.capture(), anyInt());
|
||||
|
||||
eksClusterManager.registerClusterNodeInstance(cluster, "mock-container-id");
|
||||
Instance initialClusterNode = eksClusterManager.getRegisteredClusterNodeInstance(cluster);
|
||||
assertNotNull(initialClusterNode);
|
||||
String initialNodeName = eksClusterManager.deriveClusterNodePrivateDnsName(cluster);
|
||||
String initialProviderId = eksClusterManager.deriveClusterNodeProviderId(cluster);
|
||||
|
||||
try {
|
||||
String script = "#!/bin/bash\n/etc/eks/bootstrap.sh " + clusterName;
|
||||
String instanceId = launchInstance(account, "us-east-1", "t3.medium", script);
|
||||
|
||||
await().atMost(Duration.ofSeconds(10)).until(() ->
|
||||
RequestScopes.callAs(account, () -> eksService.isInstanceJoined(clusterName, instanceId)));
|
||||
List<Instance> joined = RequestScopes.callAs(account, () -> eksService.getJoinedInstances(clusterName));
|
||||
assertEquals(1, joined.size());
|
||||
Instance joinedInst = joined.getFirst();
|
||||
assertEquals(instanceId, joinedInst.getInstanceId());
|
||||
|
||||
String az = joinedInst.getPlacement() != null ? joinedInst.getPlacement().getAvailabilityZone() : "us-east-1a";
|
||||
String expectedNodeName = joinedInst.getPrivateDnsName() != null ? joinedInst.getPrivateDnsName() : instanceId + ".ec2.internal";
|
||||
assertEquals(expectedNodeName, eksClusterManager.deriveInstanceNodeName(joinedInst, "us-east-1"));
|
||||
assertEquals("aws:///" + az + "/" + instanceId, eksClusterManager.deriveInstanceNodeProviderId(joinedInst, "us-east-1"));
|
||||
|
||||
List<String[]> cmds = cmdCaptor.getAllValues();
|
||||
assertEquals(2, cmds.size());
|
||||
assertTrue(cmds.getFirst()[2].contains(expectedNodeName)
|
||||
&& cmds.getFirst()[2].contains("aws:///" + az + "/" + instanceId)
|
||||
&& cmds.getFirst()[2].contains("\"topology.kubernetes.io/zone\":\"" + az + "\"")
|
||||
&& cmds.getFirst()[2].contains("\"topology.kubernetes.io/region\":\"us-east-1\"")
|
||||
&& cmds.getFirst()[2].contains("\"node.kubernetes.io/instance-type\":\"t3.medium\"")
|
||||
&& cmds.getFirst()[2].contains("\"kubernetes.io/arch\":\"amd64\""));
|
||||
assertEquals("node", cmds.get(1)[2]);
|
||||
assertEquals(expectedNodeName, cmds.get(1)[3]);
|
||||
assertTrue(cmds.get(1)[7].contains("Ready") && cmds.get(1)[7].contains("True"));
|
||||
|
||||
assertEquals(initialNodeName, eksClusterManager.deriveClusterNodePrivateDnsName(cluster));
|
||||
assertEquals(initialProviderId, eksClusterManager.deriveClusterNodeProviderId(cluster));
|
||||
assertEquals(initialClusterNode.getInstanceId(), eksClusterManager.getRegisteredClusterNodeInstance(cluster).getInstanceId());
|
||||
|
||||
ec2Form(account, "DescribeInstances", "InstanceId.1", instanceId).statusCode(200)
|
||||
.body("DescribeInstancesResponse.reservationSet.item.instancesSet.item.instanceId", equalTo(instanceId),
|
||||
"DescribeInstancesResponse.reservationSet.item.instancesSet.item.privateDnsName", equalTo(expectedNodeName),
|
||||
"DescribeInstancesResponse.reservationSet.item.instancesSet.item.instanceType", equalTo("t3.medium"));
|
||||
} finally {
|
||||
eksClusterManager.unregisterMetadataEndpoint(cluster);
|
||||
try {
|
||||
RequestScopes.runAs(account, () -> eksService.deleteCluster(clusterName));
|
||||
} catch (Exception ignored) {
|
||||
// Best effort cluster cleanup
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void subnetlessLaunchesGetDistinctAddressesAndNodeNames() {
|
||||
String account = "123456789012";
|
||||
String id1 = launchInstance(account, "us-east-1", "t3.micro", null);
|
||||
String id2 = launchInstance(account, "us-east-1", "t3.micro", null);
|
||||
Instance inst1 = RequestScopes.callAs(account, () -> ec2Service.getInstance("us-east-1", id1).orElseThrow());
|
||||
Instance inst2 = RequestScopes.callAs(account, () -> ec2Service.getInstance("us-east-1", id2).orElseThrow());
|
||||
|
||||
assertNotNull(inst1.getPrivateIpAddress());
|
||||
assertNotNull(inst2.getPrivateIpAddress());
|
||||
assertNotEquals(inst1.getPrivateIpAddress(), inst2.getPrivateIpAddress());
|
||||
assertNotEquals(eksClusterManager.deriveInstanceNodeName(inst1, "us-east-1"),
|
||||
eksClusterManager.deriveInstanceNodeName(inst2, "us-east-1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void unrelatedOrMissingClusterDoesNotJoin() {
|
||||
String account = "123456789012";
|
||||
String clusterName = "unrelated-" + UUID.randomUUID().toString().substring(0, 8);
|
||||
Cluster cluster = createTestCluster(clusterName, account);
|
||||
try {
|
||||
String instId = launchInstance(account, "us-east-1", "t3.micro", "#!/bin/bash\necho hello world");
|
||||
assertFalse(RequestScopes.callAs(account, () -> eksService.isInstanceJoined(clusterName, instId)));
|
||||
assertTrue(RequestScopes.callAs(account, () -> eksService.getJoinedInstances(clusterName)).isEmpty());
|
||||
} finally {
|
||||
eksClusterManager.unregisterMetadataEndpoint(cluster);
|
||||
}
|
||||
|
||||
String instId2 = launchInstance(account, "us-east-1", "t3.micro",
|
||||
"#!/bin/bash\n/etc/eks/bootstrap.sh non-existent-cluster-999");
|
||||
assertNotNull(instId2);
|
||||
ec2Form(account, "DescribeInstances", "InstanceId.1", instId2).statusCode(200)
|
||||
.body("DescribeInstancesResponse.reservationSet.item.instancesSet.item.instanceId", equalTo(instId2));
|
||||
}
|
||||
|
||||
@Test
|
||||
void programmaticJoinInvocableOutsideCreatePath() {
|
||||
String account = "123456789012";
|
||||
String clusterName = "prog-join-" + UUID.randomUUID().toString().substring(0, 8);
|
||||
Cluster cluster = createTestCluster(clusterName, account);
|
||||
try {
|
||||
String instId = launchInstance(account, "us-east-1", "m5.large", null);
|
||||
assertFalse(RequestScopes.callAs(account, () -> eksService.isInstanceJoined(clusterName, instId)));
|
||||
RequestScopes.runAs(account, () -> eksService.joinInstance(clusterName, instId));
|
||||
assertTrue(RequestScopes.callAs(account, () -> eksService.isInstanceJoined(clusterName, instId)));
|
||||
List<Instance> joined = RequestScopes.callAs(account, () -> eksService.getJoinedInstances(clusterName));
|
||||
assertEquals(1, joined.size());
|
||||
assertEquals(instId, joined.getFirst().getInstanceId());
|
||||
} finally {
|
||||
eksClusterManager.unregisterMetadataEndpoint(cluster);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void ebsVolumeAttachmentOnClusterNodeRemainsFunctionalWithJoinedInstances() {
|
||||
String account = "123456789012";
|
||||
String clusterName = "ebs-test-" + UUID.randomUUID().toString().substring(0, 8);
|
||||
Cluster cluster = createTestCluster(clusterName, account);
|
||||
eksClusterManager.registerClusterNodeInstance(cluster, "mock-container-id");
|
||||
Instance clusterNode = eksClusterManager.getRegisteredClusterNodeInstance(cluster);
|
||||
assertNotNull(clusterNode);
|
||||
String nodeId = clusterNode.getInstanceId();
|
||||
|
||||
try {
|
||||
String instId = launchInstance(account, "us-east-1", "t3.medium", null);
|
||||
RequestScopes.runAs(account, () -> eksService.joinInstance(clusterName, instId));
|
||||
assertTrue(RequestScopes.callAs(account, () -> eksService.isInstanceJoined(clusterName, instId)));
|
||||
|
||||
String volumeId = ec2Form(account, "CreateVolume", "AvailabilityZone", "us-east-1a", "Size", "10", "VolumeType", "gp3")
|
||||
.statusCode(200).extract().path("CreateVolumeResponse.volumeId");
|
||||
ec2Form(account, "AttachVolume", "VolumeId", volumeId, "InstanceId", nodeId, "Device", "/dev/xvdf")
|
||||
.statusCode(200).body("AttachVolumeResponse.status", equalTo("attaching"));
|
||||
ec2Form(account, "DetachVolume", "VolumeId", volumeId, "InstanceId", nodeId, "Device", "/dev/xvdf")
|
||||
.statusCode(200).body("DetachVolumeResponse.status", equalTo("detaching"));
|
||||
} finally {
|
||||
eksClusterManager.unregisterMetadataEndpoint(cluster);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void joinRejectsCrossClusterAndCrossRegionInstances() {
|
||||
String account = "123456789012";
|
||||
String cName1 = "multi-1-" + UUID.randomUUID().toString().substring(0, 8);
|
||||
String cName2 = "multi-2-" + UUID.randomUUID().toString().substring(0, 8);
|
||||
Cluster c1 = createTestCluster(cName1, account), c2 = createTestCluster(cName2, account);
|
||||
try {
|
||||
String instId = launchInstance(account, "us-east-1", "t3.medium", null);
|
||||
RequestScopes.runAs(account, () -> eksService.joinInstance(cName1, instId));
|
||||
assertTrue(RequestScopes.callAs(account, () -> eksService.isInstanceJoined(cName1, instId)));
|
||||
assertThrows(AwsException.class, () -> RequestScopes.runAs(account, () -> eksService.joinInstance(cName2, instId)));
|
||||
assertFalse(RequestScopes.callAs(account, () -> eksService.isInstanceJoined(cName2, instId)));
|
||||
|
||||
String westInstId = launchInstance(account, "us-west-2", "t3.medium", null);
|
||||
assertThrows(AwsException.class, () ->
|
||||
RequestScopes.runAs(account, "us-east-1", () -> eksService.joinInstance(cName1, westInstId)));
|
||||
} finally {
|
||||
eksClusterManager.unregisterMetadataEndpoint(c1);
|
||||
eksClusterManager.unregisterMetadataEndpoint(c2);
|
||||
}
|
||||
}
|
||||
|
||||
private ValidatableResponse ec2Form(String account, String action, String... params) {
|
||||
RequestSpecification req = given().header("Authorization", auth(account, "ec2", "us-east-1")).formParam("Action", action);
|
||||
for (int i = 0; i < params.length; i += 2) {
|
||||
req.formParam(params[i], params[i + 1]);
|
||||
}
|
||||
return req.post("/").then();
|
||||
}
|
||||
|
||||
private String launchInstance(String account, String region, String type, String userData) {
|
||||
RequestSpecification req = given().header("Authorization", auth(account, "ec2", region))
|
||||
.formParam("Action", "RunInstances").formParam("ImageId", "ami-amazonlinux2023")
|
||||
.formParam("InstanceType", type != null ? type : "t3.micro")
|
||||
.formParam("MinCount", "1").formParam("MaxCount", "1");
|
||||
if (userData != null) {
|
||||
req.formParam("UserData", Base64.getEncoder().encodeToString(userData.getBytes(StandardCharsets.UTF_8)));
|
||||
}
|
||||
return req.post("/").then().statusCode(200).extract().path("RunInstancesResponse.instancesSet.item.instanceId");
|
||||
}
|
||||
|
||||
private Cluster createTestCluster(String name, String account) {
|
||||
CreateClusterRequest req = new CreateClusterRequest();
|
||||
req.setName(name);
|
||||
req.setRoleArn("arn:aws:iam::" + account + ":role/EksClusterRole");
|
||||
return RequestScopes.callAs(account, () -> eksService.createCluster(req));
|
||||
}
|
||||
|
||||
private static String auth(String account, String service, String region) {
|
||||
return "AWS4-HMAC-SHA256 Credential=" + account + "/20260917/" + region + "/" + service
|
||||
+ "/aws4_request, SignedHeaders=host, Signature=abc";
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user