diff --git a/docs/services/cloudformation.md b/docs/services/cloudformation.md index 2e38949871..ca281dabc5 100644 --- a/docs/services/cloudformation.md +++ b/docs/services/cloudformation.md @@ -267,7 +267,7 @@ cross-resource references. | Kinesis Data Firehose | `DeliveryStream` (`DeliveryStreamName`, `Tags` and, from an S3 destination, `BucketARN`, `RoleARN`, `Prefix`, `ErrorOutputPrefix`, `CompressionFormat`, `BufferingHints`, `CloudWatchLoggingOptions` and `ProcessingConfiguration` are applied; other properties are ignored, and a destination member the template drops on update keeps its stored value, as on AWS) | | IoT Core | `Authorizer`, `DomainConfiguration` (`ServerCertificates` resolves to a JSON string), `Policy` (deleted after detaching it from its principals; on AWS the delete fails with `DeleteConflictException` while the policy is attached), `Thing`, `TopicRule` | | CloudFront | `CachePolicy`, `ConnectionGroup`, `Distribution`, `DistributionTenant`, `Function` (`KeyValueStoreAssociations` is ignored), `KeyGroup`, `OriginAccessControl`, `OriginRequestPolicy`, `PublicKey`, `ResponseHeadersPolicy` | -| CloudWatch | `Alarm`, `CompositeAlarm`, `Dashboard`, `OTelEnrichment` (one per account and Region; Ref returns the account ID; a create while enrichment runs fails with `AlreadyExists`, and a failed update puts the previous filters back). Composite alarms have backing definitions with name Ref and Arn GetAtt, rollback, and replacement cleanup. Composite actions are stored only; suppression properties are rejected. | +| CloudWatch | `Alarm`, `CompositeAlarm`, `Dashboard`, `OTelEnrichment` (one per account and Region; Ref returns the account ID; a create while enrichment runs fails with `AlreadyExists`, and a failed update puts the previous filters back), `ResourceMetricsConfiguration` (Ref returns the monitored resource's ARN; a create for an ARN that has a configuration fails with `AlreadyExists`, and a failed update puts the previous metric selections back). Composite alarms have backing definitions with name Ref and Arn GetAtt, rollback, and replacement cleanup. Composite actions are stored only; suppression properties are rejected. | | CloudWatch Logs | `LogGroup`, `LogStream`, `MetricFilter` | | CloudWatch Observability Admin | `TelemetryEnrichment` (Ref returns the scope, `ACCOUNT`; starts and stops resource tags for telemetry in the stack's Region) | | WAFv2 | `IPSet`, `LoggingConfiguration`, `WebACL`, `WebACLAssociation` | diff --git a/docs/services/cloudwatch.md b/docs/services/cloudwatch.md index 7bffdfef0c..2d66d42d3d 100644 --- a/docs/services/cloudwatch.md +++ b/docs/services/cloudwatch.md @@ -1040,6 +1040,17 @@ collected and the configuration answers without `MetricSelections`. "When you de group, its resource metrics configuration is deleted automatically", and `DeleteReplicationGroup` does so in Floci. +CloudFormation's `AWS::CloudWatch::ResourceMetricsConfiguration` creates the configuration of its +`ResourceArn` and deletes it with the stack. `Ref` returns that ARN, and `CreatedAt` and `UpdatedAt` +return the configuration's timestamps to the millisecond, as the API answers them. A change to +`MetricSelections` updates the configuration in place, so a template that drops the list collects +every detailed metric again. A change to `ResourceArn` replaces it: the new ARN's configuration is +created, and the old one is deleted once the update completes. A stack update that fails puts the +previous selections back. A create for an ARN that has a configuration fails with `AlreadyExists`, as +CloudFormation's resource handler contract requires of a create, and leaves that configuration as it +is. `CreatedAt` and `UpdatedAt` are read-only, so a template that sets either fails with `InvalidRequest`. A +configuration already deleted with its replication group is taken as deleted. + ### Composite alarm evaluation A composite alarm is evaluated when it is created, when `PutCompositeAlarm` updates it, and when diff --git a/src/main/java/io/floci/aws/services/cloudformation/provisioners/CfnExceptions.java b/src/main/java/io/floci/aws/services/cloudformation/provisioners/CfnExceptions.java index e26016dae4..80552c5d0c 100644 --- a/src/main/java/io/floci/aws/services/cloudformation/provisioners/CfnExceptions.java +++ b/src/main/java/io/floci/aws/services/cloudformation/provisioners/CfnExceptions.java @@ -1,6 +1,9 @@ package io.floci.aws.services.cloudformation.provisioners; import io.floci.aws.core.common.AwsException; +import tools.jackson.databind.JsonNode; + +import java.util.List; /** * Exceptions shared by extracted CloudFormation resource provisioners. @@ -18,4 +21,26 @@ public final class CfnExceptions { "CloudFormation cannot update a stack when a custom-named resource requires replacing. " + "Rename " + name + " and update the stack again.", 400); } + + /** + * Thrown when a create meets an entity that already holds the resource's identifier, as a resource handler fails + * such a create with {@code AlreadyExists}. + */ + public static AwsException alreadyExists(String resourceType, String identifier) { + return new AwsException("AlreadyExists", "Resource of type '" + resourceType + "' with identifier '" + + identifier + "' already exists.", 400); + } + + /** + * Refuses the first of {@code readOnly}, the schema's {@code readOnlyProperties}, that {@code template} sets: a + * read-only property can be returned by a read "but can't be set by the user". + */ + public static void refuseReadOnly(JsonNode template, List readOnly) { + for (String name : readOnly) { + if (template.has(name)) { + throw new AwsException("InvalidRequest", + name + " is a ReadOnly property which cannot be specified in the template", 400); + } + } + } } diff --git a/src/main/java/io/floci/aws/services/cloudformation/provisioners/CfnRollback.java b/src/main/java/io/floci/aws/services/cloudformation/provisioners/CfnRollback.java index e7c14d7e2c..cfaccfc5c0 100644 --- a/src/main/java/io/floci/aws/services/cloudformation/provisioners/CfnRollback.java +++ b/src/main/java/io/floci/aws/services/cloudformation/provisioners/CfnRollback.java @@ -173,6 +173,20 @@ public final class CfnRollback { */ public static final String DASHBOARD_UPDATE_SNAPSHOT_ATTR = "__FlociDashboardUpdateSnapshot"; + /** + * The OTel enrichment filters an in-place update replaced, or the fact that it wrote none, so a failed stack + * update can put them back. Written and spent by {@code CloudWatchOTelEnrichmentCfnProvisioner}. + */ + public static final String OTEL_ENRICHMENT_UPDATE_SNAPSHOT_ATTR = "__FlociOTelEnrichmentUpdateSnapshot"; + + /** + * The configuration an in-place update replaced the selections of, so a failed stack update can put them back; an + * update that wrote nothing keeps none. Written and spent by + * {@code CloudWatchResourceMetricsConfigurationCfnProvisioner}. + */ + public static final String RESOURCE_METRICS_CONFIGURATION_UPDATE_SNAPSHOT_ATTR = + "__FlociResourceMetricsConfigurationUpdateSnapshot"; + /** * The tags an EKS cluster carried before an in-place update changed them, so a failed stack * update can put them back. Written and spent by {@code EksCfnProvisioner}. diff --git a/src/main/java/io/floci/aws/services/cloudformation/provisioners/CloudWatchOTelEnrichmentCfnProvisioner.java b/src/main/java/io/floci/aws/services/cloudformation/provisioners/CloudWatchOTelEnrichmentCfnProvisioner.java index 0d706f385c..ffa9603832 100644 --- a/src/main/java/io/floci/aws/services/cloudformation/provisioners/CloudWatchOTelEnrichmentCfnProvisioner.java +++ b/src/main/java/io/floci/aws/services/cloudformation/provisioners/CloudWatchOTelEnrichmentCfnProvisioner.java @@ -37,7 +37,7 @@ import java.util.Set; public class CloudWatchOTelEnrichmentCfnProvisioner implements CfnResourceProvisioner { private static final String TYPE = "AWS::CloudWatch::OTelEnrichment"; - private static final String SNAPSHOT = "FlociOTelEnrichmentSnapshot"; + private static final String SNAPSHOT = CfnRollback.OTEL_ENRICHMENT_UPDATE_SNAPSHOT_ATTR; private static final String RUNNING = "RUNNING"; private static final ObjectMapper MAPPER = JacksonConfig.jsonMapper(); @@ -76,8 +76,7 @@ public class CloudWatchOTelEnrichmentCfnProvisioner implements CfnResourceProvis } resource.getAttributes().put(SNAPSHOT, snapshot); } else if (enrichments.startIfStopped(region, include, exclude, null).isEmpty()) { - throw new AwsException("AlreadyExists", "Resource of type '" + TYPE + "' with identifier '" - + ctx.accountId() + "' already exists.", 400); + throw CfnExceptions.alreadyExists(TYPE, ctx.accountId()); } resource.setPhysicalId(ctx.accountId()); resource.getAttributes().put("AccountId", ctx.accountId()); diff --git a/src/main/java/io/floci/aws/services/cloudformation/provisioners/CloudWatchResourceMetricsConfigurationCfnProvisioner.java b/src/main/java/io/floci/aws/services/cloudformation/provisioners/CloudWatchResourceMetricsConfigurationCfnProvisioner.java new file mode 100644 index 0000000000..f19f82dbd1 --- /dev/null +++ b/src/main/java/io/floci/aws/services/cloudformation/provisioners/CloudWatchResourceMetricsConfigurationCfnProvisioner.java @@ -0,0 +1,182 @@ +package io.floci.aws.services.cloudformation.provisioners; + +import io.floci.aws.core.common.AwsArnUtils; +import io.floci.aws.core.common.AwsException; +import io.floci.aws.core.common.JacksonConfig; +import io.floci.aws.core.common.JsonNodes; +import io.floci.aws.services.cloudformation.model.StackResource; +import io.floci.aws.services.cloudwatch.metrics.ResourceMetricsConfigurationService; +import io.floci.aws.services.cloudwatch.metrics.model.ResourceMetricsConfiguration; +import io.floci.aws.services.cloudwatch.metrics.model.ResourceMetricsConfiguration.ResourceMetricSelection; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.ObjectMapper; + +import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; + +/** + * Provisions {@code AWS::CloudWatch::ResourceMetricsConfiguration}, which "Turns on CloudWatch detailed monitoring for + * an individual AWS resource." "The resource is identified by its Amazon Resource Name (ARN), and the ARN also serves + * as the identifier for this CloudFormation resource", so {@code Ref} is the monitored resource's ARN, and + * {@code CreatedAt} and {@code UpdatedAt} are the configuration's timestamps. + * + *

{@code MetricSelections} updates in place and replaces the selections, so a dropped list collects "all available + * detailed metrics". {@code ResourceArn} requires replacement: the new ARN's configuration is created, and the old one + * is deleted once the update commits. A create for an ARN that has a configuration fails as a resource handler fails a + * create of a resource that exists, and {@code CreatedAt} or {@code UpdatedAt} set in the template is refused, as + * read-only properties "can't be set by the user". A failed update puts the previous selections back. A + * configuration already gone with its replication group is taken as deleted. + */ +@ApplicationScoped +public class CloudWatchResourceMetricsConfigurationCfnProvisioner implements CfnResourceProvisioner { + + private static final String TYPE = "AWS::CloudWatch::ResourceMetricsConfiguration"; + private static final String SNAPSHOT = CfnRollback.RESOURCE_METRICS_CONFIGURATION_UPDATE_SNAPSHOT_ATTR; + private static final List READ_ONLY = List.of("CreatedAt", "UpdatedAt"); + private static final ObjectMapper MAPPER = JacksonConfig.jsonMapper(); + + private final ResourceMetricsConfigurationService configurations; + + @Inject + public CloudWatchResourceMetricsConfigurationCfnProvisioner(ResourceMetricsConfigurationService configurations) { + this.configurations = configurations; + } + + @Override + public Set resourceTypes() { + return Set.of(TYPE); + } + + @Override + public void provision(StackResource resource, JsonNode props, ProvisionContext ctx) { + resource.getAttributes().remove(SNAPSHOT); + Map attributesBefore = Map.copyOf(resource.getAttributes()); + JsonNode resolved = CfnPropertyTypes.readValidated(TYPE, props, ctx.engine()); + CfnExceptions.refuseReadOnly(resolved, READ_ONLY); + String arn = JsonNodes.asText(resolved.path("ResourceArn")); + List selections = selections(resolved); + String region = ctx.region(); + ResourceMetricsConfiguration configuration; + // Only the configured ARN updates in place. Any other prior id, a replaced ARN or a dispatcher stub from + // before this provisioner existed, means a new configuration. + if (ctx.isUpdate() && arn.equals(ctx.priorPhysicalId())) { + configuration = configurations.get(region, arn); + PropertyChanges changes = ctx.changes(TYPE, props); + // A selection whose Ref reads a resource this update replaces is UNCHANGED in the template, yet resolves + // to a new value, so the resolved selections are compared with the stored ones as well. + if (!changes.added().isEmpty() || !changes.changed().isEmpty() || !changes.dropped().isEmpty() + || !Objects.equals(configuration.metricSelections(), selections)) { + ResourceMetricsConfiguration prior = configuration; + configuration = configurations.update(region, arn, selections); + resource.getAttributes().put(SNAPSHOT, MAPPER.createObjectNode().put("region", region) + .set("configuration", MAPPER.valueToTree(prior)).toString()); + } + } else { + configuration = create(region, arn, selections); + } + resource.setPhysicalId(arn); + putTimestamps(resource, configuration); + ReplacementCleanup.record(resource, ctx, attributesBefore); + } + + private static void putTimestamps(StackResource resource, ResourceMetricsConfiguration configuration) { + resource.getAttributes().put("CreatedAt", timestamp(configuration.createdAt())); + resource.getAttributes().put("UpdatedAt", timestamp(configuration.updatedAt())); + } + + private ResourceMetricsConfiguration create(String region, String arn, List selections) { + try { + return configurations.create(region, arn, selections); + } catch (AwsException refused) { + if ("ConflictException".equals(refused.getErrorCode())) { + throw CfnExceptions.alreadyExists(TYPE, arn); + } + throw refused; + } + } + + /** {@code instant} to the millisecond, as the API answers it. */ + private static String timestamp(Instant instant) { + return instant.truncatedTo(ChronoUnit.MILLIS).toString(); + } + + /** The selections the template lists, the model having checked each; null when it lists none. */ + private static List selections(JsonNode resolved) { + JsonNode list = resolved.path("MetricSelections"); + if (list.isMissingNode() || list.isNull()) { + return null; + } + List selections = new ArrayList<>(); + for (JsonNode selection : list) { + List names = new ArrayList<>(); + for (JsonNode name : selection.path("IncludeMetrics")) { + names.add(JsonNodes.asText(name)); + } + selections.add(new ResourceMetricSelection(names)); + } + return selections; + } + + @Override + public boolean hasReplacementUpdate(StackResource resource) { + return ReplacementCleanup.hasReplacement(resource); + } + + @Override + public String updateCleanupPhysicalId(StackResource resource) { + return ReplacementCleanup.cleanupPhysicalId(resource); + } + + /** Deletes the configuration a replacement displaced; an in-place update has only its snapshot to spend. */ + @Override + public UpdateCleanupResult completeUpdate(StackResource resource) { + UpdateCleanupResult replaced = ReplacementCleanup.complete(resource, this::delete); + if (!replaced.applicable() && resource.getAttributes().containsKey(SNAPSHOT)) { + return new UpdateCleanupResult(true, true, null, 0, null); + } + return replaced; + } + + @Override + public void clearUpdate(StackResource resource) { + ReplacementCleanup.clear(resource); + resource.getAttributes().remove(SNAPSHOT); + } + + /** + * A replacement deletes the configuration it created; an in-place update puts the selections it replaced back, the + * attributes taking the timestamps of that write, and one that wrote nothing has nothing to undo. + */ + @Override + public boolean rollbackUpdate(StackResource resource) { + if (ReplacementCleanup.rollback(resource, this::delete)) { + return true; + } + JsonNode snapshot = CfnRollback.updateSnapshot(resource, SNAPSHOT); + if (snapshot == null) { + return true; + } + ResourceMetricsConfiguration prior = MAPPER.convertValue(snapshot.path("configuration"), + ResourceMetricsConfiguration.class); + putTimestamps(resource, configurations.update(JsonNodes.asText(snapshot.path("region")), + prior.resourceArn(), prior.metricSelections())); + resource.getAttributes().remove(SNAPSHOT); + return true; + } + + @Override + public void delete(String resourceType, String physicalId, String region) { + if (!AwsArnUtils.isArn(physicalId)) { + return; + } + CfnDeletes.safeDelete("CloudWatch resource metrics configuration", physicalId, + () -> configurations.delete(region, physicalId), "ResourceNotFoundException"); + } +} diff --git a/src/main/java/io/floci/aws/services/cloudformation/provisioners/CognitoUserPoolUserCfnProvisioner.java b/src/main/java/io/floci/aws/services/cloudformation/provisioners/CognitoUserPoolUserCfnProvisioner.java index 7f6371130b..e9195069df 100644 --- a/src/main/java/io/floci/aws/services/cloudformation/provisioners/CognitoUserPoolUserCfnProvisioner.java +++ b/src/main/java/io/floci/aws/services/cloudformation/provisioners/CognitoUserPoolUserCfnProvisioner.java @@ -82,8 +82,7 @@ public class CognitoUserPoolUserCfnProvisioner implements CfnResourceProvisioner if ("RESEND".equalsIgnoreCase(messageAction)) { // RESEND hands back an existing user the stack never created, and AWS refuses it as a name conflict. CognitoUser existing = cognitoService.adminGetUser(userPoolId, name); - throw new AwsException("AlreadyExists", "Resource of type 'AWS::Cognito::UserPoolUser' with identifier '" - + userPoolId + "|" + existing.getUsername() + "' already exists.", 400); + throw CfnExceptions.alreadyExists("AWS::Cognito::UserPoolUser", userPoolId + "|" + existing.getUsername()); } Map clientMetadata = new LinkedHashMap<>(); for (Map.Entry entry : resolved.path("ClientMetadata").properties()) { 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 d388b3ff03..e0feef8978 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 @@ -245,12 +245,7 @@ public class EmrCfnProvisioner implements CfnResourceProvisioner { 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); - } - } + CfnExceptions.refuseReadOnly(template, CLUSTER_READ_ONLY); requireUniqueTaskNames(template.path("Instances")); Map tags = new LinkedHashMap<>(); template.path("Tags").forEach(tag -> tags.put(JsonNodes.asText(tag.path("Key")), JsonNodes.asText(tag.path("Value")))); @@ -708,7 +703,7 @@ public class EmrCfnProvisioner implements CfnResourceProvisioner { */ private void provisionStep(StackResource r, JsonNode props, ProvisionContext ctx, boolean stub) { JsonNode template = new CfnPropertyTypes.HandlerReader(ctx.engine()).read(STEP, props); - refuseReadOnly(template, "Id"); + CfnExceptions.refuseReadOnly(template, List.of("Id")); if (ctx.isUpdate() && !stub && !ctx.changes(STEP, props).requiresReplacement()) { r.setPhysicalId(ctx.priorPhysicalId()); r.getAttributes().put("Id", ctx.priorPhysicalId()); @@ -740,7 +735,7 @@ public class EmrCfnProvisioner implements CfnResourceProvisioner { */ private void provisionInstanceGroup(StackResource r, JsonNode props, ProvisionContext ctx, boolean stub) { JsonNode template = new CfnPropertyTypes.HandlerReader(ctx.engine()).read(INSTANCE_GROUP, props); - refuseReadOnly(template, "InstanceGroupId"); + CfnExceptions.refuseReadOnly(template, List.of("InstanceGroupId")); requireTask(template, "InstanceRole"); String clusterId = JsonNodes.asText(template.path("JobFlowId")); JsonNode policy = template.get("AutoScalingPolicy"); @@ -806,7 +801,7 @@ public class EmrCfnProvisioner implements CfnResourceProvisioner { */ private void provisionInstanceFleet(StackResource r, JsonNode props, ProvisionContext ctx, boolean stub) { JsonNode template = new CfnPropertyTypes.HandlerReader(ctx.engine()).read(INSTANCE_FLEET, props); - refuseReadOnly(template, "InstanceFleetId"); + CfnExceptions.refuseReadOnly(template, List.of("InstanceFleetId")); requireTask(template, "InstanceFleetType"); String clusterId = JsonNodes.asText(template.path("ClusterId")); PropertyChanges changes = ctx.isUpdate() && !stub ? ctx.changes(INSTANCE_FLEET, props) : null; @@ -993,13 +988,6 @@ public class EmrCfnProvisioner implements CfnResourceProvisioner { } } - private static void refuseReadOnly(JsonNode template, String name) { - if (template.has(name)) { - throw new AwsException("InvalidRequest", - name + " is a ReadOnly property which cannot be specified in the template", 400); - } - } - private static AwsException notFound(String type, String id) { return new AwsException("NotFound", "Resource of type '" + type + "' with identifier '" + id + "' was not found.", 404); diff --git a/src/main/java/io/floci/aws/services/cloudformation/provisioners/EmrContainersCfnProvisioner.java b/src/main/java/io/floci/aws/services/cloudformation/provisioners/EmrContainersCfnProvisioner.java index 4eaa986d54..e3b2fade73 100644 --- a/src/main/java/io/floci/aws/services/cloudformation/provisioners/EmrContainersCfnProvisioner.java +++ b/src/main/java/io/floci/aws/services/cloudformation/provisioners/EmrContainersCfnProvisioner.java @@ -113,12 +113,7 @@ public class EmrContainersCfnProvisioner implements CfnResourceProvisioner { } Map attributesBefore = new HashMap<>(r.getAttributes()); JsonNode template = new CfnPropertyTypes.HandlerReader(ctx.engine()).read(TYPE, props); - 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); - } - } + CfnExceptions.refuseReadOnly(template, READ_ONLY); Map tags = new LinkedHashMap<>(); template.path("Tags").forEach(tag -> tags.put(JsonNodes.asText(tag.path("Key")), JsonNodes.asText(tag.path("Value")))); // A stack from before this type had a provisioner, or deployed while EMR on EKS was disabled, holds the 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 index 2ffaff449d..4cb3b98eac 100644 --- a/src/main/java/io/floci/aws/services/cloudformation/provisioners/EmrServerlessCfnProvisioner.java +++ b/src/main/java/io/floci/aws/services/cloudformation/provisioners/EmrServerlessCfnProvisioner.java @@ -165,12 +165,7 @@ public class EmrServerlessCfnProvisioner implements CfnResourceProvisioner { if (architecture != null && !EmrServerlessService.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); - } - } + CfnExceptions.refuseReadOnly(template, READ_ONLY); } /** diff --git a/src/main/java/io/floci/aws/services/cloudformation/provisioners/EmrStudioCfnProvisioner.java b/src/main/java/io/floci/aws/services/cloudformation/provisioners/EmrStudioCfnProvisioner.java index d1e6d04201..76f7cd9eee 100644 --- a/src/main/java/io/floci/aws/services/cloudformation/provisioners/EmrStudioCfnProvisioner.java +++ b/src/main/java/io/floci/aws/services/cloudformation/provisioners/EmrStudioCfnProvisioner.java @@ -155,12 +155,7 @@ public class EmrStudioCfnProvisioner implements CfnResourceProvisioner { private void provisionStudio(StackResource r, JsonNode props, ProvisionContext ctx, boolean stub) { JsonNode template = new CfnPropertyTypes.HandlerReader(ctx.engine()).read(STUDIO, props); - 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); - } - } + CfnExceptions.refuseReadOnly(template, READ_ONLY); Map tags = new LinkedHashMap<>(); template.path("Tags").forEach(tag -> tags.put(JsonNodes.asText(tag.path("Key")), JsonNodes.asText(tag.path("Value")))); PropertyChanges changes = ctx.isUpdate() && !stub ? ctx.changes(STUDIO, props) : null; diff --git a/src/main/java/io/floci/aws/services/cloudformation/provisioners/ObservabilityAdminTelemetryEnrichmentCfnProvisioner.java b/src/main/java/io/floci/aws/services/cloudformation/provisioners/ObservabilityAdminTelemetryEnrichmentCfnProvisioner.java index 8cefa5568c..f5d1ca7e5f 100644 --- a/src/main/java/io/floci/aws/services/cloudformation/provisioners/ObservabilityAdminTelemetryEnrichmentCfnProvisioner.java +++ b/src/main/java/io/floci/aws/services/cloudformation/provisioners/ObservabilityAdminTelemetryEnrichmentCfnProvisioner.java @@ -1,6 +1,5 @@ package io.floci.aws.services.cloudformation.provisioners; -import io.floci.aws.core.common.AwsException; import io.floci.aws.core.common.JsonNodes; import io.floci.aws.services.cloudformation.model.StackResource; import io.floci.aws.services.observabilityadmin.ObservabilityAdminService; @@ -50,8 +49,7 @@ public class ObservabilityAdminTelemetryEnrichmentCfnProvisioner implements CfnR // Scope is the only property and it is create-only, so an update has nothing to change in place. if (!ctx.isUpdate() || ctx.changes(TYPE, props).requiresReplacement()) { if (!observabilityAdmin.startTelemetryEnrichmentIfStopped(region)) { - throw new AwsException("AlreadyExists", "Resource of type '" + TYPE + "' with identifier '" + scope - + "' already exists.", 400); + throw CfnExceptions.alreadyExists(TYPE, scope); } } resource.setPhysicalId(scope); diff --git a/src/main/resources/aws/cfn-property-types.json b/src/main/resources/aws/cfn-property-types.json index a649621979..c77e5d9390 100644 --- a/src/main/resources/aws/cfn-property-types.json +++ b/src/main/resources/aws/cfn-property-types.json @@ -8,6 +8,7 @@ "operations": { "AWS::AutoScaling::LaunchConfiguration": "AWS::AutoScaling::LaunchConfiguration", "AWS::CloudWatch::OTelEnrichment": "AWS::CloudWatch::OTelEnrichment", + "AWS::CloudWatch::ResourceMetricsConfiguration": "AWS::CloudWatch::ResourceMetricsConfiguration", "AWS::DSQL::Cluster": "AWS::DSQL::Cluster", "AWS::EC2::Instance": "AWS::EC2::Instance", "AWS::EC2::LaunchTemplate": "AWS::EC2::LaunchTemplate", @@ -156,6 +157,46 @@ "AWS::CloudWatch::OTelEnrichment/Status": { "type": "string" }, + "AWS::CloudWatch::ResourceMetricsConfiguration": { + "type": "structure", + "members": { + "ResourceArn": "AWS::CloudWatch::ResourceMetricsConfiguration.ResourceArn", + "MetricSelections": "AWS::CloudWatch::ResourceMetricsConfiguration.MetricSelections", + "CreatedAt": "String", + "UpdatedAt": "String" + }, + "required": [ + "ResourceArn" + ] + }, + "AWS::CloudWatch::ResourceMetricsConfiguration.MetricSelections": { + "type": "list", + "member": "AWS::CloudWatch::ResourceMetricsConfiguration/ResourceMetricSelection" + }, + "AWS::CloudWatch::ResourceMetricsConfiguration.ResourceArn": { + "type": "string", + "minLength": 20, + "maxLength": 2048, + "pattern": "^arn:[a-zA-Z0-9-]+:[a-zA-Z0-9-]+:[a-zA-Z0-9-]*:\\d{12}:.+$" + }, + "AWS::CloudWatch::ResourceMetricsConfiguration/ResourceMetricSelection": { + "type": "structure", + "members": { + "IncludeMetrics": "AWS::CloudWatch::ResourceMetricsConfiguration/ResourceMetricSelection.IncludeMetrics" + }, + "required": [ + "IncludeMetrics" + ] + }, + "AWS::CloudWatch::ResourceMetricsConfiguration/ResourceMetricSelection.IncludeMetrics": { + "type": "list", + "member": "AWS::CloudWatch::ResourceMetricsConfiguration/ResourceMetricSelection.IncludeMetrics[]" + }, + "AWS::CloudWatch::ResourceMetricsConfiguration/ResourceMetricSelection.IncludeMetrics[]": { + "type": "string", + "minLength": 1, + "maxLength": 255 + }, "AWS::DSQL::Cluster": { "type": "structure", "members": { diff --git a/src/main/resources/cloudformation/create-only-properties.json b/src/main/resources/cloudformation/create-only-properties.json index c1f85ca496..006462ff9e 100644 --- a/src/main/resources/cloudformation/create-only-properties.json +++ b/src/main/resources/cloudformation/create-only-properties.json @@ -238,6 +238,9 @@ "DashboardName" ], "AWS::CloudWatch::OTelEnrichment": [], + "AWS::CloudWatch::ResourceMetricsConfiguration": [ + "ResourceArn" + ], "AWS::CodeBuild::Project": [ "Name" ], 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 74952a7c5d..100912f192 100644 --- a/src/test/java/io/floci/aws/services/cloudformation/CfnProvisionerFixture.java +++ b/src/test/java/io/floci/aws/services/cloudformation/CfnProvisionerFixture.java @@ -47,6 +47,7 @@ import io.floci.aws.services.cloudformation.provisioners.CloudWatchCfnProvisione import io.floci.aws.services.cloudformation.provisioners.CloudWatchCompositeAlarmCfnProvisioner; import io.floci.aws.services.cloudformation.provisioners.CloudWatchDashboardCfnProvisioner; import io.floci.aws.services.cloudformation.provisioners.CloudWatchOTelEnrichmentCfnProvisioner; +import io.floci.aws.services.cloudformation.provisioners.CloudWatchResourceMetricsConfigurationCfnProvisioner; import io.floci.aws.services.cloudformation.provisioners.CodeDeployCfnProvisioner; import io.floci.aws.services.cloudformation.provisioners.CognitoCfnProvisioner; import io.floci.aws.services.cloudformation.provisioners.CognitoIdentityProviderCfnProvisioner; @@ -141,6 +142,7 @@ import io.floci.aws.services.cloudwatch.logs.CloudWatchLogsMetricFilterService; import io.floci.aws.services.cloudwatch.logs.CloudWatchLogsService; import io.floci.aws.services.cloudwatch.metrics.CloudWatchMetricsService; import io.floci.aws.services.cloudwatch.metrics.OTelEnrichmentService; +import io.floci.aws.services.cloudwatch.metrics.ResourceMetricsConfigurationService; import io.floci.aws.services.codedeploy.CodeDeployService; import io.floci.aws.services.cognito.CognitoService; import io.floci.aws.services.configservice.AwsConfigService; @@ -307,6 +309,7 @@ final class CfnProvisionerFixture { private FlowLogService flowLogService; private CloudWatchDashboardsService cloudWatchDashboardsService; private OTelEnrichmentService otelEnrichmentService; + private ResourceMetricsConfigurationService resourceMetricsConfigurationService; private ObservabilityAdminService observabilityAdminService; private CloudWatchLogsMetricFilterService logsMetricFilterService; private IotAuthorizerService iotAuthorizerService; @@ -456,6 +459,10 @@ final class CfnProvisionerFixture { if (otelEnrichmentService != null) { discovered.add(new CloudWatchOTelEnrichmentCfnProvisioner(otelEnrichmentService)); } + if (resourceMetricsConfigurationService != null) { + discovered.add(new CloudWatchResourceMetricsConfigurationCfnProvisioner( + resourceMetricsConfigurationService)); + } if (observabilityAdminService != null) { discovered.add(new ObservabilityAdminTelemetryEnrichmentCfnProvisioner(observabilityAdminService)); } @@ -940,6 +947,11 @@ final class CfnProvisionerFixture { return this; } + public Builder resourceMetricsConfigurations(ResourceMetricsConfigurationService v) { + this.resourceMetricsConfigurationService = v; + return this; + } + public Builder observabilityAdmin(ObservabilityAdminService v) { this.observabilityAdminService = v; return this; diff --git a/src/test/java/io/floci/aws/services/cloudformation/CloudFormationResourceMetricsConfigurationIntegrationTest.java b/src/test/java/io/floci/aws/services/cloudformation/CloudFormationResourceMetricsConfigurationIntegrationTest.java new file mode 100644 index 0000000000..4837652921 --- /dev/null +++ b/src/test/java/io/floci/aws/services/cloudformation/CloudFormationResourceMetricsConfigurationIntegrationTest.java @@ -0,0 +1,256 @@ +package io.floci.aws.services.cloudformation; + +import io.floci.aws.testing.AwsTestClients; +import io.floci.aws.testing.CfnStackWaits; +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.cloudformation.CloudFormationClient; +import software.amazon.awssdk.services.cloudformation.model.Stack; +import software.amazon.awssdk.services.cloudformation.model.StackEvent; +import software.amazon.awssdk.services.cloudwatch.CloudWatchClient; +import software.amazon.awssdk.services.cloudwatch.model.ResourceMetricSelection; +import software.amazon.awssdk.services.cloudwatch.model.ResourceMetricsConfiguration; +import software.amazon.awssdk.services.cloudwatch.model.ResourceNotFoundException; + +import java.time.Instant; +import java.util.List; +import java.util.UUID; +import java.util.stream.Stream; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * {@code AWS::CloudWatch::ResourceMetricsConfiguration}, the detailed monitoring configuration of a replication group + * as a stack resource, each test in a Region of its own. + */ +@QuarkusTest +class CloudFormationResourceMetricsConfigurationIntegrationTest { + // An account of its own, so no other test configures the same ARNs. + private static final String ACCOUNT = "848484848484"; + + @Test + void theStackConfiguresTheGroupUpdatesInPlaceReplacesOnANewArnAndDeletesOnDelete() { + String region = "eu-north-1"; + String stack = "cfn-resource-metrics-" + UUID.randomUUID(); + String first = group(region, "first"); + String second = group(region, "second"); + try (CloudFormationClient cfn = AwsTestClients.create(CloudFormationClient.builder(), ACCOUNT, Region.of(region)); + CloudWatchClient cloudWatch = AwsTestClients.create(CloudWatchClient.builder(), ACCOUNT, + Region.of(region))) { + try { + Stack created = CfnStackWaits.createStack(cfn, stack, template(first, """ + , "MetricSelections": [{"IncludeMetrics": ["valkey.memory.used"]}]""", ""), "CREATE_COMPLETE"); + + ResourceMetricsConfiguration configured = get(cloudWatch, first); + assertEquals(first, CfnStackWaits.output(created, "ConfigRef")); + assertEquals(configured.createdAt(), Instant.parse(CfnStackWaits.output(created, "ConfigCreatedAt"))); + assertEquals(configured.updatedAt(), Instant.parse(CfnStackWaits.output(created, "ConfigUpdatedAt"))); + assertEquals(List.of(selection("valkey.memory.used")), configured.metricSelections()); + + Stack dropped = CfnStackWaits.updateStack(cfn, stack, template(first, "", ""), "UPDATE_COMPLETE"); + ResourceMetricsConfiguration everything = get(cloudWatch, first); + assertFalse(everything.hasMetricSelections(), "a dropped list collects every detailed metric"); + assertEquals(configured.createdAt(), everything.createdAt()); + assertEquals(everything.updatedAt(), Instant.parse(CfnStackWaits.output(dropped, "ConfigUpdatedAt"))); + + Stack replaced = CfnStackWaits.updateStack(cfn, stack, template(second, """ + , "MetricSelections": [{"IncludeMetrics": ["valkey.keyspace.hits"]}]""", ""), + "UPDATE_COMPLETE"); + assertEquals(second, CfnStackWaits.output(replaced, "ConfigRef")); + assertEquals(List.of(selection("valkey.keyspace.hits")), get(cloudWatch, second).metricSelections()); + assertGone(cloudWatch, first); + } finally { + CfnStackWaits.deleteStack(cfn, stack); + } + assertGone(cloudWatch, second); + } + } + + @Test + void aSelectionReadingAReplacedResourceTakesItsNewValue() { + String region = "ap-southeast-3"; + String stack = "cfn-resource-metrics-" + UUID.randomUUID(); + String arn = group(region, "source"); + try (CloudFormationClient cfn = AwsTestClients.create(CloudFormationClient.builder(), ACCOUNT, Region.of(region)); + CloudWatchClient cloudWatch = AwsTestClients.create(CloudWatchClient.builder(), ACCOUNT, + Region.of(region))) { + try { + CfnStackWaits.createStack(cfn, stack, template(arn, """ + , "MetricSelections": [{"IncludeMetrics": [{"Ref": "Source"}]}]""", source("metric.a")), + "CREATE_COMPLETE"); + assertEquals(List.of(selection("metric.a")), get(cloudWatch, arn).metricSelections()); + + CfnStackWaits.updateStack(cfn, stack, template(arn, """ + , "MetricSelections": [{"IncludeMetrics": [{"Ref": "Source"}]}]""", source("metric.b")), + "UPDATE_COMPLETE"); + assertEquals(List.of(selection("metric.b")), get(cloudWatch, arn).metricSelections()); + } finally { + CfnStackWaits.deleteStack(cfn, stack); + } + } + } + + @Test + void aFailedUpdatePutsThePreviousSelectionsAndArnBack() { + String region = "ca-west-1"; + String stack = "cfn-resource-metrics-" + UUID.randomUUID(); + String arn = group(region, "kept"); + String other = group(region, "rolled-back"); + try (CloudFormationClient cfn = AwsTestClients.create(CloudFormationClient.builder(), ACCOUNT, Region.of(region)); + CloudWatchClient cloudWatch = AwsTestClients.create(CloudWatchClient.builder(), ACCOUNT, + Region.of(region))) { + try { + CfnStackWaits.createStack(cfn, stack, template(arn, """ + , "MetricSelections": [{"IncludeMetrics": ["valkey.memory.used"]}]""", ""), "CREATE_COMPLETE"); + ResourceMetricsConfiguration before = get(cloudWatch, arn); + + CfnStackWaits.updateStack(cfn, stack, template(arn, """ + , "MetricSelections": [{"IncludeMetrics": ["valkey.keyspace.hits"]}]""", + CfnStackWaits.failingResourceAfter("Config")), "UPDATE_ROLLBACK_COMPLETE"); + ResourceMetricsConfiguration restored = get(cloudWatch, arn); + assertEquals(before.metricSelections(), restored.metricSelections()); + assertEquals(before.createdAt(), restored.createdAt()); + + CfnStackWaits.updateStack(cfn, stack, template(other, "", + CfnStackWaits.failingResourceAfter("Config")), "UPDATE_ROLLBACK_COMPLETE"); + assertGone(cloudWatch, other); + assertEquals(before.metricSelections(), get(cloudWatch, arn).metricSelections()); + } finally { + CfnStackWaits.deleteStack(cfn, stack); + } + assertGone(cloudWatch, arn); + } + } + + @Test + void aCreateForAConfiguredArnFailsAsAlreadyExistsAndLeavesTheConfigurationInPlace() { + String region = "me-central-1"; + String stack = "cfn-resource-metrics-" + UUID.randomUUID(); + String arn = group(region, "taken"); + try (CloudFormationClient cfn = AwsTestClients.create(CloudFormationClient.builder(), ACCOUNT, Region.of(region)); + CloudWatchClient cloudWatch = AwsTestClients.create(CloudWatchClient.builder(), ACCOUNT, + Region.of(region))) { + cloudWatch.createResourceMetricsConfiguration(request -> request.resourceArn(arn) + .metricSelections(selection("valkey.memory.used"))); + try { + CfnStackWaits.createStack(cfn, stack, template(arn, "", ""), "ROLLBACK_COMPLETE"); + assertEquals("Resource of type 'AWS::CloudWatch::ResourceMetricsConfiguration' with identifier '" + + arn + "' already exists.", CfnStackWaits.failedResourceReason(stack, authorization(region))); + assertEquals(List.of(selection("valkey.memory.used")), get(cloudWatch, arn).metricSelections()); + } finally { + CfnStackWaits.deleteStack(cfn, stack); + cloudWatch.deleteResourceMetricsConfiguration(request -> request.resourceArn(arn)); + } + } + } + + @Test + void aReplacedConfigurationAlreadyGoneIsTakenAsDeleted() { + String region = "il-central-1"; + String stack = "cfn-resource-metrics-" + UUID.randomUUID(); + String gone = group(region, "gone"); + String next = group(region, "next"); + try (CloudFormationClient cfn = AwsTestClients.create(CloudFormationClient.builder(), ACCOUNT, Region.of(region)); + CloudWatchClient cloudWatch = AwsTestClients.create(CloudWatchClient.builder(), ACCOUNT, + Region.of(region))) { + try { + CfnStackWaits.createStack(cfn, stack, template(gone, "", ""), "CREATE_COMPLETE"); + cloudWatch.deleteResourceMetricsConfiguration(request -> request.resourceArn(gone)); + + CfnStackWaits.updateStack(cfn, stack, template(next, "", ""), "UPDATE_COMPLETE"); + + List failed = cfn.describeStackEvents(request -> request.stackName(stack)).stackEvents() + .stream().filter(event -> "DELETE_FAILED".equals(event.resourceStatusAsString())).toList(); + assertEquals(List.of(), failed, "the cleanup takes the missing configuration as deleted"); + get(cloudWatch, next); + } finally { + CfnStackWaits.deleteStack(cfn, stack); + } + } + } + + @ParameterizedTest + @MethodSource("invalidResources") + void aResourceTheModelOrCloudWatchRefusesFailsWithItsMessage(String properties, String reason) { + String region = "sa-east-1"; + String stack = "cfn-resource-metrics-" + UUID.randomUUID(); + try (CloudFormationClient cfn = AwsTestClients.create(CloudFormationClient.builder(), ACCOUNT, + Region.of(region))) { + try { + CfnStackWaits.createStack(cfn, stack, """ + {"Resources": {"Config": {"Type": "AWS::CloudWatch::ResourceMetricsConfiguration", + "Properties": %s}}}""".formatted(properties), "ROLLBACK_COMPLETE"); + String failure = CfnStackWaits.failedResourceReason(stack, authorization(region)); + assertTrue(failure.contains(reason), "reason " + failure + " lacks " + reason); + } finally { + CfnStackWaits.deleteStack(cfn, stack); + } + } + } + + static Stream invalidResources() { + return Stream.of( + Arguments.of("{}", "required key [ResourceArn] not found"), + Arguments.of("{\"ResourceArn\": \"replicationgroup:not-an-arn\"}", + "failed validation constraint for keyword [pattern]"), + Arguments.of(""" + {"ResourceArn": "arn:aws:elasticache:sa-east-1:848484848484:replicationgroup:g", + "MetricSelections": [{}]}""", "required key [IncludeMetrics] not found"), + Arguments.of("{\"ResourceArn\": \"arn:aws:dynamodb:sa-east-1:848484848484:table/orders\"}", + "Unsupported resource type"), + Arguments.of(""" + {"ResourceArn": "arn:aws:elasticache:sa-east-1:848484848484:replicationgroup:g", + "CreatedAt": "2026-12-04T10:00:00Z"}""", + "CreatedAt is a ReadOnly property which cannot be specified in the template")); + } + + /** The configuration of {@code arn}, with {@code properties} after its ARN, then {@code more} resources. */ + private static String template(String arn, String properties, String more) { + return """ + {"Resources": { + "Config": {"Type": "AWS::CloudWatch::ResourceMetricsConfiguration", + "Properties": {"ResourceArn": "%s"%s}}%s}, + "Outputs": { + "ConfigRef": {"Value": {"Ref": "Config"}}, + "ConfigCreatedAt": {"Value": {"Fn::GetAtt": ["Config", "CreatedAt"]}}, + "ConfigUpdatedAt": {"Value": {"Fn::GetAtt": ["Config", "UpdatedAt"]}}}} + """.formatted(arn, properties, more); + } + + /** An SSM parameter named {@code name}, whose {@code Ref} is that name. */ + private static String source(String name) { + return """ + , + "Source": {"Type": "AWS::SSM::Parameter", + "Properties": {"Name": "%s", "Type": "String", "Value": "v"}}""".formatted(name); + } + + private static String group(String region, String name) { + return "arn:aws:elasticache:" + region + ":" + ACCOUNT + ":replicationgroup:" + name; + } + + private static ResourceMetricSelection selection(String metric) { + return ResourceMetricSelection.builder().includeMetrics(metric).build(); + } + + private static ResourceMetricsConfiguration get(CloudWatchClient cloudWatch, String arn) { + return cloudWatch.getResourceMetricsConfiguration(request -> request.resourceArn(arn)) + .resourceMetricsConfiguration(); + } + + private static void assertGone(CloudWatchClient cloudWatch, String arn) { + assertThrows(ResourceNotFoundException.class, () -> get(cloudWatch, arn), arn); + } + + private static String authorization(String region) { + return "AWS4-HMAC-SHA256 Credential=" + ACCOUNT + "/20261204/" + region + + "/cloudformation/aws4_request, SignedHeaders=host, Signature=abc"; + } +} diff --git a/src/test/java/io/floci/aws/services/cloudformation/provisioners/CloudWatchOTelEnrichmentCfnProvisionerTest.java b/src/test/java/io/floci/aws/services/cloudformation/provisioners/CloudWatchOTelEnrichmentCfnProvisionerTest.java index 57ddfd50b5..36cb9602ee 100644 --- a/src/test/java/io/floci/aws/services/cloudformation/provisioners/CloudWatchOTelEnrichmentCfnProvisionerTest.java +++ b/src/test/java/io/floci/aws/services/cloudformation/provisioners/CloudWatchOTelEnrichmentCfnProvisionerTest.java @@ -33,7 +33,7 @@ import static org.mockito.Mockito.when; class CloudWatchOTelEnrichmentCfnProvisionerTest { private static final String REGION = "us-east-1"; private static final String ACCOUNT = "000000000000"; - private static final String SNAPSHOT = "FlociOTelEnrichmentSnapshot"; + private static final String SNAPSHOT = CfnRollback.OTEL_ENRICHMENT_UPDATE_SNAPSHOT_ATTR; private static final JsonNode SQS = json(""" {"IncludeFilters": [{"Namespace": "AWS/SQS", "MetricNames": ["NumberOfMessagesSent"]}]}"""); diff --git a/src/test/java/io/floci/aws/services/cloudformation/provisioners/CloudWatchResourceMetricsConfigurationCfnProvisionerTest.java b/src/test/java/io/floci/aws/services/cloudformation/provisioners/CloudWatchResourceMetricsConfigurationCfnProvisionerTest.java new file mode 100644 index 0000000000..c5036fa873 --- /dev/null +++ b/src/test/java/io/floci/aws/services/cloudformation/provisioners/CloudWatchResourceMetricsConfigurationCfnProvisionerTest.java @@ -0,0 +1,203 @@ +package io.floci.aws.services.cloudformation.provisioners; + +import io.floci.aws.core.common.AwsException; +import io.floci.aws.services.cloudformation.model.StackResource; +import io.floci.aws.services.cloudwatch.metrics.ResourceMetricsConfigurationService; +import io.floci.aws.services.cloudwatch.metrics.model.ResourceMetricsConfiguration; +import io.floci.aws.services.cloudwatch.metrics.model.ResourceMetricsConfiguration.ResourceMetricSelection; +import org.junit.jupiter.api.Test; +import tools.jackson.databind.JsonNode; + +import java.time.Instant; +import java.util.List; + +import static io.floci.aws.services.cloudformation.provisioners.ProvisionContexts.json; +import static io.floci.aws.services.cloudformation.provisioners.ProvisionContexts.standalone; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +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.anyString; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +/** The resource metrics configuration provisioner over a mocked configuration service, in us-east-1. */ +class CloudWatchResourceMetricsConfigurationCfnProvisionerTest { + private static final String REGION = "us-east-1"; + private static final String GROUP = "arn:aws:elasticache:us-east-1:000000000000:replicationgroup:orders"; + private static final String OTHER = "arn:aws:elasticache:us-east-1:000000000000:replicationgroup:billing"; + private static final String SNAPSHOT = CfnRollback.RESOURCE_METRICS_CONFIGURATION_UPDATE_SNAPSHOT_ATTR; + private static final Instant CREATED = Instant.parse("2026-12-04T10:00:00.123456789Z"); + private static final JsonNode MEMORY = json(""" + {"ResourceArn": "%s", "MetricSelections": [{"IncludeMetrics": ["valkey.memory.used"]}]}""".formatted(GROUP)); + + private final ResourceMetricsConfigurationService configurations = mock(ResourceMetricsConfigurationService.class); + private final CloudWatchResourceMetricsConfigurationCfnProvisioner provisioner = + new CloudWatchResourceMetricsConfigurationCfnProvisioner(configurations); + + @Test + void aCreateConfiguresTheArnWithTheTemplatesSelections() { + List memory = selections("valkey.memory.used"); + when(configurations.create(REGION, GROUP, memory)).thenReturn(configuration(GROUP, memory)); + StackResource resource = resource(); + + provisioner.provision(resource, MEMORY, standalone(null, null)); + + verify(configurations).create(REGION, GROUP, memory); + assertEquals(GROUP, resource.getPhysicalId()); + assertEquals("2026-12-04T10:00:00.123Z", resource.getAttributes().get("CreatedAt"), "as the API answers it"); + assertEquals("2026-12-04T10:00:00.123Z", resource.getAttributes().get("UpdatedAt")); + } + + @Test + void aCreateWithoutSelectionsCollectsEveryDetailedMetric() { + when(configurations.create(REGION, GROUP, null)).thenReturn(configuration(GROUP, null)); + + provisioner.provision(resource(), json("{\"ResourceArn\": \"" + GROUP + "\"}"), standalone(null, null)); + + verify(configurations).create(REGION, GROUP, null); + } + + @Test + void aCreateForAConfiguredArnFailsAsAlreadyExists() { + when(configurations.create(anyString(), anyString(), any())).thenThrow(new AwsException("ConflictException", + "This operation attempted to create a resource that already exists.", 409)); + + AwsException refused = assertThrows(AwsException.class, + () -> provisioner.provision(resource(), MEMORY, standalone(null, null))); + + assertEquals("AlreadyExists", refused.getErrorCode()); + assertEquals("Resource of type 'AWS::CloudWatch::ResourceMetricsConfiguration' with identifier '" + GROUP + + "' already exists.", refused.getMessage()); + } + + @Test + void anUpdateResolvingToTheStoredSelectionsWritesNothingAndHasNothingToUndo() { + when(configurations.get(REGION, GROUP)).thenReturn(configuration(GROUP, selections("valkey.memory.used"))); + StackResource resource = resource(); + + provisioner.provision(resource, MEMORY, standalone(GROUP, MEMORY)); + + verify(configurations, never()).update(anyString(), anyString(), any()); + assertFalse(resource.getAttributes().containsKey(SNAPSHOT)); + assertEquals(UpdateCleanupResult.notApplicable(), provisioner.completeUpdate(resource)); + assertTrue(provisioner.rollbackUpdate(resource)); + verify(configurations, never()).update(anyString(), anyString(), any()); + } + + /** What a selection's Ref to a replaced resource looks like here: the same template, other stored selections. */ + @Test + void anUpdateResolvingToOtherSelectionsWritesThemAndARollbackPutsTheStoredOnesBack() { + List hits = selections("valkey.keyspace.hits"); + List memory = selections("valkey.memory.used"); + when(configurations.get(REGION, GROUP)).thenReturn(configuration(GROUP, hits)); + when(configurations.update(REGION, GROUP, memory)).thenReturn(configuration(GROUP, memory)); + when(configurations.update(REGION, GROUP, hits)).thenReturn(new ResourceMetricsConfiguration(GROUP, hits, + CREATED, Instant.parse("2026-12-04T11:00:00.456789Z"))); + StackResource resource = resource(); + + provisioner.provision(resource, MEMORY, standalone(GROUP, MEMORY)); + + verify(configurations).update(REGION, GROUP, memory); + assertFalse(provisioner.hasReplacementUpdate(resource), "the same ARN updates in place"); + + assertTrue(provisioner.rollbackUpdate(resource)); + + verify(configurations).update(REGION, GROUP, hits); + assertEquals("2026-12-04T11:00:00.456Z", resource.getAttributes().get("UpdatedAt"), + "the rollback's write is what GetResourceMetricsConfiguration answers"); + assertFalse(resource.getAttributes().containsKey(SNAPSHOT)); + } + + @Test + void aCommittedInPlaceUpdateSpendsItsSnapshot() { + List memory = selections("valkey.memory.used"); + when(configurations.get(REGION, GROUP)).thenReturn(configuration(GROUP, selections("valkey.keyspace.hits"))); + when(configurations.update(REGION, GROUP, memory)).thenReturn(configuration(GROUP, memory)); + StackResource resource = resource(); + provisioner.provision(resource, MEMORY, standalone(GROUP, MEMORY)); + assertTrue(resource.getAttributes().containsKey(SNAPSHOT)); + + assertEquals(new UpdateCleanupResult(true, true, null, 0, null), provisioner.completeUpdate(resource)); + provisioner.clearUpdate(resource); + + assertFalse(resource.getAttributes().containsKey(SNAPSHOT)); + assertEquals(UpdateCleanupResult.notApplicable(), provisioner.completeUpdate(resource)); + } + + @Test + void aTimestampTheTemplateSetsIsRefusedAsReadOnly() { + JsonNode stamped = json("{\"ResourceArn\": \"" + GROUP + "\", \"UpdatedAt\": \"2026-12-04T10:00:00Z\"}"); + + AwsException refused = assertThrows(AwsException.class, + () -> provisioner.provision(resource(), stamped, standalone(null, null))); + + assertEquals("InvalidRequest", refused.getErrorCode()); + assertEquals("UpdatedAt is a ReadOnly property which cannot be specified in the template", + refused.getMessage()); + verifyNoInteractions(configurations); + } + + @Test + void anUpdateDroppingTheSelectionsClearsThem() { + when(configurations.get(REGION, GROUP)).thenReturn(configuration(GROUP, selections("valkey.memory.used"))); + when(configurations.update(REGION, GROUP, null)).thenReturn(configuration(GROUP, null)); + + provisioner.provision(resource(), json("{\"ResourceArn\": \"" + GROUP + "\"}"), standalone(GROUP, MEMORY)); + + verify(configurations).update(REGION, GROUP, null); + } + + @Test + void anUpdateToAnotherArnCreatesItsConfigurationAndOwesTheOldOneADelete() { + JsonNode other = json("{\"ResourceArn\": \"" + OTHER + "\"}"); + when(configurations.create(REGION, OTHER, null)).thenReturn(configuration(OTHER, null)); + StackResource resource = resource(); + resource.setPhysicalId(GROUP); + + provisioner.provision(resource, other, standalone(GROUP, MEMORY)); + + verify(configurations).create(REGION, OTHER, null); + verify(configurations, never()).update(anyString(), anyString(), any()); + assertEquals(OTHER, resource.getPhysicalId()); + assertTrue(provisioner.hasReplacementUpdate(resource)); + assertEquals(GROUP, provisioner.updateCleanupPhysicalId(resource)); + } + + @Test + void aDeleteTakesAMissingConfigurationAsDeleted() { + doThrow(new AwsException("ResourceNotFoundException", "The named resource does not exist.", 404)) + .when(configurations).delete(REGION, GROUP); + + provisioner.delete("AWS::CloudWatch::ResourceMetricsConfiguration", GROUP, REGION); + + verify(configurations).delete(REGION, GROUP); + } + + @Test + void aDeleteOfAStubFromBeforeThisProvisionerTouchesNoConfiguration() { + provisioner.delete("AWS::CloudWatch::ResourceMetricsConfiguration", "Config-0123abcd", REGION); + + verifyNoInteractions(configurations); + } + + private static StackResource resource() { + StackResource resource = new StackResource(); + resource.setLogicalId("Config"); + resource.setResourceType("AWS::CloudWatch::ResourceMetricsConfiguration"); + return resource; + } + + private static List selections(String... metrics) { + return List.of(new ResourceMetricSelection(List.of(metrics))); + } + + private static ResourceMetricsConfiguration configuration(String arn, List selections) { + return new ResourceMetricsConfiguration(arn, selections, CREATED, CREATED); + } +} diff --git a/src/test/resources/cloudformation/drop-policy.tsv b/src/test/resources/cloudformation/drop-policy.tsv index 71b4dd9b95..8d2cfa99f4 100644 --- a/src/test/resources/cloudformation/drop-policy.tsv +++ b/src/test/resources/cloudformation/drop-policy.tsv @@ -122,6 +122,8 @@ AWS::CloudTrail::Trail SnsTopicName keep:the update skips a null, so the stored AWS::CloudTrail::Trail TrailName keep:the update finds the trail by its physical id AWS::CloudWatch::OTelEnrichment ExcludeFilters clear an update replaces both filter lists as a pair, so a dropped list reads back empty AWS::CloudWatch::OTelEnrichment IncludeFilters clear an update replaces both filter lists as a pair, so a dropped list reads back empty +AWS::CloudWatch::ResourceMetricsConfiguration MetricSelections clear an update without the selections removes the filter, so every detailed metric is collected +AWS::CloudWatch::ResourceMetricsConfiguration ResourceArn create-only AWS::Cognito::UserPoolGroup Description clear AWS::Cognito::UserPoolGroup GroupName create-only a drop gives the group a generated name, so the group is replaced AWS::Cognito::UserPoolGroup Precedence keep:the update skips a null, so the stored value stays diff --git a/src/test/resources/cloudformation/schema-surface.tsv b/src/test/resources/cloudformation/schema-surface.tsv index 608e52d778..9f5bf87b89 100644 --- a/src/test/resources/cloudformation/schema-surface.tsv +++ b/src/test/resources/cloudformation/schema-surface.tsv @@ -64,6 +64,7 @@ AWS::CloudWatch::Alarm Arn ActionConfiguration,ActionsEnabled,AlarmActions,Alarm AWS::CloudWatch::CompositeAlarm Arn ActionConfiguration,ActionsEnabled,ActionsSuppressor,ActionsSuppressorExtensionPeriod,ActionsSuppressorWaitPeriod,AlarmActions,AlarmDescription,AlarmName,AlarmRule,InsufficientDataActions,OKActions,Tags AWS::CloudWatch::Dashboard DashboardBody,DashboardName,Tags AWS::CloudWatch::OTelEnrichment AccountId,Status ExcludeFilters,IncludeFilters +AWS::CloudWatch::ResourceMetricsConfiguration CreatedAt,UpdatedAt MetricSelections,ResourceArn AWS::CodeBuild::Project Arn Artifacts,AutoRetryLimit,BadgeEnabled,BuildBatchConfig,Cache,ConcurrentBuildLimit,Description,EncryptionKey,Environment,FileSystemLocations,LogsConfig,Name,QueuedTimeoutInMinutes,ResourceAccessRole,SecondaryArtifacts,SecondarySourceVersions,SecondarySources,ServiceRole,Source,SourceVersion,Tags,TimeoutInMinutes,Triggers,Visibility,VpcConfig AWS::CodeDeploy::Application ApplicationName,ComputePlatform,Tags AWS::CodeDeploy::DeploymentConfig ComputePlatform,DeploymentConfigName,MinimumHealthyHosts,TrafficRoutingConfig,ZonalConfig diff --git a/src/test/resources/cloudformation/supported-resource-types.tsv b/src/test/resources/cloudformation/supported-resource-types.tsv index 9f988d6c7b..2ae6d6c371 100644 --- a/src/test/resources/cloudformation/supported-resource-types.tsv +++ b/src/test/resources/cloudformation/supported-resource-types.tsv @@ -65,6 +65,7 @@ AWS::CloudWatch::Alarm CloudWatchCfnProvisioner AWS::CloudWatch::CompositeAlarm CloudWatchCompositeAlarmCfnProvisioner AWS::CloudWatch::Dashboard CloudWatchDashboardCfnProvisioner AWS::CloudWatch::OTelEnrichment CloudWatchOTelEnrichmentCfnProvisioner +AWS::CloudWatch::ResourceMetricsConfiguration CloudWatchResourceMetricsConfigurationCfnProvisioner AWS::CodeBuild::Project CodeBuildCfnProvisioner AWS::CodeDeploy::Application CodeDeployCfnProvisioner AWS::CodeDeploy::DeploymentConfig CodeDeployCfnProvisioner diff --git a/tools/aws/regen_cfn_property_types.py b/tools/aws/regen_cfn_property_types.py index 7086254af6..31c09d1cca 100644 --- a/tools/aws/regen_cfn_property_types.py +++ b/tools/aws/regen_cfn_property_types.py @@ -50,8 +50,8 @@ ARCHIVE_URL = "https://schema.cloudformation.us-east-1.amazonaws.com/Cloudformat FETCH_TIMEOUT_SECONDS = 60 # The resource types whose provisioners read their properties through CfnPropertyTypes. -RESOURCE_TYPES = ["AWS::AutoScaling::LaunchConfiguration", "AWS::CloudWatch::OTelEnrichment", "AWS::DSQL::Cluster", - "AWS::EC2::Instance", +RESOURCE_TYPES = ["AWS::AutoScaling::LaunchConfiguration", "AWS::CloudWatch::OTelEnrichment", + "AWS::CloudWatch::ResourceMetricsConfiguration", "AWS::DSQL::Cluster", "AWS::EC2::Instance", "AWS::EC2::LaunchTemplate", "AWS::ECS::TaskDefinition", "AWS::EKS::Cluster", "AWS::EMR::Cluster", "AWS::EMR::InstanceFleetConfig", "AWS::EMR::InstanceGroupConfig", "AWS::EMR::SecurityConfiguration", "AWS::EMR::Step", "AWS::EMR::Studio", diff --git a/tools/docs/cfn_resource_types.yaml b/tools/docs/cfn_resource_types.yaml index 0bac32a651..352fd4856f 100644 --- a/tools/docs/cfn_resource_types.yaml +++ b/tools/docs/cfn_resource_types.yaml @@ -206,6 +206,7 @@ notes: AWS::S3::BucketPolicy: document stored on the bucket; S3 does not evaluate it AWS::SQS::QueuePolicy: accepted; policy not enforced AWS::CloudWatch::OTelEnrichment: one per account and Region; Ref returns the account ID; a create while enrichment runs fails with `AlreadyExists`, and a failed update puts the previous filters back + AWS::CloudWatch::ResourceMetricsConfiguration: Ref returns the monitored resource's ARN; a create for an ARN that has a configuration fails with `AlreadyExists`, and a failed update puts the previous metric selections back AWS::ObservabilityAdmin::TelemetryEnrichment: Ref returns the scope, `ACCOUNT`; starts and stops resource tags for telemetry in the stack's Region AWS::Lambda::Function: Zip via S3/inline `ZipFile`, Image, and the `hot-reload` bind-mount bucket AWS::Lambda::EventSourceMapping: 'SQS, Kinesis, DynamoDB Streams; `ParallelizationFactor` and `TumblingWindowInSeconds` are ignored'