Skip to content

armgit / floci

Public Imported from GitHub
0

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

feat(emr): resize instance groups and fleets, list bootstrap actions (#4900)

David82977a7f03a0
diff --git a/README.md b/README.md
index 9d852aa4ca..8d085798a5 100644
--- a/README.md
+++ b/README.md
@@ -346,7 +346,7 @@ For operation-level compatibility, see the [Services Overview](https://floci.io/
| Amazon MQ | Real Docker | RabbitMQ broker via rabbitmq:3-management; AMQP + management console |
| Athena | In-process with DuckDB sidecar | Real SQL execution over S3 and Glue-backed views |
| Glue | In-process | Data Catalog, Schema Registry, tables consumed by Athena |
-| EMR | In-process | Cluster (job flow) lifecycle, instance groups and fleets, steps, security configurations, scaling and termination policies, block public access, tagging |
+| EMR | In-process | Cluster (job flow) lifecycle, instance groups and fleets (including resizing), bootstrap actions, steps, security configurations, scaling and termination policies, block public access, tagging |
| Data Firehose | In-process | Streaming delivery, buffered flush to S3 with GZIP/ZIP/Snappy compression |
| Managed Service for Apache Flink | Real Docker | Kinesis Analytics V2 control plane; StartApplication runs a real Flink cluster (JobManager + TaskManager, image per RuntimeEnvironment), pulls the application JAR from local S3, and submits the job |
| ECS | Real Docker | Clusters, task definitions, tasks, services, capacity providers, task sets |
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
index c2cb89f7d2..d40aeb3845 100644
--- 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
@@ -248,6 +248,65 @@ class EmrTest {
assertThat(after.permittedPublicSecurityGroupRuleRanges()).hasSize(2);
}
+ @Test
+ @Order(15)
+ void modifyInstanceGroupsResizesCore() {
+ String coreGroupId = emr.listInstanceGroups(r -> r.clusterId(clusterId)).instanceGroups().stream()
+ .filter(g -> g.instanceGroupType() == InstanceGroupType.CORE)
+ .findFirst().orElseThrow().id();
+ emr.modifyInstanceGroups(r -> r.clusterId(clusterId)
+ .instanceGroups(InstanceGroupModifyConfig.builder().instanceGroupId(coreGroupId).instanceCount(4).build()));
+ InstanceGroup core = emr.listInstanceGroups(r -> r.clusterId(clusterId)).instanceGroups().stream()
+ .filter(g -> g.id().equals(coreGroupId)).findFirst().orElseThrow();
+ assertThat(core.requestedInstanceCount()).isEqualTo(4);
+ assertThat(core.runningInstanceCount()).isEqualTo(4);
+ assertThat(emr.listInstances(r -> r.clusterId(clusterId)).instances()).hasSize(5); // 1 master + 4 core
+ }
+
+ @Test
+ @Order(16)
+ void bootstrapActionsAndFleetResize() {
+ String fleetClusterId = emr.runJobFlow(r -> r
+ .name("floci-emr-sdk-fleet")
+ .releaseLabel("emr-7.5.0")
+ .bootstrapActions(BootstrapActionConfig.builder()
+ .name("install")
+ .scriptBootstrapAction(ScriptBootstrapActionConfig.builder()
+ .path("s3://bucket/install.sh").args("--fast").build())
+ .build())
+ .instances(JobFlowInstancesConfig.builder()
+ .keepJobFlowAliveWhenNoSteps(true)
+ .instanceFleets(
+ InstanceFleetConfig.builder().instanceFleetType(InstanceFleetType.MASTER)
+ .targetOnDemandCapacity(1)
+ .instanceTypeConfigs(InstanceTypeConfig.builder().instanceType("m5.xlarge").build())
+ .build(),
+ InstanceFleetConfig.builder().instanceFleetType(InstanceFleetType.CORE)
+ .targetOnDemandCapacity(2)
+ .instanceTypeConfigs(InstanceTypeConfig.builder().instanceType("m5.xlarge").build())
+ .build())
+ .build()))
+ .jobFlowId();
+ try {
+ List<Command> actions = emr.listBootstrapActions(r -> r.clusterId(fleetClusterId)).bootstrapActions();
+ assertThat(actions).hasSize(1);
+ assertThat(actions.get(0).scriptPath()).isEqualTo("s3://bucket/install.sh");
+ assertThat(actions.get(0).args()).containsExactly("--fast");
+
+ String coreFleetId = emr.listInstanceFleets(r -> r.clusterId(fleetClusterId)).instanceFleets().stream()
+ .filter(f -> f.instanceFleetType() == InstanceFleetType.CORE)
+ .findFirst().orElseThrow().id();
+ emr.modifyInstanceFleet(r -> r.clusterId(fleetClusterId).instanceFleet(InstanceFleetModifyConfig.builder()
+ .instanceFleetId(coreFleetId).targetOnDemandCapacity(5).build()));
+ InstanceFleet core = emr.listInstanceFleets(r -> r.clusterId(fleetClusterId)).instanceFleets().stream()
+ .filter(f -> f.id().equals(coreFleetId)).findFirst().orElseThrow();
+ assertThat(core.targetOnDemandCapacity()).isEqualTo(5);
+ assertThat(core.provisionedOnDemandCapacity()).isEqualTo(5);
+ } finally {
+ emr.terminateJobFlows(r -> r.jobFlowIds(fleetClusterId));
+ }
+ }
+
@Test
@Order(20)
void terminate() {
diff --git a/docs/services/emr.md b/docs/services/emr.md
index e1d571ebcc..fea52b099f 100644
--- a/docs/services/emr.md
+++ b/docs/services/emr.md
@@ -35,6 +35,9 @@ Floci emulates the Amazon EMR (Elastic MapReduce) management API. Clusters (job
| `ListSecurityConfigurations` | Lists all security configurations |
| `AddTags` | Adds tags to a cluster |
| `RemoveTags` | Removes tags from a cluster |
+| `ModifyInstanceGroups` | Resizes or reconfigures instance groups |
+| `ModifyInstanceFleet` | Changes an instance fleet's target capacities |
+| `ListBootstrapActions` | Lists the bootstrap actions given to `RunJobFlow` |
| `PutManagedScalingPolicy` | Sets a cluster's managed scaling policy |
| `GetManagedScalingPolicy` | Returns a cluster's managed scaling policy |
| `RemoveManagedScalingPolicy` | Removes a cluster's managed scaling policy |
diff --git a/docs/services/index.md b/docs/services/index.md
index e4a1b47073..65b9c7e75c 100644
--- a/docs/services/index.md
+++ b/docs/services/index.md
@@ -77,7 +77,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac
| [Redshift](redshift.md) | `POST /` with `Action=` param + PostgreSQL container | Query + PostgreSQL wire (+ CFN) | 35 |
| [Redshift Data API](redshift-data.md) | `POST /` + `X-Amz-Target: RedshiftData.*` | JSON 1.1 | 11 |
| [Redshift Serverless](redshift-serverless.md) | `POST /` + `X-Amz-Target: RedshiftServerless.*` | JSON 1.1 | 8 |
-| [EMR](emr.md) | `POST /` + `X-Amz-Target: ElasticMapReduce.*` | JSON 1.1 | 34 |
+| [EMR](emr.md) | `POST /` + `X-Amz-Target: ElasticMapReduce.*` | JSON 1.1 | 37 |
| [EMR Serverless](emr-serverless.md) | `/applications/*`, `/tags/*` | REST JSON | 10 |
| [Data Firehose](firehose.md) | `POST /` + `X-Amz-Target: Firehose_20150804.*` | JSON 1.1 | 12 |
| [ECS](ecs.md) | `POST /` + `X-Amz-Target: AmazonEC2ContainerServiceV20141113.*` | JSON 1.1 | 58 |
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
index e16af78632..d38e2776ac 100644
--- a/src/main/java/io/github/hectorvent/floci/services/emr/EmrHandler.java
+++ b/src/main/java/io/github/hectorvent/floci/services/emr/EmrHandler.java
@@ -71,6 +71,9 @@ public class EmrHandler {
case "ListSecurityConfigurations" -> handleListSecurityConfigurations();
case "AddTags" -> handleAddTags(request);
case "RemoveTags" -> handleRemoveTags(request);
+ case "ModifyInstanceGroups" -> handleModifyInstanceGroups(request, region);
+ case "ModifyInstanceFleet" -> handleModifyInstanceFleet(request);
+ case "ListBootstrapActions" -> handleListBootstrapActions(request);
case "PutManagedScalingPolicy" -> handlePutManagedScalingPolicy(request);
case "GetManagedScalingPolicy" -> handleGetManagedScalingPolicy(request);
case "RemoveManagedScalingPolicy" -> handleRemoveManagedScalingPolicy(request);
@@ -117,6 +120,11 @@ public class EmrHandler {
cluster.setApplications(rawArray(request.path("Applications")));
cluster.setConfigurations(rawArray(request.path("Configurations")));
cluster.setTags(parseTags(request.path("Tags")));
+ JsonNode bootstrapActions = request.path("BootstrapActions");
+ if (!bootstrapActions.isMissingNode() && !bootstrapActions.isNull()) {
+ EmrService.validateBootstrapActions(bootstrapActions);
+ cluster.setBootstrapActions(rawArray(bootstrapActions));
+ }
JsonNode managedScaling = request.path("ManagedScalingPolicy");
if (!managedScaling.isMissingNode() && !managedScaling.isNull()) {
EmrService.validateManagedScalingPolicy(managedScaling);
@@ -288,7 +296,7 @@ public class EmrHandler {
ArrayNode arr = response.putArray("Instances");
int n = 1;
for (EmrInstanceGroup group : cluster.getInstanceGroups()) {
- for (int i = 0; i < Math.max(1, group.getRunningInstanceCount()); i++) {
+ for (int i = 0; i < group.getRunningInstanceCount(); i++) {
arr.add(syntheticInstanceNode(cluster, group, n++));
}
}
@@ -346,6 +354,53 @@ public class EmrHandler {
// ──────────────────────────── Builders ────────────────────────────
+ private Response handleModifyInstanceGroups(JsonNode request, String region) {
+ List<EmrService.InstanceGroupModification> modifications = new ArrayList<>();
+ for (JsonNode g : request.path("InstanceGroups")) {
+ JsonNode count = g.path("InstanceCount");
+ JsonNode configurations = g.path("Configurations");
+ modifications.add(new EmrService.InstanceGroupModification(
+ g.path("InstanceGroupId").asText(null),
+ count.isMissingNode() || count.isNull() ? null : count.asInt(),
+ configurations.isArray() ? configurations.toString() : null));
+ }
+ service.modifyInstanceGroups(text(request, "ClusterId"), region, modifications);
+ return Response.ok(objectMapper.createObjectNode()).build();
+ }
+
+ private Response handleModifyInstanceFleet(JsonNode request) {
+ JsonNode fleet = request.path("InstanceFleet");
+ JsonNode onDemand = fleet.path("TargetOnDemandCapacity");
+ JsonNode spot = fleet.path("TargetSpotCapacity");
+ service.modifyInstanceFleet(text(request, "ClusterId"), fleet.path("InstanceFleetId").asText(null),
+ onDemand.isMissingNode() || onDemand.isNull() ? null : onDemand.asInt(),
+ spot.isMissingNode() || spot.isNull() ? null : spot.asInt());
+ return Response.ok(objectMapper.createObjectNode()).build();
+ }
+
+ /** Each BootstrapActionConfig given to RunJobFlow, as the Command shape: Name, ScriptPath and Args. */
+ private Response handleListBootstrapActions(JsonNode request) {
+ String raw = service.listBootstrapActions(text(request, "ClusterId"));
+ ObjectNode response = objectMapper.createObjectNode();
+ ArrayNode arr = response.putArray("BootstrapActions");
+ if (raw == null) {
+ return Response.ok(response).build();
+ }
+ try {
+ for (JsonNode action : objectMapper.readTree(raw)) {
+ ObjectNode command = arr.addObject();
+ command.put("Name", action.path("Name").asText());
+ JsonNode script = action.path("ScriptBootstrapAction");
+ command.put("ScriptPath", script.path("Path").asText());
+ ArrayNode args = command.putArray("Args");
+ script.path("Args").forEach(args::add);
+ }
+ } catch (Exception e) {
+ LOG.warnv("Failed to parse stored BootstrapActions JSON; list left empty. Value: {0}", raw);
+ }
+ return Response.ok(response).build();
+ }
+
private Response handlePutManagedScalingPolicy(JsonNode request) {
service.putManagedScalingPolicy(text(request, "ClusterId"), request.get("ManagedScalingPolicy"));
return Response.ok(objectMapper.createObjectNode()).build();
@@ -529,6 +584,13 @@ public class EmrHandler {
if (g.getAutoScalingPolicy() != null) {
node.set("AutoScalingPolicy", autoScalingPolicyNode(g.getAutoScalingPolicy()));
}
+ if (g.getConfigurations() != null) {
+ // Floci applies a reconfiguration at once, so the applied configuration is the requested one.
+ setRawJson(node, "Configurations", g.getConfigurations());
+ node.put("ConfigurationsVersion", g.getConfigurationsVersion());
+ setRawJson(node, "LastSuccessfullyAppliedConfigurations", g.getConfigurations());
+ node.put("LastSuccessfullyAppliedConfigurationsVersion", g.getConfigurationsVersion());
+ }
return node;
}
@@ -628,6 +690,9 @@ public class EmrHandler {
group.setMarket(g.path("Market").asText(null));
group.setBidPrice(g.path("BidPrice").asText(null));
group.setRequestedInstanceCount(g.path("InstanceCount").asInt(0));
+ // Kept as given, an empty list included, so creation reads back like ModifyInstanceGroups.
+ JsonNode configurations = g.path("Configurations");
+ group.setConfigurations(configurations.isArray() ? configurations.toString() : null);
JsonNode autoScaling = g.path("AutoScalingPolicy");
if (!autoScaling.isMissingNode() && !autoScaling.isNull()) {
EmrService.validateAutoScalingPolicy(autoScaling, group.getInstanceGroupType());
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
index 689b4d833f..d705af98eb 100644
--- a/src/main/java/io/github/hectorvent/floci/services/emr/EmrService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/emr/EmrService.java
@@ -19,6 +19,7 @@ import jakarta.inject.Inject;
import java.security.SecureRandom;
import java.time.Instant;
import java.util.ArrayList;
+import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
@@ -262,6 +263,52 @@ public class EmrService {
return ids;
}
+ /** One InstanceGroupModifyConfig: a null count or configurations leaves that setting as it is. */
+ public record InstanceGroupModification(String instanceGroupId, Integer instanceCount, String configurations) {}
+
+ /**
+ * Resizes or reconfigures instance groups in place. ClusterId is optional in the request, so
+ * without it each group is looked up across the account's clusters in the Region. Every modification is
+ * checked before any is applied.
+ */
+ public synchronized void modifyInstanceGroups(String clusterId, String region,
+ List<InstanceGroupModification> modifications) {
+ if (modifications.isEmpty()) {
+ throw invalid("InstanceGroups must contain at least one instance group.");
+ }
+ Map<String, EmrCluster> touched = new LinkedHashMap<>();
+ List<EmrInstanceGroup> groups = new ArrayList<>();
+ for (InstanceGroupModification mod : modifications) {
+ EmrCluster found = clusterId != null ? requireCluster(clusterId) : clusterOwning(region, mod.instanceGroupId());
+ // 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());
+ if (mod.instanceCount() != null) {
+ if (mod.instanceCount() < 0) {
+ throw invalid("InstanceCount must not be negative.");
+ }
+ if ("MASTER".equals(group.getInstanceGroupType())
+ && mod.instanceCount() != group.getRequestedInstanceCount()) {
+ throw invalid("The instance count of a master instance group cannot be modified.");
+ }
+ }
+ groups.add(group);
+ }
+ for (int i = 0; i < modifications.size(); i++) {
+ InstanceGroupModification mod = modifications.get(i);
+ EmrInstanceGroup group = groups.get(i);
+ if (mod.instanceCount() != null) {
+ group.setRequestedInstanceCount(mod.instanceCount());
+ group.setRunningInstanceCount(mod.instanceCount());
+ }
+ if (mod.configurations() != null) {
+ group.setConfigurations(mod.configurations());
+ group.setConfigurationsVersion(group.getConfigurationsVersion() + 1);
+ }
+ }
+ touched.forEach(clusterStore::put);
+ }
+
public List<EmrInstanceGroup> listInstanceGroups(String clusterId) {
return requireCluster(clusterId).getInstanceGroups();
}
@@ -277,6 +324,38 @@ public class EmrService {
return fleet.getId();
}
+ /** Resizes an instance fleet; a null target leaves that capacity as it is. */
+ public synchronized void modifyInstanceFleet(String clusterId, String instanceFleetId,
+ Integer targetOnDemandCapacity, Integer targetSpotCapacity) {
+ EmrCluster cluster = requireCluster(clusterId);
+ if (instanceFleetId == null) {
+ throw invalid("InstanceFleetId is required.");
+ }
+ EmrInstanceFleet fleet = cluster.getInstanceFleets().stream()
+ .filter(f -> instanceFleetId.equals(f.getId()))
+ .findFirst()
+ .orElseThrow(() -> invalid("Instance fleet " + instanceFleetId + " is not in cluster " + clusterId + "."));
+ int onDemand = targetOnDemandCapacity != null ? targetOnDemandCapacity : fleet.getTargetOnDemandCapacity();
+ int spot = targetSpotCapacity != null ? targetSpotCapacity : fleet.getTargetSpotCapacity();
+ if (onDemand < 0 || spot < 0) {
+ throw invalid("Target capacities must not be negative.");
+ }
+ if ("MASTER".equals(fleet.getInstanceFleetType())
+ && (onDemand != fleet.getTargetOnDemandCapacity() || spot != fleet.getTargetSpotCapacity())) {
+ throw invalid("The target capacity of a master instance fleet cannot be modified.");
+ }
+ fleet.setTargetOnDemandCapacity(onDemand);
+ fleet.setTargetSpotCapacity(spot);
+ fleet.setProvisionedOnDemandCapacity(onDemand);
+ fleet.setProvisionedSpotCapacity(spot);
+ clusterStore.put(clusterId, cluster);
+ }
+
+ /** The cluster's bootstrap actions as given to RunJobFlow, raw JSON; null when it had none. */
+ public String listBootstrapActions(String clusterId) {
+ return requireCluster(clusterId).getBootstrapActions();
+ }
+
public List<EmrInstanceFleet> listInstanceFleets(String clusterId) {
return requireCluster(clusterId).getInstanceFleets();
}
@@ -527,6 +606,30 @@ public class EmrService {
}
}
+ /** Each BootstrapActionConfig needs a Name and a ScriptBootstrapAction with a Path. */
+ static void validateBootstrapActions(JsonNode actions) {
+ if (!actions.isArray()) {
+ throw invalid("BootstrapActions must be a list.");
+ }
+ for (JsonNode action : actions) {
+ if (action.path("Name").asText("").isEmpty()
+ || action.path("ScriptBootstrapAction").path("Path").asText("").isEmpty()) {
+ throw invalid("Each bootstrap action needs a Name and a ScriptBootstrapAction.Path.");
+ }
+ }
+ }
+
+ private EmrCluster clusterOwning(String region, String instanceGroupId) {
+ if (instanceGroupId == null) {
+ throw invalid("InstanceGroupId is required.");
+ }
+ return clusterStore.scan(k -> true).stream()
+ .filter(c -> region.equals(c.getRegion()))
+ .filter(c -> c.getInstanceGroups().stream().anyMatch(g -> instanceGroupId.equals(g.getId())))
+ .findFirst()
+ .orElseThrow(() -> invalid("Instance group " + instanceGroupId + " is not valid."));
+ }
+
private static AwsException invalid(String message) {
return new AwsException("InvalidRequestException", message, 400);
}
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
index d686ffe45f..a44f58de9c 100644
--- 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
@@ -44,6 +44,8 @@ public class EmrCluster {
private String ec2Attributes;
private String applications;
private String configurations;
+ // The cluster's BootstrapActions (BootstrapActionConfig list) as given, raw JSON; null when none.
+ private String bootstrapActions;
// The cluster's ManagedScalingPolicy and AutoTerminationPolicy as given, raw JSON; null when none.
private String managedScalingPolicy;
private String autoTerminationPolicy;
@@ -157,6 +159,9 @@ public class EmrCluster {
public String getConfigurations() { return configurations; }
public void setConfigurations(String configurations) { this.configurations = configurations; }
+ public String getBootstrapActions() { return bootstrapActions; }
+ public void setBootstrapActions(String bootstrapActions) { this.bootstrapActions = bootstrapActions; }
+
public String getManagedScalingPolicy() { return managedScalingPolicy; }
public void setManagedScalingPolicy(String managedScalingPolicy) { this.managedScalingPolicy = managedScalingPolicy; }
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
index 92f7ee2419..eee2918427 100644
--- 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
@@ -17,6 +17,9 @@ public class EmrInstanceGroup {
private String state;
/** The AutoScalingPolicy as given (Constraints and Rules), raw JSON; null when none is attached. */
private String autoScalingPolicy;
+ /** The group's Configurations as given, raw JSON; null when none. Applied at once, so it is also the last applied. */
+ private String configurations;
+ private long configurationsVersion;
public EmrInstanceGroup() {}
@@ -35,6 +38,12 @@ public class EmrInstanceGroup {
public String getMarket() { return market; }
public void setMarket(String market) { this.market = market; }
+ public String getConfigurations() { return configurations; }
+ public void setConfigurations(String configurations) { this.configurations = configurations; }
+
+ public long getConfigurationsVersion() { return configurationsVersion; }
+ public void setConfigurationsVersion(long configurationsVersion) { this.configurationsVersion = configurationsVersion; }
+
public String getBidPrice() { return bidPrice; }
public void setBidPrice(String bidPrice) { this.bidPrice = bidPrice; }
diff --git a/src/test/java/io/github/hectorvent/floci/services/emr/EmrResizeIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/emr/EmrResizeIntegrationTest.java
new file mode 100644
index 0000000000..e583dc770e
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/emr/EmrResizeIntegrationTest.java
@@ -0,0 +1,188 @@
+package io.github.hectorvent.floci.services.emr;
+
+import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
+import io.quarkus.test.junit.QuarkusTest;
+import io.restassured.response.Response;
+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 java.util.List;
+
+import static io.restassured.RestAssured.given;
+import static org.hamcrest.Matchers.equalTo;
+import static org.hamcrest.Matchers.hasSize;
+import static org.hamcrest.Matchers.nullValue;
+
+/**
+ * EMR instance group and fleet resizing and bootstrap action listing over the AWS JSON 1.1 wire
+ * protocol.
+ */
+@QuarkusTest
+@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
+class EmrResizeIntegrationTest {
+
+ private static final String CT = "application/x-amz-json-1.1";
+ private static final String PREFIX = "ElasticMapReduce.";
+
+ private static String groupsClusterId;
+ private static String masterGroupId;
+ private static String coreGroupId;
+ private static String taskGroupId;
+ private static String fleetClusterId;
+ private static String masterFleetId;
+ private static String coreFleetId;
+
+ @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("/");
+ }
+
+ private static String groupId(String type) {
+ return call("ListInstanceGroups", "{\"ClusterId\":\"" + groupsClusterId + "\"}").jsonPath()
+ .getString("InstanceGroups.find { it.InstanceGroupType == '" + type + "' }.Id");
+ }
+
+ @Test
+ @Order(1)
+ void runJobFlowStoresBootstrapActions() {
+ Response resp = call("RunJobFlow",
+ "{\"Name\":\"resize\",\"ReleaseLabel\":\"emr-7.5.0\","
+ + "\"BootstrapActions\":[{\"Name\":\"install\",\"ScriptBootstrapAction\":"
+ + "{\"Path\":\"s3://bucket/install.sh\",\"Args\":[\"--fast\",\"1\"]}},"
+ + "{\"Name\":\"noargs\",\"ScriptBootstrapAction\":{\"Path\":\"s3://bucket/b.sh\"}}],"
+ + "\"Instances\":{\"KeepJobFlowAliveWhenNoSteps\":true,"
+ + "\"InstanceGroups\":[{\"InstanceRole\":\"MASTER\",\"InstanceType\":\"m5.xlarge\",\"InstanceCount\":1},"
+ + "{\"InstanceRole\":\"CORE\",\"InstanceType\":\"m5.xlarge\",\"InstanceCount\":2},"
+ + "{\"InstanceRole\":\"TASK\",\"InstanceType\":\"m5.xlarge\",\"InstanceCount\":1,"
+ + "\"Configurations\":[]}]}}");
+ resp.then().statusCode(200);
+ groupsClusterId = resp.jsonPath().getString("JobFlowId");
+ masterGroupId = groupId("MASTER");
+ coreGroupId = groupId("CORE");
+ taskGroupId = groupId("TASK");
+
+ call("ListInstanceGroups", "{\"ClusterId\":\"" + groupsClusterId + "\"}").then().statusCode(200)
+ .body("InstanceGroups.find { it.Id == '" + taskGroupId + "' }.Configurations", hasSize(0))
+ .body("InstanceGroups.find { it.Id == '" + coreGroupId + "' }.Configurations", nullValue());
+
+ call("ListBootstrapActions", "{\"ClusterId\":\"" + groupsClusterId + "\"}").then().statusCode(200)
+ .body("BootstrapActions", hasSize(2))
+ .body("BootstrapActions[0].Name", equalTo("install"))
+ .body("BootstrapActions[0].ScriptPath", equalTo("s3://bucket/install.sh"))
+ .body("BootstrapActions[0].Args", equalTo(List.of("--fast", "1")))
+ .body("BootstrapActions[1].Args", hasSize(0));
+ }
+
+ @Test
+ @Order(2)
+ void listBootstrapActionsEmptyAndValidated() {
+ Response resp = call("RunJobFlow", "{\"Name\":\"plain\",\"Instances\":{\"InstanceGroups\":"
+ + "[{\"InstanceRole\":\"MASTER\",\"InstanceType\":\"m5.xlarge\",\"InstanceCount\":1}]}}");
+ call("ListBootstrapActions", "{\"ClusterId\":\"" + resp.jsonPath().getString("JobFlowId") + "\"}")
+ .then().statusCode(200).body("BootstrapActions", hasSize(0));
+ call("ListBootstrapActions", "{\"ClusterId\":\"j-MISSING\"}")
+ .then().statusCode(400).body("__type", equalTo("InvalidRequestException"));
+ call("RunJobFlow", "{\"Name\":\"bad\",\"BootstrapActions\":[{\"Name\":\"x\"}]}")
+ .then().statusCode(400).body("__type", equalTo("InvalidRequestException"));
+ }
+
+ @Test
+ @Order(3)
+ void modifyInstanceGroupsResizesAndReconfigures() {
+ call("ModifyInstanceGroups", "{\"ClusterId\":\"" + groupsClusterId + "\",\"InstanceGroups\":["
+ + "{\"InstanceGroupId\":\"" + coreGroupId + "\",\"InstanceCount\":4},"
+ + "{\"InstanceGroupId\":\"" + taskGroupId + "\",\"InstanceCount\":0,\"Configurations\":"
+ + "[{\"Classification\":\"yarn-site\",\"Properties\":{\"yarn.nodemanager.vmem-check-enabled\":\"false\"}}]}]}")
+ .then().statusCode(200);
+ call("ListInstanceGroups", "{\"ClusterId\":\"" + groupsClusterId + "\"}").then().statusCode(200)
+ .body("InstanceGroups.find { it.Id == '" + coreGroupId + "' }.RequestedInstanceCount", equalTo(4))
+ .body("InstanceGroups.find { it.Id == '" + coreGroupId + "' }.RunningInstanceCount", equalTo(4))
+ .body("InstanceGroups.find { it.Id == '" + coreGroupId + "' }.Configurations", nullValue())
+ .body("InstanceGroups.find { it.Id == '" + taskGroupId + "' }.RunningInstanceCount", equalTo(0))
+ .body("InstanceGroups.find { it.Id == '" + taskGroupId + "' }.Configurations[0].Classification",
+ equalTo("yarn-site"))
+ .body("InstanceGroups.find { it.Id == '" + taskGroupId + "' }.ConfigurationsVersion", equalTo(1))
+ .body("InstanceGroups.find { it.Id == '" + taskGroupId + "' }.LastSuccessfullyAppliedConfigurationsVersion",
+ equalTo(1));
+ // 1 master + 4 core + 0 task.
+ call("ListInstances", "{\"ClusterId\":\"" + groupsClusterId + "\"}").then().statusCode(200)
+ .body("Instances", hasSize(5));
+ }
+
+ @Test
+ @Order(4)
+ void modifyInstanceGroupsWithoutClusterIdFindsTheGroup() {
+ call("ModifyInstanceGroups", "{\"InstanceGroups\":[{\"InstanceGroupId\":\"" + coreGroupId
+ + "\",\"InstanceCount\":3}]}").then().statusCode(200);
+ call("ListInstanceGroups", "{\"ClusterId\":\"" + groupsClusterId + "\"}").then().statusCode(200)
+ .body("InstanceGroups.find { it.Id == '" + coreGroupId + "' }.RunningInstanceCount", equalTo(3));
+ }
+
+ @Test
+ @Order(5)
+ void modifyInstanceGroupsIsValidatedBeforeAnyChange() {
+ // The second modification is rejected, so the first is not applied either.
+ call("ModifyInstanceGroups", "{\"ClusterId\":\"" + groupsClusterId + "\",\"InstanceGroups\":["
+ + "{\"InstanceGroupId\":\"" + coreGroupId + "\",\"InstanceCount\":9},"
+ + "{\"InstanceGroupId\":\"" + masterGroupId + "\",\"InstanceCount\":3}]}")
+ .then().statusCode(400).body("__type", equalTo("InvalidRequestException"));
+ call("ListInstanceGroups", "{\"ClusterId\":\"" + groupsClusterId + "\"}").then().statusCode(200)
+ .body("InstanceGroups.find { it.Id == '" + coreGroupId + "' }.RunningInstanceCount", equalTo(3));
+
+ call("ModifyInstanceGroups", "{\"ClusterId\":\"" + groupsClusterId + "\",\"InstanceGroups\":["
+ + "{\"InstanceGroupId\":\"" + coreGroupId + "\",\"InstanceCount\":-1}]}")
+ .then().statusCode(400).body("__type", equalTo("InvalidRequestException"));
+ call("ModifyInstanceGroups", "{\"InstanceGroups\":[{\"InstanceGroupId\":\"ig-MISSING\",\"InstanceCount\":1}]}")
+ .then().statusCode(400).body("__type", equalTo("InvalidRequestException"));
+ call("ModifyInstanceGroups", "{\"ClusterId\":\"" + groupsClusterId + "\",\"InstanceGroups\":[]}")
+ .then().statusCode(400).body("__type", equalTo("InvalidRequestException"));
+ }
+
+ @Test
+ @Order(6)
+ void modifyInstanceFleetResizes() {
+ Response resp = call("RunJobFlow", "{\"Name\":\"fleets\",\"Instances\":{\"KeepJobFlowAliveWhenNoSteps\":true,"
+ + "\"InstanceFleets\":[{\"InstanceFleetType\":\"MASTER\",\"TargetOnDemandCapacity\":1,"
+ + "\"InstanceTypeConfigs\":[{\"InstanceType\":\"m5.xlarge\"}]},"
+ + "{\"InstanceFleetType\":\"CORE\",\"TargetOnDemandCapacity\":2,\"TargetSpotCapacity\":2,"
+ + "\"InstanceTypeConfigs\":[{\"InstanceType\":\"m5.xlarge\"}]}]}}");
+ resp.then().statusCode(200);
+ fleetClusterId = resp.jsonPath().getString("JobFlowId");
+ Response fleets = call("ListInstanceFleets", "{\"ClusterId\":\"" + fleetClusterId + "\"}");
+ masterFleetId = fleets.jsonPath().getString("InstanceFleets.find { it.InstanceFleetType == 'MASTER' }.Id");
+ coreFleetId = fleets.jsonPath().getString("InstanceFleets.find { it.InstanceFleetType == 'CORE' }.Id");
+
+ call("ModifyInstanceFleet", "{\"ClusterId\":\"" + fleetClusterId + "\",\"InstanceFleet\":"
+ + "{\"InstanceFleetId\":\"" + coreFleetId + "\",\"TargetSpotCapacity\":6}}")
+ .then().statusCode(200);
+ call("ListInstanceFleets", "{\"ClusterId\":\"" + fleetClusterId + "\"}").then().statusCode(200)
+ .body("InstanceFleets.find { it.Id == '" + coreFleetId + "' }.TargetOnDemandCapacity", equalTo(2))
+ .body("InstanceFleets.find { it.Id == '" + coreFleetId + "' }.TargetSpotCapacity", equalTo(6))
+ .body("InstanceFleets.find { it.Id == '" + coreFleetId + "' }.ProvisionedSpotCapacity", equalTo(6));
+ }
+
+ @Test
+ @Order(7)
+ void modifyInstanceFleetIsValidated() {
+ call("ModifyInstanceFleet", "{\"ClusterId\":\"" + fleetClusterId + "\",\"InstanceFleet\":"
+ + "{\"InstanceFleetId\":\"" + masterFleetId + "\",\"TargetOnDemandCapacity\":3}}")
+ .then().statusCode(400).body("__type", equalTo("InvalidRequestException"));
+ call("ModifyInstanceFleet", "{\"ClusterId\":\"" + fleetClusterId + "\",\"InstanceFleet\":"
+ + "{\"InstanceFleetId\":\"" + coreFleetId + "\",\"TargetOnDemandCapacity\":-1}}")
+ .then().statusCode(400).body("__type", equalTo("InvalidRequestException"));
+ call("ModifyInstanceFleet", "{\"ClusterId\":\"" + fleetClusterId + "\",\"InstanceFleet\":"
+ + "{\"InstanceFleetId\":\"if-MISSING\",\"TargetOnDemandCapacity\":1}}")
+ .then().statusCode(400).body("__type", equalTo("InvalidRequestException"));
+ call("ModifyInstanceFleet", "{\"ClusterId\":\"j-MISSING\",\"InstanceFleet\":"
+ + "{\"InstanceFleetId\":\"" + coreFleetId + "\",\"TargetOnDemandCapacity\":1}}")
+ .then().statusCode(400).body("__type", equalTo("InvalidRequestException"));
+ }
+}