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

@@ -26,6 +26,11 @@ public final class SmithyValidationErrors {
return count + String.join("; ", violations);
}
/** The violation for a required member the request leaves out. */
public static String notNull(String path) {
return "Value null at '" + path + "' failed to satisfy constraint: Member must not be null";
}
/** The 400 error carrying {@link #message} under the protocol's validation error code. */
public static AwsException exception(String errorCode, List<String> violations) {
return new AwsException(errorCode, message(violations), 400);
@@ -10,7 +10,9 @@ import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.AwsJson11Controller;
import io.github.hectorvent.floci.core.common.AwsJsonTimestamp;
import io.github.hectorvent.floci.core.common.AwsRegions;
import io.github.hectorvent.floci.core.common.JsonErrorResponseUtils;
import io.github.hectorvent.floci.core.common.PaginatedResult;
import io.github.hectorvent.floci.core.common.SmithyValidationErrors;
import io.github.hectorvent.floci.services.emr.model.EmrBlockPublicAccess;
import io.github.hectorvent.floci.services.emr.model.EmrCluster;
import io.github.hectorvent.floci.services.emr.model.EmrInstanceFleet;
@@ -98,6 +100,10 @@ public class EmrHandler {
.build();
};
} catch (AwsException e) {
if (e.getExtendedData() != null) {
// Members an error adds to its message, such as InvalidRequestException's ErrorCode.
return JsonErrorResponseUtils.createErrorResponse(e);
}
return Response.status(e.getHttpStatus())
.entity(new AwsErrorResponse(e.jsonType(), e.getMessage()))
.build();
@@ -180,29 +186,34 @@ public class EmrHandler {
}
private Response handleTerminateJobFlows(JsonNode request) {
requireMembers(request, "JobFlowIds");
service.terminateJobFlows(stringList(request.path("JobFlowIds")));
return Response.ok(objectMapper.createObjectNode()).build();
}
private Response handleSetTerminationProtection(JsonNode request) {
requireMembers(request, "JobFlowIds", "TerminationProtected");
service.setTerminationProtection(stringList(request.path("JobFlowIds")),
request.path("TerminationProtected").asBoolean(false));
return Response.ok(objectMapper.createObjectNode()).build();
}
private Response handleSetVisibleToAllUsers(JsonNode request) {
requireMembers(request, "JobFlowIds", "VisibleToAllUsers");
service.setVisibleToAllUsers(stringList(request.path("JobFlowIds")),
request.path("VisibleToAllUsers").asBoolean(true));
return Response.ok(objectMapper.createObjectNode()).build();
}
private Response handleSetKeepAlive(JsonNode request) {
requireMembers(request, "JobFlowIds", "KeepJobFlowAliveWhenNoSteps");
service.setKeepJobFlowAliveWhenNoSteps(stringList(request.path("JobFlowIds")),
request.path("KeepJobFlowAliveWhenNoSteps").asBoolean(false));
return Response.ok(objectMapper.createObjectNode()).build();
}
private Response handleSetUnhealthyNodeReplacement(JsonNode request) {
requireMembers(request, "JobFlowIds", "UnhealthyNodeReplacement");
service.setUnhealthyNodeReplacement(stringList(request.path("JobFlowIds")),
request.path("UnhealthyNodeReplacement").asBoolean(false));
return Response.ok(objectMapper.createObjectNode()).build();
@@ -244,6 +255,7 @@ public class EmrHandler {
}
private Response handleCancelSteps(JsonNode request) {
requireMembers(request, "StepIds");
List<EmrService.CancelStepInfo> infos = service.cancelSteps(
text(request, "ClusterId"), stringList(request.path("StepIds")));
ObjectNode response = objectMapper.createObjectNode();
@@ -860,6 +872,25 @@ public class EmrHandler {
return values;
}
/**
* Refuses a request that leaves out members its model requires, which would otherwise read as an
* empty list or a default flag and succeed on nothing. The wording is AWS's framework validation, as
* for RunJobFlow's Name; an explicitly empty JobFlowIds is still a valid list.
*/
private static void requireMembers(JsonNode request, String... members) {
List<String> violations = new ArrayList<>();
for (String member : members) {
JsonNode value = request.path(member);
if (value.isMissingNode() || value.isNull()) {
violations.add(SmithyValidationErrors.notNull(
Character.toLowerCase(member.charAt(0)) + member.substring(1)));
}
}
if (!violations.isEmpty()) {
throw SmithyValidationErrors.validationException(violations);
}
}
private String text(JsonNode request, String field) {
JsonNode node = request.path(field);
return node.isMissingNode() || node.isNull() ? null : node.asText(null);
@@ -45,6 +45,9 @@ public class EmrService {
private static final String UPPER_ALNUM = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
private static final SecureRandom RANDOM = new SecureRandom();
// AWS's answer to a change on a terminated cluster, for AddJobFlowSteps and ModifyInstanceFleet.
private static final String JOB_FLOW_SHUT_DOWN =
"A job flow that is shutting down, terminated, or finished may not be modified.";
private final StorageBackend<String, EmrCluster> clusterStore;
private final StorageBackend<String, SecurityConfiguration> secConfigStore;
@@ -81,9 +84,7 @@ public class EmrService {
// Only a missing Name fails AWS's framework validation: the member is REQUIRED but its
// constraint is len=[0..256], so an explicit empty string is accepted by real EMR.
if (cluster.getName() == null) {
throw SmithyValidationErrors.validationException(
"Value null at 'name' failed to satisfy constraint: "
+ "Member must not be null");
throw SmithyValidationErrors.validationException(SmithyValidationErrors.notNull("name"));
}
String id = "j-" + randomId(13);
cluster.setId(id);
@@ -212,10 +213,12 @@ public class EmrService {
// ──────────────────────────── Steps ────────────────────────────
public synchronized List<String> addJobFlowSteps(String clusterId, List<EmrStep> steps) {
EmrCluster cluster = requireCluster(clusterId);
// AWS's own wording for an unknown job flow here, not DescribeCluster's: a botocore ClientError
// (raster-foundry/raster-foundry#352) and a CloudTrail record on AWS re:Post both show it.
EmrCluster cluster = clusterId == null ? requireCluster(null) : findCluster(clusterId).orElseThrow(
() -> new AwsException("ValidationException", "Specified job flow ID does not exist.", 400));
if ("TERMINATED".equals(cluster.getState())) {
throw new AwsException("ValidationException",
"A job flow that is shutting down, terminated, or finished may not be modified.", 400);
throw new AwsException("ValidationException", JOB_FLOW_SHUT_DOWN, 400);
}
List<String> ids = new ArrayList<>();
for (EmrStep step : steps) {
@@ -315,7 +318,12 @@ public class EmrService {
List<EmrInstanceGroup> groups = new ArrayList<>();
for (InstanceGroupModification mod : modifications) {
EmrCluster found = clusterId != null ? requireCluster(clusterId) : clusterOwning(region, mod.instanceGroupId());
rejectTerminatedCluster(found);
// AWS's answer here, recorded by Terraform users
// (hashicorp/terraform-provider-aws#1355 and #9400).
if ("TERMINATED".equals(found.getState())) {
throw new AwsException("ValidationException",
"An instance group may only be modified when the cluster is running or waiting.", 400);
}
// One copy per cluster, so two groups of the same cluster are changed and stored together.
EmrCluster cluster = touched.computeIfAbsent(found.getId(), id -> found);
EmrInstanceGroup group = requireInstanceGroup(cluster, mod.instanceGroupId());
@@ -368,7 +376,12 @@ public class EmrService {
if (instanceFleetId == null) {
throw invalid("InstanceFleetId is required.");
}
rejectTerminatedCluster(cluster);
// AWS's answer for a cluster terminated a while before, ErrorCode member included
// (hashicorp/terraform-provider-aws#31375, 2023).
if ("TERMINATED".equals(cluster.getState())) {
throw new AwsException("InvalidRequestException", JOB_FLOW_SHUT_DOWN, 400,
Map.of("ErrorCode", "INVALID_JOB_SHUT_DOWN"));
}
EmrInstanceFleet fleet = cluster.getInstanceFleets().stream()
.filter(f -> instanceFleetId.equals(f.getId()))
.findFirst()
@@ -183,8 +183,8 @@ public class AslExecutor {
private static final int INLINE_MAP_MAX_CONCURRENCY = 40;
private static final int DISTRIBUTED_MAP_MAX_CONCURRENCY = 10_000;
// How often a .sync integration (ecs:runTask, states:startExecution) re-reads the job it waits
// on. The wait itself is bounded by the Task's TimeoutSeconds and the execution's budget.
// How often a .sync integration (ecs:runTask, elasticmapreduce, states:startExecution) re-reads the job
// it waits on. The wait itself is bounded by the Task's TimeoutSeconds and the execution's budget.
private static final long SYNC_POLL_INTERVAL_MS = 100;
// AWS caps the string input of States.Base64Encode/Base64Decode/Hash at 10,000 characters
@@ -267,6 +267,7 @@ public class AslExecutor {
private final Instance<StepFunctionsService> sfnService;
private final WebClient webClient;
private final ApiGatewayTaskInvoker apiGatewayTaskInvoker;
private final EmrTaskInvoker emrTaskInvoker;
private final EmulatorConfig config;
private final NestedTaskCredentials nestedTaskCredentials;
private final CustomResourceLiveness customResourceLiveness;
@@ -297,14 +298,15 @@ public class AslExecutor {
Instance<StepFunctionsService> sfnService, EmulatorConfig config, Vertx vertx,
CustomResourceLiveness customResourceLiveness, RedshiftDataJsonHandler redshiftDataHandler,
ServiceRegistry serviceRegistry, NestedTaskCredentials nestedTaskCredentials,
LambdaTaskAuthorizer lambdaTaskAuthorizer, ApiGatewayTaskInvoker apiGatewayTaskInvoker) {
LambdaTaskAuthorizer lambdaTaskAuthorizer, ApiGatewayTaskInvoker apiGatewayTaskInvoker,
EmrTaskInvoker emrTaskInvoker) {
this(lambdaExecutor, targetResolver, dynamoDb, dynamoDbJsonHandler,
sqsJsonHandler, snsJsonHandler, cloudFormationHandler,
ec2Service, s3Service, ecsService, ecsJsonHandler,
eventBridgeHandler, schedulerService, schedulerController, rdsDataService,
objectMapper, jsonataEvaluator, sfnService, config, vertx, customResourceLiveness,
Clock.systemUTC(), TimeUnit.NANOSECONDS::sleep, null, redshiftDataHandler, serviceRegistry,
nestedTaskCredentials, lambdaTaskAuthorizer, null, null, apiGatewayTaskInvoker);
nestedTaskCredentials, lambdaTaskAuthorizer, null, null, apiGatewayTaskInvoker, emrTaskInvoker);
}
AslExecutor(LambdaExecutorService lambdaExecutor, LambdaTargetResolver targetResolver,
@@ -322,8 +324,9 @@ public class AslExecutor {
RedshiftDataJsonHandler redshiftDataHandler, ServiceRegistry serviceRegistry,
NestedTaskCredentials nestedTaskCredentials, LambdaTaskAuthorizer lambdaTaskAuthorizer,
Duration expressMaxExecutionTimeOverride, LongSupplier nanoTimeOverride,
ApiGatewayTaskInvoker apiGatewayTaskInvoker) {
ApiGatewayTaskInvoker apiGatewayTaskInvoker, EmrTaskInvoker emrTaskInvoker) {
this.apiGatewayTaskInvoker = apiGatewayTaskInvoker;
this.emrTaskInvoker = emrTaskInvoker;
this.nestedTaskCredentials = nestedTaskCredentials;
this.serviceRegistry = serviceRegistry;
this.lambdaTaskAuthorizer = lambdaTaskAuthorizer;
@@ -386,7 +389,7 @@ public class AslExecutor {
ec2Service, s3Service, ecsService, ecsJsonHandler,
eventBridgeHandler, schedulerService, schedulerController, rdsDataService,
objectMapper, jsonataEvaluator, sfnService, config, vertx, customResourceLiveness,
Clock.systemUTC(), TimeUnit.NANOSECONDS::sleep, null, null, null, null, null, null, null, null);
Clock.systemUTC(), TimeUnit.NANOSECONDS::sleep, null, null, null, null, null, null, null, null, null);
}
// Kept for tests that do not exercise the Redshift Data API integration.
@@ -407,7 +410,7 @@ public class AslExecutor {
ec2Service, s3Service, ecsService, ecsJsonHandler,
eventBridgeHandler, schedulerService, schedulerController, rdsDataService,
objectMapper, jsonataEvaluator, sfnService, config, vertx, customResourceLiveness,
clock, sleeper, maxWaitSecondsOverride, null, null, null, null, null, null, null);
clock, sleeper, maxWaitSecondsOverride, null, null, null, null, null, null, null, null);
}
AslExecutor(LambdaExecutorService lambdaExecutor, LambdaFunctionStore functionStore,
@@ -1444,6 +1447,14 @@ public class AslExecutor {
jobSubmitted);
}
// EMR optimized integrations: request-response and .sync. AWS supports no .waitForTaskToken
// variant, so one carrying a token falls through to Unsupported resource.
if (integration.isOptimizedService("elasticmapreduce") && taskToken == null) {
String region = extractRegionFromArn(sm.getStateMachineArn());
return invokeEmr(integration, input, region, executionArn, executionDeadlineNanos, taskDeadlineNanos,
jobSubmitted);
}
// AWS SDK service integrations: Step Functions
if (integration.isSdkService("sfn")) {
String region = extractRegionFromArn(sm.getStateMachineArn());
@@ -2193,6 +2204,43 @@ public class AslExecutor {
}
}
/**
* The {@code elasticmapreduce:} integrations. A {@code .sync} Task records its call's response as
* submitted and polls the cluster or step as {@code ecs:runTask.sync} polls its tasks, bounded by
* the same two clocks; whatever ends the wait first abandons the job.
*/
private JsonNode invokeEmr(StatesIntegration integration, JsonNode input, String region, String executionArn,
long executionDeadlineNanos, long taskDeadlineNanos,
Consumer<JsonNode> jobSubmitted) throws Exception {
EmrTaskInvoker.Job job = emrTaskInvoker.start(integration, input, region);
if (integration.suffix().isEmpty()) {
return job.response();
}
try {
jobSubmitted.accept(job.response());
} catch (RuntimeException e) {
emrTaskInvoker.abandon(job, region);
throw e;
}
while (true) {
try {
sleepOrTimeOutTask(TimeUnit.MILLISECONDS.toNanos(SYNC_POLL_INTERVAL_MS),
executionDeadlineNanos, taskDeadlineNanos);
} catch (TaskTimedOutException | ExecutionTimedOutException | InterruptedException e) {
emrTaskInvoker.abandon(job, region);
throw e;
}
if (abortedByCaller(executionArn)) {
emrTaskInvoker.abandon(job, region);
throw new ExecutionAbortedException();
}
Optional<JsonNode> result = emrTaskInvoker.poll(job, region);
if (result.isPresent()) {
return result.get();
}
}
}
/**
* The reason AWS writes on a job it stops because the {@code .sync} Task waiting on it ended
* first, whichever way it ended: verbatim, as the ECS task's {@code stoppedReason} and the child
@@ -0,0 +1,258 @@
package io.github.hectorvent.floci.services.stepfunctions;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.RequestScopes;
import io.github.hectorvent.floci.services.emr.EmrHandler;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import jakarta.ws.rs.core.Response;
import org.jboss.logging.Logger;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.Set;
/**
* The optimized {@code arn:<partition>:states:::elasticmapreduce:*} integrations. Each one is an EMR
* API under renamed fields, as the Step Functions guide's "Optimized Amazon EMR APIs" table lists
* them, run through {@link EmrHandler} in the state machine's Region. A {@code .sync} Task calls
* {@link #start}, then {@link #poll} until its cluster or step is done; {@link AslExecutor} owns the
* wait between polls.
*/
@ApplicationScoped
public class EmrTaskInvoker {
private static final Logger LOG = Logger.getLogger(EmrTaskInvoker.class);
// A failure is named after the SDK exception class: the errors EMR models keep their own, and any
// other code is the base class. AWS re:Post, "AWS Step Function does not recognize job flow ID":
// a ValidationException fails addStep.sync as EMR.AmazonElasticMapReduceException.
private static final Set<String> MODELED_ERRORS = Set.of("InvalidRequestException", "InternalServerException");
private static final String BASE_ERROR = "AmazonElasticMapReduceException";
private static final Set<String> APIS = Set.of("createCluster", "setClusterTerminationProtection",
"terminateCluster", "addStep", "cancelStep", "modifyInstanceFleetByName", "modifyInstanceGroupByName");
private static final Set<String> SYNC_APIS = Set.of("createCluster", "terminateCluster", "addStep");
private static final Set<String> TERMINATED_STATES = Set.of("TERMINATED", "TERMINATED_WITH_ERRORS");
private static final Set<String> FAILED_STEP_STATES = Set.of("FAILED", "CANCELLED", "INTERRUPTED");
private final EmrHandler emr;
private final ObjectMapper objectMapper;
@Inject
public EmrTaskInvoker(EmrHandler emr, ObjectMapper objectMapper) {
this.emr = emr;
this.objectMapper = objectMapper;
}
/**
* A started call: the integration's response, and the cluster, or step, a {@code .sync} Task
* waits on.
*/
record Job(String api, String clusterId, String stepId, ObjectNode response) {}
Job start(StatesIntegration integration, JsonNode input, String region) {
String api = integration.api();
if (!APIS.contains(api)
|| !integration.suffix().isEmpty() && !(".sync".equals(integration.suffix()) && SYNC_APIS.contains(api))) {
throw unsupported(integration);
}
JsonNode request = input != null && input.isObject() ? input : objectMapper.createObjectNode();
// The integration's own fields, named as the Task wrote them: renamed into JobFlowIds or StepIds,
// a missing one would reach EMR as a "null" id.
String clusterId = "createCluster".equals(api) ? null : required(request, "ClusterId");
return switch (api) {
case "createCluster" -> createCluster(request, region);
case "setClusterTerminationProtection" -> new Job(api, clusterId, null,
call("SetTerminationProtection", withJobFlowIds(request), region));
case "terminateCluster" -> new Job(api, clusterId, null,
call("TerminateJobFlows", withJobFlowIds(request), region));
case "addStep" -> addStep(request, clusterId, region);
case "cancelStep" -> cancelStep(request, clusterId, region);
case "modifyInstanceFleetByName" -> modifyInstanceFleetByName(request, clusterId, region);
case "modifyInstanceGroupByName" -> modifyInstanceGroupByName(request, clusterId, region);
default -> throw unsupported(integration);
};
}
/**
* The Task's result once the job is done, empty while it runs. The result is the describe call's
* response with the starting call's merged in: a {@code createCluster.sync} output recorded on
* AWS is {@code Cluster}, the SDK metadata, then {@code ClusterId}.
*/
Optional<JsonNode> poll(Job job, String region) {
if ("addStep".equals(job.api())) {
ObjectNode request = clusterRequest(job.clusterId());
request.put("StepId", job.stepId());
JsonNode described = call("DescribeStep", request, region);
String state = described.path("Step").path("Status").path("State").asText();
if (FAILED_STEP_STATES.contains(state)) {
throw failed(described);
}
return "COMPLETED".equals(state) ? Optional.of(merged(described, job.response())) : Optional.empty();
}
JsonNode described = call("DescribeCluster", clusterRequest(job.clusterId()), region);
String state = described.path("Cluster").path("Status").path("State").asText();
if ("terminateCluster".equals(job.api())) {
return TERMINATED_STATES.contains(state)
? Optional.of(merged(described, job.response())) : Optional.empty();
}
if (TERMINATED_STATES.contains(state)) {
throw failed(described);
}
return "WAITING".equals(state) ? Optional.of(merged(described, job.response())) : Optional.empty();
}
/**
* Best effort, for a {@code .sync} Task that ends before its job does: Step Functions "will make a
* best-effort attempt to cancel the task", and addStep's IAM policy grants it CancelSteps. A cluster
* is left running, since "Step Functions does not terminate an Amazon EMR cluster automatically if
* execution is stopped."
*/
void abandon(Job job, String region) {
if (!"addStep".equals(job.api())) {
return;
}
ObjectNode request = clusterRequest(job.clusterId());
request.putArray("StepIds").add(job.stepId());
try {
call("CancelSteps", request, region);
} catch (RuntimeException e) {
LOG.warnv("elasticmapreduce:addStep.sync ended before its step {0} did, and the step could not be "
+ "cancelled: {1}", job.stepId(), e.getMessage());
}
}
private Job createCluster(JsonNode request, String region) {
// The two differences the guide lists from RunJobFlow. No source gives the error AWS answers either with.
if (!request.path("Instances").path("KeepJobFlowAliveWhenNoSteps").booleanValue()) {
throw refused("The field Instances.KeepJobFlowAliveWhenNoSteps is mandatory, "
+ "and must have the Boolean value TRUE.");
}
if (request.has("Steps")) {
throw refused("The field Steps is not allowed.");
}
String clusterId = call("RunJobFlow", request, region).path("JobFlowId").asText();
return new Job("createCluster", clusterId, null, objectMapper.createObjectNode().put("ClusterId", clusterId));
}
private Job addStep(JsonNode request, String clusterId, String region) {
if (!request.path("Step").isObject()) {
throw refused("The field Step is required.");
}
ObjectNode add = request.deepCopy();
add.remove(List.of("ClusterId", "Step"));
add.put("JobFlowId", clusterId);
add.putArray("Steps").add(request.get("Step"));
String stepId = call("AddJobFlowSteps", add, region).path("StepIds").path(0).asText();
return new Job("addStep", clusterId, stepId, objectMapper.createObjectNode().put("StepId", stepId));
}
private Job cancelStep(JsonNode request, String clusterId, String region) {
String stepId = required(request, "StepId");
ObjectNode cancel = request.deepCopy();
cancel.remove("StepId");
cancel.putArray("StepIds").add(stepId);
JsonNode info = call("CancelSteps", cancel, region).path("CancelStepsInfoList").path(0);
ObjectNode response = objectMapper.createObjectNode();
response.set("CancelStepsInfo", info.isMissingNode() ? objectMapper.createObjectNode() : info);
return new Job("cancelStep", clusterId, null, response);
}
private Job modifyInstanceFleetByName(JsonNode request, String clusterId, String region) {
JsonNode fleet = request.path("InstanceFleet");
if (fleet.has("InstanceFleetId")) {
throw refused("The field InstanceFleet.InstanceFleetId is not allowed.");
}
String name = required(request, "InstanceFleetName");
JsonNode fleets = call("ListInstanceFleets", clusterRequest(clusterId), region).path("InstanceFleets");
ObjectNode modification = fleet.isObject() ? fleet.deepCopy() : objectMapper.createObjectNode();
modification.put("InstanceFleetId", idOfNamed(fleets, name, "instance fleet"));
ObjectNode modify = clusterRequest(clusterId);
modify.set("InstanceFleet", modification);
return new Job("modifyInstanceFleetByName", clusterId, null, call("ModifyInstanceFleet", modify, region));
}
private Job modifyInstanceGroupByName(JsonNode request, String clusterId, String region) {
JsonNode group = request.path("InstanceGroup");
if (group.has("InstanceGroupId")) {
throw refused("The field InstanceGroup.InstanceGroupId is not allowed.");
}
String name = required(request, "InstanceGroupName");
JsonNode groups = call("ListInstanceGroups", clusterRequest(clusterId), region).path("InstanceGroups");
ObjectNode modification = group.isObject() ? group.deepCopy() : objectMapper.createObjectNode();
modification.put("InstanceGroupId", idOfNamed(groups, name, "instance group"));
ObjectNode modify = clusterRequest(clusterId);
modify.putArray("InstanceGroups").add(modification);
return new Job("modifyInstanceGroupByName", clusterId, null, call("ModifyInstanceGroups", modify, region));
}
/** The guide asks for unique names whenever a ByName API is used; the lookup reads ListInstance*. */
private static String idOfNamed(JsonNode members, String name, String kind) {
List<String> ids = new ArrayList<>();
for (JsonNode member : members) {
if (name.equals(member.path("Name").asText(null))) {
ids.add(member.path("Id").asText());
}
}
if (ids.size() == 1) {
return ids.get(0);
}
throw refused(ids.isEmpty()
? "The cluster has no " + kind + " named '" + name + "'."
: "The cluster has " + ids.size() + " " + kind + "s named '" + name + "'.");
}
/** The request with {@code ClusterId} renamed to EMR's {@code JobFlowIds}. */
private ObjectNode withJobFlowIds(JsonNode request) {
ObjectNode renamed = request.deepCopy();
renamed.putArray("JobFlowIds").add(renamed.remove("ClusterId"));
return renamed;
}
private ObjectNode clusterRequest(String clusterId) {
return objectMapper.createObjectNode().put("ClusterId", clusterId);
}
private ObjectNode merged(JsonNode described, ObjectNode response) {
ObjectNode result = described.deepCopy();
result.setAll(response);
return result;
}
/** Runs in the state machine's Region, which EMR reads to find its clusters. */
private ObjectNode call(String action, JsonNode request, String region) {
Response response = RequestScopes.callAs(null, region, () -> emr.handle(action, request, region));
if (response.getStatus() >= 400) {
JsonNode error = objectMapper.valueToTree(response.getEntity());
String type = error.path("__type").asText();
String name = MODELED_ERRORS.contains(type) ? type : BASE_ERROR;
throw new AslExecutor.FailStateException("EMR." + name, error.path("message").asText());
}
return response.getEntity() instanceof ObjectNode body ? body : objectMapper.createObjectNode();
}
/** A job that ended without succeeding: the cause is its describe response, as a JSON string. */
private static AslExecutor.FailStateException failed(JsonNode described) {
return new AslExecutor.FailStateException("States.TaskFailed", described.toString());
}
/** A field the integration's request names a cluster, step or member by, as a non-blank string. */
private static String required(JsonNode request, String field) {
JsonNode value = request.path(field);
if (!value.isTextual() || value.asText().isBlank()) {
throw refused("The field " + field + " is required.");
}
return value.asText();
}
private static AslExecutor.FailStateException refused(String cause) {
return new AslExecutor.FailStateException("States.TaskFailed", cause);
}
private static AslExecutor.FailStateException unsupported(StatesIntegration integration) {
return new AslExecutor.FailStateException("States.TaskFailed", "Unsupported resource: " + integration);
}
}