feat(batch): support array and multi-node parallel jobs (#3595)

SubmitJob previously rejected arrayProperties/nodeProperties/nodeOverrides
outright. Array jobs now fan out real child jobs (<parentId>:<index>) that
run through the existing single-job pipeline; the parent's status and
arrayProperties.statusSummary are computed live from its children on every
DescribeJobs/ListJobs call instead of being stored and incrementally
updated, which avoids a race between concurrently finishing children.

Multi-node parallel jobs are supported via a new "multinode" job
definition type (numNodes/mainNode/nodeRangeProperties, validated for full
node coverage). SubmitJob runs one Docker container per node concurrently;
per AWS's documented MNP semantics, the job's status, retry decision, and
started/stoppedAt/statusReason are all determined solely by the main node,
not by any node that happens to fail. nodeOverrides.numNodes is supported
with AWS's real validation (requires an open-ended node range).

ListJobs gains arrayJobId and multiNodeJobId support.

dependsOn (job dependencies), CancelJob/TerminateJob (not implemented at
all, pre-existing), EventBridge forwarding of these new fields, and
CloudFormation-provisioned multinode job definitions remain out of scope
and are noted in docs/services/batch.md.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-09-14 23:02:04 -04:00
1 parent b2b43dfb3c
commit 74d4782b51
13 files changed
+1511 -78

No files matched your search

+55 -4
View File
@@ -17,7 +17,7 @@ Floci Batch implements the AWS Batch control plane for local integration tests.
| `UpdateJobQueue` | `POST /v1/updatejobqueue` | Update a job queue's state, priority, and compute environment order |
| `DeleteJobQueue` | `POST /v1/deletejobqueue` | Delete a `DISABLED` job queue; deleting a missing queue is a no-op |
| `DescribeJobQueues` | `POST /v1/describejobqueues` | Describe all or selected job queues |
| `RegisterJobDefinition` | `POST /v1/registerjobdefinition` | Register a revisioned container job definition |
| `RegisterJobDefinition` | `POST /v1/registerjobdefinition` | Register a revisioned `container` or `multinode` job definition |
| `DeregisterJobDefinition` | `POST /v1/deregisterjobdefinition` | Mark a job definition revision inactive |
| `DescribeJobDefinitions` | `POST /v1/describejobdefinitions` | List job definitions by name, ARN, revision, and status |
| `SubmitJob` | `POST /v1/submitjob` | Submit a local Batch job |
@@ -45,11 +45,13 @@ Supported `SubmitJob` fields:
- `parameters`
- `containerOverrides.command`
- `containerOverrides.environment`
- `arrayProperties.size` (array jobs)
- `nodeOverrides.numNodes`, `nodeOverrides.nodePropertyOverrides` (multi-node parallel jobs)
- `timeout.attemptDurationSeconds`
- `retryStrategy.attempts`
- `tags`
`containerOverrides.command` replaces the job-definition command. Command entries like `Ref::inputKey` are resolved from the merged parameter map before execution. Submit-time environment overrides merge over job-definition environment variables.
`containerOverrides.command` replaces the job-definition command. Command entries like `Ref::inputKey` are resolved from the merged parameter map before execution. Submit-time environment overrides merge over job-definition environment variables. `dependsOn` (job dependencies) is not supported.
Jobs move through these local statuses:
@@ -59,6 +61,32 @@ SUBMITTED -> PENDING -> RUNNABLE -> STARTING -> RUNNING -> SUCCEEDED|FAILED
Driving every immediate-mode job through `PENDING` is a local simplification for tests. AWS may skip that state when there are no dependency or capacity waits.
### Array jobs
Submitting with `arrayProperties.size` (2-10,000) fans out one child job per index, sharing the
parent's job name and running through the same execution pipeline as a normal job (each child gets
its own Docker container in `docker` mode). The parent's `status` and `arrayProperties.statusSummary`
are computed live from its children on every `DescribeJobs`/`ListJobs` call rather than stored and
updated incrementally, so there is nothing to race when many children finish concurrently. A
queue-level `ListJobs` shows one entry per array job (the parent); pass `arrayJobId` to list its
children. `TerminateJob`/`CancelJob` cascade is not applicable since neither operation is
implemented (see Limitations).
### Multi-node parallel (MNP) jobs
A job definition registered with `"type": "multinode"` and `nodeProperties` (`numNodes`, `mainNode`,
`nodeRangeProperties`) becomes an MNP job definition; `SubmitJob` against it (with optional
`nodeOverrides`) runs one container per node concurrently in `docker` mode, each with
`AWS_BATCH_JOB_NODE_INDEX`, `AWS_BATCH_JOB_MAIN_NODE_INDEX`, and `AWS_BATCH_JOB_NUM_NODES` set. The
job's status, retry decision, and `startedAt`/`stoppedAt`/`statusReason` are all determined solely by
the **main node** (matching AWS: a child node failing does not fail or retry the job). Every node
still runs to completion rather than being stopped early (see Limitations below for the two cases
this affects). `DescribeJobs`/queue-level `ListJobs` return one entry for the whole
job (with `nodeProperties`, no per-node `container`); pass `multiNodeJobId` to `ListJobs` for a
one-entry-per-node breakdown with each node's own `container` and `nodeProperties.nodeIndex`.
`containerOverrides` and array jobs are not supported on MNP job definitions; use `nodeOverrides`
instead.
## EventBridge
EventBridge targets whose ARN points at a Batch job queue can include:
@@ -103,6 +131,29 @@ IAM roles, VPC fields, Fargate declarations, log configuration, storage, and res
- No IAM enforcement.
- No VPC/subnet/security-group simulation.
- No AWS-faithful capacity scheduling.
- No array job fan-out or multi-node jobs.
- `CancelJob` and `TerminateJob` are not implemented.
- No job dependencies (`dependsOn`).
- `CancelJob` and `TerminateJob` are not implemented, so there is no way to cancel/terminate an
array job's children or an MNP job's nodes either — this is the same pre-existing gap as for a
regular job, not something array/MNP jobs make worse.
- EventBridge input transformers work through the existing EventBridge target input path; full Batch-specific input-transformer parity is not implemented.
- An MNP job does not finish the instant its main node exits. AWS stops the job (and its remaining
child nodes) as soon as the main node exits; Floci instead waits for every node's container to
exit before scoring the attempt, so a child that outlives the main node keeps the job `RUNNING`
longer than AWS would. Closing this needs a way for `BatchDockerRunner` to stop one node's
container from outside that node's own run loop, which does not exist yet.
**Known follow-ups on the array/MNP surface** (not required for `SubmitJob`/`DescribeJobs`/`ListJobs`
correctness, deliberately deferred):
- `submitFromEventBridge` does not forward `arrayProperties`/`nodeOverrides` from a rule target's
`BatchParameters`, even though `ArrayProperties` is accepted and echoed back as target metadata
(see EventBridge section above). An EventBridge-triggered Batch job cannot fan out as an array or
run as MNP today; only a direct `SubmitJob` call can.
- CloudFormation's `AWS::Batch::JobDefinition` provisioner only registers `container`-type job
definitions; there is no way to provision a `multinode` job definition via CloudFormation, only
via a direct `RegisterJobDefinition` call.
- `ListJobs` with `arrayJobId` ignores the `filters` parameter (only `jobStatus` is honored for
children) — matches AWS's own note that filters don't apply to child jobs, but it means array
children can't be filtered by `JOB_NAME`/`JOB_DEFINITION`/etc.
- `ListJobs` with `multiNodeJobId` has no pagination (`maxResults`/`nextToken`); it always returns
every node in one response.
@@ -13,6 +13,7 @@ import io.github.hectorvent.floci.core.common.docker.ContainerSpec;
import io.github.hectorvent.floci.core.common.docker.ContainerStorageHelper;
import io.github.hectorvent.floci.services.batch.model.BatchJob;
import io.github.hectorvent.floci.services.batch.model.BatchKeyValue;
import io.github.hectorvent.floci.services.batch.model.BatchNodeExecution;
import io.github.hectorvent.floci.services.batch.model.BatchResourceRequirement;
import io.github.hectorvent.floci.services.batch.model.BatchRunResult;
import jakarta.enterprise.context.ApplicationScoped;
@@ -56,21 +57,44 @@ public class BatchDockerRunner implements ContainerTeardown {
}
public BatchRunResult run(BatchJob job, int attemptNumber) {
long startedAt = System.currentTimeMillis();
String logStreamName = logStreamer.generateLogStreamName(
job.getJobDefinitionName() + "/default/" + job.getJobId());
String containerName = ContainerStorageHelper.dockerName(config, "floci-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());
}
// A distinct inFlightContainers key per node, since nodes of one job run concurrently.
public BatchRunResult run(BatchJob job, int attemptNumber, BatchNodeExecution node) {
String logStreamName = logStreamer.generateLogStreamName(
job.getJobDefinitionName() + "/default/" + job.getJobId() + "/" + node.getNodeIndex());
String containerName = ContainerStorageHelper.dockerName(config,
"floci-batch-" + job.getJobId() + "-" + attemptNumber + "-node" + node.getNodeIndex());
String inFlightKey = job.getJobId() + "#node" + node.getNodeIndex();
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());
}
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) {
long startedAt = System.currentTimeMillis();
Closeable logHandle = null;
String containerId = null;
try {
if (job.getContainerImage() == null || job.getContainerImage().isBlank()) {
return failed(startedAt, logStreamName, "Job definition container image is missing");
if (image == null || image.isBlank()) {
return failed(startedAt, logStreamName, missingImageMessage);
}
ContainerBuilder.Builder builder = containerBuilder.newContainer(job.getContainerImage())
ContainerBuilder.Builder builder = containerBuilder.newContainer(image)
.withName(containerName)
.withEnv(buildEnvironment(job, attemptNumber))
.withEnv(env)
.withDockerNetwork(config.services().batch().dockerNetwork())
.withHostDockerInternalOnLinux()
.withEmbeddedDns()
@@ -78,20 +102,19 @@ public class BatchDockerRunner implements ContainerTeardown {
.withLabels(ContainerStorageHelper.resourceIdentityLabels(
"batch", job.getJobId(), job.getAccountId(), job.getRegion()));
if (job.getResolvedCommand() != null && !job.getResolvedCommand().isEmpty()) {
builder.withCmd(job.getResolvedCommand());
if (command != null && !command.isEmpty()) {
builder.withCmd(command);
}
applyResourceRequirements(builder, job);
applyResourceRequirements(builder, resourceRequirements, job.getJobId());
ContainerSpec spec = builder.build();
containerId = lifecycleManager.createAndStart(spec).containerId();
inFlightContainers.put(job.getJobId(), containerId);
logHandle = logStreamer.attach(containerId, LOG_GROUP, logStreamName, job.getRegion(),
"batch:" + job.getJobName() + ":" + job.getJobId());
inFlightContainers.put(inFlightKey, containerId);
logHandle = logStreamer.attach(containerId, LOG_GROUP, logStreamName, job.getRegion(), logSourceLabel);
Integer exitCode = waitForExit(containerId, timeout(job));
long stoppedAt = System.currentTimeMillis();
releaseAndStop(job.getJobId(), containerId, logHandle);
releaseAndStop(inFlightKey, containerId, logHandle);
if (exitCode == null) {
return new BatchRunResult(137, "Job timed out", logStreamName, startedAt, stoppedAt, true);
}
@@ -100,7 +123,7 @@ public class BatchDockerRunner implements ContainerTeardown {
} catch (Exception e) {
LOG.warnv("Batch Docker job {0} failed: {1}", job.getJobId(), e.getMessage());
if (containerId != null) {
releaseAndStop(job.getJobId(), containerId, logHandle);
releaseAndStop(inFlightKey, containerId, logHandle);
}
return failed(startedAt, logStreamName, e.getMessage());
}
@@ -143,6 +166,25 @@ public class BatchDockerRunner implements ContainerTeardown {
}
private List<String> buildEnvironment(BatchJob job, int attemptNumber) {
List<String> env = baseEnvironment(job, attemptNumber);
appendEnvironment(env, job.getResolvedEnvironment());
return env;
}
private List<String> buildNodeEnvironment(BatchJob job, int attemptNumber, BatchNodeExecution node) {
List<String> env = baseEnvironment(job, attemptNumber);
int numNodes = job.getNodeProperties() != null && job.getNodeProperties().getNumNodes() != null
? job.getNodeProperties().getNumNodes() : 1;
int mainNode = job.getNodeProperties() != null && job.getNodeProperties().getMainNode() != null
? job.getNodeProperties().getMainNode() : 0;
env.add("AWS_BATCH_JOB_NODE_INDEX=" + node.getNodeIndex());
env.add("AWS_BATCH_JOB_MAIN_NODE_INDEX=" + mainNode);
env.add("AWS_BATCH_JOB_NUM_NODES=" + numNodes);
appendEnvironment(env, node.getResolvedEnvironment());
return env;
}
private List<String> baseEnvironment(BatchJob job, int attemptNumber) {
List<String> env = new ArrayList<>();
env.add("AWS_REGION=" + job.getRegion());
env.add("AWS_DEFAULT_REGION=" + job.getRegion());
@@ -158,14 +200,18 @@ public class BatchDockerRunner implements ContainerTeardown {
env.add("AWS_BATCH_JOB_ATTEMPT=" + attemptNumber);
env.add("AWS_BATCH_JQ_NAME=" + job.getJobQueueName());
env.add("AWS_BATCH_CE_NAME=local");
if (job.getResolvedEnvironment() != null) {
for (BatchKeyValue kv : job.getResolvedEnvironment()) {
env.add(kv.getName() + "=" + (kv.getValue() != null ? kv.getValue() : ""));
}
}
return env;
}
private void appendEnvironment(List<String> env, List<BatchKeyValue> resolvedEnvironment) {
if (resolvedEnvironment == null) {
return;
}
for (BatchKeyValue kv : resolvedEnvironment) {
env.add(kv.getName() + "=" + (kv.getValue() != null ? kv.getValue() : ""));
}
}
String resolveEndpointHostname() {
if (containerDetector.isRunningInContainer()) {
return config.hostname().orElse(EmbeddedDnsServer.DEFAULT_SUFFIX);
@@ -173,11 +219,12 @@ public class BatchDockerRunner implements ContainerTeardown {
return "host.docker.internal";
}
private void applyResourceRequirements(ContainerBuilder.Builder builder, BatchJob job) {
if (job.getResourceRequirements() == null) {
private void applyResourceRequirements(ContainerBuilder.Builder builder,
List<BatchResourceRequirement> resourceRequirements, String jobId) {
if (resourceRequirements == null) {
return;
}
for (BatchResourceRequirement requirement : job.getResourceRequirements()) {
for (BatchResourceRequirement requirement : resourceRequirements) {
if (!"MEMORY".equalsIgnoreCase(requirement.getType()) || requirement.getValue() == null) {
continue;
}
@@ -185,7 +232,7 @@ public class BatchDockerRunner implements ContainerTeardown {
builder.withMemoryMb(Integer.parseInt(requirement.getValue()));
} catch (NumberFormatException e) {
LOG.warnv("Ignoring invalid Batch MEMORY resource value for job {0}: {1}",
job.getJobId(), requirement.getValue());
jobId, requirement.getValue());
}
return;
}
@@ -22,6 +22,11 @@ import io.github.hectorvent.floci.services.batch.model.BatchJob;
import io.github.hectorvent.floci.services.batch.model.BatchJobDefinition;
import io.github.hectorvent.floci.services.batch.model.BatchJobQueue;
import io.github.hectorvent.floci.services.batch.model.BatchKeyValue;
import io.github.hectorvent.floci.services.batch.model.BatchNodeExecution;
import io.github.hectorvent.floci.services.batch.model.BatchNodeOverrides;
import io.github.hectorvent.floci.services.batch.model.BatchNodeProperties;
import io.github.hectorvent.floci.services.batch.model.BatchNodePropertyOverride;
import io.github.hectorvent.floci.services.batch.model.BatchNodeRangeProperty;
import io.github.hectorvent.floci.services.batch.model.BatchResourceRequirement;
import io.github.hectorvent.floci.services.batch.model.BatchRetryStrategy;
import io.github.hectorvent.floci.services.batch.model.BatchRunResult;
@@ -37,6 +42,7 @@ import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
@@ -51,7 +57,9 @@ public class BatchService {
private static final int FILTERED_MAX_RESULTS = 100;
private static final int MAX_TAGS = 50;
private static final Pattern JOB_NAME_PATTERN = Pattern.compile("[A-Za-z0-9][A-Za-z0-9_-]{0,127}");
private static final Set<String> SUPPORTED_JOB_DEFINITION_TYPES = Set.of("container");
private static final Set<String> SUPPORTED_JOB_DEFINITION_TYPES = Set.of("container", "multinode");
private static final int MIN_ARRAY_SIZE = 2;
private static final int MAX_ARRAY_SIZE = 10000;
private static final Set<String> SUPPORTED_COMPUTE_ENVIRONMENT_TYPES = Set.of("MANAGED", "UNMANAGED");
private static final Set<String> SUPPORTED_COMPUTE_ENVIRONMENT_STATES = Set.of("ENABLED", "DISABLED");
private static final Set<String> SUPPORTED_LIST_FILTERS = Set.of(
@@ -329,11 +337,6 @@ public class BatchService {
String name = requiredText(request, "jobDefinitionName");
String type = requiredText(request, "type");
validateJobDefinitionType(type);
BatchContainerProperties container = tree(request.path("containerProperties"), BatchContainerProperties.class);
if (container == null) {
throw client("containerProperties is required for container job definitions");
}
validateEnvironment(container.getEnvironment());
int revision = nextRevision(name);
BatchJobDefinition def = new BatchJobDefinition();
@@ -342,7 +345,21 @@ public class BatchService {
def.setJobDefinitionArn(arn(region, "job-definition/" + name + ":" + revision));
def.setStatus("ACTIVE");
def.setType(type);
def.setContainerProperties(container);
if ("multinode".equals(type)) {
if (request.hasNonNull("containerProperties")) {
throw client("containerProperties is not supported for multinode job definitions; use nodeProperties");
}
BatchNodeProperties nodeProperties = tree(request.path("nodeProperties"), BatchNodeProperties.class);
validateNodeProperties(nodeProperties);
def.setNodeProperties(nodeProperties);
} else {
BatchContainerProperties container = tree(request.path("containerProperties"), BatchContainerProperties.class);
if (container == null) {
throw client("containerProperties is required for container job definitions");
}
validateEnvironment(container.getEnvironment());
def.setContainerProperties(container);
}
def.setParameters(stringMap(request.path("parameters")));
def.setRetryStrategy(tree(request.path("retryStrategy"), BatchRetryStrategy.class));
validateRetryStrategy(def.getRetryStrategy());
@@ -417,15 +434,164 @@ public class BatchService {
throw client("Job definition is not ACTIVE: " + def.getJobDefinitionArn());
}
Integer arraySize = parseArraySize(request);
boolean multiNode = "multinode".equals(def.getType());
if (arraySize != null && multiNode) {
throw client("Array jobs are not supported for multi-node parallel job definitions");
}
Map<String, String> parameters = new LinkedHashMap<>(def.getParameters());
parameters.putAll(stringMap(request.path("parameters")));
if (multiNode) {
return submitMultiNodeJob(request, region, jobName, queue, def, parameters);
}
if (arraySize != null) {
return submitArrayJob(request, region, jobName, queue, def, parameters, arraySize);
}
BatchJob job = buildJob(request, region, jobName, queue, def, parameters, UUID.randomUUID().toString());
putJob(job);
dispatchRun(job);
return submitJobResponse(job);
}
private ObjectNode submitArrayJob(JsonNode request, String region, String jobName, BatchJobQueue queue,
BatchJobDefinition def, Map<String, String> parameters, int size) {
BatchJob parent = new BatchJob();
parent.setJobId(UUID.randomUUID().toString());
parent.setJobArn(arn(region, "job/" + parent.getJobId()));
parent.setJobName(jobName);
parent.setJobQueue(queue.getJobQueueArn());
parent.setJobQueueName(queue.getJobQueueName());
parent.setJobDefinition(def.getJobDefinitionArn());
parent.setJobDefinitionName(def.getJobDefinitionName());
parent.setJobDefinitionRevision(def.getRevision());
parent.setStatus(BatchStatus.SUBMITTED.name());
parent.setCreatedAt(now());
parent.setParameters(parameters);
parent.setArraySize(size);
parent.setRetryStrategy(treeOrDefault(request.path("retryStrategy"), def.getRetryStrategy(), BatchRetryStrategy.class));
validateRetryStrategy(parent.getRetryStrategy());
parent.setTimeout(treeOrDefault(request.path("timeout"), def.getTimeout(), BatchTimeout.class));
validateTimeout(parent.getTimeout());
parent.setTags(stringMap(request.path("tags")));
validateTags(parent.getTags());
parent.setRegion(region);
parent.setAccountId(regionResolver.getAccountId());
// Build children outside the lock; write them under one lock so no reader sees a partial array.
List<BatchJob> children = new ArrayList<>(size);
for (int index = 0; index < size; index++) {
BatchJob child = buildJob(request, region, jobName, queue, def, parameters, parent.getJobId() + ":" + index);
child.setArrayJobId(parent.getJobId());
child.setArrayIndex(index);
children.add(child);
}
synchronized (this) {
putJob(parent);
for (BatchJob child : children) {
putJob(child);
}
}
for (BatchJob child : children) {
dispatchRun(child);
}
return submitJobResponse(parent);
}
private ObjectNode submitMultiNodeJob(JsonNode request, String region, String jobName, BatchJobQueue queue,
BatchJobDefinition def, Map<String, String> parameters) {
if (request.hasNonNull("containerOverrides")) {
throw client("containerOverrides is not supported for multi-node parallel jobs; use nodeOverrides");
}
BatchNodeProperties defNodeProperties = def.getNodeProperties();
if (defNodeProperties == null) {
throw client("Job definition is missing nodeProperties: " + def.getJobDefinitionArn());
}
BatchNodeOverrides overrides = tree(request.path("nodeOverrides"), BatchNodeOverrides.class);
int numNodes = resolveEffectiveNumNodes(defNodeProperties, overrides);
int mainNode = defNodeProperties.getMainNode();
BatchNodeProperties effective = new BatchNodeProperties();
effective.setNumNodes(numNodes);
effective.setMainNode(mainNode);
effective.setNodeRangeProperties(defNodeProperties.getNodeRangeProperties());
BatchJob job = new BatchJob();
job.setJobId(UUID.randomUUID().toString());
job.setJobArn(arn(region, "job/" + job.getJobId()));
job.setJobName(jobName);
job.setJobQueue(queue.getJobQueueArn());
job.setJobQueueName(queue.getJobQueueName());
job.setJobDefinition(def.getJobDefinitionArn());
job.setJobDefinitionName(def.getJobDefinitionName());
job.setJobDefinitionRevision(def.getRevision());
job.setStatus(BatchStatus.SUBMITTED.name());
job.setCreatedAt(now());
job.setParameters(parameters);
job.setNodeProperties(effective);
job.setRetryStrategy(treeOrDefault(request.path("retryStrategy"), def.getRetryStrategy(), BatchRetryStrategy.class));
validateRetryStrategy(job.getRetryStrategy());
job.setTimeout(treeOrDefault(request.path("timeout"), def.getTimeout(), BatchTimeout.class));
validateTimeout(job.getTimeout());
job.setTags(stringMap(request.path("tags")));
validateTags(job.getTags());
job.setRegion(region);
job.setAccountId(regionResolver.getAccountId());
job.setNodeExecutions(resolveNodeExecutions(effective, overrides, parameters, mainNode, numNodes));
putJob(job);
if (shouldRunDocker()) {
Thread.startVirtualThread(() -> runMultiNodeJob(job.getAccountId(), job.getJobId()));
} else {
runMultiNodeJob(job.getAccountId(), job.getJobId());
}
return submitJobResponse(job);
}
private List<BatchNodeExecution> resolveNodeExecutions(BatchNodeProperties nodeProperties,
BatchNodeOverrides overrides,
Map<String, String> parameters,
int mainNode, int numNodes) {
List<BatchNodeExecution> executions = new ArrayList<>(numNodes);
for (int nodeIndex = 0; nodeIndex < numNodes; nodeIndex++) {
BatchContainerProperties nodeContainer = resolveNodeRangeContainer(nodeProperties, nodeIndex, numNodes);
if (nodeContainer == null) {
throw client("No nodeRangeProperties cover node index " + nodeIndex);
}
BatchContainerOverrides nodeOverride = resolveNodeOverrideForIndex(overrides, nodeIndex, numNodes);
validateEnvironment(nodeOverride != null ? nodeOverride.getEnvironment() : null);
List<String> command = nodeOverride != null
&& nodeOverride.getCommand() != null && !nodeOverride.getCommand().isEmpty()
? nodeOverride.getCommand()
: nodeContainer.getCommand();
List<BatchResourceRequirement> resourceRequirements = nodeOverride != null
&& nodeOverride.getResourceRequirements() != null && !nodeOverride.getResourceRequirements().isEmpty()
? nodeOverride.getResourceRequirements()
: nodeContainer.getResourceRequirements();
BatchNodeExecution execution = new BatchNodeExecution();
execution.setNodeIndex(nodeIndex);
execution.setMainNode(nodeIndex == mainNode);
execution.setContainerImage(nodeContainer.getImage());
execution.setResolvedCommand(resolveCommand(command, parameters));
execution.setResolvedEnvironment(resolveEnvironment(nodeContainer.getEnvironment(),
nodeOverride != null ? nodeOverride.getEnvironment() : null));
execution.setResourceRequirements(resourceRequirements);
executions.add(execution);
}
return executions;
}
private BatchJob buildJob(JsonNode request, String region, String jobName, BatchJobQueue queue,
BatchJobDefinition def, Map<String, String> parameters, String jobId) {
BatchContainerOverrides overrides = tree(request.path("containerOverrides"), BatchContainerOverrides.class);
if (overrides == null) {
overrides = new BatchContainerOverrides();
}
validateEnvironment(overrides.getEnvironment());
Map<String, String> parameters = new LinkedHashMap<>(def.getParameters());
parameters.putAll(stringMap(request.path("parameters")));
BatchContainerProperties container = def.getContainerProperties() != null
? def.getContainerProperties() : new BatchContainerProperties();
List<String> command = overrides.getCommand() != null && !overrides.getCommand().isEmpty()
@@ -433,8 +599,8 @@ public class BatchService {
: container.getCommand();
BatchJob job = new BatchJob();
job.setJobId(UUID.randomUUID().toString());
job.setJobArn(arn(region, "job/" + job.getJobId()));
job.setJobId(jobId);
job.setJobArn(arn(region, "job/" + jobId));
job.setJobName(jobName);
job.setJobQueue(queue.getJobQueueArn());
job.setJobQueueName(queue.getJobQueueName());
@@ -457,13 +623,18 @@ public class BatchService {
job.setRegion(region);
job.setAccountId(regionResolver.getAccountId());
job.setContainerImage(container.getImage());
putJob(job);
return job;
}
private void dispatchRun(BatchJob job) {
if (shouldRunDocker()) {
Thread.startVirtualThread(() -> runJob(job.getAccountId(), job.getJobId()));
} else {
runJob(job.getAccountId(), job.getJobId());
}
}
private ObjectNode submitJobResponse(BatchJob job) {
ObjectNode out = objectMapper.createObjectNode();
out.put("jobArn", job.getJobArn());
out.put("jobId", job.getJobId());
@@ -471,6 +642,18 @@ public class BatchService {
return out;
}
private Integer parseArraySize(JsonNode request) {
JsonNode arrayProperties = request.path("arrayProperties");
if (!arrayProperties.isObject() || !arrayProperties.hasNonNull("size")) {
return null;
}
int size = arrayProperties.path("size").asInt();
if (size < MIN_ARRAY_SIZE || size > MAX_ARRAY_SIZE) {
throw client("arrayProperties.size must be between " + MIN_ARRAY_SIZE + " and " + MAX_ARRAY_SIZE);
}
return size;
}
public synchronized ObjectNode describeJobs(JsonNode request) {
List<String> ids = stringList(request.path("jobs"));
if (ids.isEmpty()) {
@@ -489,27 +672,38 @@ public class BatchService {
}
public synchronized ObjectNode listJobs(JsonNode request) {
if (!request.hasNonNull("jobQueue")) {
throw client("jobQueue is required");
String jobQueueRef = textOrNull(request, "jobQueue");
String arrayJobId = textOrNull(request, "arrayJobId");
String multiNodeJobId = textOrNull(request, "multiNodeJobId");
int selectorCount = (jobQueueRef != null ? 1 : 0) + (arrayJobId != null ? 1 : 0)
+ (multiNodeJobId != null ? 1 : 0);
if (selectorCount != 1) {
throw client("Exactly one of jobQueue, arrayJobId, or multiNodeJobId is required");
}
if (request.hasNonNull("arrayJobId") || request.hasNonNull("multiNodeJobId")) {
throw client("arrayJobId and multiNodeJobId are not supported");
if (arrayJobId != null) {
return listArrayChildren(arrayJobId, request);
}
BatchJobQueue queue = resolveJobQueue(requiredText(request, "jobQueue"));
if (multiNodeJobId != null) {
return listMultiNodeJobNodes(multiNodeJobId);
}
BatchJobQueue queue = resolveJobQueue(jobQueueRef);
String status = textOrNull(request, "jobStatus");
ListFilter filter = listFilter(request);
String effectiveStatus = filter == null && status == null ? BatchStatus.RUNNING.name() : status;
String effectiveStatusFilter = filter == null && status == null ? BatchStatus.RUNNING.name() : status;
int maxResults = request.hasNonNull("maxResults")
? Math.max(1, Math.min(filter == null ? DEFAULT_MAX_RESULTS : FILTERED_MAX_RESULTS,
request.path("maxResults").asInt()))
: filter == null ? DEFAULT_MAX_RESULTS : FILTERED_MAX_RESULTS;
int offset = parseNextToken(textOrNull(request, "nextToken"));
// A queue-level listing shows one entry per array job (the parent), matching AWS.
List<BatchJob> jobs = jobStore.scan(k -> true).stream()
.filter(job -> queue.getJobQueueArn().equals(job.getJobQueue()))
.filter(job -> job.getArrayIndex() == null)
.filter(job -> (filter != null && !"SHARE_IDENTIFIER".equals(filter.name()))
|| effectiveStatus == null
|| effectiveStatus.equals(job.getStatus()))
|| effectiveStatusFilter == null
|| effectiveStatusFilter.equals(effectiveStatus(job)))
.filter(job -> matchesListFilter(job, filter))
.sorted(Comparator.comparingLong(BatchJob::getCreatedAt)
.reversed()
@@ -529,6 +723,49 @@ public class BatchService {
return out;
}
// Only jobStatus is honored here; AWS's filters parameter doesn't apply to array children.
private ObjectNode listArrayChildren(String arrayJobId, JsonNode request) {
String status = textOrNull(request, "jobStatus");
int maxResults = request.hasNonNull("maxResults")
? Math.max(1, Math.min(FILTERED_MAX_RESULTS, request.path("maxResults").asInt()))
: FILTERED_MAX_RESULTS;
int offset = parseNextToken(textOrNull(request, "nextToken"));
List<BatchJob> children = jobStore.scan(k -> true).stream()
.filter(job -> arrayJobId.equals(job.getArrayJobId()))
.filter(job -> status == null || status.equals(job.getStatus()))
.sorted(Comparator.comparingInt(BatchJob::getArrayIndex))
.toList();
ArrayNode summaries = objectMapper.createArrayNode();
int end = Math.min(children.size(), offset + maxResults);
for (int i = offset; i < end; i++) {
summaries.add(jobSummary(children.get(i)));
}
ObjectNode out = objectMapper.createObjectNode();
out.set("jobSummaryList", summaries);
if (end < children.size()) {
out.put("nextToken", String.valueOf(end));
}
return out;
}
// No pagination: realistic node counts are small, so every node is always returned.
private ObjectNode listMultiNodeJobNodes(String jobId) {
ArrayNode summaries = objectMapper.createArrayNode();
getJob(jobId).ifPresent(job -> {
if (job.getNodeProperties() != null) {
for (BatchNodeExecution execution : job.getNodeExecutions()) {
summaries.add(nodeJobSummary(job, execution));
}
}
});
ObjectNode out = objectMapper.createObjectNode();
out.set("jobSummaryList", summaries);
return out;
}
// Does not forward BatchParameters.ArrayProperties/NodeOverrides: always a plain single job.
public void submitFromEventBridge(String jobQueueArn, String jobDefinition, String jobName,
Map<String, String> parameters, JsonNode retryStrategy, String region) {
ObjectNode request = objectMapper.createObjectNode();
@@ -636,6 +873,123 @@ public class BatchService {
return false;
}
private void runMultiNodeJob(String accountId, String jobId) {
try {
BatchJob job = getJobForAccount(accountId, jobId).orElse(null);
if (job == null) {
return;
}
int maxAttempts = maxAttempts(job);
for (int attemptNumber = 1; attemptNumber <= maxAttempts; attemptNumber++) {
transition(accountId, jobId, BatchStatus.PENDING, null, false);
sleepQuietly();
transition(accountId, jobId, BatchStatus.RUNNABLE, null, false);
sleepQuietly();
transition(accountId, jobId, BatchStatus.STARTING, null, false);
sleepQuietly();
transition(accountId, jobId, BatchStatus.RUNNING, null, true);
BatchJob attemptJob = getJobForAccount(accountId, jobId).orElse(null);
if (attemptJob == null) {
return;
}
List<BatchRunResult> nodeResults = runNodes(attemptJob, attemptNumber);
if (finishMultiNodeAttempt(accountId, jobId, nodeResults, attemptNumber >= maxAttempts)) {
return;
}
}
} catch (Exception e) {
LOG.warnv("Batch multi-node job {0} failed while running: {1}", jobId, e.getMessage());
failJob(accountId, jobId, e.getMessage());
}
}
// Nodes run concurrently to completion; not preempted on failure (no cancellation hook).
private List<BatchRunResult> runNodes(BatchJob job, int attemptNumber) {
List<BatchNodeExecution> executions = job.getNodeExecutions();
if (!shouldRunDocker()) {
long started = job.getStartedAt() != null ? job.getStartedAt() : now();
List<BatchRunResult> results = new ArrayList<>(executions.size());
for (int i = 0; i < executions.size(); i++) {
sleepQuietly();
results.add(new BatchRunResult(0, null,
job.getJobDefinitionName() + "/default/" + job.getJobId() + "/" + i, started, now(), false));
}
return results;
}
List<BatchRunResult> results = new ArrayList<>(executions.size());
for (int i = 0; i < executions.size(); i++) {
results.add(null);
}
List<Thread> threads = new ArrayList<>(executions.size());
for (int i = 0; i < executions.size(); i++) {
int nodeIndex = i;
threads.add(Thread.startVirtualThread(() -> {
BatchRunResult result = dockerRunner.run(job, attemptNumber, executions.get(nodeIndex));
synchronized (results) {
results.set(nodeIndex, result);
}
}));
}
for (Thread thread : threads) {
try {
thread.join();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
return results;
}
// The main node alone determines the attempt's outcome; a failing child never fails or retries the job.
private synchronized boolean finishMultiNodeAttempt(String accountId, String jobId,
List<BatchRunResult> nodeResults, boolean finalAttempt) {
BatchJob job = getJobForAccount(accountId, jobId).orElse(null);
if (job == null) {
return true;
}
List<BatchNodeExecution> executions = job.getNodeExecutions();
BatchRunResult mainResult = null;
for (int i = 0; i < executions.size(); i++) {
BatchRunResult result = nodeResults.get(i);
BatchAttemptContainer container = new BatchAttemptContainer();
container.setExitCode(result.exitCode());
container.setReason(result.reason());
container.setLogStreamName(result.logStreamName());
executions.get(i).setContainer(container);
if (executions.get(i).isMainNode()) {
mainResult = result;
}
}
if (mainResult == null) {
throw new IllegalStateException("No main node among node executions for job " + jobId);
}
BatchAttempt attempt = new BatchAttempt();
attempt.setStartedAt(mainResult.startedAt());
attempt.setStoppedAt(mainResult.stoppedAt());
attempt.setStatusReason(mainResult.reason());
job.getAttempts().add(attempt);
if (mainResult.exitCode() == 0) {
job.setStoppedAt(mainResult.stoppedAt());
job.setStatus(BatchStatus.SUCCEEDED.name());
job.setStatusReason("Job completed successfully");
putJobForAccount(accountId, job);
return true;
}
if (mainResult.timedOut() || finalAttempt) {
job.setStoppedAt(mainResult.stoppedAt());
job.setStatus(BatchStatus.FAILED.name());
job.setStatusReason(mainResult.reason());
putJobForAccount(accountId, job);
return true;
}
job.setStatus(BatchStatus.RUNNABLE.name());
job.setStatusReason("Attempt failed; retrying");
putJobForAccount(accountId, job);
return false;
}
private int maxAttempts(BatchJob job) {
if (job.getRetryStrategy() == null || job.getRetryStrategy().getAttempts() == null) {
return 1;
@@ -832,7 +1186,7 @@ public class BatchService {
private void validateJobDefinitionType(String type) {
if (!SUPPORTED_JOB_DEFINITION_TYPES.contains(type)) {
throw client("Only container job definitions are supported");
throw client("Only container and multinode job definitions are supported");
}
}
@@ -923,14 +1277,189 @@ public class BatchService {
}
}
private void validateNodeProperties(BatchNodeProperties nodeProperties) {
if (nodeProperties == null) {
throw client("nodeProperties is required for multinode job definitions");
}
Integer numNodes = nodeProperties.getNumNodes();
Integer mainNode = nodeProperties.getMainNode();
if (numNodes == null || numNodes < 1) {
throw client("nodeProperties.numNodes must be at least 1");
}
if (mainNode == null || mainNode < 0 || mainNode >= numNodes) {
throw client("nodeProperties.mainNode must be between 0 and numNodes - 1");
}
List<BatchNodeRangeProperty> ranges = nodeProperties.getNodeRangeProperties();
if (ranges == null || ranges.isEmpty()) {
throw client("nodeProperties.nodeRangeProperties is required");
}
boolean[] covered = new boolean[numNodes];
for (BatchNodeRangeProperty range : ranges) {
int[] bounds = parseTargetNodes(range.getTargetNodes(), numNodes);
for (int i = bounds[0]; i <= bounds[1]; i++) {
covered[i] = true;
}
if (range.getContainer() == null || range.getContainer().getImage() == null
|| range.getContainer().getImage().isBlank()) {
throw client("nodeRangeProperties targeting " + range.getTargetNodes()
+ " must specify a container image");
}
validateEnvironment(range.getContainer().getEnvironment());
}
for (int i = 0; i < numNodes; i++) {
if (!covered[i]) {
throw client("nodeRangeProperties must cover every node index from 0 to numNodes - 1; "
+ "node " + i + " is not covered");
}
}
}
// Parses a node range like "0:3", ":3" (start=0), "4:" (end=numNodes-1), or a bare index.
private int[] parseTargetNodes(String targetNodes, int numNodes) {
if (targetNodes == null || targetNodes.isBlank()) {
throw client("targetNodes is required for each node range");
}
int colon = targetNodes.indexOf(':');
int start;
int end;
try {
if (colon < 0) {
start = Integer.parseInt(targetNodes.trim());
end = start;
} else {
String startText = targetNodes.substring(0, colon).trim();
String endText = targetNodes.substring(colon + 1).trim();
start = startText.isEmpty() ? 0 : Integer.parseInt(startText);
end = endText.isEmpty() ? numNodes - 1 : Integer.parseInt(endText);
}
} catch (NumberFormatException e) {
throw client("Invalid targetNodes range: " + targetNodes);
}
if (start < 0 || end < start || end > numNodes - 1) {
throw client("targetNodes range out of bounds: " + targetNodes);
}
return new int[]{start, end};
}
// The last range in submission order that covers the index wins (AWS's "nested ranges override").
private BatchContainerProperties resolveNodeRangeContainer(BatchNodeProperties nodeProperties,
int nodeIndex, int numNodes) {
BatchContainerProperties resolved = null;
for (BatchNodeRangeProperty range : nodeProperties.getNodeRangeProperties()) {
int[] bounds = parseTargetNodes(range.getTargetNodes(), numNodes);
if (nodeIndex >= bounds[0] && nodeIndex <= bounds[1]) {
resolved = range.getContainer();
}
}
return resolved;
}
private BatchContainerOverrides resolveNodeOverrideForIndex(BatchNodeOverrides overrides,
int nodeIndex, int numNodes) {
if (overrides == null || overrides.getNodePropertyOverrides() == null) {
return null;
}
BatchContainerOverrides resolved = null;
for (BatchNodePropertyOverride override : overrides.getNodePropertyOverrides()) {
int[] bounds = parseTargetNodes(override.getTargetNodes(), numNodes);
if (nodeIndex >= bounds[0] && nodeIndex <= bounds[1]) {
resolved = override.getContainerOverrides();
}
}
return resolved;
}
private int resolveEffectiveNumNodes(BatchNodeProperties defNodeProperties, BatchNodeOverrides overrides) {
if (overrides == null || overrides.getNumNodes() == null) {
return defNodeProperties.getNumNodes();
}
int overrideNumNodes = overrides.getNumNodes();
if (overrideNumNodes < 1) {
throw client("nodeOverrides.numNodes must be at least 1");
}
if (defNodeProperties.getMainNode() >= overrideNumNodes) {
throw client("nodeOverrides.numNodes must be greater than the job definition's mainNode index");
}
boolean hasOpenRange = defNodeProperties.getNodeRangeProperties().stream()
.anyMatch(range -> isOpenRangeStartingBefore(range.getTargetNodes(), overrideNumNodes));
if (!hasOpenRange) {
throw client("nodeOverrides.numNodes requires an open-ended node range "
+ "(e.g. \"n:\") in the job definition");
}
return overrideNumNodes;
}
private boolean isOpenRangeStartingBefore(String targetNodes, int limit) {
int colon = targetNodes == null ? -1 : targetNodes.indexOf(':');
if (colon < 0 || !targetNodes.substring(colon + 1).trim().isEmpty()) {
return false;
}
String startText = targetNodes.substring(0, colon).trim();
try {
int start = startText.isEmpty() ? 0 : Integer.parseInt(startText);
return start < limit;
} catch (NumberFormatException ignored) {
return false; // malformed range: already registration-time validated, just not a match here
}
}
private void rejectUnsupportedSubmitFields(JsonNode request) {
if (request.hasNonNull("arrayProperties") || request.hasNonNull("dependsOn")
|| request.hasNonNull("nodeOverrides") || request.hasNonNull("nodeProperties")) {
throw client("Array, dependency, and multi-node jobs are not supported");
if (request.hasNonNull("dependsOn")) {
throw client("Job dependencies (dependsOn) are not supported");
}
}
private ObjectNode jobSummary(BatchJob job) {
ObjectNode summary = objectMapper.createObjectNode();
summary.put("jobArn", job.getJobArn());
summary.put("jobId", job.getJobId());
summary.put("jobName", job.getJobName());
summary.put("jobDefinition", job.getJobDefinition());
summary.put("createdAt", job.getCreatedAt());
if (job.getArraySize() != null) {
ArrayRollup rollup = arrayRollup(job.getJobId());
summary.put("status", rollup.status());
if (rollup.startedAt() != null) {
summary.put("startedAt", rollup.startedAt());
}
if (rollup.stoppedAt() != null) {
summary.put("stoppedAt", rollup.stoppedAt());
}
ObjectNode arrayProperties = summary.putObject("arrayProperties");
arrayProperties.put("size", job.getArraySize());
ObjectNode summaryNode = arrayProperties.putObject("statusSummary");
rollup.statusSummary().forEach(summaryNode::put);
} else {
summary.put("status", job.getStatus());
if (job.getStartedAt() != null) {
summary.put("startedAt", job.getStartedAt());
}
if (job.getStoppedAt() != null) {
summary.put("stoppedAt", job.getStoppedAt());
}
if (job.getStatusReason() != null) {
summary.put("statusReason", job.getStatusReason());
}
if (job.getArrayJobId() != null) {
summary.putObject("arrayProperties").put("index", job.getArrayIndex());
}
}
if (job.getContainer() != null) {
ObjectNode container = objectMapper.createObjectNode();
if (job.getContainer().getExitCode() != null) {
container.put("exitCode", job.getContainer().getExitCode());
}
if (job.getContainer().getReason() != null) {
container.put("reason", job.getContainer().getReason());
}
if (!container.isEmpty()) {
summary.set("container", container);
}
}
return summary;
}
private ObjectNode nodeJobSummary(BatchJob job, BatchNodeExecution execution) {
ObjectNode summary = objectMapper.createObjectNode();
summary.put("jobArn", job.getJobArn());
summary.put("jobId", job.getJobId());
@@ -947,13 +1476,17 @@ public class BatchService {
if (job.getStatusReason() != null) {
summary.put("statusReason", job.getStatusReason());
}
if (job.getContainer() != null) {
ObjectNode nodeProperties = summary.putObject("nodeProperties");
nodeProperties.put("nodeIndex", execution.getNodeIndex());
nodeProperties.put("isMainNode", execution.isMainNode());
nodeProperties.put("numNodes", job.getNodeProperties().getNumNodes());
if (execution.getContainer() != null) {
ObjectNode container = objectMapper.createObjectNode();
if (job.getContainer().getExitCode() != null) {
container.put("exitCode", job.getContainer().getExitCode());
if (execution.getContainer().getExitCode() != null) {
container.put("exitCode", execution.getContainer().getExitCode());
}
if (job.getContainer().getReason() != null) {
container.put("reason", job.getContainer().getReason());
if (execution.getContainer().getReason() != null) {
container.put("reason", execution.getContainer().getReason());
}
if (!container.isEmpty()) {
summary.set("container", container);
@@ -962,6 +1495,46 @@ public class BatchService {
return summary;
}
/** {@code status} is the current status; {@code statusSummary} always reflects live children. */
private record ArrayRollup(String status, Long startedAt, Long stoppedAt, Map<String, Integer> statusSummary) {
}
private String effectiveStatus(BatchJob job) {
return job.getArraySize() != null ? arrayRollup(job.getJobId()).status() : job.getStatus();
}
// Computed live from children on every read, rather than an incrementally updated counter, to avoid races.
private ArrayRollup arrayRollup(String parentJobId) {
List<BatchJob> children = jobStore.scan(k -> true).stream()
.filter(job -> parentJobId.equals(job.getArrayJobId()))
.toList();
Map<String, Integer> statusSummary = new LinkedHashMap<>();
for (BatchJob child : children) {
statusSummary.merge(child.getStatus(), 1, Integer::sum);
}
boolean anyFailed = children.stream().anyMatch(c -> BatchStatus.FAILED.name().equals(c.getStatus()));
boolean allSucceeded = !children.isEmpty()
&& children.stream().allMatch(c -> BatchStatus.SUCCEEDED.name().equals(c.getStatus()));
String status;
if (anyFailed) {
status = BatchStatus.FAILED.name();
} else if (allSucceeded) {
status = BatchStatus.SUCCEEDED.name();
} else if (children.stream().anyMatch(c -> !BatchStatus.SUBMITTED.name().equals(c.getStatus()))) {
status = BatchStatus.PENDING.name();
} else {
status = BatchStatus.SUBMITTED.name();
}
Long startedAt = children.stream().map(BatchJob::getStartedAt).filter(Objects::nonNull)
.min(Long::compare).orElse(null);
Long stoppedAt = null;
if (BatchStatus.SUCCEEDED.name().equals(status) || BatchStatus.FAILED.name().equals(status)) {
stoppedAt = children.stream().map(BatchJob::getStoppedAt).filter(Objects::nonNull)
.max(Long::compare).orElse(null);
}
return new ArrayRollup(status, startedAt, stoppedAt, statusSummary);
}
private ObjectNode computeEnvironmentDetail(BatchComputeEnvironment env) {
ObjectNode detail = objectMapper.createObjectNode();
detail.put("computeEnvironmentName", env.getComputeEnvironmentName());
@@ -1010,6 +1583,9 @@ public class BatchService {
if (def.getContainerProperties() != null) {
detail.set("containerProperties", objectMapper.valueToTree(def.getContainerProperties()));
}
if (def.getNodeProperties() != null) {
detail.set("nodeProperties", objectMapper.valueToTree(def.getNodeProperties()));
}
if (def.getParameters() != null && !def.getParameters().isEmpty()) {
detail.set("parameters", objectMapper.valueToTree(def.getParameters()));
}
@@ -1035,17 +1611,41 @@ public class BatchService {
detail.put("jobName", job.getJobName());
detail.put("jobQueue", job.getJobQueue());
detail.put("jobDefinition", job.getJobDefinition());
detail.put("status", job.getStatus());
detail.put("createdAt", job.getCreatedAt());
if (job.getStatusReason() != null) {
detail.put("statusReason", job.getStatusReason());
if (job.getArraySize() != null) {
ArrayRollup rollup = arrayRollup(job.getJobId());
detail.put("status", rollup.status());
if (rollup.startedAt() != null) {
detail.put("startedAt", rollup.startedAt());
}
if (rollup.stoppedAt() != null) {
detail.put("stoppedAt", rollup.stoppedAt());
}
ObjectNode arrayProperties = detail.putObject("arrayProperties");
arrayProperties.put("size", job.getArraySize());
ObjectNode summaryNode = arrayProperties.putObject("statusSummary");
rollup.statusSummary().forEach(summaryNode::put);
arrayProperties.put("statusSummaryLastUpdatedAt", now());
} else {
detail.put("status", job.getStatus());
if (job.getStatusReason() != null) {
detail.put("statusReason", job.getStatusReason());
}
if (job.getStartedAt() != null) {
detail.put("startedAt", job.getStartedAt());
}
if (job.getStoppedAt() != null) {
detail.put("stoppedAt", job.getStoppedAt());
}
if (job.getArrayJobId() != null) {
detail.putObject("arrayProperties").put("index", job.getArrayIndex());
}
}
if (job.getStartedAt() != null) {
detail.put("startedAt", job.getStartedAt());
}
if (job.getStoppedAt() != null) {
detail.put("stoppedAt", job.getStoppedAt());
if (job.getNodeProperties() != null) {
detail.set("nodeProperties", objectMapper.valueToTree(job.getNodeProperties()));
}
detail.set("parameters", objectMapper.valueToTree(job.getParameters()));
detail.set("attempts", objectMapper.valueToTree(job.getAttempts()));
if (job.getRetryStrategy() != null) {
@@ -1058,21 +1658,24 @@ public class BatchService {
detail.set("tags", objectMapper.valueToTree(job.getTags()));
}
ObjectNode container = detail.putObject("container");
if (job.getContainerImage() != null) {
container.put("image", job.getContainerImage());
}
container.set("command", objectMapper.valueToTree(job.getResolvedCommand()));
container.set("environment", objectMapper.valueToTree(job.getResolvedEnvironment()));
if (job.getContainer() != null) {
if (job.getContainer().getExitCode() != null) {
container.put("exitCode", job.getContainer().getExitCode());
// MNP and array-parent jobs have no single container of their own.
if (job.getNodeProperties() == null && job.getArraySize() == null) {
ObjectNode container = detail.putObject("container");
if (job.getContainerImage() != null) {
container.put("image", job.getContainerImage());
}
if (job.getContainer().getReason() != null) {
container.put("reason", job.getContainer().getReason());
}
if (job.getContainer().getLogStreamName() != null) {
container.put("logStreamName", job.getContainer().getLogStreamName());
container.set("command", objectMapper.valueToTree(job.getResolvedCommand()));
container.set("environment", objectMapper.valueToTree(job.getResolvedEnvironment()));
if (job.getContainer() != null) {
if (job.getContainer().getExitCode() != null) {
container.put("exitCode", job.getContainer().getExitCode());
}
if (job.getContainer().getReason() != null) {
container.put("reason", job.getContainer().getReason());
}
if (job.getContainer().getLogStreamName() != null) {
container.put("logStreamName", job.getContainer().getLogStreamName());
}
}
}
return detail;
@@ -39,6 +39,11 @@ public class BatchJob {
private String region;
private String accountId;
private String containerImage;
private String arrayJobId;
private Integer arrayIndex;
private Integer arraySize;
private BatchNodeProperties nodeProperties;
private List<BatchNodeExecution> nodeExecutions = new ArrayList<>();
public String getJobId() {
return jobId;
@@ -247,4 +252,44 @@ public class BatchJob {
public void setContainerImage(String containerImage) {
this.containerImage = containerImage;
}
public String getArrayJobId() {
return arrayJobId;
}
public void setArrayJobId(String arrayJobId) {
this.arrayJobId = arrayJobId;
}
public Integer getArrayIndex() {
return arrayIndex;
}
public void setArrayIndex(Integer arrayIndex) {
this.arrayIndex = arrayIndex;
}
public Integer getArraySize() {
return arraySize;
}
public void setArraySize(Integer arraySize) {
this.arraySize = arraySize;
}
public BatchNodeProperties getNodeProperties() {
return nodeProperties;
}
public void setNodeProperties(BatchNodeProperties nodeProperties) {
this.nodeProperties = nodeProperties;
}
public List<BatchNodeExecution> getNodeExecutions() {
return nodeExecutions;
}
public void setNodeExecutions(List<BatchNodeExecution> nodeExecutions) {
this.nodeExecutions = nodeExecutions != null ? nodeExecutions : new ArrayList<>();
}
}
@@ -18,6 +18,7 @@ public class BatchJobDefinition {
private String status;
private String type;
private BatchContainerProperties containerProperties;
private BatchNodeProperties nodeProperties;
private Map<String, String> parameters = new HashMap<>();
private BatchRetryStrategy retryStrategy;
private BatchTimeout timeout;
@@ -75,6 +76,14 @@ public class BatchJobDefinition {
this.containerProperties = containerProperties;
}
public BatchNodeProperties getNodeProperties() {
return nodeProperties;
}
public void setNodeProperties(BatchNodeProperties nodeProperties) {
this.nodeProperties = nodeProperties;
}
public Map<String, String> getParameters() {
return parameters;
}
@@ -0,0 +1,78 @@
package io.github.hectorvent.floci.services.batch.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.util.ArrayList;
import java.util.List;
// The resolved, per-node execution spec and runtime result for one node of a multi-node job.
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_EMPTY)
public class BatchNodeExecution {
private int nodeIndex;
private boolean mainNode;
private String containerImage;
private List<String> resolvedCommand = new ArrayList<>();
private List<BatchKeyValue> resolvedEnvironment = new ArrayList<>();
private List<BatchResourceRequirement> resourceRequirements = new ArrayList<>();
private BatchAttemptContainer container;
public int getNodeIndex() {
return nodeIndex;
}
public void setNodeIndex(int nodeIndex) {
this.nodeIndex = nodeIndex;
}
public boolean isMainNode() {
return mainNode;
}
public void setMainNode(boolean mainNode) {
this.mainNode = mainNode;
}
public String getContainerImage() {
return containerImage;
}
public void setContainerImage(String containerImage) {
this.containerImage = containerImage;
}
public List<String> getResolvedCommand() {
return resolvedCommand;
}
public void setResolvedCommand(List<String> resolvedCommand) {
this.resolvedCommand = resolvedCommand != null ? resolvedCommand : new ArrayList<>();
}
public List<BatchKeyValue> getResolvedEnvironment() {
return resolvedEnvironment;
}
public void setResolvedEnvironment(List<BatchKeyValue> resolvedEnvironment) {
this.resolvedEnvironment = resolvedEnvironment != null ? resolvedEnvironment : new ArrayList<>();
}
public List<BatchResourceRequirement> getResourceRequirements() {
return resourceRequirements;
}
public void setResourceRequirements(List<BatchResourceRequirement> resourceRequirements) {
this.resourceRequirements = resourceRequirements != null ? resourceRequirements : new ArrayList<>();
}
public BatchAttemptContainer getContainer() {
return container;
}
public void setContainer(BatchAttemptContainer container) {
this.container = container;
}
}
@@ -0,0 +1,32 @@
package io.github.hectorvent.floci.services.batch.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.util.ArrayList;
import java.util.List;
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_EMPTY)
public class BatchNodeOverrides {
private Integer numNodes;
private List<BatchNodePropertyOverride> nodePropertyOverrides = new ArrayList<>();
public Integer getNumNodes() {
return numNodes;
}
public void setNumNodes(Integer numNodes) {
this.numNodes = numNodes;
}
public List<BatchNodePropertyOverride> getNodePropertyOverrides() {
return nodePropertyOverrides;
}
public void setNodePropertyOverrides(List<BatchNodePropertyOverride> nodePropertyOverrides) {
this.nodePropertyOverrides = nodePropertyOverrides != null ? nodePropertyOverrides : new ArrayList<>();
}
}
@@ -0,0 +1,41 @@
package io.github.hectorvent.floci.services.batch.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.util.ArrayList;
import java.util.List;
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_EMPTY)
public class BatchNodeProperties {
private Integer numNodes;
private Integer mainNode;
private List<BatchNodeRangeProperty> nodeRangeProperties = new ArrayList<>();
public Integer getNumNodes() {
return numNodes;
}
public void setNumNodes(Integer numNodes) {
this.numNodes = numNodes;
}
public Integer getMainNode() {
return mainNode;
}
public void setMainNode(Integer mainNode) {
this.mainNode = mainNode;
}
public List<BatchNodeRangeProperty> getNodeRangeProperties() {
return nodeRangeProperties;
}
public void setNodeRangeProperties(List<BatchNodeRangeProperty> nodeRangeProperties) {
this.nodeRangeProperties = nodeRangeProperties != null ? nodeRangeProperties : new ArrayList<>();
}
}
@@ -0,0 +1,29 @@
package io.github.hectorvent.floci.services.batch.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import io.quarkus.runtime.annotations.RegisterForReflection;
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_EMPTY)
public class BatchNodePropertyOverride {
private String targetNodes;
private BatchContainerOverrides containerOverrides;
public String getTargetNodes() {
return targetNodes;
}
public void setTargetNodes(String targetNodes) {
this.targetNodes = targetNodes;
}
public BatchContainerOverrides getContainerOverrides() {
return containerOverrides;
}
public void setContainerOverrides(BatchContainerOverrides containerOverrides) {
this.containerOverrides = containerOverrides;
}
}
@@ -0,0 +1,29 @@
package io.github.hectorvent.floci.services.batch.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import io.quarkus.runtime.annotations.RegisterForReflection;
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_EMPTY)
public class BatchNodeRangeProperty {
private String targetNodes;
private BatchContainerProperties container;
public String getTargetNodes() {
return targetNodes;
}
public void setTargetNodes(String targetNodes) {
this.targetNodes = targetNodes;
}
public BatchContainerProperties getContainer() {
return container;
}
public void setContainer(BatchContainerProperties container) {
this.container = container;
}
}
@@ -394,6 +394,7 @@ public class BatchCfnProvisioner implements CfnResourceProvisioner {
req.set("containerProperties",
containerProperties(ctx.engine().resolveNode(props.get("ContainerProperties"))));
}
// NodeProperties (multinode job definitions) is not translated here yet.
putStringMapFromObject(req, "parameters", props, "Parameters", ctx);
if (props != null && props.has("RetryStrategy")) {
req.set("retryStrategy", retryStrategy(ctx.engine().resolveNode(props.get("RetryStrategy"))));
@@ -579,6 +579,129 @@ class BatchIntegrationTest {
.statusCode(200);
}
@Test
void submitArrayJobOverTheWireFansOutAndAggregates() {
String suffix = uniqueSuffix();
String queueArn = createQueue("batch-array-queue-" + suffix, createComputeEnvironment("batch-array-ce-" + suffix));
String definitionArn = registerJobDefinition("batch-array-job-" + suffix, "[\"ok\"]", "[]");
String parentId = givenJson("""
{
"jobName": "batch-array-submit-%s",
"jobQueue": "%s",
"jobDefinition": "%s",
"arrayProperties": {"size": 3}
}
""".formatted(suffix, queueArn, definitionArn))
.when()
.post("/v1/submitjob")
.then()
.statusCode(200)
.body("jobId", notNullValue())
.extract().path("jobId");
givenJson("{\"jobs\":[\"%s\"]}".formatted(parentId))
.when()
.post("/v1/describejobs")
.then()
.statusCode(200)
.body("jobs[0].status", equalTo("SUCCEEDED"))
.body("jobs[0].arrayProperties.size", equalTo(3))
.body("jobs[0].arrayProperties.statusSummary.SUCCEEDED", equalTo(3));
givenJson("{\"jobs\":[\"%s:0\",\"%s:1\",\"%s:2\"]}".formatted(parentId, parentId, parentId))
.when()
.post("/v1/describejobs")
.then()
.statusCode(200)
.body("jobs", hasSize(3))
.body("jobs[0].arrayProperties.index", equalTo(0))
.body("jobs[0].status", equalTo("SUCCEEDED"));
givenJson("{\"arrayJobId\":\"%s\"}".formatted(parentId))
.when()
.post("/v1/listjobs")
.then()
.statusCode(200)
.body("jobSummaryList", hasSize(3));
givenJson("{\"jobQueue\":\"%s\",\"jobStatus\":\"SUCCEEDED\"}".formatted(queueArn))
.when()
.post("/v1/listjobs")
.then()
.statusCode(200)
.body("jobSummaryList.findAll { it.jobId.startsWith('%s') }".formatted(parentId), hasSize(1));
}
@Test
void submitArrayJobRejectsSizeOutOfRange() {
String suffix = uniqueSuffix();
String queueArn = createQueue("batch-array-bad-queue-" + suffix, createComputeEnvironment("batch-array-bad-ce-" + suffix));
String definitionArn = registerJobDefinition("batch-array-bad-job-" + suffix, "[\"ok\"]", "[]");
givenJson("""
{"jobName":"array-too-small-%s","jobQueue":"%s","jobDefinition":"%s","arrayProperties":{"size":1}}
""".formatted(suffix, queueArn, definitionArn))
.when()
.post("/v1/submitjob")
.then()
.statusCode(400)
.body("__type", equalTo("ClientException"));
}
@Test
void submitMultiNodeJobOverTheWireRunsAllNodes() {
String suffix = uniqueSuffix();
String queueArn = createQueue("batch-mnp-queue-" + suffix, createComputeEnvironment("batch-mnp-ce-" + suffix));
String definitionArn = givenJson("""
{
"jobDefinitionName": "batch-mnp-job-%s",
"type": "multinode",
"nodeProperties": {
"numNodes": 2,
"mainNode": 0,
"nodeRangeProperties": [
{"targetNodes": "0:0", "container": {"image": "public.ecr.aws/example/main:latest"}},
{"targetNodes": "1:1", "container": {"image": "public.ecr.aws/example/worker:latest"}}
]
}
}
""".formatted(suffix))
.when()
.post("/v1/registerjobdefinition")
.then()
.statusCode(200)
.extract().path("jobDefinitionArn");
String jobId = givenJson("""
{"jobName":"batch-mnp-submit-%s","jobQueue":"%s","jobDefinition":"%s"}
""".formatted(suffix, queueArn, definitionArn))
.when()
.post("/v1/submitjob")
.then()
.statusCode(200)
.extract().path("jobId");
givenJson("{\"jobs\":[\"%s\"]}".formatted(jobId))
.when()
.post("/v1/describejobs")
.then()
.statusCode(200)
.body("jobs[0].status", equalTo("SUCCEEDED"))
.body("jobs[0].nodeProperties.numNodes", equalTo(2))
.body("jobs[0].nodeProperties.mainNode", equalTo(0))
.body("jobs[0].container", nullValue());
givenJson("{\"multiNodeJobId\":\"%s\"}".formatted(jobId))
.when()
.post("/v1/listjobs")
.then()
.statusCode(200)
.body("jobSummaryList", hasSize(2))
.body("jobSummaryList.find { it.nodeProperties.nodeIndex == 0 }.nodeProperties.isMainNode", equalTo(true))
.body("jobSummaryList.find { it.nodeProperties.nodeIndex == 1 }.nodeProperties.isMainNode", equalTo(false));
}
@Test
void describeUnknownJobsReturnsEmptyList() {
givenJson("{\"jobs\":[\"does-not-exist\"]}")
@@ -12,6 +12,7 @@ import io.github.hectorvent.floci.services.batch.model.BatchComputeEnvironment;
import io.github.hectorvent.floci.services.batch.model.BatchJob;
import io.github.hectorvent.floci.services.batch.model.BatchJobDefinition;
import io.github.hectorvent.floci.services.batch.model.BatchJobQueue;
import io.github.hectorvent.floci.services.batch.model.BatchNodeExecution;
import io.github.hectorvent.floci.services.batch.model.BatchRunResult;
import org.junit.jupiter.api.Test;
@@ -21,6 +22,7 @@ import java.util.LinkedHashMap;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.function.Predicate;
import static org.junit.jupiter.api.Assertions.assertEquals;
@@ -448,6 +450,349 @@ class BatchServiceTest {
assertEquals(0, repeated.size());
}
@Test
void submitArrayJobFansOutChildrenAndAggregatesStatus() throws Exception {
BatchService service = immediateService(new InMemoryStorage<String, BatchJob>());
String computeArn = service.createComputeEnvironment(json("""
{"computeEnvironmentName":"array-ce","type":"MANAGED"}
"""), REGION).path("computeEnvironmentArn").asText();
String queueArn = service.createJobQueue(json("""
{
"jobQueueName":"array-queue",
"priority":1,
"computeEnvironmentOrder":[{"order":1,"computeEnvironment":"%s"}]
}
""".formatted(computeArn)), REGION).path("jobQueueArn").asText();
String definitionArn = service.registerJobDefinition(json("""
{
"jobDefinitionName":"array-job",
"type":"container",
"containerProperties":{"image":"public.ecr.aws/example/job:latest"}
}
"""), REGION).path("jobDefinitionArn").asText();
JsonNode submitted = service.submitJob(json("""
{
"jobName":"array-submit",
"jobQueue":"%s",
"jobDefinition":"%s",
"arrayProperties":{"size":3}
}
""".formatted(queueArn, definitionArn)), REGION);
String parentId = submitted.path("jobId").asText();
JsonNode parent = service.describeJobs(json("""
{"jobs":["%s"]}
""".formatted(parentId))).path("jobs").get(0);
assertEquals("SUCCEEDED", parent.path("status").asText());
assertEquals(3, parent.path("arrayProperties").path("size").asInt());
assertEquals(3, parent.path("arrayProperties").path("statusSummary").path("SUCCEEDED").asInt());
assertEquals(0, parent.path("container").size());
JsonNode child = service.describeJobs(json("""
{"jobs":["%s:1"]}
""".formatted(parentId))).path("jobs").get(0);
assertEquals("SUCCEEDED", child.path("status").asText());
assertEquals(1, child.path("arrayProperties").path("index").asInt());
assertEquals("array-submit", child.path("jobName").asText());
JsonNode childList = service.listJobs(json("""
{"arrayJobId":"%s"}
""".formatted(parentId))).path("jobSummaryList");
assertEquals(3, childList.size());
for (int i = 0; i < 3; i++) {
assertEquals(i, childList.get(i).path("arrayProperties").path("index").asInt());
}
JsonNode queueList = service.listJobs(json("""
{"jobQueue":"%s","jobStatus":"SUCCEEDED"}
""".formatted(queueArn))).path("jobSummaryList");
long matchingParents = 0;
for (JsonNode summary : queueList) {
if (parentId.equals(summary.path("jobId").asText())) {
matchingParents++;
}
assertEquals(false, summary.path("jobId").asText().contains(":"));
}
assertEquals(1, matchingParents);
}
@Test
void submitArrayJobRejectsSizeOutOfBounds() throws Exception {
BatchService service = immediateService(new InMemoryStorage<String, BatchJob>());
String queueArn = arrayReadyQueue(service);
String definitionArn = service.registerJobDefinition(json("""
{
"jobDefinitionName":"array-bounds-job",
"type":"container",
"containerProperties":{"image":"public.ecr.aws/example/job:latest"}
}
"""), REGION).path("jobDefinitionArn").asText();
AwsException tooSmall = assertThrows(AwsException.class, () -> service.submitJob(json("""
{"jobName":"too-small","jobQueue":"%s","jobDefinition":"%s","arrayProperties":{"size":1}}
""".formatted(queueArn, definitionArn)), REGION));
assertEquals("ClientException", tooSmall.getErrorCode());
AwsException tooBig = assertThrows(AwsException.class, () -> service.submitJob(json("""
{"jobName":"too-big","jobQueue":"%s","jobDefinition":"%s","arrayProperties":{"size":10001}}
""".formatted(queueArn, definitionArn)), REGION));
assertEquals("ClientException", tooBig.getErrorCode());
}
@Test
void listJobsRequiresExactlyOneSelector() throws Exception {
BatchService service = immediateService(new InMemoryStorage<String, BatchJob>());
String queueArn = arrayReadyQueue(service);
AwsException none = assertThrows(AwsException.class, () -> service.listJobs(json("{}")));
assertEquals("ClientException", none.getErrorCode());
AwsException both = assertThrows(AwsException.class, () -> service.listJobs(json("""
{"jobQueue":"%s","arrayJobId":"some-id"}
""".formatted(queueArn))));
assertEquals("ClientException", both.getErrorCode());
}
@Test
void registerMultiNodeJobDefinitionValidatesRangeCoverage() {
BatchService service = immediateService(new InMemoryStorage<String, BatchJob>());
AwsException e = assertThrows(AwsException.class, () -> service.registerJobDefinition(json("""
{
"jobDefinitionName":"gap-def",
"type":"multinode",
"nodeProperties":{
"numNodes":3,
"mainNode":0,
"nodeRangeProperties":[
{"targetNodes":"0:0","container":{"image":"main:latest"}}
]
}
}
"""), REGION));
assertEquals("ClientException", e.getErrorCode());
}
@Test
void registerMultiNodeJobDefinitionRejectsContainerProperties() {
BatchService service = immediateService(new InMemoryStorage<String, BatchJob>());
AwsException e = assertThrows(AwsException.class, () -> service.registerJobDefinition(json("""
{
"jobDefinitionName":"mixed-def",
"type":"multinode",
"containerProperties":{"image":"solo:latest"},
"nodeProperties":{
"numNodes":2,
"mainNode":0,
"nodeRangeProperties":[{"targetNodes":"0:1","container":{"image":"worker:latest"}}]
}
}
"""), REGION));
assertEquals("ClientException", e.getErrorCode());
}
@Test
void submitMultiNodeJobRunsAllNodesAndSucceeds() throws Exception {
BatchService service = immediateService(new InMemoryStorage<String, BatchJob>());
String queueArn = arrayReadyQueue(service);
String definitionArn = service.registerJobDefinition(json("""
{
"jobDefinitionName":"mnp-job",
"type":"multinode",
"nodeProperties":{
"numNodes":2,
"mainNode":0,
"nodeRangeProperties":[
{"targetNodes":"0:0","container":{"image":"main:latest"}},
{"targetNodes":"1:1","container":{"image":"worker:latest"}}
]
}
}
"""), REGION).path("jobDefinitionArn").asText();
String jobId = service.submitJob(json("""
{"jobName":"mnp-submit","jobQueue":"%s","jobDefinition":"%s"}
""".formatted(queueArn, definitionArn)), REGION).path("jobId").asText();
JsonNode job = waitForJobStatus(service, jobId, "SUCCEEDED");
assertNotNull(job);
assertEquals(2, job.path("nodeProperties").path("numNodes").asInt());
assertEquals(0, job.path("nodeProperties").path("mainNode").asInt());
assertEquals(1, job.path("attempts").size());
assertEquals(0, job.path("container").size());
JsonNode nodes = service.listJobs(json("""
{"multiNodeJobId":"%s"}
""".formatted(jobId))).path("jobSummaryList");
assertEquals(2, nodes.size());
assertEquals(0, nodes.get(0).path("nodeProperties").path("nodeIndex").asInt());
assertEquals(true, nodes.get(0).path("nodeProperties").path("isMainNode").asBoolean());
assertEquals(1, nodes.get(1).path("nodeProperties").path("nodeIndex").asInt());
assertEquals(false, nodes.get(1).path("nodeProperties").path("isMainNode").asBoolean());
}
@Test
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)))
.thenAnswer(invocation -> {
BatchNodeExecution node = invocation.getArgument(2);
return node.getNodeIndex() == 1
? new BatchRunResult(3, "worker crashed", "log-1", 1L, 2L, false)
: new BatchRunResult(0, null, "log-0", 1L, 2L, false);
});
BatchService service = dockerService(runner);
String queueArn = arrayReadyQueue(service);
String definitionArn = service.registerJobDefinition(json("""
{
"jobDefinitionName":"mnp-child-fail-job",
"type":"multinode",
"nodeProperties":{
"numNodes":2,
"mainNode":0,
"nodeRangeProperties":[{"targetNodes":"0:1","container":{"image":"worker:latest"}}]
}
}
"""), REGION).path("jobDefinitionArn").asText();
String jobId = service.submitJob(json("""
{"jobName":"mnp-child-fail-submit","jobQueue":"%s","jobDefinition":"%s"}
""".formatted(queueArn, definitionArn)), REGION).path("jobId").asText();
JsonNode job = waitForJobStatus(service, jobId, "SUCCEEDED");
assertNotNull(job);
verify(runner, times(2)).run(any(BatchJob.class), anyInt(), any(BatchNodeExecution.class));
JsonNode nodes = service.listJobs(json("""
{"multiNodeJobId":"%s"}
""".formatted(jobId))).path("jobSummaryList");
assertEquals(3, nodes.get(1).path("container").path("exitCode").asInt());
}
@Test
void submitMultiNodeJobFailsWhenTheMainNodeFails() throws Exception {
BatchDockerRunner runner = mock(BatchDockerRunner.class);
when(runner.run(any(BatchJob.class), anyInt(), any(BatchNodeExecution.class)))
.thenAnswer(invocation -> {
BatchNodeExecution node = invocation.getArgument(2);
return node.isMainNode()
? new BatchRunResult(3, "main crashed", "log-0", 1L, 2L, false)
: new BatchRunResult(0, null, "log-1", 1L, 2L, false);
});
BatchService service = dockerService(runner);
String queueArn = arrayReadyQueue(service);
String definitionArn = service.registerJobDefinition(json("""
{
"jobDefinitionName":"mnp-main-fail-job",
"type":"multinode",
"nodeProperties":{
"numNodes":2,
"mainNode":0,
"nodeRangeProperties":[{"targetNodes":"0:1","container":{"image":"worker:latest"}}]
}
}
"""), REGION).path("jobDefinitionArn").asText();
String jobId = service.submitJob(json("""
{"jobName":"mnp-main-fail-submit","jobQueue":"%s","jobDefinition":"%s"}
""".formatted(queueArn, definitionArn)), REGION).path("jobId").asText();
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));
}
@Test
void submitMultiNodeJobRejectsContainerOverrides() throws Exception {
BatchService service = immediateService(new InMemoryStorage<String, BatchJob>());
String queueArn = arrayReadyQueue(service);
String definitionArn = service.registerJobDefinition(json("""
{
"jobDefinitionName":"mnp-overrides-job",
"type":"multinode",
"nodeProperties":{
"numNodes":1,
"mainNode":0,
"nodeRangeProperties":[{"targetNodes":"0:0","container":{"image":"main:latest"}}]
}
}
"""), REGION).path("jobDefinitionArn").asText();
AwsException e = assertThrows(AwsException.class, () -> service.submitJob(json("""
{
"jobName":"mnp-overrides-submit","jobQueue":"%s","jobDefinition":"%s",
"containerOverrides":{"command":["nope"]}
}
""".formatted(queueArn, definitionArn)), REGION));
assertEquals("ClientException", e.getErrorCode());
}
@Test
void submitJobRejectsArrayPropertiesForMultiNodeJobDefinition() throws Exception {
BatchService service = immediateService(new InMemoryStorage<String, BatchJob>());
String queueArn = arrayReadyQueue(service);
String definitionArn = service.registerJobDefinition(json("""
{
"jobDefinitionName":"mnp-array-job",
"type":"multinode",
"nodeProperties":{
"numNodes":1,
"mainNode":0,
"nodeRangeProperties":[{"targetNodes":"0:0","container":{"image":"main:latest"}}]
}
}
"""), REGION).path("jobDefinitionArn").asText();
AwsException e = assertThrows(AwsException.class, () -> service.submitJob(json("""
{"jobName":"mnp-array-submit","jobQueue":"%s","jobDefinition":"%s","arrayProperties":{"size":2}}
""".formatted(queueArn, definitionArn)), REGION));
assertEquals("ClientException", e.getErrorCode());
}
@Test
void nodeOverridesNumNodesRequiresAnOpenEndedRange() throws Exception {
BatchService service = immediateService(new InMemoryStorage<String, BatchJob>());
String queueArn = arrayReadyQueue(service);
String definitionArn = service.registerJobDefinition(json("""
{
"jobDefinitionName":"mnp-closed-range-job",
"type":"multinode",
"nodeProperties":{
"numNodes":2,
"mainNode":0,
"nodeRangeProperties":[{"targetNodes":"0:1","container":{"image":"worker:latest"}}]
}
}
"""), REGION).path("jobDefinitionArn").asText();
AwsException e = assertThrows(AwsException.class, () -> service.submitJob(json("""
{
"jobName":"mnp-closed-range-submit","jobQueue":"%s","jobDefinition":"%s",
"nodeOverrides":{"numNodes":4}
}
""".formatted(queueArn, definitionArn)), REGION));
assertEquals("ClientException", e.getErrorCode());
}
private String arrayReadyQueue(BatchService service) throws Exception {
String suffix = UUID.randomUUID().toString();
String computeArn = service.createComputeEnvironment(json("""
{"computeEnvironmentName":"ce-%s","type":"MANAGED"}
""".formatted(suffix)), REGION).path("computeEnvironmentArn").asText();
return service.createJobQueue(json("""
{
"jobQueueName":"queue-%s",
"priority":1,
"computeEnvironmentOrder":[{"order":1,"computeEnvironment":"%s"}]
}
""".formatted(suffix, computeArn)), REGION).path("jobQueueArn").asText();
}
private BatchService dockerService(BatchDockerRunner runner) {
EmulatorConfig config = mock(EmulatorConfig.class);
EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);