feat(batch): support canceling and terminating jobs (#3922)

* feat(batch): support canceling and terminating jobs

* fix(batch): close job termination race
This commit is contained in:
XuJian authored and GitHub committed 2026-09-19 23:50:48 -04:00
1 parent c5de8331b7
commit 9c4cd8c9e1
7 files changed
+723 -44

No files matched your search

@@ -119,6 +119,20 @@ public class BatchController {
Response.ok(service.submitJob(request, region)).build());
}
@POST
@Path("/v1/canceljob")
public Response cancelJob(@Context HttpHeaders headers, String body) {
return handle(headers, body, (request, region) ->
Response.ok(service.cancelJob(request)).build());
}
@POST
@Path("/v1/terminatejob")
public Response terminateJob(@Context HttpHeaders headers, String body) {
return handle(headers, body, (request, region) ->
Response.ok(service.terminateJob(request)).build());
}
@POST
@Path("/v1/describejobs")
public Response describeJobs(@Context HttpHeaders headers, String body) {
@@ -25,6 +25,7 @@ import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
@ApplicationScoped
@@ -36,6 +37,7 @@ public class BatchDockerRunner implements ContainerTeardown {
// Containers of jobs currently inside run(); drained on emulator shutdown so a
// SIGTERM mid-job does not orphan the container.
private final ConcurrentHashMap<String, String> inFlightContainers = new ConcurrentHashMap<>();
private final Set<String> stopRequestedJobs = ConcurrentHashMap.newKeySet();
private final ContainerBuilder containerBuilder;
private final ContainerLifecycleManager lifecycleManager;
@@ -88,6 +90,9 @@ public class BatchDockerRunner implements ContainerTeardown {
String containerId = null;
try {
if (stopRequestedJobs.contains(job.getJobId())) {
return stopped(startedAt, logStreamName);
}
if (image == null || image.isBlank()) {
return failed(startedAt, logStreamName, missingImageMessage);
}
@@ -110,7 +115,15 @@ public class BatchDockerRunner implements ContainerTeardown {
ContainerSpec spec = builder.build();
containerId = lifecycleManager.createAndStart(spec).containerId();
inFlightContainers.put(inFlightKey, containerId);
if (stopRequestedJobs.contains(job.getJobId())) {
releaseAndStop(inFlightKey, containerId, null);
return stopped(startedAt, logStreamName);
}
logHandle = logStreamer.attach(containerId, LOG_GROUP, logStreamName, job.getRegion(), logSourceLabel);
if (stopRequestedJobs.contains(job.getJobId())) {
releaseAndStop(inFlightKey, containerId, logHandle);
return stopped(startedAt, logStreamName);
}
Integer exitCode = waitForExit(containerId, timeout(job));
long stoppedAt = System.currentTimeMillis();
@@ -129,7 +142,30 @@ public class BatchDockerRunner implements ContainerTeardown {
}
}
// Whoever wins the map removal owns the stop — stopManagedContainers() may have
public void requestStop(String jobId) {
stopRequestedJobs.add(jobId);
}
public void stopJob(String jobId) {
for (Map.Entry<String, String> entry : new ConcurrentHashMap<>(inFlightContainers).entrySet()) {
if (!entry.getKey().equals(jobId) && !entry.getKey().startsWith(jobId + "#node")) {
continue;
}
if (inFlightContainers.remove(entry.getKey(), entry.getValue())) {
try {
lifecycleManager.stopAndRemove(entry.getValue(), null);
} catch (Exception e) {
LOG.warnv("Failed to stop Batch container for job {0}: {1}", jobId, e.getMessage());
}
}
}
}
public void clearStopRequest(String jobId) {
stopRequestedJobs.remove(jobId);
}
// Whoever wins the map removal owns the stop. stopManagedContainers() may have
// claimed the container first during shutdown, but the log stream is still ours.
private void releaseAndStop(String jobId, String containerId, Closeable logHandle) {
if (inFlightContainers.remove(jobId, containerId)) {
@@ -165,6 +201,11 @@ public class BatchDockerRunner implements ContainerTeardown {
return new BatchRunResult(1, reason, logStreamName, startedAt, System.currentTimeMillis(), false);
}
private BatchRunResult stopped(long startedAt, String logStreamName) {
return new BatchRunResult(137, "Job terminated", logStreamName,
startedAt, System.currentTimeMillis(), false);
}
private List<String> buildEnvironment(BatchJob job, int attemptNumber) {
List<String> env = baseEnvironment(job, attemptNumber);
appendEnvironment(env, job.getResolvedEnvironment());
@@ -56,6 +56,7 @@ public class BatchService {
private static final int DEFAULT_MAX_RESULTS = 1000;
private static final int FILTERED_MAX_RESULTS = 100;
private static final int MAX_TAGS = 50;
private static final int MAX_JOB_CONTROL_REASON_LENGTH = 1024;
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", "multinode");
private static final int MIN_ARRAY_SIZE = 2;
@@ -64,6 +65,8 @@ public class BatchService {
private static final Set<String> SUPPORTED_COMPUTE_ENVIRONMENT_STATES = Set.of("ENABLED", "DISABLED");
private static final Set<String> SUPPORTED_LIST_FILTERS = Set.of(
"JOB_NAME", "JOB_DEFINITION", "BEFORE_CREATED_AT", "AFTER_CREATED_AT", "SHARE_IDENTIFIER");
private static final Set<String> TERMINAL_JOB_STATUSES = Set.of(
BatchStatus.SUCCEEDED.name(), BatchStatus.FAILED.name());
private final StorageBackend<String, BatchJobDefinition> jobDefinitionStore;
private final StorageBackend<String, BatchJobQueue> jobQueueStore;
@@ -456,6 +459,71 @@ public class BatchService {
return submitJobResponse(job);
}
public ObjectNode cancelJob(JsonNode request) {
return controlJob(request, false);
}
public ObjectNode terminateJob(JsonNode request) {
return controlJob(request, true);
}
private ObjectNode controlJob(JsonNode request, boolean terminate) {
String jobId = requiredText(request, "jobId");
String reason = requiredText(request, "reason");
if (reason.length() > MAX_JOB_CONTROL_REASON_LENGTH) {
throw client("reason must be at most " + MAX_JOB_CONTROL_REASON_LENGTH + " characters");
}
List<String> jobsToStop = new ArrayList<>();
synchronized (this) {
BatchJob job = getJob(jobId).orElseThrow(() -> client("Job not found: " + jobId));
if (job.getArraySize() != null) {
boolean changed = false;
List<BatchJob> children = jobStore.scan(k -> true).stream()
.filter(child -> jobId.equals(child.getArrayJobId()))
.toList();
for (BatchJob child : children) {
boolean wasRunning = BatchStatus.RUNNING.name().equals(child.getStatus());
if (controlSingleJob(child, reason, terminate)) {
changed = true;
if (terminate && wasRunning) {
dockerRunner.requestStop(child.getJobId());
jobsToStop.add(child.getJobId());
}
}
}
if (changed) {
job.setStatusReason(reason);
putJob(job);
}
} else {
boolean wasRunning = BatchStatus.RUNNING.name().equals(job.getStatus());
if (controlSingleJob(job, reason, terminate) && terminate && wasRunning) {
dockerRunner.requestStop(job.getJobId());
jobsToStop.add(job.getJobId());
}
}
}
jobsToStop.forEach(dockerRunner::stopJob);
return objectMapper.createObjectNode();
}
private boolean controlSingleJob(BatchJob job, String reason, boolean terminate) {
if (isTerminalStatus(job.getStatus())) {
return false;
}
if (!terminate && (BatchStatus.STARTING.name().equals(job.getStatus())
|| BatchStatus.RUNNING.name().equals(job.getStatus()))) {
return false;
}
job.setStatus(BatchStatus.FAILED.name());
job.setStatusReason(reason);
job.setStoppedAt(now());
putJob(job);
return true;
}
private ObjectNode submitArrayJob(JsonNode request, String region, String jobName, BatchJobQueue queue,
BatchJobDefinition def, Map<String, String> parameters, int size) {
BatchJob parent = new BatchJob();
@@ -800,13 +868,21 @@ public class BatchService {
}
int maxAttempts = maxAttempts(job);
for (int attemptNumber = 1; attemptNumber <= maxAttempts; attemptNumber++) {
transition(accountId, jobId, BatchStatus.PENDING, null, false);
if (!transition(accountId, jobId, BatchStatus.PENDING, null, false)) {
return;
}
sleepQuietly();
transition(accountId, jobId, BatchStatus.RUNNABLE, null, false);
if (!transition(accountId, jobId, BatchStatus.RUNNABLE, null, false)) {
return;
}
sleepQuietly();
transition(accountId, jobId, BatchStatus.STARTING, null, false);
if (!transition(accountId, jobId, BatchStatus.STARTING, null, false)) {
return;
}
sleepQuietly();
transition(accountId, jobId, BatchStatus.RUNNING, null, true);
if (!transition(accountId, jobId, BatchStatus.RUNNING, null, true)) {
return;
}
BatchJob attemptJob = getJobForAccount(accountId, jobId).orElse(null);
if (attemptJob == null) {
return;
@@ -821,6 +897,8 @@ public class BatchService {
} catch (Exception e) {
LOG.warnv("Batch job {0} failed while running: {1}", jobId, e.getMessage());
failJob(accountId, jobId, e.getMessage());
} finally {
dockerRunner.clearStopRequest(jobId);
}
}
@@ -840,6 +918,7 @@ public class BatchService {
if (job == null) {
return true;
}
boolean controlledTerminal = isTerminalStatus(job.getStatus());
BatchAttemptContainer container = new BatchAttemptContainer();
container.setExitCode(result.exitCode());
container.setReason(result.reason());
@@ -853,6 +932,10 @@ public class BatchService {
job.getAttempts().add(attempt);
job.setContainer(container);
if (controlledTerminal) {
putJobForAccount(accountId, job);
return true;
}
if (result.exitCode() == 0) {
job.setStoppedAt(result.stoppedAt());
job.setStatus(BatchStatus.SUCCEEDED.name());
@@ -881,13 +964,21 @@ public class BatchService {
}
int maxAttempts = maxAttempts(job);
for (int attemptNumber = 1; attemptNumber <= maxAttempts; attemptNumber++) {
transition(accountId, jobId, BatchStatus.PENDING, null, false);
if (!transition(accountId, jobId, BatchStatus.PENDING, null, false)) {
return;
}
sleepQuietly();
transition(accountId, jobId, BatchStatus.RUNNABLE, null, false);
if (!transition(accountId, jobId, BatchStatus.RUNNABLE, null, false)) {
return;
}
sleepQuietly();
transition(accountId, jobId, BatchStatus.STARTING, null, false);
if (!transition(accountId, jobId, BatchStatus.STARTING, null, false)) {
return;
}
sleepQuietly();
transition(accountId, jobId, BatchStatus.RUNNING, null, true);
if (!transition(accountId, jobId, BatchStatus.RUNNING, null, true)) {
return;
}
BatchJob attemptJob = getJobForAccount(accountId, jobId).orElse(null);
if (attemptJob == null) {
return;
@@ -900,6 +991,8 @@ public class BatchService {
} catch (Exception e) {
LOG.warnv("Batch multi-node job {0} failed while running: {1}", jobId, e.getMessage());
failJob(accountId, jobId, e.getMessage());
} finally {
dockerRunner.clearStopRequest(jobId);
}
}
@@ -947,6 +1040,7 @@ public class BatchService {
if (job == null) {
return true;
}
boolean controlledTerminal = isTerminalStatus(job.getStatus());
List<BatchNodeExecution> executions = job.getNodeExecutions();
BatchRunResult mainResult = null;
for (int i = 0; i < executions.size(); i++) {
@@ -970,6 +1064,11 @@ public class BatchService {
attempt.setStatusReason(mainResult.reason());
job.getAttempts().add(attempt);
if (controlledTerminal) {
putJobForAccount(accountId, job);
return true;
}
if (mainResult.exitCode() == 0) {
job.setStoppedAt(mainResult.stoppedAt());
job.setStatus(BatchStatus.SUCCEEDED.name());
@@ -999,7 +1098,7 @@ public class BatchService {
private synchronized void failJob(String accountId, String jobId, String reason) {
BatchJob job = getJobForAccount(accountId, jobId).orElse(null);
if (job == null) {
if (job == null || isTerminalStatus(job.getStatus())) {
return;
}
job.setStatus(BatchStatus.FAILED.name());
@@ -1008,10 +1107,11 @@ public class BatchService {
putJobForAccount(accountId, job);
}
private synchronized void transition(String accountId, String jobId, BatchStatus status, String reason, boolean started) {
private synchronized boolean transition(String accountId, String jobId, BatchStatus status,
String reason, boolean started) {
BatchJob job = getJobForAccount(accountId, jobId).orElse(null);
if (job == null) {
return;
if (job == null || isTerminalStatus(job.getStatus())) {
return false;
}
job.setStatus(status.name());
if (reason != null) {
@@ -1021,6 +1121,11 @@ public class BatchService {
job.setStartedAt(now());
}
putJobForAccount(accountId, job);
return true;
}
private boolean isTerminalStatus(String status) {
return TERMINAL_JOB_STATUSES.contains(status);
}
private void sleepQuietly() {
@@ -1419,6 +1524,9 @@ public class BatchService {
if (job.getArraySize() != null) {
ArrayRollup rollup = arrayRollup(job.getJobId());
summary.put("status", rollup.status());
if (job.getStatusReason() != null) {
summary.put("statusReason", job.getStatusReason());
}
if (rollup.startedAt() != null) {
summary.put("startedAt", rollup.startedAt());
}
@@ -1512,11 +1620,13 @@ public class BatchService {
for (BatchJob child : children) {
statusSummary.merge(child.getStatus(), 1, Integer::sum);
}
boolean allTerminal = !children.isEmpty()
&& children.stream().allMatch(child -> isTerminalStatus(child.getStatus()));
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) {
if (allTerminal && anyFailed) {
status = BatchStatus.FAILED.name();
} else if (allSucceeded) {
status = BatchStatus.SUCCEEDED.name();
@@ -1616,6 +1726,9 @@ public class BatchService {
if (job.getArraySize() != null) {
ArrayRollup rollup = arrayRollup(job.getJobId());
detail.put("status", rollup.status());
if (job.getStatusReason() != null) {
detail.put("statusReason", job.getStatusReason());
}
if (rollup.startedAt() != null) {
detail.put("startedAt", rollup.startedAt());
}