Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

feat(cloudwatch): provision AWS::CloudWatch::Dashboard (#3231)

Mario Toffia460aa0718ee5
diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationCloudWatchDashboardTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationCloudWatchDashboardTest.java
new file mode 100644
index 0000000000..5aba65a442
--- /dev/null
+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationCloudWatchDashboardTest.java
@@ -0,0 +1,208 @@
+package com.floci.test;
+
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+import software.amazon.awssdk.services.cloudformation.CloudFormationClient;
+import software.amazon.awssdk.services.cloudformation.model.CloudFormationException;
+import software.amazon.awssdk.services.cloudformation.model.DescribeStacksRequest;
+import software.amazon.awssdk.services.cloudformation.model.Output;
+import software.amazon.awssdk.services.cloudformation.model.Parameter;
+import software.amazon.awssdk.services.cloudformation.model.Stack;
+import software.amazon.awssdk.services.cloudwatch.CloudWatchClient;
+import software.amazon.awssdk.services.cloudwatch.model.GetDashboardResponse;
+import software.amazon.awssdk.services.cloudwatch.model.CloudWatchException;
+import software.amazon.awssdk.services.cloudwatch.model.Tag;
+
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+/**
+ * Drives an {@code AWS::CloudWatch::Dashboard} through the CloudFormation SDK and reads it back
+ * through the CloudWatch SDK: {@code Ref} is the name, a body or tag change updates in place, a
+ * name change replaces the dashboard and removes the displaced one, and the stack delete removes it.
+ */
+@DisplayName("CloudFormation AWS::CloudWatch::Dashboard")
+class CloudFormationCloudWatchDashboardTest {
+
+ private static CloudFormationClient cloudFormation;
+ private static CloudWatchClient cloudWatch;
+ private static String stackName;
+ private static String dashboardName;
+
+ @BeforeAll
+ static void setup() {
+ cloudFormation = TestFixtures.cloudFormationClient();
+ cloudWatch = TestFixtures.cloudWatchClient();
+ stackName = TestFixtures.uniqueName("compat-cfn-dashboard");
+ dashboardName = TestFixtures.uniqueName("compat-dashboard");
+ }
+
+ @AfterAll
+ static void cleanup() {
+ if (cloudFormation != null) {
+ try {
+ cloudFormation.deleteStack(r -> r.stackName(stackName));
+ waitForDeleted(stackName, 60);
+ } catch (Exception e) {
+ System.err.println("CloudFormation dashboard cleanup skipped: " + e.getMessage());
+ }
+ cloudFormation.close();
+ }
+ if (cloudWatch != null) {
+ cloudWatch.close();
+ }
+ }
+
+ @Test
+ void dashboardFollowsTheTemplateThroughCreateUpdateReplacementAndDelete() throws InterruptedException {
+ cloudFormation.createStack(r -> r
+ .stackName(stackName)
+ .templateBody(template())
+ .parameters(parameters(dashboardName, "Requests", "platform")));
+ assertThat(waitForTerminal(stackName, 60)).isEqualTo("CREATE_COMPLETE");
+
+ assertThat(output("DashboardRef")).as("Ref is the dashboard name").isEqualTo(dashboardName);
+ GetDashboardResponse created = get(dashboardName);
+ assertThat(created.dashboardBody())
+ .isEqualTo("{\"widgets\":[{\"type\":\"text\",\"properties\":{\"markdown\":\"Requests\"}}]}");
+ assertThat(created.dashboardArn()).endsWith(":dashboard/" + dashboardName);
+ assertThat(tags(created.dashboardArn())).containsExactlyEntriesOf(Map.of("team", "platform"));
+
+ cloudFormation.updateStack(r -> r
+ .stackName(stackName)
+ .templateBody(template())
+ .parameters(parameters(dashboardName, "Errors", "data")));
+ assertThat(waitForTerminal(stackName, 60)).isEqualTo("UPDATE_COMPLETE");
+ assertThat(output("DashboardRef")).as("a body or tag change updates in place").isEqualTo(dashboardName);
+ assertThat(get(dashboardName).dashboardBody()).contains("\"Errors\"");
+ assertThat(tags(created.dashboardArn())).containsExactlyEntriesOf(Map.of("team", "data"));
+
+ String renamed = dashboardName + "-v2";
+ cloudFormation.updateStack(r -> r
+ .stackName(stackName)
+ .templateBody(template())
+ .parameters(parameters(renamed, "Errors", "data")));
+ assertThat(waitForTerminal(stackName, 60)).isEqualTo("UPDATE_COMPLETE");
+ assertThat(output("DashboardRef")).as("a name change replaces the dashboard").isEqualTo(renamed);
+ assertThat(get(renamed).dashboardBody()).contains("\"Errors\"");
+ assertDashboardMissing(dashboardName, "the displaced dashboard is deleted once the update commits");
+
+ cloudFormation.deleteStack(r -> r.stackName(stackName));
+ waitForDeleted(stackName, 60);
+ assertDashboardMissing(renamed, "the stack delete removes the dashboard");
+ }
+
+ /**
+ * GetDashboard answers ResourceNotFound with HTTP 404 for a dashboard that does not exist. The
+ * code is asserted rather than the exception class: the SDK resolves the class from the JSON
+ * error type, and the code is what both the Query and JSON wire forms carry.
+ */
+ private static void assertDashboardMissing(String name, String because) {
+ assertThatThrownBy(() -> get(name))
+ .as(because)
+ .isInstanceOfSatisfying(CloudWatchException.class, e -> {
+ assertThat(e.statusCode()).isEqualTo(404);
+ assertThat(e.awsErrorDetails().errorCode()).isEqualTo("ResourceNotFound");
+ });
+ }
+
+ private static GetDashboardResponse get(String name) {
+ return cloudWatch.getDashboard(r -> r.dashboardName(name));
+ }
+
+ private static Map<String, String> tags(String arn) {
+ return cloudWatch.listTagsForResource(r -> r.resourceARN(arn)).tags().stream()
+ .collect(Collectors.toMap(Tag::key, Tag::value));
+ }
+
+ private static String template() {
+ return """
+ {
+ "Parameters": {
+ "Name": {"Type": "String"},
+ "Title": {"Type": "String"},
+ "Team": {"Type": "String"}
+ },
+ "Resources": {
+ "Dashboard": {
+ "Type": "AWS::CloudWatch::Dashboard",
+ "Properties": {
+ "DashboardName": {"Ref": "Name"},
+ "DashboardBody": {"Fn::Join": ["", [
+ "{\\"widgets\\":[{\\"type\\":\\"text\\",\\"properties\\":{\\"markdown\\":\\"",
+ {"Ref": "Title"},
+ "\\"}}]}"
+ ]]},
+ "Tags": [{"Key": "team", "Value": {"Ref": "Team"}}]
+ }
+ }
+ },
+ "Outputs": {
+ "DashboardRef": {"Value": {"Ref": "Dashboard"}}
+ }
+ }
+ """;
+ }
+
+ private static List<Parameter> parameters(String name, String title, String team) {
+ return List.of(
+ Parameter.builder().parameterKey("Name").parameterValue(name).build(),
+ Parameter.builder().parameterKey("Title").parameterValue(title).build(),
+ Parameter.builder().parameterKey("Team").parameterValue(team).build());
+ }
+
+ private static String output(String key) {
+ Stack stack = cloudFormation.describeStacks(
+ DescribeStacksRequest.builder().stackName(stackName).build()).stacks().get(0);
+ return stack.outputs().stream()
+ .filter(o -> key.equals(o.outputKey()))
+ .map(Output::outputValue)
+ .findFirst()
+ .orElseThrow(() -> new AssertionError("stack " + stackName + " has no output " + key));
+ }
+
+ private static String waitForTerminal(String name, int maxSeconds) throws InterruptedException {
+ long deadline = System.currentTimeMillis() + maxSeconds * 1000L;
+ while (System.currentTimeMillis() < deadline) {
+ List<Stack> stacks = cloudFormation.describeStacks(
+ DescribeStacksRequest.builder().stackName(name).build()).stacks();
+ if (!stacks.isEmpty()) {
+ String status = stacks.get(0).stackStatusAsString();
+ if (!status.endsWith("_IN_PROGRESS")) {
+ return status;
+ }
+ }
+ Thread.sleep(500);
+ }
+ throw new AssertionError(
+ "Stack " + name + " did not reach a terminal state within " + maxSeconds + "s");
+ }
+
+ private static void waitForDeleted(String name, int maxSeconds) throws InterruptedException {
+ long deadline = System.currentTimeMillis() + maxSeconds * 1000L;
+ while (System.currentTimeMillis() < deadline) {
+ try {
+ List<Stack> stacks = cloudFormation.describeStacks(
+ DescribeStacksRequest.builder().stackName(name).build()).stacks();
+ if (stacks.isEmpty()
+ || "DELETE_COMPLETE".equals(stacks.get(0).stackStatusAsString())) {
+ return;
+ }
+ } catch (CloudFormationException e) {
+ if (e.getMessage() != null && e.getMessage().contains("does not exist")) {
+ return;
+ }
+ throw e;
+ }
+ Thread.sleep(500);
+ }
+ throw new AssertionError(
+ "Stack " + name + " was not deleted within " + maxSeconds + "s");
+ }
+}
diff --git a/docs/services/cloudformation.md b/docs/services/cloudformation.md
index 3caf02508e..d5bf43ec3d 100644
--- a/docs/services/cloudformation.md
+++ b/docs/services/cloudformation.md
@@ -100,7 +100,7 @@ cross-resource references.
| Kinesis Data Firehose | `DeliveryStream` |
| IoT Core | `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`, `Distribution`, `OriginAccessControl`, `OriginRequestPolicy`, `ResponseHeadersPolicy` |
-| CloudWatch | `Alarm` |
+| CloudWatch | `Alarm`, `Dashboard` |
| CloudWatch Logs | `LogGroup` |
| WAFv2 | `WebACL` |
| Config | `ConfigRule` |
diff --git a/docs/services/cloudwatch.md b/docs/services/cloudwatch.md
index c0a5e234e3..b47ca469b7 100644
--- a/docs/services/cloudwatch.md
+++ b/docs/services/cloudwatch.md
@@ -197,6 +197,13 @@ aws logs put-retention-policy \
| `DeleteMetricStream` | Delete a metric stream |
| `StartMetricStreams` | Move metric streams to `running` |
| `StopMetricStreams` | Move metric streams to `stopped` |
+| `PutDashboard` | Create a dashboard, or replace its body when the name is taken (tags apply on create only) |
+| `GetDashboard` | Read a dashboard body and ARN |
+| `ListDashboards` | List dashboards, optionally by name prefix |
+| `DeleteDashboards` | Delete dashboards by name |
+| `TagResource` | Tag an alarm or dashboard by ARN |
+| `UntagResource` | Remove tags from an alarm or dashboard |
+| `ListTagsForResource` | List the tags of an alarm or dashboard |
Metric streams are stored as definitions with their `running` or `stopped` state. Floci never
delivers metrics to the Firehose delivery stream a metric stream names.
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnRollback.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnRollback.java
index 78d05a9078..937e7aa7ec 100644
--- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnRollback.java
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnRollback.java
@@ -61,6 +61,14 @@ public final class CfnRollback {
*/
public static final String EVENT_INVOKE_CONFIG_SNAPSHOT_ATTR = "__FlociEventInvokeConfigSnapshot";
+ /**
+ * Holds the body and tags a dashboard carried before an in-place update changed them, or the
+ * fact that it did not exist, so a failed stack update can put it back. Written by
+ * {@code CloudWatchDashboardCfnProvisioner} before its first mutating call and spent by its
+ * {@code rollbackUpdate}.
+ */
+ public static final String DASHBOARD_UPDATE_SNAPSHOT_ATTR = "__FlociDashboardUpdateSnapshot";
+
/**
* Holds the pipe a rename displaced: the name it still lives under, the region that addresses
* it, how many times deleting it has been attempted, and when the replacement was created.
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CloudWatchDashboardCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CloudWatchDashboardCfnProvisioner.java
new file mode 100644
index 0000000000..52e8d8012f
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CloudWatchDashboardCfnProvisioner.java
@@ -0,0 +1,250 @@
+package io.github.hectorvent.floci.services.cloudformation.provisioners;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
+import io.github.hectorvent.floci.services.cloudwatch.dashboards.CloudWatchDashboardsService;
+import io.github.hectorvent.floci.services.cloudwatch.dashboards.model.Dashboard;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.inject.Inject;
+
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * Provisions {@code AWS::CloudWatch::Dashboard}. Alarms belong to {@link CloudWatchCfnProvisioner};
+ * this class takes only the dashboards service so the test fixture can wire it from that service.
+ *
+ * <p>The dashboard name is the physical id and {@code Ref}, generated when the template gives none
+ * and kept across updates. It is create-only: an update that keeps it puts the body again and
+ * drives the tags to the template's set, since {@code PutDashboard} leaves an existing dashboard's
+ * tags alone, and keeps the body and tags it replaces on the resource so a failed stack update can
+ * put them back. An update that changes it, or drops an explicit name for a generated one, creates
+ * the new dashboard and leaves the displaced one to the {@link ReplacementCleanup} record, deleted
+ * once the update commits or put back on rollback.
+ *
+ * <p>The schema declares no read-only properties, so there is nothing for {@code Fn::GetAtt}.
+ */
+@ApplicationScoped
+public class CloudWatchDashboardCfnProvisioner implements CfnResourceProvisioner {
+
+ private static final String TYPE = "AWS::CloudWatch::Dashboard";
+ private static final ObjectMapper MAPPER = new ObjectMapper();
+ private static final int DASHBOARD_NAME_MAX_LENGTH = 255;
+ /** The registry schema's {@code maxItems} for Tags, which CloudFormation checks before the handler runs. */
+ private static final int MAX_TAGS = 50;
+ /**
+ * Records whether the dashboard's name came from the template or was generated, so a later
+ * update can tell an explicit name being dropped, which replaces the dashboard on AWS, from
+ * an unnamed dashboard keeping the name it was given. Read back off the stored attributes.
+ */
+ private static final String NAME_MODE_ATTR = "FlociDashboardNameMode";
+ private static final String NAME_MODE_EXPLICIT = "explicit";
+ private static final String NAME_MODE_GENERATED = "generated";
+
+ private final CloudWatchDashboardsService dashboardsService;
+
+ @Inject
+ public CloudWatchDashboardCfnProvisioner(CloudWatchDashboardsService dashboardsService) {
+ this.dashboardsService = dashboardsService;
+ }
+
+ @Override
+ public Set<String> resourceTypes() {
+ return Set.of(TYPE);
+ }
+
+ @Override
+ public void provision(StackResource r, JsonNode props, ProvisionContext ctx) {
+ // A snapshot describes the update in flight; one an earlier update left behind is stale.
+ r.getAttributes().remove(CfnRollback.DASHBOARD_UPDATE_SNAPSHOT_ATTR);
+ Map<String, String> attributesBefore = Map.copyOf(r.getAttributes());
+ String explicitName = ctx.resolveOptional(props, "DashboardName");
+ boolean hasExplicitName = explicitName != null && !explicitName.isBlank();
+ if (hasExplicitName && explicitName.length() > DASHBOARD_NAME_MAX_LENGTH) {
+ throw new AwsException("ValidationError",
+ TYPE + " DashboardName must be at most " + DASHBOARD_NAME_MAX_LENGTH + " characters", 400);
+ }
+ // The body is a string on the wire; a template may still write it as a JSON object.
+ String body = props == null ? null : ctx.engine().resolveJsonAttribute(props.path("DashboardBody"));
+ if (body == null || body.isBlank()) {
+ throw new AwsException("ValidationError", TYPE + " requires DashboardBody", 400);
+ }
+ Map<String, String> tags = ctx.resolveTags(props, "Tags");
+ if (tags.size() > MAX_TAGS) {
+ throw new AwsException("ValidationError",
+ TYPE + " Tags must hold at most " + MAX_TAGS + " entries, got " + tags.size(), 400);
+ }
+ String name = physicalName(r, ctx, explicitName, hasExplicitName);
+
+ if (ctx.reusesPriorEntity(name)) {
+ snapshotBeforeUpdate(r, name, ctx.region());
+ }
+ try {
+ // PutDashboard creates or replaces the body in full, and applies the tags on create only.
+ Dashboard dashboard = dashboardsService.putDashboard(name, body, tags, ctx.region());
+ if (ctx.reusesPriorEntity(name)) {
+ reconcileTags(dashboard.getDashboardArn(), tags, ctx.region());
+ }
+ } catch (RuntimeException failure) {
+ unwind(r, name, failure);
+ throw failure;
+ }
+ r.setPhysicalId(name);
+ r.getAttributes().put(NAME_MODE_ATTR, hasExplicitName ? NAME_MODE_EXPLICIT : NAME_MODE_GENERATED);
+ ReplacementCleanup.record(r, ctx, attributesBefore);
+ }
+
+ /**
+ * A provision that changed the dashboard and then failed undoes itself. CloudFormationService
+ * puts the resource the stack held before the attempt back in its place, and that object never
+ * carried the snapshot taken here, so it marks the resource restored and the rollback walker
+ * skips {@link #rollbackUpdate}: without this the stack reports a completed rollback while the
+ * new body, or a half-reconciled set of tags, is still live. The stack must report the original
+ * failure, so an unwind that cannot restore is attached to it and recorded as a rollback
+ * failure, which ends the stack in UPDATE_ROLLBACK_FAILED rather than claiming the prior
+ * dashboard is intact. The unwind repeats the tag call the update just made, so it can come
+ * back carrying the very exception that interrupted the update; a throwable cannot be
+ * suppressed under itself, and the failure is recorded before the two are joined so that
+ * record never depends on it.
+ */
+ private void unwind(StackResource r, String name, RuntimeException failure) {
+ try {
+ rollbackUpdate(r);
+ r.getAttributes().put(CfnRollback.UPDATE_ROLLBACK_RESTORED_ATTR, "true");
+ } catch (RuntimeException unwindFailure) {
+ r.getAttributes().put(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR,
+ "Could not roll back the update of dashboard " + name + ": " + unwindFailure.getMessage());
+ if (unwindFailure != failure) {
+ failure.addSuppressed(unwindFailure);
+ }
+ }
+ }
+
+ /**
+ * The template's name when it gives one; otherwise the generated name the dashboard already
+ * has, unless the previous name was explicit, since dropping an explicit name is a replacement
+ * on AWS rather than the old name living on; and a fresh generated name failing both.
+ */
+ private static String physicalName(StackResource r, ProvisionContext ctx, String explicitName,
+ boolean hasExplicitName) {
+ if (hasExplicitName) {
+ return explicitName;
+ }
+ boolean explicitNameRemoved = ctx.isUpdate()
+ && NAME_MODE_EXPLICIT.equals(r.getAttributes().get(NAME_MODE_ATTR));
+ if (ctx.isUpdate() && !explicitNameRemoved) {
+ return ctx.priorPhysicalId();
+ }
+ return ctx.generatePhysicalName(r.getLogicalId(), DASHBOARD_NAME_MAX_LENGTH, false);
+ }
+
+ private void reconcileTags(String dashboardArn, Map<String, String> desired, String region) {
+ Map<String, String> current = dashboardsService.listTagsForResource(dashboardArn, region);
+ List<String> stale = ProvisionContext.staleTagKeys(current, desired);
+ if (!stale.isEmpty()) {
+ dashboardsService.untagResource(dashboardArn, stale, region);
+ }
+ if (!desired.isEmpty()) {
+ dashboardsService.tagResource(dashboardArn, desired, region);
+ }
+ }
+
+ /**
+ * Keeps the body and tags the dashboard has before an in-place update changes them, so
+ * {@link #rollbackUpdate} can put them back. A dashboard that is already gone is recorded as
+ * absent, so a rollback removes the one the update created in its place.
+ */
+ private void snapshotBeforeUpdate(StackResource r, String name, String region) {
+ ObjectNode snapshot = MAPPER.createObjectNode();
+ snapshot.put("region", region);
+ snapshot.put("name", name);
+ try {
+ Dashboard current = dashboardsService.getDashboard(name, region);
+ snapshot.put("body", current.getDashboardBody());
+ ObjectNode tags = snapshot.putObject("tags");
+ current.getTags().forEach(tags::put);
+ } catch (AwsException e) {
+ if (!"ResourceNotFound".equals(e.getErrorCode())) {
+ throw e;
+ }
+ snapshot.put("absent", true);
+ }
+ r.getAttributes().put(CfnRollback.DASHBOARD_UPDATE_SNAPSHOT_ATTR, snapshot.toString());
+ }
+
+ @Override
+ public void delete(String resourceType, String physicalId, String region) {
+ if (physicalId == null || physicalId.isBlank()) {
+ return;
+ }
+ // ResourceNotFound is CloudWatch's own code for a dashboard that is already gone.
+ CfnDeletes.safeDelete("CloudWatch dashboard", physicalId,
+ () -> dashboardsService.deleteDashboards(List.of(physicalId), region),
+ "ResourceNotFound");
+ }
+
+ @Override
+ public boolean hasReplacementUpdate(StackResource resource) {
+ return ReplacementCleanup.hasReplacement(resource);
+ }
+
+ @Override
+ public String updateCleanupPhysicalId(StackResource resource) {
+ return ReplacementCleanup.cleanupPhysicalId(resource);
+ }
+
+ @Override
+ public UpdateCleanupResult completeUpdate(StackResource resource) {
+ return ReplacementCleanup.complete(resource, this::delete);
+ }
+
+ @Override
+ public void clearUpdate(StackResource resource) {
+ resource.getAttributes().remove(CfnRollback.DASHBOARD_UPDATE_SNAPSHOT_ATTR);
+ ReplacementCleanup.clear(resource);
+ }
+
+ /**
+ * A replacement is undone through the cleanup record and an in-place update from the snapshot
+ * taken before it: the body is put back and the tags driven to the set the snapshot holds.
+ * With neither on the resource the provision failed before it changed anything, since every
+ * mutation is preceded by the snapshot or followed by the record, so there is nothing to undo.
+ */
+ @Override
+ public boolean rollbackUpdate(StackResource resource) {
+ if (ReplacementCleanup.rollback(resource, this::delete)) {
+ return true;
+ }
+ // The snapshot is spent only once the restore succeeded: a restore that throws leaves it in
+ // place for the next attempt instead of reporting a rollback that never happened.
+ String raw = resource.getAttributes().get(CfnRollback.DASHBOARD_UPDATE_SNAPSHOT_ATTR);
+ if (raw == null) {
+ return true;
+ }
+ JsonNode snapshot;
+ try {
+ snapshot = MAPPER.readTree(raw);
+ } catch (JsonProcessingException e) {
+ throw new IllegalStateException("Could not read the dashboard update snapshot for "
+ + resource.getLogicalId(), e);
+ }
+ String region = snapshot.path("region").asText();
+ String name = snapshot.path("name").asText();
+ if (snapshot.path("absent").asBoolean(false)) {
+ delete(TYPE, name, region);
+ } else {
+ Map<String, String> tags = new LinkedHashMap<>();
+ snapshot.path("tags").fields().forEachRemaining(tag -> tags.put(tag.getKey(), tag.getValue().asText()));
+ Dashboard restored = dashboardsService.putDashboard(name, snapshot.path("body").asText(), tags, region);
+ reconcileTags(restored.getDashboardArn(), tags, region);
+ }
+ resource.getAttributes().remove(CfnRollback.DASHBOARD_UPDATE_SNAPSHOT_ATTR);
+ return true;
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java
index c1bb65ef44..b30010461c 100644
--- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java
@@ -35,6 +35,7 @@ import io.github.hectorvent.floci.services.cloudformation.provisioners.EventsCfn
import io.github.hectorvent.floci.services.cloudformation.provisioners.CdkMetadataCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.CloudTrailCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.CloudWatchCfnProvisioner;
+import io.github.hectorvent.floci.services.cloudformation.provisioners.CloudWatchDashboardCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.CognitoCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.Ec2LaunchTemplateCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.Ec2NetworkCfnProvisioner;
@@ -69,6 +70,7 @@ import io.github.hectorvent.floci.services.cloudformation.provisioners.CfnResour
import io.github.hectorvent.floci.services.cloudformation.provisioners.CloudFormationResourceRegistry;
import io.github.hectorvent.floci.services.cloudfront.CloudFrontService;
import io.github.hectorvent.floci.services.cloudtrail.CloudTrailService;
+import io.github.hectorvent.floci.services.cloudwatch.dashboards.CloudWatchDashboardsService;
import io.github.hectorvent.floci.services.cloudwatch.logs.CloudWatchLogsService;
import io.github.hectorvent.floci.services.cloudwatch.metrics.CloudWatchMetricsService;
import io.github.hectorvent.floci.services.cognito.CognitoService;
@@ -166,6 +168,7 @@ final class CfnProvisionerFixture {
// Services that back a provisioner without being a constructor argument of the
// dispatcher. They exist only so inferredProvisioners() can wire their provisioner.
private FlowLogService flowLogService;
+ private CloudWatchDashboardsService cloudWatchDashboardsService;
private IotDomainConfigurationService iotDomainConfigurationService;
private IotService iotService;
private LambdaMicrovmsService lambdaMicrovmsService;
@@ -249,6 +252,9 @@ final class CfnProvisionerFixture {
if (cloudWatchMetricsService != null) {
discovered.add(new CloudWatchCfnProvisioner(cloudWatchMetricsService));
}
+ if (cloudWatchDashboardsService != null) {
+ discovered.add(new CloudWatchDashboardCfnProvisioner(cloudWatchDashboardsService));
+ }
if (iamService != null) {
discovered.add(new IamRoleCfnProvisioner(iamService));
discovered.add(new IamUserCfnProvisioner(iamService));
@@ -515,6 +521,11 @@ final class CfnProvisionerFixture {
return this;
}
+ public Builder cloudWatchDashboards(CloudWatchDashboardsService v) {
+ this.cloudWatchDashboardsService = v;
+ return this;
+ }
+
public Builder iotDomainConfiguration(IotDomainConfigurationService v) {
this.iotDomainConfigurationService = v;
return this;
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationCloudWatchDashboardIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationCloudWatchDashboardIntegrationTest.java
new file mode 100644
index 0000000000..c269a0f0b1
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationCloudWatchDashboardIntegrationTest.java
@@ -0,0 +1,433 @@
+package io.github.hectorvent.floci.services.cloudformation;
+
+import io.github.hectorvent.floci.core.common.XmlParser;
+import io.github.hectorvent.floci.services.cloudwatch.dashboards.CloudWatchDashboardsService;
+import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
+import io.quarkus.test.junit.QuarkusTest;
+import io.quarkus.test.junit.mockito.InjectSpy;
+import io.restassured.response.Response;
+import io.restassured.specification.RequestSpecification;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+import org.mockito.Mockito;
+
+import java.util.List;
+import java.util.Map;
+
+import static io.restassured.RestAssured.given;
+import static org.hamcrest.Matchers.containsString;
+import static org.hamcrest.Matchers.equalTo;
+import static org.hamcrest.Matchers.not;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
+import static org.mockito.ArgumentMatchers.anyMap;
+import static org.mockito.ArgumentMatchers.anyString;
+
+/**
+ * Provisions an {@code AWS::CloudWatch::Dashboard} through a CloudFormation stack and reads it
+ * back through the CloudWatch API. {@code Ref} is the dashboard name; a body or tag change updates
+ * the dashboard in place; a name change replaces it and deletes the displaced dashboard once the
+ * update commits; a failed update rolls the replacement back; and the stack delete removes it.
+ */
+@QuarkusTest
+class CloudFormationCloudWatchDashboardIntegrationTest {
+
+ @InjectSpy
+ CloudWatchDashboardsService dashboardsService;
+
+ private static final String CFN_AUTH =
+ "AWS4-HMAC-SHA256 Credential=test/20260908/us-east-1/cloudformation/aws4_request";
+ private static final String CW_AUTH =
+ "AWS4-HMAC-SHA256 Credential=test/20260908/us-east-1/monitoring/aws4_request";
+
+ /**
+ * The body is an {@code Fn::Join} of fragments, the shape the CDK emits, and the name, the
+ * widget title and the tag value are parameters so one template drives every update.
+ */
+ private static final String TEMPLATE = """
+ {
+ "Parameters": {
+ "Name": {"Type": "String"},
+ "Title": {"Type": "String", "Default": "Requests"},
+ "Team": {"Type": "String", "Default": "platform"}
+ },
+ "Resources": {
+ "Dashboard": {
+ "Type": "AWS::CloudWatch::Dashboard",
+ "Properties": {
+ "DashboardName": {"Ref": "Name"},
+ "DashboardBody": {"Fn::Join": ["", [
+ "{\\"widgets\\":[{\\"type\\":\\"text\\",\\"properties\\":{\\"markdown\\":\\"",
+ {"Ref": "Title"},
+ "\\"}}]}"
+ ]]},
+ "Tags": [{"Key": "team", "Value": {"Ref": "Team"}}%s]
+ }
+ }%s
+ },
+ "Outputs": {
+ "DashboardRef": {"Value": {"Ref": "Dashboard"}}
+ }
+ }
+ """;
+
+ private static final String UNNAMED_TEMPLATE = """
+ {
+ "Parameters": {"Title": {"Type": "String", "Default": "Latency"}},
+ "Resources": {
+ "Dashboard": {
+ "Type": "AWS::CloudWatch::Dashboard",
+ "Properties": {
+ "DashboardBody": {"widgets": [{"type": "text", "properties": {"markdown": {"Ref": "Title"}}}]}
+ }
+ }
+ },
+ "Outputs": {
+ "DashboardRef": {"Value": {"Ref": "Dashboard"}}
+ }
+ }
+ """;
+
+ private static final String EXTRA_TAG = ", {\"Key\": \"env\", \"Value\": \"dev\"}";
+
+ /** A resource that fails after the dashboard, so the update rolls the replacement back. */
+ private static final String FAILING_RESOURCE = """
+ ,
+ "BadSecret": {
+ "Type": "AWS::SecretsManager::Secret",
+ "DependsOn": "Dashboard",
+ "Properties": {
+ "Name": "dashboard-rollback-%s",
+ "SecretString": "explicit",
+ "GenerateSecretString": {"PasswordLength": 32}
+ }
+ }""";
+
+ @BeforeAll
+ static void configureRestAssured() {
+ RestAssuredJsonUtils.configureAwsContentTypes();
+ }
+
+ @Test
+ void dashboardFollowsTheTemplateThroughCreateUpdateReplacementAndDelete() throws InterruptedException {
+ String suffix = Long.toString(System.nanoTime(), 36);
+ String stack = "cfn-dashboard-" + suffix;
+ String name = "ops-" + suffix;
+ String renamed = "ops-v2-" + suffix;
+
+ cloudFormation(stack, "CreateStack", TEMPLATE.formatted(EXTRA_TAG, ""), Map.of("Name", name));
+ assertEquals(name, outputValue(describeStacks(stack, "CREATE_COMPLETE"), "DashboardRef"),
+ "Ref is the dashboard name");
+ getDashboard(name).then()
+ .statusCode(200)
+ .body("GetDashboardResponse.GetDashboardResult.DashboardName", equalTo(name))
+ .body("GetDashboardResponse.GetDashboardResult.DashboardBody",
+ equalTo("{\"widgets\":[{\"type\":\"text\",\"properties\":{\"markdown\":\"Requests\"}}]}"));
+ String arn = dashboardArn(name);
+ assertTags(arn, Map.of("team", "platform", "env", "dev"), Map.of());
+
+ cloudFormation(stack, "UpdateStack", TEMPLATE.formatted("", ""),
+ Map.of("Name", name, "Title", "Errors", "Team", "data"));
+ assertEquals(name, outputValue(describeStacks(stack, "UPDATE_COMPLETE"), "DashboardRef"),
+ "a body or tag change keeps the same dashboard");
+ getDashboard(name).then()
+ .statusCode(200)
+ .body("GetDashboardResponse.GetDashboardResult.DashboardBody", containsString("\"Errors\""));
+ assertTags(arn, Map.of("team", "data"), Map.of("env", "dev"));
+
+ cloudFormation(stack, "UpdateStack", TEMPLATE.formatted("", ""),
+ Map.of("Name", renamed, "Title", "Errors", "Team", "data"));
+ assertEquals(renamed, outputValue(describeStacks(stack, "UPDATE_COMPLETE"), "DashboardRef"),
+ "a name change is a replacement");
+ getDashboard(renamed).then()
+ .statusCode(200)
+ .body("GetDashboardResponse.GetDashboardResult.DashboardBody", containsString("\"Errors\""));
+ assertTags(dashboardArn(renamed), Map.of("team", "data"), Map.of());
+ getDashboard(name).then()
+ .statusCode(404)
+ .body("ErrorResponse.Error.Code", equalTo("ResourceNotFound"));
+ assertEvent(describeEvents(stack), "DELETE_COMPLETE", name);
+
+ cloudFormation(stack, "DeleteStack", null, Map.of());
+ awaitStackDeleted(stack);
+ getDashboard(renamed).then()
+ .statusCode(404)
+ .body("ErrorResponse.Error.Code", equalTo("ResourceNotFound"));
+ }
+
+ @Test
+ void anUnnamedDashboardKeepsItsGeneratedNameAcrossUpdates() throws InterruptedException {
+ String suffix = Long.toString(System.nanoTime(), 36);
+ String stack = "cfn-dashboard-unnamed-" + suffix;
+
+ cloudFormation(stack, "CreateStack", UNNAMED_TEMPLATE, Map.of());
+ String generated = outputValue(describeStacks(stack, "CREATE_COMPLETE"), "DashboardRef");
+ assertTrue(generated.startsWith(stack + "-Dashboard-"), generated);
+ getDashboard(generated).then()
+ .statusCode(200)
+ .body("GetDashboardResponse.GetDashboardResult.DashboardBody",
+ equalTo("{\"widgets\":[{\"type\":\"text\",\"properties\":{\"markdown\":\"Latency\"}}]}"));
+
+ cloudFormation(stack, "UpdateStack", UNNAMED_TEMPLATE, Map.of("Title", "Throughput"));
+ assertEquals(generated, outputValue(describeStacks(stack, "UPDATE_COMPLETE"), "DashboardRef"));
+ getDashboard(generated).then()
+ .statusCode(200)
+ .body("GetDashboardResponse.GetDashboardResult.DashboardBody", containsString("\"Throughput\""));
+
+ cloudFormation(stack, "DeleteStack", null, Map.of());
+ awaitStackDeleted(stack);
+ getDashboard(generated).then().statusCode(404);
+ }
+
+ @Test
+ void aFailedUpdateRollsTheReplacementBack() throws InterruptedException {
+ String suffix = Long.toString(System.nanoTime(), 36);
+ String stack = "cfn-dashboard-rb-" + suffix;
+ String name = "ops-rb-" + suffix;
+ String renamed = "ops-rb-v2-" + suffix;
+
+ cloudFormation(stack, "CreateStack", TEMPLATE.formatted("", ""), Map.of("Name", name));
+ describeStacks(stack, "CREATE_COMPLETE");
+
+ cloudFormation(stack, "UpdateStack", TEMPLATE.formatted("", FAILING_RESOURCE.formatted(suffix)),
+ Map.of("Name", renamed));
+ String rolledBack = describeStacks(stack, "UPDATE_ROLLBACK_COMPLETE");
+ assertEquals(name, outputValue(rolledBack, "DashboardRef"), "the resource names the prior dashboard again");
+ getDashboard(name).then().statusCode(200);
+ getDashboard(renamed).then()
+ .statusCode(404)
+ .body("ErrorResponse.Error.Code", equalTo("ResourceNotFound"));
+
+ cloudFormation(stack, "DeleteStack", null, Map.of());
+ awaitStackDeleted(stack);
+ }
+
+ /** An in-place body and tag change is put back from the snapshot the update took. */
+ @Test
+ void aFailedUpdateRestoresTheBodyAndTagsAnInPlaceUpdateChanged() throws InterruptedException {
+ String suffix = Long.toString(System.nanoTime(), 36);
+ String stack = "cfn-dashboard-ip-" + suffix;
+ String name = "ops-ip-" + suffix;
+
+ cloudFormation(stack, "CreateStack", TEMPLATE.formatted(EXTRA_TAG, ""), Map.of("Name", name));
+ describeStacks(stack, "CREATE_COMPLETE");
+ String arn = dashboardArn(name);
+
+ cloudFormation(stack, "UpdateStack", TEMPLATE.formatted("", FAILING_RESOURCE.formatted(suffix)),
+ Map.of("Name", name, "Title", "Errors", "Team", "data"));
+ String rolledBack = describeStacks(stack, "UPDATE_ROLLBACK_COMPLETE");
+ assertEquals(name, outputValue(rolledBack, "DashboardRef"));
+ getDashboard(name).then()
+ .statusCode(200)
+ .body("GetDashboardResponse.GetDashboardResult.DashboardBody", containsString("\"Requests\""))
+ .body("GetDashboardResponse.GetDashboardResult.DashboardBody", not(containsString("\"Errors\"")));
+ assertTags(arn, Map.of("team", "platform", "env", "dev"), Map.of());
+
+ cloudFormation(stack, "DeleteStack", null, Map.of());
+ awaitStackDeleted(stack);
+ }
+
+ /**
+ * The tag reconciliation runs after PutDashboard has already written the new body, so a failure
+ * there leaves the dashboard carrying the update the stack is about to disown. The provisioner
+ * puts the body and tags back before the failure leaves it, and the stack reports a clean
+ * rollback with the original failure as the resource's reason.
+ */
+ @Test
+ void anUpdateThatFailedOnItsTagsPutsTheDashboardBackAndTheStackRollsBackCleanly()
+ throws InterruptedException {
+ String suffix = Long.toString(System.nanoTime(), 36);
+ String stack = "cfn-dashboard-tagfail-" + suffix;
+ String name = "ops-tagfail-" + suffix;
+
+ cloudFormation(stack, "CreateStack", TEMPLATE.formatted(EXTRA_TAG, ""), Map.of("Name", name));
+ describeStacks(stack, "CREATE_COMPLETE");
+ String arn = dashboardArn(name);
+
+ // The update's tag call fails; the restore's own tag call is left working, which is what
+ // makes this the clean-rollback case rather than the failed-restore one below.
+ Mockito.doThrow(new IllegalStateException("simulated tagResource failure"))
+ .doCallRealMethod()
+ .when(dashboardsService)
+ .tagResource(anyString(), anyMap(), anyString());
+ try {
+ cloudFormation(stack, "UpdateStack", TEMPLATE.formatted("", ""),
+ Map.of("Name", name, "Title", "Errors", "Team", "data"));
+ String rolledBack = describeStacks(stack, "UPDATE_ROLLBACK_COMPLETE");
+ assertEquals(name, outputValue(rolledBack, "DashboardRef"));
+ getDashboard(name).then()
+ .statusCode(200)
+ .body("GetDashboardResponse.GetDashboardResult.DashboardBody", containsString("\"Requests\""))
+ .body("GetDashboardResponse.GetDashboardResult.DashboardBody", not(containsString("\"Errors\"")));
+ assertTags(arn, Map.of("team", "platform", "env", "dev"), Map.of());
+ String events = describeEvents(stack);
+ assertTrue(events.contains("simulated tagResource failure"), events);
+ assertTrue(events.contains("<ResourceStatusReason>Resource update rolled back</ResourceStatusReason>"),
+ events);
+ } finally {
+ Mockito.doCallRealMethod().when(dashboardsService).tagResource(anyString(), anyMap(), anyString());
+ }
+
+ cloudFormation(stack, "DeleteStack", null, Map.of());
+ awaitStackDeleted(stack);
+ }
+
+ /**
+ * The restore repeats the tag call the update just made, so a tag failure that persists takes
+ * the restore down with it and nobody knows what the dashboard carries. The stack says so:
+ * UPDATE_ROLLBACK_FAILED naming the dashboard, rather than a clean rollback claiming the prior
+ * dashboard is intact.
+ */
+ @Test
+ void aFailedRestoreLeavesTheStackInUpdateRollbackFailedNamingTheDashboard() throws InterruptedException {
+ String suffix = Long.toString(System.nanoTime(), 36);
+ String stack = "cfn-dashboard-restorefail-" + suffix;
+ String name = "ops-restorefail-" + suffix;
+
+ cloudFormation(stack, "CreateStack", TEMPLATE.formatted(EXTRA_TAG, ""), Map.of("Name", name));
+ describeStacks(stack, "CREATE_COMPLETE");
+
+ Mockito.doThrow(new IllegalStateException("simulated persistent tagResource failure"))
+ .when(dashboardsService)
+ .tagResource(anyString(), anyMap(), anyString());
+ try {
+ cloudFormation(stack, "UpdateStack", TEMPLATE.formatted("", ""),
+ Map.of("Name", name, "Title", "Errors", "Team", "data"));
+ String failed = describeStacks(stack, "UPDATE_ROLLBACK_FAILED");
+ assertTrue(failed.contains("The following resource(s) failed to roll back: [Dashboard]."), failed);
+ String events = describeEvents(stack);
+ assertTrue(events.contains("Could not roll back the update of dashboard " + name
+ + ": simulated persistent tagResource failure"), events);
+ assertTrue(!events.contains("<ResourceStatusReason>Resource update rolled back</ResourceStatusReason>"),
+ events);
+ } finally {
+ Mockito.doCallRealMethod().when(dashboardsService).tagResource(anyString(), anyMap(), anyString());
+ }
+
+ cloudFormation(stack, "DeleteStack", null, Map.of());
+ awaitStackDeleted(stack);
+ // A resource left UPDATE_FAILED by a failed rollback is not one DeleteStack removes, so the
+ // dashboard outlives the stack and this test removes it itself.
+ dashboardsService.deleteDashboards(List.of(name), "us-east-1");
+ }
+
+ /** Dropping an explicit name is a replacement on AWS: the dashboard comes back under a generated name. */
+ @Test
+ void droppingTheExplicitNameReplacesTheDashboard() throws InterruptedException {
+ String suffix = Long.toString(System.nanoTime(), 36);
+ String stack = "cfn-dashboard-drop-" + suffix;
+ String name = "ops-drop-" + suffix;
+
+ cloudFormation(stack, "CreateStack", TEMPLATE.formatted("", ""), Map.of("Name", name));
+ describeStacks(stack, "CREATE_COMPLETE");
+
+ cloudFormation(stack, "UpdateStack", UNNAMED_TEMPLATE, Map.of());
+ String generated = outputValue(describeStacks(stack, "UPDATE_COMPLETE"), "DashboardRef");
+ assertTrue(generated.startsWith(stack + "-Dashboard-"), generated);
+ getDashboard(generated).then().statusCode(200);
+ getDashboard(name).then()
+ .statusCode(404)
+ .body("ErrorResponse.Error.Code", equalTo("ResourceNotFound"));
+
+ cloudFormation(stack, "DeleteStack", null, Map.of());
+ awaitStackDeleted(stack);
+ }
+
+ private static Response getDashboard(String name) {
+ return given()
+ .contentType("application/x-www-form-urlencoded")
+ .header("Authorization", CW_AUTH)
+ .formParam("Action", "GetDashboard")
+ .formParam("DashboardName", name)
+ .when().post("/");
+ }
+
+ private static String dashboardArn(String name) {
+ return getDashboard(name).then().statusCode(200)
+ .extract().path("GetDashboardResponse.GetDashboardResult.DashboardArn");
+ }
+
+ private static void assertTags(String arn, Map<String, String> present, Map<String, String> absent) {
+ String tags = given()
+ .contentType("application/x-www-form-urlencoded")
+ .header("Authorization", CW_AUTH)
+ .formParam("Action", "ListTagsForResource")
+ .formParam("ResourceARN", arn)
+ .when().post("/").then().statusCode(200).extract().asString();
+ present.forEach((key, value) -> assertTrue(
+ tags.contains("<Key>" + key + "</Key>") && tags.contains("<Value>" + value + "</Value>"),
+ "expected tag " + key + "=" + value + " in " + tags));
+ absent.forEach((key, value) -> assertTrue(!tags.contains("<Key>" + key + "</Key>"),
+ "tag " + key + " should be gone: " + tags));
+ }
+
+ private static void cloudFormation(String stack, String action, String templateBody,
+ Map<String, String> parameters) {
+ RequestSpecification request = given()
+ .contentType("application/x-www-form-urlencoded")
+ .header("Authorization", CFN_AUTH)
+ .formParam("Action", action)
+ .formParam("StackName", stack);
+ if (templateBody != null) {
+ request.formParam("TemplateBody", templateBody);
+ }
+ int index = 1;
+ for (Map.Entry<String, String> parameter : parameters.entrySet()) {
+ request.formParam("Parameters.member." + index + ".ParameterKey", parameter.getKey());
+ request.formParam("Parameters.member." + index + ".ParameterValue", parameter.getValue());
+ index++;
+ }
+ request.when().post("/").then().statusCode(200);
+ }
+
+ private static String describeStacks(String stack, String expectedStatus) {
+ return given()
+ .contentType("application/x-www-form-urlencoded")
+ .header("Authorization", CFN_AUTH)
+ .formParam("Action", "DescribeStacks")
+ .formParam("StackName", stack)
+ .when().post("/").then().statusCode(200)
+ .body(containsString("<StackStatus>" + expectedStatus + "</StackStatus>"))
+ .extract().asString();
+ }
+
+ private static String describeEvents(String stack) {
+ return given()
+ .contentType("application/x-www-form-urlencoded")
+ .header("Authorization", CFN_AUTH)
+ .formParam("Action", "DescribeStackEvents")
+ .formParam("StackName", stack)
+ .when().post("/").then().statusCode(200).extract().asString();
+ }
+
+ private static void assertEvent(String eventsXml, String status, String physicalId) {
+ boolean found = XmlParser.extractGroups(eventsXml, "member").stream()
+ .anyMatch(event -> status.equals(event.get("ResourceStatus"))
+ && physicalId.equals(event.get("PhysicalResourceId")));
+ assertTrue(found, "no " + status + " event for " + physicalId + " in " + eventsXml);
+ }
+
+ private static void awaitStackDeleted(String stack) throws InterruptedException {
+ for (int i = 0; i < 100; i++) {
+ String body = given()
+ .contentType("application/x-www-form-urlencoded")
+ .header("Authorization", CFN_AUTH)
+ .formParam("Action", "DescribeStacks")
+ .formParam("StackName", stack)
+ .when().post("/").then().extract().asString();
+ if (body.contains("does not exist")) {
+ return;
+ }
+ if (body.contains("<StackStatus>DELETE_FAILED</StackStatus>")) {
+ fail("stack delete failed: " + body);
+ }
+ Thread.sleep(50);
+ }
+ fail("stack " + stack + " was not deleted within the timeout");
+ }
+
+ private static String outputValue(String xml, String key) {
+ return XmlParser.extractPairs(xml, "Outputs", "OutputKey", "OutputValue").get(key);
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CloudWatchDashboardCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CloudWatchDashboardCfnProvisionerTest.java
new file mode 100644
index 0000000000..e92226989a
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CloudWatchDashboardCfnProvisionerTest.java
@@ -0,0 +1,545 @@
+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.cloudwatch.dashboards.CloudWatchDashboardsService;
+import io.github.hectorvent.floci.services.cloudwatch.dashboards.model.Dashboard;
+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 java.util.Set;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertSame;
+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.anyList;
+import static org.mockito.ArgumentMatchers.anyMap;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.doThrow;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyNoInteractions;
+import static org.mockito.Mockito.when;
+
+/**
+ * {@code AWS::CloudWatch::Dashboard}: the name is the physical id and create-only, the body is
+ * put on create and on every update, tags are driven to the template's set on update, and a
+ * changed name is a replacement whose displaced dashboard is left to the cleanup record.
+ */
+class CloudWatchDashboardCfnProvisionerTest {
+
+ private static final ObjectMapper MAPPER = new ObjectMapper();
+ private static final String REGION = "us-east-1";
+ private static final String ACCOUNT_ID = "000000000000";
+ private static final String STACK = "my-stack";
+ private static final String TYPE = "AWS::CloudWatch::Dashboard";
+ private static final String BODY = "{\"widgets\":[{\"type\":\"text\",\"properties\":{\"markdown\":\"hi\"}}]}";
+ private static final String OLD_BODY = "{\"widgets\":[{\"type\":\"text\",\"properties\":{\"markdown\":\"was here\"}}]}";
+
+ private CloudWatchDashboardsService dashboards;
+ private CloudWatchDashboardCfnProvisioner provisioner;
+ private CloudFormationTemplateEngine engine;
+
+ @BeforeEach
+ void setUp() {
+ dashboards = mock(CloudWatchDashboardsService.class);
+ provisioner = new CloudWatchDashboardCfnProvisioner(dashboards);
+ 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(engine.resolveJsonAttribute(any())).thenAnswer(i -> {
+ JsonNode node = i.getArgument(0);
+ if (node == null || node.isMissingNode() || node.isNull()) {
+ return null;
+ }
+ return node.isTextual() ? node.asText() : node.toString();
+ });
+ when(dashboards.putDashboard(anyString(), anyString(), anyMap(), eq(REGION))).thenAnswer(i ->
+ new Dashboard(i.getArgument(0), arn(i.getArgument(0)), i.getArgument(1)));
+ when(dashboards.listTagsForResource(anyString(), eq(REGION))).thenReturn(Map.of());
+ // The service never answers null: a missing dashboard throws. Tests that care about the
+ // dashboard before an update stub their own.
+ when(dashboards.getDashboard(anyString(), eq(REGION))).thenAnswer(i ->
+ new Dashboard(i.getArgument(0), arn(i.getArgument(0)), "{}"));
+ }
+
+ private static String arn(String name) {
+ return "arn:aws:cloudwatch::" + ACCOUNT_ID + ":dashboard/" + name;
+ }
+
+ private static JsonNode props(String json) {
+ try {
+ return MAPPER.readTree(json);
+ } catch (Exception e) {
+ throw new IllegalArgumentException(e);
+ }
+ }
+
+ private static StackResource resource() {
+ StackResource r = new StackResource();
+ r.setLogicalId("Dashboard");
+ r.setResourceType(TYPE);
+ r.setAttributes(new HashMap<>());
+ return r;
+ }
+
+ private StackResource provision(String json, String priorPhysicalId) {
+ return provision(json, priorPhysicalId, Map.of());
+ }
+
+ /** Provisions as a create (no prior id) or an update (prior id and the attributes it left). */
+ private StackResource provision(String json, String priorPhysicalId, Map<String, String> priorAttributes) {
+ StackResource r = resource();
+ r.setPhysicalId(priorPhysicalId);
+ r.getAttributes().putAll(priorAttributes);
+ provisioner.provision(r, props(json),
+ new ProvisionContext(engine, REGION, ACCOUNT_ID, STACK, priorPhysicalId));
+ return r;
+ }
+
+ @Test
+ void servesOnlyTheDashboardType() {
+ assertEquals(Set.of(TYPE), provisioner.resourceTypes());
+ }
+
+ @Test
+ void createPutsTheDashboardUnderTheExplicitName() {
+ StackResource r = provision("""
+ {"DashboardName": "ops", "DashboardBody": %s}
+ """.formatted(MAPPER.valueToTree(BODY)), null);
+
+ verify(dashboards).putDashboard("ops", BODY, Map.of(), REGION);
+ assertEquals("ops", r.getPhysicalId(), "Ref is the dashboard name");
+ assertEquals(Map.of("FlociDashboardNameMode", "explicit"), r.getAttributes(),
+ "the schema declares no Fn::GetAtt attributes; only the name mode is recorded");
+ assertFalse(provisioner.hasReplacementUpdate(r));
+ }
+
+ /** CloudFormation takes the body as a string; a template can still write it as JSON. */
+ @Test
+ void aBodyGivenAsAnObjectIsSerialised() {
+ StackResource r = provision("""
+ {"DashboardName": "ops", "DashboardBody": {"widgets": []}}
+ """, null);
+
+ verify(dashboards).putDashboard("ops", "{\"widgets\":[]}", Map.of(), REGION);
+ assertEquals("ops", r.getPhysicalId());
+ }
+
+ @Test
+ void anUnnamedDashboardGetsAGeneratedNameThatLaterUpdatesKeep() {
+ StackResource created = provision("""
+ {"DashboardBody": "{}"}
+ """, null);
+ String generated = created.getPhysicalId();
+ assertTrue(generated.startsWith("my-stack-Dashboard-"), generated);
+
+ StackResource updated = provision("""
+ {"DashboardBody": "{\\"widgets\\":[]}"}
+ """, generated, created.getAttributes());
+
+ assertEquals(generated, updated.getPhysicalId(), "an unnamed dashboard keeps its name across updates");
+ verify(dashboards).putDashboard(generated, "{\"widgets\":[]}", Map.of(), REGION);
+ assertFalse(provisioner.hasReplacementUpdate(updated));
+ }
+
+ @Test
+ void dashboardBodyIsRequired() {
+ AwsException e = assertThrows(AwsException.class, () -> provision("""
+ {"DashboardName": "ops"}
+ """, null));
+
+ assertEquals("ValidationError", e.getErrorCode());
+ assertTrue(e.getMessage().contains("DashboardBody"), e.getMessage());
+ verifyNoInteractions(dashboards);
+ }
+
+ @Test
+ void aNameLongerThanTheSchemaAllowsIsRejected() {
+ AwsException e = assertThrows(AwsException.class, () -> provision("""
+ {"DashboardName": "%s", "DashboardBody": "{}"}
+ """.formatted("n".repeat(256)), null));
+
+ assertEquals("ValidationError", e.getErrorCode());
+ assertTrue(e.getMessage().contains("DashboardName"), e.getMessage());
+ verifyNoInteractions(dashboards);
+ }
+
+ @Test
+ void tagsAreAppliedOnCreate() {
+ ArgumentCaptor<Map<String, String>> tags = ArgumentCaptor.captor();
+
+ provision("""
+ {"DashboardName": "ops", "DashboardBody": "{}",
+ "Tags": [{"Key": "team", "Value": "platform"}, {"Key": "env", "Value": "dev"}]}
+ """, null);
+
+ verify(dashboards).putDashboard(eq("ops"), eq("{}"), tags.capture(), eq(REGION));
+ assertEquals(Map.of("team", "platform", "env", "dev"), tags.getValue());
+ verify(dashboards, never()).tagResource(anyString(), anyMap(), anyString());
+ verify(dashboards, never()).untagResource(anyString(), anyList(), anyString());
+ }
+
+ /** PutDashboard keeps a dashboard's tags when it replaces it, so the update reconciles them itself. */
+ @Test
+ void anUpdateDrivesTheTagsToTheTemplate() {
+ when(dashboards.listTagsForResource(arn("ops"), REGION))
+ .thenReturn(Map.of("team", "platform", "stale", "gone"));
+
+ StackResource r = provision("""
+ {"DashboardName": "ops", "DashboardBody": "{}",
+ "Tags": [{"Key": "team", "Value": "data"}, {"Key": "env", "Value": "dev"}]}
+ """, "ops");
+
+ verify(dashboards).putDashboard(eq("ops"), eq("{}"), anyMap(), eq(REGION));
+ verify(dashboards).untagResource(arn("ops"), List.of("stale"), REGION);
+ verify(dashboards).tagResource(arn("ops"), Map.of("team", "data", "env", "dev"), REGION);
+ assertEquals("ops", r.getPhysicalId());
+ assertFalse(provisioner.hasReplacementUpdate(r));
+ }
+
+ @Test
+ void anUpdateWithNoTagsRemovesTheStoredOnes() {
+ when(dashboards.listTagsForResource(arn("ops"), REGION)).thenReturn(Map.of("team", "platform"));
+
+ provision("""
+ {"DashboardName": "ops", "DashboardBody": "{}"}
+ """, "ops");
+
+ verify(dashboards).untagResource(arn("ops"), List.of("team"), REGION);
+ verify(dashboards, never()).tagResource(anyString(), anyMap(), anyString());
+ }
+
+ @Test
+ void anUpdateWithUnchangedTagsRemovesNothing() {
+ when(dashboards.listTagsForResource(arn("ops"), REGION)).thenReturn(Map.of("team", "platform"));
+
+ provision("""
+ {"DashboardName": "ops", "DashboardBody": "{}",
+ "Tags": [{"Key": "team", "Value": "platform"}]}
+ """, "ops");
+
+ verify(dashboards, never()).untagResource(anyString(), anyList(), anyString());
+ verify(dashboards).tagResource(arn("ops"), Map.of("team", "platform"), REGION);
+ }
+
+ /** DashboardName is create-only: a new name creates a second dashboard and leaves the first to the cleanup. */
+ @Test
+ void aRenameIsAReplacementThatLeavesThePriorToTheCleanup() {
+ StackResource r = provision("""
+ {"DashboardName": "ops-v2", "DashboardBody": "{}", "Tags": [{"Key": "team", "Value": "platform"}]}
+ """, "ops");
+
+ verify(dashboards).putDashboard("ops-v2", "{}", Map.of("team", "platform"), REGION);
+ verify(dashboards, never()).deleteDashboards(anyList(), anyString());
+ verify(dashboards, never()).listTagsForResource(anyString(), anyString());
+ assertEquals("ops-v2", r.getPhysicalId());
+ assertTrue(provisioner.hasReplacementUpdate(r));
+ assertEquals("ops", provisioner.updateCleanupPhysicalId(r));
+ }
+
+ @Test
+ void completingAReplacementDeletesTheDisplacedDashboard() {
+ StackResource r = provision("""
+ {"DashboardName": "ops-v2", "DashboardBody": "{}"}
+ """, "ops");
+
+ UpdateCleanupResult result = provisioner.completeUpdate(r);
+
+ assertTrue(result.applicable());
+ assertTrue(result.complete());
+ verify(dashboards).deleteDashboards(List.of("ops"), REGION);
+ assertFalse(provisioner.hasReplacementUpdate(r));
+ }
+
+ @Test
+ void rollingBackAReplacementDeletesTheNewDashboardAndRestoresThePriorName() {
+ StackResource r = provision("""
+ {"DashboardName": "ops-v2", "DashboardBody": "{}"}
+ """, "ops");
+
+ assertTrue(provisioner.rollbackUpdate(r));
+
+ verify(dashboards).deleteDashboards(List.of("ops-v2"), REGION);
+ verify(dashboards, never()).deleteDashboards(List.of("ops"), REGION);
+ assertEquals("ops", r.getPhysicalId());
+ assertFalse(provisioner.hasReplacementUpdate(r));
+ }
+
+ /** Dropping an explicit name is a replacement on AWS: the dashboard gets a generated name. */
+ @Test
+ void droppingAnExplicitNameReplacesTheDashboardWithAGeneratedOne() {
+ StackResource r = provision("""
+ {"DashboardBody": "{}"}
+ """, "ops", Map.of("FlociDashboardNameMode", "explicit"));
+
+ assertTrue(r.getPhysicalId().startsWith("my-stack-Dashboard-"), r.getPhysicalId());
+ verify(dashboards).putDashboard(eq(r.getPhysicalId()), eq("{}"), anyMap(), eq(REGION));
+ assertTrue(provisioner.hasReplacementUpdate(r));
+ assertEquals("ops", provisioner.updateCleanupPhysicalId(r));
+ assertEquals("generated", r.getAttributes().get("FlociDashboardNameMode"));
+ }
+
+ @Test
+ void moreTagsThanTheSchemaAllowsAreRejected() {
+ StringBuilder tags = new StringBuilder();
+ for (int i = 0; i < 51; i++) {
+ tags.append(i > 0 ? "," : "").append("{\"Key\": \"k").append(i).append("\", \"Value\": \"v\"}");
+ }
+
+ AwsException e = assertThrows(AwsException.class, () -> provision("""
+ {"DashboardName": "ops", "DashboardBody": "{}", "Tags": [%s]}
+ """.formatted(tags), "ops"));
+
+ assertEquals("ValidationError", e.getErrorCode());
+ assertTrue(e.getMessage().contains("Tags"), e.getMessage());
+ verify(dashboards, never()).putDashboard(anyString(), anyString(), anyMap(), anyString());
+ verify(dashboards, never()).tagResource(anyString(), anyMap(), anyString());
+ }
+
+ /** The body and tags before an in-place update are kept, and a failed stack update puts them back. */
+ @Test
+ void anInPlaceUpdateIsRolledBackFromTheBodyAndTagsItReplaced() {
+ Dashboard before = new Dashboard("ops", arn("ops"), "{\"widgets\":[{\"type\":\"text\"}]}");
+ before.setTags(new java.util.LinkedHashMap<>(Map.of("team", "platform")));
+ when(dashboards.getDashboard("ops", REGION)).thenReturn(before);
+ when(dashboards.listTagsForResource(arn("ops"), REGION)).thenReturn(Map.of("team", "platform"));
+
+ StackResource r = provision("""
+ {"DashboardName": "ops", "DashboardBody": "{}", "Tags": [{"Key": "env", "Value": "dev"}]}
+ """, "ops", Map.of("FlociDashboardNameMode", "explicit"));
+ assertTrue(r.getAttributes().containsKey(CfnRollback.DASHBOARD_UPDATE_SNAPSHOT_ATTR));
+ when(dashboards.listTagsForResource(arn("ops"), REGION)).thenReturn(Map.of("env", "dev"));
+
+ assertTrue(provisioner.rollbackUpdate(r));
+
+ verify(dashboards).putDashboard("ops", "{\"widgets\":[{\"type\":\"text\"}]}", Map.of("team", "platform"), REGION);
+ verify(dashboards).untagResource(arn("ops"), List.of("env"), REGION);
+ verify(dashboards).tagResource(arn("ops"), Map.of("team", "platform"), REGION);
+ assertFalse(r.getAttributes().containsKey(CfnRollback.DASHBOARD_UPDATE_SNAPSHOT_ATTR),
+ "the snapshot is spent by the rollback");
+ }
+
+ /** A restore that fails keeps the snapshot, so the next rollback attempt still has it. */
+ @Test
+ void aFailedRestoreKeepsTheSnapshot() {
+ StackResource r = provision("""
+ {"DashboardName": "ops", "DashboardBody": "{}"}
+ """, "ops", Map.of("FlociDashboardNameMode", "explicit"));
+ doThrow(new AwsException("InternalServiceError", "boom", 500))
+ .when(dashboards).putDashboard(eq("ops"), eq("{}"), anyMap(), eq(REGION));
+
+ assertThrows(AwsException.class, () -> provisioner.rollbackUpdate(r));
+
+ assertTrue(r.getAttributes().containsKey(CfnRollback.DASHBOARD_UPDATE_SNAPSHOT_ATTR));
+ }
+
+ /** A dashboard deleted outside the stack is recreated by the update; a rollback removes it again. */
+ @Test
+ void rollingBackAnUpdateThatRecreatedAMissingDashboardDeletesIt() {
+ when(dashboards.getDashboard("ops", REGION))
+ .thenThrow(new AwsException("ResourceNotFound", "Dashboard does not exist: ops", 404));
+
+ StackResource r = provision("""
+ {"DashboardName": "ops", "DashboardBody": "{}"}
+ """, "ops", Map.of("FlociDashboardNameMode", "explicit"));
+
+ assertTrue(provisioner.rollbackUpdate(r));
+ verify(dashboards).deleteDashboards(List.of("ops"), REGION);
+ }
+
+ /** A successful update clears the snapshot, so a later rollback cannot restore stale state. */
+ @Test
+ void aCommittedUpdateDropsTheSnapshot() {
+ StackResource r = provision("""
+ {"DashboardName": "ops", "DashboardBody": "{}"}
+ """, "ops", Map.of("FlociDashboardNameMode", "explicit"));
+
+ provisioner.clearUpdate(r);
+
+ assertFalse(r.getAttributes().containsKey(CfnRollback.DASHBOARD_UPDATE_SNAPSHOT_ATTR));
+ assertNull(provisioner.updateCleanupPhysicalId(r));
+ assertTrue(provisioner.rollbackUpdate(r), "nothing is left to undo");
+ verify(dashboards, never()).deleteDashboards(anyList(), anyString());
+ }
+
+ /** A provision that failed before it changed anything has nothing to undo. */
+ @Test
+ void aProvisionThatFailedBeforeMutatingReportsRolledBack() {
+ doThrow(new AwsException("InvalidParameterInput", "The dashboard body is invalid", 400))
+ .when(dashboards).putDashboard(eq("ops-v2"), anyString(), anyMap(), eq(REGION));
+ StackResource r = resource();
+ r.setPhysicalId("ops");
+ assertThrows(AwsException.class, () -> provisioner.provision(r, props("""
+ {"DashboardName": "ops-v2", "DashboardBody": "not json"}
+ """), new ProvisionContext(engine, REGION, ACCOUNT_ID, STACK, "ops")));
+
+ assertTrue(provisioner.rollbackUpdate(r));
+ verify(dashboards, never()).deleteDashboards(anyList(), anyString());
+ }
+
+ /**
+ * An in-place update that put the body and then failed on the tags unwinds itself. The stack
+ * keeps the resource it had before the attempt, and that object never carried the snapshot, so
+ * a rollback driven from it would skip this provisioner and leave the new body live.
+ */
+ @Test
+ void anInPlaceUpdateThatFailedOnItsTagsPutsTheBodyBack() {
+ Dashboard before = new Dashboard("ops", arn("ops"), OLD_BODY);
+ before.setTags(new java.util.LinkedHashMap<>(Map.of("team", "platform")));
+ when(dashboards.getDashboard("ops", REGION)).thenReturn(before);
+ when(dashboards.listTagsForResource(arn("ops"), REGION)).thenReturn(Map.of("team", "platform"));
+ doThrow(new AwsException("InternalServiceError", "boom", 500))
+ .when(dashboards).untagResource(arn("ops"), List.of("team"), REGION);
+
+ assertThrows(AwsException.class, () -> provision("""
+ {"DashboardName": "ops", "DashboardBody": "{}", "Tags": [{"Key": "env", "Value": "dev"}]}
+ """, "ops", Map.of("FlociDashboardNameMode", "explicit")));
+
+ verify(dashboards).putDashboard("ops", OLD_BODY, Map.of("team", "platform"), REGION);
+ }
+
+ /** The unwind reports the resource restored, so the stack does not call the rollback again. */
+ @Test
+ void anUnwoundInPlaceUpdateIsMarkedRestored() {
+ Dashboard before = new Dashboard("ops", arn("ops"), OLD_BODY);
+ before.setTags(new java.util.LinkedHashMap<>(Map.of("team", "platform")));
+ when(dashboards.getDashboard("ops", REGION)).thenReturn(before);
+ when(dashboards.listTagsForResource(arn("ops"), REGION)).thenReturn(Map.of("team", "platform"));
+ doThrow(new AwsException("InternalServiceError", "boom", 500))
+ .when(dashboards).untagResource(arn("ops"), List.of("team"), REGION);
+
+ StackResource r = resource();
+ r.setPhysicalId("ops");
+ r.getAttributes().put("FlociDashboardNameMode", "explicit");
+ assertThrows(AwsException.class, () -> provisioner.provision(r, props("""
+ {"DashboardName": "ops", "DashboardBody": "{}", "Tags": [{"Key": "env", "Value": "dev"}]}
+ """), new ProvisionContext(engine, REGION, ACCOUNT_ID, STACK, "ops")));
+
+ assertEquals("true", r.getAttributes().get(CfnRollback.UPDATE_ROLLBACK_RESTORED_ATTR));
+ assertFalse(r.getAttributes().containsKey(CfnRollback.DASHBOARD_UPDATE_SNAPSHOT_ATTR),
+ "the snapshot is spent by the unwind");
+ assertFalse(r.getAttributes().containsKey(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR));
+ }
+
+ /**
+ * An unwind that cannot put the body back keeps the snapshot and records the failure, so the
+ * stack ends in UPDATE_ROLLBACK_FAILED instead of claiming the prior dashboard is live.
+ */
+ @Test
+ void anUnwindThatCannotRestoreIsReportedAsARollbackFailure() {
+ Dashboard before = new Dashboard("ops", arn("ops"), OLD_BODY);
+ before.setTags(new java.util.LinkedHashMap<>(Map.of("team", "platform")));
+ when(dashboards.getDashboard("ops", REGION)).thenReturn(before);
+ when(dashboards.listTagsForResource(arn("ops"), REGION)).thenReturn(Map.of("team", "platform"));
+ doThrow(new AwsException("InternalServiceError", "boom", 500))
+ .when(dashboards).untagResource(arn("ops"), List.of("team"), REGION);
+ doThrow(new AwsException("InternalServiceError", "still down", 500))
+ .when(dashboards).putDashboard(eq("ops"), eq(OLD_BODY), anyMap(), eq(REGION));
+
+ StackResource r = resource();
+ r.setPhysicalId("ops");
+ r.getAttributes().put("FlociDashboardNameMode", "explicit");
+ AwsException thrown = assertThrows(AwsException.class, () -> provisioner.provision(r, props("""
+ {"DashboardName": "ops", "DashboardBody": "{}", "Tags": [{"Key": "env", "Value": "dev"}]}
+ """), new ProvisionContext(engine, REGION, ACCOUNT_ID, STACK, "ops")));
+
+ assertEquals("boom", thrown.getMessage(), "the original failure is what the stack reports");
+ assertTrue(r.getAttributes().containsKey(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR));
+ assertTrue(r.getAttributes().containsKey(CfnRollback.DASHBOARD_UPDATE_SNAPSHOT_ATTR),
+ "the snapshot is kept for the next attempt");
+ assertFalse(r.getAttributes().containsKey(CfnRollback.UPDATE_ROLLBACK_RESTORED_ATTR));
+ }
+
+ /**
+ * The unwind repeats the tag call the update just made, so a service that keeps failing hands
+ * back the same exception instance. A throwable cannot suppress itself; the failure is still
+ * recorded and the original one still reported.
+ */
+ @Test
+ void anUnwindThatFailsWithTheUpdatesOwnExceptionIsStillRecorded() {
+ Dashboard before = new Dashboard("ops", arn("ops"), OLD_BODY);
+ before.setTags(new java.util.LinkedHashMap<>(Map.of("team", "platform")));
+ when(dashboards.getDashboard("ops", REGION)).thenReturn(before);
+ when(dashboards.listTagsForResource(arn("ops"), REGION)).thenReturn(Map.of("team", "platform"));
+ when(dashboards.putDashboard(eq("ops"), anyString(), anyMap(), eq(REGION))).thenReturn(before);
+ AwsException persistent = new AwsException("InternalServiceError", "tags down", 500);
+ doThrow(persistent).when(dashboards).tagResource(eq(arn("ops")), anyMap(), eq(REGION));
+
+ StackResource r = resource();
+ r.setPhysicalId("ops");
+ r.getAttributes().put("FlociDashboardNameMode", "explicit");
+ AwsException thrown = assertThrows(AwsException.class, () -> provisioner.provision(r, props("""
+ {"DashboardName": "ops", "DashboardBody": "{}", "Tags": [{"Key": "team", "Value": "data"}]}
+ """), new ProvisionContext(engine, REGION, ACCOUNT_ID, STACK, "ops")));
+
+ assertSame(persistent, thrown);
+ assertEquals(0, thrown.getSuppressed().length);
+ assertEquals("Could not roll back the update of dashboard ops: tags down",
+ r.getAttributes().get(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR));
+ assertTrue(r.getAttributes().containsKey(CfnRollback.DASHBOARD_UPDATE_SNAPSHOT_ATTR));
+ assertFalse(r.getAttributes().containsKey(CfnRollback.UPDATE_ROLLBACK_RESTORED_ATTR));
+ }
+
+ @Test
+ void aRejectedBodyLeavesThePriorNameInPlace() {
+ doThrow(new AwsException("InvalidParameterInput", "The dashboard body is invalid", 400))
+ .when(dashboards).putDashboard(eq("ops-v2"), anyString(), anyMap(), eq(REGION));
+ StackResource r = resource();
+ r.setPhysicalId("ops");
+
+ assertThrows(AwsException.class, () -> provisioner.provision(r, props("""
+ {"DashboardName": "ops-v2", "DashboardBody": "not json"}
+ """), new ProvisionContext(engine, REGION, ACCOUNT_ID, STACK, "ops")));
+
+ assertEquals("ops", r.getPhysicalId());
+ assertFalse(provisioner.hasReplacementUpdate(r));
+ }
+
+ @Test
+ void deleteRemovesTheDashboard() {
+ provisioner.delete(TYPE, "ops", REGION);
+
+ verify(dashboards).deleteDashboards(List.of("ops"), REGION);
+ }
+
+ @Test
+ void deleteToleratesADashboardThatIsAlreadyGone() {
+ doThrow(new AwsException("ResourceNotFound", "Dashboard does not exist: ops", 404))
+ .when(dashboards).deleteDashboards(List.of("ops"), REGION);
+
+ provisioner.delete(TYPE, "ops", REGION);
+ }
+
+ @Test
+ void deletePropagatesAnyOtherFailure() {
+ doThrow(new AwsException("InternalServiceError", "boom", 500))
+ .when(dashboards).deleteDashboards(List.of("ops"), REGION);
+
+ assertThrows(AwsException.class, () -> provisioner.delete(TYPE, "ops", REGION));
+ }
+
+ @Test
+ void deleteIgnoresAMissingId() {
+ provisioner.delete(TYPE, null, REGION);
+ provisioner.delete(TYPE, " ", REGION);
+
+ verifyNoInteractions(dashboards);
+ }
+}
diff --git a/src/test/resources/cloudformation/supported-resource-types.tsv b/src/test/resources/cloudformation/supported-resource-types.tsv
index 2488ba5907..466accd0c3 100644
--- a/src/test/resources/cloudformation/supported-resource-types.tsv
+++ b/src/test/resources/cloudformation/supported-resource-types.tsv
@@ -34,6 +34,7 @@ AWS::CloudFront::OriginRequestPolicy CloudFrontCfnProvisioner
AWS::CloudFront::ResponseHeadersPolicy CloudFrontCfnProvisioner
AWS::CloudTrail::Trail CloudTrailCfnProvisioner
AWS::CloudWatch::Alarm CloudWatchCfnProvisioner
+AWS::CloudWatch::Dashboard CloudWatchDashboardCfnProvisioner
AWS::CodeBuild::Project CodeBuildCfnProvisioner
AWS::CodePipeline::CustomActionType CodePipelineCfnProvisioner
AWS::CodePipeline::Pipeline CodePipelineCfnProvisioner