diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/EcsFargateTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/EcsFargateTest.java index 6a12e16986..bb1ed53c1c 100644 --- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/EcsFargateTest.java +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/EcsFargateTest.java @@ -12,15 +12,20 @@ import software.amazon.awssdk.services.ec2.model.DescribeSubnetsRequest; import software.amazon.awssdk.services.ecs.EcsClient; import software.amazon.awssdk.services.ecs.model.AwsVpcConfiguration; import software.amazon.awssdk.services.ecs.model.CapacityProviderStrategyItem; +import software.amazon.awssdk.services.ecs.model.Cluster; +import software.amazon.awssdk.services.ecs.model.ClusterField; import software.amazon.awssdk.services.ecs.model.Compatibility; import software.amazon.awssdk.services.ecs.model.ContainerDefinition; import software.amazon.awssdk.services.ecs.model.CreateClusterRequest; import software.amazon.awssdk.services.ecs.model.DeleteTaskDefinitionsRequest; import software.amazon.awssdk.services.ecs.model.DeregisterTaskDefinitionRequest; +import software.amazon.awssdk.services.ecs.model.DescribeClustersRequest; +import software.amazon.awssdk.services.ecs.model.DescribeClustersResponse; import software.amazon.awssdk.services.ecs.model.DescribeTaskDefinitionRequest; import software.amazon.awssdk.services.ecs.model.DescribeTasksRequest; import software.amazon.awssdk.services.ecs.model.DescribeTasksResponse; import software.amazon.awssdk.services.ecs.model.EcsException; +import software.amazon.awssdk.services.ecs.model.KeyValuePair; import software.amazon.awssdk.services.ecs.model.EphemeralStorage; import software.amazon.awssdk.services.ecs.model.LaunchType; import software.amazon.awssdk.services.ecs.model.NetworkConfiguration; @@ -208,8 +213,36 @@ class EcsFargateTest { @Test @Order(6) - @DisplayName("DescribeTasks - an unknown reference comes back as MISSING") + @DisplayName("DescribeClusters - include gates the optional members and statistics deserialize") + void describeClustersHonoursInclude() { + Cluster bare = ecs.describeClusters(DescribeClustersRequest.builder() + .clusters(clusterName).build()).clusters().get(0); + assertThat(bare.statistics()).isEmpty(); + assertThat(bare.hasStatistics()).isFalse(); + assertThat(bare.hasTags()).isFalse(); + + Cluster full = ecs.describeClusters(DescribeClustersRequest.builder() + .clusters(clusterName) + .include(ClusterField.STATISTICS, ClusterField.SETTINGS, ClusterField.TAGS, + ClusterField.ATTACHMENTS, ClusterField.CONFIGURATIONS) + .build()).clusters().get(0); + assertThat(full.hasStatistics()).isTrue(); + assertThat(full.statistics()).extracting(KeyValuePair::name) + .contains("runningFargateTasksCount", "runningEC2TasksCount", + "activeFargateServiceCount", "drainingEC2ServiceCount"); + assertThat(full.hasAttachments()).isTrue(); + } + + @Test + @Order(7) + @DisplayName("DescribeClusters and DescribeTasks - an unknown reference comes back as MISSING") void describeReportsMissingRatherThanDroppingTheReference() { + DescribeClustersResponse clusters = ecs.describeClusters(DescribeClustersRequest.builder() + .clusters(clusterName, "sdk-no-such-cluster").build()); + assertThat(clusters.clusters()).hasSize(1); + assertThat(clusters.failures()).singleElement() + .satisfies(failure -> assertThat(failure.reason()).isEqualTo("MISSING")); + DescribeTasksResponse tasks = ecs.describeTasks(DescribeTasksRequest.builder() .cluster(clusterName) .tasks("00000000000000000000000000000000") diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/EcsTests.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/EcsTests.java index b2acdfb6ca..3a84ee6dc0 100644 --- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/EcsTests.java +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/EcsTests.java @@ -508,7 +508,11 @@ class EcsTests { @Order(25) @DisplayName("PutAttributes - set attributes") void putAttributes() { - String targetId = cluster.clusterArn(); + // An attribute targets a container instance of the cluster; ECS rejects anything else with + // a TargetNotFoundException, so this test registers one rather than aiming at the cluster. + String targetId = ecs.registerContainerInstance(RegisterContainerInstanceRequest.builder() + .cluster(clusterName) + .build()).containerInstance().containerInstanceArn(); List stored = ecs.putAttributes(PutAttributesRequest.builder() .cluster(clusterName) .attributes( @@ -534,6 +538,14 @@ class EcsTests { .build()).attributes(); assertThat(deleted).isNotEmpty(); + + // The instance existed only as an attribute target. Deregister it, because ECS refuses to + // delete a cluster that still has one and the delete-cluster tests below rely on that. + ecs.deregisterContainerInstance(DeregisterContainerInstanceRequest.builder() + .cluster(clusterName) + .containerInstance(targetId) + .force(true) + .build()); } @Test @@ -919,12 +931,24 @@ class EcsTests { @Test @Order(50) - @DisplayName("CreateTaskSet - create task set") + @DisplayName("CreateTaskSet - the full lifecycle on an EXTERNAL-controller service") void createTaskSet() { + // Task sets only exist on a service that uses the EXTERNAL or CODE_DEPLOY deployment + // controller; the rolling service the rest of this class uses cannot hold one. + String externalService = serviceName + "-external"; + ecs.createService(CreateServiceRequest.builder() + .cluster(clusterName) + .serviceName(externalService) + .taskDefinition(family + ":1") + .desiredCount(3) + .deploymentController(dc -> dc.type(DeploymentControllerType.EXTERNAL)) + .launchType(LaunchType.FARGATE) + .build()); + software.amazon.awssdk.services.ecs.model.TaskSet ts = ecs.createTaskSet(CreateTaskSetRequest.builder() .cluster(clusterName) - .service(serviceName) + .service(externalService) .taskDefinition(family + ":1") .launchType(LaunchType.FARGATE) .scale(Scale.builder().value(50.0).unit(ScaleUnit.PERCENT).build()) @@ -933,6 +957,13 @@ class EcsTests { assertThat(ts).isNotNull(); assertThat(ts.taskSetArn()).isNotNull(); assertThat(ts.status()).isEqualTo("ACTIVE"); + // 3 desired at 50 percent is 1.5, which ECS rounds up. + assertThat(ts.computedDesiredCount()).isEqualTo(2); + // Floci places no tasks for a task set, so it reports steady rather than stabilising + // towards a count nothing will reach: a client waiting for stability would never return. + assertThat(ts.stabilityStatus()).isEqualTo(StabilityStatus.STEADY_STATE); + assertThat(ts.stabilityStatusAt()).isNotNull(); + assertThat(ts.platformVersion()).isNotBlank(); String taskSetArn = ts.taskSetArn(); @@ -940,45 +971,68 @@ class EcsTests { List sets = ecs.describeTaskSets(DescribeTaskSetsRequest.builder() .cluster(clusterName) - .service(serviceName) + .service(externalService) .taskSets(taskSetArn) .build()).taskSets(); assertThat(sets).hasSize(1); assertThat(sets.get(0).taskSetArn()).isEqualTo(taskSetArn); + // An unknown task set is a MISSING failure, not a dropped reference. + DescribeTaskSetsResponse missing = ecs.describeTaskSets(DescribeTaskSetsRequest.builder() + .cluster(clusterName) + .service(externalService) + .taskSets("ecs-svc/does-not-exist") + .build()); + assertThat(missing.taskSets()).isEmpty(); + assertThat(missing.failures()).singleElement() + .satisfies(failure -> assertThat(failure.reason()).isEqualTo("MISSING")); + // Update task set software.amazon.awssdk.services.ecs.model.TaskSet updated = ecs.updateTaskSet(UpdateTaskSetRequest.builder() .cluster(clusterName) - .service(serviceName) + .service(externalService) .taskSet(taskSetArn) .scale(Scale.builder().value(100.0).unit(ScaleUnit.PERCENT).build()) .build()).taskSet(); assertThat(updated).isNotNull(); assertThat(updated.scale().value()).isEqualTo(100.0); + assertThat(updated.computedDesiredCount()).isEqualTo(3); // Update primary task set software.amazon.awssdk.services.ecs.model.TaskSet primary = ecs.updateServicePrimaryTaskSet(UpdateServicePrimaryTaskSetRequest.builder() .cluster(clusterName) - .service(serviceName) + .service(externalService) .primaryTaskSet(taskSetArn) .build()).taskSet(); assertThat(primary).isNotNull(); assertThat(primary.status()).isEqualTo("PRIMARY"); - // Delete task set + // A task set that has not been scaled down to zero needs force to delete. + assertThatThrownBy(() -> ecs.deleteTaskSet(DeleteTaskSetRequest.builder() + .cluster(clusterName) + .service(externalService) + .taskSet(taskSetArn) + .build())) + .isInstanceOf(EcsException.class) + .hasMessageContaining("scaled down to zero"); + software.amazon.awssdk.services.ecs.model.TaskSet deleted = ecs.deleteTaskSet(DeleteTaskSetRequest.builder() .cluster(clusterName) - .service(serviceName) + .service(externalService) .taskSet(taskSetArn) + .force(true) .build()).taskSet(); - assertThat(deleted).isNotNull(); + assertThat(deleted.status()).isEqualTo("DRAINING"); + + ecs.deleteService(DeleteServiceRequest.builder() + .cluster(clusterName).service(externalService).force(true).build()); } @Test diff --git a/docs/services/ecs.md b/docs/services/ecs.md index a4a7fa37a4..23ef13b771 100644 --- a/docs/services/ecs.md +++ b/docs/services/ecs.md @@ -24,6 +24,33 @@ what the caller asked for nor what AWS answers. | `PutClusterCapacityProviders` | Associate capacity providers with a cluster | | `DeleteCluster` | Delete an empty cluster | +A cluster round-trips what it was created with: `settings`, `tags`, `configuration`, +`serviceConnectDefaults`, `capacityProviders` and `defaultCapacityProviderStrategy` are all +accepted on `CreateCluster` and returned as sent. `UpdateCluster` replaces only the members the +request named, leaving the ones it omits alone; `UpdateClusterSettings` replaces `settings` +outright. + +`DescribeClusters` returns `settings`, `tags`, `statistics`, `attachments` and `configuration` +only when `include` asks for them, one of `SETTINGS`, `TAGS`, `STATISTICS`, `ATTACHMENTS` and +`CONFIGURATIONS`; any other value is rejected. A member that was asked for is returned even when +it is empty, so a client can tell an empty answer from a withheld one. `STATISTICS` reports the +eight documented counts split by launch type (`runningEC2TasksCount`, `runningFargateTasksCount`, +`pendingEC2TasksCount`, `pendingFargateTasksCount`, `activeEC2ServiceCount`, +`activeFargateServiceCount`, `drainingEC2ServiceCount`, `drainingFargateServiceCount`) as +name/value strings. The API reference spells one of those names `RunningFargateTasksCount`; Floci +follows the wire, which is lower camel case like the other seven. `ATTACHMENTS` is always an empty +list, because Floci creates no managed scaling policies to attach. + +`DescribeClusters` reports a cluster it cannot resolve as a `MISSING` entry in `failures` rather +than dropping it, as `DescribeServices` and `DescribeTasks` do. `ListClusters` pages with +`maxResults` (1 to 100) and `nextToken`, returning up to 100 ARNs when the request names neither. + +`DeleteCluster` only deletes an empty cluster, and says which way it is not empty: +`ClusterContainsServicesException` while a service is still `ACTIVE`, +`ClusterContainsContainerInstancesException` while a container instance is still registered, and +`ClusterContainsTasksException` while a task is still running. Delete the services, deregister the +instances and stop the tasks first, as on AWS. + ### Task Definitions | Operation | Description | @@ -78,6 +105,15 @@ call. A deleted revision is not dropped, because AWS keeps describing it and the it keep running; it just cannot start anything new, so `RunTask`, `CreateService` and `UpdateService` refuse it. +`ListTaskDefinitions` lists only `ACTIVE` revisions unless another `status` is asked for, orders +them lexicographically by family and then numerically by revision (`sort: DESC` reverses it, so +revision 11 sorts after revision 2 rather than before it), and pages with `maxResults` and +`nextToken`. + +`ListTaskDefinitionFamilies` filters on `familyPrefix` and on `status`, where `ACTIVE` keeps the +families with at least one ACTIVE revision, `INACTIVE` the families with none, and `ALL` (the +default) keeps both. It pages with `maxResults` and `nextToken` the same way. + At launch, a container's `dependsOn` decides the start order, and a `COMPLETE`, `SUCCESS` or `HEALTHY` condition holds the dependent container until the dependency gets there. The wait is bounded by the dependent container's `startTimeout`, defaulting to 60 seconds rather than AWS's @@ -199,10 +235,26 @@ A created service reports the documented defaults: `propagateTags` is `NONE` and a load-balanced service whose task definition does not use `awsvpc`, which is the only case AWS permits it in. +A described service always carries `events` and `taskSets`, empty list and all, so a client can +tell an empty answer from a member Floci never wrote. `taskSets` holds the service's task sets, the +same ones `DescribeTaskSets` returns, which is where a blue/green deploy tool reads them from. +`events` is derived from the service's current state rather than replayed from a rollout, the same +way `deployments` is: a service that has converged reports the one event tools poll for, +`(service ) has reached a steady state.`, with an id stable across calls; one still +converging reports none. Each `deployments` entry carries the placement it runs under, its +`launchType` or `capacityProviderStrategy`, `platformVersion`, `platformFamily` and +`networkConfiguration`, not only its id and counts. + `RunTask` places at most 10 tasks per call and rejects `propagateTags: SERVICE`, which is a service-only option; `TASK_DEFINITION` copies the task definition's tags onto each task. `StartTask` requires the `containerInstances` it places onto, at most 10 of them. +`ListTasks` filters by `cluster`, `family`, `desiredStatus`, `launchType`, `containerInstance`, +`serviceName` and `startedBy`, and pages with `maxResults` and `nextToken` (100 per page by +default). The default filter is a desired status of `RUNNING`, so a listing that has not asked for +stopped tasks does not get them, `PENDING` matches nothing (ECS never sets that desired status), +and `startedBy` has to be the only filter in the request. + 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, `platformVersion` and `forceNewDeployment`. The ones AWS documents as not @@ -256,6 +308,10 @@ local cluster has no container instances, so an EC2 default would have nowhere t | `ListServices` | List service ARNs in a cluster | | `ListServicesByNamespace` | List services filtered by Cloud Map namespace | +`ListServices` filters on `launchType` and `schedulingStrategy` as well as `cluster`, and pages +with `maxResults` and `nextToken`. Unlike every other ECS listing, which pages a hundred at a +time, a request that names no `maxResults` gets ten ARNs and a `nextToken`. + #### Service deployments An `ACTIVE` service reports exactly one `PRIMARY` entry in `services[].deployments`, @@ -297,6 +353,7 @@ Known differences from AWS: 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. +- `StopServiceDeployment` is not implemented. #### ECS EventBridge events @@ -342,6 +399,30 @@ unchanged. | `DescribeTaskSets` | Describe task sets for a service | | `UpdateServicePrimaryTaskSet` | Promote a task set to primary | +A task set can only be created in a service whose deployment controller is `EXTERNAL` or +`CODE_DEPLOY`; a rolling service runs its own deployments, and AWS refuses the call rather than +creating a task set nothing will place. `launchType` and `capacityProviderStrategy` are mutually +exclusive, and a request naming neither takes the cluster's `defaultCapacityProviderStrategy`, +falling back to `EC2`. `scale` accepts only the `PERCENT` unit. + +The task set round-trips `networkConfiguration` (defaulting to the service's), `loadBalancers`, +`serviceRegistries`, `platformVersion` and `tags`, and reports `platformFamily`, `startedBy` +(`CODE_DEPLOY` for a task set Floci's CodeDeploy created, unset for an external one) and +`stabilityStatusAt`. `computedDesiredCount` is the service's `desiredCount` times the task set's +scale percentage, always rounded up: 3 desired at 50 percent is 2 tasks, not 1. `UpdateTaskSet` +recomputes it. + +Floci places no tasks for a task set, so `runningCount` and `pendingCount` stay at 0 and +`stabilityStatus` is always `STEADY_STATE`. On AWS the status reaches `STEADY_STATE` once the +running count matches the computed one; reporting `STABILIZING` here would hang anything that +waits for the set to stabilise, since no count ever moves. + +`DeleteTaskSet` refuses a task set that has not been scaled down to zero unless `force` is set. +`DescribeTaskSets` returns tags only for `include: ["TAGS"]` and reports a reference naming no +task set of that service as a `MISSING` failure. A task set reference that resolves to nothing is +a `TaskSetNotFoundException`, and task sets are scoped to one cluster and service: another +service's task set is not visible through this one. + ### Container Instances | Operation | Description | @@ -353,6 +434,32 @@ unchanged. | `UpdateContainerAgent` | Trigger agent update (stub) | | `UpdateContainerInstancesState` | Drain or activate container instances | +`RegisterContainerInstance` keeps what the agent sent: `totalResources` comes back as both +`registeredResources` and `remainingResources`, and `versionInfo`, `attributes`, `tags` and a +re-registered `containerInstanceArn` all round-trip. The agent version is reported inside +`versionInfo`, which is where the `ContainerInstance` shape puts it, not as a top-level +`agentVersion`. An instance also reports `registeredAt` and a `version` counter that each state +change increments. + +`DeregisterContainerInstance` leaves the instance in the cluster as `INACTIVE` rather than +dropping it, so a later `DescribeContainerInstances` still answers for it, as on AWS. A cluster's +`registeredContainerInstancesCount` counts only the `ACTIVE` and `DRAINING` instances. + +`ListContainerInstances` defaults to every instance other than the `INACTIVE` ones, validates +`status` against the five documented values, and pages with `maxResults` (1 to 100) and +`nextToken`. The cluster query language `filter` is accepted and ignored. + +`UpdateContainerInstancesState` sets only `ACTIVE` or `DRAINING`, takes at most 10 instances per +call, and refuses to drain an instance that is not `ACTIVE` first. It and +`DescribeContainerInstances` report an instance the cluster does not have as a `MISSING` failure +rather than dropping it. + +`DescribeContainerInstances` withholds two members until the request asks for them, and rejects an +`include` value that is neither: `TAGS` for the instance's tags, and `CONTAINER_INSTANCE_HEALTH` +for its `healthStatus`. Floci runs no agent health checks of its own, so the one check it reports +is `AGENT_CONNECTIVITY`, taken from the registration state the instance already tracks, and +`overallStatus` follows it. + ### Capacity Providers | Operation | Description | @@ -388,6 +495,23 @@ one of the four values `CapacityProviderStatus` takes. | `ListServiceDeployments` | List service deployment ARNs | | `DescribeServiceRevisions` | Describe service revisions | +A deployment is recorded on `CreateService` and on every `UpdateService` that rolls one, together +with the service revision it targets. The two are linked the way AWS links them: a deployment +reports `targetServiceRevision` (its ARN and the task counts) and `sourceServiceRevisions`, and +the service itself reports `currentServiceDeployment` and `currentServiceRevisions`, so a caller +gets from `DescribeServices` to the deployment without listing first. A service deployment carries +no `taskDefinition` member, because AWS's `ServiceDeployment` shape has none: the revision names +it. + +A service revision is the snapshot of the service's configuration at that moment, copied rather +than referenced, so it keeps reporting what the service looked like then: `taskDefinition`, the +`launchType` or `capacityProviderStrategy`, `platformVersion`, `platformFamily`, +`networkConfiguration`, `loadBalancers`, `serviceRegistries`, `serviceConnectConfiguration` and +one `containerImages` entry per container definition. `guardDutyEnabled` is always `false`: Floci +runs no runtime monitoring. Floci applies a change in place rather than rolling it, so a +deployment is `SUCCESSFUL` with the same `startedAt` and `finishedAt` from the moment it is +recorded. Both describes report an ARN that resolves to nothing as a `MISSING` failure. + ### Tags | Operation | Description | @@ -412,6 +536,32 @@ parsed map, so 51 entries that collapse to fewer distinct keys are still rejecte | `DeleteAttributes` | Remove attributes from resources | | `ListAttributes` | List resources with a given attribute | +An account setting name must be one of the eleven ECS accepts, and its value is checked against +what that name allows: `0`, `7` or `14` for `fargateTaskRetirementWaitPeriod`, `blocking` or +`non-blocking` for `defaultLogDriverMode`, `enhanced` on top of the usual flags for +`containerInsights`, and `enabled`/`disabled`/`on`/`off` for the rest. A `Setting` reports its +`principalArn` and its `type`, which is `user` except for `guardDutyActivate`, the setting +GuardDuty owns on the account's behalf. + +A request that names no `principalArn` acts for the account root, since Floci does not +authenticate a separate user, and `PutAccountSettingDefault` writes that same root row: AWS +describes the effective value as "the account settings for the root user or the default setting". +`ListAccountSettings` returns only the settings the principal explicitly set, which is why an +untouched account lists nothing; with `effectiveSettings: true` it returns all eleven at the value +that principal actually reads, falling back from its own setting to the root default to the +setting's built-in default. It pages with `maxResults` (1 to 10) and `nextToken`, ten at a time. + +A setting is persisted under `::` rather than the name alone, so settings +written by an earlier Floci version are ignored after upgrading: delete +`ecs-account-settings.json` from the persistence directory, or write the settings again. + +Attributes belong to a cluster, not to a target id alone, so the same container instance id in two +clusters is two targets. An attribute must name a container instance the cluster has, or the call +is a `TargetNotFoundException`, and a target holds at most 10 custom attributes +(`AttributeLimitExceededException` past that, and for a single call carrying more than 10). +`ListAttributes` requires `targetType`, whose only valid value is `container-instance`, and pages +with `maxResults` (1 to 100) and `nextToken`. + ### Agent / State Change Stubs | Operation | Description | diff --git a/src/main/java/io/github/hectorvent/floci/services/codedeploy/CodeDeployService.java b/src/main/java/io/github/hectorvent/floci/services/codedeploy/CodeDeployService.java index 66414e3c97..e196f60da6 100644 --- a/src/main/java/io/github/hectorvent/floci/services/codedeploy/CodeDeployService.java +++ b/src/main/java/io/github/hectorvent/floci/services/codedeploy/CodeDeployService.java @@ -1363,8 +1363,10 @@ public class CodeDeployService { createTaskSet.setService(serviceName); createTaskSet.setTaskDefinition(appSpec.taskDefinition); createTaskSet.setScaleValue(100.0); - createTaskSet.setScaleUnit("PERCENT"); + // ECS reports the deployment id as the task set's externalId, and CODE_DEPLOY as + // its startedBy, which is how a client tells a CodeDeploy set from an external one. createTaskSet.setExternalId(deploymentId); + createTaskSet.setStartedBy("CODE_DEPLOY"); greenTaskSet = ecsService.createTaskSet(createTaskSet, region); appendTaskSetInfo(ecsTargetMap, greenTaskSet, greenTgArn, 0.0); finishLifecycleEvent(installEvent, "Succeeded"); 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 28f1bf0077..1e24b23636 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 @@ -15,7 +15,9 @@ import io.github.hectorvent.floci.services.ecs.model.ContainerOverride; import io.github.hectorvent.floci.services.ecs.model.CreateClusterRequest; import io.github.hectorvent.floci.services.ecs.model.CreateServiceRequest; import io.github.hectorvent.floci.services.ecs.model.CreateTaskSetRequest; +import io.github.hectorvent.floci.services.ecs.model.RegisterContainerInstanceRequest; import io.github.hectorvent.floci.services.ecs.model.EnvironmentFile; +import io.github.hectorvent.floci.services.ecs.model.Failure; import io.github.hectorvent.floci.services.ecs.model.EphemeralStorage; import io.github.hectorvent.floci.services.ecs.model.FirelensConfiguration; import io.github.hectorvent.floci.services.ecs.model.HealthCheck; @@ -171,6 +173,8 @@ public class EcsJsonHandler { request.setClusterName(req.has("clusterName") ? req.path("clusterName").asText() : null); request.setTags(parseTagMap(req.path("tags"))); request.setSettings(parseClusterSettings(req.path("settings"))); + request.setConfiguration(parseRawObject(req.path("configuration"))); + request.setServiceConnectDefaults(parseRawObject(req.path("serviceConnectDefaults"))); if (req.has("capacityProviders")) { request.setCapacityProviders(jsonArrayToList(req.path("capacityProviders"))); } @@ -185,22 +189,50 @@ public class EcsJsonHandler { } private Response handleDescribeClusters(JsonNode req, String region) { - List ids = jsonArrayToList(req.path("clusters")); - List found = service.describeClusters(ids, region); + List clusterIds = jsonArrayToList(req.path("clusters")); + Set include = parseClusterIncludes(req.path("include")); + EcsService.DescribeClustersResult found = service.describeClustersDetailed(clusterIds, region); ObjectNode resp = objectMapper.createObjectNode(); ArrayNode arr = objectMapper.createArrayNode(); - found.forEach(c -> arr.add(writer.clusterNode(c))); + found.clusters().forEach(c -> arr.add(writer.clusterNode(c, include))); resp.set("clusters", arr); - resp.set("failures", objectMapper.createArrayNode()); + ArrayNode failures = objectMapper.createArrayNode(); + found.failures().forEach(f -> failures.add(writer.failureNode(f))); + resp.set("failures", failures); return Response.ok(resp).build(); } + /** Rejects an unknown include the way ECS does, rather than silently returning less. */ + private Set parseClusterIncludes(JsonNode node) { + List requested = jsonArrayToList(node); + validateIncludes(requested, EcsResponseWriter.ALL_CLUSTER_INCLUDES); + return Set.copyOf(requested); + } + + /** The two fields DescribeContainerInstances withholds unless the request asks for them. */ + private static final Set CONTAINER_INSTANCE_INCLUDES = + Set.of("TAGS", "CONTAINER_INSTANCE_HEALTH"); + + private static void validateIncludes(List requested, Set allowed) { + for (String value : requested) { + if (!allowed.contains(value)) { + throw new AwsException("InvalidParameterException", + "Invalid include value: " + value, 400); + } + } + } + private Response handleListClusters(JsonNode req, String region) { - List arns = service.listClusters(region); + Integer maxResults = req.hasNonNull("maxResults") ? req.path("maxResults").asInt() : null; + String nextToken = req.hasNonNull("nextToken") ? req.path("nextToken").asText() : null; + EcsService.ListPage page = service.listClusters(maxResults, nextToken, region); ObjectNode resp = objectMapper.createObjectNode(); ArrayNode arr = objectMapper.createArrayNode(); - arns.forEach(arr::add); + page.arns().forEach(arr::add); resp.set("clusterArns", arr); + if (page.nextToken() != null) { + resp.put("nextToken", page.nextToken()); + } return Response.ok(resp).build(); } @@ -215,7 +247,9 @@ public class EcsJsonHandler { private Response handleUpdateCluster(JsonNode req, String region) { String clusterId = req.path("cluster").asText(); List settings = parseClusterSettings(req.path("settings")); - EcsCluster cluster = service.updateCluster(clusterId, settings, region); + EcsCluster cluster = service.updateCluster(clusterId, settings, + parseRawObject(req.path("configuration")), + parseRawObject(req.path("serviceConnectDefaults")), region); ObjectNode resp = objectMapper.createObjectNode(); resp.set("cluster", writer.clusterNode(cluster)); return Response.ok(resp).build(); @@ -292,22 +326,40 @@ public class EcsJsonHandler { private Response handleListTaskDefinitions(JsonNode req, String region) { String familyPrefix = req.has("familyPrefix") ? req.path("familyPrefix").asText() : null; - String status = req.has("status") ? req.path("status").asText() : null; - List arns = service.listTaskDefinitions(familyPrefix, status); + String status = parseChoice(req, "status", TASK_DEFINITION_STATUSES); + String sort = parseChoice(req, "sort", SORT_ORDERS); + Integer maxResults = req.hasNonNull("maxResults") ? req.path("maxResults").asInt() : null; + String nextToken = req.hasNonNull("nextToken") ? req.path("nextToken").asText() : null; + + EcsService.ListPage page = service.listTaskDefinitions(familyPrefix, status, sort, + maxResults, nextToken); + ObjectNode resp = objectMapper.createObjectNode(); ArrayNode arr = objectMapper.createArrayNode(); - arns.forEach(arr::add); + page.arns().forEach(arr::add); resp.set("taskDefinitionArns", arr); + if (page.nextToken() != null) { + resp.put("nextToken", page.nextToken()); + } return Response.ok(resp).build(); } private Response handleListTaskDefinitionFamilies(JsonNode req, String region) { String familyPrefix = req.has("familyPrefix") ? req.path("familyPrefix").asText() : null; - List families = service.listTaskDefinitionFamilies(familyPrefix); + String status = parseChoice(req, "status", FAMILY_STATUSES); + Integer maxResults = req.hasNonNull("maxResults") ? req.path("maxResults").asInt() : null; + String nextToken = req.hasNonNull("nextToken") ? req.path("nextToken").asText() : null; + + EcsService.ListPage page = service.listTaskDefinitionFamilies(familyPrefix, status, + maxResults, nextToken); + ObjectNode resp = objectMapper.createObjectNode(); ArrayNode arr = objectMapper.createArrayNode(); - families.forEach(arr::add); + page.arns().forEach(arr::add); resp.set("families", arr); + if (page.nextToken() != null) { + resp.put("nextToken", page.nextToken()); + } return Response.ok(resp).build(); } @@ -409,16 +461,25 @@ public class EcsJsonHandler { private Response handleListTasks(JsonNode req, String region) { ListTasksRequest request = new ListTasksRequest(); request.setCluster(req.has("cluster") ? req.path("cluster").asText() : null); + request.setContainerInstance(req.hasNonNull("containerInstance") + ? req.path("containerInstance").asText() : null); + request.setDesiredStatus(parseChoice(req, "desiredStatus", DESIRED_STATUSES)); request.setFamily(req.has("family") ? req.path("family").asText() : null); - request.setDesiredStatus(req.has("desiredStatus") ? req.path("desiredStatus").asText() : null); + request.setLaunchType(parseEnum(req, "launchType", LaunchType.class)); request.setServiceName(req.has("serviceName") ? req.path("serviceName").asText() : null); + request.setStartedBy(req.hasNonNull("startedBy") ? req.path("startedBy").asText() : null); + request.setMaxResults(req.hasNonNull("maxResults") ? req.path("maxResults").asInt() : null); + request.setNextToken(req.hasNonNull("nextToken") ? req.path("nextToken").asText() : null); - List arns = service.listTasks(request, region); + EcsService.ListPage result = service.listTasks(request, region); ObjectNode resp = objectMapper.createObjectNode(); ArrayNode arr = objectMapper.createArrayNode(); - arns.forEach(arr::add); + result.arns().forEach(arr::add); resp.set("taskArns", arr); + if (result.nextToken() != null) { + resp.put("nextToken", result.nextToken()); + } return Response.ok(resp).build(); } @@ -635,12 +696,21 @@ public class EcsJsonHandler { private Response handleListServices(JsonNode req, String region) { String cluster = req.has("cluster") ? req.path("cluster").asText() : null; - List arns = service.listServices(cluster, region); + LaunchType launchType = parseEnum(req, "launchType", LaunchType.class); + String schedulingStrategy = parseChoice(req, "schedulingStrategy", SCHEDULING_STRATEGIES); + Integer maxResults = req.hasNonNull("maxResults") ? req.path("maxResults").asInt() : null; + String nextToken = req.hasNonNull("nextToken") ? req.path("nextToken").asText() : null; + + EcsService.ListPage page = service.listServices(cluster, launchType, schedulingStrategy, + maxResults, nextToken, region); ObjectNode resp = objectMapper.createObjectNode(); ArrayNode arr = objectMapper.createArrayNode(); - arns.forEach(arr::add); + page.arns().forEach(arr::add); resp.set("serviceArns", arr); + if (page.nextToken() != null) { + resp.put("nextToken", page.nextToken()); + } return Response.ok(resp).build(); } @@ -682,42 +752,51 @@ public class EcsJsonHandler { // ── Account Settings ────────────────────────────────────────────────────── private Response handlePutAccountSetting(JsonNode req, String region) { - String name = req.path("name").asText(); - String value = req.path("value").asText(); - var entry = service.putAccountSetting(name, value); + EcsService.AccountSetting setting = service.putAccountSetting( + req.path("name").asText(), req.path("value").asText(), principalArn(req)); ObjectNode resp = objectMapper.createObjectNode(); - resp.set("setting", writer.settingNode(entry.getKey(), entry.getValue())); + resp.set("setting", writer.settingNode(setting)); return Response.ok(resp).build(); } private Response handlePutAccountSettingDefault(JsonNode req, String region) { - String name = req.path("name").asText(); - String value = req.path("value").asText(); - var entry = service.putAccountSettingDefault(name, value); + EcsService.AccountSetting setting = service.putAccountSettingDefault( + req.path("name").asText(), req.path("value").asText()); ObjectNode resp = objectMapper.createObjectNode(); - resp.set("setting", writer.settingNode(entry.getKey(), entry.getValue())); + resp.set("setting", writer.settingNode(setting)); return Response.ok(resp).build(); } private Response handleDeleteAccountSetting(JsonNode req, String region) { - String name = req.path("name").asText(); - var entry = service.deleteAccountSetting(name); + EcsService.AccountSetting setting = + service.deleteAccountSetting(req.path("name").asText(), principalArn(req)); ObjectNode resp = objectMapper.createObjectNode(); - resp.set("setting", writer.settingNode(entry.getKey(), entry.getValue())); + resp.set("setting", writer.settingNode(setting)); return Response.ok(resp).build(); } private Response handleListAccountSettings(JsonNode req, String region) { - String filterName = req.has("name") ? req.path("name").asText() : null; - String filterValue = req.has("value") ? req.path("value").asText() : null; - var settings = service.listAccountSettings(filterName, filterValue); + EcsService.AccountSettingPage page = service.listAccountSettings( + req.hasNonNull("name") ? req.path("name").asText() : null, + req.hasNonNull("value") ? req.path("value").asText() : null, + principalArn(req), + req.path("effectiveSettings").asBoolean(false), + req.hasNonNull("maxResults") ? req.path("maxResults").asInt() : null, + req.hasNonNull("nextToken") ? req.path("nextToken").asText() : null); ObjectNode resp = objectMapper.createObjectNode(); ArrayNode arr = objectMapper.createArrayNode(); - settings.forEach(e -> arr.add(writer.settingNode(e.getKey(), e.getValue()))); + page.settings().forEach(s -> arr.add(writer.settingNode(s))); resp.set("settings", arr); + if (page.nextToken() != null) { + resp.put("nextToken", page.nextToken()); + } return Response.ok(resp).build(); } + private static String principalArn(JsonNode req) { + return req.hasNonNull("principalArn") ? req.path("principalArn").asText() : null; + } + // ── Attributes ──────────────────────────────────────────────────────────── private Response handlePutAttributes(JsonNode req, String region) { @@ -744,25 +823,44 @@ public class EcsJsonHandler { private Response handleListAttributes(JsonNode req, String region) { String cluster = req.has("cluster") ? req.path("cluster").asText() : null; - String targetType = req.has("targetType") ? req.path("targetType").asText() : null; - String attributeName = req.has("attributeName") ? req.path("attributeName").asText() : null; - String attributeValue = req.has("attributeValue") ? req.path("attributeValue").asText() : null; - List result = service.listAttributes(cluster, targetType, attributeName, attributeValue, region); + String targetType = req.hasNonNull("targetType") ? req.path("targetType").asText() : null; + String attributeName = req.hasNonNull("attributeName") ? req.path("attributeName").asText() : null; + String attributeValue = req.hasNonNull("attributeValue") ? req.path("attributeValue").asText() : null; + Integer maxResults = req.hasNonNull("maxResults") ? req.path("maxResults").asInt() : null; + String nextToken = req.hasNonNull("nextToken") ? req.path("nextToken").asText() : null; + + EcsService.ListAttributesPage page = service.listAttributes(cluster, targetType, + attributeName, attributeValue, maxResults, nextToken, region); + ObjectNode resp = objectMapper.createObjectNode(); ArrayNode arr = objectMapper.createArrayNode(); - result.forEach(a -> arr.add(writer.attributeNode(a))); + page.attributes().forEach(a -> arr.add(writer.attributeNode(a))); resp.set("attributes", arr); + if (page.nextToken() != null) { + resp.put("nextToken", page.nextToken()); + } return Response.ok(resp).build(); } // ── Container Instances ─────────────────────────────────────────────────── private Response handleRegisterContainerInstance(JsonNode req, String region) { - String cluster = req.has("cluster") ? req.path("cluster").asText() : null; - String instanceIdentityDocument = req.has("instanceIdentityDocument") - ? req.path("instanceIdentityDocument").asText() : null; - List attrs = parseAttributes(req.path("attributes")); - ContainerInstance instance = service.registerContainerInstance(cluster, instanceIdentityDocument, attrs, region); + RegisterContainerInstanceRequest request = new RegisterContainerInstanceRequest(); + request.setCluster(req.has("cluster") ? req.path("cluster").asText() : null); + request.setContainerInstanceArn(req.hasNonNull("containerInstanceArn") + ? req.path("containerInstanceArn").asText() : null); + request.setInstanceIdentityDocument(req.hasNonNull("instanceIdentityDocument") + ? req.path("instanceIdentityDocument").asText() : null); + request.setAttributes(parseAttributes(req.path("attributes"))); + if (req.has("totalResources")) { + request.setTotalResources(parseRawObjectList(req.path("totalResources"))); + } + request.setVersionInfo(parseRawObject(req.path("versionInfo"))); + if (req.has("platformDevices")) { + request.setPlatformDevices(parseRawObjectList(req.path("platformDevices"))); + } + request.setTags(parseTagMap(req.path("tags"))); + ContainerInstance instance = service.registerContainerInstance(request, region); ObjectNode resp = objectMapper.createObjectNode(); resp.set("containerInstance", writer.containerInstanceNode(instance)); return Response.ok(resp).build(); @@ -781,23 +879,37 @@ public class EcsJsonHandler { private Response handleDescribeContainerInstances(JsonNode req, String region) { String cluster = req.has("cluster") ? req.path("cluster").asText() : null; List instanceRefs = jsonArrayToList(req.path("containerInstances")); - List found = service.describeContainerInstances(cluster, instanceRefs, region); + List include = jsonArrayToList(req.path("include")); + validateIncludes(include, CONTAINER_INSTANCE_INCLUDES); + boolean includeTags = include.contains("TAGS"); + boolean includeHealth = include.contains("CONTAINER_INSTANCE_HEALTH"); + EcsService.DescribeContainerInstancesResult found = + service.describeContainerInstancesDetailed(cluster, instanceRefs, region); ObjectNode resp = objectMapper.createObjectNode(); ArrayNode arr = objectMapper.createArrayNode(); - found.forEach(ci -> arr.add(writer.containerInstanceNode(ci))); + found.instances().forEach(ci -> + arr.add(writer.containerInstanceNode(ci, includeTags, includeHealth))); resp.set("containerInstances", arr); - resp.set("failures", objectMapper.createArrayNode()); + ArrayNode failures = objectMapper.createArrayNode(); + found.failures().forEach(f -> failures.add(writer.failureNode(f))); + resp.set("failures", failures); return Response.ok(resp).build(); } private Response handleListContainerInstances(JsonNode req, String region) { String cluster = req.has("cluster") ? req.path("cluster").asText() : null; - String status = req.has("status") ? req.path("status").asText() : null; - List arns = service.listContainerInstances(cluster, status, region); + String status = parseChoice(req, "status", CONTAINER_INSTANCE_STATUSES); + Integer maxResults = req.hasNonNull("maxResults") ? req.path("maxResults").asInt() : null; + String nextToken = req.hasNonNull("nextToken") ? req.path("nextToken").asText() : null; + EcsService.ListPage page = + service.listContainerInstances(cluster, status, maxResults, nextToken, region); ObjectNode resp = objectMapper.createObjectNode(); ArrayNode arr = objectMapper.createArrayNode(); - arns.forEach(arr::add); + page.arns().forEach(arr::add); resp.set("containerInstanceArns", arr); + if (page.nextToken() != null) { + resp.put("nextToken", page.nextToken()); + } return Response.ok(resp).build(); } @@ -814,12 +926,15 @@ public class EcsJsonHandler { String cluster = req.has("cluster") ? req.path("cluster").asText() : null; List instanceRefs = jsonArrayToList(req.path("containerInstances")); String status = req.path("status").asText(); - List updated = service.updateContainerInstancesState(cluster, instanceRefs, status, region); + EcsService.UpdateContainerInstancesStateResult updated = + service.updateContainerInstancesState(cluster, instanceRefs, status, region); ObjectNode resp = objectMapper.createObjectNode(); ArrayNode arr = objectMapper.createArrayNode(); - updated.forEach(ci -> arr.add(writer.containerInstanceNode(ci))); + updated.instances().forEach(ci -> arr.add(writer.containerInstanceNode(ci))); resp.set("containerInstances", arr); - resp.set("failures", objectMapper.createArrayNode()); + ArrayNode failures = objectMapper.createArrayNode(); + updated.failures().forEach(f -> failures.add(writer.failureNode(f))); + resp.set("failures", failures); return Response.ok(resp).build(); } @@ -875,9 +990,21 @@ public class EcsJsonHandler { request.setService(req.path("service").asText()); request.setTaskDefinition(req.path("taskDefinition").asText()); request.setLaunchType(parseEnum(req, "launchType", LaunchType.class)); - request.setScaleValue(req.path("scale").path("value").asDouble(100.0)); - request.setScaleUnit(req.path("scale").path("unit").asText("PERCENT")); + request.setCapacityProviderStrategy( + parseCapacityProviderStrategy(req.path("capacityProviderStrategy"))); + request.setPlatformVersion(req.hasNonNull("platformVersion") + ? req.path("platformVersion").asText() : null); + if (req.hasNonNull("scale")) { + request.setScaleValue(req.path("scale").path("value").asDouble(100.0)); + request.setScaleUnit(req.path("scale").hasNonNull("unit") + ? req.path("scale").path("unit").asText() : null); + } request.setExternalId(req.has("externalId") ? req.path("externalId").asText() : null); + request.setNetworkConfiguration(parseNetworkConfiguration(req.path("networkConfiguration"))); + request.setLoadBalancers(parseLoadBalancers(req.path("loadBalancers"))); + request.setServiceRegistries(req.has("serviceRegistries") + ? parseRawObjectList(req.path("serviceRegistries")) : null); + request.setTags(parseTagMap(req.path("tags"))); TaskSet ts = service.createTaskSet(request, region); @@ -891,7 +1018,8 @@ public class EcsJsonHandler { String svc = req.path("service").asText(); String taskSet = req.path("taskSet").asText(); double scaleValue = req.path("scale").path("value").asDouble(100.0); - String scaleUnit = req.path("scale").path("unit").asText("PERCENT"); + String scaleUnit = req.path("scale").hasNonNull("unit") + ? req.path("scale").path("unit").asText() : null; TaskSet ts = service.updateTaskSet(cluster, svc, taskSet, scaleValue, scaleUnit, region); @@ -917,13 +1045,18 @@ public class EcsJsonHandler { String cluster = req.has("cluster") ? req.path("cluster").asText() : null; String svc = req.path("service").asText(); List taskSetRefs = req.has("taskSets") ? jsonArrayToList(req.path("taskSets")) : null; + boolean includeTags = jsonArrayToList(req.path("include")).contains("TAGS"); - List found = service.describeTaskSets(cluster, svc, taskSetRefs, region); + EcsService.DescribeTaskSetsResult found = + service.describeTaskSetsDetailed(cluster, svc, taskSetRefs, region); ObjectNode resp = objectMapper.createObjectNode(); ArrayNode arr = objectMapper.createArrayNode(); - found.forEach(ts -> arr.add(writer.taskSetNode(ts))); + found.taskSets().forEach(ts -> arr.add(writer.taskSetNode(ts, includeTags))); resp.set("taskSets", arr); + ArrayNode failures = objectMapper.createArrayNode(); + found.failures().forEach(f -> failures.add(writer.failureNode(f))); + resp.set("failures", failures); return Response.ok(resp).build(); } @@ -948,9 +1081,20 @@ public class EcsJsonHandler { ArrayNode arr = objectMapper.createArrayNode(); found.forEach(d -> arr.add(writer.serviceDeploymentNode(d))); resp.set("serviceDeployments", arr); + resp.set("failures", missingFailures(arns, + found.stream().map(ServiceDeployment::getServiceDeploymentArn).toList())); return Response.ok(resp).build(); } + /** The references that resolved to nothing, reported as ECS reports them rather than dropped. */ + private ArrayNode missingFailures(List requested, List resolved) { + ArrayNode failures = objectMapper.createArrayNode(); + requested.stream() + .filter(arn -> !resolved.contains(arn)) + .forEach(arn -> failures.add(writer.failureNode(Failure.missing(arn)))); + return failures; + } + private Response handleListServiceDeployments(JsonNode req, String region) { String svc = req.path("service").asText(); String cluster = req.has("cluster") ? req.path("cluster").asText() : null; @@ -967,7 +1111,11 @@ public class EcsJsonHandler { brief.put("clusterArn", d.getClusterArn()); brief.put("status", d.getStatus()); if (d.getCreatedAt() != null) { brief.put("createdAt", d.getCreatedAt().toEpochMilli() / 1000.0); } - if (d.getUpdatedAt() != null) { brief.put("finishedAt", d.getUpdatedAt().toEpochMilli() / 1000.0); } + if (d.getStartedAt() != null) { brief.put("startedAt", d.getStartedAt().toEpochMilli() / 1000.0); } + if (d.getFinishedAt() != null) { brief.put("finishedAt", d.getFinishedAt().toEpochMilli() / 1000.0); } + if (d.getTargetServiceRevisionArn() != null) { + brief.put("targetServiceRevisionArn", d.getTargetServiceRevisionArn()); + } arr.add(brief); }); resp.set("serviceDeployments", arr); @@ -981,6 +1129,8 @@ public class EcsJsonHandler { ArrayNode arr = objectMapper.createArrayNode(); found.forEach(r -> arr.add(writer.serviceRevisionNode(r))); resp.set("serviceRevisions", arr); + resp.set("failures", missingFailures(arns, + found.stream().map(ServiceRevision::getServiceRevisionArn).toList())); return Response.ok(resp).build(); } @@ -1540,10 +1690,17 @@ public class EcsJsonHandler { Set.of("EC2", "FARGATE", "EXTERNAL", "MANAGED_INSTANCES"); private static final Set PID_MODES = Set.of("host", "task"); private static final Set IPC_MODES = Set.of("host", "task", "none"); + private static final Set CONTAINER_INSTANCE_STATUSES = + Set.of("ACTIVE", "DRAINING", "REGISTERING", "DEREGISTERING", "REGISTRATION_FAILED"); private static final Set SCHEDULING_STRATEGIES = Set.of("REPLICA", "DAEMON"); private static final Set DEPLOYMENT_CONTROLLER_TYPES = Set.of("ECS", "CODE_DEPLOY", "EXTERNAL"); private static final Set AZ_REBALANCING = Set.of("ENABLED", "DISABLED"); private static final Set PROPAGATE_TAGS = Set.of("TASK_DEFINITION", "SERVICE", "NONE"); + private static final Set DESIRED_STATUSES = Set.of("RUNNING", "PENDING", "STOPPED"); + private static final Set TASK_DEFINITION_STATUSES = + Set.of("ACTIVE", "INACTIVE", "DELETE_IN_PROGRESS"); + private static final Set SORT_ORDERS = Set.of("ASC", "DESC"); + private static final Set FAMILY_STATUSES = Set.of("ACTIVE", "INACTIVE", "ALL"); private static final Set DEPENDENCY_CONDITIONS = Set.of( ContainerDependency.START, ContainerDependency.COMPLETE, ContainerDependency.SUCCESS, ContainerDependency.HEALTHY); 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 6da158a178..59c0bdebb0 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 @@ -7,6 +7,7 @@ import io.github.hectorvent.floci.services.ecs.model.CapacityProviderStrategyIte import io.github.hectorvent.floci.services.ecs.model.Container; import io.github.hectorvent.floci.services.ecs.model.ContainerDefinition; import io.github.hectorvent.floci.services.ecs.model.ContainerDependency; +import io.github.hectorvent.floci.services.ecs.model.ContainerImage; import io.github.hectorvent.floci.services.ecs.model.ContainerInstance; import io.github.hectorvent.floci.services.ecs.model.ContainerOverride; import io.github.hectorvent.floci.services.ecs.model.Deployment; @@ -30,6 +31,7 @@ import io.github.hectorvent.floci.services.ecs.model.ProtectedTask; import io.github.hectorvent.floci.services.ecs.model.RuntimePlatform; import io.github.hectorvent.floci.services.ecs.model.Secret; import io.github.hectorvent.floci.services.ecs.model.ServiceDeployment; +import io.github.hectorvent.floci.services.ecs.model.ServiceEvent; import io.github.hectorvent.floci.services.ecs.model.ServiceRevision; import io.github.hectorvent.floci.services.ecs.model.TaskDefinition; import io.github.hectorvent.floci.services.ecs.model.TaskNetworkInterface; @@ -47,6 +49,7 @@ import java.time.Instant; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.Set; /** * Renders ECS domain objects to the JSON 1.1 shapes the data plane returns. @@ -69,7 +72,25 @@ public class EcsResponseWriter { // ── Clusters ────────────────────────────────────────────────────────────── + /** + * The include values DescribeClusters understands. Every operation other than DescribeClusters + * returns the cluster whole, so {@link #clusterNode(EcsCluster)} passes all of them. + */ + public static final Set ALL_CLUSTER_INCLUDES = + Set.of("ATTACHMENTS", "CONFIGURATIONS", "SETTINGS", "STATISTICS", "TAGS"); + public ObjectNode clusterNode(EcsCluster c) { + return clusterNode(c, ALL_CLUSTER_INCLUDES); + } + + /** + * Renders a cluster, holding back the members DescribeClusters only returns when the request + * asked for them: "If this field is omitted, this information isn't included." + * + *

The gated members are emitted whenever they are asked for, empty array and all, so a + * client can tell an empty answer from a withheld one. + */ + public ObjectNode clusterNode(EcsCluster c, Set include) { ObjectNode n = objectMapper.createObjectNode(); n.put("clusterArn", c.getClusterArn()); n.put("clusterName", c.getClusterName()); @@ -78,7 +99,7 @@ public class EcsResponseWriter { n.put("runningTasksCount", c.getRunningTasksCount()); n.put("pendingTasksCount", c.getPendingTasksCount()); n.put("activeServicesCount", c.getActiveServicesCount()); - if (c.getSettings() != null && !c.getSettings().isEmpty()) { + if (include.contains("SETTINGS") && c.getSettings() != null && !c.getSettings().isEmpty()) { ArrayNode settings = objectMapper.createArrayNode(); c.getSettings().forEach(s -> { ObjectNode sn = objectMapper.createObjectNode(); @@ -88,12 +109,36 @@ public class EcsResponseWriter { }); n.set("settings", settings); } + if (include.contains("STATISTICS")) { + ArrayNode statistics = objectMapper.createArrayNode(); + service.clusterStatistics(c).forEach(kv -> { + ObjectNode sn = objectMapper.createObjectNode(); + sn.put("name", kv.name()); + sn.put("value", kv.value()); + statistics.add(sn); + }); + n.set("statistics", statistics); + } + if (include.contains("ATTACHMENTS")) { + // Floci creates no managed scaling policies, so a cluster never has attachments. + n.set("attachments", objectMapper.createArrayNode()); + } + if (include.contains("CONFIGURATIONS") && c.getConfiguration() != null) { + n.set("configuration", objectMapper.valueToTree(c.getConfiguration())); + } if (c.getCapacityProviders() != null) { ArrayNode cp = objectMapper.createArrayNode(); c.getCapacityProviders().forEach(cp::add); n.set("capacityProviders", cp); } - if (c.getTags() != null && !c.getTags().isEmpty()) { + if (c.getDefaultCapacityProviderStrategy() != null) { + n.set("defaultCapacityProviderStrategy", + objectMapper.valueToTree(c.getDefaultCapacityProviderStrategy())); + } + if (c.getServiceConnectDefaults() != null) { + n.set("serviceConnectDefaults", objectMapper.valueToTree(c.getServiceConnectDefaults())); + } + if (include.contains("TAGS") && c.getTags() != null && !c.getTags().isEmpty()) { n.set("tags", tagsNode(c.getTags())); } return n; @@ -652,10 +697,41 @@ public class EcsResponseWriter { ArrayNode deployments = objectMapper.createArrayNode(); service.deploymentsFor(s).forEach(d -> deployments.add(deploymentNode(d))); n.set("deployments", deployments); + // Both are always reported, empty and all: a service under the ECS controller has no task + // sets, and one that has not converged yet has no events, and a client has to be able to + // tell that from a member the emulator simply never writes. + ArrayNode taskSets = objectMapper.createArrayNode(); + service.taskSetsFor(s).forEach(ts -> taskSets.add(taskSetNode(ts))); + n.set("taskSets", taskSets); + ArrayNode events = objectMapper.createArrayNode(); + service.eventsFor(s).forEach(e -> events.add(serviceEventNode(e))); + n.set("events", events); + // The service points at the deployment and revision it is currently on, which is how a + // caller gets from DescribeServices to DescribeServiceDeployments without listing first. + ServiceDeployment current = service.currentServiceDeployment(s); + if (current != null) { + n.put("currentServiceDeployment", current.getServiceDeploymentArn()); + if (current.getTargetServiceRevisionArn() != null) { + ObjectNode revision = objectMapper.createObjectNode(); + revision.put("arn", current.getTargetServiceRevisionArn()); + revision.put("requestedTaskCount", s.getDesiredCount()); + revision.put("runningTaskCount", s.getRunningCount()); + revision.put("pendingTaskCount", s.getPendingCount()); + n.set("currentServiceRevisions", objectMapper.createArrayNode().add(revision)); + } + } EcsJsonPassthrough.write(n, s.getUnparsed(), objectMapper); return n; } + private ObjectNode serviceEventNode(ServiceEvent event) { + ObjectNode n = objectMapper.createObjectNode(); + n.put("id", event.id()); + putInstant(n, "createdAt", event.createdAt()); + n.put("message", event.message()); + return n; + } + private ObjectNode loadBalancerNode(EcsLoadBalancer lb) { ObjectNode n = objectMapper.createObjectNode(); if (lb.getTargetGroupArn() != null) { n.put("targetGroupArn", lb.getTargetGroupArn()); } @@ -691,15 +767,29 @@ public class EcsResponseWriter { n.put("failedTasks", d.getFailedTasks()); n.put("rolloutState", d.getRolloutState()); n.put("rolloutStateReason", d.getRolloutStateReason()); - if (d.getLaunchType() != null) { n.put("launchType", d.getLaunchType().name()); } - if (d.getCreatedAt() != null) { n.put("createdAt", d.getCreatedAt().toEpochMilli() / 1000.0); } - if (d.getUpdatedAt() != null) { n.put("updatedAt", d.getUpdatedAt().toEpochMilli() / 1000.0); } + if (d.getCapacityProviderStrategy() != null && !d.getCapacityProviderStrategy().isEmpty()) { + n.set("capacityProviderStrategy", + capacityProviderStrategyNode(d.getCapacityProviderStrategy())); + } else if (d.getLaunchType() != null) { + n.put("launchType", d.getLaunchType().name()); + } + if (d.getPlatformVersion() != null) { n.put("platformVersion", d.getPlatformVersion()); } + if (d.getPlatformFamily() != null) { n.put("platformFamily", d.getPlatformFamily()); } + if (d.getNetworkConfiguration() != null + && d.getNetworkConfiguration().getAwsvpcConfiguration() != null) { + n.set("networkConfiguration", + networkConfigurationNode(d.getNetworkConfiguration().getAwsvpcConfiguration())); + } + putInstant(n, "createdAt", d.getCreatedAt()); + putInstant(n, "updatedAt", d.getUpdatedAt()); if (d.getServiceConnectConfiguration() != null) { n.set("serviceConnectConfiguration", objectMapper.valueToTree(d.getServiceConnectConfiguration())); } return n; } + // ── Everything else ─────────────────────────────────────────────────────── + public ObjectNode failureNode(Failure f) { ObjectNode n = objectMapper.createObjectNode(); n.put("arn", f.arn()); @@ -709,25 +799,73 @@ public class EcsResponseWriter { } public ObjectNode containerInstanceNode(ContainerInstance ci) { + return containerInstanceNode(ci, true, true); + } + + /** + * @param includeTags DescribeContainerInstances returns tags only for {@code include: ["TAGS"]} + * @param includeHealth and the health status only for + * {@code include: ["CONTAINER_INSTANCE_HEALTH"]}: "If this field is + * omitted, tags and container instance health status aren't included in + * the response." + */ + public ObjectNode containerInstanceNode(ContainerInstance ci, boolean includeTags, + boolean includeHealth) { ObjectNode n = objectMapper.createObjectNode(); n.put("containerInstanceArn", ci.getContainerInstanceArn()); n.put("ec2InstanceId", ci.getEc2InstanceId()); n.put("status", ci.getStatus()); + if (ci.getStatusReason() != null) { n.put("statusReason", ci.getStatusReason()); } n.put("runningTasksCount", ci.getRunningTasksCount()); n.put("pendingTasksCount", ci.getPendingTasksCount()); - n.put("agentVersion", ci.getAgentVersion()); n.put("agentConnected", ci.isAgentConnected()); + if (ci.getAgentUpdateStatus() != null) { n.put("agentUpdateStatus", ci.getAgentUpdateStatus()); } + if (ci.getCapacityProviderName() != null) { + n.put("capacityProviderName", ci.getCapacityProviderName()); + } + n.put("version", ci.getVersion()); + putInstant(n, "registeredAt", ci.getRegisteredAt()); + if (ci.getVersionInfo() != null) { + n.set("versionInfo", objectMapper.valueToTree(ci.getVersionInfo())); + } + if (ci.getRegisteredResources() != null) { + n.set("registeredResources", objectMapper.valueToTree(ci.getRegisteredResources())); + } + if (ci.getRemainingResources() != null) { + n.set("remainingResources", objectMapper.valueToTree(ci.getRemainingResources())); + } if (ci.getAttributes() != null && !ci.getAttributes().isEmpty()) { ArrayNode attrs = objectMapper.createArrayNode(); ci.getAttributes().forEach(a -> attrs.add(attributeNode(a))); n.set("attributes", attrs); } - if (ci.getTags() != null && !ci.getTags().isEmpty()) { + if (includeHealth) { + n.set("healthStatus", containerInstanceHealthNode(ci)); + } + if (includeTags && ci.getTags() != null && !ci.getTags().isEmpty()) { n.set("tags", tagsNode(ci.getTags())); } return n; } + /** + * The instance's health. Floci runs no agent health checks of its own, so the one check it can + * answer honestly is {@code AGENT_CONNECTIVITY}, taken from the registration state the + * instance already tracks, and the overall status follows it. + */ + private ObjectNode containerInstanceHealthNode(ContainerInstance ci) { + String status = ci.isAgentConnected() ? "OK" : "IMPAIRED"; + ObjectNode health = objectMapper.createObjectNode(); + health.put("overallStatus", status); + ObjectNode connectivity = objectMapper.createObjectNode(); + connectivity.put("type", "AGENT_CONNECTIVITY"); + connectivity.put("status", status); + putInstant(connectivity, "lastUpdated", ci.getRegisteredAt()); + putInstant(connectivity, "lastStatusChange", ci.getRegisteredAt()); + health.set("details", objectMapper.createArrayNode().add(connectivity)); + return health; + } + /** @param includeTags DescribeCapacityProviders returns tags only for {@code include: ["TAGS"]}. */ public ObjectNode capacityProviderNode(CapacityProvider cp, boolean includeTags) { ObjectNode n = objectMapper.createObjectNode(); @@ -752,6 +890,11 @@ public class EcsResponseWriter { } public ObjectNode taskSetNode(TaskSet ts) { + return taskSetNode(ts, true); + } + + /** @param includeTags DescribeTaskSets returns tags only for {@code include: ["TAGS"]}. */ + public ObjectNode taskSetNode(TaskSet ts, boolean includeTags) { ObjectNode n = objectMapper.createObjectNode(); n.put("id", ts.getId()); n.put("taskSetArn", ts.getTaskSetArn()); @@ -763,29 +906,79 @@ public class EcsResponseWriter { n.put("pendingCount", ts.getPendingCount()); n.put("runningCount", ts.getRunningCount()); n.put("stabilityStatus", ts.getStabilityStatus()); + putInstant(n, "stabilityStatusAt", ts.getStabilityStatusAt()); if (ts.getLaunchType() != null) { n.put("launchType", ts.getLaunchType().name()); } + if (ts.getCapacityProviderStrategy() != null && !ts.getCapacityProviderStrategy().isEmpty()) { + n.set("capacityProviderStrategy", + capacityProviderStrategyNode(ts.getCapacityProviderStrategy())); + } + if (ts.getPlatformVersion() != null) { n.put("platformVersion", ts.getPlatformVersion()); } + if (ts.getPlatformFamily() != null) { n.put("platformFamily", ts.getPlatformFamily()); } if (ts.getExternalId() != null) { n.put("externalId", ts.getExternalId()); } + if (ts.getStartedBy() != null) { n.put("startedBy", ts.getStartedBy()); } + if (ts.getNetworkConfiguration() != null + && ts.getNetworkConfiguration().getAwsvpcConfiguration() != null) { + n.set("networkConfiguration", + networkConfigurationNode(ts.getNetworkConfiguration().getAwsvpcConfiguration())); + } + if (ts.getLoadBalancers() != null && !ts.getLoadBalancers().isEmpty()) { + ArrayNode lbs = objectMapper.createArrayNode(); + ts.getLoadBalancers().forEach(lb -> lbs.add(loadBalancerNode(lb))); + n.set("loadBalancers", lbs); + } + if (ts.getServiceRegistries() != null && !ts.getServiceRegistries().isEmpty()) { + n.set("serviceRegistries", objectMapper.valueToTree(ts.getServiceRegistries())); + } ObjectNode scale = objectMapper.createObjectNode(); scale.put("value", ts.getScaleValue()); scale.put("unit", ts.getScaleUnit()); n.set("scale", scale); - if (ts.getCreatedAt() != null) { n.put("createdAt", ts.getCreatedAt().toEpochMilli() / 1000.0); } - if (ts.getUpdatedAt() != null) { n.put("updatedAt", ts.getUpdatedAt().toEpochMilli() / 1000.0); } - if (ts.getTags() != null && !ts.getTags().isEmpty()) { + putInstant(n, "createdAt", ts.getCreatedAt()); + putInstant(n, "updatedAt", ts.getUpdatedAt()); + if (includeTags && ts.getTags() != null && !ts.getTags().isEmpty()) { n.set("tags", tagsNode(ts.getTags())); } return n; } + /** + * A service deployment. AWS's {@code ServiceDeployment} shape carries no + * {@code taskDefinition}: the deployment points at the revision it targets, and the revision + * names the task definition, so that is the only route reported here. + */ public ObjectNode serviceDeploymentNode(ServiceDeployment d) { ObjectNode n = objectMapper.createObjectNode(); n.put("serviceDeploymentArn", d.getServiceDeploymentArn()); n.put("serviceArn", d.getServiceArn()); n.put("clusterArn", d.getClusterArn()); - n.put("taskDefinition", d.getTaskDefinition()); n.put("status", d.getStatus()); - if (d.getCreatedAt() != null) { n.put("createdAt", d.getCreatedAt().toEpochMilli() / 1000.0); } - if (d.getUpdatedAt() != null) { n.put("updatedAt", d.getUpdatedAt().toEpochMilli() / 1000.0); } + putInstant(n, "createdAt", d.getCreatedAt()); + putInstant(n, "startedAt", d.getStartedAt()); + putInstant(n, "finishedAt", d.getFinishedAt()); + putInstant(n, "updatedAt", d.getUpdatedAt()); + if (d.getTargetServiceRevisionArn() != null) { + n.set("targetServiceRevision", + serviceRevisionSummaryNode(d.getTargetServiceRevisionArn(), d.getServiceArn())); + } + ArrayNode sources = objectMapper.createArrayNode(); + if (d.getSourceServiceRevisionArns() != null) { + d.getSourceServiceRevisionArns() + .forEach(arn -> sources.add(serviceRevisionSummaryNode(arn, d.getServiceArn()))); + } + n.set("sourceServiceRevisions", sources); + return n; + } + + /** The counts a revision summary reports track the service the revision belongs to. */ + private ObjectNode serviceRevisionSummaryNode(String revisionArn, String serviceArn) { + ObjectNode n = objectMapper.createObjectNode(); + n.put("arn", revisionArn); + EcsServiceModel svc = service.serviceByArn(serviceArn); + if (svc != null) { + n.put("requestedTaskCount", svc.getDesiredCount()); + n.put("runningTaskCount", svc.getRunningCount()); + n.put("pendingTaskCount", svc.getPendingCount()); + } return n; } @@ -795,8 +988,45 @@ public class EcsResponseWriter { n.put("serviceArn", r.getServiceArn()); n.put("clusterArn", r.getClusterArn()); n.put("taskDefinition", r.getTaskDefinition()); - if (r.getLaunchType() != null) { n.put("launchType", r.getLaunchType().name()); } - if (r.getCreatedAt() != null) { n.put("createdAt", r.getCreatedAt().toEpochMilli() / 1000.0); } + if (r.getCapacityProviderStrategy() != null && !r.getCapacityProviderStrategy().isEmpty()) { + n.set("capacityProviderStrategy", + capacityProviderStrategyNode(r.getCapacityProviderStrategy())); + } else if (r.getLaunchType() != null) { + n.put("launchType", r.getLaunchType().name()); + } + if (r.getPlatformVersion() != null) { n.put("platformVersion", r.getPlatformVersion()); } + if (r.getPlatformFamily() != null) { n.put("platformFamily", r.getPlatformFamily()); } + if (r.getLoadBalancers() != null && !r.getLoadBalancers().isEmpty()) { + ArrayNode lbs = objectMapper.createArrayNode(); + r.getLoadBalancers().forEach(lb -> lbs.add(loadBalancerNode(lb))); + n.set("loadBalancers", lbs); + } + if (r.getServiceRegistries() != null && !r.getServiceRegistries().isEmpty()) { + n.set("serviceRegistries", objectMapper.valueToTree(r.getServiceRegistries())); + } + if (r.getNetworkConfiguration() != null + && r.getNetworkConfiguration().getAwsvpcConfiguration() != null) { + n.set("networkConfiguration", + networkConfigurationNode(r.getNetworkConfiguration().getAwsvpcConfiguration())); + } + if (r.getServiceConnectConfiguration() != null) { + n.set("serviceConnectConfiguration", + objectMapper.valueToTree(r.getServiceConnectConfiguration())); + } + if (r.getContainerImages() != null && !r.getContainerImages().isEmpty()) { + ArrayNode images = objectMapper.createArrayNode(); + for (ContainerImage image : r.getContainerImages()) { + ObjectNode imageNode = objectMapper.createObjectNode(); + imageNode.put("containerName", image.containerName()); + imageNode.put("image", image.image()); + if (image.imageDigest() != null) { imageNode.put("imageDigest", image.imageDigest()); } + images.add(imageNode); + } + n.set("containerImages", images); + } + // Floci runs no GuardDuty runtime monitoring, which is what this reports. + n.put("guardDutyEnabled", false); + putInstant(n, "createdAt", r.getCreatedAt()); return n; } @@ -817,10 +1047,12 @@ public class EcsResponseWriter { return n; } - public ObjectNode settingNode(String name, String value) { + public ObjectNode settingNode(EcsService.AccountSetting setting) { ObjectNode n = objectMapper.createObjectNode(); - n.put("name", name); - n.put("value", value); + n.put("name", setting.name()); + n.put("value", setting.value()); + if (setting.principalArn() != null) { n.put("principalArn", setting.principalArn()); } + if (setting.type() != null) { n.put("type", setting.type()); } return n; } 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 21d54c69d3..925821e029 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 @@ -21,6 +21,7 @@ import io.github.hectorvent.floci.services.ecs.model.ClusterSetting; import io.github.hectorvent.floci.services.ecs.model.Container; import io.github.hectorvent.floci.services.ecs.model.ContainerDefinition; import io.github.hectorvent.floci.services.ecs.model.ContainerDependency; +import io.github.hectorvent.floci.services.ecs.model.ContainerImage; import io.github.hectorvent.floci.services.ecs.model.ContainerInstance; import io.github.hectorvent.floci.services.ecs.model.CreateClusterRequest; import io.github.hectorvent.floci.services.ecs.model.CreateServiceRequest; @@ -34,16 +35,19 @@ import io.github.hectorvent.floci.services.ecs.model.EcsLoadBalancer; import io.github.hectorvent.floci.services.ecs.model.EcsServiceModel; import io.github.hectorvent.floci.services.ecs.model.EcsTask; import io.github.hectorvent.floci.services.ecs.model.FirelensConfiguration; +import io.github.hectorvent.floci.services.ecs.model.KeyValuePair; import io.github.hectorvent.floci.services.ecs.model.LaunchType; import io.github.hectorvent.floci.services.ecs.model.ListTasksRequest; import io.github.hectorvent.floci.services.ecs.model.ManagedAgent; import io.github.hectorvent.floci.services.ecs.model.NetworkConfiguration; import io.github.hectorvent.floci.services.ecs.model.NetworkMode; import io.github.hectorvent.floci.services.ecs.model.ProtectedTask; +import io.github.hectorvent.floci.services.ecs.model.RegisterContainerInstanceRequest; import io.github.hectorvent.floci.services.ecs.model.RegisterTaskDefinitionRequest; import io.github.hectorvent.floci.services.ecs.model.RunTaskRequest; import io.github.hectorvent.floci.services.ecs.model.RuntimePlatform; import io.github.hectorvent.floci.services.ecs.model.ServiceDeployment; +import io.github.hectorvent.floci.services.ecs.model.ServiceEvent; import io.github.hectorvent.floci.services.ecs.model.ServiceRevision; import io.github.hectorvent.floci.services.ecs.model.TaskDefinition; import io.github.hectorvent.floci.services.ecs.model.TaskNetworkInterface; @@ -58,7 +62,9 @@ import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import org.jboss.logging.Logger; +import java.nio.charset.StandardCharsets; import java.time.Instant; +import java.util.Base64; import java.util.ArrayList; import java.util.Collection; @@ -142,6 +148,10 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab 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; + /** A listing returns at most a hundred ARNs per page. */ + private static final int MAX_LIST_RESULTS = 100; + /** ListServices answers with ten ARNs per page when the request names no maxResults. */ + private static final int DEFAULT_SERVICE_PAGE_SIZE = 10; public static final String STATUS_ACTIVE = "ACTIVE"; public static final String STATUS_INACTIVE = "INACTIVE"; public static final String STATUS_DELETE_IN_PROGRESS = "DELETE_IN_PROGRESS"; @@ -367,6 +377,8 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab if (request.getSettings() != null && !request.getSettings().isEmpty()) { cluster.setSettings(new ArrayList<>(request.getSettings())); } + cluster.setConfiguration(request.getConfiguration()); + cluster.setServiceConnectDefaults(request.getServiceConnectDefaults()); cluster.setCapacityProviders(request.getCapacityProviders()); cluster.setDefaultCapacityProviderStrategy(request.getDefaultCapacityProviderStrategy()); clusters.put(key, cluster); @@ -375,29 +387,124 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab } public List describeClusters(List clusterIds, String region) { + return describeClustersDetailed(clusterIds, region).clusters(); + } + + public record DescribeClustersResult(List clusters, List failures) {} + + /** + * Resolves each reference, reporting the ones that do not exist as {@code MISSING} failures. + * As with DescribeServices, ECS answers a describe for an unknown cluster with a failure entry + * rather than an error, and a client that sees neither a cluster nor a failure cannot tell the + * difference between "does not exist" and "the call did not happen". + */ + public DescribeClustersResult describeClustersDetailed(List clusterIds, String region) { if (clusterIds == null || clusterIds.isEmpty()) { - return List.of(getOrCreateDefaultCluster(region)); + return new DescribeClustersResult(List.of(getOrCreateDefaultCluster(region)), List.of()); } List result = new ArrayList<>(); + List failures = new ArrayList<>(); for (String id : clusterIds) { EcsCluster cluster = resolveCluster(id, region); if (cluster != null) { result.add(cluster); + } else { + failures.add(Failure.missing(id != null && id.startsWith("arn:") + ? id : regionResolver.buildArn("ecs", region, "cluster/" + id))); } } - return result; + return new DescribeClustersResult(result, failures); + } + + /** + * The task and service counts DescribeClusters reports under {@code STATISTICS}, separated by + * launch type. + * + *

The API reference spells one of the eight names {@code RunningFargateTasksCount}; every + * other name in that list, and the value real ECS returns, is lower camel case, so Floci + * follows the wire and not the typo. Values are strings, as ECS returns them. + */ + public List clusterStatistics(EcsCluster cluster) { + String clusterArn = cluster.getClusterArn(); + List clusterTasks = tasks.values().stream() + .filter(t -> clusterArn.equals(t.getClusterArn())) + .toList(); + List clusterServices = services.values().stream() + .filter(s -> clusterArn.equals(s.getClusterArn())) + .toList(); + return List.of( + statistic("runningEC2TasksCount", countTasks(clusterTasks, "RUNNING", LaunchType.EC2)), + statistic("runningFargateTasksCount", countTasks(clusterTasks, "RUNNING", LaunchType.FARGATE)), + statistic("pendingEC2TasksCount", countTasks(clusterTasks, "PENDING", LaunchType.EC2)), + statistic("pendingFargateTasksCount", countTasks(clusterTasks, "PENDING", LaunchType.FARGATE)), + statistic("activeEC2ServiceCount", countServices(clusterServices, STATUS_ACTIVE, LaunchType.EC2)), + statistic("activeFargateServiceCount", countServices(clusterServices, STATUS_ACTIVE, LaunchType.FARGATE)), + statistic("drainingEC2ServiceCount", countServices(clusterServices, "DRAINING", LaunchType.EC2)), + statistic("drainingFargateServiceCount", countServices(clusterServices, "DRAINING", LaunchType.FARGATE))); + } + + private static KeyValuePair statistic(String name, long value) { + return new KeyValuePair(name, String.valueOf(value)); + } + + private static long countTasks(List clusterTasks, String status, LaunchType launchType) { + return clusterTasks.stream() + .filter(t -> status.equals(t.getLastStatus())) + .filter(t -> launchType == effectiveLaunchType(t.getLaunchType())) + .count(); + } + + private static long countServices(List clusterServices, String status, + LaunchType launchType) { + return clusterServices.stream() + .filter(s -> status.equals(s.getStatus())) + .filter(s -> launchType == effectiveLaunchType(s.getLaunchType())) + .count(); + } + + /** A task or service that named no launch type placed on EC2, which is the ECS default. */ + private static LaunchType effectiveLaunchType(LaunchType launchType) { + return launchType == null ? LaunchType.EC2 : launchType; } public List listClusters(String region) { + return listClusters(null, null, region).arns(); + } + + public ListPage listClusters(Integer maxResults, String nextToken, String region) { String prefix = region + "::"; - return clusters.entrySet().stream() + List arns = clusters.entrySet().stream() .filter(e -> e.getKey().startsWith(prefix)) .map(e -> e.getValue().getClusterArn()) .toList(); + return paginate(arns, maxResults, nextToken); } + /** + * Deletes a cluster, refusing while anything is still registered against it: "You must + * deregister all container instances from this cluster before you may delete it", and a + * cluster that still has services or running tasks reports its own exception for each. + */ public EcsCluster deleteCluster(String clusterId, String region) { EcsCluster cluster = resolveClusterOrThrow(clusterId, region); + long activeServices = services.values().stream() + .filter(s -> cluster.getClusterArn().equals(s.getClusterArn())) + .filter(s -> !"INACTIVE".equals(s.getStatus())) + .count(); + if (activeServices > 0) { + throw new AwsException("ClusterContainsServicesException", + "The cluster cannot be deleted while services are active.", 400); + } + String instancePrefix = containerInstanceKey(cluster.getClusterArn(), ""); + long registeredInstances = containerInstances.entrySet().stream() + .filter(e -> e.getKey().startsWith(instancePrefix)) + .map(Map.Entry::getValue) + .filter(ci -> !STATUS_INACTIVE.equals(ci.getStatus())) + .count(); + if (registeredInstances > 0) { + throw new AwsException("ClusterContainsContainerInstancesException", + "The cluster cannot be deleted while container instances are active.", 400); + } long runningTasks = tasks.values().stream() .filter(t -> t.getClusterArn().equals(cluster.getClusterArn())) .filter(t -> !TaskStatus.STOPPED.name().equals(t.getLastStatus())) @@ -412,10 +519,26 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab } public EcsCluster updateCluster(String clusterRef, List settings, String region) { + return updateCluster(clusterRef, settings, null, null, region); + } + + /** + * UpdateCluster replaces only the members the request named: unlike UpdateClusterSettings, it + * leaves the ones it omits alone. + */ + public EcsCluster updateCluster(String clusterRef, List settings, + Map configuration, + Map serviceConnectDefaults, String region) { EcsCluster cluster = resolveClusterOrThrow(clusterRef, region); if (settings != null) { cluster.setSettings(settings); } + if (configuration != null) { + cluster.setConfiguration(configuration); + } + if (serviceConnectDefaults != null) { + cluster.setServiceConnectDefaults(serviceConnectDefaults); + } persistCluster(region, cluster); return cluster; } @@ -889,19 +1012,64 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab } public List listTaskDefinitions(String familyPrefix, String status) { - return taskDefinitions.values().stream() + return listTaskDefinitions(familyPrefix, status, null, null, null).arns(); + } + + /** + * Lists task definition ARNs. + * + *

Only {@code ACTIVE} revisions are listed unless another status is asked for, and the + * order is lexicographic by family then numeric by revision, so the newest revision of a + * family comes last (or first under {@code DESC}). Listing by ARN string alone would put + * revision 10 before revision 2. + */ + public ListPage listTaskDefinitions(String familyPrefix, String status, String sort, + Integer maxResults, String nextToken) { + String effectiveStatus = status != null ? status : STATUS_ACTIVE; + Comparator order = Comparator + .comparing(TaskDefinition::getFamily) + .thenComparingInt(TaskDefinition::getRevision); + if ("DESC".equals(sort)) { + order = order.reversed(); + } + List arns = taskDefinitions.values().stream() .filter(td -> familyPrefix == null || td.getFamily().startsWith(familyPrefix)) - .filter(td -> status == null || status.equals(td.getStatus())) + .filter(td -> effectiveStatus.equals(td.getStatus())) + .sorted(order) .map(TaskDefinition::getTaskDefinitionArn) - .sorted() .toList(); + return paginate(arns, maxResults, nextToken); } public List listTaskDefinitionFamilies(String familyPrefix) { - return latestRevisions.keySet().stream() + return listTaskDefinitionFamilies(familyPrefix, null, null, null).arns(); + } + + /** + * Lists task definition family names. + * + *

Both active and inactive families are listed unless a status narrows it: {@code ACTIVE} + * keeps only the families that still have an ACTIVE revision, {@code INACTIVE} keeps only + * those that have none. A family survives the deregistration of all its revisions, which is + * why the unfiltered listing still names it. + */ + public ListPage listTaskDefinitionFamilies(String familyPrefix, String status, + Integer maxResults, String nextToken) { + List families = latestRevisions.keySet().stream() .filter(f -> familyPrefix == null || f.startsWith(familyPrefix)) + .filter(f -> matchesFamilyStatus(f, status)) .sorted() .toList(); + return paginate(families, maxResults, nextToken); + } + + private boolean matchesFamilyStatus(String family, String status) { + if (status == null || "ALL".equals(status)) { + return true; + } + boolean hasActiveRevision = taskDefinitions.values().stream() + .anyMatch(td -> family.equals(td.getFamily()) && STATUS_ACTIVE.equals(td.getStatus())); + return STATUS_ACTIVE.equals(status) == hasActiveRevision; } public TaskDefinition deregisterTaskDefinition(String taskDefinitionRef, String region) { @@ -1606,13 +1774,29 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab request.setFamily(family); request.setDesiredStatus(desiredStatus); request.setServiceName(serviceName); - return listTasks(request, region); + return listTasks(request, region).arns(); } - public List listTasks(ListTasksRequest request, String region) { + /** A page of ARNs, with the token that continues the listing. */ + public record ListPage(List arns, String nextToken) {} + + /** + * Lists task ARNs under the request's filters. + * + *

The default filter is a desired status of {@code RUNNING}, as on AWS: a listing that has + * not asked for stopped tasks does not get them. {@code PENDING} matches nothing, because ECS + * only ever sets a task's desired status to RUNNING or STOPPED. + */ + public ListPage listTasks(ListTasksRequest request, String region) { + String startedBy = request.getStartedBy(); + if (startedBy != null && !startedBy.isBlank() && request.hasOtherFilters()) { + throw new AwsException("InvalidParameterException", + "When you specify startedBy as a filter, it must be the only filter used.", 400); + } + String desiredStatus = request.getDesiredStatus() != null + ? request.getDesiredStatus() : TaskStatus.RUNNING.name(); + String clusterRef = request.getCluster(); - String family = request.getFamily(); - String desiredStatus = request.getDesiredStatus(); String serviceName = request.getServiceName(); // Resolving the default cluster also creates and persists it, and ListTasks is a read: // when no cluster is named, look the default up without materializing it. A service @@ -1626,14 +1810,73 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab EcsServiceModel svc = serviceName != null && cluster != null ? services.get(serviceKey(region, cluster.getClusterName(), serviceName)) : null; + String family = request.getFamily(); + LaunchType launchType = request.getLaunchType(); + String containerInstance = request.getContainerInstance(); - return tasks.values().stream() + List matching = tasks.values().stream() .filter(t -> clusterArn == null || t.getClusterArn().equals(clusterArn)) .filter(t -> family == null || t.getTaskDefinitionArn().contains("/" + family + ":")) - .filter(t -> desiredStatus == null || desiredStatus.equals(t.getDesiredStatus())) + .filter(t -> desiredStatus.equals(t.getDesiredStatus())) + .filter(t -> launchType == null || launchType == t.getLaunchType()) + .filter(t -> startedBy == null || startedBy.isBlank() || startedBy.equals(t.getStartedBy())) + .filter(t -> containerInstance == null + || matchesContainerInstance(t, containerInstance, clusterArn)) .filter(t -> serviceName == null || (svc != null && ownedBy(t, svc, cluster))) .map(EcsTask::getTaskArn) .toList(); + + return paginate(matching, request.getMaxResults(), request.getNextToken()); + } + + /** A container instance filter takes the instance's id or its full ARN. */ + private boolean matchesContainerInstance(EcsTask task, String containerInstance, String clusterArn) { + String taskInstanceArn = task.getContainerInstanceArn(); + if (taskInstanceArn == null) { + return false; + } + return taskInstanceArn.equals(containerInstance) + || taskInstanceArn.endsWith("/" + containerInstance); + } + + /** + * Cuts a listing into the page the caller asked for. The token is the opaque offset AWS's + * tokens are, and the page size is capped the way ListTasks caps it. + */ + private static ListPage paginate(List arns, Integer maxResults, String nextToken) { + return paginate(arns, maxResults, nextToken, MAX_LIST_RESULTS); + } + + /** + * @param defaultPageSize the page size when the request names none, which is not the same for + * every listing: ListServices answers with ten, the rest with a hundred. + */ + private static ListPage paginate(List arns, Integer maxResults, String nextToken, + int defaultPageSize) { + int offset = decodeListToken(nextToken); + int pageSize = maxResults != null && maxResults > 0 + ? Math.min(maxResults, MAX_LIST_RESULTS) : defaultPageSize; + if (offset >= arns.size()) { + return new ListPage(List.of(), null); + } + int end = Math.min(offset + pageSize, arns.size()); + String token = end < arns.size() + ? Base64.getUrlEncoder().withoutPadding() + .encodeToString(String.valueOf(end).getBytes(StandardCharsets.UTF_8)) + : null; + return new ListPage(List.copyOf(arns.subList(offset, end)), token); + } + + private static int decodeListToken(String nextToken) { + if (nextToken == null || nextToken.isBlank()) { + return 0; + } + try { + return Integer.parseInt(new String(Base64.getUrlDecoder().decode(nextToken), + StandardCharsets.UTF_8)); + } catch (IllegalArgumentException e) { + throw new AwsException("InvalidParameterException", "The nextToken is not valid.", 400); + } } // ── Task Protection ─────────────────────────────────────────────────────── @@ -2162,14 +2405,30 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab } public List listServices(String clusterRef, String region) { + return listServices(clusterRef, null, null, null, null, region).arns(); + } + + /** + * Lists service ARNs in a cluster, filtered by launch type and scheduling strategy. + * + *

ListServices pages ten at a time when the request names no {@code maxResults}, unlike the + * other listings, which page a hundred at a time. + */ + public ListPage listServices(String clusterRef, LaunchType launchType, String schedulingStrategy, + Integer maxResults, String nextToken, String region) { EcsCluster cluster = resolveClusterOrDefault(clusterRef, region); String prefix = serviceKeyPrefix(region, cluster.getClusterName()); - return services.entrySet().stream() + List arns = services.entrySet().stream() .filter(e -> e.getKey().startsWith(prefix)) .map(Map.Entry::getValue) .filter(svc -> !"INACTIVE".equals(svc.getStatus())) + .filter(svc -> launchType == null || launchType == svc.getLaunchType()) + .filter(svc -> schedulingStrategy == null + || schedulingStrategy.equals(svc.getSchedulingStrategy() != null + ? svc.getSchedulingStrategy() : DEFAULT_SCHEDULING_STRATEGY)) .map(EcsServiceModel::getServiceArn) .toList(); + return paginate(arns, maxResults, nextToken, DEFAULT_SERVICE_PAGE_SIZE); } public List listServicesByNamespace(String namespace, String region) { @@ -2274,48 +2533,208 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab // ── Account Settings ────────────────────────────────────────────────────── - public Map.Entry putAccountSetting(String name, String value) { - accountSettings.put(name, value); - return Map.entry(name, value); + /** The account setting names ECS accepts, in the order ListAccountSettings reports them. */ + private static final List ACCOUNT_SETTING_NAMES = List.of( + "serviceLongArnFormat", "taskLongArnFormat", "containerInstanceLongArnFormat", + "awsvpcTrunking", "containerInsights", "fargateFIPSMode", "tagResourceAuthorization", + "fargateTaskRetirementWaitPeriod", "guardDutyActivate", "defaultLogDriverMode", + "fargateEventWindows"); + + /** + * What each setting reads as when neither the principal nor the account default set it. + * {@code defaultLogDriverMode} is {@code non-blocking} because ECS changed that default on + * June 25 2025, which the API reference records in its own note. + */ + private static final Map ACCOUNT_SETTING_DEFAULTS = Map.ofEntries( + Map.entry("serviceLongArnFormat", "enabled"), + Map.entry("taskLongArnFormat", "enabled"), + Map.entry("containerInstanceLongArnFormat", "enabled"), + Map.entry("awsvpcTrunking", "disabled"), + Map.entry("containerInsights", "disabled"), + Map.entry("fargateFIPSMode", "disabled"), + Map.entry("tagResourceAuthorization", "disabled"), + Map.entry("fargateTaskRetirementWaitPeriod", "7"), + Map.entry("guardDutyActivate", "disabled"), + Map.entry("defaultLogDriverMode", "non-blocking"), + Map.entry("fargateEventWindows", "disabled")); + + /** GuardDuty owns this one on the account's behalf, so its setting reports as aws_managed. */ + private static final String AWS_MANAGED_SETTING = "guardDutyActivate"; + /** ListAccountSettings pages ten at a time, and never accepts more than ten. */ + private static final int MAX_ACCOUNT_SETTING_RESULTS = 10; + + /** One row of the account-setting table, which is what the {@code Setting} shape carries. */ + public record AccountSetting(String name, String value, String principalArn, String type) {} + + /** + * Sets one principal's account setting. A request that names no principal sets it for the + * caller, which here is the account root, because Floci does not authenticate a separate user. + */ + public AccountSetting putAccountSetting(String name, String value, String principalArn) { + validateAccountSetting(name, value); + String principal = principalArn != null ? principalArn : rootPrincipalArn(); + accountSettings.put(accountSettingKey(principal, name), value); + return new AccountSetting(name, value, principal, settingType(name)); } - public Map.Entry putAccountSettingDefault(String name, String value) { - accountSettings.put(name, value); - return Map.entry(name, value); + /** + * Sets the account-wide default, which every principal without an explicit setting reads. AWS + * stores that on the root user, so setting the default and setting the root user's own value + * are the same write. + */ + public AccountSetting putAccountSettingDefault(String name, String value) { + return putAccountSetting(name, value, rootPrincipalArn()); } - public Map.Entry deleteAccountSetting(String name) { - String removed = accountSettings.remove(name); - return Map.entry(name, removed != null ? removed : ""); + public AccountSetting deleteAccountSetting(String name, String principalArn) { + requireAccountSettingName(name); + String principal = principalArn != null ? principalArn : rootPrincipalArn(); + String removed = accountSettings.remove(accountSettingKey(principal, name)); + return new AccountSetting(name, + removed != null ? removed : effectiveAccountSetting(principal, name), + principal, settingType(name)); } - public List> listAccountSettings(String filterName, String filterValue) { - return accountSettings.entrySet().stream() - .filter(e -> filterName == null || filterName.equals(e.getKey())) - .filter(e -> filterValue == null || filterValue.equals(e.getValue())) + /** A page of account settings, with the token that continues the listing. */ + public record AccountSettingPage(List settings, String nextToken) {} + + /** + * Lists a principal's account settings. With {@code effectiveSettings}, every name is reported + * at the value that principal actually reads: its own setting, else the account default, else + * the setting's built-in default. Without it, only the settings that principal explicitly set + * are returned, which is why an untouched account lists nothing. + */ + public AccountSettingPage listAccountSettings(String filterName, String filterValue, + String principalArn, boolean effectiveSettings, + Integer maxResults, String nextToken) { + if (filterName != null) { + requireAccountSettingName(filterName); + } + if (filterValue != null && filterName == null) { + throw new AwsException("InvalidParameterException", + "You must also specify an account setting name to filter by value.", 400); + } + String principal = principalArn != null ? principalArn : rootPrincipalArn(); + List settings = new ArrayList<>(); + for (String name : ACCOUNT_SETTING_NAMES) { + String explicit = accountSettings.get(accountSettingKey(principal, name)); + if (explicit != null) { + settings.add(new AccountSetting(name, explicit, principal, settingType(name))); + } else if (effectiveSettings) { + settings.add(new AccountSetting(name, effectiveAccountSetting(principal, name), + principal, settingType(name))); + } + } + List filtered = settings.stream() + .filter(s -> filterName == null || filterName.equals(s.name())) + .filter(s -> filterValue == null || filterValue.equals(s.value())) .toList(); + + int offset = decodeListToken(nextToken); + int pageSize = maxResults != null && maxResults > 0 + ? Math.min(maxResults, MAX_ACCOUNT_SETTING_RESULTS) : MAX_ACCOUNT_SETTING_RESULTS; + if (offset >= filtered.size()) { + return new AccountSettingPage(List.of(), null); + } + int end = Math.min(offset + pageSize, filtered.size()); + String token = end < filtered.size() + ? Base64.getUrlEncoder().withoutPadding() + .encodeToString(String.valueOf(end).getBytes(StandardCharsets.UTF_8)) + : null; + return new AccountSettingPage(List.copyOf(filtered.subList(offset, end)), token); + } + + private String effectiveAccountSetting(String principal, String name) { + String explicit = accountSettings.get(accountSettingKey(principal, name)); + if (explicit != null) { + return explicit; + } + String accountDefault = accountSettings.get(accountSettingKey(rootPrincipalArn(), name)); + return accountDefault != null ? accountDefault : ACCOUNT_SETTING_DEFAULTS.get(name); + } + + private static String settingType(String name) { + return AWS_MANAGED_SETTING.equals(name) ? "aws_managed" : "user"; + } + + private static String accountSettingKey(String principalArn, String name) { + return principalArn + "::" + name; + } + + private String rootPrincipalArn() { + return "arn:aws:iam::" + regionResolver.getAccountId() + ":root"; + } + + private static void requireAccountSettingName(String name) { + if (!ACCOUNT_SETTING_NAMES.contains(name)) { + throw new AwsException("InvalidParameterException", + "Invalid account setting name: " + name, 400); + } + } + + /** + * Most settings are an opt-in flag, but two are not: the Fargate retirement wait is a number of + * calendar days, and the default log driver mode names a delivery mode. + */ + private static void validateAccountSetting(String name, String value) { + requireAccountSettingName(name); + Set allowed = switch (name) { + case "fargateTaskRetirementWaitPeriod" -> Set.of("0", "7", "14"); + case "defaultLogDriverMode" -> Set.of("blocking", "non-blocking"); + case "containerInsights" -> Set.of("enabled", "disabled", "enhanced", "on", "off"); + default -> Set.of("enabled", "disabled", "on", "off"); + }; + if (!allowed.contains(value)) { + throw new AwsException("InvalidParameterException", + "Invalid value for account setting " + name + ": " + value, 400); + } } // ── Attributes ──────────────────────────────────────────────────────────── + /** The only target an attribute can be applied to. */ + private static final String ATTRIBUTE_TARGET_TYPE = "container-instance"; + /** "You can specify up to 10 custom attributes for each resource." */ + private static final int MAX_ATTRIBUTES_PER_TARGET = 10; + + /** + * Applies attributes to container instances of one cluster. Attributes are stored per cluster, + * not per target id alone: the same instance id in two clusters is two different targets, and + * ListAttributes is documented as listing "the attributes for Amazon ECS resources within a + * specified target type and cluster". + */ public List putAttributes(String clusterRef, List attrs, String region) { + EcsCluster cluster = resolveClusterOrDefault(clusterRef, region); + if (attrs.size() > MAX_ATTRIBUTES_PER_TARGET) { + throw new AwsException("AttributeLimitExceededException", + "You can specify up to " + MAX_ATTRIBUTES_PER_TARGET + + " attributes in a single call.", 400); + } List stored = new ArrayList<>(); for (Attribute attr : attrs) { - String targetId = attr.targetId(); - List existing = attributes.computeIfAbsent(targetId, k -> new ArrayList<>()); + requireAttributeTarget(cluster, attr); + String key = attributeKey(cluster, attr.targetId()); + List existing = attributes.computeIfAbsent(key, k -> new ArrayList<>()); existing.removeIf(a -> a.name().equals(attr.name())); + if (existing.size() >= MAX_ATTRIBUTES_PER_TARGET) { + throw new AwsException("AttributeLimitExceededException", + "You can apply up to " + MAX_ATTRIBUTES_PER_TARGET + + " custom attributes for each resource.", 400); + } existing.add(attr); - attributes.put(targetId, existing); + attributes.put(key, existing); stored.add(attr); } return stored; } public List deleteAttributes(String clusterRef, List attrs, String region) { + EcsCluster cluster = resolveClusterOrDefault(clusterRef, region); List deleted = new ArrayList<>(); for (Attribute attr : attrs) { - String targetId = attr.targetId(); - List existing = attributes.get(targetId); + requireAttributeTarget(cluster, attr); + String key = attributeKey(cluster, attr.targetId()); + List existing = attributes.get(key); if (existing != null) { existing.removeIf(a -> { if (a.name().equals(attr.name())) { @@ -2325,52 +2744,138 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab return false; }); if (existing.isEmpty()) { - attributes.remove(targetId); + attributes.remove(key); } else { - attributes.put(targetId, existing); + attributes.put(key, existing); } } } return deleted; } - public List listAttributes(String clusterRef, String targetType, - String attributeName, String attributeValue, String region) { - return attributes.values().stream() - .flatMap(List::stream) - .filter(a -> targetType == null || targetType.equals(a.targetType())) + /** + * An attribute names a container instance of this cluster, and ECS answers one that does not + * exist with a {@code TargetNotFoundException} rather than storing an orphan. + */ + private void requireAttributeTarget(EcsCluster cluster, Attribute attr) { + if (attr.targetType() != null && !ATTRIBUTE_TARGET_TYPE.equals(attr.targetType())) { + throw new AwsException("InvalidParameterException", + "Invalid target type: " + attr.targetType(), 400); + } + if (resolveContainerInstance(cluster.getClusterArn(), attr.targetId()) == null) { + throw new AwsException("TargetNotFoundException", + "The specified target was not found: " + attr.targetId(), 400); + } + } + + private static String attributeKey(EcsCluster cluster, String targetId) { + return cluster.getClusterArn() + "/" + targetId; + } + + /** {@code targetType} is required, and {@code container-instance} is its only valid value. */ + public ListAttributesPage listAttributes(String clusterRef, String targetType, + String attributeName, String attributeValue, + Integer maxResults, String nextToken, String region) { + EcsCluster cluster = resolveClusterOrDefault(clusterRef, region); + if (!ATTRIBUTE_TARGET_TYPE.equals(targetType)) { + throw new AwsException("InvalidParameterException", + "targetType is required and must be " + ATTRIBUTE_TARGET_TYPE + ".", 400); + } + if (attributeValue != null && attributeName == null) { + throw new AwsException("InvalidParameterException", + "You must also specify an attribute name to filter by value.", 400); + } + String prefix = cluster.getClusterArn() + "/"; + List matches = attributes.entrySet().stream() + .filter(e -> e.getKey().startsWith(prefix)) + .flatMap(e -> e.getValue().stream()) .filter(a -> attributeName == null || attributeName.equals(a.name())) .filter(a -> attributeValue == null || attributeValue.equals(a.value())) .toList(); + + int offset = decodeListToken(nextToken); + int pageSize = maxResults != null && maxResults > 0 + ? Math.min(maxResults, MAX_LIST_RESULTS) : MAX_LIST_RESULTS; + if (offset >= matches.size()) { + return new ListAttributesPage(List.of(), null); + } + int end = Math.min(offset + pageSize, matches.size()); + String token = end < matches.size() + ? Base64.getUrlEncoder().withoutPadding() + .encodeToString(String.valueOf(end).getBytes(StandardCharsets.UTF_8)) + : null; + return new ListAttributesPage(List.copyOf(matches.subList(offset, end)), token); } + /** A page of attributes, with the token that continues the listing. */ + public record ListAttributesPage(List attributes, String nextToken) {} + // ── Container Instances ─────────────────────────────────────────────────── + /** The statuses a container instance can report. */ + private static final Set CONTAINER_INSTANCE_STATUSES = Set.of( + "ACTIVE", "DRAINING", "REGISTERING", "DEREGISTERING", "REGISTRATION_FAILED", "INACTIVE"); + /** "The only valid values for this action are ACTIVE and DRAINING." */ + private static final Set UPDATABLE_CONTAINER_INSTANCE_STATUSES = Set.of("ACTIVE", "DRAINING"); + /** "A list of up to 10 container instance IDs or full ARN entries." */ + private static final int MAX_CONTAINER_INSTANCES_PER_UPDATE = 10; + /** What the agent reports when a registration carried no versionInfo of its own. */ + private static final Map DEFAULT_VERSION_INFO = + Map.of("agentVersion", "1.0.0", "agentHash", "floci", "dockerVersion", "DockerVersion: 24.0.0"); + public ContainerInstance registerContainerInstance(String clusterRef, String instanceIdentityDocument, List instanceAttributes, String region) { - EcsCluster cluster = resolveClusterOrDefault(clusterRef, region); + RegisterContainerInstanceRequest request = new RegisterContainerInstanceRequest(); + request.setCluster(clusterRef); + request.setInstanceIdentityDocument(instanceIdentityDocument); + request.setAttributes(instanceAttributes); + return registerContainerInstance(request, region); + } + + /** + * Registers a container instance, keeping the resources, version info and tags the agent sent: + * {@code totalResources} is what the instance reports it has, and ECS echoes it back as both + * {@code registeredResources} and, until tasks are placed, {@code remainingResources}. + */ + public ContainerInstance registerContainerInstance(RegisterContainerInstanceRequest request, + String region) { + EcsCluster cluster = resolveClusterOrDefault(request.getCluster(), region); String instanceId = "i-floci-" + UUID.randomUUID().toString().substring(0, 8); - String instanceArn = regionResolver.buildArn("ecs", region, - "container-instance/" + cluster.getClusterName() + "/" + UUID.randomUUID()); + String instanceArn = request.getContainerInstanceArn() != null + ? request.getContainerInstanceArn() + : regionResolver.buildArn("ecs", region, + "container-instance/" + cluster.getClusterName() + "/" + UUID.randomUUID()); ContainerInstance instance = new ContainerInstance(); instance.setContainerInstanceArn(instanceArn); instance.setEc2InstanceId(instanceId); - instance.setStatus("ACTIVE"); - instance.setAgentVersion("1.0.0"); + instance.setStatus(STATUS_ACTIVE); instance.setAgentConnected(true); - if (instanceAttributes != null) { - instance.setAttributes(new ArrayList<>(instanceAttributes)); + instance.setVersion(1); + instance.setRegisteredAt(Instant.now()); + instance.setVersionInfo(request.getVersionInfo() != null + ? request.getVersionInfo() : DEFAULT_VERSION_INFO); + instance.setRegisteredResources(request.getTotalResources()); + instance.setRemainingResources(request.getTotalResources()); + if (request.getAttributes() != null) { + instance.setAttributes(new ArrayList<>(request.getAttributes())); + } + if (request.getTags() != null && !request.getTags().isEmpty()) { + instance.setTags(new LinkedHashMap<>(request.getTags())); } String key = containerInstanceKey(cluster.getClusterArn(), instanceArn); containerInstances.put(key, instance); - cluster.setRegisteredContainerInstancesCount(cluster.getRegisteredContainerInstancesCount() + 1); - persistCluster(region, cluster); + refreshRegisteredInstanceCount(cluster, region); LOG.infov("Registered container instance: {0} in cluster {1}", instanceArn, cluster.getClusterName()); return instance; } + /** + * Deregisters an instance, leaving it in the cluster as {@code INACTIVE} rather than dropping + * it: AWS keeps answering DescribeContainerInstances for a deregistered instance, and only + * ACTIVE and DRAINING instances count towards the cluster's registered count. + */ public ContainerInstance deregisterContainerInstance(String clusterRef, String instanceRef, boolean force, String region) { EcsCluster cluster = resolveClusterOrDefault(clusterRef, region); @@ -2387,54 +2892,131 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab } } - String key = containerInstanceKey(cluster.getClusterArn(), instance.getContainerInstanceArn()); - containerInstances.remove(key); - instance.setStatus("INACTIVE"); - cluster.setRegisteredContainerInstancesCount( - Math.max(0, cluster.getRegisteredContainerInstancesCount() - 1)); - persistCluster(region, cluster); + instance.setStatus(STATUS_INACTIVE); + instance.setAgentConnected(false); + instance.setVersion(instance.getVersion() + 1); + refreshRegisteredInstanceCount(cluster, region); return instance; } + /** "This includes container instances in both ACTIVE and DRAINING status." */ + private void refreshRegisteredInstanceCount(EcsCluster cluster, String region) { + String prefix = containerInstanceKey(cluster.getClusterArn(), ""); + long registered = containerInstances.entrySet().stream() + .filter(e -> e.getKey().startsWith(prefix)) + .map(Map.Entry::getValue) + .filter(ci -> STATUS_ACTIVE.equals(ci.getStatus()) || "DRAINING".equals(ci.getStatus())) + .count(); + cluster.setRegisteredContainerInstancesCount((int) registered); + persistCluster(region, cluster); + } + public List describeContainerInstances(String clusterRef, List instanceRefs, String region) { + return describeContainerInstancesDetailed(clusterRef, instanceRefs, region).instances(); + } + + public record DescribeContainerInstancesResult(List instances, + List failures) {} + + public DescribeContainerInstancesResult describeContainerInstancesDetailed( + String clusterRef, List instanceRefs, String region) { EcsCluster cluster = resolveClusterOrDefault(clusterRef, region); List result = new ArrayList<>(); + List failures = new ArrayList<>(); for (String ref : instanceRefs) { ContainerInstance instance = resolveContainerInstance(cluster.getClusterArn(), ref); if (instance != null) { result.add(instance); + } else { + failures.add(Failure.missing(ref.startsWith("arn:") ? ref + : containerInstanceArnFor(cluster, ref, region))); } } - return result; + return new DescribeContainerInstancesResult(result, failures); + } + + private String containerInstanceArnFor(EcsCluster cluster, String ref, String region) { + return regionResolver.buildArn("ecs", region, + "container-instance/" + cluster.getClusterName() + "/" + ref); } public List listContainerInstances(String clusterRef, String status, String region) { + return listContainerInstances(clusterRef, status, null, null, region).arns(); + } + + /** + * Lists container instance ARNs. A request that names no status gets every instance other than + * the {@code INACTIVE} ones, which is AWS's documented default rather than everything. + */ + public ListPage listContainerInstances(String clusterRef, String status, Integer maxResults, + String nextToken, String region) { EcsCluster cluster = resolveClusterOrDefault(clusterRef, region); + if (status != null && !CONTAINER_INSTANCE_STATUSES.contains(status)) { + throw new AwsException("InvalidParameterException", + "Invalid container instance status: " + status, 400); + } String prefix = containerInstanceKey(cluster.getClusterArn(), ""); - return containerInstances.entrySet().stream() + List arns = containerInstances.entrySet().stream() .filter(e -> e.getKey().startsWith(prefix)) - .filter(e -> status == null || status.equals(e.getValue().getStatus())) - .map(e -> e.getValue().getContainerInstanceArn()) + .map(Map.Entry::getValue) + .filter(ci -> status != null + ? status.equals(ci.getStatus()) + : !STATUS_INACTIVE.equals(ci.getStatus())) + .map(ContainerInstance::getContainerInstanceArn) .toList(); + return paginate(arns, maxResults, nextToken); } public ContainerInstance updateContainerAgent(String clusterRef, String instanceRef, String region) { EcsCluster cluster = resolveClusterOrDefault(clusterRef, region); - return resolveContainerInstanceOrThrow(cluster.getClusterArn(), instanceRef); + ContainerInstance instance = resolveContainerInstanceOrThrow(cluster.getClusterArn(), instanceRef); + instance.setAgentUpdateStatus("UPDATED"); + instance.setVersion(instance.getVersion() + 1); + return instance; } - public List updateContainerInstancesState(String clusterRef, - List instanceRefs, - String status, String region) { + public record UpdateContainerInstancesStateResult(List instances, + List failures) {} + + /** + * Moves instances between {@code ACTIVE} and {@code DRAINING}, the only two states this action + * sets. "A container instance can't be changed to DRAINING until it has reached an ACTIVE + * status", and an instance the cluster does not have comes back as a failure, not an error. + */ + public UpdateContainerInstancesStateResult updateContainerInstancesState( + String clusterRef, List instanceRefs, String status, String region) { EcsCluster cluster = resolveClusterOrDefault(clusterRef, region); + if (!UPDATABLE_CONTAINER_INSTANCE_STATUSES.contains(status)) { + throw new AwsException("InvalidParameterException", + "The only valid container instance states for this action are " + + "ACTIVE and DRAINING.", 400); + } + if (instanceRefs.size() > MAX_CONTAINER_INSTANCES_PER_UPDATE) { + throw new AwsException("InvalidParameterException", + "You can update at most " + MAX_CONTAINER_INSTANCES_PER_UPDATE + + " container instances in a single call.", 400); + } List updated = new ArrayList<>(); + List failures = new ArrayList<>(); for (String ref : instanceRefs) { - ContainerInstance instance = resolveContainerInstanceOrThrow(cluster.getClusterArn(), ref); + ContainerInstance instance = resolveContainerInstance(cluster.getClusterArn(), ref); + if (instance == null) { + failures.add(Failure.missing(ref.startsWith("arn:") ? ref + : containerInstanceArnFor(cluster, ref, region))); + continue; + } + if ("DRAINING".equals(status) && !STATUS_ACTIVE.equals(instance.getStatus())) { + throw new AwsException("InvalidParameterException", + "Container instance " + instance.getContainerInstanceArn() + + " must be ACTIVE before it can be set to DRAINING.", 400); + } instance.setStatus(status); + instance.setVersion(instance.getVersion() + 1); updated.add(instance); } - return updated; + refreshRegisteredInstanceCount(cluster, region); + return new UpdateContainerInstancesStateResult(updated, failures); } // ── Capacity Providers ──────────────────────────────────────────────────── @@ -2625,6 +3207,13 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab // ── Task Sets ───────────────────────────────────────────────────────────── + /** The deployment controllers a task set can live under; a ROLLING service manages its own. */ + private static final Set TASK_SET_CONTROLLERS = Set.of("EXTERNAL", "CODE_DEPLOY"); + /** The only unit {@code Scale} accepts, so the computed count is always a percentage. */ + private static final String SCALE_UNIT_PERCENT = "PERCENT"; + /** The stability a task set reports while Floci places no tasks of its own for one. */ + private static final String STABILITY_STATUS_STEADY_STATE = "STEADY_STATE"; + public TaskSet createTaskSet(String clusterRef, String serviceRef, String taskDefinitionRef, LaunchType launchType, double scaleValue, String scaleUnit, String externalId, String region) { @@ -2639,11 +3228,33 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab return createTaskSet(request, region); } + /** + * Creates a task set, which only a service using the {@code EXTERNAL} or {@code CODE_DEPLOY} + * deployment controller can have: a ROLLING service runs its own deployments, and AWS refuses + * the call rather than creating a task set nothing will ever place. + */ public TaskSet createTaskSet(CreateTaskSetRequest request, String region) { EcsCluster cluster = resolveClusterOrDefault(request.getCluster(), region); EcsServiceModel svc = resolveServiceOrThrow(cluster.getClusterName(), request.getService(), region); TaskDefinition taskDef = resolveTaskDefinitionOrThrow(request.getTaskDefinition(), region); + String controller = svc.getDeploymentController() != null + ? svc.getDeploymentController() : "ECS"; + if (!TASK_SET_CONTROLLERS.contains(controller)) { + throw new AwsException("InvalidParameterException", + "Task sets can only be created for services using the EXTERNAL or CODE_DEPLOY " + + "deployment controller type.", 400); + } + if (request.getLaunchType() != null && request.getCapacityProviderStrategy() != null + && !request.getCapacityProviderStrategy().isEmpty()) { + throw new AwsException("InvalidParameterException", + "You cannot specify both a launch type and a capacity provider strategy.", 400); + } + if (request.getScaleUnit() != null && !SCALE_UNIT_PERCENT.equals(request.getScaleUnit())) { + throw new AwsException("InvalidParameterException", + "Invalid scale unit: " + request.getScaleUnit(), 400); + } + String setId = "ecs-svc/" + UUID.randomUUID().toString().replace("-", ""); String taskSetArn = regionResolver.buildArn("ecs", region, "task-set/" + cluster.getClusterName() + "/" + svc.getServiceName() + "/" + setId); @@ -2654,59 +3265,168 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab ts.setServiceArn(svc.getServiceArn()); ts.setClusterArn(cluster.getClusterArn()); ts.setTaskDefinition(taskDef.getTaskDefinitionArn()); - ts.setStatus("ACTIVE"); + ts.setStatus(STATUS_ACTIVE); ts.setScaleValue(request.getScaleValue() != null ? request.getScaleValue() : 100.0); - ts.setScaleUnit(request.getScaleUnit() != null ? request.getScaleUnit() : "PERCENT"); - ts.setLaunchType(request.getLaunchType() != null ? request.getLaunchType() : LaunchType.FARGATE); + ts.setScaleUnit(SCALE_UNIT_PERCENT); + ts.setCapacityProviderStrategy(request.getCapacityProviderStrategy()); + ts.setLaunchType(taskSetLaunchType(request, cluster)); ts.setExternalId(request.getExternalId()); - ts.setStabilityStatus("STEADY_STATE"); + ts.setStartedBy(request.getStartedBy()); + ts.setNetworkConfiguration(request.getNetworkConfiguration() != null + ? request.getNetworkConfiguration() : svc.getNetworkConfiguration()); + ts.setLoadBalancers(request.getLoadBalancers()); + ts.setServiceRegistries(request.getServiceRegistries()); + if (request.getTags() != null && !request.getTags().isEmpty()) { + ts.setTags(new LinkedHashMap<>(request.getTags())); + } + if (ts.getLaunchType() == LaunchType.FARGATE) { + String requested = request.getPlatformVersion(); + ts.setPlatformVersion(requested == null || requested.isBlank() + || PLATFORM_VERSION_LATEST.equals(requested) ? DEFAULT_PLATFORM_VERSION : requested); + ts.setPlatformFamily(platformFamilyOf(taskDef)); + } ts.setCreatedAt(Instant.now()); ts.setUpdatedAt(Instant.now()); + applyTaskSetScale(ts, svc); taskSets.put(taskSetArn, ts); return ts; } + /** + * A task set that names neither a launch type nor a capacity provider strategy takes the + * cluster's default strategy, and falls back to EC2 when the cluster has none, as AWS does. + */ + private LaunchType taskSetLaunchType(CreateTaskSetRequest request, EcsCluster cluster) { + if (request.getLaunchType() != null) { + return request.getLaunchType(); + } + List strategy = request.getCapacityProviderStrategy(); + if (strategy == null || strategy.isEmpty()) { + strategy = clusterDefaultStrategy(cluster); + } + if (strategy == null || strategy.isEmpty()) { + return LaunchType.EC2; + } + return strategy.stream() + .map(CapacityProviderStrategyItem::capacityProvider) + .anyMatch(FARGATE_CAPACITY_PROVIDERS::contains) ? LaunchType.FARGATE : LaunchType.EC2; + } + + /** + * Stamps {@code computedDesiredCount}, which AWS derives from the service's desired count and + * the task set's scale percentage, always rounding up: a computed 1.2 becomes 2 tasks. + * + *

Floci places no tasks for a task set, so its running and pending counts stay at zero. A + * stability status derived from them would leave every set on a service with a desired count + * above zero in {@code STABILIZING} for ever, hanging anything that waits for the set to + * stabilise, so the set is reported {@code STEADY_STATE} until Floci tracks tasks for it. + */ + private void applyTaskSetScale(TaskSet ts, EcsServiceModel svc) { + ts.setComputedDesiredCount( + (int) Math.ceil(svc.getDesiredCount() * ts.getScaleValue() / 100.0)); + ts.setStabilityStatus(STABILITY_STATUS_STEADY_STATE); + ts.setStabilityStatusAt(Instant.now()); + } + public TaskSet updateTaskSet(String clusterRef, String serviceRef, String taskSetRef, double scaleValue, String scaleUnit, String region) { - TaskSet ts = resolveTaskSetOrThrow(taskSetRef); + EcsCluster cluster = resolveClusterOrDefault(clusterRef, region); + EcsServiceModel svc = resolveServiceOrThrow(cluster.getClusterName(), serviceRef, region); + TaskSet ts = resolveTaskSetOrThrow(svc, taskSetRef); + if (scaleUnit != null && !SCALE_UNIT_PERCENT.equals(scaleUnit)) { + throw new AwsException("InvalidParameterException", + "Invalid scale unit: " + scaleUnit, 400); + } ts.setScaleValue(scaleValue); - ts.setScaleUnit(scaleUnit != null ? scaleUnit : "PERCENT"); + ts.setScaleUnit(SCALE_UNIT_PERCENT); ts.setUpdatedAt(Instant.now()); + applyTaskSetScale(ts, svc); return ts; } + /** + * Deletes a task set. Without {@code force}, AWS refuses one that has not been scaled down to + * zero, so a deploy tool that forgot to drain the set is told rather than silently losing it. + */ public TaskSet deleteTaskSet(String clusterRef, String serviceRef, String taskSetRef, boolean force, String region) { - TaskSet ts = resolveTaskSetOrThrow(taskSetRef); + EcsCluster cluster = resolveClusterOrDefault(clusterRef, region); + EcsServiceModel svc = resolveServiceOrThrow(cluster.getClusterName(), serviceRef, region); + TaskSet ts = resolveTaskSetOrThrow(svc, taskSetRef); + if (!force && (ts.getComputedDesiredCount() > 0 || ts.getRunningCount() > 0 + || ts.getPendingCount() > 0)) { + throw new AwsException("InvalidParameterException", + "The task set cannot be deleted because it has not been scaled down to zero. " + + "Use the force flag to delete it anyway.", 400); + } ts.setStatus("DRAINING"); + ts.setUpdatedAt(Instant.now()); taskSets.remove(ts.getTaskSetArn()); return ts; } public List describeTaskSets(String clusterRef, String serviceRef, List taskSetRefs, String region) { + return describeTaskSetsDetailed(clusterRef, serviceRef, taskSetRefs, region).taskSets(); + } + + /** + * The task sets of a service, which {@code DescribeServices} reports on the service itself: + * a client driving a blue/green deploy reads them from there rather than making a second + * DescribeTaskSets call. + */ + public List taskSetsFor(EcsServiceModel svc) { + if (svc == null) { + return List.of(); + } + return taskSets.values().stream() + .filter(ts -> svc.getServiceArn().equals(ts.getServiceArn())) + .sorted(Comparator.comparing(TaskSet::getCreatedAt, + Comparator.nullsLast(Comparator.naturalOrder()))) + .toList(); + } + + public record DescribeTaskSetsResult(List taskSets, List failures) {} + + /** Reports a reference that names no task set of this service as a {@code MISSING} failure. */ + public DescribeTaskSetsResult describeTaskSetsDetailed(String clusterRef, String serviceRef, + List taskSetRefs, String region) { EcsCluster cluster = resolveClusterOrDefault(clusterRef, region); EcsServiceModel svc = resolveServiceOrThrow(cluster.getClusterName(), serviceRef, region); - Stream stream = taskSets.values().stream() - .filter(ts -> ts.getServiceArn().equals(svc.getServiceArn())); - if (taskSetRefs != null && !taskSetRefs.isEmpty()) { - stream = stream.filter(ts -> taskSetRefs.contains(ts.getTaskSetArn()) - || taskSetRefs.contains(ts.getId())); + List ofService = taskSets.values().stream() + .filter(ts -> ts.getServiceArn().equals(svc.getServiceArn())) + .toList(); + if (taskSetRefs == null || taskSetRefs.isEmpty()) { + return new DescribeTaskSetsResult(ofService, List.of()); } - return stream.toList(); + List found = new ArrayList<>(); + List failures = new ArrayList<>(); + for (String ref : taskSetRefs) { + TaskSet match = ofService.stream() + .filter(ts -> ref.equals(ts.getTaskSetArn()) || ref.equals(ts.getId())) + .findFirst().orElse(null); + if (match != null) { + found.add(match); + } else { + failures.add(Failure.missing(ref.startsWith("arn:") ? ref + : regionResolver.buildArn("ecs", region, "task-set/" + + cluster.getClusterName() + "/" + svc.getServiceName() + "/" + ref))); + } + } + return new DescribeTaskSetsResult(found, failures); } public TaskSet updateServicePrimaryTaskSet(String clusterRef, String serviceRef, String primaryTaskSetRef, String region) { EcsCluster cluster = resolveClusterOrDefault(clusterRef, region); EcsServiceModel svc = resolveServiceOrThrow(cluster.getClusterName(), serviceRef, region); - TaskSet primary = resolveTaskSetOrThrow(primaryTaskSetRef); + TaskSet primary = resolveTaskSetOrThrow(svc, primaryTaskSetRef); taskSets.values().stream() .filter(ts -> ts.getServiceArn().equals(svc.getServiceArn())) .forEach(ts -> ts.setStatus(ts.getTaskSetArn().equals(primary.getTaskSetArn()) - ? "PRIMARY" : "ACTIVE")); + ? "PRIMARY" : STATUS_ACTIVE)); primary.setUpdatedAt(Instant.now()); return primary; @@ -2777,7 +3497,16 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab d.setRolloutState(converged ? "COMPLETED" : "IN_PROGRESS"); d.setRolloutStateReason("ECS deployment " + deploymentId + (converged ? " completed." : " in progress.")); - d.setLaunchType(svc.getLaunchType()); + // A deployment reports the placement it runs under the same way the service does: a + // capacity provider strategy when there is one, a launch type otherwise, never both. + if (svc.getCapacityProviderStrategy() != null && !svc.getCapacityProviderStrategy().isEmpty()) { + d.setCapacityProviderStrategy(svc.getCapacityProviderStrategy()); + } else { + d.setLaunchType(svc.getLaunchType()); + } + d.setPlatformVersion(svc.getPlatformVersion()); + d.setPlatformFamily(svc.getPlatformFamily()); + d.setNetworkConfiguration(svc.getNetworkConfiguration()); d.setServiceConnectConfiguration(svc.getServiceConnectConfiguration()); // The deployment's own start time, not the service's: a task-definition change mints a // new deployment id, so reporting service creation here would contradict it. Older @@ -2790,6 +3519,30 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab return List.of(d); } + /** + * The service's event log, derived from its current state for the same reason + * {@link #deploymentsFor} derives its deployments: Floci applies a change in place instead of + * running a rollout, so there is no history to replay. A converged service reports the one + * event tools actually poll for, "has reached a steady state"; one still converging reports + * none. + * + *

The event id is derived from the deployment it belongs to rather than minted per call, + * so a client that persists it does not see a new event on every describe. + */ + public List eventsFor(EcsServiceModel svc) { + if (svc == null || !"ACTIVE".equals(svc.getStatus()) + || svc.getRunningCount() < svc.getDesiredCount()) { + return List.of(); + } + String deploymentId = deploymentId(svc); + Instant at = svc.getLastDeploymentAt() != null ? svc.getLastDeploymentAt() : svc.getCreatedAt(); + return List.of(new ServiceEvent( + UUID.nameUUIDFromBytes((deploymentId + ":steady-state").getBytes(StandardCharsets.UTF_8)) + .toString(), + at, + "(service " + svc.getServiceName() + ") has reached a steady state.")); + } + private static String newDeploymentId() { return "ecs-svc/" + java.util.UUID.randomUUID().toString().replace("-", ""); } @@ -2815,6 +3568,15 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab return "ecs-svc/" + Long.toUnsignedString(hash); } + /** + * Records the deployment and the revision it targets. The revision is the snapshot of the + * service's configuration, so it is copied out of the service rather than read back from it + * later; the deployment links to it, which is how a caller gets from + * {@code DescribeServiceDeployments} to what was actually deployed. + * + *

Floci applies a change in place instead of rolling it, so a deployment is finished the + * moment it is recorded: {@code startedAt} and {@code finishedAt} are both its creation time. + */ private void recordServiceDeployment(EcsServiceModel svc, String taskDefinition, String region) { String deploymentId = UUID.randomUUID().toString().replace("-", ""); String deploymentArn = regionResolver.buildArn("ecs", region, @@ -2822,6 +3584,15 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab String revisionId = UUID.randomUUID().toString().replace("-", ""); String revisionArn = regionResolver.buildArn("ecs", region, "service-revision/" + revisionId); + Instant now = Instant.now(); + + List priorRevisions = serviceRevisions.values().stream() + .filter(r -> svc.getServiceArn().equals(r.getServiceArn())) + .sorted(Comparator.comparing(ServiceRevision::getCreatedAt, + Comparator.nullsLast(Comparator.naturalOrder())).reversed()) + .limit(1) + .map(ServiceRevision::getServiceRevisionArn) + .toList(); ServiceDeployment deployment = new ServiceDeployment(); deployment.setServiceDeploymentArn(deploymentArn); @@ -2829,8 +3600,12 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab deployment.setClusterArn(svc.getClusterArn()); deployment.setTaskDefinition(taskDefinition); deployment.setStatus("SUCCESSFUL"); - deployment.setCreatedAt(Instant.now()); - deployment.setUpdatedAt(Instant.now()); + deployment.setCreatedAt(now); + deployment.setStartedAt(now); + deployment.setFinishedAt(now); + deployment.setUpdatedAt(now); + deployment.setTargetServiceRevisionArn(revisionArn); + deployment.setSourceServiceRevisionArns(priorRevisions); serviceDeployments.put(deploymentArn, deployment); ServiceRevision revision = new ServiceRevision(); @@ -2839,10 +3614,63 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab revision.setClusterArn(svc.getClusterArn()); revision.setTaskDefinition(taskDefinition); revision.setLaunchType(svc.getLaunchType()); - revision.setCreatedAt(Instant.now()); + revision.setCapacityProviderStrategy(svc.getCapacityProviderStrategy()); + revision.setPlatformVersion(svc.getPlatformVersion()); + revision.setPlatformFamily(svc.getPlatformFamily()); + revision.setLoadBalancers(svc.getLoadBalancers()); + revision.setServiceRegistries(svc.getServiceRegistries()); + revision.setNetworkConfiguration(svc.getNetworkConfiguration()); + revision.setServiceConnectConfiguration(svc.getServiceConnectConfiguration()); + revision.setContainerImages(containerImagesOf(taskDefinition, region)); + revision.setCreatedAt(now); serviceRevisions.put(revisionArn, revision); } + /** The images the revision's task definition pins, one entry per container definition. */ + private List containerImagesOf(String taskDefinitionRef, String region) { + TaskDefinition taskDef; + try { + taskDef = resolveTaskDefinitionOrThrow(taskDefinitionRef, region); + } catch (AwsException expected) { + // The revision records what it can. A service can outlive the revision it was created + // on, and a snapshot with no images is better than failing the whole call. + LOG.debugv("No task definition for service revision images: {0}", taskDefinitionRef); + return List.of(); + } + if (taskDef.getContainerDefinitions() == null) { + return List.of(); + } + return taskDef.getContainerDefinitions().stream() + .map(def -> new ContainerImage(def.getName(), def.getImage(), null)) + .toList(); + } + + /** The counts a service revision summary reports, which track the service they belong to. */ + public EcsServiceModel serviceByArn(String serviceArn) { + if (serviceArn == null) { + return null; + } + return services.values().stream() + .filter(s -> serviceArn.equals(s.getServiceArn())) + .findFirst().orElse(null); + } + + public ServiceRevision serviceRevisionByArn(String revisionArn) { + return revisionArn == null ? null : serviceRevisions.get(revisionArn); + } + + /** The service's most recent deployment, which is the one {@code Service} points at. */ + public ServiceDeployment currentServiceDeployment(EcsServiceModel svc) { + if (svc == null) { + return null; + } + return serviceDeployments.values().stream() + .filter(d -> svc.getServiceArn().equals(d.getServiceArn())) + .max(Comparator.comparing(ServiceDeployment::getCreatedAt, + Comparator.nullsFirst(Comparator.naturalOrder()))) + .orElse(null); + } + // ── Stub operations ──────────────────────────────────────────────────────── public String submitTaskStateChange() { @@ -3429,14 +4257,18 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab return cp; } - private TaskSet resolveTaskSetOrThrow(String ref) { - TaskSet ts = taskSets.get(ref); - if (ts != null) { return ts; } - ts = taskSets.values().stream() - .filter(t -> t.getId().equals(ref)) + /** + * Resolves a task set of this service by ARN or id. A reference that names none is a + * {@code TaskSetNotFoundException}, which is the error the SDKs model for it; the task sets of + * another service do not count, because task sets are scoped to a cluster and a service. + */ + private TaskSet resolveTaskSetOrThrow(EcsServiceModel svc, String ref) { + TaskSet ts = taskSets.values().stream() + .filter(t -> t.getServiceArn().equals(svc.getServiceArn())) + .filter(t -> t.getTaskSetArn().equals(ref) || t.getId().equals(ref)) .findFirst().orElse(null); if (ts == null) { - throw new AwsException("InvalidParameterException", "Task set not found: " + ref, 400); + throw new AwsException("TaskSetNotFoundException", "Task set not found: " + ref, 400); } return ts; } diff --git a/src/main/java/io/github/hectorvent/floci/services/ecs/model/ContainerImage.java b/src/main/java/io/github/hectorvent/floci/services/ecs/model/ContainerImage.java new file mode 100644 index 0000000000..962a5d7123 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/ecs/model/ContainerImage.java @@ -0,0 +1,12 @@ +package io.github.hectorvent.floci.services.ecs.model; + +import io.quarkus.runtime.annotations.RegisterForReflection; + +/** + * One container image a service revision pins. {@code imageDigest} is the digest the image + * resolved to; a revision Floci minted from a task definition alone has not pulled anything yet + * and reports none. + */ +@RegisterForReflection +public record ContainerImage(String containerName, String image, String imageDigest) { +} diff --git a/src/main/java/io/github/hectorvent/floci/services/ecs/model/ContainerInstance.java b/src/main/java/io/github/hectorvent/floci/services/ecs/model/ContainerInstance.java index 7ed33cb63e..80e1c3dcb8 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ecs/model/ContainerInstance.java +++ b/src/main/java/io/github/hectorvent/floci/services/ecs/model/ContainerInstance.java @@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.ecs.model; import io.quarkus.runtime.annotations.RegisterForReflection; +import java.time.Instant; import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -15,8 +16,16 @@ public class ContainerInstance { private String status; private int runningTasksCount; private int pendingTasksCount; - private String agentVersion; + private String statusReason; private boolean agentConnected; + private String agentUpdateStatus; + private String capacityProviderName; + private long version; + private Instant registeredAt; + /** The agent's own {@code versionInfo}: agentHash, agentVersion and dockerVersion. */ + private Map versionInfo; + private List> registeredResources; + private List> remainingResources; private List attributes = new ArrayList<>(); private Map tags = new HashMap<>(); @@ -35,12 +44,33 @@ public class ContainerInstance { public int getPendingTasksCount() { return pendingTasksCount; } public void setPendingTasksCount(int pendingTasksCount) { this.pendingTasksCount = pendingTasksCount; } - public String getAgentVersion() { return agentVersion; } - public void setAgentVersion(String agentVersion) { this.agentVersion = agentVersion; } + public String getStatusReason() { return statusReason; } + public void setStatusReason(String statusReason) { this.statusReason = statusReason; } public boolean isAgentConnected() { return agentConnected; } public void setAgentConnected(boolean agentConnected) { this.agentConnected = agentConnected; } + public String getAgentUpdateStatus() { return agentUpdateStatus; } + public void setAgentUpdateStatus(String agentUpdateStatus) { this.agentUpdateStatus = agentUpdateStatus; } + + public String getCapacityProviderName() { return capacityProviderName; } + public void setCapacityProviderName(String capacityProviderName) { this.capacityProviderName = capacityProviderName; } + + public long getVersion() { return version; } + public void setVersion(long version) { this.version = version; } + + public Instant getRegisteredAt() { return registeredAt; } + public void setRegisteredAt(Instant registeredAt) { this.registeredAt = registeredAt; } + + public Map getVersionInfo() { return versionInfo; } + public void setVersionInfo(Map versionInfo) { this.versionInfo = versionInfo; } + + public List> getRegisteredResources() { return registeredResources; } + public void setRegisteredResources(List> resources) { this.registeredResources = resources; } + + public List> getRemainingResources() { return remainingResources; } + public void setRemainingResources(List> resources) { this.remainingResources = resources; } + public List getAttributes() { return attributes; } public void setAttributes(List attributes) { this.attributes = attributes; } diff --git a/src/main/java/io/github/hectorvent/floci/services/ecs/model/CreateClusterRequest.java b/src/main/java/io/github/hectorvent/floci/services/ecs/model/CreateClusterRequest.java index 5d0b44efee..610f5684be 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ecs/model/CreateClusterRequest.java +++ b/src/main/java/io/github/hectorvent/floci/services/ecs/model/CreateClusterRequest.java @@ -12,6 +12,8 @@ public class CreateClusterRequest { private String clusterName; private Map tags; private List settings; + private Map configuration; + private Map serviceConnectDefaults; private List capacityProviders; private List> defaultCapacityProviderStrategy; @@ -24,6 +26,12 @@ public class CreateClusterRequest { public List getSettings() { return settings; } public void setSettings(List settings) { this.settings = settings; } + public Map getConfiguration() { return configuration; } + public void setConfiguration(Map configuration) { this.configuration = configuration; } + + public Map getServiceConnectDefaults() { return serviceConnectDefaults; } + public void setServiceConnectDefaults(Map defaults) { this.serviceConnectDefaults = defaults; } + public List getCapacityProviders() { return capacityProviders; } public void setCapacityProviders(List capacityProviders) { this.capacityProviders = capacityProviders; } diff --git a/src/main/java/io/github/hectorvent/floci/services/ecs/model/CreateTaskSetRequest.java b/src/main/java/io/github/hectorvent/floci/services/ecs/model/CreateTaskSetRequest.java index f19cc87350..ebb92999e2 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ecs/model/CreateTaskSetRequest.java +++ b/src/main/java/io/github/hectorvent/floci/services/ecs/model/CreateTaskSetRequest.java @@ -2,6 +2,9 @@ package io.github.hectorvent.floci.services.ecs.model; import io.quarkus.runtime.annotations.RegisterForReflection; +import java.util.List; +import java.util.Map; + /** A parsed {@code CreateTaskSet} request. */ @RegisterForReflection public class CreateTaskSetRequest { @@ -10,9 +13,17 @@ public class CreateTaskSetRequest { private String service; private String taskDefinition; private LaunchType launchType; + private List capacityProviderStrategy; + private String platformVersion; private Double scaleValue; private String scaleUnit; private String externalId; + /** Set by Floci's CodeDeploy, which reports {@code CODE_DEPLOY}; an external deployment leaves it unset. */ + private String startedBy; + private NetworkConfiguration networkConfiguration; + private List loadBalancers; + private List> serviceRegistries; + private Map tags; public String getCluster() { return cluster; } public void setCluster(String cluster) { this.cluster = cluster; } @@ -26,6 +37,14 @@ public class CreateTaskSetRequest { public LaunchType getLaunchType() { return launchType; } public void setLaunchType(LaunchType launchType) { this.launchType = launchType; } + public List getCapacityProviderStrategy() { return capacityProviderStrategy; } + public void setCapacityProviderStrategy(List strategy) { + this.capacityProviderStrategy = strategy; + } + + public String getPlatformVersion() { return platformVersion; } + public void setPlatformVersion(String platformVersion) { this.platformVersion = platformVersion; } + public Double getScaleValue() { return scaleValue; } public void setScaleValue(Double scaleValue) { this.scaleValue = scaleValue; } @@ -34,4 +53,23 @@ public class CreateTaskSetRequest { public String getExternalId() { return externalId; } public void setExternalId(String externalId) { this.externalId = externalId; } + + public String getStartedBy() { return startedBy; } + public void setStartedBy(String startedBy) { this.startedBy = startedBy; } + + public NetworkConfiguration getNetworkConfiguration() { return networkConfiguration; } + public void setNetworkConfiguration(NetworkConfiguration networkConfiguration) { + this.networkConfiguration = networkConfiguration; + } + + 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 getTags() { return tags; } + public void setTags(Map tags) { this.tags = tags; } } diff --git a/src/main/java/io/github/hectorvent/floci/services/ecs/model/Deployment.java b/src/main/java/io/github/hectorvent/floci/services/ecs/model/Deployment.java index 933f280973..f3913a2a25 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ecs/model/Deployment.java +++ b/src/main/java/io/github/hectorvent/floci/services/ecs/model/Deployment.java @@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.ecs.model; import io.quarkus.runtime.annotations.RegisterForReflection; import java.time.Instant; +import java.util.List; import java.util.Map; /** @@ -24,6 +25,10 @@ public class Deployment { private String rolloutState; private String rolloutStateReason; private LaunchType launchType; + private List capacityProviderStrategy; + private String platformVersion; + private String platformFamily; + private NetworkConfiguration networkConfiguration; private Instant createdAt; private Instant updatedAt; /** @@ -53,6 +58,18 @@ public class Deployment { public void setRolloutStateReason(String rolloutStateReason) { this.rolloutStateReason = rolloutStateReason; } public LaunchType getLaunchType() { return launchType; } public void setLaunchType(LaunchType launchType) { this.launchType = launchType; } + public List getCapacityProviderStrategy() { return capacityProviderStrategy; } + public void setCapacityProviderStrategy(List capacityProviderStrategy) { + this.capacityProviderStrategy = capacityProviderStrategy; + } + 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 NetworkConfiguration getNetworkConfiguration() { return networkConfiguration; } + public void setNetworkConfiguration(NetworkConfiguration networkConfiguration) { + this.networkConfiguration = networkConfiguration; + } public Instant getCreatedAt() { return createdAt; } public void setCreatedAt(Instant createdAt) { this.createdAt = createdAt; } public Instant getUpdatedAt() { return updatedAt; } diff --git a/src/main/java/io/github/hectorvent/floci/services/ecs/model/EcsCluster.java b/src/main/java/io/github/hectorvent/floci/services/ecs/model/EcsCluster.java index 55c578fd58..ed0c055bfd 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ecs/model/EcsCluster.java +++ b/src/main/java/io/github/hectorvent/floci/services/ecs/model/EcsCluster.java @@ -19,6 +19,8 @@ public class EcsCluster { private List settings; private List capacityProviders; private List> defaultCapacityProviderStrategy; + private Map configuration; + private Map serviceConnectDefaults; private Map tags = new HashMap<>(); public String getClusterArn() { return clusterArn; } @@ -51,6 +53,12 @@ public class EcsCluster { public List> getDefaultCapacityProviderStrategy() { return defaultCapacityProviderStrategy; } public void setDefaultCapacityProviderStrategy(List> s) { this.defaultCapacityProviderStrategy = s; } + public Map getConfiguration() { return configuration; } + public void setConfiguration(Map configuration) { this.configuration = configuration; } + + public Map getServiceConnectDefaults() { return serviceConnectDefaults; } + public void setServiceConnectDefaults(Map defaults) { this.serviceConnectDefaults = defaults; } + public Map getTags() { return tags; } public void setTags(Map tags) { this.tags = tags; } } diff --git a/src/main/java/io/github/hectorvent/floci/services/ecs/model/ListTasksRequest.java b/src/main/java/io/github/hectorvent/floci/services/ecs/model/ListTasksRequest.java index 799f7627d7..4d26d49b02 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ecs/model/ListTasksRequest.java +++ b/src/main/java/io/github/hectorvent/floci/services/ecs/model/ListTasksRequest.java @@ -2,24 +2,60 @@ package io.github.hectorvent.floci.services.ecs.model; import io.quarkus.runtime.annotations.RegisterForReflection; -/** A parsed {@code ListTasks} request. Every member narrows the listing. */ +/** + * A parsed {@code ListTasks} request. + * + *

Every member narrows the listing. {@code startedBy} is the exception: ECS requires it to be + * used on its own, which {@link #hasOtherFilters()} is there to check. {@code cluster} is not a + * filter for that rule, it is the scope the listing runs in, so it pairs with {@code startedBy}. + */ @RegisterForReflection public class ListTasksRequest { private String cluster; + private String containerInstance; private String desiredStatus; private String family; + private LaunchType launchType; private String serviceName; + private String startedBy; + private Integer maxResults; + private String nextToken; public String getCluster() { return cluster; } public void setCluster(String cluster) { this.cluster = cluster; } + public String getContainerInstance() { return containerInstance; } + public void setContainerInstance(String containerInstance) { this.containerInstance = containerInstance; } + public String getDesiredStatus() { return desiredStatus; } public void setDesiredStatus(String desiredStatus) { this.desiredStatus = desiredStatus; } public String getFamily() { return family; } public void setFamily(String family) { this.family = family; } + public LaunchType getLaunchType() { return launchType; } + public void setLaunchType(LaunchType launchType) { this.launchType = launchType; } + public String getServiceName() { return serviceName; } public void setServiceName(String serviceName) { this.serviceName = serviceName; } + + public String getStartedBy() { return startedBy; } + public void setStartedBy(String startedBy) { this.startedBy = startedBy; } + + public Integer getMaxResults() { return maxResults; } + public void setMaxResults(Integer maxResults) { this.maxResults = maxResults; } + + public String getNextToken() { return nextToken; } + public void setNextToken(String nextToken) { this.nextToken = nextToken; } + + /** + * Whether any filter other than {@code startedBy} is set. The cluster and the pagination + * members do not count: the cluster scopes the listing rather than narrowing it, and AWS + * accepts {@code list-tasks --cluster X --started-by Y}. + */ + public boolean hasOtherFilters() { + return containerInstance != null || desiredStatus != null + || family != null || launchType != null || serviceName != null; + } } diff --git a/src/main/java/io/github/hectorvent/floci/services/ecs/model/RegisterContainerInstanceRequest.java b/src/main/java/io/github/hectorvent/floci/services/ecs/model/RegisterContainerInstanceRequest.java new file mode 100644 index 0000000000..ceffc66866 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/ecs/model/RegisterContainerInstanceRequest.java @@ -0,0 +1,51 @@ +package io.github.hectorvent.floci.services.ecs.model; + +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.util.List; +import java.util.Map; + +/** A parsed {@code RegisterContainerInstance} request, which only the ECS agent sends. */ +@RegisterForReflection +public class RegisterContainerInstanceRequest { + + private String cluster; + /** Set when the agent is re-registering an instance it already has an ARN for. */ + private String containerInstanceArn; + private String instanceIdentityDocument; + private List attributes; + private List> totalResources; + private Map versionInfo; + private List> platformDevices; + private Map tags; + + public String getCluster() { return cluster; } + public void setCluster(String cluster) { this.cluster = cluster; } + + public String getContainerInstanceArn() { return containerInstanceArn; } + public void setContainerInstanceArn(String containerInstanceArn) { + this.containerInstanceArn = containerInstanceArn; + } + + public String getInstanceIdentityDocument() { return instanceIdentityDocument; } + public void setInstanceIdentityDocument(String doc) { this.instanceIdentityDocument = doc; } + + public List getAttributes() { return attributes; } + public void setAttributes(List attributes) { this.attributes = attributes; } + + public List> getTotalResources() { return totalResources; } + public void setTotalResources(List> totalResources) { + this.totalResources = totalResources; + } + + public Map getVersionInfo() { return versionInfo; } + public void setVersionInfo(Map versionInfo) { this.versionInfo = versionInfo; } + + public List> getPlatformDevices() { return platformDevices; } + public void setPlatformDevices(List> platformDevices) { + this.platformDevices = platformDevices; + } + + public Map getTags() { return tags; } + public void setTags(Map tags) { this.tags = tags; } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/ecs/model/ServiceDeployment.java b/src/main/java/io/github/hectorvent/floci/services/ecs/model/ServiceDeployment.java index ca31b680c1..92bd833162 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ecs/model/ServiceDeployment.java +++ b/src/main/java/io/github/hectorvent/floci/services/ecs/model/ServiceDeployment.java @@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.ecs.model; import io.quarkus.runtime.annotations.RegisterForReflection; import java.time.Instant; +import java.util.List; @RegisterForReflection public class ServiceDeployment { @@ -10,10 +11,35 @@ public class ServiceDeployment { private String serviceDeploymentArn; private String serviceArn; private String clusterArn; + /** + * Internal only. AWS's {@code ServiceDeployment} shape has no {@code taskDefinition} member: + * a caller reaches the task definition through {@link #targetServiceRevisionArn}, so this is + * never written to the wire. + */ private String taskDefinition; private String status; private Instant createdAt; + private Instant startedAt; + private Instant finishedAt; private Instant updatedAt; + private String targetServiceRevisionArn; + private List sourceServiceRevisionArns; + + public Instant getStartedAt() { return startedAt; } + public void setStartedAt(Instant startedAt) { this.startedAt = startedAt; } + + public Instant getFinishedAt() { return finishedAt; } + public void setFinishedAt(Instant finishedAt) { this.finishedAt = finishedAt; } + + public String getTargetServiceRevisionArn() { return targetServiceRevisionArn; } + public void setTargetServiceRevisionArn(String targetServiceRevisionArn) { + this.targetServiceRevisionArn = targetServiceRevisionArn; + } + + public List getSourceServiceRevisionArns() { return sourceServiceRevisionArns; } + public void setSourceServiceRevisionArns(List sourceServiceRevisionArns) { + this.sourceServiceRevisionArns = sourceServiceRevisionArns; + } public String getServiceDeploymentArn() { return serviceDeploymentArn; } public void setServiceDeploymentArn(String serviceDeploymentArn) { this.serviceDeploymentArn = serviceDeploymentArn; } diff --git a/src/main/java/io/github/hectorvent/floci/services/ecs/model/ServiceEvent.java b/src/main/java/io/github/hectorvent/floci/services/ecs/model/ServiceEvent.java new file mode 100644 index 0000000000..6463f3a6b3 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/ecs/model/ServiceEvent.java @@ -0,0 +1,14 @@ +package io.github.hectorvent.floci.services.ecs.model; + +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.time.Instant; + +/** + * One entry of the event log {@code DescribeServices} reports on {@code services[].events}. + * Tools tail it for the "has reached a steady state" message the scheduler emits once a + * deployment converges. + */ +@RegisterForReflection +public record ServiceEvent(String id, Instant createdAt, String message) { +} diff --git a/src/main/java/io/github/hectorvent/floci/services/ecs/model/ServiceRevision.java b/src/main/java/io/github/hectorvent/floci/services/ecs/model/ServiceRevision.java index 3e90bc159b..333a3577ae 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ecs/model/ServiceRevision.java +++ b/src/main/java/io/github/hectorvent/floci/services/ecs/model/ServiceRevision.java @@ -3,7 +3,14 @@ package io.github.hectorvent.floci.services.ecs.model; import io.quarkus.runtime.annotations.RegisterForReflection; import java.time.Instant; +import java.util.List; +import java.util.Map; +/** + * The immutable snapshot of a service's configuration at the moment a deployment was created. + * Everything a revision carries is copied from the service, not referenced, so a revision keeps + * reporting what the service looked like then even after the service moves on. + */ @RegisterForReflection public class ServiceRevision { @@ -12,8 +19,50 @@ public class ServiceRevision { private String clusterArn; private String taskDefinition; private LaunchType launchType; + private List capacityProviderStrategy; + private String platformVersion; + private String platformFamily; + private List loadBalancers; + private List> serviceRegistries; + private NetworkConfiguration networkConfiguration; + private List containerImages; + private Map serviceConnectConfiguration; private Instant createdAt; + public List getCapacityProviderStrategy() { return capacityProviderStrategy; } + public void setCapacityProviderStrategy(List capacityProviderStrategy) { + this.capacityProviderStrategy = capacityProviderStrategy; + } + + 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 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; + } + + public List getContainerImages() { return containerImages; } + public void setContainerImages(List containerImages) { + this.containerImages = containerImages; + } + + public Map getServiceConnectConfiguration() { return serviceConnectConfiguration; } + public void setServiceConnectConfiguration(Map serviceConnectConfiguration) { + this.serviceConnectConfiguration = serviceConnectConfiguration; + } + public String getServiceRevisionArn() { return serviceRevisionArn; } public void setServiceRevisionArn(String serviceRevisionArn) { this.serviceRevisionArn = serviceRevisionArn; } diff --git a/src/main/java/io/github/hectorvent/floci/services/ecs/model/TaskSet.java b/src/main/java/io/github/hectorvent/floci/services/ecs/model/TaskSet.java index 677bd85030..14d1115c9f 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ecs/model/TaskSet.java +++ b/src/main/java/io/github/hectorvent/floci/services/ecs/model/TaskSet.java @@ -4,6 +4,7 @@ import io.quarkus.runtime.annotations.RegisterForReflection; import java.time.Instant; import java.util.HashMap; +import java.util.List; import java.util.Map; @RegisterForReflection @@ -21,8 +22,16 @@ public class TaskSet { private double scaleValue; private String scaleUnit; private String stabilityStatus; + private Instant stabilityStatusAt; private LaunchType launchType; + private List capacityProviderStrategy; + private String platformVersion; + private String platformFamily; private String externalId; + private String startedBy; + private NetworkConfiguration networkConfiguration; + private List loadBalancers; + private List> serviceRegistries; private Instant createdAt; private Instant updatedAt; private Map tags = new HashMap<>(); @@ -63,12 +72,42 @@ public class TaskSet { public String getStabilityStatus() { return stabilityStatus; } public void setStabilityStatus(String stabilityStatus) { this.stabilityStatus = stabilityStatus; } + public Instant getStabilityStatusAt() { return stabilityStatusAt; } + public void setStabilityStatusAt(Instant stabilityStatusAt) { this.stabilityStatusAt = stabilityStatusAt; } + public LaunchType getLaunchType() { return launchType; } public void setLaunchType(LaunchType launchType) { this.launchType = launchType; } + public List getCapacityProviderStrategy() { return capacityProviderStrategy; } + public void setCapacityProviderStrategy(List strategy) { + this.capacityProviderStrategy = strategy; + } + + 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 String getExternalId() { return externalId; } public void setExternalId(String externalId) { this.externalId = externalId; } + public String getStartedBy() { return startedBy; } + public void setStartedBy(String startedBy) { this.startedBy = startedBy; } + + public NetworkConfiguration getNetworkConfiguration() { return networkConfiguration; } + public void setNetworkConfiguration(NetworkConfiguration networkConfiguration) { + this.networkConfiguration = networkConfiguration; + } + + 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 Instant getCreatedAt() { return createdAt; } public void setCreatedAt(Instant createdAt) { this.createdAt = createdAt; } diff --git a/src/test/java/io/github/hectorvent/floci/services/ecs/EcsCreateClusterSettingsIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ecs/EcsCreateClusterSettingsIntegrationTest.java index 8fb0b0200e..19f60dadbb 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ecs/EcsCreateClusterSettingsIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ecs/EcsCreateClusterSettingsIntegrationTest.java @@ -53,10 +53,11 @@ class EcsCreateClusterSettingsIntegrationTest { .body("cluster.settings[0].value", equalTo("enabled")); // The drift the issue describes is not in the CreateCluster response but in what a later - // read reports, which is what a client compares its configuration against. + // read reports, which is what a client compares its configuration against. DescribeClusters + // only reports settings when the request asks for them, which terraform-provider-aws does. ecs("DescribeClusters") .body(""" - {"clusters": ["%s"]} + {"clusters": ["%s"], "include": ["SETTINGS"]} """.formatted(cluster)) .when() .post("/") 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 28a1f83020..227d93d5aa 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 @@ -449,7 +449,80 @@ class EcsFargateEdgeCaseIntegrationTest { .then().body("message", containsString("role parameter")); } - // ── Service updates ────────────────────────────────────────────────────── + // ── ListTasks filters ───────────────────────────────────────────────────── + + @Test + void listTasksDefaultsToTheRunningTasks() { + String family = seed("edge-list-default"); + String running = call("RunTask", "{\"cluster\":\"" + CLUSTER + "\",\"taskDefinition\":\"" + + family + "\",\"launchType\":\"FARGATE\"," + NETWORK + "}", 200) + .jsonPath().getString("tasks[0].taskArn"); + String stopped = call("RunTask", "{\"cluster\":\"" + CLUSTER + "\",\"taskDefinition\":\"" + + family + "\",\"launchType\":\"FARGATE\"," + NETWORK + "}", 200) + .jsonPath().getString("tasks[0].taskArn"); + call("StopTask", "{\"cluster\":\"" + CLUSTER + "\",\"task\":\"" + stopped + "\"}", 200); + + // Without a desiredStatus the listing is RUNNING only, which is AWS's default filter. + List byDefault = call("ListTasks", "{\"cluster\":\"" + CLUSTER + "\",\"family\":\"" + + family + "\"}", 200).jsonPath().getList("taskArns"); + assertTrue(byDefault.contains(running), "a running task must be listed by default"); + assertFalse(byDefault.contains(stopped), "a stopped task must not be listed by default"); + + List stoppedOnly = call("ListTasks", "{\"cluster\":\"" + CLUSTER + "\",\"family\":\"" + + family + "\",\"desiredStatus\":\"STOPPED\"}", 200).jsonPath().getList("taskArns"); + assertTrue(stoppedOnly.contains(stopped), "STOPPED must list the stopped task"); + assertFalse(stoppedOnly.contains(running), "STOPPED must not list the running task"); + + // ECS never sets a desired status of PENDING, so that filter matches nothing. + assertTrue(call("ListTasks", "{\"cluster\":\"" + CLUSTER + "\",\"family\":\"" + family + + "\",\"desiredStatus\":\"PENDING\"}", 200) + .jsonPath().getList("taskArns").isEmpty(), "PENDING must match nothing"); + } + + @Test + void listTasksFiltersByLaunchTypeAndStartedBy() { + String family = seed("edge-list-filters"); + String tagged = call("RunTask", "{\"cluster\":\"" + CLUSTER + "\",\"taskDefinition\":\"" + + family + "\",\"launchType\":\"FARGATE\"," + NETWORK + + ",\"startedBy\":\"edge-batch-7\"}", 200) + .jsonPath().getString("tasks[0].taskArn"); + + assertTrue(call("ListTasks", "{\"cluster\":\"" + CLUSTER + "\",\"family\":\"" + family + + "\",\"launchType\":\"FARGATE\"}", 200) + .jsonPath().getList("taskArns").contains(tagged)); + assertTrue(call("ListTasks", "{\"cluster\":\"" + CLUSTER + "\",\"family\":\"" + family + + "\",\"launchType\":\"EC2\"}", 200) + .jsonPath().getList("taskArns").isEmpty(), "no task here runs on EC2"); + + assertTrue(call("ListTasks", "{\"startedBy\":\"edge-batch-7\"}", 200) + .jsonPath().getList("taskArns").contains(tagged)); + // The cluster scopes the listing rather than filtering it, so it pairs with startedBy. + assertTrue(call("ListTasks", "{\"cluster\":\"" + CLUSTER + "\",\"startedBy\":\"edge-batch-7\"}", 200) + .jsonPath().getList("taskArns").contains(tagged)); + // Any other filter alongside startedBy is still refused. + call("ListTasks", "{\"cluster\":\"" + CLUSTER + "\",\"family\":\"" + family + + "\",\"startedBy\":\"edge-batch-7\"}", 400) + .then().body("message", containsString("only filter")); + } + + @Test + void listTasksPaginates() { + String family = seed("edge-list-paging"); + call("RunTask", "{\"cluster\":\"" + CLUSTER + "\",\"taskDefinition\":\"" + family + + "\",\"count\":3,\"launchType\":\"FARGATE\"," + NETWORK + "}", 200); + + Response first = call("ListTasks", "{\"cluster\":\"" + CLUSTER + "\",\"family\":\"" + family + + "\",\"maxResults\":2}", 200); + first.then().body("taskArns", hasSize(2)); + String token = first.jsonPath().getString("nextToken"); + assertTrue(token != null && !token.isBlank(), "a truncated listing must return a token"); + + Response second = call("ListTasks", "{\"cluster\":\"" + CLUSTER + "\",\"family\":\"" + family + + "\",\"maxResults\":2,\"nextToken\":\"" + token + "\"}", 200); + second.then().body("taskArns", hasSize(1)); + assertEquals(null, second.jsonPath().getString("nextToken"), + "the last page carries no token"); + } @Test void onlyTheDocumentedUpdatesRollTheServiceDeployment() { @@ -553,6 +626,127 @@ class EcsFargateEdgeCaseIntegrationTest { .then().body("message", containsString("being deleted")); } + @Test + void listTaskDefinitionsDefaultsToActiveAndOrdersByRevision() { + for (int i = 0; i < 11; i++) { + registerSize("edge-list-td", "256", "512", 200); + } + call("DeregisterTaskDefinition", "{\"taskDefinition\":\"edge-list-td:1\"}", 200); + + List active = call("ListTaskDefinitions", + "{\"familyPrefix\":\"edge-list-td\"}", 200).jsonPath().getList("taskDefinitionArns"); + assertFalse(active.stream().anyMatch(arn -> arn.endsWith("edge-list-td:1")), + "a deregistered revision is not listed by default"); + // Ascending by revision, so revision 11 comes after revision 2 rather than before it. + assertTrue(active.getFirst().endsWith(":2"), "the lowest active revision comes first: " + active); + assertTrue(active.getLast().endsWith(":11"), "the newest revision comes last: " + active); + + List descending = call("ListTaskDefinitions", + "{\"familyPrefix\":\"edge-list-td\",\"sort\":\"DESC\"}", 200) + .jsonPath().getList("taskDefinitionArns"); + assertTrue(descending.getFirst().endsWith(":11"), "DESC lists the newest first: " + descending); + + List inactive = call("ListTaskDefinitions", + "{\"familyPrefix\":\"edge-list-td\",\"status\":\"INACTIVE\"}", 200) + .jsonPath().getList("taskDefinitionArns"); + assertEquals(1, inactive.size(), "only the deregistered revision is INACTIVE"); + + Response firstPage = call("ListTaskDefinitions", + "{\"familyPrefix\":\"edge-list-td\",\"maxResults\":3}", 200); + firstPage.then().body("taskDefinitionArns", hasSize(3)); + assertTrue(firstPage.jsonPath().getString("nextToken") != null, + "a truncated listing returns a token"); + } + + @Test + void listServicesFiltersAndPagesTheWayAwsDoes() { + String family = seed("edge-list-services"); + for (int i = 0; i < 12; i++) { + call("CreateService", "{\"cluster\":\"" + CLUSTER + "\",\"serviceName\":\"edge-svc-" + i + + "\",\"taskDefinition\":\"" + family + "\",\"desiredCount\":0," + + "\"launchType\":\"FARGATE\"," + NETWORK + "}", 200); + } + + // ListServices pages ten at a time by default, unlike the other listings. + Response defaultPage = call("ListServices", "{\"cluster\":\"" + CLUSTER + "\"}", 200); + defaultPage.then().body("serviceArns", hasSize(10)); + assertTrue(defaultPage.jsonPath().getString("nextToken") != null, + "a truncated listing returns a token"); + + assertTrue(call("ListServices", "{\"cluster\":\"" + CLUSTER + + "\",\"launchType\":\"EC2\",\"maxResults\":100}", 200) + .jsonPath().getList("serviceArns").isEmpty(), "no service here runs on EC2"); + assertFalse(call("ListServices", "{\"cluster\":\"" + CLUSTER + + "\",\"launchType\":\"FARGATE\",\"maxResults\":100}", 200) + .jsonPath().getList("serviceArns").isEmpty(), "the Fargate services are listed"); + assertTrue(call("ListServices", "{\"cluster\":\"" + CLUSTER + + "\",\"schedulingStrategy\":\"DAEMON\",\"maxResults\":100}", 200) + .jsonPath().getList("serviceArns").isEmpty(), "none of these are daemons"); + } + + @Test + void listTaskDefinitionFamiliesFiltersByWhetherARevisionIsActive() { + registerSize("edge-family-active", "256", "512", 200); + registerSize("edge-family-gone", "256", "512", 200); + call("DeregisterTaskDefinition", "{\"taskDefinition\":\"edge-family-gone:1\"}", 200); + + // Both are listed without a status, which is AWS's default. + List all = call("ListTaskDefinitionFamilies", + "{\"familyPrefix\":\"edge-family-\",\"maxResults\":100}", 200) + .jsonPath().getList("families"); + assertTrue(all.containsAll(List.of("edge-family-active", "edge-family-gone")), all.toString()); + + assertEquals(List.of("edge-family-active"), call("ListTaskDefinitionFamilies", + "{\"familyPrefix\":\"edge-family-\",\"status\":\"ACTIVE\",\"maxResults\":100}", 200) + .jsonPath().getList("families")); + assertEquals(List.of("edge-family-gone"), call("ListTaskDefinitionFamilies", + "{\"familyPrefix\":\"edge-family-\",\"status\":\"INACTIVE\",\"maxResults\":100}", 200) + .jsonPath().getList("families")); + } + + @Test + void describeClustersWithholdsEverythingTheIncludeDidNotAskFor() { + String cluster = "edge-include-cluster"; + call("CreateCluster", "{\"clusterName\":\"" + cluster + "\"," + + "\"settings\":[{\"name\":\"containerInsights\",\"value\":\"enabled\"}]," + + "\"tags\":[{\"key\":\"team\",\"value\":\"platform\"}]," + + "\"configuration\":{\"executeCommandConfiguration\":{\"logging\":\"DEFAULT\"}}}", 200); + + Response bare = call("DescribeClusters", "{\"clusters\":[\"" + cluster + "\"]}", 200); + bare.then() + .body("clusters[0].clusterName", equalTo(cluster)) + .body("clusters[0].settings", nullValue()) + .body("clusters[0].tags", nullValue()) + .body("clusters[0].statistics", nullValue()) + .body("clusters[0].attachments", nullValue()) + .body("clusters[0].configuration", nullValue()); + + call("DescribeClusters", "{\"clusters\":[\"" + cluster + "\"]," + + "\"include\":[\"SETTINGS\",\"TAGS\",\"STATISTICS\",\"ATTACHMENTS\",\"CONFIGURATIONS\"]}", 200) + .then() + .body("clusters[0].settings", hasSize(1)) + .body("clusters[0].tags", hasSize(1)) + .body("clusters[0].attachments", hasSize(0)) + .body("clusters[0].configuration.executeCommandConfiguration.logging", equalTo("DEFAULT")) + .body("clusters[0].statistics", hasSize(8)) + .body("clusters[0].statistics.find { it.name == 'runningFargateTasksCount' }.value", + equalTo("0")); + + call("DescribeClusters", "{\"clusters\":[\"" + cluster + "\"],\"include\":[\"NOPE\"]}", 400); + } + + @Test + void describeClustersReportsAnUnknownClusterAsMissingRatherThanDroppingIt() { + call("CreateCluster", "{\"clusterName\":\"" + CLUSTER + "\"}", 200); + + call("DescribeClusters", "{\"clusters\":[\"" + CLUSTER + "\",\"edge-no-such-cluster\"]}", 200) + .then() + .body("clusters", hasSize(1)) + .body("failures", hasSize(1)) + .body("failures[0].reason", equalTo("MISSING")) + .body("failures[0].arn", containsString("cluster/edge-no-such-cluster")); + } + @Test void describeTasksReportsAnUnknownTaskAsMissingRatherThanDroppingIt() { call("CreateCluster", "{\"clusterName\":\"" + CLUSTER + "\"}", 200); @@ -564,6 +758,399 @@ class EcsFargateEdgeCaseIntegrationTest { .body("failures[0].reason", equalTo("MISSING")); } + @Test + void listClustersPagesTheWayAwsDoes() { + for (int i = 0; i < 3; i++) { + call("CreateCluster", "{\"clusterName\":\"edge-page-cluster-" + i + "\"}", 200); + } + + Response first = call("ListClusters", "{\"maxResults\":1}", 200); + first.then().body("clusterArns", hasSize(1)).body("nextToken", notNullValue()); + + String token = first.jsonPath().getString("nextToken"); + Response second = call("ListClusters", "{\"maxResults\":1,\"nextToken\":\"" + token + "\"}", 200); + second.then().body("clusterArns", hasSize(1)); + assertNotEquals(first.jsonPath().getString("clusterArns[0]"), + second.jsonPath().getString("clusterArns[0]")); + + // No maxResults pages a hundred at a time, so a handful of clusters comes back whole. + call("ListClusters", "{}", 200).then().body("nextToken", nullValue()); + } + + @Test + void clusterStatisticsCountRunningFargateTasks() { + String cluster = "edge-stats-cluster"; + call("CreateCluster", "{\"clusterName\":\"" + cluster + "\"}", 200); + registerSize("edge-stats", "256", "512", 200); + call("RunTask", "{\"cluster\":\"" + cluster + "\",\"taskDefinition\":\"edge-stats\"," + + "\"launchType\":\"FARGATE\"," + NETWORK + "}", 200); + + List> statistics = call("DescribeClusters", + "{\"clusters\":[\"" + cluster + "\"],\"include\":[\"STATISTICS\"]}", 200) + .jsonPath().getList("clusters[0].statistics"); + + assertEquals("1", statistics.stream() + .filter(s -> "runningFargateTasksCount".equals(s.get("name"))) + .findFirst().orElseThrow().get("value")); + assertEquals("0", statistics.stream() + .filter(s -> "runningEC2TasksCount".equals(s.get("name"))) + .findFirst().orElseThrow().get("value")); + } + + // ── Task sets ───────────────────────────────────────────────────────────── + + /** Creates an EXTERNAL-controller service, which is the only kind that can hold task sets. */ + private static String seedExternalService(String name) { + String family = seed(name + "-td"); + call("CreateService", "{\"cluster\":\"" + CLUSTER + "\",\"serviceName\":\"" + name + "\"," + + "\"taskDefinition\":\"" + family + "\",\"desiredCount\":3," + + "\"deploymentController\":{\"type\":\"EXTERNAL\"}," + + "\"launchType\":\"FARGATE\"," + NETWORK + "}", 200); + return family; + } + + @Test + void aTaskSetNeedsAServiceThatUsesAnExternalDeploymentController() { + String family = seed("edge-rolling-td"); + call("CreateService", "{\"cluster\":\"" + CLUSTER + "\",\"serviceName\":\"edge-rolling-svc\"," + + "\"taskDefinition\":\"" + family + "\",\"desiredCount\":1," + + "\"launchType\":\"FARGATE\"," + NETWORK + "}", 200); + + call("CreateTaskSet", "{\"cluster\":\"" + CLUSTER + "\",\"service\":\"edge-rolling-svc\"," + + "\"taskDefinition\":\"" + family + "\"}", 400) + .then().body("message", containsString("EXTERNAL")); + } + + @Test + void aTaskSetRoundTripsItsMembersAndComputesItsDesiredCount() { + String family = seedExternalService("edge-taskset-svc"); + + Response created = call("CreateTaskSet", "{\"cluster\":\"" + CLUSTER + + "\",\"service\":\"edge-taskset-svc\",\"taskDefinition\":\"" + family + "\"," + + "\"launchType\":\"FARGATE\",\"externalId\":\"d-EXAMPLE\"," + + "\"scale\":{\"value\":50,\"unit\":\"PERCENT\"}," + + "\"networkConfiguration\":{\"awsvpcConfiguration\":{\"subnets\":" + + "[\"subnet-default-us-east-1-a\"]}}," + + "\"loadBalancers\":[{\"targetGroupArn\":\"arn:aws:elasticloadbalancing:us-east-1:" + + "000000000000:targetgroup/tg/1\",\"containerName\":\"app\",\"containerPort\":80}]," + + "\"tags\":[{\"key\":\"team\",\"value\":\"platform\"}]}", 200); + + created.then() + .body("taskSet.status", equalTo("ACTIVE")) + .body("taskSet.launchType", equalTo("FARGATE")) + .body("taskSet.platformVersion", equalTo("1.4.0")) + .body("taskSet.platformFamily", equalTo("Linux")) + .body("taskSet.externalId", equalTo("d-EXAMPLE")) + .body("taskSet.scale.value", equalTo(50.0f)) + .body("taskSet.scale.unit", equalTo("PERCENT")) + // 3 desired at 50 percent is 1.5, and AWS always rounds the computed count up. + .body("taskSet.computedDesiredCount", equalTo(2)) + // Floci places no tasks for a task set, so it is steady rather than for ever + // stabilising towards a count that nothing will ever reach. + .body("taskSet.stabilityStatus", equalTo("STEADY_STATE")) + .body("taskSet.stabilityStatusAt", notNullValue()) + .body("taskSet.networkConfiguration.awsvpcConfiguration.subnets", hasSize(1)) + .body("taskSet.loadBalancers[0].containerPort", equalTo(80)); + + String id = created.jsonPath().getString("taskSet.id"); + + // Tags come back from DescribeTaskSets only when the request asks for them. + call("DescribeTaskSets", "{\"cluster\":\"" + CLUSTER + "\",\"service\":\"edge-taskset-svc\"}", 200) + .then() + .body("taskSets[0].tags", nullValue()) + .body("taskSets[0].stabilityStatus", equalTo("STEADY_STATE")); + call("DescribeTaskSets", "{\"cluster\":\"" + CLUSTER + "\",\"service\":\"edge-taskset-svc\"," + + "\"include\":[\"TAGS\"]}", 200) + .then().body("taskSets[0].tags", hasSize(1)); + + // A scale change recomputes the desired count. + call("UpdateTaskSet", "{\"cluster\":\"" + CLUSTER + "\",\"service\":\"edge-taskset-svc\"," + + "\"taskSet\":\"" + id + "\",\"scale\":{\"value\":100,\"unit\":\"PERCENT\"}}", 200) + .then() + .body("taskSet.computedDesiredCount", equalTo(3)) + .body("taskSet.stabilityStatus", equalTo("STEADY_STATE")); + + // Deleting a task set that has not been scaled to zero needs force. + call("DeleteTaskSet", "{\"cluster\":\"" + CLUSTER + "\",\"service\":\"edge-taskset-svc\"," + + "\"taskSet\":\"" + id + "\"}", 400) + .then().body("message", containsString("scaled down to zero")); + call("DeleteTaskSet", "{\"cluster\":\"" + CLUSTER + "\",\"service\":\"edge-taskset-svc\"," + + "\"taskSet\":\"" + id + "\",\"force\":true}", 200) + .then().body("taskSet.status", equalTo("DRAINING")); + } + + @Test + void describeTaskSetsReportsAnUnknownTaskSetAsMissing() { + seedExternalService("edge-taskset-missing"); + + call("DescribeTaskSets", "{\"cluster\":\"" + CLUSTER + "\"," + + "\"service\":\"edge-taskset-missing\",\"taskSets\":[\"ecs-svc/nope\"]}", 200) + .then() + .body("taskSets", hasSize(0)) + .body("failures", hasSize(1)) + .body("failures[0].reason", equalTo("MISSING")); + + call("UpdateTaskSet", "{\"cluster\":\"" + CLUSTER + "\",\"service\":\"edge-taskset-missing\"," + + "\"taskSet\":\"ecs-svc/nope\",\"scale\":{\"value\":100,\"unit\":\"PERCENT\"}}", 400) + .then().body("__type", containsString("TaskSetNotFoundException")); + } + + @Test + void aTaskSetCannotNameBothALaunchTypeAndACapacityProviderStrategy() { + String family = seedExternalService("edge-taskset-both"); + + call("CreateTaskSet", "{\"cluster\":\"" + CLUSTER + "\",\"service\":\"edge-taskset-both\"," + + "\"taskDefinition\":\"" + family + "\",\"launchType\":\"FARGATE\"," + + "\"capacityProviderStrategy\":[{\"capacityProvider\":\"FARGATE_SPOT\",\"weight\":1}]}", 400) + .then().body("message", containsString("capacity provider strategy")); + } + + // ── Account settings and attributes ─────────────────────────────────────── + + @Test + void accountSettingsAreValidatedPerName() { + call("PutAccountSetting", "{\"name\":\"nonsenseSetting\",\"value\":\"enabled\"}", 400) + .then().body("message", containsString("Invalid account setting name")); + call("PutAccountSetting", "{\"name\":\"containerInsights\",\"value\":\"maybe\"}", 400) + .then().body("message", containsString("Invalid value")); + + // Two settings are not opt-in flags: a wait period in days and a log delivery mode. + call("PutAccountSetting", "{\"name\":\"fargateTaskRetirementWaitPeriod\",\"value\":\"14\"}", 200); + call("PutAccountSetting", "{\"name\":\"fargateTaskRetirementWaitPeriod\",\"value\":\"3\"}", 400); + call("PutAccountSetting", "{\"name\":\"defaultLogDriverMode\",\"value\":\"blocking\"}", 200); + call("PutAccountSetting", "{\"name\":\"defaultLogDriverMode\",\"value\":\"enabled\"}", 400); + // enhanced is a containerInsights value only. + call("PutAccountSetting", "{\"name\":\"containerInsights\",\"value\":\"enhanced\"}", 200); + call("PutAccountSetting", "{\"name\":\"awsvpcTrunking\",\"value\":\"enhanced\"}", 400); + } + + @Test + void anAccountSettingReportsItsPrincipalAndType() { + call("PutAccountSetting", "{\"name\":\"awsvpcTrunking\",\"value\":\"enabled\"," + + "\"principalArn\":\"arn:aws:iam::000000000000:user/edge\"}", 200) + .then() + .body("setting.name", equalTo("awsvpcTrunking")) + .body("setting.value", equalTo("enabled")) + .body("setting.principalArn", equalTo("arn:aws:iam::000000000000:user/edge")) + .body("setting.type", equalTo("user")); + + // A principal sees only what it set; effectiveSettings fills in the rest. + call("ListAccountSettings", "{\"principalArn\":\"arn:aws:iam::000000000000:user/edge\"," + + "\"name\":\"containerInsights\"}", 200) + .then().body("settings", hasSize(0)); + call("ListAccountSettings", "{\"principalArn\":\"arn:aws:iam::000000000000:user/edge\"," + + "\"name\":\"containerInsights\",\"effectiveSettings\":true}", 200) + .then().body("settings", hasSize(1)); + + // GuardDuty owns its setting on the account's behalf. + call("ListAccountSettings", "{\"name\":\"guardDutyActivate\",\"effectiveSettings\":true}", 200) + .then().body("settings[0].type", equalTo("aws_managed")); + } + + @Test + void effectiveAccountSettingsFallBackToTheAccountDefaultThenTheBuiltIn() { + String principal = "arn:aws:iam::000000000000:user/edge-fallback"; + + // Untouched, the built-in default applies. + call("ListAccountSettings", "{\"principalArn\":\"" + principal + "\"," + + "\"name\":\"awsvpcTrunking\",\"effectiveSettings\":true}", 200) + .then().body("settings[0].value", equalTo("disabled")); + + // The account default lives on the root user, which is where AWS keeps it too. + call("PutAccountSettingDefault", "{\"name\":\"awsvpcTrunking\",\"value\":\"enabled\"}", 200) + .then().body("setting.principalArn", containsString(":root")); + call("ListAccountSettings", "{\"principalArn\":\"" + principal + "\"," + + "\"name\":\"awsvpcTrunking\",\"effectiveSettings\":true}", 200) + .then().body("settings[0].value", equalTo("enabled")); + + // The principal's own setting wins over the account default. + call("PutAccountSetting", "{\"name\":\"awsvpcTrunking\",\"value\":\"disabled\"," + + "\"principalArn\":\"" + principal + "\"}", 200); + call("ListAccountSettings", "{\"principalArn\":\"" + principal + "\"," + + "\"name\":\"awsvpcTrunking\",\"effectiveSettings\":true}", 200) + .then().body("settings[0].value", equalTo("disabled")); + + // Deleting it falls back to the account default again. + call("DeleteAccountSetting", "{\"name\":\"awsvpcTrunking\",\"principalArn\":\"" + + principal + "\"}", 200) + .then().body("setting.value", equalTo("disabled")); + call("ListAccountSettings", "{\"principalArn\":\"" + principal + "\"," + + "\"name\":\"awsvpcTrunking\",\"effectiveSettings\":true}", 200) + .then().body("settings[0].value", equalTo("enabled")); + + // The full effective listing is eleven settings, which pages ten at a time. + Response page = call("ListAccountSettings", + "{\"principalArn\":\"" + principal + "\",\"effectiveSettings\":true}", 200); + page.then().body("settings", hasSize(10)).body("nextToken", notNullValue()); + call("ListAccountSettings", "{\"principalArn\":\"" + principal + "\"," + + "\"effectiveSettings\":true,\"nextToken\":\"" + page.jsonPath().getString("nextToken") + + "\"}", 200) + .then().body("settings", hasSize(1)).body("nextToken", nullValue()); + } + + @Test + void attributesAreScopedToTheirClusterAndNeedARegisteredTarget() { + String cluster = "edge-attr-cluster"; + String other = "edge-attr-other"; + call("CreateCluster", "{\"clusterName\":\"" + cluster + "\"}", 200); + call("CreateCluster", "{\"clusterName\":\"" + other + "\"}", 200); + + String instance = call("RegisterContainerInstance", "{\"cluster\":\"" + cluster + "\"}", 200) + .jsonPath().getString("containerInstance.containerInstanceArn"); + + // An attribute on a target the cluster does not have is a TargetNotFoundException. + call("PutAttributes", "{\"cluster\":\"" + cluster + "\",\"attributes\":" + + "[{\"name\":\"stack\",\"value\":\"prod\",\"targetType\":\"container-instance\"," + + "\"targetId\":\"nope\"}]}", 400) + .then().body("__type", containsString("TargetNotFoundException")); + + call("PutAttributes", "{\"cluster\":\"" + cluster + "\",\"attributes\":" + + "[{\"name\":\"stack\",\"value\":\"prod\",\"targetType\":\"container-instance\"," + + "\"targetId\":\"" + instance + "\"}]}", 200) + .then().body("attributes", hasSize(1)); + + // targetType is required, and container-instance is its only value. + call("ListAttributes", "{\"cluster\":\"" + cluster + "\"}", 400) + .then().body("message", containsString("targetType")); + call("ListAttributes", "{\"cluster\":\"" + cluster + "\",\"targetType\":\"task\"}", 400); + + call("ListAttributes", "{\"cluster\":\"" + cluster + "\"," + + "\"targetType\":\"container-instance\"}", 200) + .then().body("attributes.find { it.name == 'stack' }.value", equalTo("prod")); + + // The other cluster never sees it. + call("ListAttributes", "{\"cluster\":\"" + other + "\"," + + "\"targetType\":\"container-instance\"}", 200) + .then().body("attributes.findAll { it.name == 'stack' }", hasSize(0)); + } + + @Test + void aTargetTakesAtMostTenCustomAttributes() { + String cluster = "edge-attr-limit"; + call("CreateCluster", "{\"clusterName\":\"" + cluster + "\"}", 200); + String instance = call("RegisterContainerInstance", "{\"cluster\":\"" + cluster + "\"}", 200) + .jsonPath().getString("containerInstance.containerInstanceArn"); + + StringBuilder ten = new StringBuilder(); + for (int i = 0; i < 10; i++) { + if (i > 0) { ten.append(','); } + ten.append("{\"name\":\"a").append(i).append("\",\"value\":\"v\",") + .append("\"targetType\":\"container-instance\",\"targetId\":\"") + .append(instance).append("\"}"); + } + call("PutAttributes", "{\"cluster\":\"" + cluster + "\",\"attributes\":[" + ten + "]}", 200); + + call("PutAttributes", "{\"cluster\":\"" + cluster + "\",\"attributes\":" + + "[{\"name\":\"a10\",\"value\":\"v\",\"targetType\":\"container-instance\"," + + "\"targetId\":\"" + instance + "\"}]}", 400) + .then().body("__type", containsString("AttributeLimitExceededException")); + } + + // ── Container instances ─────────────────────────────────────────────────── + + @Test + void aRegisteredContainerInstanceReportsWhatTheAgentSent() { + String cluster = "edge-ci-register"; + call("CreateCluster", "{\"clusterName\":\"" + cluster + "\"}", 200); + + call("RegisterContainerInstance", "{\"cluster\":\"" + cluster + "\"," + + "\"versionInfo\":{\"agentVersion\":\"1.79.0\",\"agentHash\":\"abc1234\"," + + "\"dockerVersion\":\"DockerVersion: 24.0.5\"}," + + "\"totalResources\":[{\"name\":\"CPU\",\"type\":\"INTEGER\",\"integerValue\":4096}," + + "{\"name\":\"MEMORY\",\"type\":\"INTEGER\",\"integerValue\":7482}]," + + "\"tags\":[{\"key\":\"fleet\",\"value\":\"batch\"}]}", 200) + .then() + .body("containerInstance.status", equalTo("ACTIVE")) + .body("containerInstance.registeredAt", notNullValue()) + .body("containerInstance.version", equalTo(1)) + // versionInfo is where the agent version lives; there is no top-level agentVersion. + .body("containerInstance.agentVersion", nullValue()) + .body("containerInstance.versionInfo.agentVersion", equalTo("1.79.0")) + .body("containerInstance.versionInfo.dockerVersion", equalTo("DockerVersion: 24.0.5")) + .body("containerInstance.registeredResources", hasSize(2)) + .body("containerInstance.remainingResources", hasSize(2)) + .body("containerInstance.tags", hasSize(1)); + + call("DescribeClusters", "{\"clusters\":[\"" + cluster + "\"]}", 200) + .then().body("clusters[0].registeredContainerInstancesCount", equalTo(1)); + } + + @Test + void aDeregisteredContainerInstanceStaysDescribableAsInactive() { + String cluster = "edge-ci-deregister"; + call("CreateCluster", "{\"clusterName\":\"" + cluster + "\"}", 200); + String instance = call("RegisterContainerInstance", "{\"cluster\":\"" + cluster + "\"}", 200) + .jsonPath().getString("containerInstance.containerInstanceArn"); + + call("DeregisterContainerInstance", "{\"cluster\":\"" + cluster + "\"," + + "\"containerInstance\":\"" + instance + "\"}", 200) + .then().body("containerInstance.status", equalTo("INACTIVE")); + + // AWS keeps answering a describe for a deregistered instance. + call("DescribeContainerInstances", "{\"cluster\":\"" + cluster + "\"," + + "\"containerInstances\":[\"" + instance + "\"]}", 200) + .then() + .body("containerInstances", hasSize(1)) + .body("containerInstances[0].status", equalTo("INACTIVE")); + + // The default listing excludes it, and only ACTIVE and DRAINING instances are registered. + call("ListContainerInstances", "{\"cluster\":\"" + cluster + "\"}", 200) + .then().body("containerInstanceArns", hasSize(0)); + call("DescribeClusters", "{\"clusters\":[\"" + cluster + "\"]}", 200) + .then().body("clusters[0].registeredContainerInstancesCount", equalTo(0)); + } + + @Test + void containerInstanceStateOnlyMovesBetweenActiveAndDraining() { + String cluster = "edge-ci-state"; + call("CreateCluster", "{\"clusterName\":\"" + cluster + "\"}", 200); + String instance = call("RegisterContainerInstance", "{\"cluster\":\"" + cluster + "\"}", 200) + .jsonPath().getString("containerInstance.containerInstanceArn"); + + call("UpdateContainerInstancesState", "{\"cluster\":\"" + cluster + "\"," + + "\"containerInstances\":[\"" + instance + "\"],\"status\":\"REGISTERING\"}", 400) + .then().body("message", containsString("ACTIVE and DRAINING")); + + call("UpdateContainerInstancesState", "{\"cluster\":\"" + cluster + "\"," + + "\"containerInstances\":[\"" + instance + "\"],\"status\":\"DRAINING\"}", 200) + .then().body("containerInstances[0].status", equalTo("DRAINING")); + + // A DRAINING instance is not ACTIVE, so it cannot be set to DRAINING again. + call("UpdateContainerInstancesState", "{\"cluster\":\"" + cluster + "\"," + + "\"containerInstances\":[\"" + instance + "\"],\"status\":\"DRAINING\"}", 400) + .then().body("message", containsString("must be ACTIVE")); + + // A DRAINING instance still counts as registered and still lists by default. + call("ListContainerInstances", "{\"cluster\":\"" + cluster + "\"}", 200) + .then().body("containerInstanceArns", hasSize(1)); + call("ListContainerInstances", "{\"cluster\":\"" + cluster + "\",\"status\":\"ACTIVE\"}", 200) + .then().body("containerInstanceArns", hasSize(0)); + call("ListContainerInstances", "{\"cluster\":\"" + cluster + "\",\"status\":\"nonsense\"}", 400); + + call("UpdateContainerInstancesState", "{\"cluster\":\"" + cluster + "\"," + + "\"containerInstances\":[\"" + instance + "\"],\"status\":\"ACTIVE\"}", 200) + .then().body("containerInstances[0].status", equalTo("ACTIVE")); + } + + @Test + void anUnknownContainerInstanceIsAFailureNotAnError() { + String cluster = "edge-ci-missing"; + call("CreateCluster", "{\"clusterName\":\"" + cluster + "\"}", 200); + + call("DescribeContainerInstances", "{\"cluster\":\"" + cluster + "\"," + + "\"containerInstances\":[\"no-such-instance\"]}", 200) + .then() + .body("containerInstances", hasSize(0)) + .body("failures", hasSize(1)) + .body("failures[0].reason", equalTo("MISSING")); + + call("UpdateContainerInstancesState", "{\"cluster\":\"" + cluster + "\"," + + "\"containerInstances\":[\"no-such-instance\"],\"status\":\"DRAINING\"}", 200) + .then() + .body("containerInstances", hasSize(0)) + .body("failures[0].reason", equalTo("MISSING")); + } + // ── Derived compatibilities and requiresAttributes ──────────────────────── @Test @@ -619,6 +1206,65 @@ class EcsFargateEdgeCaseIntegrationTest { .then().body("message", containsString("containerInstances")); } + // ── The Service shape's own members ────────────────────────────────────── + + @Test + void aServiceReportsItsEventsAndTaskSetsAndWhatItsDeploymentRunsOn() { + String family = seed("edge-svc-shape-td"); + call("CreateService", "{\"cluster\":\"" + CLUSTER + "\",\"serviceName\":\"edge-svc-shape\"," + + "\"taskDefinition\":\"" + family + "\",\"desiredCount\":0," + + "\"launchType\":\"FARGATE\"," + NETWORK + "}", 200); + + call("DescribeServices", "{\"cluster\":\"" + CLUSTER + + "\",\"services\":[\"edge-svc-shape\"]}", 200) + .then() + // Both members are always present, so a client can tell an empty answer from one + // the emulator never wrote. + .body("services[0].taskSets", hasSize(0)) + .body("services[0].events", hasSize(1)) + .body("services[0].events[0].message", + containsString("(service edge-svc-shape) has reached a steady state.")) + .body("services[0].events[0].id", notNullValue()) + .body("services[0].events[0].createdAt", notNullValue()) + // The deployment carries the placement the service runs under, not just its id. + .body("services[0].deployments[0].launchType", equalTo("FARGATE")) + .body("services[0].deployments[0].platformVersion", equalTo("1.4.0")) + .body("services[0].deployments[0].platformFamily", equalTo("Linux")) + .body("services[0].deployments[0].networkConfiguration.awsvpcConfiguration.subnets", + hasSize(1)); + } + + @Test + void aServicesTaskSetsAreVisibleOnTheServiceItself() { + String family = seedExternalService("edge-svc-tasksets"); + call("CreateTaskSet", "{\"cluster\":\"" + CLUSTER + "\",\"service\":\"edge-svc-tasksets\"," + + "\"taskDefinition\":\"" + family + "\",\"launchType\":\"FARGATE\"}", 200); + + call("DescribeServices", "{\"cluster\":\"" + CLUSTER + + "\",\"services\":[\"edge-svc-tasksets\"]}", 200) + .then() + .body("services[0].taskSets", hasSize(1)) + .body("services[0].taskSets[0].status", equalTo("ACTIVE")); + } + + // ── Cluster deletion ───────────────────────────────────────────────────── + + @Test + void aClusterWithRegisteredContainerInstancesCannotBeDeleted() { + String cluster = "edge-delete-with-instances"; + call("CreateCluster", "{\"clusterName\":\"" + cluster + "\"}", 200); + String instance = call("RegisterContainerInstance", "{\"cluster\":\"" + cluster + "\"}", 200) + .jsonPath().getString("containerInstance.containerInstanceArn"); + + call("DeleteCluster", "{\"cluster\":\"" + cluster + "\"}", 400) + .then().body("__type", containsString("ClusterContainsContainerInstancesException")); + + call("DeregisterContainerInstance", "{\"cluster\":\"" + cluster + "\"," + + "\"containerInstance\":\"" + instance + "\"}", 200); + call("DeleteCluster", "{\"cluster\":\"" + cluster + "\"}", 200) + .then().body("cluster.status", equalTo("INACTIVE")); + } + // ── Capacity providers ─────────────────────────────────────────────────── @Test @@ -775,6 +1421,9 @@ class EcsFargateEdgeCaseIntegrationTest { + "\"networkMode\":\"AWSVPC\"," + "\"containerDefinitions\":[{\"name\":\"app\",\"image\":\"nginx:latest\"}]}", 400) .then().body("message", containsString("networkMode")); + + call("ListContainerInstances", "{\"cluster\":\"" + CLUSTER + "\",\"status\":\"BOGUS\"}", 400) + .then().body("message", containsString("status")); } @Test @@ -791,4 +1440,95 @@ class EcsFargateEdgeCaseIntegrationTest { + "\"tags\":[{\"key\":\"\",\"value\":\"v\"}]}", 400) .then().body("message", containsString("Tag keys")); } + + // ── Container instance health ──────────────────────────────────────────── + + @Test + void containerInstanceHealthIsWithheldUntilTheRequestAsksForIt() { + String cluster = "edge-ci-health"; + call("CreateCluster", "{\"clusterName\":\"" + cluster + "\"}", 200); + String instance = call("RegisterContainerInstance", "{\"cluster\":\"" + cluster + "\"}", 200) + .jsonPath().getString("containerInstance.containerInstanceArn"); + String describe = "{\"cluster\":\"" + cluster + "\",\"containerInstances\":[\"" + + instance + "\"]"; + + call("DescribeContainerInstances", describe + "}", 200) + .then().body("containerInstances[0].healthStatus", nullValue()); + + call("DescribeContainerInstances", describe + ",\"include\":[\"CONTAINER_INSTANCE_HEALTH\"]}", 200) + .then() + .body("containerInstances[0].healthStatus.overallStatus", equalTo("OK")) + .body("containerInstances[0].healthStatus.details[0].type", + equalTo("AGENT_CONNECTIVITY")); + + call("DescribeContainerInstances", describe + ",\"include\":[\"NOPE\"]}", 400) + .then().body("message", containsString("include")); + } + + // ── Service deployments and revisions ──────────────────────────────────── + + @Test + void aServiceDeploymentPointsAtTheRevisionItDeployed() { + String family = seed("edge-deployment-td"); + call("CreateService", "{\"cluster\":\"" + CLUSTER + "\",\"serviceName\":\"edge-deployment-svc\"," + + "\"taskDefinition\":\"" + family + "\",\"desiredCount\":0," + + "\"launchType\":\"FARGATE\"," + NETWORK + "}", 200); + + Response listed = call("ListServiceDeployments", "{\"cluster\":\"" + CLUSTER + + "\",\"service\":\"edge-deployment-svc\"}", 200); + listed.then() + .body("serviceDeployments", hasSize(1)) + .body("serviceDeployments[0].targetServiceRevisionArn", + containsString("service-revision/")) + .body("serviceDeployments[0].startedAt", notNullValue()) + .body("serviceDeployments[0].finishedAt", notNullValue()); + + String deploymentArn = listed.jsonPath().getString("serviceDeployments[0].serviceDeploymentArn"); + String revisionArn = listed.jsonPath().getString("serviceDeployments[0].targetServiceRevisionArn"); + + call("DescribeServiceDeployments", "{\"serviceDeploymentArns\":[\"" + deploymentArn + "\"]}", 200) + .then() + .body("serviceDeployments[0].status", equalTo("SUCCESSFUL")) + .body("serviceDeployments[0].targetServiceRevision.arn", equalTo(revisionArn)) + .body("serviceDeployments[0].targetServiceRevision.requestedTaskCount", equalTo(0)) + // AWS's ServiceDeployment shape has no taskDefinition; the revision carries it. + .body("serviceDeployments[0].taskDefinition", nullValue()); + + // The service points back at both, so a caller never has to list first. + call("DescribeServices", "{\"cluster\":\"" + CLUSTER + + "\",\"services\":[\"edge-deployment-svc\"]}", 200) + .then() + .body("services[0].currentServiceDeployment", equalTo(deploymentArn)) + .body("services[0].currentServiceRevisions[0].arn", equalTo(revisionArn)); + } + + @Test + void aServiceRevisionSnapshotsTheConfigurationItWasCreatedWith() { + String family = seed("edge-revision-td"); + call("CreateService", "{\"cluster\":\"" + CLUSTER + "\",\"serviceName\":\"edge-revision-svc\"," + + "\"taskDefinition\":\"" + family + "\",\"desiredCount\":0," + + "\"launchType\":\"FARGATE\"," + NETWORK + "}", 200); + + String revisionArn = call("ListServiceDeployments", "{\"cluster\":\"" + CLUSTER + + "\",\"service\":\"edge-revision-svc\"}", 200) + .jsonPath().getString("serviceDeployments[0].targetServiceRevisionArn"); + + call("DescribeServiceRevisions", "{\"serviceRevisionArns\":[\"" + revisionArn + "\"]}", 200) + .then() + .body("serviceRevisions[0].taskDefinition", containsString(family)) + .body("serviceRevisions[0].launchType", equalTo("FARGATE")) + .body("serviceRevisions[0].platformVersion", equalTo("1.4.0")) + .body("serviceRevisions[0].platformFamily", equalTo("Linux")) + .body("serviceRevisions[0].networkConfiguration.awsvpcConfiguration.subnets", + hasSize(1)) + .body("serviceRevisions[0].containerImages[0].containerName", equalTo("app")) + .body("serviceRevisions[0].containerImages[0].image", equalTo("nginx:latest")) + .body("serviceRevisions[0].guardDutyEnabled", equalTo(false)); + + call("DescribeServiceRevisions", "{\"serviceRevisionArns\":[\"arn:aws:ecs:us-east-1:" + + "000000000000:service-revision/nope\"]}", 200) + .then() + .body("serviceRevisions", hasSize(0)) + .body("failures[0].reason", equalTo("MISSING")); + } } diff --git a/src/test/java/io/github/hectorvent/floci/services/ecs/EcsIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ecs/EcsIntegrationTest.java index fd1bb6d2f6..863ace178e 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ecs/EcsIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ecs/EcsIntegrationTest.java @@ -420,8 +420,10 @@ class EcsIntegrationTest { @Test @Order(18) void listTaskDefinitions() { + // Scoped by family: the unfiltered listing pages a hundred at a time, as it does on AWS, + // and the rest of the suite registers more families than fit on one page. ecs("ListTaskDefinitions") - .body("{}") + .body("{\"familyPrefix\":\"" + TASK_DEF_FAMILY + "\"}") .when() .post("/") .then() @@ -432,8 +434,9 @@ class EcsIntegrationTest { @Test @Order(19) void listTaskDefinitionFamilies() { + // Scoped for the same reason as listTaskDefinitions: this listing pages too. ecs("ListTaskDefinitionFamilies") - .body("{}") + .body("{\"familyPrefix\":\"" + TASK_DEF_FAMILY + "\"}") .when() .post("/") .then() @@ -1011,7 +1014,32 @@ class EcsIntegrationTest { @Test @Order(53) + void deleteClusterRejectsAClusterThatStillHasServices() { + ecs("DeleteCluster") + .body(""" + {"cluster": "%s"} + """.formatted(CLUSTER_NAME)) + .when() + .post("/") + .then() + .statusCode(400) + .body("__type", containsString("ClusterContainsServicesException")); + } + + @Test + @Order(54) void deleteCluster() { + // zero-count-svc outlives the service tests and keeps the cluster non-empty, which is + // exactly what AWS refuses to delete over. + ecs("DeleteService") + .body(""" + {"cluster": "%s", "service": "zero-count-svc"} + """.formatted(CLUSTER_NAME)) + .when() + .post("/") + .then() + .statusCode(200); + ecs("DeleteCluster") .body(""" {"cluster": "%s"} @@ -1025,7 +1053,7 @@ class EcsIntegrationTest { } @Test - @Order(54) + @Order(55) void deleteClusterNotFound() { ecs("DeleteCluster") .body(""" diff --git a/src/test/java/io/github/hectorvent/floci/services/ecs/EcsServiceDaemonSchedulingTest.java b/src/test/java/io/github/hectorvent/floci/services/ecs/EcsServiceDaemonSchedulingTest.java index 6523a5ef5e..cbb7543cd8 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ecs/EcsServiceDaemonSchedulingTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ecs/EcsServiceDaemonSchedulingTest.java @@ -92,7 +92,10 @@ class EcsServiceDaemonSchedulingTest { assertEquals(0, runningTasks(service).size()); service.reconcileServices(); - long attempts = service.describeTasks(null, service.listTasks(null, null, null, null, REGION), REGION).size(); + // Both attempts died on launch, so they are the STOPPED tasks: ListTasks only returns the + // running ones unless a desired status is asked for, as on AWS. + long attempts = service.describeTasks(null, + service.listTasks(null, null, "STOPPED", null, REGION), REGION).size(); assertEquals(2, attempts, "the uncovered instance is retried on the next tick"); } diff --git a/src/test/java/io/github/hectorvent/floci/services/ecs/EcsServicePersistenceTest.java b/src/test/java/io/github/hectorvent/floci/services/ecs/EcsServicePersistenceTest.java index abd7b960a9..93a646880e 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ecs/EcsServicePersistenceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ecs/EcsServicePersistenceTest.java @@ -51,9 +51,12 @@ class EcsServicePersistenceTest { Map.of("tier", "web"), REGION); EcsServiceModel svc = first.createService("app-cluster", "web-svc", td.getTaskDefinitionArn(), 0, LaunchType.FARGATE, List.of(), awsvpcConfiguration(), Map.of("team", "payments"), REGION); + // An attribute names a container instance of the cluster, as it must on AWS. + String instanceArn = first.registerContainerInstance("app-cluster", null, List.of(), REGION) + .getContainerInstanceArn(); first.putAttributes("app-cluster", - List.of(new Attribute("stack", "prod", "container-instance", "ci-1")), REGION); - first.putAccountSetting("containerInsights", "enabled"); + List.of(new Attribute("stack", "prod", "container-instance", instanceArn)), REGION); + first.putAccountSetting("containerInsights", "enabled", null); // Simulate restart: a fresh instance reloading from the same shared store. EcsService reloaded = serviceWithStorage(storage); @@ -70,10 +73,10 @@ class EcsServicePersistenceTest { List.of(svc.getServiceArn()), REGION).getFirst(); assertEquals("payments", reloadedSvc.getTags().get("team")); - assertEquals("prod", reloaded.listAttributes("app-cluster", null, "stack", null, REGION) - .getFirst().value()); - assertEquals("enabled", reloaded.listAccountSettings("containerInsights", null) - .getFirst().getValue()); + assertEquals("prod", reloaded.listAttributes("app-cluster", "container-instance", "stack", + null, null, null, REGION).attributes().getFirst().value()); + assertEquals("enabled", reloaded.listAccountSettings("containerInsights", null, null, + false, null, null).settings().getFirst().value()); // latestRevisions persisted: registering the same family again yields the next revision. assertEquals(2, reloaded.registerTaskDefinition("web", List.of(container("app", "nginx:latest")), @@ -88,15 +91,18 @@ class EcsServicePersistenceTest { EcsCluster cluster = first.createCluster("c1", Map.of(), REGION); first.tagResource(cluster.getClusterArn(), Map.of("env", "test", "owner", "qa")); first.untagResource(cluster.getClusterArn(), List.of("owner")); - first.putAttributes("c1", List.of(new Attribute("a", "1", "container-instance", "t1")), REGION); - first.deleteAttributes("c1", List.of(new Attribute("a", "1", "container-instance", "t1")), REGION); + String instanceArn = first.registerContainerInstance("c1", null, List.of(), REGION) + .getContainerInstanceArn(); + first.putAttributes("c1", List.of(new Attribute("a", "1", "container-instance", instanceArn)), REGION); + first.deleteAttributes("c1", List.of(new Attribute("a", "1", "container-instance", instanceArn)), REGION); EcsService reloaded = serviceWithStorage(storage); Map tags = reloaded.listTagsForResource(cluster.getClusterArn()); assertEquals("test", tags.get("env")); assertFalse(tags.containsKey("owner"), "untagged key must not reappear after restart"); - assertTrue(reloaded.listAttributes("c1", null, "a", null, REGION).isEmpty(), + assertTrue(reloaded.listAttributes("c1", "container-instance", "a", null, null, null, REGION) + .attributes().isEmpty(), "deleted attribute must not reappear after restart"); }