feat(cloudformation): provision Cloud Map namespaces and services (#4599)

* feat(cloudformation): provision Cloud Map namespaces and services

AWS::ServiceDiscovery::PrivateDnsNamespace, PublicDnsNamespace,
HttpNamespace and Service were stubbed, so a stack reported them created
while nothing existed in Cloud Map and Fn::GetAtt resolved to literals.

CloudMapCfnProvisioner creates them through CloudMapService. Ref returns
the id; Fn::GetAtt exposes Id and Arn, HostedZoneId on a DNS namespace and
Name on a service. An unnamed service is named <LogicalId>-<12 chars>, as
measured on AWS. Description, DnsConfig, HealthCheckConfig and Tags update
in place; a createOnly change replaces the resource through
ReplacementCleanup, and a rolled-back replacement restores the createOnly
record. A Ref to a Number parameter is coerced back to a JSON number for
DnsRecords TTL and FailureThreshold.

Closes #4596
* fix(cloudformation): roll back in-place Cloud Map updates

An in-place namespace or service update followed by a later resource
failing left the Cloud Map changes live and the stack in
UPDATE_ROLLBACK_FAILED, since rollbackUpdate only undid replacements.
The provisioner now keeps the description, DnsConfig, HealthCheckConfig
and tags an in-place update overwrites and puts them back on rollback;
a committed update drops the snapshot.
* fix(cloudmap): reject DNS record type changes on service update

UpdateService only changes the TTLs of a service's existing DNS records on AWS. An in-place CloudFormation update that changes the record types, or gives a DnsConfig to a service without one, now fails with InvalidInput instead of being applied, so it rolls back like on AWS and a rollback never has to remove a DnsConfig.
* fix(cloudmap): accept only TTL changes in a service DnsConfig update

UpdateService carries only DnsRecords on AWS and CloudFormation does not support a RoutingPolicy update. Comparing the record types as a set let a RoutingPolicy change or an added record of the same type through; the requested and stored DnsConfig now have to match apart from the TTLs.
* fix(cloudmap): ignore DNS record order in a service DnsConfig update

A TTL-only update that listed the same records in another order was rejected. The comparison now uses the sorted record types, so counts, types and RoutingPolicy still have to match.
* test(cloudformation): restore a real HealthCheckConfig in the Cloud Map rollback test

The in-place rollback test went from a null health check config to null, so dropping it from the snapshot would have passed.
This commit is contained in:
Mario Toffia authored and GitHub committed 2026-09-30 21:45:18 -05:00
1 parent 31038ee2a4
commit a338a430cc
13 files changed
+1173 -1

No files matched your search

@@ -14,6 +14,7 @@ import io.github.hectorvent.floci.services.batch.BatchService;
import io.github.hectorvent.floci.services.cloudformation.provisioners.CfnDynamicReferences;
import io.github.hectorvent.floci.services.cloudformation.provisioners.CfnResourceDispatcher;
import io.github.hectorvent.floci.services.cloudformation.provisioners.CloudFrontCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.CloudMapCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.ConfigCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.DynamoDbCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.Ec2FlowLogCfnProvisioner;
@@ -96,6 +97,7 @@ import io.github.hectorvent.floci.services.cloudformation.provisioners.SsmCfnPro
import io.github.hectorvent.floci.services.cloudformation.provisioners.CfnResourceProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.CloudFormationResourceRegistry;
import io.github.hectorvent.floci.services.cloudfront.CloudFrontService;
import io.github.hectorvent.floci.services.cloudmap.CloudMapService;
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.CloudWatchLogsMetricFilterService;
@@ -211,6 +213,7 @@ final class CfnProvisionerFixture {
private WafV2Service wafV2Service;
private BackupService backupService;
private RedshiftService redshiftService;
private CloudMapService cloudMapService;
private CloudFormationResourceRegistry resourceRegistry;
private boolean registryChosenByTest;
private CfnDynamicReferences dynamicReferences;
@@ -420,6 +423,9 @@ final class CfnProvisionerFixture {
if (redshiftService != null) {
discovered.add(new RedshiftClusterCfnProvisioner(redshiftService));
}
if (cloudMapService != null) {
discovered.add(new CloudMapCfnProvisioner(cloudMapService));
}
return discovered;
}
@@ -672,6 +678,11 @@ final class CfnProvisionerFixture {
return redshiftService(s);
}
public Builder cloudMap(CloudMapService v) {
this.cloudMapService = v;
return this;
}
public Builder registry(CloudFormationResourceRegistry v) {
this.resourceRegistry = v;
this.registryChosenByTest = true;
@@ -0,0 +1,270 @@
package io.github.hectorvent.floci.services.cloudformation;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.core.common.XmlParser;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.Response;
import io.restassured.specification.RequestSpecification;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import static io.restassured.RestAssured.given;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.endsWith;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.matchesPattern;
import static org.hamcrest.Matchers.startsWith;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
/**
* Provisions an {@code AWS::ServiceDiscovery::PrivateDnsNamespace} with a named and an unnamed
* {@code AWS::ServiceDiscovery::Service} through a stack, checks Ref and Fn::GetAtt against Cloud
* Map, that a Number parameter TTL is stored as a number, that Description and TTL update in place,
* that a later resource failing the update puts those in-place changes back, that renaming the
* service replaces it, and that deleting the stack removes everything.
*/
@QuarkusTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class CloudMapCfnIntegrationTest {
private static final String CFN_AUTH =
"AWS4-HMAC-SHA256 Credential=test/20260905/us-east-1/cloudformation/aws4_request";
private static final String CLOUD_MAP_AUTH =
"AWS4-HMAC-SHA256 Credential=test/20260905/us-east-1/servicediscovery/aws4_request";
private static final String CLOUD_MAP_TARGET = "Route53AutoNaming_v20170314.";
private static final ObjectMapper MAPPER = new ObjectMapper();
private static final String STACK = "cloudmap-cfn-it";
private static final String NAMESPACE_NAME =
"cfn-" + UUID.randomUUID().toString().replace("-", "").substring(0, 8) + ".internal";
private static final String TEMPLATE = """
{
"Parameters": {
"NsDescription": {"Type": "String", "Default": "d1"},
"Ttl": {"Type": "Number", "Default": 60},
"Fail": {"Type": "String", "Default": "false"}
},
"Conditions": {
"Failing": {"Fn::Equals": [{"Ref": "Fail"}, "true"]}
},
"Resources": {
"Ns": {
"Type": "AWS::ServiceDiscovery::PrivateDnsNamespace",
"Properties": {
"Name": "%s",
"Vpc": "vpc-0123456789abcdef0",
"Description": {"Ref": "NsDescription"},
"Tags": [{"Key": "k1", "Value": "v1"}]
}
},
"Svc": {
"Type": "AWS::ServiceDiscovery::Service",
"Properties": {
"Name": "%s",
"NamespaceId": {"Fn::GetAtt": ["Ns", "Id"]},
"Description": "main service",
"DnsConfig": {
"NamespaceId": {"Fn::GetAtt": ["Ns", "Id"]},
"RoutingPolicy": "MULTIVALUE",
"DnsRecords": [{"Type": "A", "TTL": {"Ref": "Ttl"}}]
},
"HealthCheckCustomConfig": {"FailureThreshold": 1}
}
},
"SvcNoName": {
"Type": "AWS::ServiceDiscovery::Service",
"Properties": {
"DnsConfig": {
"NamespaceId": {"Fn::GetAtt": ["Ns", "Id"]},
"DnsRecords": [{"Type": "A", "TTL": 30}]
}
}
},
"BadSecret": {
"Type": "AWS::SecretsManager::Secret",
"Condition": "Failing",
"DependsOn": "Svc",
"Properties": {"SecretString": "explicit", "GenerateSecretString": {"PasswordLength": 32}}
}
},
"Outputs": {
"NsRef": {"Value": {"Ref": "Ns"}},
"NsId": {"Value": {"Fn::GetAtt": ["Ns", "Id"]}},
"NsArn": {"Value": {"Fn::GetAtt": ["Ns", "Arn"]}},
"NsHz": {"Value": {"Fn::GetAtt": ["Ns", "HostedZoneId"]}},
"SvcRef": {"Value": {"Ref": "Svc"}},
"SvcId": {"Value": {"Fn::GetAtt": ["Svc", "Id"]}},
"SvcArn": {"Value": {"Fn::GetAtt": ["Svc", "Arn"]}},
"SvcName": {"Value": {"Fn::GetAtt": ["Svc", "Name"]}},
"NoNameRef": {"Value": {"Ref": "SvcNoName"}},
"NoNameName": {"Value": {"Fn::GetAtt": ["SvcNoName", "Name"]}}
}
}
""";
private static String namespaceId;
private static String serviceId;
private static String replacedServiceId;
private static String noNameServiceId;
@BeforeAll
static void configure() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@Test
@Order(1)
void createPublishesIdsAndStoresTheTtlAsANumber() throws Exception {
cloudFormation("CreateStack", "main", Map.of());
assertEquals("CREATE_COMPLETE", CfnStackWaits.awaitTerminal(STACK).status());
String outputs = describeStacks();
namespaceId = outputValue(outputs, "NsRef");
serviceId = outputValue(outputs, "SvcRef");
noNameServiceId = outputValue(outputs, "NoNameRef");
assertThat(namespaceId, startsWith("ns-"));
assertThat(serviceId, startsWith("srv-"));
assertEquals(namespaceId, outputValue(outputs, "NsId"));
assertEquals(serviceId, outputValue(outputs, "SvcId"));
assertThat(outputValue(outputs, "NsArn"), endsWith(":namespace/" + namespaceId));
assertThat(outputValue(outputs, "SvcArn"), endsWith(":service/" + serviceId));
String hostedZoneId = MAPPER.readTree(cloudMap("GetNamespace", "{\"Id\":\"" + namespaceId + "\"}")
.then().statusCode(200)
.extract().asString())
.path("Namespace").path("Properties").path("DnsProperties").path("HostedZoneId").asText(null);
assertThat(hostedZoneId, matchesPattern("Z[A-Z0-9]{13}"));
assertEquals(hostedZoneId, outputValue(outputs, "NsHz"));
assertEquals("main", outputValue(outputs, "SvcName"));
assertThat(outputValue(outputs, "NoNameName"), matchesPattern("SvcNoName-[0-9a-f]{12}"));
List<String> names = listServices(namespaceId).jsonPath().getList("Services.Name");
assertThat(names, containsInAnyOrder("main", outputValue(outputs, "NoNameName")));
cloudMap("GetService", "{\"Id\":\"" + serviceId + "\"}")
.then().statusCode(200)
.body("Service.DnsConfig.DnsRecords[0].TTL", equalTo(60))
.body("Service.HealthCheckCustomConfig.FailureThreshold", equalTo(1));
}
@Test
@Order(2)
void updatingDescriptionAndTtlKeepsTheIds() {
cloudFormation("UpdateStack", "main", Map.of("NsDescription", "d2", "Ttl", "120"));
assertEquals("UPDATE_COMPLETE", CfnStackWaits.awaitTerminal(STACK).status());
String outputs = describeStacks();
assertEquals(namespaceId, outputValue(outputs, "NsId"));
assertEquals(serviceId, outputValue(outputs, "SvcId"));
cloudMap("GetNamespace", "{\"Id\":\"" + namespaceId + "\"}")
.then().statusCode(200)
.body("Namespace.Description", equalTo("d2"));
cloudMap("GetService", "{\"Id\":\"" + serviceId + "\"}")
.then().statusCode(200)
.body("Service.DnsConfig.DnsRecords[0].TTL", equalTo(120));
}
@Test
@Order(3)
void aFailedUpdateRestoresTheInPlaceChanges() {
cloudFormation("UpdateStack", "main", Map.of("NsDescription", "d3", "Ttl", "90", "Fail", "true"));
assertEquals("UPDATE_ROLLBACK_COMPLETE", CfnStackWaits.awaitTerminal(STACK).status());
String outputs = describeStacks();
assertEquals(namespaceId, outputValue(outputs, "NsId"));
assertEquals(serviceId, outputValue(outputs, "SvcId"));
cloudMap("GetNamespace", "{\"Id\":\"" + namespaceId + "\"}")
.then().statusCode(200)
.body("Namespace.Description", equalTo("d2"));
cloudMap("GetService", "{\"Id\":\"" + serviceId + "\"}")
.then().statusCode(200)
.body("Service.DnsConfig.DnsRecords[0].TTL", equalTo(120));
}
@Test
@Order(4)
void renamingTheServiceReplacesIt() {
cloudFormation("UpdateStack", "main2", Map.of("NsDescription", "d2", "Ttl", "120"));
assertEquals("UPDATE_COMPLETE", CfnStackWaits.awaitTerminal(STACK).status());
String outputs = describeStacks();
replacedServiceId = outputValue(outputs, "SvcId");
assertNotEquals(serviceId, replacedServiceId);
assertEquals("main2", outputValue(outputs, "SvcName"));
cloudMap("GetService", "{\"Id\":\"" + serviceId + "\"}")
.then().statusCode(404)
.body("__type", equalTo("ServiceNotFound"));
List<String> names = listServices(namespaceId).jsonPath().getList("Services.Name");
assertThat(names, containsInAnyOrder("main2", outputValue(outputs, "NoNameName")));
}
@Test
@Order(5)
void deletingTheStackRemovesTheNamespaceAndServices() {
cloudFormation("DeleteStack", "main2", Map.of());
CfnStackWaits.awaitStackDeleted(STACK);
cloudMap("GetNamespace", "{\"Id\":\"" + namespaceId + "\"}")
.then().statusCode(404)
.body("__type", equalTo("NamespaceNotFound"));
for (String id : List.of(serviceId, replacedServiceId, noNameServiceId)) {
cloudMap("GetService", "{\"Id\":\"" + id + "\"}")
.then().statusCode(404)
.body("__type", equalTo("ServiceNotFound"));
}
}
private static void cloudFormation(String action, String serviceName, Map<String, String> parameters) {
RequestSpecification request = given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CFN_AUTH)
.formParam("Action", action)
.formParam("StackName", STACK);
if (!"DeleteStack".equals(action)) {
request.formParam("TemplateBody", TEMPLATE.formatted(NAMESPACE_NAME, serviceName));
}
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() {
return given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CFN_AUTH)
.formParam("Action", "DescribeStacks")
.formParam("StackName", STACK)
.when().post("/").then().statusCode(200)
.extract().asString();
}
private static String outputValue(String xml, String key) {
return XmlParser.extractPairs(xml, "Outputs", "OutputKey", "OutputValue").get(key);
}
private static Response listServices(String nsId) {
return cloudMap("ListServices", "{\"Filters\":[{\"Name\":\"NAMESPACE_ID\",\"Values\":[\""
+ nsId + "\"],\"Condition\":\"EQ\"}]}");
}
private static Response cloudMap(String action, String body) {
return given()
.contentType("application/x-amz-json-1.1")
.header("Authorization", CLOUD_MAP_AUTH)
.header("X-Amz-Target", CLOUD_MAP_TARGET + action)
.body(body)
.when().post("/");
}
}
@@ -0,0 +1,397 @@
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.cloudmap.CloudMapService;
import io.github.hectorvent.floci.services.cloudmap.model.Namespace;
import io.github.hectorvent.floci.services.cloudmap.model.Operation;
import io.github.hectorvent.floci.services.cloudmap.model.Service;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.matchesPattern;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* The Cloud Map namespace types and {@code AWS::ServiceDiscovery::Service} in isolation: the ids
* back Ref and Fn::GetAtt, a textual TTL reaches the service as a number, an unchanged createOnly
* set updates in place, a changed one replaces, a rolled back replacement puts the createOnly record
* back, a rolled back in-place update puts the prior description, DnsConfig, health check and tags
* back from its snapshot, a committed update drops that snapshot, and delete tolerates only the
* not-found codes.
*/
class CloudMapCfnProvisionerTest {
private static final String PRIVATE_DNS_NAMESPACE = "AWS::ServiceDiscovery::PrivateDnsNamespace";
private static final String PUBLIC_DNS_NAMESPACE = "AWS::ServiceDiscovery::PublicDnsNamespace";
private static final String HTTP_NAMESPACE = "AWS::ServiceDiscovery::HttpNamespace";
private static final String SERVICE = "AWS::ServiceDiscovery::Service";
private static final String SNAPSHOT_ATTR = "__FlociCloudMapUpdateSnapshot";
private static final String NS_ARN = "arn:aws:servicediscovery:us-east-1:000000000000:namespace/ns-1";
private static final String SRV_ARN = "arn:aws:servicediscovery:us-east-1:000000000000:service/srv-1";
private static final String SRV2_ARN = "arn:aws:servicediscovery:us-east-1:000000000000:service/srv-2";
private final CloudMapService cloudMap = mock(CloudMapService.class);
private final CloudMapCfnProvisioner provisioner = new CloudMapCfnProvisioner(cloudMap);
private final ObjectMapper mapper = new ObjectMapper();
@Test
void namespaceCreatePublishesIdArnAndHostedZoneId() throws Exception {
stubNamespaceCreate();
StackResource r = resource(PRIVATE_DNS_NAMESPACE, "Ns");
provisioner.provision(r, props("""
{"Name": "svc.internal", "Vpc": "vpc-1", "Description": "d1",
"Tags": [{"Key": "k1", "Value": "v1"}]}"""), ctx(null));
verify(cloudMap).createPrivateDnsNamespace("svc.internal", "vpc-1", null, "d1",
Map.of("k1", "v1"), "us-east-1");
assertEquals("ns-1", r.getPhysicalId());
assertEquals("ns-1", r.getAttributes().get("Id"));
assertEquals(NS_ARN, r.getAttributes().get("Arn"));
assertEquals("Z0123456789ABC", r.getAttributes().get("HostedZoneId"));
}
@Test
void httpNamespaceCreatePublishesIdAndArn() throws Exception {
Operation op = stubNamespace(null);
when(cloudMap.createHttpNamespace(any(), any(), any(), any(), any())).thenReturn(op);
StackResource r = resource(HTTP_NAMESPACE, "Http");
provisioner.provision(r, props("""
{"Name": "svc-http", "Description": "d1"}"""), ctx(null));
verify(cloudMap).createHttpNamespace("svc-http", null, "d1", Map.of(), "us-east-1");
assertEquals("ns-1", r.getPhysicalId());
assertEquals("ns-1", r.getAttributes().get("Id"));
assertEquals(NS_ARN, r.getAttributes().get("Arn"));
assertFalse(r.getAttributes().containsKey("HostedZoneId"));
}
@Test
void publicDnsNamespaceCreatePublishesIdArnAndHostedZoneId() throws Exception {
Operation op = stubNamespace("Z0123456789ABC");
when(cloudMap.createPublicDnsNamespace(any(), any(), any(), any(), any())).thenReturn(op);
StackResource r = resource(PUBLIC_DNS_NAMESPACE, "Pub");
provisioner.provision(r, props("""
{"Name": "example.com"}"""), ctx(null));
verify(cloudMap).createPublicDnsNamespace("example.com", null, null, Map.of(), "us-east-1");
assertEquals("ns-1", r.getPhysicalId());
assertEquals("ns-1", r.getAttributes().get("Id"));
assertEquals(NS_ARN, r.getAttributes().get("Arn"));
assertEquals("Z0123456789ABC", r.getAttributes().get("HostedZoneId"));
}
@Test
void serviceCreatePassesATextualTtlAsANumber() throws Exception {
stubServiceCreate("srv-1", SRV_ARN);
StackResource r = resource(SERVICE, "Svc");
provisioner.provision(r, props("""
{"Name": "main", "NamespaceId": "ns-1", "Description": "svc",
"DnsConfig": {"NamespaceId": "ns-1", "RoutingPolicy": "MULTIVALUE",
"DnsRecords": [{"Type": "A", "TTL": "60"}]},
"HealthCheckCustomConfig": {"FailureThreshold": "1"}}"""), ctx(null));
ArgumentCaptor<String> dnsConfig = ArgumentCaptor.forClass(String.class);
ArgumentCaptor<String> customConfig = ArgumentCaptor.forClass(String.class);
verify(cloudMap).createService(any(), any(), any(), any(), dnsConfig.capture(), any(),
customConfig.capture(), any(), any(), any());
assertEquals("{\"NamespaceId\":\"ns-1\",\"RoutingPolicy\":\"MULTIVALUE\","
+ "\"DnsRecords\":[{\"Type\":\"A\",\"TTL\":60}]}", dnsConfig.getValue());
assertEquals("{\"FailureThreshold\":1}", customConfig.getValue());
assertEquals("srv-1", r.getPhysicalId());
assertEquals("srv-1", r.getAttributes().get("Id"));
assertEquals(SRV_ARN, r.getAttributes().get("Arn"));
assertEquals("main", r.getAttributes().get("Name"));
}
@Test
void serviceWithoutNameGetsALogicalIdBasedName() throws Exception {
stubServiceCreate("srv-1", SRV_ARN);
StackResource r = resource(SERVICE, "SvcNoName");
provisioner.provision(r, props("""
{"DnsConfig": {"NamespaceId": "ns-1", "DnsRecords": [{"Type": "A", "TTL": 30}]}}"""), ctx(null));
ArgumentCaptor<String> name = ArgumentCaptor.forClass(String.class);
ArgumentCaptor<String> namespaceId = ArgumentCaptor.forClass(String.class);
verify(cloudMap).createService(name.capture(), namespaceId.capture(), any(), any(), any(), any(),
any(), any(), any(), any());
assertThat(name.getValue(), matchesPattern("SvcNoName-[0-9a-f]{12}"));
assertEquals("ns-1", namespaceId.getValue());
assertEquals(name.getValue(), r.getAttributes().get("Name"));
}
@Test
void namespaceUpdateWithUnchangedNameAndVpcUpdatesInPlace() throws Exception {
stubNamespaceCreate();
StackResource r = resource(PRIVATE_DNS_NAMESPACE, "Ns");
provisioner.provision(r, props("""
{"Name": "svc.internal", "Vpc": "vpc-1", "Description": "d1",
"Tags": [{"Key": "k1", "Value": "v1"}]}"""), ctx(null));
Map<String, String> stored = new LinkedHashMap<>();
stored.put("k1", "v1");
stored.put("stale", "x");
when(cloudMap.listTagsForResource(NS_ARN)).thenReturn(stored);
provisioner.provision(r, props("""
{"Name": "svc.internal", "Vpc": "vpc-1", "Description": "d2",
"Tags": [{"Key": "k1", "Value": "v2"}]}"""), ctx("ns-1"));
verify(cloudMap, times(1)).createPrivateDnsNamespace(any(), any(), any(), any(), any(), any());
verify(cloudMap).updateNamespace("ns-1", "d2");
verify(cloudMap).untagResource(NS_ARN, List.of("stale"));
verify(cloudMap).tagResource(NS_ARN, Map.of("k1", "v2"));
assertEquals("ns-1", r.getPhysicalId());
assertEquals("ns-1", r.getAttributes().get("Id"));
assertFalse(provisioner.hasReplacementUpdate(r));
}
@Test
void serviceUpdateWithUnchangedCreateOnlyPropertiesUpdatesInPlace() throws Exception {
stubServiceCreate("srv-1", SRV_ARN);
StackResource r = resource(SERVICE, "Svc");
provisioner.provision(r, props("""
{"Name": "main", "NamespaceId": "ns-1", "Description": "d1",
"DnsConfig": {"DnsRecords": [{"Type": "A", "TTL": 60}]}}"""), ctx(null));
provisioner.provision(r, props("""
{"Name": "main", "NamespaceId": "ns-1", "Description": "d2",
"DnsConfig": {"DnsRecords": [{"Type": "A", "TTL": "120"}]},
"HealthCheckConfig": {"Type": "HTTP", "FailureThreshold": "1"}}"""),
ctx("srv-1"));
verify(cloudMap, times(1)).createService(any(), any(), any(), any(), any(), any(), any(), any(),
any(), any());
verify(cloudMap).updateService("srv-1", "d2", "{\"DnsRecords\":[{\"Type\":\"A\",\"TTL\":120}]}",
"{\"Type\":\"HTTP\",\"FailureThreshold\":1}");
verify(cloudMap).tagResource(SRV_ARN, Map.of());
assertEquals("srv-1", r.getPhysicalId());
assertFalse(provisioner.hasReplacementUpdate(r));
}
@Test
void serviceUpdateWithAChangedNameReplacesTheService() throws Exception {
stubServiceCreate("srv-1", SRV_ARN);
StackResource r = resource(SERVICE, "Svc");
provisioner.provision(r, props("""
{"Name": "main", "NamespaceId": "ns-1"}"""), ctx(null));
stubServiceCreate("srv-2", SRV2_ARN);
provisioner.provision(r, props("""
{"Name": "main2", "NamespaceId": "ns-1"}"""), ctx("srv-1"));
verify(cloudMap, times(2)).createService(any(), any(), any(), any(), any(), any(), any(), any(),
any(), any());
verify(cloudMap, never()).updateService(anyString(), any(), any(), any());
assertEquals("srv-2", r.getPhysicalId());
assertEquals("main2", r.getAttributes().get("Name"));
assertTrue(provisioner.hasReplacementUpdate(r));
assertEquals("srv-1", provisioner.updateCleanupPhysicalId(r));
}
@Test
void rolledBackReplacementRestoresTheCreateOnlyRecordSoARetryReplacesAgain() throws Exception {
stubServiceCreate("srv-1", SRV_ARN);
StackResource r = resource(SERVICE, "Svc");
provisioner.provision(r, props("""
{"Name": "main", "NamespaceId": "ns-1"}"""), ctx(null));
String createdRecord = r.getAttributes().get("__FlociCreateOnly");
stubServiceCreate("srv-2", SRV2_ARN);
provisioner.provision(r, props("""
{"Name": "main2", "NamespaceId": "ns-1"}"""), ctx("srv-1"));
assertTrue(provisioner.rollbackUpdate(r));
verify(cloudMap).deleteService("srv-2");
assertEquals("srv-1", r.getPhysicalId());
assertEquals(createdRecord, r.getAttributes().get("__FlociCreateOnly"));
assertFalse(r.getAttributes().containsKey("__FlociCreateOnlyPrior"));
provisioner.provision(r, props("""
{"Name": "main2", "NamespaceId": "ns-1"}"""), ctx("srv-1"));
verify(cloudMap, times(2)).createService(eq("main2"), any(), any(), any(), any(), any(), any(), any(),
any(), any());
verify(cloudMap, never()).updateService(anyString(), any(), any(), any());
assertEquals("srv-2", r.getPhysicalId());
}
@Test
void serviceInPlaceUpdateRollsBackToTheSnapshot() throws Exception {
Service stored = stubServiceCreate("srv-1", SRV_ARN);
StackResource r = resource(SERVICE, "Svc");
provisioner.provision(r, props("""
{"Name": "main", "NamespaceId": "ns-1"}"""), ctx(null));
stored.setDescription("d1");
stored.setDnsConfig("{\"DnsRecords\":[{\"Type\":\"A\",\"TTL\":60}]}");
stored.setHealthCheckConfig("{\"Type\":\"HTTP\",\"ResourcePath\":\"/\",\"FailureThreshold\":1}");
stored.setTags(new HashMap<>(Map.of("k1", "v1")));
when(cloudMap.listTagsForResource(SRV_ARN)).thenReturn(Map.of("k1", "v2"));
provisioner.provision(r, props("""
{"Name": "main", "NamespaceId": "ns-1", "Description": "d2",
"DnsConfig": {"DnsRecords": [{"Type": "A", "TTL": "120"}]},
"HealthCheckConfig": {"Type": "HTTP", "ResourcePath": "/health", "FailureThreshold": 2},
"Tags": [{"Key": "k1", "Value": "v2"}]}"""), ctx("srv-1"));
assertTrue(provisioner.rollbackUpdate(r));
verify(cloudMap).updateService("srv-1", "d1", "{\"DnsRecords\":[{\"Type\":\"A\",\"TTL\":60}]}",
"{\"Type\":\"HTTP\",\"ResourcePath\":\"/\",\"FailureThreshold\":1}");
verify(cloudMap).tagResource(SRV_ARN, Map.of("k1", "v1"));
assertFalse(r.getAttributes().containsKey(SNAPSHOT_ATTR));
assertEquals("srv-1", r.getPhysicalId());
}
@Test
void namespaceInPlaceUpdateRollsBackToTheSnapshot() throws Exception {
stubNamespaceCreate();
Namespace stored = new Namespace();
stored.setId("ns-1");
stored.setArn(NS_ARN);
stored.setDescription("d1");
stored.setTags(new HashMap<>(Map.of("k1", "v1")));
when(cloudMap.getNamespace("ns-1")).thenReturn(stored);
StackResource r = resource(PRIVATE_DNS_NAMESPACE, "Ns");
provisioner.provision(r, props("""
{"Name": "svc.internal", "Vpc": "vpc-1", "Description": "d1",
"Tags": [{"Key": "k1", "Value": "v1"}]}"""), ctx(null));
provisioner.provision(r, props("""
{"Name": "svc.internal", "Vpc": "vpc-1", "Description": "d2",
"Tags": [{"Key": "k1", "Value": "v2"}]}"""), ctx("ns-1"));
assertTrue(provisioner.rollbackUpdate(r));
verify(cloudMap).updateNamespace("ns-1", "d2");
verify(cloudMap).updateNamespace("ns-1", "d1");
verify(cloudMap).tagResource(NS_ARN, Map.of("k1", "v1"));
assertFalse(r.getAttributes().containsKey(SNAPSHOT_ATTR));
assertEquals("ns-1", r.getPhysicalId());
}
@Test
void committedUpdateDropsTheSnapshot() throws Exception {
stubServiceCreate("srv-1", SRV_ARN);
StackResource r = resource(SERVICE, "Svc");
provisioner.provision(r, props("""
{"Name": "main", "NamespaceId": "ns-1"}"""), ctx(null));
provisioner.provision(r, props("""
{"Name": "main", "NamespaceId": "ns-1", "Description": "d2"}"""), ctx("srv-1"));
assertTrue(r.getAttributes().containsKey(SNAPSHOT_ATTR));
provisioner.completeUpdate(r);
assertFalse(r.getAttributes().containsKey(SNAPSHOT_ATTR));
}
@Test
void deleteNamespaceToleratesNamespaceNotFound() {
doThrow(new AwsException("NamespaceNotFound", "gone", 404))
.when(cloudMap).deleteNamespace("ns-1", "us-east-1");
assertDoesNotThrow(() -> provisioner.delete(PRIVATE_DNS_NAMESPACE, "ns-1", "us-east-1"));
verify(cloudMap).deleteNamespace("ns-1", "us-east-1");
}
@Test
void deleteServiceToleratesServiceNotFound() {
doThrow(new AwsException("ServiceNotFound", "gone", 404)).when(cloudMap).deleteService("srv-1");
assertDoesNotThrow(() -> provisioner.delete(SERVICE, "srv-1", "us-east-1"));
verify(cloudMap).deleteService("srv-1");
}
@Test
void deleteServiceWithInstancesPropagatesResourceInUse() {
doThrow(new AwsException("ResourceInUse", "has instances", 400)).when(cloudMap).deleteService("srv-1");
AwsException failure = assertThrows(AwsException.class,
() -> provisioner.delete(SERVICE, "srv-1", "us-east-1"));
assertEquals("ResourceInUse", failure.getErrorCode());
}
private void stubNamespaceCreate() {
Operation op = stubNamespace("Z0123456789ABC");
when(cloudMap.createPrivateDnsNamespace(any(), any(), any(), any(), any(), any())).thenReturn(op);
}
/** Stubs the lookup of namespace ns-1 and returns the create operation that targets it. */
private Operation stubNamespace(String hostedZoneId) {
Operation op = new Operation();
op.getTargets().put("NAMESPACE", "ns-1");
Namespace ns = new Namespace();
ns.setId("ns-1");
ns.setArn(NS_ARN);
ns.setHostedZoneId(hostedZoneId);
when(cloudMap.getNamespace("ns-1")).thenReturn(ns);
return op;
}
/** Stubs the create and the lookup of one service, returning the instance both hand out. */
private Service stubServiceCreate(String id, String arn) {
Service service = new Service();
service.setId(id);
service.setArn(arn);
when(cloudMap.createService(any(), any(), any(), any(), any(), any(), any(), any(), any(), any()))
.thenAnswer(inv -> {
service.setName(inv.getArgument(0));
return service;
});
when(cloudMap.getService(id)).thenReturn(service);
return service;
}
private ProvisionContext ctx(String priorPhysicalId) {
CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class);
when(engine.resolve(any())).thenAnswer(inv -> {
JsonNode node = inv.getArgument(0);
return node == null ? null : node.asText();
});
// The engine rebuilds plain objects, and a Ref to a Number parameter resolves to text such as
// "60", which the templates above write literally.
when(engine.resolveNode(any())).thenAnswer(inv -> {
JsonNode node = inv.getArgument(0);
return node == null ? null : node.deepCopy();
});
return new ProvisionContext(engine, "us-east-1", "000000000000", "my-stack", priorPhysicalId);
}
private JsonNode props(String json) throws Exception {
return mapper.readTree(json);
}
private static StackResource resource(String type, String logicalId) {
StackResource r = new StackResource();
r.setLogicalId(logicalId);
r.setResourceType(type);
r.setAttributes(new HashMap<>());
return r;
}
}
@@ -0,0 +1,113 @@
package io.github.hectorvent.floci.services.cloudmap;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.cloudmap.model.Service;
import io.quarkus.test.junit.QuarkusTest;
import jakarta.inject.Inject;
import org.junit.jupiter.api.Test;
import java.util.Map;
import java.util.UUID;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
@QuarkusTest
class CloudMapServiceTest {
private static final String REGION = "us-east-1";
private static final String A_RECORD_DNS_CONFIG =
"{\"RoutingPolicy\":\"MULTIVALUE\",\"DnsRecords\":[{\"Type\":\"A\",\"TTL\":60}]}";
@Inject
CloudMapService cloudMapService;
@Test
void updateServiceChangesTheTtlOfTheExistingRecords() {
Service service = createService(privateDnsNamespace(), "ttl", "original", A_RECORD_DNS_CONFIG);
cloudMapService.updateService(service.getId(), "original",
"{\"RoutingPolicy\":\"MULTIVALUE\",\"DnsRecords\":[{\"Type\":\"A\",\"TTL\":30}]}", null);
assertTrue(cloudMapService.getService(service.getId()).getDnsConfig().contains("\"TTL\":30"));
}
@Test
void updateServiceAcceptsTheSameRecordsInAnotherOrder() {
Service service = createService(privateDnsNamespace(), "order", "original",
"{\"RoutingPolicy\":\"MULTIVALUE\",\"DnsRecords\":[{\"Type\":\"A\",\"TTL\":60},"
+ "{\"Type\":\"AAAA\",\"TTL\":60}]}");
cloudMapService.updateService(service.getId(), "original",
"{\"RoutingPolicy\":\"MULTIVALUE\",\"DnsRecords\":[{\"Type\":\"AAAA\",\"TTL\":30},"
+ "{\"Type\":\"A\",\"TTL\":30}]}", null);
String stored = cloudMapService.getService(service.getId()).getDnsConfig();
assertTrue(stored.contains("\"TTL\":30"));
assertFalse(stored.contains("\"TTL\":60"));
}
@Test
void updateServiceRejectsAChangedRecordType() {
Service service = createService(privateDnsNamespace(), "type", "original", A_RECORD_DNS_CONFIG);
AwsException error = assertThrows(AwsException.class, () -> cloudMapService.updateService(
service.getId(), "changed",
"{\"RoutingPolicy\":\"MULTIVALUE\",\"DnsRecords\":[{\"Type\":\"AAAA\",\"TTL\":60}]}", null));
assertEquals("InvalidInput", error.getErrorCode());
Service stored = cloudMapService.getService(service.getId());
assertEquals(A_RECORD_DNS_CONFIG, stored.getDnsConfig());
assertEquals("original", stored.getDescription());
}
@Test
void updateServiceRejectsAChangedRoutingPolicy() {
Service service = createService(privateDnsNamespace(), "routing", "original", A_RECORD_DNS_CONFIG);
AwsException error = assertThrows(AwsException.class, () -> cloudMapService.updateService(
service.getId(), "original",
"{\"RoutingPolicy\":\"WEIGHTED\",\"DnsRecords\":[{\"Type\":\"A\",\"TTL\":60}]}", null));
assertEquals("InvalidInput", error.getErrorCode());
assertEquals(A_RECORD_DNS_CONFIG, cloudMapService.getService(service.getId()).getDnsConfig());
}
@Test
void updateServiceRejectsAnAddedRecord() {
Service service = createService(privateDnsNamespace(), "added", "original", A_RECORD_DNS_CONFIG);
AwsException error = assertThrows(AwsException.class, () -> cloudMapService.updateService(
service.getId(), "original",
"{\"RoutingPolicy\":\"MULTIVALUE\",\"DnsRecords\":[{\"Type\":\"A\",\"TTL\":60},"
+ "{\"Type\":\"A\",\"TTL\":60}]}", null));
assertEquals("InvalidInput", error.getErrorCode());
assertEquals(A_RECORD_DNS_CONFIG, cloudMapService.getService(service.getId()).getDnsConfig());
}
@Test
void updateServiceRejectsADnsConfigForAServiceWithoutOne() {
Service service = createService(privateDnsNamespace(), "nodns", null, null);
AwsException error = assertThrows(AwsException.class, () -> cloudMapService.updateService(
service.getId(), null, "{\"DnsRecords\":[{\"Type\":\"A\",\"TTL\":60}]}", null));
assertEquals("InvalidInput", error.getErrorCode());
assertNull(cloudMapService.getService(service.getId()).getDnsConfig());
}
private String privateDnsNamespace() {
String name = "svctest" + UUID.randomUUID().toString().substring(0, 8) + ".internal";
return cloudMapService.createPrivateDnsNamespace(name, "vpc-dns", null, null, Map.of(), REGION)
.getTargets().get("NAMESPACE");
}
private Service createService(String namespaceId, String name, String description, String dnsConfig) {
return cloudMapService.createService(name, namespaceId, null, description,
dnsConfig, null, null, null, Map.of(), REGION);
}
}