From f59990e2703909c99042af6a09e6cf70585e4fe1 Mon Sep 17 00:00:00 2001 From: Priamo Germosen <6233424+pgermosen@users.noreply.github.com> Date: Sun, 15 Nov 2026 13:47:59 -0400 Subject: [PATCH] fix(mwaa): put an environment's Airflow container on its VPC's network (#8470) An environment's NetworkConfiguration names the subnets Amazon MWAA runs its workers in, but the Airflow container stayed on Floci's own network, so a DAG could not reach an EC2 instance, or anything else in the VPC, at the private address EC2 reports. Before the container starts, it now joins its VPC's Docker network at an address leased from the first subnet, as EC2 instances and VPC-configured Lambda functions do, and keeps the network it was created on, where its metadata database is. The address goes back once the container is removed, on delete or after a failed start. A subnet EC2 does not know, or VPC networks switched off, leaves it as before. --- docs/services/mwaa.md | 4 + .../services/mwaa/MwaaEnvironmentManager.java | 144 +++++++++++++- .../floci/aws/services/mwaa/MwaaService.java | 49 ++++- .../mwaa/MwaaEnvironmentManagerTest.java | 180 +++++++++++++++++- .../aws/services/mwaa/MwaaServiceTest.java | 26 +++ 5 files changed, 398 insertions(+), 5 deletions(-) diff --git a/docs/services/mwaa.md b/docs/services/mwaa.md index 6e114df37a..1d96b7a94b 100644 --- a/docs/services/mwaa.md +++ b/docs/services/mwaa.md @@ -62,6 +62,10 @@ If configured, the script is fetched from S3 at environment-creation time and in The Airflow container is pointed back at Floci itself (`AWS_ENDPOINT_URL`, placeholder credentials, region) using the same mechanism Lambda and ECS containers already use to reach the emulator — so a DAG's own `boto3.client("s3")`/`boto3.client("secretsmanager")` calls resolve against Floci instead of attempting to reach real AWS. +### VPC (`NetworkConfiguration`) + +Amazon MWAA runs an environment's workers in the subnets its `NetworkConfiguration` names. Floci puts the Airflow container on that VPC's Docker network, at an address leased from the first subnet, the way it places EC2 instances and VPC-configured Lambda functions, so a DAG reaches an EC2 instance, or anything else in the VPC, by its private IP. The container keeps the network it was created on, where its metadata database is. A subnet EC2 does not know, or `FLOCI_SERVICES_EC2_VPC_NETWORKS_ENABLED=false`, leaves it there alone. Security groups are not enforced, as for EC2. As on AWS, `DeleteSubnet` refuses a subnet an environment uses (`DependencyViolation`), and `UpdateEnvironment` changes only the security groups: an environment's subnets, and so its VPC, are fixed at creation. + !!! note "Docker socket required" Real mode starts privileged Docker containers. Mount the Docker socket and set the Docker network so containers can reach each other. diff --git a/src/main/java/io/floci/aws/services/mwaa/MwaaEnvironmentManager.java b/src/main/java/io/floci/aws/services/mwaa/MwaaEnvironmentManager.java index f7f5dfa4d5..d3fc8af147 100644 --- a/src/main/java/io/floci/aws/services/mwaa/MwaaEnvironmentManager.java +++ b/src/main/java/io/floci/aws/services/mwaa/MwaaEnvironmentManager.java @@ -6,6 +6,7 @@ import com.github.dockerjava.api.model.ContainerNetwork; import io.floci.aws.config.EmulatorConfig; import io.floci.aws.core.common.AwsArnUtils; import io.floci.aws.core.common.Base64Url; +import io.floci.aws.core.common.RequestScopes; import io.floci.aws.core.common.docker.ContainerBuilder; import io.floci.aws.core.common.docker.ContainerDetector; import io.floci.aws.core.common.docker.ContainerExec; @@ -15,7 +16,11 @@ import io.floci.aws.core.common.docker.ContainerSpec; import io.floci.aws.core.common.docker.ContainerStorageHelper; import io.floci.aws.core.common.docker.LaunchedContainerAwsEnv; import io.floci.aws.core.common.docker.RetryingTarCopier; +import io.floci.aws.services.ec2.Ec2Service; +import io.floci.aws.services.ec2.model.Subnet; +import io.floci.aws.services.ec2.net.Cidr4; import io.floci.aws.services.mwaa.model.Environment; +import io.floci.aws.services.mwaa.model.NetworkConfiguration; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import org.jboss.logging.Logger; @@ -29,11 +34,13 @@ import java.nio.charset.StandardCharsets; import java.security.SecureRandom; import java.util.ArrayList; import java.util.Base64; +import java.util.Collection; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Optional; import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; @@ -91,18 +98,23 @@ public class MwaaEnvironmentManager { private final ContainerDetector containerDetector; private final EmulatorConfig config; private final LaunchedContainerAwsEnv awsEnv; + private final Ec2Service ec2Service; + /** The VPC address each Airflow container holds, by container id, returned once the container is gone. */ + private final Map vpcLeases = new ConcurrentHashMap<>(); @Inject public MwaaEnvironmentManager(ContainerBuilder containerBuilder, ContainerLifecycleManager lifecycleManager, ContainerDetector containerDetector, EmulatorConfig config, - LaunchedContainerAwsEnv awsEnv) { + LaunchedContainerAwsEnv awsEnv, + Ec2Service ec2Service) { this.containerBuilder = containerBuilder; this.lifecycleManager = lifecycleManager; this.containerDetector = containerDetector; this.config = config; this.awsEnv = awsEnv; + this.ec2Service = ec2Service; } /** @@ -220,6 +232,7 @@ public class MwaaEnvironmentManager { String containerId = lifecycleManager.create(spec); ContainerInfo info; try { + joinVpcNetwork(environment, containerId); // Real MWAA documents startup scripts using "sudo yum install ..." as the baseline way // to install OS packages — sudo is assumed to just work for the airflow user. The stock // apache/airflow image ships sudo but requires a password, so without this grant every @@ -252,6 +265,7 @@ public class MwaaEnvironmentManager { info = lifecycleManager.startCreated(containerId, spec); } catch (Exception e) { lifecycleManager.removeIfExists(containerId); + releaseVpcLeaseIfGone(containerId); throw e; } environment.setAirflowContainerId(info.containerId()); @@ -365,6 +379,7 @@ public class MwaaEnvironmentManager { String name = environment.getName(); if (environment.getAirflowContainerId() != null) { lifecycleManager.stopAndRemove(environment.getAirflowContainerId(), null); + releaseVpcLeaseIfGone(environment.getAirflowContainerId()); } if (environment.getDbContainerId() != null) { lifecycleManager.stopAndRemove(environment.getDbContainerId(), null); @@ -376,6 +391,133 @@ public class MwaaEnvironmentManager { LOG.infov("Stopped MWAA containers for environment {0}", name); } + /** + * Puts the Airflow container on the VPC network of the environment's {@code NetworkConfiguration}, at an + * address leased from its first subnet, before the container starts: Amazon MWAA runs the environment's + * workers in those subnets, so its DAGs reach what the VPC holds (an EC2 instance, a database) by private + * address. The container keeps the network it was created on, which holds its metadata database. Without + * Docker-backed VPC networks, or for subnets EC2 does not know, it stays there alone. The subnet is checked and + * the lease recorded while EC2 holds its subnet references, so a DeleteSubnet cannot pass its dependency check + * between the two ({@link #holdsSubnet}). + */ + void joinVpcNetwork(Environment environment, String containerId) { + String subnetId = firstSubnet(environment); + if (ec2Service == null || subnetId == null) { + return; + } + String accountId = environmentAccount(environment); + String region = regionOf(environment); + // Provisioning can run outside the CreateEnvironment request, so the environment's account is named. + RequestScopes.runAs(accountId, region, () -> ec2Service.runWithSubnetReferencesHeld(region, () -> { + String vpcId = vpcOf(region, subnetId); + if (vpcId == null) { + return; + } + Optional address = ec2Service.allocateVpcPrivateIp(region, subnetId); + if (address.isEmpty()) { + return; + } + if (ec2Service.attachContainerToVpc(region, vpcId, subnetId, containerId, address.get()).isPresent()) { + vpcLeases.put(containerId, new VpcLease(accountId, region, vpcId, subnetId, address.get())); + LOG.infov("MWAA environment {0} joined VPC {1} at {2}", environment.getName(), vpcId, + address.get()); + } else { + ec2Service.releaseVpcPrivateIp(region, subnetId, address.get()); + } + })); + } + + /** + * Re-claims the VPC address an environment's Airflow container still holds after Floci restarts, when it was + * kept running ({@code keep-running-on-shutdown}): the address leases are in memory, so without this EC2 could + * hand the same address to an instance and Docker would refuse it. The container is found by its name. + */ + void reclaimVpcAddress(Environment environment) { + String subnetId = firstSubnet(environment); + if (ec2Service == null || subnetId == null) { + return; + } + String containerId; + Collection networks; + try { + InspectContainerResponse inspect = lifecycleManager.getDockerClient() + .inspectContainerCmd(airflowContainerName(config, environment)).exec(); + containerId = inspect.getId(); + networks = inspect.getNetworkSettings() == null || inspect.getNetworkSettings().getNetworks() == null + ? List.of() : inspect.getNetworkSettings().getNetworks().values(); + } catch (NotFoundException expected) { + // The container did not outlive the restart, so there is no address to re-claim. + return; + } + String accountId = environmentAccount(environment); + String region = regionOf(environment); + RequestScopes.runAs(accountId, region, () -> { + List subnets = ec2Service.describeSubnets(region, List.of(subnetId), Map.of()); + Optional cidr = subnets.size() == 1 ? Cidr4.parse(subnets.getFirst().getCidrBlock()) + : Optional.empty(); + if (cidr.isEmpty()) { + return; + } + for (ContainerNetwork network : networks) { + Optional address = Cidr4.parse(network.getIpAddress() + "/32"); + if (address.isPresent() && cidr.get().containsAddress(address.get().network()) + && ec2Service.reserveVpcPrivateIp(region, subnetId, network.getIpAddress())) { + vpcLeases.put(containerId, new VpcLease(accountId, region, subnets.getFirst().getVpcId(), + subnetId, network.getIpAddress())); + LOG.infov("MWAA environment {0} re-claimed its VPC address {1}", environment.getName(), + network.getIpAddress()); + return; + } + } + }); + } + + /** Whether a live Airflow container of the account holds an address in the subnet. */ + boolean holdsSubnet(String accountId, String region, String subnetId) { + return vpcLeases.values().stream().anyMatch(lease -> lease.accountId().equals(accountId) + && lease.region().equals(region) && lease.subnetId().equals(subnetId)); + } + + /** Whether a live Airflow container of the account is on the VPC's network. */ + boolean holdsVpc(String accountId, String region, String vpcId) { + return vpcLeases.values().stream().anyMatch(lease -> lease.accountId().equals(accountId) + && lease.region().equals(region) && lease.vpcId().equals(vpcId)); + } + + private static String firstSubnet(Environment environment) { + NetworkConfiguration network = environment.getNetworkConfiguration(); + List subnetIds = network == null ? null : network.getSubnetIds(); + return subnetIds == null || subnetIds.isEmpty() ? null : subnetIds.getFirst(); + } + + private String vpcOf(String region, String subnetId) { + List subnets = ec2Service.describeSubnets(region, List.of(subnetId), Map.of()); + return subnets.size() == 1 ? subnets.getFirst().getVpcId() : null; + } + + /** + * Gives the container's VPC address back once Docker no longer has the container. A removal that failed (it + * logs and carries on) leaves the address held, so the lease is kept rather than offered to someone else. + */ + private void releaseVpcLeaseIfGone(String containerId) { + VpcLease lease = vpcLeases.get(containerId); + if (lease == null) { + return; + } + try { + lifecycleManager.getDockerClient().inspectContainerCmd(containerId).exec(); + LOG.warnv("MWAA container {0} is still present after removal; it keeps VPC address {1}", containerId, + lease.address()); + } catch (NotFoundException expected) { + // Gone, so its address is free. + vpcLeases.remove(containerId); + ec2Service.releaseVpcPrivateIp(lease.region(), lease.subnetId(), lease.address()); + } + } + + private record VpcLease(String accountId, String region, String vpcId, String subnetId, String address) { + } + /** Writes {@code content} to {@code DAGS_MOUNT/relativePath} inside the Airflow container. */ public void copyDagFile(Environment environment, String relativePath, byte[] content) { copyFileIntoContainer(environment.getAirflowContainerId(), DAGS_MOUNT, relativePath, content); diff --git a/src/main/java/io/floci/aws/services/mwaa/MwaaService.java b/src/main/java/io/floci/aws/services/mwaa/MwaaService.java index 726e12f424..617247a6a7 100644 --- a/src/main/java/io/floci/aws/services/mwaa/MwaaService.java +++ b/src/main/java/io/floci/aws/services/mwaa/MwaaService.java @@ -11,9 +11,11 @@ import io.floci.aws.core.common.docker.PortAllocator; import io.floci.aws.core.storage.AccountAwareStorageBackend; import io.floci.aws.core.storage.StorageBackend; import io.floci.aws.core.storage.StorageFactory; +import io.floci.aws.services.ec2.VpcDependencyProvider; import io.floci.aws.services.mwaa.model.CreateEnvironmentRequest; import io.floci.aws.services.mwaa.model.Environment; import io.floci.aws.services.mwaa.model.EnvironmentStatus; +import io.floci.aws.services.mwaa.model.NetworkConfiguration; import io.floci.aws.services.mwaa.model.UpdateEnvironmentRequest; import io.floci.aws.services.mwaa.proxy.MwaaProxyManager; import io.floci.aws.services.mwaa.proxy.MwaaWebProxy; @@ -45,7 +47,7 @@ import java.util.regex.Pattern; import java.util.stream.Collectors; @ApplicationScoped -public class MwaaService implements TagHandler { +public class MwaaService implements TagHandler, VpcDependencyProvider { private static final Logger LOG = Logger.getLogger(MwaaService.class); @@ -133,9 +135,46 @@ public class MwaaService implements TagHandler { if (!config.services().mwaa().mock()) { startReadinessPoller(); startDagSyncPoller(); + for (Environment environment : allEnvironments()) { + environmentManager.reclaimVpcAddress(environment); + } } } + /** + * Amazon MWAA keeps network interfaces in each subnet an environment names, so DeleteSubnet refuses one an + * environment still uses, as it does here. A plain read of the caller's environments and of the addresses live + * Airflow containers hold, which takes no lock of this service. + */ + @Override + public boolean hasSubnetDependency(String region, String subnetId) { + String accountId = regionResolver.getAccountId(); + return holdsLiveAddresses() && environmentManager.holdsSubnet(accountId, region, subnetId) + || environmentsOf(accountId, region).stream() + .filter(environment -> environment.getStatus() != EnvironmentStatus.DELETED) + .map(Environment::getNetworkConfiguration) + .anyMatch(network -> network != null && network.getSubnetIds() != null + && network.getSubnetIds().contains(subnetId)); + } + + /** A VPC is only deleted once its subnets are, which {@link #hasSubnetDependency} guards; this adds live leases. */ + @Override + public boolean hasVpcDependency(String region, String vpcId) { + return holdsLiveAddresses() && environmentManager.holdsVpc(regionResolver.getAccountId(), region, vpcId); + } + + /** Mock mode runs no containers, so no Airflow container holds a VPC address there. */ + private boolean holdsLiveAddresses() { + return !config.services().mwaa().mock(); + } + + private List environmentsOf(String accountId, String region) { + List environments = storage instanceof AccountAwareStorageBackend aware + ? aware.scanForAccount(accountId, k -> true) + : storage.scan(k -> true); + return environments.stream().filter(environment -> region.equals(environmentRegion(environment))).toList(); + } + @PreDestroy public void shutdown() { readinessPoller.shutdownNow(); @@ -338,7 +377,13 @@ public class MwaaService implements TagHandler { environment.setPluginsS3Path(request.getPluginsS3Path()); } if (request.getNetworkConfiguration() != null) { - environment.setNetworkConfiguration(request.getNetworkConfiguration()); + // UpdateEnvironment's NetworkConfiguration holds only SecurityGroupIds: an environment's subnets, and so + // its VPC, are fixed at creation, as Amazon MWAA has them. + NetworkConfiguration network = new NetworkConfiguration(); + network.setSubnetIds(environment.getNetworkConfiguration() != null + ? environment.getNetworkConfiguration().getSubnetIds() : null); + network.setSecurityGroupIds(request.getNetworkConfiguration().getSecurityGroupIds()); + environment.setNetworkConfiguration(network); } if (request.getLoggingConfiguration() != null) { environment.setLoggingConfiguration(request.getLoggingConfiguration()); diff --git a/src/test/java/io/floci/aws/services/mwaa/MwaaEnvironmentManagerTest.java b/src/test/java/io/floci/aws/services/mwaa/MwaaEnvironmentManagerTest.java index cec2efcb53..ec35971678 100644 --- a/src/test/java/io/floci/aws/services/mwaa/MwaaEnvironmentManagerTest.java +++ b/src/test/java/io/floci/aws/services/mwaa/MwaaEnvironmentManagerTest.java @@ -2,8 +2,12 @@ package io.floci.aws.services.mwaa; import com.github.dockerjava.api.DockerClient; import com.github.dockerjava.api.command.CopyArchiveToContainerCmd; +import com.github.dockerjava.api.command.InspectContainerCmd; +import com.github.dockerjava.api.command.InspectContainerResponse; import com.github.dockerjava.api.exception.NotFoundException; +import com.github.dockerjava.api.model.ContainerNetwork; import com.github.dockerjava.api.model.Mount; +import com.github.dockerjava.api.model.NetworkSettings; import io.floci.aws.config.EmulatorConfig; import io.floci.aws.core.common.dns.EmbeddedDnsServer; import io.floci.aws.core.common.docker.ContainerBuilder; @@ -16,11 +20,15 @@ import io.floci.aws.core.common.docker.ContainerLifecycleManager.EndpointInfo; import io.floci.aws.core.common.docker.ContainerSpec; import io.floci.aws.core.common.docker.DockerHostResolver; import io.floci.aws.core.common.docker.LaunchedContainerAwsEnv; +import io.floci.aws.services.ec2.Ec2Service; +import io.floci.aws.services.ec2.model.Subnet; import io.floci.aws.services.mwaa.model.Environment; +import io.floci.aws.services.mwaa.model.NetworkConfiguration; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; +import org.mockito.InOrder; import org.mockito.Mockito; import java.nio.charset.StandardCharsets; @@ -49,6 +57,8 @@ class MwaaEnvironmentManagerTest { private ContainerDetector containerDetector; private MwaaEnvironmentManager manager; private EmulatorConfig.MwaaServiceConfig mwaaConfig; + private Ec2Service ec2Service; + private EmulatorConfig config; @BeforeEach void setUp() { @@ -65,7 +75,7 @@ class MwaaEnvironmentManagerTest { when(servicesConfig.mwaa()).thenReturn(mwaaConfig); when(servicesConfig.dockerNetwork()).thenReturn(Optional.empty()); - EmulatorConfig config = Mockito.mock(EmulatorConfig.class); + config = Mockito.mock(EmulatorConfig.class); when(config.docker()).thenReturn(dockerConfig); when(config.services()).thenReturn(servicesConfig); when(config.defaultRegion()).thenReturn("us-east-1"); @@ -90,8 +100,174 @@ class MwaaEnvironmentManagerTest { "AWS_SECRET_ACCESS_KEY=test", "AWS_ENDPOINT_URL=http://localhost:4566")); + ec2Service = Mockito.mock(Ec2Service.class); + Mockito.doAnswer(invocation -> { + invocation.getArgument(1, Runnable.class).run(); + return null; + }).when(ec2Service).runWithSubnetReferencesHeld(any(), any()); manager = new MwaaEnvironmentManager(containerBuilder, lifecycleManager, containerDetector, config, - awsEnv); + awsEnv, ec2Service); + } + + /** Docker answers an inspect of the container: present, or gone once it has been removed. */ + private InspectContainerCmd dockerInspecting(String container, boolean present) { + DockerClient dockerClient = lifecycleManager.getDockerClient() != null ? lifecycleManager.getDockerClient() + : Mockito.mock(DockerClient.class); + when(lifecycleManager.getDockerClient()).thenReturn(dockerClient); + InspectContainerCmd inspect = Mockito.mock(InspectContainerCmd.class); + when(dockerClient.inspectContainerCmd(container)).thenReturn(inspect); + if (present) { + when(inspect.exec()).thenReturn(Mockito.mock(InspectContainerResponse.class)); + } else { + when(inspect.exec()).thenThrow(new NotFoundException("No such container: " + container)); + } + return inspect; + } + + private Environment environmentInSubnets(String... subnetIds) { + NetworkConfiguration network = new NetworkConfiguration(); + network.setSubnetIds(List.of(subnetIds)); + network.setSecurityGroupIds(List.of("sg-1")); + Environment environment = new Environment(); + environment.setName("vpc-env"); + environment.setAccountId("000000000000"); + environment.setNetworkConfiguration(network); + return environment; + } + + private void subnetInVpc(String subnetId, String vpcId) { + Subnet subnet = new Subnet(); + subnet.setSubnetId(subnetId); + subnet.setVpcId(vpcId); + subnet.setCidrBlock("172.31.0.0/20"); + when(ec2Service.describeSubnets("us-east-1", List.of(subnetId), Map.of())).thenReturn(List.of(subnet)); + } + + private void airflowContainerStarts() { + when(containerDetector.isRunningInContainer()).thenReturn(false); + when(lifecycleManager.create(any())).thenReturn("airflow-container-id"); + when(lifecycleManager.startCreated(eq("airflow-container-id"), any())).thenReturn(new ContainerInfo( + "airflow-container-id", Map.of(8080, new EndpointInfo("172.18.0.5", 8080)))); + } + + @Test + void anEnvironmentInAVpcJoinsItsNetworkBeforeAirflowStartsAndGivesTheAddressBackOnDelete() { + airflowContainerStarts(); + subnetInVpc("subnet-a", "vpc-1"); + when(ec2Service.allocateVpcPrivateIp("us-east-1", "subnet-a")).thenReturn(Optional.of("172.31.0.20")); + when(ec2Service.attachContainerToVpc("us-east-1", "vpc-1", "subnet-a", "airflow-container-id", "172.31.0.20")) + .thenReturn(Optional.of("floci-vpc-1")); + Environment environment = environmentInSubnets("subnet-a", "subnet-b"); + + manager.startAirflowContainer(environment, "2.10.5", "172.18.0.9", "db-secret-pw", null, null); + verify(ec2Service, never()).releaseVpcPrivateIp(any(), any(), any()); + assertTrue(manager.holdsSubnet("000000000000", "us-east-1", "subnet-a")); + assertTrue(manager.holdsVpc("000000000000", "us-east-1", "vpc-1")); + assertFalse(manager.holdsSubnet("111111111111", "us-east-1", "subnet-a")); + dockerInspecting("airflow-container-id", false); + manager.stopEnvironment(environment); + assertFalse(manager.holdsSubnet("000000000000", "us-east-1", "subnet-a")); + + InOrder order = Mockito.inOrder(lifecycleManager, ec2Service); + order.verify(lifecycleManager).create(any()); + order.verify(ec2Service).attachContainerToVpc("us-east-1", "vpc-1", "subnet-a", "airflow-container-id", + "172.31.0.20"); + order.verify(lifecycleManager).startCreated(eq("airflow-container-id"), any()); + order.verify(lifecycleManager).stopAndRemove("airflow-container-id", null); + order.verify(ec2Service).releaseVpcPrivateIp("us-east-1", "subnet-a", "172.31.0.20"); + } + + @Test + void anAddressTheVpcNetworkRefusesIsGivenBackAndAirflowStillStarts() { + airflowContainerStarts(); + subnetInVpc("subnet-a", "vpc-1"); + when(ec2Service.allocateVpcPrivateIp("us-east-1", "subnet-a")).thenReturn(Optional.of("172.31.0.21")); + when(ec2Service.attachContainerToVpc("us-east-1", "vpc-1", "subnet-a", "airflow-container-id", "172.31.0.21")) + .thenReturn(Optional.empty()); + + manager.startAirflowContainer(environmentInSubnets("subnet-a"), "2.10.5", "172.18.0.9", "db-secret-pw", + null, null); + + verify(ec2Service).releaseVpcPrivateIp("us-east-1", "subnet-a", "172.31.0.21"); + verify(lifecycleManager).startCreated(eq("airflow-container-id"), any()); + } + + @Test + void aFailedStartGivesTheVpcAddressBackAfterRemovingTheContainer() { + airflowContainerStarts(); + subnetInVpc("subnet-a", "vpc-1"); + when(ec2Service.allocateVpcPrivateIp("us-east-1", "subnet-a")).thenReturn(Optional.of("172.31.0.22")); + when(ec2Service.attachContainerToVpc("us-east-1", "vpc-1", "subnet-a", "airflow-container-id", "172.31.0.22")) + .thenReturn(Optional.of("floci-vpc-1")); + when(lifecycleManager.startCreated(eq("airflow-container-id"), any())) + .thenThrow(new RuntimeException("start failed")); + dockerInspecting("airflow-container-id", false); + + assertThrows(RuntimeException.class, () -> manager.startAirflowContainer(environmentInSubnets("subnet-a"), + "2.10.5", "172.18.0.9", "db-secret-pw", null, null)); + + InOrder order = Mockito.inOrder(lifecycleManager, ec2Service); + order.verify(lifecycleManager).removeIfExists("airflow-container-id"); + order.verify(ec2Service).releaseVpcPrivateIp("us-east-1", "subnet-a", "172.31.0.22"); + } + + @Test + void aContainerDockerFailedToRemoveKeepsItsVpcAddress() { + airflowContainerStarts(); + subnetInVpc("subnet-a", "vpc-1"); + when(ec2Service.allocateVpcPrivateIp("us-east-1", "subnet-a")).thenReturn(Optional.of("172.31.0.24")); + when(ec2Service.attachContainerToVpc("us-east-1", "vpc-1", "subnet-a", "airflow-container-id", "172.31.0.24")) + .thenReturn(Optional.of("floci-vpc-1")); + Environment environment = environmentInSubnets("subnet-a"); + manager.startAirflowContainer(environment, "2.10.5", "172.18.0.9", "db-secret-pw", null, null); + dockerInspecting("airflow-container-id", true); + + manager.stopEnvironment(environment); + + verify(ec2Service, never()).releaseVpcPrivateIp(any(), any(), any()); + assertTrue(manager.holdsSubnet("000000000000", "us-east-1", "subnet-a")); + } + + @Test + void aContainerKeptAcrossARestartReclaimsItsVpcAddress() { + subnetInVpc("subnet-a", "vpc-1"); + Environment environment = environmentInSubnets("subnet-a"); + environment.setArn("arn:aws:airflow:us-east-1:000000000000:environment/vpc-env"); + DockerClient dockerClient = Mockito.mock(DockerClient.class); + when(lifecycleManager.getDockerClient()).thenReturn(dockerClient); + InspectContainerCmd inspect = Mockito.mock(InspectContainerCmd.class); + InspectContainerResponse response = Mockito.mock(InspectContainerResponse.class); + NetworkSettings settings = Mockito.mock(NetworkSettings.class); + when(dockerClient.inspectContainerCmd(MwaaEnvironmentManager.airflowContainerName(config, environment))) + .thenReturn(inspect); + when(inspect.exec()).thenReturn(response); + when(response.getId()).thenReturn("kept-container-id"); + when(response.getNetworkSettings()).thenReturn(settings); + when(settings.getNetworks()).thenReturn(Map.of( + "floci-mwaa", new ContainerNetwork().withIpv4Address("172.18.0.5"), + "floci-vpc-1", new ContainerNetwork().withIpv4Address("172.31.0.30"))); + when(ec2Service.reserveVpcPrivateIp("us-east-1", "subnet-a", "172.31.0.30")).thenReturn(true); + + manager.reclaimVpcAddress(environment); + + verify(ec2Service).reserveVpcPrivateIp("us-east-1", "subnet-a", "172.31.0.30"); + verify(ec2Service, never()).reserveVpcPrivateIp("us-east-1", "subnet-a", "172.18.0.5"); + assertTrue(manager.holdsSubnet("000000000000", "us-east-1", "subnet-a")); + } + + @Test + void anEnvironmentOutsideAnyVpcEc2KnowsStaysOnItsOwnNetwork() { + airflowContainerStarts(); + when(ec2Service.describeSubnets("us-east-1", List.of("subnet-unknown"), Map.of())).thenReturn(List.of()); + + manager.startAirflowContainer(environmentInSubnets("subnet-unknown"), "2.10.5", "172.18.0.9", + "db-secret-pw", null, null); + Environment withoutNetwork = new Environment(); + withoutNetwork.setName("no-vpc-env"); + manager.startAirflowContainer(withoutNetwork, "2.10.5", "172.18.0.9", "db-secret-pw", null, null); + + verify(ec2Service, never()).allocateVpcPrivateIp(any(), any()); + verify(ec2Service, never()).attachContainerToVpc(any(), any(), any(), any(), any()); } @SuppressWarnings("unchecked") diff --git a/src/test/java/io/floci/aws/services/mwaa/MwaaServiceTest.java b/src/test/java/io/floci/aws/services/mwaa/MwaaServiceTest.java index 69dd96e0c4..316dd86a1b 100644 --- a/src/test/java/io/floci/aws/services/mwaa/MwaaServiceTest.java +++ b/src/test/java/io/floci/aws/services/mwaa/MwaaServiceTest.java @@ -272,6 +272,32 @@ class MwaaServiceTest { return request; } + @Test + void anUpdateChangesAnEnvironmentsSecurityGroupsButNotItsSubnets() { + mwaaService.createEnvironment("network-env", createRequest("arn:aws:s3:::my-bucket", "dags")); + NetworkConfiguration requested = new NetworkConfiguration(); + requested.setSubnetIds(List.of("subnet-9")); + requested.setSecurityGroupIds(List.of("sg-2")); + UpdateEnvironmentRequest request = new UpdateEnvironmentRequest(); + request.setNetworkConfiguration(requested); + + Environment updated = mwaaService.updateEnvironment("network-env", request); + + assertEquals(List.of("subnet-1", "subnet-2"), updated.getNetworkConfiguration().getSubnetIds()); + assertEquals(List.of("sg-2"), updated.getNetworkConfiguration().getSecurityGroupIds()); + } + + @Test + void aSubnetAnEnvironmentUsesCannotBeDeletedUntilTheEnvironmentIsGone() { + mwaaService.createEnvironment("subnet-env", createRequest("arn:aws:s3:::my-bucket", "dags")); + + assertTrue(mwaaService.hasSubnetDependency("us-east-1", "subnet-2")); + assertFalse(mwaaService.hasSubnetDependency("us-east-1", "subnet-3")); + assertFalse(mwaaService.hasSubnetDependency("eu-west-1", "subnet-2")); + mwaaService.deleteEnvironment("subnet-env"); + assertFalse(mwaaService.hasSubnetDependency("us-east-1", "subnet-2")); + } + @Test void createEnvironment() { Environment environment = mwaaService.createEnvironment("test-env",