diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/EcsCapacityCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/EcsCapacityCfnProvisioner.java new file mode 100644 index 0000000000..6ad70391d4 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/EcsCapacityCfnProvisioner.java @@ -0,0 +1,276 @@ +package io.github.hectorvent.floci.services.cloudformation.provisioners; + +import com.fasterxml.jackson.databind.JsonNode; +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.services.cloudformation.model.StackResource; +import io.github.hectorvent.floci.services.ecs.EcsService; +import io.github.hectorvent.floci.services.ecs.model.CapacityProvider; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import org.jboss.logging.Logger; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; + +/** + * CloudFormation provisioning for ECS capacity: {@code AWS::ECS::CapacityProvider} and + * {@code AWS::ECS::ClusterCapacityProviderAssociations}. Injects only {@link EcsService}, per the + * per-service provisioner decomposition of {@code CloudFormationResourceProvisioner}. + * + *

CloudFormation spells these properties in PascalCase while {@code EcsService} stores the ECS + * JSON API's camelCase shape (that is what {@code CreateCapacityProvider} puts there). The whole + * {@code AutoScalingGroupProvider} sub-tree is therefore carried across with its keys + * decapitalized, so a capacity provider created by a stack holds the same state as one created + * through the API — including {@code ManagedScaling}, {@code ManagedTerminationProtection} and + * {@code ManagedDraining}. + */ +@ApplicationScoped +public class EcsCapacityCfnProvisioner implements CfnResourceProvisioner { + + private static final Logger LOG = Logger.getLogger(EcsCapacityCfnProvisioner.class); + + private static final String CAPACITY_PROVIDER = "AWS::ECS::CapacityProvider"; + private static final String ASSOCIATIONS = "AWS::ECS::ClusterCapacityProviderAssociations"; + + private final EcsService ecsService; + + @Inject + public EcsCapacityCfnProvisioner(EcsService ecsService) { + this.ecsService = ecsService; + } + + @Override + public Set resourceTypes() { + return Set.of(CAPACITY_PROVIDER, ASSOCIATIONS); + } + + @Override + public void provision(StackResource r, JsonNode props, ProvisionContext ctx) { + switch (r.getResourceType()) { + case CAPACITY_PROVIDER -> provisionCapacityProvider(r, props, ctx); + case ASSOCIATIONS -> provisionAssociations(r, props, ctx); + default -> throw new IllegalStateException( + "EcsCapacityCfnProvisioner cannot handle " + r.getResourceType()); + } + } + + @Override + public void delete(String resourceType, String physicalId, String region) { + if (physicalId == null || physicalId.isBlank()) { + return; + } + switch (resourceType) { + case CAPACITY_PROVIDER -> deleteCapacityProvider(physicalId); + // Deleting the association resource leaves the cluster in place with no capacity + // providers attached, which is what AWS does: the associations are the resource. + case ASSOCIATIONS -> clearAssociations(physicalId, region); + default -> { } + } + } + + private void provisionCapacityProvider(StackResource r, JsonNode props, ProvisionContext ctx) { + String existingName = r.getPhysicalId(); + String declaredName = ctx.resolveOptional(props, "Name"); + // An unnamed provider keeps the name its first execution generated. Minting a fresh one on + // every pass left the previous provider behind with nothing referencing it. + String name = declaredName != null && !declaredName.isBlank() + ? declaredName + : (existingName != null && !existingName.isBlank() + ? existingName + : ctx.generatePhysicalName(r.getLogicalId(), 255, false)); + + if (existingName != null && !existingName.isBlank() && !existingName.equals(name)) { + throw new AwsException("ValidationError", + "Updating Name requires resource replacement, which is not supported.", 400); + } + + Map asgProvider = asgProvider(props, ctx); + Map tags = tags(props, ctx); + + // UpdateStack re-executes every resource with the physical id it got at create time, and + // createCapacityProvider rejects a name that already exists, so an unchanged provider used + // to fail the whole update. An empty result also covers a provider removed out of band, + // which is recreated rather than reported as a failure. + CapacityProvider existing = existingName == null || existingName.isBlank() + ? null + : ecsService.describeCapacityProviders(List.of(existingName)).stream() + .findFirst().orElse(null); + + if (existing == null) { + ecsService.createCapacityProvider(name, asgProvider, tags, ctx.region()); + } else { + if (!Objects.equals(asgArn(existing.getAutoScalingGroupProvider()), asgArn(asgProvider))) { + throw new AwsException("ValidationError", + "Updating AutoScalingGroupArn requires resource replacement, which is not " + + "supported.", 400); + } + ecsService.updateCapacityProvider(name, asgProvider); + applyTags(existing, tags); + } + // Ref returns the capacity provider name; AWS exposes no Fn::GetAtt attributes here. + r.setPhysicalId(name); + } + + /** AutoScalingGroupArn is createOnly, so a change to it is a replacement rather than an update. */ + private static String asgArn(Map asgProvider) { + Object arn = asgProvider == null ? null : asgProvider.get("autoScalingGroupArn"); + return arn == null ? null : arn.toString(); + } + + /** + * Tags are updatable in place. updateCapacityProvider carries only the Auto Scaling settings, + * so a tag the template dropped would otherwise survive the update. + */ + private void applyTags(CapacityProvider existing, Map tags) { + Map current = existing.getTags() == null ? Map.of() : existing.getTags(); + List dropped = current.keySet().stream() + .filter(key -> !tags.containsKey(key)) + .toList(); + if (!dropped.isEmpty()) { + ecsService.untagResource(existing.getCapacityProviderArn(), dropped); + } + if (!tags.isEmpty()) { + ecsService.tagResource(existing.getCapacityProviderArn(), tags); + } + } + + private void provisionAssociations(StackResource r, JsonNode props, ProvisionContext ctx) { + String cluster = ctx.resolveOptional(props, "Cluster"); + List providers = new ArrayList<>(); + if (props != null && props.has("CapacityProviders")) { + for (JsonNode entry : props.get("CapacityProviders")) { + String id = ctx.engine().resolve(entry); + if (id != null && !id.isBlank()) { + providers.add(id); + } + } + } + List> strategy = new ArrayList<>(); + if (props != null && props.has("DefaultCapacityProviderStrategy")) { + for (JsonNode entry : props.get("DefaultCapacityProviderStrategy")) { + Map item = new HashMap<>(); + String provider = ctx.engine().resolve(entry.path("CapacityProvider")); + if (provider != null) { + item.put("capacityProvider", provider); + } + if (entry.hasNonNull("Weight")) { + item.put("weight", entry.get("Weight").asInt()); + } + if (entry.hasNonNull("Base")) { + item.put("base", entry.get("Base").asInt()); + } + strategy.add(item); + } + } + ecsService.putClusterCapacityProviders(cluster, providers, strategy, ctx.region()); + r.setPhysicalId(cluster); + } + + /** + * Carries {@code AutoScalingGroupProvider} across verbatim, resolving intrinsics and + * decapitalizing keys so the stored shape matches {@code CreateCapacityProvider}'s. + */ + private Map asgProvider(JsonNode props, ProvisionContext ctx) { + JsonNode asg = props != null ? props.path("AutoScalingGroupProvider") : null; + if (asg == null || !asg.isObject()) { + return new LinkedHashMap<>(); + } + Object converted = toApiShape(ctx.engine().resolveNode(asg)); + if (converted instanceof Map map) { + @SuppressWarnings("unchecked") + Map typed = (Map) map; + return typed; + } + return new LinkedHashMap<>(); + } + + private Map tags(JsonNode props, ProvisionContext ctx) { + Map out = new HashMap<>(); + JsonNode tagsNode = props != null ? props.get("Tags") : null; + if (tagsNode == null || !tagsNode.isArray()) { + return out; + } + for (JsonNode entry : tagsNode) { + JsonNode resolved = ctx.engine().resolveNode(entry); + String key = resolved.path("Key").asText(null); + if (key != null) { + out.put(key, resolved.path("Value").asText("")); + } + } + return out; + } + + /** Recursively converts a resolved CloudFormation node to the ECS API's camelCase Java shape. */ + private Object toApiShape(JsonNode node) { + if (node == null || node.isNull() || node.isMissingNode()) { + return null; + } + if (node.isObject()) { + Map out = new LinkedHashMap<>(); + node.fields().forEachRemaining(field -> { + Object value = toApiShape(field.getValue()); + if (value != null) { + out.put(decapitalize(field.getKey()), value); + } + }); + return out; + } + if (node.isArray()) { + List out = new ArrayList<>(); + for (JsonNode item : node) { + Object value = toApiShape(item); + if (value != null) { + out.add(value); + } + } + return out; + } + if (node.isBoolean()) { + return node.booleanValue(); + } + if (node.isIntegralNumber()) { + return node.asInt(); + } + if (node.isNumber()) { + return node.asDouble(); + } + String text = node.asText(); + return text.isEmpty() ? null : text; + } + + private String decapitalize(String key) { + if (key == null || key.isEmpty()) { + return key; + } + return Character.toLowerCase(key.charAt(0)) + key.substring(1); + } + + private void deleteCapacityProvider(String physicalId) { + // Idempotent: a provider that never got created (rollback) or was already removed is + // delete-complete. describeCapacityProviders resolves both names and ARNs. + if (ecsService.describeCapacityProviders(List.of(physicalId)).isEmpty()) { + LOG.debugv("ECS capacity provider {0} already gone, treating delete as complete", physicalId); + return; + } + ecsService.deleteCapacityProvider(physicalId); + } + + private void clearAssociations(String clusterRef, String region) { + try { + ecsService.putClusterCapacityProviders(clusterRef, List.of(), List.of(), region); + } catch (AwsException e) { + // The cluster itself is deleted right after this resource; if it is already gone there + // is nothing left to detach. Any other failure must still fail the stack delete. + if (!"ClusterNotFoundException".equals(e.getErrorCode())) { + throw e; + } + LOG.debugv("ECS cluster {0} already gone, treating association delete as complete: {1}", + clusterRef, e.getMessage()); + } + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationEcsCapacityIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationEcsCapacityIntegrationTest.java new file mode 100644 index 0000000000..4732aff4e6 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationEcsCapacityIntegrationTest.java @@ -0,0 +1,231 @@ +package io.github.hectorvent.floci.services.cloudformation; + +import io.github.hectorvent.floci.testing.RestAssuredJsonUtils; +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.not; + +/** + * End-to-end check that CloudFormation provisions ECS capacity providers and + * cluster associations (issue #1998) into EcsService, and unwinds both on stack + * delete. Control-plane only. + */ +@QuarkusTest +class CloudFormationEcsCapacityIntegrationTest { + + private static final String CFN_AUTH = + "AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/cloudformation/aws4_request"; + private static final String ECS_TARGET = "AmazonEC2ContainerServiceV20141113."; + private static final String ECS_CT = "application/x-amz-json-1.1"; + + @BeforeAll + static void configureRestAssured() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @Test + void capacityProviderAndAssociationsProvision() { + String suffix = Long.toString(System.nanoTime(), 36); + String stackName = "cfn-ecscap-" + suffix; + String clusterName = "cap-cluster-" + suffix; + String providerName = "cap-provider-" + suffix; + + createStack(stackName, template(clusterName, providerName)); + + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", CFN_AUTH) + .formParam("Action", "DescribeStacks") + .formParam("StackName", stackName) + .when() + .post("/") + .then() + .statusCode(200) + .body(containsString("CREATE_COMPLETE")); + + given() + .header("X-Amz-Target", ECS_TARGET + "DescribeClusters") + .contentType(ECS_CT) + .body("{\"clusters\":[\"" + clusterName + "\"]}") + .when() + .post("/") + .then() + .statusCode(200) + .body(containsString(providerName)); + + // Tags declared on the capacity provider reach ECS instead of being replaced by an empty map. + String providers = describeCapacityProviders(providerName); + assertThat(providers, containsString(providerName)); + assertThat(providers, containsString("owner")); + assertThat(providers, containsString("platform")); + } + + @Test + void stackUpdateReusesTheCapacityProviderItAlreadyCreated() { + // UpdateStack re-executes every resource with the physical id it got at create time, and + // createCapacityProvider rejects an existing name, so the whole update used to fail. The + // aws-bench CDK scenarios redeploy iteratively, which is where this surfaces. + String suffix = Long.toString(System.nanoTime(), 36); + String stackName = "cfn-ecscap-upd-" + suffix; + String clusterName = "cap-cluster-upd-" + suffix; + String providerName = "cap-provider-upd-" + suffix; + + createStack(stackName, template(clusterName, providerName)); + + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", CFN_AUTH) + .formParam("Action", "UpdateStack") + .formParam("StackName", stackName) + .formParam("TemplateBody", template(clusterName, providerName) + .replace("\"TargetCapacity\": 80", "\"TargetCapacity\": 40") + .replace("{\"Key\": \"owner\", \"Value\": \"platform\"}", + "{\"Key\": \"owner\", \"Value\": \"infra\"}")) + .when() + .post("/") + .then() + .statusCode(200); + + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", CFN_AUTH) + .formParam("Action", "DescribeStacks") + .formParam("StackName", stackName) + .when() + .post("/") + .then() + .statusCode(200) + .body(containsString("UPDATE_COMPLETE")); + + // One provider still, carrying the updated tag value. The updated AutoScalingGroupProvider + // is asserted in EcsCapacityCfnProvisionerTest instead: DescribeCapacityProviders does not + // serialize autoScalingGroupProvider, so it is not observable here. + String providers = describeCapacityProviders(providerName); + assertThat(providers, containsString(providerName)); + assertThat(providers, containsString("infra")); + assertThat(providers, not(containsString("platform"))); + } + + @Test + void stackDeleteRemovesProviderAndAssociations() throws Exception { + String suffix = Long.toString(System.nanoTime(), 36); + String stackName = "cfn-ecscap-del-" + suffix; + String clusterName = "cap-cluster-del-" + suffix; + String providerName = "cap-provider-del-" + suffix; + + String stackArn = createStack(stackName, template(clusterName, providerName)); + assertThat(describeCapacityProviders(providerName), containsString(providerName)); + + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", CFN_AUTH) + .formParam("Action", "DeleteStack") + .formParam("StackName", stackName) + .when() + .post("/") + .then() + .statusCode(200); + + String settled = awaitStackSettled(stackArn); + assertThat(settled, containsString("DELETE_COMPLETE")); + + // The capacity provider must be deregistered, not left behind by an unsupported delete. + assertThat(describeCapacityProviders(providerName), not(containsString(providerName))); + } + + private static String template(String clusterName, String providerName) { + return """ + { + "Resources": { + "Cluster": { + "Type": "AWS::ECS::Cluster", + "Properties": {"ClusterName": "%s"} + }, + "Provider": { + "Type": "AWS::ECS::CapacityProvider", + "Properties": { + "Name": "%s", + "AutoScalingGroupProvider": { + "AutoScalingGroupArn": "arn:aws:autoscaling:us-east-1:000000000000:autoScalingGroup:x:autoScalingGroupName/asg-x", + "ManagedTerminationProtection": "ENABLED", + "ManagedDraining": "ENABLED", + "ManagedScaling": {"Status": "ENABLED", "TargetCapacity": 80} + }, + "Tags": [{"Key": "owner", "Value": "platform"}] + } + }, + "Assoc": { + "Type": "AWS::ECS::ClusterCapacityProviderAssociations", + "Properties": { + "Cluster": {"Ref": "Cluster"}, + "CapacityProviders": [{"Ref": "Provider"}, "FARGATE"], + "DefaultCapacityProviderStrategy": [ + {"CapacityProvider": {"Ref": "Provider"}, "Weight": 1} + ] + } + } + } + } + """.formatted(clusterName, providerName); + } + + private String createStack(String stackName, String template) { + String xml = given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", CFN_AUTH) + .formParam("Action", "CreateStack") + .formParam("StackName", stackName) + .formParam("TemplateBody", template) + .when() + .post("/") + .then() + .statusCode(200) + .body(containsString("")) + .extract().asString(); + return xml.substring(xml.indexOf("") + "".length(), xml.indexOf("")); + } + + private String describeCapacityProviders(String providerName) { + return given() + .header("X-Amz-Target", ECS_TARGET + "DescribeCapacityProviders") + .contentType(ECS_CT) + .body("{\"capacityProviders\":[\"" + providerName + "\"]}") + .when() + .post("/") + .then() + .statusCode(200) + .extract().asString(); + } + + private String awaitStackSettled(String stackArn) throws Exception { + long deadline = System.currentTimeMillis() + 10_000; + while (System.currentTimeMillis() < deadline) { + String xml = describeStacks(stackArn); + if (xml.contains("DELETE_COMPLETE") + || xml.contains("DELETE_FAILED")) { + return xml; + } + Thread.sleep(200); + } + throw new AssertionError("Stack did not settle into DELETE_COMPLETE/DELETE_FAILED: " + + describeStacks(stackArn)); + } + + private String describeStacks(String stackArn) { + return given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", CFN_AUTH) + .formParam("Action", "DescribeStacks") + .formParam("StackName", stackArn) + .when() + .post("/") + .then() + .statusCode(200) + .extract().asString(); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/EcsCapacityCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/EcsCapacityCfnProvisionerTest.java new file mode 100644 index 0000000000..08f786117f --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/EcsCapacityCfnProvisionerTest.java @@ -0,0 +1,344 @@ +package io.github.hectorvent.floci.services.cloudformation.provisioners; + +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.CloudFormationTemplateEngine; +import io.github.hectorvent.floci.services.cloudformation.model.StackResource; +import io.github.hectorvent.floci.services.ecs.EcsService; +import io.github.hectorvent.floci.services.ecs.model.CapacityProvider; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.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.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +/** + * The ECS capacity CFN provisioner in isolation: one mocked service, no Quarkus boot. + */ +class EcsCapacityCfnProvisionerTest { + + private static final String PROVIDER_TYPE = "AWS::ECS::CapacityProvider"; + private static final String ASSOCIATIONS_TYPE = "AWS::ECS::ClusterCapacityProviderAssociations"; + private static final String ASG_ARN = + "arn:aws:autoscaling:us-east-1:000000000000:autoScalingGroup:x:autoScalingGroupName/asg-x"; + + private final EcsService ecs = mock(EcsService.class); + private final EcsCapacityCfnProvisioner provisioner = new EcsCapacityCfnProvisioner(ecs); + private final ObjectMapper mapper = new ObjectMapper(); + + private ProvisionContext ctx() { + // Scalars only: resolve returns the node's text and resolveNode is structure-preserving, + // which is what the engine does for templates without intrinsics. + CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class); + when(engine.resolve(any())).thenAnswer(inv -> { + JsonNode node = inv.getArgument(0); + return node == null ? null : node.asText(); + }); + when(engine.resolveNode(any())).thenAnswer(inv -> inv.getArgument(0)); + return new ProvisionContext(engine, "us-east-1", "000000000000", "my-stack"); + } + + private StackResource resource(String type, String logicalId) { + StackResource r = new StackResource(); + r.setLogicalId(logicalId); + r.setResourceType(type); + r.setAttributes(new HashMap<>()); + return r; + } + + @Test + void capacityProviderUsesDeclaredName() { + StackResource r = resource(PROVIDER_TYPE, "Provider"); + ObjectNode props = mapper.createObjectNode(); + props.put("Name", "the-provider"); + props.putObject("AutoScalingGroupProvider").put("AutoScalingGroupArn", ASG_ARN); + + provisioner.provision(r, props, ctx()); + + assertEquals("the-provider", r.getPhysicalId()); + verify(ecs).createCapacityProvider(eq("the-provider"), any(), any(), eq("us-east-1")); + } + + @Test + void capacityProviderWithoutNameGeneratesPhysicalName() { + StackResource r = resource(PROVIDER_TYPE, "Provider"); + + provisioner.provision(r, mapper.createObjectNode(), ctx()); + + assertEquals("my-stack-Provider", r.getPhysicalId().replaceAll("-[0-9a-f]{12}$", "")); + } + + private CapacityProvider stored(String name, String asgArn, Map tags) { + CapacityProvider cp = new CapacityProvider(); + cp.setName(name); + cp.setCapacityProviderArn("arn:aws:ecs:us-east-1:000000000000:capacity-provider/" + name); + Map asg = new HashMap<>(); + asg.put("autoScalingGroupArn", asgArn); + cp.setAutoScalingGroupProvider(asg); + cp.setTags(new HashMap<>(tags)); + return cp; + } + + @Test + void updateReusesTheExistingProviderInsteadOfCreatingIt() { + // UpdateStack re-executes the resource with the physical id it already has, and + // createCapacityProvider rejects an existing name, so this used to fail the whole update. + StackResource r = resource(PROVIDER_TYPE, "Provider"); + r.setPhysicalId("the-provider"); + when(ecs.describeCapacityProviders(List.of("the-provider"))) + .thenReturn(List.of(stored("the-provider", ASG_ARN, Map.of()))); + ObjectNode props = mapper.createObjectNode(); + props.put("Name", "the-provider"); + ObjectNode asg = props.putObject("AutoScalingGroupProvider"); + asg.put("AutoScalingGroupArn", ASG_ARN); + asg.put("ManagedDraining", "ENABLED"); + + provisioner.provision(r, props, ctx()); + + assertEquals("the-provider", r.getPhysicalId()); + verify(ecs, never()).createCapacityProvider(anyString(), any(), any(), anyString()); + ArgumentCaptor> asgCaptor = ArgumentCaptor.forClass(Map.class); + verify(ecs).updateCapacityProvider(eq("the-provider"), asgCaptor.capture()); + assertEquals("ENABLED", asgCaptor.getValue().get("managedDraining")); + } + + @Test + void anUnnamedProviderKeepsItsGeneratedNameAcrossUpdates() { + // A fresh generated name on every pass created a second provider and orphaned the first. + StackResource r = resource(PROVIDER_TYPE, "Provider"); + r.setPhysicalId("my-stack-Provider-abcdef123456"); + when(ecs.describeCapacityProviders(List.of("my-stack-Provider-abcdef123456"))) + .thenReturn(List.of(stored("my-stack-Provider-abcdef123456", null, Map.of()))); + + provisioner.provision(r, mapper.createObjectNode(), ctx()); + + assertEquals("my-stack-Provider-abcdef123456", r.getPhysicalId()); + verify(ecs, never()).createCapacityProvider(anyString(), any(), any(), anyString()); + verify(ecs).updateCapacityProvider(eq("my-stack-Provider-abcdef123456"), any()); + } + + @Test + void aProviderRemovedOutOfBandIsRecreated() { + StackResource r = resource(PROVIDER_TYPE, "Provider"); + r.setPhysicalId("the-provider"); + when(ecs.describeCapacityProviders(List.of("the-provider"))).thenReturn(List.of()); + ObjectNode props = mapper.createObjectNode(); + props.put("Name", "the-provider"); + props.putObject("AutoScalingGroupProvider").put("AutoScalingGroupArn", ASG_ARN); + + provisioner.provision(r, props, ctx()); + + verify(ecs).createCapacityProvider(eq("the-provider"), any(), any(), eq("us-east-1")); + verify(ecs, never()).updateCapacityProvider(anyString(), any()); + } + + @Test + void changingNameIsRejectedAsAReplacement() { + StackResource r = resource(PROVIDER_TYPE, "Provider"); + r.setPhysicalId("the-provider"); + ObjectNode props = mapper.createObjectNode(); + props.put("Name", "a-different-provider"); + + AwsException failure = assertThrows(AwsException.class, () -> provisioner.provision(r, props, ctx())); + + assertEquals("ValidationError", failure.getErrorCode()); + verify(ecs, never()).createCapacityProvider(anyString(), any(), any(), anyString()); + verify(ecs, never()).updateCapacityProvider(anyString(), any()); + } + + @Test + void changingAutoScalingGroupArnIsRejectedAsAReplacement() { + StackResource r = resource(PROVIDER_TYPE, "Provider"); + r.setPhysicalId("the-provider"); + when(ecs.describeCapacityProviders(List.of("the-provider"))) + .thenReturn(List.of(stored("the-provider", ASG_ARN, Map.of()))); + ObjectNode props = mapper.createObjectNode(); + props.put("Name", "the-provider"); + props.putObject("AutoScalingGroupProvider") + .put("AutoScalingGroupArn", ASG_ARN.replace("asg-x", "asg-y")); + + AwsException failure = assertThrows(AwsException.class, () -> provisioner.provision(r, props, ctx())); + + assertEquals("ValidationError", failure.getErrorCode()); + verify(ecs, never()).updateCapacityProvider(anyString(), any()); + } + + @Test + void updateAppliesTagChangesAndRemovesTheOnesTheTemplateDropped() { + // updateCapacityProvider carries only the Auto Scaling settings, so a dropped tag would + // otherwise survive the update. + StackResource r = resource(PROVIDER_TYPE, "Provider"); + r.setPhysicalId("the-provider"); + String arn = "arn:aws:ecs:us-east-1:000000000000:capacity-provider/the-provider"; + when(ecs.describeCapacityProviders(List.of("the-provider"))) + .thenReturn(List.of(stored("the-provider", ASG_ARN, Map.of("keep", "1", "drop", "2")))); + ObjectNode props = mapper.createObjectNode(); + props.put("Name", "the-provider"); + props.putObject("AutoScalingGroupProvider").put("AutoScalingGroupArn", ASG_ARN); + var tags = props.putArray("Tags"); + tags.addObject().put("Key", "keep").put("Value", "1"); + + provisioner.provision(r, props, ctx()); + + verify(ecs).untagResource(arn, List.of("drop")); + verify(ecs).tagResource(arn, Map.of("keep", "1")); + } + + /** Greptile P1: ManagedScaling / ManagedTerminationProtection / ManagedDraining were dropped. */ + @Test + void capacityProviderCarriesFullAutoScalingGroupProvider() { + StackResource r = resource(PROVIDER_TYPE, "Provider"); + ObjectNode props = mapper.createObjectNode(); + props.put("Name", "the-provider"); + ObjectNode asg = props.putObject("AutoScalingGroupProvider"); + asg.put("AutoScalingGroupArn", ASG_ARN); + asg.put("ManagedTerminationProtection", "ENABLED"); + asg.put("ManagedDraining", "ENABLED"); + ObjectNode scaling = asg.putObject("ManagedScaling"); + scaling.put("Status", "ENABLED"); + scaling.put("TargetCapacity", 80); + scaling.put("MinimumScalingStepSize", 1); + scaling.put("MaximumScalingStepSize", 10); + scaling.put("InstanceWarmupPeriod", 300); + + provisioner.provision(r, props, ctx()); + + @SuppressWarnings("unchecked") + ArgumentCaptor> captor = ArgumentCaptor.forClass(Map.class); + verify(ecs).createCapacityProvider(eq("the-provider"), captor.capture(), any(), eq("us-east-1")); + Map asgProvider = captor.getValue(); + + // Stored in the ECS JSON API's camelCase shape, the same one CreateCapacityProvider writes. + assertEquals(ASG_ARN, asgProvider.get("autoScalingGroupArn")); + assertEquals("ENABLED", asgProvider.get("managedTerminationProtection")); + assertEquals("ENABLED", asgProvider.get("managedDraining")); + @SuppressWarnings("unchecked") + Map managedScaling = (Map) asgProvider.get("managedScaling"); + assertEquals("ENABLED", managedScaling.get("status")); + assertEquals(80, managedScaling.get("targetCapacity")); + assertEquals(1, managedScaling.get("minimumScalingStepSize")); + assertEquals(10, managedScaling.get("maximumScalingStepSize")); + assertEquals(300, managedScaling.get("instanceWarmupPeriod")); + } + + /** Greptile P1: Tags were replaced with an empty map. */ + @Test + void capacityProviderCarriesTags() { + StackResource r = resource(PROVIDER_TYPE, "Provider"); + ObjectNode props = mapper.createObjectNode(); + props.put("Name", "the-provider"); + var tags = props.putArray("Tags"); + tags.addObject().put("Key", "env").put("Value", "prod"); + tags.addObject().put("Key", "team").put("Value", "platform"); + + provisioner.provision(r, props, ctx()); + + @SuppressWarnings("unchecked") + ArgumentCaptor> captor = ArgumentCaptor.forClass(Map.class); + verify(ecs).createCapacityProvider(eq("the-provider"), any(), captor.capture(), eq("us-east-1")); + assertEquals(Map.of("env", "prod", "team", "platform"), captor.getValue()); + } + + @Test + void associationsPutProvidersAndStrategy() { + StackResource r = resource(ASSOCIATIONS_TYPE, "Assoc"); + ObjectNode props = mapper.createObjectNode(); + props.put("Cluster", "the-cluster"); + var providers = props.putArray("CapacityProviders"); + providers.add("the-provider"); + providers.add("FARGATE"); + var strategy = props.putArray("DefaultCapacityProviderStrategy"); + strategy.addObject().put("CapacityProvider", "the-provider").put("Weight", 2).put("Base", 1); + + provisioner.provision(r, props, ctx()); + + assertEquals("the-cluster", r.getPhysicalId()); + verify(ecs).putClusterCapacityProviders("the-cluster", + List.of("the-provider", "FARGATE"), + List.of(Map.of("capacityProvider", "the-provider", "weight", 2, "base", 1)), + "us-east-1"); + } + + @Test + void unhandledTypeThrows() { + StackResource r = resource("AWS::ECS::Cluster", "Cluster"); + assertThrows(IllegalStateException.class, + () -> provisioner.provision(r, mapper.createObjectNode(), ctx())); + } + + /** Greptile P1: stack delete and rollback left the capacity provider registered. */ + @Test + void deleteCapacityProviderDelegatesToService() { + CapacityProvider existing = new CapacityProvider(); + existing.setName("the-provider"); + when(ecs.describeCapacityProviders(List.of("the-provider"))).thenReturn(List.of(existing)); + + provisioner.delete(PROVIDER_TYPE, "the-provider", "us-east-1"); + + verify(ecs).deleteCapacityProvider("the-provider"); + } + + @Test + void deleteCapacityProviderAlreadyGoneIsDeleteComplete() { + when(ecs.describeCapacityProviders(anyList())).thenReturn(List.of()); + + provisioner.delete(PROVIDER_TYPE, "the-provider", "us-east-1"); + + verify(ecs, never()).deleteCapacityProvider(anyString()); + } + + /** Greptile P1: the cluster kept its associations after the stack was deleted. */ + @Test + void deleteAssociationsDetachesProvidersFromCluster() { + provisioner.delete(ASSOCIATIONS_TYPE, "the-cluster", "us-east-1"); + + verify(ecs).putClusterCapacityProviders("the-cluster", List.of(), List.of(), "us-east-1"); + } + + @Test + void deleteAssociationsToleratesAMissingCluster() { + when(ecs.putClusterCapacityProviders(anyString(), anyList(), anyList(), anyString())) + .thenThrow(new AwsException("ClusterNotFoundException", "Cluster not found: gone", 400)); + + provisioner.delete(ASSOCIATIONS_TYPE, "gone", "us-east-1"); + } + + @Test + void deleteAssociationsPropagatesOtherFailures() { + when(ecs.putClusterCapacityProviders(anyString(), anyList(), anyList(), anyString())) + .thenThrow(new AwsException("ServerException", "boom", 500)); + + AwsException thrown = assertThrows(AwsException.class, + () -> provisioner.delete(ASSOCIATIONS_TYPE, "the-cluster", "us-east-1")); + assertEquals("ServerException", thrown.getErrorCode()); + } + + @Test + void deleteWithoutAPhysicalIdIsANoOp() { + provisioner.delete(PROVIDER_TYPE, null, "us-east-1"); + provisioner.delete(ASSOCIATIONS_TYPE, " ", "us-east-1"); + verifyNoInteractions(ecs); + } + + @Test + void resourceTypesCoverBothCapacityTypes() { + assertTrue(provisioner.resourceTypes().containsAll(List.of(PROVIDER_TYPE, ASSOCIATIONS_TYPE))); + assertEquals(2, provisioner.resourceTypes().size()); + } +}