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

@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.services.batch;
import com.github.dockerjava.api.DockerClient;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.dns.EmbeddedDnsServer;
import io.github.hectorvent.floci.core.common.docker.ContainerBuilder;
@@ -8,15 +9,28 @@ import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager;
import io.github.hectorvent.floci.core.common.docker.ContainerLogStreamer;
import io.github.hectorvent.floci.core.common.docker.ContainerSpec;
import io.github.hectorvent.floci.services.batch.model.BatchJob;
import com.github.dockerjava.api.DockerClient;
import io.github.hectorvent.floci.services.batch.model.BatchNodeExecution;
import io.github.hectorvent.floci.services.batch.model.BatchRunResult;
import org.junit.jupiter.api.Test;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.RETURNS_SELF;
import static org.mockito.Mockito.mock;
@@ -99,6 +113,165 @@ class BatchDockerRunnerTest {
"io.floci.region", "us-east-1"));
}
@Test
void stopJobStopsAnInFlightContainer() throws Exception {
EmulatorConfig config = mock(EmulatorConfig.class);
EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);
EmulatorConfig.BatchServiceConfig batch = mock(EmulatorConfig.BatchServiceConfig.class);
when(config.services()).thenReturn(services);
when(services.batch()).thenReturn(batch);
when(batch.dockerNetwork()).thenReturn(Optional.empty());
when(config.port()).thenReturn(4566);
when(config.hostname()).thenReturn(Optional.empty());
CountDownLatch containerStarted = new CountDownLatch(1);
AtomicBoolean stopped = new AtomicBoolean();
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
when(lifecycleManager.createAndStart(any())).thenAnswer(invocation -> {
containerStarted.countDown();
return new ContainerLifecycleManager.ContainerInfo("container-id", Map.of());
});
DockerClient dockerClient = mock(DockerClient.class, RETURNS_DEEP_STUBS);
when(lifecycleManager.getDockerClient()).thenReturn(dockerClient);
when(dockerClient.inspectContainerCmd("container-id").exec().getState().getRunning())
.thenAnswer(invocation -> !stopped.get());
when(dockerClient.inspectContainerCmd("container-id").exec().getState().getExitCodeLong()).thenReturn(137L);
doAnswer(invocation -> {
stopped.set(true);
return null;
}).when(lifecycleManager).stopAndRemove(eq("container-id"), isNull());
ContainerBuilder containerBuilder = mock(ContainerBuilder.class);
ContainerBuilder.Builder builder = mock(ContainerBuilder.Builder.class, RETURNS_SELF);
when(containerBuilder.newContainer(anyString())).thenReturn(builder);
when(builder.build()).thenReturn(mock(ContainerSpec.class));
BatchDockerRunner runner = new BatchDockerRunner(containerBuilder, lifecycleManager,
mock(ContainerLogStreamer.class), config, mock(ContainerDetector.class));
BatchJob job = job();
AtomicReference<BatchRunResult> result = new AtomicReference<>();
Thread runThread = Thread.startVirtualThread(() -> result.set(runner.run(job, 1)));
assertTrue(containerStarted.await(2, TimeUnit.SECONDS));
runner.requestStop(job.getJobId());
runner.stopJob(job.getJobId());
runThread.join(2000);
assertFalse(runThread.isAlive());
assertEquals(137, result.get().exitCode());
verify(lifecycleManager).stopAndRemove("container-id", null);
}
@Test
void stopJobAfterRequestIsClearedDoesNotRecreateStopMarker() {
EmulatorConfig config = config(Optional.empty());
EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);
EmulatorConfig.BatchServiceConfig batch = mock(EmulatorConfig.BatchServiceConfig.class);
when(config.services()).thenReturn(services);
when(services.batch()).thenReturn(batch);
when(batch.dockerNetwork()).thenReturn(Optional.empty());
when(config.port()).thenReturn(4566);
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
when(lifecycleManager.createAndStart(any())).thenReturn(
new ContainerLifecycleManager.ContainerInfo("container-id", Map.of()));
DockerClient dockerClient = mock(DockerClient.class, RETURNS_DEEP_STUBS);
when(lifecycleManager.getDockerClient()).thenReturn(dockerClient);
when(dockerClient.inspectContainerCmd("container-id").exec().getState().getRunning()).thenReturn(false);
when(dockerClient.inspectContainerCmd("container-id").exec().getState().getExitCodeLong()).thenReturn(0L);
ContainerBuilder containerBuilder = mock(ContainerBuilder.class);
ContainerBuilder.Builder builder = mock(ContainerBuilder.Builder.class, RETURNS_SELF);
when(containerBuilder.newContainer(anyString())).thenReturn(builder);
when(builder.build()).thenReturn(mock(ContainerSpec.class));
BatchDockerRunner runner = new BatchDockerRunner(containerBuilder, lifecycleManager,
mock(ContainerLogStreamer.class), config, mock(ContainerDetector.class));
runner.requestStop("job-1");
runner.clearStopRequest("job-1");
runner.stopJob("job-1");
BatchRunResult result = runner.run(job(), 1);
assertEquals(0, result.exitCode());
verify(lifecycleManager).createAndStart(any());
}
@Test
void stopJobStopsEveryInFlightNodeContainer() throws Exception {
EmulatorConfig config = config(Optional.empty());
EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);
EmulatorConfig.BatchServiceConfig batch = mock(EmulatorConfig.BatchServiceConfig.class);
when(config.services()).thenReturn(services);
when(services.batch()).thenReturn(batch);
when(batch.dockerNetwork()).thenReturn(Optional.empty());
when(config.port()).thenReturn(4566);
CountDownLatch containersStarted = new CountDownLatch(2);
AtomicInteger containerSequence = new AtomicInteger();
Set<String> stoppedContainers = ConcurrentHashMap.newKeySet();
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
when(lifecycleManager.createAndStart(any())).thenAnswer(invocation -> {
String containerId = "container-" + containerSequence.getAndIncrement();
containersStarted.countDown();
return new ContainerLifecycleManager.ContainerInfo(containerId, Map.of());
});
DockerClient dockerClient = mock(DockerClient.class, RETURNS_DEEP_STUBS);
when(lifecycleManager.getDockerClient()).thenReturn(dockerClient);
for (int i = 0; i < 2; i++) {
String containerId = "container-" + i;
when(dockerClient.inspectContainerCmd(containerId).exec().getState().getRunning())
.thenAnswer(invocation -> !stoppedContainers.contains(containerId));
when(dockerClient.inspectContainerCmd(containerId).exec().getState().getExitCodeLong()).thenReturn(137L);
doAnswer(invocation -> {
stoppedContainers.add(containerId);
return null;
}).when(lifecycleManager).stopAndRemove(eq(containerId), isNull());
}
ContainerBuilder containerBuilder = mock(ContainerBuilder.class);
ContainerBuilder.Builder builder = mock(ContainerBuilder.Builder.class, RETURNS_SELF);
when(containerBuilder.newContainer(anyString())).thenReturn(builder);
when(builder.build()).thenReturn(mock(ContainerSpec.class));
BatchDockerRunner runner = new BatchDockerRunner(containerBuilder, lifecycleManager,
mock(ContainerLogStreamer.class), config, mock(ContainerDetector.class));
BatchJob job = job();
BatchNodeExecution firstNode = node(0);
BatchNodeExecution secondNode = node(1);
AtomicReference<BatchRunResult> firstResult = new AtomicReference<>();
AtomicReference<BatchRunResult> secondResult = new AtomicReference<>();
Thread firstThread = Thread.startVirtualThread(() -> firstResult.set(runner.run(job, 1, firstNode)));
Thread secondThread = Thread.startVirtualThread(() -> secondResult.set(runner.run(job, 1, secondNode)));
assertTrue(containersStarted.await(2, TimeUnit.SECONDS));
runner.requestStop(job.getJobId());
runner.stopJob(job.getJobId());
firstThread.join(2000);
secondThread.join(2000);
assertFalse(firstThread.isAlive());
assertFalse(secondThread.isAlive());
assertEquals(137, firstResult.get().exitCode());
assertEquals(137, secondResult.get().exitCode());
verify(lifecycleManager).stopAndRemove("container-0", null);
verify(lifecycleManager).stopAndRemove("container-1", null);
}
private BatchJob job() {
BatchJob job = new BatchJob();
job.setJobId("job-1");
job.setJobName("my-job");
job.setJobQueueName("my-queue");
job.setJobDefinitionName("my-def");
job.setContainerImage("busybox:stable");
job.setRegion("us-east-1");
job.setAccountId("000000000000");
return job;
}
private BatchNodeExecution node(int nodeIndex) {
BatchNodeExecution node = new BatchNodeExecution();
node.setNodeIndex(nodeIndex);
node.setContainerImage("busybox:stable");
return node;
}
private BatchDockerRunner runner(EmulatorConfig config, ContainerDetector detector) {
return new BatchDockerRunner(
mock(ContainerBuilder.class),
@@ -80,6 +80,49 @@ class BatchIntegrationTest {
.body("jobSummaryList.find { it.jobId == '%s' }.container.taskArn".formatted(jobId), nullValue());
}
@Test
void cancelAndTerminateJobExposeAwsRoutes() {
String suffix = uniqueSuffix();
String queueArn = createQueue("batch-control-queue-" + suffix,
createComputeEnvironment("batch-control-ce-" + suffix));
String definitionArn = registerJobDefinition("batch-control-job-" + suffix, "[]", "[]");
String jobId = submit(queueArn, definitionArn, "batch-control-submit-" + suffix);
givenJson("""
{"jobId":"%s","reason":"No longer needed"}
""".formatted(jobId))
.when()
.post("/v1/canceljob")
.then()
.statusCode(200);
givenJson("""
{"jobId":"%s","reason":"Stop requested"}
""".formatted(jobId))
.when()
.post("/v1/terminatejob")
.then()
.statusCode(200);
givenJson("""
{"jobId":"%s"}
""".formatted(jobId))
.when()
.post("/v1/canceljob")
.then()
.statusCode(400)
.body("__type", equalTo("ClientException"));
givenJson("""
{"jobId":"missing-job","reason":"Stop requested"}
""")
.when()
.post("/v1/terminatejob")
.then()
.statusCode(400)
.body("__type", equalTo("ClientException"));
}
@Test
void jobDefinitionRevisionsAndDeregister() {
String suffix = uniqueSuffix();
@@ -14,6 +14,7 @@ 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 io.github.hectorvent.floci.services.batch.model.BatchStatus;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
@@ -23,14 +24,19 @@ import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.function.Predicate;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@@ -779,6 +785,265 @@ class BatchServiceTest {
assertEquals("ClientException", e.getErrorCode());
}
@Test
void cancelJobFailsRunnableJobWithRequestedReason() throws Exception {
InMemoryStorage<String, BatchJob> jobStore = new InMemoryStorage<>();
BatchService service = service("immediate", jobStore, mock(BatchDockerRunner.class));
BatchJob job = storedJob("cancel-runnable", BatchStatus.RUNNABLE);
jobStore.put(job.getJobId(), job);
service.cancelJob(json("""
{"jobId":"cancel-runnable","reason":"No longer needed"}
"""));
JsonNode detail = service.describeJobs(json("""
{"jobs":["cancel-runnable"]}
""")).path("jobs").get(0);
assertEquals("FAILED", detail.path("status").asText());
assertEquals("No longer needed", detail.path("statusReason").asText());
assertTrue(detail.path("stoppedAt").asLong() > 0);
}
@Test
void cancelJobDoesNotStopRunningJob() throws Exception {
BatchDockerRunner runner = mock(BatchDockerRunner.class);
CountDownLatch runStarted = new CountDownLatch(1);
CountDownLatch releaseRun = new CountDownLatch(1);
when(runner.run(any(BatchJob.class), anyInt())).thenAnswer(invocation -> {
runStarted.countDown();
assertTrue(releaseRun.await(2, TimeUnit.SECONDS));
return new BatchRunResult(0, null, "log-stream", 1L, 2L, false);
});
BatchService service = dockerService(runner);
String queueArn = arrayReadyQueue(service);
String definitionArn = service.registerJobDefinition(json("""
{
"jobDefinitionName":"cancel-running-job",
"type":"container",
"containerProperties":{"image":"job:latest"}
}
"""), REGION).path("jobDefinitionArn").asText();
String jobId = service.submitJob(json("""
{"jobName":"cancel-running","jobQueue":"%s","jobDefinition":"%s"}
""".formatted(queueArn, definitionArn)), REGION).path("jobId").asText();
assertTrue(runStarted.await(2, TimeUnit.SECONDS));
try {
service.cancelJob(json("""
{"jobId":"%s","reason":"Too late to cancel"}
""".formatted(jobId)));
JsonNode running = service.describeJobs(json("""
{"jobs":["%s"]}
""".formatted(jobId))).path("jobs").get(0);
assertEquals("RUNNING", running.path("status").asText());
verify(runner, never()).requestStop(jobId);
verify(runner, never()).stopJob(jobId);
} finally {
releaseRun.countDown();
}
assertNotNull(waitForJobStatus(service, jobId, "SUCCEEDED"));
}
@Test
void terminateJobStopsRunningContainerAndPreservesRequestedReason() throws Exception {
BatchDockerRunner runner = mock(BatchDockerRunner.class);
CountDownLatch runStarted = new CountDownLatch(1);
CountDownLatch stopRequested = new CountDownLatch(1);
when(runner.run(any(BatchJob.class), anyInt())).thenAnswer(invocation -> {
runStarted.countDown();
assertTrue(stopRequested.await(2, TimeUnit.SECONDS));
return new BatchRunResult(137, "Job terminated", "log-stream", 1L, 2L, false);
});
doAnswer(invocation -> {
stopRequested.countDown();
return null;
}).when(runner).requestStop(any(String.class));
BatchService service = dockerService(runner);
String queueArn = arrayReadyQueue(service);
String definitionArn = service.registerJobDefinition(json("""
{
"jobDefinitionName":"terminate-running-job",
"type":"container",
"containerProperties":{"image":"job:latest"}
}
"""), REGION).path("jobDefinitionArn").asText();
String jobId = service.submitJob(json("""
{"jobName":"terminate-running","jobQueue":"%s","jobDefinition":"%s"}
""".formatted(queueArn, definitionArn)), REGION).path("jobId").asText();
assertTrue(runStarted.await(2, TimeUnit.SECONDS));
service.terminateJob(json("""
{"jobId":"%s","reason":"Operator requested shutdown"}
""".formatted(jobId)));
JsonNode failed = waitForJobStatus(service, jobId, "FAILED");
assertNotNull(failed);
assertEquals("Operator requested shutdown", failed.path("statusReason").asText());
JsonNode failedWithAttempt = waitForJobAttemptCount(service, jobId, 1);
assertNotNull(failedWithAttempt);
assertEquals(137, failedWithAttempt.path("attempts").get(0).path("container").path("exitCode").asInt());
assertEquals("Operator requested shutdown", failedWithAttempt.path("statusReason").asText());
verify(runner).requestStop(jobId);
verify(runner).stopJob(jobId);
}
@Test
void jobControlValidatesRequiredFieldsReasonLimitAndUnknownJobs() throws Exception {
InMemoryStorage<String, BatchJob> jobStore = new InMemoryStorage<>();
BatchService service = immediateService(jobStore);
AwsException missingJobId = assertThrows(AwsException.class, () -> service.cancelJob(json("""
{"reason":"No longer needed"}
""")));
assertEquals("ClientException", missingJobId.getErrorCode());
assertEquals("jobId is required", missingJobId.getMessage());
AwsException missingReason = assertThrows(AwsException.class, () -> service.terminateJob(json("""
{"jobId":"job-1"}
""")));
assertEquals("ClientException", missingReason.getErrorCode());
assertEquals("reason is required", missingReason.getMessage());
BatchJob boundaryJob = storedJob("boundary-job", BatchStatus.RUNNABLE);
jobStore.put(boundaryJob.getJobId(), boundaryJob);
String boundaryReason = "x".repeat(1024);
service.cancelJob(json("""
{"jobId":"boundary-job","reason":"%s"}
""".formatted(boundaryReason)));
JsonNode boundaryDetail = service.describeJobs(json("""
{"jobs":["boundary-job"]}
""")).path("jobs").get(0);
assertEquals(boundaryReason, boundaryDetail.path("statusReason").asText());
BatchJob overLimitJob = storedJob("over-limit-job", BatchStatus.RUNNABLE);
jobStore.put(overLimitJob.getJobId(), overLimitJob);
AwsException overLimit = assertThrows(AwsException.class, () -> service.cancelJob(json("""
{"jobId":"over-limit-job","reason":"%s"}
""".formatted("x".repeat(1025)))));
assertEquals("ClientException", overLimit.getErrorCode());
AwsException unknownJob = assertThrows(AwsException.class, () -> service.terminateJob(json("""
{"jobId":"unknown-job","reason":"Stop requested"}
""")));
assertEquals("ClientException", unknownJob.getErrorCode());
assertEquals("Job not found: unknown-job", unknownJob.getMessage());
}
@Test
void jobControlIsIdempotentForTerminalJobs() throws Exception {
InMemoryStorage<String, BatchJob> jobStore = new InMemoryStorage<>();
BatchDockerRunner runner = mock(BatchDockerRunner.class);
BatchService service = service("docker", jobStore, runner);
BatchJob succeeded = storedJob("succeeded-job", BatchStatus.SUCCEEDED);
succeeded.setStatusReason("Job completed successfully");
BatchJob failed = storedJob("failed-job", BatchStatus.FAILED);
failed.setStatusReason("Original failure");
jobStore.put(succeeded.getJobId(), succeeded);
jobStore.put(failed.getJobId(), failed);
service.cancelJob(json("""
{"jobId":"succeeded-job","reason":"Cancel again"}
"""));
service.terminateJob(json("""
{"jobId":"failed-job","reason":"Terminate again"}
"""));
JsonNode jobs = service.describeJobs(json("""
{"jobs":["succeeded-job","failed-job"]}
""")).path("jobs");
assertEquals("SUCCEEDED", jobs.get(0).path("status").asText());
assertEquals("Job completed successfully", jobs.get(0).path("statusReason").asText());
assertEquals("FAILED", jobs.get(1).path("status").asText());
assertEquals("Original failure", jobs.get(1).path("statusReason").asText());
verify(runner, never()).requestStop(any(String.class));
verify(runner, never()).stopJob(any(String.class));
}
@Test
void terminateMultiNodeJobStopsNodesAndPreservesRequestedReason() throws Exception {
BatchDockerRunner runner = mock(BatchDockerRunner.class);
CountDownLatch nodesStarted = new CountDownLatch(2);
CountDownLatch stopRequested = new CountDownLatch(1);
when(runner.run(any(BatchJob.class), anyInt(), any(BatchNodeExecution.class)))
.thenAnswer(invocation -> {
BatchNodeExecution node = invocation.getArgument(2);
nodesStarted.countDown();
assertTrue(stopRequested.await(2, TimeUnit.SECONDS));
return new BatchRunResult(137, "Job terminated", "log-" + node.getNodeIndex(),
1L, 2L, false);
});
doAnswer(invocation -> {
stopRequested.countDown();
return null;
}).when(runner).requestStop(any(String.class));
BatchService service = dockerService(runner);
String queueArn = arrayReadyQueue(service);
String definitionArn = service.registerJobDefinition(json("""
{
"jobDefinitionName":"terminate-mnp-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":"terminate-mnp","jobQueue":"%s","jobDefinition":"%s"}
""".formatted(queueArn, definitionArn)), REGION).path("jobId").asText();
assertTrue(nodesStarted.await(2, TimeUnit.SECONDS));
service.terminateJob(json("""
{"jobId":"%s","reason":"Stop every node"}
""".formatted(jobId)));
JsonNode failedWithAttempt = waitForJobAttemptCount(service, jobId, 1);
assertNotNull(failedWithAttempt);
assertEquals("FAILED", failedWithAttempt.path("status").asText());
assertEquals("Stop every node", failedWithAttempt.path("statusReason").asText());
JsonNode nodes = service.listJobs(json("""
{"multiNodeJobId":"%s"}
""".formatted(jobId))).path("jobSummaryList");
assertEquals(137, nodes.get(0).path("container").path("exitCode").asInt());
assertEquals(137, nodes.get(1).path("container").path("exitCode").asInt());
verify(runner).requestStop(jobId);
verify(runner).stopJob(jobId);
}
@Test
void terminateArrayParentFailsAndStopsEveryNonterminalChild() throws Exception {
InMemoryStorage<String, BatchJob> jobStore = new InMemoryStorage<>();
BatchDockerRunner runner = mock(BatchDockerRunner.class);
BatchService service = service("docker", jobStore, runner);
BatchJob parent = storedJob("array-parent", BatchStatus.SUBMITTED);
parent.setArraySize(2);
BatchJob first = storedJob("array-parent:0", BatchStatus.RUNNABLE);
first.setArrayJobId(parent.getJobId());
first.setArrayIndex(0);
BatchJob second = storedJob("array-parent:1", BatchStatus.RUNNING);
second.setArrayJobId(parent.getJobId());
second.setArrayIndex(1);
jobStore.put(parent.getJobId(), parent);
jobStore.put(first.getJobId(), first);
jobStore.put(second.getJobId(), second);
service.terminateJob(json("""
{"jobId":"array-parent","reason":"Stop the array"}
"""));
JsonNode detail = service.describeJobs(json("""
{"jobs":["array-parent","array-parent:0","array-parent:1"]}
""")).path("jobs");
assertEquals("FAILED", detail.get(0).path("status").asText());
assertEquals("Stop the array", detail.get(0).path("statusReason").asText());
assertEquals("FAILED", detail.get(1).path("status").asText());
assertEquals("FAILED", detail.get(2).path("status").asText());
verify(runner).requestStop("array-parent:1");
verify(runner, never()).stopJob("array-parent:0");
verify(runner).stopJob("array-parent:1");
}
private String arrayReadyQueue(BatchService service) throws Exception {
String suffix = UUID.randomUUID().toString();
String computeArn = service.createComputeEnvironment(json("""
@@ -794,31 +1059,17 @@ class BatchServiceTest {
}
private BatchService dockerService(BatchDockerRunner runner) {
EmulatorConfig config = mock(EmulatorConfig.class);
EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);
EmulatorConfig.BatchServiceConfig batch = mock(EmulatorConfig.BatchServiceConfig.class);
when(config.services()).thenReturn(services);
when(services.batch()).thenReturn(batch);
when(batch.runnerMode()).thenReturn("docker");
return new BatchService(
new InMemoryStorage<String, BatchJobDefinition>(),
new InMemoryStorage<String, BatchJobQueue>(),
new InMemoryStorage<String, BatchComputeEnvironment>(),
new InMemoryStorage<String, BatchJob>(),
new RegionResolver(REGION, ACCOUNT),
config,
objectMapper,
runner);
return service("docker", new InMemoryStorage<String, BatchJob>(), runner);
}
private BatchService immediateService(StorageBackend<String, BatchJob> jobStore) {
private BatchService service(String runnerMode, StorageBackend<String, BatchJob> jobStore,
BatchDockerRunner runner) {
EmulatorConfig config = mock(EmulatorConfig.class);
EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);
EmulatorConfig.BatchServiceConfig batch = mock(EmulatorConfig.BatchServiceConfig.class);
when(config.services()).thenReturn(services);
when(services.batch()).thenReturn(batch);
when(batch.runnerMode()).thenReturn("immediate");
when(batch.runnerMode()).thenReturn(runnerMode);
return new BatchService(
new InMemoryStorage<String, BatchJobDefinition>(),
@@ -828,7 +1079,25 @@ class BatchServiceTest {
new RegionResolver(REGION, ACCOUNT),
config,
objectMapper,
mock(BatchDockerRunner.class));
runner);
}
private BatchService immediateService(StorageBackend<String, BatchJob> jobStore) {
return service("immediate", jobStore, mock(BatchDockerRunner.class));
}
private BatchJob storedJob(String jobId, BatchStatus status) {
BatchJob job = new BatchJob();
job.setJobId(jobId);
job.setJobArn("arn:aws:batch:us-east-1:" + ACCOUNT + ":job/" + jobId);
job.setJobName(jobId);
job.setJobQueue("queue");
job.setJobDefinition("definition");
job.setStatus(status.name());
job.setCreatedAt(1L);
job.setRegion(REGION);
job.setAccountId(ACCOUNT);
return job;
}
private ObjectNode json(String body) throws Exception {
@@ -848,6 +1117,19 @@ class BatchServiceTest {
return null;
}
private JsonNode waitForJobAttemptCount(BatchService service, String jobId, int attemptCount) throws Exception {
ObjectNode request = objectMapper.createObjectNode();
request.putArray("jobs").add(jobId);
for (int i = 0; i < 100; i++) {
JsonNode job = service.describeJobs(request).path("jobs").get(0);
if (job != null && job.path("attempts").size() == attemptCount) {
return job;
}
Thread.sleep(10);
}
return null;
}
private static final class ReverseScanJobStorage implements StorageBackend<String, BatchJob> {
private final LinkedHashMap<String, BatchJob> store = new LinkedHashMap<>();