From 2d724d15aa7748c2b82427797daf0bbceea1a15e Mon Sep 17 00:00:00 2001 From: Hector Ventura Date: Sun, 30 Aug 2026 21:47:44 -0500 Subject: [PATCH] refactor(cloudformation): move Kinesis and CloudWatch to their own provisioners (#2758) Migrates AWS::Kinesis::Stream and AWS::CloudWatch::Alarm out of the switch. Two unrelated services in one slice because each is a single service call with property mapping and no shared state; splitting them would cost two review cycles for one mechanical change. Kinesis carries an update path: an unchanged name reconciles stream mode, retention and tags rather than calling createStream again, which the service rejects with ResourceInUseException. It uses ctx.priorPhysicalId() for the same reason the log group slice does, since the body assigns the new id before it returns. sameNameExistingResource, deleteRenamedResource and parseIntProp are copied rather than shared: each still has callers in the monolith. addAlarmActions moves, since all three of its call sites are inside the alarm body. Both service fields leave the monolith; their constructor parameters stay until the endgame. The existing Kinesis and CloudWatch alarm integration tests are QuarkusTests resolved through CDI, so they exercise the new provisioners with no edit, which is the regression evidence for this slice. --- .../CloudFormationResourceProvisioner.java | 165 ------------- .../CloudWatchCfnProvisioner.java | 113 +++++++++ .../provisioners/KinesisCfnProvisioner.java | 167 +++++++++++++ .../CloudWatchCfnProvisionerTest.java | 171 +++++++++++++ .../KinesisCfnProvisionerTest.java | 225 ++++++++++++++++++ .../supported-resource-types.tsv | 4 +- 6 files changed, 678 insertions(+), 167 deletions(-) create mode 100644 src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CloudWatchCfnProvisioner.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/KinesisCfnProvisioner.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CloudWatchCfnProvisionerTest.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/KinesisCfnProvisionerTest.java diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java index 817e53041f..5f94200fc4 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java @@ -225,7 +225,6 @@ public class CloudFormationResourceProvisioner { "AWS::Batch::JobQueue", "AWS::CloudFormation::CustomResource", "AWS::CloudFront::Distribution", - "AWS::CloudWatch::Alarm", "AWS::Cognito::UserPool", "AWS::Cognito::UserPoolClient", "AWS::DynamoDB::GlobalTable", @@ -256,7 +255,6 @@ public class CloudFormationResourceProvisioner { "AWS::IAM::ManagedPolicy", "AWS::IAM::Policy", "AWS::IAM::User", - "AWS::Kinesis::Stream", "AWS::Lambda::EventSourceMapping", "AWS::Lambda::Function", "AWS::Lambda::LayerVersion", @@ -307,8 +305,6 @@ public class CloudFormationResourceProvisioner { private final Ec2Service ec2Service; private final RdsService rdsService; private final EksService eksService; - private final KinesisService kinesisService; - private final CloudWatchMetricsService cloudWatchMetricsService; private final AutoScalingService autoScalingService; private final DocDbService docDbService; private final CloudFrontService cloudFrontService; @@ -374,8 +370,6 @@ public class CloudFormationResourceProvisioner { this.ec2Service = ec2Service; this.rdsService = rdsService; this.eksService = eksService; - this.kinesisService = kinesisService; - this.cloudWatchMetricsService = cloudWatchMetricsService; this.autoScalingService = autoScalingService; this.docDbService = docDbService; this.cloudFrontService = cloudFrontService; @@ -513,10 +507,6 @@ public class CloudFormationResourceProvisioner { provisionDbProxyTargetGroup(resource, properties, engine, region); case "AWS::EKS::Cluster" -> provisionEksCluster(resource, properties, engine, stackName); case "AWS::EKS::Nodegroup" -> provisionEksNodegroup(resource, properties, engine, stackName); - case "AWS::Kinesis::Stream" -> - provisionKinesisStream(resource, properties, engine, region, stackName); - case "AWS::CloudWatch::Alarm" -> - provisionCloudWatchAlarm(resource, properties, engine, region, stackName); case "AWS::AutoScaling::LaunchConfiguration" -> provisionLaunchConfiguration(resource, properties, engine, region, stackName); case "AWS::AutoScaling::AutoScalingGroup" -> @@ -750,9 +740,6 @@ public class CloudFormationResourceProvisioner { case "AWS::RDS::DBClusterParameterGroup" -> rdsService.deleteDbClusterParameterGroup(physicalId, region); case "AWS::EKS::Cluster" -> eksService.deleteCluster(physicalId); - case "AWS::Kinesis::Stream" -> kinesisService.deleteStream(physicalId, region); - case "AWS::CloudWatch::Alarm" -> - cloudWatchMetricsService.deleteAlarms(List.of(physicalId), region); case "AWS::AutoScaling::LaunchConfiguration" -> autoScalingService.deleteLaunchConfiguration(region, physicalId); case "AWS::AutoScaling::AutoScalingGroup" -> @@ -930,160 +917,8 @@ public class CloudFormationResourceProvisioner { // ── Kinesis ───────────────────────────────────────────────────────────────── - private void provisionKinesisStream(StackResource r, JsonNode props, CloudFormationTemplateEngine engine, - String region, String stackName) { - String explicitName = resolveOptional(props, "Name", engine); - String priorPhysicalId = r.getPhysicalId(); - String name; - if (explicitName != null && !explicitName.isBlank()) { - name = explicitName; - } else if (priorPhysicalId != null) { - name = priorPhysicalId; - } else { - name = generatePhysicalName(stackName, r.getLogicalId(), 128, false); - } - String streamMode = null; - if (props != null && props.has("StreamModeDetails")) { - streamMode = engine.resolve(props.get("StreamModeDetails").path("StreamMode")); - if (streamMode != null && streamMode.isBlank()) { - streamMode = null; - } - } - // ShardCount is required for PROVISIONED streams; default to 1 when unset (ON_DEMAND ignores it). - int shardCount = 1; - String shards = resolveOptional(props, "ShardCount", engine); - if (shards != null && !shards.isBlank()) { - try { - shardCount = Integer.parseInt(shards.trim()); - } catch (NumberFormatException ignored) { - // keep default - } - } - Integer retention = null; - String retentionProp = resolveOptional(props, "RetentionPeriodHours", engine); - if (retentionProp != null && !retentionProp.isBlank()) { - try { - retention = Integer.parseInt(retentionProp.trim()); - } catch (NumberFormatException ignored) { - // leave default - } - } - Map tags = new LinkedHashMap<>(); - if (props != null && props.has("Tags") && props.get("Tags").isArray()) { - for (JsonNode tag : props.get("Tags")) { - String key = engine.resolve(tag.path("Key")); - if (!key.isEmpty()) { - tags.put(key, engine.resolve(tag.path("Value"))); - } - } - } - - // provision() re-runs on every UpdateStack, so a same-named stream already on file must be - // reconciled instead of re-created (createStream throws ResourceInUseException). ShardCount - // changes aren't reconciled here: KinesisService has no UpdateShardCount support to call into. - KinesisStream stream = - sameNameExistingResource(priorPhysicalId, name, n -> kinesisService.describeStream(n, region)); - if (stream != null) { - kinesisService.updateStreamMode(name, streamMode != null ? streamMode : "PROVISIONED", region); - if (retention != null) { - if (retention > stream.getRetentionPeriodHours()) { - kinesisService.increaseStreamRetentionPeriod(name, retention, region); - } else if (retention < stream.getRetentionPeriodHours()) { - kinesisService.decreaseStreamRetentionPeriod(name, retention, region); - } - } - Map existingTags = kinesisService.listTagsForStream(name, region); - List tagsToRemove = existingTags.keySet().stream() - .filter(key -> !tags.containsKey(key)) - .toList(); - if (!tagsToRemove.isEmpty()) { - kinesisService.removeTagsFromStream(name, tagsToRemove, region); - } - if (!tags.isEmpty()) { - kinesisService.addTagsToStream(name, tags, region); - } - stream = kinesisService.describeStream(name, region); - } else { - stream = kinesisService.createStream(name, shardCount, streamMode, region); - if (retention != null) { - stream.setRetentionPeriodHours(retention); - } - if (!tags.isEmpty()) { - stream.getTags().putAll(tags); - } - deleteRenamedResource(priorPhysicalId, name, id -> kinesisService.deleteStream(id, region), - "Kinesis stream"); - } - - // Ref returns the stream name; Fn::GetAtt Arn returns the stream ARN. - r.setPhysicalId(name); - r.getAttributes().put("Arn", stream.getStreamArn()); - } - // ── CloudWatch ────────────────────────────────────────────────────────────── - private void provisionCloudWatchAlarm(StackResource r, JsonNode props, CloudFormationTemplateEngine engine, - String region, String stackName) { - String name = resolveOptional(props, "AlarmName", engine); - if (name == null || name.isBlank()) { - name = generatePhysicalName(stackName, r.getLogicalId(), 255, false); - } - - MetricAlarm alarm = new MetricAlarm(); - alarm.setAlarmName(name); - alarm.setAlarmDescription(resolveOptional(props, "AlarmDescription", engine)); - alarm.setMetricName(resolveOptional(props, "MetricName", engine)); - alarm.setNamespace(resolveOptional(props, "Namespace", engine)); - alarm.setStatistic(resolveOptional(props, "Statistic", engine)); - alarm.setUnit(resolveOptional(props, "Unit", engine)); - alarm.setComparisonOperator(resolveOptional(props, "ComparisonOperator", engine)); - alarm.setPeriod(parseIntProp(props, "Period", engine, 60)); - alarm.setEvaluationPeriods(parseIntProp(props, "EvaluationPeriods", engine, 1)); - alarm.setDatapointsToAlarm(parseIntProp(props, "DatapointsToAlarm", engine, alarm.getEvaluationPeriods())); - String threshold = resolveOptional(props, "Threshold", engine); - if (threshold != null && !threshold.isBlank()) { - try { - alarm.setThreshold(Double.parseDouble(threshold.trim())); - } catch (NumberFormatException ignored) { - // leave default - } - } - String treatMissing = resolveOptional(props, "TreatMissingData", engine); - if (treatMissing != null && !treatMissing.isBlank()) { - alarm.setTreatMissingData(treatMissing); - } - String actionsEnabled = resolveOptional(props, "ActionsEnabled", engine); - alarm.setActionsEnabled(actionsEnabled == null || Boolean.parseBoolean(actionsEnabled)); - - if (props != null && props.has("Dimensions") && props.get("Dimensions").isArray()) { - List dimensions = new ArrayList<>(); - for (JsonNode dim : props.get("Dimensions")) { - dimensions.add(new Dimension(engine.resolve(dim.path("Name")), engine.resolve(dim.path("Value")))); - } - alarm.setDimensions(dimensions); - } - addAlarmActions(props, "AlarmActions", engine, alarm.getAlarmActions()); - addAlarmActions(props, "OKActions", engine, alarm.getOkActions()); - addAlarmActions(props, "InsufficientDataActions", engine, alarm.getInsufficientDataActions()); - - cloudWatchMetricsService.putMetricAlarm(alarm, region); - // Ref returns the alarm name; Fn::GetAtt Arn returns the alarm ARN. - r.setPhysicalId(name); - r.getAttributes().put("Arn", alarm.getAlarmArn()); - } - - private void addAlarmActions(JsonNode props, String field, CloudFormationTemplateEngine engine, - List target) { - if (props != null && props.has(field) && props.get(field).isArray()) { - for (JsonNode action : props.get(field)) { - String resolved = engine.resolve(action); - if (resolved != null && !resolved.isBlank()) { - target.add(resolved); - } - } - } - } - // ── Auto Scaling ──────────────────────────────────────────────────────────── private void provisionLaunchConfiguration(StackResource r, JsonNode props, CloudFormationTemplateEngine engine, diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CloudWatchCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CloudWatchCfnProvisioner.java new file mode 100644 index 0000000000..cfe9185575 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CloudWatchCfnProvisioner.java @@ -0,0 +1,113 @@ +package io.github.hectorvent.floci.services.cloudformation.provisioners; + +import com.fasterxml.jackson.databind.JsonNode; +import io.github.hectorvent.floci.services.cloudformation.model.StackResource; +import io.github.hectorvent.floci.services.cloudwatch.metrics.CloudWatchMetricsService; +import io.github.hectorvent.floci.services.cloudwatch.metrics.model.Dimension; +import io.github.hectorvent.floci.services.cloudwatch.metrics.model.MetricAlarm; +import jakarta.enterprise.context.ApplicationScoped; + +import java.util.ArrayList; +import java.util.List; +import java.util.Set; + +/** Provisions {@code AWS::CloudWatch::Alarm}. */ +@ApplicationScoped +public class CloudWatchCfnProvisioner implements CfnResourceProvisioner { + + private static final int ALARM_NAME_MAX_LENGTH = 255; + private static final int DEFAULT_PERIOD_SECONDS = 60; + private static final int DEFAULT_EVALUATION_PERIODS = 1; + + private final CloudWatchMetricsService cloudWatchMetricsService; + + public CloudWatchCfnProvisioner(CloudWatchMetricsService cloudWatchMetricsService) { + this.cloudWatchMetricsService = cloudWatchMetricsService; + } + + @Override + public Set resourceTypes() { + return Set.of("AWS::CloudWatch::Alarm"); + } + + @Override + public void provision(StackResource r, JsonNode props, ProvisionContext ctx) { + String name = ctx.resolveOptional(props, "AlarmName"); + if (name == null || name.isBlank()) { + name = ctx.generatePhysicalName(r.getLogicalId(), ALARM_NAME_MAX_LENGTH, false); + } + + MetricAlarm alarm = new MetricAlarm(); + alarm.setAlarmName(name); + alarm.setAlarmDescription(ctx.resolveOptional(props, "AlarmDescription")); + alarm.setMetricName(ctx.resolveOptional(props, "MetricName")); + alarm.setNamespace(ctx.resolveOptional(props, "Namespace")); + alarm.setStatistic(ctx.resolveOptional(props, "Statistic")); + alarm.setUnit(ctx.resolveOptional(props, "Unit")); + alarm.setComparisonOperator(ctx.resolveOptional(props, "ComparisonOperator")); + alarm.setPeriod(parseIntProp(props, "Period", ctx, DEFAULT_PERIOD_SECONDS)); + alarm.setEvaluationPeriods(parseIntProp(props, "EvaluationPeriods", ctx, DEFAULT_EVALUATION_PERIODS)); + alarm.setDatapointsToAlarm( + parseIntProp(props, "DatapointsToAlarm", ctx, alarm.getEvaluationPeriods())); + String threshold = ctx.resolveOptional(props, "Threshold"); + if (threshold != null && !threshold.isBlank()) { + try { + alarm.setThreshold(Double.parseDouble(threshold.trim())); + } catch (NumberFormatException ignored) { + // leave default + } + } + String treatMissing = ctx.resolveOptional(props, "TreatMissingData"); + if (treatMissing != null && !treatMissing.isBlank()) { + alarm.setTreatMissingData(treatMissing); + } + String actionsEnabled = ctx.resolveOptional(props, "ActionsEnabled"); + alarm.setActionsEnabled(actionsEnabled == null || Boolean.parseBoolean(actionsEnabled)); + + if (props != null && props.has("Dimensions") && props.get("Dimensions").isArray()) { + List dimensions = new ArrayList<>(); + for (JsonNode dim : props.get("Dimensions")) { + dimensions.add(new Dimension(ctx.engine().resolve(dim.path("Name")), + ctx.engine().resolve(dim.path("Value")))); + } + alarm.setDimensions(dimensions); + } + addAlarmActions(props, "AlarmActions", ctx, alarm.getAlarmActions()); + addAlarmActions(props, "OKActions", ctx, alarm.getOkActions()); + addAlarmActions(props, "InsufficientDataActions", ctx, alarm.getInsufficientDataActions()); + + cloudWatchMetricsService.putMetricAlarm(alarm, ctx.region()); + // Ref returns the alarm name; Fn::GetAtt Arn returns the alarm ARN. + r.setPhysicalId(name); + r.getAttributes().put("Arn", alarm.getAlarmArn()); + } + + private void addAlarmActions(JsonNode props, String field, ProvisionContext ctx, List target) { + if (props != null && props.has(field) && props.get(field).isArray()) { + for (JsonNode action : props.get(field)) { + String resolved = ctx.engine().resolve(action); + if (resolved != null && !resolved.isBlank()) { + target.add(resolved); + } + } + } + } + + /** Copied from the monolith, which still has callers for it. */ + private int parseIntProp(JsonNode props, String name, ProvisionContext ctx, int fallback) { + String value = ctx.resolveOptional(props, name); + if (value == null || value.isBlank()) { + return fallback; + } + try { + return Integer.parseInt(value.trim()); + } catch (NumberFormatException e) { + return fallback; + } + } + + @Override + public void delete(String resourceType, String physicalId, String region) { + cloudWatchMetricsService.deleteAlarms(List.of(physicalId), region); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/KinesisCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/KinesisCfnProvisioner.java new file mode 100644 index 0000000000..6bd22ad6e6 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/KinesisCfnProvisioner.java @@ -0,0 +1,167 @@ +package io.github.hectorvent.floci.services.cloudformation.provisioners; + +import com.fasterxml.jackson.databind.JsonNode; +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.services.cloudformation.model.StackResource; +import io.github.hectorvent.floci.services.kinesis.KinesisService; +import io.github.hectorvent.floci.services.kinesis.model.KinesisStream; +import jakarta.enterprise.context.ApplicationScoped; +import org.jboss.logging.Logger; + +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.function.Consumer; +import java.util.function.Function; + +/** Provisions {@code AWS::Kinesis::Stream}. */ +@ApplicationScoped +public class KinesisCfnProvisioner implements CfnResourceProvisioner { + + private static final Logger LOG = Logger.getLogger(KinesisCfnProvisioner.class); + + private static final int STREAM_NAME_MAX_LENGTH = 128; + private static final int DEFAULT_SHARD_COUNT = 1; + private static final String DEFAULT_STREAM_MODE = "PROVISIONED"; + + private final KinesisService kinesisService; + + public KinesisCfnProvisioner(KinesisService kinesisService) { + this.kinesisService = kinesisService; + } + + @Override + public Set resourceTypes() { + return Set.of("AWS::Kinesis::Stream"); + } + + @Override + public void provision(StackResource r, JsonNode props, ProvisionContext ctx) { + String explicitName = ctx.resolveOptional(props, "Name"); + String priorPhysicalId = ctx.priorPhysicalId(); + String name; + if (explicitName != null && !explicitName.isBlank()) { + name = explicitName; + } else if (priorPhysicalId != null) { + name = priorPhysicalId; + } else { + name = ctx.generatePhysicalName(r.getLogicalId(), STREAM_NAME_MAX_LENGTH, false); + } + + String streamMode = null; + if (props != null && props.has("StreamModeDetails")) { + streamMode = ctx.engine().resolve(props.get("StreamModeDetails").path("StreamMode")); + if (streamMode != null && streamMode.isBlank()) { + streamMode = null; + } + } + // ShardCount is required for PROVISIONED streams; default to 1 when unset (ON_DEMAND ignores it). + int shardCount = DEFAULT_SHARD_COUNT; + String shards = ctx.resolveOptional(props, "ShardCount"); + if (shards != null && !shards.isBlank()) { + try { + shardCount = Integer.parseInt(shards.trim()); + } catch (NumberFormatException ignored) { + // keep default + } + } + Integer retention = null; + String retentionProp = ctx.resolveOptional(props, "RetentionPeriodHours"); + if (retentionProp != null && !retentionProp.isBlank()) { + try { + retention = Integer.parseInt(retentionProp.trim()); + } catch (NumberFormatException ignored) { + // leave default + } + } + Map tags = new LinkedHashMap<>(); + if (props != null && props.has("Tags") && props.get("Tags").isArray()) { + for (JsonNode tag : props.get("Tags")) { + String key = ctx.engine().resolve(tag.path("Key")); + if (!key.isEmpty()) { + tags.put(key, ctx.engine().resolve(tag.path("Value"))); + } + } + } + + // provision() re-runs on every UpdateStack, so a same-named stream already on file must be + // reconciled instead of re-created (createStream throws ResourceInUseException). ShardCount + // changes aren't reconciled here: KinesisService has no UpdateShardCount support to call into. + KinesisStream stream = sameNameExistingResource(priorPhysicalId, name, + n -> kinesisService.describeStream(n, ctx.region())); + if (stream != null) { + kinesisService.updateStreamMode(name, + streamMode != null ? streamMode : DEFAULT_STREAM_MODE, ctx.region()); + if (retention != null) { + if (retention > stream.getRetentionPeriodHours()) { + kinesisService.increaseStreamRetentionPeriod(name, retention, ctx.region()); + } else if (retention < stream.getRetentionPeriodHours()) { + kinesisService.decreaseStreamRetentionPeriod(name, retention, ctx.region()); + } + } + Map existingTags = kinesisService.listTagsForStream(name, ctx.region()); + List tagsToRemove = existingTags.keySet().stream() + .filter(key -> !tags.containsKey(key)) + .toList(); + if (!tagsToRemove.isEmpty()) { + kinesisService.removeTagsFromStream(name, tagsToRemove, ctx.region()); + } + if (!tags.isEmpty()) { + kinesisService.addTagsToStream(name, tags, ctx.region()); + } + stream = kinesisService.describeStream(name, ctx.region()); + } else { + stream = kinesisService.createStream(name, shardCount, streamMode, ctx.region()); + if (retention != null) { + stream.setRetentionPeriodHours(retention); + } + if (!tags.isEmpty()) { + stream.getTags().putAll(tags); + } + deleteRenamedResource(priorPhysicalId, name, + id -> kinesisService.deleteStream(id, ctx.region()), "Kinesis stream"); + } + + // Ref returns the stream name; Fn::GetAtt Arn returns the stream ARN. + r.setPhysicalId(name); + r.getAttributes().put("Arn", stream.getStreamArn()); + } + + /** + * The resource already on file under this same name, or null when this is a create or a rename. + * Copied from the monolith, which still has callers for it. + */ + private T sameNameExistingResource(String priorPhysicalId, String name, Function lookup) { + if (priorPhysicalId == null || !priorPhysicalId.equals(name)) { + return null; + } + try { + return lookup.apply(name); + } catch (AwsException notFound) { + // Expected when the resource was deleted out of band since the prior update; the + // caller falls back to creating it fresh under the same name. + LOG.debugv(notFound, "No existing {0} found on file, falling back to create", name); + return null; + } + } + + /** Best-effort removal of the old resource after a rename. Copied, as above. */ + private void deleteRenamedResource(String priorPhysicalId, String newName, Consumer delete, + String resourceKind) { + if (priorPhysicalId == null || priorPhysicalId.equals(newName)) { + return; + } + try { + delete.accept(priorPhysicalId); + } catch (RuntimeException e) { + LOG.warnv(e, "Failed to delete renamed {0} {1} after replacement by {2}", + resourceKind, priorPhysicalId, newName); + } + } + + @Override + public void delete(String resourceType, String physicalId, String region) { + kinesisService.deleteStream(physicalId, region); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CloudWatchCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CloudWatchCfnProvisionerTest.java new file mode 100644 index 0000000000..e50da67102 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CloudWatchCfnProvisionerTest.java @@ -0,0 +1,171 @@ +package io.github.hectorvent.floci.services.cloudformation.provisioners; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine; +import io.github.hectorvent.floci.services.cloudformation.model.StackResource; +import io.github.hectorvent.floci.services.cloudwatch.metrics.CloudWatchMetricsService; +import io.github.hectorvent.floci.services.cloudwatch.metrics.model.MetricAlarm; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +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.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +/** {@code AWS::CloudWatch::Alarm}. */ +class CloudWatchCfnProvisionerTest { + + private static final ObjectMapper MAPPER = new ObjectMapper(); + private static final String REGION = "us-east-1"; + + private CloudWatchMetricsService metrics; + private CloudWatchCfnProvisioner provisioner; + private ProvisionContext ctx; + + @BeforeEach + void setUp() { + metrics = mock(CloudWatchMetricsService.class); + provisioner = new CloudWatchCfnProvisioner(metrics); + CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class); + when(engine.resolve(any())).thenAnswer(i -> { + JsonNode node = i.getArgument(0); + return node == null || node.isMissingNode() || node.isNull() ? null : node.asText(); + }); + when(engine.resolveNode(any())).thenAnswer(i -> i.getArgument(0)); + ctx = new ProvisionContext(engine, REGION, "000000000000", "my-stack"); + } + + private static JsonNode props(String json) { + try { + return MAPPER.readTree(json); + } catch (Exception e) { + throw new IllegalArgumentException(e); + } + } + + private MetricAlarm provisionAndCapture(String json) { + StackResource r = new StackResource(); + r.setLogicalId("Alarm"); + r.setResourceType("AWS::CloudWatch::Alarm"); + r.setAttributes(new HashMap<>()); + provisioner.provision(r, props(json), ctx); + ArgumentCaptor alarm = ArgumentCaptor.forClass(MetricAlarm.class); + verify(metrics).putMetricAlarm(alarm.capture(), eq(REGION)); + return alarm.getValue(); + } + + @Test + void refIsTheAlarmNameAndTheAlarmReachesTheService() { + StackResource r = new StackResource(); + r.setLogicalId("Alarm"); + r.setResourceType("AWS::CloudWatch::Alarm"); + r.setAttributes(new HashMap<>()); + + provisioner.provision(r, props(""" + {"AlarmName": "cpu-high", "MetricName": "CPUUtilization", "Namespace": "AWS/EC2", + "ComparisonOperator": "GreaterThanThreshold", "Threshold": "80.5"} + """), ctx); + + assertEquals("cpu-high", r.getPhysicalId(), "Ref is the alarm name"); + assertTrue(r.getAttributes().containsKey("Arn"), "aws-cloudwatch-alarm.json declares Arn read-only"); + + ArgumentCaptor alarm = ArgumentCaptor.forClass(MetricAlarm.class); + verify(metrics).putMetricAlarm(alarm.capture(), eq(REGION)); + assertEquals("CPUUtilization", alarm.getValue().getMetricName()); + assertEquals("AWS/EC2", alarm.getValue().getNamespace()); + assertEquals(80.5, alarm.getValue().getThreshold()); + } + + @Test + void anUnnamedAlarmGetsAGeneratedStackScopedName() { + StackResource r = new StackResource(); + r.setLogicalId("Alarm"); + r.setResourceType("AWS::CloudWatch::Alarm"); + r.setAttributes(new HashMap<>()); + + provisioner.provision(r, props("{}"), ctx); + + assertTrue(r.getPhysicalId().startsWith("my-stack-Alarm-"), r.getPhysicalId()); + } + + @Test + void periodAndEvaluationPeriodsFallBackToTheAwsDefaults() { + MetricAlarm alarm = provisionAndCapture(""" + {"AlarmName": "a"} + """); + + assertEquals(60, alarm.getPeriod()); + assertEquals(1, alarm.getEvaluationPeriods()); + // DatapointsToAlarm defaults to EvaluationPeriods rather than to a fixed number. + assertEquals(1, alarm.getDatapointsToAlarm()); + } + + @Test + void datapointsToAlarmDefaultsToEvaluationPeriods() { + MetricAlarm alarm = provisionAndCapture(""" + {"AlarmName": "a", "EvaluationPeriods": "5"} + """); + + assertEquals(5, alarm.getEvaluationPeriods()); + assertEquals(5, alarm.getDatapointsToAlarm()); + } + + /** ActionsEnabled is true on AWS unless explicitly disabled, so an absent property means true. */ + @Test + void actionsAreEnabledUnlessExplicitlyDisabled() { + assertTrue(provisionAndCapture(""" + {"AlarmName": "a"} + """).isActionsEnabled()); + + setUp(); + assertFalse(provisionAndCapture(""" + {"AlarmName": "a", "ActionsEnabled": "false"} + """).isActionsEnabled()); + } + + @Test + void dimensionsAndAllThreeActionListsAreCarried() { + MetricAlarm alarm = provisionAndCapture(""" + { + "AlarmName": "a", + "Dimensions": [{"Name": "InstanceId", "Value": "i-123"}], + "AlarmActions": ["arn:alarm"], + "OKActions": ["arn:ok"], + "InsufficientDataActions": ["arn:insufficient"] + } + """); + + assertEquals(1, alarm.getDimensions().size()); + assertEquals("InstanceId", alarm.getDimensions().get(0).name()); + assertEquals("i-123", alarm.getDimensions().get(0).value()); + assertEquals(List.of("arn:alarm"), alarm.getAlarmActions()); + assertEquals(List.of("arn:ok"), alarm.getOkActions()); + assertEquals(List.of("arn:insufficient"), alarm.getInsufficientDataActions()); + } + + @Test + void anUnparseableThresholdIsIgnoredRatherThanFailingTheResource() { + MetricAlarm alarm = provisionAndCapture(""" + {"AlarmName": "a", "Threshold": "high"} + """); + + assertEquals(0.0, alarm.getThreshold()); + } + + @Test + void deleteReachesTheService() { + provisioner.delete("AWS::CloudWatch::Alarm", "cpu-high", REGION); + verify(metrics).deleteAlarms(List.of("cpu-high"), REGION); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/KinesisCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/KinesisCfnProvisionerTest.java new file mode 100644 index 0000000000..70dc0dad0c --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/KinesisCfnProvisionerTest.java @@ -0,0 +1,225 @@ +package io.github.hectorvent.floci.services.cloudformation.provisioners; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine; +import io.github.hectorvent.floci.services.cloudformation.model.StackResource; +import io.github.hectorvent.floci.services.kinesis.KinesisService; +import io.github.hectorvent.floci.services.kinesis.model.KinesisStream; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +/** {@code AWS::Kinesis::Stream}, whose provision body doubles as its update path. */ +class KinesisCfnProvisionerTest { + + private static final ObjectMapper MAPPER = new ObjectMapper(); + private static final String REGION = "us-east-1"; + + private KinesisService kinesis; + private KinesisCfnProvisioner provisioner; + private CloudFormationTemplateEngine engine; + + @BeforeEach + void setUp() { + kinesis = mock(KinesisService.class); + provisioner = new KinesisCfnProvisioner(kinesis); + engine = mock(CloudFormationTemplateEngine.class); + when(engine.resolve(any())).thenAnswer(i -> { + JsonNode node = i.getArgument(0); + return node == null || node.isMissingNode() || node.isNull() ? null : node.asText(); + }); + when(engine.resolveNode(any())).thenAnswer(i -> i.getArgument(0)); + when(kinesis.listTagsForStream(anyString(), anyString())).thenReturn(Map.of()); + } + + private static JsonNode props(String json) { + try { + return MAPPER.readTree(json); + } catch (Exception e) { + throw new IllegalArgumentException(e); + } + } + + private static KinesisStream stream(String arn, int retentionHours) { + KinesisStream s = new KinesisStream(); + s.setStreamArn(arn); + s.setRetentionPeriodHours(retentionHours); + return s; + } + + private StackResource provision(String json, String priorPhysicalId) { + StackResource r = new StackResource(); + r.setLogicalId("Stream"); + r.setResourceType("AWS::Kinesis::Stream"); + r.setPhysicalId(priorPhysicalId); + r.setAttributes(new HashMap<>()); + provisioner.provision(r, props(json), + new ProvisionContext(engine, REGION, "000000000000", "my-stack", priorPhysicalId)); + return r; + } + + @Test + void createUsesTheExplicitNameAndExposesTheArn() { + when(kinesis.createStream(eq("s"), anyInt(), any(), eq(REGION))) + .thenReturn(stream("arn:aws:kinesis:us-east-1:000000000000:stream/s", 24)); + + StackResource r = provision(""" + {"Name": "s", "ShardCount": "3"} + """, null); + + verify(kinesis).createStream("s", 3, null, REGION); + assertEquals("s", r.getPhysicalId(), "Ref is the stream name"); + // aws-kinesis-stream.json readOnlyProperties + assertEquals(Map.of("Arn", "arn:aws:kinesis:us-east-1:000000000000:stream/s"), r.getAttributes()); + } + + @Test + void shardCountDefaultsToOneWhenAbsentOrUnparseable() { + when(kinesis.createStream(anyString(), anyInt(), any(), anyString())).thenReturn(stream("arn", 24)); + + provision(""" + {"Name": "a"} + """, null); + verify(kinesis).createStream("a", 1, null, REGION); + + provision(""" + {"Name": "b", "ShardCount": "many"} + """, null); + verify(kinesis).createStream("b", 1, null, REGION); + } + + @Test + void streamModeDetailsAreForwarded() { + when(kinesis.createStream(anyString(), anyInt(), any(), anyString())).thenReturn(stream("arn", 24)); + + provision(""" + {"Name": "s", "StreamModeDetails": {"StreamMode": "ON_DEMAND"}} + """, null); + + verify(kinesis).createStream("s", 1, "ON_DEMAND", REGION); + } + + /** + * provision() re-runs on every UpdateStack, so an unchanged name must reconcile rather than + * call createStream again, which the service rejects with ResourceInUseException. + */ + @Test + void anUnchangedNameReconcilesInsteadOfRecreating() { + when(kinesis.describeStream("s", REGION)).thenReturn(stream("arn", 24)); + + provision(""" + {"Name": "s"} + """, "s"); + + verify(kinesis, never()).createStream(anyString(), anyInt(), any(), anyString()); + verify(kinesis).updateStreamMode("s", "PROVISIONED", REGION); + } + + @Test + void retentionMovesInTheRightDirectionOnly() { + when(kinesis.describeStream("s", REGION)).thenReturn(stream("arn", 24)); + + provision(""" + {"Name": "s", "RetentionPeriodHours": "48"} + """, "s"); + verify(kinesis).increaseStreamRetentionPeriod("s", 48, REGION); + + provision(""" + {"Name": "s", "RetentionPeriodHours": "12"} + """, "s"); + verify(kinesis).decreaseStreamRetentionPeriod("s", 12, REGION); + + provision(""" + {"Name": "s", "RetentionPeriodHours": "24"} + """, "s"); + verify(kinesis, never()).increaseStreamRetentionPeriod("s", 24, REGION); + verify(kinesis, never()).decreaseStreamRetentionPeriod("s", 24, REGION); + } + + @Test + void reconcileRemovesTagsDroppedFromTheTemplate() { + when(kinesis.describeStream("s", REGION)).thenReturn(stream("arn", 24)); + when(kinesis.listTagsForStream("s", REGION)).thenReturn(Map.of("stale", "1", "kept", "2")); + + provision(""" + {"Name": "s", "Tags": [{"Key": "kept", "Value": "2"}]} + """, "s"); + + verify(kinesis).removeTagsFromStream("s", List.of("stale"), REGION); + verify(kinesis).addTagsToStream("s", Map.of("kept", "2"), REGION); + } + + /** A stream deleted out of band since the last update falls back to a fresh create. */ + @Test + void aMissingStreamFallsBackToCreate() { + when(kinesis.describeStream("s", REGION)) + .thenThrow(new AwsException("ResourceNotFoundException", "gone", 400)); + when(kinesis.createStream(anyString(), anyInt(), any(), anyString())).thenReturn(stream("arn", 24)); + + provision(""" + {"Name": "s"} + """, "s"); + + verify(kinesis).createStream("s", 1, null, REGION); + } + + @Test + void aRenameCreatesTheNewStreamAndBestEffortDeletesTheOld() { + when(kinesis.createStream(eq("new"), anyInt(), any(), anyString())).thenReturn(stream("arn", 24)); + + StackResource r = provision(""" + {"Name": "new"} + """, "old"); + + assertEquals("new", r.getPhysicalId()); + verify(kinesis).deleteStream("old", REGION); + } + + /** A failure deleting the renamed-away stream must not fail the resource. */ + @Test + void aFailedCleanupOfTheRenamedStreamIsSwallowed() { + when(kinesis.createStream(eq("new"), anyInt(), any(), anyString())).thenReturn(stream("arn", 24)); + org.mockito.Mockito.doThrow(new RuntimeException("boom")) + .when(kinesis).deleteStream("old", REGION); + + StackResource r = provision(""" + {"Name": "new"} + """, "old"); + + assertEquals("new", r.getPhysicalId(), "the new stream is still the resource's physical id"); + } + + @Test + void anUnnamedStreamGetsAGeneratedNameKeptAcrossUpdates() { + when(kinesis.createStream(anyString(), anyInt(), any(), anyString())).thenReturn(stream("arn", 24)); + + StackResource created = provision("{}", null); + assertTrue(created.getPhysicalId().startsWith("my-stack-Stream-"), created.getPhysicalId()); + + when(kinesis.describeStream(created.getPhysicalId(), REGION)).thenReturn(stream("arn", 24)); + StackResource updated = provision("{}", created.getPhysicalId()); + assertEquals(created.getPhysicalId(), updated.getPhysicalId()); + } + + @Test + void deleteReachesTheService() { + provisioner.delete("AWS::Kinesis::Stream", "s", REGION); + verify(kinesis).deleteStream("s", REGION); + } +} diff --git a/src/test/resources/cloudformation/supported-resource-types.tsv b/src/test/resources/cloudformation/supported-resource-types.tsv index e6d720ffe4..b31fb19afb 100644 --- a/src/test/resources/cloudformation/supported-resource-types.tsv +++ b/src/test/resources/cloudformation/supported-resource-types.tsv @@ -20,7 +20,7 @@ AWS::Batch::JobQueue LEGACY_SWITCH AWS::CDK::Metadata CdkMetadataCfnProvisioner AWS::CloudFormation::CustomResource LEGACY_SWITCH AWS::CloudFront::Distribution LEGACY_SWITCH -AWS::CloudWatch::Alarm LEGACY_SWITCH +AWS::CloudWatch::Alarm CloudWatchCfnProvisioner AWS::CodeBuild::Project CodeBuildCfnProvisioner AWS::CodePipeline::CustomActionType CodePipelineCfnProvisioner AWS::CodePipeline::Pipeline CodePipelineCfnProvisioner @@ -72,7 +72,7 @@ AWS::IAM::Role IamRoleCfnProvisioner AWS::IAM::User LEGACY_SWITCH AWS::KMS::Alias KmsCfnProvisioner AWS::KMS::Key KmsCfnProvisioner -AWS::Kinesis::Stream LEGACY_SWITCH +AWS::Kinesis::Stream KinesisCfnProvisioner AWS::KinesisFirehose::DeliveryStream FirehoseCfnProvisioner AWS::Lambda::Alias LambdaVersionAliasCfnProvisioner AWS::Lambda::EventSourceMapping LEGACY_SWITCH