fix(batch): put a job's container on its compute environment's VPC network (#8509)

This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-11-15 18:09:00 -04:00
1 parent ca032c1a03
commit 0fccd475b7
8 files changed
+323 -89

No files matched your search

+5 -1
View File
@@ -40,6 +40,10 @@ Batch uses `floci.services.batch.runner-mode`.
`process` mode is not implemented.
### VPC (`computeResources.subnets`)
AWS Batch runs a job on an instance or Fargate task in the subnets of its queue's compute environment. In `docker` mode, Floci puts the job's container (each node's, for a multi-node job) on that VPC's Docker network, at an address leased from the first subnet of the first compute environment, in the queue's order, that names any, the way it places EC2 instances and VPC-configured Lambda functions, so a job reaches a database or anything else in the VPC by its private IP. A queue of unmanaged compute environments, a subnet EC2 does not know, or `FLOCI_SERVICES_EC2_VPC_NETWORKS_ENABLED=false` leaves the container on its own network. Security groups are not enforced, as for EC2. While a job's container runs, `DeleteSubnet` refuses its subnet and `DeleteVpc` its VPC (`DependencyViolation`); Floci runs no idle instances, so a compute environment's subnets alone hold nothing.
## Submit Behavior
Supported `SubmitJob` fields:
@@ -150,7 +154,7 @@ IAM roles, VPC fields, Fargate declarations, log configuration, storage, and res
## Limitations
- No IAM enforcement.
- No VPC/subnet/security-group simulation.
- Security groups are not enforced, and only `docker` mode places jobs on their VPC's network.
- No AWS-faithful capacity scheduling.
- No job dependencies (`dependsOn`).
- EventBridge input transformers work through the existing EventBridge target input path; full Batch-specific input-transformer parity is not implemented.
@@ -0,0 +1,53 @@
package io.floci.aws.core.common.docker;
import io.floci.aws.config.EmulatorConfig;
import org.jboss.logging.Logger;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* The containers one service starts for work that does not outlive the process, such as builds or jobs: each carries
* the deployment's owner label and this process's run label, so the containers an earlier run left behind (a crash
* keeps them running, holding their network addresses, with nothing left to finish) are known and removed. Removal is
* retried before each new container until one pass removes them all.
*/
public final class RunLabelledContainers {
private final String service;
private final String runLabel;
private final EmulatorConfig config;
private final ContainerReconciler reconciler;
private final String runId = UUID.randomUUID().toString();
private final AtomicBoolean leftoversRemoved = new AtomicBoolean();
/**
* @param service the service label the containers carry, such as {@code batch}
* @param runLabel the label naming the process run that created a container, such as {@code io.floci.batch.run}
*/
public RunLabelledContainers(ContainerLifecycleManager lifecycleManager, EmulatorConfig config, String service,
String runLabel, Logger log) {
this.service = service;
this.runLabel = runLabel;
this.config = config;
this.reconciler = new ContainerReconciler(lifecycleManager, log);
}
/** The owner and run labels a container of this run carries, beside its resource identity. */
public Map<String, String> labels() {
return Map.of(ContainerStorageHelper.OWNER_LABEL, ContainerStorageHelper.ownerIdentity(config),
runLabel, runId);
}
/** Removes the service's containers an earlier run of this deployment left, until a pass removes them all. */
public void removeLeftovers() {
if (!leftoversRemoved.get() && reconciler.reconcile(
Map.of(ContainerStorageHelper.SERVICE_LABEL, service,
ContainerStorageHelper.OWNER_LABEL, ContainerStorageHelper.ownerIdentity(config)),
container -> !runId.equals(ContainerStorageHelper.CONTAINER_LABEL_ALIASES
.labelValue(container.getLabels(), runLabel)))) {
leftoversRemoved.set(true);
}
}
}
@@ -4,6 +4,7 @@ import com.github.dockerjava.api.command.InspectContainerResponse;
import com.github.dockerjava.api.exception.NotFoundException;
import io.floci.aws.config.EmulatorConfig;
import io.floci.aws.core.common.ContainerTeardown;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.common.dns.EmbeddedDnsServer;
import io.floci.aws.core.common.docker.ContainerBuilder;
import io.floci.aws.core.common.docker.ContainerDetector;
@@ -11,11 +12,15 @@ import io.floci.aws.core.common.docker.ContainerLifecycleManager;
import io.floci.aws.core.common.docker.ContainerLogStreamer;
import io.floci.aws.core.common.docker.ContainerSpec;
import io.floci.aws.core.common.docker.ContainerStorageHelper;
import io.floci.aws.core.common.docker.RunLabelledContainers;
import io.floci.aws.services.batch.model.BatchJob;
import io.floci.aws.services.batch.model.BatchKeyValue;
import io.floci.aws.services.batch.model.BatchNodeExecution;
import io.floci.aws.services.batch.model.BatchResourceRequirement;
import io.floci.aws.services.batch.model.BatchRunResult;
import io.floci.aws.services.ec2.Ec2Service;
import io.floci.aws.services.ec2.VpcContainerLeases;
import io.floci.aws.services.ec2.VpcDependencyProvider;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
@@ -23,13 +28,17 @@ import org.jboss.logging.Logger;
import java.io.Closeable;
import java.time.Duration;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
@ApplicationScoped
public class BatchDockerRunner implements ContainerTeardown {
public class BatchDockerRunner implements ContainerTeardown, VpcDependencyProvider {
/** The label naming the Floci process that created a job container, set by {@link #jobLabels}. */
static final String RUN_LABEL = "io.floci.batch.run";
private static final Logger LOG = Logger.getLogger(BatchDockerRunner.class);
private static final String LOG_GROUP = "/aws/batch/job";
@@ -44,32 +53,47 @@ public class BatchDockerRunner implements ContainerTeardown {
private final ContainerLogStreamer logStreamer;
private final EmulatorConfig config;
private final ContainerDetector containerDetector;
private final RegionResolver regionResolver;
/** The VPC address each running job container holds, given back once the container is gone. */
private final VpcContainerLeases vpcLeases;
/** This run's job containers, so a later run knows the ones a crash leaves for leftovers. */
private final RunLabelledContainers runContainers;
@Inject
public BatchDockerRunner(ContainerBuilder containerBuilder,
ContainerLifecycleManager lifecycleManager,
ContainerLogStreamer logStreamer,
EmulatorConfig config,
ContainerDetector containerDetector) {
ContainerDetector containerDetector,
RegionResolver regionResolver,
Ec2Service ec2Service) {
this.containerBuilder = containerBuilder;
this.lifecycleManager = lifecycleManager;
this.logStreamer = logStreamer;
this.config = config;
this.containerDetector = containerDetector;
this.regionResolver = regionResolver;
this.vpcLeases = new VpcContainerLeases(ec2Service, "Batch job", () -> lifecycleManager.getDockerClient());
this.runContainers = new RunLabelledContainers(lifecycleManager, config, "batch", RUN_LABEL, LOG);
}
public BatchRunResult run(BatchJob job, int attemptNumber) {
/**
* Runs one attempt of {@code job} in a container; with a {@code subnetId}, from the job's compute environment,
* the container joins that subnet's VPC network first.
*/
public BatchRunResult run(BatchJob job, int attemptNumber, String subnetId) {
String logStreamName = logStreamer.generateLogStreamName(
job.getJobDefinitionName() + "/default/" + job.getJobId());
String containerName = ContainerStorageHelper.dockerName(config, "batch-" + job.getJobId() + "-" + attemptNumber);
return runContainer(job, job.getJobId(), containerName, logStreamName,
"batch:" + job.getJobName() + ":" + job.getJobId(),
job.getContainerImage(), "Job definition container image is missing",
job.getResolvedCommand(), buildEnvironment(job, attemptNumber), job.getResourceRequirements());
job.getResolvedCommand(), buildEnvironment(job, attemptNumber), job.getResourceRequirements(),
subnetId);
}
// A distinct inFlightContainers key per node, since nodes of one job run concurrently.
public BatchRunResult run(BatchJob job, int attemptNumber, BatchNodeExecution node) {
public BatchRunResult run(BatchJob job, int attemptNumber, BatchNodeExecution node, String subnetId) {
String logStreamName = logStreamer.generateLogStreamName(
job.getJobDefinitionName() + "/default/" + job.getJobId() + "/" + node.getNodeIndex());
String containerName = ContainerStorageHelper.dockerName(config,
@@ -78,13 +102,14 @@ public class BatchDockerRunner implements ContainerTeardown {
return runContainer(job, inFlightKey, containerName, logStreamName,
"batch:" + job.getJobName() + ":" + job.getJobId() + ":node" + node.getNodeIndex(),
node.getContainerImage(), "Node " + node.getNodeIndex() + " container image is missing",
node.getResolvedCommand(), buildNodeEnvironment(job, attemptNumber, node), node.getResourceRequirements());
node.getResolvedCommand(), buildNodeEnvironment(job, attemptNumber, node), node.getResourceRequirements(),
subnetId);
}
private BatchRunResult runContainer(BatchJob job, String inFlightKey, String containerName, String logStreamName,
String logSourceLabel, String image, String missingImageMessage,
List<String> command, List<String> env,
List<BatchResourceRequirement> resourceRequirements) {
List<BatchResourceRequirement> resourceRequirements, String subnetId) {
long startedAt = System.currentTimeMillis();
Closeable logHandle = null;
String containerId = null;
@@ -105,8 +130,7 @@ public class BatchDockerRunner implements ContainerTeardown {
.withEmbeddedDns()
.withLogRotation()
.withJavaTrustStore()
.withLabels(ContainerStorageHelper.resourceIdentityLabels(
"batch", job.getJobId(), job.getAccountId(), job.getRegion()));
.withLabels(jobLabels(job));
if (command != null && !command.isEmpty()) {
builder.withCmd(command);
@@ -114,8 +138,14 @@ public class BatchDockerRunner implements ContainerTeardown {
applyResourceRequirements(builder, resourceRequirements, job.getJobId());
ContainerSpec spec = builder.build();
containerId = lifecycleManager.createAndStart(spec).containerId();
// Job state does not outlive the process, so a crash's job containers have nothing left to finish.
runContainers.removeLeftovers();
containerId = lifecycleManager.create(spec);
inFlightContainers.put(inFlightKey, containerId);
// AWS Batch runs the job on an instance or Fargate task in its compute environment's subnets; the
// command is the entrypoint, so the container joins that network before it starts.
vpcLeases.join(job.getAccountId(), job.getRegion(), null, subnetId, containerId, job.getJobId());
lifecycleManager.startCreated(containerId, spec);
if (stopRequestedJobs.contains(job.getJobId())) {
releaseAndStop(inFlightKey, containerId, null);
return stopped(startedAt, logStreamName);
@@ -143,6 +173,28 @@ public class BatchDockerRunner implements ContainerTeardown {
}
}
/** A job container's labels: its resource identity, and the deployment and run that created it. */
private Map<String, String> jobLabels(BatchJob job) {
Map<String, String> labels = new LinkedHashMap<>(ContainerStorageHelper.resourceIdentityLabels(
"batch", job.getJobId(), job.getAccountId(), job.getRegion()));
labels.putAll(runContainers.labels());
return labels;
}
/**
* A running job's network interface is in its subnet, so DeleteSubnet refuses it until the job's container is
* gone, as on AWS; a compute environment's subnets alone hold none here, since Floci runs no idle instances.
*/
@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);
}
public void requestStop(String jobId) {
stopRequestedJobs.add(jobId);
}
@@ -155,6 +207,7 @@ public class BatchDockerRunner implements ContainerTeardown {
if (inFlightContainers.remove(entry.getKey(), entry.getValue())) {
try {
lifecycleManager.stopAndRemove(entry.getValue(), null);
vpcLeases.releaseIfGone(entry.getValue());
} catch (Exception e) {
LOG.warnv("Failed to stop Batch container for job {0}: {1}", jobId, e.getMessage());
}
@@ -178,6 +231,8 @@ public class BatchDockerRunner implements ContainerTeardown {
LOG.debugv("Error closing log stream for job {0}: {1}", jobId, e.getMessage());
}
}
// Whoever removed the container, its address goes back once Docker confirms it gone.
vpcLeases.releaseIfGone(containerId);
}
/**
@@ -190,6 +245,7 @@ public class BatchDockerRunner implements ContainerTeardown {
if (inFlightContainers.remove(entry.getKey(), entry.getValue())) {
try {
lifecycleManager.stopAndRemove(entry.getValue(), null);
vpcLeases.releaseIfGone(entry.getValue());
} catch (Exception e) {
LOG.warnv("Failed to stop Batch container for job {0} on shutdown: {1}",
entry.getKey(), e.getMessage());
@@ -9,6 +9,7 @@ import io.floci.aws.config.EmulatorConfig;
import io.floci.aws.core.common.AwsArnUtils;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.common.RequestScopes;
import io.floci.aws.core.storage.AccountAwareStorageBackend;
import io.floci.aws.core.storage.StorageBackend;
import io.floci.aws.core.storage.StorageFactory;
@@ -1037,7 +1038,7 @@ public class BatchService {
return;
}
BatchRunResult result = shouldRunDocker()
? dockerRunner.run(attemptJob, attemptNumber)
? dockerRunner.run(attemptJob, attemptNumber, subnetFor(attemptJob))
: immediateSuccess(attemptJob);
if (finishAttempt(accountId, jobId, result, attemptNumber >= maxAttempts)) {
return;
@@ -1051,6 +1052,30 @@ public class BatchService {
}
}
/**
* The subnet a job runs in: AWS Batch places it in a subnet of a compute environment of its queue, here the first
* subnet of the first, in the queue's order, that names any. Null for a queue of unmanaged compute environments.
* Read as the job's account, since jobs run outside the SubmitJob request.
*/
private String subnetFor(BatchJob job) {
return RequestScopes.callAs(job.getAccountId(), job.getRegion(), () -> {
BatchJobQueue queue = resolveJobQueueOptional(job.getJobQueue()).orElse(null);
if (queue == null || queue.getComputeEnvironmentOrder() == null) {
return null;
}
return queue.getComputeEnvironmentOrder().stream()
.sorted(Comparator.comparingInt(BatchComputeEnvironmentOrder::getOrder))
.map(order -> resolveComputeEnvironmentOptional(order.getComputeEnvironment()))
.flatMap(Optional::stream)
.map(environment -> environment.getComputeResources().get("subnets"))
.filter(subnets -> subnets instanceof List<?> list && !list.isEmpty()
&& list.getFirst() instanceof String)
.map(subnets -> (String) ((List<?>) subnets).getFirst())
.findFirst()
.orElse(null);
});
}
private boolean shouldRunDocker() {
return "docker".equalsIgnoreCase(config.services().batch().runnerMode());
}
@@ -1163,10 +1188,11 @@ public class BatchService {
results.add(null);
}
List<Thread> threads = new ArrayList<>(executions.size());
String subnetId = subnetFor(job);
for (int i = 0; i < executions.size(); i++) {
int nodeIndex = i;
threads.add(Thread.startVirtualThread(() -> {
BatchRunResult result = dockerRunner.run(job, attemptNumber, executions.get(nodeIndex));
BatchRunResult result = dockerRunner.run(job, attemptNumber, executions.get(nodeIndex), subnetId);
synchronized (results) {
results.set(nodeIndex, result);
}
@@ -16,10 +16,10 @@ 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;
import io.floci.aws.core.common.docker.RunLabelledContainers;
import io.floci.aws.services.codebuild.BuildspecParser.ParsedArtifacts;
import io.floci.aws.services.codebuild.BuildspecParser.ParsedBuildspec;
import io.floci.aws.services.codebuild.model.Build;
@@ -57,7 +57,6 @@ 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;
@@ -89,10 +88,8 @@ public class CodeBuildRunner implements ContainerTeardown, VpcDependencyProvider
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();
/** This run's build containers, so a later run knows the ones a crash leaves for leftovers. */
private final RunLabelledContainers runContainers;
private final ConcurrentHashMap<String, String> runningContainers = new ConcurrentHashMap<>();
private final ConcurrentHashMap<String, AtomicBoolean> stopFlags = new ConcurrentHashMap<>();
@@ -122,7 +119,7 @@ public class CodeBuildRunner implements ContainerTeardown, VpcDependencyProvider
this.regionResolver = regionResolver;
this.containerEndpoint = containerEndpoint;
this.vpcLeases = new VpcContainerLeases(ec2Service, "CodeBuild build", () -> dockerClient);
this.containerReconciler = new ContainerReconciler(lifecycleManager, LOG);
this.runContainers = new RunLabelledContainers(lifecycleManager, config, "codebuild", RUN_LABEL, LOG);
}
/**
@@ -254,7 +251,8 @@ public class CodeBuildRunner implements ContainerTeardown, VpcDependencyProvider
.withLabels(buildLabels(buildId, region))
.build();
removeLeftoverContainers();
// Build state does not outlive the process, so a crash's build containers have nothing left to finish.
runContainers.removeLeftovers();
ContainerLifecycleManager.ContainerInfo info = lifecycleManager.createAndStart(spec);
containerId = info.containerId();
runningContainers.put(executionId, containerId);
@@ -446,26 +444,10 @@ public class CodeBuildRunner implements ContainerTeardown, VpcDependencyProvider
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);
labels.putAll(runContainers.labels());
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.
@@ -60,7 +60,7 @@ class BatchDockerRunnerDockerIntegrationTest {
test "$FLOCI_HOSTNAME" = "%s"
""".formatted(expectedEndpoint, expectedEndpoint, expectedHostname)));
BatchRunResult result = runner.run(job, 1);
BatchRunResult result = runner.run(job, 1, null);
assertEquals(0, result.exitCode(), result.reason());
}
@@ -1,7 +1,10 @@
package io.floci.aws.services.batch;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.command.InspectContainerResponse;
import com.github.dockerjava.api.exception.NotFoundException;
import io.floci.aws.config.EmulatorConfig;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.common.dns.EmbeddedDnsServer;
import io.floci.aws.core.common.docker.ContainerBuilder;
import io.floci.aws.core.common.docker.ContainerDetector;
@@ -11,8 +14,14 @@ import io.floci.aws.core.common.docker.ContainerSpec;
import io.floci.aws.services.batch.model.BatchJob;
import io.floci.aws.services.batch.model.BatchNodeExecution;
import io.floci.aws.services.batch.model.BatchRunResult;
import io.floci.aws.services.ec2.Ec2Service;
import io.floci.aws.services.ec2.model.Subnet;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.InOrder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
@@ -33,6 +42,7 @@ import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.RETURNS_SELF;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@@ -65,21 +75,13 @@ class BatchDockerRunnerTest {
@Test
void runLabelsContainerWithResourceIdentity() {
EmulatorConfig config = mock(EmulatorConfig.class);
EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);
EmulatorConfig.BatchServiceConfig batch = mock(EmulatorConfig.BatchServiceConfig.class);
when(config.services()).thenReturn(services);
when(services.batch()).thenReturn(batch);
when(batch.dockerNetwork()).thenReturn(Optional.empty());
when(config.port()).thenReturn(4566);
when(config.hostname()).thenReturn(Optional.empty());
EmulatorConfig config = batchConfig();
ContainerDetector detector = mock(ContainerDetector.class);
when(detector.isRunningInContainer()).thenReturn(false);
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
when(lifecycleManager.createAndStart(any())).thenReturn(
new ContainerLifecycleManager.ContainerInfo("container-id", Map.of()));
when(lifecycleManager.create(any())).thenReturn("container-id");
DockerClient dockerClient =
mock(DockerClient.class, RETURNS_DEEP_STUBS);
when(lifecycleManager.getDockerClient()).thenReturn(dockerClient);
@@ -92,7 +94,7 @@ class BatchDockerRunnerTest {
when(builder.build()).thenReturn(new ContainerSpec("test-image"));
BatchDockerRunner runner = new BatchDockerRunner(containerBuilder, lifecycleManager,
mock(ContainerLogStreamer.class), config, detector);
mock(ContainerLogStreamer.class), config, detector, null, null);
BatchJob job = new BatchJob();
job.setJobId("job-1");
@@ -103,33 +105,32 @@ class BatchDockerRunnerTest {
job.setRegion("us-east-1");
job.setAccountId("000000000000");
runner.run(job, 1);
runner.run(job, 1, null);
verify(builder).withLabels(Map.of(
ArgumentCaptor<Map<String, String>> labels = ArgumentCaptor.captor();
verify(builder).withLabels(labels.capture());
assertEquals(Map.of(
"io.floci", "aws",
"io.floci.service", "batch",
"io.floci.resource-id", "job-1",
"io.floci.account", "000000000000",
"io.floci.region", "us-east-1"));
"io.floci.region", "us-east-1",
"io.floci.owner", "4566"), withoutRunLabel(labels.getValue()));
// The run label lets a later run tell this run's containers from a crash's leftovers.
assertTrue(labels.getValue().containsKey(BatchDockerRunner.RUN_LABEL));
// A job's JVMs trust Floci's CA as well.
verify(builder).withJavaTrustStore();
}
@Test
void stopJobStopsAnInFlightContainer() throws Exception {
EmulatorConfig config = mock(EmulatorConfig.class);
EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);
EmulatorConfig.BatchServiceConfig batch = mock(EmulatorConfig.BatchServiceConfig.class);
when(config.services()).thenReturn(services);
when(services.batch()).thenReturn(batch);
when(batch.dockerNetwork()).thenReturn(Optional.empty());
when(config.port()).thenReturn(4566);
when(config.hostname()).thenReturn(Optional.empty());
EmulatorConfig config = batchConfig();
CountDownLatch containerStarted = new CountDownLatch(1);
AtomicBoolean stopped = new AtomicBoolean();
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
when(lifecycleManager.createAndStart(any())).thenAnswer(invocation -> {
when(lifecycleManager.create(any())).thenReturn("container-id");
when(lifecycleManager.startCreated(eq("container-id"), any())).thenAnswer(invocation -> {
containerStarted.countDown();
return new ContainerLifecycleManager.ContainerInfo("container-id", Map.of());
});
@@ -148,11 +149,11 @@ class BatchDockerRunnerTest {
when(containerBuilder.newContainer(anyString())).thenReturn(builder);
when(builder.build()).thenReturn(new ContainerSpec("test-image"));
BatchDockerRunner runner = new BatchDockerRunner(containerBuilder, lifecycleManager,
mock(ContainerLogStreamer.class), config, mock(ContainerDetector.class));
mock(ContainerLogStreamer.class), config, mock(ContainerDetector.class), null, null);
BatchJob job = job();
AtomicReference<BatchRunResult> result = new AtomicReference<>();
Thread runThread = Thread.startVirtualThread(() -> result.set(runner.run(job, 1)));
Thread runThread = Thread.startVirtualThread(() -> result.set(runner.run(job, 1, null)));
assertTrue(containerStarted.await(2, TimeUnit.SECONDS));
runner.requestStop(job.getJobId());
runner.stopJob(job.getJobId());
@@ -174,8 +175,7 @@ class BatchDockerRunnerTest {
when(config.port()).thenReturn(4566);
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
when(lifecycleManager.createAndStart(any())).thenReturn(
new ContainerLifecycleManager.ContainerInfo("container-id", Map.of()));
when(lifecycleManager.create(any())).thenReturn("container-id");
DockerClient dockerClient = mock(DockerClient.class, RETURNS_DEEP_STUBS);
when(lifecycleManager.getDockerClient()).thenReturn(dockerClient);
when(dockerClient.inspectContainerCmd("container-id").exec().getState().getRunning()).thenReturn(false);
@@ -185,15 +185,16 @@ class BatchDockerRunnerTest {
when(containerBuilder.newContainer(anyString())).thenReturn(builder);
when(builder.build()).thenReturn(new ContainerSpec("test-image"));
BatchDockerRunner runner = new BatchDockerRunner(containerBuilder, lifecycleManager,
mock(ContainerLogStreamer.class), config, mock(ContainerDetector.class));
mock(ContainerLogStreamer.class), config, mock(ContainerDetector.class), null, null);
runner.requestStop("job-1");
runner.clearStopRequest("job-1");
runner.stopJob("job-1");
BatchRunResult result = runner.run(job(), 1);
BatchRunResult result = runner.run(job(), 1, null);
assertEquals(0, result.exitCode());
verify(lifecycleManager).createAndStart(any());
verify(lifecycleManager).create(any());
verify(lifecycleManager).startCreated(eq("container-id"), any());
}
@Test
@@ -210,10 +211,11 @@ class BatchDockerRunnerTest {
AtomicInteger containerSequence = new AtomicInteger();
Set<String> stoppedContainers = ConcurrentHashMap.newKeySet();
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
when(lifecycleManager.createAndStart(any())).thenAnswer(invocation -> {
String containerId = "container-" + containerSequence.getAndIncrement();
when(lifecycleManager.create(any()))
.thenAnswer(invocation -> "container-" + containerSequence.getAndIncrement());
when(lifecycleManager.startCreated(anyString(), any())).thenAnswer(invocation -> {
containersStarted.countDown();
return new ContainerLifecycleManager.ContainerInfo(containerId, Map.of());
return new ContainerLifecycleManager.ContainerInfo(invocation.getArgument(0), Map.of());
});
DockerClient dockerClient = mock(DockerClient.class, RETURNS_DEEP_STUBS);
when(lifecycleManager.getDockerClient()).thenReturn(dockerClient);
@@ -232,15 +234,15 @@ class BatchDockerRunnerTest {
when(containerBuilder.newContainer(anyString())).thenReturn(builder);
when(builder.build()).thenReturn(new ContainerSpec("test-image"));
BatchDockerRunner runner = new BatchDockerRunner(containerBuilder, lifecycleManager,
mock(ContainerLogStreamer.class), config, mock(ContainerDetector.class));
mock(ContainerLogStreamer.class), config, mock(ContainerDetector.class), null, null);
BatchJob job = job();
BatchNodeExecution firstNode = node(0);
BatchNodeExecution secondNode = node(1);
AtomicReference<BatchRunResult> firstResult = new AtomicReference<>();
AtomicReference<BatchRunResult> secondResult = new AtomicReference<>();
Thread firstThread = Thread.startVirtualThread(() -> firstResult.set(runner.run(job, 1, firstNode)));
Thread secondThread = Thread.startVirtualThread(() -> secondResult.set(runner.run(job, 1, secondNode)));
Thread firstThread = Thread.startVirtualThread(() -> firstResult.set(runner.run(job, 1, firstNode, null)));
Thread secondThread = Thread.startVirtualThread(() -> secondResult.set(runner.run(job, 1, secondNode, null)));
assertTrue(containersStarted.await(2, TimeUnit.SECONDS));
runner.requestStop(job.getJobId());
runner.stopJob(job.getJobId());
@@ -274,13 +276,91 @@ class BatchDockerRunnerTest {
return node;
}
@Test
void aJobInAVpcJoinsItsSubnetsNetworkAndGivesTheAddressBackOnceItsContainerIsGone() {
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-a");
subnet.setVpcId("vpc-1");
when(ec2.describeSubnets("us-east-1", List.of("subnet-a"), Map.of())).thenReturn(List.of(subnet));
when(ec2.allocateVpcPrivateIp("us-east-1", "subnet-a")).thenReturn(Optional.of("10.0.1.30"));
when(ec2.attachContainerToVpc("us-east-1", "vpc-1", "subnet-a", "container-id", "10.0.1.30"))
.thenReturn(Optional.of("10.0.1.30"));
RegionResolver regionResolver = mock(RegionResolver.class);
when(regionResolver.getAccountId()).thenReturn("000000000000");
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
when(lifecycleManager.create(any())).thenReturn("container-id");
DockerClient dockerClient = mock(DockerClient.class, RETURNS_DEEP_STUBS);
when(lifecycleManager.getDockerClient()).thenReturn(dockerClient);
InspectContainerResponse exited = mock(InspectContainerResponse.class, RETURNS_DEEP_STUBS);
when(exited.getState().getRunning()).thenReturn(false);
when(exited.getState().getExitCodeLong()).thenReturn(0L);
AtomicBoolean removed = new AtomicBoolean();
AtomicBoolean heldWhileRunning = new AtomicBoolean();
BatchDockerRunner[] runnerRef = new BatchDockerRunner[1];
when(dockerClient.inspectContainerCmd("container-id").exec()).thenAnswer(invocation -> {
if (removed.get()) {
throw new NotFoundException("gone");
}
heldWhileRunning.compareAndSet(false, runnerRef[0].hasSubnetDependency("us-east-1", "subnet-a"));
return exited;
});
doAnswer(invocation -> {
removed.set(true);
return null;
}).when(lifecycleManager).stopAndRemove(eq("container-id"), any());
ContainerBuilder containerBuilder = mock(ContainerBuilder.class);
ContainerBuilder.Builder builder = mock(ContainerBuilder.Builder.class, RETURNS_SELF);
when(containerBuilder.newContainer(anyString())).thenReturn(builder);
when(builder.build()).thenReturn(new ContainerSpec("test-image"));
BatchDockerRunner runner = new BatchDockerRunner(containerBuilder, lifecycleManager,
mock(ContainerLogStreamer.class), batchConfig(), mock(ContainerDetector.class), regionResolver, ec2);
runnerRef[0] = runner;
BatchRunResult result = runner.run(job(), 1, "subnet-a");
assertEquals(0, result.exitCode());
// The job's command is the entrypoint, so the container is on the VPC network before it starts.
InOrder order = inOrder(ec2, lifecycleManager);
order.verify(ec2).attachContainerToVpc("us-east-1", "vpc-1", "subnet-a", "container-id", "10.0.1.30");
order.verify(lifecycleManager).startCreated(eq("container-id"), any());
assertTrue(heldWhileRunning.get(), "the job's address holds its subnet while it runs");
verify(ec2).releaseVpcPrivateIp("us-east-1", "subnet-a", "10.0.1.30");
assertFalse(runner.hasSubnetDependency("us-east-1", "subnet-a"));
}
private static Map<String, String> withoutRunLabel(Map<String, String> labels) {
Map<String, String> rest = new HashMap<>(labels);
rest.remove(BatchDockerRunner.RUN_LABEL);
return rest;
}
private static EmulatorConfig batchConfig() {
EmulatorConfig config = mock(EmulatorConfig.class);
EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);
EmulatorConfig.BatchServiceConfig batch = mock(EmulatorConfig.BatchServiceConfig.class);
when(config.services()).thenReturn(services);
when(services.batch()).thenReturn(batch);
when(batch.dockerNetwork()).thenReturn(Optional.empty());
when(config.port()).thenReturn(4566);
when(config.hostname()).thenReturn(Optional.empty());
return config;
}
private BatchDockerRunner runner(EmulatorConfig config, ContainerDetector detector) {
return new BatchDockerRunner(
mock(ContainerBuilder.class),
mock(ContainerLifecycleManager.class),
mock(ContainerLogStreamer.class),
config,
detector);
detector,
null,
null);
}
private EmulatorConfig config(Optional<String> hostname) {
@@ -37,6 +37,8 @@ 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.anyInt;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.nullable;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
@@ -51,10 +53,41 @@ class BatchServiceTest {
private final ObjectMapper objectMapper = new ObjectMapper();
@Test
void aJobRunsInTheFirstSubnetOfTheFirstComputeEnvironmentOfItsQueueThatNamesAny() throws Exception {
BatchDockerRunner runner = mock(BatchDockerRunner.class);
when(runner.run(any(BatchJob.class), anyInt(), nullable(String.class)))
.thenReturn(new BatchRunResult(0, null, "log-stream", 1L, 2L, false));
BatchService service = dockerService(runner);
String unmanaged = service.createComputeEnvironment(json("""
{"computeEnvironmentName":"unmanaged-ce","type":"UNMANAGED"}
"""), REGION).path("computeEnvironmentArn").asText();
String fargate = service.createComputeEnvironment(json("""
{"computeEnvironmentName":"fargate-ce","type":"MANAGED",
"computeResources":{"type":"FARGATE","maxvCpus":4,"subnets":["subnet-a","subnet-b"],
"securityGroupIds":["sg-1"]}}
"""), REGION).path("computeEnvironmentArn").asText();
String queueArn = service.createJobQueue(json("""
{"jobQueueName":"vpc-queue","priority":1,"computeEnvironmentOrder":[
{"order":2,"computeEnvironment":"%s"},{"order":1,"computeEnvironment":"%s"}]}
""".formatted(fargate, unmanaged)), REGION).path("jobQueueArn").asText();
String definitionArn = service.registerJobDefinition(json("""
{"jobDefinitionName":"vpc-job","type":"container",
"containerProperties":{"image":"public.ecr.aws/example/job:latest"}}
"""), REGION).path("jobDefinitionArn").asText();
String jobId = service.submitJob(json("""
{"jobName":"vpc-submit","jobQueue":"%s","jobDefinition":"%s"}
""".formatted(queueArn, definitionArn)), REGION).path("jobId").asText();
assertNotNull(waitForJobStatus(service, jobId, "SUCCEEDED"));
verify(runner).run(any(BatchJob.class), eq(1), eq("subnet-a"));
}
@Test
void dockerTimeoutFailsWithoutRetryingRemainingAttempts() throws Exception {
BatchDockerRunner runner = mock(BatchDockerRunner.class);
when(runner.run(any(BatchJob.class), anyInt()))
when(runner.run(any(BatchJob.class), anyInt(), nullable(String.class)))
.thenReturn(new BatchRunResult(137, "Job timed out", "log-stream", 1L, 2L, true));
BatchService service = dockerService(runner);
@@ -90,13 +123,13 @@ class BatchServiceTest {
assertNotNull(job);
assertEquals("Job timed out", job.path("statusReason").asText());
assertEquals(1, job.path("attempts").size());
verify(runner, times(1)).run(any(BatchJob.class), anyInt());
verify(runner, times(1)).run(any(BatchJob.class), anyInt(), nullable(String.class));
}
@Test
void dockerRetriesFailedAttemptAndCanSucceed() throws Exception {
BatchDockerRunner runner = mock(BatchDockerRunner.class);
when(runner.run(any(BatchJob.class), anyInt()))
when(runner.run(any(BatchJob.class), anyInt(), nullable(String.class)))
.thenReturn(new BatchRunResult(1, "first failed", "log-1", 1L, 2L, false))
.thenReturn(new BatchRunResult(0, null, "log-2", 3L, 4L, false));
BatchService service = dockerService(runner);
@@ -128,13 +161,13 @@ class BatchServiceTest {
assertNotNull(job);
assertEquals(2, job.path("attempts").size());
assertEquals(0, job.path("attempts").get(1).path("container").path("exitCode").asInt());
verify(runner, times(2)).run(any(BatchJob.class), anyInt());
verify(runner, times(2)).run(any(BatchJob.class), anyInt(), nullable(String.class));
}
@Test
void dockerRetryExhaustionFailsJobAndKeepsAttempts() throws Exception {
BatchDockerRunner runner = mock(BatchDockerRunner.class);
when(runner.run(any(BatchJob.class), anyInt()))
when(runner.run(any(BatchJob.class), anyInt(), nullable(String.class)))
.thenReturn(new BatchRunResult(1, "failed once", "log-1", 1L, 2L, false))
.thenReturn(new BatchRunResult(2, "failed twice", "log-2", 3L, 4L, false));
BatchService service = dockerService(runner);
@@ -167,7 +200,7 @@ class BatchServiceTest {
assertEquals("failed twice", job.path("statusReason").asText());
assertEquals(2, job.path("attempts").size());
assertEquals(2, job.path("attempts").get(1).path("container").path("exitCode").asInt());
verify(runner, times(2)).run(any(BatchJob.class), anyInt());
verify(runner, times(2)).run(any(BatchJob.class), anyInt(), nullable(String.class));
}
@Test
@@ -647,7 +680,7 @@ class BatchServiceTest {
void submitMultiNodeJobSucceedsWhenOnlyAChildNodeFails() throws Exception {
// AWS determines the job's outcome solely from the main node, per the MNP user guide.
BatchDockerRunner runner = mock(BatchDockerRunner.class);
when(runner.run(any(BatchJob.class), anyInt(), any(BatchNodeExecution.class)))
when(runner.run(any(BatchJob.class), anyInt(), any(BatchNodeExecution.class), nullable(String.class)))
.thenAnswer(invocation -> {
BatchNodeExecution node = invocation.getArgument(2);
return node.getNodeIndex() == 1
@@ -674,7 +707,7 @@ class BatchServiceTest {
JsonNode job = waitForJobStatus(service, jobId, "SUCCEEDED");
assertNotNull(job);
verify(runner, times(2)).run(any(BatchJob.class), anyInt(), any(BatchNodeExecution.class));
verify(runner, times(2)).run(any(BatchJob.class), anyInt(), any(BatchNodeExecution.class), nullable(String.class));
JsonNode nodes = service.listJobs(json("""
{"multiNodeJobId":"%s"}
@@ -685,7 +718,7 @@ class BatchServiceTest {
@Test
void submitMultiNodeJobFailsWhenTheMainNodeFails() throws Exception {
BatchDockerRunner runner = mock(BatchDockerRunner.class);
when(runner.run(any(BatchJob.class), anyInt(), any(BatchNodeExecution.class)))
when(runner.run(any(BatchJob.class), anyInt(), any(BatchNodeExecution.class), nullable(String.class)))
.thenAnswer(invocation -> {
BatchNodeExecution node = invocation.getArgument(2);
return node.isMainNode()
@@ -713,7 +746,7 @@ class BatchServiceTest {
JsonNode job = waitForJobStatus(service, jobId, "FAILED");
assertNotNull(job);
assertEquals("main crashed", job.path("statusReason").asText());
verify(runner, times(2)).run(any(BatchJob.class), anyInt(), any(BatchNodeExecution.class));
verify(runner, times(2)).run(any(BatchJob.class), anyInt(), any(BatchNodeExecution.class), nullable(String.class));
}
@Test
@@ -812,7 +845,7 @@ class BatchServiceTest {
BatchDockerRunner runner = mock(BatchDockerRunner.class);
CountDownLatch runStarted = new CountDownLatch(1);
CountDownLatch releaseRun = new CountDownLatch(1);
when(runner.run(any(BatchJob.class), anyInt())).thenAnswer(invocation -> {
when(runner.run(any(BatchJob.class), anyInt(), nullable(String.class))).thenAnswer(invocation -> {
runStarted.countDown();
assertTrue(releaseRun.await(2, TimeUnit.SECONDS));
return new BatchRunResult(0, null, "log-stream", 1L, 2L, false);
@@ -852,7 +885,7 @@ class BatchServiceTest {
BatchDockerRunner runner = mock(BatchDockerRunner.class);
CountDownLatch runStarted = new CountDownLatch(1);
CountDownLatch stopRequested = new CountDownLatch(1);
when(runner.run(any(BatchJob.class), anyInt())).thenAnswer(invocation -> {
when(runner.run(any(BatchJob.class), anyInt(), nullable(String.class))).thenAnswer(invocation -> {
runStarted.countDown();
assertTrue(stopRequested.await(2, TimeUnit.SECONDS));
return new BatchRunResult(137, "Job terminated", "log-stream", 1L, 2L, false);
@@ -967,7 +1000,7 @@ class BatchServiceTest {
BatchDockerRunner runner = mock(BatchDockerRunner.class);
CountDownLatch nodesStarted = new CountDownLatch(2);
CountDownLatch stopRequested = new CountDownLatch(1);
when(runner.run(any(BatchJob.class), anyInt(), any(BatchNodeExecution.class)))
when(runner.run(any(BatchJob.class), anyInt(), any(BatchNodeExecution.class), nullable(String.class)))
.thenAnswer(invocation -> {
BatchNodeExecution node = invocation.getArgument(2);
nodesStarted.countDown();