Light, fluffy, and always free - The AWS Local Emulator alternative
fix(ec2): return the network interface association in DescribeInstances (#6872)
Allen Sanbornd72653365916
diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2ContainerManager.java b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2ContainerManager.javaindex e9c7c310ae..df4e094780 100644--- a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2ContainerManager.java+++ b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2ContainerManager.java@@ -525,11 +525,6 @@ public class Ec2ContainerManager {refreshMetadataAddresses(instance, containerId);- if (!markRunning(instance)) {- failLaunch(instance, leasedPrivateIp);- return;- }-// Set public-facing addresses only for instances due one, by the rule mock instances// follow too, or holding an Elastic IP their interface carries, which RunInstances// recorded. Private-subnet instances have no public IP/DNS, matching real EC2.@@ -537,6 +532,12 @@ public class Ec2ContainerManager {exposeReachablePublicAddress(instance);}+ // Published before the state flips, so a poller that sees running never sees it without the address.+ if (!markRunning(instance)) {+ failLaunch(instance, leasedPrivateIp);+ return;+ }+LOG.infov("EC2 instance {0} running in container {1} (SSH host port {2})",instanceId, containerId, String.valueOf(sshHostPort));@@ -740,6 +741,9 @@ public class Ec2ContainerManager {String containerIp;boolean alreadyCleaned;synchronized (instance) {+ // A launch cancelled after its address was published must not keep it.+ instance.setPublicIpAddress(null);+ instance.setPublicDnsName(null);alreadyCleaned = isLaunchCancelledState(instance)&& instance.getDockerContainerId() == null&& instance.getSshHostPort() <= 0diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandler.java b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandler.javaindex 29804f1179..cc191d05d8 100644--- a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandler.java+++ b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandler.java@@ -959,8 +959,10 @@ public class Ec2QueryHandler {.start("instancesSet");Map<String, String> capacityAssociations = service.capacityReservationAssociations(region);Map<String, List<VolumeAttachment>> volumeAttachments = service.instanceVolumeAttachments(res.getInstances());+ Ec2Service.ElasticAddresses elasticAddresses = service.elasticAddresses(region);for (Instance inst : res.getInstances()) {- xml.start("item").raw(instanceXml(inst, capacityAssociations, volumeAttachments)).end("item");+ xml.start("item").raw(instanceXml(inst, capacityAssociations, volumeAttachments, elasticAddresses))+ .end("item");}xml.end("instancesSet").end("RunInstancesResponse");@@ -1425,6 +1427,7 @@ public class Ec2QueryHandler {Map<String, String> capacityAssociations = service.capacityReservationAssociations(region);Map<String, List<VolumeAttachment>> volumeAttachments = service.instanceVolumeAttachments(reservations.stream().flatMap(res -> res.getInstances().stream()).toList());+ Ec2Service.ElasticAddresses elasticAddresses = service.elasticAddresses(region);for (Reservation res : reservations) {xml.start("item").elem("reservationId", res.getReservationId())@@ -1432,7 +1435,8 @@ public class Ec2QueryHandler {.start("groupSet").end("groupSet").start("instancesSet");for (Instance inst : res.getInstances()) {- xml.start("item").raw(instanceXml(inst, capacityAssociations, volumeAttachments)).end("item");+ xml.start("item").raw(instanceXml(inst, capacityAssociations, volumeAttachments, elasticAddresses))+ .end("item");}xml.end("instancesSet").end("item");}@@ -5159,7 +5163,8 @@ public class Ec2QueryHandler {// ─── XML fragment builders ────────────────────────────────────────────────private String instanceXml(Instance inst, Map<String, String> capacityAssociations,- Map<String, List<VolumeAttachment>> volumeAttachments) {+ Map<String, List<VolumeAttachment>> volumeAttachments,+ Ec2Service.ElasticAddresses elasticAddresses) {XmlBuilder xml = new XmlBuilder().elem("instanceId", inst.getInstanceId()).elem("imageId", inst.getImageId())@@ -5229,8 +5234,17 @@ public class Ec2QueryHandler {.elem("groupName", gi.getGroupName()).end("item");}- xml.end("groupSet")- .start("attachment")+ xml.end("groupSet");+ // The provider derives associate_public_ip_address from the presence of this element.+ NetworkInterfaceAssociation association = service.instanceInterfaceAssociation(inst, eni, elasticAddresses);+ if (association != null) {+ xml.start("association")+ .elem("publicIp", association.getPublicIp())+ .elem("publicDnsName", inst.getPublicDnsName())+ .elem("ipOwnerId", association.getIpOwnerId())+ .end("association");+ }+ xml.start("attachment").elem("attachmentId", eni.getAttachmentId()).elem("deviceIndex", String.valueOf(eni.getDeviceIndex())).elem("status", "attached");diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.javaindex 1cadc7bb87..c63fffaad5 100644--- a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java+++ b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java@@ -141,6 +141,7 @@ import java.util.Optional;import java.util.Random;import java.util.Set;import java.util.TreeMap;+import java.util.TreeSet;import java.util.UUID;import java.util.concurrent.ConcurrentHashMap;import java.util.concurrent.CopyOnWriteArrayList;@@ -5012,8 +5013,20 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab* the primary interface it was associated through, or null.*/private Address primaryElasticAddress(String region, Instance instance) {+ return primaryElasticAddress(region, instance, elasticAddresses(region));+ }++ private Address primaryElasticAddress(String region, Instance instance, ElasticAddresses elastic) {+ TreeSet<Integer> candidates = new TreeSet<>(+ elastic.positions().getOrDefault(instance.getInstanceId(), List.of()));String primaryInterfaceId = primaryInterfaceId(instance);- for (Address address : addresses.scan(k -> k.startsWith(region + "::"))) {+ if (primaryInterfaceId != null) {+ candidates.addAll(elastic.positions().getOrDefault(primaryInterfaceId, List.of()));+ }+ for (int position : candidates) {+ // The index keeps live addresses: one disassociated or moved since it was read no+ // longer names this instance or its interface, so the owner is checked again here.+ Address address = elastic.associated().get(position);boolean onInstance = instance.getInstanceId().equals(address.getInstanceId())|| primaryInterfaceId != null && primaryInterfaceId.equals(address.getNetworkInterfaceId());if (onInstance && address.getAssociationId() != null@@ -5024,6 +5037,59 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettabreturn null;}+ /**+ * A region's associated Elastic IPs in store order, each position listed under its instance id+ * and its interface id, so a response rendering many instances reads the store once. An+ * address associated with an instance after the index was read is not found for it.+ */+ record ElasticAddresses(List<Address> associated, Map<String, List<Integer>> positions) {}++ ElasticAddresses elasticAddresses(String region) {+ List<Address> associated = addresses.scan(k -> k.startsWith(region + "::")).stream()+ .filter(address -> address.getAssociationId() != null)+ .toList();+ Map<String, List<Integer>> positions = new HashMap<>();+ for (int i = 0; i < associated.size(); i++) {+ for (String owner : new String[] {associated.get(i).getInstanceId(),+ associated.get(i).getNetworkInterfaceId()}) {+ if (owner != null) {+ positions.computeIfAbsent(owner, k -> new ArrayList<>()).add(i);+ }+ }+ }+ return new ElasticAddresses(associated, positions);+ }++ /**+ * The association DescribeInstances shows on an instance's primary interface: the Elastic IP+ * on its primary private address, owned by the interface owner exactly as+ * DescribeNetworkInterfaces shows it, otherwise the automatic public address (owned by+ * "amazon"), otherwise null. Other interfaces carry none.+ */+ NetworkInterfaceAssociation instanceInterfaceAssociation(Instance instance, InstanceNetworkInterface eni,+ ElasticAddresses elasticAddresses) {+ if (eni.getDeviceIndex() != 0) {+ return null;+ }+ Address elastic = primaryElasticAddress(instance.getRegion(), instance, elasticAddresses);+ if (elastic != null) {+ // Copied once and checked again: a disassociation between the lookup and the copy+ // leaves no association id, and then the instance's own address is shown instead.+ NetworkInterfaceAssociation association = networkInterfaceAssociation(elastic, eni.getOwnerId());+ if (association.getAssociationId() != null && association.getPublicIp() != null) {+ return association;+ }+ }+ String publicIp = instance.getPublicIpAddress();+ if (publicIp == null || publicIp.isBlank()) {+ return null;+ }+ NetworkInterfaceAssociation association = new NetworkInterfaceAssociation();+ association.setPublicIp(publicIp);+ association.setIpOwnerId("amazon");+ return association;+ }+public String platformDetailsForInstance(Instance instance) {Image image = findImageForCapture(instance.getRegion(), instance.getImageId());return image != null && "windows".equalsIgnoreCase(image.getPlatform())diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ContainerManagerTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ContainerManagerTest.javaindex 6cf893cfa8..d9cf1f3a7d 100644--- a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ContainerManagerTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ContainerManagerTest.java@@ -37,6 +37,7 @@ 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.model.Instance;import io.github.hectorvent.floci.services.ec2.model.InstanceNetworkInterface;+import io.github.hectorvent.floci.services.ec2.model.InstanceState;import io.github.hectorvent.floci.services.ec2.net.VpcNetworkManager;import io.github.hectorvent.floci.services.ec2.portforward.Ec2PortForwardManager;import org.junit.jupiter.api.AfterEach;@@ -873,8 +874,8 @@ class Ec2ContainerManagerTest {void reachablePublicAddressIsNullBeforeAContainerExists() {Ec2ContainerManager manager = managerWithReachability(mock(ContainerNetworkReachability.class));- assertEquals(null, manager.reachablePublicAddress(new Instance()));- assertEquals(null, manager.reachablePublicAddress(null));+ assertNull(manager.reachablePublicAddress(new Instance()));+ assertNull(manager.reachablePublicAddress(null));}private static Ec2ContainerManager managerWithReachability(ContainerNetworkReachability reachability) {@@ -1454,6 +1455,62 @@ class Ec2ContainerManagerTest {assertEquals("terminated", instance.getState().getName());}+ @Test+ void launchPublishesThePublicAddressBeforeTheInstanceReportsRunning() throws Exception {+ Ec2ContainerManager.containerBridgeIpAttempts = 2;+ Ec2ContainerManager.containerBridgeIpPollMillis = 1;+ LaunchHarness harness = launchHarness();+ InspectContainerCmd inspect = mock(InspectContainerCmd.class);+ when(harness.dockerClient.inspectContainerCmd(TEST_CONTAINER_ID)).thenReturn(inspect);+ InspectContainerResponse withIp = inspectResponse("172.18.0.10");+ when(inspect.exec()).thenReturn(withIp);+ harness.stubSuccessfulExecs(new CountDownLatch(0), new CountDownLatch(0));+ AtomicReference<String> addressWhenRunning = new AtomicReference<>("never running");+ Instance instance = new Instance() {+ @Override+ public void setState(InstanceState state) {+ if (state != null && "running".equals(state.getName())) {+ addressWhenRunning.set(String.valueOf(getPublicIpAddress()));+ }+ super.setState(state);+ }+ };+ instance.setInstanceId("i-public-before-running");+ instance.setAssociatePublicIp(true);+ harness.manager.launch(instance, "ubuntu:24.04", null, "us-west-2");+ awaitUntil(() -> "running".equals(instance.getState().getName()), Duration.ofSeconds(2));++ // A poller that sees running, as Terraform's wait does, must already find the address.+ assertEquals("127.0.0.1", addressWhenRunning.get());+ }++ @Test+ void launchCancelledAfterItsAddressWasPublishedKeepsNoAddress() throws Exception {+ Ec2ContainerManager.containerBridgeIpAttempts = 2;+ Ec2ContainerManager.containerBridgeIpPollMillis = 1;+ LaunchHarness harness = launchHarness();+ InspectContainerCmd inspect = mock(InspectContainerCmd.class);+ when(harness.dockerClient.inspectContainerCmd(TEST_CONTAINER_ID)).thenReturn(inspect);+ InspectContainerResponse withIp = inspectResponse("172.18.0.10");+ when(inspect.exec()).thenReturn(withIp);+ harness.stubSuccessfulExecs(new CountDownLatch(0), new CountDownLatch(0));+ Instance instance = instance("i-cancelled-with-address");+ instance.setAssociatePublicIp(true);+ // The launch is cancelled while the worker is between registering the container and+ // publishing its address, so markRunning refuses and failLaunch runs.+ doAnswer(invocation -> {+ instance.setState(InstanceState.terminated());+ return null;+ }).when(harness.metadataServer).registerContainer(any(), any(), any());+ harness.manager.launch(instance, "ubuntu:24.04", null, "us-west-2");++ awaitUntil(() -> instance.getPublicIpAddress() == null && "terminated".equals(instance.getState().getName())+ && instance.getDockerContainerId() == null, Duration.ofSeconds(2));+ assertEquals("terminated", instance.getState().getName());+ assertNull(instance.getPublicIpAddress());+ assertNull(instance.getPublicDnsName());+ }+@Testvoid launchMarksInstanceRunningBeforeUserDataCompletes() throws Exception {Ec2ContainerManager.containerBridgeIpAttempts = 2;diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2MockPublicAddressIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2MockPublicAddressIntegrationTest.javaindex bd8b0a8776..abd3d11706 100644--- a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2MockPublicAddressIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2MockPublicAddressIntegrationTest.java@@ -7,6 +7,7 @@ import io.github.hectorvent.floci.testing.EnforcementFixtures;import io.quarkus.test.junit.QuarkusTest;import io.quarkus.test.junit.QuarkusTestProfile;import io.quarkus.test.junit.TestProfile;+import io.restassured.path.xml.XmlPath;import io.restassured.response.ValidatableResponse;import io.restassured.specification.RequestSpecification;import jakarta.inject.Inject;@@ -137,9 +138,12 @@ class Ec2MockPublicAddressIntegrationTest {assertTrue(publicIp.matches(DOCUMENTATION_ADDRESS));}assertEquals(publicIp, describe(owner, instance).extract().xmlPath().getString(INSTANCE + "ipAddress"));+ // The provider derives associate_public_ip_address from the interface's association element.+ assertAssociation(owner, instance, publicExpected ? publicIp : null, "amazon");if (!"asg".equals(source)) {request("StopInstances", owner).formParam("InstanceId.1", instance).post("/").then().statusCode(200);assertEquals("", describe(owner, instance).extract().xmlPath().getString(INSTANCE + "ipAddress"));+ assertAssociation(owner, instance, null, null);request("StartInstances", owner).formParam("InstanceId.1", instance).post("/").then().statusCode(200);ValidatableResponse restarted = describe(owner, instance);assertEquals(privateIp, restarted.extract().path(INSTANCE + "privateIpAddress"));@@ -253,6 +257,7 @@ class Ec2MockPublicAddressIntegrationTest {.extract().path("RunInstancesResponse.instancesSet.item.instanceId");String launched = publicIp(owner, instance);assertEquals(automatic, !launched.isEmpty());+ assertAssociation(owner, instance, automatic ? launched : null, "amazon");ValidatableResponse allocated = request("AllocateAddress", owner).formParam("Domain", "vpc").post("/").then().statusCode(200);@@ -262,8 +267,17 @@ class Ec2MockPublicAddressIntegrationTest {.formParam("InstanceId", instance).post("/").then().statusCode(200).extract().path("AssociateAddressResponse.associationId");assertEquals(elastic, publicIp(owner, instance));+ // An Elastic IP is owned by the account, and DescribeNetworkInterfaces says the same.+ assertAssociation(owner, instance, elastic, owner);+ String eni = describe(owner, instance).extract().xmlPath()+ .getString(INSTANCE + "networkInterfaceSet.item.networkInterfaceId");+ XmlPath interfaceView = request("DescribeNetworkInterfaces", owner).formParam("NetworkInterfaceId.1", eni)+ .post("/").then().statusCode(200).extract().xmlPath();+ assertEquals(elastic, interfaceView.getString("DescribeNetworkInterfacesResponse.networkInterfaceSet.item.association.publicIp"));+ assertEquals(owner, interfaceView.getString("DescribeNetworkInterfacesResponse.networkInterfaceSet.item.association.ipOwnerId"));request("StopInstances", owner).formParam("InstanceId.1", instance).post("/").then().statusCode(200);assertEquals(elastic, publicIp(owner, instance));+ assertAssociation(owner, instance, elastic, owner);request("StartInstances", owner).formParam("InstanceId.1", instance).post("/").then().statusCode(200);assertEquals(elastic, publicIp(owner, instance));@@ -272,6 +286,7 @@ class Ec2MockPublicAddressIntegrationTest {String replacement = publicIp(owner, instance);assertEquals(automatic, !replacement.isEmpty());assertNotEquals(elastic, replacement);+ assertAssociation(owner, instance, automatic ? replacement : null, "amazon");request("AssociateAddress", owner).formParam("AllocationId", allocation).formParam("InstanceId", instance).post("/").then().statusCode(200);@@ -646,6 +661,40 @@ class Ec2MockPublicAddressIntegrationTest {request("DeleteVpc", owner).formParam("VpcId", vpc).post("/").then().statusCode(200);}+ /** Reads the primary interface's association back through DescribeInstances; null expects none. */+ private void assertAssociation(String owner, String instance, String publicIp, String ipOwnerId) {+ XmlPath xml = describe(owner, instance).extract().xmlPath();+ List<Object> items = xml.getList(INSTANCE + "networkInterfaceSet.item.association");+ if (publicIp == null) {+ assertEquals(0, items.size(), "unexpected association " + items);+ } else {+ assertEquals(1, items.size());+ assertEquals(publicIp, xml.getString(INSTANCE + "networkInterfaceSet.item.association.publicIp"));+ assertEquals(ipOwnerId, xml.getString(INSTANCE + "networkInterfaceSet.item.association.ipOwnerId"));+ }+ }++ @Test+ void onlyThePrimaryInterfaceCarriesTheInstanceAssociation() {+ String owner = Long.toString(ACCOUNTS.incrementAndGet());+ String instance = request("RunInstances", owner).formParam("ImageId", "ami-amazonlinux2023")+ .formParam("InstanceType", "t3.micro").formParam("MinCount", 1).formParam("MaxCount", 1)+ .post("/").then().statusCode(200)+ .extract().path("RunInstancesResponse.instancesSet.item.instanceId");+ String subnet = describe(owner, instance).extract().xmlPath().getString(INSTANCE + "subnetId");+ String second = request("CreateNetworkInterface", owner).formParam("SubnetId", subnet)+ .post("/").then().statusCode(200)+ .extract().path("CreateNetworkInterfaceResponse.networkInterface.networkInterfaceId");+ request("AttachNetworkInterface", owner).formParam("NetworkInterfaceId", second)+ .formParam("InstanceId", instance).formParam("DeviceIndex", 1).post("/").then().statusCode(200);+ XmlPath xml = describe(owner, instance).extract().xmlPath();+ assertEquals(2, xml.getList(INSTANCE + "networkInterfaceSet.item").size());+ assertEquals(1, xml.getList(INSTANCE + "networkInterfaceSet.item.association").size());+ assertEquals(0, xml.getList(INSTANCE + "networkInterfaceSet.item.find { it.networkInterfaceId == '"+ + second + "' }.association").size());+ request("TerminateInstances", owner).formParam("InstanceId.1", instance).post("/").then().statusCode(200);+ }+private String publicIp(String owner, String instance) {return describe(owner, instance).extract().xmlPath().getString(INSTANCE + "ipAddress");}diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServiceTest.javaindex 04c9ed1c24..a9c312a6b0 100644--- a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServiceTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServiceTest.java@@ -142,6 +142,7 @@ import static org.mockito.ArgumentMatchers.eq;import static org.mockito.Mockito.CALLS_REAL_METHODS;import static org.mockito.Mockito.RETURNS_SELF;import static org.mockito.Mockito.atLeastOnce;+import static org.mockito.Mockito.clearInvocations;import static org.mockito.Mockito.doAnswer;import static org.mockito.Mockito.doThrow;import static org.mockito.Mockito.inOrder;@@ -350,6 +351,84 @@ class Ec2ServiceTest {.count());}+ @Test+ void describeInstancesScansTheAddressesOnceWhateverTheInstanceCount() {+ AccountAwareStorageBackend<Address> addressStore = spy(AccountAwareStorageBackend.<Address>inMemory("000000000000"));+ Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),+ mock(Ec2PortForwardManager.class), mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class),+ new Ec2InstanceTypeCatalog(), new InMemoryStorageFactory(Map.of("ec2-addresses.json", addressStore)));+ List<Instance> launched = service.runInstances("us-east-1", "ami-test", "t3.micro", 3, 3, null, List.of(),+ null, null, List.of(), null, null).getInstances();+ Address elastic = service.allocateAddress("us-east-1");+ service.associateAddress("us-east-1", elastic.getAllocationId(), launched.get(1).getInstanceId());+ Ec2QueryHandler handler = new Ec2QueryHandler(service, mock(EmulatorConfig.class),+ mock(FlowLogService.class), mock(Ec2EbsEncryptionService.class),+ mock(Ec2SnapshotBlockPublicAccessService.class), mock(Ec2IpamService.class),+ new RegionResolver("us-east-1", "000000000000"));+ // The first read settles the pending launches, which reads the addresses once per launch.+ handler.handle("DescribeInstances", new MultivaluedHashMap<>(), "us-east-1");+ clearInvocations(addressStore);++ Response response = handler.handle("DescribeInstances", new MultivaluedHashMap<>(), "us-east-1");++ assertEquals(200, response.getStatus());+ String xml = response.getEntity().toString();+ assertTrue(xml.contains("<association><publicIp>" + elastic.getPublicIp() + "</publicIp>"), xml);+ verify(addressStore, times(1)).scan(any());+ }++ @ParameterizedTest+ @ValueSource(strings = {"kept", "disassociated", "reassigned"})+ void anIndexReadBeforeAnElasticIpMovedShowsItOnlyWhereItStillIs(String change) {+ Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),+ mock(Ec2PortForwardManager.class), mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class),+ new Ec2InstanceTypeCatalog(), new InMemoryStorageFactory());+ List<Instance> launched = service.runInstances("us-east-1", "ami-test", "t3.micro", 2, 2, null, List.of(),+ null, null, List.of(), null, null).getInstances();+ String formerId = launched.get(0).getInstanceId();+ String newOwnerId = launched.get(1).getInstanceId();+ String allocationId = service.allocateAddress("us-east-1").getAllocationId();+ String associationId = service.associateAddress("us-east-1", allocationId, formerId).getAssociationId();+ Ec2Service.ElasticAddresses read = service.elasticAddresses("us-east-1");++ if ("reassigned".equals(change)) {+ service.associateAddress("us-east-1", allocationId, newOwnerId);+ } else if ("disassociated".equals(change)) {+ service.disassociateAddress("us-east-1", associationId);+ }++ Address live = service.describeAddresses("us-east-1", List.of(allocationId), Map.of()).getFirst();+ Instance former = describedInstance(service, formerId);+ NetworkInterfaceAssociation shown = service.instanceInterfaceAssociation(former,+ former.getNetworkInterfaces().getFirst(), read);+ if ("kept".equals(change)) {+ assertNotNull(shown, "the instance still holding the Elastic IP shows no association");+ assertEquals(allocationId, shown.getAllocationId());+ assertEquals(associationId, shown.getAssociationId());+ assertEquals(live.getPublicIp(), shown.getPublicIp());+ return;+ }+ assertTrue(shown == null || !allocationId.equals(shown.getAllocationId()),+ "the former instance still shows " + allocationId);+ if ("reassigned".equals(change)) {+ // Known limit: the index was read before the move, so the new owner is not found in it+ // and shows its public address (the Elastic IP's) as an automatic one, owned by "amazon".+ Instance newOwner = describedInstance(service, newOwnerId);+ NetworkInterfaceAssociation moved = service.instanceInterfaceAssociation(newOwner,+ newOwner.getNetworkInterfaces().getFirst(), read);+ assertNotNull(moved);+ assertNull(moved.getAllocationId());+ assertEquals("amazon", moved.getIpOwnerId());+ assertEquals(live.getPublicIp(), moved.getPublicIp());+ assertEquals(newOwner.getPublicIpAddress(), moved.getPublicIp());+ }+ }++ private static Instance describedInstance(Ec2Service service, String instanceId) {+ return service.describeInstances("us-east-1", List.of(instanceId), Map.of())+ .getFirst().getInstances().getFirst();+ }+@Testvoid aLaunchRefusedWhenItTakesCapacityLeavesNoVolumeBehind() {Ec2Service service = spy(new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),