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

@@ -12,6 +12,8 @@ import com.github.dockerjava.api.model.StreamType;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.Closeable;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.function.Consumer;
@@ -106,8 +108,10 @@ class ContainerExecTest {
}
@Test
void aCommandThatOutlivesItsTimeoutIsReportedWithWhatItPrintedSoFar() {
void aCommandThatOutlivesItsTimeoutIsReportedWithWhatItPrintedSoFar() throws IOException {
Closeable attach = mock(Closeable.class);
startWith(callback -> {
callback.onStart(attach);
callback.onNext(frame(StreamType.STDOUT, "partial"));
callback.onNext(frame(StreamType.STDERR, "warning"));
});
@@ -118,6 +122,7 @@ class ContainerExecTest {
assertEquals(-1L, result.exitCode());
assertEquals("partial", result.stdout());
assertEquals("warning\nTimed out after 0s", result.stderr());
verify(attach).close();
verify(dockerClient, never()).inspectExecCmd(EXEC_ID);
}
@@ -172,13 +177,14 @@ class ContainerExecTest {
}
@Test
void anInterruptIsRaisedAndTheInterruptFlagKept() {
startWith(callback -> {
});
void anInterruptIsRaisedAndTheInterruptFlagKept() throws IOException {
Closeable attach = mock(Closeable.class);
startWith(callback -> callback.onStart(attach));
Thread.currentThread().interrupt();
try {
assertThrows(IllegalStateException.class, () -> ContainerExec.run(dockerClient, CONTAINER_ID, CMD, 5));
assertTrue(Thread.currentThread().isInterrupted());
verify(attach).close();
} finally {
Thread.interrupted();
}
@@ -39,7 +39,9 @@ import com.github.dockerjava.api.command.InspectExecResponse;
import com.github.dockerjava.api.command.InspectVolumeCmd;
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.services.ec2.Ec2InstanceTypeCatalog;
import io.github.hectorvent.floci.services.ec2.Ec2MetadataServer;
import io.github.hectorvent.floci.services.ec2.model.Instance;
import org.junit.jupiter.api.BeforeEach;
@@ -319,7 +321,8 @@ class EksClusterManagerTest {
"io.floci.service", "eks",
"io.floci.resource-id", "my-cluster",
"io.floci.account", "000000000000",
"io.floci.region", "us-east-1"));
"io.floci.region", "us-east-1",
"io.floci.eks.node-capacity", "m5.large:unbounded"));
}
@ParameterizedTest
@@ -362,6 +365,7 @@ class EksClusterManagerTest {
private EmulatorConfig.StorageConfig storage;
private ContainerLifecycleManager lifecycleManager;
private PortAllocator portAllocator;
private DockerClient dockerClient;
private EksClusterManager manager;
@BeforeEach
@@ -388,6 +392,8 @@ class EksClusterManagerTest {
when(containerBuilder.newContainer(anyString())).thenReturn(builder);
when(builder.build()).thenReturn(Mockito.mock(ContainerSpec.class));
portAllocator = Mockito.mock(PortAllocator.class);
dockerClient = Mockito.mock(DockerClient.class, Mockito.RETURNS_DEEP_STUBS);
when(lifecycleManager.getDockerClient()).thenReturn(dockerClient);
manager = new EksClusterManager(containerBuilder, lifecycleManager,
Mockito.mock(ContainerDetector.class), portAllocator,
@@ -397,12 +403,14 @@ class EksClusterManagerTest {
// Container's getters are final, so survivors are built from JSON instead of mocked.
private Container survivingContainer(String id) {
return containerFromJson("{\"Id\":\"" + id + "\"}");
return containerFromJson("{\"Id\":\"" + id + "\","
+ "\"Labels\":{\"io.floci.eks.node-capacity\":\"m5.large:unbounded\"}}");
}
private Container survivingContainerOwnedBy(String id, String accountId) {
return containerFromJson("{\"Id\":\"" + id + "\","
+ "\"Labels\":{\"io.floci.account\":\"" + accountId + "\"}}");
+ "\"Labels\":{\"io.floci.account\":\"" + accountId + "\","
+ "\"io.floci.eks.node-capacity\":\"m5.large:unbounded\"}}");
}
private Container containerFromJson(String json) {
@@ -446,6 +454,136 @@ class EksClusterManagerTest {
verify(lifecycleManager, never()).create(any());
}
@Test
void recreatesAnOldSurvivorWithoutCapacityLimits() {
when(lifecycleManager.findByName("floci-eks-demo"))
.thenReturn(Optional.of(containerFromJson("{\"Id\":\"cid-old\"}")));
when(lifecycleManager.adopt("cid-old", List.of(6443)))
.thenReturn(new ContainerInfo("cid-old", Map.of(), Map.of(6443, 6440)));
stubFreshStart("cid-new", 6440);
Cluster cluster = cluster();
manager.restoreCluster(cluster);
assertEquals("cid-new", cluster.getContainerId());
verify(lifecycleManager).create(any());
verify(portAllocator, never()).allocate(6440, 6499);
verify(dockerClient).stopContainerCmd("cid-old");
}
@Test
void restoresOldSurvivorWhenCapacityReplacementFails() {
when(lifecycleManager.findByName("floci-eks-demo"))
.thenReturn(Optional.of(containerFromJson("{\"Id\":\"cid-old\"}")));
when(lifecycleManager.adopt("cid-old", List.of(6443)))
.thenReturn(new ContainerInfo("cid-old", Map.of(), Map.of(6443, 6440)));
when(lifecycleManager.create(any())).thenReturn("cid-new");
when(lifecycleManager.startCreated(any(), any()))
.thenThrow(new RuntimeException("replacement failed"));
Cluster cluster = cluster();
manager.restoreCluster(cluster);
assertEquals("cid-old", cluster.getContainerId());
assertEquals(6440, cluster.getHostPort());
verify(lifecycleManager).removeIfExistsStrict("floci-eks-demo");
verify(dockerClient).stopContainerCmd("cid-old");
verify(portAllocator, never()).allocate(6440, 6499);
}
@Test
void firstNodeGroupReplacementKeepsTheClusterEndpoint() {
when(lifecycleManager.create(any())).thenReturn("cid-new");
when(lifecycleManager.startCreated(any(), any()))
.thenReturn(new ContainerInfo("cid-new", Map.of()));
Cluster cluster = cluster();
cluster.setDockerName("floci-eks-demo");
cluster.setContainerId("cid-old");
cluster.setHostPort(6441);
cluster.setNodeInstanceType("t3.medium");
assertTrue(manager.restartForNodeCapacity(cluster, "m5.large"));
assertEquals("cid-new", cluster.getContainerId());
assertEquals(6441, cluster.getHostPort());
assertEquals("https://localhost:6441", cluster.getEndpoint());
verify(portAllocator, never()).allocate(6440, 6499);
verify(portAllocator, never()).release(6441);
verify(dockerClient).stopContainerCmd("cid-old");
verify(lifecycleManager, Mockito.times(2))
.removeIfExistsStrict("floci-eks-demo.capacity-backup");
}
@Test
void capacityBackupDoesNotCollideWithAnotherClusterName() {
when(lifecycleManager.create(any())).thenReturn("cid-new");
when(lifecycleManager.startCreated(any(), any()))
.thenReturn(new ContainerInfo("cid-new", Map.of()));
Cluster cluster = cluster();
cluster.setName("foo");
cluster.setDockerName("floci-eks-foo");
cluster.setContainerId("cid-foo");
cluster.setHostPort(6441);
cluster.setNodeInstanceType("t3.medium");
Cluster other = cluster();
other.setName("foo-capacity-backup");
other.setDockerName("floci-eks-foo-capacity-backup");
other.setContainerId("cid-other");
assertTrue(manager.restartForNodeCapacity(cluster, "m5.large"));
manager.stopCluster(cluster);
assertTrue(other.getName().matches(EksService.CLUSTER_NAME_REGEX));
assertFalse("foo.capacity-backup".matches(EksService.CLUSTER_NAME_REGEX));
assertEquals("floci-eks-foo-capacity-backup", manager.clusterResourceName(other));
verify(lifecycleManager, Mockito.times(3))
.removeIfExistsStrict("floci-eks-foo.capacity-backup");
verify(lifecycleManager, never()).removeIfExistsStrict(other.getDockerName());
verify(lifecycleManager, never()).stopAndRemove("cid-other", null);
}
@Test
void failedFirstNodeGroupReplacementRestoresPreviousContainerAndType() {
when(lifecycleManager.create(any())).thenReturn("cid-new");
when(lifecycleManager.startCreated(any(), any()))
.thenThrow(new IllegalStateException("replacement failed"));
when(lifecycleManager.adopt("cid-old", List.of(6443)))
.thenReturn(new ContainerInfo("cid-old", Map.of(), Map.of(6443, 6441)));
Cluster cluster = cluster();
cluster.setDockerName("floci-eks-demo");
cluster.setContainerId("cid-old");
cluster.setHostPort(6441);
cluster.setNodeInstanceType("t3.medium");
assertFalse(manager.restartForNodeCapacity(cluster, "m5.large"));
assertEquals("m5.large", cluster.getNodeInstanceType());
assertEquals("cid-old", cluster.getContainerId());
assertEquals(6441, cluster.getHostPort());
assertEquals("https://localhost:6441", cluster.getEndpoint());
verify(portAllocator, never()).allocate(6440, 6499);
verify(portAllocator, never()).release(6441);
verify(lifecycleManager, never()).removeVolume(anyString());
}
@Test
void backupCleanupFailureKeepsTheNewNodeRunning() {
when(lifecycleManager.findByName("floci-eks-demo"))
.thenReturn(Optional.of(containerFromJson("{\"Id\":\"cid-old\"}")));
when(lifecycleManager.adopt("cid-old", List.of(6443)))
.thenReturn(new ContainerInfo("cid-old", Map.of(), Map.of(6443, 6440)));
stubFreshStart("cid-new", 6440);
Mockito.doNothing().doThrow(new IllegalStateException("Docker cleanup failed"))
.when(lifecycleManager).removeIfExistsStrict("floci-eks-demo.capacity-backup");
Cluster cluster = cluster();
manager.restoreCluster(cluster);
assertEquals("cid-new", cluster.getContainerId());
verify(lifecycleManager, Mockito.times(1)).adopt("cid-old", List.of(6443));
verify(lifecycleManager, never()).removeIfExistsStrict("floci-eks-demo");
}
@Test
void recreatesTheContainerWhenNoneSurvives() {
when(lifecycleManager.findByName("floci-eks-demo")).thenReturn(Optional.empty());
@@ -504,6 +642,20 @@ class EksClusterManagerTest {
verify(lifecycleManager, never()).removeVolume(anyString());
}
@Test
void backupCleanupFailureDoesNotLeaveTheLiveNodeRunning() {
Cluster cluster = cluster();
cluster.setDockerName("floci-eks-demo");
cluster.setContainerId("cid-new");
Mockito.doThrow(new IllegalStateException("Docker cleanup failed"))
.when(lifecycleManager).removeIfExistsStrict("floci-eks-demo.capacity-backup");
assertThrows(IllegalStateException.class, () -> manager.stopCluster(cluster));
verify(lifecycleManager).stopAndRemove("cid-new", null);
verify(lifecycleManager, never()).removeVolume(anyString());
}
@Test
void stopClusterRemovesTheDataVolumeInMemoryStorageMode() {
when(storage.mode()).thenReturn("memory");
@@ -1454,6 +1606,8 @@ class EksClusterManagerTest {
Container container = Mockito.mock(Container.class);
when(container.getId()).thenReturn("surviving-container-id");
when(container.getLabels()).thenReturn(Map.of(
"io.floci.eks.node-capacity", "m5.large:unbounded"));
when(lifecycleManager.findByName("floci-eks-my-cluster")).thenReturn(Optional.of(container));
when(lifecycleManager.adopt(anyString(), any())).thenReturn(
new ContainerInfo("surviving-container-id", Map.of(6443, new ContainerLifecycleManager.EndpointInfo("localhost", 6500)), Map.of(6443, 6500)));
@@ -1745,6 +1899,74 @@ class EksClusterManagerTest {
config, regionResolver, null, Mockito.mock(EksOidcService.class));
}
@Test
void nodeGroupTypeControlsContainerAndSynthesizedInstance() {
DockerClient dockerClient = Mockito.mock(DockerClient.class, Mockito.RETURNS_DEEP_STUBS);
Info host = Mockito.mock(Info.class);
when(host.getMemTotal()).thenReturn(16L * 1024 * 1024 * 1024);
when(host.getNCPU()).thenReturn(8);
when(dockerClient.infoCmd().exec()).thenReturn(host);
when(lifecycleManager.getDockerClient()).thenReturn(dockerClient);
Cluster cluster = new Cluster();
cluster.setName("capacity-cluster");
cluster.setNodeInstanceType(manager.selectNodeInstanceType("t3.medium"));
manager.startCluster(cluster);
Ec2InstanceTypeCatalog catalog = new Ec2InstanceTypeCatalog();
EksNodeCapacity.Limits limits = EksNodeCapacity.calculate(
catalog.find("t3.medium").orElseThrow(), host.getMemTotal(), host.getNCPU(), 0, 0);
verify(builder).withMemoryBytes(limits.memoryBytes());
verify(builder).withCpuUnits(limits.vcpus() * 1024);
@SuppressWarnings("unchecked")
ArgumentCaptor<List<String>> cmdCaptor = ArgumentCaptor.forClass(List.class);
verify(builder).withCmd(cmdCaptor.capture());
List<String> expectedArgs = new ArrayList<>();
limits.addKubeletArgs(expectedArgs);
assertTrue(cmdCaptor.getValue().containsAll(expectedArgs));
assertEquals("t3.medium", manager.synthesizeClusterNodeInstance(
cluster, "172.17.0.2", "us-east-1", "000000000000").getInstanceType());
}
@Test
void hostTooSmallLeavesClusterUnboundedAndStarting() {
DockerClient dockerClient = Mockito.mock(DockerClient.class, Mockito.RETURNS_DEEP_STUBS);
Info host = Mockito.mock(Info.class);
when(host.getMemTotal()).thenReturn(1024L * 1024 * 1024);
when(host.getNCPU()).thenReturn(2);
when(dockerClient.infoCmd().exec()).thenReturn(host);
when(lifecycleManager.getDockerClient()).thenReturn(dockerClient);
Cluster cluster = new Cluster();
cluster.setName("small-host");
assertDoesNotThrow(() -> manager.startCluster(cluster));
verify(builder, never()).withMemoryBytes(Mockito.anyLong());
verify(builder, never()).withCpuUnits(Mockito.anyInt());
@SuppressWarnings("unchecked")
ArgumentCaptor<List<String>> cmdCaptor = ArgumentCaptor.forClass(List.class);
verify(builder).withCmd(cmdCaptor.capture());
assertFalse(cmdCaptor.getValue().stream().anyMatch(arg -> arg.contains("reserved=")
|| arg.contains("eviction-hard=")));
}
@Test
void explicitCeilingSurvivesMissingDockerHostInformation() {
when(eks.maxMemoryMib()).thenReturn(512);
when(eks.maxVcpus()).thenReturn(1);
Cluster cluster = new Cluster();
cluster.setName("capped-cluster");
manager.startCluster(cluster);
verify(builder).withMemoryBytes(512L * 1024 * 1024);
verify(builder).withCpuUnits(1024);
@SuppressWarnings("unchecked")
ArgumentCaptor<List<String>> cmdCaptor = ArgumentCaptor.forClass(List.class);
verify(builder).withCmd(cmdCaptor.capture());
assertFalse(cmdCaptor.getValue().stream().anyMatch(arg -> arg.contains("reserved=")
|| arg.contains("eviction-hard=")));
}
@Test
void resolveClusterImageMapsSupportedVersions() {
Cluster cluster = new Cluster();
@@ -2208,6 +2430,8 @@ class EksClusterManagerTest {
void restoreClusterAttachesLogsForAdoptedContainer() {
Container container = Mockito.mock(Container.class);
when(container.getId()).thenReturn("adopted-container-id-12345678901234567890");
when(container.getLabels()).thenReturn(Map.of(
"io.floci.eks.node-capacity", "m5.large:unbounded"));
when(lifecycleManager.findByName("floci-eks-prod-cluster")).thenReturn(Optional.of(container));
when(lifecycleManager.adopt(anyString(), any())).thenReturn(
new ContainerInfo("adopted-container-id-12345678901234567890",
@@ -342,6 +342,52 @@ class EksLaunchTemplateUserDataTest {
}
}
@Test
void laterGroupWaitsForFirstBootstrapBeforeBecomingActive() throws InterruptedException {
String script = "#!/bin/bash\nexit 1\n";
String encoded = Base64.getEncoder().encodeToString(script.getBytes(StandardCharsets.UTF_8));
String ltId = createLaunchTemplate("lt-pending-first", encoded);
CountDownLatch enteredExecution = new CountDownLatch(1);
CountDownLatch releaseExecution = new CountDownLatch(1);
when(clusterManager.executeUserData(any(Cluster.class), eq("ng-1"), eq(encoded)))
.thenAnswer(invocation -> {
enteredExecution.countDown();
assertTrue(releaseExecution.await(5, TimeUnit.SECONDS));
return UserDataPipeline.ExecutionResult.failed(1L, 1, 1, "bootstrap failed");
});
CreateNodeGroupRequest firstRequest = nodeGroupRequest("ng-1");
firstRequest.setLaunchTemplate(Map.of("id", ltId));
AtomicReference<Nodegroup> firstResult = new AtomicReference<>();
Thread first = new Thread(() -> firstResult.set(eksService.createNodeGroup(CLUSTER_NAME, firstRequest)));
first.start();
try {
assertTrue(enteredExecution.await(5, TimeUnit.SECONDS));
assertEquals(NodegroupStatus.CREATING,
eksService.describeNodeGroup(CLUSTER_NAME, "ng-1").getStatus());
AtomicReference<Nodegroup> secondResult = new AtomicReference<>();
Thread second = new Thread(() -> secondResult.set(
eksService.createNodeGroup(CLUSTER_NAME, nodeGroupRequest("ng-2"))));
second.start();
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5);
while (!eksService.listNodeGroups(CLUSTER_NAME).contains("ng-2")
&& System.nanoTime() < deadline) {
Thread.sleep(10);
}
assertEquals(NodegroupStatus.CREATING,
eksService.describeNodeGroup(CLUSTER_NAME, "ng-2").getStatus());
releaseExecution.countDown();
first.join(5000);
second.join(5000);
assertEquals(NodegroupStatus.CREATE_FAILED, firstResult.get().getStatus());
assertEquals(NodegroupStatus.ACTIVE, secondResult.get().getStatus());
} finally {
releaseExecution.countDown();
}
}
@Test
void unstubbedClusterManagerDoesNotThrowNpe() {
String script = "#!/bin/bash\necho 'unstubbed'\n";
@@ -0,0 +1,84 @@
package io.github.hectorvent.floci.services.eks;
import io.github.hectorvent.floci.services.ec2.Ec2InstanceTypeCatalog;
import io.github.hectorvent.floci.services.ec2.Ec2InstanceTypeCatalog.CatalogInstanceType;
import io.github.hectorvent.floci.services.ec2.Ec2InstanceTypeCatalog.CatalogNetworkCard;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
class EksNodeCapacityTest {
private static final long MIB = 1024L * 1024L;
private final Ec2InstanceTypeCatalog catalog = new Ec2InstanceTypeCatalog();
@Test
void reservationsFollowTheAppliedLimitAndTheInstancePodDensity() {
CatalogInstanceType type = catalog.find("m5.large").orElseThrow();
long hostMib = 16384;
EksNodeCapacity.Limits limits = EksNodeCapacity.calculate(type, hostMib * MIB, 8, 0, 0);
long limitMib = limits.memoryBytes() / MIB;
int maxPods = type.networkCards.getFirst().maximumNetworkInterfaces
* (type.ipv4AddressesPerInterface - 1) + 2;
assertEquals(type.memoryMib + Math.max(128, type.memoryMib / 10), limitMib);
assertEquals(type.vcpu, limits.vcpus());
assertEquals(255 + 11L * maxPods, limits.kubeMemoryMib());
assertEquals(Math.max(128, limitMib / 10), limits.systemMemoryMib());
assertEquals(hostMib - limitMib + 100, limits.evictionMemoryMib());
assertEquals((8 - limits.vcpus()) * 1000, limits.systemCpuMilli());
assertEquals(70, limits.kubeCpuMilli());
List<String> args = new ArrayList<>();
limits.addKubeletArgs(args);
assertTrue(args.contains("--kubelet-arg=system-reserved=cpu=" + limits.systemCpuMilli()
+ "m,memory=" + limits.systemMemoryMib() + "Mi"));
assertTrue(args.contains("--kubelet-arg=kube-reserved=cpu=" + limits.kubeCpuMilli()
+ "m,memory=" + limits.kubeMemoryMib() + "Mi"));
assertTrue(args.contains("--kubelet-arg=eviction-hard=memory.available<"
+ limits.evictionMemoryMib() + "Mi,nodefs.available<10%,nodefs.inodesFree<5%"));
}
@Test
void hostAndUserCeilingsBoundTheContainerAndReservations() {
CatalogInstanceType type = catalog.find("m5.large").orElseThrow();
EksNodeCapacity.Limits limits = EksNodeCapacity.calculate(type, 8192 * MIB, 4, 4096, 1);
assertEquals(4096 * MIB, limits.memoryBytes());
assertEquals(1, limits.vcpus());
assertEquals(60, limits.kubeCpuMilli());
assertEquals(3000, limits.systemCpuMilli());
assertEquals(8192 - 4096 + 100, limits.evictionMemoryMib());
}
@Test
void largeManagedNodeUsesThe250PodCapForMemoryReservation() {
CatalogInstanceType type = new CatalogInstanceType();
type.vcpu = 32;
type.memoryMib = 131072;
type.ipv4AddressesPerInterface = 50;
CatalogNetworkCard card = new CatalogNetworkCard();
card.networkCardIndex = 0;
card.maximumNetworkInterfaces = 15;
type.networkCards = List.of(card);
EksNodeCapacity.Limits limits = EksNodeCapacity.calculate(type, 262144 * MIB, 64, 0, 0);
assertEquals(255 + 11 * 250, limits.kubeMemoryMib());
}
@Test
void tooSmallHostOrMissingHostInformationFallsBackToUnbounded() {
CatalogInstanceType type = catalog.find("m5.large").orElseThrow();
assertNull(EksNodeCapacity.calculate(type, 1024 * MIB, 2, 0, 0));
assertNull(EksNodeCapacity.calculate(type, 0, 0, 0, 0));
EksNodeCapacity.Limits capped = EksNodeCapacity.calculate(type, 8192 * MIB, 2, 512, 0);
assertNotNull(capped);
assertEquals(512 * MIB, capped.memoryBytes());
assertTrue(capped.kubeMemoryMib() + capped.systemMemoryMib()
+ 100 < capped.memoryBytes() / MIB);
}
}
@@ -52,14 +52,21 @@ import java.nio.file.Path;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@@ -901,6 +908,69 @@ class EksServiceTest {
assertEquals("1.30-eks-1", nodeGroup.getReleaseVersion());
}
@Test
void firstNodeGroupSelectsAndRestartsTheSharedNodeOnce() {
EksClusterManager clusterManager = mock(EksClusterManager.class);
when(clusterManager.tryStartCluster(any())).thenReturn(true);
when(clusterManager.selectNodeInstanceType("t3.medium")).thenReturn("t3.medium");
when(clusterManager.restartForNodeCapacity(any(), anyString())).thenReturn(true);
EksService service = newService(clusterManager, false);
CreateClusterRequest request = new CreateClusterRequest();
request.setName("capacity-cluster");
request.setRoleArn("arn:aws:iam::000000000000:role/eks-role");
Cluster cluster = service.createCluster(request);
cluster.setContainerId("existing-container");
service.createNodeGroup("capacity-cluster", nodeGroupRequest("first"));
assertEquals("t3.medium", cluster.getNodeInstanceType());
verify(clusterManager).restartForNodeCapacity(cluster, "m5.large");
service.createNodeGroup("capacity-cluster", nodeGroupRequest("second"));
verify(clusterManager).restartForNodeCapacity(cluster, "m5.large");
}
@Test
void concurrentFirstNodeGroupsChooseOnlyOneCapacity() throws Exception {
EksClusterManager clusterManager = mock(EksClusterManager.class);
when(clusterManager.tryStartCluster(any())).thenReturn(true);
when(clusterManager.selectNodeInstanceType("t3.medium")).thenReturn("t3.medium");
CountDownLatch restartEntered = new CountDownLatch(1);
CountDownLatch releaseRestart = new CountDownLatch(1);
when(clusterManager.restartForNodeCapacity(any(), anyString())).thenAnswer(invocation -> {
restartEntered.countDown();
if (!releaseRestart.await(10, TimeUnit.SECONDS)) {
throw new IllegalStateException("Timed out waiting to finish the first restart");
}
return true;
});
EksService service = newService(clusterManager, false);
CreateClusterRequest request = new CreateClusterRequest();
request.setName("concurrent-capacity");
request.setRoleArn("arn:aws:iam::000000000000:role/eks-role");
Cluster cluster = service.createCluster(request);
cluster.setContainerId("existing-container");
ExecutorService executor = Executors.newFixedThreadPool(2);
try {
Future<Nodegroup> first = executor.submit(() -> service.createNodeGroup(
"concurrent-capacity", nodeGroupRequest("first")));
assertTrue(restartEntered.await(10, TimeUnit.SECONDS));
CreateNodeGroupRequest secondRequest = nodeGroupRequest("second");
secondRequest.setInstanceTypes(List.of("m5.large"));
Future<Nodegroup> second = executor.submit(() -> service.createNodeGroup(
"concurrent-capacity", secondRequest));
releaseRestart.countDown();
first.get(10, TimeUnit.SECONDS);
second.get(10, TimeUnit.SECONDS);
assertEquals("t3.medium", cluster.getNodeInstanceType());
verify(clusterManager, times(1)).restartForNodeCapacity(cluster, "m5.large");
} finally {
releaseRestart.countDown();
executor.shutdownNow();
}
}
@Test
void nodeGroupLifecycleDescribeListDelete() {
createTestCluster("my-eks-cluster");