mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(ec2): retry Docker port collisions (#2029)
* fix(ec2): retry Docker port collisions * fix(cloudformation): clean failed EC2 launches * fix(ec2): bound container launch failures * fix(ec2): cancel timed out container launches * fix(ec2): track containers during startup * test(ec2): align launch mocks with public IP option * test(ec2): cover cancellation during Docker create * fix(ec2): allow slow container cold starts * fix(ec2): make launch failure cleanup idempotent
This commit is contained in:
1 parent
bd3b5b427b
commit
b27b32f044
7 files changed
+587
-58
No files matched your search
+121
@@ -0,0 +1,121 @@
|
||||
package io.github.hectorvent.floci.services.cloudformation;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.CfnRollback;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.CloudFormationResourceRegistry;
|
||||
import io.github.hectorvent.floci.services.ec2.Ec2Service;
|
||||
import io.github.hectorvent.floci.services.ec2.model.Instance;
|
||||
import io.github.hectorvent.floci.services.ec2.model.InstanceState;
|
||||
import io.github.hectorvent.floci.services.ec2.model.Reservation;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.function.Function;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
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.anyList;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class CloudFormationEc2ProvisionerTest {
|
||||
|
||||
private final ObjectMapper mapper = new ObjectMapper();
|
||||
private Ec2Service ec2Service;
|
||||
private CloudFormationResourceProvisioner provisioner;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
ec2Service = mock(Ec2Service.class);
|
||||
provisioner = new CloudFormationResourceProvisioner(
|
||||
null, null, null, null, null, null, null, null, null, null,
|
||||
null, null, null, null, null, null, mapper, null, null, null, null, null, null,
|
||||
ec2Service, null, null, null, null, null, null, null,
|
||||
null, null, new CloudFormationResourceRegistry(List.of()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void terminatedContainerLaunchMarksEc2ResourceCreateFailed() throws Exception {
|
||||
Instance instance = new Instance();
|
||||
instance.setInstanceId("i-launch-failed");
|
||||
instance.setState(InstanceState.terminated());
|
||||
Reservation reservation = new Reservation();
|
||||
reservation.getInstances().add(instance);
|
||||
when(ec2Service.runInstances(anyString(), anyString(), anyString(), anyInt(), anyInt(), any(), anyList(),
|
||||
any(), any(), anyList(), any(), any(), any())).thenReturn(reservation);
|
||||
doThrow(new AwsException("InternalError", "EC2 instance i-launch-failed failed to launch because its container terminated during launch", 500))
|
||||
.when(ec2Service).awaitContainerLaunch(instance);
|
||||
|
||||
StackResource resource = provisioner.provision("Server", "AWS::EC2::Instance", properties(), engine(),
|
||||
"us-east-1", "000000000000", "test-stack");
|
||||
|
||||
assertEquals("CREATE_FAILED", resource.getStatus());
|
||||
assertEquals("i-launch-failed", resource.getPhysicalId());
|
||||
assertEquals("true", resource.getAttributes().get(CfnRollback.ROLLBACK_OWNED_ATTR));
|
||||
assertTrue(resource.getStatusReason().contains("container terminated during launch"));
|
||||
verify(ec2Service).awaitContainerLaunch(instance);
|
||||
}
|
||||
|
||||
@Test
|
||||
void timedOutContainerLaunchMarksEc2ResourceCreateFailed() throws Exception {
|
||||
Instance instance = new Instance();
|
||||
instance.setInstanceId("i-launch-timed-out");
|
||||
instance.setState(InstanceState.pending());
|
||||
Reservation reservation = new Reservation();
|
||||
reservation.getInstances().add(instance);
|
||||
when(ec2Service.runInstances(anyString(), anyString(), anyString(), anyInt(), anyInt(), any(), anyList(),
|
||||
any(), any(), anyList(), any(), any(), any())).thenReturn(reservation);
|
||||
doThrow(new AwsException("InternalError",
|
||||
"EC2 instance i-launch-timed-out failed to launch because it did not reach running state before the launch timeout",
|
||||
500)).when(ec2Service).awaitContainerLaunch(instance);
|
||||
|
||||
StackResource resource = provisioner.provision("Server", "AWS::EC2::Instance", properties(), engine(),
|
||||
"us-east-1", "000000000000", "test-stack");
|
||||
|
||||
assertEquals("CREATE_FAILED", resource.getStatus());
|
||||
assertEquals("i-launch-timed-out", resource.getPhysicalId());
|
||||
assertEquals("true", resource.getAttributes().get(CfnRollback.ROLLBACK_OWNED_ATTR));
|
||||
assertTrue(resource.getStatusReason().contains("launch timeout"));
|
||||
verify(ec2Service).awaitContainerLaunch(instance);
|
||||
}
|
||||
|
||||
@Test
|
||||
void successfulContainerLaunchDoesNotKeepRollbackOwnershipMarker() throws Exception {
|
||||
Instance instance = new Instance();
|
||||
instance.setInstanceId("i-launch-succeeded");
|
||||
instance.setState(InstanceState.running());
|
||||
Reservation reservation = new Reservation();
|
||||
reservation.getInstances().add(instance);
|
||||
when(ec2Service.runInstances(anyString(), anyString(), anyString(), anyInt(), anyInt(), any(), anyList(),
|
||||
any(), any(), anyList(), any(), any(), any())).thenReturn(reservation);
|
||||
|
||||
StackResource resource = provisioner.provision("Server", "AWS::EC2::Instance", properties(), engine(),
|
||||
"us-east-1", "000000000000", "test-stack");
|
||||
|
||||
assertEquals("CREATE_COMPLETE", resource.getStatus());
|
||||
assertNull(resource.getAttributes().get(CfnRollback.ROLLBACK_OWNED_ATTR));
|
||||
verify(ec2Service).awaitContainerLaunch(instance);
|
||||
}
|
||||
|
||||
private JsonNode properties() throws Exception {
|
||||
return mapper.readTree("""
|
||||
{"ImageId":"ami-12345678","InstanceType":"t3.micro"}
|
||||
""");
|
||||
}
|
||||
|
||||
private CloudFormationTemplateEngine engine() {
|
||||
return new CloudFormationTemplateEngine("000000000000", "us-east-1", "test-stack", "stack/id",
|
||||
Map.of(), Map.of(), Map.of(), Map.of(), Map.of(), mapper, (Function<String, String>) name -> null);
|
||||
}
|
||||
}
|
||||
+119
-5
@@ -42,6 +42,7 @@ import java.util.function.BooleanSupplier;
|
||||
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyInt;
|
||||
@@ -49,11 +50,12 @@ import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Answers.RETURNS_SELF;
|
||||
import static org.mockito.Answers.RETURNS_DEEP_STUBS;
|
||||
import static org.mockito.Mockito.after;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.timeout;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.timeout;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
import static org.mockito.Mockito.withSettings;
|
||||
@@ -389,10 +391,118 @@ class Ec2ContainerManagerTest {
|
||||
harness.manager.launch(instance, "ubuntu:24.04", null, "us-west-2");
|
||||
|
||||
awaitUntil(() -> "terminated".equals(instance.getState().getName()), Duration.ofSeconds(2));
|
||||
assertEquals(TEST_CONTAINER_ID, instance.getDockerContainerId());
|
||||
verify(harness.lifecycleManager, timeout(2_000)).removeIfExists(TEST_CONTAINER_ID);
|
||||
verify(harness.portAllocator, timeout(2_000)).release(2201);
|
||||
assertNull(instance.getDockerContainerId());
|
||||
verify(harness.metadataServer, never()).registerContainer(anyString(), anyString(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void launchRetriesWithNextPortWhenDockerReportsHostPortCollision() throws Exception {
|
||||
Ec2ContainerManager.containerBridgeIpAttempts = 1;
|
||||
Ec2ContainerManager.containerBridgeIpPollMillis = 1;
|
||||
LaunchHarness harness = launchHarness();
|
||||
when(harness.portAllocator.allocate(anyInt(), anyInt())).thenReturn(2201, 2202);
|
||||
when(harness.lifecycleManager.create(any(ContainerSpec.class)))
|
||||
.thenReturn("container-conflict", TEST_CONTAINER_ID);
|
||||
when(harness.lifecycleManager.startCreated(anyString(), any(ContainerSpec.class)))
|
||||
.thenThrow(new RuntimeException("Bind for 0.0.0.0:2201 failed: port is already allocated"))
|
||||
.thenReturn(null);
|
||||
|
||||
InspectContainerCmd inspect = mock(InspectContainerCmd.class);
|
||||
InspectContainerResponse withIp = inspectResponse("172.18.0.12");
|
||||
when(harness.dockerClient.inspectContainerCmd(TEST_CONTAINER_ID)).thenReturn(inspect);
|
||||
when(inspect.exec()).thenReturn(withIp);
|
||||
harness.stubSuccessfulExecs(new CountDownLatch(0), new CountDownLatch(0));
|
||||
|
||||
Instance instance = instance("i-port-collision");
|
||||
harness.manager.launch(instance, "ubuntu:24.04", null, "us-west-2");
|
||||
|
||||
awaitUntil(() -> "running".equals(instance.getState().getName()), Duration.ofSeconds(2));
|
||||
assertEquals(2202, instance.getSshHostPort());
|
||||
verify(harness.lifecycleManager).removeIfExists("container-conflict");
|
||||
verify(harness.portAllocator).markReserved(2201);
|
||||
verify(harness.builder).withPortBinding(22, 2201);
|
||||
verify(harness.builder).withPortBinding(22, 2202);
|
||||
}
|
||||
|
||||
@Test
|
||||
void launchReleasesPortAndCleansUpContainerAfterNonRetryableStartFailure() throws Exception {
|
||||
LaunchHarness harness = launchHarness();
|
||||
when(harness.lifecycleManager.startCreated(eq(TEST_CONTAINER_ID), any(ContainerSpec.class)))
|
||||
.thenThrow(new RuntimeException("Docker daemon unavailable"));
|
||||
|
||||
Instance instance = instance("i-start-failure");
|
||||
harness.manager.launch(instance, "ubuntu:24.04", null, "us-west-2");
|
||||
|
||||
awaitUntil(() -> "terminated".equals(instance.getState().getName()), Duration.ofSeconds(2));
|
||||
verify(harness.lifecycleManager).removeIfExists(TEST_CONTAINER_ID);
|
||||
verify(harness.portAllocator).release(2201);
|
||||
}
|
||||
|
||||
@Test
|
||||
void launchTerminatesBeforeCleanupFailure() throws Exception {
|
||||
LaunchHarness harness = launchHarness();
|
||||
when(harness.lifecycleManager.startCreated(eq(TEST_CONTAINER_ID), any(ContainerSpec.class)))
|
||||
.thenThrow(new RuntimeException("Docker daemon unavailable"));
|
||||
doThrow(new RuntimeException("port-forward cleanup failed"))
|
||||
.when(harness.portForwardManager).unpublishAll(any(Instance.class));
|
||||
|
||||
Instance instance = instance("i-cleanup-failure");
|
||||
harness.manager.launch(instance, "ubuntu:24.04", null, "us-west-2");
|
||||
|
||||
awaitUntil(() -> "terminated".equals(instance.getState().getName()), Duration.ofSeconds(2));
|
||||
verify(harness.portForwardManager).unpublishAll(instance);
|
||||
}
|
||||
|
||||
@Test
|
||||
void cancelledLaunchRemovesContainerThatStartsAfterCancellation() throws Exception {
|
||||
LaunchHarness harness = launchHarness();
|
||||
CountDownLatch startEntered = new CountDownLatch(1);
|
||||
CountDownLatch allowStart = new CountDownLatch(1);
|
||||
when(harness.lifecycleManager.startCreated(eq(TEST_CONTAINER_ID), any(ContainerSpec.class))).thenAnswer(invocation -> {
|
||||
startEntered.countDown();
|
||||
assertTrue(allowStart.await(2, TimeUnit.SECONDS));
|
||||
return null;
|
||||
});
|
||||
|
||||
Instance instance = instance("i-cancelled-launch");
|
||||
harness.manager.launch(instance, "ubuntu:24.04", null, "us-west-2");
|
||||
|
||||
assertTrue(startEntered.await(2, TimeUnit.SECONDS), "container startup should begin");
|
||||
assertTrue(harness.manager.cancelLaunch(instance));
|
||||
verify(harness.lifecycleManager).removeIfExists(TEST_CONTAINER_ID);
|
||||
verify(harness.portAllocator).release(2201);
|
||||
|
||||
allowStart.countDown();
|
||||
verify(harness.portAllocator, after(500).times(1)).release(2201);
|
||||
}
|
||||
|
||||
@Test
|
||||
void cancelledLaunchRemovesContainerCreatedAfterCancellation() throws Exception {
|
||||
LaunchHarness harness = launchHarness();
|
||||
CountDownLatch createEntered = new CountDownLatch(1);
|
||||
CountDownLatch allowCreate = new CountDownLatch(1);
|
||||
when(harness.lifecycleManager.create(any(ContainerSpec.class))).thenAnswer(invocation -> {
|
||||
createEntered.countDown();
|
||||
assertTrue(allowCreate.await(2, TimeUnit.SECONDS));
|
||||
return TEST_CONTAINER_ID;
|
||||
});
|
||||
|
||||
Instance instance = instance("i-cancelled-during-create");
|
||||
harness.manager.launch(instance, "ubuntu:24.04", null, "us-west-2");
|
||||
|
||||
assertTrue(createEntered.await(2, TimeUnit.SECONDS), "container creation should begin");
|
||||
assertTrue(harness.manager.cancelLaunch(instance));
|
||||
assertEquals("terminated", instance.getState().getName());
|
||||
|
||||
allowCreate.countDown();
|
||||
verify(harness.lifecycleManager, timeout(2_000)).removeIfExists(TEST_CONTAINER_ID);
|
||||
verify(harness.portAllocator, timeout(2_000)).release(2201);
|
||||
verify(harness.lifecycleManager, never()).startCreated(eq(TEST_CONTAINER_ID), any(ContainerSpec.class));
|
||||
assertEquals("terminated", instance.getState().getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
void launchMarksInstanceRunningBeforeUserDataCompletes() throws Exception {
|
||||
Ec2ContainerManager.containerBridgeIpAttempts = 2;
|
||||
@@ -593,6 +703,7 @@ class Ec2ContainerManagerTest {
|
||||
DockerClient dockerClient = mock(DockerClient.class);
|
||||
Ec2MetadataServer metadataServer = mock(Ec2MetadataServer.class);
|
||||
ContainerLogStreamer logStreamer = mock(ContainerLogStreamer.class);
|
||||
Ec2PortForwardManager portForwardManager = mock(Ec2PortForwardManager.class);
|
||||
Ec2ContainerManager manager = new Ec2ContainerManager(
|
||||
containerBuilder,
|
||||
lifecycleManager,
|
||||
@@ -603,9 +714,9 @@ class Ec2ContainerManagerTest {
|
||||
portAllocator,
|
||||
config,
|
||||
metadataServer,
|
||||
mock(Ec2PortForwardManager.class));
|
||||
return new LaunchHarness(manager, dockerClient, metadataServer, logStreamer, builder,
|
||||
new CopyOnWriteArrayList<>());
|
||||
portForwardManager);
|
||||
return new LaunchHarness(manager, lifecycleManager, dockerClient, metadataServer, logStreamer, builder,
|
||||
portAllocator, portForwardManager, new CopyOnWriteArrayList<>());
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -649,10 +760,13 @@ class Ec2ContainerManagerTest {
|
||||
}
|
||||
|
||||
private record LaunchHarness(Ec2ContainerManager manager,
|
||||
ContainerLifecycleManager lifecycleManager,
|
||||
DockerClient dockerClient,
|
||||
Ec2MetadataServer metadataServer,
|
||||
ContainerLogStreamer logStreamer,
|
||||
ContainerBuilder.Builder builder,
|
||||
PortAllocator portAllocator,
|
||||
Ec2PortForwardManager portForwardManager,
|
||||
List<String[]> executedCommands) {
|
||||
void stubSuccessfulExecs(CountDownLatch userDataStarted, CountDownLatch finishUserData) throws Exception {
|
||||
AtomicReference<String[]> currentCommand = new AtomicReference<>();
|
||||
|
||||
@@ -15,6 +15,7 @@ import io.github.hectorvent.floci.services.ec2.model.IpPermission;
|
||||
import io.github.hectorvent.floci.services.ec2.model.Ipv6Range;
|
||||
import io.github.hectorvent.floci.services.ec2.model.SecurityGroupRule;
|
||||
import io.github.hectorvent.floci.services.ec2.model.UserIdGroupPair;
|
||||
import io.github.hectorvent.floci.services.ec2.model.InstanceState;
|
||||
import io.github.hectorvent.floci.services.ec2.model.LaunchTemplate;
|
||||
import io.github.hectorvent.floci.services.ec2.model.ManagedPrefixList;
|
||||
import io.github.hectorvent.floci.services.ec2.model.SecurityGroupRule;
|
||||
@@ -39,9 +40,9 @@ import io.github.hectorvent.floci.services.ec2.model.Vpc;
|
||||
import io.github.hectorvent.floci.services.ec2.model.VpcEndpoint;
|
||||
import io.github.hectorvent.floci.services.ec2.model.Volume;
|
||||
import io.github.hectorvent.floci.services.ec2.model.VolumeAttachment;
|
||||
import io.github.hectorvent.floci.services.ec2.model.InstanceState;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
@@ -80,6 +81,40 @@ class Ec2ServiceTest {
|
||||
verifyNoInteractions(containerManager);
|
||||
}
|
||||
|
||||
@Test
|
||||
void awaitContainerLaunchReportsTerminatedContainer() {
|
||||
Ec2Service service = new Ec2Service(mockConfig(false), mock(Ec2ContainerManager.class),
|
||||
mock(Ec2PortForwardManager.class), mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class),
|
||||
new Ec2InstanceTypeCatalog(), new InMemoryStorageFactory());
|
||||
Instance instance = new Instance();
|
||||
instance.setInstanceId("i-terminated");
|
||||
instance.setState(InstanceState.terminated());
|
||||
|
||||
AwsException error = assertThrows(AwsException.class, () -> service.awaitContainerLaunch(instance));
|
||||
|
||||
assertEquals("InternalError", error.getErrorCode());
|
||||
assertTrue(error.getMessage().contains("container terminated during launch"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void awaitContainerLaunchTimesOutWhileInstanceIsPending() {
|
||||
Ec2ContainerManager containerManager = mock(Ec2ContainerManager.class);
|
||||
Ec2Service service = new Ec2Service(mockConfig(false), containerManager,
|
||||
mock(Ec2PortForwardManager.class), mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class),
|
||||
new Ec2InstanceTypeCatalog(), new InMemoryStorageFactory());
|
||||
Instance instance = new Instance();
|
||||
instance.setInstanceId("i-pending");
|
||||
instance.setState(InstanceState.pending());
|
||||
when(containerManager.cancelLaunch(instance)).thenReturn(true);
|
||||
|
||||
AwsException error = assertThrows(AwsException.class,
|
||||
() -> service.awaitContainerLaunch(instance, Duration.ZERO));
|
||||
|
||||
assertEquals("InternalError", error.getErrorCode());
|
||||
assertTrue(error.getMessage().contains("did not reach running state before the launch timeout"));
|
||||
verify(containerManager).cancelLaunch(instance);
|
||||
}
|
||||
|
||||
@Test
|
||||
void runInstancesRequiresImageIdInsteadOfDefaulting() {
|
||||
Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),
|
||||
|
||||
Reference in new issue
Block a user