From 858bf8d2dbb9941d7ee814dde923ee0a683449d0 Mon Sep 17 00:00:00 2001 From: Priamo Germosen <6233424+pgermosen@users.noreply.github.com> Date: Sat, 21 Nov 2026 13:59:46 -0400 Subject: [PATCH] feat(cloudformation): provision AWS::EMRServerless::Application (#9148) A template can now create an EMR Serverless application. It was not served, so the stack reported CREATE_COMPLETE with nothing behind it. The provisioner goes through the services the EMR Serverless API uses, so a stack and a direct call see the same application, and it does what AWS's own resource handler does: - The properties are read as the handler's model validation reads them, against the registry schema, now in the vendored property types; an Architecture outside its enum and a read-only ApplicationId or Arn are refused. - Ref is the application id; Fn::GetAtt gives ApplicationId and Arn. - A create sends every property to CreateApplication, the Key/Value lists of InitialCapacity and LogTypeMap as the API's maps. - An update sends UpdateApplication the settings the template changed and drives the tags to the template's, removing any other. A dropped setting stays as it is, but for InitialCapacity, which the handler sends as an empty map, and so clears. - Name and Type are create-only: a change replaces the application, and the old one is deleted once the update commits. - A later resource's failure puts back the settings and tags the update changed; a failure of the update itself puts back what it had changed by then, nothing when UpdateApplication refused it, and a restore that fails keeps its snapshot for ContinueUpdateRollback. - Neither an update nor a delete stops a STARTED application, so one the API refuses fails the resource, as on AWS. The vendored create-only properties and schema surface also take AWS's new AWS::CertificateManager::Certificate properties, RootHierarchyType and CertificateUsage, which their drift checks on this change asked for; the ACM provisioner accepts and ignores both. --- docs/services/cloudformation.md | 1 + .../EmrServerlessCfnProvisioner.java | 357 +++++++++++++++ .../resources/aws/cfn-property-types.json | 384 ++++++++++++++++ .../create-only-properties.json | 8 +- .../cloudformation/CfnProvisionerFixture.java | 18 + ...rverlessApplicationCfnIntegrationTest.java | 119 +++++ .../EmrServerlessCfnProvisionerTest.java | 427 ++++++++++++++++++ .../cloudformation/schema-surface.tsv | 3 +- .../supported-resource-types.tsv | 1 + .../cloudformation/writable-property-gaps.tsv | 2 + tools/aws/regen_cfn_property_types.py | 3 +- tools/docs/cfn_resource_types.yaml | 3 + 12 files changed, 1323 insertions(+), 3 deletions(-) create mode 100644 src/main/java/io/floci/aws/services/cloudformation/provisioners/EmrServerlessCfnProvisioner.java create mode 100644 src/test/java/io/floci/aws/services/cloudformation/EmrServerlessApplicationCfnIntegrationTest.java create mode 100644 src/test/java/io/floci/aws/services/cloudformation/provisioners/EmrServerlessCfnProvisionerTest.java diff --git a/docs/services/cloudformation.md b/docs/services/cloudformation.md index 766de72392..367c8c987d 100644 --- a/docs/services/cloudformation.md +++ b/docs/services/cloudformation.md @@ -220,6 +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 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` | | Aurora DSQL | `Cluster` | | ElastiCache | `CacheCluster` (starts a real container; modifying an existing cluster in place is not supported), `ReplicationGroup` (starts a real container; modifying an existing group in place is not supported), `SubnetGroup`, `User` (Tags are ignored), `UserGroup` (Tags are ignored), `ServerlessCache` (GetAtt uses the dotted Endpoint.* and ReaderEndpoint.* form) | diff --git a/src/main/java/io/floci/aws/services/cloudformation/provisioners/EmrServerlessCfnProvisioner.java b/src/main/java/io/floci/aws/services/cloudformation/provisioners/EmrServerlessCfnProvisioner.java new file mode 100644 index 0000000000..9c52ca797a --- /dev/null +++ b/src/main/java/io/floci/aws/services/cloudformation/provisioners/EmrServerlessCfnProvisioner.java @@ -0,0 +1,357 @@ +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.emrserverless.EmrServerlessJobRunService; +import io.floci.aws.services.emrserverless.EmrServerlessService; +import io.floci.aws.services.emrserverless.model.Application; +import io.floci.aws.services.emrserverless.model.CreateApplicationRequest; +import io.floci.aws.services.emrserverless.model.UpdateApplicationRequest; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicBoolean; + +/** + * CloudFormation provisioning for {@code AWS::EMRServerless::Application}, through the services the EMR Serverless + * API itself uses. {@code Ref} is the application id; {@code Fn::GetAtt} gives {@code ApplicationId} and {@code Arn}. + * + *

It does what AWS's resource handler does (aws-cloudformation-resource-providers-emrserverless): the properties are + * read as the handler's model validation reads them, a create sends them to CreateApplication, and an update sends + * UpdateApplication the settings the template changed, then drives the application's tags to the template's, removing + * any other. A setting the template drops is left as it is, as the handler sends null for it, but for + * {@code InitialCapacity}, which it sends as an empty map, and so clears. {@code Name} and {@code Type} are + * create-only, so a change to either replaces the application. Neither path starts or stops the application: an update + * a STARTED application cannot take fails as UpdateApplication refuses it, and so does the delete of one. + */ +@ApplicationScoped +public class EmrServerlessCfnProvisioner implements CfnResourceProvisioner { + + private static final String TYPE = "AWS::EMRServerless::Application"; + /** What an in-place update is about to change, for {@link #rollbackUpdate} to put back. */ + static final String SNAPSHOT_ATTR = "__FlociEmrServerlessApplicationUpdateSnapshot"; + private static final ObjectMapper MAPPER = new ObjectMapper().findAndRegisterModules(); + private static final String INITIAL_CAPACITY = "InitialCapacity"; + /** The settings UpdateApplication takes, which CreateApplication takes too, by their template names. */ + private static final List SETTINGS = List.of("ReleaseLabel", "Architecture", "InitialCapacity", + "MaximumCapacity", "AutoStartConfiguration", "AutoStopConfiguration", "NetworkConfiguration", + "ImageConfiguration", "WorkerTypeSpecifications", "MonitoringConfiguration", "RuntimeConfiguration", + "SchedulerConfiguration", "InteractiveConfiguration", "IdentityCenterConfiguration"); + /** The settings an empty value clears, which is how a rollback takes back one the application did not hold. */ + private static final Set CLEARED_WHEN_EMPTY = + Set.of("initialCapacity", "imageConfiguration", "workerTypeSpecifications"); + private static final String SCHEDULER = "schedulerConfiguration"; + /** The registry schema's {@code Architecture} enum, which model validation holds a template to. */ + private static final Set ARCHITECTURES = Set.of("ARM64", "X86_64"); + /** The schema's read-only properties, which a user cannot set. */ + private static final List READ_ONLY = List.of("ApplicationId", "Arn"); + + private final EmrServerlessService applications; + private final EmrServerlessJobRunService jobRuns; + + @Inject + public EmrServerlessCfnProvisioner(EmrServerlessService applications, EmrServerlessJobRunService jobRuns) { + this.applications = applications; + this.jobRuns = jobRuns; + } + + @Override + public Set resourceTypes() { + return Set.of(TYPE); + } + + @Override + public boolean hasReplacementUpdate(StackResource resource) { + return ReplacementCleanup.hasReplacement(resource); + } + + @Override + public String updateCleanupPhysicalId(StackResource resource) { + return ReplacementCleanup.cleanupPhysicalId(resource); + } + + @Override + public UpdateCleanupResult completeUpdate(StackResource resource) { + resource.getAttributes().remove(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, SNAPSHOT_ATTR); + } + + @Override + public void clearUpdate(StackResource resource) { + resource.getAttributes().remove(SNAPSHOT_ATTR); + ReplacementCleanup.clear(resource); + } + + /** + * A replacement or a stub migration is undone through the cleanup record, and an in-place update from the snapshot + * taken before it. The snapshot is spent only once the restore succeeded, so one that throws leaves it for + * ContinueUpdateRollback to retry. + */ + @Override + public boolean rollbackUpdate(StackResource resource) { + if (ReplacementCleanup.rollback(resource, this::delete)) { + return true; + } + JsonNode snapshot = CfnRollback.updateSnapshot(resource, SNAPSHOT_ATTR); + if (snapshot == null) { + return false; + } + restore(snapshot, true, true); + resource.getAttributes().remove(SNAPSHOT_ATTR); + return true; + } + + @Override + public void provision(StackResource r, JsonNode props, ProvisionContext ctx) { + // A snapshot describes the update in flight; one an earlier update left behind is stale. + r.getAttributes().remove(SNAPSHOT_ATTR); + if (ctx.isUpdate()) { + ReplacementCleanup.endRollbackRetry(r); + } + Map attributesBefore = new HashMap<>(r.getAttributes()); + JsonNode template = new CfnPropertyTypes.HandlerReader(ctx.engine()).read(TYPE, props); + checkTemplate(template); + Map tags = tags(template); + // A stack from before this type had a provisioner, or deployed while EMR Serverless was disabled, holds the + // dispatcher's stub, which names no application: taking over its id is a create. + boolean stub = CfnResourceDispatcher.isStub(ctx.priorPhysicalId(), attributesBefore); + PropertyChanges changes = ctx.isUpdate() && !stub ? ctx.changes(TYPE, props) : null; + if (changes != null && !changes.requiresReplacement()) { + updateInPlace(r, ctx, template, changes, tags); + } else { + CreateApplicationRequest request = MAPPER.convertValue(settings(template, SETTINGS), + CreateApplicationRequest.class); + request.setName(template.path("Name").textValue()); + request.setType(template.path("Type").textValue()); + request.setTags(tags.isEmpty() ? null : tags); + request.setClientToken(UUID.randomUUID().toString()); + publish(r, applications.createApplication(request)); + } + ReplacementCleanup.record(r, ctx, attributesBefore); + } + + /** + * What model validation checks that the vendored shapes do not hold: the {@code Architecture} enum, in the schema + * validator's wording. Also the read-only properties, which the schema guide says a user cannot set, refused as + * AWS's handler for EMR on EKS's virtual cluster refuses its {@code Arn}. + */ + private static void checkTemplate(JsonNode template) { + String architecture = template.path("Architecture").textValue(); + if (architecture != null && !ARCHITECTURES.contains(architecture)) { + throw CfnPropertyTypes.modelValidation("#/Architecture: " + architecture + " is not a valid enum value)"); + } + for (String readOnly : READ_ONLY) { + if (template.has(readOnly)) { + throw new AwsException("InvalidRequest", + readOnly + " is a ReadOnly property which cannot be specified in the template", 400); + } + } + } + + /** + * The update AWS's handler makes, from the application the prior physical id names: it fails, as the handler's + * check of the application does, when that one is gone. The application's settings and tags as they are now are + * snapshotted first, so a later resource's failure puts them back, and a failure here puts back what it had changed + * before it propagates: nothing, when UpdateApplication refused the update. + */ + private void updateInPlace(StackResource r, ProvisionContext ctx, JsonNode template, PropertyChanges changes, + Map tags) { + String id = ctx.priorPhysicalId(); + Application live = applications.findLive(id).orElseThrow(() -> new AwsException("NotFound", + "Resource of type '" + TYPE + "' with identifier '" + id + "' was not found.", 404)); + ObjectNode update = updatedSettings(template, changes); + ObjectNode snapshot = MAPPER.createObjectNode(); + snapshot.put("applicationId", id); + snapshot.put("arn", live.getArn()); + snapshot.set("settings", restoring(live, update)); + snapshot.set("tags", MAPPER.valueToTree(live.getTags() == null ? Map.of() : live.getTags())); + publish(r, live); + r.getAttributes().put(SNAPSHOT_ATTR, snapshot.toString()); + AtomicBoolean settingsChanged = new AtomicBoolean(); + AtomicBoolean tagsTouched = new AtomicBoolean(); + CfnRollback.guarded(r, ctx, false, () -> { }, + () -> restore(snapshot, settingsChanged.get(), tagsTouched.get()), () -> { + if (!update.isEmpty()) { + jobRuns.updateApplication(id, MAPPER.convertValue(update, UpdateApplicationRequest.class)); + settingsChanged.set(true); + } + tagsTouched.set(true); + reconcileTags(live.getArn(), tags); + }); + } + + /** + * The settings the template added or changed, in the API's shape, and an empty {@code initialCapacity} when it + * dropped {@code InitialCapacity}, which AWS's handler sends whether the template has one or not. + */ + private static ObjectNode updatedSettings(JsonNode template, PropertyChanges changes) { + List sent = new ArrayList<>(); + for (String name : SETTINGS) { + PropertyChanges.Kind kind = changes.kindOf(name); + if (kind == PropertyChanges.Kind.ADDED || kind == PropertyChanges.Kind.CHANGED) { + sent.add(name); + } + } + ObjectNode update = settings(template, sent); + if (changes.kindOf(INITIAL_CAPACITY) == PropertyChanges.Kind.DROPPED) { + update.putObject("initialCapacity"); + } + return update; + } + + /** + * What puts back each setting {@code update} sends: the application's own value, or an empty one where that clears + * a setting it did not hold. Any other setting it did not hold stays as the update left it, which is what AWS's + * rollback, an update back to the previous template, does too: a scheduler configuration the update set where an + * empty one had turned queuing off among them, as a STARTED application cannot take an empty one back. + */ + private static ObjectNode restoring(Application live, ObjectNode update) { + ObjectNode restore = MAPPER.createObjectNode(); + JsonNode held = MAPPER.valueToTree(live); + update.fieldNames().forEachRemaining(member -> { + JsonNode value = held.get(member); + if (value != null && !value.isNull()) { + restore.set(member, SCHEDULER.equals(member) ? heldScheduler(value, update.get(member)) : value); + } else if (CLEARED_WHEN_EMPTY.contains(member)) { + restore.putObject(member); + } + }); + return restore; + } + + /** + * The held scheduler configuration's members the update sent: a member it left out kept its value, and the one + * change a STARTED application takes, {@code maxConcurrentRuns}, stays the one its restore makes. An update that + * turned queuing off with an empty one is undone with every member. + */ + private static JsonNode heldScheduler(JsonNode held, JsonNode sent) { + if (sent.isEmpty()) { + return held; + } + ObjectNode restore = MAPPER.createObjectNode(); + sent.fieldNames().forEachRemaining(member -> { + if (held.has(member)) { + restore.set(member, held.get(member)); + } + }); + return restore; + } + + /** Puts back the settings and the tags the snapshot holds, each when the update got as far as changing it. */ + private void restore(JsonNode snapshot, boolean settingsChanged, boolean tagsTouched) { + String id = snapshot.path("applicationId").asText(); + JsonNode settings = snapshot.path("settings"); + if (settingsChanged && !settings.isEmpty()) { + jobRuns.updateApplication(id, MAPPER.convertValue(settings, UpdateApplicationRequest.class)); + } + if (tagsTouched) { + Map tags = new LinkedHashMap<>(); + snapshot.path("tags").properties().forEach(tag -> tags.put(tag.getKey(), tag.getValue().asText())); + reconcileTags(snapshot.path("arn").asText(), tags); + } + } + + /** Drives the application's tags to {@code desired}, removing every other, as AWS's handler does. */ + private void reconcileTags(String arn, Map desired) { + EmrServerlessService.ResourceArn resource = applications.resourceArn(arn); + CfnRollback.reconcileTags(applications.listTags(resource).keySet(), desired, + dropped -> applications.untagResource(resource, dropped), + added -> applications.tagResource(resource, added)); + } + + /** The template's settings named in {@code names}, as the API names and shapes them. */ + private static ObjectNode settings(JsonNode template, List names) { + ObjectNode settings = MAPPER.createObjectNode(); + for (String name : names) { + JsonNode value = template.get(name); + if (value != null) { + settings.set(apiName(name), apiShape(name, value)); + } + } + return settings; + } + + /** + * A template value in the API's shape: each member named as the API names it, the {@code Key}/{@code Value} + * lists the template gives {@code InitialCapacity} and {@code LogTypeMap} (the API's {@code logTypes}) in as maps, + * and the keys of the worker type and configuration property maps kept as they are. + */ + private static JsonNode apiShape(String name, JsonNode value) { + return switch (name) { + case INITIAL_CAPACITY, "LogTypeMap" -> keyed(value); + case "WorkerTypeSpecifications" -> byKey(value); + case "Properties" -> value; + default -> { + if (value.isArray()) { + ArrayNode items = MAPPER.createArrayNode(); + value.forEach(item -> items.add(apiShape("", item))); + yield items; + } + if (!value.isObject()) { + yield value; + } + ObjectNode shaped = MAPPER.createObjectNode(); + value.properties().forEach(member -> shaped.set(apiName(member.getKey()), + apiShape(member.getKey(), member.getValue()))); + yield shaped; + } + }; + } + + private static String apiName(String name) { + return "LogTypeMap".equals(name) ? "logTypes" : CfnApiShapeConverter.lowerFirst(name); + } + + private static ObjectNode keyed(JsonNode entries) { + ObjectNode map = MAPPER.createObjectNode(); + entries.forEach(entry -> map.set(entry.path("Key").asText(), apiShape("", entry.path("Value")))); + return map; + } + + private static ObjectNode byKey(JsonNode object) { + ObjectNode map = MAPPER.createObjectNode(); + object.properties().forEach(member -> map.set(member.getKey(), apiShape("", member.getValue()))); + return map; + } + + private static Map tags(JsonNode template) { + Map tags = new LinkedHashMap<>(); + template.path("Tags").forEach(tag -> tags.put(tag.path("Key").asText(), tag.path("Value").asText())); + return tags; + } + + private static void publish(StackResource r, Application app) { + r.setPhysicalId(app.getApplicationId()); + r.getAttributes().put("ApplicationId", app.getApplicationId()); + r.getAttributes().put("Arn", app.getArn()); + } + + /** + * Deletes the application unless it is already gone, which a deleted one is, being left TERMINATED. One that is + * not stopped or created fails, as DeleteApplication refuses it and AWS's handler does not stop it first. + */ + @Override + public void delete(String resourceType, String physicalId, String region) { + applications.whileLive(physicalId, app -> applications.deleteApplication(physicalId)); + } +} diff --git a/src/main/resources/aws/cfn-property-types.json b/src/main/resources/aws/cfn-property-types.json index 074e470f73..434cfd697b 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::EMRServerless::Application": "AWS::EMRServerless::Application", "AWS::Events::Rule": "AWS::Events::Rule", "AWS::Lambda::Function": "AWS::Lambda::Function", "AWS::Lambda::LayerVersion": "AWS::Lambda::LayerVersion", @@ -1949,6 +1950,389 @@ "Enabled": "Boolean" } }, + "AWS::EMRServerless::Application": { + "type": "structure", + "members": { + "Architecture": "AWS::EMRServerless::Application/Architecture", + "Name": "AWS::EMRServerless::Application.Name", + "ReleaseLabel": "AWS::EMRServerless::Application.ReleaseLabel", + "Type": "String", + "InitialCapacity": "AWS::EMRServerless::Application/InitialCapacityConfigMap", + "MaximumCapacity": "AWS::EMRServerless::Application/MaximumAllowedResources", + "Tags": "AWS::EMRServerless::Application.Tags", + "AutoStartConfiguration": "AWS::EMRServerless::Application/AutoStartConfiguration", + "AutoStopConfiguration": "AWS::EMRServerless::Application/AutoStopConfiguration", + "ImageConfiguration": "AWS::EMRServerless::Application/ImageConfigurationInput", + "MonitoringConfiguration": "AWS::EMRServerless::Application/MonitoringConfiguration", + "RuntimeConfiguration": "AWS::EMRServerless::Application/ConfigurationList", + "InteractiveConfiguration": "AWS::EMRServerless::Application/InteractiveConfiguration", + "NetworkConfiguration": "AWS::EMRServerless::Application/NetworkConfiguration", + "Arn": "AWS::EMRServerless::Application.Arn", + "ApplicationId": "AWS::EMRServerless::Application.ApplicationId", + "WorkerTypeSpecifications": "AWS::EMRServerless::Application/WorkerTypeSpecificationInputMap", + "SchedulerConfiguration": "AWS::EMRServerless::Application/SchedulerConfiguration", + "IdentityCenterConfiguration": "AWS::EMRServerless::Application/IdentityCenterConfiguration" + }, + "required": [ + "ReleaseLabel", + "Type" + ] + }, + "AWS::EMRServerless::Application.ApplicationId": { + "type": "string", + "minLength": 1, + "maxLength": 64 + }, + "AWS::EMRServerless::Application.Arn": { + "type": "string", + "pattern": "^arn:(aws[a-zA-Z0-9-]*):emr-serverless:.+:(\\d{12}):\\/applications\\/[0-9a-zA-Z]+$" + }, + "AWS::EMRServerless::Application.Name": { + "type": "string", + "minLength": 1, + "maxLength": 64, + "pattern": "^[A-Za-z0-9._\\/#-]+$" + }, + "AWS::EMRServerless::Application.ReleaseLabel": { + "type": "string", + "minLength": 1, + "maxLength": 64, + "pattern": "^[A-Za-z0-9._/-]+$" + }, + "AWS::EMRServerless::Application.Tags": { + "type": "list", + "member": "AWS::EMRServerless::Application/Tag" + }, + "AWS::EMRServerless::Application/Architecture": { + "type": "string" + }, + "AWS::EMRServerless::Application/AutoStartConfiguration": { + "type": "structure", + "members": { + "Enabled": "Boolean" + } + }, + "AWS::EMRServerless::Application/AutoStopConfiguration": { + "type": "structure", + "members": { + "Enabled": "Boolean", + "IdleTimeoutMinutes": "Integer" + } + }, + "AWS::EMRServerless::Application/Classification": { + "type": "string", + "minLength": 1, + "maxLength": 1024, + "pattern": ".*\\S.*" + }, + "AWS::EMRServerless::Application/CloudWatchLoggingConfiguration": { + "type": "structure", + "members": { + "Enabled": "Boolean", + "LogGroupName": "AWS::EMRServerless::Application/LogGroupName", + "LogStreamNamePrefix": "AWS::EMRServerless::Application/LogStreamNamePrefix", + "EncryptionKeyArn": "AWS::EMRServerless::Application/EncryptionKeyArn", + "LogTypeMap": "AWS::EMRServerless::Application/CloudWatchLoggingConfiguration.LogTypeMap" + } + }, + "AWS::EMRServerless::Application/CloudWatchLoggingConfiguration.LogTypeMap": { + "type": "list", + "member": "AWS::EMRServerless::Application/LogTypeMapKeyValuePair" + }, + "AWS::EMRServerless::Application/ConfigurationList": { + "type": "list", + "member": "AWS::EMRServerless::Application/ConfigurationObject" + }, + "AWS::EMRServerless::Application/ConfigurationObject": { + "type": "structure", + "members": { + "Classification": "AWS::EMRServerless::Application/Classification", + "Properties": "AWS::EMRServerless::Application/ConfigurationObject.Properties", + "Configurations": "AWS::EMRServerless::Application/ConfigurationObject.Configurations" + }, + "required": [ + "Classification" + ] + }, + "AWS::EMRServerless::Application/ConfigurationObject.Configurations": { + "type": "list", + "member": "AWS::EMRServerless::Application/ConfigurationObject" + }, + "AWS::EMRServerless::Application/ConfigurationObject.Properties": { + "type": "map", + "value": "AWS::EMRServerless::Application/SensitivePropertiesMap" + }, + "AWS::EMRServerless::Application/CpuSize": { + "type": "string", + "minLength": 1, + "maxLength": 15, + "pattern": "^[1-9][0-9]*(\\s)?(vCPU|vcpu|VCPU)?$" + }, + "AWS::EMRServerless::Application/DiskSize": { + "type": "string", + "minLength": 1, + "maxLength": 15, + "pattern": "^[1-9][0-9]*(\\s)?(GB|gb|gB|Gb)$" + }, + "AWS::EMRServerless::Application/DiskType": { + "type": "string", + "pattern": "^(SHUFFLE_OPTIMIZED|[Ss]huffle_[Oo]ptimized|STANDARD|[Ss]tandard)$" + }, + "AWS::EMRServerless::Application/EncryptionKeyArn": { + "type": "string", + "minLength": 20, + "maxLength": 2048, + "pattern": "^arn:(aws[a-zA-Z0-9-]*):kms:[a-zA-Z0-9\\-]*:(\\d{12})?:key\\/[a-zA-Z0-9-]+$" + }, + "AWS::EMRServerless::Application/IdentityCenterConfiguration": { + "type": "structure", + "members": { + "IdentityCenterInstanceArn": "AWS::EMRServerless::Application/IdentityCenterConfiguration.IdentityCenterInstanceArn", + "UserBackgroundSessionsEnabled": "Boolean" + } + }, + "AWS::EMRServerless::Application/IdentityCenterConfiguration.IdentityCenterInstanceArn": { + "type": "string", + "minLength": 1, + "maxLength": 1024, + "pattern": "^arn:(aws[a-zA-Z0-9-]*):sso:::instance/(sso)?ins-[a-zA-Z0-9-.]{16}$" + }, + "AWS::EMRServerless::Application/ImageConfigurationInput": { + "type": "structure", + "members": { + "ImageUri": "AWS::EMRServerless::Application/ImageConfigurationInput.ImageUri" + } + }, + "AWS::EMRServerless::Application/ImageConfigurationInput.ImageUri": { + "type": "string", + "minLength": 1, + "maxLength": 1024, + "pattern": "^([a-z0-9]+[a-z0-9-.]*)\\/((?:[a-z0-9]+(?:[._-][a-z0-9]+)*\\/)*[a-z0-9]+(?:[._-][a-z0-9]+)*)(?:\\:([a-zA-Z0-9_][a-zA-Z0-9-._]{0,299})|@(sha256:[0-9a-f]{64}))$" + }, + "AWS::EMRServerless::Application/InitialCapacityConfig": { + "type": "structure", + "members": { + "WorkerCount": "Integer", + "WorkerConfiguration": "AWS::EMRServerless::Application/WorkerConfiguration" + }, + "required": [ + "WorkerCount", + "WorkerConfiguration" + ] + }, + "AWS::EMRServerless::Application/InitialCapacityConfigKeyValuePair": { + "type": "structure", + "members": { + "Key": "AWS::EMRServerless::Application/InitialCapacityConfigKeyValuePair.Key", + "Value": "AWS::EMRServerless::Application/InitialCapacityConfig" + }, + "required": [ + "Key", + "Value" + ] + }, + "AWS::EMRServerless::Application/InitialCapacityConfigKeyValuePair.Key": { + "type": "string", + "minLength": 1, + "maxLength": 50, + "pattern": "^[a-zA-Z]+[-_]*[a-zA-Z]+$" + }, + "AWS::EMRServerless::Application/InitialCapacityConfigMap": { + "type": "list", + "member": "AWS::EMRServerless::Application/InitialCapacityConfigKeyValuePair" + }, + "AWS::EMRServerless::Application/InteractiveConfiguration": { + "type": "structure", + "members": { + "LivyEndpointEnabled": "Boolean", + "StudioEnabled": "Boolean", + "SessionEnabled": "Boolean" + } + }, + "AWS::EMRServerless::Application/LogGroupName": { + "type": "string", + "minLength": 1, + "maxLength": 512, + "pattern": "^[\\.\\-_/#A-Za-z0-9]+$" + }, + "AWS::EMRServerless::Application/LogStreamNamePrefix": { + "type": "string", + "minLength": 1, + "maxLength": 512, + "pattern": "^[^:*]*$" + }, + "AWS::EMRServerless::Application/LogTypeList": { + "type": "list", + "member": "AWS::EMRServerless::Application/LogTypeString" + }, + "AWS::EMRServerless::Application/LogTypeMapKeyValuePair": { + "type": "structure", + "members": { + "Key": "AWS::EMRServerless::Application/WorkerTypeString", + "Value": "AWS::EMRServerless::Application/LogTypeList" + }, + "required": [ + "Key", + "Value" + ] + }, + "AWS::EMRServerless::Application/LogTypeString": { + "type": "string", + "minLength": 1, + "maxLength": 50, + "pattern": "^[a-zA-Z]+[-_]*[a-zA-Z]+$" + }, + "AWS::EMRServerless::Application/ManagedPersistenceMonitoringConfiguration": { + "type": "structure", + "members": { + "Enabled": "Boolean", + "EncryptionKeyArn": "AWS::EMRServerless::Application/EncryptionKeyArn" + } + }, + "AWS::EMRServerless::Application/MaximumAllowedResources": { + "type": "structure", + "members": { + "Cpu": "AWS::EMRServerless::Application/CpuSize", + "Memory": "AWS::EMRServerless::Application/MemorySize", + "Disk": "AWS::EMRServerless::Application/DiskSize" + }, + "required": [ + "Cpu", + "Memory" + ] + }, + "AWS::EMRServerless::Application/MemorySize": { + "type": "string", + "minLength": 1, + "maxLength": 15, + "pattern": "^[1-9][0-9]*(\\s)?(GB|gb|gB|Gb)?$" + }, + "AWS::EMRServerless::Application/MonitoringConfiguration": { + "type": "structure", + "members": { + "S3MonitoringConfiguration": "AWS::EMRServerless::Application/S3MonitoringConfiguration", + "ManagedPersistenceMonitoringConfiguration": "AWS::EMRServerless::Application/ManagedPersistenceMonitoringConfiguration", + "CloudWatchLoggingConfiguration": "AWS::EMRServerless::Application/CloudWatchLoggingConfiguration", + "PrometheusMonitoringConfiguration": "AWS::EMRServerless::Application/PrometheusMonitoringConfiguration" + } + }, + "AWS::EMRServerless::Application/NetworkConfiguration": { + "type": "structure", + "members": { + "SubnetIds": "AWS::EMRServerless::Application/NetworkConfiguration.SubnetIds", + "SecurityGroupIds": "AWS::EMRServerless::Application/NetworkConfiguration.SecurityGroupIds" + } + }, + "AWS::EMRServerless::Application/NetworkConfiguration.SecurityGroupIds": { + "type": "list", + "member": "AWS::EMRServerless::Application/SecurityGroupId" + }, + "AWS::EMRServerless::Application/NetworkConfiguration.SubnetIds": { + "type": "list", + "member": "AWS::EMRServerless::Application/SubnetId" + }, + "AWS::EMRServerless::Application/PrometheusMonitoringConfiguration": { + "type": "structure", + "members": { + "RemoteWriteUrl": "AWS::EMRServerless::Application/RemoteWriteUrl" + } + }, + "AWS::EMRServerless::Application/RemoteWriteUrl": { + "type": "string", + "minLength": 1, + "maxLength": 10280, + "pattern": "^https://aps-workspaces.([a-z]{2}-[a-z-]{1,20}-[1-9]).amazonaws(.[0-9A-Za-z]{2,4})+/workspaces/[-_.0-9A-Za-z]{1,100}/api/v1/remote_write$" + }, + "AWS::EMRServerless::Application/S3MonitoringConfiguration": { + "type": "structure", + "members": { + "LogUri": "AWS::EMRServerless::Application/UriString", + "EncryptionKeyArn": "AWS::EMRServerless::Application/EncryptionKeyArn" + } + }, + "AWS::EMRServerless::Application/SchedulerConfiguration": { + "type": "structure", + "members": { + "QueueTimeoutMinutes": "Integer", + "MaxConcurrentRuns": "Integer" + } + }, + "AWS::EMRServerless::Application/SecurityGroupId": { + "type": "string", + "minLength": 1, + "maxLength": 32, + "pattern": "^[-0-9a-zA-Z]+" + }, + "AWS::EMRServerless::Application/SensitivePropertiesMap": { + "type": "string", + "minLength": 1, + "maxLength": 1024, + "pattern": ".*\\S.*" + }, + "AWS::EMRServerless::Application/SubnetId": { + "type": "string", + "minLength": 1, + "maxLength": 32, + "pattern": "^[-0-9a-zA-Z]+" + }, + "AWS::EMRServerless::Application/Tag": { + "type": "structure", + "members": { + "Key": "AWS::EMRServerless::Application/Tag.Key", + "Value": "AWS::EMRServerless::Application/Tag.Value" + }, + "required": [ + "Key", + "Value" + ] + }, + "AWS::EMRServerless::Application/Tag.Key": { + "type": "string", + "minLength": 1, + "maxLength": 128, + "pattern": "^[A-Za-z0-9 /_.:=+@-]+$" + }, + "AWS::EMRServerless::Application/Tag.Value": { + "type": "string", + "minLength": 0, + "maxLength": 256, + "pattern": "^[A-Za-z0-9 /_.:=+@-]*$" + }, + "AWS::EMRServerless::Application/UriString": { + "type": "string", + "minLength": 1, + "maxLength": 10280, + "pattern": "[\\u0020-\\uD7FF\\uE000-\\uFFFD\\uD800\\uDBFF-\\uDC00\\uDFFF\\r\\n\\t]*" + }, + "AWS::EMRServerless::Application/WorkerConfiguration": { + "type": "structure", + "members": { + "Cpu": "AWS::EMRServerless::Application/CpuSize", + "Memory": "AWS::EMRServerless::Application/MemorySize", + "Disk": "AWS::EMRServerless::Application/DiskSize", + "DiskType": "AWS::EMRServerless::Application/DiskType" + }, + "required": [ + "Cpu", + "Memory" + ] + }, + "AWS::EMRServerless::Application/WorkerTypeSpecificationInput": { + "type": "structure", + "members": { + "ImageConfiguration": "AWS::EMRServerless::Application/ImageConfigurationInput" + } + }, + "AWS::EMRServerless::Application/WorkerTypeSpecificationInputMap": { + "type": "map", + "value": "AWS::EMRServerless::Application/WorkerTypeSpecificationInput" + }, + "AWS::EMRServerless::Application/WorkerTypeString": { + "type": "string", + "minLength": 1, + "maxLength": 50, + "pattern": "^[a-zA-Z]+[-_]*[a-zA-Z]+$" + }, "AWS::Events::Rule": { "type": "structure", "members": { diff --git a/src/main/resources/cloudformation/create-only-properties.json b/src/main/resources/cloudformation/create-only-properties.json index c1b2f013d8..53704904d0 100644 --- a/src/main/resources/cloudformation/create-only-properties.json +++ b/src/main/resources/cloudformation/create-only-properties.json @@ -189,7 +189,9 @@ "KeyAlgorithm", "DomainName", "CertificateAuthorityArn", - "CertificateExport" + "CertificateExport", + "RootHierarchyType", + "CertificateUsage" ], "AWS::CloudFormation::CustomResource": [ "ServiceToken" @@ -526,6 +528,10 @@ "AmiType", "Subnets" ], + "AWS::EMRServerless::Application": [ + "Name", + "Type" + ], "AWS::ElastiCache::CacheCluster": [ "Port", "SnapshotArns", 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 71fe956a75..66d021a952 100644 --- a/src/test/java/io/floci/aws/services/cloudformation/CfnProvisionerFixture.java +++ b/src/test/java/io/floci/aws/services/cloudformation/CfnProvisionerFixture.java @@ -76,6 +76,7 @@ import io.floci.aws.services.cloudformation.provisioners.EksCfnProvisioner; import io.floci.aws.services.cloudformation.provisioners.ElastiCacheCfnProvisioner; import io.floci.aws.services.cloudformation.provisioners.ElastiCacheServerlessCfnProvisioner; import io.floci.aws.services.cloudformation.provisioners.ElbV2CfnProvisioner; +import io.floci.aws.services.cloudformation.provisioners.EmrServerlessCfnProvisioner; import io.floci.aws.services.cloudformation.provisioners.EventsArchiveCfnProvisioner; import io.floci.aws.services.cloudformation.provisioners.EventsCfnProvisioner; import io.floci.aws.services.cloudformation.provisioners.EventsV2CfnProvisioner; @@ -153,6 +154,8 @@ 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.emrserverless.EmrServerlessJobRunService; +import io.floci.aws.services.emrserverless.EmrServerlessService; import io.floci.aws.services.eventbridge.EventBridgeService; import io.floci.aws.services.eventbridgev2.EventBridgeV2Service; import io.floci.aws.services.firehose.FirehoseService; @@ -277,6 +280,8 @@ final class CfnProvisionerFixture { private CloudTrailService cloudTrailService; private SchedulerService schedulerService; private CodeDeployService codeDeployService; + private EmrServerlessService emrServerlessService; + private EmrServerlessJobRunService emrServerlessJobRunService; private TransferService transferService; // Services that back a provisioner without being a constructor argument of the // dispatcher. They exist only so inferredProvisioners() can wire their provisioner. @@ -563,6 +568,9 @@ final class CfnProvisionerFixture { if (codeDeployService != null) { discovered.add(new CodeDeployCfnProvisioner(codeDeployService)); } + if (emrServerlessService != null && emrServerlessJobRunService != null) { + discovered.add(new EmrServerlessCfnProvisioner(emrServerlessService, emrServerlessJobRunService)); + } if (transferService != null) { discovered.add(new TransferCfnProvisioner(transferService)); } @@ -793,6 +801,16 @@ final class CfnProvisionerFixture { return this; } + public Builder emrServerless(EmrServerlessService v) { + this.emrServerlessService = v; + return this; + } + + public Builder emrServerlessJobRuns(EmrServerlessJobRunService v) { + this.emrServerlessJobRunService = v; + return this; + } + public Builder transfer(TransferService v) { this.transferService = v; return this; diff --git a/src/test/java/io/floci/aws/services/cloudformation/EmrServerlessApplicationCfnIntegrationTest.java b/src/test/java/io/floci/aws/services/cloudformation/EmrServerlessApplicationCfnIntegrationTest.java new file mode 100644 index 0000000000..dd004c86c3 --- /dev/null +++ b/src/test/java/io/floci/aws/services/cloudformation/EmrServerlessApplicationCfnIntegrationTest.java @@ -0,0 +1,119 @@ +package io.floci.aws.services.cloudformation; + +import io.floci.aws.testing.CfnStackWaits; +import io.floci.aws.testing.CfnTestStack; +import io.floci.aws.testing.EmrServerlessRequests; +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 org.hamcrest.Matchers.aMapWithSize; +import static org.hamcrest.Matchers.anEmptyMap; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasEntry; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; + +/** + * Provisions {@code AWS::EMRServerless::Application} through a stack and reads the application back through EMR + * Serverless: the template's settings reach it in the API's shape, {@code Ref} and {@code Fn::GetAtt} name it, an + * update changes it in place, a later resource's failure puts it back, a new {@code Name} replaces it, and deleting + * the stack deletes it. + */ +@QuarkusTest +class EmrServerlessApplicationCfnIntegrationTest { + + @RegisterExtension + final CfnTestStack stack = new CfnTestStack("emr-serverless-app-cfn-it"); + + @BeforeAll + static void configureRestAssured() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @Test + void createUpdateRollBackReplaceAndDeleteAnApplication() { + Stack created = stack.create(template("etl", 30, "v1", true, false)); + String id = output(created, "Ref"); + assertEquals(id, output(created, "ApplicationId")); + assertEquals("arn:aws:emr-serverless:us-east-1:000000000000:/applications/" + id, output(created, "Arn")); + getApplication(id).statusCode(200) + .body("application.name", equalTo("etl")) + .body("application.type", equalTo("SPARK")) + .body("application.state", equalTo("CREATED")) + .body("application.autoStopConfiguration.idleTimeoutMinutes", equalTo(30)) + .body("application.initialCapacity.Driver.workerCount", equalTo(2)) + .body("application.initialCapacity.Driver.workerConfiguration.cpu", equalTo("2 vCPU")) + .body("application.monitoringConfiguration.cloudWatchLoggingConfiguration.logTypes.SPARK_DRIVER[0]", + equalTo("STDOUT")) + .body("application.runtimeConfiguration[0].properties", hasEntry("spark.driver.cores", "2")) + .body("application.tags", aMapWithSize(1)) + .body("application.tags.stage", equalTo("v1")); + + // The update drops InitialCapacity, which clears it, and changes the idle timeout and the tag in place. + Stack updated = stack.update(template("etl", 45, "v2", false, false), "UPDATE_COMPLETE"); + assertEquals(id, output(updated, "Ref")); + getApplication(id).statusCode(200) + .body("application.autoStopConfiguration.idleTimeoutMinutes", equalTo(45)) + .body("application.initialCapacity", anEmptyMap()) + .body("application.tags.stage", equalTo("v2")); + + stack.update(template("etl", 60, "v3", false, true), "UPDATE_ROLLBACK_COMPLETE"); + getApplication(id).statusCode(200) + .body("application.autoStopConfiguration.idleTimeoutMinutes", equalTo(45)) + .body("application.tags.stage", equalTo("v2")); + + // Name is create-only: a new one replaces the application, and the committed update deletes the old one. + Stack replaced = stack.update(template("etl-2", 45, "v2", false, false), "UPDATE_COMPLETE"); + String replacement = output(replaced, "Ref"); + assertNotEquals(id, replacement); + getApplication(replacement).statusCode(200).body("application.name", equalTo("etl-2")); + getApplication(id).statusCode(200).body("application.state", equalTo("TERMINATED")); + + CfnStackWaits.deleteStack(stack.name()); + + getApplication(replacement).statusCode(200).body("application.state", equalTo("TERMINATED")); + } + + private static String template(String name, int idleMinutes, String stage, boolean initialCapacity, + boolean laterFails) { + return """ + { + "Resources": { + "App": { + "Type": "AWS::EMRServerless::Application", + "Properties": { + "Name": "%s", + "ReleaseLabel": "emr-7.5.0", + "Type": "SPARK", + "AutoStopConfiguration": {"Enabled": true, "IdleTimeoutMinutes": %d},%s + "MonitoringConfiguration": {"CloudWatchLoggingConfiguration": {"Enabled": true, + "LogTypeMap": [{"Key": "SPARK_DRIVER", "Value": ["STDOUT"]}]}}, + "RuntimeConfiguration": [{"Classification": "spark-defaults", + "Properties": {"spark.driver.cores": "2"}}], + "Tags": [{"Key": "stage", "Value": "%s"}] + } + }%s + }, + "Outputs": { + "Ref": {"Value": {"Ref": "App"}}, + "ApplicationId": {"Value": {"Fn::GetAtt": ["App", "ApplicationId"]}}, + "Arn": {"Value": {"Fn::GetAtt": ["App", "Arn"]}} + } + } + """.formatted(name, idleMinutes, initialCapacity ? """ + + "InitialCapacity": [{"Key": "Driver", "Value": {"WorkerCount": 2, + "WorkerConfiguration": {"Cpu": "2 vCPU", "Memory": "4 GB"}}}],""" : "", stage, + laterFails ? CfnStackWaits.failingResourceAfter("App") : ""); + } + + private static ValidatableResponse getApplication(String id) { + return EmrServerlessRequests.emrServerless("us-east-1").when().get("/applications/" + id).then(); + } +} diff --git a/src/test/java/io/floci/aws/services/cloudformation/provisioners/EmrServerlessCfnProvisionerTest.java b/src/test/java/io/floci/aws/services/cloudformation/provisioners/EmrServerlessCfnProvisionerTest.java new file mode 100644 index 0000000000..d20b5033b7 --- /dev/null +++ b/src/test/java/io/floci/aws/services/cloudformation/provisioners/EmrServerlessCfnProvisionerTest.java @@ -0,0 +1,427 @@ +package io.floci.aws.services.cloudformation.provisioners; + +import com.fasterxml.jackson.core.JsonProcessingException; +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.CloudFormationTemplateEngine; +import io.floci.aws.services.cloudformation.model.StackResource; +import io.floci.aws.services.emrserverless.EmrServerlessJobRunService; +import io.floci.aws.services.emrserverless.EmrServerlessService; +import io.floci.aws.services.emrserverless.model.Application; +import io.floci.aws.services.emrserverless.model.AutoStopConfiguration; +import io.floci.aws.services.emrserverless.model.CreateApplicationRequest; +import io.floci.aws.services.emrserverless.model.InitialCapacityConfig; +import io.floci.aws.services.emrserverless.model.SchedulerConfiguration; +import io.floci.aws.services.emrserverless.model.UpdateApplicationRequest; +import io.floci.aws.services.emrserverless.model.WorkerConfiguration; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; + +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.function.Consumer; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +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.eq; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +/** {@code AWS::EMRServerless::Application} in isolation, with the EMR Serverless services mocked. */ +class EmrServerlessCfnProvisionerTest { + + private static final String ID = "00fexampleapp01"; + private static final String ARN = "arn:aws:emr-serverless:us-east-1:000000000000:/applications/" + ID; + private static final ObjectMapper MAPPER = new ObjectMapper(); + private static final EmrServerlessService.ResourceArn RESOURCE = + new EmrServerlessService.ResourceArn(ARN, ID, null, null); + + private final EmrServerlessService applications = mock(EmrServerlessService.class); + private final EmrServerlessJobRunService jobRuns = mock(EmrServerlessJobRunService.class); + private final EmrServerlessCfnProvisioner provisioner = new EmrServerlessCfnProvisioner(applications, jobRuns); + + private static ProvisionContext ctx(String priorPhysicalId, String priorProperties) { + return new ProvisionContext(CloudFormationTemplateEngine.standalone("000000000000", "us-east-1", "my-stack", + MAPPER, null), "us-east-1", "000000000000", "my-stack", priorPhysicalId, event -> { }, + priorProperties == null ? null : json(priorProperties)); + } + + private static StackResource resource() { + StackResource r = new StackResource(); + r.setLogicalId("App"); + r.setResourceType("AWS::EMRServerless::Application"); + r.setAttributes(new HashMap<>()); + return r; + } + + /** The resource as the create that made application {@link #ID} left it. */ + private static StackResource provisioned() { + StackResource r = resource(); + r.setPhysicalId(ID); + r.getAttributes().put("ApplicationId", ID); + r.getAttributes().put("Arn", ARN); + return r; + } + + private static Application app(String id, Map tags) { + Application app = new Application(); + app.setApplicationId(id); + app.setArn("arn:aws:emr-serverless:us-east-1:000000000000:/applications/" + id); + app.setReleaseLabel("emr-7.5.0"); + app.setType("SPARK"); + app.setState("CREATED"); + app.setTags(new LinkedHashMap<>(tags)); + return app; + } + + /** Application {@link #ID} stopping after 15 idle minutes with two pre-initialized drivers. */ + private static Application live() { + Application live = app(ID, Map.of("team", "data")); + AutoStopConfiguration autoStop = new AutoStopConfiguration(); + autoStop.setEnabled(true); + autoStop.setIdleTimeoutMinutes(15); + live.setAutoStopConfiguration(autoStop); + WorkerConfiguration worker = new WorkerConfiguration(); + worker.setCpu("2 vCPU"); + worker.setMemory("4 GB"); + InitialCapacityConfig capacity = new InitialCapacityConfig(); + capacity.setWorkerCount(2L); + capacity.setWorkerConfiguration(worker); + live.setInitialCapacity(Map.of("Driver", capacity)); + return live; + } + + private static JsonNode json(String text) { + try { + return MAPPER.readTree(text); + } catch (JsonProcessingException e) { + throw new IllegalArgumentException(text, e); + } + } + + /** Tags in the order given, as key, value, key, value. */ + private static Map tags(String... keysAndValues) { + Map tags = new LinkedHashMap<>(); + for (int i = 0; i < keysAndValues.length; i += 2) { + tags.put(keysAndValues[i], keysAndValues[i + 1]); + } + return tags; + } + + /** What ListTagsForResource answers for application {@link #ID}, the first time and then every time after. */ + private void stubTags(Map first, Map after) { + when(applications.resourceArn(ARN)).thenReturn(RESOURCE); + when(applications.listTags(RESOURCE)).thenReturn(first, after); + } + + private static final String PRIOR = """ + {"ReleaseLabel": "emr-7.5.0", "Type": "SPARK", + "AutoStopConfiguration": {"Enabled": true, "IdleTimeoutMinutes": 15}, + "InitialCapacity": [{"Key": "Driver", + "Value": {"WorkerCount": 2, "WorkerConfiguration": {"Cpu": "2 vCPU", "Memory": "4 GB"}}}], + "Tags": [{"Key": "team", "Value": "data"}]} + """; + private static final String UPDATED = """ + {"ReleaseLabel": "emr-7.5.0", "Type": "SPARK", + "AutoStopConfiguration": {"Enabled": true, "IdleTimeoutMinutes": 30}, + "Tags": [{"Key": "stage", "Value": "prod"}]} + """; + + @Test + void createsTheApplicationWithTheTemplateInTheApiShape() { + when(applications.createApplication(any())).thenReturn(app(ID, Map.of())); + StackResource r = resource(); + + provisioner.provision(r, json(""" + {"Name": "etl", "ReleaseLabel": "emr-7.5.0", "Type": "SPARK", "Architecture": "ARM64", + "InitialCapacity": [{"Key": "Driver", + "Value": {"WorkerCount": "2", "WorkerConfiguration": {"Cpu": "2 vCPU", "Memory": "4 GB"}}}], + "AutoStopConfiguration": {"Enabled": "true", "IdleTimeoutMinutes": "30"}, + "MonitoringConfiguration": {"CloudWatchLoggingConfiguration": {"Enabled": true, + "LogTypeMap": [{"Key": "SPARK_DRIVER", "Value": ["STDOUT", "STDERR"]}]}}, + "RuntimeConfiguration": [{"Classification": "spark-defaults", + "Properties": {"spark.driver.cores": "2"}}], + "WorkerTypeSpecifications": {"Driver": {"ImageConfiguration": + {"ImageUri": "public.ecr.aws/emr-serverless/spark/emr-7.5.0:latest"}}}, + "SchedulerConfiguration": {"MaxConcurrentRuns": "5"}, + "Tags": [{"Key": "team", "Value": "data"}]} + """), ctx(null, null)); + + ArgumentCaptor created = ArgumentCaptor.forClass(CreateApplicationRequest.class); + verify(applications).createApplication(created.capture()); + CreateApplicationRequest request = created.getValue(); + assertEquals("etl", request.getName()); + assertEquals("SPARK", request.getType()); + assertEquals("emr-7.5.0", request.getReleaseLabel()); + assertEquals("ARM64", request.getArchitecture()); + assertEquals(2L, request.getInitialCapacity().get("Driver").getWorkerCount()); + assertEquals("4 GB", request.getInitialCapacity().get("Driver").getWorkerConfiguration().getMemory()); + assertEquals(Boolean.TRUE, request.getAutoStopConfiguration().getEnabled()); + assertEquals(30, request.getAutoStopConfiguration().getIdleTimeoutMinutes()); + assertEquals(json(""" + {"cloudWatchLoggingConfiguration": {"enabled": true, + "logTypes": {"SPARK_DRIVER": ["STDOUT", "STDERR"]}}} + """), MAPPER.valueToTree(request.getMonitoringConfiguration())); + assertEquals(json(""" + [{"classification": "spark-defaults", "properties": {"spark.driver.cores": "2"}}] + """), MAPPER.valueToTree(request.getRuntimeConfiguration())); + assertEquals("public.ecr.aws/emr-serverless/spark/emr-7.5.0:latest", + request.getWorkerTypeSpecifications().get("Driver").getImageConfiguration().getImageUri()); + assertEquals(json("{\"maxConcurrentRuns\": 5}"), MAPPER.valueToTree(request.getSchedulerConfiguration())); + assertEquals(Map.of("team", "data"), request.getTags()); + assertFalse(request.getClientToken().isBlank()); + assertEquals(ID, r.getPhysicalId()); + assertEquals(ID, r.getAttributes().get("ApplicationId")); + assertEquals("arn:aws:emr-serverless:us-east-1:000000000000:/applications/" + ID, r.getAttributes().get("Arn")); + } + + @Test + void aTemplateTheHandlersModelValidationRefusesFailsBeforeAnyCall() { + AwsException missing = assertThrows(AwsException.class, + () -> provisioner.provision(resource(), json("{\"Type\": \"SPARK\"}"), ctx(null, null))); + AwsException extraneous = assertThrows(AwsException.class, () -> provisioner.provision(resource(), json(""" + {"ReleaseLabel": "emr-7.5.0", "Type": "SPARK", "AutoStopConfiguration": {"Idle": 5}} + """), ctx(null, null))); + + AwsException architecture = assertThrows(AwsException.class, () -> provisioner.provision(resource(), + json("{\"ReleaseLabel\": \"emr-7.5.0\", \"Type\": \"SPARK\", \"Architecture\": \"AMD64\"}"), + ctx(null, null))); + AwsException readOnly = assertThrows(AwsException.class, () -> provisioner.provision(resource(), + json("{\"ReleaseLabel\": \"emr-7.5.0\", \"Type\": \"SPARK\", \"ApplicationId\": \"00fmine\"}"), + ctx(null, null))); + + assertEquals("Model validation failed (#: required key [ReleaseLabel] not found)", missing.getMessage()); + assertEquals("Model validation failed (#/AutoStopConfiguration: extraneous key [Idle] is not permitted)", + extraneous.getMessage()); + assertEquals("Model validation failed (#/Architecture: AMD64 is not a valid enum value)", + architecture.getMessage()); + assertEquals("ApplicationId is a ReadOnly property which cannot be specified in the template", + readOnly.getMessage()); + verifyNoInteractions(applications, jobRuns); + } + + @Test + void anUpdateSendsWhatTheTemplateChangedClearsADroppedInitialCapacityAndTakesTheTagsToTheTemplates() { + when(applications.findLive(ID)).thenReturn(Optional.of(live())); + stubTags(tags("team", "data", "owner", "ops"), tags()); + StackResource r = provisioned(); + + provisioner.provision(r, json(UPDATED), ctx(ID, PRIOR)); + + ArgumentCaptor updated = ArgumentCaptor.forClass(UpdateApplicationRequest.class); + verify(jobRuns).updateApplication(eq(ID), updated.capture()); + UpdateApplicationRequest request = updated.getValue(); + assertEquals(30, request.getAutoStopConfiguration().getIdleTimeoutMinutes()); + assertEquals(Map.of(), request.getInitialCapacity()); + assertNull(request.getReleaseLabel()); + assertNull(request.getArchitecture()); + verify(applications).untagResource(RESOURCE, List.of("team", "owner")); + verify(applications).tagResource(RESOURCE, Map.of("stage", "prod")); + verify(applications, never()).createApplication(any()); + assertEquals(ID, r.getPhysicalId()); + assertTrue(r.getAttributes().containsKey(EmrServerlessCfnProvisioner.SNAPSHOT_ATTR)); + } + + @Test + void aRollbackPutsBackTheSettingsAndTagsTheUpdateChanged() { + when(applications.findLive(ID)).thenReturn(Optional.of(live())); + stubTags(tags("team", "data"), tags("stage", "prod")); + StackResource r = provisioned(); + provisioner.provision(r, json(UPDATED), ctx(ID, PRIOR)); + + assertTrue(provisioner.rollbackUpdate(r)); + + ArgumentCaptor updates = ArgumentCaptor.forClass(UpdateApplicationRequest.class); + verify(jobRuns, times(2)).updateApplication(eq(ID), updates.capture()); + UpdateApplicationRequest restore = updates.getAllValues().get(1); + assertEquals(15, restore.getAutoStopConfiguration().getIdleTimeoutMinutes()); + assertEquals(2L, restore.getInitialCapacity().get("Driver").getWorkerCount()); + assertNull(restore.getReleaseLabel()); + verify(applications).untagResource(RESOURCE, List.of("stage")); + verify(applications).tagResource(RESOURCE, Map.of("team", "data")); + assertFalse(r.getAttributes().containsKey(EmrServerlessCfnProvisioner.SNAPSHOT_ATTR)); + } + + @Test + void aSettingTheApplicationDidNotHoldIsClearedOnRollbackWhereAnEmptyValueClearsIt() { + Application live = app(ID, Map.of()); + when(applications.findLive(ID)).thenReturn(Optional.of(live)); + stubTags(tags(), tags()); + StackResource r = provisioned(); + provisioner.provision(r, json(""" + {"ReleaseLabel": "emr-7.5.0", "Type": "SPARK", + "ImageConfiguration": {"ImageUri": "public.ecr.aws/emr-serverless/spark/emr-7.5.0:latest"}, + "AutoStartConfiguration": {"Enabled": false}} + """), ctx(ID, "{\"ReleaseLabel\": \"emr-7.5.0\", \"Type\": \"SPARK\"}")); + + provisioner.rollbackUpdate(r); + + ArgumentCaptor updates = ArgumentCaptor.forClass(UpdateApplicationRequest.class); + verify(jobRuns, times(2)).updateApplication(eq(ID), updates.capture()); + UpdateApplicationRequest restore = updates.getAllValues().get(1); + assertNull(restore.getImageConfiguration().getImageUri()); + assertNull(restore.getAutoStartConfiguration()); + } + + @Test + void anUpdateUpdateApplicationRefusesChangedNothingSoNothingIsPutBack() { + when(applications.findLive(ID)).thenReturn(Optional.of(live())); + AwsException refused = new AwsException("ValidationException", "refused", 400); + // A STARTED application refuses the restore's stopped-only settings as well. + when(jobRuns.updateApplication(eq(ID), any())).thenThrow(refused); + StackResource r = provisioned(); + + AwsException thrown = assertThrows(AwsException.class, + () -> provisioner.provision(r, json(UPDATED), ctx(ID, PRIOR))); + + assertEquals(refused, thrown); + verify(jobRuns, times(1)).updateApplication(eq(ID), any()); + verify(applications, never()).listTags(any()); + assertNull(r.getAttributes().get(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR)); + } + + @Test + void aTagFailureAfterTheSettingsChangedPutsTheSettingsAndTagsBackBeforeItPropagates() { + when(applications.findLive(ID)).thenReturn(Optional.of(live())); + stubTags(tags("team", "data"), tags()); + AwsException tagging = new AwsException("ValidationException", "tagging", 400); + doThrow(tagging).doNothing().when(applications).tagResource(eq(RESOURCE), any()); + StackResource r = provisioned(); + + AwsException thrown = assertThrows(AwsException.class, + () -> provisioner.provision(r, json(UPDATED), ctx(ID, PRIOR))); + + assertEquals(tagging, thrown); + ArgumentCaptor updates = ArgumentCaptor.forClass(UpdateApplicationRequest.class); + verify(jobRuns, times(2)).updateApplication(eq(ID), updates.capture()); + assertEquals(15, updates.getAllValues().get(1).getAutoStopConfiguration().getIdleTimeoutMinutes()); + verify(applications).tagResource(RESOURCE, Map.of("team", "data")); + assertNull(r.getAttributes().get(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR)); + } + + @Test + void aSchedulerChangeIsPutBackWithTheMembersTheUpdateSentSoAStartedApplicationTakesIt() { + Application live = app(ID, Map.of()); + SchedulerConfiguration scheduler = new SchedulerConfiguration(); + scheduler.setProperty("maxConcurrentRuns", 15); + scheduler.setProperty("queueTimeoutMinutes", 360); + live.setSchedulerConfiguration(scheduler); + when(applications.findLive(ID)).thenReturn(Optional.of(live)); + stubTags(tags(), tags()); + StackResource r = provisioned(); + provisioner.provision(r, json(""" + {"ReleaseLabel": "emr-7.5.0", "Type": "SPARK", "SchedulerConfiguration": {"MaxConcurrentRuns": 10}} + """), ctx(ID, "{\"ReleaseLabel\": \"emr-7.5.0\", \"Type\": \"SPARK\"}")); + + provisioner.rollbackUpdate(r); + + ArgumentCaptor updates = ArgumentCaptor.forClass(UpdateApplicationRequest.class); + verify(jobRuns, times(2)).updateApplication(eq(ID), updates.capture()); + assertEquals(json("{\"maxConcurrentRuns\": 10}"), + MAPPER.valueToTree(updates.getAllValues().get(0).getSchedulerConfiguration())); + assertEquals(json("{\"maxConcurrentRuns\": 15}"), + MAPPER.valueToTree(updates.getAllValues().get(1).getSchedulerConfiguration())); + } + + @Test + void aSchedulerTheUpdateSetWhereQueuingWasOffIsLeftAsTheUpdateLeftIt() { + Application live = app(ID, Map.of()); + live.setSchedulerOff(true); + when(applications.findLive(ID)).thenReturn(Optional.of(live)); + stubTags(tags(), tags()); + StackResource r = provisioned(); + provisioner.provision(r, json(""" + {"ReleaseLabel": "emr-7.5.0", "Type": "SPARK", "SchedulerConfiguration": {"MaxConcurrentRuns": 10}, + "AutoStopConfiguration": {"Enabled": false}} + """), ctx(ID, "{\"ReleaseLabel\": \"emr-7.5.0\", \"Type\": \"SPARK\"}")); + + provisioner.rollbackUpdate(r); + + verify(jobRuns, times(1)).updateApplication(eq(ID), any()); + } + + @Test + void anUndoThatFailedLeavesItsSnapshotForContinueUpdateRollback() { + StackResource previous = provisioned(); + StackResource attempted = provisioned(); + attempted.getAttributes().put(EmrServerlessCfnProvisioner.SNAPSHOT_ATTR, "{}"); + StackResource undone = provisioned(); + undone.getAttributes().put(EmrServerlessCfnProvisioner.SNAPSHOT_ATTR, "{}"); + + provisioner.mergeFailedUpdateResourceTracking(previous, undone); + assertFalse(previous.getAttributes().containsKey(EmrServerlessCfnProvisioner.SNAPSHOT_ATTR)); + attempted.getAttributes().put(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR, "Could not restore"); + provisioner.mergeFailedUpdateResourceTracking(previous, attempted); + + assertEquals("{}", previous.getAttributes().get(EmrServerlessCfnProvisioner.SNAPSHOT_ATTR)); + } + + @Test + void anUpdateOfAnApplicationThatIsGoneFailsAsTheHandlerDoes() { + when(applications.findLive(ID)).thenReturn(Optional.empty()); + + AwsException e = assertThrows(AwsException.class, + () -> provisioner.provision(provisioned(), json(UPDATED), ctx(ID, PRIOR))); + + assertEquals("Resource of type 'AWS::EMRServerless::Application' with identifier '" + ID + + "' was not found.", e.getMessage()); + verifyNoInteractions(jobRuns); + } + + @Test + void changingTheNameReplacesTheApplicationAndLeavesTheOldOneForTheCleanup() { + when(applications.createApplication(any())).thenReturn(app("00fnewapp02", Map.of())); + StackResource r = provisioned(); + + provisioner.provision(r, json("{\"Name\": \"b\", \"ReleaseLabel\": \"emr-7.5.0\", \"Type\": \"SPARK\"}"), + ctx(ID, "{\"Name\": \"a\", \"ReleaseLabel\": \"emr-7.5.0\", \"Type\": \"SPARK\"}")); + + assertEquals("00fnewapp02", r.getPhysicalId()); + assertTrue(provisioner.hasReplacementUpdate(r)); + assertEquals(ID, provisioner.updateCleanupPhysicalId(r)); + verify(applications, never()).findLive(any()); + verifyNoInteractions(jobRuns); + } + + @Test + void aStubFromBeforeTheTypeHadAProvisionerIsTakenOverByACreate() { + when(applications.createApplication(any())).thenReturn(app(ID, Map.of())); + StackResource r = resource(); + r.setPhysicalId("App-0a1b2c3d"); + r.getAttributes().put("Arn", CfnResourceDispatcher.STUB_ARN_PREFIX + "App"); + + provisioner.provision(r, json("{\"ReleaseLabel\": \"emr-7.5.0\", \"Type\": \"SPARK\"}"), + ctx("App-0a1b2c3d", "{\"ReleaseLabel\": \"emr-7.5.0\", \"Type\": \"SPARK\"}")); + + assertEquals(ID, r.getPhysicalId()); + assertEquals(ARN, r.getAttributes().get("Arn")); + verify(applications, never()).findLive(any()); + } + + @Test + void theDeleteRemovesALiveApplicationAndLeavesAGoneOneAlone() { + when(applications.whileLive(eq(ID), any())).thenAnswer(inv -> { + inv.>getArgument(1).accept(live()); + return true; + }); + + provisioner.delete("AWS::EMRServerless::Application", ID, "us-east-1"); + provisioner.delete("AWS::EMRServerless::Application", "00fgoneapp03", "us-east-1"); + + verify(applications).deleteApplication(ID); + verify(applications, never()).deleteApplication("00fgoneapp03"); + } +} diff --git a/src/test/resources/cloudformation/schema-surface.tsv b/src/test/resources/cloudformation/schema-surface.tsv index 423345ef27..00d8b06729 100644 --- a/src/test/resources/cloudformation/schema-surface.tsv +++ b/src/test/resources/cloudformation/schema-surface.tsv @@ -44,7 +44,7 @@ AWS::Bedrock::ApplicationInferenceProfile CreatedAt,InferenceProfileArn,Inferenc AWS::BedrockAgentCore::Memory CreatedAt,FailureReason,MemoryArn,MemoryId,Status,UpdatedAt Description,EncryptionKeyArn,EventExpiryDuration,IndexedKeys,MemoryExecutionRoleArn,MemoryStrategies,Name,NamespaceKeys,StreamDeliveryResources,Tags AWS::BedrockAgentCore::Runtime AgentRuntimeArn,AgentRuntimeId,AgentRuntimeVersion,CreatedAt,FailureReason,LastUpdatedAt,Status,WorkloadIdentityDetails AgentRuntimeArtifact,AgentRuntimeName,AuthorizerConfiguration,CapacityProviderConfiguration,Description,EnvironmentVariables,FilesystemConfigurations,HooksConfiguration,LifecycleConfiguration,NetworkConfiguration,PlatformVersion,ProtocolConfiguration,RequestHeaderConfiguration,ResourceConfigurations,RoleArn,Tags AWS::BedrockAgentCore::RuntimeEndpoint AgentRuntimeArn,AgentRuntimeEndpointArn,CreatedAt,FailureReason,Id,LastUpdatedAt,LiveVersion,Status,TargetVersion AgentRuntimeId,AgentRuntimeVersion,Description,Name,Tags -AWS::CertificateManager::Certificate CertificateArn CertificateAuthorityArn,CertificateExport,CertificateTransparencyLoggingPreference,DomainName,DomainValidationOptions,KeyAlgorithm,SubjectAlternativeNames,Tags,ValidationMethod +AWS::CertificateManager::Certificate CertificateArn CertificateAuthorityArn,CertificateExport,CertificateTransparencyLoggingPreference,CertificateUsage,DomainName,DomainValidationOptions,KeyAlgorithm,RootHierarchyType,SubjectAlternativeNames,Tags,ValidationMethod AWS::CloudFormation::CustomResource Id ServiceTimeout,ServiceToken AWS::CloudFormation::StackSet StackSetId AdministrationRoleARN,AutoDeployment,CallAs,Capabilities,Description,ExecutionRoleName,ManagedExecution,OperationPreferences,Parameters,PermissionModel,StackInstancesGroup,StackSetName,Tags,TemplateBody,TemplateURL AWS::CloudFront::CachePolicy Id,LastModifiedTime CachePolicyConfig @@ -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::EMRServerless::Application ApplicationId,Arn Architecture,AutoStartConfiguration,AutoStopConfiguration,IdentityCenterConfiguration,ImageConfiguration,InitialCapacity,InteractiveConfiguration,MaximumCapacity,MonitoringConfiguration,Name,NetworkConfiguration,ReleaseLabel,RuntimeConfiguration,SchedulerConfiguration,Tags,Type,WorkerTypeSpecifications AWS::ElastiCache::CacheCluster ConfigurationEndpoint,RedisEndpoint AZMode,AutoMinorVersionUpgrade,CacheNodeType,CacheParameterGroupName,CacheSubnetGroupName,ClusterName,Engine,EngineVersion,IpDiscovery,LogDeliveryConfigurations,NetworkType,NotificationTopicArn,NumCacheNodes,Port,PreferredAvailabilityZone,PreferredAvailabilityZones,PreferredMaintenanceWindow,SnapshotArns,SnapshotName,SnapshotRetentionLimit,SnapshotWindow,Tags,TransitEncryptionEnabled,VpcSecurityGroupIds AWS::ElastiCache::ReplicationGroup ConfigurationEndPoint,EffectiveDurability,PrimaryEndPoint,ReadEndPoint,ReaderEndPoint AtRestEncryptionEnabled,AuthToken,AutoMinorVersionUpgrade,AutomaticFailoverEnabled,CacheNodeType,CacheParameterGroupName,CacheSubnetGroupName,ClusterMode,DataTieringEnabled,Durability,Engine,EngineVersion,GlobalReplicationGroupId,IpDiscovery,KmsKeyId,LogDeliveryConfigurations,MultiAZEnabled,NetworkType,NodeGroupConfiguration,NotificationTopicArn,NumCacheClusters,NumNodeGroups,Port,PreferredCacheClusterAZs,PreferredMaintenanceWindow,PrimaryClusterId,ReplicasPerNodeGroup,ReplicationGroupDescription,ReplicationGroupId,SecurityGroupIds,SnapshotArns,SnapshotName,SnapshotRetentionLimit,SnapshotWindow,SnapshottingClusterId,Tags,TransitEncryptionEnabled,TransitEncryptionMode,UserGroupIds AWS::ElastiCache::ServerlessCache ARN,CreateTime,FullEngineVersion,Status CacheUsageLimits,ConnectionType,DailySnapshotTime,Description,Endpoint,Engine,FinalSnapshotName,KmsKeyId,MajorEngineVersion,NetworkType,ReaderEndpoint,SecurityGroupIds,ServerlessCacheName,SnapshotArnsToRestore,SnapshotRetentionLimit,SubnetIds,Tags,UserGroupId diff --git a/src/test/resources/cloudformation/supported-resource-types.tsv b/src/test/resources/cloudformation/supported-resource-types.tsv index c1b3f4885b..5f33ee3c62 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::EMRServerless::Application EmrServerlessCfnProvisioner AWS::ElastiCache::CacheCluster ElastiCacheCfnProvisioner AWS::ElastiCache::ReplicationGroup ElastiCacheCfnProvisioner AWS::ElastiCache::ServerlessCache ElastiCacheServerlessCfnProvisioner diff --git a/src/test/resources/cloudformation/writable-property-gaps.tsv b/src/test/resources/cloudformation/writable-property-gaps.tsv index b65dc1bffe..987a8fe5a5 100644 --- a/src/test/resources/cloudformation/writable-property-gaps.tsv +++ b/src/test/resources/cloudformation/writable-property-gaps.tsv @@ -127,7 +127,9 @@ AWS::BedrockAgentCore::Runtime PlatformVersion accepted and not stored, a warnin AWS::BedrockAgentCore::Runtime RequestHeaderConfiguration accepted and not stored, a warning is logged AWS::BedrockAgentCore::Runtime ResourceConfigurations accepted and not stored, a warning is logged AWS::CertificateManager::Certificate CertificateAuthorityArn accepted and ignored +AWS::CertificateManager::Certificate CertificateUsage accepted and ignored AWS::CertificateManager::Certificate DomainValidationOptions accepted and ignored, as the AcmCfnProvisioner javadoc records +AWS::CertificateManager::Certificate RootHierarchyType accepted and ignored AWS::CloudFormation::CustomResource ServiceTimeout accepted and ignored AWS::CloudFormation::StackSet AdministrationRoleARN accepted and ignored; local StackSets deploy without assuming an administration role AWS::CloudFormation::StackSet CallAs accepted and ignored; local StackSets do not model delegated administrator authorization diff --git a/tools/aws/regen_cfn_property_types.py b/tools/aws/regen_cfn_property_types.py index fe1ece80b3..710a1ea25a 100644 --- a/tools/aws/regen_cfn_property_types.py +++ b/tools/aws/regen_cfn_property_types.py @@ -51,7 +51,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::Events::Rule", + "AWS::EC2::LaunchTemplate", "AWS::ECS::TaskDefinition", "AWS::EKS::Cluster", + "AWS::EMRServerless::Application", "AWS::Events::Rule", "AWS::Lambda::Function", "AWS::Lambda::LayerVersion", "AWS::SES::ConfigurationSetEventDestination"] diff --git a/tools/docs/cfn_resource_types.yaml b/tools/docs/cfn_resource_types.yaml index 9a52f61fa5..b85f29d518 100644 --- a/tools/docs/cfn_resource_types.yaml +++ b/tools/docs/cfn_resource_types.yaml @@ -27,6 +27,7 @@ order: - AWS::ECS - AWS::EFS - AWS::EKS + - AWS::EMRServerless - AWS::RDS - AWS::DSQL - AWS::ElastiCache @@ -156,6 +157,7 @@ service_labels: AWS::ECS: ECS AWS::EFS: EFS AWS::EKS: EKS + AWS::EMRServerless: EMR Serverless AWS::ElasticLoadBalancingV2: Elastic Load Balancing v2 AWS::Events: EventBridge AWS::EventsV2: EventBridge V2 @@ -228,6 +230,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::EMRServerless::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' AWS::IAM::User: 'template `LoginProfile` and `PermissionsBoundary` are ignored; an API-created login profile is removed on delete' AWS::ApiGateway::Authorizer: 'created with `Name`, `Type`, `AuthorizerUri`, `IdentitySource`, `AuthorizerResultTtlInSeconds` and `ProviderARNs`; updated in place for those, keeping the id; a template that drops `AuthorizerResultTtlInSeconds`, `IdentitySource` or `ProviderARNs` restores the TTL of 300 and clears the identity source and the pools, a dropped `AuthorizerUri` keeps the current one, and dropping `IdentitySource` from a `TOKEN` or `COGNITO_USER_POOLS` authorizer fails the resource, as AWS requires it there; a change to `RestApiId` replaces the authorizer, as the registry marks it create-only, and deletes the old one once the update commits; `AuthorizerCredentials`, `AuthType` and `IdentityValidationExpression` are not stored' AWS::ApiGateway::Stage: 'created with `RestApiId`, `StageName`, `DeploymentId` and `Description`; updated in place for `DeploymentId` and `Description`, keeping the stage variables and method settings set outside the stack; a template that drops `Description` clears it, and a dropped `DeploymentId` keeps the current one; a change to `RestApiId` or `StageName` replaces the stage, as the registry marks them create-only, and deletes the old one once the update commits unless `UpdateReplacePolicy: Retain` keeps it, a name already taken on the API fails the update; `AccessLogSetting`, `CacheClusterEnabled`, `CacheClusterSize`, `CanarySetting`, `ClientCertificateId`, `DocumentationVersion`, `MethodSettings`, `Tags`, `TracingEnabled` and `Variables` are accepted and not stored'