Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

feat(emr): add Amazon EMR management API (Phase 1) (#1321)

Hector Ventura8b5adea915a3
diff --git a/compatibility-tests/sdk-test-java/pom.xml b/compatibility-tests/sdk-test-java/pom.xml
index 7c884febf2..8d0f5013da 100644
--- a/compatibility-tests/sdk-test-java/pom.xml
+++ b/compatibility-tests/sdk-test-java/pom.xml
@@ -176,6 +176,11 @@
<groupId>software.amazon.awssdk</groupId>
<artifactId>cloudtrail</artifactId>
</dependency>
+ <!-- EMR client -->
+ <dependency>
+ <groupId>software.amazon.awssdk</groupId>
+ <artifactId>emr</artifactId>
+ </dependency>
<!-- Kinesis client -->
<dependency>
<groupId>software.amazon.awssdk</groupId>
diff --git a/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java b/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java
index 60b478dda7..76738650a3 100644
--- a/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java
+++ b/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java
@@ -12,6 +12,7 @@ import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.core.client.config.SdkAdvancedClientOption;
import software.amazon.awssdk.services.eventbridge.EventBridgeClient;
import software.amazon.awssdk.services.servicediscovery.ServiceDiscoveryClient;
+import software.amazon.awssdk.services.emr.EmrClient;
import software.amazon.awssdk.services.iam.IamClient;
import software.amazon.awssdk.services.kinesis.KinesisAsyncClient;
import software.amazon.awssdk.services.kinesis.KinesisClient;
@@ -486,6 +487,14 @@ public final class TestFixtures {
.build();
}
+ public static EmrClient emrClient() {
+ return EmrClient.builder()
+ .endpointOverride(ENDPOINT)
+ .region(REGION)
+ .credentialsProvider(CREDENTIALS)
+ .build();
+ }
+
public static SfnClient sfnClient() {
return SfnClient.builder()
.endpointOverride(ENDPOINT)
diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/EmrTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/EmrTest.java
new file mode 100644
index 0000000000..e62a935e50
--- /dev/null
+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/EmrTest.java
@@ -0,0 +1,177 @@
+package com.floci.test;
+
+import org.junit.jupiter.api.*;
+import software.amazon.awssdk.services.emr.EmrClient;
+import software.amazon.awssdk.services.emr.model.*;
+
+import java.util.List;
+
+import static org.assertj.core.api.Assertions.*;
+
+/**
+ * EMR validated through the real AWS SDK v2 client: run job flow → describe cluster →
+ * add step → instance groups → security config → terminate. Verifies the ActionOnFailure
+ * legacy alias and the InvalidRequestException not-found shape.
+ */
+@DisplayName("EMR")
+@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
+class EmrTest {
+
+ private static EmrClient emr;
+ private static String clusterId;
+ private static String stepId;
+ private static String secConfigName;
+
+ @BeforeAll
+ static void setup() {
+ emr = TestFixtures.emrClient();
+ secConfigName = TestFixtures.uniqueName("emr-sec");
+ }
+
+ @AfterAll
+ static void cleanup() {
+ try {
+ emr.terminateJobFlows(r -> r.jobFlowIds(clusterId));
+ } catch (Exception ignored) {}
+ try {
+ emr.deleteSecurityConfiguration(r -> r.name(secConfigName));
+ } catch (Exception ignored) {}
+ emr.close();
+ }
+
+ @Test
+ @Order(1)
+ void runJobFlow() {
+ RunJobFlowResponse resp = emr.runJobFlow(r -> r
+ .name("floci-emr-sdk")
+ .releaseLabel("emr-7.5.0")
+ .instances(JobFlowInstancesConfig.builder()
+ .keepJobFlowAliveWhenNoSteps(true)
+ .instanceGroups(
+ InstanceGroupConfig.builder().name("master")
+ .instanceRole(InstanceRoleType.MASTER)
+ .instanceType("m5.xlarge").instanceCount(1).build(),
+ InstanceGroupConfig.builder().name("core")
+ .instanceRole(InstanceRoleType.CORE)
+ .instanceType("m5.xlarge").instanceCount(2).build())
+ .build())
+ .steps(StepConfig.builder()
+ .name("initial")
+ .actionOnFailure(ActionOnFailure.TERMINATE_JOB_FLOW)
+ .hadoopJarStep(HadoopJarStepConfig.builder()
+ .jar("command-runner.jar").args("echo", "hi").build())
+ .build()));
+ clusterId = resp.jobFlowId();
+ assertThat(clusterId).startsWith("j-");
+ assertThat(resp.clusterArn()).contains("cluster/" + clusterId);
+ }
+
+ @Test
+ @Order(2)
+ void describeClusterWaiting() {
+ DescribeClusterResponse resp = emr.describeCluster(r -> r.clusterId(clusterId));
+ Cluster cluster = resp.cluster();
+ assertThat(cluster.status().state()).isEqualTo(ClusterState.WAITING);
+ assertThat(cluster.releaseLabel()).isEqualTo("emr-7.5.0");
+ assertThat(cluster.instanceCollectionType()).isEqualTo(InstanceCollectionType.INSTANCE_GROUP);
+ assertThat(cluster.autoTerminate()).isFalse();
+ }
+
+ @Test
+ @Order(3)
+ void listClustersByState() {
+ ListClustersResponse resp = emr.listClusters(r -> r.clusterStates(ClusterState.WAITING));
+ assertThat(resp.clusters()).anyMatch(c -> c.id().equals(clusterId));
+ }
+
+ @Test
+ @Order(4)
+ void listInstanceGroups() {
+ ListInstanceGroupsResponse resp = emr.listInstanceGroups(r -> r.clusterId(clusterId));
+ assertThat(resp.instanceGroups()).hasSize(2);
+ assertThat(resp.instanceGroups())
+ .anyMatch(g -> g.instanceGroupType() == InstanceGroupType.CORE
+ && g.runningInstanceCount() == 2);
+ }
+
+ @Test
+ @Order(5)
+ void listInstances() {
+ ListInstancesResponse resp = emr.listInstances(r -> r.clusterId(clusterId));
+ assertThat(resp.instances()).hasSize(3); // 1 master + 2 core
+ }
+
+ @Test
+ @Order(6)
+ void addStepWithLegacyAlias() {
+ AddJobFlowStepsResponse resp = emr.addJobFlowSteps(r -> r
+ .jobFlowId(clusterId)
+ .steps(StepConfig.builder()
+ .name("added")
+ .actionOnFailure(ActionOnFailure.TERMINATE_CLUSTER)
+ .hadoopJarStep(HadoopJarStepConfig.builder()
+ .jar("command-runner.jar").mainClass("org.Main").args("run").build())
+ .build()));
+ assertThat(resp.stepIds()).hasSize(1);
+ stepId = resp.stepIds().get(0);
+ }
+
+ @Test
+ @Order(7)
+ void describeStepCompleted() {
+ DescribeStepResponse resp = emr.describeStep(r -> r.clusterId(clusterId).stepId(stepId));
+ assertThat(resp.step().name()).isEqualTo("added");
+ assertThat(resp.step().actionOnFailure()).isEqualTo(ActionOnFailure.TERMINATE_CLUSTER);
+ assertThat(resp.step().config().mainClass()).isEqualTo("org.Main");
+ assertThat(resp.step().status().state()).isEqualTo(StepState.COMPLETED);
+ }
+
+ @Test
+ @Order(8)
+ void listStepsNewestFirst() {
+ ListStepsResponse resp = emr.listSteps(r -> r.clusterId(clusterId));
+ List<StepSummary> steps = resp.steps();
+ assertThat(steps).hasSize(2);
+ assertThat(steps.get(0).name()).isEqualTo("added");
+ }
+
+ @Test
+ @Order(9)
+ void setKeepAliveTogglesAutoTerminate() {
+ emr.setKeepJobFlowAliveWhenNoSteps(r -> r.jobFlowIds(clusterId).keepJobFlowAliveWhenNoSteps(false));
+ Cluster cluster = emr.describeCluster(r -> r.clusterId(clusterId)).cluster();
+ assertThat(cluster.autoTerminate()).isTrue();
+ }
+
+ @Test
+ @Order(10)
+ void securityConfigurationRoundTrip() {
+ CreateSecurityConfigurationResponse created = emr.createSecurityConfiguration(r -> r
+ .name(secConfigName).securityConfiguration("{\"EncryptionConfiguration\":{}}"));
+ assertThat(created.name()).isEqualTo(secConfigName);
+ assertThat(created.creationDateTime()).isNotNull();
+
+ DescribeSecurityConfigurationResponse described =
+ emr.describeSecurityConfiguration(r -> r.name(secConfigName));
+ assertThat(described.securityConfiguration()).contains("EncryptionConfiguration");
+
+ emr.deleteSecurityConfiguration(r -> r.name(secConfigName));
+ }
+
+ @Test
+ @Order(11)
+ void terminate() {
+ emr.terminateJobFlows(r -> r.jobFlowIds(clusterId));
+ Cluster cluster = emr.describeCluster(r -> r.clusterId(clusterId)).cluster();
+ assertThat(cluster.status().state()).isEqualTo(ClusterState.TERMINATED);
+ assertThat(cluster.status().stateChangeReason().code())
+ .isEqualTo(ClusterStateChangeReasonCode.USER_REQUEST);
+ }
+
+ @Test
+ @Order(12)
+ void describeUnknownClusterThrowsInvalidRequest() {
+ assertThatThrownBy(() -> emr.describeCluster(r -> r.clusterId("j-DOESNOTEXIST0")))
+ .isInstanceOf(InvalidRequestException.class);
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java
index 39c5605022..e3b27ceb14 100644
--- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java
+++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java
@@ -324,6 +324,7 @@ public interface EmulatorConfig {
RdsDataServiceConfig rdsData();
EventBridgeServiceConfig eventbridge();
CloudMapServiceConfig cloudmap();
+ EmrServiceConfig emr();
SchedulerServiceConfig scheduler();
CloudWatchLogsServiceConfig cloudwatchlogs();
CloudWatchMetricsServiceConfig cloudwatchmetrics();
@@ -575,6 +576,18 @@ public interface EmulatorConfig {
int operationCompletionDelaySeconds();
}
+ interface EmrServiceConfig {
+ @WithDefault("true")
+ boolean enabled();
+
+ @WithDefault("emr-7.5.0")
+ String defaultReleaseLabel();
+
+ /** Delay before a cluster reaches WAITING; 0 = advance synchronously. */
+ @WithDefault("0")
+ int clusterStartupDelaySeconds();
+ }
+
interface SchedulerServiceConfig {
@WithDefault("true")
boolean enabled();
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/AwsJson11Controller.java b/src/main/java/io/github/hectorvent/floci/core/common/AwsJson11Controller.java
index bc117df033..ef69246682 100644
--- a/src/main/java/io/github/hectorvent/floci/core/common/AwsJson11Controller.java
+++ b/src/main/java/io/github/hectorvent/floci/core/common/AwsJson11Controller.java
@@ -25,6 +25,7 @@ import io.github.hectorvent.floci.services.cloudwatch.logs.CloudWatchLogsHandler
import io.github.hectorvent.floci.services.cognito.CognitoJsonHandler;
import io.github.hectorvent.floci.services.cloudmap.CloudMapHandler;
import io.github.hectorvent.floci.services.eventbridge.EventBridgeHandler;
+import io.github.hectorvent.floci.services.emr.EmrHandler;
import io.github.hectorvent.floci.services.kinesis.KinesisJsonHandler;
import io.github.hectorvent.floci.services.kms.KmsJsonHandler;
import io.github.hectorvent.floci.services.secretsmanager.SecretsManagerJsonHandler;
@@ -57,6 +58,7 @@ public class AwsJson11Controller {
private final SsmJsonHandler ssmJsonHandler;
private final EventBridgeHandler eventBridgeHandler;
private final CloudMapHandler cloudMapHandler;
+ private final EmrHandler emrHandler;
private final CloudWatchLogsHandler cloudWatchLogsHandler;
private final SecretsManagerJsonHandler secretsManagerJsonHandler;
private final KinesisJsonHandler kinesisJsonHandler;
@@ -88,6 +90,7 @@ public class AwsJson11Controller {
RegionResolver regionResolver,
SsmJsonHandler ssmJsonHandler, EventBridgeHandler eventBridgeHandler,
CloudMapHandler cloudMapHandler,
+ EmrHandler emrHandler,
CloudWatchLogsHandler cloudWatchLogsHandler,
SecretsManagerJsonHandler secretsManagerJsonHandler,
KinesisJsonHandler kinesisJsonHandler,
@@ -116,6 +119,7 @@ public class AwsJson11Controller {
this.ssmJsonHandler = ssmJsonHandler;
this.eventBridgeHandler = eventBridgeHandler;
this.cloudMapHandler = cloudMapHandler;
+ this.emrHandler = emrHandler;
this.cloudWatchLogsHandler = cloudWatchLogsHandler;
this.secretsManagerJsonHandler = secretsManagerJsonHandler;
this.kinesisJsonHandler = kinesisJsonHandler;
@@ -172,6 +176,7 @@ public class AwsJson11Controller {
case "ssm" -> ssmJsonHandler.handle(action, request, region);
case "events" -> eventBridgeHandler.handle(action, request, region);
case "servicediscovery" -> cloudMapHandler.handle(action, request, region);
+ case "elasticmapreduce" -> emrHandler.handle(action, request, region);
case "logs" -> cloudWatchLogsHandler.handle(action, request, region);
case "secretsmanager" -> secretsManagerJsonHandler.handle(action, request, region);
case "kinesis" -> kinesisJsonHandler.handle(action, request, region);
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java b/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java
index 84de0aa4d2..97839e6dc9 100644
--- a/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java
+++ b/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java
@@ -108,6 +108,10 @@ public class ResolvedServiceCatalog {
"cloudmap", config.storage().mode(), 5000L, null, ServiceProtocol.JSON,
protocols(ServiceProtocol.JSON),
Set.of("Route53AutoNaming_v20170314."), Set.of("servicediscovery"), Set.of(), Set.of()),
+ descriptor("elasticmapreduce", "emr", config.services().emr().enabled(), true,
+ "emr", config.storage().mode(), 5000L, null, ServiceProtocol.JSON,
+ protocols(ServiceProtocol.JSON),
+ Set.of("ElasticMapReduce."), Set.of("elasticmapreduce"), Set.of(), Set.of()),
descriptor("scheduler", "scheduler", config.services().scheduler().enabled(), true,
"scheduler", config.storage().mode(), 5000L, null, ServiceProtocol.JSON,
protocols(ServiceProtocol.JSON),
diff --git a/src/main/java/io/github/hectorvent/floci/services/emr/EmrHandler.java b/src/main/java/io/github/hectorvent/floci/services/emr/EmrHandler.java
new file mode 100644
index 0000000000..d6ab870853
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/emr/EmrHandler.java
@@ -0,0 +1,620 @@
+package io.github.hectorvent.floci.services.emr;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ArrayNode;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import io.github.hectorvent.floci.core.common.AwsErrorResponse;
+import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.core.common.AwsJson11Controller;
+import io.github.hectorvent.floci.services.emr.model.EmrCluster;
+import io.github.hectorvent.floci.services.emr.model.EmrInstanceFleet;
+import io.github.hectorvent.floci.services.emr.model.EmrInstanceGroup;
+import io.github.hectorvent.floci.services.emr.model.EmrStep;
+import io.github.hectorvent.floci.services.emr.model.SecurityConfiguration;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.inject.Inject;
+import jakarta.ws.rs.core.Response;
+import org.jboss.logging.Logger;
+
+import java.time.Instant;
+import java.util.ArrayList;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * EMR (elasticmapreduce) JSON 1.1 handler. Dispatched from {@link AwsJson11Controller}
+ * under the {@code ElasticMapReduce.} target prefix.
+ */
+@ApplicationScoped
+public class EmrHandler {
+
+ private static final Logger LOG = Logger.getLogger(EmrHandler.class);
+
+ private final EmrService service;
+ private final ObjectMapper objectMapper;
+
+ @Inject
+ public EmrHandler(EmrService service, ObjectMapper objectMapper) {
+ this.service = service;
+ this.objectMapper = objectMapper;
+ }
+
+ public Response handle(String action, JsonNode request, String region) {
+ LOG.debugv("EMR action: {0}", action);
+ try {
+ return switch (action) {
+ case "RunJobFlow" -> handleRunJobFlow(request, region);
+ case "DescribeCluster" -> handleDescribeCluster(request);
+ case "ListClusters" -> handleListClusters(request, region);
+ case "TerminateJobFlows" -> handleTerminateJobFlows(request);
+ case "SetTerminationProtection" -> handleSetTerminationProtection(request);
+ case "SetVisibleToAllUsers" -> handleSetVisibleToAllUsers(request);
+ case "SetKeepJobFlowAliveWhenNoSteps" -> handleSetKeepAlive(request);
+ case "SetUnhealthyNodeReplacement" -> handleSetUnhealthyNodeReplacement(request);
+ case "ModifyCluster" -> handleModifyCluster(request);
+ case "AddJobFlowSteps" -> handleAddJobFlowSteps(request);
+ case "DescribeStep" -> handleDescribeStep(request);
+ case "ListSteps" -> handleListSteps(request);
+ case "CancelSteps" -> handleCancelSteps(request);
+ case "AddInstanceGroups" -> handleAddInstanceGroups(request);
+ case "ListInstanceGroups" -> handleListInstanceGroups(request);
+ case "AddInstanceFleet" -> handleAddInstanceFleet(request);
+ case "ListInstanceFleets" -> handleListInstanceFleets(request);
+ case "ListInstances" -> handleListInstances(request);
+ case "CreateSecurityConfiguration" -> handleCreateSecurityConfiguration(request);
+ case "DescribeSecurityConfiguration" -> handleDescribeSecurityConfiguration(request);
+ case "DeleteSecurityConfiguration" -> handleDeleteSecurityConfiguration(request);
+ case "ListSecurityConfigurations" -> handleListSecurityConfigurations();
+ case "AddTags" -> handleAddTags(request);
+ case "RemoveTags" -> handleRemoveTags(request);
+ default -> Response.status(400)
+ .entity(new AwsErrorResponse("InvalidRequestException",
+ "Operation " + action + " is not supported."))
+ .build();
+ };
+ } catch (AwsException e) {
+ return Response.status(e.getHttpStatus())
+ .entity(new AwsErrorResponse(e.jsonType(), e.getMessage()))
+ .build();
+ } catch (Exception e) {
+ LOG.errorv("EMR error processing action {0}: {1}", action, e.getMessage());
+ return Response.status(500)
+ .entity(new AwsErrorResponse("InternalServerException", e.getMessage()))
+ .build();
+ }
+ }
+
+ // ──────────────────────────── Cluster lifecycle ────────────────────────────
+
+ private Response handleRunJobFlow(JsonNode request, String region) {
+ EmrCluster cluster = new EmrCluster();
+ cluster.setName(text(request, "Name"));
+ cluster.setReleaseLabel(text(request, "ReleaseLabel"));
+ cluster.setLogUri(text(request, "LogUri"));
+ cluster.setServiceRole(text(request, "ServiceRole"));
+ cluster.setJobFlowRole(text(request, "JobFlowRole"));
+ cluster.setAutoScalingRole(text(request, "AutoScalingRole"));
+ cluster.setScaleDownBehavior(text(request, "ScaleDownBehavior"));
+ cluster.setSecurityConfiguration(text(request, "SecurityConfiguration"));
+ cluster.setCustomAmiId(text(request, "CustomAmiId"));
+ cluster.setVisibleToAllUsers(request.path("VisibleToAllUsers").asBoolean(true));
+ cluster.setStepConcurrencyLevel(request.path("StepConcurrencyLevel").asInt(1));
+ cluster.setEbsRootVolumeSize(request.path("EbsRootVolumeSize").asInt(0));
+ cluster.setApplications(rawArray(request.path("Applications")));
+ cluster.setConfigurations(rawArray(request.path("Configurations")));
+ cluster.setTags(parseTags(request.path("Tags")));
+
+ JsonNode instances = request.path("Instances");
+ cluster.setKeepJobFlowAliveWhenNoSteps(instances.path("KeepJobFlowAliveWhenNoSteps").asBoolean(false));
+ cluster.setTerminationProtected(instances.path("TerminationProtected").asBoolean(false));
+ cluster.setUnhealthyNodeReplacement(instances.path("UnhealthyNodeReplacement").asBoolean(false));
+ cluster.setEc2Attributes(buildEc2Attributes(instances));
+ cluster.setInstanceGroups(parseInstanceGroups(instances.path("InstanceGroups")));
+ cluster.setInstanceFleets(parseInstanceFleets(instances.path("InstanceFleets")));
+ cluster.setSteps(parseSteps(request.path("Steps")));
+
+ EmrCluster created = service.runJobFlow(cluster, region);
+ ObjectNode response = objectMapper.createObjectNode();
+ response.put("JobFlowId", created.getId());
+ response.put("ClusterArn", created.getClusterArn());
+ return Response.ok(response).build();
+ }
+
+ private Response handleDescribeCluster(JsonNode request) {
+ EmrCluster cluster = service.describeCluster(text(request, "ClusterId"));
+ ObjectNode response = objectMapper.createObjectNode();
+ response.set("Cluster", clusterNode(cluster));
+ return Response.ok(response).build();
+ }
+
+ private Response handleListClusters(JsonNode request, String region) {
+ List<String> states = stringList(request.path("ClusterStates"));
+ ObjectNode response = objectMapper.createObjectNode();
+ ArrayNode arr = response.putArray("Clusters");
+ for (EmrCluster c : service.listClusters(region, states)) {
+ arr.add(clusterSummaryNode(c));
+ }
+ return Response.ok(response).build();
+ }
+
+ private Response handleTerminateJobFlows(JsonNode request) {
+ service.terminateJobFlows(stringList(request.path("JobFlowIds")));
+ return Response.ok(objectMapper.createObjectNode()).build();
+ }
+
+ private Response handleSetTerminationProtection(JsonNode request) {
+ service.setTerminationProtection(stringList(request.path("JobFlowIds")),
+ request.path("TerminationProtected").asBoolean(false));
+ return Response.ok(objectMapper.createObjectNode()).build();
+ }
+
+ private Response handleSetVisibleToAllUsers(JsonNode request) {
+ service.setVisibleToAllUsers(stringList(request.path("JobFlowIds")),
+ request.path("VisibleToAllUsers").asBoolean(true));
+ return Response.ok(objectMapper.createObjectNode()).build();
+ }
+
+ private Response handleSetKeepAlive(JsonNode request) {
+ service.setKeepJobFlowAliveWhenNoSteps(stringList(request.path("JobFlowIds")),
+ request.path("KeepJobFlowAliveWhenNoSteps").asBoolean(false));
+ return Response.ok(objectMapper.createObjectNode()).build();
+ }
+
+ private Response handleSetUnhealthyNodeReplacement(JsonNode request) {
+ service.setUnhealthyNodeReplacement(stringList(request.path("JobFlowIds")),
+ request.path("UnhealthyNodeReplacement").asBoolean(false));
+ return Response.ok(objectMapper.createObjectNode()).build();
+ }
+
+ private Response handleModifyCluster(JsonNode request) {
+ Integer level = request.has("StepConcurrencyLevel") ? request.path("StepConcurrencyLevel").asInt() : null;
+ int result = service.modifyCluster(text(request, "ClusterId"), level);
+ return Response.ok(objectMapper.createObjectNode().put("StepConcurrencyLevel", result)).build();
+ }
+
+ // ──────────────────────────── Steps ────────────────────────────
+
+ private Response handleAddJobFlowSteps(JsonNode request) {
+ List<String> ids = service.addJobFlowSteps(text(request, "JobFlowId"), parseSteps(request.path("Steps")));
+ ObjectNode response = objectMapper.createObjectNode();
+ ArrayNode arr = response.putArray("StepIds");
+ ids.forEach(arr::add);
+ return Response.ok(response).build();
+ }
+
+ private Response handleDescribeStep(JsonNode request) {
+ EmrStep step = service.describeStep(text(request, "ClusterId"), text(request, "StepId"));
+ ObjectNode response = objectMapper.createObjectNode();
+ response.set("Step", stepNode(step));
+ return Response.ok(response).build();
+ }
+
+ private Response handleListSteps(JsonNode request) {
+ List<EmrStep> steps = service.listSteps(text(request, "ClusterId"),
+ stringList(request.path("StepStates")), stringList(request.path("StepIds")));
+ ObjectNode response = objectMapper.createObjectNode();
+ ArrayNode arr = response.putArray("Steps");
+ for (EmrStep step : steps) {
+ arr.add(stepNode(step));
+ }
+ return Response.ok(response).build();
+ }
+
+ private Response handleCancelSteps(JsonNode request) {
+ List<EmrService.CancelStepInfo> infos = service.cancelSteps(
+ text(request, "ClusterId"), stringList(request.path("StepIds")));
+ ObjectNode response = objectMapper.createObjectNode();
+ ArrayNode arr = response.putArray("CancelStepsInfoList");
+ for (EmrService.CancelStepInfo info : infos) {
+ ObjectNode node = objectMapper.createObjectNode();
+ node.put("StepId", info.stepId());
+ node.put("Status", info.status());
+ if (info.reason() != null) {
+ node.put("Reason", info.reason());
+ }
+ arr.add(node);
+ }
+ return Response.ok(response).build();
+ }
+
+ // ──────────────────────────── Instance groups / fleets ────────────────────────────
+
+ private Response handleAddInstanceGroups(JsonNode request) {
+ List<String> ids = service.addInstanceGroups(text(request, "JobFlowId"),
+ parseInstanceGroups(request.path("InstanceGroups")));
+ ObjectNode response = objectMapper.createObjectNode();
+ response.put("JobFlowId", text(request, "JobFlowId"));
+ ArrayNode arr = response.putArray("InstanceGroupIds");
+ ids.forEach(arr::add);
+ return Response.ok(response).build();
+ }
+
+ private Response handleListInstanceGroups(JsonNode request) {
+ List<EmrInstanceGroup> groups = service.listInstanceGroups(text(request, "ClusterId"));
+ ObjectNode response = objectMapper.createObjectNode();
+ ArrayNode arr = response.putArray("InstanceGroups");
+ for (EmrInstanceGroup g : groups) {
+ arr.add(instanceGroupNode(g));
+ }
+ return Response.ok(response).build();
+ }
+
+ private Response handleAddInstanceFleet(JsonNode request) {
+ EmrInstanceFleet fleet = parseInstanceFleet(request.path("InstanceFleet"));
+ String id = service.addInstanceFleet(text(request, "ClusterId"), fleet);
+ ObjectNode response = objectMapper.createObjectNode();
+ response.put("ClusterId", text(request, "ClusterId"));
+ response.put("InstanceFleetId", id);
+ return Response.ok(response).build();
+ }
+
+ private Response handleListInstanceFleets(JsonNode request) {
+ List<EmrInstanceFleet> fleets = service.listInstanceFleets(text(request, "ClusterId"));
+ ObjectNode response = objectMapper.createObjectNode();
+ ArrayNode arr = response.putArray("InstanceFleets");
+ for (EmrInstanceFleet f : fleets) {
+ arr.add(instanceFleetNode(f));
+ }
+ return Response.ok(response).build();
+ }
+
+ private Response handleListInstances(JsonNode request) {
+ EmrCluster cluster = service.getClusterForInstances(text(request, "ClusterId"));
+ ObjectNode response = objectMapper.createObjectNode();
+ ArrayNode arr = response.putArray("Instances");
+ int n = 1;
+ for (EmrInstanceGroup group : cluster.getInstanceGroups()) {
+ for (int i = 0; i < Math.max(1, group.getRunningInstanceCount()); i++) {
+ arr.add(syntheticInstanceNode(cluster, group, n++));
+ }
+ }
+ return Response.ok(response).build();
+ }
+
+ // ──────────────────────────── Security configurations ────────────────────────────
+
+ private Response handleCreateSecurityConfiguration(JsonNode request) {
+ SecurityConfiguration sc = service.createSecurityConfiguration(
+ text(request, "Name"), text(request, "SecurityConfiguration"));
+ ObjectNode response = objectMapper.createObjectNode();
+ response.put("Name", sc.getName());
+ response.put("CreationDateTime", epoch(sc.getCreationDateTime()));
+ return Response.ok(response).build();
+ }
+
+ private Response handleDescribeSecurityConfiguration(JsonNode request) {
+ SecurityConfiguration sc = service.describeSecurityConfiguration(text(request, "Name"));
+ ObjectNode response = objectMapper.createObjectNode();
+ response.put("Name", sc.getName());
+ response.put("SecurityConfiguration", sc.getSecurityConfiguration());
+ response.put("CreationDateTime", epoch(sc.getCreationDateTime()));
+ return Response.ok(response).build();
+ }
+
+ private Response handleDeleteSecurityConfiguration(JsonNode request) {
+ service.deleteSecurityConfiguration(text(request, "Name"));
+ return Response.ok(objectMapper.createObjectNode()).build();
+ }
+
+ private Response handleListSecurityConfigurations() {
+ ObjectNode response = objectMapper.createObjectNode();
+ ArrayNode arr = response.putArray("SecurityConfigurations");
+ for (SecurityConfiguration sc : service.listSecurityConfigurations()) {
+ ObjectNode node = objectMapper.createObjectNode();
+ node.put("Name", sc.getName());
+ node.put("CreationDateTime", epoch(sc.getCreationDateTime()));
+ arr.add(node);
+ }
+ return Response.ok(response).build();
+ }
+
+ // ──────────────────────────── Tags ────────────────────────────
+
+ private Response handleAddTags(JsonNode request) {
+ service.addTags(text(request, "ResourceId"), parseTags(request.path("Tags")));
+ return Response.ok(objectMapper.createObjectNode()).build();
+ }
+
+ private Response handleRemoveTags(JsonNode request) {
+ service.removeTags(text(request, "ResourceId"), stringList(request.path("TagKeys")));
+ return Response.ok(objectMapper.createObjectNode()).build();
+ }
+
+ // ──────────────────────────── Builders ────────────────────────────
+
+ private ObjectNode clusterNode(EmrCluster c) {
+ ObjectNode node = objectMapper.createObjectNode();
+ node.put("Id", c.getId());
+ node.put("Name", c.getName());
+ node.set("Status", clusterStatusNode(c));
+ setRawJson(node, "Ec2InstanceAttributes", c.getEc2Attributes());
+ if (c.getInstanceCollectionType() != null) {
+ node.put("InstanceCollectionType", c.getInstanceCollectionType());
+ }
+ if (c.getLogUri() != null) {
+ node.put("LogUri", c.getLogUri());
+ }
+ if (c.getReleaseLabel() != null) {
+ node.put("ReleaseLabel", c.getReleaseLabel());
+ }
+ node.put("AutoTerminate", c.isAutoTerminate());
+ node.put("TerminationProtected", c.isTerminationProtected());
+ node.put("UnhealthyNodeReplacement", c.isUnhealthyNodeReplacement());
+ node.put("VisibleToAllUsers", c.isVisibleToAllUsers());
+ setRawJson(node, "Applications", c.getApplications());
+ setRawJson(node, "Configurations", c.getConfigurations());
+ node.set("Tags", tagArray(c.getTags()));
+ if (c.getServiceRole() != null) {
+ node.put("ServiceRole", c.getServiceRole());
+ }
+ node.put("NormalizedInstanceHours", c.getNormalizedInstanceHours());
+ if (c.getMasterPublicDnsName() != null) {
+ node.put("MasterPublicDnsName", c.getMasterPublicDnsName());
+ }
+ if (c.getAutoScalingRole() != null) {
+ node.put("AutoScalingRole", c.getAutoScalingRole());
+ }
+ if (c.getScaleDownBehavior() != null) {
+ node.put("ScaleDownBehavior", c.getScaleDownBehavior());
+ }
+ if (c.getCustomAmiId() != null) {
+ node.put("CustomAmiId", c.getCustomAmiId());
+ }
+ node.put("EbsRootVolumeSize", c.getEbsRootVolumeSize());
+ node.put("StepConcurrencyLevel", c.getStepConcurrencyLevel());
+ node.put("ClusterArn", c.getClusterArn());
+ return node;
+ }
+
+ private ObjectNode clusterSummaryNode(EmrCluster c) {
+ ObjectNode node = objectMapper.createObjectNode();
+ node.put("Id", c.getId());
+ node.put("Name", c.getName());
+ node.set("Status", clusterStatusNode(c));
+ node.put("NormalizedInstanceHours", c.getNormalizedInstanceHours());
+ node.put("ClusterArn", c.getClusterArn());
+ return node;
+ }
+
+ private ObjectNode clusterStatusNode(EmrCluster c) {
+ ObjectNode status = objectMapper.createObjectNode();
+ status.put("State", c.getState());
+ ObjectNode reason = status.putObject("StateChangeReason");
+ if (c.getStateChangeReasonCode() != null) {
+ reason.put("Code", c.getStateChangeReasonCode());
+ }
+ if (c.getStateChangeMessage() != null) {
+ reason.put("Message", c.getStateChangeMessage());
+ }
+ ObjectNode timeline = status.putObject("Timeline");
+ putEpoch(timeline, "CreationDateTime", c.getCreationDateTime());
+ putEpoch(timeline, "ReadyDateTime", c.getReadyDateTime());
+ putEpoch(timeline, "EndDateTime", c.getEndDateTime());
+ return status;
+ }
+
+ private ObjectNode stepNode(EmrStep step) {
+ ObjectNode node = objectMapper.createObjectNode();
+ node.put("Id", step.getId());
+ node.put("Name", step.getName());
+ ObjectNode config = node.putObject("Config");
+ if (step.getJar() != null) {
+ config.put("Jar", step.getJar());
+ }
+ if (step.getMainClass() != null) {
+ config.put("MainClass", step.getMainClass());
+ }
+ ArrayNode args = config.putArray("Args");
+ step.getArgs().forEach(args::add);
+ ObjectNode props = config.putObject("Properties");
+ step.getProperties().forEach(props::put);
+ node.put("ActionOnFailure", step.getActionOnFailure());
+ ObjectNode status = node.putObject("Status");
+ status.put("State", step.getState());
+ if (step.getStateChangeReason() != null) {
+ status.putObject("StateChangeReason").put("Message", step.getStateChangeReason());
+ }
+ ObjectNode timeline = status.putObject("Timeline");
+ putEpoch(timeline, "CreationDateTime", step.getCreationDateTime());
+ putEpoch(timeline, "StartDateTime", step.getStartDateTime());
+ putEpoch(timeline, "EndDateTime", step.getEndDateTime());
+ return node;
+ }
+
+ private ObjectNode instanceGroupNode(EmrInstanceGroup g) {
+ ObjectNode node = objectMapper.createObjectNode();
+ node.put("Id", g.getId());
+ if (g.getName() != null) {
+ node.put("Name", g.getName());
+ }
+ node.put("InstanceGroupType", g.getInstanceGroupType());
+ node.put("InstanceType", g.getInstanceType());
+ if (g.getMarket() != null) {
+ node.put("Market", g.getMarket());
+ }
+ if (g.getBidPrice() != null) {
+ node.put("BidPrice", g.getBidPrice());
+ }
+ node.put("RequestedInstanceCount", g.getRequestedInstanceCount());
+ node.put("RunningInstanceCount", g.getRunningInstanceCount());
+ node.putObject("Status").put("State", g.getState());
+ return node;
+ }
+
+ private ObjectNode instanceFleetNode(EmrInstanceFleet f) {
+ ObjectNode node = objectMapper.createObjectNode();
+ node.put("Id", f.getId());
+ if (f.getName() != null) {
+ node.put("Name", f.getName());
+ }
+ node.put("InstanceFleetType", f.getInstanceFleetType());
+ node.put("TargetOnDemandCapacity", f.getTargetOnDemandCapacity());
+ node.put("TargetSpotCapacity", f.getTargetSpotCapacity());
+ node.put("ProvisionedOnDemandCapacity", f.getProvisionedOnDemandCapacity());
+ node.put("ProvisionedSpotCapacity", f.getProvisionedSpotCapacity());
+ node.putObject("Status").put("State", f.getState());
+ return node;
+ }
+
+ private ObjectNode syntheticInstanceNode(EmrCluster cluster, EmrInstanceGroup group, int index) {
+ ObjectNode node = objectMapper.createObjectNode();
+ node.put("Id", "ci-" + index + cluster.getId());
+ node.put("Ec2InstanceId", "i-" + String.format("%017d", index));
+ node.put("PublicDnsName", "ec2-203-0-113-" + index + ".compute-1.amazonaws.com");
+ node.put("PrivateDnsName", "ip-10-0-0-" + index + ".ec2.internal");
+ node.put("PrivateIpAddress", "10.0.0." + index);
+ node.put("InstanceGroupId", group.getId());
+ if (group.getMarket() != null) {
+ node.put("Market", group.getMarket());
+ }
+ node.put("InstanceType", group.getInstanceType());
+ node.putObject("Status").put("State", "RUNNING");
+ return node;
+ }
+
+ private ArrayNode tagArray(Map<String, String> tags) {
+ ArrayNode out = objectMapper.createArrayNode();
+ tags.forEach((k, v) -> {
+ ObjectNode tag = objectMapper.createObjectNode();
+ tag.put("Key", k);
+ tag.put("Value", v);
+ out.add(tag);
+ });
+ return out;
+ }
+
+ // ──────────────────────────── Parsing ────────────────────────────
+
+ private List<EmrStep> parseSteps(JsonNode stepsNode) {
+ List<EmrStep> steps = new ArrayList<>();
+ if (!stepsNode.isArray()) {
+ return steps;
+ }
+ for (JsonNode s : stepsNode) {
+ EmrStep step = new EmrStep();
+ step.setName(s.path("Name").asText(null));
+ step.setActionOnFailure(s.path("ActionOnFailure").asText(null));
+ step.setExecutionRoleArn(s.path("ExecutionRoleArn").asText(null));
+ JsonNode jar = s.path("HadoopJarStep");
+ step.setJar(jar.path("Jar").asText(null));
+ step.setMainClass(jar.path("MainClass").asText(null));
+ step.setArgs(stringList(jar.path("Args")));
+ JsonNode props = jar.path("Properties");
+ if (props.isArray()) {
+ Map<String, String> map = new LinkedHashMap<>();
+ props.forEach(p -> map.put(p.path("Key").asText(), p.path("Value").asText()));
+ step.setProperties(map);
+ }
+ steps.add(step);
+ }
+ return steps;
+ }
+
+ private List<EmrInstanceGroup> parseInstanceGroups(JsonNode groupsNode) {
+ List<EmrInstanceGroup> groups = new ArrayList<>();
+ if (!groupsNode.isArray()) {
+ return groups;
+ }
+ for (JsonNode g : groupsNode) {
+ EmrInstanceGroup group = new EmrInstanceGroup();
+ group.setName(g.path("Name").asText(null));
+ group.setInstanceGroupType(g.path("InstanceRole").asText(null));
+ group.setInstanceType(g.path("InstanceType").asText(null));
+ group.setMarket(g.path("Market").asText(null));
+ group.setBidPrice(g.path("BidPrice").asText(null));
+ group.setRequestedInstanceCount(g.path("InstanceCount").asInt(0));
+ groups.add(group);
+ }
+ return groups;
+ }
+
+ private List<EmrInstanceFleet> parseInstanceFleets(JsonNode fleetsNode) {
+ List<EmrInstanceFleet> fleets = new ArrayList<>();
+ if (!fleetsNode.isArray()) {
+ return fleets;
+ }
+ for (JsonNode f : fleetsNode) {
+ fleets.add(parseInstanceFleet(f));
+ }
+ return fleets;
+ }
+
+ private EmrInstanceFleet parseInstanceFleet(JsonNode f) {
+ EmrInstanceFleet fleet = new EmrInstanceFleet();
+ fleet.setName(f.path("Name").asText(null));
+ fleet.setInstanceFleetType(f.path("InstanceFleetType").asText(null));
+ fleet.setTargetOnDemandCapacity(f.path("TargetOnDemandCapacity").asInt(0));
+ fleet.setTargetSpotCapacity(f.path("TargetSpotCapacity").asInt(0));
+ return fleet;
+ }
+
+ private String buildEc2Attributes(JsonNode instances) {
+ ObjectNode ec2 = objectMapper.createObjectNode();
+ copyText(instances, "Ec2KeyName", ec2, "Ec2KeyName");
+ copyText(instances, "Ec2SubnetId", ec2, "Ec2SubnetId");
+ copyText(instances, "EmrManagedMasterSecurityGroup", ec2, "EmrManagedMasterSecurityGroup");
+ copyText(instances, "EmrManagedSlaveSecurityGroup", ec2, "EmrManagedSlaveSecurityGroup");
+ copyText(instances, "ServiceAccessSecurityGroup", ec2, "ServiceAccessSecurityGroup");
+ return ec2.isEmpty() ? null : ec2.toString();
+ }
+
+ private void copyText(JsonNode src, String srcField, ObjectNode dst, String dstField) {
+ JsonNode v = src.path(srcField);
+ if (!v.isMissingNode() && !v.isNull() && !v.asText().isEmpty()) {
+ dst.put(dstField, v.asText());
+ }
+ }
+
+ private Map<String, String> parseTags(JsonNode tagsNode) {
+ Map<String, String> tags = new LinkedHashMap<>();
+ if (tagsNode.isArray()) {
+ for (JsonNode tag : tagsNode) {
+ String key = tag.path("Key").asText(null);
+ if (key != null) {
+ tags.put(key, tag.path("Value").asText(null));
+ }
+ }
+ }
+ return tags;
+ }
+
+ private List<String> stringList(JsonNode node) {
+ List<String> values = new ArrayList<>();
+ if (node != null && node.isArray()) {
+ node.forEach(v -> values.add(v.asText()));
+ }
+ return values;
+ }
+
+ private String text(JsonNode request, String field) {
+ JsonNode node = request.path(field);
+ return node.isMissingNode() || node.isNull() ? null : node.asText(null);
+ }
+
+ private String rawArray(JsonNode node) {
+ return (node != null && node.isArray() && !node.isEmpty()) ? node.toString() : null;
+ }
+
+ private void setRawJson(ObjectNode target, String field, String rawJson) {
+ if (rawJson == null) {
+ return;
+ }
+ try {
+ target.set(field, objectMapper.readTree(rawJson));
+ } catch (Exception e) {
+ LOG.warnv("Failed to parse stored {0} JSON; field omitted. Value: {1}", field, rawJson);
+ }
+ }
+
+ private long epoch(Instant instant) {
+ return instant == null ? 0L : instant.getEpochSecond();
+ }
+
+ private void putEpoch(ObjectNode node, String field, Instant instant) {
+ if (instant != null) {
+ node.put(field, instant.getEpochSecond());
+ }
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/emr/EmrService.java b/src/main/java/io/github/hectorvent/floci/services/emr/EmrService.java
new file mode 100644
index 0000000000..58fd0c5c48
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/emr/EmrService.java
@@ -0,0 +1,358 @@
+package io.github.hectorvent.floci.services.emr;
+
+import com.fasterxml.jackson.core.type.TypeReference;
+import io.github.hectorvent.floci.config.EmulatorConfig;
+import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.core.common.RegionResolver;
+import io.github.hectorvent.floci.core.storage.StorageBackend;
+import io.github.hectorvent.floci.core.storage.StorageFactory;
+import io.github.hectorvent.floci.services.emr.model.EmrCluster;
+import io.github.hectorvent.floci.services.emr.model.EmrInstanceFleet;
+import io.github.hectorvent.floci.services.emr.model.EmrInstanceGroup;
+import io.github.hectorvent.floci.services.emr.model.EmrStep;
+import io.github.hectorvent.floci.services.emr.model.SecurityConfiguration;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.inject.Inject;
+
+import java.security.SecureRandom;
+import java.time.Instant;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * EMR management-plane business logic. Cluster and step lifecycles are simulated
+ * through immediate state transitions (no Hadoop runs): clusters land in WAITING and
+ * initial steps in COMPLETED. The {@code clusterStartupDelaySeconds} config exists for
+ * future deferred transitions; Phase 1 advances synchronously for deterministic tests.
+ */
+@ApplicationScoped
+public class EmrService {
+
+ private static final String UPPER_ALNUM = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
+ private static final SecureRandom RANDOM = new SecureRandom();
+
+ private final StorageBackend<String, EmrCluster> clusterStore;
+ private final StorageBackend<String, SecurityConfiguration> secConfigStore;
+ private final RegionResolver regionResolver;
+ private final String defaultReleaseLabel;
+
+ @Inject
+ public EmrService(StorageFactory storageFactory, EmulatorConfig config, RegionResolver regionResolver) {
+ this.clusterStore = storageFactory.create("emr", "emr-clusters.json",
+ new TypeReference<Map<String, EmrCluster>>() {});
+ this.secConfigStore = storageFactory.create("emr", "emr-security-configs.json",
+ new TypeReference<Map<String, SecurityConfiguration>>() {});
+ this.regionResolver = regionResolver;
+ this.defaultReleaseLabel = config.services().emr().defaultReleaseLabel();
+ }
+
+ // ──────────────────────────── Cluster lifecycle ────────────────────────────
+
+ public EmrCluster runJobFlow(EmrCluster cluster, String region) {
+ if (cluster.getName() == null || cluster.getName().isBlank()) {
+ throw new AwsException("InternalServerError", "Name is required.", 500);
+ }
+ String id = "j-" + randomId(13);
+ cluster.setId(id);
+ cluster.setRegion(region);
+ cluster.setClusterArn(regionResolver.buildArn("elasticmapreduce", region, "cluster/" + id));
+ if (cluster.getReleaseLabel() == null) {
+ cluster.setReleaseLabel(defaultReleaseLabel);
+ }
+ cluster.setInstanceCollectionType(cluster.getInstanceFleets().isEmpty()
+ ? "INSTANCE_GROUP" : "INSTANCE_FLEET");
+ cluster.setAutoTerminate(!cluster.isKeepJobFlowAliveWhenNoSteps());
+ cluster.setMasterPublicDnsName("ip-10-0-0-1." + region + ".compute.internal");
+ cluster.setCreationDateTime(Instant.now());
+ for (EmrInstanceGroup g : cluster.getInstanceGroups()) {
+ g.setId("ig-" + randomId(13));
+ g.setRunningInstanceCount(g.getRequestedInstanceCount());
+ g.setState("RUNNING");
+ }
+ for (EmrInstanceFleet f : cluster.getInstanceFleets()) {
+ f.setId("if-" + randomId(13));
+ f.setProvisionedOnDemandCapacity(f.getTargetOnDemandCapacity());
+ f.setProvisionedSpotCapacity(f.getTargetSpotCapacity());
+ f.setState("RUNNING");
+ }
+ for (EmrStep step : cluster.getSteps()) {
+ initStep(step);
+ completeStep(step);
+ }
+ advanceToWaiting(cluster);
+ clusterStore.put(id, cluster);
+ return cluster;
+ }
+
+ public EmrCluster describeCluster(String id) {
+ return requireCluster(id);
+ }
+
+ public List<EmrCluster> listClusters(String region, List<String> states) {
+ List<EmrCluster> result = new ArrayList<>();
+ for (EmrCluster c : clusterStore.scan(k -> true)) {
+ if (!region.equals(c.getRegion())) {
+ continue;
+ }
+ if (states != null && !states.isEmpty() && !states.contains(c.getState())) {
+ continue;
+ }
+ result.add(c);
+ }
+ return result;
+ }
+
+ public void terminateJobFlows(List<String> ids) {
+ for (String id : ids) {
+ EmrCluster cluster = clusterStore.get(id).orElse(null);
+ if (cluster == null) {
+ continue;
+ }
+ if (cluster.isTerminationProtected()) {
+ throw new AwsException("InternalServerError",
+ "Cluster " + id + " is protected from termination.", 500);
+ }
+ if ("TERMINATED".equals(cluster.getState())) {
+ continue;
+ }
+ cluster.setState("TERMINATED");
+ cluster.setStateChangeReasonCode("USER_REQUEST");
+ cluster.setStateChangeMessage("Terminated by user request");
+ cluster.setEndDateTime(Instant.now());
+ clusterStore.put(id, cluster);
+ }
+ }
+
+ public void setTerminationProtection(List<String> ids, boolean value) {
+ mutateClusters(ids, c -> c.setTerminationProtected(value));
+ }
+
+ public void setVisibleToAllUsers(List<String> ids, boolean value) {
+ mutateClusters(ids, c -> c.setVisibleToAllUsers(value));
+ }
+
+ public void setKeepJobFlowAliveWhenNoSteps(List<String> ids, boolean value) {
+ mutateClusters(ids, c -> {
+ c.setKeepJobFlowAliveWhenNoSteps(value);
+ c.setAutoTerminate(!value);
+ });
+ }
+
+ public void setUnhealthyNodeReplacement(List<String> ids, boolean value) {
+ mutateClusters(ids, c -> c.setUnhealthyNodeReplacement(value));
+ }
+
+ public int modifyCluster(String id, Integer stepConcurrencyLevel) {
+ EmrCluster cluster = requireCluster(id);
+ if (stepConcurrencyLevel != null) {
+ cluster.setStepConcurrencyLevel(stepConcurrencyLevel);
+ clusterStore.put(id, cluster);
+ }
+ return cluster.getStepConcurrencyLevel();
+ }
+
+ // ──────────────────────────── Steps ────────────────────────────
+
+ public List<String> addJobFlowSteps(String clusterId, List<EmrStep> steps) {
+ EmrCluster cluster = clusterStore.get(clusterId).orElseThrow(() -> new AwsException(
+ "InternalServerError", "Cluster " + clusterId + " does not exist.", 500));
+ List<String> ids = new ArrayList<>();
+ for (EmrStep step : steps) {
+ initStep(step);
+ completeStep(step);
+ cluster.getSteps().add(step);
+ ids.add(step.getId());
+ }
+ clusterStore.put(clusterId, cluster);
+ return ids;
+ }
+
+ public EmrStep describeStep(String clusterId, String stepId) {
+ EmrCluster cluster = requireCluster(clusterId);
+ return cluster.getSteps().stream()
+ .filter(s -> s.getId().equals(stepId))
+ .findFirst()
+ .orElseThrow(() -> new AwsException("InvalidRequestException",
+ "Step " + stepId + " does not exist.", 400));
+ }
+
+ public List<EmrStep> listSteps(String clusterId, List<String> states, List<String> stepIds) {
+ EmrCluster cluster = requireCluster(clusterId);
+ List<EmrStep> result = new ArrayList<>();
+ // AWS returns steps in reverse submission order (newest first).
+ List<EmrStep> steps = cluster.getSteps();
+ for (int i = steps.size() - 1; i >= 0; i--) {
+ EmrStep step = steps.get(i);
+ if (states != null && !states.isEmpty() && !states.contains(step.getState())) {
+ continue;
+ }
+ if (stepIds != null && !stepIds.isEmpty() && !stepIds.contains(step.getId())) {
+ continue;
+ }
+ result.add(step);
+ }
+ return result;
+ }
+
+ public record CancelStepInfo(String stepId, String status, String reason) {}
+
+ public List<CancelStepInfo> cancelSteps(String clusterId, List<String> stepIds) {
+ EmrCluster cluster = requireCluster(clusterId);
+ List<CancelStepInfo> result = new ArrayList<>();
+ for (String stepId : stepIds) {
+ EmrStep step = cluster.getSteps().stream()
+ .filter(s -> s.getId().equals(stepId)).findFirst().orElse(null);
+ if (step == null) {
+ result.add(new CancelStepInfo(stepId, "FAILED", "Step does not exist."));
+ } else if ("PENDING".equals(step.getState())) {
+ step.setState("CANCELLED");
+ step.setEndDateTime(Instant.now());
+ result.add(new CancelStepInfo(stepId, "SUBMITTED", null));
+ } else {
+ result.add(new CancelStepInfo(stepId, "FAILED",
+ "Step is not in a cancellable state: " + step.getState()));
+ }
+ }
+ clusterStore.put(clusterId, cluster);
+ return result;
+ }
+
+ // ──────────────────────────── Instance groups / fleets ────────────────────────────
+
+ public List<String> addInstanceGroups(String clusterId, List<EmrInstanceGroup> groups) {
+ EmrCluster cluster = requireCluster(clusterId);
+ List<String> ids = new ArrayList<>();
+ for (EmrInstanceGroup group : groups) {
+ group.setId("ig-" + randomId(13));
+ group.setRunningInstanceCount(group.getRequestedInstanceCount());
+ group.setState("RUNNING");
+ cluster.getInstanceGroups().add(group);
+ ids.add(group.getId());
+ }
+ clusterStore.put(clusterId, cluster);
+ return ids;
+ }
+
+ public List<EmrInstanceGroup> listInstanceGroups(String clusterId) {
+ return requireCluster(clusterId).getInstanceGroups();
+ }
+
+ public String addInstanceFleet(String clusterId, EmrInstanceFleet fleet) {
+ EmrCluster cluster = requireCluster(clusterId);
+ fleet.setId("if-" + randomId(13));
+ fleet.setProvisionedOnDemandCapacity(fleet.getTargetOnDemandCapacity());
+ fleet.setProvisionedSpotCapacity(fleet.getTargetSpotCapacity());
+ fleet.setState("RUNNING");
+ cluster.getInstanceFleets().add(fleet);
+ clusterStore.put(clusterId, cluster);
+ return fleet.getId();
+ }
+
+ public List<EmrInstanceFleet> listInstanceFleets(String clusterId) {
+ return requireCluster(clusterId).getInstanceFleets();
+ }
+
+ public EmrCluster getClusterForInstances(String clusterId) {
+ return requireCluster(clusterId);
+ }
+
+ // ──────────────────────────── Security configurations ────────────────────────────
+
+ public SecurityConfiguration createSecurityConfiguration(String name, String json) {
+ if (name == null || name.isBlank()) {
+ throw new AwsException("InvalidRequestException", "Name is required.", 400);
+ }
+ if (secConfigStore.get(name).isPresent()) {
+ throw new AwsException("InvalidRequestException",
+ "Security configuration already exists: " + name, 400);
+ }
+ SecurityConfiguration sc = new SecurityConfiguration();
+ sc.setName(name);
+ sc.setSecurityConfiguration(json);
+ sc.setCreationDateTime(Instant.now());
+ secConfigStore.put(name, sc);
+ return sc;
+ }
+
+ public SecurityConfiguration describeSecurityConfiguration(String name) {
+ return secConfigStore.get(name).orElseThrow(() -> new AwsException(
+ "InvalidRequestException", "Security configuration does not exist: " + name, 400));
+ }
+
+ public void deleteSecurityConfiguration(String name) {
+ if (secConfigStore.get(name).isEmpty()) {
+ throw new AwsException("InvalidRequestException",
+ "Security configuration does not exist: " + name, 400);
+ }
+ secConfigStore.delete(name);
+ }
+
+ public List<SecurityConfiguration> listSecurityConfigurations() {
+ return new ArrayList<>(secConfigStore.scan(k -> true));
+ }
+
+ // ──────────────────────────── Tags ────────────────────────────
+
+ public void addTags(String resourceId, Map<String, String> tags) {
+ EmrCluster cluster = requireCluster(resourceId);
+ cluster.getTags().putAll(tags);
+ clusterStore.put(resourceId, cluster);
+ }
+
+ public void removeTags(String resourceId, List<String> keys) {
+ EmrCluster cluster = requireCluster(resourceId);
+ keys.forEach(cluster.getTags()::remove);
+ clusterStore.put(resourceId, cluster);
+ }
+
+ // ──────────────────────────── Helpers ────────────────────────────
+
+ private EmrCluster requireCluster(String id) {
+ if (id == null) {
+ throw new AwsException("InvalidRequestException", "ClusterId is required.", 400);
+ }
+ return clusterStore.get(id).orElseThrow(() -> new AwsException(
+ "InvalidRequestException", "Cluster id '" + id + "' is not valid.", 400));
+ }
+
+ private void mutateClusters(List<String> ids, java.util.function.Consumer<EmrCluster> mutation) {
+ for (String id : ids) {
+ clusterStore.get(id).ifPresent(c -> {
+ mutation.accept(c);
+ clusterStore.put(id, c);
+ });
+ }
+ }
+
+ private void advanceToWaiting(EmrCluster cluster) {
+ cluster.setState("WAITING");
+ cluster.setStateChangeReasonCode(cluster.getSteps().isEmpty() ? null : "ALL_STEPS_COMPLETED");
+ cluster.setStateChangeMessage("Cluster ready to run steps.");
+ cluster.setReadyDateTime(Instant.now());
+ }
+
+ private void initStep(EmrStep step) {
+ step.setId("s-" + randomId(13));
+ step.setState("PENDING");
+ step.setCreationDateTime(Instant.now());
+ if (step.getActionOnFailure() == null) {
+ step.setActionOnFailure("TERMINATE_CLUSTER");
+ }
+ }
+
+ private void completeStep(EmrStep step) {
+ Instant now = Instant.now();
+ step.setStartDateTime(now);
+ step.setEndDateTime(now);
+ step.setState("COMPLETED");
+ }
+
+ private String randomId(int length) {
+ StringBuilder sb = new StringBuilder(length);
+ for (int i = 0; i < length; i++) {
+ sb.append(UPPER_ALNUM.charAt(RANDOM.nextInt(UPPER_ALNUM.length())));
+ }
+ return sb.toString();
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/emr/model/EmrCluster.java b/src/main/java/io/github/hectorvent/floci/services/emr/model/EmrCluster.java
new file mode 100644
index 0000000000..aa63255f33
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/emr/model/EmrCluster.java
@@ -0,0 +1,180 @@
+package io.github.hectorvent.floci.services.emr.model;
+
+import io.quarkus.runtime.annotations.RegisterForReflection;
+
+import java.time.Instant;
+import java.util.ArrayList;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * An EMR cluster (job flow). State machine:
+ * STARTING → BOOTSTRAPPING → RUNNING → WAITING, then → TERMINATING → TERMINATED.
+ * Steps, instance groups and fleets are stored as nested lists. Complex sub-structures
+ * (ec2 attributes, applications, configurations) are stored as raw JSON strings.
+ */
+@RegisterForReflection
+public class EmrCluster {
+
+ private String id;
+ private String name;
+ private String state = "STARTING";
+ private String stateChangeReasonCode;
+ private String stateChangeMessage;
+ private String releaseLabel;
+ private String logUri;
+ private String serviceRole;
+ private String jobFlowRole;
+ private String autoScalingRole;
+ private String scaleDownBehavior;
+ private String securityConfiguration;
+ private String customAmiId;
+ private String masterPublicDnsName;
+ private String clusterArn;
+ private String instanceCollectionType;
+ private boolean terminationProtected;
+ private boolean visibleToAllUsers = true;
+ private boolean autoTerminate;
+ private boolean unhealthyNodeReplacement;
+ private boolean keepJobFlowAliveWhenNoSteps;
+ private int normalizedInstanceHours;
+ private int stepConcurrencyLevel = 1;
+ private int ebsRootVolumeSize;
+ private String ec2Attributes;
+ private String applications;
+ private String configurations;
+ private String region;
+ private Instant creationDateTime;
+ private Instant readyDateTime;
+ private Instant endDateTime;
+ private Map<String, String> tags = new LinkedHashMap<>();
+ private List<EmrStep> steps = new ArrayList<>();
+ private List<EmrInstanceGroup> instanceGroups = new ArrayList<>();
+ private List<EmrInstanceFleet> instanceFleets = new ArrayList<>();
+
+ public EmrCluster() {}
+
+ public String getId() { return id; }
+ public void setId(String id) { this.id = id; }
+
+ public String getName() { return name; }
+ public void setName(String name) { this.name = name; }
+
+ public String getState() { return state; }
+ public void setState(String state) { this.state = state; }
+
+ public String getStateChangeReasonCode() { return stateChangeReasonCode; }
+ public void setStateChangeReasonCode(String stateChangeReasonCode) {
+ this.stateChangeReasonCode = stateChangeReasonCode;
+ }
+
+ public String getStateChangeMessage() { return stateChangeMessage; }
+ public void setStateChangeMessage(String stateChangeMessage) { this.stateChangeMessage = stateChangeMessage; }
+
+ public String getReleaseLabel() { return releaseLabel; }
+ public void setReleaseLabel(String releaseLabel) { this.releaseLabel = releaseLabel; }
+
+ public String getLogUri() { return logUri; }
+ public void setLogUri(String logUri) { this.logUri = logUri; }
+
+ public String getServiceRole() { return serviceRole; }
+ public void setServiceRole(String serviceRole) { this.serviceRole = serviceRole; }
+
+ public String getJobFlowRole() { return jobFlowRole; }
+ public void setJobFlowRole(String jobFlowRole) { this.jobFlowRole = jobFlowRole; }
+
+ public String getAutoScalingRole() { return autoScalingRole; }
+ public void setAutoScalingRole(String autoScalingRole) { this.autoScalingRole = autoScalingRole; }
+
+ public String getScaleDownBehavior() { return scaleDownBehavior; }
+ public void setScaleDownBehavior(String scaleDownBehavior) { this.scaleDownBehavior = scaleDownBehavior; }
+
+ public String getSecurityConfiguration() { return securityConfiguration; }
+ public void setSecurityConfiguration(String securityConfiguration) {
+ this.securityConfiguration = securityConfiguration;
+ }
+
+ public String getCustomAmiId() { return customAmiId; }
+ public void setCustomAmiId(String customAmiId) { this.customAmiId = customAmiId; }
+
+ public String getMasterPublicDnsName() { return masterPublicDnsName; }
+ public void setMasterPublicDnsName(String masterPublicDnsName) {
+ this.masterPublicDnsName = masterPublicDnsName;
+ }
+
+ public String getClusterArn() { return clusterArn; }
+ public void setClusterArn(String clusterArn) { this.clusterArn = clusterArn; }
+
+ public String getInstanceCollectionType() { return instanceCollectionType; }
+ public void setInstanceCollectionType(String instanceCollectionType) {
+ this.instanceCollectionType = instanceCollectionType;
+ }
+
+ public boolean isTerminationProtected() { return terminationProtected; }
+ public void setTerminationProtected(boolean terminationProtected) {
+ this.terminationProtected = terminationProtected;
+ }
+
+ public boolean isVisibleToAllUsers() { return visibleToAllUsers; }
+ public void setVisibleToAllUsers(boolean visibleToAllUsers) { this.visibleToAllUsers = visibleToAllUsers; }
+
+ public boolean isAutoTerminate() { return autoTerminate; }
+ public void setAutoTerminate(boolean autoTerminate) { this.autoTerminate = autoTerminate; }
+
+ public boolean isUnhealthyNodeReplacement() { return unhealthyNodeReplacement; }
+ public void setUnhealthyNodeReplacement(boolean unhealthyNodeReplacement) {
+ this.unhealthyNodeReplacement = unhealthyNodeReplacement;
+ }
+
+ public boolean isKeepJobFlowAliveWhenNoSteps() { return keepJobFlowAliveWhenNoSteps; }
+ public void setKeepJobFlowAliveWhenNoSteps(boolean keepJobFlowAliveWhenNoSteps) {
+ this.keepJobFlowAliveWhenNoSteps = keepJobFlowAliveWhenNoSteps;
+ }
+
+ public int getNormalizedInstanceHours() { return normalizedInstanceHours; }
+ public void setNormalizedInstanceHours(int normalizedInstanceHours) {
+ this.normalizedInstanceHours = normalizedInstanceHours;
+ }
+
+ public int getStepConcurrencyLevel() { return stepConcurrencyLevel; }
+ public void setStepConcurrencyLevel(int stepConcurrencyLevel) {
+ this.stepConcurrencyLevel = stepConcurrencyLevel;
+ }
+
+ public int getEbsRootVolumeSize() { return ebsRootVolumeSize; }
+ public void setEbsRootVolumeSize(int ebsRootVolumeSize) { this.ebsRootVolumeSize = ebsRootVolumeSize; }
+
+ public String getEc2Attributes() { return ec2Attributes; }
+ public void setEc2Attributes(String ec2Attributes) { this.ec2Attributes = ec2Attributes; }
+
+ public String getApplications() { return applications; }
+ public void setApplications(String applications) { this.applications = applications; }
+
+ public String getConfigurations() { return configurations; }
+ public void setConfigurations(String configurations) { this.configurations = configurations; }
+
+ public String getRegion() { return region; }
+ public void setRegion(String region) { this.region = region; }
+
+ public Instant getCreationDateTime() { return creationDateTime; }
+ public void setCreationDateTime(Instant creationDateTime) { this.creationDateTime = creationDateTime; }
+
+ public Instant getReadyDateTime() { return readyDateTime; }
+ public void setReadyDateTime(Instant readyDateTime) { this.readyDateTime = readyDateTime; }
+
+ public Instant getEndDateTime() { return endDateTime; }
+ public void setEndDateTime(Instant endDateTime) { this.endDateTime = endDateTime; }
+
+ public Map<String, String> getTags() { return tags; }
+ public void setTags(Map<String, String> tags) { this.tags = tags; }
+
+ public List<EmrStep> getSteps() { return steps; }
+ public void setSteps(List<EmrStep> steps) { this.steps = steps; }
+
+ public List<EmrInstanceGroup> getInstanceGroups() { return instanceGroups; }
+ public void setInstanceGroups(List<EmrInstanceGroup> instanceGroups) { this.instanceGroups = instanceGroups; }
+
+ public List<EmrInstanceFleet> getInstanceFleets() { return instanceFleets; }
+ public void setInstanceFleets(List<EmrInstanceFleet> instanceFleets) { this.instanceFleets = instanceFleets; }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/emr/model/EmrInstanceFleet.java b/src/main/java/io/github/hectorvent/floci/services/emr/model/EmrInstanceFleet.java
new file mode 100644
index 0000000000..c542e22987
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/emr/model/EmrInstanceFleet.java
@@ -0,0 +1,49 @@
+package io.github.hectorvent.floci.services.emr.model;
+
+import io.quarkus.runtime.annotations.RegisterForReflection;
+
+/** An EMR instance fleet (MASTER | CORE | TASK). */
+@RegisterForReflection
+public class EmrInstanceFleet {
+
+ private String id;
+ private String name;
+ private String instanceFleetType;
+ private int targetOnDemandCapacity;
+ private int targetSpotCapacity;
+ private int provisionedOnDemandCapacity;
+ private int provisionedSpotCapacity;
+ private String state;
+
+ public EmrInstanceFleet() {}
+
+ public String getId() { return id; }
+ public void setId(String id) { this.id = id; }
+
+ public String getName() { return name; }
+ public void setName(String name) { this.name = name; }
+
+ public String getInstanceFleetType() { return instanceFleetType; }
+ public void setInstanceFleetType(String instanceFleetType) { this.instanceFleetType = instanceFleetType; }
+
+ public int getTargetOnDemandCapacity() { return targetOnDemandCapacity; }
+ public void setTargetOnDemandCapacity(int targetOnDemandCapacity) {
+ this.targetOnDemandCapacity = targetOnDemandCapacity;
+ }
+
+ public int getTargetSpotCapacity() { return targetSpotCapacity; }
+ public void setTargetSpotCapacity(int targetSpotCapacity) { this.targetSpotCapacity = targetSpotCapacity; }
+
+ public int getProvisionedOnDemandCapacity() { return provisionedOnDemandCapacity; }
+ public void setProvisionedOnDemandCapacity(int provisionedOnDemandCapacity) {
+ this.provisionedOnDemandCapacity = provisionedOnDemandCapacity;
+ }
+
+ public int getProvisionedSpotCapacity() { return provisionedSpotCapacity; }
+ public void setProvisionedSpotCapacity(int provisionedSpotCapacity) {
+ this.provisionedSpotCapacity = provisionedSpotCapacity;
+ }
+
+ public String getState() { return state; }
+ public void setState(String state) { this.state = state; }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/emr/model/EmrInstanceGroup.java b/src/main/java/io/github/hectorvent/floci/services/emr/model/EmrInstanceGroup.java
new file mode 100644
index 0000000000..8f469e679f
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/emr/model/EmrInstanceGroup.java
@@ -0,0 +1,51 @@
+package io.github.hectorvent.floci.services.emr.model;
+
+import io.quarkus.runtime.annotations.RegisterForReflection;
+
+/** An EMR instance group (MASTER | CORE | TASK). */
+@RegisterForReflection
+public class EmrInstanceGroup {
+
+ private String id;
+ private String name;
+ private String instanceGroupType;
+ private String instanceType;
+ private String market;
+ private String bidPrice;
+ private int requestedInstanceCount;
+ private int runningInstanceCount;
+ private String state;
+
+ public EmrInstanceGroup() {}
+
+ public String getId() { return id; }
+ public void setId(String id) { this.id = id; }
+
+ public String getName() { return name; }
+ public void setName(String name) { this.name = name; }
+
+ public String getInstanceGroupType() { return instanceGroupType; }
+ public void setInstanceGroupType(String instanceGroupType) { this.instanceGroupType = instanceGroupType; }
+
+ public String getInstanceType() { return instanceType; }
+ public void setInstanceType(String instanceType) { this.instanceType = instanceType; }
+
+ public String getMarket() { return market; }
+ public void setMarket(String market) { this.market = market; }
+
+ public String getBidPrice() { return bidPrice; }
+ public void setBidPrice(String bidPrice) { this.bidPrice = bidPrice; }
+
+ public int getRequestedInstanceCount() { return requestedInstanceCount; }
+ public void setRequestedInstanceCount(int requestedInstanceCount) {
+ this.requestedInstanceCount = requestedInstanceCount;
+ }
+
+ public int getRunningInstanceCount() { return runningInstanceCount; }
+ public void setRunningInstanceCount(int runningInstanceCount) {
+ this.runningInstanceCount = runningInstanceCount;
+ }
+
+ public String getState() { return state; }
+ public void setState(String state) { this.state = state; }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/emr/model/EmrStep.java b/src/main/java/io/github/hectorvent/floci/services/emr/model/EmrStep.java
new file mode 100644
index 0000000000..7ef9356432
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/emr/model/EmrStep.java
@@ -0,0 +1,69 @@
+package io.github.hectorvent.floci.services.emr.model;
+
+import io.quarkus.runtime.annotations.RegisterForReflection;
+
+import java.time.Instant;
+import java.util.ArrayList;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+/** An EMR job-flow step. State machine: PENDING → RUNNING → COMPLETED (or CANCELLED/FAILED). */
+@RegisterForReflection
+public class EmrStep {
+
+ private String id;
+ private String name;
+ private String jar;
+ private String mainClass;
+ private List<String> args = new ArrayList<>();
+ private Map<String, String> properties = new LinkedHashMap<>();
+ private String actionOnFailure;
+ private String state;
+ private String stateChangeReason;
+ private String executionRoleArn;
+ private Instant creationDateTime;
+ private Instant startDateTime;
+ private Instant endDateTime;
+
+ public EmrStep() {}
+
+ public String getId() { return id; }
+ public void setId(String id) { this.id = id; }
+
+ public String getName() { return name; }
+ public void setName(String name) { this.name = name; }
+
+ public String getJar() { return jar; }
+ public void setJar(String jar) { this.jar = jar; }
+
+ public String getMainClass() { return mainClass; }
+ public void setMainClass(String mainClass) { this.mainClass = mainClass; }
+
+ public List<String> getArgs() { return args; }
+ public void setArgs(List<String> args) { this.args = args; }
+
+ public Map<String, String> getProperties() { return properties; }
+ public void setProperties(Map<String, String> properties) { this.properties = properties; }
+
+ public String getActionOnFailure() { return actionOnFailure; }
+ public void setActionOnFailure(String actionOnFailure) { this.actionOnFailure = actionOnFailure; }
+
+ public String getState() { return state; }
+ public void setState(String state) { this.state = state; }
+
+ public String getStateChangeReason() { return stateChangeReason; }
+ public void setStateChangeReason(String stateChangeReason) { this.stateChangeReason = stateChangeReason; }
+
+ public String getExecutionRoleArn() { return executionRoleArn; }
+ public void setExecutionRoleArn(String executionRoleArn) { this.executionRoleArn = executionRoleArn; }
+
+ public Instant getCreationDateTime() { return creationDateTime; }
+ public void setCreationDateTime(Instant creationDateTime) { this.creationDateTime = creationDateTime; }
+
+ public Instant getStartDateTime() { return startDateTime; }
+ public void setStartDateTime(Instant startDateTime) { this.startDateTime = startDateTime; }
+
+ public Instant getEndDateTime() { return endDateTime; }
+ public void setEndDateTime(Instant endDateTime) { this.endDateTime = endDateTime; }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/emr/model/SecurityConfiguration.java b/src/main/java/io/github/hectorvent/floci/services/emr/model/SecurityConfiguration.java
new file mode 100644
index 0000000000..8630b50f3c
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/emr/model/SecurityConfiguration.java
@@ -0,0 +1,27 @@
+package io.github.hectorvent.floci.services.emr.model;
+
+import io.quarkus.runtime.annotations.RegisterForReflection;
+
+import java.time.Instant;
+
+/** An EMR security configuration: a named JSON document. */
+@RegisterForReflection
+public class SecurityConfiguration {
+
+ private String name;
+ private String securityConfiguration;
+ private Instant creationDateTime;
+
+ public SecurityConfiguration() {}
+
+ public String getName() { return name; }
+ public void setName(String name) { this.name = name; }
+
+ public String getSecurityConfiguration() { return securityConfiguration; }
+ public void setSecurityConfiguration(String securityConfiguration) {
+ this.securityConfiguration = securityConfiguration;
+ }
+
+ public Instant getCreationDateTime() { return creationDateTime; }
+ public void setCreationDateTime(Instant creationDateTime) { this.creationDateTime = creationDateTime; }
+}
diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml
index 084e9a43bd..9b38571b0d 100644
--- a/src/main/resources/application.yml
+++ b/src/main/resources/application.yml
@@ -45,6 +45,7 @@ quarkus:
- --initialize-at-run-time=io.github.hectorvent.floci.services.route53.Route53Service
- --initialize-at-run-time=io.github.hectorvent.floci.services.kms.KmsService
- --initialize-at-run-time=io.github.hectorvent.floci.services.cloudfront.CloudFrontService
+ - --initialize-at-run-time=io.github.hectorvent.floci.services.emr.EmrService
floci:
@@ -195,6 +196,8 @@ floci:
enabled: true
cloudmap:
enabled: true
+ emr:
+ enabled: true
scheduler:
enabled: true
cloudwatchlogs:
diff --git a/src/test/java/io/github/hectorvent/floci/services/emr/EmrIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/emr/EmrIntegrationTest.java
new file mode 100644
index 0000000000..389b392f8f
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/emr/EmrIntegrationTest.java
@@ -0,0 +1,187 @@
+package io.github.hectorvent.floci.services.emr;
+
+import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
+import io.restassured.response.Response;
+import io.quarkus.test.junit.QuarkusTest;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.MethodOrderer;
+import org.junit.jupiter.api.Order;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.TestMethodOrder;
+
+import static io.restassured.RestAssured.given;
+import static org.hamcrest.Matchers.equalTo;
+import static org.hamcrest.Matchers.hasSize;
+import static org.hamcrest.Matchers.notNullValue;
+import static org.hamcrest.Matchers.startsWith;
+
+/**
+ * EMR cluster lifecycle over the AWS JSON 1.1 wire protocol: run job flow → describe →
+ * add steps → instance groups → security config → terminate. Covers the
+ * ActionOnFailure legacy alias and the InvalidRequestException not-found shape.
+ */
+@QuarkusTest
+@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
+class EmrIntegrationTest {
+
+ private static final String CT = "application/x-amz-json-1.1";
+ private static final String PREFIX = "ElasticMapReduce.";
+
+ private static String clusterId;
+ private static String stepId;
+
+ @BeforeAll
+ static void configure() {
+ RestAssuredJsonUtils.configureAwsContentTypes();
+ }
+
+ private static Response call(String action, String body) {
+ return given().contentType(CT).header("X-Amz-Target", PREFIX + action)
+ .body(body).when().post("/");
+ }
+
+ @Test
+ @Order(1)
+ void runJobFlow() {
+ Response resp = call("RunJobFlow",
+ "{\"Name\":\"floci-emr\",\"ReleaseLabel\":\"emr-7.5.0\","
+ + "\"Instances\":{\"KeepJobFlowAliveWhenNoSteps\":true,"
+ + "\"InstanceGroups\":[{\"Name\":\"master\",\"InstanceRole\":\"MASTER\","
+ + "\"InstanceType\":\"m5.xlarge\",\"InstanceCount\":1},"
+ + "{\"Name\":\"core\",\"InstanceRole\":\"CORE\","
+ + "\"InstanceType\":\"m5.xlarge\",\"InstanceCount\":2}]},"
+ + "\"Steps\":[{\"Name\":\"initial\",\"ActionOnFailure\":\"TERMINATE_JOB_FLOW\","
+ + "\"HadoopJarStep\":{\"Jar\":\"command-runner.jar\",\"Args\":[\"echo\",\"hi\"]}}]}");
+ resp.then().statusCode(200)
+ .body("JobFlowId", startsWith("j-"))
+ .body("ClusterArn", notNullValue());
+ clusterId = resp.jsonPath().getString("JobFlowId");
+ }
+
+ @Test
+ @Order(2)
+ void describeClusterIsWaiting() {
+ call("DescribeCluster", "{\"ClusterId\":\"" + clusterId + "\"}")
+ .then().statusCode(200)
+ .body("Cluster.Id", equalTo(clusterId))
+ .body("Cluster.Status.State", equalTo("WAITING"))
+ .body("Cluster.ReleaseLabel", equalTo("emr-7.5.0"))
+ .body("Cluster.InstanceCollectionType", equalTo("INSTANCE_GROUP"))
+ .body("Cluster.AutoTerminate", equalTo(false));
+ }
+
+ @Test
+ @Order(3)
+ void listClustersFilteredByState() {
+ call("ListClusters", "{\"ClusterStates\":[\"WAITING\"]}")
+ .then().statusCode(200)
+ .body("Clusters.find { it.Id == '" + clusterId + "' }.Name", equalTo("floci-emr"));
+ }
+
+ @Test
+ @Order(4)
+ void listInstanceGroups() {
+ call("ListInstanceGroups", "{\"ClusterId\":\"" + clusterId + "\"}")
+ .then().statusCode(200)
+ .body("InstanceGroups", hasSize(2))
+ .body("InstanceGroups.find { it.InstanceGroupType == 'CORE' }.RunningInstanceCount", equalTo(2));
+ }
+
+ @Test
+ @Order(5)
+ void listInstancesSynthetic() {
+ call("ListInstances", "{\"ClusterId\":\"" + clusterId + "\"}")
+ .then().statusCode(200)
+ .body("Instances", hasSize(3)) // 1 master + 2 core
+ .body("Instances[0].Status.State", equalTo("RUNNING"));
+ }
+
+ @Test
+ @Order(6)
+ void addStepWithLegacyActionAlias() {
+ stepId = call("AddJobFlowSteps",
+ "{\"JobFlowId\":\"" + clusterId + "\",\"Steps\":[{\"Name\":\"added\","
+ + "\"ActionOnFailure\":\"TERMINATE_CLUSTER\","
+ + "\"HadoopJarStep\":{\"Jar\":\"command-runner.jar\",\"MainClass\":\"org.Main\","
+ + "\"Args\":[\"run\"]}}]}")
+ .then().statusCode(200)
+ .body("StepIds", hasSize(1))
+ .extract().jsonPath().getString("StepIds[0]");
+ }
+
+ @Test
+ @Order(7)
+ void describeStepCompleted() {
+ call("DescribeStep", "{\"ClusterId\":\"" + clusterId + "\",\"StepId\":\"" + stepId + "\"}")
+ .then().statusCode(200)
+ .body("Step.Id", equalTo(stepId))
+ .body("Step.Name", equalTo("added"))
+ .body("Step.ActionOnFailure", equalTo("TERMINATE_CLUSTER"))
+ .body("Step.Config.MainClass", equalTo("org.Main"))
+ .body("Step.Status.State", equalTo("COMPLETED"));
+ }
+
+ @Test
+ @Order(8)
+ void listStepsNewestFirst() {
+ call("ListSteps", "{\"ClusterId\":\"" + clusterId + "\"}")
+ .then().statusCode(200)
+ .body("Steps", hasSize(2))
+ .body("Steps[0].Name", equalTo("added")) // newest first
+ .body("Steps[1].Name", equalTo("initial"));
+ }
+
+ @Test
+ @Order(9)
+ void modifyStepConcurrency() {
+ call("ModifyCluster", "{\"ClusterId\":\"" + clusterId + "\",\"StepConcurrencyLevel\":5}")
+ .then().statusCode(200)
+ .body("StepConcurrencyLevel", equalTo(5));
+ }
+
+ @Test
+ @Order(10)
+ void securityConfigurationRoundTrip() {
+ call("CreateSecurityConfiguration",
+ "{\"Name\":\"floci-emr-sec\",\"SecurityConfiguration\":\"{\\\"EncryptionConfiguration\\\":{}}\"}")
+ .then().statusCode(200)
+ .body("Name", equalTo("floci-emr-sec"))
+ .body("CreationDateTime", notNullValue());
+
+ call("DescribeSecurityConfiguration", "{\"Name\":\"floci-emr-sec\"}")
+ .then().statusCode(200)
+ .body("SecurityConfiguration", equalTo("{\"EncryptionConfiguration\":{}}"));
+
+ call("DeleteSecurityConfiguration", "{\"Name\":\"floci-emr-sec\"}").then().statusCode(200);
+ }
+
+ @Test
+ @Order(11)
+ void tagsRoundTrip() {
+ call("AddTags", "{\"ResourceId\":\"" + clusterId + "\",\"Tags\":[{\"Key\":\"env\",\"Value\":\"test\"}]}")
+ .then().statusCode(200);
+ call("DescribeCluster", "{\"ClusterId\":\"" + clusterId + "\"}")
+ .then().statusCode(200)
+ .body("Cluster.Tags.find { it.Key == 'env' }.Value", equalTo("test"));
+ call("RemoveTags", "{\"ResourceId\":\"" + clusterId + "\",\"TagKeys\":[\"env\"]}")
+ .then().statusCode(200);
+ }
+
+ @Test
+ @Order(12)
+ void terminateCluster() {
+ call("TerminateJobFlows", "{\"JobFlowIds\":[\"" + clusterId + "\"]}").then().statusCode(200);
+ call("DescribeCluster", "{\"ClusterId\":\"" + clusterId + "\"}")
+ .then().statusCode(200)
+ .body("Cluster.Status.State", equalTo("TERMINATED"))
+ .body("Cluster.Status.StateChangeReason.Code", equalTo("USER_REQUEST"));
+ }
+
+ @Test
+ @Order(13)
+ void describeUnknownClusterIsInvalidRequest() {
+ call("DescribeCluster", "{\"ClusterId\":\"j-DOESNOTEXIST0\"}")
+ .then().statusCode(400)
+ .body("__type", equalTo("InvalidRequestException"));
+ }
+}
diff --git a/src/test/resources/application.yml b/src/test/resources/application.yml
index 1b8dedaabe..20e0ca2860 100644
--- a/src/test/resources/application.yml
+++ b/src/test/resources/application.yml
@@ -112,6 +112,8 @@ floci:
enabled: true
cloudmap:
enabled: true
+ emr:
+ enabled: true
scheduler:
enabled: true
cloudwatchlogs: