From dc41417e79964a70a94c0ea89c3035e193936c78 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?V=C5=A9=20Th=E1=BA=BF=20Huy?= <31652864+vuthehuyht@users.noreply.github.com> Date: Fri, 9 Oct 2026 06:25:31 +0700 Subject: [PATCH] fix(ec2): avoid Docker waits on the first CreateVpc (#5179) * fix: avoid Docker waits on first EC2 CreateVpc * fix(ec2): reseed default VPC resources after a state reset Ec2Service now implements Resettable: clear() forgets the seeded account scopes and seeds the default region again, so a reset followed by DescribeVpcs still returns the default VPC and subnets. Also run Ec2CreateVpcLatencyTest in the non-mock EC2 compatibility job, where VPC planning is active and a regression of the first-call Docker wait would be caught. * refactor(ec2): share one default-region seeding method between startup and reset Ec2Startup and Ec2Service.clear() repeated the same enabled check and seed call. Both now go through Ec2Service.seedDefaultRegionIfEnabled() so they cannot drift apart. Also reorder the Resettable import. --- .github/workflows/compatibility.yml | 2 +- .../floci/test/Ec2CreateVpcLatencyTest.java | 63 ++++++++++++ docs/services/ec2.md | 12 +++ .../floci/services/ec2/Ec2Service.java | 17 +++- .../floci/services/ec2/Ec2Startup.java | 24 +++++ .../services/ec2/net/VpcNetworkManager.java | 99 ++++++++++++------- .../floci/services/ec2/Ec2ServiceTest.java | 77 ++++++++++++++- .../services/ec2/Ec2StartupServiceTest.java | 34 +++++++ .../ec2/net/VpcNetworkManagerTest.java | 99 +++++++++++++++++++ 9 files changed, 385 insertions(+), 42 deletions(-) create mode 100644 compatibility-tests/sdk-test-java/src/test/java/com/floci/test/Ec2CreateVpcLatencyTest.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Startup.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/ec2/Ec2StartupServiceTest.java diff --git a/.github/workflows/compatibility.yml b/.github/workflows/compatibility.yml index 2ad3991445..c503ef30aa 100644 --- a/.github/workflows/compatibility.yml +++ b/.github/workflows/compatibility.yml @@ -536,7 +536,7 @@ jobs: -e FLOCI_EC2_CONTAINERS="$1" \ -v "$(pwd)/test-results/$1:/results" \ --entrypoint bash \ - compat-sdk-test-java -c 'status=0; mvn test -B -Dtest=Ec2ContainerTest -Dorg.slf4j.simpleLogger.defaultLogLevel=warn || status=$?; cp target/surefire-reports/TEST-*.xml /results/ 2>/dev/null || true; exit $status' + compat-sdk-test-java -c 'status=0; mvn test -B -Dtest=Ec2ContainerTest,Ec2CreateVpcLatencyTest -Dorg.slf4j.simpleLogger.defaultLogLevel=warn || status=$?; cp target/surefire-reports/TEST-*.xml /results/ 2>/dev/null || true; exit $status' SH - name: Run tests with security group enforcement diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/Ec2CreateVpcLatencyTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/Ec2CreateVpcLatencyTest.java new file mode 100644 index 0000000000..195ded8fe6 --- /dev/null +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/Ec2CreateVpcLatencyTest.java @@ -0,0 +1,63 @@ +package com.floci.test; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import software.amazon.awssdk.services.ec2.Ec2Client; +import software.amazon.awssdk.services.ec2.model.CreateVpcRequest; +import software.amazon.awssdk.services.ec2.model.Filter; +import software.amazon.awssdk.services.ec2.model.ResourceType; +import software.amazon.awssdk.services.ec2.model.Tag; +import software.amazon.awssdk.services.ec2.model.TagSpecification; +import software.amazon.awssdk.services.ec2.model.Vpc; + +import java.time.Duration; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + +class Ec2CreateVpcLatencyTest { + + @Test + @DisplayName("CreateVpc returns promptly with default SDK retries and keeps intentional creates distinct") + void createVpcWithDefaultRetriesCreatesExactlyOneVpcPerCall() { + String name = TestFixtures.uniqueName("create-vpc-latency"); + Filter filter = Filter.builder().name("tag:Name").values(name).build(); + CreateVpcRequest request = CreateVpcRequest.builder() + .cidrBlock("42.0.0.0/16") + .tagSpecifications(TagSpecification.builder() + .resourceType(ResourceType.VPC) + .tags(Tag.builder().key("Name").value(name).build()) + .build()) + .build(); + + try (Ec2Client ec2 = TestFixtures.ec2Client()) { + try { + long start = System.nanoTime(); + String first = ec2.createVpc(request).vpc().vpcId(); + Duration elapsed = Duration.ofNanos(System.nanoTime() - start); + + assertThat(elapsed).isLessThan(Duration.ofSeconds(5)); + assertThat(ec2.describeVpcs(describe -> describe.filters(filter)).vpcs()) + .extracting(Vpc::vpcId).containsExactly(first); + + String second = ec2.createVpc(request).vpc().vpcId(); + assertThat(second).isNotEqualTo(first); + assertThat(ec2.describeVpcs(describe -> describe.filters(filter)).vpcs()) + .extracting(Vpc::vpcId).containsExactlyInAnyOrder(first, second); + } finally { + List created = ec2.describeVpcs(describe -> describe.filters(filter)).vpcs(); + for (Vpc vpc : created) { + ec2.deleteVpc(delete -> delete.vpcId(vpc.vpcId())); + } + } + } + } + + @Test + @DisplayName("DescribeVpcs exposes a fresh account's default VPC before CreateVpc") + void describeVpcsSeedsDefaultsBeforeAnyMutation() { + try (Ec2Client ec2 = TestFixtures.ec2Client("517500000001")) { + assertThat(ec2.describeVpcs().vpcs()).filteredOn(Vpc::isDefault).hasSize(1); + } + } +} diff --git a/docs/services/ec2.md b/docs/services/ec2.md index 8e8cb2ef12..a72092b34f 100644 --- a/docs/services/ec2.md +++ b/docs/services/ec2.md @@ -856,6 +856,18 @@ launches. An instance's reported private IP is then an address its container act from the subnet CIDR the caller declared, not a plausible-looking number. Instances in the same VPC reach each other at those addresses; instances in different VPCs sit on different bridges. +`CreateVpc` and `CreateSubnet` record declarations without contacting Docker. CIDR collision +checks and fallback address planning run when a consumer first needs an effective address or +network attachment. This keeps management calls responsive even when the Docker daemon is slow. +For overlapping VPC CIDRs, the first VPC whose addresses are needed keeps the declared range; +later VPCs use the fallback pool. Within one emulator run, allocated addresses remain on the +same effective range. + +When EC2 is enabled, Floci initializes its service, restores persisted state, and seeds the +configured region's default resources during startup. Other account and region scopes seed on +first access. Docker reconciliation can lengthen startup, and Docker-backed instance launches +still depend on daemon responsiveness. + One network per **VPC**, not per subnet: subnets inside a VPC route to each other in AWS, so a network per subnet would manufacture a partition AWS does not have. Per-subnet addressing is kept anyway: the network's IPAM pool is the whole VPC CIDR and each subnet allocates static addresses 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.java index 39984d7615..26f7837f61 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 @@ -10,6 +10,7 @@ import io.github.hectorvent.floci.core.common.CidrCanonicalizer; import io.github.hectorvent.floci.core.common.ContainerTeardown; import io.github.hectorvent.floci.core.common.RequestContext; import io.github.hectorvent.floci.core.common.RequestScopes; +import io.github.hectorvent.floci.core.common.Resettable; import io.github.hectorvent.floci.core.resource.ExplorerResource; import io.github.hectorvent.floci.core.resource.ResourceProvider; import io.github.hectorvent.floci.core.resource.SupportedResourceType; @@ -135,7 +136,7 @@ import java.util.stream.Collectors; import java.util.stream.Stream; @ApplicationScoped -public class Ec2Service implements ContainerTeardown, ResourceProvider { +public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettable { private static final Logger LOG = Logger.getLogger(Ec2Service.class); @@ -999,6 +1000,20 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider { // ─── Default resource seeding ────────────────────────────────────────────── + // Storage is wiped before clear() runs, so the seeded-scope memory must go too or the default + // VPC and subnets would never come back. + @Override + public void clear() { + seededAccountRegions.clear(); + seedDefaultRegionIfEnabled(); + } + + public void seedDefaultRegionIfEnabled() { + if (config.services().ec2().enabled()) { + ensureDefaultResources(config.defaultRegion()); + } + } + public void ensureDefaultResources(String region) { String ownerAccountId = callerAccountId(); String seedScope = ownerAccountId + "::" + region; diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Startup.java b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Startup.java new file mode 100644 index 0000000000..efc9363830 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Startup.java @@ -0,0 +1,24 @@ +package io.github.hectorvent.floci.services.ec2; + +import io.quarkus.runtime.StartupEvent; +import jakarta.annotation.Priority; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.enterprise.event.Observes; +import jakarta.inject.Inject; +import jakarta.interceptor.Interceptor; + +@ApplicationScoped +public class Ec2Startup { + + private final Ec2Service service; + + @Inject + public Ec2Startup(Ec2Service service) { + this.service = service; + } + + // Run after the lifecycle's boot hooks and persistent-path validation. + void onStart(@Observes @Priority(Interceptor.Priority.APPLICATION + 600) StartupEvent ignored) { + service.seedDefaultRegionIfEnabled(); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/net/VpcNetworkManager.java b/src/main/java/io/github/hectorvent/floci/services/ec2/net/VpcNetworkManager.java index 6fd03f5a35..4d623be409 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ec2/net/VpcNetworkManager.java +++ b/src/main/java/io/github/hectorvent/floci/services/ec2/net/VpcNetworkManager.java @@ -170,43 +170,60 @@ public class VpcNetworkManager { // ─── Declaration: CreateVpc / CreateSubnet ──────────────────────────────── /** - * Records the address plan for a VPC. Called from CreateVpc and from default-resource - * seeding; the Docker network itself is only created when the first instance needs it - * (see {@link #attach}), because most roots in this corpus create VPCs they never launch - * anything into and a Linux bridge per unused VPC is pure daemon churn. + * Records a VPC declaration without contacting Docker. Its address plan is resolved when + * a consumer first needs an effective CIDR or private address; the network itself is only + * created on attachment. Management requests must not wait for the Docker daemon. */ public void declareVpc(String region, String vpcId, String declaredCidr) { if (!enabled() || region == null || vpcId == null) { return; } - synchronized (planLock) { - // Deliberately not computeIfAbsent: planVpc reads the whole binding map to detect - // collisions, and ConcurrentHashMap forbids that from inside a mapping function. - String vpcKey = key(region, vpcId); - if (!bindings.containsKey(vpcKey)) { - bindings.put(vpcKey, planVpc(region, vpcId, declaredCidr)); - } - } + bindings.putIfAbsent(key(region, vpcId), + new VpcBinding(region, vpcId, declaredCidr, networkName(region, vpcId))); } - /** Records the address plan for a subnet inside an already-declared VPC. */ + /** Records a subnet declaration inside an already-declared VPC. */ public void declareSubnet(String region, String vpcId, String subnetId, String declaredCidr) { if (!enabled() || region == null || vpcId == null || subnetId == null) { return; } - synchronized (planLock) { - VpcBinding vpc = bindings.get(key(region, vpcId)); - if (vpc == null) { - return; + VpcBinding vpc = bindings.get(key(region, vpcId)); + if (vpc == null) { + return; + } + synchronized (vpc.declarationLock) { + if (!vpc.subnetDeclarations.containsKey(subnetId)) { + vpc.subnetDeclarations.put(subnetId, declaredCidr); } - if (!vpc.subnets.containsKey(subnetId)) { + if (vpc.planned && !vpc.subnets.containsKey(subnetId)) { vpc.subnets.put(subnetId, planSubnet(vpc, subnetId, declaredCidr)); } subnetOwner.put(key(region, subnetId), key(region, vpcId)); } } - private VpcBinding planVpc(String region, String vpcId, String declaredCidr) { + private VpcBinding plannedVpc(String region, String vpcId) { + VpcBinding vpc = bindings.get(key(region, vpcId)); + if (vpc == null || vpc.planned) { + return vpc; + } + synchronized (planLock) { + if (!vpc.planned) { + planVpc(vpc); + synchronized (vpc.declarationLock) { + vpc.subnetDeclarations.forEach((subnetId, cidr) -> + vpc.subnets.put(subnetId, planSubnet(vpc, subnetId, cidr))); + vpc.planned = true; + } + } + } + return vpc; + } + + private void planVpc(VpcBinding vpc) { + String region = vpc.region; + String vpcId = vpc.vpcId; + String declaredCidr = vpc.declaredCidr; Optional declared = Cidr4.parse(declaredCidr); String rejection = rejectionReason(region, vpcId, declared, declaredCidr, List.of()); Cidr4 effective; @@ -229,8 +246,8 @@ public class VpcNetworkManager { vpcId, region, String.valueOf(declaredCidr), rejection, effective); } } - return new VpcBinding(region, vpcId, declared.orElse(null), effective, rejection != null, - networkName(region, vpcId)); + vpc.effective = effective; + vpc.substituted = rejection != null; } /** @@ -480,7 +497,9 @@ public class VpcNetworkManager { } public void releasePrivateIp(String region, String subnetId, String address) { - SubnetBinding subnet = subnetBinding(region, subnetId); + String vpcKey = subnetOwner.get(key(region, subnetId)); + VpcBinding vpc = vpcKey == null ? null : bindings.get(vpcKey); + SubnetBinding subnet = vpc == null ? null : vpc.subnets.get(subnetId); if (subnet != null && address != null) { subnet.leased.remove(address); } @@ -505,7 +524,7 @@ public class VpcNetworkManager { if (!enabled() || containerId == null || address == null) { return Optional.empty(); } - VpcBinding vpc = bindings.get(key(region, vpcId)); + VpcBinding vpc = plannedVpc(region, vpcId); if (vpc == null || vpc.effective == null) { return Optional.empty(); } @@ -549,7 +568,7 @@ public class VpcNetworkManager { if (!enabled() || containerId == null || vpcId == null) { return false; } - VpcBinding vpc = bindings.get(key(region, vpcId)); + VpcBinding vpc = plannedVpc(region, vpcId); if (vpc == null || vpc.effective == null) { return false; } @@ -773,7 +792,10 @@ public class VpcNetworkManager { } VpcBinding vpc = bindings.get(vpcKey); if (vpc != null) { - vpc.subnets.remove(subnetId); + synchronized (vpc.declarationLock) { + vpc.subnetDeclarations.remove(subnetId); + vpc.subnets.remove(subnetId); + } } } @@ -783,7 +805,9 @@ public class VpcNetworkManager { if (vpc == null) { return; } - vpc.subnets.keySet().forEach(subnetId -> subnetOwner.remove(key(region, subnetId))); + synchronized (vpc.declarationLock) { + vpc.subnetDeclarations.keySet().forEach(subnetId -> subnetOwner.remove(key(region, subnetId))); + } if (!vpc.created) { return; } @@ -901,7 +925,7 @@ public class VpcNetworkManager { // ─── Introspection, for tests and reporting ────────────────────────────── public Optional effectiveVpcCidr(String region, String vpcId) { - VpcBinding vpc = bindings.get(key(region, vpcId)); + VpcBinding vpc = plannedVpc(region, vpcId); return vpc == null || vpc.effective == null ? Optional.empty() : Optional.of(vpc.effective.toString()); } @@ -917,7 +941,7 @@ public class VpcNetworkManager { } public boolean isSubstituted(String region, String vpcId) { - VpcBinding vpc = bindings.get(key(region, vpcId)); + VpcBinding vpc = plannedVpc(region, vpcId); return vpc != null && vpc.substituted; } @@ -932,6 +956,9 @@ public class VpcNetworkManager { return null; } VpcBinding vpc = bindings.get(vpcKey); + if (vpc != null) { + vpc = plannedVpc(vpc.region, vpc.vpcId); + } return vpc == null ? null : vpc.subnets.get(subnetId); } @@ -977,21 +1004,23 @@ public class VpcNetworkManager { private static final class VpcBinding { final String region; final String vpcId; + final String declaredCidr; final Cidr4 declared; - final Cidr4 effective; - final boolean substituted; + Cidr4 effective; + boolean substituted; final String networkName; + final Object declarationLock = new Object(); + final Map subnetDeclarations = new LinkedHashMap<>(); final Map subnets = new ConcurrentHashMap<>(); + volatile boolean planned; volatile boolean created; volatile String flociContainerId; - VpcBinding(String region, String vpcId, Cidr4 declared, Cidr4 effective, - boolean substituted, String networkName) { + VpcBinding(String region, String vpcId, String declaredCidr, String networkName) { this.region = region; this.vpcId = vpcId; - this.declared = declared; - this.effective = effective; - this.substituted = substituted; + this.declaredCidr = declaredCidr; + this.declared = Cidr4.parse(declaredCidr).orElse(null); this.networkName = networkName; } } 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.java index f5b0675ee0..fbaab59eb9 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 @@ -1,6 +1,7 @@ package io.github.hectorvent.floci.services.ec2; import com.fasterxml.jackson.core.type.TypeReference; +import com.github.dockerjava.api.DockerClient; import io.github.hectorvent.floci.config.EmulatorConfig; import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.core.common.RequestContext; @@ -87,6 +88,7 @@ import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.argThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; +import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; @@ -94,6 +96,29 @@ import static org.mockito.Mockito.when; class Ec2ServiceTest { + @Test + void createAndDescribeVpcsDoNotContactDockerEvenOnFirstUse() { + EmulatorConfig config = mockConfig(false); + EmulatorConfig.VpcNetworksConfig networks = mock(EmulatorConfig.VpcNetworksConfig.class); + when(config.services().ec2().vpcNetworks()).thenReturn(networks); + when(networks.enabled()).thenReturn(true); + when(config.docker()).thenReturn(mock(EmulatorConfig.DockerConfig.class)); + when(config.docker().resourceNamespace()).thenReturn(Optional.empty()); + DockerClient docker = mock(DockerClient.class); + VpcNetworkManager manager = new VpcNetworkManager(config, docker, null); + Ec2Service service = new Ec2Service(config, mock(Ec2ContainerManager.class), + mock(Ec2PortForwardManager.class), mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class), + new Ec2InstanceTypeCatalog(), new InMemoryStorageFactory(), manager); + + Vpc created = service.createVpc("eu-central-1", "42.0.0.0/16", false); + service.createTags("eu-central-1", List.of(created.getVpcId()), List.of(new Tag("Name", "probe"))); + List found = service.describeVpcs("eu-central-1", List.of(), Map.of("tag:Name", List.of("probe"))); + + assertEquals(List.of(created.getVpcId()), found.stream().map(Vpc::getVpcId).toList()); + assertTrue(service.describeVpcs("eu-central-1", List.of(), Map.of()).stream().anyMatch(Vpc::isDefault)); + verifyNoInteractions(docker); + } + @Test void sharedDescribeVpcsOmitsUnknownIdsButExplicitLookupStillRejectsThem() { Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class), @@ -4516,6 +4541,7 @@ class Ec2ServiceTest { private static final class InMemoryStorageFactory extends StorageFactory { private final Map> overrides; private final jakarta.enterprise.inject.Instance requestContextInstance; + private final List> created = new ArrayList<>(); private InMemoryStorageFactory() { this(Map.of(), null); @@ -4544,11 +4570,18 @@ class Ec2ServiceTest { if (override != null) { return (AccountAwareStorageBackend) override; } - if (requestContextInstance != null) { - return new AccountAwareStorageBackend<>(new io.github.hectorvent.floci.core.storage.InMemoryStorage<>(), - requestContextInstance, "000000000000"); - } - return AccountAwareStorageBackend.inMemory("000000000000"); + AccountAwareStorageBackend backend = requestContextInstance != null + ? new AccountAwareStorageBackend<>(new io.github.hectorvent.floci.core.storage.InMemoryStorage<>(), + requestContextInstance, "000000000000") + : AccountAwareStorageBackend.inMemory("000000000000"); + created.add(backend); + return backend; + } + + // Same effect as StorageFactory.clearAll() on the backends this factory handed out. + @Override + public synchronized void clearAll() { + created.forEach(AccountAwareStorageBackend::clear); } } @@ -4998,6 +5031,40 @@ class Ec2ServiceTest { assertTrue(service.hostInstances("us-east-1", hostId[0]).isEmpty()); } + @Test + void seedDefaultRegionIfEnabledDoesNothingWhenEc2IsDisabled() { + EmulatorConfig config = mockConfig(true); + when(config.services().ec2().enabled()).thenReturn(false); + when(config.defaultRegion()).thenReturn("us-east-1"); + Ec2Service service = spy(new Ec2Service(config, mock(Ec2ContainerManager.class), + mock(Ec2PortForwardManager.class), mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class), + new Ec2InstanceTypeCatalog(), new InMemoryStorageFactory())); + + service.seedDefaultRegionIfEnabled(); + + verify(service, never()).ensureDefaultResources(anyString()); + } + + @Test + void clearSeedsDefaultVpcAndSubnetsAgainAfterStorageWipe() { + EmulatorConfig config = mockConfig(true); + when(config.services().ec2().enabled()).thenReturn(true); + when(config.defaultRegion()).thenReturn("us-east-1"); + InMemoryStorageFactory storageFactory = new InMemoryStorageFactory(); + Ec2Service service = new Ec2Service(config, mock(Ec2ContainerManager.class), + mock(Ec2PortForwardManager.class), mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class), + new Ec2InstanceTypeCatalog(), storageFactory); + service.ensureDefaultResources("us-east-1"); + // A reset wipes storage before it calls clear(). + storageFactory.clearAll(); + assertTrue(service.describeVpcs("us-east-1", List.of(), Map.of()).isEmpty()); + + service.clear(); + + assertTrue(service.describeVpcs("us-east-1", List.of(), Map.of()).stream().anyMatch(Vpc::isDefault)); + assertFalse(service.describeSubnets("us-east-1", List.of(), Map.of()).isEmpty()); + } + @Test void allocateHostsAcceptsModelledZoneWithNoSubnet() { Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class), diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2StartupServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2StartupServiceTest.java new file mode 100644 index 0000000000..a8dfbb154b --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2StartupServiceTest.java @@ -0,0 +1,34 @@ +package io.github.hectorvent.floci.services.ec2; + +import io.quarkus.runtime.StartupEvent; +import jakarta.annotation.Priority; +import jakarta.enterprise.inject.spi.ObserverMethod; +import org.junit.jupiter.api.Test; + +import java.lang.reflect.Method; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; + +class Ec2StartupServiceTest { + + @Test + void startupObserverRunsAfterDefaultLifecycleObservers() throws ReflectiveOperationException { + Method observer = Ec2Startup.class.getDeclaredMethod("onStart", StartupEvent.class); + Priority priority = observer.getParameters()[0].getAnnotation(Priority.class); + + assertTrue(priority.value() > ObserverMethod.DEFAULT_PRIORITY, + "EC2 initialization must follow the lifecycle's boot hooks and path validation"); + } + + @Test + void startupSeedsThroughTheSameEntryPointAsReset() { + Ec2Service service = mock(Ec2Service.class); + + new Ec2Startup(service).onStart(new StartupEvent()); + + verify(service).seedDefaultRegionIfEnabled(); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/net/VpcNetworkManagerTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/net/VpcNetworkManagerTest.java index 9982813967..da8e2d9a96 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ec2/net/VpcNetworkManagerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ec2/net/VpcNetworkManagerTest.java @@ -22,6 +22,11 @@ import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; @@ -36,6 +41,7 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; class VpcNetworkManagerTest { @@ -106,6 +112,99 @@ class VpcNetworkManagerTest { existingNetwork(name, subnet, labels, Map.of()); } + @Test + void declaringAndDeletingUnusedNetworksDoesNotContactDocker() { + manager.declareVpc(REGION, "vpc-private", "10.0.0.0/16"); + manager.declareSubnet(REGION, "vpc-private", "subnet-a", "10.0.1.0/24"); + manager.declareVpc(REGION, "vpc-public", "42.0.0.0/16"); + manager.forgetSubnet(REGION, "subnet-a"); + manager.deleteVpcNetwork(REGION, "vpc-private"); + manager.deleteVpcNetwork(REGION, "vpc-public"); + + verifyNoInteractions(docker); + assertTrue(manager.allocatePrivateIp(REGION, "subnet-a").isEmpty()); + assertTrue(manager.effectiveVpcCidr(REGION, "vpc-public").isEmpty()); + } + + @Test + void collisionChecksSeeNetworksAddedAfterDeclaration() { + manager.declareVpc(REGION, "vpc-late", "10.0.0.0/16"); + manager.declareSubnet(REGION, "vpc-late", "subnet-late", "10.0.1.0/24"); + existingNetwork("external", "10.0.0.0/16", Map.of()); + + String address = manager.allocatePrivateIp(REGION, "subnet-late").orElseThrow(); + + assertTrue(manager.isSubstituted(REGION, "vpc-late")); + assertFalse(address.startsWith("10.0.")); + } + + @Test + void addingASubnetAfterPlanningKeepsExistingLeases() { + manager.declareVpc(REGION, "vpc-1", "10.0.0.0/16"); + manager.declareSubnet(REGION, "vpc-1", "subnet-a", "10.0.1.0/24"); + assertTrue(manager.reservePrivateIp(REGION, "subnet-a", "10.0.1.10")); + manager.declareSubnet(REGION, "vpc-1", "subnet-b", "10.0.2.0/24"); + + assertEquals("10.0.1.11", manager.allocatePrivateIp(REGION, "subnet-a").orElseThrow()); + assertEquals("10.0.2.10", manager.allocatePrivateIp(REGION, "subnet-b").orElseThrow()); + } + + @Test + void declaringAnotherVpcDoesNotWaitForBlockedDockerPlanning() throws Exception { + manager.declareVpc(REGION, "vpc-planning", "10.0.0.0/16"); + CountDownLatch entered = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + when(docker.listNetworksCmd().exec()).thenAnswer(invocation -> { + entered.countDown(); + assertTrue(release.await(5, TimeUnit.SECONDS)); + return List.of(); + }); + try (ExecutorService executor = Executors.newFixedThreadPool(2)) { + Future> planning = executor.submit(() -> + manager.effectiveVpcCidr(REGION, "vpc-planning")); + try { + assertTrue(entered.await(2, TimeUnit.SECONDS)); + Future declaration = executor.submit(() -> + manager.declareVpc(REGION, "vpc-new", "10.1.0.0/16")); + declaration.get(1, TimeUnit.SECONDS); + } finally { + release.countDown(); + } + assertEquals("10.0.0.0/16", planning.get(2, TimeUnit.SECONDS).orElseThrow()); + } + } + + @Test + void declaringASubnetDoesNotWaitForDockerMaterialization() throws Exception { + manager.declareVpc(REGION, "vpc-1", "10.0.0.0/16"); + manager.declareSubnet(REGION, "vpc-1", "subnet-a", "10.0.1.0/24"); + String address = manager.allocatePrivateIp(REGION, "subnet-a").orElseThrow(); + CountDownLatch entered = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + InspectNetworkCmd inspect = mock(InspectNetworkCmd.class, RETURNS_SELF); + when(docker.inspectNetworkCmd()).thenReturn(inspect); + when(inspect.exec()).thenAnswer(invocation -> { + entered.countDown(); + assertTrue(release.await(5, TimeUnit.SECONDS)); + throw new NotFoundException("network not created yet"); + }); + + try (ExecutorService executor = Executors.newFixedThreadPool(2)) { + Future> attaching = executor.submit(() -> + manager.attach(REGION, "vpc-1", "subnet-a", "container-1", address)); + try { + assertTrue(entered.await(2, TimeUnit.SECONDS)); + Future declaration = executor.submit(() -> + manager.declareSubnet(REGION, "vpc-1", "subnet-b", "10.0.2.0/24")); + declaration.get(1, TimeUnit.SECONDS); + } finally { + release.countDown(); + } + assertTrue(attaching.get(2, TimeUnit.SECONDS).isPresent()); + } + assertEquals("10.0.2.10", manager.allocatePrivateIp(REGION, "subnet-b").orElseThrow()); + } + private void existingNetwork(String name, String subnet, Map labels, Map containers) { Network network = mock(Network.class);