diff --git a/docs/services/cloudformation.md b/docs/services/cloudformation.md
index 7814d7607d..57e3f61937 100644
--- a/docs/services/cloudformation.md
+++ b/docs/services/cloudformation.md
@@ -220,7 +220,7 @@ cross-resource references.
| ECS | `Cluster`, `TaskDefinition`, `Service`, `CapacityProvider`, `ClusterCapacityProviderAssociations` |
| EFS | `FileSystem` (metadata only, there is no NFS data plane), `MountTarget` (`SecurityGroups` update in place, every other property replaces), `AccessPoint` (`AccessPointTags` update in place, every other property replaces) |
| EKS | `Cluster` (created with `Name`, `Version`, `RoleArn`, `Tags`, `EncryptionConfig`, `ResourcesVpcConfig`, `Logging`, `AccessConfig` and `KubernetesNetworkConfig.IpFamily` and `ServiceIpv4Cidr`, a replacement included; a change to `EncryptionConfig`, `IpFamily` or `ServiceIpv4Cidr` replaces the cluster with the new value applied; `ElasticLoadBalancing`, `ServiceIpv6Cidr` and `ResourcesVpcConfig.ControlPlaneEgressMode` are accepted and ignored; updated in place for `Tags`, keeping tags added outside the stack, for `Logging`, for `AccessConfig.AuthenticationMode` (a mode cannot be moved back, so a stack update that does so fails, and a stack rollback restores it) and for `ResourcesVpcConfig` endpoint access and `PublicAccessCidrs`; a change to `Name`, `RoleArn`, `EncryptionConfig`, `BootstrapSelfManagedAddons`, `OutpostConfig`, `AccessConfig.BootstrapClusterCreatorAdminPermissions`, `KubernetesNetworkConfig.IpFamily` or `KubernetesNetworkConfig.ServiceIpv4Cidr` replaces the cluster, as the registry marks them create-only, and deletes the old one once the update commits; a change to `Version` is accepted with a warning and not applied, as the emulator has no `UpdateClusterVersion`; a change to the subnets or security groups of `ResourcesVpcConfig` fails the resource, as the emulator's `UpdateClusterConfig` does not change them), `Nodegroup` (created with `ClusterName`, `NodegroupName`, `NodeRole`, `Subnets` and `Tags`; updated in place for `Tags`, keeping tags added outside the stack; a change to `ClusterName`, `NodegroupName`, `NodeRole`, `Subnets`, `AmiType`, `CapacityType`, `DiskSize`, `InstanceTypes` or `RemoteAccess` replaces the nodegroup, as the registry marks them create-only, and deletes the old one once the update commits; `ScalingConfig`, `Labels`, `Taints`, `UpdateConfig`, `Version`, `ReleaseVersion`, `ForceUpdateEnabled`, `LaunchTemplate`, `NodeRepairConfig` and `WarmPoolConfig` are accepted and not applied, whether changed or dropped, with a warning, as the emulator cannot update a nodegroup in place) |
-| EMR | `SecurityConfiguration` (created with `Name`, generated when the template gives none, and the `SecurityConfiguration` JSON, as an object or its text; both are create-only, so any change replaces it and deletes the old one once the update commits, and a change that keeps a template's own `Name` is refused, as for every custom-named resource), `Studio` (created with every property; a template that sets the read-only `Arn`, `StudioId` or `Url` is refused; updated in place through `UpdateStudio` for `Name`, `Description`, `SubnetIds` and `DefaultS3Location`, a dropped setting kept as it is, and for `Tags`, keeping tags added outside the stack; a change to `IdpAuthUrl` or `IdpRelayStateParameterName` is accepted with a warning and not applied, as no Studio API changes them; a rollback puts back the name, description, location and tags, but not subnets an update added, which `UpdateStudio` cannot take away; a change to a create-only property replaces the Studio and deletes the old one once the update commits), `StudioSessionMapping` (`Ref` is `StudioId|IdentityType|IdentityName`, the schema's primary identifier; `SessionPolicyArn` updates in place, and a change to any of the three others replaces the mapping) |
+| EMR | `Cluster` (created through `RunJobFlow`, once it is waiting or running, its master, core and task groups or fleets as `RunJobFlow`'s `InstanceGroups` or `InstanceFleets`; `AdditionalInfo`, `KerberosAttributes`, `OSReleaseLabel`, `EbsRootVolumeIops`, `EbsRootVolumeThroughput`, `PlacementGroupConfigs`, `LogEncryptionKmsKeyId` and `MonitoringConfiguration`, `Instances`' `Ec2SubnetIds`, additional security groups and `HadoopVersion`, a group's `EbsConfiguration` and `CustomAmiId` and a fleet's launch and resize specifications are accepted with a warning and not stored; task groups and fleets need unique names; a template that sets the read-only `Id` or `MasterPublicDNS` is refused; updated in place for `AutoTerminationPolicy`, `ManagedScalingPolicy`, `StepConcurrencyLevel`, `VisibleToAllUsers`, `Tags` (keeping tags added outside the stack), `TerminationProtected`, `UnhealthyNodeReplacement`, a core or task group's `InstanceCount` and `AutoScalingPolicy` and a core or task fleet's target capacities, a dropped one taking its default; any other change, within `Instances` included, replaces the cluster and terminates the old one once the update commits; a termination-protected cluster refuses the delete), `SecurityConfiguration` (created with `Name`, generated when the template gives none, and the `SecurityConfiguration` JSON, as an object or its text; both are create-only, so any change replaces it and deletes the old one once the update commits, and a change that keeps a template's own `Name` is refused, as for every custom-named resource), `Studio` (created with every property; a template that sets the read-only `Arn`, `StudioId` or `Url` is refused; updated in place through `UpdateStudio` for `Name`, `Description`, `SubnetIds` and `DefaultS3Location`, a dropped setting kept as it is, and for `Tags`, keeping tags added outside the stack; a change to `IdpAuthUrl` or `IdpRelayStateParameterName` is accepted with a warning and not applied, as no Studio API changes them; a rollback puts back the name, description, location and tags, but not subnets an update added, which `UpdateStudio` cannot take away; a change to a create-only property replaces the Studio and deletes the old one once the update commits), `StudioSessionMapping` (`Ref` is `StudioId|IdentityType|IdentityName`, the schema's primary identifier; `SessionPolicyArn` updates in place, and a change to any of the three others replaces the mapping) |
| EMR on EKS | `VirtualCluster` (created with `Name`, `ContainerProvider`, `SecurityConfigurationId`, `SessionEnabled` and `Tags`; a template that sets the read-only `Arn` or `Id` is refused; updated in place for `Tags` alone, which end as the template lists them, any other but an `aws:` one removed; a change to any other property replaces the virtual cluster, as the registry marks them create-only, and terminates the old one once the update commits; an update of a virtual cluster that is terminated or gone fails) |
| EMR Serverless | `Application` (created with every property, `Name` and `Type` included; updated in place through `UpdateApplication` for the settings a template changes, a dropped setting kept as it is but for `InitialCapacity`, which is cleared, and for `Tags`, which end as the template lists them, any other removed; a change to `Name` or `Type` replaces the application and deletes the old one once the update commits; neither an update nor a delete stops a `STARTED` application, so one it refuses fails the resource, as on AWS) |
| RDS | `DBInstance` (starts a real container), `DBCluster` (starts a real container), `DBSubnetGroup`, `DBParameterGroup`, `DBClusterParameterGroup`, `DBProxy`, `DBProxyTargetGroup` |
diff --git a/src/main/java/io/floci/aws/services/cloudformation/provisioners/EmrCfnProvisioner.java b/src/main/java/io/floci/aws/services/cloudformation/provisioners/EmrCfnProvisioner.java
index 5156ddbf6a..d6672a4213 100644
--- a/src/main/java/io/floci/aws/services/cloudformation/provisioners/EmrCfnProvisioner.java
+++ b/src/main/java/io/floci/aws/services/cloudformation/provisioners/EmrCfnProvisioner.java
@@ -1,41 +1,112 @@
package io.floci.aws.services.cloudformation.provisioners;
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.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.EmrInstanceFleet;
+import io.floci.aws.services.emr.model.EmrInstanceGroup;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
+import org.jboss.logging.Logger;
+import java.time.Duration;
+import java.time.Instant;
+import java.util.ArrayList;
+import java.util.Collection;
import java.util.HashMap;
+import java.util.HashSet;
+import java.util.LinkedHashMap;
+import java.util.List;
import java.util.Map;
+import java.util.Objects;
import java.util.Set;
+import java.util.concurrent.atomic.AtomicBoolean;
/**
- * CloudFormation provisioning for Amazon EMR's own types over {@link EmrService}: for now
- * {@code AWS::EMR::SecurityConfiguration}, whose {@code Ref} is its name and which has no {@code Fn::GetAtt}
- * attributes.
+ * CloudFormation provisioning for Amazon EMR's own types over {@link EmrService}:
+ * {@code AWS::EMR::SecurityConfiguration} and {@code AWS::EMR::Cluster}. No AWS handler for these types is public, so
+ * each follows its schema, the template reference and the API it calls.
*
*
Both of a security configuration's properties are create-only and its schema has no update handler, so any change
* replaces it: under a new name, generated when the template gives none, and refused, as for every custom-named
- * resource, when the template keeps its own name. The {@code SecurityConfiguration} JSON is taken as an object or as
- * the text of one, as the schema allows both.
+ * resource, when the template keeps its own name. Its {@code Ref} is its name, and the {@code SecurityConfiguration}
+ * JSON is taken as an object or as the text of one, as the schema allows both.
+ *
+ *
A cluster's {@code Ref} is its id; {@code Fn::GetAtt} gives {@code Id} and {@code MasterPublicDNS}. It is created
+ * through RunJobFlow, from the template in RunJobFlow's own members: the master, core and task groups or fleets become
+ * {@code InstanceGroups} or {@code InstanceFleets} with their roles, a configuration's {@code ConfigurationProperties}
+ * its {@code Properties}, and a step's {@code StepProperties} its {@code Properties}. The create completes once the
+ * cluster is waiting or running, as CloudFormation's does, and fails when it terminates first.
+ *
+ *
The reference marks every cluster property but {@code Instances}, {@code AutoTerminationPolicy},
+ * {@code ManagedScalingPolicy}, {@code StepConcurrencyLevel}, {@code VisibleToAllUsers} and {@code Tags} as replacing
+ * the cluster, and says of its instance groups and fleets that, "After creating the cluster, you can only modify the
+ * mutable properties", a group's {@code AutoScalingPolicy} and {@code InstanceCount} and a fleet's
+ * {@code TargetOnDemandCapacity} and {@code TargetSpotCapacity}: "Modifying any other property results in cluster
+ * replacement". The update handler's permissions add {@code TerminationProtected} and
+ * {@code UnhealthyNodeReplacement}, which their own calls change, so any other change to {@code Instances} replaces the
+ * cluster too. Those mutable settings are compared with the ones the stack last applied, resolved, so one a parameter
+ * changes counts; the ones that changed are applied in place, a dropped one taking its default and a dropped policy
+ * being removed, and only the tag keys the stack set are its to change or drop. A later resource's failure, or a
+ * failure of the update itself, puts back what it had applied.
*/
@ApplicationScoped
public class EmrCfnProvisioner implements CfnResourceProvisioner {
+ private static final Logger LOG = Logger.getLogger(EmrCfnProvisioner.class);
private static final String SECURITY_CONFIGURATION = "AWS::EMR::SecurityConfiguration";
+ private static final String CLUSTER = "AWS::EMR::Cluster";
private static final int NAME_MAX_LENGTH = 255;
+ /** What an in-place cluster update is about to change, for {@link #rollbackUpdate} to put back. */
+ static final String CLUSTER_SNAPSHOT_ATTR = "__FlociEmrClusterUpdateSnapshot";
+ /** The tag keys the template that provisioned the cluster set: the next update drops the ones it omits. */
+ static final String CLUSTER_TAG_KEYS_ATTR = "__FlociEmrClusterTagKeys";
+ /** The resolved {@code Instances} without its mutable settings: a change to it replaces the cluster. */
+ static final String CLUSTER_SHAPE_ATTR = "__FlociEmrClusterInstancesShape";
+ /** The resolved mutable settings the stack last applied, which an update is compared with. */
+ static final String CLUSTER_APPLIED_ATTR = "__FlociEmrClusterAppliedSettings";
+ private static final ObjectMapper MAPPER = new ObjectMapper();
+ private static final List CLUSTER_READ_ONLY = List.of("Id", "MasterPublicDNS");
+ /** The cluster properties RunJobFlow takes as the template writes them. */
+ private static final List RUN_JOB_FLOW_MEMBERS = List.of("Name", "ReleaseLabel", "LogUri", "ServiceRole",
+ "JobFlowRole", "AutoScalingRole", "ScaleDownBehavior", "SecurityConfiguration", "CustomAmiId",
+ "VisibleToAllUsers", "StepConcurrencyLevel", "EbsRootVolumeSize", "Applications", "BootstrapActions",
+ "ManagedScalingPolicy", "AutoTerminationPolicy", "SessionEnabled", "Tags");
+ /** The cluster properties Floci's RunJobFlow keeps nothing of: accepted with a warning and not stored. */
+ private static final List CLUSTER_NOT_STORED = List.of("AdditionalInfo", "KerberosAttributes",
+ "OSReleaseLabel", "EbsRootVolumeIops", "EbsRootVolumeThroughput", "PlacementGroupConfigs",
+ "LogEncryptionKmsKeyId", "MonitoringConfiguration");
+ /** The members of {@code Instances} Floci's RunJobFlow keeps nothing of, accepted with a warning. */
+ private static final List INSTANCES_NOT_STORED = List.of("Ec2SubnetIds", "AdditionalMasterSecurityGroups",
+ "AdditionalSlaveSecurityGroups", "HadoopVersion");
+ /** The members of an instance group, and of an instance fleet, Floci's RunJobFlow keeps nothing of. */
+ private static final List GROUP_NOT_STORED = List.of("EbsConfiguration", "CustomAmiId");
+ private static final List FLEET_NOT_STORED = List.of("LaunchSpecifications", "ResizeSpecifications");
+ private static final String GROUPS = "groups";
+ private static final String FLEETS = "fleets";
+ private static final Duration READY_TIMEOUT = Duration.ofMinutes(15);
+ private static final Set READY = Set.of("WAITING", "RUNNING");
+ private static final Set ENDED = Set.of("TERMINATING", "TERMINATED", "TERMINATED_WITH_ERRORS");
private final EmrService emrService;
+ private final EmrHandler emrHandler;
@Inject
- public EmrCfnProvisioner(EmrService emrService) {
+ public EmrCfnProvisioner(EmrService emrService, EmrHandler emrHandler) {
this.emrService = emrService;
+ this.emrHandler = emrHandler;
}
@Override
public Set resourceTypes() {
- return Set.of(SECURITY_CONFIGURATION);
+ return Set.of(SECURITY_CONFIGURATION, CLUSTER);
}
@Override
@@ -50,49 +121,554 @@ public class EmrCfnProvisioner implements CfnResourceProvisioner {
@Override
public UpdateCleanupResult completeUpdate(StackResource resource) {
+ resource.getAttributes().remove(CLUSTER_SNAPSHOT_ATTR);
return ReplacementCleanup.complete(resource, this::delete);
}
+ /**
+ * An in-place update whose own undo failed leaves its snapshot on the attempted resource, which the engine discards
+ * for the previous one: carried over, it lets ContinueUpdateRollback try the restore again.
+ */
+ @Override
+ public void mergeFailedUpdateResourceTracking(StackResource previous, StackResource attempted) {
+ CfnRollback.carryFailedUndoSnapshot(previous, attempted, CLUSTER_SNAPSHOT_ATTR);
+ }
+
@Override
public void clearUpdate(StackResource resource) {
+ resource.getAttributes().remove(CLUSTER_SNAPSHOT_ATTR);
ReplacementCleanup.clear(resource);
}
+ /**
+ * A replacement or a stub migration is undone through the cleanup record, and an in-place cluster update from the
+ * snapshot taken before it, which is spent only once the restore succeeded.
+ */
@Override
public boolean rollbackUpdate(StackResource resource) {
- return ReplacementCleanup.rollback(resource, this::delete);
+ if (ReplacementCleanup.rollback(resource, this::delete)) {
+ return true;
+ }
+ JsonNode snapshot = CfnRollback.updateSnapshot(resource, CLUSTER_SNAPSHOT_ATTR);
+ if (snapshot == null) {
+ return false;
+ }
+ Set every = new HashSet<>();
+ snapshot.path("settings").fieldNames().forEachRemaining(every::add);
+ restoreCluster(snapshot, every, true);
+ Ec2Tags.restoreRecord(resource, CLUSTER_TAG_KEYS_ATTR, snapshot.path("tags"));
+ // What the stack applied before this update, which the next update is compared with.
+ resource.getAttributes().put(CLUSTER_APPLIED_ATTR, snapshot.path("appliedBefore").asText());
+ resource.getAttributes().remove(CLUSTER_SNAPSHOT_ATTR);
+ return true;
}
@Override
public void provision(StackResource r, JsonNode props, ProvisionContext ctx) {
+ r.getAttributes().remove(CLUSTER_SNAPSHOT_ATTR);
if (ctx.isUpdate()) {
ReplacementCleanup.endRollbackRetry(r);
}
Map attributesBefore = new HashMap<>(r.getAttributes());
- JsonNode template = new CfnPropertyTypes.HandlerReader(ctx.engine()).read(SECURITY_CONFIGURATION, props);
- String explicitName = template.path("Name").textValue();
boolean stub = CfnResourceDispatcher.isStub(ctx.priorPhysicalId(), attributesBefore);
- if (ctx.isUpdate() && !stub && !ctx.changes(SECURITY_CONFIGURATION, props).requiresReplacement()) {
- r.setPhysicalId(ctx.priorPhysicalId());
- } else {
- if (ctx.isUpdate() && !stub && explicitName != null && explicitName.equals(ctx.priorPhysicalId())) {
- throw CfnExceptions.customNamedReplacement(explicitName);
- }
- String name = explicitName != null ? explicitName
- : ctx.generatePhysicalName(r.getLogicalId(), NAME_MAX_LENGTH, false);
- JsonNode configuration = template.path("SecurityConfiguration");
- emrService.createSecurityConfiguration(name,
- configuration.isTextual() ? configuration.textValue() : configuration.toString(), ctx.region());
- r.setPhysicalId(name);
+ switch (r.getResourceType()) {
+ case SECURITY_CONFIGURATION -> provisionSecurityConfiguration(r, props, ctx, stub);
+ case CLUSTER -> provisionCluster(r, props, ctx, stub);
+ default -> throw new IllegalStateException("EmrCfnProvisioner cannot provision " + r.getResourceType());
}
ReplacementCleanup.record(r, ctx, attributesBefore);
}
- /** Deletes the security configuration, unless the Region lists none of that name, it being gone. */
+ private void provisionSecurityConfiguration(StackResource r, JsonNode props, ProvisionContext ctx, boolean stub) {
+ JsonNode template = new CfnPropertyTypes.HandlerReader(ctx.engine()).read(SECURITY_CONFIGURATION, props);
+ String explicitName = template.path("Name").textValue();
+ if (ctx.isUpdate() && !stub && !ctx.changes(SECURITY_CONFIGURATION, props).requiresReplacement()) {
+ r.setPhysicalId(ctx.priorPhysicalId());
+ return;
+ }
+ if (ctx.isUpdate() && !stub && explicitName != null && explicitName.equals(ctx.priorPhysicalId())) {
+ throw CfnExceptions.customNamedReplacement(explicitName);
+ }
+ String name = explicitName != null ? explicitName
+ : ctx.generatePhysicalName(r.getLogicalId(), NAME_MAX_LENGTH, false);
+ JsonNode configuration = template.path("SecurityConfiguration");
+ emrService.createSecurityConfiguration(name,
+ configuration.isTextual() ? configuration.textValue() : configuration.toString(), ctx.region());
+ r.setPhysicalId(name);
+ }
+
+ // ──────────────────────────── Cluster ────────────────────────────
+
+ private void provisionCluster(StackResource r, JsonNode props, ProvisionContext ctx, boolean stub) {
+ JsonNode template = new CfnPropertyTypes.HandlerReader(ctx.engine()).read(CLUSTER, props);
+ for (String readOnly : CLUSTER_READ_ONLY) {
+ if (template.has(readOnly)) {
+ throw new AwsException("InvalidRequest",
+ readOnly + " is a ReadOnly property which cannot be specified in the template", 400);
+ }
+ }
+ requireUniqueTaskNames(template.path("Instances"));
+ Map tags = new LinkedHashMap<>();
+ template.path("Tags").forEach(tag -> tags.put(tag.path("Key").asText(), tag.path("Value").asText()));
+ String shape = instancesShape(template.path("Instances")).toString();
+ ObjectNode applied = mutableSettings(template);
+ boolean inPlace = ctx.isUpdate() && !stub && !ctx.changes(CLUSTER, props).requiresReplacement()
+ && shape.equals(r.getAttributes().get(CLUSTER_SHAPE_ATTR));
+ if (inPlace) {
+ updateClusterInPlace(r, ctx, applied, tags);
+ } else {
+ warnNotStored(r.getLogicalId(), template);
+ EmrCluster created = emrService.runJobFlow(emrHandler.clusterFrom(runJobFlowRequest(template),
+ ctx.region()), ctx.region());
+ r.setPhysicalId(created.getId());
+ r.getAttributes().put("Id", created.getId());
+ // A cluster that terminates, or never gets ready, before the create completes is terminated again, its
+ // termination protection cleared first, as TerminateJobFlows refuses a protected cluster.
+ List createdIds = List.of(created.getId());
+ CfnRollback.guarded(r, ctx, true, () -> {
+ emrService.setTerminationProtection(createdIds, false);
+ emrService.terminateJobFlows(createdIds);
+ }, () -> { }, () -> publishCluster(r, awaitReady(created.getId())));
+ Ec2Tags.recordKeys(r, CLUSTER_TAG_KEYS_ATTR, tags);
+ }
+ r.getAttributes().put(CLUSTER_SHAPE_ATTR, shape);
+ r.getAttributes().put(CLUSTER_APPLIED_ATTR, applied.toString());
+ }
+
+ /**
+ * The reference's rule for task groups and fleets: "Each task instance group must have a unique name specified so
+ * that CloudFormation can differentiate between the task instance groups", and the same of fleets. An update
+ * matches them up by it.
+ */
+ private static void requireUniqueTaskNames(JsonNode instances) {
+ for (String member : List.of("TaskInstanceGroups", "TaskInstanceFleets")) {
+ Set names = new HashSet<>();
+ for (JsonNode task : instances.path(member)) {
+ String name = task.path("Name").asText("");
+ if (name.isBlank() || !names.add(name)) {
+ String kind = member.endsWith("Groups") ? "group" : "fleet";
+ throw new AwsException("InvalidRequest", "Each task instance " + kind + " must have a unique "
+ + "name specified so that CloudFormation can differentiate between the task instance "
+ + kind + "s.", 400);
+ }
+ }
+ }
+ }
+
+ /** Warns of each property, or member of {@code Instances}, its groups or fleets, RunJobFlow keeps nothing of. */
+ private static void warnNotStored(String logicalId, JsonNode template) {
+ List ignored = new ArrayList<>();
+ for (String name : CLUSTER_NOT_STORED) {
+ if (template.has(name)) {
+ ignored.add(name);
+ }
+ }
+ JsonNode instances = template.path("Instances");
+ for (String name : INSTANCES_NOT_STORED) {
+ if (instances.has(name)) {
+ ignored.add("Instances." + name);
+ }
+ }
+ List groups = new ArrayList<>(List.of(instances.path("MasterInstanceGroup"),
+ instances.path("CoreInstanceGroup")));
+ instances.path("TaskInstanceGroups").forEach(groups::add);
+ List fleets = new ArrayList<>(List.of(instances.path("MasterInstanceFleet"),
+ instances.path("CoreInstanceFleet")));
+ instances.path("TaskInstanceFleets").forEach(fleets::add);
+ for (String name : GROUP_NOT_STORED) {
+ if (groups.stream().anyMatch(group -> group.has(name))) {
+ ignored.add("an instance group's " + name);
+ }
+ }
+ for (String name : FLEET_NOT_STORED) {
+ if (fleets.stream().anyMatch(fleet -> fleet.has(name))) {
+ ignored.add("an instance fleet's " + name);
+ }
+ }
+ if (!ignored.isEmpty()) {
+ LOG.warnv("EMR cluster {0}: {1} accepted and not stored", logicalId, String.join(", ", ignored));
+ }
+ }
+
+ /** The RunJobFlow request the template describes, in RunJobFlow's own members. */
+ private static ObjectNode runJobFlowRequest(JsonNode template) {
+ ObjectNode request = MAPPER.createObjectNode();
+ for (String name : RUN_JOB_FLOW_MEMBERS) {
+ if (template.has(name)) {
+ request.set(name, template.get(name));
+ }
+ }
+ if (template.has("Configurations")) {
+ request.set("Configurations", configurations(template.get("Configurations")));
+ }
+ if (template.has("Steps")) {
+ ArrayNode steps = request.putArray("Steps");
+ template.get("Steps").forEach(step -> {
+ ObjectNode copy = step.deepCopy();
+ JsonNode jar = copy.path("HadoopJarStep");
+ if (jar instanceof ObjectNode hadoop && hadoop.has("StepProperties")) {
+ hadoop.set("Properties", hadoop.remove("StepProperties"));
+ }
+ steps.add(copy);
+ });
+ }
+ ObjectNode instances = template.get("Instances") instanceof ObjectNode given ? given.deepCopy()
+ : MAPPER.createObjectNode();
+ ArrayNode groups = MAPPER.createArrayNode();
+ ArrayNode fleets = MAPPER.createArrayNode();
+ addRole(groups, "InstanceRole", "MASTER", instances.remove("MasterInstanceGroup"));
+ addRole(groups, "InstanceRole", "CORE", instances.remove("CoreInstanceGroup"));
+ instances.path("TaskInstanceGroups").forEach(group -> addRole(groups, "InstanceRole", "TASK", group));
+ instances.remove("TaskInstanceGroups");
+ addRole(fleets, "InstanceFleetType", "MASTER", instances.remove("MasterInstanceFleet"));
+ addRole(fleets, "InstanceFleetType", "CORE", instances.remove("CoreInstanceFleet"));
+ instances.path("TaskInstanceFleets").forEach(fleet -> addRole(fleets, "InstanceFleetType", "TASK", fleet));
+ instances.remove("TaskInstanceFleets");
+ if (!groups.isEmpty()) {
+ instances.set("InstanceGroups", groups);
+ }
+ if (!fleets.isEmpty()) {
+ instances.set("InstanceFleets", fleets);
+ }
+ request.set("Instances", instances);
+ return request;
+ }
+
+ private static void addRole(ArrayNode into, String roleMember, String role, JsonNode config) {
+ if (config == null || !config.isObject()) {
+ return;
+ }
+ ObjectNode copy = ((ObjectNode) config).deepCopy();
+ copy.put(roleMember, role);
+ if (copy.has("Configurations")) {
+ copy.set("Configurations", configurations(copy.get("Configurations")));
+ }
+ copy.path("InstanceTypeConfigs").forEach(type -> {
+ if (type instanceof ObjectNode typeConfig && typeConfig.has("Configurations")) {
+ typeConfig.set("Configurations", configurations(typeConfig.get("Configurations")));
+ }
+ });
+ into.add(copy);
+ }
+
+ /** Configurations as the API names them: the template's {@code ConfigurationProperties} are {@code Properties}. */
+ private static ArrayNode configurations(JsonNode list) {
+ ArrayNode out = MAPPER.createArrayNode();
+ list.forEach(configuration -> {
+ ObjectNode copy = MAPPER.createObjectNode();
+ if (configuration.has("Classification")) {
+ copy.set("Classification", configuration.get("Classification"));
+ }
+ if (configuration.has("ConfigurationProperties")) {
+ copy.set("Properties", configuration.get("ConfigurationProperties"));
+ }
+ if (configuration.has("Configurations")) {
+ copy.set("Configurations", configurations(configuration.get("Configurations")));
+ }
+ out.add(copy);
+ });
+ return out;
+ }
+
+ /**
+ * {@code Instances} without what an update can change in place, task groups and fleets keyed by name. The master
+ * group's count and the master fleet's capacities stay, as ModifyInstanceGroups and ModifyInstanceFleet refuse to
+ * change them, so a change to either replaces the cluster.
+ */
+ private static JsonNode instancesShape(JsonNode instances) {
+ ObjectNode shape = instances.isObject() ? ((ObjectNode) instances).deepCopy() : MAPPER.createObjectNode();
+ shape.remove(List.of("TerminationProtected", "UnhealthyNodeReplacement"));
+ if (shape.get("CoreInstanceGroup") instanceof ObjectNode core) {
+ core.remove(List.of("InstanceCount", "AutoScalingPolicy"));
+ }
+ if (shape.get("CoreInstanceFleet") instanceof ObjectNode core) {
+ core.remove(List.of("TargetOnDemandCapacity", "TargetSpotCapacity"));
+ }
+ shape.set("TaskInstanceGroups", byName(shape.remove("TaskInstanceGroups"), "InstanceCount",
+ "AutoScalingPolicy"));
+ shape.set("TaskInstanceFleets", byName(shape.remove("TaskInstanceFleets"), "TargetOnDemandCapacity",
+ "TargetSpotCapacity"));
+ return shape;
+ }
+
+ private static ObjectNode byName(JsonNode list, String... mutable) {
+ ObjectNode byName = MAPPER.createObjectNode();
+ if (list != null) {
+ list.forEach(config -> {
+ ObjectNode copy = ((ObjectNode) config).deepCopy();
+ copy.remove(List.of(mutable));
+ byName.set(config.path("Name").asText(), copy);
+ });
+ }
+ return byName;
+ }
+
+ /**
+ * The mutable settings the template gives, resolved, a dropped one at its default: protection and node replacement
+ * off, visible to all users, one step at a time, and no scaling or termination policy.
+ */
+ private static ObjectNode mutableSettings(JsonNode template) {
+ JsonNode instances = template.path("Instances");
+ ObjectNode settings = MAPPER.createObjectNode();
+ settings.put("TerminationProtected", instances.path("TerminationProtected").asBoolean(false));
+ settings.put("UnhealthyNodeReplacement", instances.path("UnhealthyNodeReplacement").asBoolean(false));
+ settings.put("VisibleToAllUsers", template.path("VisibleToAllUsers").asBoolean(true));
+ settings.put("StepConcurrencyLevel", template.path("StepConcurrencyLevel").asInt(1));
+ settings.set("ManagedScalingPolicy", template.get("ManagedScalingPolicy"));
+ settings.set("AutoTerminationPolicy", template.get("AutoTerminationPolicy"));
+ ObjectNode groups = settings.putObject(GROUPS);
+ putGroup(groups, "CORE", instances.get("CoreInstanceGroup"));
+ instances.path("TaskInstanceGroups").forEach(group -> putGroup(groups, "TASK:" + group.path("Name").asText(),
+ group));
+ ObjectNode fleets = settings.putObject(FLEETS);
+ putFleet(fleets, "CORE", instances.get("CoreInstanceFleet"));
+ instances.path("TaskInstanceFleets").forEach(fleet -> putFleet(fleets, "TASK:" + fleet.path("Name").asText(),
+ fleet));
+ return settings;
+ }
+
+ private static void putGroup(ObjectNode groups, String key, JsonNode config) {
+ if (config != null && config.isObject()) {
+ ObjectNode group = groups.putObject(key);
+ group.put("InstanceCount", config.path("InstanceCount").asInt());
+ group.set("AutoScalingPolicy", config.get("AutoScalingPolicy"));
+ }
+ }
+
+ private static void putFleet(ObjectNode fleets, String key, JsonNode config) {
+ if (config != null && config.isObject()) {
+ ObjectNode fleet = fleets.putObject(key);
+ fleet.put("TargetOnDemandCapacity", config.path("TargetOnDemandCapacity").asInt(0));
+ fleet.put("TargetSpotCapacity", config.path("TargetSpotCapacity").asInt(0));
+ }
+ }
+
+ /**
+ * The in-place update of the cluster the prior physical id names, which fails when it has terminated or is gone.
+ * The settings that differ from the ones the stack last applied are snapshotted at those values, and the owned tags
+ * at the cluster's, so a later resource's failure puts them back; a failure here puts back the ones it had applied.
+ */
+ private void updateClusterInPlace(StackResource r, ProvisionContext ctx, ObjectNode desired,
+ Map tags) {
+ String id = ctx.priorPhysicalId();
+ EmrCluster live = liveCluster(id);
+ JsonNode last = CfnRollback.updateSnapshot(r, CLUSTER_APPLIED_ATTR);
+ ObjectNode prior = MAPPER.createObjectNode();
+ Map changed = changedSettings(last == null ? desired : last, desired, prior);
+ Set owned = Ec2Tags.ownedKeys(r, CLUSTER_TAG_KEYS_ATTR, ctx);
+ ObjectNode snapshot = MAPPER.createObjectNode();
+ snapshot.put("clusterId", id);
+ snapshot.put("region", ctx.region());
+ snapshot.set("settings", prior);
+ snapshot.put("appliedBefore", last == null ? desired.toString() : last.toString());
+ Ec2Tags.snapshotOwned(snapshot.putObject("tags"), owned, tags,
+ live.getTags() == null ? Map.of() : live.getTags(), r.getAttributes().get(CLUSTER_TAG_KEYS_ATTR));
+ publishCluster(r, live);
+ r.getAttributes().put(CLUSTER_SNAPSHOT_ATTR, snapshot.toString());
+ Set applied = new HashSet<>();
+ AtomicBoolean tagsTouched = new AtomicBoolean();
+ CfnRollback.guarded(r, ctx, false, () -> { },
+ () -> restoreCluster(snapshot, applied, tagsTouched.get()), () -> {
+ for (Map.Entry setting : changed.entrySet()) {
+ apply(id, ctx.region(), setting.getKey(), setting.getValue());
+ applied.add(setting.getKey());
+ }
+ tagsTouched.set(true);
+ reconcileTags(id, Ec2Tags.touched(owned, tags), tags);
+ Ec2Tags.recordKeys(r, CLUSTER_TAG_KEYS_ATTR, tags);
+ });
+ }
+
+ /**
+ * The settings whose desired value differs from the last applied one, keyed as {@link #apply} takes them, with the
+ * last applied value of each put in {@code prior}. A group or fleet the update names but the last did not is a
+ * change to {@code Instances}' shape, which replaces the cluster, so it is not met here.
+ */
+ private static Map changedSettings(JsonNode last, JsonNode desired, ObjectNode prior) {
+ Map changed = new LinkedHashMap<>();
+ for (String name : List.of("TerminationProtected", "UnhealthyNodeReplacement", "VisibleToAllUsers",
+ "StepConcurrencyLevel", "ManagedScalingPolicy", "AutoTerminationPolicy")) {
+ compare(changed, prior, name, last.get(name), desired.get(name));
+ }
+ desired.path(GROUPS).properties().forEach(group -> {
+ JsonNode before = last.path(GROUPS).path(group.getKey());
+ compare(changed, prior, "group:" + group.getKey() + ":InstanceCount", before.get("InstanceCount"),
+ group.getValue().get("InstanceCount"));
+ compare(changed, prior, "group:" + group.getKey() + ":AutoScalingPolicy", before.get("AutoScalingPolicy"),
+ group.getValue().get("AutoScalingPolicy"));
+ });
+ desired.path(FLEETS).properties().forEach(fleet -> compare(changed, prior, "fleet:" + fleet.getKey(),
+ last.path(FLEETS).get(fleet.getKey()), fleet.getValue()));
+ return changed;
+ }
+
+ private static void compare(Map changed, ObjectNode prior, String key, JsonNode before,
+ JsonNode after) {
+ JsonNode was = before == null || before.isNull() ? null : before;
+ JsonNode now = after == null || after.isNull() ? null : after;
+ if (!Objects.equals(was, now)) {
+ changed.put(key, now);
+ prior.set(key, was);
+ }
+ }
+
+ /** Applies one setting, keyed as {@link #changedSettings} gives it, to the cluster; null removes a policy. */
+ private void apply(String clusterId, String region, String key, JsonNode value) {
+ List ids = List.of(clusterId);
+ switch (key) {
+ case "TerminationProtected" -> emrService.setTerminationProtection(ids, value.asBoolean());
+ case "UnhealthyNodeReplacement" -> emrService.setUnhealthyNodeReplacement(ids, value.asBoolean());
+ case "VisibleToAllUsers" -> emrService.setVisibleToAllUsers(ids, value.asBoolean());
+ case "StepConcurrencyLevel" -> emrService.modifyCluster(clusterId, value.asInt());
+ case "ManagedScalingPolicy" -> {
+ if (value == null) {
+ emrService.removeManagedScalingPolicy(clusterId);
+ } else {
+ emrService.putManagedScalingPolicy(clusterId, value);
+ }
+ }
+ case "AutoTerminationPolicy" -> {
+ if (value == null) {
+ emrService.removeAutoTerminationPolicy(clusterId);
+ } else {
+ emrService.putAutoTerminationPolicy(clusterId, value);
+ }
+ }
+ default -> applyInstanceSetting(clusterId, region, key, value);
+ }
+ }
+
+ private void applyInstanceSetting(String clusterId, String region, String key, JsonNode value) {
+ if (key.startsWith("fleet:")) {
+ EmrInstanceFleet fleet = fleet(clusterId, key.substring("fleet:".length()));
+ emrService.modifyInstanceFleet(clusterId, fleet.getId(), value.path("TargetOnDemandCapacity").asInt(),
+ value.path("TargetSpotCapacity").asInt());
+ return;
+ }
+ String[] parts = key.split(":", 2);
+ String member = parts[1].substring(parts[1].lastIndexOf(':') + 1);
+ EmrInstanceGroup group = group(clusterId, parts[1].substring(0, parts[1].lastIndexOf(':')));
+ if ("InstanceCount".equals(member)) {
+ emrService.modifyInstanceGroups(clusterId, region,
+ List.of(new InstanceGroupModification(group.getId(), value.asInt(), null)));
+ } else if (value == null) {
+ emrService.removeAutoScalingPolicy(clusterId, group.getId());
+ } else {
+ emrService.putAutoScalingPolicy(clusterId, group.getId(), value);
+ }
+ }
+
+ /** The cluster's group a settings key names: {@code CORE}, or {@code TASK:} and its name. */
+ private EmrInstanceGroup group(String clusterId, String key) {
+ return emrService.listInstanceGroups(clusterId).stream().filter(group -> key.startsWith("TASK:")
+ ? "TASK".equals(group.getInstanceGroupType()) && key.substring(5).equals(group.getName())
+ : key.equals(group.getInstanceGroupType()))
+ .findFirst().orElseThrow(() -> new AwsException("NotFound",
+ "Cluster " + clusterId + " has no instance group " + key + ".", 404));
+ }
+
+ private EmrInstanceFleet fleet(String clusterId, String key) {
+ return emrService.listInstanceFleets(clusterId).stream().filter(fleet -> key.startsWith("TASK:")
+ ? "TASK".equals(fleet.getInstanceFleetType()) && key.substring(5).equals(fleet.getName())
+ : key.equals(fleet.getInstanceFleetType()))
+ .findFirst().orElseThrow(() -> new AwsException("NotFound",
+ "Cluster " + clusterId + " has no instance fleet " + key + ".", 404));
+ }
+
+ /** Puts back the settings named in {@code keys} at their snapshotted values, and the tags once touched. */
+ private void restoreCluster(JsonNode snapshot, Set keys, boolean tagsTouched) {
+ String id = snapshot.path("clusterId").asText();
+ String region = snapshot.path("region").asText();
+ snapshot.path("settings").properties().forEach(setting -> {
+ if (keys.contains(setting.getKey())) {
+ apply(id, region, setting.getKey(), setting.getValue().isNull() ? null : setting.getValue());
+ }
+ });
+ if (tagsTouched) {
+ JsonNode tags = snapshot.path("tags");
+ List touched = new ArrayList<>();
+ tags.path("touched").forEach(key -> touched.add(key.asText()));
+ reconcileTags(id, touched, CfnRollback.snapshotTags(tags));
+ }
+ }
+
+ private void reconcileTags(String clusterId, Collection managedKeys, Map desired) {
+ CfnRollback.reconcileTags(managedKeys, desired, dropped -> emrService.removeTags(clusterId, dropped),
+ added -> emrService.addTags(clusterId, added));
+ }
+
+ /** The cluster {@code id}, failing as an update of one that has terminated, or is gone, fails. */
+ private EmrCluster liveCluster(String id) {
+ AwsException notFound = new AwsException("NotFound",
+ "Resource of type '" + CLUSTER + "' with identifier '" + id + "' was not found.", 404);
+ EmrCluster cluster;
+ try {
+ cluster = emrService.describeCluster(id);
+ } catch (AwsException e) {
+ if ("InvalidRequestException".equals(e.getErrorCode())) {
+ throw notFound;
+ }
+ throw e;
+ }
+ if (ENDED.contains(cluster.getState())) {
+ throw notFound;
+ }
+ return cluster;
+ }
+
+ /**
+ * The cluster once it is waiting or running, or has ended because it ran its steps and was not kept alive without
+ * them, which is a cluster that came up; one that terminates otherwise, or never gets there, fails the create.
+ */
+ private EmrCluster awaitReady(String id) {
+ Instant deadline = Instant.now().plus(READY_TIMEOUT);
+ while (true) {
+ EmrCluster cluster = emrService.describeCluster(id);
+ if (READY.contains(cluster.getState()) || ("TERMINATED".equals(cluster.getState())
+ && "ALL_STEPS_COMPLETED".equals(cluster.getStateChangeReasonCode()))) {
+ return cluster;
+ }
+ if (ENDED.contains(cluster.getState())) {
+ throw new AwsException("NotStabilized", "Resource of type '" + CLUSTER + "' with identifier '" + id
+ + "' did not stabilize: it is " + cluster.getState() + ".", 400);
+ }
+ if (Instant.now().isAfter(deadline)) {
+ throw new AwsException("NotStabilized", "Resource of type '" + CLUSTER + "' with identifier '" + id
+ + "' did not stabilize: it is still " + cluster.getState() + ".", 400);
+ }
+ try {
+ Thread.sleep(200);
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ throw new IllegalStateException("Interrupted waiting for EMR cluster " + id, e);
+ }
+ }
+ }
+
+ private static void publishCluster(StackResource r, EmrCluster cluster) {
+ r.setPhysicalId(cluster.getId());
+ r.getAttributes().put("Id", cluster.getId());
+ if (cluster.getMasterPublicDnsName() != null) {
+ r.getAttributes().put("MasterPublicDNS", cluster.getMasterPublicDnsName());
+ }
+ }
+
+ /**
+ * Deletes the security configuration, unless the Region lists none of that name, it being gone, or terminates the
+ * cluster, which TerminateJobFlows leaves be when it has terminated or is gone, and refuses when it is termination
+ * protected.
+ */
@Override
public void delete(String resourceType, String physicalId, String region) {
- if (emrService.listSecurityConfigurations(region).stream().anyMatch(sc -> physicalId.equals(sc.getName()))) {
- emrService.deleteSecurityConfiguration(physicalId, region);
+ switch (resourceType) {
+ case SECURITY_CONFIGURATION -> {
+ if (emrService.listSecurityConfigurations(region).stream()
+ .anyMatch(sc -> physicalId.equals(sc.getName()))) {
+ emrService.deleteSecurityConfiguration(physicalId, region);
+ }
+ }
+ case CLUSTER -> emrService.terminateJobFlows(List.of(physicalId));
+ default -> throw new IllegalStateException("EmrCfnProvisioner cannot delete " + resourceType);
}
}
}
diff --git a/src/main/java/io/floci/aws/services/emr/EmrHandler.java b/src/main/java/io/floci/aws/services/emr/EmrHandler.java
index cc01a7244b..7b409b9013 100644
--- a/src/main/java/io/floci/aws/services/emr/EmrHandler.java
+++ b/src/main/java/io/floci/aws/services/emr/EmrHandler.java
@@ -167,6 +167,18 @@ public class EmrHandler {
// ──────────────────────────── Cluster lifecycle ────────────────────────────
private Response handleRunJobFlow(JsonNode request, String region) {
+ EmrCluster created = service.runJobFlow(clusterFrom(request, region), region);
+ ObjectNode response = objectMapper.createObjectNode();
+ response.put("JobFlowId", created.getId());
+ response.put("ClusterArn", created.getClusterArn());
+ return Response.ok(response).build();
+ }
+
+ /**
+ * The cluster a RunJobFlow request describes, its members read and checked as RunJobFlow reads them, for this
+ * handler and for CloudFormation's {@code AWS::EMR::Cluster}, which describes a cluster in the same members.
+ */
+ public EmrCluster clusterFrom(JsonNode request, String region) {
EmrCluster cluster = new EmrCluster();
cluster.setName(text(request, "Name"));
cluster.setReleaseLabel(text(request, "ReleaseLabel"));
@@ -210,12 +222,7 @@ public class EmrHandler {
cluster.setInstanceGroups(groups.isEmpty() && fleets.isEmpty() ? uniformInstanceGroups(instances) : groups);
cluster.setInstanceFleets(fleets);
cluster.setSteps(parseSteps(request.path("Steps"), text(request, "StepExecutionRoleArn")));
-
- 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();
+ return cluster;
}
private Response handleDescribeCluster(JsonNode request) {
diff --git a/src/main/resources/aws/cfn-property-types.json b/src/main/resources/aws/cfn-property-types.json
index 8bb9d40bb4..2cec208033 100644
--- a/src/main/resources/aws/cfn-property-types.json
+++ b/src/main/resources/aws/cfn-property-types.json
@@ -12,6 +12,7 @@
"AWS::EC2::LaunchTemplate": "AWS::EC2::LaunchTemplate",
"AWS::ECS::TaskDefinition": "AWS::ECS::TaskDefinition",
"AWS::EKS::Cluster": "AWS::EKS::Cluster",
+ "AWS::EMR::Cluster": "AWS::EMR::Cluster",
"AWS::EMR::SecurityConfiguration": "AWS::EMR::SecurityConfiguration",
"AWS::EMR::Studio": "AWS::EMR::Studio",
"AWS::EMR::StudioSessionMapping": "AWS::EMR::StudioSessionMapping",
@@ -1955,6 +1956,569 @@
"Enabled": "Boolean"
}
},
+ "AWS::EMR::Cluster": {
+ "type": "structure",
+ "members": {
+ "MasterPublicDNS": "String",
+ "AdditionalInfo": "Json",
+ "Applications": "AWS::EMR::Cluster.Applications",
+ "AutoScalingRole": "String",
+ "AutoTerminationPolicy": "AWS::EMR::Cluster/AutoTerminationPolicy",
+ "BootstrapActions": "AWS::EMR::Cluster.BootstrapActions",
+ "Configurations": "AWS::EMR::Cluster.Configurations",
+ "CustomAmiId": "String",
+ "EbsRootVolumeSize": "Integer",
+ "Id": "String",
+ "Instances": "AWS::EMR::Cluster/JobFlowInstancesConfig",
+ "JobFlowRole": "String",
+ "KerberosAttributes": "AWS::EMR::Cluster/KerberosAttributes",
+ "LogEncryptionKmsKeyId": "String",
+ "LogUri": "String",
+ "ManagedScalingPolicy": "AWS::EMR::Cluster/ManagedScalingPolicy",
+ "Name": "String",
+ "ReleaseLabel": "String",
+ "OSReleaseLabel": "String",
+ "ScaleDownBehavior": "String",
+ "SecurityConfiguration": "String",
+ "ServiceRole": "String",
+ "StepConcurrencyLevel": "Integer",
+ "Steps": "AWS::EMR::Cluster.Steps",
+ "VisibleToAllUsers": "Boolean",
+ "EbsRootVolumeIops": "Integer",
+ "EbsRootVolumeThroughput": "Integer",
+ "PlacementGroupConfigs": "AWS::EMR::Cluster.PlacementGroupConfigs",
+ "Tags": "AWS::EMR::Cluster.Tags",
+ "MonitoringConfiguration": "AWS::EMR::Cluster/MonitoringConfiguration",
+ "SessionEnabled": "Boolean"
+ },
+ "required": [
+ "Instances",
+ "ServiceRole",
+ "JobFlowRole",
+ "Name"
+ ]
+ },
+ "AWS::EMR::Cluster.Applications": {
+ "type": "list",
+ "member": "AWS::EMR::Cluster/Application"
+ },
+ "AWS::EMR::Cluster.BootstrapActions": {
+ "type": "list",
+ "member": "AWS::EMR::Cluster/BootstrapActionConfig"
+ },
+ "AWS::EMR::Cluster.Configurations": {
+ "type": "list",
+ "member": "AWS::EMR::Cluster/EMRConfiguration"
+ },
+ "AWS::EMR::Cluster.PlacementGroupConfigs": {
+ "type": "list",
+ "member": "AWS::EMR::Cluster/PlacementGroupConfig"
+ },
+ "AWS::EMR::Cluster.Steps": {
+ "type": "list",
+ "member": "AWS::EMR::Cluster/StepConfig"
+ },
+ "AWS::EMR::Cluster.Tags": {
+ "type": "list",
+ "member": "AWS::EMR::Cluster/Tag"
+ },
+ "AWS::EMR::Cluster/Application": {
+ "type": "structure",
+ "members": {
+ "AdditionalInfo": "AWS::EMR::Cluster/Application.AdditionalInfo",
+ "Args": "AWS::EMR::Cluster/Application.Args",
+ "Name": "String",
+ "Version": "String"
+ }
+ },
+ "AWS::EMR::Cluster/Application.AdditionalInfo": {
+ "type": "map",
+ "value": "String"
+ },
+ "AWS::EMR::Cluster/Application.Args": {
+ "type": "list",
+ "member": "String"
+ },
+ "AWS::EMR::Cluster/AutoScalingPolicy": {
+ "type": "structure",
+ "members": {
+ "Constraints": "AWS::EMR::Cluster/ScalingConstraints",
+ "Rules": "AWS::EMR::Cluster/AutoScalingPolicy.Rules"
+ },
+ "required": [
+ "Constraints",
+ "Rules"
+ ]
+ },
+ "AWS::EMR::Cluster/AutoScalingPolicy.Rules": {
+ "type": "list",
+ "member": "AWS::EMR::Cluster/ScalingRule"
+ },
+ "AWS::EMR::Cluster/AutoTerminationPolicy": {
+ "type": "structure",
+ "members": {
+ "IdleTimeout": "Integer"
+ }
+ },
+ "AWS::EMR::Cluster/BootstrapActionConfig": {
+ "type": "structure",
+ "members": {
+ "Name": "String",
+ "ScriptBootstrapAction": "AWS::EMR::Cluster/ScriptBootstrapActionConfig"
+ },
+ "required": [
+ "Name",
+ "ScriptBootstrapAction"
+ ]
+ },
+ "AWS::EMR::Cluster/CloudWatchAlarmDefinition": {
+ "type": "structure",
+ "members": {
+ "ComparisonOperator": "String",
+ "Dimensions": "AWS::EMR::Cluster/CloudWatchAlarmDefinition.Dimensions",
+ "EvaluationPeriods": "Integer",
+ "MetricName": "String",
+ "Namespace": "String",
+ "Period": "Integer",
+ "Statistic": "String",
+ "Threshold": "Double",
+ "Unit": "String"
+ },
+ "required": [
+ "ComparisonOperator",
+ "MetricName",
+ "Period",
+ "Threshold"
+ ]
+ },
+ "AWS::EMR::Cluster/CloudWatchAlarmDefinition.Dimensions": {
+ "type": "list",
+ "member": "AWS::EMR::Cluster/MetricDimension"
+ },
+ "AWS::EMR::Cluster/CloudWatchLogConfiguration": {
+ "type": "structure",
+ "members": {
+ "Enabled": "Boolean",
+ "LogGroupName": "String",
+ "LogStreamNamePrefix": "String",
+ "EncryptionKeyArn": "String",
+ "LogTypes": "AWS::EMR::Cluster/CloudWatchLogConfiguration.LogTypes"
+ },
+ "required": [
+ "Enabled"
+ ]
+ },
+ "AWS::EMR::Cluster/CloudWatchLogConfiguration.LogTypes": {
+ "type": "map",
+ "value": "AWS::EMR::Cluster/CloudWatchLogConfiguration.LogTypes.*"
+ },
+ "AWS::EMR::Cluster/CloudWatchLogConfiguration.LogTypes.*": {
+ "type": "list",
+ "member": "String"
+ },
+ "AWS::EMR::Cluster/ComputeLimits": {
+ "type": "structure",
+ "members": {
+ "MaximumCapacityUnits": "Integer",
+ "MaximumCoreCapacityUnits": "Integer",
+ "MaximumOnDemandCapacityUnits": "Integer",
+ "MinimumCapacityUnits": "Integer",
+ "UnitType": "String"
+ },
+ "required": [
+ "MaximumCapacityUnits",
+ "MinimumCapacityUnits",
+ "UnitType"
+ ]
+ },
+ "AWS::EMR::Cluster/EMRConfiguration": {
+ "type": "structure",
+ "members": {
+ "Classification": "String",
+ "ConfigurationProperties": "AWS::EMR::Cluster/EMRConfiguration.ConfigurationProperties",
+ "Configurations": "AWS::EMR::Cluster/EMRConfiguration.Configurations"
+ }
+ },
+ "AWS::EMR::Cluster/EMRConfiguration.ConfigurationProperties": {
+ "type": "map",
+ "value": "String"
+ },
+ "AWS::EMR::Cluster/EMRConfiguration.Configurations": {
+ "type": "list",
+ "member": "AWS::EMR::Cluster/EMRConfiguration"
+ },
+ "AWS::EMR::Cluster/EbsBlockDeviceConfig": {
+ "type": "structure",
+ "members": {
+ "VolumeSpecification": "AWS::EMR::Cluster/VolumeSpecification",
+ "VolumesPerInstance": "Integer"
+ },
+ "required": [
+ "VolumeSpecification"
+ ]
+ },
+ "AWS::EMR::Cluster/EbsConfiguration": {
+ "type": "structure",
+ "members": {
+ "EbsBlockDeviceConfigs": "AWS::EMR::Cluster/EbsConfiguration.EbsBlockDeviceConfigs",
+ "EbsOptimized": "Boolean"
+ }
+ },
+ "AWS::EMR::Cluster/EbsConfiguration.EbsBlockDeviceConfigs": {
+ "type": "list",
+ "member": "AWS::EMR::Cluster/EbsBlockDeviceConfig"
+ },
+ "AWS::EMR::Cluster/HadoopJarStepConfig": {
+ "type": "structure",
+ "members": {
+ "Args": "AWS::EMR::Cluster/HadoopJarStepConfig.Args",
+ "Jar": "String",
+ "MainClass": "String",
+ "StepProperties": "AWS::EMR::Cluster/HadoopJarStepConfig.StepProperties"
+ },
+ "required": [
+ "Jar"
+ ]
+ },
+ "AWS::EMR::Cluster/HadoopJarStepConfig.Args": {
+ "type": "list",
+ "member": "String"
+ },
+ "AWS::EMR::Cluster/HadoopJarStepConfig.StepProperties": {
+ "type": "list",
+ "member": "AWS::EMR::Cluster/KeyValue"
+ },
+ "AWS::EMR::Cluster/InstanceFleetConfig": {
+ "type": "structure",
+ "members": {
+ "InstanceTypeConfigs": "AWS::EMR::Cluster/InstanceFleetConfig.InstanceTypeConfigs",
+ "LaunchSpecifications": "AWS::EMR::Cluster/InstanceFleetProvisioningSpecifications",
+ "ResizeSpecifications": "AWS::EMR::Cluster/InstanceFleetResizingSpecifications",
+ "Name": "String",
+ "TargetOnDemandCapacity": "Integer",
+ "TargetSpotCapacity": "Integer"
+ }
+ },
+ "AWS::EMR::Cluster/InstanceFleetConfig.InstanceTypeConfigs": {
+ "type": "list",
+ "member": "AWS::EMR::Cluster/InstanceTypeConfig"
+ },
+ "AWS::EMR::Cluster/InstanceFleetProvisioningSpecifications": {
+ "type": "structure",
+ "members": {
+ "OnDemandSpecification": "AWS::EMR::Cluster/OnDemandProvisioningSpecification",
+ "SpotSpecification": "AWS::EMR::Cluster/SpotProvisioningSpecification"
+ }
+ },
+ "AWS::EMR::Cluster/InstanceFleetResizingSpecifications": {
+ "type": "structure",
+ "members": {
+ "SpotResizeSpecification": "AWS::EMR::Cluster/SpotResizingSpecification",
+ "OnDemandResizeSpecification": "AWS::EMR::Cluster/OnDemandResizingSpecification"
+ }
+ },
+ "AWS::EMR::Cluster/InstanceGroupConfig": {
+ "type": "structure",
+ "members": {
+ "AutoScalingPolicy": "AWS::EMR::Cluster/AutoScalingPolicy",
+ "BidPrice": "String",
+ "Configurations": "AWS::EMR::Cluster/InstanceGroupConfig.Configurations",
+ "CustomAmiId": "String",
+ "EbsConfiguration": "AWS::EMR::Cluster/EbsConfiguration",
+ "InstanceCount": "Integer",
+ "InstanceType": "String",
+ "Market": "String",
+ "Name": "String"
+ },
+ "required": [
+ "InstanceCount",
+ "InstanceType"
+ ]
+ },
+ "AWS::EMR::Cluster/InstanceGroupConfig.Configurations": {
+ "type": "list",
+ "member": "AWS::EMR::Cluster/EMRConfiguration"
+ },
+ "AWS::EMR::Cluster/InstanceTypeConfig": {
+ "type": "structure",
+ "members": {
+ "BidPrice": "String",
+ "BidPriceAsPercentageOfOnDemandPrice": "Double",
+ "Configurations": "AWS::EMR::Cluster/InstanceTypeConfig.Configurations",
+ "CustomAmiId": "String",
+ "EbsConfiguration": "AWS::EMR::Cluster/EbsConfiguration",
+ "InstanceType": "String",
+ "Priority": "Double",
+ "WeightedCapacity": "Integer"
+ },
+ "required": [
+ "InstanceType"
+ ]
+ },
+ "AWS::EMR::Cluster/InstanceTypeConfig.Configurations": {
+ "type": "list",
+ "member": "AWS::EMR::Cluster/EMRConfiguration"
+ },
+ "AWS::EMR::Cluster/JobFlowInstancesConfig": {
+ "type": "structure",
+ "members": {
+ "AdditionalMasterSecurityGroups": "AWS::EMR::Cluster/JobFlowInstancesConfig.AdditionalMasterSecurityGroups",
+ "AdditionalSlaveSecurityGroups": "AWS::EMR::Cluster/JobFlowInstancesConfig.AdditionalSlaveSecurityGroups",
+ "Ec2KeyName": "String",
+ "Ec2SubnetId": "String",
+ "Ec2SubnetIds": "AWS::EMR::Cluster/JobFlowInstancesConfig.Ec2SubnetIds",
+ "EmrManagedMasterSecurityGroup": "String",
+ "EmrManagedSlaveSecurityGroup": "String",
+ "HadoopVersion": "String",
+ "KeepJobFlowAliveWhenNoSteps": "Boolean",
+ "CoreInstanceFleet": "AWS::EMR::Cluster/InstanceFleetConfig",
+ "MasterInstanceFleet": "AWS::EMR::Cluster/InstanceFleetConfig",
+ "TaskInstanceFleets": "AWS::EMR::Cluster/JobFlowInstancesConfig.TaskInstanceFleets",
+ "CoreInstanceGroup": "AWS::EMR::Cluster/InstanceGroupConfig",
+ "MasterInstanceGroup": "AWS::EMR::Cluster/InstanceGroupConfig",
+ "TaskInstanceGroups": "AWS::EMR::Cluster/JobFlowInstancesConfig.TaskInstanceGroups",
+ "Placement": "AWS::EMR::Cluster/PlacementType",
+ "ServiceAccessSecurityGroup": "String",
+ "TerminationProtected": "Boolean",
+ "UnhealthyNodeReplacement": "Boolean"
+ }
+ },
+ "AWS::EMR::Cluster/JobFlowInstancesConfig.AdditionalMasterSecurityGroups": {
+ "type": "list",
+ "member": "String"
+ },
+ "AWS::EMR::Cluster/JobFlowInstancesConfig.AdditionalSlaveSecurityGroups": {
+ "type": "list",
+ "member": "String"
+ },
+ "AWS::EMR::Cluster/JobFlowInstancesConfig.Ec2SubnetIds": {
+ "type": "list",
+ "member": "String"
+ },
+ "AWS::EMR::Cluster/JobFlowInstancesConfig.TaskInstanceFleets": {
+ "type": "list",
+ "member": "AWS::EMR::Cluster/InstanceFleetConfig"
+ },
+ "AWS::EMR::Cluster/JobFlowInstancesConfig.TaskInstanceGroups": {
+ "type": "list",
+ "member": "AWS::EMR::Cluster/InstanceGroupConfig"
+ },
+ "AWS::EMR::Cluster/KerberosAttributes": {
+ "type": "structure",
+ "members": {
+ "ADDomainJoinPassword": "String",
+ "ADDomainJoinUser": "String",
+ "CrossRealmTrustPrincipalPassword": "String",
+ "KdcAdminPassword": "String",
+ "Realm": "String"
+ },
+ "required": [
+ "Realm",
+ "KdcAdminPassword"
+ ]
+ },
+ "AWS::EMR::Cluster/KeyValue": {
+ "type": "structure",
+ "members": {
+ "Key": "String",
+ "Value": "String"
+ }
+ },
+ "AWS::EMR::Cluster/ManagedScalingPolicy": {
+ "type": "structure",
+ "members": {
+ "UtilizationPerformanceIndex": "Integer",
+ "ScalingStrategy": "String",
+ "ComputeLimits": "AWS::EMR::Cluster/ComputeLimits"
+ }
+ },
+ "AWS::EMR::Cluster/MetricDimension": {
+ "type": "structure",
+ "members": {
+ "Key": "String",
+ "Value": "String"
+ },
+ "required": [
+ "Key",
+ "Value"
+ ]
+ },
+ "AWS::EMR::Cluster/MonitoringConfiguration": {
+ "type": "structure",
+ "members": {
+ "CloudWatchLogConfiguration": "AWS::EMR::Cluster/CloudWatchLogConfiguration"
+ }
+ },
+ "AWS::EMR::Cluster/OnDemandCapacityReservationOptions": {
+ "type": "structure",
+ "members": {
+ "CapacityReservationPreference": "String",
+ "CapacityReservationResourceGroupArn": "String",
+ "UsageStrategy": "String"
+ }
+ },
+ "AWS::EMR::Cluster/OnDemandProvisioningSpecification": {
+ "type": "structure",
+ "members": {
+ "AllocationStrategy": "String",
+ "CapacityReservationOptions": "AWS::EMR::Cluster/OnDemandCapacityReservationOptions"
+ },
+ "required": [
+ "AllocationStrategy"
+ ]
+ },
+ "AWS::EMR::Cluster/OnDemandResizingSpecification": {
+ "type": "structure",
+ "members": {
+ "TimeoutDurationMinutes": "Integer",
+ "AllocationStrategy": "String",
+ "CapacityReservationOptions": "AWS::EMR::Cluster/OnDemandCapacityReservationOptions"
+ }
+ },
+ "AWS::EMR::Cluster/PlacementGroupConfig": {
+ "type": "structure",
+ "members": {
+ "InstanceRole": "String",
+ "PlacementStrategy": "String"
+ },
+ "required": [
+ "InstanceRole"
+ ]
+ },
+ "AWS::EMR::Cluster/PlacementType": {
+ "type": "structure",
+ "members": {
+ "AvailabilityZone": "String"
+ },
+ "required": [
+ "AvailabilityZone"
+ ]
+ },
+ "AWS::EMR::Cluster/ScalingAction": {
+ "type": "structure",
+ "members": {
+ "Market": "String",
+ "SimpleScalingPolicyConfiguration": "AWS::EMR::Cluster/SimpleScalingPolicyConfiguration"
+ },
+ "required": [
+ "SimpleScalingPolicyConfiguration"
+ ]
+ },
+ "AWS::EMR::Cluster/ScalingConstraints": {
+ "type": "structure",
+ "members": {
+ "MaxCapacity": "Integer",
+ "MinCapacity": "Integer"
+ },
+ "required": [
+ "MaxCapacity",
+ "MinCapacity"
+ ]
+ },
+ "AWS::EMR::Cluster/ScalingRule": {
+ "type": "structure",
+ "members": {
+ "Action": "AWS::EMR::Cluster/ScalingAction",
+ "Description": "String",
+ "Name": "String",
+ "Trigger": "AWS::EMR::Cluster/ScalingTrigger"
+ },
+ "required": [
+ "Action",
+ "Name",
+ "Trigger"
+ ]
+ },
+ "AWS::EMR::Cluster/ScalingTrigger": {
+ "type": "structure",
+ "members": {
+ "CloudWatchAlarmDefinition": "AWS::EMR::Cluster/CloudWatchAlarmDefinition"
+ },
+ "required": [
+ "CloudWatchAlarmDefinition"
+ ]
+ },
+ "AWS::EMR::Cluster/ScriptBootstrapActionConfig": {
+ "type": "structure",
+ "members": {
+ "Args": "AWS::EMR::Cluster/ScriptBootstrapActionConfig.Args",
+ "Path": "String"
+ },
+ "required": [
+ "Path"
+ ]
+ },
+ "AWS::EMR::Cluster/ScriptBootstrapActionConfig.Args": {
+ "type": "list",
+ "member": "String"
+ },
+ "AWS::EMR::Cluster/SimpleScalingPolicyConfiguration": {
+ "type": "structure",
+ "members": {
+ "AdjustmentType": "String",
+ "CoolDown": "Integer",
+ "ScalingAdjustment": "Integer"
+ },
+ "required": [
+ "ScalingAdjustment"
+ ]
+ },
+ "AWS::EMR::Cluster/SpotProvisioningSpecification": {
+ "type": "structure",
+ "members": {
+ "AllocationStrategy": "String",
+ "BlockDurationMinutes": "Integer",
+ "TimeoutAction": "String",
+ "TimeoutDurationMinutes": "Integer"
+ },
+ "required": [
+ "TimeoutAction",
+ "TimeoutDurationMinutes"
+ ]
+ },
+ "AWS::EMR::Cluster/SpotResizingSpecification": {
+ "type": "structure",
+ "members": {
+ "TimeoutDurationMinutes": "Integer",
+ "AllocationStrategy": "String"
+ }
+ },
+ "AWS::EMR::Cluster/StepConfig": {
+ "type": "structure",
+ "members": {
+ "ActionOnFailure": "String",
+ "HadoopJarStep": "AWS::EMR::Cluster/HadoopJarStepConfig",
+ "Name": "String"
+ },
+ "required": [
+ "HadoopJarStep",
+ "Name"
+ ]
+ },
+ "AWS::EMR::Cluster/Tag": {
+ "type": "structure",
+ "members": {
+ "Key": "String",
+ "Value": "String"
+ },
+ "required": [
+ "Key",
+ "Value"
+ ]
+ },
+ "AWS::EMR::Cluster/VolumeSpecification": {
+ "type": "structure",
+ "members": {
+ "Iops": "Integer",
+ "SizeInGB": "Integer",
+ "Throughput": "Integer",
+ "VolumeType": "String"
+ },
+ "required": [
+ "SizeInGB",
+ "VolumeType"
+ ]
+ },
"AWS::EMR::SecurityConfiguration": {
"type": "structure",
"members": {
diff --git a/src/main/resources/cloudformation/create-only-properties.json b/src/main/resources/cloudformation/create-only-properties.json
index 08d32b98a2..dc0dcdf3e3 100644
--- a/src/main/resources/cloudformation/create-only-properties.json
+++ b/src/main/resources/cloudformation/create-only-properties.json
@@ -528,6 +528,31 @@
"AmiType",
"Subnets"
],
+ "AWS::EMR::Cluster": [
+ "Steps",
+ "EbsRootVolumeSize",
+ "SecurityConfiguration",
+ "ScaleDownBehavior",
+ "ReleaseLabel",
+ "KerberosAttributes",
+ "ServiceRole",
+ "LogEncryptionKmsKeyId",
+ "Name",
+ "JobFlowRole",
+ "LogUri",
+ "AdditionalInfo",
+ "Applications",
+ "AutoScalingRole",
+ "BootstrapActions",
+ "Configurations",
+ "CustomAmiId",
+ "OSReleaseLabel",
+ "EbsRootVolumeIops",
+ "EbsRootVolumeThroughput",
+ "PlacementGroupConfigs",
+ "MonitoringConfiguration",
+ "SessionEnabled"
+ ],
"AWS::EMR::SecurityConfiguration": [
"Name",
"SecurityConfiguration"
diff --git a/src/test/java/io/floci/aws/services/cloudformation/CfnProvisionerFixture.java b/src/test/java/io/floci/aws/services/cloudformation/CfnProvisionerFixture.java
index df5b8e4779..b333ba3e23 100644
--- a/src/test/java/io/floci/aws/services/cloudformation/CfnProvisionerFixture.java
+++ b/src/test/java/io/floci/aws/services/cloudformation/CfnProvisionerFixture.java
@@ -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;
diff --git a/src/test/java/io/floci/aws/services/cloudformation/EmrClusterCfnIntegrationTest.java b/src/test/java/io/floci/aws/services/cloudformation/EmrClusterCfnIntegrationTest.java
new file mode 100644
index 0000000000..992f8b9b24
--- /dev/null
+++ b/src/test/java/io/floci/aws/services/cloudformation/EmrClusterCfnIntegrationTest.java
@@ -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));
+ }
+}
diff --git a/src/test/java/io/floci/aws/services/cloudformation/provisioners/EmrCfnProvisionerTest.java b/src/test/java/io/floci/aws/services/cloudformation/provisioners/EmrCfnProvisionerTest.java
index 7ca2a825b8..c0398de26b 100644
--- a/src/test/java/io/floci/aws/services/cloudformation/provisioners/EmrCfnProvisionerTest.java
+++ b/src/test/java/io/floci/aws/services/cloudformation/provisioners/EmrCfnProvisionerTest.java
@@ -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 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));
+ }
}
diff --git a/src/test/resources/cloudformation/schema-surface.tsv b/src/test/resources/cloudformation/schema-surface.tsv
index 05036ecb6d..23a84d6da8 100644
--- a/src/test/resources/cloudformation/schema-surface.tsv
+++ b/src/test/resources/cloudformation/schema-surface.tsv
@@ -108,6 +108,7 @@ AWS::EFS::FileSystem Arn,FileSystemId AvailabilityZoneName,BackupPolicy,BypassPo
AWS::EFS::MountTarget Id FileSystemId,IpAddress,IpAddressType,Ipv6Address,SecurityGroups,SubnetId
AWS::EKS::Cluster Arn,CertificateAuthorityData,ClusterSecurityGroupId,EncryptionConfigKeyArn,Endpoint,Id,OpenIdConnectIssuerUrl AccessConfig,ActiveCertificateAuthorityId,BootstrapSelfManagedAddons,CertificateAuthority,ComputeConfig,ControlPlaneScalingConfig,DeletionProtection,EncryptionConfig,Force,KubeApiServerConfig,KubeControllerManagerConfig,KubeSchedulerConfig,KubernetesNetworkConfig,Logging,Name,OutpostConfig,RemoteNetworkConfig,ResourcesVpcConfig,RoleArn,RollbackConfig,StorageConfig,Tags,UpgradePolicy,Version,ZonalShiftConfig
AWS::EKS::Nodegroup Arn,Id AmiType,CapacityType,ClusterName,DiskSize,ForceUpdateEnabled,InstanceTypes,Labels,LaunchTemplate,NodeRepairConfig,NodeRole,NodegroupName,ReleaseVersion,RemoteAccess,ScalingConfig,Subnets,Tags,Taints,UpdateConfig,Version,WarmPoolConfig
+AWS::EMR::Cluster Id,MasterPublicDNS AdditionalInfo,Applications,AutoScalingRole,AutoTerminationPolicy,BootstrapActions,Configurations,CustomAmiId,EbsRootVolumeIops,EbsRootVolumeSize,EbsRootVolumeThroughput,Instances,JobFlowRole,KerberosAttributes,LogEncryptionKmsKeyId,LogUri,ManagedScalingPolicy,MonitoringConfiguration,Name,OSReleaseLabel,PlacementGroupConfigs,ReleaseLabel,ScaleDownBehavior,SecurityConfiguration,ServiceRole,SessionEnabled,StepConcurrencyLevel,Steps,Tags
AWS::EMR::SecurityConfiguration Name,SecurityConfiguration
AWS::EMR::Studio Arn,StudioId,Url AuthMode,DefaultS3Location,Description,EncryptionKeyArn,EngineSecurityGroupId,IdcInstanceArn,IdcUserAssignment,IdpAuthUrl,IdpRelayStateParameterName,Name,ServiceRole,SubnetIds,Tags,TrustedIdentityPropagationEnabled,UserRole,VpcId,WorkspaceSecurityGroupId
AWS::EMR::StudioSessionMapping IdentityName,IdentityType,SessionPolicyArn,StudioId
diff --git a/src/test/resources/cloudformation/supported-resource-types.tsv b/src/test/resources/cloudformation/supported-resource-types.tsv
index 9b4aec46da..65bf4b044f 100644
--- a/src/test/resources/cloudformation/supported-resource-types.tsv
+++ b/src/test/resources/cloudformation/supported-resource-types.tsv
@@ -109,6 +109,7 @@ AWS::EFS::FileSystem EfsCfnProvisioner
AWS::EFS::MountTarget EfsCfnProvisioner
AWS::EKS::Cluster EksCfnProvisioner
AWS::EKS::Nodegroup EksCfnProvisioner
+AWS::EMR::Cluster EmrCfnProvisioner
AWS::EMR::SecurityConfiguration EmrCfnProvisioner
AWS::EMR::Studio EmrStudioCfnProvisioner
AWS::EMR::StudioSessionMapping EmrStudioCfnProvisioner
diff --git a/src/test/resources/cloudformation/writable-property-gaps.tsv b/src/test/resources/cloudformation/writable-property-gaps.tsv
index 987a8fe5a5..8e96c2c641 100644
--- a/src/test/resources/cloudformation/writable-property-gaps.tsv
+++ b/src/test/resources/cloudformation/writable-property-gaps.tsv
@@ -319,6 +319,14 @@ AWS::EKS::Nodegroup Taints accepted and ignored
AWS::EKS::Nodegroup UpdateConfig accepted and ignored
AWS::EKS::Nodegroup Version accepted and ignored
AWS::EKS::Nodegroup WarmPoolConfig accepted and ignored
+AWS::EMR::Cluster AdditionalInfo accepted with a warning and not stored, as Floci's RunJobFlow keeps none of it
+AWS::EMR::Cluster EbsRootVolumeIops accepted with a warning and not stored, as Floci's RunJobFlow keeps none of it
+AWS::EMR::Cluster EbsRootVolumeThroughput accepted with a warning and not stored, as Floci's RunJobFlow keeps none of it
+AWS::EMR::Cluster KerberosAttributes accepted with a warning and not stored, as Floci's RunJobFlow keeps none of it
+AWS::EMR::Cluster LogEncryptionKmsKeyId accepted with a warning and not stored, as Floci's RunJobFlow keeps none of it
+AWS::EMR::Cluster MonitoringConfiguration accepted with a warning and not stored, as Floci's RunJobFlow keeps none of it
+AWS::EMR::Cluster OSReleaseLabel accepted with a warning and not stored, as Floci's RunJobFlow keeps none of it
+AWS::EMR::Cluster PlacementGroupConfigs accepted with a warning and not stored, as Floci's RunJobFlow keeps none of it
AWS::ElastiCache::CacheCluster AZMode accepted and ignored, a warning is logged
AWS::ElastiCache::CacheCluster AutoMinorVersionUpgrade accepted and ignored
AWS::ElastiCache::CacheCluster LogDeliveryConfigurations accepted and ignored, a warning is logged
diff --git a/tools/aws/regen_cfn_property_types.py b/tools/aws/regen_cfn_property_types.py
index 93a98c76a7..dfc45c6fff 100644
--- a/tools/aws/regen_cfn_property_types.py
+++ b/tools/aws/regen_cfn_property_types.py
@@ -52,7 +52,8 @@ FETCH_TIMEOUT_SECONDS = 60
# The resource types whose provisioners read their properties through CfnPropertyTypes.
RESOURCE_TYPES = ["AWS::AutoScaling::LaunchConfiguration", "AWS::DSQL::Cluster", "AWS::EC2::Instance",
"AWS::EC2::LaunchTemplate", "AWS::ECS::TaskDefinition", "AWS::EKS::Cluster",
- "AWS::EMR::SecurityConfiguration", "AWS::EMR::Studio", "AWS::EMR::StudioSessionMapping",
+ "AWS::EMR::Cluster", "AWS::EMR::SecurityConfiguration", "AWS::EMR::Studio",
+ "AWS::EMR::StudioSessionMapping",
"AWS::EMRContainers::VirtualCluster", "AWS::EMRServerless::Application",
"AWS::Events::Connection", "AWS::Events::Rule",
"AWS::Lambda::Function", "AWS::Lambda::LayerVersion",
diff --git a/tools/docs/cfn_resource_types.yaml b/tools/docs/cfn_resource_types.yaml
index ee5c2107d7..06442e873a 100644
--- a/tools/docs/cfn_resource_types.yaml
+++ b/tools/docs/cfn_resource_types.yaml
@@ -100,7 +100,7 @@ type_order:
AWS::ECS: [Cluster, TaskDefinition, Service]
AWS::EFS: [FileSystem, MountTarget, AccessPoint]
AWS::EKS: [Cluster, Nodegroup]
- AWS::EMR: [SecurityConfiguration, Studio, StudioSessionMapping]
+ AWS::EMR: [Cluster, SecurityConfiguration, Studio, StudioSessionMapping]
AWS::RDS:
[DBInstance, DBCluster, DBSubnetGroup, DBParameterGroup, DBClusterParameterGroup]
AWS::ElastiCache:
@@ -235,6 +235,7 @@ notes:
AWS::Transfer::User: 'management plane only; Ref returns the user ARN; Arn attribute supported; Policy and PosixProfile are not supported; a ServerId or UserName change replaces the user'
AWS::EKS::Cluster: 'created with `Name`, `Version`, `RoleArn`, `Tags`, `EncryptionConfig`, `ResourcesVpcConfig`, `Logging`, `AccessConfig` and `KubernetesNetworkConfig.IpFamily` and `ServiceIpv4Cidr`, a replacement included; a change to `EncryptionConfig`, `IpFamily` or `ServiceIpv4Cidr` replaces the cluster with the new value applied; `ElasticLoadBalancing`, `ServiceIpv6Cidr` and `ResourcesVpcConfig.ControlPlaneEgressMode` are accepted and ignored; updated in place for `Tags`, keeping tags added outside the stack, for `Logging`, for `AccessConfig.AuthenticationMode` (a mode cannot be moved back, so a stack update that does so fails, and a stack rollback restores it) and for `ResourcesVpcConfig` endpoint access and `PublicAccessCidrs`; a change to `Name`, `RoleArn`, `EncryptionConfig`, `BootstrapSelfManagedAddons`, `OutpostConfig`, `AccessConfig.BootstrapClusterCreatorAdminPermissions`, `KubernetesNetworkConfig.IpFamily` or `KubernetesNetworkConfig.ServiceIpv4Cidr` replaces the cluster, as the registry marks them create-only, and deletes the old one once the update commits; a change to `Version` is accepted with a warning and not applied, as the emulator has no `UpdateClusterVersion`; a change to the subnets or security groups of `ResourcesVpcConfig` fails the resource, as the emulator''s `UpdateClusterConfig` does not change them'
AWS::EKS::Nodegroup: 'created with `ClusterName`, `NodegroupName`, `NodeRole`, `Subnets` and `Tags`; updated in place for `Tags`, keeping tags added outside the stack; a change to `ClusterName`, `NodegroupName`, `NodeRole`, `Subnets`, `AmiType`, `CapacityType`, `DiskSize`, `InstanceTypes` or `RemoteAccess` replaces the nodegroup, as the registry marks them create-only, and deletes the old one once the update commits; `ScalingConfig`, `Labels`, `Taints`, `UpdateConfig`, `Version`, `ReleaseVersion`, `ForceUpdateEnabled`, `LaunchTemplate`, `NodeRepairConfig` and `WarmPoolConfig` are accepted and not applied, whether changed or dropped, with a warning, as the emulator cannot update a nodegroup in place'
+ AWS::EMR::Cluster: 'created through `RunJobFlow`, once it is waiting or running, its master, core and task groups or fleets as `RunJobFlow`''s `InstanceGroups` or `InstanceFleets`; `AdditionalInfo`, `KerberosAttributes`, `OSReleaseLabel`, `EbsRootVolumeIops`, `EbsRootVolumeThroughput`, `PlacementGroupConfigs`, `LogEncryptionKmsKeyId` and `MonitoringConfiguration`, `Instances`'' `Ec2SubnetIds`, additional security groups and `HadoopVersion`, a group''s `EbsConfiguration` and `CustomAmiId` and a fleet''s launch and resize specifications are accepted with a warning and not stored; task groups and fleets need unique names; a template that sets the read-only `Id` or `MasterPublicDNS` is refused; updated in place for `AutoTerminationPolicy`, `ManagedScalingPolicy`, `StepConcurrencyLevel`, `VisibleToAllUsers`, `Tags` (keeping tags added outside the stack), `TerminationProtected`, `UnhealthyNodeReplacement`, a core or task group''s `InstanceCount` and `AutoScalingPolicy` and a core or task fleet''s target capacities, a dropped one taking its default; any other change, within `Instances` included, replaces the cluster and terminates the old one once the update commits; a termination-protected cluster refuses the delete'
AWS::EMR::SecurityConfiguration: 'created with `Name`, generated when the template gives none, and the `SecurityConfiguration` JSON, as an object or its text; both are create-only, so any change replaces it and deletes the old one once the update commits, and a change that keeps a template''s own `Name` is refused, as for every custom-named resource'
AWS::EMR::Studio: 'created with every property; a template that sets the read-only `Arn`, `StudioId` or `Url` is refused; updated in place through `UpdateStudio` for `Name`, `Description`, `SubnetIds` and `DefaultS3Location`, a dropped setting kept as it is, and for `Tags`, keeping tags added outside the stack; a change to `IdpAuthUrl` or `IdpRelayStateParameterName` is accepted with a warning and not applied, as no Studio API changes them; a rollback puts back the name, description, location and tags, but not subnets an update added, which `UpdateStudio` cannot take away; a change to a create-only property replaces the Studio and deletes the old one once the update commits'
AWS::EMR::StudioSessionMapping: '`Ref` is `StudioId|IdentityType|IdentityName`, the schema''s primary identifier; `SessionPolicyArn` updates in place, and a change to any of the three others replaces the mapping'