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

@@ -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.