fix(eks): fail the delete when Docker cannot remove the cluster container (#4960)

* fix(eks): keep the API server port reserved when Docker cannot remove the container

stopAndRemove is best effort: it logs Docker errors and returns. Releasing the port regardless could hand it to another cluster while the old container still publishes it. stopAndRemove now reports whether Docker confirmed the container is gone, and stopCluster only releases the port then.

* fix(eks): fail the delete when Docker cannot remove the cluster container

Keeping the port reserved after an unconfirmed removal orphaned it once DeleteCluster dropped the cluster record: nothing released it until Floci restarted, so repeated failures could exhaust the API server port range. stopCluster now uses stopAndRemoveStrict, as it already does for the capacity backup, so the delete fails and keeps the record, and a retried delete releases the port once Docker confirms the container is gone. This reverts the boolean return on the best-effort stopAndRemove, which no longer has a caller that needs it.

* fix(core): close the log stream after the container stops in strict cleanup

stopAndRemoveStrict closed the log stream before stopping the container, so its follower could shut down while Docker was still stopping it and drop the final log lines. stopAndRemove already closes after the stop and remove; the strict variant now does the same. This keeps EKS control-plane logs intact now that stopCluster uses the strict variant, and fixes the same ordering for RDS.

* fix(eks): keep the log stream of a cluster whose container could not be removed

When Docker could neither stop nor remove the container, stopAndRemoveStrict still closed its log stream and stopCluster had already dropped the handle, so a container that kept running lost its control-plane and audit logs and the retried delete had nothing to close. The strict variant now closes the stream only once the container is stopped or gone, as stopAndRemove does, and stopCluster puts the handle back when removal fails.

* fix(eks): keep a failed cluster delete retryable without stale state

When Docker cannot remove the cluster container, the delete now leaves
everything a retry needs and nothing it could trip over:

- the log handle is never put back on failure; it is removed by value
  once the container is gone, so a delete that lost a race to a
  successful one cannot restore a handle under a deleted cluster's name
- attaching logs for a new or adopted container closes and replaces a
  handle still registered under the name instead of skipping the attach,
  so a recreated cluster always gets its control-plane logs
- the node stays registered on the metadata server until the container
  is confirmed gone
- the host port is read and cleared under the cluster lock, so it is
  released exactly once
- stopAndRemoveStrict leaves the log stream open on any removal failure
  and closes it only once the container is gone
- DeleteCluster restores the previous status instead of leaving the
  cluster stuck in DELETING; only the delete that set DELETING restores it

* fix(eks): reject a DeleteCluster that overlaps one still in progress

A delete that failed to remove the container restored the shared
cluster's status even while an overlapping delete had removed the
container and was still tearing the cluster down, so the cluster briefly
looked ACTIVE with no API server behind it.

Deletes of the same cluster now run one at a time: an overlapping
DeleteCluster fails with ResourceInUseException, so only the delete that
set DELETING can restore the previous status. The guard tracks the
delete in progress rather than the status, so a cluster left in
DELETING by an earlier failure can still be deleted again.
This commit is contained in:
Niels Kootstra authored and GitHub committed 2026-10-03 17:35:02 -04:00
1 parent 7822b2c396
commit d5fd4d52f1
6 files changed
+336 -45

No files matched your search

@@ -25,6 +25,7 @@ import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.io.Closeable;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
@@ -170,6 +171,70 @@ class ContainerLifecycleManagerVolumeTest {
assertFalse(manager.volumeExists("some-volume"));
}
@Test
void strictContainerCleanupStopsContainerBeforeClosingItsLogStream() {
StopContainerCmd stop = mock(StopContainerCmd.class, RETURNS_SELF);
RemoveContainerCmd remove = mock(RemoveContainerCmd.class, RETURNS_SELF);
List<String> operations = new ArrayList<>();
doAnswer(invocation -> {
operations.add("stop");
return null;
}).when(stop).exec();
doAnswer(invocation -> {
operations.add("remove");
return null;
}).when(remove).exec();
when(dockerClient.stopContainerCmd("container-id")).thenReturn(stop);
when(dockerClient.removeContainerCmd("container-id")).thenReturn(remove);
manager.stopAndRemoveStrict("container-id", () -> operations.add("logs"));
assertEquals(List.of("stop", "remove", "logs"), operations);
}
@Test
void strictContainerCleanupClosesTheLogStreamOfAnAlreadyMissingContainer() {
StopContainerCmd stop = mock(StopContainerCmd.class, RETURNS_SELF);
when(dockerClient.stopContainerCmd("container-id")).thenReturn(stop);
when(stop.exec()).thenThrow(new NotFoundException("gone"));
List<String> operations = new ArrayList<>();
manager.stopAndRemoveStrict("container-id", () -> operations.add("logs"));
assertEquals(List.of("logs"), operations);
}
@Test
void strictContainerCleanupLeavesTheLogStreamOpenWhenDockerCouldNotStopOrRemoveTheContainer() {
StopContainerCmd stop = mock(StopContainerCmd.class, RETURNS_SELF);
RemoveContainerCmd remove = mock(RemoveContainerCmd.class, RETURNS_SELF);
when(dockerClient.stopContainerCmd("container-id")).thenReturn(stop);
when(stop.exec()).thenThrow(new DockerException("stop failed", 500));
when(dockerClient.removeContainerCmd("container-id")).thenReturn(remove);
when(remove.exec()).thenThrow(new DockerException("remove failed", 500));
List<String> operations = new ArrayList<>();
assertThrows(IllegalStateException.class, () ->
manager.stopAndRemoveStrict("container-id", () -> operations.add("logs")));
assertEquals(List.of(), operations);
}
@Test
void strictContainerCleanupLeavesTheLogStreamOpenWhenDockerStoppedButCouldNotRemoveTheContainer() {
StopContainerCmd stop = mock(StopContainerCmd.class, RETURNS_SELF);
RemoveContainerCmd remove = mock(RemoveContainerCmd.class, RETURNS_SELF);
when(dockerClient.stopContainerCmd("container-id")).thenReturn(stop);
when(dockerClient.removeContainerCmd("container-id")).thenReturn(remove);
when(remove.exec()).thenThrow(new DockerException("remove failed", 500));
List<String> operations = new ArrayList<>();
assertThrows(IllegalStateException.class, () ->
manager.stopAndRemoveStrict("container-id", () -> operations.add("logs")));
assertEquals(List.of(), operations);
}
@Test
void strictContainerCleanupPropagatesRemovalFailure() {
StopContainerCmd stop = mock(StopContainerCmd.class, RETURNS_SELF);
@@ -197,6 +262,20 @@ class ContainerLifecycleManagerVolumeTest {
verify(remove).exec();
}
@Test
void strictContainerCleanupClosesTheLogStreamOnceForcedRemovalSucceedsAfterStopFailure() throws Exception {
StopContainerCmd stop = mock(StopContainerCmd.class, RETURNS_SELF);
RemoveContainerCmd remove = mock(RemoveContainerCmd.class, RETURNS_SELF);
Closeable logStream = mock(Closeable.class);
when(dockerClient.stopContainerCmd("container-id")).thenReturn(stop);
when(stop.exec()).thenThrow(new DockerException("stop failed", 500));
when(dockerClient.removeContainerCmd("container-id")).thenReturn(remove);
manager.stopAndRemoveStrict("container-id", logStream);
verify(logStream).close();
}
@Test
void strictStaleContainerCleanupPropagatesRemovalFailure() {
RemoveContainerCmd remove = mock(RemoveContainerCmd.class, RETURNS_SELF);
@@ -532,6 +532,33 @@ class EksClusterManagerTest {
verify(portAllocator).release(6441);
}
@Test
void deletingAClusterWhoseContainerDockerCouldNotRemoveKeepsItsPortReserved() {
stubFreshStart("cid-1", 6441);
Mockito.doThrow(new IllegalStateException("Failed to remove container cid-1"))
.when(lifecycleManager).stopAndRemoveStrict("cid-1", null);
Cluster cluster = cluster();
manager.startCluster(cluster);
assertThrows(IllegalStateException.class, () -> manager.stopCluster(cluster));
verify(portAllocator, never()).release(6441);
}
@Test
void retryingADeleteAfterContainerRemovalFailedHandsThePortBack() {
stubFreshStart("cid-1", 6441);
Mockito.doThrow(new IllegalStateException("Failed to remove container cid-1")).doNothing()
.when(lifecycleManager).stopAndRemoveStrict("cid-1", null);
Cluster cluster = cluster();
manager.startCluster(cluster);
assertThrows(IllegalStateException.class, () -> manager.stopCluster(cluster));
manager.stopCluster(cluster);
verify(portAllocator, Mockito.times(1)).release(6441);
}
@Test
void retryingADeleteAfterBackupCleanupFailedHandsThePortBackOnlyOnce() {
Cluster cluster = cluster();
@@ -554,6 +581,7 @@ class EksClusterManagerTest {
Cluster cluster = cluster();
assertThrows(IllegalStateException.class, () -> manager.startCluster(cluster));
assertEquals(0, cluster.getHostPort());
manager.stopCluster(cluster);
verify(portAllocator, Mockito.times(1)).release(6441);
@@ -584,7 +612,7 @@ class EksClusterManagerTest {
verify(lifecycleManager, Mockito.times(3))
.removeIfExistsStrict("floci-aws-eks-capacity-backup.foo");
verify(lifecycleManager, never()).removeIfExistsStrict(other.getDockerName());
verify(lifecycleManager, never()).stopAndRemove("cid-other", null);
verify(lifecycleManager, never()).stopAndRemoveStrict("cid-other", null);
}
@ParameterizedTest
@@ -604,7 +632,7 @@ class EksClusterManagerTest {
manager.stopCluster(cluster);
verify(lifecycleManager).stopAndRemove("cid-numeric", null);
verify(lifecycleManager).stopAndRemoveStrict("cid-numeric", null);
verify(lifecycleManager).removeIfExistsStrict("floci-aws-eks-capacity-backup.999999999999");
verify(lifecycleManager, never()).removeIfExistsStrict(otherDockerName);
}
@@ -752,7 +780,7 @@ class EksClusterManagerTest {
cluster.setContainerId("cid-1");
manager.stopCluster(cluster);
verify(lifecycleManager).stopAndRemove("cid-1", null);
verify(lifecycleManager).stopAndRemoveStrict("cid-1", null);
// The volume must survive so restoreCluster can bring the workloads back.
verify(lifecycleManager, never()).removeVolume(anyString());
}
@@ -767,7 +795,7 @@ class EksClusterManagerTest {
assertThrows(IllegalStateException.class, () -> manager.stopCluster(cluster));
verify(lifecycleManager).stopAndRemove("cid-new", null);
verify(lifecycleManager).stopAndRemoveStrict("cid-new", null);
verify(lifecycleManager, never()).removeVolume(anyString());
}
@@ -779,7 +807,7 @@ class EksClusterManagerTest {
cluster.setContainerId("cid-1");
manager.stopCluster(cluster);
verify(lifecycleManager).stopAndRemove("cid-1", null);
verify(lifecycleManager).stopAndRemoveStrict("cid-1", null);
verify(lifecycleManager).removeVolume("floci-aws-eks-demo");
}
@@ -1612,6 +1640,40 @@ class EksClusterManagerTest {
verify(metadataServer).unregisterInstance(any());
assertNull(manager.getRegisteredClusterNodeInstance(cluster));
}
@Test
void aDeleteThatCouldNotRemoveTheContainerKeepsItsNodeOnTheMetadataServer() {
Cluster cluster = new Cluster();
cluster.setName("test-cluster");
manager.configureLinkLocalMetadataEndpoint(cluster, "container-42");
cluster.setContainerId("container-42");
Mockito.doThrow(new IllegalStateException("Failed to remove container container-42"))
.when(lifecycleManager).stopAndRemoveStrict("container-42", null);
assertThrows(IllegalStateException.class, () -> manager.stopCluster(cluster));
verify(metadataServer, never()).unregisterInstance(any());
assertNotNull(manager.getRegisteredClusterNodeInstance(cluster));
}
@Test
void retryingADeleteAfterContainerRemovalFailedRemovesTheNodeFromTheMetadataServer() {
EmulatorConfig.StorageConfig storage = Mockito.mock(EmulatorConfig.StorageConfig.class);
when(config.storage()).thenReturn(storage);
when(storage.mode()).thenReturn("memory");
Cluster cluster = new Cluster();
cluster.setName("test-cluster");
manager.configureLinkLocalMetadataEndpoint(cluster, "container-42");
cluster.setContainerId("container-42");
Mockito.doThrow(new IllegalStateException("Failed to remove container container-42"))
.doNothing()
.when(lifecycleManager).stopAndRemoveStrict("container-42", null);
assertThrows(IllegalStateException.class, () -> manager.stopCluster(cluster));
manager.stopCluster(cluster);
assertNull(manager.getRegisteredClusterNodeInstance(cluster));
}
}
@Nested
@@ -2779,6 +2841,72 @@ class EksClusterManagerTest {
assertEquals("container-id-123456789012345678901234567890", cluster.getContainerId());
}
@Test
void logHandleSurvivesADeleteThatCouldNotRemoveTheContainer() {
Cluster cluster = new Cluster();
cluster.setName("prod-cluster");
cluster.setLogging(new Logging(List.of(new LogSetup(List.of("api"), true))));
manager.startCluster(cluster);
Mockito.doThrow(new IllegalStateException("Failed to remove container"))
.when(lifecycleManager).stopAndRemoveStrict("container-id-123456789012345678901234567890", mockHandle);
assertThrows(IllegalStateException.class, () -> manager.stopCluster(cluster));
assertEquals(mockHandle, manager.getLogHandle(cluster));
}
@Test
void aRecreatedClusterReplacesALogHandleLeftBehindUnderItsName() throws Exception {
Cluster stale = new Cluster();
stale.setName("prod-cluster");
stale.setLogging(new Logging(List.of(new LogSetup(List.of("api"), true))));
manager.startCluster(stale);
Closeable freshHandle = Mockito.mock(Closeable.class);
when(logStreamer.attachForAccount(anyString(), anyString(), anyString(), anyString(), anyString(), anyString()))
.thenReturn(freshHandle);
Cluster recreated = new Cluster();
recreated.setName("prod-cluster");
recreated.setLogging(new Logging(List.of(new LogSetup(List.of("api"), true))));
manager.startCluster(recreated);
verify(mockHandle).close();
assertEquals(freshHandle, manager.getLogHandle(recreated));
}
@Test
void retryingADeleteAfterContainerRemovalFailedReleasesTheLogHandle() {
Cluster cluster = new Cluster();
cluster.setName("prod-cluster");
cluster.setLogging(new Logging(List.of(new LogSetup(List.of("api"), true))));
manager.startCluster(cluster);
Mockito.doThrow(new IllegalStateException("Failed to remove container"))
.doNothing()
.when(lifecycleManager).stopAndRemoveStrict("container-id-123456789012345678901234567890", mockHandle);
assertThrows(IllegalStateException.class, () -> manager.stopCluster(cluster));
manager.stopCluster(cluster);
assertNull(manager.getLogHandle(cluster));
}
@Test
void aFailedDeleteOverlappingASuccessfulOneLeavesNoLogHandleBehind() {
Cluster cluster = new Cluster();
cluster.setName("prod-cluster");
cluster.setLogging(new Logging(List.of(new LogSetup(List.of("api"), true))));
manager.startCluster(cluster);
String containerId = "container-id-123456789012345678901234567890";
Mockito.doAnswer(failing -> {
manager.stopCluster(cluster);
throw new IllegalStateException("Failed to remove container");
}).doNothing().when(lifecycleManager).stopAndRemoveStrict(eq(containerId), any());
assertThrows(IllegalStateException.class, () -> manager.stopCluster(cluster));
assertNull(manager.getLogHandle(cluster));
}
@Test
void logHandleIsReleasedOnClusterStop() {
Cluster cluster = new Cluster();
@@ -2790,7 +2918,7 @@ class EksClusterManagerTest {
manager.stopCluster(cluster);
verify(lifecycleManager).stopAndRemove("container-id-123456789012345678901234567890", mockHandle);
verify(lifecycleManager).stopAndRemoveStrict("container-id-123456789012345678901234567890", mockHandle);
assertNull(manager.getLogHandle(cluster));
}
@@ -2810,7 +2938,7 @@ class EksClusterManagerTest {
manager.startCluster(cluster);
manager.stopCluster(cluster);
verify(lifecycleManager).stopAndRemove("container-id-123456789012345678901234567890", mockHandle);
verify(lifecycleManager).stopAndRemoveStrict("container-id-123456789012345678901234567890", mockHandle);
assertNull(manager.getLogHandle(cluster));
}
@@ -2824,7 +2952,7 @@ class EksClusterManagerTest {
manager.detachCluster(cluster);
verify(mockHandle).close();
verify(lifecycleManager, never()).stopAndRemove(anyString(), any());
verify(lifecycleManager, never()).stopAndRemoveStrict(anyString(), any());
assertNull(manager.getLogHandle(cluster));
}
@@ -2995,7 +3123,7 @@ class EksClusterManagerTest {
"us-east-1", "eks-audit:audit-cluster", false);
manager.stopCluster(cluster);
verify(lifecycleManager).stopAndRemove("container-id-123456789012345678901234567890", mockAuditHandle);
verify(lifecycleManager).stopAndRemoveStrict("container-id-123456789012345678901234567890", mockAuditHandle);
assertNull(manager.getLogHandle(cluster));
}
@@ -62,6 +62,7 @@ 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.doAnswer;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
@@ -521,6 +522,50 @@ class EksServiceTest {
verify(clusterManager, never()).detachCluster(any(Cluster.class));
}
@Test
void aDeleteOverlappingOneStillInProgressIsRejectedAndCannotReviveTheCluster() {
Cluster cluster = activeCluster();
EksClusterManager clusterManager = mock(EksClusterManager.class);
EksService service = serviceWithCluster(cluster, clusterManager, false);
AwsException[] overlapping = new AwsException[1];
doAnswer(firstDelete -> {
overlapping[0] = assertThrows(AwsException.class, () -> service.deleteCluster("running-cluster"));
return null;
}).when(clusterManager).stopCluster(cluster);
service.deleteCluster("running-cluster");
assertEquals("ResourceInUseException", overlapping[0].getErrorCode());
assertThrows(AwsException.class, () -> service.describeCluster("running-cluster"));
}
@Test
void aClusterLeftDeletingCanBeDeletedAgainOnceTheEarlierDeleteFinished() {
Cluster cluster = activeCluster();
EksClusterManager clusterManager = mock(EksClusterManager.class);
EksService service = serviceWithCluster(cluster, clusterManager, false);
doThrow(new IllegalStateException("Failed to remove container"))
.doNothing()
.when(clusterManager).stopCluster(cluster);
assertThrows(IllegalStateException.class, () -> service.deleteCluster("running-cluster"));
service.deleteCluster("running-cluster");
assertThrows(AwsException.class, () -> service.describeCluster("running-cluster"));
}
@Test
void aDeleteThatCouldNotRemoveTheClusterContainerLeavesTheClusterActive() {
Cluster cluster = activeCluster();
EksClusterManager clusterManager = mock(EksClusterManager.class);
EksService service = serviceWithCluster(cluster, clusterManager, false);
doThrow(new IllegalStateException("Failed to remove container")).when(clusterManager).stopCluster(cluster);
assertThrows(IllegalStateException.class, () -> service.deleteCluster("running-cluster"));
assertEquals(ClusterStatus.ACTIVE, service.describeCluster("running-cluster").getStatus());
}
private static Cluster activeCluster() {
Cluster cluster = new Cluster();
cluster.setName("running-cluster");