From efe6cbc78ada0ad4d22bdc4ec42157b72c8f501b Mon Sep 17 00:00:00 2001 From: jibin-jusdb Date: Wed, 4 Nov 2026 15:48:14 +0530 Subject: [PATCH] feat(ec2): report the service-network address as public IP when Floci runs in a container (#7384) * feat(ec2): report the service-network address as public IP when Floci runs in a container Adds FLOCI_SERVICES_EC2_PUBLIC_IP_FROM_SERVICE_NETWORK (default false). When Floci itself runs as a container and the option is on, an instance's public IP is its address on Floci's own Docker network, so clients on that network reach the guest's real ports, port 22 included. * fix(ec2): record the service-network address and follow protected guests to their helper Resolve the address once at launch, start and restore instead of asking Docker on every public-address read, which DescribeAddresses does under a lock. A security-group protected guest shares its firewall helper's network namespace, so its address is the helper's. * fix(ec2): share the helper lookup and retry a failed service-network lookup Use one container: network-mode lookup for protectedNamespace and the service-network address. A lookup that fails on a Docker error is no longer recorded as the answer; the next address read retries it on the executor without waiting. * fix(ec2): run service-network lookup retries off the launch pool Retries ran on the bounded launch executor, whose blocking backpressure could leave launch workers waiting on each other. They now get their own virtual-thread executor, and a retry that cannot be scheduled is logged with the instance id. * fix(ec2): publish a service-network lookup only for the container it read A lookup records the container it starts for, asks Docker outside the instance lock, and publishes under the lock only while the instance still runs that container, so a lookup that outlives a replacement or a teardown cannot overwrite what came after it. The retry executor now comes in through the package-private constructor and is final. --- docs/services/ec2.md | 1 + .../floci/config/EmulatorConfig.java | 10 + .../services/ec2/Ec2ContainerManager.java | 136 +++++++++- .../floci/services/ec2/model/Instance.java | 8 + src/main/resources/application.yml | 3 + .../services/ec2/Ec2ContainerManagerTest.java | 248 ++++++++++++++++++ 6 files changed, 401 insertions(+), 5 deletions(-) diff --git a/docs/services/ec2.md b/docs/services/ec2.md index 23eb0b6fe1..a9dadd9da3 100644 --- a/docs/services/ec2.md +++ b/docs/services/ec2.md @@ -1370,6 +1370,7 @@ State is reported settled rather than transitional, as elsewhere in this service | `FLOCI_SERVICES_EC2_MOCK_PUBLIC_ADDRESS` | `127.0.0.1` | The address every mock instance due one gets when `FLOCI_SERVICES_EC2_MOCK_PUBLIC_ADDRESSES` is `fixed`, for example this host's own address; an Elastic IP associated with its primary private address shows it too | | `FLOCI_SERVICES_EC2_AWS_FAITHFUL_PRIVATE_IP` | `false` | Report the CFN/subnet-allocated private IP instead of the container bridge IP; routing and IMDS are unaffected | | `FLOCI_SERVICES_EC2_CONTAINER_IPS_ROUTABLE` | auto-detect | Whether an instance's container IP is reachable from the machines consuming Floci's API (Terraform, Terratest, your shell). When it is, DescribeInstances and DescribeAddresses report the container IP, so port 22 really is port 22; when it is not, they report `127.0.0.1` and reachability goes through the published high host ports. Detected by a throwaway TCP connect; set explicitly when Floci itself runs as a container | +| `FLOCI_SERVICES_EC2_PUBLIC_IP_FROM_SERVICE_NETWORK` | `false` | When Floci itself runs as a container, report an instance's address on Floci's own Docker network as its public IP, so clients on that network (an orchestrator, a worker running Ansible) reach the guest's real ports, port 22 included | | `FLOCI_SERVICES_EC2_RECONCILE_CONTAINERS_ON_STARTUP` | `true` | On startup, remove instance containers this Floci left on the daemon whose record did not survive the restart or came back terminated; stopped instances are never swept | | `FLOCI_SERVICES_EC2_VPC_NETWORKS_ENABLED` | `true` | Back each VPC with a real Docker network (see [VPC Docker networks](#vpc-docker-networks)) | | `FLOCI_SERVICES_EC2_VPC_NETWORKS_FALLBACK_POOL` | `10.240.0.0/12` | RFC 1918 pool that substituted CIDRs are drawn from | diff --git a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java index 9c925a88d2..ef8af5bc82 100644 --- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java +++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java @@ -3455,6 +3455,16 @@ public interface EmulatorConfig { */ Optional containerIpsRoutable(); + /** + * When Floci itself runs as a container, report an instance's address on Floci's own + * Docker network as its public IP, so clients on that network (an orchestrator, a worker + * running Ansible) reach the guest's real ports there, as they would an AWS public IP. + * + * Env var: FLOCI_SERVICES_EC2_PUBLIC_IP_FROM_SERVICE_NETWORK + */ + @WithDefault("false") + boolean publicIpFromServiceNetwork(); + /** * When true, Floci removes on startup any EC2 instance container left on the Docker * daemon by a previous run of this same Floci (matched by the 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.java index a5f2c4436b..255d0b6b03 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 @@ -55,6 +55,7 @@ import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.RejectedExecutionHandler; import java.util.concurrent.Semaphore; @@ -159,6 +160,11 @@ public class Ec2ContainerManager { private final ExecutorService executor; private final Semaphore metadataSetupSlots = new Semaphore(METADATA_SETUP_CONCURRENCY); private final Map> lifecycleOperations = new ConcurrentHashMap<>(); + /** Instances whose service-network lookup failed and is retried on the next address read. */ + private final Set serviceNetworkRetries = ConcurrentHashMap.newKeySet(); + private final Set serviceNetworkRetriesRunning = ConcurrentHashMap.newKeySet(); + /** Runs service-network lookup retries; see {@link #createServiceNetworkRetryExecutor}. */ + private final ExecutorService serviceNetworkRetryExecutor; private final Duration userDataExecutionTimeout; private final Set> activeUserDataCallbacks = ConcurrentHashMap.newKeySet(); @@ -186,11 +192,10 @@ public class Ec2ContainerManager { return null; } InspectContainerResponse worker = dockerClient.inspectContainerCmd(containerId).exec(); - String mode = worker.getHostConfig() == null ? null : worker.getHostConfig().getNetworkMode(); - if (mode == null || !mode.startsWith("container:")) { + String helperId = namespaceOwnerId(worker); + if (helperId == null) { return null; } - String helperId = mode.substring("container:".length()); InspectContainerResponse helper = dockerClient.inspectContainerCmd(helperId).exec(); Map labels = helper.getConfig().getLabels(); if (!ALIASES.consistent(helperId, labels) @@ -208,6 +213,15 @@ public class Ec2ContainerManager { private record ProtectedNamespace(String helperId, String transportAddress) {} + /** + * The container whose network namespace this one joined through a {@code container:} network + * mode, as a security-group protected guest joins its firewall helper's; null when it has its own. + */ + private static String namespaceOwnerId(InspectContainerResponse container) { + String mode = container.getHostConfig() == null ? null : container.getHostConfig().getNetworkMode(); + return mode != null && mode.startsWith("container:") ? mode.substring("container:".length()) : null; + } + public void restoreSecurityGroups(Instance instance, String region, List groups, Map> prefixLists) { if (firewallManager == null || !firewallManager.enabled()) { @@ -290,7 +304,8 @@ public class Ec2ContainerManager { this(containerBuilder, lifecycleManager, logStreamer, containerDetector, dockerHostResolver, dockerClient, portAllocator, config, metadataServer, portForwardManager, regionResolver, containerNetworkReachability, vpcNetworkManager, reachableEndpoint, instanceTypeCatalog, - createLaunchExecutor(), Duration.ofMinutes(USER_DATA_EXECUTION_TIMEOUT_MINUTES)); + createLaunchExecutor(), createServiceNetworkRetryExecutor(), + Duration.ofMinutes(USER_DATA_EXECUTION_TIMEOUT_MINUTES)); } public Ec2ContainerManager(ContainerBuilder containerBuilder, @@ -328,6 +343,7 @@ public class Ec2ContainerManager { ContainerReachableEndpoint reachableEndpoint, Ec2InstanceTypeCatalog instanceTypeCatalog, ExecutorService executor, + ExecutorService serviceNetworkRetryExecutor, Duration userDataExecutionTimeout) { this.containerBuilder = containerBuilder; this.lifecycleManager = lifecycleManager; @@ -345,6 +361,7 @@ public class Ec2ContainerManager { this.reachableEndpoint = reachableEndpoint; this.instanceTypeCatalog = instanceTypeCatalog != null ? instanceTypeCatalog : new Ec2InstanceTypeCatalog(); this.executor = executor; + this.serviceNetworkRetryExecutor = serviceNetworkRetryExecutor; this.userDataExecutionTimeout = userDataExecutionTimeout; } @@ -367,7 +384,15 @@ public class Ec2ContainerManager { this(containerBuilder, lifecycleManager, logStreamer, containerDetector, dockerHostResolver, dockerClient, portAllocator, config, metadataServer, portForwardManager, regionResolver, containerNetworkReachability, vpcNetworkManager, reachableEndpoint, new Ec2InstanceTypeCatalog(), - executor, userDataExecutionTimeout); + executor, createServiceNetworkRetryExecutor(), userDataExecutionTimeout); + } + + /** + * Its own virtual threads, never {@link #createLaunchExecutor}'s: that pool blocks a full queue's + * submitters, and a launch worker waiting on it for a retry could stall them all. + */ + private static ExecutorService createServiceNetworkRetryExecutor() { + return Executors.newThreadPerTaskExecutor(Thread.ofVirtual().name("ec2-service-network-retry-", 0).factory()); } private static ExecutorService createLaunchExecutor() { @@ -389,6 +414,7 @@ public class Ec2ContainerManager { void stop() { closeActiveUserDataCallbacks(); executor.shutdownNow(); + serviceNetworkRetryExecutor.shutdownNow(); closeActiveUserDataCallbacks(); } @@ -514,6 +540,7 @@ public class Ec2ContainerManager { } if (containerIp != null && !containerIp.isBlank()) { instance.setContainerBridgeIp(containerIp); + refreshServiceNetworkIp(instance); if (started.namespace() == null) { exposeReachablePrivateAddress(instance, containerIp, config.services().ec2().awsFaithfulPrivateIp()); @@ -765,6 +792,8 @@ public class Ec2ContainerManager { instance.setDockerContainerId(null); instance.setSshHostPort(0); instance.setContainerBridgeIp(null); + instance.setServiceNetworkIp(null); + serviceNetworkRetries.remove(instance.getInstanceId()); } if (alreadyCleaned) { return; @@ -1027,6 +1056,7 @@ public class Ec2ContainerManager { : namespace.transportAddress(); if (containerIp != null && !containerIp.isBlank()) { instance.setContainerBridgeIp(containerIp); + refreshServiceNetworkIp(instance); if (namespace == null) { exposeReachablePrivateAddress(instance, containerIp, config.services().ec2().awsFaithfulPrivateIp()); @@ -1216,6 +1246,7 @@ public class Ec2ContainerManager { metadataServer.unregisterContainer(previousContainerIp, instance); } instance.setContainerBridgeIp(containerIp); + refreshServiceNetworkIp(instance); exposeReachablePrivateAddress(instance, containerIp, config.services().ec2().awsFaithfulPrivateIp()); if (instance.getPublicIpAddress() != null || AutomaticPublicAddress.isDue(instance, true)) { exposeReachablePublicAddress(instance); @@ -1316,6 +1347,13 @@ public class Ec2ContainerManager { if (instance == null) { return null; } + if (config.services().ec2().publicIpFromServiceNetwork()) { + retryServiceNetworkIp(instance); + String serviceNetworkIp = instance.getServiceNetworkIp(); + if (serviceNetworkIp != null && !serviceNetworkIp.isBlank()) { + return serviceNetworkIp; + } + } String containerIp = instance.getContainerBridgeIp(); if (containerIp == null || containerIp.isBlank()) { return null; @@ -1323,6 +1361,94 @@ public class Ec2ContainerManager { return containerNetworkReachability.isContainerIpRoutable(containerIp) ? containerIp : "127.0.0.1"; } + /** + * Records the instance's address on Floci's own Docker network, when + * {@code publicIpFromServiceNetwork} is on and Floci runs as a container, so + * {@link #reachablePublicAddress} reports it without asking Docker. Called where the container's + * addresses are (re)learned: launch, start and restore. + */ + void refreshServiceNetworkIp(Instance instance) { + String instanceId = instance.getInstanceId(); + // The container is the lookup's generation: a result is published only while the instance + // still runs that container, so a lookup that outlives a replacement or a teardown cannot + // overwrite what came after it. Docker is asked outside the instance lock. + String containerId; + synchronized (instance) { + containerId = instance.getDockerContainerId(); + } + String address; + try { + address = resolveServiceNetworkIp(instanceId, containerId); + } catch (RuntimeException e) { + synchronized (instance) { + if (containerId != null && containerId.equals(instance.getDockerContainerId())) { + // A Docker hiccup is not an answer: keep what was recorded and let the next + // address read retry the lookup in the background. + serviceNetworkRetries.add(instanceId); + } + } + LOG.debugv("Could not read the service-network address of {0}, will retry: {1}", + instanceId, e.getMessage()); + return; + } + synchronized (instance) { + if (!Objects.equals(containerId, instance.getDockerContainerId())) { + return; + } + instance.setServiceNetworkIp(address); + serviceNetworkRetries.remove(instanceId); + } + } + + /** + * Retries a failed {@link #refreshServiceNetworkIp} in the background, at most one attempt per + * instance at a time, so the address read that notices it never waits on Docker. + */ + private void retryServiceNetworkIp(Instance instance) { + String instanceId = instance.getInstanceId(); + if (!serviceNetworkRetries.contains(instanceId) || !serviceNetworkRetriesRunning.add(instanceId)) { + return; + } + try { + serviceNetworkRetryExecutor.execute(() -> { + try { + refreshServiceNetworkIp(instance); + } finally { + serviceNetworkRetriesRunning.remove(instanceId); + } + }); + } catch (RuntimeException e) { + // Only a shutting-down executor refuses; the next address read tries again. + serviceNetworkRetriesRunning.remove(instanceId); + LOG.warnv("Could not schedule the service-network lookup retry for {0}: {1}", + instanceId, e.getMessage()); + } + } + + private String resolveServiceNetworkIp(String instanceId, String containerId) { + if (!config.services().ec2().publicIpFromServiceNetwork() || !containerDetector.isRunningInContainer() + || containerId == null) { + return null; + } + Optional network = containerBuilder.resolveDockerNetwork(Optional.empty()); + if (network.isEmpty()) { + return null; + } + InspectContainerResponse inspect = dockerClient.inspectContainerCmd(containerId).exec(); + // A security-group protected guest joins its firewall helper's network namespace and has + // no attachment of its own: the helper's address on the network is the guest's. + String helperId = namespaceOwnerId(inspect); + if (helperId != null) { + inspect = dockerClient.inspectContainerCmd(helperId).exec(); + } + if (inspect.getNetworkSettings() == null || inspect.getNetworkSettings().getNetworks() == null) { + return null; + } + ContainerNetwork attached = inspect.getNetworkSettings().getNetworks().get(network.get()); + return attached == null || attached.getIpAddress() == null || attached.getIpAddress().isBlank() + ? null : attached.getIpAddress(); + } + /** * Publishes {@link #reachablePublicAddress} as the instance's public IP and DNS name. * The DNS name is set to the same literal rather than an AWS-shaped diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/model/Instance.java b/src/main/java/io/github/hectorvent/floci/services/ec2/model/Instance.java index 632c2d446a..36503733af 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ec2/model/Instance.java +++ b/src/main/java/io/github/hectorvent/floci/services/ec2/model/Instance.java @@ -92,6 +92,11 @@ public class Instance { * registered so metadata answers either way. */ private String imdsSourceIp; + /** + * The instance's address on Floci's own Docker network, recorded at launch, start and + * restore when {@code publicIpFromServiceNetwork} is on, so reporting it needs no Docker call. + */ + private String serviceNetworkIp; private String userData; private String encodedUserData; private int sshHostPort; @@ -249,6 +254,9 @@ public class Instance { public String getContainerBridgeIp() { return containerBridgeIp; } public void setContainerBridgeIp(String containerBridgeIp) { this.containerBridgeIp = containerBridgeIp; } + public String getServiceNetworkIp() { return serviceNetworkIp; } + public void setServiceNetworkIp(String serviceNetworkIp) { this.serviceNetworkIp = serviceNetworkIp; } + public String getImdsSourceIp() { return imdsSourceIp; } public void setImdsSourceIp(String imdsSourceIp) { this.imdsSourceIp = imdsSourceIp; } diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index b9d06b72d4..3a446034bb 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -755,6 +755,9 @@ floci: # FLOCI_SERVICES_EC2_INSTANCE_RESOURCE_LIMITS instance-resource-limits: true aws-faithful-private-ip: false + # Floci in a container: report an instance's address on Floci's own Docker network as its + # public IP. FLOCI_SERVICES_EC2_PUBLIC_IP_FROM_SERVICE_NETWORK + public-ip-from-service-network: false # container-ips-routable: true # Auto-detected by default (a throwaway TCP probe toward # the container network). Set explicitly when the probe # can't speak for your clients, e.g. Floci itself running 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.java index 2cda79071d..a4834a338d 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 @@ -92,6 +92,7 @@ import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.after; import static org.mockito.Mockito.atLeastOnce; +import static org.mockito.Mockito.clearInvocations; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.doReturn; @@ -1101,6 +1102,253 @@ class Ec2ContainerManagerTest { assertNull(manager.reachablePublicAddress(null)); } + @Test + void reachablePublicAddressReportsTheServiceNetworkAddressWhenEnabledInAContainer() { + DockerClient docker = guestDocker("172.20.0.9", null); + Ec2ContainerManager manager = managerOnServiceNetwork(true, true, docker); + Instance instance = serviceNetworkInstance(); + + manager.refreshServiceNetworkIp(instance); + + assertEquals("172.20.0.9", instance.getServiceNetworkIp()); + assertEquals("172.20.0.9", manager.reachablePublicAddress(instance)); + } + + @Test + void reachablePublicAddressReportsTheRecordedAddressWithoutAskingDocker() { + DockerClient docker = guestDocker("172.20.0.9", null); + Ec2ContainerManager manager = managerOnServiceNetwork(true, true, docker); + Instance instance = serviceNetworkInstance(); + manager.refreshServiceNetworkIp(instance); + + manager.reachablePublicAddress(instance); + manager.reachablePublicAddress(instance); + + verify(docker, times(1)).inspectContainerCmd(TEST_CONTAINER_ID); + } + + @Test + void aFailedLookupIsRetriedInTheBackgroundByTheNextAddressRead() { + DockerClient docker = guestDocker("172.20.0.9", null); + InspectContainerResponse guest = docker.inspectContainerCmd(TEST_CONTAINER_ID).exec(); + when(docker.inspectContainerCmd(TEST_CONTAINER_ID).exec()) + .thenThrow(new IllegalStateException("daemon busy")).thenReturn(guest); + ExecutorService launchExecutor = mock(ExecutorService.class); + ExecutorService retryExecutor = mock(ExecutorService.class); + List tasks = new ArrayList<>(); + doAnswer(invocation -> tasks.add(invocation.getArgument(0))).when(retryExecutor).execute(any(Runnable.class)); + Ec2ContainerManager manager = managerOnServiceNetwork(true, true, docker, launchExecutor, retryExecutor); + Instance instance = serviceNetworkInstance(); + manager.refreshServiceNetworkIp(instance); + clearInvocations(docker); + + assertEquals("127.0.0.1", manager.reachablePublicAddress(instance)); + assertEquals("127.0.0.1", manager.reachablePublicAddress(instance)); + verify(docker, never()).inspectContainerCmd(anyString()); + assertEquals(1, tasks.size()); + + tasks.getFirst().run(); + + assertEquals("172.20.0.9", manager.reachablePublicAddress(instance)); + assertEquals(1, tasks.size()); + // Never on the launch pool, whose blocking backpressure could stall the workers behind it. + verify(launchExecutor, never()).execute(any(Runnable.class)); + verify(launchExecutor, never()).submit(any(Runnable.class)); + } + + @Test + void aLookupThatOutlivesAContainerReplacementDoesNotOverwriteTheNewAddress() throws Exception { + CountDownLatch staleInspectStarted = new CountDownLatch(1); + CountDownLatch releaseStaleInspect = new CountDownLatch(1); + DockerClient docker = mock(DockerClient.class, RETURNS_DEEP_STUBS); + InspectContainerResponse oldGuest = inspectWithNetworks( + Map.of("floci-net", new ContainerNetwork().withIpv4Address("172.20.0.9"))); + InspectContainerResponse newGuest = inspectWithNetworks( + Map.of("floci-net", new ContainerNetwork().withIpv4Address("172.20.0.21"))); + when(docker.inspectContainerCmd("old-container").exec()).thenAnswer(invocation -> { + staleInspectStarted.countDown(); + releaseStaleInspect.await(5, TimeUnit.SECONDS); + return oldGuest; + }); + when(docker.inspectContainerCmd("new-container").exec()).thenReturn(newGuest); + Ec2ContainerManager manager = managerOnServiceNetwork(true, true, docker); + Instance instance = serviceNetworkInstance(); + instance.setDockerContainerId("old-container"); + + Thread staleLookup = Thread.ofVirtual().start(() -> manager.refreshServiceNetworkIp(instance)); + assertTrue(staleInspectStarted.await(5, TimeUnit.SECONDS)); + synchronized (instance) { + instance.setDockerContainerId("new-container"); + } + manager.refreshServiceNetworkIp(instance); + releaseStaleInspect.countDown(); + staleLookup.join(Duration.ofSeconds(5)); + + assertFalse(staleLookup.isAlive()); + assertEquals("172.20.0.21", instance.getServiceNetworkIp()); + assertEquals("172.20.0.21", manager.reachablePublicAddress(instance)); + } + + @Test + void aLookupInFlightDuringTeardownCannotRestoreTheAddress() throws Exception { + CountDownLatch staleInspectStarted = new CountDownLatch(1); + CountDownLatch releaseStaleInspect = new CountDownLatch(1); + AtomicBoolean firstInspect = new AtomicBoolean(true); + DockerClient docker = mock(DockerClient.class, RETURNS_DEEP_STUBS); + InspectContainerResponse guest = inspectWithNetworks( + Map.of("floci-net", new ContainerNetwork().withIpv4Address("172.20.0.9"))); + when(docker.inspectContainerCmd(TEST_CONTAINER_ID).exec()).thenAnswer(invocation -> { + if (firstInspect.getAndSet(false)) { + staleInspectStarted.countDown(); + releaseStaleInspect.await(5, TimeUnit.SECONDS); + } + return guest; + }); + Ec2ContainerManager manager = managerOnServiceNetwork(true, true, docker); + Instance instance = serviceNetworkInstance(); + instance.setState(InstanceState.pending()); + + Thread staleLookup = Thread.ofVirtual().start(() -> manager.refreshServiceNetworkIp(instance)); + assertTrue(staleInspectStarted.await(5, TimeUnit.SECONDS)); + assertTrue(manager.cancelLaunch(instance)); + releaseStaleInspect.countDown(); + staleLookup.join(Duration.ofSeconds(5)); + + assertFalse(staleLookup.isAlive()); + assertNull(instance.getDockerContainerId()); + assertNull(instance.getServiceNetworkIp()); + } + + @Test + void aProtectedGuestReportsItsFirewallHelpersServiceNetworkAddress() { + DockerClient docker = guestDocker(null, "172.20.0.11"); + Ec2ContainerManager manager = managerOnServiceNetwork(true, true, docker); + Instance instance = serviceNetworkInstance(); + + manager.refreshServiceNetworkIp(instance); + + assertEquals("172.20.0.11", manager.reachablePublicAddress(instance)); + } + + @Test + void reachablePublicAddressIgnoresTheServiceNetworkWhenDisabled() { + DockerClient docker = guestDocker("172.20.0.9", null); + Ec2ContainerManager manager = managerOnServiceNetwork(false, true, docker); + Instance instance = serviceNetworkInstance(); + + manager.refreshServiceNetworkIp(instance); + + assertNull(instance.getServiceNetworkIp()); + assertEquals("127.0.0.1", manager.reachablePublicAddress(instance)); + verify(docker, never()).inspectContainerCmd(anyString()); + } + + @Test + void reachablePublicAddressIgnoresTheServiceNetworkWhenFlociRunsOnTheHost() { + DockerClient docker = guestDocker("172.20.0.9", null); + Ec2ContainerManager manager = managerOnServiceNetwork(true, false, docker); + Instance instance = serviceNetworkInstance(); + + manager.refreshServiceNetworkIp(instance); + + assertEquals("127.0.0.1", manager.reachablePublicAddress(instance)); + } + + @Test + void reachablePublicAddressFallsBackWhenTheInstanceIsNotOnTheServiceNetwork() { + DockerClient docker = guestDocker(null, null); + Ec2ContainerManager manager = managerOnServiceNetwork(true, true, docker); + Instance instance = serviceNetworkInstance(); + + manager.refreshServiceNetworkIp(instance); + + assertEquals("127.0.0.1", manager.reachablePublicAddress(instance)); + } + + private static Instance serviceNetworkInstance() { + Instance instance = new Instance(); + instance.setInstanceId("i-service-network"); + instance.setDockerContainerId(TEST_CONTAINER_ID); + instance.setContainerBridgeIp("172.17.0.4"); + return instance; + } + + /** + * A daemon whose guest container sits on the bridge, unroutable from the host, and on Floci's + * own network {@code floci-net} at {@code guestIp} when that is not null. With a + * {@code helperIp}, the guest instead joins a firewall helper's namespace, as a security-group + * protected guest does, and the helper is on {@code floci-net} at that address. + */ + private static DockerClient guestDocker(String guestIp, String helperIp) { + DockerClient docker = mock(DockerClient.class, RETURNS_DEEP_STUBS); + Map guestNetworks = new LinkedHashMap<>(); + if (helperIp == null) { + guestNetworks.put("bridge", new ContainerNetwork().withIpv4Address("172.17.0.4")); + } + if (guestIp != null) { + guestNetworks.put("floci-net", new ContainerNetwork().withIpv4Address(guestIp)); + } + InspectContainerResponse guest = inspectWithNetworks(guestNetworks); + if (helperIp != null) { + HostConfig hostConfig = mock(HostConfig.class); + when(hostConfig.getNetworkMode()).thenReturn("container:helper-1"); + when(guest.getHostConfig()).thenReturn(hostConfig); + InspectContainerResponse helper = inspectWithNetworks(Map.of( + "bridge", new ContainerNetwork().withIpv4Address("172.17.0.5"), + "floci-net", new ContainerNetwork().withIpv4Address(helperIp))); + when(docker.inspectContainerCmd("helper-1").exec()).thenReturn(helper); + } + when(docker.inspectContainerCmd(TEST_CONTAINER_ID).exec()).thenReturn(guest); + clearInvocations(docker); + return docker; + } + + private static InspectContainerResponse inspectWithNetworks(Map networks) { + InspectContainerResponse inspect = mock(InspectContainerResponse.class); + NetworkSettings settings = mock(NetworkSettings.class); + when(inspect.getNetworkSettings()).thenReturn(settings); + when(settings.getNetworks()).thenReturn(networks); + return inspect; + } + + private static Ec2ContainerManager managerOnServiceNetwork(boolean enabled, boolean inContainer, + DockerClient docker) { + return managerOnServiceNetwork(enabled, inContainer, docker, mock(ExecutorService.class), + mock(ExecutorService.class)); + } + + /** A manager on {@code docker} whose bridge addresses are unroutable from the host. */ + private static Ec2ContainerManager managerOnServiceNetwork(boolean enabled, boolean inContainer, + DockerClient docker, ExecutorService executor, + ExecutorService retryExecutor) { + EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS); + when(config.services().ec2().publicIpFromServiceNetwork()).thenReturn(enabled); + ContainerDetector detector = mock(ContainerDetector.class); + when(detector.isRunningInContainer()).thenReturn(inContainer); + ContainerBuilder builder = mock(ContainerBuilder.class); + when(builder.resolveDockerNetwork(Optional.empty())).thenReturn(Optional.of("floci-net")); + + return new Ec2ContainerManager( + builder, + mock(ContainerLifecycleManager.class), + mock(ContainerLogStreamer.class), + detector, + mock(DockerHostResolver.class), + docker, + mock(PortAllocator.class), + config, + mock(Ec2MetadataServer.class), + mock(Ec2PortForwardManager.class), + mock(RegionResolver.class), + mock(ContainerNetworkReachability.class), + mock(VpcNetworkManager.class), + mock(ContainerReachableEndpoint.class), + new Ec2InstanceTypeCatalog(), + executor, + retryExecutor, + Duration.ofSeconds(5)); + } + private static Ec2ContainerManager managerWithReachability(ContainerNetworkReachability reachability) { return new Ec2ContainerManager( mock(ContainerBuilder.class),