diff --git a/docs/services/ecs.md b/docs/services/ecs.md index 8072fd5337..a4a7fa37a4 100644 --- a/docs/services/ecs.md +++ b/docs/services/ecs.md @@ -205,10 +205,13 @@ service-only option; `TASK_DEFINITION` copies the task definition's tags onto ea On `UpdateService`, the changes that start new tasks roll the deployment: the task definition, the network configuration, the load balancers, the service registries, the Service Connect -configuration, and `forceNewDeployment`. The ones AWS documents as not triggering a deployment -(`desiredCount`, `deploymentConfiguration`, `enableExecuteCommand`, `enableECSManagedTags`, -`propagateTags`, `healthCheckGracePeriodSeconds`, `availabilityZoneRebalancing`, the capacity -provider strategy and the placement members) are applied without rolling anything. +configuration, `platformVersion` and `forceNewDeployment`. The ones AWS documents as not +triggering a deployment (`desiredCount`, `deploymentConfiguration`, `enableExecuteCommand`, +`enableECSManagedTags`, `propagateTags`, `healthCheckGracePeriodSeconds`, +`availabilityZoneRebalancing`, the capacity provider strategy and the placement members) are +applied without rolling anything. An update replaces only the members it names: one that sends +`placementStrategy` alone leaves a `placementConstraints` stored earlier in place, and an empty +array clears a member the way AWS clears it. Every `awsvpc` task gets a real ENI in the subnet it asked for, in Docker and in mock mode alike, and reports it as an `attachments` entry with its `networkInterfaceId`, `privateIPv4Address` and @@ -289,6 +292,11 @@ Known differences from AWS: `deployments` list still reports a single `PRIMARY` throughout. - `updatedAt` equals `createdAt`. AWS advances it as a rollout progresses; Floci has no intermediate rollout state to report. +- `deploymentConfiguration` (including the circuit breaker), `healthCheckGracePeriodSeconds`, + `serviceRegistries` and the placement constraints and strategies are stored and reported as + given, so a client that reads them back sees no drift, but the reconciler does not act on them: + it converges to `desiredCount` without a maximum or minimum percent, registers nothing in Cloud + Map, and places tasks without evaluating constraints. #### ECS EventBridge events @@ -354,6 +362,24 @@ unchanged. | `DeleteCapacityProvider` | Delete a capacity provider | | `DescribeCapacityProviders` | Describe capacity providers (includes FARGATE built-ins) | +A capacity provider name is validated the way AWS documents it: up to 255 letters, numbers, +underscores and hyphens, and never prefixed with `aws`, `ecs` or `fargate`. A created provider +reports its `capacityProviderArn`, a `type` of `EC2_AUTOSCALING`, and the +`autoScalingGroupProvider` it was created with, so a client that wrote one reads back what it +registered instead of seeing drift. + +`DescribeCapacityProviders` returns tags only for `include: ["TAGS"]`, and reports a name that +resolves to nothing as a `MISSING` entry in `failures` rather than dropping it. The built-in +`FARGATE` and `FARGATE_SPOT` providers are described with their own ARNs and a `type` matching +their name. + +`DeleteCapacityProvider` refuses the reserved `FARGATE` and `FARGATE_SPOT` providers, one that is +still attached to a cluster (detach it with `PutClusterCapacityProviders`, or delete the cluster, +first), and one still named in an active service's capacity provider strategy, which AWS requires +to be removed with `UpdateService` before the provider goes. A deleted provider is reported with +`updateStatus: DELETE_IN_PROGRESS` and an unchanged `status`, because `DELETE_IN_PROGRESS` is not +one of the four values `CapacityProviderStatus` takes. + ### Service Deployments & Revisions | Operation | Description | diff --git a/src/main/java/io/github/hectorvent/floci/services/ecs/EcsJsonHandler.java b/src/main/java/io/github/hectorvent/floci/services/ecs/EcsJsonHandler.java index 51cdac028c..28f1bf0077 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ecs/EcsJsonHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/ecs/EcsJsonHandler.java @@ -455,6 +455,18 @@ public class EcsJsonHandler { // ── Services ────────────────────────────────────────────────────────────── + /** + * Members of CreateService the parser consumes. {@code clientToken} is deliberately not + * round-tripped: it is a request-only member and has no place on the Service shape. + */ + private static final Set SERVICE_CONSUMED = Set.of( + "cluster", "serviceName", "taskDefinition", "service", "desiredCount", "launchType", + "capacityProviderStrategy", "platformVersion", "loadBalancers", "serviceRegistries", + "networkConfiguration", "tags", "schedulingStrategy", "deploymentController", + "availabilityZoneRebalancing", "serviceConnectConfiguration", "deploymentConfiguration", + "enableExecuteCommand", "enableECSManagedTags", "propagateTags", + "healthCheckGracePeriodSeconds", "role", "clientToken", "forceNewDeployment"); + private Response handleCreateService(JsonNode req, String region) { CreateServiceRequest request = new CreateServiceRequest(); request.setCluster(req.has("cluster") ? req.path("cluster").asText() : null); @@ -463,7 +475,10 @@ public class EcsJsonHandler { request.setDesiredCount(req.path("desiredCount").asInt(1)); request.setLaunchType(parseEnum(req, "launchType", LaunchType.class)); request.setCapacityProviderStrategy(parseCapacityProviderStrategy(req.path("capacityProviderStrategy"))); + request.setPlatformVersion(req.hasNonNull("platformVersion") + ? req.path("platformVersion").asText() : null); request.setLoadBalancers(parseLoadBalancers(req.path("loadBalancers"))); + request.setServiceRegistries(parseRawObjectList(req.path("serviceRegistries"))); request.setNetworkConfiguration(parseNetworkConfiguration(req.path("networkConfiguration"))); request.setTags(parseTagMap(req.path("tags"))); request.setSchedulingStrategy(parseChoice(req, "schedulingStrategy", SCHEDULING_STRATEGIES)); @@ -471,6 +486,14 @@ public class EcsJsonHandler { "deploymentController.type", DEPLOYMENT_CONTROLLER_TYPES)); request.setAvailabilityZoneRebalancing(parseChoice(req, "availabilityZoneRebalancing", AZ_REBALANCING)); request.setServiceConnectConfiguration(parseRawObject(req.path("serviceConnectConfiguration"))); + request.setDeploymentConfiguration(parseRawObject(req.path("deploymentConfiguration"))); + request.setEnableExecuteCommand(req.path("enableExecuteCommand").asBoolean(false)); + request.setEnableECSManagedTags(req.path("enableECSManagedTags").asBoolean(false)); + request.setPropagateTags(parseChoice(req, "propagateTags", PROPAGATE_TAGS)); + request.setHealthCheckGracePeriodSeconds(req.hasNonNull("healthCheckGracePeriodSeconds") + ? req.path("healthCheckGracePeriodSeconds").asInt() : null); + request.setRoleArn(req.hasNonNull("role") ? req.path("role").asText() : null); + request.setUnparsed(EcsJsonPassthrough.capture(req, objectMapper, SERVICE_CONSUMED)); EcsServiceModel svc = service.createService(request, region); @@ -490,6 +513,23 @@ public class EcsJsonHandler { request.setForceNewDeployment(req.path("forceNewDeployment").asBoolean(false)); request.setServiceConnectConfiguration(parseRawObject(req.path("serviceConnectConfiguration"))); request.setCapacityProviderStrategy(parseCapacityProviderStrategy(req.path("capacityProviderStrategy"))); + request.setPlatformVersion(req.hasNonNull("platformVersion") + ? req.path("platformVersion").asText() : null); + request.setEnableExecuteCommand(req.hasNonNull("enableExecuteCommand") + ? req.path("enableExecuteCommand").asBoolean() : null); + request.setEnableECSManagedTags(req.hasNonNull("enableECSManagedTags") + ? req.path("enableECSManagedTags").asBoolean() : null); + request.setPropagateTags(parseChoice(req, "propagateTags", PROPAGATE_TAGS)); + request.setHealthCheckGracePeriodSeconds(req.hasNonNull("healthCheckGracePeriodSeconds") + ? req.path("healthCheckGracePeriodSeconds").asInt() : null); + request.setDeploymentConfiguration(parseRawObject(req.path("deploymentConfiguration"))); + if (req.has("loadBalancers")) { + request.setLoadBalancers(parseLoadBalancers(req.path("loadBalancers"))); + } + if (req.has("serviceRegistries")) { + request.setServiceRegistries(parseRawObjectList(req.path("serviceRegistries"))); + } + request.setUnparsed(EcsJsonPassthrough.capture(req, objectMapper, SERVICE_CONSUMED)); EcsServiceModel svc = service.updateService(request, region); @@ -579,12 +619,13 @@ public class EcsJsonHandler { String cluster = req.has("cluster") ? req.path("cluster").asText() : null; List serviceIds = jsonArrayToList(req.path("services")); + boolean includeTags = jsonArrayToList(req.path("include")).contains("TAGS"); EcsService.DescribeServicesResult found = service.describeServicesDetailed(cluster, serviceIds, region); ObjectNode resp = objectMapper.createObjectNode(); ArrayNode arr = objectMapper.createArrayNode(); - found.services().forEach(s -> arr.add(writer.serviceNode(s))); + found.services().forEach(s -> arr.add(writer.serviceNode(s, includeTags))); resp.set("services", arr); ArrayNode failures = objectMapper.createArrayNode(); found.failures().forEach(f -> failures.add(writer.failureNode(f))); @@ -813,11 +854,16 @@ public class EcsJsonHandler { private Response handleDescribeCapacityProviders(JsonNode req, String region) { List providers = req.has("capacityProviders") ? jsonArrayToList(req.path("capacityProviders")) : null; - List found = service.describeCapacityProviders(providers); + boolean includeTags = jsonArrayToList(req.path("include")).contains("TAGS"); + EcsService.DescribeCapacityProvidersResult result = + service.describeCapacityProvidersDetailed(providers, region); ObjectNode resp = objectMapper.createObjectNode(); ArrayNode arr = objectMapper.createArrayNode(); - found.forEach(cp -> arr.add(writer.capacityProviderNode(cp))); + result.capacityProviders().forEach(cp -> arr.add(writer.capacityProviderNode(cp, includeTags))); resp.set("capacityProviders", arr); + ArrayNode failures = objectMapper.createArrayNode(); + result.failures().forEach(f -> failures.add(writer.failureNode(f))); + resp.set("failures", failures); return Response.ok(resp).build(); } diff --git a/src/main/java/io/github/hectorvent/floci/services/ecs/EcsResponseWriter.java b/src/main/java/io/github/hectorvent/floci/services/ecs/EcsResponseWriter.java index 44ad307af5..6da158a178 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ecs/EcsResponseWriter.java +++ b/src/main/java/io/github/hectorvent/floci/services/ecs/EcsResponseWriter.java @@ -586,6 +586,14 @@ public class EcsResponseWriter { // ── Services ────────────────────────────────────────────────────────────── /** Renders a service for a describe, gating its tags on {@code include: ["TAGS"]}. */ + public ObjectNode serviceNode(EcsServiceModel s, boolean includeTags) { + ObjectNode n = serviceNode(s); + if (!includeTags) { + n.remove("tags"); + } + return n; + } + public ObjectNode serviceNode(EcsServiceModel s) { ObjectNode n = objectMapper.createObjectNode(); n.put("serviceArn", s.getServiceArn()); @@ -602,8 +610,11 @@ public class EcsResponseWriter { } else if (s.getLaunchType() != null) { n.put("launchType", s.getLaunchType().name()); } + if (s.getPlatformVersion() != null) { n.put("platformVersion", s.getPlatformVersion()); } + if (s.getPlatformFamily() != null) { n.put("platformFamily", s.getPlatformFamily()); } putInstant(n, "createdAt", s.getCreatedAt()); if (s.getNamespace() != null) { n.put("namespace", s.getNamespace()); } + if (s.getRoleArn() != null) { n.put("roleArn", s.getRoleArn()); } // Services persisted before these fields existed read back with the AWS defaults. n.put("schedulingStrategy", s.getSchedulingStrategy() != null ? s.getSchedulingStrategy() : EcsService.DEFAULT_SCHEDULING_STRATEGY); @@ -611,6 +622,18 @@ public class EcsResponseWriter { ? s.getDeploymentController() : EcsService.DEFAULT_DEPLOYMENT_CONTROLLER); n.put("availabilityZoneRebalancing", s.getAvailabilityZoneRebalancing() != null ? s.getAvailabilityZoneRebalancing() : EcsService.DEFAULT_AZ_REBALANCING_UNSET); + n.put("enableExecuteCommand", s.isEnableExecuteCommand()); + n.put("enableECSManagedTags", s.isEnableECSManagedTags()); + if (s.getPropagateTags() != null) { n.put("propagateTags", s.getPropagateTags()); } + if (s.getHealthCheckGracePeriodSeconds() != null) { + n.put("healthCheckGracePeriodSeconds", s.getHealthCheckGracePeriodSeconds()); + } + if (s.getDeploymentConfiguration() != null) { + n.set("deploymentConfiguration", objectMapper.valueToTree(s.getDeploymentConfiguration())); + } + if (s.getServiceRegistries() != null && !s.getServiceRegistries().isEmpty()) { + n.set("serviceRegistries", objectMapper.valueToTree(s.getServiceRegistries())); + } if (s.getTags() != null && !s.getTags().isEmpty()) { n.set("tags", tagsNode(s.getTags())); } @@ -629,6 +652,7 @@ public class EcsResponseWriter { ArrayNode deployments = objectMapper.createArrayNode(); service.deploymentsFor(s).forEach(d -> deployments.add(deploymentNode(d))); n.set("deployments", deployments); + EcsJsonPassthrough.write(n, s.getUnparsed(), objectMapper); return n; } @@ -705,17 +729,28 @@ public class EcsResponseWriter { } /** @param includeTags DescribeCapacityProviders returns tags only for {@code include: ["TAGS"]}. */ - public ObjectNode capacityProviderNode(CapacityProvider cp) { + public ObjectNode capacityProviderNode(CapacityProvider cp, boolean includeTags) { ObjectNode n = objectMapper.createObjectNode(); n.put("name", cp.getName()); n.put("status", cp.getStatus()); if (cp.getCapacityProviderArn() != null) { n.put("capacityProviderArn", cp.getCapacityProviderArn()); } - if (cp.getTags() != null && !cp.getTags().isEmpty()) { + if (cp.getUpdateStatus() != null) { n.put("updateStatus", cp.getUpdateStatus()); } + if (cp.getType() != null) { n.put("type", cp.getType()); } + // The provider's own configuration, which a client that created it reads back to confirm + // what it registered. Dropping it reads as drift in Terraform's aws_ecs_capacity_provider. + if (cp.getAutoScalingGroupProvider() != null) { + n.set("autoScalingGroupProvider", objectMapper.valueToTree(cp.getAutoScalingGroupProvider())); + } + if (includeTags && cp.getTags() != null && !cp.getTags().isEmpty()) { n.set("tags", tagsNode(cp.getTags())); } return n; } + public ObjectNode capacityProviderNode(CapacityProvider cp) { + return capacityProviderNode(cp, true); + } + public ObjectNode taskSetNode(TaskSet ts) { ObjectNode n = objectMapper.createObjectNode(); n.put("id", ts.getId()); diff --git a/src/main/java/io/github/hectorvent/floci/services/ecs/EcsService.java b/src/main/java/io/github/hectorvent/floci/services/ecs/EcsService.java index ff9509791c..21d54c69d3 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ecs/EcsService.java +++ b/src/main/java/io/github/hectorvent/floci/services/ecs/EcsService.java @@ -14,6 +14,7 @@ import io.github.hectorvent.floci.core.storage.StorageFactory; import io.github.hectorvent.floci.services.ecs.container.EcsContainerManager; import io.github.hectorvent.floci.services.ecs.container.EcsTaskHandle; import io.github.hectorvent.floci.services.ecs.model.Attribute; +import io.github.hectorvent.floci.services.ecs.model.AwsVpcConfiguration; import io.github.hectorvent.floci.services.ecs.model.CapacityProvider; import io.github.hectorvent.floci.services.ecs.model.CapacityProviderStrategyItem; import io.github.hectorvent.floci.services.ecs.model.ClusterSetting; @@ -65,7 +66,9 @@ import java.util.Collections; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; +import java.util.Locale; import java.util.Map; +import java.util.Objects; import java.util.stream.Collectors; import java.util.Set; import java.util.Comparator; @@ -77,6 +80,7 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; +import java.util.regex.Pattern; import java.util.stream.Stream; import io.github.hectorvent.floci.core.resource.ExplorerResource; import io.github.hectorvent.floci.core.resource.ResourceProvider; @@ -135,6 +139,7 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab public static final String STOP_CODE_SERVICE_SCHEDULER_INITIATED = "ServiceSchedulerInitiated"; public static final String PROPAGATE_TAGS_SERVICE = "SERVICE"; public static final String PROPAGATE_TAGS_TASK_DEFINITION = "TASK_DEFINITION"; + public static final String PROPAGATE_TAGS_NONE = "NONE"; /** RunTask places at most ten tasks in one call, and StartTask at most ten instances. */ public static final int MAX_TASKS_PER_RUN = 10; public static final String STATUS_ACTIVE = "ACTIVE"; @@ -1210,11 +1215,19 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab request.setGroup("service:" + svc.getServiceName()); request.setStartedBy(deploymentId(svc)); request.setNetworkConfiguration(svc.getNetworkConfiguration()); + request.setPlatformVersion(svc.getPlatformVersion()); + request.setEnableExecuteCommand(svc.isEnableExecuteCommand()); // A service pinned to a capacity provider places its tasks through it, unless the // reconciler is placing a DAEMON task on a named container instance. if (containerInstanceArn == null) { request.setCapacityProviderStrategy(svc.getCapacityProviderStrategy()); } + if (EcsService.PROPAGATE_TAGS_SERVICE.equals(svc.getPropagateTags())) { + request.setTags(svc.getTags()); + } + if (PROPAGATE_TAGS_TASK_DEFINITION.equals(svc.getPropagateTags())) { + request.setPropagateTags(PROPAGATE_TAGS_TASK_DEFINITION); + } EcsTask task = launchTasks(cluster, taskDef, request, containerInstanceArn, svc.getServiceArn(), region).getFirst(); task.setDeploymentId(deploymentId(svc)); @@ -1758,6 +1771,7 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab } svc.setDesiredCount(desiredCount); svc.setLoadBalancers(request.getLoadBalancers()); + svc.setServiceRegistries(request.getServiceRegistries()); svc.setNetworkConfiguration(request.getNetworkConfiguration()); // AWS echoes these on every DescribeServices; clients that persist them (Terraform's // aws_ecs_service reads all three, and schedulingStrategy is ForceNew) treat a missing @@ -1777,6 +1791,18 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab svc.setAvailabilityZoneRebalancing(request.getAvailabilityZoneRebalancing() != null ? request.getAvailabilityZoneRebalancing() : DEFAULT_AZ_REBALANCING_ON_CREATE); svc.setServiceConnectConfiguration(request.getServiceConnectConfiguration()); + svc.setDeploymentConfiguration(request.getDeploymentConfiguration()); + svc.setEnableExecuteCommand(request.isEnableExecuteCommand()); + svc.setEnableECSManagedTags(request.isEnableECSManagedTags()); + // Both have documented defaults a created service reports back. + svc.setPropagateTags(request.getPropagateTags() != null + ? request.getPropagateTags() : PROPAGATE_TAGS_NONE); + svc.setHealthCheckGracePeriodSeconds(request.getHealthCheckGracePeriodSeconds() != null + ? request.getHealthCheckGracePeriodSeconds() : 0); + validateServiceRole(request, taskDef); + svc.setRoleArn(request.getRoleArn()); + svc.setUnparsed(request.getUnparsed()); + applyServicePlatform(svc, taskDef, request.getPlatformVersion()); svc.setStatus("ACTIVE"); svc.setCreatedAt(Instant.now()); svc.setLastDeploymentAt(svc.getCreatedAt()); @@ -1857,7 +1883,15 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab } svc.setDesiredCount(request.getDesiredCount()); } + // The members whose change starts new tasks, as UpdateService documents them: the network + // configuration, the load balancers, the service registries, the Service Connect + // configuration, the task definition and the platform version. The rest (desired count, + // deployment configuration, the exec and managed-tag switches, placement, propagateTags, + // the capacity provider strategy) are applied without rolling anything. + boolean rollingChange = false; if (request.getNetworkConfiguration() != null) { + rollingChange |= networkConfigurationChanged(svc.getNetworkConfiguration(), + request.getNetworkConfiguration()); svc.setNetworkConfiguration(request.getNetworkConfiguration()); } if (request.getAvailabilityZoneRebalancing() != null) { @@ -1869,6 +1903,32 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab ? svc.getLaunchType() : placementFor(request.getCapacityProviderStrategy().getFirst().capacityProvider()).launchType()); } + if (request.getEnableExecuteCommand() != null) { + svc.setEnableExecuteCommand(request.getEnableExecuteCommand()); + } + if (request.getEnableECSManagedTags() != null) { + svc.setEnableECSManagedTags(request.getEnableECSManagedTags()); + } + if (request.getPropagateTags() != null) { + svc.setPropagateTags(request.getPropagateTags()); + } + if (request.getHealthCheckGracePeriodSeconds() != null) { + svc.setHealthCheckGracePeriodSeconds(request.getHealthCheckGracePeriodSeconds()); + } + if (request.getDeploymentConfiguration() != null) { + svc.setDeploymentConfiguration(request.getDeploymentConfiguration()); + } + if (request.getLoadBalancers() != null) { + rollingChange |= loadBalancersChanged(svc.getLoadBalancers(), request.getLoadBalancers()); + svc.setLoadBalancers(request.getLoadBalancers()); + } + if (request.getServiceRegistries() != null) { + rollingChange |= !request.getServiceRegistries().equals(svc.getServiceRegistries()); + svc.setServiceRegistries(request.getServiceRegistries()); + } + if (request.getUnparsed() != null) { + svc.setUnparsed(mergedUnparsed(svc.getUnparsed(), request.getUnparsed())); + } // UpdateServiceRequest.serviceConnectConfiguration is documented as "This parameter // triggers a new service deployment", so a real change rolls the deployment the way a // task-definition change does. An omitted parameter is not a change and rolls nothing. @@ -1879,12 +1939,22 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab svc.setServiceConnectConfiguration(serviceConnectConfiguration); } boolean taskDefChanged = false; + String platformVersionBefore = svc.getPlatformVersion(); if (request.getTaskDefinition() != null) { TaskDefinition resolved = resolveLaunchableTaskDefinition(request.getTaskDefinition(), region); taskDefChanged = !resolved.getTaskDefinitionArn().equals(svc.getTaskDefinition()); svc.setTaskDefinition(resolved.getTaskDefinitionArn()); + applyServicePlatform(svc, resolved, request.getPlatformVersion() != null + ? request.getPlatformVersion() : svc.getPlatformVersion()); + } else if (request.getPlatformVersion() != null) { + svc.setPlatformVersion(PLATFORM_VERSION_LATEST.equals(request.getPlatformVersion()) + ? DEFAULT_PLATFORM_VERSION : request.getPlatformVersion()); } - if (taskDefChanged || forceNewDeployment || serviceConnectChanged) { + // UpdateServiceRequest.platformVersion is documented as "This parameter triggers a new + // service deployment". Compared after resolution, so a request that asks for LATEST on a + // service already running the version LATEST resolves to is not a change. + rollingChange |= !Objects.equals(platformVersionBefore, svc.getPlatformVersion()); + if (taskDefChanged || forceNewDeployment || serviceConnectChanged || rollingChange) { svc.setDeploymentId(newDeploymentId()); svc.setLastDeploymentAt(Instant.now()); recordServiceDeployment(svc, svc.getTaskDefinition(), region); @@ -1897,6 +1967,71 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab return svc; } + /** + * Folds an update's passthrough members into the ones the service already carries. UpdateService + * replaces only the members a request names, so a service created with {@code + * placementConstraints} and updated with only {@code placementStrategy} keeps its constraints. + * A member the update does name is replaced outright, which is how an empty array clears one. + */ + private static Map mergedUnparsed(Map current, + Map update) { + if (current == null || current.isEmpty()) { + return update; + } + Map merged = new LinkedHashMap<>(current); + merged.putAll(update); + return merged; + } + + /** Whether an update's awsvpc configuration differs from the one the service already had. */ + private static boolean networkConfigurationChanged(NetworkConfiguration current, + NetworkConfiguration updated) { + AwsVpcConfiguration before = current == null ? null : current.getAwsvpcConfiguration(); + AwsVpcConfiguration after = updated == null ? null : updated.getAwsvpcConfiguration(); + if (before == null || after == null) { + return before != after; + } + return !Objects.equals(before.getSubnets(), after.getSubnets()) + || !Objects.equals(before.getSecurityGroups(), after.getSecurityGroups()) + || !Objects.equals(before.getAssignPublicIp(), after.getAssignPublicIp()); + } + + /** Whether an update's load balancers differ from the ones the service already had. */ + private static boolean loadBalancersChanged(List current, + List updated) { + return !loadBalancerKeys(current).equals(loadBalancerKeys(updated)); + } + + private static List loadBalancerKeys(List loadBalancers) { + if (loadBalancers == null) { + return List.of(); + } + return loadBalancers.stream() + .map(lb -> lb.getTargetGroupArn() + "|" + lb.getLoadBalancerName() + "|" + + lb.getContainerName() + "|" + lb.getContainerPort()) + .toList(); + } + + /** + * A {@code role} is only permitted on a load-balanced service whose task definition does not + * use {@code awsvpc}: with awsvpc, or without a load balancer, ECS uses the service-linked + * role instead and rejects one given here. + */ + private static void validateServiceRole(CreateServiceRequest request, TaskDefinition taskDef) { + if (request.getRoleArn() == null || request.getRoleArn().isBlank()) { + return; + } + if (request.getLoadBalancers() == null || request.getLoadBalancers().isEmpty()) { + throw new AwsException("InvalidParameterException", + "The role parameter is only permitted when the service uses a load balancer.", 400); + } + if (taskDef.getNetworkMode() == NetworkMode.awsvpc) { + throw new AwsException("InvalidParameterException", + "The role parameter is not permitted for a task definition that uses the " + + "awsvpc network mode.", 400); + } + } + /** * The launch type a service's tasks get. An explicit one wins; otherwise the first entry of * the service's own capacity provider strategy, then the cluster's default strategy, decides @@ -1917,6 +2052,19 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab return placementFor(strategy.getFirst().capacityProvider()).launchType(); } + /** A Fargate service reports the platform its tasks run on; an EC2 service reports neither. */ + private static void applyServicePlatform(EcsServiceModel svc, TaskDefinition taskDef, String platformVersion) { + if (svc.getLaunchType() != LaunchType.FARGATE) { + svc.setPlatformVersion(null); + svc.setPlatformFamily(null); + return; + } + svc.setPlatformVersion(platformVersion == null || platformVersion.isBlank() + || PLATFORM_VERSION_LATEST.equals(platformVersion) + ? DEFAULT_PLATFORM_VERSION : platformVersion); + svc.setPlatformFamily(platformFamilyOf(taskDef)); + } + /** * The platform family a Fargate task or service reports. * @@ -2291,8 +2439,18 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab // ── Capacity Providers ──────────────────────────────────────────────────── + /** The two providers Fargate predefines, which exist in every account and cannot be deleted. */ + private static final Set RESERVED_CAPACITY_PROVIDERS = Set.of("FARGATE", "FARGATE_SPOT"); + private static final List RESERVED_CAPACITY_PROVIDER_PREFIXES = + List.of("aws", "ecs", "fargate"); + private static final int MAX_CAPACITY_PROVIDER_NAME_LENGTH = 255; + private static final Pattern CAPACITY_PROVIDER_NAME_PATTERN = Pattern.compile("[A-Za-z0-9_-]+"); + /** The only provider type Floci mints: a created provider always wraps an Auto Scaling group. */ + private static final String CAPACITY_PROVIDER_TYPE_EC2 = "EC2_AUTOSCALING"; + public CapacityProvider createCapacityProvider(String name, Map asgProvider, Map tags, String region) { + validateCapacityProviderName(name); if (capacityProviders.containsKey(name)) { throw new AwsException("InvalidParameterException", "A capacity provider with name " + name + " already exists.", 400); @@ -2301,6 +2459,8 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab cp.setName(name); cp.setCapacityProviderArn(regionResolver.buildArn("ecs", region, "capacity-provider/" + name)); cp.setStatus("ACTIVE"); + cp.setUpdateStatus("CREATE_COMPLETE"); + cp.setType(CAPACITY_PROVIDER_TYPE_EC2); cp.setAutoScalingGroupProvider(asgProvider); if (tags != null) { cp.setTags(tags); @@ -2312,47 +2472,154 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab public CapacityProvider updateCapacityProvider(String name, Map asgProvider) { CapacityProvider cp = resolveCapacityProviderOrThrow(name); cp.setAutoScalingGroupProvider(asgProvider); + cp.setUpdateStatus("UPDATE_COMPLETE"); capacityProviders.put(cp.getName(), cp); return cp; } + /** + * Deletes a capacity provider. "The FARGATE and FARGATE_SPOT capacity providers are reserved + * and can't be deleted", and "only capacity providers that aren't associated with a cluster + * can be deleted": both come back as InvalidParameterException rather than removing anything. + * + *

The deleted provider is reported with {@code updateStatus: DELETE_IN_PROGRESS} and an + * unchanged {@code status}: DELETE_IN_PROGRESS is not one of the four values + * {@code CapacityProviderStatus} takes, so reporting it there hands the SDK an enum it + * cannot map. + */ public CapacityProvider deleteCapacityProvider(String nameOrArn) { + if (RESERVED_CAPACITY_PROVIDERS.contains(nameOrArn)) { + throw new AwsException("InvalidParameterException", + "The " + nameOrArn + " capacity provider is reserved and can't be deleted.", 400); + } CapacityProvider cp = resolveCapacityProviderOrThrow(nameOrArn); - cp.setStatus("DELETE_IN_PROGRESS"); + String attachedTo = clusterUsingCapacityProvider(cp.getName()); + if (attachedTo != null) { + throw new AwsException("InvalidParameterException", + "The capacity provider " + cp.getName() + " is associated with cluster " + + attachedTo + " and can't be deleted. Remove it with " + + "PutClusterCapacityProviders or delete the cluster first.", 400); + } + String usedBy = serviceUsingCapacityProvider(cp); + if (usedBy != null) { + throw new AwsException("InvalidParameterException", + "The capacity provider " + cp.getName() + " is in the capacity provider " + + "strategy of service " + usedBy + " and can't be deleted. Remove it " + + "from the service's capacity provider strategy with UpdateService " + + "first.", 400); + } + cp.setUpdateStatus("DELETE_IN_PROGRESS"); capacityProviders.remove(cp.getName()); return cp; } + public record DescribeCapacityProvidersResult(List capacityProviders, + List failures) {} + public List describeCapacityProviders(List providers) { + return describeCapacityProvidersDetailed(providers, regionResolver.getDefaultRegion()) + .capacityProviders(); + } + + /** + * Describes capacity providers, reporting a name that matches none as a {@code MISSING} + * failure rather than dropping it from the answer. + */ + public DescribeCapacityProvidersResult describeCapacityProvidersDetailed(List providers, + String region) { if (providers == null || providers.isEmpty()) { - List result = new ArrayList<>(List.of(builtInFargate(), builtInFargateSpot())); + List result = + new ArrayList<>(List.of(builtInFargate(region), builtInFargateSpot(region))); result.addAll(capacityProviders.values()); - return result; + return new DescribeCapacityProvidersResult(result, List.of()); } - return providers.stream() - .map(p -> { - if ("FARGATE".equals(p)) { return builtInFargate(); } - if ("FARGATE_SPOT".equals(p)) { return builtInFargateSpot(); } - return capacityProviders.getOrDefault(p, - capacityProviders.values().stream() - .filter(cp -> cp.getCapacityProviderArn().equals(p)) - .findFirst().orElse(null)); - }) - .filter(cp -> cp != null) - .toList(); + List found = new ArrayList<>(); + List failures = new ArrayList<>(); + for (String ref : providers) { + CapacityProvider cp = switch (ref) { + case "FARGATE" -> builtInFargate(region); + case "FARGATE_SPOT" -> builtInFargateSpot(region); + default -> capacityProviders.getOrDefault(ref, + capacityProviders.values().stream() + .filter(p -> ref.equals(p.getCapacityProviderArn())) + .findFirst().orElse(null)); + }; + if (cp == null) { + failures.add(Failure.missing(ref.startsWith("arn:") ? ref + : regionResolver.buildArn("ecs", region, "capacity-provider/" + ref))); + continue; + } + found.add(cp); + } + return new DescribeCapacityProvidersResult(found, failures); } - private CapacityProvider builtInFargate() { - CapacityProvider cp = new CapacityProvider(); - cp.setName("FARGATE"); - cp.setStatus("ACTIVE"); - return cp; + /** The cluster a capacity provider is attached to, or {@code null} when none is. */ + private String clusterUsingCapacityProvider(String name) { + return clusters.values().stream() + .filter(c -> c.getCapacityProviders() != null && c.getCapacityProviders().contains(name)) + .map(EcsCluster::getClusterName) + .findFirst().orElse(null); } - private CapacityProvider builtInFargateSpot() { + /** + * The first active service whose capacity provider strategy still names {@code cp}, by name or + * by ARN, or {@code null}. DeleteCapacityProvider requires the provider to be out of every + * service's strategy, not only out of every cluster. A deleted service is INACTIVE and holds + * nothing back. + */ + private String serviceUsingCapacityProvider(CapacityProvider cp) { + return services.values().stream() + .filter(svc -> !"INACTIVE".equals(svc.getStatus())) + .filter(svc -> svc.getCapacityProviderStrategy() != null + && svc.getCapacityProviderStrategy().stream() + .anyMatch(item -> cp.getName().equals(item.capacityProvider()) + || cp.getCapacityProviderArn().equals(item.capacityProvider()))) + .map(EcsServiceModel::getServiceName) + .findFirst().orElse(null); + } + + /** + * "Up to 255 characters are allowed. They include letters (both upper and lowercase letters), + * numbers, underscores (_), and hyphens (-). The name can't be prefixed with aws, ecs, or + * fargate." + */ + private static void validateCapacityProviderName(String name) { + if (name == null || name.isBlank()) { + throw new AwsException("InvalidParameterException", + "Capacity provider name is required.", 400); + } + if (name.length() > MAX_CAPACITY_PROVIDER_NAME_LENGTH + || !CAPACITY_PROVIDER_NAME_PATTERN.matcher(name).matches()) { + throw new AwsException("InvalidParameterException", + "Capacity provider names can be up to " + MAX_CAPACITY_PROVIDER_NAME_LENGTH + + " characters long and contain letters, numbers, underscores and " + + "hyphens only.", 400); + } + String lower = name.toLowerCase(Locale.ROOT); + for (String reserved : RESERVED_CAPACITY_PROVIDER_PREFIXES) { + if (lower.startsWith(reserved)) { + throw new AwsException("InvalidParameterException", + "Capacity provider names can't be prefixed with \"aws\", \"ecs\" or " + + "\"fargate\".", 400); + } + } + } + + private CapacityProvider builtInFargate(String region) { + return builtInCapacityProvider("FARGATE", region); + } + + private CapacityProvider builtInFargateSpot(String region) { + return builtInCapacityProvider("FARGATE_SPOT", region); + } + + private CapacityProvider builtInCapacityProvider(String name, String region) { CapacityProvider cp = new CapacityProvider(); - cp.setName("FARGATE_SPOT"); + cp.setName(name); cp.setStatus("ACTIVE"); + cp.setType(name); + cp.setCapacityProviderArn(regionResolver.buildArn("ecs", region, "capacity-provider/" + name)); return cp; } diff --git a/src/main/java/io/github/hectorvent/floci/services/ecs/model/CapacityProvider.java b/src/main/java/io/github/hectorvent/floci/services/ecs/model/CapacityProvider.java index 080124da3c..c3b7cdd85d 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ecs/model/CapacityProvider.java +++ b/src/main/java/io/github/hectorvent/floci/services/ecs/model/CapacityProvider.java @@ -11,6 +11,13 @@ public class CapacityProvider { private String capacityProviderArn; private String name; private String status; + /** + * {@code CREATE_COMPLETE}, {@code DELETE_IN_PROGRESS} and the rest. Separate from + * {@link #status}, whose only values are PROVISIONING, ACTIVE, DEPROVISIONING and INACTIVE: + * a delete leaves the provider ACTIVE and reports its progress here. + */ + private String updateStatus; + private String type; private Map autoScalingGroupProvider; private Map tags = new HashMap<>(); @@ -23,6 +30,12 @@ public class CapacityProvider { public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } + public String getUpdateStatus() { return updateStatus; } + public void setUpdateStatus(String updateStatus) { this.updateStatus = updateStatus; } + + public String getType() { return type; } + public void setType(String type) { this.type = type; } + public Map getAutoScalingGroupProvider() { return autoScalingGroupProvider; } public void setAutoScalingGroupProvider(Map autoScalingGroupProvider) { this.autoScalingGroupProvider = autoScalingGroupProvider; diff --git a/src/main/java/io/github/hectorvent/floci/services/ecs/model/CreateServiceRequest.java b/src/main/java/io/github/hectorvent/floci/services/ecs/model/CreateServiceRequest.java index a1d9a8753e..e6c17c233f 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ecs/model/CreateServiceRequest.java +++ b/src/main/java/io/github/hectorvent/floci/services/ecs/model/CreateServiceRequest.java @@ -15,13 +15,23 @@ public class CreateServiceRequest { private int desiredCount = 1; private LaunchType launchType; private List capacityProviderStrategy; + private String platformVersion; private List loadBalancers; + private List> serviceRegistries; private NetworkConfiguration networkConfiguration; private Map tags; private String schedulingStrategy; private String deploymentControllerType; private String availabilityZoneRebalancing; private Map serviceConnectConfiguration; + private Map deploymentConfiguration; + private boolean enableExecuteCommand; + private boolean enableECSManagedTags; + private String propagateTags; + private Integer healthCheckGracePeriodSeconds; + private String roleArn; + /** Members Floci does not act on, such as placement constraints and strategies. */ + private Map unparsed; public String getCluster() { return cluster; } public void setCluster(String cluster) { this.cluster = cluster; } @@ -43,9 +53,17 @@ public class CreateServiceRequest { this.capacityProviderStrategy = capacityProviderStrategy; } + public String getPlatformVersion() { return platformVersion; } + public void setPlatformVersion(String platformVersion) { this.platformVersion = platformVersion; } + public List getLoadBalancers() { return loadBalancers; } public void setLoadBalancers(List loadBalancers) { this.loadBalancers = loadBalancers; } + public List> getServiceRegistries() { return serviceRegistries; } + public void setServiceRegistries(List> serviceRegistries) { + this.serviceRegistries = serviceRegistries; + } + public NetworkConfiguration getNetworkConfiguration() { return networkConfiguration; } public void setNetworkConfiguration(NetworkConfiguration networkConfiguration) { this.networkConfiguration = networkConfiguration; @@ -72,4 +90,32 @@ public class CreateServiceRequest { this.serviceConnectConfiguration = serviceConnectConfiguration; } + public Map getDeploymentConfiguration() { return deploymentConfiguration; } + public void setDeploymentConfiguration(Map deploymentConfiguration) { + this.deploymentConfiguration = deploymentConfiguration; + } + + public boolean isEnableExecuteCommand() { return enableExecuteCommand; } + public void setEnableExecuteCommand(boolean enableExecuteCommand) { + this.enableExecuteCommand = enableExecuteCommand; + } + + public boolean isEnableECSManagedTags() { return enableECSManagedTags; } + public void setEnableECSManagedTags(boolean enableECSManagedTags) { + this.enableECSManagedTags = enableECSManagedTags; + } + + public String getPropagateTags() { return propagateTags; } + public void setPropagateTags(String propagateTags) { this.propagateTags = propagateTags; } + + public Integer getHealthCheckGracePeriodSeconds() { return healthCheckGracePeriodSeconds; } + public void setHealthCheckGracePeriodSeconds(Integer healthCheckGracePeriodSeconds) { + this.healthCheckGracePeriodSeconds = healthCheckGracePeriodSeconds; + } + + public String getRoleArn() { return roleArn; } + public void setRoleArn(String roleArn) { this.roleArn = roleArn; } + + public Map getUnparsed() { return unparsed; } + public void setUnparsed(Map unparsed) { this.unparsed = unparsed; } } diff --git a/src/main/java/io/github/hectorvent/floci/services/ecs/model/EcsServiceModel.java b/src/main/java/io/github/hectorvent/floci/services/ecs/model/EcsServiceModel.java index a04c05a71f..7b03251288 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ecs/model/EcsServiceModel.java +++ b/src/main/java/io/github/hectorvent/floci/services/ecs/model/EcsServiceModel.java @@ -40,7 +40,20 @@ public class EcsServiceModel { * it; the Service shape itself has no member for it. */ private Map serviceConnectConfiguration; + private String platformVersion; + private String platformFamily; private List capacityProviderStrategy; + private boolean enableExecuteCommand; + private boolean enableECSManagedTags; + private String propagateTags; + private Integer healthCheckGracePeriodSeconds; + private String roleArn; + /** {@code deploymentConfiguration}, kept raw: Floci reports it but runs no rollout against it. */ + private Map deploymentConfiguration; + /** {@code serviceRegistries}, kept raw: Cloud Map registration is not emulated. */ + private List> serviceRegistries; + /** Members Floci does not act on, kept verbatim so DescribeServices round-trips. */ + private Map unparsed; public String getServiceArn() { return serviceArn; } public void setServiceArn(String serviceArn) { this.serviceArn = serviceArn; } @@ -114,9 +127,48 @@ public class EcsServiceModel { this.serviceConnectConfiguration = serviceConnectConfiguration; } + public String getPlatformVersion() { return platformVersion; } + public void setPlatformVersion(String platformVersion) { this.platformVersion = platformVersion; } + + public String getPlatformFamily() { return platformFamily; } + public void setPlatformFamily(String platformFamily) { this.platformFamily = platformFamily; } + public List getCapacityProviderStrategy() { return capacityProviderStrategy; } public void setCapacityProviderStrategy(List capacityProviderStrategy) { this.capacityProviderStrategy = capacityProviderStrategy; } + public boolean isEnableExecuteCommand() { return enableExecuteCommand; } + public void setEnableExecuteCommand(boolean enableExecuteCommand) { + this.enableExecuteCommand = enableExecuteCommand; + } + + public boolean isEnableECSManagedTags() { return enableECSManagedTags; } + public void setEnableECSManagedTags(boolean enableECSManagedTags) { + this.enableECSManagedTags = enableECSManagedTags; + } + + public String getPropagateTags() { return propagateTags; } + public void setPropagateTags(String propagateTags) { this.propagateTags = propagateTags; } + + public Integer getHealthCheckGracePeriodSeconds() { return healthCheckGracePeriodSeconds; } + public void setHealthCheckGracePeriodSeconds(Integer healthCheckGracePeriodSeconds) { + this.healthCheckGracePeriodSeconds = healthCheckGracePeriodSeconds; + } + + public String getRoleArn() { return roleArn; } + public void setRoleArn(String roleArn) { this.roleArn = roleArn; } + + public Map getDeploymentConfiguration() { return deploymentConfiguration; } + public void setDeploymentConfiguration(Map deploymentConfiguration) { + this.deploymentConfiguration = deploymentConfiguration; + } + + public List> getServiceRegistries() { return serviceRegistries; } + public void setServiceRegistries(List> serviceRegistries) { + this.serviceRegistries = serviceRegistries; + } + + public Map getUnparsed() { return unparsed; } + public void setUnparsed(Map unparsed) { this.unparsed = unparsed; } } diff --git a/src/main/java/io/github/hectorvent/floci/services/ecs/model/UpdateServiceRequest.java b/src/main/java/io/github/hectorvent/floci/services/ecs/model/UpdateServiceRequest.java index 0f6202ab49..21f5051c42 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ecs/model/UpdateServiceRequest.java +++ b/src/main/java/io/github/hectorvent/floci/services/ecs/model/UpdateServiceRequest.java @@ -23,6 +23,15 @@ public class UpdateServiceRequest { private boolean forceNewDeployment; private Map serviceConnectConfiguration; private List capacityProviderStrategy; + private String platformVersion; + private Boolean enableExecuteCommand; + private Boolean enableECSManagedTags; + private String propagateTags; + private Integer healthCheckGracePeriodSeconds; + private Map deploymentConfiguration; + private List loadBalancers; + private List> serviceRegistries; + private Map unparsed; public String getCluster() { return cluster; } public void setCluster(String cluster) { this.cluster = cluster; } @@ -59,4 +68,40 @@ public class UpdateServiceRequest { this.capacityProviderStrategy = capacityProviderStrategy; } + public String getPlatformVersion() { return platformVersion; } + public void setPlatformVersion(String platformVersion) { this.platformVersion = platformVersion; } + + public Boolean getEnableExecuteCommand() { return enableExecuteCommand; } + public void setEnableExecuteCommand(Boolean enableExecuteCommand) { + this.enableExecuteCommand = enableExecuteCommand; + } + + public Boolean getEnableECSManagedTags() { return enableECSManagedTags; } + public void setEnableECSManagedTags(Boolean enableECSManagedTags) { + this.enableECSManagedTags = enableECSManagedTags; + } + + public String getPropagateTags() { return propagateTags; } + public void setPropagateTags(String propagateTags) { this.propagateTags = propagateTags; } + + public Integer getHealthCheckGracePeriodSeconds() { return healthCheckGracePeriodSeconds; } + public void setHealthCheckGracePeriodSeconds(Integer healthCheckGracePeriodSeconds) { + this.healthCheckGracePeriodSeconds = healthCheckGracePeriodSeconds; + } + + public Map getDeploymentConfiguration() { return deploymentConfiguration; } + public void setDeploymentConfiguration(Map deploymentConfiguration) { + this.deploymentConfiguration = deploymentConfiguration; + } + + public List getLoadBalancers() { return loadBalancers; } + public void setLoadBalancers(List loadBalancers) { this.loadBalancers = loadBalancers; } + + public List> getServiceRegistries() { return serviceRegistries; } + public void setServiceRegistries(List> serviceRegistries) { + this.serviceRegistries = serviceRegistries; + } + + public Map getUnparsed() { return unparsed; } + public void setUnparsed(Map unparsed) { this.unparsed = unparsed; } } 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 index 4732aff4e6..4bdd265040 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationEcsCapacityIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationEcsCapacityIntegrationTest.java @@ -102,13 +102,12 @@ class CloudFormationEcsCapacityIntegrationTest { .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. + // One provider still, carrying the updated tag value and the updated scaling target. String providers = describeCapacityProviders(providerName); assertThat(providers, containsString(providerName)); assertThat(providers, containsString("infra")); assertThat(providers, not(containsString("platform"))); + assertThat(providers, containsString("\"targetCapacity\":40")); } @Test @@ -135,7 +134,11 @@ class CloudFormationEcsCapacityIntegrationTest { assertThat(settled, containsString("DELETE_COMPLETE")); // The capacity provider must be deregistered, not left behind by an unsupported delete. - assertThat(describeCapacityProviders(providerName), not(containsString(providerName))); + // A name that resolves to nothing comes back as a MISSING failure, so the provider is + // gone when the describe returns no providers at all. + String afterDelete = describeCapacityProviders(providerName); + assertThat(afterDelete, containsString("\"capacityProviders\":[]")); + assertThat(afterDelete, containsString("\"reason\":\"MISSING\"")); } private static String template(String clusterName, String providerName) { @@ -190,11 +193,12 @@ class CloudFormationEcsCapacityIntegrationTest { return xml.substring(xml.indexOf("") + "".length(), xml.indexOf("")); } + /** Asks for TAGS explicitly: without the include, AWS leaves them out of the response. */ private String describeCapacityProviders(String providerName) { return given() .header("X-Amz-Target", ECS_TARGET + "DescribeCapacityProviders") .contentType(ECS_CT) - .body("{\"capacityProviders\":[\"" + providerName + "\"]}") + .body("{\"capacityProviders\":[\"" + providerName + "\"],\"include\":[\"TAGS\"]}") .when() .post("/") .then() diff --git a/src/test/java/io/github/hectorvent/floci/services/ecs/EcsFargateEdgeCaseIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ecs/EcsFargateEdgeCaseIntegrationTest.java index f466162fa9..28a1f83020 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ecs/EcsFargateEdgeCaseIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ecs/EcsFargateEdgeCaseIntegrationTest.java @@ -425,8 +425,95 @@ class EcsFargateEdgeCaseIntegrationTest { "the attachment must carry the details AWS reports, got: " + names); } + @Test + void aCreatedServiceReportsTheDocumentedDefaults() { + String family = seed("edge-service-defaults"); + + call("CreateService", "{\"cluster\":\"" + CLUSTER + "\",\"serviceName\":\"edge-defaults-svc\"," + + "\"taskDefinition\":\"" + family + "\",\"desiredCount\":0,\"launchType\":\"FARGATE\"," + + NETWORK + "}", 200) + .then() + .body("service.propagateTags", equalTo("NONE")) + .body("service.healthCheckGracePeriodSeconds", equalTo(0)) + .body("service.enableExecuteCommand", equalTo(false)) + .body("service.enableECSManagedTags", equalTo(false)); + } + + @Test + void aServiceRoleIsOnlyPermittedWithALoadBalancerAndWithoutAwsvpc() { + String family = seed("edge-service-role"); + + call("CreateService", "{\"cluster\":\"" + CLUSTER + "\",\"serviceName\":\"edge-role-svc\"," + + "\"taskDefinition\":\"" + family + "\",\"desiredCount\":0,\"launchType\":\"FARGATE\"," + + NETWORK + ",\"role\":\"arn:aws:iam::000000000000:role/ecsServiceRole\"}", 400) + .then().body("message", containsString("role parameter")); + } + // ── Service updates ────────────────────────────────────────────────────── + @Test + void onlyTheDocumentedUpdatesRollTheServiceDeployment() { + String family = seed("edge-update-rolls"); + call("CreateService", "{\"cluster\":\"" + CLUSTER + "\",\"serviceName\":\"edge-roll-svc\"," + + "\"taskDefinition\":\"" + family + "\",\"desiredCount\":0,\"launchType\":\"FARGATE\"," + + NETWORK + "}", 200); + + String initial = deploymentId("edge-roll-svc"); + + // desiredCount and the exec switch are documented as not triggering a deployment. + call("UpdateService", "{\"cluster\":\"" + CLUSTER + "\",\"service\":\"edge-roll-svc\"," + + "\"desiredCount\":0,\"enableExecuteCommand\":true}", 200); + assertEquals(initial, deploymentId("edge-roll-svc"), + "desiredCount and enableExecuteCommand must not roll the deployment"); + + // A changed network configuration starts new tasks, so it rolls. + call("UpdateService", "{\"cluster\":\"" + CLUSTER + "\",\"service\":\"edge-roll-svc\"," + + "\"networkConfiguration\":{\"awsvpcConfiguration\":{\"subnets\":" + + "[\"subnet-default-us-east-1-b\"]}}}", 200); + assertNotEquals(initial, deploymentId("edge-roll-svc"), + "a changed network configuration must roll the deployment"); + + // platformVersion is documented as triggering a deployment, but only where it changes: + // LATEST on a service already running the version LATEST resolves to is not a change. + String rolled = deploymentId("edge-roll-svc"); + call("UpdateService", "{\"cluster\":\"" + CLUSTER + "\",\"service\":\"edge-roll-svc\"," + + "\"platformVersion\":\"LATEST\"}", 200); + assertEquals(rolled, deploymentId("edge-roll-svc"), + "LATEST on a service already at the resolved version must not roll the deployment"); + + call("UpdateService", "{\"cluster\":\"" + CLUSTER + "\",\"service\":\"edge-roll-svc\"," + + "\"platformVersion\":\"1.3.0\"}", 200) + .then().body("service.platformVersion", equalTo("1.3.0")); + assertNotEquals(rolled, deploymentId("edge-roll-svc"), + "a changed platformVersion must roll the deployment"); + } + + @Test + void anUpdateReplacesOnlyTheMembersItNames() { + String family = seed("edge-update-members"); + call("CreateService", "{\"cluster\":\"" + CLUSTER + "\",\"serviceName\":\"edge-members-svc\"," + + "\"taskDefinition\":\"" + family + "\",\"desiredCount\":0,\"launchType\":\"FARGATE\"," + + NETWORK + ",\"placementConstraints\":[{\"type\":\"distinctInstance\"}]}", 200) + .then().body("service.placementConstraints[0].type", equalTo("distinctInstance")); + + call("UpdateService", "{\"cluster\":\"" + CLUSTER + "\",\"service\":\"edge-members-svc\"," + + "\"placementStrategy\":[{\"type\":\"spread\"," + + "\"field\":\"attribute:ecs.availability-zone\"}]}", 200) + .then().body("service.placementStrategy[0].type", equalTo("spread")) + .body("service.placementConstraints[0].type", equalTo("distinctInstance")); + + call("DescribeServices", "{\"cluster\":\"" + CLUSTER + + "\",\"services\":[\"edge-members-svc\"]}", 200) + .then().body("services[0].placementConstraints[0].type", equalTo("distinctInstance")) + .body("services[0].placementStrategy[0].type", equalTo("spread")); + + // A member the update does name is replaced outright, which is how an empty array clears it. + call("UpdateService", "{\"cluster\":\"" + CLUSTER + "\",\"service\":\"edge-members-svc\"," + + "\"placementConstraints\":[]}", 200) + .then().body("service.placementConstraints", hasSize(0)) + .body("service.placementStrategy[0].type", equalTo("spread")); + } + private static String deploymentId(String serviceName) { return call("DescribeServices", "{\"cluster\":\"" + CLUSTER + "\",\"services\":[\"" + serviceName + "\"]}", 200) @@ -534,6 +621,104 @@ class EcsFargateEdgeCaseIntegrationTest { // ── Capacity providers ─────────────────────────────────────────────────── + @Test + void capacityProviderNamesCannotUseTheReservedPrefixes() { + for (String reserved : List.of("aws-edge-cp", "ecs-edge-cp", "fargate-edge-cp")) { + call("CreateCapacityProvider", "{\"name\":\"" + reserved + "\"," + + "\"autoScalingGroupProvider\":{\"autoScalingGroupArn\":\"arn:aws:autoscaling:" + + "us-east-1:000000000000:autoScalingGroup:x:autoScalingGroupName/asg-x\"}}", 400) + .then().body("message", containsString("prefixed")); + } + call("CreateCapacityProvider", "{\"name\":\"edge cp with spaces\"," + + "\"autoScalingGroupProvider\":{\"autoScalingGroupArn\":\"arn:aws:autoscaling:" + + "us-east-1:000000000000:autoScalingGroup:x:autoScalingGroupName/asg-x\"}}", 400); + } + + @Test + void aCapacityProviderRoundTripsItsGroupAndGatesItsTags() { + String name = "edge-cp-roundtrip"; + call("CreateCapacityProvider", "{\"name\":\"" + name + "\"," + + "\"autoScalingGroupProvider\":{\"autoScalingGroupArn\":\"arn:aws:autoscaling:" + + "us-east-1:000000000000:autoScalingGroup:x:autoScalingGroupName/asg-x\"," + + "\"managedScaling\":{\"status\":\"ENABLED\",\"targetCapacity\":75}}," + + "\"tags\":[{\"key\":\"owner\",\"value\":\"platform\"}]}", 200) + .then() + .body("capacityProvider.type", equalTo("EC2_AUTOSCALING")) + .body("capacityProvider.capacityProviderArn", containsString("capacity-provider/" + name)); + + call("DescribeCapacityProviders", "{\"capacityProviders\":[\"" + name + "\"]}", 200) + .then() + .body("capacityProviders[0].autoScalingGroupProvider.managedScaling.targetCapacity", + equalTo(75)) + // Tags are held back until the request asks for them. + .body("capacityProviders[0].tags", nullValue()); + + call("DescribeCapacityProviders", "{\"capacityProviders\":[\"" + name + + "\"],\"include\":[\"TAGS\"]}", 200) + .then().body("capacityProviders[0].tags", hasSize(1)); + } + + @Test + void anUnknownCapacityProviderIsAFailureAndTheFargateOnesCannotBeDeleted() { + call("DescribeCapacityProviders", "{\"capacityProviders\":[\"edge-cp-nope\"]}", 200) + .then() + .body("capacityProviders", hasSize(0)) + .body("failures", hasSize(1)) + .body("failures[0].reason", equalTo("MISSING")) + .body("failures[0].arn", containsString("capacity-provider/edge-cp-nope")); + + call("DescribeCapacityProviders", "{\"capacityProviders\":[\"FARGATE\"]}", 200) + .then() + .body("capacityProviders[0].type", equalTo("FARGATE")) + .body("capacityProviders[0].capacityProviderArn", + containsString("capacity-provider/FARGATE")); + + call("DeleteCapacityProvider", "{\"capacityProvider\":\"FARGATE\"}", 400) + .then().body("message", containsString("reserved")); + } + + @Test + void aCapacityProviderAttachedToAClusterCannotBeDeleted() { + String cluster = "edge-cp-attached-cluster"; + String name = "edge-cp-attached"; + call("CreateCapacityProvider", "{\"name\":\"" + name + "\"," + + "\"autoScalingGroupProvider\":{\"autoScalingGroupArn\":\"arn:aws:autoscaling:" + + "us-east-1:000000000000:autoScalingGroup:x:autoScalingGroupName/asg-x\"}}", 200); + call("CreateCluster", "{\"clusterName\":\"" + cluster + "\",\"capacityProviders\":[\"" + + name + "\"]}", 200); + + call("DeleteCapacityProvider", "{\"capacityProvider\":\"" + name + "\"}", 400) + .then().body("message", containsString(cluster)); + + call("PutClusterCapacityProviders", "{\"cluster\":\"" + cluster + "\"," + + "\"capacityProviders\":[],\"defaultCapacityProviderStrategy\":[]}", 200); + call("DeleteCapacityProvider", "{\"capacityProvider\":\"" + name + "\"}", 200) + .then().body("capacityProvider.updateStatus", equalTo("DELETE_IN_PROGRESS")) + // DELETE_IN_PROGRESS is an updateStatus, never one of the four status values. + .body("capacityProvider.status", equalTo("ACTIVE")); + } + + @Test + void aCapacityProviderInAServiceStrategyCannotBeDeleted() { + String family = seed("edge-cp-in-service"); + String name = "edge-cp-in-strategy"; + call("CreateCapacityProvider", "{\"name\":\"" + name + "\"," + + "\"autoScalingGroupProvider\":{\"autoScalingGroupArn\":\"arn:aws:autoscaling:" + + "us-east-1:000000000000:autoScalingGroup:y:autoScalingGroupName/asg-y\"}}", 200); + call("CreateService", "{\"cluster\":\"" + CLUSTER + "\",\"serviceName\":\"edge-cp-svc\"," + + "\"taskDefinition\":\"" + family + "\",\"desiredCount\":0," + NETWORK + "," + + "\"capacityProviderStrategy\":[{\"capacityProvider\":\"" + name + + "\",\"weight\":1}]}", 200); + + // The provider is in no cluster, so only the service's strategy holds the delete back. + call("DeleteCapacityProvider", "{\"capacityProvider\":\"" + name + "\"}", 400) + .then().body("message", containsString("edge-cp-svc")); + + call("DeleteService", "{\"cluster\":\"" + CLUSTER + "\",\"service\":\"edge-cp-svc\"}", 200); + call("DeleteCapacityProvider", "{\"capacityProvider\":\"" + name + "\"}", 200) + .then().body("capacityProvider.updateStatus", equalTo("DELETE_IN_PROGRESS")); + } + // ── Round trips the parser used to drop ────────────────────────────────── @Test diff --git a/src/test/java/io/github/hectorvent/floci/services/ecs/EcsFargateTaskIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ecs/EcsFargateTaskIntegrationTest.java index 3fa89e6928..373fd4bc8f 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ecs/EcsFargateTaskIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ecs/EcsFargateTaskIntegrationTest.java @@ -250,6 +250,33 @@ class EcsFargateTaskIntegrationTest { .then().body("message", containsString("Network Configuration must be provided")); } + @Test + void createServiceReportsThePlatformAndExecCommandMembers() { + String family = seed("fargate-service-members"); + call("CreateService", "{\"cluster\":\"" + CLUSTER + "\",\"serviceName\":\"fargate-members-svc\"," + + "\"taskDefinition\":\"" + family + "\",\"desiredCount\":0,\"launchType\":\"FARGATE\"," + + NETWORK + ",\"platformVersion\":\"LATEST\",\"enableExecuteCommand\":true," + + "\"enableECSManagedTags\":true,\"propagateTags\":\"SERVICE\"," + + "\"healthCheckGracePeriodSeconds\":30," + + "\"deploymentConfiguration\":{\"maximumPercent\":200,\"minimumHealthyPercent\":100}}", 200) + .then() + .body("service.platformVersion", equalTo("1.4.0")) + .body("service.platformFamily", equalTo("Linux")) + .body("service.enableExecuteCommand", equalTo(true)) + .body("service.enableECSManagedTags", equalTo(true)) + .body("service.propagateTags", equalTo("SERVICE")) + .body("service.healthCheckGracePeriodSeconds", equalTo(30)) + .body("service.deploymentConfiguration.maximumPercent", equalTo(200)) + .body("service.deploymentConfiguration.minimumHealthyPercent", equalTo(100)); + + call("DescribeServices", "{\"cluster\":\"" + CLUSTER + + "\",\"services\":[\"fargate-members-svc\"]}", 200) + .then() + .body("services[0].platformVersion", equalTo("1.4.0")) + .body("services[0].enableExecuteCommand", equalTo(true)) + .body("services[0].deploymentConfiguration.minimumHealthyPercent", equalTo(100)); + } + @Test void createServiceOnACapacityProviderStrategyReportsItInsteadOfALaunchType() { String family = seed("fargate-service-strategy");