feat(cloudformation): provision AWS::EMR::Cluster (#9156)

A template can now create an EMR cluster. It was not served, so the
stack reported CREATE_COMPLETE with nothing behind it. EmrCfnProvisioner
creates it through RunJobFlow, reading the template as RunJobFlow reads
its request, from a method EmrHandler now shares.

- The properties are read as model validation reads them, against the
  registry schema, now in the vendored property types, and a template
  that sets the read-only Id or MasterPublicDNS is refused.
- Ref is the cluster id; Fn::GetAtt gives Id and MasterPublicDNS.
- The master, core and task groups or fleets become RunJobFlow's
  InstanceGroups or InstanceFleets with their roles, a configuration's
  ConfigurationProperties its Properties, and a step's StepProperties
  its Properties. The create completes once the cluster is waiting or
  running, and a cluster that terminates first fails it and is
  terminated again, its termination protection cleared first.
- The properties, and members of Instances, its groups and its fleets,
  that Floci's RunJobFlow keeps nothing of are accepted with a warning,
  and recorded as ignored. Task groups and fleets need unique names, as
  the reference says, and a cluster that ran its steps and ended came
  up, so its create completes.
- An update applies in place what the reference and the update handler
  let change: AutoTerminationPolicy, ManagedScalingPolicy,
  StepConcurrencyLevel, VisibleToAllUsers, TerminationProtected,
  UnhealthyNodeReplacement, a core or task group's InstanceCount and
  AutoScalingPolicy, a core or task fleet's target capacities, and the
  tag keys the stack owns. They are compared with the values the stack
  last applied, resolved, so one a parameter changes counts. Any other
  change, within Instances included, replaces the cluster: the master
  group's count and the master fleet's capacities among them, which
  the API refuses to change.
- A later resource's failure, or a failure of the update itself, puts
  back what it had applied. A terminated cluster fails an update, and a
  termination-protected one refuses the delete, as TerminateJobFlows
  does.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-11-21 17:31:03 -04:00
1 parent 37bf8f90d2
commit 546770ab69
13 files changed
+1548 -38

No files matched your search

@@ -157,6 +157,7 @@ import io.floci.aws.services.elasticache.ElastiCacheMemcachedService;
import io.floci.aws.services.elasticache.ElastiCacheServerlessService;
import io.floci.aws.services.elasticache.ElastiCacheService;
import io.floci.aws.services.elbv2.ElbV2Service;
import io.floci.aws.services.emr.EmrHandler;
import io.floci.aws.services.emr.EmrService;
import io.floci.aws.services.emr.EmrStudioService;
import io.floci.aws.services.emrcontainers.EmrContainersService;
@@ -287,6 +288,7 @@ final class CfnProvisionerFixture {
private SchedulerService schedulerService;
private CodeDeployService codeDeployService;
private EmrService emrService;
private EmrHandler emrHandler;
private EmrStudioService emrStudioService;
private EmrContainersService emrContainersService;
private EmrServerlessService emrServerlessService;
@@ -577,8 +579,8 @@ final class CfnProvisionerFixture {
if (codeDeployService != null) {
discovered.add(new CodeDeployCfnProvisioner(codeDeployService));
}
if (emrService != null) {
discovered.add(new EmrCfnProvisioner(emrService));
if (emrService != null && emrHandler != null) {
discovered.add(new EmrCfnProvisioner(emrService, emrHandler));
}
if (emrStudioService != null) {
discovered.add(new EmrStudioCfnProvisioner(emrStudioService));
@@ -824,6 +826,11 @@ final class CfnProvisionerFixture {
return this;
}
public Builder emrHandler(EmrHandler v) {
this.emrHandler = v;
return this;
}
public Builder emrStudio(EmrStudioService v) {
this.emrStudioService = v;
return this;
@@ -0,0 +1,110 @@
package io.floci.aws.services.cloudformation;
import io.floci.aws.testing.CfnStackWaits;
import io.floci.aws.testing.CfnTestStack;
import io.floci.aws.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.ValidatableResponse;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import software.amazon.awssdk.services.cloudformation.model.Stack;
import static io.floci.aws.testing.CfnStackWaits.output;
import static io.floci.aws.testing.EmrRequests.emr;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasItem;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
/**
* Provisions {@code AWS::EMR::Cluster} through a stack and reads the cluster back through EMR: {@code Ref} and
* {@code Fn::GetAtt} name it once it is waiting, an update resizes the core group, raises the step concurrency and
* retags it in place, a later resource's failure puts those back, a new release label replaces it, and deleting the
* stack terminates it.
*/
@QuarkusTest
class EmrClusterCfnIntegrationTest {
@RegisterExtension
final CfnTestStack stack = new CfnTestStack("emr-cluster-cfn-it");
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@Test
void createResizeRollBackReplaceAndDeleteACluster() {
Stack created = stack.create(template("emr-7.5.0", 2, 1, "v1", false));
String id = output(created, "Ref");
assertEquals(id, output(created, "Id"));
describe(id)
.body("Cluster.Name", equalTo("etl"))
.body("Cluster.Status.State", equalTo("WAITING"))
.body("Cluster.MasterPublicDnsName", equalTo(output(created, "MasterPublicDNS")))
.body("Cluster.Tags.Value", hasItem("v1"));
coreCount(id, 2);
Stack resized = stack.update(template("emr-7.5.0", 3, 2, "v2", false), "UPDATE_COMPLETE");
assertEquals(id, output(resized, "Ref"));
describe(id).body("Cluster.StepConcurrencyLevel", equalTo(2)).body("Cluster.Tags.Value", hasItem("v2"));
coreCount(id, 3);
stack.update(template("emr-7.5.0", 4, 3, "v3", true), "UPDATE_ROLLBACK_COMPLETE");
describe(id).body("Cluster.StepConcurrencyLevel", equalTo(2)).body("Cluster.Tags.Value", hasItem("v2"));
coreCount(id, 3);
// ReleaseLabel replaces the cluster, and the committed update terminates the old one.
Stack replaced = stack.update(template("emr-7.6.0", 3, 2, "v2", false), "UPDATE_COMPLETE");
String replacement = output(replaced, "Ref");
assertNotEquals(id, replacement);
describe(replacement).body("Cluster.ReleaseLabel", equalTo("emr-7.6.0"));
describe(id).body("Cluster.Status.State", equalTo("TERMINATED"));
CfnStackWaits.deleteStack(stack.name());
describe(replacement).body("Cluster.Status.State", equalTo("TERMINATED"));
}
private static String template(String release, int coreCount, int stepConcurrency, String stage,
boolean laterFails) {
return """
{
"Resources": {
"Cluster": {
"Type": "AWS::EMR::Cluster",
"Properties": {
"Name": "etl",
"ReleaseLabel": "%s",
"JobFlowRole": "EMR_EC2_DefaultRole",
"ServiceRole": "EMR_DefaultRole",
"StepConcurrencyLevel": %d,
"Instances": {
"KeepJobFlowAliveWhenNoSteps": true,
"MasterInstanceGroup": {"InstanceCount": 1, "InstanceType": "m5.xlarge"},
"CoreInstanceGroup": {"InstanceCount": %d, "InstanceType": "m5.xlarge"}
},
"Tags": [{"Key": "stage", "Value": "%s"}]
}
}%s
},
"Outputs": {
"Ref": {"Value": {"Ref": "Cluster"}},
"Id": {"Value": {"Fn::GetAtt": ["Cluster", "Id"]}},
"MasterPublicDNS": {"Value": {"Fn::GetAtt": ["Cluster", "MasterPublicDNS"]}}
}
}
""".formatted(release, stepConcurrency, coreCount, stage,
laterFails ? CfnStackWaits.failingResourceAfter("Cluster") : "");
}
private static ValidatableResponse describe(String id) {
return emr("DescribeCluster", "{\"ClusterId\": \"" + id + "\"}").then().statusCode(200);
}
private static void coreCount(String id, int count) {
emr("ListInstanceGroups", "{\"ClusterId\": \"" + id + "\"}").then().statusCode(200)
.body("InstanceGroups.find { it.InstanceGroupType == 'CORE' }.RequestedInstanceCount", equalTo(count));
}
}
@@ -4,19 +4,27 @@ import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.services.cloudformation.model.StackResource;
import io.floci.aws.services.emr.EmrHandler;
import io.floci.aws.services.emr.EmrService;
import io.floci.aws.services.emr.EmrService.InstanceGroupModification;
import io.floci.aws.services.emr.model.EmrCluster;
import io.floci.aws.services.emr.model.EmrInstanceGroup;
import io.floci.aws.services.emr.model.SecurityConfiguration;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static io.floci.aws.services.cloudformation.provisioners.ProvisionContexts.json;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
@@ -25,7 +33,7 @@ import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
/** {@code AWS::EMR::SecurityConfiguration} in isolation, with {@link EmrService} mocked. */
/** {@code AWS::EMR::SecurityConfiguration} and {@code AWS::EMR::Cluster} in isolation, with EMR mocked. */
class EmrCfnProvisionerTest {
private static final ObjectMapper MAPPER = new ObjectMapper();
@@ -33,7 +41,8 @@ class EmrCfnProvisionerTest {
{"EncryptionConfiguration": {"EnableInTransitEncryption": false, "EnableAtRestEncryption": false}}""";
private final EmrService emr = mock(EmrService.class);
private final EmrCfnProvisioner provisioner = new EmrCfnProvisioner(emr);
private final EmrHandler handler = mock(EmrHandler.class);
private final EmrCfnProvisioner provisioner = new EmrCfnProvisioner(emr, handler);
private static ProvisionContext ctx(String priorPhysicalId, String priorProperties) {
return ProvisionContexts.standalone(priorPhysicalId, priorProperties == null ? null : json(priorProperties));
@@ -120,4 +129,204 @@ class EmrCfnProvisionerTest {
verify(emr).deleteSecurityConfiguration("tls", "us-east-1");
verify(emr, never()).deleteSecurityConfiguration(eq("gone"), any());
}
private static final String CLUSTER_ID = "j-ABCDEFGHIJKLM";
private static final String MANAGED_SCALING = """
{"ComputeLimits": {"UnitType": "Instances", "MinimumCapacityUnits": 2, "MaximumCapacityUnits": 6}}""";
/** A cluster template whose core group has {@code coreCount} instances of {@code coreType}. */
private static String clusterProps(int coreCount, String coreType, String extra) {
return """
{"Name": "etl", "ReleaseLabel": "emr-7.5.0", "JobFlowRole": "EMR_EC2_DefaultRole",
"ServiceRole": "EMR_DefaultRole", "Configurations": [{"Classification": "spark-defaults",
"ConfigurationProperties": {"spark.executor.cores": "2"}}],
"Instances": {"TerminationProtected": true,
"MasterInstanceGroup": {"InstanceCount": 1, "InstanceType": "m5.xlarge"},
"CoreInstanceGroup": {"InstanceCount": %d, "InstanceType": "%s"},
"TaskInstanceGroups": [{"Name": "spot", "InstanceCount": 1, "InstanceType": "m5.xlarge"}]},
"Steps": [{"Name": "pi", "ActionOnFailure": "CONTINUE", "HadoopJarStep": {"Jar": "command-runner.jar",
"Args": ["spark-example", "SparkPi"], "StepProperties": [{"Key": "k", "Value": "v"}]}}],
"Tags": [{"Key": "stage", "Value": "v1"}]%s}
""".formatted(coreCount, coreType, extra);
}
private static StackResource cluster(String physicalId) {
StackResource r = resource(physicalId);
r.setLogicalId("Cluster");
r.setResourceType("AWS::EMR::Cluster");
return r;
}
private static EmrCluster emrCluster(String id, String state) {
EmrCluster cluster = new EmrCluster();
cluster.setId(id);
cluster.setState(state);
cluster.setMasterPublicDnsName("ec2-10-0-0-1.compute-1.amazonaws.com");
cluster.setTerminationProtected(true);
cluster.setTags(Map.of("stage", "v1"));
return cluster;
}
private static EmrInstanceGroup group(String id, String type, String name) {
EmrInstanceGroup group = new EmrInstanceGroup();
group.setId(id);
group.setInstanceGroupType(type);
group.setName(name);
return group;
}
/** The cluster as a create of {@code clusterProps(2, "m5.xlarge", "")} left the resource. */
private StackResource created() {
when(handler.clusterFrom(any(), any())).thenReturn(new EmrCluster());
when(emr.runJobFlow(any(), eq("us-east-1"))).thenReturn(emrCluster(CLUSTER_ID, "STARTING"));
when(emr.describeCluster(CLUSTER_ID)).thenReturn(emrCluster(CLUSTER_ID, "WAITING"));
StackResource r = cluster(null);
provisioner.provision(r, json(clusterProps(2, "m5.xlarge", "")), ctx(null, null));
return r;
}
@Test
void createsTheClusterFromTheTemplateInRunJobFlowsMembersOnceItIsReady() {
StackResource r = created();
ArgumentCaptor<JsonNode> request = ArgumentCaptor.forClass(JsonNode.class);
verify(handler).clusterFrom(request.capture(), eq("us-east-1"));
JsonNode sent = request.getValue();
assertEquals("etl", sent.path("Name").asText());
assertEquals(json("{\"spark.executor.cores\": \"2\"}"), sent.path("Configurations").get(0).get("Properties"));
JsonNode groups = sent.path("Instances").path("InstanceGroups");
assertEquals(List.of("MASTER", "CORE", "TASK"),
List.of(groups.get(0).path("InstanceRole").asText(), groups.get(1).path("InstanceRole").asText(),
groups.get(2).path("InstanceRole").asText()));
assertEquals(2, groups.get(1).path("InstanceCount").asInt());
assertTrue(sent.path("Instances").path("TerminationProtected").asBoolean());
assertFalse(sent.path("Instances").has("CoreInstanceGroup"));
assertEquals(json("[{\"Key\": \"k\", \"Value\": \"v\"}]"),
sent.path("Steps").get(0).path("HadoopJarStep").get("Properties"));
assertEquals(CLUSTER_ID, r.getPhysicalId());
assertEquals(CLUSTER_ID, r.getAttributes().get("Id"));
assertEquals("ec2-10-0-0-1.compute-1.amazonaws.com", r.getAttributes().get("MasterPublicDNS"));
assertNotNull(r.getAttributes().get(EmrCfnProvisioner.CLUSTER_SHAPE_ATTR));
}
@Test
void aClusterThatTerminatesBeforeItIsReadyFailsTheCreateAndIsTerminatedAgain() {
when(handler.clusterFrom(any(), any())).thenReturn(new EmrCluster());
when(emr.runJobFlow(any(), eq("us-east-1"))).thenReturn(emrCluster(CLUSTER_ID, "STARTING"));
when(emr.describeCluster(CLUSTER_ID)).thenReturn(emrCluster(CLUSTER_ID, "TERMINATED_WITH_ERRORS"));
AwsException e = assertThrows(AwsException.class, () -> provisioner.provision(cluster(null),
json(clusterProps(2, "m5.xlarge", "")), ctx(null, null)));
assertEquals("NotStabilized", e.getErrorCode());
verify(emr).setTerminationProtection(List.of(CLUSTER_ID), false);
verify(emr).terminateJobFlows(List.of(CLUSTER_ID));
}
@Test
void anUpdateAppliesTheMutableSettingsThatChangedAndARollbackPutsThemBack() {
StackResource r = created();
when(emr.listInstanceGroups(CLUSTER_ID)).thenReturn(List.of(group("ig-M", "MASTER", null),
group("ig-C", "CORE", null), group("ig-T", "TASK", "spot")));
String updated = clusterProps(3, "m5.xlarge", ", \"StepConcurrencyLevel\": 2, \"ManagedScalingPolicy\": "
+ MANAGED_SCALING).replace("\"TerminationProtected\": true", "\"TerminationProtected\": false");
provisioner.provision(r, json(updated), ctx(CLUSTER_ID, clusterProps(2, "m5.xlarge", "")));
assertTrue(provisioner.rollbackUpdate(r));
verify(emr).modifyInstanceGroups(CLUSTER_ID, "us-east-1",
List.of(new InstanceGroupModification("ig-C", 3, null)));
verify(emr).modifyInstanceGroups(CLUSTER_ID, "us-east-1",
List.of(new InstanceGroupModification("ig-C", 2, null)));
verify(emr).setTerminationProtection(List.of(CLUSTER_ID), false);
verify(emr).setTerminationProtection(List.of(CLUSTER_ID), true);
verify(emr).modifyCluster(CLUSTER_ID, 2);
verify(emr).modifyCluster(CLUSTER_ID, 1);
verify(emr).putManagedScalingPolicy(CLUSTER_ID, json(MANAGED_SCALING));
verify(emr).removeManagedScalingPolicy(CLUSTER_ID);
verify(emr, never()).setVisibleToAllUsers(any(), anyBoolean());
assertEquals(CLUSTER_ID, r.getPhysicalId());
assertFalse(r.getAttributes().containsKey(EmrCfnProvisioner.CLUSTER_SNAPSHOT_ATTR));
}
@Test
void anotherCoreInstanceTypeReplacesTheCluster() {
StackResource r = created();
when(emr.runJobFlow(any(), eq("us-east-1"))).thenReturn(emrCluster("j-REPLACEMENT", "STARTING"));
when(emr.describeCluster("j-REPLACEMENT")).thenReturn(emrCluster("j-REPLACEMENT", "WAITING"));
provisioner.provision(r, json(clusterProps(2, "m5.2xlarge", "")), ctx(CLUSTER_ID, clusterProps(2, "m5.xlarge",
"")));
assertEquals("j-REPLACEMENT", r.getPhysicalId());
assertEquals(CLUSTER_ID, provisioner.updateCleanupPhysicalId(r));
}
@Test
void anUpdateOfATerminatedClusterFailsAndATemplateThatSetsItsIdIsRefused() {
StackResource r = created();
when(emr.describeCluster(CLUSTER_ID)).thenReturn(emrCluster(CLUSTER_ID, "TERMINATED"));
AwsException terminated = assertThrows(AwsException.class, () -> provisioner.provision(r,
json(clusterProps(3, "m5.xlarge", "")), ctx(CLUSTER_ID, clusterProps(2, "m5.xlarge", ""))));
AwsException readOnly = assertThrows(AwsException.class, () -> provisioner.provision(cluster(null),
json(clusterProps(2, "m5.xlarge", ", \"Id\": \"j-MINE\"")), ctx(null, null)));
assertEquals("Resource of type 'AWS::EMR::Cluster' with identifier '" + CLUSTER_ID + "' was not found.",
terminated.getMessage());
assertEquals("Id is a ReadOnly property which cannot be specified in the template", readOnly.getMessage());
}
@Test
void aMasterCountChangeReplacesTheClusterAsModifyInstanceGroupsRefusesIt() {
StackResource r = created();
when(emr.runJobFlow(any(), eq("us-east-1"))).thenReturn(emrCluster("j-REPLACEMENT", "STARTING"));
when(emr.describeCluster("j-REPLACEMENT")).thenReturn(emrCluster("j-REPLACEMENT", "WAITING"));
String twoMasters = clusterProps(2, "m5.xlarge", "").replace(
"\"MasterInstanceGroup\": {\"InstanceCount\": 1", "\"MasterInstanceGroup\": {\"InstanceCount\": 3");
provisioner.provision(r, json(twoMasters), ctx(CLUSTER_ID, clusterProps(2, "m5.xlarge", "")));
assertEquals("j-REPLACEMENT", r.getPhysicalId());
verify(emr, never()).modifyInstanceGroups(any(), any(), any());
}
@Test
void taskGroupsWithoutAUniqueNameAreRefused() {
String unnamed = clusterProps(2, "m5.xlarge", "").replace("{\"Name\": \"spot\", ", "{");
String twice = clusterProps(2, "m5.xlarge", "").replace(
"[{\"Name\": \"spot\", \"InstanceCount\": 1, \"InstanceType\": \"m5.xlarge\"}]",
"[{\"Name\": \"spot\", \"InstanceCount\": 1, \"InstanceType\": \"m5.xlarge\"}, "
+ "{\"Name\": \"spot\", \"InstanceCount\": 2, \"InstanceType\": \"m5.xlarge\"}]");
for (String props : List.of(unnamed, twice)) {
AwsException e = assertThrows(AwsException.class,
() -> provisioner.provision(cluster(null), json(props), ctx(null, null)));
assertEquals("Each task instance group must have a unique name specified so that CloudFormation can "
+ "differentiate between the task instance groups.", e.getMessage());
}
verifyNoInteractions(emr);
}
@Test
void aClusterThatRanItsStepsAndEndedCameUpSoTheCreateCompletes() {
when(handler.clusterFrom(any(), any())).thenReturn(new EmrCluster());
when(emr.runJobFlow(any(), eq("us-east-1"))).thenReturn(emrCluster(CLUSTER_ID, "STARTING"));
EmrCluster ended = emrCluster(CLUSTER_ID, "TERMINATED");
ended.setStateChangeReasonCode("ALL_STEPS_COMPLETED");
when(emr.describeCluster(CLUSTER_ID)).thenReturn(ended);
StackResource r = cluster(null);
provisioner.provision(r, json(clusterProps(2, "m5.xlarge", "")), ctx(null, null));
assertEquals(CLUSTER_ID, r.getPhysicalId());
verify(emr, never()).terminateJobFlows(any());
}
@Test
void theClusterDeleteTerminatesIt() {
provisioner.delete("AWS::EMR::Cluster", CLUSTER_ID, "us-east-1");
verify(emr).terminateJobFlows(List.of(CLUSTER_ID));
}
}