mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(batch): add AWS Batch service support (#1332)
This commit is contained in:
1 parent
234af69bd2
commit
022436eaae
39 files changed
+4516
-4
No files matched your search
+75
@@ -0,0 +1,75 @@
|
||||
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.ContainerDetector;
|
||||
import io.github.hectorvent.floci.services.batch.model.BatchJob;
|
||||
import io.github.hectorvent.floci.services.batch.model.BatchRunResult;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.Assumptions;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
@QuarkusTest
|
||||
class BatchDockerRunnerDockerIntegrationTest {
|
||||
|
||||
private static final String IMAGE = "public.ecr.aws/docker/library/busybox:latest";
|
||||
|
||||
@Inject
|
||||
BatchDockerRunner runner;
|
||||
|
||||
@Inject
|
||||
DockerClient dockerClient;
|
||||
|
||||
@Inject
|
||||
EmulatorConfig config;
|
||||
|
||||
@Inject
|
||||
ContainerDetector containerDetector;
|
||||
|
||||
@BeforeEach
|
||||
void requireDocker() {
|
||||
Assumptions.assumeTrue(isDockerAvailable(), "Docker daemon must be available for Batch Docker runner tests");
|
||||
}
|
||||
|
||||
@Test
|
||||
void dockerRunnerInjectsContainerReachableEndpoint() {
|
||||
String suffix = Long.toString(System.nanoTime(), 36);
|
||||
String expectedHostname = containerDetector.isRunningInContainer()
|
||||
? config.hostname().orElse(EmbeddedDnsServer.DEFAULT_SUFFIX)
|
||||
: "host.docker.internal";
|
||||
String expectedEndpoint = "http://" + expectedHostname + ":" + config.port();
|
||||
|
||||
BatchJob job = new BatchJob();
|
||||
job.setJobId("docker-env-" + suffix);
|
||||
job.setJobName("docker-env-" + suffix);
|
||||
job.setJobDefinitionName("docker-env-test");
|
||||
job.setJobQueueName("docker-env-test-queue");
|
||||
job.setRegion(config.defaultRegion());
|
||||
job.setContainerImage(IMAGE);
|
||||
job.setResolvedCommand(List.of("sh", "-c", """
|
||||
test "$AWS_ENDPOINT_URL" = "%s" &&
|
||||
test "$FLOCI_ENDPOINT" = "%s" &&
|
||||
test "$FLOCI_HOSTNAME" = "%s"
|
||||
""".formatted(expectedEndpoint, expectedEndpoint, expectedHostname)));
|
||||
|
||||
BatchRunResult result = runner.run(job, 1);
|
||||
|
||||
assertEquals(0, result.exitCode(), result.reason());
|
||||
}
|
||||
|
||||
private boolean isDockerAvailable() {
|
||||
try {
|
||||
dockerClient.pingCmd().exec();
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package io.github.hectorvent.floci.services.batch;
|
||||
|
||||
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;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerDetector;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerLogStreamer;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class BatchDockerRunnerTest {
|
||||
|
||||
@Test
|
||||
void resolveEndpointHostnameUsesHostGatewayWhenFlociRunsNatively() {
|
||||
ContainerDetector detector = mock(ContainerDetector.class);
|
||||
when(detector.isRunningInContainer()).thenReturn(false);
|
||||
|
||||
assertEquals("host.docker.internal", runner(config(Optional.empty()), detector).resolveEndpointHostname());
|
||||
}
|
||||
|
||||
@Test
|
||||
void resolveEndpointHostnameUsesConfiguredHostnameWhenFlociRunsInContainer() {
|
||||
ContainerDetector detector = mock(ContainerDetector.class);
|
||||
when(detector.isRunningInContainer()).thenReturn(true);
|
||||
|
||||
assertEquals("floci.internal", runner(config(Optional.of("floci.internal")), detector).resolveEndpointHostname());
|
||||
}
|
||||
|
||||
@Test
|
||||
void resolveEndpointHostnameUsesEmbeddedDnsSuffixWhenContainerizedWithoutHostname() {
|
||||
ContainerDetector detector = mock(ContainerDetector.class);
|
||||
when(detector.isRunningInContainer()).thenReturn(true);
|
||||
|
||||
assertEquals(EmbeddedDnsServer.DEFAULT_SUFFIX, runner(config(Optional.empty()), detector).resolveEndpointHostname());
|
||||
}
|
||||
|
||||
private BatchDockerRunner runner(EmulatorConfig config, ContainerDetector detector) {
|
||||
return new BatchDockerRunner(
|
||||
mock(ContainerBuilder.class),
|
||||
mock(ContainerLifecycleManager.class),
|
||||
mock(ContainerLogStreamer.class),
|
||||
config,
|
||||
detector);
|
||||
}
|
||||
|
||||
private EmulatorConfig config(Optional<String> hostname) {
|
||||
EmulatorConfig config = mock(EmulatorConfig.class);
|
||||
when(config.hostname()).thenReturn(hostname);
|
||||
return config;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,539 @@
|
||||
package io.github.hectorvent.floci.services.batch;
|
||||
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.greaterThan;
|
||||
import static org.hamcrest.Matchers.hasSize;
|
||||
import static org.hamcrest.Matchers.notNullValue;
|
||||
import static org.hamcrest.Matchers.nullValue;
|
||||
|
||||
@QuarkusTest
|
||||
class BatchIntegrationTest {
|
||||
|
||||
private static final String AUTH =
|
||||
"AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/batch/aws4_request";
|
||||
|
||||
@Test
|
||||
void submitDescribeAndListImmediateJob() {
|
||||
String suffix = uniqueSuffix();
|
||||
String queueArn = createQueue("batch-queue-" + suffix, createComputeEnvironment("batch-ce-" + suffix));
|
||||
String definitionArn = registerJobDefinition("batch-job-" + suffix,
|
||||
"[\"Ref::inputKey\",\"Ref::outputKey\",\"--literal\"]",
|
||||
"[{\"name\":\"MODE\",\"value\":\"definition\"}]");
|
||||
|
||||
String jobId = givenJson("""
|
||||
{
|
||||
"jobName": "batch-submit-%s",
|
||||
"jobQueue": "%s",
|
||||
"jobDefinition": "%s",
|
||||
"parameters": {
|
||||
"inputKey": "payloads/input.json",
|
||||
"outputKey": "payloads/output.json"
|
||||
},
|
||||
"containerOverrides": {
|
||||
"environment": [{"name":"MODE","value":"override"}]
|
||||
},
|
||||
"timeout": {"attemptDurationSeconds": 60}
|
||||
}
|
||||
""".formatted(suffix, queueArn, definitionArn))
|
||||
.when()
|
||||
.post("/v1/submitjob")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("jobId", notNullValue())
|
||||
.body("jobArn", containsString(":batch:us-east-1:000000000000:job/"))
|
||||
.extract().path("jobId");
|
||||
|
||||
givenJson("{\"jobs\":[\"%s\"]}".formatted(jobId))
|
||||
.when()
|
||||
.post("/v1/describejobs")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("jobs", hasSize(1))
|
||||
.body("jobs[0].status", equalTo("SUCCEEDED"))
|
||||
.body("jobs[0].jobQueue", equalTo(queueArn))
|
||||
.body("jobs[0].jobDefinition", equalTo(definitionArn))
|
||||
.body("jobs[0].container.command[0]", equalTo("payloads/input.json"))
|
||||
.body("jobs[0].container.command[1]", equalTo("payloads/output.json"))
|
||||
.body("jobs[0].container.command[2]", equalTo("--literal"))
|
||||
.body("jobs[0].container.environment.find { it.name == 'MODE' }.value", equalTo("override"))
|
||||
.body("jobs[0].attempts", hasSize(1))
|
||||
.body("jobs[0].attempts[0].container.exitCode", equalTo(0))
|
||||
.body("jobs[0].attempts[0].container.taskArn", nullValue());
|
||||
|
||||
givenJson("{\"jobQueue\":\"%s\",\"jobStatus\":\"SUCCEEDED\"}".formatted(queueArn))
|
||||
.when()
|
||||
.post("/v1/listjobs")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("jobSummaryList", hasSize(greaterThan(0)))
|
||||
.body("jobSummaryList.find { it.jobId == '%s' }.status".formatted(jobId), equalTo("SUCCEEDED"))
|
||||
.body("jobSummaryList.find { it.jobId == '%s' }.jobQueue".formatted(jobId), nullValue())
|
||||
.body("jobSummaryList.find { it.jobId == '%s' }.container.exitCode".formatted(jobId), equalTo(0))
|
||||
.body("jobSummaryList.find { it.jobId == '%s' }.container.logStreamName".formatted(jobId), nullValue())
|
||||
.body("jobSummaryList.find { it.jobId == '%s' }.container.taskArn".formatted(jobId), nullValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
void jobDefinitionRevisionsAndDeregister() {
|
||||
String suffix = uniqueSuffix();
|
||||
String queueArn = createQueue("batch-rev-queue-" + suffix, createComputeEnvironment("batch-rev-ce-" + suffix));
|
||||
String jobName = "batch-rev-job-" + suffix;
|
||||
String revisionOne = registerJobDefinition(jobName, "[\"rev1\"]", "[]");
|
||||
String revisionTwo = registerJobDefinition(jobName, "[\"rev2\"]", "[]");
|
||||
|
||||
givenJson("{\"jobDefinition\":\"%s\"}".formatted(jobName))
|
||||
.when()
|
||||
.post("/v1/deregisterjobdefinition")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("ClientException"));
|
||||
|
||||
givenJson("{\"jobDefinition\":\"%s\"}".formatted(revisionTwo))
|
||||
.when()
|
||||
.post("/v1/deregisterjobdefinition")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
givenJson("{\"jobDefinitionName\":\"%s\",\"status\":\"ACTIVE\"}".formatted(jobName))
|
||||
.when()
|
||||
.post("/v1/describejobdefinitions")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("jobDefinitions", hasSize(1))
|
||||
.body("jobDefinitions[0].jobDefinitionArn", equalTo(revisionOne))
|
||||
.body("jobDefinitions[0].revision", equalTo(1));
|
||||
|
||||
String jobId = givenJson("""
|
||||
{"jobName":"latest-active-%s","jobQueue":"%s","jobDefinition":"%s"}
|
||||
""".formatted(suffix, queueArn, jobName))
|
||||
.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].jobDefinition", equalTo(revisionOne))
|
||||
.body("jobs[0].container.command[0]", equalTo("rev1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void submitResolvesJobDefinitionNameRevisionAndArns() {
|
||||
String suffix = uniqueSuffix();
|
||||
String queueArn = createQueue("batch-resolve-queue-" + suffix, createComputeEnvironment("batch-resolve-ce-" + suffix));
|
||||
String jobName = "batch-resolve-job-" + suffix;
|
||||
String revisionOne = registerJobDefinition(jobName, "[\"rev1\"]", "[]");
|
||||
String revisionTwo = registerJobDefinition(jobName, "[\"rev2\"]", "[]");
|
||||
String arnWithoutRevision = revisionTwo.substring(0, revisionTwo.lastIndexOf(':'));
|
||||
|
||||
String byNameRevision = submit(queueArn, jobName + ":1", "batch-resolve-name-rev-" + suffix);
|
||||
String byFullArn = submit(queueArn, revisionTwo, "batch-resolve-full-arn-" + suffix);
|
||||
String byArnWithoutRevision = submit(queueArn, arnWithoutRevision, "batch-resolve-arn-latest-" + suffix);
|
||||
|
||||
givenJson("{\"jobs\":[\"%s\",\"%s\",\"%s\"]}".formatted(byNameRevision, byFullArn, byArnWithoutRevision))
|
||||
.when()
|
||||
.post("/v1/describejobs")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("jobs.find { it.jobId == '%s' }.jobDefinition".formatted(byNameRevision), equalTo(revisionOne))
|
||||
.body("jobs.find { it.jobId == '%s' }.container.command[0]".formatted(byNameRevision), equalTo("rev1"))
|
||||
.body("jobs.find { it.jobId == '%s' }.jobDefinition".formatted(byFullArn), equalTo(revisionTwo))
|
||||
.body("jobs.find { it.jobId == '%s' }.container.command[0]".formatted(byFullArn), equalTo("rev2"))
|
||||
.body("jobs.find { it.jobId == '%s' }.jobDefinition".formatted(byArnWithoutRevision), equalTo(revisionTwo))
|
||||
.body("jobs.find { it.jobId == '%s' }.container.command[0]".formatted(byArnWithoutRevision), equalTo("rev2"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void listJobsPaginatesNewestFirst() throws Exception {
|
||||
String suffix = uniqueSuffix();
|
||||
String queueArn = createQueue("batch-page-queue-" + suffix, createComputeEnvironment("batch-page-ce-" + suffix));
|
||||
String definitionArn = registerJobDefinition("batch-page-job-" + suffix, "[\"ok\"]", "[]");
|
||||
String firstName = "batch-page-first-" + suffix;
|
||||
String secondName = "batch-page-second-" + suffix;
|
||||
|
||||
submit(queueArn, definitionArn, firstName);
|
||||
Thread.sleep(5);
|
||||
submit(queueArn, definitionArn, secondName);
|
||||
|
||||
String nextToken = givenJson("""
|
||||
{"jobQueue":"%s","jobStatus":"SUCCEEDED","maxResults":1}
|
||||
""".formatted(queueArn))
|
||||
.when()
|
||||
.post("/v1/listjobs")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("jobSummaryList", hasSize(1))
|
||||
.body("jobSummaryList[0].jobName", equalTo(secondName))
|
||||
.body("nextToken", equalTo("1"))
|
||||
.extract().path("nextToken");
|
||||
|
||||
givenJson("""
|
||||
{"jobQueue":"%s","jobStatus":"SUCCEEDED","maxResults":1,"nextToken":"%s"}
|
||||
""".formatted(queueArn, nextToken))
|
||||
.when()
|
||||
.post("/v1/listjobs")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("jobSummaryList", hasSize(1))
|
||||
.body("jobSummaryList[0].jobName", equalTo(firstName));
|
||||
}
|
||||
|
||||
@Test
|
||||
void listJobsUsesAwsFilters() throws Exception {
|
||||
String suffix = uniqueSuffix();
|
||||
String queueArn = createQueue("batch-dedupe-queue-" + suffix, createComputeEnvironment("batch-dedupe-ce-" + suffix));
|
||||
String definitionArn = registerJobDefinition("batch-dedupe-job-" + suffix, "[\"ok\"]", "[]");
|
||||
String prefix = "batch-dedupe-match-" + suffix;
|
||||
String oldName = prefix + "-old";
|
||||
String newName = prefix + "-new";
|
||||
|
||||
submit(queueArn, definitionArn, oldName);
|
||||
Thread.sleep(5);
|
||||
long createdAfter = System.currentTimeMillis();
|
||||
Thread.sleep(5);
|
||||
submit(queueArn, definitionArn, newName);
|
||||
submit(queueArn, definitionArn, "batch-dedupe-other-" + suffix);
|
||||
|
||||
givenJson("""
|
||||
{
|
||||
"jobQueue":"%s",
|
||||
"jobStatus":"RUNNING",
|
||||
"filters":[{"name":"JOB_NAME","values":["%s*"]}]
|
||||
}
|
||||
""".formatted(queueArn, prefix.toUpperCase()))
|
||||
.when()
|
||||
.post("/v1/listjobs")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("jobSummaryList", hasSize(2))
|
||||
.body("jobSummaryList.find { it.jobName == '%s' }.jobId".formatted(oldName), notNullValue())
|
||||
.body("jobSummaryList.find { it.jobName == '%s' }.jobId".formatted(newName), notNullValue());
|
||||
|
||||
givenJson("""
|
||||
{
|
||||
"jobQueue":"%s",
|
||||
"jobStatus":"SUCCEEDED",
|
||||
"filters":[{"name":"AFTER_CREATED_AT","values":["%d"]}]
|
||||
}
|
||||
""".formatted(queueArn, createdAfter))
|
||||
.when()
|
||||
.post("/v1/listjobs")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("jobSummaryList", hasSize(2))
|
||||
.body("jobSummaryList.find { it.jobName == '%s' }.jobId".formatted(newName), notNullValue())
|
||||
.body("jobSummaryList.find { it.jobName == 'batch-dedupe-other-%s' }.jobId".formatted(suffix), notNullValue());
|
||||
|
||||
givenJson("""
|
||||
{
|
||||
"jobQueue":"%s",
|
||||
"filters":[
|
||||
{"name":"JOB_NAME","values":["%s*"]},
|
||||
{"name":"AFTER_CREATED_AT","values":["%d"]}
|
||||
]
|
||||
}
|
||||
""".formatted(queueArn, prefix, createdAfter))
|
||||
.when()
|
||||
.post("/v1/listjobs")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("ClientException"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void describeControlPlaneResourcesPaginateAndValidateJobDefinitionFilters() {
|
||||
String suffix = uniqueSuffix();
|
||||
String firstCompute = createComputeEnvironment("batch-desc-ce-a-" + suffix);
|
||||
String secondCompute = createComputeEnvironment("batch-desc-ce-b-" + suffix);
|
||||
createQueue("batch-desc-queue-a-" + suffix, firstCompute);
|
||||
createQueue("batch-desc-queue-b-" + suffix, secondCompute);
|
||||
String definitionOne = registerJobDefinition("batch-desc-job-a-" + suffix, "[\"a\"]", "[]");
|
||||
String definitionTwo = registerJobDefinition("batch-desc-job-b-" + suffix, "[\"b\"]", "[]");
|
||||
|
||||
givenJson("{\"computeEnvironments\":[\"%s\",\"%s\"],\"maxResults\":1}".formatted(firstCompute, secondCompute))
|
||||
.when()
|
||||
.post("/v1/describecomputeenvironments")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("computeEnvironments", hasSize(1))
|
||||
.body("computeEnvironments[0].createdAt", nullValue())
|
||||
.body("computeEnvironments[0].region", nullValue())
|
||||
.body("computeEnvironments[0].accountId", nullValue())
|
||||
.body("nextToken", equalTo("1"));
|
||||
|
||||
givenJson("{\"jobQueues\":[\"batch-desc-queue-a-%s\"],\"maxResults\":1}".formatted(suffix))
|
||||
.when()
|
||||
.post("/v1/describejobqueues")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("jobQueues", hasSize(1))
|
||||
.body("jobQueues[0].createdAt", nullValue())
|
||||
.body("jobQueues[0].region", nullValue())
|
||||
.body("jobQueues[0].accountId", nullValue());
|
||||
|
||||
givenJson("""
|
||||
{"jobDefinitions":["%s","%s"],"maxResults":1}
|
||||
""".formatted(definitionOne, definitionTwo))
|
||||
.when()
|
||||
.post("/v1/describejobdefinitions")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("jobDefinitions", hasSize(1))
|
||||
.body("jobDefinitions[0].createdAt", nullValue())
|
||||
.body("jobDefinitions[0].region", nullValue())
|
||||
.body("jobDefinitions[0].accountId", nullValue())
|
||||
.body("jobDefinitions[0].containerProperties.jobRoleArn", nullValue())
|
||||
.body("jobDefinitions[0].retryStrategy.evaluateOnExit", nullValue())
|
||||
.body("nextToken", equalTo("1"));
|
||||
|
||||
givenJson("""
|
||||
{"jobDefinitions":["%s"],"status":"ACTIVE"}
|
||||
""".formatted(definitionOne))
|
||||
.when()
|
||||
.post("/v1/describejobdefinitions")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("ClientException"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void validationErrorsUseClientException() {
|
||||
String suffix = uniqueSuffix();
|
||||
String queueArn = createQueue("batch-error-queue-" + suffix, createComputeEnvironment("batch-error-ce-" + suffix));
|
||||
String definitionArn = registerJobDefinition("batch-error-job-" + suffix, "[\"ok\"]", "[]");
|
||||
|
||||
givenJson("{}")
|
||||
.when()
|
||||
.post("/v1/listjobs")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("ClientException"));
|
||||
|
||||
givenJson("""
|
||||
{"jobName":"missing-queue-%s","jobQueue":"missing","jobDefinition":"%s"}
|
||||
""".formatted(suffix, definitionArn))
|
||||
.when()
|
||||
.post("/v1/submitjob")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("ClientException"));
|
||||
|
||||
givenJson("""
|
||||
{
|
||||
"jobName":"bad-env-%s",
|
||||
"jobQueue":"%s",
|
||||
"jobDefinition":"%s",
|
||||
"containerOverrides": {
|
||||
"environment": [{"name":"AWS_BATCH_BAD","value":"nope"}]
|
||||
}
|
||||
}
|
||||
""".formatted(suffix, queueArn, definitionArn))
|
||||
.when()
|
||||
.post("/v1/submitjob")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("ClientException"));
|
||||
|
||||
givenJson("""
|
||||
{
|
||||
"jobDefinitionName": "bad-retry-%s",
|
||||
"type": "container",
|
||||
"containerProperties": {"image":"public.ecr.aws/example/job:latest"},
|
||||
"retryStrategy": {"attempts": 11}
|
||||
}
|
||||
""".formatted(suffix))
|
||||
.when()
|
||||
.post("/v1/registerjobdefinition")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("ClientException"));
|
||||
|
||||
givenJson("""
|
||||
{
|
||||
"jobDefinitionName": "bad-timeout-%s",
|
||||
"type": "container",
|
||||
"containerProperties": {"image":"public.ecr.aws/example/job:latest"},
|
||||
"timeout": {"attemptDurationSeconds": 59}
|
||||
}
|
||||
""".formatted(suffix))
|
||||
.when()
|
||||
.post("/v1/registerjobdefinition")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("ClientException"));
|
||||
|
||||
givenJson("""
|
||||
{
|
||||
"jobDefinitionName": "bad-type-%s",
|
||||
"type": "multinode"
|
||||
}
|
||||
""".formatted(suffix))
|
||||
.when()
|
||||
.post("/v1/registerjobdefinition")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("ClientException"));
|
||||
|
||||
givenJson("""
|
||||
{
|
||||
"computeEnvironmentName": "bad-ce-missing-type-%s"
|
||||
}
|
||||
""".formatted(suffix))
|
||||
.when()
|
||||
.post("/v1/createcomputeenvironment")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("ClientException"));
|
||||
|
||||
givenJson("""
|
||||
{
|
||||
"jobDefinitionName": "bad-missing-container-%s",
|
||||
"type": "container"
|
||||
}
|
||||
""".formatted(suffix))
|
||||
.when()
|
||||
.post("/v1/registerjobdefinition")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("ClientException"));
|
||||
|
||||
givenJson("""
|
||||
{
|
||||
"jobDefinitionName": "bad-register-env-%s",
|
||||
"type": "container",
|
||||
"containerProperties": {
|
||||
"environment": [{"name":"AWS_BATCH_BAD","value":"nope"}]
|
||||
}
|
||||
}
|
||||
""".formatted(suffix))
|
||||
.when()
|
||||
.post("/v1/registerjobdefinition")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("ClientException"));
|
||||
|
||||
givenJson("""
|
||||
{"jobName":"bad/name-%s","jobQueue":"%s","jobDefinition":"%s"}
|
||||
""".formatted(suffix, queueArn, definitionArn))
|
||||
.when()
|
||||
.post("/v1/submitjob")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("ClientException"));
|
||||
|
||||
givenJson("{\"jobDefinition\":\"batch-error-job-%s\"}".formatted(suffix))
|
||||
.when()
|
||||
.post("/v1/deregisterjobdefinition")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("ClientException"));
|
||||
|
||||
givenJson("{\"jobDefinitions\":[\"%s\"],\"nextToken\":\"not-a-number\"}".formatted(definitionArn))
|
||||
.when()
|
||||
.post("/v1/describejobdefinitions")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("ClientException"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void describeUnknownJobsReturnsEmptyList() {
|
||||
givenJson("{\"jobs\":[\"does-not-exist\"]}")
|
||||
.when()
|
||||
.post("/v1/describejobs")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("jobs", hasSize(0));
|
||||
}
|
||||
|
||||
private static io.restassured.specification.RequestSpecification givenJson(String body) {
|
||||
return given()
|
||||
.header("Authorization", AUTH)
|
||||
.contentType("application/json")
|
||||
.body(body);
|
||||
}
|
||||
|
||||
private String createComputeEnvironment(String name) {
|
||||
return givenJson("""
|
||||
{
|
||||
"computeEnvironmentName": "%s",
|
||||
"type": "MANAGED",
|
||||
"computeResources": {"type":"FARGATE","maxvCpus":4}
|
||||
}
|
||||
""".formatted(name))
|
||||
.when()
|
||||
.post("/v1/createcomputeenvironment")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.extract().path("computeEnvironmentArn");
|
||||
}
|
||||
|
||||
private String createQueue(String name, String computeEnvironmentArn) {
|
||||
return givenJson("""
|
||||
{
|
||||
"jobQueueName": "%s",
|
||||
"priority": 1,
|
||||
"computeEnvironmentOrder": [{
|
||||
"order": 1,
|
||||
"computeEnvironment": "%s"
|
||||
}]
|
||||
}
|
||||
""".formatted(name, computeEnvironmentArn))
|
||||
.when()
|
||||
.post("/v1/createjobqueue")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.extract().path("jobQueueArn");
|
||||
}
|
||||
|
||||
private String registerJobDefinition(String name, String commandJson, String environmentJson) {
|
||||
return givenJson("""
|
||||
{
|
||||
"jobDefinitionName": "%s",
|
||||
"type": "container",
|
||||
"platformCapabilities": ["FARGATE"],
|
||||
"containerProperties": {
|
||||
"image": "public.ecr.aws/example/job:latest",
|
||||
"command": %s,
|
||||
"environment": %s,
|
||||
"resourceRequirements": [
|
||||
{"type":"VCPU","value":"1"},
|
||||
{"type":"MEMORY","value":"512"}
|
||||
]
|
||||
},
|
||||
"retryStrategy": {"attempts": 2}
|
||||
}
|
||||
""".formatted(name, commandJson, environmentJson))
|
||||
.when()
|
||||
.post("/v1/registerjobdefinition")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.extract().path("jobDefinitionArn");
|
||||
}
|
||||
|
||||
private String submit(String queueArn, String definitionArn, String jobName) {
|
||||
return givenJson("""
|
||||
{"jobName":"%s","jobQueue":"%s","jobDefinition":"%s"}
|
||||
""".formatted(jobName, queueArn, definitionArn))
|
||||
.when()
|
||||
.post("/v1/submitjob")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.extract().path("jobId");
|
||||
}
|
||||
|
||||
private static String uniqueSuffix() {
|
||||
return Long.toString(System.nanoTime(), 36);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,313 @@
|
||||
package io.github.hectorvent.floci.services.batch;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
|
||||
import io.github.hectorvent.floci.core.storage.StorageBackend;
|
||||
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.BatchRunResult;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.function.Predicate;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyInt;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class BatchServiceTest {
|
||||
|
||||
private static final String REGION = "us-east-1";
|
||||
private static final String ACCOUNT = "000000000000";
|
||||
|
||||
private final ObjectMapper objectMapper = new ObjectMapper();
|
||||
|
||||
@Test
|
||||
void dockerTimeoutFailsWithoutRetryingRemainingAttempts() throws Exception {
|
||||
BatchDockerRunner runner = mock(BatchDockerRunner.class);
|
||||
when(runner.run(any(BatchJob.class), anyInt()))
|
||||
.thenReturn(new BatchRunResult(137, "Job timed out", "log-stream", 1L, 2L, true));
|
||||
BatchService service = dockerService(runner);
|
||||
|
||||
String computeArn = service.createComputeEnvironment(json("""
|
||||
{"computeEnvironmentName":"timeout-ce","type":"MANAGED"}
|
||||
"""), REGION).path("computeEnvironmentArn").asText();
|
||||
String queueArn = service.createJobQueue(json("""
|
||||
{
|
||||
"jobQueueName":"timeout-queue",
|
||||
"priority":1,
|
||||
"computeEnvironmentOrder":[{"order":1,"computeEnvironment":"%s"}]
|
||||
}
|
||||
""".formatted(computeArn)), REGION).path("jobQueueArn").asText();
|
||||
String definitionArn = service.registerJobDefinition(json("""
|
||||
{
|
||||
"jobDefinitionName":"timeout-job",
|
||||
"type":"container",
|
||||
"containerProperties":{"image":"public.ecr.aws/example/job:latest"},
|
||||
"retryStrategy":{"attempts":3}
|
||||
}
|
||||
"""), REGION).path("jobDefinitionArn").asText();
|
||||
|
||||
String jobId = service.submitJob(json("""
|
||||
{
|
||||
"jobName":"timeout-submit",
|
||||
"jobQueue":"%s",
|
||||
"jobDefinition":"%s",
|
||||
"timeout":{"attemptDurationSeconds":60}
|
||||
}
|
||||
""".formatted(queueArn, definitionArn)), REGION).path("jobId").asText();
|
||||
|
||||
JsonNode job = waitForJobStatus(service, jobId, "FAILED");
|
||||
assertNotNull(job);
|
||||
assertEquals("Job timed out", job.path("statusReason").asText());
|
||||
assertEquals(1, job.path("attempts").size());
|
||||
verify(runner, times(1)).run(any(BatchJob.class), anyInt());
|
||||
}
|
||||
|
||||
@Test
|
||||
void dockerRetriesFailedAttemptAndCanSucceed() throws Exception {
|
||||
BatchDockerRunner runner = mock(BatchDockerRunner.class);
|
||||
when(runner.run(any(BatchJob.class), anyInt()))
|
||||
.thenReturn(new BatchRunResult(1, "first failed", "log-1", 1L, 2L, false))
|
||||
.thenReturn(new BatchRunResult(0, null, "log-2", 3L, 4L, false));
|
||||
BatchService service = dockerService(runner);
|
||||
|
||||
String computeArn = service.createComputeEnvironment(json("""
|
||||
{"computeEnvironmentName":"retry-ce","type":"MANAGED"}
|
||||
"""), REGION).path("computeEnvironmentArn").asText();
|
||||
String queueArn = service.createJobQueue(json("""
|
||||
{
|
||||
"jobQueueName":"retry-queue",
|
||||
"priority":1,
|
||||
"computeEnvironmentOrder":[{"order":1,"computeEnvironment":"%s"}]
|
||||
}
|
||||
""".formatted(computeArn)), REGION).path("jobQueueArn").asText();
|
||||
String definitionArn = service.registerJobDefinition(json("""
|
||||
{
|
||||
"jobDefinitionName":"retry-job",
|
||||
"type":"container",
|
||||
"containerProperties":{"image":"public.ecr.aws/example/job:latest"},
|
||||
"retryStrategy":{"attempts":2}
|
||||
}
|
||||
"""), REGION).path("jobDefinitionArn").asText();
|
||||
|
||||
String jobId = service.submitJob(json("""
|
||||
{"jobName":"retry-submit","jobQueue":"%s","jobDefinition":"%s"}
|
||||
""".formatted(queueArn, definitionArn)), REGION).path("jobId").asText();
|
||||
|
||||
JsonNode job = waitForJobStatus(service, jobId, "SUCCEEDED");
|
||||
assertNotNull(job);
|
||||
assertEquals(2, job.path("attempts").size());
|
||||
assertEquals(0, job.path("attempts").get(1).path("container").path("exitCode").asInt());
|
||||
verify(runner, times(2)).run(any(BatchJob.class), anyInt());
|
||||
}
|
||||
|
||||
@Test
|
||||
void dockerRetryExhaustionFailsJobAndKeepsAttempts() throws Exception {
|
||||
BatchDockerRunner runner = mock(BatchDockerRunner.class);
|
||||
when(runner.run(any(BatchJob.class), anyInt()))
|
||||
.thenReturn(new BatchRunResult(1, "failed once", "log-1", 1L, 2L, false))
|
||||
.thenReturn(new BatchRunResult(2, "failed twice", "log-2", 3L, 4L, false));
|
||||
BatchService service = dockerService(runner);
|
||||
|
||||
String computeArn = service.createComputeEnvironment(json("""
|
||||
{"computeEnvironmentName":"exhaust-ce","type":"MANAGED"}
|
||||
"""), REGION).path("computeEnvironmentArn").asText();
|
||||
String queueArn = service.createJobQueue(json("""
|
||||
{
|
||||
"jobQueueName":"exhaust-queue",
|
||||
"priority":1,
|
||||
"computeEnvironmentOrder":[{"order":1,"computeEnvironment":"%s"}]
|
||||
}
|
||||
""".formatted(computeArn)), REGION).path("jobQueueArn").asText();
|
||||
String definitionArn = service.registerJobDefinition(json("""
|
||||
{
|
||||
"jobDefinitionName":"exhaust-job",
|
||||
"type":"container",
|
||||
"containerProperties":{"image":"public.ecr.aws/example/job:latest"},
|
||||
"retryStrategy":{"attempts":2}
|
||||
}
|
||||
"""), REGION).path("jobDefinitionArn").asText();
|
||||
|
||||
String jobId = service.submitJob(json("""
|
||||
{"jobName":"exhaust-submit","jobQueue":"%s","jobDefinition":"%s"}
|
||||
""".formatted(queueArn, definitionArn)), REGION).path("jobId").asText();
|
||||
|
||||
JsonNode job = waitForJobStatus(service, jobId, "FAILED");
|
||||
assertNotNull(job);
|
||||
assertEquals("failed twice", job.path("statusReason").asText());
|
||||
assertEquals(2, job.path("attempts").size());
|
||||
assertEquals(2, job.path("attempts").get(1).path("container").path("exitCode").asInt());
|
||||
verify(runner, times(2)).run(any(BatchJob.class), anyInt());
|
||||
}
|
||||
|
||||
@Test
|
||||
void listJobsUsesStableJobIdTiebreakerForSameCreatedAt() throws Exception {
|
||||
ReverseScanJobStorage jobStore = new ReverseScanJobStorage();
|
||||
BatchService service = immediateService(jobStore);
|
||||
|
||||
String computeArn = service.createComputeEnvironment(json("""
|
||||
{"computeEnvironmentName":"page-tie-ce","type":"MANAGED"}
|
||||
"""), REGION).path("computeEnvironmentArn").asText();
|
||||
String queueArn = service.createJobQueue(json("""
|
||||
{
|
||||
"jobQueueName":"page-tie-queue",
|
||||
"priority":1,
|
||||
"computeEnvironmentOrder":[{"order":1,"computeEnvironment":"%s"}]
|
||||
}
|
||||
""".formatted(computeArn)), REGION).path("jobQueueArn").asText();
|
||||
String definitionArn = service.registerJobDefinition(json("""
|
||||
{
|
||||
"jobDefinitionName":"page-tie-job",
|
||||
"type":"container",
|
||||
"containerProperties":{"image":"public.ecr.aws/example/job:latest"}
|
||||
}
|
||||
"""), REGION).path("jobDefinitionArn").asText();
|
||||
|
||||
service.submitJob(json("""
|
||||
{"jobName":"page-tie-first","jobQueue":"%s","jobDefinition":"%s"}
|
||||
""".formatted(queueArn, definitionArn)), REGION);
|
||||
service.submitJob(json("""
|
||||
{"jobName":"page-tie-second","jobQueue":"%s","jobDefinition":"%s"}
|
||||
""".formatted(queueArn, definitionArn)), REGION);
|
||||
|
||||
List<BatchJob> jobs = jobStore.scan(k -> true);
|
||||
assertEquals(2, jobs.size());
|
||||
BatchJob secondInserted = jobs.get(0);
|
||||
BatchJob firstInserted = jobs.get(1);
|
||||
secondInserted.setCreatedAt(123L);
|
||||
secondInserted.setJobId("b-job");
|
||||
firstInserted.setCreatedAt(123L);
|
||||
firstInserted.setJobId("a-job");
|
||||
|
||||
JsonNode firstPage = service.listJobs(json("""
|
||||
{"jobQueue":"%s","jobStatus":"SUCCEEDED","maxResults":1}
|
||||
""".formatted(queueArn)));
|
||||
assertEquals("a-job", firstPage.path("jobSummaryList").get(0).path("jobId").asText());
|
||||
|
||||
JsonNode secondPage = service.listJobs(json("""
|
||||
{"jobQueue":"%s","jobStatus":"SUCCEEDED","maxResults":1,"nextToken":"%s"}
|
||||
""".formatted(queueArn, firstPage.path("nextToken").asText())));
|
||||
assertEquals("b-job", secondPage.path("jobSummaryList").get(0).path("jobId").asText());
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
private BatchService immediateService(StorageBackend<String, BatchJob> jobStore) {
|
||||
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");
|
||||
|
||||
return new BatchService(
|
||||
new InMemoryStorage<String, BatchJobDefinition>(),
|
||||
new InMemoryStorage<String, BatchJobQueue>(),
|
||||
new InMemoryStorage<String, BatchComputeEnvironment>(),
|
||||
jobStore,
|
||||
new RegionResolver(REGION, ACCOUNT),
|
||||
config,
|
||||
objectMapper,
|
||||
mock(BatchDockerRunner.class));
|
||||
}
|
||||
|
||||
private ObjectNode json(String body) throws Exception {
|
||||
return (ObjectNode) objectMapper.readTree(body);
|
||||
}
|
||||
|
||||
private JsonNode waitForJobStatus(BatchService service, String jobId, String status) 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 && status.equals(job.path("status").asText())) {
|
||||
return job;
|
||||
}
|
||||
Thread.sleep(10);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static final class ReverseScanJobStorage implements StorageBackend<String, BatchJob> {
|
||||
private final LinkedHashMap<String, BatchJob> store = new LinkedHashMap<>();
|
||||
|
||||
@Override
|
||||
public void put(String key, BatchJob value) {
|
||||
store.put(key, value);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<BatchJob> get(String key) {
|
||||
return Optional.ofNullable(store.get(key));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void delete(String key) {
|
||||
store.remove(key);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<BatchJob> scan(Predicate<String> keyFilter) {
|
||||
List<BatchJob> values = new ArrayList<>();
|
||||
store.forEach((key, value) -> {
|
||||
if (keyFilter.test(key)) {
|
||||
values.add(value);
|
||||
}
|
||||
});
|
||||
Collections.reverse(values);
|
||||
return values;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<String> keys() {
|
||||
return Set.copyOf(store.keySet());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void flush() {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void load() {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clear() {
|
||||
store.clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
+199
@@ -0,0 +1,199 @@
|
||||
package io.github.hectorvent.floci.services.cloudformation;
|
||||
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.hasSize;
|
||||
import static org.hamcrest.Matchers.notNullValue;
|
||||
|
||||
@QuarkusTest
|
||||
class CloudFormationBatchIntegrationTest {
|
||||
|
||||
private static final String BATCH_AUTH =
|
||||
"AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/batch/aws4_request";
|
||||
|
||||
@Test
|
||||
void createStackWithBatchResourcesRegistersUsableQueueAndDefinition() {
|
||||
String suffix = Long.toString(System.nanoTime(), 36);
|
||||
String computeName = "cfn-batch-ce-" + suffix;
|
||||
String queueName = "cfn-batch-queue-" + suffix;
|
||||
String definitionName = "cfn-batch-job-" + suffix;
|
||||
String stackName = "cfn-batch-stack-" + suffix;
|
||||
|
||||
String template = """
|
||||
{
|
||||
"Resources": {
|
||||
"Compute": {
|
||||
"Type": "AWS::Batch::ComputeEnvironment",
|
||||
"Properties": {
|
||||
"ComputeEnvironmentName": "%s",
|
||||
"Type": "MANAGED",
|
||||
"ComputeResources": {
|
||||
"Type": "FARGATE",
|
||||
"MaxvCpus": 4,
|
||||
"Subnets": ["subnet-local"],
|
||||
"SecurityGroupIds": ["sg-local"]
|
||||
}
|
||||
}
|
||||
},
|
||||
"Queue": {
|
||||
"Type": "AWS::Batch::JobQueue",
|
||||
"Properties": {
|
||||
"JobQueueName": "%s",
|
||||
"Priority": 1,
|
||||
"ComputeEnvironmentOrder": [{
|
||||
"Order": 1,
|
||||
"ComputeEnvironment": {"Ref": "Compute"}
|
||||
}]
|
||||
}
|
||||
},
|
||||
"Definition": {
|
||||
"Type": "AWS::Batch::JobDefinition",
|
||||
"Properties": {
|
||||
"JobDefinitionName": "%s",
|
||||
"Type": "container",
|
||||
"PlatformCapabilities": ["FARGATE"],
|
||||
"ContainerProperties": {
|
||||
"Image": "public.ecr.aws/example/job:latest",
|
||||
"Command": ["Ref::inputKey"],
|
||||
"Environment": [{"Name":"FROM_CFN","Value":"yes"}],
|
||||
"ResourceRequirements": [
|
||||
{"Type":"VCPU","Value":"1"},
|
||||
{"Type":"MEMORY","Value":"512"}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"Outputs": {
|
||||
"ComputeArn": {"Value": {"Fn::GetAtt": ["Compute", "ComputeEnvironmentArn"]}},
|
||||
"QueueArn": {"Value": {"Fn::GetAtt": ["Queue", "JobQueueArn"]}},
|
||||
"DefinitionArn": {"Value": {"Fn::GetAtt": ["Definition", "JobDefinitionArn"]}}
|
||||
}
|
||||
}
|
||||
""".formatted(computeName, queueName, definitionName);
|
||||
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "CreateStack")
|
||||
.formParam("StackName", stackName)
|
||||
.formParam("TemplateBody", template)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body(containsString("<StackId>"));
|
||||
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "DescribeStacks")
|
||||
.formParam("StackName", stackName)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body(containsString("compute-environment/" + computeName))
|
||||
.body(containsString("job-queue/" + queueName))
|
||||
.body(containsString("job-definition/" + definitionName + ":1"));
|
||||
|
||||
givenBatchJson("{\"jobQueues\":[\"%s\"]}".formatted(queueName))
|
||||
.when()
|
||||
.post("/v1/describejobqueues")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("jobQueues", hasSize(1))
|
||||
.body("jobQueues[0].jobQueueName", equalTo(queueName));
|
||||
|
||||
String jobId = givenBatchJson("""
|
||||
{
|
||||
"jobName": "cfn-batch-submit-%s",
|
||||
"jobQueue": "%s",
|
||||
"jobDefinition": "%s",
|
||||
"parameters": {"inputKey":"from-cfn.json"}
|
||||
}
|
||||
""".formatted(suffix, queueName, definitionName))
|
||||
.when()
|
||||
.post("/v1/submitjob")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("jobId", notNullValue())
|
||||
.extract().path("jobId");
|
||||
|
||||
givenBatchJson("{\"jobs\":[\"%s\"]}".formatted(jobId))
|
||||
.when()
|
||||
.post("/v1/describejobs")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("jobs[0].status", equalTo("SUCCEEDED"))
|
||||
.body("jobs[0].container.command[0]", equalTo("from-cfn.json"))
|
||||
.body("jobs[0].container.environment.find { it.name == 'FROM_CFN' }.value", equalTo("yes"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createStackWithBatchArrayTargetPreservesMetadataWithoutArrayFanout() {
|
||||
String suffix = Long.toString(System.nanoTime(), 36);
|
||||
String stackName = "cfn-batch-array-target-" + suffix;
|
||||
String template = """
|
||||
{
|
||||
"Resources": {
|
||||
"Rule": {
|
||||
"Type": "AWS::Events::Rule",
|
||||
"Properties": {
|
||||
"Name": "%s",
|
||||
"EventPattern": {"source": ["local.test"]},
|
||||
"Targets": [{
|
||||
"Id": "batch-target",
|
||||
"Arn": "arn:aws:batch:us-east-1:000000000000:job-queue/local",
|
||||
"BatchParameters": {
|
||||
"JobDefinition": "local-job",
|
||||
"JobName": "array-job",
|
||||
"ArrayProperties": {"Size": 2}
|
||||
}
|
||||
}]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
""".formatted("cfn-batch-array-rule-" + suffix);
|
||||
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "CreateStack")
|
||||
.formParam("StackName", stackName)
|
||||
.formParam("TemplateBody", template)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "DescribeStacks")
|
||||
.formParam("StackName", stackName)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body(containsString("<StackStatus>CREATE_COMPLETE</StackStatus>"));
|
||||
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "DescribeStackResources")
|
||||
.formParam("StackName", stackName)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body(containsString("CREATE_COMPLETE"));
|
||||
}
|
||||
|
||||
private static io.restassured.specification.RequestSpecification givenBatchJson(String body) {
|
||||
return given()
|
||||
.header("Authorization", BATCH_AUTH)
|
||||
.contentType("application/json")
|
||||
.body(body);
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -48,7 +48,7 @@ class CustomResourceProvisionerTest {
|
||||
|
||||
provisioner = new CloudFormationResourceProvisioner(
|
||||
null, null, null, null, lambdaService, null, null, null, null, null,
|
||||
null, null, null, null, null, null, mapper, store, endpoint, null, null, null);
|
||||
null, null, null, null, null, null, mapper, store, endpoint, null, null, null, null);
|
||||
}
|
||||
|
||||
private CloudFormationTemplateEngine engine() {
|
||||
|
||||
+171
@@ -0,0 +1,171 @@
|
||||
package io.github.hectorvent.floci.services.eventbridge;
|
||||
|
||||
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.notNullValue;
|
||||
import static org.hamcrest.Matchers.nullValue;
|
||||
|
||||
@QuarkusTest
|
||||
class EventBridgeBatchIntegrationTest {
|
||||
|
||||
private static final String EVENT_BRIDGE_CONTENT_TYPE = "application/x-amz-json-1.1";
|
||||
private static final String BATCH_AUTH =
|
||||
"AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/batch/aws4_request";
|
||||
|
||||
@BeforeAll
|
||||
static void configureRestAssured() {
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
}
|
||||
|
||||
@Test
|
||||
void putEventsBatchTargetSubmitsVisibleBatchJob() {
|
||||
String suffix = Long.toString(System.nanoTime(), 36);
|
||||
String computeArn = createComputeEnvironment("eb-batch-ce-" + suffix);
|
||||
String queueArn = createQueue("eb-batch-queue-" + suffix, computeArn);
|
||||
String definitionArn = registerJobDefinition("eb-batch-job-" + suffix);
|
||||
String ruleName = "eb-batch-rule-" + suffix;
|
||||
String submittedJobName = "eb-batch-submitted-" + suffix;
|
||||
|
||||
given()
|
||||
.contentType(EVENT_BRIDGE_CONTENT_TYPE)
|
||||
.header("X-Amz-Target", "AWSEvents.PutRule")
|
||||
.body("""
|
||||
{"Name":"%s","EventPattern":"{\\"source\\":[\\"local.batch\\"]}"}
|
||||
""".formatted(ruleName))
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
given()
|
||||
.contentType(EVENT_BRIDGE_CONTENT_TYPE)
|
||||
.header("X-Amz-Target", "AWSEvents.PutTargets")
|
||||
.body("""
|
||||
{
|
||||
"Rule": "%s",
|
||||
"Targets": [{
|
||||
"Id": "batch",
|
||||
"Arn": "%s",
|
||||
"Input": "{\\"Parameters\\":{\\"inputKey\\":\\"from-event.json\\"}}",
|
||||
"BatchParameters": {
|
||||
"JobDefinition": "%s",
|
||||
"JobName": "%s",
|
||||
"ArrayProperties": {"Size": 2},
|
||||
"RetryStrategy": {"Attempts": 2, "EvaluateOnExit": [{"Action": "EXIT"}]}
|
||||
}
|
||||
}]
|
||||
}
|
||||
""".formatted(ruleName, queueArn, definitionArn, submittedJobName))
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
given()
|
||||
.contentType(EVENT_BRIDGE_CONTENT_TYPE)
|
||||
.header("X-Amz-Target", "AWSEvents.ListTargetsByRule")
|
||||
.body("""
|
||||
{"Rule": "%s"}
|
||||
""".formatted(ruleName))
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("Targets[0].BatchParameters.ArrayProperties.Size", equalTo(2))
|
||||
.body("Targets[0].BatchParameters.RetryStrategy.Attempts", equalTo(2))
|
||||
.body("Targets[0].BatchParameters.RetryStrategy.EvaluateOnExit", nullValue());
|
||||
|
||||
given()
|
||||
.contentType(EVENT_BRIDGE_CONTENT_TYPE)
|
||||
.header("X-Amz-Target", "AWSEvents.PutEvents")
|
||||
.body("""
|
||||
{
|
||||
"Entries": [{
|
||||
"Source": "local.batch",
|
||||
"DetailType": "BatchRequested",
|
||||
"Detail": "{}"
|
||||
}]
|
||||
}
|
||||
""")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
String jobId = givenBatchJson("""
|
||||
{"jobQueue":"%s","jobStatus":"SUCCEEDED"}
|
||||
""".formatted(queueArn))
|
||||
.when()
|
||||
.post("/v1/listjobs")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("jobSummaryList.find { it.jobName == '%s' }.jobId".formatted(submittedJobName), notNullValue())
|
||||
.extract().path("jobSummaryList.find { it.jobName == '%s' }.jobId".formatted(submittedJobName));
|
||||
|
||||
givenBatchJson("{\"jobs\":[\"%s\"]}".formatted(jobId))
|
||||
.when()
|
||||
.post("/v1/describejobs")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("jobs[0].jobName", equalTo(submittedJobName))
|
||||
.body("jobs[0].retryStrategy.attempts", equalTo(2))
|
||||
.body("jobs[0].retryStrategy.evaluateOnExit", nullValue())
|
||||
.body("jobs[0].container.command[0]", equalTo("from-event.json"));
|
||||
}
|
||||
|
||||
private String createComputeEnvironment(String name) {
|
||||
return givenBatchJson("""
|
||||
{"computeEnvironmentName":"%s","type":"MANAGED"}
|
||||
""".formatted(name))
|
||||
.when()
|
||||
.post("/v1/createcomputeenvironment")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.extract().path("computeEnvironmentArn");
|
||||
}
|
||||
|
||||
private String createQueue(String name, String computeEnvironmentArn) {
|
||||
return givenBatchJson("""
|
||||
{
|
||||
"jobQueueName":"%s",
|
||||
"priority":1,
|
||||
"computeEnvironmentOrder":[{"order":1,"computeEnvironment":"%s"}]
|
||||
}
|
||||
""".formatted(name, computeEnvironmentArn))
|
||||
.when()
|
||||
.post("/v1/createjobqueue")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.extract().path("jobQueueArn");
|
||||
}
|
||||
|
||||
private String registerJobDefinition(String name) {
|
||||
return givenBatchJson("""
|
||||
{
|
||||
"jobDefinitionName":"%s",
|
||||
"type":"container",
|
||||
"containerProperties": {
|
||||
"image":"public.ecr.aws/example/job:latest",
|
||||
"command":["Ref::inputKey"]
|
||||
}
|
||||
}
|
||||
""".formatted(name))
|
||||
.when()
|
||||
.post("/v1/registerjobdefinition")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.extract().path("jobDefinitionArn");
|
||||
}
|
||||
|
||||
private static io.restassured.specification.RequestSpecification givenBatchJson(String body) {
|
||||
return given()
|
||||
.header("Authorization", BATCH_AUTH)
|
||||
.contentType("application/json")
|
||||
.body(body);
|
||||
}
|
||||
}
|
||||
+79
@@ -1,6 +1,9 @@
|
||||
package io.github.hectorvent.floci.services.eventbridge;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import io.github.hectorvent.floci.services.batch.BatchService;
|
||||
import io.github.hectorvent.floci.services.eventbridge.model.BatchParameters;
|
||||
import io.github.hectorvent.floci.services.eventbridge.model.InputTransformer;
|
||||
import io.github.hectorvent.floci.services.eventbridge.model.Target;
|
||||
import io.github.hectorvent.floci.services.lambda.LambdaService;
|
||||
@@ -19,16 +22,19 @@ class EventBridgeInvokerTest {
|
||||
|
||||
private EventBridgeInvoker invoker;
|
||||
private SqsService sqsService;
|
||||
private BatchService batchService;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
LambdaService lambdaService = mock(LambdaService.class);
|
||||
sqsService = mock(SqsService.class);
|
||||
SnsService snsService = mock(SnsService.class);
|
||||
batchService = mock(BatchService.class);
|
||||
invoker = new EventBridgeInvoker(
|
||||
lambdaService,
|
||||
sqsService,
|
||||
snsService,
|
||||
batchService,
|
||||
new ObjectMapper(),
|
||||
mock(io.github.hectorvent.floci.config.EmulatorConfig.class)
|
||||
);
|
||||
@@ -44,6 +50,79 @@ class EventBridgeInvokerTest {
|
||||
verify(sqsService).sendMessage(anyString(), eq(event), anyInt(), isNull(), isNull(), eq("eu-west-1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void invokeTarget_batchTarget_submitsBatchJobWithParametersFromPayload() throws Exception {
|
||||
JsonNode retryStrategy = new ObjectMapper().readTree("{\"Attempts\":2}");
|
||||
Target target = new Target("id1",
|
||||
"arn:aws:batch:us-west-2:000000000000:job-queue/my-queue",
|
||||
"{\"Parameters\":{\"inputKey\":\"inputs/1.json\",\"count\":2}}",
|
||||
null);
|
||||
BatchParameters batchParameters = new BatchParameters();
|
||||
batchParameters.setJobDefinition("my-job:1");
|
||||
batchParameters.setJobName("scheduled-job");
|
||||
batchParameters.setRetryStrategy(retryStrategy);
|
||||
target.setBatchParameters(batchParameters);
|
||||
|
||||
invoker.invokeTarget(target, "{\"ignored\":true}", "us-east-1");
|
||||
|
||||
verify(batchService).submitFromEventBridge(
|
||||
eq("arn:aws:batch:us-west-2:000000000000:job-queue/my-queue"),
|
||||
eq("my-job:1"),
|
||||
eq("scheduled-job"),
|
||||
eq(Map.of("inputKey", "inputs/1.json", "count", "2")),
|
||||
eq(retryStrategy),
|
||||
eq("us-west-2")
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
void invokeTarget_batchTargetDoesNotMapFlatPayloadToParameters() {
|
||||
Target target = new Target("id1",
|
||||
"arn:aws:batch:us-west-2:000000000000:job-queue/my-queue",
|
||||
"{\"inputKey\":\"ignored\"}",
|
||||
null);
|
||||
BatchParameters batchParameters = new BatchParameters();
|
||||
batchParameters.setJobDefinition("my-job:1");
|
||||
batchParameters.setJobName("scheduled-job");
|
||||
target.setBatchParameters(batchParameters);
|
||||
|
||||
invoker.invokeTarget(target, "{\"ignored\":true}", "us-east-1");
|
||||
|
||||
verify(batchService).submitFromEventBridge(
|
||||
eq("arn:aws:batch:us-west-2:000000000000:job-queue/my-queue"),
|
||||
eq("my-job:1"),
|
||||
eq("scheduled-job"),
|
||||
eq(Map.of()),
|
||||
isNull(),
|
||||
eq("us-west-2")
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
void invokeTarget_batchTargetWithoutExplicitInputDoesNotMapEventEnvelopeToParameters() {
|
||||
Target target = new Target("id1",
|
||||
"arn:aws:batch:us-west-2:000000000000:job-queue/my-queue",
|
||||
null,
|
||||
null);
|
||||
BatchParameters batchParameters = new BatchParameters();
|
||||
batchParameters.setJobDefinition("my-job:1");
|
||||
batchParameters.setJobName("scheduled-job");
|
||||
target.setBatchParameters(batchParameters);
|
||||
|
||||
invoker.invokeTarget(target, """
|
||||
{"source":"local.test","region":"us-east-1","detail":{"inputKey":"ignored"}}
|
||||
""", "us-east-1");
|
||||
|
||||
verify(batchService).submitFromEventBridge(
|
||||
eq("arn:aws:batch:us-west-2:000000000000:job-queue/my-queue"),
|
||||
eq("my-job:1"),
|
||||
eq("scheduled-job"),
|
||||
eq(Map.of()),
|
||||
isNull(),
|
||||
eq("us-west-2")
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
void extractJsonPath_topLevelField() {
|
||||
String event = "{\"source\":\"aws.s3\",\"detail-type\":\"Object Created\"}";
|
||||
|
||||
Reference in new issue
Block a user