mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(codebuild): put a VPC project's build container on its VPC's network (#8491)
This commit is contained in:
1 parent
1fea61f88b
commit
58c267e621
10 files changed
+488
-95
No files matched your search
@@ -72,6 +72,10 @@ Each `StartBuild` call:
|
||||
|
||||
Source injection and artifact extraction both use the Docker API's archive copy endpoints — no bind mounts are required. This works correctly when Floci itself runs inside a Docker container (Docker-in-Docker).
|
||||
|
||||
### VPC (`vpcConfig`)
|
||||
|
||||
CodeBuild runs a build of a project with a `vpcConfig` with a network interface in one of the project's subnets. Floci puts the build container on that VPC's Docker network, at an address leased from the first subnet, before the first phase runs, the way it places EC2 instances, VPC-configured Lambda functions and MWAA environments, so a build reaches a database or anything else in the VPC by its private IP. The container keeps the network it was created on as well. 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. While a build runs, `DeleteSubnet` refuses its subnet and `DeleteVpc` its VPC (`DependencyViolation`), as the build's network interface does on AWS; a project's `vpcConfig` alone holds none. `BatchGetBuilds` returns the project's `vpcConfig` on each build.
|
||||
|
||||
## Buildspec Support
|
||||
|
||||
Floci parses the `buildspec.yml` embedded in the project or provided via `buildspecOverride`. Supported fields:
|
||||
|
||||
@@ -16,6 +16,7 @@ import io.floci.aws.core.common.docker.ContainerDetector;
|
||||
import io.floci.aws.core.common.docker.ContainerLifecycleManager;
|
||||
import io.floci.aws.core.common.docker.ContainerLogStreamer;
|
||||
import io.floci.aws.core.common.docker.ContainerReachableEndpoint;
|
||||
import io.floci.aws.core.common.docker.ContainerReconciler;
|
||||
import io.floci.aws.core.common.docker.ContainerSpec;
|
||||
import io.floci.aws.core.common.docker.ContainerStorageHelper;
|
||||
import io.floci.aws.core.common.docker.RetryingTarCopier;
|
||||
@@ -24,6 +25,9 @@ import io.floci.aws.services.codebuild.BuildspecParser.ParsedBuildspec;
|
||||
import io.floci.aws.services.codebuild.model.Build;
|
||||
import io.floci.aws.services.codebuild.model.BuildPhase;
|
||||
import io.floci.aws.services.codebuild.model.Project;
|
||||
import io.floci.aws.services.ec2.Ec2Service;
|
||||
import io.floci.aws.services.ec2.VpcContainerLeases;
|
||||
import io.floci.aws.services.ec2.VpcDependencyProvider;
|
||||
import io.floci.aws.services.s3.S3Service;
|
||||
import io.floci.aws.services.s3.model.S3Object;
|
||||
import io.floci.aws.services.secretsmanager.SecretsManagerService;
|
||||
@@ -53,6 +57,7 @@ import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
@@ -63,7 +68,10 @@ import java.util.zip.ZipInputStream;
|
||||
import java.util.zip.ZipOutputStream;
|
||||
|
||||
@ApplicationScoped
|
||||
public class CodeBuildRunner implements ContainerTeardown {
|
||||
public class CodeBuildRunner implements ContainerTeardown, VpcDependencyProvider {
|
||||
|
||||
/** The label naming the Floci process that created a build container, set by {@link #buildLabels}. */
|
||||
static final String RUN_LABEL = "io.floci.codebuild.run";
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(CodeBuildRunner.class);
|
||||
private static final int FAILURE_OUTPUT_CHARS = 512;
|
||||
@@ -79,6 +87,12 @@ public class CodeBuildRunner implements ContainerTeardown {
|
||||
private final ContainerDetector containerDetector;
|
||||
private final RegionResolver regionResolver;
|
||||
private final ContainerReachableEndpoint containerEndpoint;
|
||||
/** The VPC address each running build's container holds, given back once the container is gone. */
|
||||
private final VpcContainerLeases vpcLeases;
|
||||
private final ContainerReconciler containerReconciler;
|
||||
/** This process's run, labelled on its build containers, so a later run knows them for leftovers. */
|
||||
private final String runId = UUID.randomUUID().toString();
|
||||
private final AtomicBoolean leftoversRemoved = new AtomicBoolean();
|
||||
|
||||
private final ConcurrentHashMap<String, String> runningContainers = new ConcurrentHashMap<>();
|
||||
private final ConcurrentHashMap<String, AtomicBoolean> stopFlags = new ConcurrentHashMap<>();
|
||||
@@ -94,7 +108,8 @@ public class CodeBuildRunner implements ContainerTeardown {
|
||||
EmulatorConfig config,
|
||||
ContainerDetector containerDetector,
|
||||
RegionResolver regionResolver,
|
||||
ContainerReachableEndpoint containerEndpoint) {
|
||||
ContainerReachableEndpoint containerEndpoint,
|
||||
Ec2Service ec2Service) {
|
||||
this.dockerClient = dockerClient;
|
||||
this.containerBuilder = containerBuilder;
|
||||
this.lifecycleManager = lifecycleManager;
|
||||
@@ -106,6 +121,8 @@ public class CodeBuildRunner implements ContainerTeardown {
|
||||
this.containerDetector = containerDetector;
|
||||
this.regionResolver = regionResolver;
|
||||
this.containerEndpoint = containerEndpoint;
|
||||
this.vpcLeases = new VpcContainerLeases(ec2Service, "CodeBuild build", () -> dockerClient);
|
||||
this.containerReconciler = new ContainerReconciler(lifecycleManager, LOG);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -119,6 +136,7 @@ public class CodeBuildRunner implements ContainerTeardown {
|
||||
if (runningContainers.remove(entry.getKey(), entry.getValue())) {
|
||||
try {
|
||||
lifecycleManager.stopAndRemove(entry.getValue(), null);
|
||||
vpcLeases.releaseIfGone(entry.getValue());
|
||||
} catch (Exception e) {
|
||||
LOG.warnv("Failed to stop CodeBuild container for build {0} on shutdown: {1}",
|
||||
entry.getKey(), e.getMessage());
|
||||
@@ -233,13 +251,14 @@ public class CodeBuildRunner implements ContainerTeardown {
|
||||
.withHostDockerInternalOnLinux()
|
||||
.withPrivileged(privileged)
|
||||
.withLogRotation()
|
||||
.withLabels(ContainerStorageHelper.resourceIdentityLabels(
|
||||
"codebuild", buildId, regionResolver.getAccountId(), region))
|
||||
.withLabels(buildLabels(buildId, region))
|
||||
.build();
|
||||
|
||||
removeLeftoverContainers();
|
||||
ContainerLifecycleManager.ContainerInfo info = lifecycleManager.createAndStart(spec);
|
||||
containerId = info.containerId();
|
||||
runningContainers.put(executionId, containerId);
|
||||
joinVpcNetwork(region, build, containerId);
|
||||
|
||||
logHandle = logStreamer.attach(containerId, logGroup, logStream, region, "codebuild:" + buildId);
|
||||
|
||||
@@ -395,12 +414,72 @@ public class CodeBuildRunner implements ContainerTeardown {
|
||||
} else if (logHandle != null) {
|
||||
try { logHandle.close(); } catch (Exception ignored) {}
|
||||
}
|
||||
// Whoever removed the container, shutdown included, its address goes back once Docker confirms it gone.
|
||||
if (containerId != null) {
|
||||
vpcLeases.releaseIfGone(containerId);
|
||||
}
|
||||
if (workspace != null) {
|
||||
deleteDirectory(workspace);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Puts a build whose project has a {@code vpcConfig} on its VPC's Docker network, at an address leased from its
|
||||
* first subnet, before any phase runs: CodeBuild runs such a build with a network interface in one of the
|
||||
* project's subnets, so it reaches what the VPC holds (a database, a cache) by private address. The configuration
|
||||
* is the one StartBuild took from the project, so a later UpdateProject does not move a build already started.
|
||||
* The build runs outside the StartBuild request, so the account comes from its ARN.
|
||||
*/
|
||||
private void joinVpcNetwork(String region, Build build, String containerId) {
|
||||
Map<String, Object> vpcConfig = build.getVpcConfig();
|
||||
Object subnets = vpcConfig == null ? null : vpcConfig.get("subnets");
|
||||
if (subnets instanceof List<?> subnetIds && !subnetIds.isEmpty()
|
||||
&& subnetIds.getFirst() instanceof String subnetId) {
|
||||
String vpcId = vpcConfig.get("vpcId") instanceof String id ? id : null;
|
||||
vpcLeases.join(AwsArnUtils.parse(build.getArn()).accountId(), region, vpcId, subnetId, containerId,
|
||||
build.getId());
|
||||
}
|
||||
}
|
||||
|
||||
/** A build container's labels: its resource identity, and the deployment and run that created it. */
|
||||
private Map<String, String> buildLabels(String buildId, String region) {
|
||||
Map<String, String> labels = new LinkedHashMap<>(ContainerStorageHelper.resourceIdentityLabels(
|
||||
"codebuild", buildId, regionResolver.getAccountId(), region));
|
||||
labels.put(ContainerStorageHelper.OWNER_LABEL, ContainerStorageHelper.ownerIdentity(config));
|
||||
labels.put(RUN_LABEL, runId);
|
||||
return labels;
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes the build containers an earlier run of this Floci left, which a crash keeps running with no build to
|
||||
* finish, and their VPC addresses with them; build state does not outlive the process. Done before builds start
|
||||
* until one pass removes them all.
|
||||
*/
|
||||
private void removeLeftoverContainers() {
|
||||
if (!leftoversRemoved.get() && containerReconciler.reconcile(
|
||||
Map.of(ContainerStorageHelper.SERVICE_LABEL, "codebuild",
|
||||
ContainerStorageHelper.OWNER_LABEL, ContainerStorageHelper.ownerIdentity(config)),
|
||||
container -> !runId.equals(ContainerStorageHelper.CONTAINER_LABEL_ALIASES
|
||||
.labelValue(container.getLabels(), RUN_LABEL)))) {
|
||||
leftoversRemoved.set(true);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A running build's network interface is in its subnet, so DeleteSubnet refuses it until the build ends, as on
|
||||
* AWS; a project's {@code vpcConfig} alone holds no interface.
|
||||
*/
|
||||
@Override
|
||||
public boolean hasSubnetDependency(String region, String subnetId) {
|
||||
return vpcLeases.holdsSubnet(regionResolver.getAccountId(), region, subnetId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasVpcDependency(String region, String vpcId) {
|
||||
return vpcLeases.holdsVpc(regionResolver.getAccountId(), region, vpcId);
|
||||
}
|
||||
|
||||
private String resolveAndAcquireSource(String region, Build build, Project project,
|
||||
String buildspecOverride, Path workspace) throws IOException {
|
||||
String sourceType = project.getSource() != null ? project.getSource().getType() : "NO_SOURCE";
|
||||
|
||||
@@ -586,6 +586,7 @@ public class CodeBuildService {
|
||||
build.setTimeoutInMinutes(timeoutOverride != null ? timeoutOverride : project.getTimeoutInMinutes());
|
||||
build.setQueuedTimeoutInMinutes(project.getQueuedTimeoutInMinutes());
|
||||
build.setEncryptionKey(project.getEncryptionKey());
|
||||
build.setVpcConfig(project.getVpcConfig());
|
||||
|
||||
ProjectEnvironment env = environmentOverride != null ? environmentOverride : project.getEnvironment();
|
||||
if (imageOverride != null || computeTypeOverride != null) {
|
||||
@@ -775,6 +776,7 @@ public class CodeBuildService {
|
||||
copy.setTimeoutInMinutes(source.getTimeoutInMinutes());
|
||||
copy.setQueuedTimeoutInMinutes(source.getQueuedTimeoutInMinutes());
|
||||
copy.setEncryptionKey(source.getEncryptionKey());
|
||||
copy.setVpcConfig(source.getVpcConfig());
|
||||
return copy;
|
||||
}
|
||||
}
|
||||
@@ -29,6 +29,7 @@ public class Build {
|
||||
private Integer timeoutInMinutes;
|
||||
private Integer queuedTimeoutInMinutes;
|
||||
private String encryptionKey;
|
||||
private Map<String, Object> vpcConfig;
|
||||
|
||||
public String getId() { return id; }
|
||||
public void setId(String id) { this.id = id; }
|
||||
@@ -83,4 +84,7 @@ public class Build {
|
||||
|
||||
public String getEncryptionKey() { return encryptionKey; }
|
||||
public void setEncryptionKey(String encryptionKey) { this.encryptionKey = encryptionKey; }
|
||||
|
||||
public Map<String, Object> getVpcConfig() { return vpcConfig; }
|
||||
public void setVpcConfig(Map<String, Object> vpcConfig) { this.vpcConfig = vpcConfig; }
|
||||
}
|
||||
@@ -0,0 +1,203 @@
|
||||
package io.floci.aws.services.ec2;
|
||||
|
||||
import com.github.dockerjava.api.DockerClient;
|
||||
import com.github.dockerjava.api.exception.NotFoundException;
|
||||
import io.floci.aws.core.common.RequestScopes;
|
||||
import io.floci.aws.services.ec2.model.Subnet;
|
||||
import io.floci.aws.services.ec2.net.Cidr4;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
/**
|
||||
* The VPC addresses one service's containers hold on their VPC's Docker network. A container joins the network of a
|
||||
* subnet's VPC at an address EC2 leases from that subnet, the way an AWS service places a network interface in a
|
||||
* subnet it was given, so it reaches what the VPC holds by private address, and gives the address back once Docker no
|
||||
* longer has the container. The service answers its {@link VpcDependencyProvider} questions from
|
||||
* {@link #holdsSubnet} and {@link #holdsVpc}, as AWS refuses to delete a subnet or VPC a network interface is in.
|
||||
*
|
||||
* <p>Leases live in memory: a container kept running across a restart takes its address back with
|
||||
* {@link #reclaim}. A container Docker could not be shown to be gone keeps its address, and is looked at again
|
||||
* whenever the service is asked whether it holds a subnet or VPC. Without Docker-backed VPC networks, or for a subnet
|
||||
* EC2 does not know, a container keeps the network it was created on.
|
||||
*/
|
||||
public final class VpcContainerLeases {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(VpcContainerLeases.class);
|
||||
|
||||
private final Ec2Service ec2;
|
||||
private final String owner;
|
||||
private final Supplier<DockerClient> docker;
|
||||
/** The address each container holds, by container id. */
|
||||
private final Map<String, Lease> leases = new ConcurrentHashMap<>();
|
||||
/** Containers whose removal Docker did not confirm, whose addresses wait for another look. */
|
||||
private final Set<String> unconfirmed = ConcurrentHashMap.newKeySet();
|
||||
|
||||
/**
|
||||
* @param ec2 EC2, which leases the addresses; null leaves every container on its own network
|
||||
* @param owner what the containers belong to, for the log, such as {@code "CodeBuild build"}
|
||||
* @param docker the Docker client that says whether a container is gone
|
||||
*/
|
||||
public VpcContainerLeases(Ec2Service ec2, String owner, Supplier<DockerClient> docker) {
|
||||
this.ec2 = ec2;
|
||||
this.owner = owner;
|
||||
this.docker = docker;
|
||||
}
|
||||
|
||||
/** An address a container holds in a subnet of a VPC, for the account and Region that own them. */
|
||||
public record Lease(String accountId, String region, String vpcId, String subnetId, String address) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Puts the container on the VPC network of {@code subnetId}'s VPC at an address leased from the subnet. 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. Runs as the account and Region named, since a service often launches
|
||||
* outside the request that asked for it. Empty when EC2 does not know the subnet, the subnet is not in
|
||||
* {@code expectedVpcId} (when one is given), EC2 has no address to lease, or the network refuses the address,
|
||||
* which is then given back, as it is when attaching fails.
|
||||
*
|
||||
* @param expectedVpcId the VPC the resource names beside its subnets, or null when it names none
|
||||
* @param name the resource the container serves, for the log
|
||||
*/
|
||||
public Optional<Lease> join(String accountId, String region, String expectedVpcId, String subnetId,
|
||||
String containerId, String name) {
|
||||
if (ec2 == null || subnetId == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
AtomicReference<Lease> joined = new AtomicReference<>();
|
||||
RequestScopes.runAs(accountId, region, () -> ec2.runWithSubnetReferencesHeld(region, () -> {
|
||||
String vpcId = vpcOf(region, subnetId);
|
||||
if (vpcId == null) {
|
||||
return;
|
||||
}
|
||||
if (expectedVpcId != null && !expectedVpcId.equals(vpcId)) {
|
||||
LOG.warnv("{0} {1} names VPC {2}, but its subnet {3} is in {4}; it stays off both", owner, name,
|
||||
expectedVpcId, subnetId, vpcId);
|
||||
return;
|
||||
}
|
||||
Optional<String> address = ec2.allocateVpcPrivateIp(region, subnetId);
|
||||
if (address.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
Optional<String> attached;
|
||||
try {
|
||||
attached = ec2.attachContainerToVpc(region, vpcId, subnetId, containerId, address.get());
|
||||
} catch (RuntimeException e) {
|
||||
ec2.releaseVpcPrivateIp(region, subnetId, address.get());
|
||||
throw e;
|
||||
}
|
||||
if (attached.isPresent()) {
|
||||
Lease lease = new Lease(accountId, region, vpcId, subnetId, address.get());
|
||||
leases.put(containerId, lease);
|
||||
joined.set(lease);
|
||||
LOG.infov("{0} {1} joined VPC {2} at {3}", owner, name, vpcId, address.get());
|
||||
} else {
|
||||
ec2.releaseVpcPrivateIp(region, subnetId, address.get());
|
||||
}
|
||||
}));
|
||||
return Optional.ofNullable(joined.get());
|
||||
}
|
||||
|
||||
/**
|
||||
* Re-claims the address a container still holds in {@code subnetId} after Floci restarted with the container
|
||||
* kept running: leases live in memory, so without this EC2 could hand the same address to another resource and
|
||||
* Docker would refuse it. {@code addresses} are the container's addresses on its networks; the first inside the
|
||||
* subnet is taken back.
|
||||
*
|
||||
* @param name the resource the container serves, for the log
|
||||
*/
|
||||
public Optional<Lease> reclaim(String accountId, String region, String subnetId, String containerId,
|
||||
Collection<String> addresses, String name) {
|
||||
if (ec2 == null || subnetId == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
return RequestScopes.callAs(accountId, region, () -> {
|
||||
List<Subnet> subnets = ec2.describeSubnets(region, List.of(subnetId), Map.of());
|
||||
Optional<Cidr4> cidr = subnets.size() == 1 ? Cidr4.parse(subnets.getFirst().getCidrBlock())
|
||||
: Optional.empty();
|
||||
if (cidr.isEmpty()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
for (String address : addresses) {
|
||||
Optional<Cidr4> host = address == null ? Optional.empty() : Cidr4.parse(address + "/32");
|
||||
if (host.isPresent() && cidr.get().containsAddress(host.get().network())
|
||||
&& ec2.reserveVpcPrivateIp(region, subnetId, address)) {
|
||||
Lease lease = new Lease(accountId, region, subnets.getFirst().getVpcId(), subnetId, address);
|
||||
leases.put(containerId, lease);
|
||||
LOG.infov("{0} {1} re-claimed its VPC address {2}", owner, name, address);
|
||||
return Optional.of(lease);
|
||||
}
|
||||
}
|
||||
return Optional.empty();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Gives the container's address back once Docker no longer has the container. A removal that failed (it logs and
|
||||
* carries on), or a Docker that cannot answer, leaves the address possibly held, so the lease is kept rather than
|
||||
* offered to someone else, and looked at again when the service is next asked about the subnet or VPC.
|
||||
*/
|
||||
public void releaseIfGone(String containerId) {
|
||||
Lease lease = containerId == null ? null : leases.get(containerId);
|
||||
if (lease == null) {
|
||||
if (containerId != null) {
|
||||
unconfirmed.remove(containerId);
|
||||
}
|
||||
return;
|
||||
}
|
||||
try {
|
||||
docker.get().inspectContainerCmd(containerId).exec();
|
||||
unconfirmed.add(containerId);
|
||||
LOG.warnv("{0} container {1} is still present after removal; it keeps VPC address {2}", owner,
|
||||
containerId, lease.address());
|
||||
} catch (NotFoundException expected) {
|
||||
// Gone, so its address is free.
|
||||
unconfirmed.remove(containerId);
|
||||
if (leases.remove(containerId, lease)) {
|
||||
ec2.releaseVpcPrivateIp(lease.region(), lease.subnetId(), lease.address());
|
||||
}
|
||||
} catch (RuntimeException e) {
|
||||
unconfirmed.add(containerId);
|
||||
LOG.warnv("{0} container {1}: Docker could not confirm it is gone ({2}); it keeps VPC address {3}",
|
||||
owner, containerId, e.getMessage(), lease.address());
|
||||
}
|
||||
}
|
||||
|
||||
/** The address the container holds, if it joined a VPC network. */
|
||||
public Optional<Lease> lease(String containerId) {
|
||||
return Optional.ofNullable(containerId == null ? null : leases.get(containerId));
|
||||
}
|
||||
|
||||
/** Whether a live container of the account holds an address in the subnet. */
|
||||
public boolean holdsSubnet(String accountId, String region, String subnetId) {
|
||||
recheckUnconfirmed();
|
||||
return leases.values().stream().anyMatch(lease -> lease.accountId().equals(accountId)
|
||||
&& lease.region().equals(region) && lease.subnetId().equals(subnetId));
|
||||
}
|
||||
|
||||
/** Whether a live container of the account is on the VPC's network. */
|
||||
public boolean holdsVpc(String accountId, String region, String vpcId) {
|
||||
recheckUnconfirmed();
|
||||
return leases.values().stream().anyMatch(lease -> lease.accountId().equals(accountId)
|
||||
&& lease.region().equals(region) && lease.vpcId().equals(vpcId));
|
||||
}
|
||||
|
||||
/** Gives back the addresses of containers whose removal was not confirmed and that Docker no longer has. */
|
||||
private void recheckUnconfirmed() {
|
||||
for (String containerId : List.copyOf(unconfirmed)) {
|
||||
releaseIfGone(containerId);
|
||||
}
|
||||
}
|
||||
|
||||
private String vpcOf(String region, String subnetId) {
|
||||
List<Subnet> subnets = ec2.describeSubnets(region, List.of(subnetId), Map.of());
|
||||
return subnets.size() == 1 ? subnets.getFirst().getVpcId() : null;
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,6 @@ 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;
|
||||
@@ -17,8 +16,7 @@ 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.ec2.VpcContainerLeases;
|
||||
import io.floci.aws.services.mwaa.model.Environment;
|
||||
import io.floci.aws.services.mwaa.model.NetworkConfiguration;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
@@ -40,7 +38,6 @@ 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;
|
||||
|
||||
@@ -99,8 +96,8 @@ public class MwaaEnvironmentManager {
|
||||
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<String, VpcLease> vpcLeases = new ConcurrentHashMap<>();
|
||||
/** The VPC address each Airflow container holds, returned once the container is gone. */
|
||||
private final VpcContainerLeases vpcLeases;
|
||||
|
||||
@Inject
|
||||
public MwaaEnvironmentManager(ContainerBuilder containerBuilder,
|
||||
@@ -115,6 +112,8 @@ public class MwaaEnvironmentManager {
|
||||
this.config = config;
|
||||
this.awsEnv = awsEnv;
|
||||
this.ec2Service = ec2Service;
|
||||
this.vpcLeases = new VpcContainerLeases(ec2Service, "MWAA environment",
|
||||
() -> lifecycleManager.getDockerClient());
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -401,30 +400,9 @@ public class MwaaEnvironmentManager {
|
||||
* 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<String> 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());
|
||||
}
|
||||
}));
|
||||
vpcLeases.join(environmentAccount(environment), regionOf(environment), null, firstSubnet(environment),
|
||||
containerId, environment.getName());
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -449,39 +427,18 @@ public class MwaaEnvironmentManager {
|
||||
// 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<Subnet> subnets = ec2Service.describeSubnets(region, List.of(subnetId), Map.of());
|
||||
Optional<Cidr4> cidr = subnets.size() == 1 ? Cidr4.parse(subnets.getFirst().getCidrBlock())
|
||||
: Optional.empty();
|
||||
if (cidr.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
for (ContainerNetwork network : networks) {
|
||||
Optional<Cidr4> 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;
|
||||
}
|
||||
}
|
||||
});
|
||||
vpcLeases.reclaim(environmentAccount(environment), regionOf(environment), subnetId, containerId,
|
||||
networks.stream().map(ContainerNetwork::getIpAddress).toList(), environment.getName());
|
||||
}
|
||||
|
||||
/** 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));
|
||||
return vpcLeases.holdsSubnet(accountId, region, 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));
|
||||
return vpcLeases.holdsVpc(accountId, region, vpcId);
|
||||
}
|
||||
|
||||
private static String firstSubnet(Environment environment) {
|
||||
@@ -490,32 +447,9 @@ public class MwaaEnvironmentManager {
|
||||
return subnetIds == null || subnetIds.isEmpty() ? null : subnetIds.getFirst();
|
||||
}
|
||||
|
||||
private String vpcOf(String region, String subnetId) {
|
||||
List<Subnet> 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.
|
||||
*/
|
||||
/** Gives the container's VPC address back once Docker no longer has the container. */
|
||||
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) {
|
||||
vpcLeases.releaseIfGone(containerId);
|
||||
}
|
||||
|
||||
/** Writes {@code content} to {@code DAGS_MOUNT/relativePath} inside the Airflow container. */
|
||||
@@ -968,7 +902,6 @@ public class MwaaEnvironmentManager {
|
||||
.throwIfTimedOut(containerId);
|
||||
}
|
||||
|
||||
|
||||
private static String generateSecret(int bytes) {
|
||||
byte[] buf = new byte[bytes];
|
||||
new SecureRandom().nextBytes(buf);
|
||||
|
||||
+73
-4
@@ -1,6 +1,8 @@
|
||||
package io.floci.aws.services.codebuild;
|
||||
|
||||
import com.github.dockerjava.api.DockerClient;
|
||||
import com.github.dockerjava.api.exception.NotFoundException;
|
||||
import com.github.dockerjava.api.model.Container;
|
||||
import io.floci.aws.config.EmulatorConfig;
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
import io.floci.aws.core.common.docker.ContainerBuilder;
|
||||
@@ -9,11 +11,14 @@ import io.floci.aws.core.common.docker.ContainerLifecycleManager;
|
||||
import io.floci.aws.core.common.docker.ContainerLogStreamer;
|
||||
import io.floci.aws.core.common.docker.ContainerReachableEndpoint;
|
||||
import io.floci.aws.core.common.docker.ContainerSpec;
|
||||
import io.floci.aws.core.common.docker.ContainerStorageHelper;
|
||||
import io.floci.aws.services.codebuild.model.Build;
|
||||
import io.floci.aws.services.codebuild.model.BuildPhase;
|
||||
import io.floci.aws.services.codebuild.model.Project;
|
||||
import io.floci.aws.services.codebuild.model.ProjectEnvironment;
|
||||
import io.floci.aws.services.codebuild.model.ProjectSource;
|
||||
import io.floci.aws.services.ec2.Ec2Service;
|
||||
import io.floci.aws.services.ec2.model.Subnet;
|
||||
import io.floci.aws.services.s3.S3Service;
|
||||
import io.floci.aws.services.s3.model.S3Object;
|
||||
import org.junit.jupiter.api.Test;
|
||||
@@ -23,6 +28,7 @@ import java.io.Closeable;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
@@ -32,10 +38,12 @@ import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipOutputStream;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyInt;
|
||||
import static org.mockito.ArgumentMatchers.anyList;
|
||||
import static org.mockito.ArgumentMatchers.anyMap;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.ArgumentMatchers.nullable;
|
||||
@@ -45,6 +53,8 @@ import static org.mockito.Mockito.doAnswer;
|
||||
import static org.mockito.Mockito.doReturn;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.spy;
|
||||
import static org.mockito.Mockito.timeout;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class CodeBuildRunnerSourceFailureTest {
|
||||
@@ -74,8 +84,66 @@ class CodeBuildRunnerSourceFailureTest {
|
||||
assertEquals("source upload failed", sourcePhase.getContexts().getFirst().get("message"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aBuildInAVpcJoinsItsNetworkBeforeTheSourceIsCopiedAndGivesTheAddressBackOnceRemoved() throws Exception {
|
||||
Ec2Service ec2 = mock(Ec2Service.class);
|
||||
doAnswer(invocation -> {
|
||||
invocation.<Runnable>getArgument(1).run();
|
||||
return null;
|
||||
}).when(ec2).runWithSubnetReferencesHeld(eq("us-east-1"), any());
|
||||
Subnet subnet = new Subnet();
|
||||
subnet.setSubnetId("subnet-1");
|
||||
subnet.setVpcId("vpc-1");
|
||||
when(ec2.describeSubnets("us-east-1", List.of("subnet-1"), Map.of())).thenReturn(List.of(subnet));
|
||||
when(ec2.allocateVpcPrivateIp("us-east-1", "subnet-1")).thenReturn(Optional.of("10.0.1.20"));
|
||||
when(ec2.attachContainerToVpc("us-east-1", "vpc-1", "subnet-1", "container", "10.0.1.20"))
|
||||
.thenReturn(Optional.of("10.0.1.20"));
|
||||
Fixture fixture = fixture(false, ec2);
|
||||
// StartBuild copied the project's vpcConfig onto the build; the project has since been updated.
|
||||
fixture.build().setVpcConfig(Map.of("vpcId", "vpc-1", "subnets", List.of("subnet-1", "subnet-2"),
|
||||
"securityGroupIds", List.of("sg-1")));
|
||||
fixture.project().setVpcConfig(Map.of("vpcId", "vpc-9", "subnets", List.of("subnet-9")));
|
||||
AtomicBoolean heldDuringCopy = new AtomicBoolean();
|
||||
doAnswer(invocation -> {
|
||||
heldDuringCopy.set(fixture.runner().hasSubnetDependency("us-east-1", "subnet-1")
|
||||
&& fixture.runner().hasVpcDependency("us-east-1", "vpc-1"));
|
||||
throw new IllegalStateException("source upload failed");
|
||||
}).when(fixture.runner()).copySourceToContainer(eq("container"), any(), anyString());
|
||||
when(fixture.docker().inspectContainerCmd("container").exec()).thenThrow(new NotFoundException("gone"));
|
||||
|
||||
fixture.run();
|
||||
|
||||
assertTrue(heldDuringCopy.get(), "the build's address holds its subnet and VPC while it runs");
|
||||
// The address is given back right after the container is removed, on the build's thread.
|
||||
verify(ec2, timeout(5_000)).releaseVpcPrivateIp("us-east-1", "subnet-1", "10.0.1.20");
|
||||
assertFalse(fixture.runner().hasSubnetDependency("us-east-1", "subnet-1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void containersAnEarlierRunLeftAreRemovedBeforeABuildStarts() throws Exception {
|
||||
Fixture fixture = fixture(false);
|
||||
Container leftover = mock(Container.class);
|
||||
when(leftover.getId()).thenReturn("leftover");
|
||||
when(leftover.getLabels()).thenReturn(Map.of(
|
||||
ContainerStorageHelper.SERVICE_LABEL, "codebuild",
|
||||
ContainerStorageHelper.OWNER_LABEL, "0",
|
||||
CodeBuildRunner.RUN_LABEL, "an-earlier-run"));
|
||||
DockerClient docker = mock(DockerClient.class, RETURNS_DEEP_STUBS);
|
||||
when(fixture.lifecycle().getDockerClient()).thenReturn(docker);
|
||||
when(docker.listContainersCmd().withShowAll(true).withLabelFilter(anyMap()).exec())
|
||||
.thenReturn(List.of(leftover));
|
||||
|
||||
fixture.run();
|
||||
|
||||
verify(fixture.lifecycle()).removeIfExistsStrict("leftover", true);
|
||||
}
|
||||
|
||||
private Fixture fixture(boolean stopDuringCopy) throws IOException {
|
||||
DockerClient docker = mock(DockerClient.class);
|
||||
return fixture(stopDuringCopy, null);
|
||||
}
|
||||
|
||||
private Fixture fixture(boolean stopDuringCopy, Ec2Service ec2) throws IOException {
|
||||
DockerClient docker = mock(DockerClient.class, RETURNS_DEEP_STUBS);
|
||||
ContainerBuilder containerBuilder = mock(ContainerBuilder.class);
|
||||
ContainerBuilder.Builder specBuilder = mock(ContainerBuilder.Builder.class, RETURNS_SELF);
|
||||
when(containerBuilder.newContainer(anyString())).thenReturn(specBuilder);
|
||||
@@ -104,7 +172,7 @@ class CodeBuildRunnerSourceFailureTest {
|
||||
when(endpoint.port()).thenReturn(4566);
|
||||
|
||||
CodeBuildRunner runner = spy(new CodeBuildRunner(docker, containerBuilder, lifecycle, logStreamer,
|
||||
s3, null, null, config, mock(ContainerDetector.class), regionResolver, endpoint));
|
||||
s3, null, null, config, mock(ContainerDetector.class), regionResolver, endpoint, ec2));
|
||||
doReturn(CodeBuildRunner.PhaseResult.ofSuccess()).when(runner)
|
||||
.runPhase(anyString(), anyString(), anyList(), anyList(), anyInt(), any(AtomicBoolean.class));
|
||||
|
||||
@@ -128,7 +196,7 @@ class CodeBuildRunnerSourceFailureTest {
|
||||
environment.setImage("alpine:latest");
|
||||
project.setEnvironment(environment);
|
||||
|
||||
return new Fixture(runner, build, project, finished);
|
||||
return new Fixture(runner, build, project, finished, docker, lifecycle);
|
||||
}
|
||||
|
||||
private byte[] sourceArchive() throws IOException {
|
||||
@@ -141,7 +209,8 @@ class CodeBuildRunnerSourceFailureTest {
|
||||
return bytes.toByteArray();
|
||||
}
|
||||
|
||||
private record Fixture(CodeBuildRunner runner, Build build, Project project, CountDownLatch finished) {
|
||||
private record Fixture(CodeBuildRunner runner, Build build, Project project, CountDownLatch finished,
|
||||
DockerClient docker, ContainerLifecycleManager lifecycle) {
|
||||
void run() throws InterruptedException {
|
||||
runner.startBuild("us-east-1", build, project, null);
|
||||
assertTrue(finished.await(10, TimeUnit.SECONDS), "build did not finish");
|
||||
|
||||
@@ -36,7 +36,8 @@ class CodeBuildRunnerTest {
|
||||
int chunkCount = 320;
|
||||
String lastLine = "error: build step failed\n";
|
||||
DockerClient dockerClient = dockerClientStreaming(chunk, chunkCount, lastLine, 2L);
|
||||
CodeBuildRunner runner = new CodeBuildRunner(dockerClient, null, null, null, null, null, null, null, null, null, null);
|
||||
CodeBuildRunner runner = new CodeBuildRunner(dockerClient, null, null, null, null, null, null, null, null, null, null,
|
||||
null);
|
||||
|
||||
CodeBuildRunner.PhaseResult result = runner.runPhase("container-1", "/src", List.of(),
|
||||
List.of("./build.sh"), 60, new AtomicBoolean(false));
|
||||
@@ -49,7 +50,8 @@ class CodeBuildRunnerTest {
|
||||
@Test
|
||||
void failureMessageIgnoresLongTrailingWhitespace() {
|
||||
DockerClient dockerClient = dockerClientStreaming(new byte[0], 0, "tests failed" + "\n".repeat(10_000), 1L);
|
||||
CodeBuildRunner runner = new CodeBuildRunner(dockerClient, null, null, null, null, null, null, null, null, null, null);
|
||||
CodeBuildRunner runner = new CodeBuildRunner(dockerClient, null, null, null, null, null, null, null, null, null, null,
|
||||
null);
|
||||
|
||||
CodeBuildRunner.PhaseResult result = runner.runPhase("container-1", "/src", List.of(),
|
||||
List.of("./test.sh"), 60, new AtomicBoolean(false));
|
||||
@@ -66,7 +68,7 @@ class CodeBuildRunnerTest {
|
||||
ContainerDetector containerDetector = mock(ContainerDetector.class);
|
||||
ContainerReachableEndpoint endpoint = new ContainerReachableEndpoint(config, null, null, null, 4811);
|
||||
CodeBuildRunner runner = new CodeBuildRunner(null, null, null, null, null, null, null,
|
||||
config, containerDetector, null, endpoint);
|
||||
config, containerDetector, null, endpoint, null);
|
||||
|
||||
assertEquals("http://host.docker.internal:4811", runner.resolveEndpointUrl());
|
||||
}
|
||||
|
||||
@@ -33,7 +33,7 @@ class CodeBuildSourceCopyTest {
|
||||
uploads.consumedBytes = 8;
|
||||
uploads.failure = new RuntimeException(new IOException("Broken pipe"));
|
||||
|
||||
new CodeBuildRunner(docker, null, null, null, null, null, null, null, null, null, null)
|
||||
new CodeBuildRunner(docker, null, null, null, null, null, null, null, null, null, null, null)
|
||||
.copySourceToContainer("build-container", workspace, "/codebuild/output/src/src", 0);
|
||||
|
||||
assertEquals(2, uploads.commands.size());
|
||||
@@ -58,7 +58,7 @@ class CodeBuildSourceCopyTest {
|
||||
uploads.failure = new RuntimeException(new IOException("Broken pipe"));
|
||||
|
||||
RuntimeException failure = assertThrows(RuntimeException.class, () ->
|
||||
new CodeBuildRunner(docker, null, null, null, null, null, null, null, null, null, null)
|
||||
new CodeBuildRunner(docker, null, null, null, null, null, null, null, null, null, null, null)
|
||||
.copySourceToContainer("build-container", workspace, "/codebuild/output/src/src", 0));
|
||||
|
||||
assertEquals(6, uploads.commands.size());
|
||||
@@ -74,7 +74,7 @@ class CodeBuildSourceCopyTest {
|
||||
uploads.failure = new IllegalStateException("No such container");
|
||||
|
||||
RuntimeException failure = assertThrows(RuntimeException.class, () ->
|
||||
new CodeBuildRunner(docker, null, null, null, null, null, null, null, null, null, null)
|
||||
new CodeBuildRunner(docker, null, null, null, null, null, null, null, null, null, null, null)
|
||||
.copySourceToContainer("build-container", workspace, "/codebuild/output/src/src", 0));
|
||||
|
||||
assertTrue(failure.getMessage().contains("No such container"));
|
||||
@@ -85,7 +85,7 @@ class CodeBuildSourceCopyTest {
|
||||
void skipsEmptyWorkspace(@TempDir Path workspace) {
|
||||
DockerClient docker = mock(DockerClient.class);
|
||||
|
||||
new CodeBuildRunner(docker, null, null, null, null, null, null, null, null, null, null)
|
||||
new CodeBuildRunner(docker, null, null, null, null, null, null, null, null, null, null, null)
|
||||
.copySourceToContainer("build-container", workspace, "/codebuild/output/src/src");
|
||||
|
||||
verifyNoInteractions(docker);
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
package io.floci.aws.services.ec2;
|
||||
|
||||
import com.github.dockerjava.api.DockerClient;
|
||||
import com.github.dockerjava.api.command.InspectContainerResponse;
|
||||
import com.github.dockerjava.api.exception.NotFoundException;
|
||||
import io.floci.aws.services.ec2.model.Subnet;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
|
||||
import static org.mockito.Mockito.doAnswer;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/** Joining a container to its subnet's VPC network, and giving the address back only once Docker says it is gone. */
|
||||
class VpcContainerLeasesTest {
|
||||
|
||||
private static final String REGION = "us-east-1";
|
||||
private static final String ACCOUNT = "000000000000";
|
||||
|
||||
private Ec2Service ec2;
|
||||
private DockerClient docker;
|
||||
private VpcContainerLeases leases;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
ec2 = mock(Ec2Service.class);
|
||||
docker = mock(DockerClient.class, RETURNS_DEEP_STUBS);
|
||||
doAnswer(invocation -> {
|
||||
invocation.<Runnable>getArgument(1).run();
|
||||
return null;
|
||||
}).when(ec2).runWithSubnetReferencesHeld(eq(REGION), any());
|
||||
Subnet subnet = new Subnet();
|
||||
subnet.setSubnetId("subnet-1");
|
||||
subnet.setVpcId("vpc-1");
|
||||
when(ec2.describeSubnets(REGION, List.of("subnet-1"), Map.of())).thenReturn(List.of(subnet));
|
||||
when(ec2.allocateVpcPrivateIp(REGION, "subnet-1")).thenReturn(Optional.of("10.0.1.20"));
|
||||
leases = new VpcContainerLeases(ec2, "Test resource", () -> docker);
|
||||
}
|
||||
|
||||
@Test
|
||||
void anAttachThatFailsGivesTheLeasedAddressBack() {
|
||||
when(ec2.attachContainerToVpc(REGION, "vpc-1", "subnet-1", "c1", "10.0.1.20"))
|
||||
.thenThrow(new IllegalStateException("docker refused"));
|
||||
|
||||
assertThrows(IllegalStateException.class, () -> leases.join(ACCOUNT, REGION, null, "subnet-1", "c1", "r1"));
|
||||
|
||||
verify(ec2).releaseVpcPrivateIp(REGION, "subnet-1", "10.0.1.20");
|
||||
assertFalse(leases.holdsSubnet(ACCOUNT, REGION, "subnet-1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSubnetOutsideTheVpcTheResourceNamesIsNotJoined() {
|
||||
assertTrue(leases.join(ACCOUNT, REGION, "vpc-other", "subnet-1", "c1", "r1").isEmpty());
|
||||
|
||||
verify(ec2, never()).allocateVpcPrivateIp(anyString(), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anAddressDockerCouldNotConfirmFreeIsGivenBackOnceTheContainerIsGone() {
|
||||
when(ec2.attachContainerToVpc(REGION, "vpc-1", "subnet-1", "c1", "10.0.1.20"))
|
||||
.thenReturn(Optional.of("10.0.1.20"));
|
||||
assertEquals("10.0.1.20", leases.join(ACCOUNT, REGION, "vpc-1", "subnet-1", "c1", "r1")
|
||||
.orElseThrow().address());
|
||||
AtomicReference<RuntimeException> inspect = new AtomicReference<>(new IllegalStateException("daemon down"));
|
||||
when(docker.inspectContainerCmd("c1").exec()).thenAnswer(invocation -> {
|
||||
if (inspect.get() != null) {
|
||||
throw inspect.get();
|
||||
}
|
||||
return mock(InspectContainerResponse.class);
|
||||
});
|
||||
|
||||
leases.releaseIfGone("c1");
|
||||
assertTrue(leases.holdsSubnet(ACCOUNT, REGION, "subnet-1"), "a Docker error keeps the address");
|
||||
|
||||
inspect.set(null);
|
||||
assertTrue(leases.holdsVpc(ACCOUNT, REGION, "vpc-1"), "a container still present keeps the address");
|
||||
|
||||
inspect.set(new NotFoundException("gone"));
|
||||
assertFalse(leases.holdsSubnet(ACCOUNT, REGION, "subnet-1"));
|
||||
verify(ec2).releaseVpcPrivateIp(REGION, "subnet-1", "10.0.1.20");
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user