feat(eks): bound cluster containers and derive kubelet reservations (#4590)

* feat(eks): bound cluster node capacity and reserve kubelet resources

* fix(eks): use the large managed node pod cap

* fix(eks): preserve node capacity through restart failures and restores

* fix(eks): retain restored node until capacity replacement starts

* fix(eks): let concurrent node groups share user data execution

* fix(eks): finalize first node group after bootstrap

* fix(eks): retain restored replacement when backup cleanup fails

* fix(eks): stop live node before retrying backup cleanup

* ci: retry transient mqtt port collision

* fix(eks): preserve cluster API port during node capacity change

* test(docker): verify exec attach stream closes on timeout

* fix(eks): keep capacity backup names outside cluster namespace
This commit is contained in:
Simone Primarosa authored and GitHub committed 2026-09-29 07:14:19 -04:00
1 parent ac41ff339a
commit 047d0d848c
15 files changed
+974 -36

No files matched your search

@@ -3086,6 +3086,14 @@ public interface EmulatorConfig {
@WithDefault("false")
boolean mock();
/** Optional ceiling for the single k3s node container, in MiB. Zero uses its instance type. */
@WithDefault("0")
int maxMemoryMib();
/** Optional vCPU ceiling for the single k3s node container. Zero uses its instance type. */
@WithDefault("0")
int maxVcpus();
@WithDefault("k3s")
String provider();
@@ -101,6 +101,7 @@ public final class ContainerExec {
dockerClient.execStartCmd(execId).exec(callback);
try {
// docker-java closes the attach stream on completion, timeout, or interruption.
if (!callback.awaitCompletion(timeoutSeconds, TimeUnit.SECONDS)) {
return new Result(-1, "", "Timed out after " + timeoutSeconds + "s", true);
}
@@ -4,6 +4,7 @@ import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.command.ExecCreateCmdResponse;
import com.github.dockerjava.api.command.InspectContainerResponse;
import com.github.dockerjava.api.model.ContainerNetwork;
import com.github.dockerjava.api.model.Info;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.config.FlociCertificateAuthority;
import io.github.hectorvent.floci.core.common.AwsRegions;
@@ -22,6 +23,8 @@ import io.github.hectorvent.floci.core.common.docker.DockerHostResolver;
import io.github.hectorvent.floci.core.common.docker.PortAllocator;
import io.github.hectorvent.floci.core.common.docker.UserDataPipeline;
import io.github.hectorvent.floci.services.ec2.ClusterNodeInstanceProvider;
import io.github.hectorvent.floci.services.ec2.Ec2InstanceTypeCatalog;
import io.github.hectorvent.floci.services.ec2.Ec2InstanceTypeCatalog.CatalogInstanceType;
import io.github.hectorvent.floci.services.ec2.Ec2MetadataProxy;
import io.github.hectorvent.floci.services.ec2.Ec2MetadataServer;
import io.github.hectorvent.floci.services.ec2.Ec2Service;
@@ -64,6 +67,7 @@ import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Base64;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
@@ -85,6 +89,8 @@ public class EksClusterManager
private static final Logger LOG = Logger.getLogger(EksClusterManager.class);
private static final int K3S_API_SERVER_PORT = 6443;
static final String DEFAULT_NODE_INSTANCE_TYPE = "m5.large";
private static final String NODE_CAPACITY_LABEL = "io.floci.eks.node-capacity";
private static final String WEBHOOK_CONFIG_DIR = "/etc";
private static final String WEBHOOK_CONFIG_FILE = "token-webhook.yaml";
@@ -140,6 +146,7 @@ public class EksClusterManager
private final EksOidcService oidcService;
private final FlociCertificateAuthority certificateAuthority;
private final ContainerLogStreamer logStreamer;
private final Ec2InstanceTypeCatalog instanceTypeCatalog = new Ec2InstanceTypeCatalog();
private final Map<String, ClusterNodeRecord> clusterNodeInstances = new ConcurrentHashMap<>();
private final Map<String, Closeable> clusterLogHandles = new ConcurrentHashMap<>();
private final List<Consumer<Instance>> nodeRegistrationListeners = new CopyOnWriteArrayList<>();
@@ -373,6 +380,10 @@ public class EksClusterManager
* {@link #isReady(Cluster)} returns true and {@link #finalizeCluster(Cluster)} is called.
*/
public void startCluster(Cluster cluster) {
startCluster(cluster, null);
}
private void startCluster(Cluster cluster, Integer retainedPort) {
String image = resolveClusterImage(cluster);
if (cluster.getDockerName() == null) {
cluster.setDockerName(accountQualifiedName(cluster));
@@ -383,7 +394,7 @@ public class EksClusterManager
cluster.getName(), image);
// Allocate host port for the k3s API server
int hostPort = portAllocator.allocate(
int hostPort = retainedPort != null ? retainedPort : portAllocator.allocate(
config.services().eks().apiServerBasePort(),
config.services().eks().apiServerMaxPort());
@@ -413,6 +424,11 @@ public class EksClusterManager
List<String> serverArgs = buildServerArgs(config.services().eks().disableCni(), serviceCidr, clusterCidr);
EksNodeCapacity.Limits nodeLimits = resolveNodeCapacity(cluster);
if (nodeLimits != null) {
nodeLimits.addKubeletArgs(serverArgs);
}
try {
String providerId = deriveClusterNodeProviderId(cluster);
serverArgs.add("--kubelet-arg=provider-id=" + providerId);
@@ -436,6 +452,9 @@ public class EksClusterManager
// 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));
ContainerBuilder.Builder specBuilder = containerBuilder.newContainer(image)
.withName(containerName)
.withEnv("K3S_KUBECONFIG_MODE", "644")
@@ -444,8 +463,16 @@ public class EksClusterManager
.withDockerNetwork(config.services().eks().dockerNetwork())
.withPrivileged(true)
.withLogRotation()
.withLabels(ContainerStorageHelper.resourceIdentityLabels(
"eks", cluster.getName(), labelAccountId, clusterRegion(cluster)));
.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();
@@ -572,25 +599,38 @@ public class EksClusterManager
return;
}
String desiredCapacity = capacityLabel(cluster, resolveNodeCapacity(cluster));
Map<String, String> existingLabels = existing.get().getLabels();
boolean capacityChanged = existingLabels == null
|| !desiredCapacity.equals(existingLabels.get(NODE_CAPACITY_LABEL));
if (!adoptSurvivingCluster(cluster, existing.get().getId())) {
startCluster(cluster);
return;
}
if (capacityChanged) {
replaceClusterContainer(cluster, null);
}
}
private boolean adoptSurvivingCluster(Cluster cluster, String containerId) {
if (config.services().eks().irsaSigningKey() && oidcService != null) {
reinjectSigningKeys(existing.get().getId(), cluster);
reinjectSigningKeys(containerId, cluster);
}
ContainerInfo info;
try {
info = lifecycleManager.adopt(existing.get().getId(), List.of(K3S_API_SERVER_PORT));
info = lifecycleManager.adopt(containerId, List.of(K3S_API_SERVER_PORT));
} catch (Exception e) {
LOG.warnv("Could not adopt surviving k3s container {0} for EKS cluster {1} ({2}); recreating it",
containerName, cluster.getName(), e.getMessage());
startCluster(cluster);
return;
cluster.getDockerName(), cluster.getName(), e.getMessage());
return false;
}
var publishedPort = info.publishedHostPort(K3S_API_SERVER_PORT);
if (publishedPort.isEmpty()) {
LOG.warnv("Surviving k3s container {0} publishes no API server port; recreating it", containerName);
startCluster(cluster);
return;
LOG.warnv("Surviving k3s container {0} publishes no API server port; recreating it",
cluster.getDockerName());
return false;
}
int hostPort = publishedPort.getAsInt();
@@ -598,7 +638,7 @@ public class EksClusterManager
portAllocator.markReserved(hostPort);
cluster.setContainerId(info.containerId());
cluster.setHostPort(hostPort);
applyEndpoints(cluster, containerName, hostPort, info);
applyEndpoints(cluster, cluster.getDockerName(), hostPort, info);
registerClusterNodeInstance(cluster, info.containerId());
configureLinkLocalMetadataEndpoint(cluster, info.containerId());
configurePodIdentityRelay(cluster, info.containerId());
@@ -608,6 +648,71 @@ public class EksClusterManager
LOG.infov("Adopted surviving k3s container {0} for EKS cluster {1} on port {2} (internal: {3})",
info.containerId(), cluster.getName(), String.valueOf(hostPort), cluster.getInternalEndpoint());
return true;
}
/** Keep the old container stopped but recoverable until its replacement has started. */
private boolean replaceClusterContainer(Cluster cluster, String previousType) {
String oldId = cluster.getContainerId();
int oldPort = cluster.getHostPort();
String containerName = cluster.getDockerName();
String backupName = capacityBackupName(cluster);
DockerClient docker = lifecycleManager.getDockerClient();
try {
lifecycleManager.removeIfExistsStrict(backupName);
} catch (RuntimeException cleanup) {
LOG.warnv("Could not clear prior EKS capacity backup for cluster {0}: {1}; keeping current node",
cluster.getName(), cleanup.getMessage());
restorePreviousNodeType(cluster, previousType);
return false;
}
boolean renamed = false;
try {
docker.renameContainerCmd(oldId).withName(backupName).exec();
renamed = true;
docker.stopContainerCmd(oldId).exec();
unregisterMetadataEndpoint(cluster);
closeQuietly(clusterLogHandles.remove(clusterResourceName(cluster)));
cluster.setContainerId(null);
startCluster(cluster, oldPort);
LOG.infov("Replaced EKS cluster {0} to apply current node capacity limits", cluster.getName());
} catch (RuntimeException replacement) {
LOG.warnv("Could not replace EKS cluster {0} for node capacity: {1}; restoring surviving node",
cluster.getName(), replacement.getMessage());
restorePreviousNodeType(cluster, previousType);
if (!renamed) {
return false;
}
try {
lifecycleManager.removeIfExistsStrict(containerName);
docker.renameContainerCmd(oldId).withName(containerName).exec();
if (!adoptSurvivingCluster(cluster, oldId)) {
throw new IllegalStateException("Could not adopt previous EKS container " + oldId);
}
} catch (RuntimeException rollback) {
throw new IllegalStateException("Could not restore EKS cluster " + cluster.getName()
+ " after node capacity replacement failed", rollback);
}
return false;
}
try {
lifecycleManager.removeIfExistsStrict(backupName);
} catch (RuntimeException cleanup) {
LOG.warnv("EKS cluster {0} replacement is running, but its stopped capacity backup"
+ " could not be removed: {1}; cluster deletion will retry",
cluster.getName(), cleanup.getMessage());
}
return true;
}
private static void restorePreviousNodeType(Cluster cluster, String previousType) {
if (previousType != null) {
cluster.setNodeInstanceType(previousType);
}
}
private static String capacityBackupName(Cluster cluster) {
return cluster.getDockerName() + ".capacity-backup";
}
/**
@@ -705,10 +810,88 @@ public class EksClusterManager
return;
}
lifecycleManager.stopAndRemove(cluster.getContainerId(), logStream);
if (cluster.getDockerName() != null) {
// A failed backup cleanup must not leave the live node running. Keep the cluster
// record so explicit deletion can be retried once Docker accepts the removal.
lifecycleManager.removeIfExistsStrict(capacityBackupName(cluster));
}
ContainerStorageHelper.removeNamedVolume(config, lifecycleManager, clusterResourceName(cluster));
LOG.infov("Stopped k3s container for cluster {0}", cluster.getName());
}
String selectNodeInstanceType(String requestedType) {
if (instanceTypeCatalog.find(requestedType).isPresent()) {
return requestedType;
}
LOG.warnv("EKS node instance type {0} is absent from the EC2 catalog; using {1}",
requestedType, DEFAULT_NODE_INSTANCE_TYPE);
return DEFAULT_NODE_INSTANCE_TYPE;
}
private EksNodeCapacity.Limits resolveNodeCapacity(Cluster cluster) {
try {
Info host = lifecycleManager.getDockerClient().infoCmd().exec();
CatalogInstanceType type = instanceTypeCatalog.find(nodeInstanceType(cluster)).orElseThrow();
EksNodeCapacity.Limits limits = EksNodeCapacity.calculate(type, host.getMemTotal(), host.getNCPU(),
config.services().eks().maxMemoryMib(), config.services().eks().maxVcpus());
if (limits == null) {
EksNodeCapacity.Limits configured = explicitCeilingWithoutHostInfo(cluster);
if (configured != null) {
return configured;
}
LOG.warnv("EKS cluster {0} cannot fit node type {1} and its kubelet reservations"
+ " within the Docker host; starting without resource limits",
cluster.getName(), type.instanceType);
} else if (limits.reducedReservations()) {
LOG.warnv("EKS cluster {0} memory ceiling reduces kubelet memory reservations below"
+ " the EKS AMI defaults", cluster.getName());
}
return limits;
} catch (Exception e) {
LOG.warnv("EKS cluster {0} Docker host capacity unavailable: {1}",
cluster.getName(), e.getMessage());
return explicitCeilingWithoutHostInfo(cluster);
}
}
private EksNodeCapacity.Limits explicitCeilingWithoutHostInfo(Cluster cluster) {
int maxMemoryMib = config.services().eks().maxMemoryMib();
int maxVcpus = config.services().eks().maxVcpus();
if (maxMemoryMib <= 0 && maxVcpus <= 0) {
return null;
}
int vcpus = instanceTypeCatalog.find(nodeInstanceType(cluster))
.map(type -> maxVcpus > 0 ? Math.min(type.vcpu, maxVcpus) : 0)
.orElse(maxVcpus);
LOG.warnv("Applying explicit EKS cluster {0} ceiling without kubelet reservations"
+ " because Docker host capacity is unavailable", cluster.getName());
return EksNodeCapacity.explicitCeilingWithoutHostInfo(maxMemoryMib, vcpus);
}
private static String capacityLabel(Cluster cluster, EksNodeCapacity.Limits limits) {
if (limits == null) {
return nodeInstanceType(cluster) + ":unbounded";
}
return nodeInstanceType(cluster) + ":" + limits.memoryBytes() + ":" + limits.vcpus()
+ ":" + limits.systemMemoryMib() + ":" + limits.kubeMemoryMib()
+ ":" + limits.evictionMemoryMib() + ":" + limits.systemCpuMilli()
+ ":" + limits.kubeCpuMilli() + ":" + limits.reducedReservations()
+ ":" + limits.kubeletArgsEnabled();
}
static String nodeInstanceType(Cluster cluster) {
return cluster != null && cluster.getNodeInstanceType() != null
? cluster.getNodeInstanceType() : DEFAULT_NODE_INSTANCE_TYPE;
}
/** Recreate the shared node with its named data volume intact, restoring its old type on failure. */
boolean restartForNodeCapacity(Cluster cluster, String previousType) {
if (cluster.getContainerId() == null) {
return true;
}
return replaceClusterContainer(cluster, previousType);
}
/**
* Releases Floci's hold on the given cluster (its metadata endpoint and log stream) and leaves
* the k3s container running, so a later Floci start can re-latch it through
@@ -2071,7 +2254,7 @@ public class EksClusterManager
inst.setInstanceId(instanceId);
inst.setImageId("ami-eks-k3s");
inst.setInstanceType("m5.large");
inst.setInstanceType(nodeInstanceType(cluster));
inst.setPlacement(new Placement(az));
inst.setRegion(safeRegion);
inst.setState(InstanceState.running());
@@ -92,11 +92,12 @@ public class EksController {
* causes Jackson to omit the property due to @JsonInclude(NON_DEFAULT).
*/
private Cluster toClusterResponse(Cluster cluster) {
if (cluster == null || !cluster.isExplicitVersion()) {
if (cluster == null || (!cluster.isExplicitVersion() && cluster.getNodeInstanceType() == null)) {
return cluster;
}
Cluster response = cluster.copy();
response.setExplicitVersion(false);
response.setNodeInstanceType(null);
return response;
}
@@ -0,0 +1,102 @@
package io.github.hectorvent.floci.services.eks;
import io.github.hectorvent.floci.services.ec2.Ec2InstanceTypeCatalog.CatalogInstanceType;
import java.util.List;
/** The one calculation shared by the Docker limit and the kubelet's node budget. */
final class EksNodeCapacity {
private static final long MIB = 1024L * 1024L;
private EksNodeCapacity() {}
record Limits(long memoryBytes, int vcpus, long systemMemoryMib, long kubeMemoryMib,
long evictionMemoryMib, int systemCpuMilli, int kubeCpuMilli,
boolean reducedReservations, boolean kubeletArgsEnabled) {
void addKubeletArgs(List<String> args) {
if (!kubeletArgsEnabled) {
return;
}
args.add("--kubelet-arg=system-reserved=cpu=" + systemCpuMilli + "m,memory="
+ systemMemoryMib + "Mi");
args.add("--kubelet-arg=kube-reserved=cpu=" + kubeCpuMilli + "m,memory="
+ kubeMemoryMib + "Mi");
args.add("--kubelet-arg=eviction-hard=memory.available<" + evictionMemoryMib
+ "Mi,nodefs.available<10%,nodefs.inodesFree<5%");
}
}
static Limits explicitCeilingWithoutHostInfo(int maxMemoryMib, int vcpus) {
return new Limits((long) Math.max(0, maxMemoryMib) * MIB, vcpus,
0, 0, 0, 0, 0, false, false);
}
/**
* Docker's host totals are also what kubelet sees in this nested setup. Its eviction threshold
* includes the host-to-cgroup gap; otherwise the cgroup can OOM before kubelet sees pressure.
* The EKS AMI kube reservation is 11 MiB per pod plus 255 MiB, and its CPU tiers are 6%,
* 1%, 0.5%, then 0.25% of successive cores. The additional system memory is Floci's
* container headroom, not an EKS AMI default.
*/
static Limits calculate(CatalogInstanceType type, long hostMemoryBytes, int hostCpus,
int maxMemoryMib, int maxVcpus) {
if (hostMemoryBytes <= 0 || hostCpus <= 0 || maxMemoryMib < 0 || maxVcpus < 0) {
return null;
}
long hostMib = hostMemoryBytes / MIB;
long requestedMib = type.memoryMib + Math.max(128L, type.memoryMib / 10L);
long hostLimitMib = Math.min(requestedMib, hostMib * 4 / 5);
long memoryMib = hostLimitMib;
if (maxMemoryMib > 0) {
memoryMib = Math.min(memoryMib, maxMemoryMib);
}
int vcpus = Math.min(type.vcpu, hostCpus);
if (maxVcpus > 0) {
vcpus = Math.min(vcpus, maxVcpus);
}
if (vcpus <= 0) {
return null;
}
int interfaces = type.networkCards.stream()
.filter(card -> card.networkCardIndex != null && card.networkCardIndex == 0
&& card.maximumNetworkInterfaces != null)
.mapToInt(card -> card.maximumNetworkInterfaces)
.findFirst().orElse(0);
int addresses = type.ipv4AddressesPerInterface == null ? 0 : type.ipv4AddressesPerInterface;
int podCap = type.vcpu > 30 ? 250 : 110;
int maxPods = interfaces > 0 && addresses > 0
? Math.min(podCap, interfaces * (addresses - 1) + 2) : podCap;
long kubeMemoryMib = 11L * maxPods + 255;
long systemMemoryMib = Math.max(128, memoryMib / 10);
long evictionBufferMib = Math.min(100, memoryMib / 4);
// Only an undersized host with no explicit ceiling falls back to the old unbounded mode.
// An operator's ceiling must remain a hard bound, even if it leaves few resources for pods.
if (maxMemoryMib == 0 && memoryMib < kubeMemoryMib + systemMemoryMib + evictionBufferMib + 256) {
return null;
}
if (memoryMib <= 0) {
return null;
}
boolean reducedReservations = maxMemoryMib > 0
&& memoryMib < kubeMemoryMib + systemMemoryMib + evictionBufferMib + 256;
if (reducedReservations) {
long reservableMib = Math.max(0, memoryMib - evictionBufferMib - 1);
kubeMemoryMib = Math.min(kubeMemoryMib, reservableMib / 2);
systemMemoryMib = Math.min(systemMemoryMib, reservableMib - kubeMemoryMib);
}
int kubeCpuMilli = cpuReservationMilli(vcpus);
int systemCpuMilli = (hostCpus - vcpus) * 1000;
long evictionMemoryMib = hostMib - memoryMib + evictionBufferMib;
return new Limits(memoryMib * MIB, vcpus, systemMemoryMib, kubeMemoryMib,
evictionMemoryMib, systemCpuMilli, kubeCpuMilli, reducedReservations, true);
}
private static int cpuReservationMilli(int vcpus) {
int first = Math.min(vcpus, 1) * 60;
int second = Math.min(Math.max(vcpus - 1, 0), 1) * 10;
int third = Math.min(Math.max(vcpus - 2, 0), 2) * 5;
int rest = Math.max(vcpus - 4, 0) * 25 / 10;
return first + second + third + rest;
}
}
@@ -48,6 +48,7 @@ import org.jboss.logging.Logger;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.HexFormat;
@@ -102,6 +103,8 @@ public class EksService implements TagHandler, ResourceProvider {
private final EksAddonService addons;
private final ScheduledExecutorService poller = Executors.newSingleThreadScheduledExecutor();
private final Map<String, UserDataClaim> appliedClusterUserData = new ConcurrentHashMap<>();
private final Map<String, Object> nodeGroupCapacityLocks = new ConcurrentHashMap<>();
private final Map<String, CompletableFuture<Boolean>> pendingFirstNodeGroups = new ConcurrentHashMap<>();
@Inject
public EksService(StorageFactory storageFactory, EmulatorConfig config,
@@ -204,6 +207,10 @@ public class EksService implements TagHandler, ResourceProvider {
LOG.infov("Restoring k3s container for persisted EKS cluster {0}", cluster.getName());
cluster.setStatus(ClusterStatus.CREATING);
cluster.setPodCidr(EksClusterManager.DEFAULT_POD_CIDR);
if (cluster.getNodeInstanceType() == null) {
firstNodeGroup(cluster.getName(), entry.accountId()).ifPresent(group ->
cluster.setNodeInstanceType(selectedNodeInstanceType(group)));
}
clusterManager.restoreCluster(cluster);
} catch (Exception e) {
if (!clusterManager.isDockerReachable()) {
@@ -233,6 +240,22 @@ public class EksService implements TagHandler, ResourceProvider {
.toList();
}
private Optional<Nodegroup> firstNodeGroup(String clusterName, String accountId) {
String prefix = clusterName + "/";
List<Nodegroup> groups;
if (nodeGroupStorage instanceof AccountAwareStorageBackend<Nodegroup> aware) {
groups = aware.scanAllAccountEntries(key -> key.startsWith(prefix)).stream()
.filter(entry -> accountId.equals(entry.accountId()))
.map(AccountAwareStorageBackend.AccountEntry::value).toList();
} else {
groups = nodeGroupStorage.scan(key -> key.startsWith(prefix));
}
return groups.stream().filter(group -> group.getStatus() == NodegroupStatus.ACTIVE)
.min(Comparator.comparing(Nodegroup::getCreatedAt,
Comparator.nullsLast(Comparator.naturalOrder()))
.thenComparing(Nodegroup::getNodegroupName));
}
/**
* Gives clusters persisted before IRSA support an OIDC issuer and signing key. Without this,
* a cluster restored from {@code eks-clusters.json} would report no
@@ -440,10 +463,15 @@ public class EksService implements TagHandler, ResourceProvider {
if (!config.services().eks().mock()) {
boolean keepRunning = config.services().eks().keepRunningOnShutdown();
for (Cluster cluster : allClusters()) {
if (keepRunning) {
clusterManager.detachCluster(cluster);
} else {
clusterManager.stopCluster(cluster);
try {
if (keepRunning) {
clusterManager.detachCluster(cluster);
} else {
clusterManager.stopCluster(cluster);
}
} catch (RuntimeException e) {
LOG.warnv("Could not clean up EKS cluster {0} during shutdown: {1}",
cluster.getName(), e.getMessage());
}
}
}
@@ -713,15 +741,130 @@ public class EksService implements TagHandler, ResourceProvider {
nodeGroup.setLabels(request.getLabels() != null ? new HashMap<>(request.getLabels()) : null);
nodeGroup.setTags(request.getTags() != null ? new HashMap<>(request.getTags()) : new HashMap<>());
if (launchTemplateData != null && launchTemplateData.getUserData() != null
&& !launchTemplateData.getUserData().isBlank()) {
applyNodeGroupUserData(cluster, nodegroupName, launchTemplateData.getUserData(), nodeGroup);
}
String capacityKey = accountId + "/" + clusterName;
Object capacityLock = nodeGroupCapacityLocks.computeIfAbsent(capacityKey,
ignored -> new Object());
boolean hasUserData = launchTemplateData != null && launchTemplateData.getUserData() != null
&& !launchTemplateData.getUserData().isBlank();
Cluster currentCluster;
CompletableFuture<Boolean> pendingFirst;
boolean ownsPendingFirst = false;
synchronized (capacityLock) {
if (nodeGroupStorage.get(storageKey).isPresent()) {
throw new AwsException("ResourceInUseException",
"Nodegroup already exists: " + nodegroupName, 409);
}
currentCluster = describeCluster(clusterName);
pendingFirst = pendingFirstNodeGroups.get(capacityKey);
boolean firstGroup = firstNodeGroup(clusterName, accountId).isEmpty() && pendingFirst == null;
if (firstGroup && !config.services().eks().mock() && clusterManager != null) {
applyFirstNodeGroupCapacity(clusterName, nodegroupName, currentCluster, nodeGroup);
} else if (!firstGroup && pendingFirst == null
&& !config.services().eks().mock() && clusterManager != null) {
if (currentCluster.getNodeInstanceType() == null) {
firstNodeGroup(clusterName, accountId).ifPresent(group ->
currentCluster.setNodeInstanceType(selectedNodeInstanceType(group)));
storage.put(clusterName, currentCluster);
}
if (!nodeGroup.getInstanceTypes().isEmpty()
&& !nodeGroup.getInstanceTypes().contains(currentCluster.getNodeInstanceType())) {
LOG.warnv("EKS cluster {0} has one shared node; nodegroup {1} cannot change its capacity from {2}",
clusterName, nodegroupName, currentCluster.getNodeInstanceType());
}
}
nodeGroupStorage.put(storageKey, nodeGroup);
if (nodeGroup.getStatus() == NodegroupStatus.ACTIVE && (hasUserData || pendingFirst != null)) {
nodeGroup.setStatus(NodegroupStatus.CREATING);
if (firstGroup && hasUserData) {
pendingFirst = new CompletableFuture<>();
ownsPendingFirst = true;
}
}
nodeGroupStorage.put(storageKey, nodeGroup);
if (ownsPendingFirst) {
pendingFirstNodeGroups.put(capacityKey, pendingFirst);
}
}
if (nodeGroup.getStatus() == NodegroupStatus.CREATING && hasUserData) {
try {
applyNodeGroupUserData(currentCluster, nodegroupName, launchTemplateData.getUserData(), nodeGroup);
} catch (Throwable e) {
synchronized (capacityLock) {
if (nodeGroupStorage.get(storageKey)
.filter(saved -> arn.equals(saved.getNodegroupArn())).isPresent()) {
nodeGroupStorage.delete(storageKey);
}
if (ownsPendingFirst) {
pendingFirstNodeGroups.remove(capacityKey, pendingFirst);
pendingFirst.complete(false);
}
}
throw e;
}
}
if (pendingFirst != null && !ownsPendingFirst) {
pendingFirst.join();
}
synchronized (capacityLock) {
boolean stored = false;
try {
if (nodeGroupStorage.get(storageKey)
.filter(saved -> arn.equals(saved.getNodegroupArn())).isPresent()) {
if (nodeGroup.getStatus() == NodegroupStatus.CREATING) {
if (!ownsPendingFirst && firstNodeGroup(clusterName, accountId).isEmpty()
&& !config.services().eks().mock() && clusterManager != null) {
Cluster refreshedCluster = describeCluster(clusterName);
applyFirstNodeGroupCapacity(clusterName, nodegroupName, refreshedCluster, nodeGroup);
}
if (nodeGroup.getStatus() == NodegroupStatus.CREATING) {
nodeGroup.setStatus(NodegroupStatus.ACTIVE);
}
}
nodeGroupStorage.put(storageKey, nodeGroup);
stored = true;
}
} finally {
if (ownsPendingFirst) {
pendingFirstNodeGroups.remove(capacityKey, pendingFirst);
pendingFirst.complete(stored && nodeGroup.getStatus() == NodegroupStatus.ACTIVE);
}
}
}
return nodeGroup;
}
private void applyFirstNodeGroupCapacity(String clusterName, String nodegroupName,
Cluster currentCluster, Nodegroup nodeGroup) {
String selectedType = selectedNodeInstanceType(nodeGroup);
String previousType = EksClusterManager.nodeInstanceType(currentCluster);
currentCluster.setNodeInstanceType(selectedType);
if (currentCluster.getContainerId() != null && !selectedType.equals(previousType)) {
currentCluster.setStatus(ClusterStatus.CREATING);
try {
if (!clusterManager.restartForNodeCapacity(currentCluster, previousType)) {
nodeGroup.setStatus(NodegroupStatus.CREATE_FAILED);
nodeGroup.setHealth(failedNodeGroupHealth(nodegroupName,
"Could not apply node capacity; the previous node was restored"));
}
} catch (RuntimeException e) {
currentCluster.setNodeInstanceType(previousType);
currentCluster.setStatus(ClusterStatus.FAILED);
nodeGroup.setStatus(NodegroupStatus.CREATE_FAILED);
nodeGroup.setHealth(failedNodeGroupHealth(nodegroupName, e.getMessage()));
LOG.errorv("EKS cluster {0} could not recover after node capacity change: {1}",
clusterName, e.getMessage());
}
}
storage.put(clusterName, currentCluster);
}
private String selectedNodeInstanceType(Nodegroup group) {
String requestedType = group.getInstanceTypes() == null || group.getInstanceTypes().isEmpty()
? null : group.getInstanceTypes().getFirst();
String selectedType = clusterManager.selectNodeInstanceType(requestedType);
return selectedType != null ? selectedType : EksClusterManager.DEFAULT_NODE_INSTANCE_TYPE;
}
private LaunchTemplateData validateLaunchTemplate(String region, Object launchTemplateObj) {
if (!(launchTemplateObj instanceof Map<?, ?> map)) {
return null;
@@ -775,11 +918,15 @@ public class EksService implements TagHandler, ResourceProvider {
}
public Nodegroup deleteNodeGroup(String clusterName, String nodegroupName) {
Nodegroup nodeGroup = describeNodeGroup(clusterName, nodegroupName);
nodeGroup.setStatus(NodegroupStatus.DELETING);
nodeGroup.setModifiedAt(Instant.now());
nodeGroupStorage.delete(nodeGroupKey(clusterName, nodegroupName));
return nodeGroup;
Object capacityLock = nodeGroupCapacityLocks.computeIfAbsent(
regionResolver.getAccountId() + "/" + clusterName, ignored -> new Object());
synchronized (capacityLock) {
Nodegroup nodeGroup = describeNodeGroup(clusterName, nodegroupName);
nodeGroup.setStatus(NodegroupStatus.DELETING);
nodeGroup.setModifiedAt(Instant.now());
nodeGroupStorage.delete(nodeGroupKey(clusterName, nodegroupName));
return nodeGroup;
}
}
public FargateProfile createFargateProfile(String clusterName, CreateFargateProfileRequest request) {
@@ -96,6 +96,11 @@ public class Cluster {
@JsonIgnore
private String dockerName;
/** Instance type selected for the single shared node container. Internal persisted metadata. */
@JsonProperty("nodeInstanceType")
@JsonInclude(JsonInclude.Include.NON_NULL)
private String nodeInstanceType;
private AccessConfig accessConfig;
public AccessConfig getAccessConfig() { return accessConfig; }
@@ -145,6 +150,9 @@ public class Cluster {
public String getContainerId() { return containerId; }
public void setContainerId(String containerId) { this.containerId = containerId; }
public String getNodeInstanceType() { return nodeInstanceType; }
public void setNodeInstanceType(String nodeInstanceType) { this.nodeInstanceType = nodeInstanceType; }
public String getAccountId() { return accountId; }
public void setAccountId(String accountId) { this.accountId = accountId; }
@@ -193,6 +201,7 @@ public class Cluster {
c.podCidr = this.podCidr;
c.explicitVersion = this.explicitVersion;
c.dockerName = this.dockerName;
c.nodeInstanceType = this.nodeInstanceType;
c.accessConfig = this.accessConfig;
return c;
}