feat(stepfunctions): add the elasticmapreduce optimized integrations (#6261)

A Task can now use the optimized EMR integrations the Step Functions
guide lists: createCluster, setClusterTerminationProtection,
terminateCluster, addStep, cancelStep, modifyInstanceFleetByName and
modifyInstanceGroupByName, with .sync for createCluster, terminateCluster
and addStep. Each calls Floci's EMR in the state machine's Region under
the guide's field names: ClusterId for JobFlowIds or JobFlowId, a single
Step or StepId, and the instance fleet or group found by name through
ListInstanceFleets or ListInstanceGroups. They failed with "Unsupported
resource" before.

A .sync Task records TaskSubmitted with the call's result and polls
DescribeCluster or DescribeStep under the Task's TimeoutSeconds and the
execution's budget, as ecs:runTask.sync does. Its result is the describe
response with the call's result after it, which is the createCluster.sync
output recorded on AWS (Cluster, then ClusterId). A step that ends FAILED,
CANCELLED or INTERRUPTED, or a cluster that terminates before WAITING,
fails the Task with States.TaskFailed and the describe response as the
cause. A wait that ends early cancels the step of an addStep.sync; a
cluster is left running, as the guide says Step Functions does.

An EMR error is named after the SDK exception class under EMR.:
InvalidRequestException and InternalServerException keep their names,
and any other code is EMR.AmazonElasticMapReduceException, as AWS reports
a ValidationException. createCluster refuses
KeepJobFlowAliveWhenNoSteps other than true and Steps, as the guide
requires, with States.TaskFailed and the guide's wording for each rule.
A Task without the ClusterId its API acts on, a cancelStep without a
StepId and a ByName request without its name fail the same way.

AddJobFlowSteps on an unknown cluster, or on one in another Region, now
answers ValidationException "Specified job flow ID does not exist.", as
AWS does: a botocore ClientError (raster-foundry/raster-foundry#352) and
a CloudTrail record on AWS re:Post show it. It answered DescribeCluster's
InvalidRequestException. That re:Post record is an addStep.sync failing
on an unknown cluster with EMR.AmazonElasticMapReduceException, which
addStep now reports as well.

ModifyInstanceGroups and ModifyInstanceFleet on a terminated cluster,
which modifyInstanceGroupByName and modifyInstanceFleetByName reach, now
answer as AWS does too: ValidationException "An instance group may only
be modified when the cluster is running or waiting."
(hashicorp/terraform-provider-aws#1355 and hashicorp/terraform-provider-aws#9400)
and InvalidRequestException "A job flow that is shutting down,
terminated, or finished may not be modified." with ErrorCode
INVALID_JOB_SHUT_DOWN (hashicorp/terraform-provider-aws#31375). Both answered InvalidRequestException "Cluster <id> is
terminated.", which no AWS response shows, and EMR's error body now
carries an error's extra members such as ErrorCode.

TerminateJobFlows, the four Set* cluster setters and CancelSteps now
refuse a request without a member their model requires (JobFlowIds and
the setting, or StepIds) with AWS's framework ValidationException, as
RunJobFlow does for Name. They read a missing list as empty and a missing
setting as its default and answered success, which the
setClusterTerminationProtection and terminateCluster integrations reached
too. The "Member must not be null" violation is now one helper in
SmithyValidationErrors.

Part of #6046 (part 10).
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-10-22 17:06:23 -05:00
1 parent c094ce3973
commit 94c4572fed
13 files changed
+987 -29

No files matched your search

@@ -42,7 +42,8 @@ class EmrClusterRegionIntegrationTest {
emr(OTHER, "AddJobFlowSteps", "{\"JobFlowId\":\"" + clusterId + "\",\"Steps\":[{\"Name\":\"s\","
+ "\"HadoopJarStep\":{\"Jar\":\"command-runner.jar\",\"Args\":[\"echo\"]}}]}")
.then().statusCode(400)
.body("__type", equalTo("InvalidRequestException"));
.body("__type", equalTo("ValidationException"))
.body("message", equalTo("Specified job flow ID does not exist."));
emr(OTHER, "ListClusters", "{}")
.then().statusCode(200)
.body("Clusters.Id", not(hasItem(clusterId)));
@@ -366,13 +366,13 @@ class EmrIntegrationTest {
@Test
@Order(17)
void addStepsToUnknownClusterIsInvalidRequest() {
void addStepsToUnknownClusterIsAValidationException() {
emr("AddJobFlowSteps",
"{\"JobFlowId\":\"j-DOESNOTEXIST0\",\"Steps\":[{\"Name\":\"s\","
+ "\"HadoopJarStep\":{\"Jar\":\"command-runner.jar\"}}]}")
.then().statusCode(400)
.body("__type", equalTo("InvalidRequestException"))
.body("message", equalTo("Cluster id 'j-DOESNOTEXIST0' is not valid."));
.body("__type", equalTo("ValidationException"))
.body("message", equalTo("Specified job flow ID does not exist."));
}
@Test
@@ -404,6 +404,40 @@ class EmrIntegrationTest {
.body("Cluster.Status.State", equalTo("WAITING"));
}
@Test
void settersAndCancelStepsRefuseARequestWithoutTheMembersTheyRequire() {
String id = emr("RunJobFlow", "{\"Name\":\"required\",\"Instances\":{\"KeepJobFlowAliveWhenNoSteps\":true}}")
.then().statusCode(200).extract().path("JobFlowId");
String ids = "\"JobFlowIds\":[\"" + id + "\"]";
assertMissing("TerminateJobFlows", "{}", "jobFlowIds");
assertMissing("SetTerminationProtection", "{\"TerminationProtected\":true}", "jobFlowIds");
assertMissing("SetTerminationProtection", "{" + ids + "}", "terminationProtected");
assertMissing("SetVisibleToAllUsers", "{" + ids + "}", "visibleToAllUsers");
assertMissing("SetKeepJobFlowAliveWhenNoSteps", "{" + ids + "}", "keepJobFlowAliveWhenNoSteps");
assertMissing("SetUnhealthyNodeReplacement", "{" + ids + "}", "unhealthyNodeReplacement");
assertMissing("CancelSteps", "{\"ClusterId\":\"" + id + "\"}", "stepIds");
emr("SetVisibleToAllUsers", "{}").then().statusCode(400)
.body("message", equalTo("2 validation errors detected: "
+ "Value null at 'jobFlowIds' failed to satisfy constraint: Member must not be null; "
+ "Value null at 'visibleToAllUsers' failed to satisfy constraint: Member must not be null"));
emr("TerminateJobFlows", "{\"JobFlowIds\":[]}").then().statusCode(200);
emr("DescribeCluster", "{\"ClusterId\":\"" + id + "\"}").then().statusCode(200)
.body("Cluster.Status.State", equalTo("WAITING"))
.body("Cluster.TerminationProtected", equalTo(false))
.body("Cluster.VisibleToAllUsers", equalTo(true))
.body("Cluster.AutoTerminate", equalTo(false));
emr("TerminateJobFlows", "{" + ids + "}").then().statusCode(200);
}
private static void assertMissing(String action, String body, String member) {
emr(action, body).then().statusCode(400)
.body("__type", equalTo("ValidationException"))
.body("message", equalTo("1 validation error detected: Value null at '" + member
+ "' failed to satisfy constraint: Member must not be null"));
}
// Catches: a cluster stored before the DNS fix keeps reporting its old us-east-1 master name.
@Test
void storedClusterReportsTheRegionalMasterDnsName() {
@@ -31,6 +31,10 @@ class EmrTerminatedCapacityIntegrationTest {
+ "\"TargetSpotCapacity\":3,\"InstanceTypeConfigs\":[{\"InstanceType\":\"m5.xlarge\"}]}]";
private static final String STEP = "{\"Name\":\"complete\","
+ "\"HadoopJarStep\":{\"Jar\":\"command-runner.jar\"}}";
private static final String GROUP_REFUSAL =
"An instance group may only be modified when the cluster is running or waiting.";
private static final String FLEET_REFUSAL =
"A job flow that is shutting down, terminated, or finished may not be modified.";
@BeforeAll
static void configure() {
@@ -133,7 +137,9 @@ class EmrTerminatedCapacityIntegrationTest {
emr("ModifyInstanceGroups", "{\"InstanceGroups\":["
+ "{\"InstanceGroupId\":\"" + activeGroup + "\",\"InstanceCount\":4},"
+ "{\"InstanceGroupId\":\"" + terminatedGroup + "\",\"InstanceCount\":4}]}")
.then().statusCode(400).body("__type", equalTo("InvalidRequestException"));
.then().statusCode(400)
.body("__type", equalTo("ValidationException"))
.body("message", equalTo(GROUP_REFUSAL));
emr("ListInstanceGroups", clusterRequest(activeId)).then().statusCode(200)
.body("InstanceGroups.find { it.Id == '" + activeGroup + "' }.RunningInstanceCount", equalTo(2));
assertTerminatedGroup(terminatedId);
@@ -172,7 +178,9 @@ class EmrTerminatedCapacityIntegrationTest {
String clusterId = includeClusterId ? "\"ClusterId\":\"" + id + "\"," : "";
emr("ModifyInstanceGroups", "{" + clusterId + "\"InstanceGroups\":[{\"InstanceGroupId\":\""
+ coreGroupId(id) + "\",\"InstanceCount\":4}]}")
.then().statusCode(400).body("__type", equalTo("InvalidRequestException"));
.then().statusCode(400)
.body("__type", equalTo("ValidationException"))
.body("message", equalTo(GROUP_REFUSAL));
assertTerminatedGroup(id);
}
@@ -181,7 +189,10 @@ class EmrTerminatedCapacityIntegrationTest {
.extract().jsonPath().getString("InstanceFleets.find { it.InstanceFleetType == 'CORE' }.Id");
emr("ModifyInstanceFleet", "{\"ClusterId\":\"" + id + "\",\"InstanceFleet\":{"
+ "\"InstanceFleetId\":\"" + fleetId + "\",\"TargetOnDemandCapacity\":4}}")
.then().statusCode(400).body("__type", equalTo("InvalidRequestException"));
.then().statusCode(400)
.body("__type", equalTo("InvalidRequestException"))
.body("message", equalTo(FLEET_REFUSAL))
.body("ErrorCode", equalTo("INVALID_JOB_SHUT_DOWN"));
assertTerminatedFleet(id);
}
@@ -0,0 +1,208 @@
package io.github.hectorvent.floci.services.stepfunctions;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.services.emr.EmrHandler;
import io.github.hectorvent.floci.services.emr.EmrService;
import io.github.hectorvent.floci.services.emr.model.EmrCluster;
import io.github.hectorvent.floci.services.emr.model.EmrStep;
import io.github.hectorvent.floci.services.stepfunctions.model.Execution;
import io.github.hectorvent.floci.services.stepfunctions.model.HistoryEvent;
import io.github.hectorvent.floci.services.stepfunctions.model.StateMachine;
import jakarta.enterprise.inject.Instance;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* The {@code .sync} waits of the {@code elasticmapreduce:} integrations, on a cluster or step held in
* a state Floci's instant lifecycle never shows. Time is a test clock the waits move forward.
*/
class AslExecutorEmrSyncTest {
private static final String REGION = "eu-west-3";
private static final String ACCOUNT = "000000000000";
private static final String CLUSTER_ID = "j-SYNCTEST00001";
private static final String STEP_ID = "s-SYNCTEST00001";
private static final String ADD_STEP = """
{"ClusterId": "j-SYNCTEST00001",
"Step": {"Name": "job", "HadoopJarStep": {"Jar": "command-runner.jar", "Args": ["true"]}}}
""";
private static final String CREATE_CLUSTER = """
{"Name": "sync", "Instances": {"KeepJobFlowAliveWhenNoSteps": true}}
""";
private final ObjectMapper objectMapper = new ObjectMapper();
private final AtomicLong testNanos = new AtomicLong();
private EmrService emrService;
private StepFunctionsService sfnService;
private AslExecutor executor;
private List<HistoryEvent> history;
@BeforeEach
@SuppressWarnings("unchecked")
void setUp() {
emrService = mock(EmrService.class);
when(emrService.addJobFlowSteps(eq(CLUSTER_ID), any())).thenReturn(List.of(STEP_ID));
when(emrService.runJobFlow(any(), anyString())).thenAnswer(invocation -> {
EmrCluster cluster = invocation.getArgument(0);
cluster.setId(CLUSTER_ID);
return cluster;
});
sfnService = mock(StepFunctionsService.class);
when(sfnService.describeExecution(any())).thenAnswer(invocation -> parent(invocation.getArgument(0), "RUNNING"));
Instance<StepFunctionsService> instance = mock(Instance.class);
when(instance.get()).thenReturn(sfnService);
executor = AslExecutorFixture.builder()
.objectMapper(objectMapper)
.sfnService(instance)
.customResourceLiveness(null)
.emrTaskInvoker(new EmrTaskInvoker(new EmrHandler(emrService, objectMapper), objectMapper))
.nanoTime(testNanos::get)
.sleeper(testNanos::addAndGet)
.build();
}
@Test
void addStepSyncCancelsItsStepWhenTheTaskTimesOut() {
when(emrService.describeStep(CLUSTER_ID, STEP_ID)).thenReturn(step("RUNNING"));
Execution execution = run("""
{"StartAt": "Add", "States": {"Add": {"Type": "Task",
"Resource": "arn:aws:states:::elasticmapreduce:addStep.sync", "TimeoutSeconds": 1, "End": true}}}
""", ADD_STEP);
assertEquals("FAILED", execution.getStatus());
assertEquals("States.Timeout", execution.getError());
verify(emrService).cancelSteps(CLUSTER_ID, List.of(STEP_ID));
}
@Test
void addStepSyncFailsWithTheStepWhenTheStepFails() throws Exception {
EmrStep failed = step("FAILED");
failed.setStateChangeReason("Step failed");
when(emrService.describeStep(CLUSTER_ID, STEP_ID)).thenReturn(failed);
Execution execution = run(task("addStep.sync"), ADD_STEP);
assertEquals("FAILED", execution.getStatus());
assertEquals("States.TaskFailed", execution.getError());
JsonNode cause = objectMapper.readTree(execution.getCause());
assertEquals(STEP_ID, cause.path("Step").path("Id").asText());
assertEquals("FAILED", cause.path("Step").path("Status").path("State").asText());
verify(emrService, never()).cancelSteps(any(), any());
}
@Test
void addStepSyncWaitsUntilTheStepCompletes() throws Exception {
AtomicInteger polls = new AtomicInteger();
when(emrService.describeStep(CLUSTER_ID, STEP_ID))
.thenAnswer(invocation -> step(polls.incrementAndGet() < 3 ? "RUNNING" : "COMPLETED"));
Execution execution = run(task("addStep.sync"), ADD_STEP);
assertEquals("SUCCEEDED", execution.getStatus(), execution.getCause());
assertEquals(3, polls.get());
JsonNode output = objectMapper.readTree(execution.getOutput());
assertEquals(List.of("Step", "StepId"), fieldNames(output));
assertEquals("COMPLETED", output.path("Step").path("Status").path("State").asText());
assertEquals(STEP_ID, output.path("StepId").asText());
}
@Test
void createClusterSyncFailsWhenTheClusterTerminatesInsteadOfWaiting() throws Exception {
when(emrService.describeCluster(CLUSTER_ID)).thenReturn(cluster("TERMINATED_WITH_ERRORS"));
Execution execution = run(task("createCluster.sync"), CREATE_CLUSTER);
assertEquals("FAILED", execution.getStatus());
assertEquals("States.TaskFailed", execution.getError());
JsonNode cause = objectMapper.readTree(execution.getCause());
assertEquals("TERMINATED_WITH_ERRORS", cause.path("Cluster").path("Status").path("State").asText());
}
@Test
void stopExecutionLeavesTheClusterOfACreateClusterSyncRunning() {
when(emrService.describeCluster(CLUSTER_ID)).thenReturn(cluster("STARTING"));
AtomicInteger parentReads = new AtomicInteger();
when(sfnService.describeExecution(any())).thenAnswer(invocation ->
parent(invocation.getArgument(0), parentReads.incrementAndGet() < 3 ? "RUNNING" : "ABORTED"));
Execution execution = run(task("createCluster.sync"), CREATE_CLUSTER);
assertNull(execution.getError());
verify(emrService, never()).terminateJobFlows(any());
assertEquals(List.of(), history.stream().map(HistoryEvent::getType)
.filter(type -> type.equals("TaskFailed") || type.equals("TaskSucceeded")).toList());
}
private static String task(String api) {
return """
{"StartAt": "Emr", "States": {"Emr": {"Type": "Task",
"Resource": "arn:aws:states:::elasticmapreduce:%s", "End": true}}}
""".formatted(api);
}
private static EmrStep step(String state) {
EmrStep step = new EmrStep();
step.setId(STEP_ID);
step.setName("job");
step.setActionOnFailure("CONTINUE");
step.setState(state);
return step;
}
private static EmrCluster cluster(String state) {
EmrCluster cluster = new EmrCluster();
cluster.setId(CLUSTER_ID);
cluster.setName("sync");
cluster.setState(state);
return cluster;
}
private static Execution parent(String executionArn, String status) {
Execution parent = new Execution();
parent.setExecutionArn(executionArn);
parent.setStatus(status);
return parent;
}
private static List<String> fieldNames(JsonNode node) {
List<String> names = new ArrayList<>();
node.fieldNames().forEachRemaining(names::add);
return names;
}
private Execution run(String definition, String input) {
StateMachine stateMachine = new StateMachine();
stateMachine.setName("emr-sync-test");
stateMachine.setStateMachineArn("arn:aws:states:%s:%s:stateMachine:emr-sync-test".formatted(REGION, ACCOUNT));
stateMachine.setRoleArn("arn:aws:iam::%s:role/test-role".formatted(ACCOUNT));
stateMachine.setDefinition(definition);
Execution execution = new Execution();
execution.setName("emr-sync-execution");
execution.setExecutionArn("arn:aws:states:%s:%s:execution:emr-sync-test:emr-sync-execution"
.formatted(REGION, ACCOUNT));
execution.setStateMachineArn(stateMachine.getStateMachineArn());
execution.setInput(input);
history = new ArrayList<>();
executor.executeSync(stateMachine, execution, history, (updated, events) -> { });
return execution;
}
}
@@ -37,7 +37,7 @@ import static org.mockito.Mockito.mock;
* <p>Every other collaborator defaults to what the convenience constructors pass: a Mockito mock
* for each integration, the system clock, a real sleeper, {@code System.nanoTime()} for deadlines,
* no Wait cap override, AWS's 5-minute Express limit, and no RDS Data, Redshift Data, service
* registry or Lambda task authorizer. A Lambda target resolver is built over the function store
* registry, Lambda task authorizer or EMR task invoker. A Lambda target resolver is built over the function store
* unless a test supplies its own.
*/
final class AslExecutorFixture {
@@ -82,6 +82,7 @@ final class AslExecutorFixture {
private LambdaTaskAuthorizer lambdaTaskAuthorizer;
private Duration expressMaxExecutionTime;
private LongSupplier nanoTime;
private EmrTaskInvoker emrTaskInvoker;
private Builder() {
}
@@ -236,6 +237,11 @@ final class AslExecutorFixture {
return this;
}
Builder emrTaskInvoker(EmrTaskInvoker emrTaskInvoker) {
this.emrTaskInvoker = emrTaskInvoker;
return this;
}
AslExecutor build() {
return new AslExecutor(lambdaExecutor,
targetResolver != null ? targetResolver : new LambdaTargetResolver(functionStore, null),
@@ -245,7 +251,7 @@ final class AslExecutorFixture {
jsonataEvaluator != null ? jsonataEvaluator : new JsonataEvaluator(objectMapper),
sfnService, config, vertx, customResourceLiveness, clock, sleeper, maxWaitSeconds,
redshiftDataHandler, serviceRegistry, null, lambdaTaskAuthorizer, expressMaxExecutionTime,
nanoTime, null);
nanoTime, null, emrTaskInvoker);
}
}
}
@@ -0,0 +1,272 @@
package io.github.hectorvent.floci.services.stepfunctions;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.github.hectorvent.floci.testing.StepFunctionsExecutions;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.Response;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import static io.github.hectorvent.floci.testing.EmrRequests.emr;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* The {@code elasticmapreduce:} optimized integrations against Floci's EMR, from a state machine in a
* Region other than the default, so every call has to reach the clusters of the state machine's own.
*/
@QuarkusTest
class StepFunctionsEmrIntegrationTest {
private static final String REGION = "eu-west-3";
private static final String ROLE_ARN = "arn:aws:iam::000000000000:role/test-role";
private static final String RESOURCE = "arn:aws:states:::elasticmapreduce:";
private static final String GROUPS_CLUSTER = """
{"Name": "sfn-emr", "ReleaseLabel": "emr-7.5.0",
"Instances": {"KeepJobFlowAliveWhenNoSteps": true, "InstanceGroups": [
{"Name": "Primary", "InstanceRole": "MASTER", "InstanceType": "m5.xlarge", "InstanceCount": 1},
{"Name": "Core", "InstanceRole": "CORE", "InstanceType": "m5.xlarge", "InstanceCount": 2}]}}
""";
private static final String FLEETS_CLUSTER = """
{"Name": "sfn-emr-fleets", "ReleaseLabel": "emr-7.5.0",
"Instances": {"KeepJobFlowAliveWhenNoSteps": true, "InstanceFleets": [
{"Name": "Primary", "InstanceFleetType": "MASTER", "TargetOnDemandCapacity": 1,
"InstanceTypeConfigs": [{"InstanceType": "m5.xlarge"}]},
{"Name": "Core", "InstanceFleetType": "CORE", "TargetOnDemandCapacity": 2,
"InstanceTypeConfigs": [{"InstanceType": "m5.xlarge"}]}]}}
""";
private static final String STEP = """
{"Name": "job", "ActionOnFailure": "CONTINUE",
"HadoopJarStep": {"Jar": "command-runner.jar", "Args": ["spark-submit", "s3://bucket/job.py"]}}
""";
private static final ObjectMapper MAPPER = new ObjectMapper();
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@Test
void aClusterIsCreatedGivenAStepResizedAndTerminated() throws Exception {
String definition = """
{"StartAt": "Create", "States": {
"Create": {"Type": "Task", "Resource": "%1$screateCluster.sync", "Parameters": %2$s,
"ResultPath": "$.cluster", "Next": "Run"},
"Run": {"Type": "Task", "Resource": "%1$saddStep.sync",
"Parameters": {"ClusterId.$": "$.cluster.ClusterId", "Step": %3$s},
"ResultPath": "$.step", "Next": "Queue"},
"Queue": {"Type": "Task", "Resource": "%1$saddStep",
"Parameters": {"ClusterId.$": "$.cluster.ClusterId", "Step": %3$s},
"ResultPath": "$.queued", "Next": "Cancel"},
"Cancel": {"Type": "Task", "Resource": "%1$scancelStep",
"Parameters": {"ClusterId.$": "$.cluster.ClusterId", "StepId.$": "$.queued.StepId"},
"ResultPath": "$.cancel", "Next": "Resize"},
"Resize": {"Type": "Task", "Resource": "%1$smodifyInstanceGroupByName",
"Parameters": {"ClusterId.$": "$.cluster.ClusterId", "InstanceGroupName": "Core",
"InstanceGroup": {"InstanceCount": 4}},
"ResultPath": "$.resize", "Next": "Terminate"},
"Terminate": {"Type": "Task", "Resource": "%1$sterminateCluster.sync",
"Parameters": {"ClusterId.$": "$.cluster.ClusterId"},
"ResultPath": "$.terminated", "End": true}}}
""".formatted(RESOURCE, GROUPS_CLUSTER, STEP);
Response execution = run(definition);
assertEquals("SUCCEEDED", execution.jsonPath().getString("status"), execution.asString());
JsonNode output = MAPPER.readTree(execution.jsonPath().getString("output"));
JsonNode cluster = output.path("cluster");
String clusterId = cluster.path("ClusterId").asText();
assertEquals(List.of("Cluster", "ClusterId"), fieldNames(cluster));
assertEquals(clusterId, cluster.path("Cluster").path("Id").asText());
assertEquals("WAITING", cluster.path("Cluster").path("Status").path("State").asText());
JsonNode step = output.path("step");
assertEquals(List.of("Step", "StepId"), fieldNames(step));
assertEquals(step.path("StepId").asText(), step.path("Step").path("Id").asText());
assertEquals("COMPLETED", step.path("Step").path("Status").path("State").asText());
String queuedId = output.path("queued").path("StepId").asText();
assertEquals(List.of("StepId"), fieldNames(output.path("queued")));
assertTrue(queuedId.startsWith("s-"), queuedId);
JsonNode cancelled = output.path("cancel").path("CancelStepsInfo");
assertEquals(queuedId, cancelled.path("StepId").asText());
assertEquals("FAILED", cancelled.path("Status").asText());
assertEquals(MAPPER.createObjectNode(), output.path("resize"));
assertEquals("TERMINATED", output.path("terminated").path("Cluster").path("Status").path("State").asText());
emr(REGION, "ListInstanceGroups", "{\"ClusterId\":\"" + clusterId + "\"}").then().statusCode(200)
.body("InstanceGroups.find { it.Name == 'Core' }.RequestedInstanceCount", equalTo(4));
emr("DescribeCluster", "{\"ClusterId\":\"" + clusterId + "\"}").then().statusCode(400);
JsonNode submitted = history(execution).stream()
.filter(event -> "TaskSubmitted".equals(event.path("type").asText()))
.findFirst().orElseThrow().path("taskSubmittedEventDetails");
assertEquals("elasticmapreduce", submitted.path("resourceType").asText());
assertEquals("createCluster.sync", submitted.path("resource").asText());
assertEquals(clusterId, MAPPER.readTree(submitted.path("output").asText()).path("ClusterId").asText());
}
@Test
void anInstanceFleetIsResizedByName() throws Exception {
String definition = """
{"StartAt": "Create", "States": {
"Create": {"Type": "Task", "Resource": "%1$screateCluster", "Parameters": %2$s,
"ResultPath": "$.cluster", "Next": "Resize"},
"Resize": {"Type": "Task", "Resource": "%1$smodifyInstanceFleetByName",
"Parameters": {"ClusterId.$": "$.cluster.ClusterId", "InstanceFleetName": "Core",
"InstanceFleet": {"TargetOnDemandCapacity": 5}},
"ResultPath": "$.resize", "End": true}}}
""".formatted(RESOURCE, FLEETS_CLUSTER);
Response execution = run(definition);
assertEquals("SUCCEEDED", execution.jsonPath().getString("status"), execution.asString());
JsonNode output = MAPPER.readTree(execution.jsonPath().getString("output"));
assertEquals(List.of("ClusterId"), fieldNames(output.path("cluster")));
emr(REGION, "ListInstanceFleets", "{\"ClusterId\":\"" + output.path("cluster").path("ClusterId").asText() + "\"}")
.then().statusCode(200)
.body("InstanceFleets.find { it.Name == 'Core' }.TargetOnDemandCapacity", equalTo(5));
}
@Test
void createClusterRefusesWhatTheGuideRulesOut() {
assertFails(task("createCluster", "{\"Name\": \"transient\", \"Instances\": {}}"), "States.TaskFailed",
"The field Instances.KeepJobFlowAliveWhenNoSteps is mandatory, and must have the Boolean value TRUE.");
assertFails(task("createCluster", """
{"Name": "with-steps", "Instances": {"KeepJobFlowAliveWhenNoSteps": true}, "Steps": [%s]}
""".formatted(STEP)), "States.TaskFailed", "The field Steps is not allowed.");
}
@Test
void aTaskWithoutTheFieldsItsApiActsOnFails() {
assertFails(task("terminateCluster", "{}"), "States.TaskFailed", "The field ClusterId is required.");
assertFails(task("addStep.sync", "{\"ClusterId\": \" \", \"Step\": " + STEP + "}"), "States.TaskFailed",
"The field ClusterId is required.");
assertFails(task("cancelStep", "{\"ClusterId\": \"j-ANY\"}"), "States.TaskFailed",
"The field StepId is required.");
assertFails(task("setClusterTerminationProtection", "{\"ClusterId\": \"j-ANY\"}"),
"EMR.AmazonElasticMapReduceException", "1 validation error detected: Value null at "
+ "'terminationProtected' failed to satisfy constraint: Member must not be null");
assertFails(task("modifyInstanceGroupByName", "{\"ClusterId\": \"j-ANY\", \"InstanceGroup\": {}}"),
"States.TaskFailed", "The field InstanceGroupName is required.");
assertFails(task("modifyInstanceFleetByName", "{\"ClusterId\": \"j-ANY\", \"InstanceFleet\": {}}"),
"States.TaskFailed", "The field InstanceFleetName is required.");
}
@Test
void emrErrorsAreNamedAfterTheSdkExceptionClass() {
assertFails(task("addStep.sync", "{\"ClusterId\": \"j-NOSUCHCLUSTER\", \"Step\": " + STEP + "}"),
"EMR.AmazonElasticMapReduceException", "Specified job flow ID does not exist.");
assertFails(task("cancelStep", "{\"ClusterId\": \"j-NOSUCHCLUSTER\", \"StepId\": \"s-NOSUCHSTEP\"}"),
"EMR.InvalidRequestException", "Cluster id 'j-NOSUCHCLUSTER' is not valid.");
String protectedCluster = """
{"StartAt": "Create", "States": {
"Create": {"Type": "Task", "Resource": "%1$screateCluster", "Parameters": %2$s,
"ResultPath": "$.cluster", "Next": "Protect"},
"Protect": {"Type": "Task", "Resource": "%1$ssetClusterTerminationProtection",
"Parameters": {"ClusterId.$": "$.cluster.ClusterId", "TerminationProtected": true},
"ResultPath": null, "Next": "Terminate"},
"Terminate": {"Type": "Task", "Resource": "%1$sterminateCluster",
"Parameters": {"ClusterId.$": "$.cluster.ClusterId"}, "End": true}}}
""".formatted(RESOURCE, GROUPS_CLUSTER);
assertFails(protectedCluster, "EMR.AmazonElasticMapReduceException",
"Could not shut down one or more job flows since they are termination protected.");
}
@Test
void aResizeAfterTheClusterTerminatedFailsAsOnAws() {
assertFails(resizeAfterTermination(GROUPS_CLUSTER, "modifyInstanceGroupByName",
"\"InstanceGroupName\": \"Core\", \"InstanceGroup\": {\"InstanceCount\": 4}"),
"EMR.AmazonElasticMapReduceException",
"An instance group may only be modified when the cluster is running or waiting.");
assertFails(resizeAfterTermination(FLEETS_CLUSTER, "modifyInstanceFleetByName",
"\"InstanceFleetName\": \"Core\", \"InstanceFleet\": {\"TargetOnDemandCapacity\": 5}"),
"EMR.InvalidRequestException",
"A job flow that is shutting down, terminated, or finished may not be modified.");
}
@Test
void aByNameLookupNeedsOneMatchAndAnUnsupportedPatternFails() {
String unknownGroup = """
{"StartAt": "Create", "States": {
"Create": {"Type": "Task", "Resource": "%1$screateCluster", "Parameters": %2$s,
"ResultPath": "$.cluster", "Next": "Resize"},
"Resize": {"Type": "Task", "Resource": "%1$smodifyInstanceGroupByName",
"Parameters": {"ClusterId.$": "$.cluster.ClusterId", "InstanceGroupName": "Task",
"InstanceGroup": {"InstanceCount": 1}}, "End": true}}}
""".formatted(RESOURCE, GROUPS_CLUSTER);
assertFails(unknownGroup, "States.TaskFailed", "The cluster has no instance group named 'Task'.");
assertFails(task("cancelStep.sync", "{\"ClusterId\": \"j-ANY\", \"StepId\": \"s-ANY\"}"),
"States.TaskFailed", "Unsupported resource: " + RESOURCE + "cancelStep.sync");
}
private static String resizeAfterTermination(String cluster, String api, String resize) {
return """
{"StartAt": "Create", "States": {
"Create": {"Type": "Task", "Resource": "%1$screateCluster", "Parameters": %2$s,
"ResultPath": "$.cluster", "Next": "Terminate"},
"Terminate": {"Type": "Task", "Resource": "%1$sterminateCluster.sync",
"Parameters": {"ClusterId.$": "$.cluster.ClusterId"},
"ResultPath": null, "Next": "Resize"},
"Resize": {"Type": "Task", "Resource": "%1$s%3$s",
"Parameters": {"ClusterId.$": "$.cluster.ClusterId", %4$s}, "End": true}}}
""".formatted(RESOURCE, cluster, api, resize);
}
private static String task(String api, String parameters) {
return """
{"StartAt": "Emr", "States": {"Emr": {"Type": "Task", "Resource": "%s%s",
"Parameters": %s, "End": true}}}
""".formatted(RESOURCE, api, parameters);
}
private void assertFails(String definition, String error, String cause) {
Response execution = run(definition);
assertEquals("FAILED", execution.jsonPath().getString("status"), execution.asString());
assertEquals(error, execution.jsonPath().getString("error"));
assertEquals(cause, execution.jsonPath().getString("cause"));
}
private Response run(String definition) {
String stateMachineArn = sfn("CreateStateMachine", MAPPER.createObjectNode()
.put("name", "sfn-emr-" + UUID.randomUUID())
.put("definition", definition)
.put("roleArn", ROLE_ARN).toString())
.then().statusCode(200).extract().path("stateMachineArn");
String executionArn = sfn("StartExecution", MAPPER.createObjectNode()
.put("stateMachineArn", stateMachineArn).put("input", "{}").toString())
.then().statusCode(200).extract().path("executionArn");
return StepFunctionsExecutions.waitForTerminalState(executionArn);
}
private List<JsonNode> history(Response execution) throws Exception {
String body = sfn("GetExecutionHistory", MAPPER.createObjectNode()
.put("executionArn", execution.jsonPath().getString("executionArn")).toString())
.then().statusCode(200).extract().asString();
List<JsonNode> events = new ArrayList<>();
MAPPER.readTree(body).path("events").forEach(events::add);
return events;
}
private static Response sfn(String action, String body) {
return given()
.header("Authorization", "AWS4-HMAC-SHA256 Credential=AKID/20260215/" + REGION
+ "/states/aws4_request, SignedHeaders=host, Signature=abc")
.header("X-Amz-Target", "AWSStepFunctions." + action)
.contentType("application/x-amz-json-1.0")
.body(body)
.when().post("/");
}
private static List<String> fieldNames(JsonNode node) {
List<String> names = new ArrayList<>();
node.fieldNames().forEachRemaining(names::add);
return names;
}
}