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

* feat(cloudwatch): provision AWS::CloudWatch::Dashboard

The dashboard name is the physical id, generated when the template gives none
and kept across updates. An update with the same name puts the body again and
drives the tags to the template's set, since PutDashboard leaves an existing
dashboard's tags alone. A changed name creates the new dashboard and leaves
the displaced one to the ReplacementCleanup record, which deletes it once the
update commits or restores it on rollback. The body may be written as a JSON
object in the template and is stored as the string the API takes.

The CloudWatch docs now list the dashboard and tag actions the handlers
already serve.

* fix(cloudwatch): roll back in-place dashboard updates and replace a dashboard whose explicit name is dropped

An in-place update keeps the body and tags it replaces on the resource, or
the fact that the dashboard did not exist, and a failed stack update puts
them back in full. The name mode is recorded as the Logs provisioner does, so
a template that drops an explicit DashboardName gets a generated name and a
replacement, as on AWS, while an unnamed dashboard keeps its generated name.
The Tags list is checked against the schema's cap of 50 on every provision,
since the tag operations an update reconciles through do not enforce it. The
integration test reads stack events with XmlParser.

* fix(cloudwatch): keep the dashboard rollback snapshot until the restore succeeds

A restore that throws left no snapshot behind, so the next rollback attempt
reported success without restoring anything. The snapshot is now spent only
after the body and tags are back.

* fix(cloudwatch): unwind a dashboard update that failed after it changed the body

An in-place update puts the body and then reconciles the tags. When the tag
calls failed, the exception left the dashboard carrying the new body while
CloudFormationService put the resource the stack held before the attempt back
in its place. That object never carried the snapshot taken by the attempt, so
the walker marked it restored and skipped rollbackUpdate: the stack reported a
completed rollback over a dashboard that still had the update's body, or a half
reconciled set of tags.

The mutating calls now unwind themselves through rollbackUpdate, the way
IotDomainConfigurationCfnProvisioner unwinds a replacement, and report the
resource restored. An unwind that cannot put the body back keeps the snapshot
and records the failure on the resource, so the stack ends in
UPDATE_ROLLBACK_FAILED rather than claiming the prior dashboard is intact, and
the original failure is still what the stack reports.

Tests: anInPlaceUpdateThatFailedOnItsTagsPutsTheBodyBack,
anUnwoundInPlaceUpdateIsMarkedRestored,
anUnwindThatCannotRestoreIsReportedAsARollbackFailure.

* fix(cloudwatch): record a dashboard unwind failure before joining it to the update failure

The unwind repeats the tag call the update just made, so a service that
keeps failing hands the unwind the very exception that interrupted the
update. Throwable.addSuppressed rejects a throwable suppressed under
itself, and that IllegalArgumentException escaped the unwind before the
rollback failure was recorded: the dispatcher reported "Self-suppression
not permitted" as the resource failure, no failure attribute reached the
stored resource, and the stack ended UPDATE_ROLLBACK_COMPLETE over a
dashboard whose tags were never put back.

The failure attribute is now written first and the two exceptions are
joined only when they differ, as PipesCfnProvisioner does. Two stack-level
tests drive the whole path through CloudFormationService with a spied
CloudWatchDashboardsService, the way CloudFormationPipesCleanupIntegrationTest
does: a one-off tag failure ends in UPDATE_ROLLBACK_COMPLETE with the prior
body and tags live, a persistent one in UPDATE_ROLLBACK_FAILED naming the
dashboard and carrying the unwind's reason.

Tests: anUnwindThatFailsWithTheUpdatesOwnExceptionIsStillRecorded,
anUpdateThatFailedOnItsTagsPutsTheDashboardBackAndTheStackRollsBackCleanly,
aFailedRestoreLeavesTheStackInUpdateRollbackFailedNamingTheDashboard.
This commit is contained in:
Mario Toffia authored and GitHub committed 2026-09-09 22:37:45 -05:00
1 parent 6eca8540a8
commit 460aa0718e
9 files changed
+1464 -1

No files matched your search

@@ -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;
@@ -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);
}
}
@@ -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);
}
}