From bf1152e144e69b1f96f78d139562cfaf883b6e58 Mon Sep 17 00:00:00 2001 From: Abhigya Date: Mon, 21 Sep 2026 08:08:32 +0530 Subject: [PATCH] feat(ecs): complete the fargate launch surface (#4017) Floci accepted a Fargate task definition and ran it, but most of the launch surface was dropped on the way through: members that AWS echoes back went missing from responses, launch type resolution never validated what it resolved, and the runtime ignored the sizing the task asked for. Task definitions. A definition round-trips whole. Members that change behaviour are typed (ephemeralStorage, dependsOn, environmentFiles, port mapping name / appProtocol / containerPortRange, pidMode, ipcMode and the container-level members the parser used to drop); members Floci does not act on go through EcsJsonPassthrough, so an unimplemented volume configuration comes back as it was sent rather than vanishing. compatibilities is derived from the definition rather than echoed from requiresCompatibilities, requiresAttributes names the capabilities the definition needs, and a revision carries its registeredAt, deregisteredAt and deleteRequestedAt through the ACTIVE / INACTIVE / DELETE_IN_PROGRESS lifecycle. Validation. Fargate task sizes are validated per CPU architecture and operating system family, ephemeral storage against its 21-200 GiB range, container dependencies for unknown names and cycles, and the parameters Fargate does not support are rejected at registration with the exception type AWS documents for them, ClientException; the message text is Floci's, since AWS does not document the wording. Enum-typed members are validated at parse time and raise InvalidParameterException instead of being treated as absent, and tag cardinality and character limits are enforced across the operations that take tags. Launch. capacityProviderStrategy is distributed across its providers the way ECS distributes it, base first and the remainder by weight, with the cluster's default strategy applying when a request carries neither it nor a launch type. The strategy is validated against the bounds the ECS model gives it: at most 20 providers, weight 0 to 1,000, base 0 to 100,000, one base per strategy, and at least one provider of non-zero weight when a strategy names more than one, since a provider of weight 0 places nothing beyond its base. A task's CPU and memory reach the container, an awsvpc task gets an ENI per task and releases it when it stops, container dependencies are ordered with cycle detection, and mock mode reports per-container detail so a client running without Docker sees the same shape. The ENI allocation reaches into EC2, whose InvalidSubnetID.NotFound and InvalidGroup.NotFound are not in RunTask's error list, so an unknown subnet or security group is reported as the InvalidParameterException AWS returns. Verified against the AWS SDK for Java v2 and the AWS ECS API reference. Adds EcsFargateTaskIntegrationTest, EcsFargateTaskDefinitionIntegrationTest and EcsFargateEdgeCaseIntegrationTest, plus an SDK-based EcsFargateTest in the compatibility suite. --- .../java/com/floci/test/EcsFargateTest.java | 221 ++++ docs/services/ecs.md | 159 ++- .../floci/services/ec2/Ec2Service.java | 45 +- .../floci/services/ecs/EcsJsonHandler.java | 463 ++++++--- .../services/ecs/EcsJsonPassthrough.java | 62 ++ .../floci/services/ecs/EcsResponseWriter.java | 312 +++++- .../floci/services/ecs/EcsService.java | 982 ++++++++++++++++-- .../ecs/container/EcsContainerManager.java | 371 ++++++- .../services/ecs/container/EcsTaskHandle.java | 27 + .../model/CapacityProviderStrategyItem.java | 19 + .../floci/services/ecs/model/Container.java | 34 + .../ecs/model/ContainerDefinition.java | 85 ++ .../ecs/model/ContainerDependency.java | 18 + .../services/ecs/model/ContainerOverride.java | 18 + .../ecs/model/CreateClusterRequest.java | 13 + .../ecs/model/CreateServiceRequest.java | 7 + .../services/ecs/model/EcsLoadBalancer.java | 9 + .../services/ecs/model/EcsServiceModel.java | 7 + .../floci/services/ecs/model/EcsTask.java | 116 +++ .../services/ecs/model/EnvironmentFile.java | 11 + .../services/ecs/model/EphemeralStorage.java | 17 + .../floci/services/ecs/model/LaunchType.java | 2 +- .../services/ecs/model/ManagedAgent.java | 24 + .../floci/services/ecs/model/PortMapping.java | 14 +- .../model/RegisterTaskDefinitionRequest.java | 19 + .../services/ecs/model/RunTaskRequest.java | 45 +- .../services/ecs/model/TaskDefinition.java | 47 + .../ecs/model/TaskNetworkInterface.java | 14 + .../services/ecs/model/TaskOverride.java | 53 + .../ecs/model/UpdateServiceRequest.java | 8 + .../floci/services/ecs/model/Volume.java | 21 +- ...nEcsDeleteAfterRestoreIntegrationTest.java | 7 +- .../floci/services/ec2/Ec2ServiceTest.java | 78 ++ .../EcsFargateEdgeCaseIntegrationTest.java | 609 +++++++++++ ...sFargateTaskDefinitionIntegrationTest.java | 220 ++++ .../ecs/EcsFargateTaskIntegrationTest.java | 264 +++++ .../services/ecs/EcsIntegrationTest.java | 20 +- .../ecs/EcsServicePersistenceTest.java | 14 +- .../EcsContainerManagerSecurityGroupTest.java | 13 +- .../EventBridgeEcsRunTaskIntegrationTest.java | 8 +- 40 files changed, 4209 insertions(+), 267 deletions(-) create mode 100644 compatibility-tests/sdk-test-java/src/test/java/com/floci/test/EcsFargateTest.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/ecs/EcsJsonPassthrough.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/ecs/model/CapacityProviderStrategyItem.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/ecs/model/ContainerDependency.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/ecs/model/EnvironmentFile.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/ecs/model/EphemeralStorage.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/ecs/model/ManagedAgent.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/ecs/model/TaskNetworkInterface.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/ecs/model/TaskOverride.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/ecs/EcsFargateEdgeCaseIntegrationTest.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/ecs/EcsFargateTaskDefinitionIntegrationTest.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/ecs/EcsFargateTaskIntegrationTest.java 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 new file mode 100644 index 0000000000..6a12e16986 --- /dev/null +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/EcsFargateTest.java @@ -0,0 +1,221 @@ +package com.floci.test; + +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.MethodOrderer; +import org.junit.jupiter.api.Order; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; +import software.amazon.awssdk.services.ec2.Ec2Client; +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.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.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.EphemeralStorage; +import software.amazon.awssdk.services.ecs.model.LaunchType; +import software.amazon.awssdk.services.ecs.model.NetworkConfiguration; +import software.amazon.awssdk.services.ecs.model.NetworkMode; +import software.amazon.awssdk.services.ecs.model.RegisterTaskDefinitionRequest; +import software.amazon.awssdk.services.ecs.model.RunTaskRequest; +import software.amazon.awssdk.services.ecs.model.StopTaskRequest; +import software.amazon.awssdk.services.ecs.model.Task; +import software.amazon.awssdk.services.ecs.model.TaskDefinition; + +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +/** + * The Fargate launch type through a real SDK client: the members the generated model carries have + * to come back populated, not just be accepted on the way in. + */ +@DisplayName("ECS Fargate launch type") +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class EcsFargateTest { + + private static EcsClient ecs; + private static Ec2Client ec2; + private static String clusterName; + private static String family; + private static String subnetId; + private static String taskArn; + + @BeforeAll + static void setup() { + ecs = TestFixtures.ecsClient(); + ec2 = TestFixtures.ec2Client(); + String suffix = String.valueOf(System.currentTimeMillis() % 100000); + clusterName = "sdk-fargate-cluster-" + suffix; + family = "sdk-fargate-task-" + suffix; + subnetId = ec2.describeSubnets(DescribeSubnetsRequest.builder().build()) + .subnets().get(0).subnetId(); + ecs.createCluster(CreateClusterRequest.builder().clusterName(clusterName).build()); + } + + @AfterAll + static void cleanup() { + if (ecs == null) { + return; + } + try { + if (taskArn != null) { + ecs.stopTask(StopTaskRequest.builder().cluster(clusterName).task(taskArn).build()); + } + } catch (EcsException ignored) { + // The task may already have stopped; cleanup must not fail the run. + } + try { + ecs.deregisterTaskDefinition(DeregisterTaskDefinitionRequest.builder() + .taskDefinition(family + ":1").build()); + ecs.deleteTaskDefinitions(DeleteTaskDefinitionsRequest.builder() + .taskDefinitions(family + ":1").build()); + } catch (EcsException ignored) { + // Same: a failed registration leaves nothing to clean up. + } + ecs.close(); + ec2.close(); + } + + @Test + @Order(1) + @DisplayName("RegisterTaskDefinition - a Fargate definition round-trips its members") + void registerFargateTaskDefinition() { + TaskDefinition registered = ecs.registerTaskDefinition(RegisterTaskDefinitionRequest.builder() + .family(family) + .requiresCompatibilities(Compatibility.FARGATE) + .networkMode(NetworkMode.AWSVPC) + .cpu("512") + .memory("1024") + .ephemeralStorage(EphemeralStorage.builder().sizeInGiB(40).build()) + .containerDefinitions(ContainerDefinition.builder() + .name("app") + .image("nginx:alpine") + .essential(true) + .user("1000:1000") + .workingDirectory("/srv") + .readonlyRootFilesystem(true) + .stopTimeout(30) + .build()) + .build()).taskDefinition(); + + assertThat(registered.compatibilitiesAsStrings()).contains("FARGATE"); + assertThat(registered.ephemeralStorage().sizeInGiB()).isEqualTo(40); + assertThat(registered.registeredAt()).isNotNull(); + + TaskDefinition described = ecs.describeTaskDefinition(DescribeTaskDefinitionRequest.builder() + .taskDefinition(family).build()).taskDefinition(); + ContainerDefinition container = described.containerDefinitions().get(0); + assertThat(described.ephemeralStorage().sizeInGiB()).isEqualTo(40); + assertThat(container.user()).isEqualTo("1000:1000"); + assertThat(container.workingDirectory()).isEqualTo("/srv"); + assertThat(container.readonlyRootFilesystem()).isTrue(); + assertThat(container.stopTimeout()).isEqualTo(30); + } + + @Test + @Order(2) + @DisplayName("RegisterTaskDefinition - a size Fargate does not offer is rejected") + void rejectsAnInvalidFargateSize() { + assertThatThrownBy(() -> ecs.registerTaskDefinition(RegisterTaskDefinitionRequest.builder() + .family(family + "-invalid") + .requiresCompatibilities(Compatibility.FARGATE) + .networkMode(NetworkMode.AWSVPC) + .cpu("256") + .memory("4096") + .containerDefinitions(ContainerDefinition.builder() + .name("app").image("nginx:alpine").build()) + .build())) + .isInstanceOf(EcsException.class) + .hasMessageContaining("No Fargate configuration exists"); + } + + @Test + @Order(3) + @DisplayName("RunTask - a Fargate task reports its platform, ENI and ephemeral storage") + void runFargateTask() { + List tasks = ecs.runTask(RunTaskRequest.builder() + .cluster(clusterName) + .taskDefinition(family) + .launchType(LaunchType.FARGATE) + .enableExecuteCommand(true) + .networkConfiguration(NetworkConfiguration.builder() + .awsvpcConfiguration(AwsVpcConfiguration.builder() + .subnets(subnetId) + .build()) + .build()) + .build()).tasks(); + + assertThat(tasks).hasSize(1); + Task task = tasks.get(0); + taskArn = task.taskArn(); + + assertThat(task.launchType()).isEqualTo(LaunchType.FARGATE); + assertThat(task.platformVersion()).isNotBlank(); + assertThat(task.platformFamily()).isEqualTo("Linux"); + assertThat(task.ephemeralStorage().sizeInGiB()).isEqualTo(40); + assertThat(task.enableExecuteCommand()).isTrue(); + assertThat(task.group()).isEqualTo("family:" + family); + assertThat(task.attachments()).hasSize(1); + assertThat(task.attachments().get(0).type()).isEqualTo("ElasticNetworkInterface"); + assertThat(task.attachments().get(0).details()) + .anySatisfy(detail -> assertThat(detail.name()).isEqualTo("privateIPv4Address")); + + Task described = ecs.describeTasks(DescribeTasksRequest.builder() + .cluster(clusterName) + .tasks(taskArn) + .build()).tasks().get(0); + assertThat(described.connectivityAsString()).isEqualTo("CONNECTED"); + assertThat(described.healthStatusAsString()).isNotBlank(); + assertThat(described.version()).isPositive(); + } + + @Test + @Order(4) + @DisplayName("RunTask - FARGATE_SPOT places through the capacity provider") + void runTaskOnFargateSpot() { + Task task = ecs.runTask(RunTaskRequest.builder() + .cluster(clusterName) + .taskDefinition(family) + .capacityProviderStrategy(CapacityProviderStrategyItem.builder() + .capacityProvider("FARGATE_SPOT") + .weight(1) + .build()) + .networkConfiguration(NetworkConfiguration.builder() + .awsvpcConfiguration(AwsVpcConfiguration.builder() + .subnets(subnetId) + .build()) + .build()) + .build()).tasks().get(0); + + assertThat(task.capacityProviderName()).isEqualTo("FARGATE_SPOT"); + // A task reports the launch type its capacity provider resolves to, alongside the provider. + assertThat(task.launchType()).isEqualTo(LaunchType.FARGATE); + + ecs.stopTask(StopTaskRequest.builder() + .cluster(clusterName).task(task.taskArn()).build()); + } + + @Test + @Order(6) + @DisplayName("DescribeTasks - an unknown reference comes back as MISSING") + void describeReportsMissingRatherThanDroppingTheReference() { + DescribeTasksResponse tasks = ecs.describeTasks(DescribeTasksRequest.builder() + .cluster(clusterName) + .tasks("00000000000000000000000000000000") + .build()); + assertThat(tasks.tasks()).isEmpty(); + assertThat(tasks.failures()).singleElement() + .satisfies(failure -> assertThat(failure.reason()).isEqualTo("MISSING")); + } +} diff --git a/docs/services/ecs.md b/docs/services/ecs.md index afedf6d7a6..8072fd5337 100644 --- a/docs/services/ecs.md +++ b/docs/services/ecs.md @@ -5,6 +5,11 @@ ECS emulates clusters, task definitions, tasks, and services. In the default configuration tasks run as real Docker containers. Set `mock: true` (enabled automatically in tests) to run tasks as in-process stubs without Docker. +A value an enum-typed member does not have is rejected with `InvalidParameterException` rather +than treated as absent. That matters more than it sounds: a `launchType` of `EC22` silently +ignored would fall through to Floci's default and place the task on Fargate, which is neither +what the caller asked for nor what AWS answers. + ## Supported Operations ### Clusters @@ -30,11 +35,59 @@ ECS emulates clusters, task definitions, tasks, and services. In the default con | `DeregisterTaskDefinition` | Mark a revision INACTIVE | | `DeleteTaskDefinitions` | Delete one or more task definitions | -`runtimePlatform` and a container's `logConfiguration` are stored and returned exactly as -registered, so a client that reads back what it wrote (Terraform, or a deploy tool verifying its -own `RegisterTaskDefinition`) sees no drift. `runtimePlatform` does not change where a local task +A task definition round-trips whole. Members Floci acts on are modelled +(`ephemeralStorage`, `pidMode`, `ipcMode`, `runtimePlatform`, and at container level `dependsOn`, +`startTimeout`, `stopTimeout`, `user`, `workingDirectory`, `readonlyRootFilesystem`, +`environmentFiles`, `dockerLabels`, `repositoryCredentials` and the rest); everything else it does +not act on, such as `proxyConfiguration`, `linuxParameters`, `ulimits`, `resourceRequirements`, +`systemControls` and placement constraints, is kept verbatim and returned as registered. A client +that reads back what it wrote (Terraform, or a deploy tool verifying its own +`RegisterTaskDefinition`) sees no drift. `runtimePlatform` does not change where a local task runs: Floci launches every task on the host's own architecture. +The round trip reaches inside the members Floci does parse. A port mapping keeps its `name`, +`appProtocol` and `containerPortRange`, which is what a service's `serviceConnectConfiguration` +and `vpcLatticeConfigurations` reference by name, and a volume keeps the configurations Floci +backs with nothing: `dockerVolumeConfiguration`, `fsxWindowsFileServerVolumeConfiguration`, +`s3filesVolumeConfiguration` and `configuredAtLaunch`. + +`compatibilities` is derived from the definition rather than echoed from +`requiresCompatibilities`: ECS reports the launch types a definition actually works on, so an +`awsvpc` definition with a valid Fargate size pair and no Fargate-unsupported parameters comes +back as `["EC2", "FARGATE"]` even when it never asked for FARGATE. `EXTERNAL` is added for any +network mode other than `awsvpc`, which ECS Anywhere instances do not support. The derivation runs +Fargate's own registration rules, so it can never disagree with what `requiresCompatibilities: +["FARGATE"]` would have accepted. + +`requiresAttributes` names the container instance capabilities the definition needs for EC2 +placement. ECS derives these from the container agent's capability model, which AWS does not +publish in full, so Floci derives the subset whose names appear verbatim in the AWS documentation: +the base `com.amazonaws.ecs.capability.docker-remote-api.1.18`, `ecs.capability.task-eni` for +`awsvpc`, `com.amazonaws.ecs.capability.task-iam-role` (or +`...task-iam-role-network-host` under `host` networking) for a `taskRoleArn`, +`com.amazonaws.ecs.capability.logging-driver.` per container log driver, +`com.amazonaws.ecs.capability.ecr-auth` for an ECR image, and +`com.amazonaws.ecs.capability.privileged-container`. Capabilities outside that set are not +reported. + +A revision goes ACTIVE, then INACTIVE on `DeregisterTaskDefinition` (which stamps +`deregisteredAt`), then `DELETE_IN_PROGRESS` on `DeleteTaskDefinitions` (which stamps +`deleteRequestedAt`). Deleting a revision that has not been deregistered is refused, as is a +reference that names only the family: `DeleteTaskDefinitions` takes a revision, at most 10 per +call. A deleted revision is not dropped, because AWS keeps describing it and the tasks already on +it keep running; it just cannot start anything new, so `RunTask`, `CreateService` and +`UpdateService` refuse it. + +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 +longer agent default, because `RunTask` here answers synchronously. A container's `cpu` becomes its +CPU shares, its `memory` its hard limit, and a container without a `memory` of its own is capped at +the task's; the task's `cpu` becomes a CPU quota. `stopTimeout` is the grace period the container gets +on teardown; a container that does not ask for one gets 5 seconds rather than AWS's 30, because +`StopTask` here answers synchronously and most containers ignore SIGTERM as PID 1. A container +still running when its grace period is up is killed, so its exit code is always reported. + `firelensConfiguration` is stored and returned the same way. `RegisterTaskDefinition` rejects a missing or unsupported `type` (`fluentd` and `fluentbit` only), and a task using `awsfirelens` must name exactly one router: a task definition with two FireLens routers, or a router publishing @@ -76,12 +129,11 @@ FirelensConfiguration config file from 's3'`, and rejects a `config-file-value` object ARN with `Invalid arn syntax`. A Fargate task can still take its config from S3 the way AWS documents, by giving the aws-for-fluent-bit init process its `aws_fluent_bit_init_s3_*` environment variables. ECS never inspects those and Floci passes them through, so that -registration is accepted here too; it fetches nothing locally either, because Floci serves no ECS -task metadata endpoint, which the init process reads before downloading. -Floci also does not validate a task definition's `compatibilities` / +registration is accepted here too; the init process reads the task metadata endpoint before +downloading. +Floci does not validate a task definition's `compatibilities` / `requiresCompatibilities` against `RunTask` `launchType`; a Fargate-compatible -definition can still be run with `launchType=EC2` (and the reverse) the same -way a missing metadata endpoint is accepted at registration. +definition can still be run with `launchType=EC2` (and the reverse). On an EC2-compatible task definition Floci reads the object from its own S3, writes it to the fixed `external.conf` path next to the generated config (`/fluent-bit/etc/external.conf` or `/fluentd/etc/external.conf`), and includes it from there, matching the paths the ECS agent uses. @@ -107,6 +159,89 @@ cycles involving both volume inheritance and log routing are rejected before con | `UpdateTaskProtection` | Set scale-in protection for tasks | | `GetTaskProtection` | Get current task protection state | +### Fargate + +A task definition that declares `FARGATE` in `requiresCompatibilities` is held to Fargate's rules +at registration: + +- `awsvpc` network mode. +- A task-level `cpu` and `memory` forming one of the documented pairs, from 256 CPU units through + 32768 (the 32 vCPU tier offers only 60 GB, 120 GB and 244 GB), in CPU units or the `1 vCPU` and + `1 GB` string forms. Windows rules out the sub-vCPU sizes. +- An `ephemeralStorage.sizeInGiB` between 21 and 200. +- None of the parameters that are not valid in a Fargate task: `disableNetworking`, + `dnsSearchDomains`, `dnsServers`, `dockerSecurityOptions`, `extraHosts`, a `GPU` + `resourceRequirements` entry, `ipcMode`, `links`, `placementConstraints`, `privileged`, + `linuxParameters.maxSwap`, `linuxParameters.swappiness`, a `pidMode` other than `task`, or a + host volume with a `sourcePath`. All of them are accepted on an EC2-compatible definition. +- A `dependsOn` graph that names only containers of the same task definition and has no cycle. + +A launched Fargate task reports what AWS reports: `platformVersion` (with `LATEST` resolved to a +concrete version, as AWS resolves it) and `platformFamily` (`Linux`, or the Windows Server family +from the task definition's `runtimePlatform.operatingSystemFamily`), `connectivity` and +`connectivityAt`, `healthStatus`, `stopCode`, `version`, `availabilityZone`, `attributes` with +`ecs.cpu-architecture`, `pullStartedAt` / `pullStoppedAt` / `stoppingAt` / `executionStoppedAt`, +`ephemeralStorage` and `fargateEphemeralStorage`, and `enableExecuteCommand`. `overrides` is +always present with one `containerOverrides` entry per container, carrying whatever the request +overrode, which is how AWS answers a task nobody overrode. `group` defaults to `family:` +for a `RunTask` and is `service:` for a service's tasks. A container that asked for no CPU +units reports `"cpu": "0"`, as on AWS. + +A task's `attachments` entry is an `ElasticNetworkInterface` carrying `subnetId`, +`networkInterfaceId`, `macAddress`, `privateDnsName` and `privateIPv4Address`. `DescribeTasks` and +`DescribeServices` report tags only when the request asks for them with `include: ["TAGS"]`, as +`DescribeTaskDefinition` already did. A task `DescribeTasks` cannot resolve comes back as a +`MISSING` entry in `failures`, which is what the `TasksRunning` and `TasksStopped` waiters treat +as terminal. + +A created service reports the documented defaults: `propagateTags` is `NONE` and +`healthCheckGracePeriodSeconds` is `0` when the request sets neither. A `role` is accepted only on +a load-balanced service whose task definition does not use `awsvpc`, which is the only case AWS +permits it in. + +`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. + +On `UpdateService`, the changes that start new tasks roll the deployment: the task definition, the +network configuration, the load balancers, the service registries, the Service Connect +configuration, and `forceNewDeployment`. The ones AWS documents as not triggering a deployment +(`desiredCount`, `deploymentConfiguration`, `enableExecuteCommand`, `enableECSManagedTags`, +`propagateTags`, `healthCheckGracePeriodSeconds`, `availabilityZoneRebalancing`, the capacity +provider strategy and the placement members) are applied without rolling anything. + +Every `awsvpc` task gets a real ENI in the subnet it asked for, in Docker and in mock mode alike, +and reports it as an `attachments` entry with its `networkInterfaceId`, `privateIPv4Address` and +`subnetId`; the task's containers report the same interface in `networkInterfaces`. A subnet that +does not exist fails the request rather than being ignored. While the task runs, `ec2 +DescribeNetworkInterfaces` reports that ENI as `in-use` and refuses to delete it, so it never +answers a search for a free interface; it carries no EC2 attachment, every member of one naming an +instance that a task does not have. The ECS attachment is reported as `DELETED` once the task +stops, and the ENI is released. Security-group enforcement +(`FLOCI_NETWORK_SECURITY_GROUP_ENFORCEMENT_ENABLED`) adds packet filtering on top of the ENI; it is +not needed for the ENI itself. + +#### Capacity providers + +`capacityProviderStrategy` is honoured on `RunTask` and `CreateService`, including the built-in +`FARGATE` and `FARGATE_SPOT` providers. Tasks are spread the way ECS spreads them: the single entry +that declares a `base` is filled first, then the rest are split by weight, with the remainder of +the integer split going to the heaviest entries. A strategy and a `launchType` in the same request +are rejected, as is an unknown provider or a second `base`, and a cluster's +`defaultCapacityProviderStrategy` applies when a request carries neither. The documented bounds +are enforced: at most 20 providers in a strategy, a `weight` of 0 to 1,000 and a `base` of 0 to +100,000. A provider of `weight` 0 places nothing beyond its base, so a strategy naming several +providers that all weigh 0 is rejected; a lone provider of `weight` 0 still places the tasks, +since the request named no alternative. + +A task placed through a provider reports `capacityProviderName` **and** the `launchType` that +provider resolves to. A service reports one or the other: `DescribeServices` omits `launchType` +for a service created with a strategy, and omits `capacityProviderStrategy` for one created with a +launch type, which is what AWS documents for the `Service` shape. + +With no launch type, no strategy and no cluster default, a task keeps Floci's `FARGATE` default: a +local cluster has no container instances, so an EC2 default would have nowhere to place it. + ### Services | Operation | Description | @@ -235,6 +370,10 @@ unchanged. | `UntagResource` | Remove tags from a resource | | `ListTagsForResource` | List tags on a resource | +Every operation that takes `tags` holds it to the limits ECS documents: at most 50 tags, a key of +1 to 128 characters and a value of up to 256. The count is taken from the request rather than the +parsed map, so 51 entries that collapse to fewer distinct keys are still rejected. + ### Account Settings & Attributes | Operation | Description | @@ -258,7 +397,7 @@ unchanged. ## Configuration -Docker-backed `awsvpc` tasks receive an emulated ENI and share one protected network namespace across their containers when `FLOCI_NETWORK_SECURITY_GROUP_ENFORCEMENT_ENABLED=true`. A task without explicit security groups uses its subnet VPC's default group. Containers in the same task can communicate over localhost. Bridge and host task networking do not attach task-level `awsvpc` security groups. Mock mode reports control-plane state and does not enforce packet filtering. +Every `awsvpc` task receives an ENI in its subnet. With `FLOCI_NETWORK_SECURITY_GROUP_ENFORCEMENT_ENABLED=true`, a Docker-backed task's containers additionally share one protected network namespace built around that ENI, and packets are filtered against its security groups. A task without explicit security groups uses its subnet VPC's default group. Containers in the same task can communicate over localhost. Bridge and host task networking do not attach task-level `awsvpc` security groups. Mock mode reports control-plane state, including the ENI, and does not enforce packet filtering. | Variable | Default | Description | |---|---|---| @@ -313,7 +452,7 @@ A task's `efsVolumeConfiguration` volumes are backed by shared local Docker volu ### Mock mode -Set `FLOCI_SERVICES_ECS_MOCK=true` to run without Docker. In this mode tasks skip container launch and immediately transition to `RUNNING`, then to `STOPPED` when stopped. This is the recommended mode for unit/integration tests and CI pipelines where Docker-in-Docker is unavailable. +Set `FLOCI_SERVICES_ECS_MOCK=true` to run without Docker. In this mode tasks skip container launch and immediately transition to `RUNNING`, then to `STOPPED` when stopped. The task still reports a container per container definition and, for `awsvpc`, a real ENI, so a client reading `containers[]` or waiting on the task's address behaves as it does against AWS; nothing is running behind those containers, so no logs are streamed. This is the recommended mode for unit/integration tests and CI pipelines where Docker-in-Docker is unavailable. ```yaml # docker-compose.yml — CI / test environment diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java index 030798a7d7..ff90127b43 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java +++ b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java @@ -8309,16 +8309,57 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider { return ni; } - /** Deletes a standalone ENI. AWS refuses while it is still attached, floci-kt9. */ + /** + * Deletes a standalone ENI. AWS refuses while it is still attached, floci-kt9, and equally + * while a service holds it: {@link #holdNetworkInterfaceForService} leaves no attachment + * behind, so the status is what says the interface is spoken for. + */ public void deleteNetworkInterface(String region, String networkInterfaceId) { NetworkInterface ni = requireStandaloneNetworkInterface(region, networkInterfaceId); - if (ni.getAttachment() != null) { + if (ni.getAttachment() != null || "in-use".equals(ni.getStatus())) { throw new AwsException("InvalidParameterValue", "Network interface '" + networkInterfaceId + "' is currently in use", 400); } networkInterfaces.delete(key(region, networkInterfaceId)); } + /** + * Marks an ENI as held by an AWS service rather than by an instance in this account, the state + * a running ECS task's interface is in. DescribeNetworkInterfaces documents the status rule + * this rests on: an interface that is not attached is {@code available}, one that is attached + * is {@code in-use}, and AWS does not let the account delete a task's interface while the task + * runs. + * + *

No attachment is synthesised. Every member AWS documents on one describes an instance + * ({@code instanceId}, {@code instanceOwnerId} "The AWS account ID of the owner of the + * instance", {@code deviceIndex} "The device index ... on the instance"), and a task has no + * instance in the account to name there. + */ + public void holdNetworkInterfaceForService(String region, String networkInterfaceId) { + NetworkInterface ni = requireStandaloneNetworkInterface(region, networkInterfaceId); + if (ni.getAttachment() != null) { + throw new AwsException("InvalidNetworkInterface.InUse", + "Interface: '" + networkInterfaceId + "' is currently in use.", 400); + } + ni.setStatus("in-use"); + networkInterfaces.put(key(region, networkInterfaceId), ni); + } + + /** + * Returns a service-held ENI to {@code available}, the mirror of + * {@link #holdNetworkInterfaceForService}. Silent on an interface that is already gone, or one + * an instance holds, so a teardown that runs twice is harmless and cannot free an attachment + * that AttachNetworkInterface owns. + */ + public void releaseNetworkInterfaceFromService(String region, String networkInterfaceId) { + NetworkInterface ni = networkInterfaces.get(key(region, networkInterfaceId)).orElse(null); + if (ni == null || ni.getAttachment() != null) { + return; + } + ni.setStatus("available"); + networkInterfaces.put(key(region, networkInterfaceId), ni); + } + /** * Attaches a standalone ENI to a running/stopped instance at the given device index, * the attach-eni example's runtime pattern (its user-data script calls this via the AWS CLI 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 e46479e0de..51cdac028c 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 @@ -6,13 +6,17 @@ import io.github.hectorvent.floci.services.ecs.container.HostVolumePolicy; import io.github.hectorvent.floci.services.ecs.model.Attribute; import io.github.hectorvent.floci.services.ecs.model.AwsVpcConfiguration; import io.github.hectorvent.floci.services.ecs.model.CapacityProvider; +import io.github.hectorvent.floci.services.ecs.model.CapacityProviderStrategyItem; import io.github.hectorvent.floci.services.ecs.model.ClusterSetting; 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.ContainerInstance; 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.EnvironmentFile; +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; import io.github.hectorvent.floci.services.ecs.model.EcsCluster; @@ -35,9 +39,10 @@ import io.github.hectorvent.floci.services.ecs.model.ServiceDeployment; import io.github.hectorvent.floci.services.ecs.model.ServiceRevision; import io.github.hectorvent.floci.services.ecs.model.Secret; import io.github.hectorvent.floci.services.ecs.model.TaskDefinition; +import io.github.hectorvent.floci.services.ecs.model.TaskOverride; import io.github.hectorvent.floci.services.ecs.model.TaskSet; -import io.github.hectorvent.floci.services.ecs.model.UpdateServiceRequest; import io.github.hectorvent.floci.services.ecs.model.EfsVolumeConfiguration; +import io.github.hectorvent.floci.services.ecs.model.UpdateServiceRequest; import io.github.hectorvent.floci.services.ecs.model.Volume; import io.github.hectorvent.floci.services.ecs.model.VolumeFrom; import com.fasterxml.jackson.databind.JsonNode; @@ -49,11 +54,13 @@ import jakarta.inject.Inject; import jakarta.ws.rs.core.Response; import java.util.ArrayList; +import java.util.Arrays; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; +import java.util.TreeSet; @ApplicationScoped public class EcsJsonHandler { @@ -87,14 +94,14 @@ public class EcsJsonHandler { case "UpdateCluster" -> handleUpdateCluster(request, region); case "UpdateClusterSettings" -> handleUpdateClusterSettings(request, region); case "PutClusterCapacityProviders" -> handlePutClusterCapacityProviders(request, region); - // Task Definitions + case "RegisterTaskDefinition" -> handleRegisterTaskDefinition(request, region); case "DescribeTaskDefinition" -> handleDescribeTaskDefinition(request, region); case "ListTaskDefinitions" -> handleListTaskDefinitions(request, region); case "ListTaskDefinitionFamilies" -> handleListTaskDefinitionFamilies(request, region); case "DeregisterTaskDefinition" -> handleDeregisterTaskDefinition(request, region); case "DeleteTaskDefinitions" -> handleDeleteTaskDefinitions(request, region); - // Tasks + case "RunTask" -> handleRunTask(request, region); case "StartTask" -> handleStartTask(request, region); case "StopTask" -> handleStopTask(request, region); @@ -102,53 +109,54 @@ public class EcsJsonHandler { case "ListTasks" -> handleListTasks(request, region); case "UpdateTaskProtection" -> handleUpdateTaskProtection(request, region); case "GetTaskProtection" -> handleGetTaskProtection(request, region); - // Services + case "CreateService" -> handleCreateService(request, region); case "UpdateService" -> handleUpdateService(request, region); case "DeleteService" -> handleDeleteService(request, region); case "DescribeServices" -> handleDescribeServices(request, region); case "ListServices" -> handleListServices(request, region); case "ListServicesByNamespace" -> handleListServicesByNamespace(request, region); - // Tags + case "TagResource" -> handleTagResource(request, region); case "UntagResource" -> handleUntagResource(request, region); case "ListTagsForResource" -> handleListTagsForResource(request, region); - // Account Settings + case "PutAccountSetting" -> handlePutAccountSetting(request, region); case "PutAccountSettingDefault" -> handlePutAccountSettingDefault(request, region); case "DeleteAccountSetting" -> handleDeleteAccountSetting(request, region); case "ListAccountSettings" -> handleListAccountSettings(request, region); - // Attributes + case "PutAttributes" -> handlePutAttributes(request, region); case "DeleteAttributes" -> handleDeleteAttributes(request, region); case "ListAttributes" -> handleListAttributes(request, region); - // Container Instances + case "RegisterContainerInstance" -> handleRegisterContainerInstance(request, region); case "DeregisterContainerInstance" -> handleDeregisterContainerInstance(request, region); case "DescribeContainerInstances" -> handleDescribeContainerInstances(request, region); case "ListContainerInstances" -> handleListContainerInstances(request, region); case "UpdateContainerAgent" -> handleUpdateContainerAgent(request, region); case "UpdateContainerInstancesState" -> handleUpdateContainerInstancesState(request, region); - // Capacity Providers + case "CreateCapacityProvider" -> handleCreateCapacityProvider(request, region); case "UpdateCapacityProvider" -> handleUpdateCapacityProvider(request, region); case "DeleteCapacityProvider" -> handleDeleteCapacityProvider(request, region); case "DescribeCapacityProviders" -> handleDescribeCapacityProviders(request, region); - // Task Sets + case "CreateTaskSet" -> handleCreateTaskSet(request, region); case "UpdateTaskSet" -> handleUpdateTaskSet(request, region); case "DeleteTaskSet" -> handleDeleteTaskSet(request, region); case "DescribeTaskSets" -> handleDescribeTaskSets(request, region); case "UpdateServicePrimaryTaskSet" -> handleUpdateServicePrimaryTaskSet(request, region); - // Service Deployments & Revisions + case "DescribeServiceDeployments" -> handleDescribeServiceDeployments(request, region); case "ListServiceDeployments" -> handleListServiceDeployments(request, region); case "DescribeServiceRevisions" -> handleDescribeServiceRevisions(request, region); - // Stubs + case "SubmitTaskStateChange" -> handleSubmitTaskStateChange(request, region); case "SubmitContainerStateChange" -> handleSubmitContainerStateChange(request, region); case "SubmitAttachmentStateChanges" -> handleSubmitAttachmentStateChanges(request, region); case "DiscoverPollEndpoint" -> handleDiscoverPollEndpoint(request, region); + default -> Response.status(400) .entity(new AwsErrorResponse("UnsupportedOperation", "Operation " + action + " is not supported.")) @@ -160,9 +168,16 @@ public class EcsJsonHandler { private Response handleCreateCluster(JsonNode req, String region) { CreateClusterRequest request = new CreateClusterRequest(); - request.setClusterName(req.path("clusterName").asText(null)); + request.setClusterName(req.has("clusterName") ? req.path("clusterName").asText() : null); request.setTags(parseTagMap(req.path("tags"))); request.setSettings(parseClusterSettings(req.path("settings"))); + if (req.has("capacityProviders")) { + request.setCapacityProviders(jsonArrayToList(req.path("capacityProviders"))); + } + if (req.has("defaultCapacityProviderStrategy")) { + request.setDefaultCapacityProviderStrategy( + parseRawObjectList(req.path("defaultCapacityProviderStrategy"))); + } EcsCluster cluster = service.createCluster(request, region); ObjectNode resp = objectMapper.createObjectNode(); resp.set("cluster", writer.clusterNode(cluster)); @@ -198,34 +213,40 @@ public class EcsJsonHandler { } private Response handleUpdateCluster(JsonNode req, String region) { - String clusterRef = req.path("cluster").asText(); + String clusterId = req.path("cluster").asText(); List settings = parseClusterSettings(req.path("settings")); - EcsCluster cluster = service.updateCluster(clusterRef, settings, region); + EcsCluster cluster = service.updateCluster(clusterId, settings, region); ObjectNode resp = objectMapper.createObjectNode(); resp.set("cluster", writer.clusterNode(cluster)); return Response.ok(resp).build(); } private Response handleUpdateClusterSettings(JsonNode req, String region) { - String clusterRef = req.path("cluster").asText(); + String clusterId = req.path("cluster").asText(); List settings = parseClusterSettings(req.path("settings")); - EcsCluster cluster = service.updateClusterSettings(clusterRef, settings, region); + EcsCluster cluster = service.updateClusterSettings(clusterId, settings, region); ObjectNode resp = objectMapper.createObjectNode(); resp.set("cluster", writer.clusterNode(cluster)); return Response.ok(resp).build(); } private Response handlePutClusterCapacityProviders(JsonNode req, String region) { - String clusterRef = req.path("cluster").asText(); + String clusterId = req.path("cluster").asText(); List providers = jsonArrayToList(req.path("capacityProviders")); List> defaultStrategy = parseRawObjectList(req.path("defaultCapacityProviderStrategy")); - EcsCluster cluster = service.putClusterCapacityProviders(clusterRef, providers, defaultStrategy, region); + EcsCluster cluster = service.putClusterCapacityProviders(clusterId, providers, defaultStrategy, region); ObjectNode resp = objectMapper.createObjectNode(); resp.set("cluster", writer.clusterNode(cluster)); return Response.ok(resp).build(); } - // ── Task Definitions ────────────────────────────────────────────────────── + // ── Task definitions ────────────────────────────────────────────────────── + + /** Members of RegisterTaskDefinition the parser consumes; the rest round-trips verbatim. */ + private static final Set TASK_DEFINITION_CONSUMED = Set.of( + "family", "containerDefinitions", "networkMode", "cpu", "memory", "taskRoleArn", + "executionRoleArn", "requiresCompatibilities", "volumes", "runtimePlatform", + "ephemeralStorage", "pidMode", "ipcMode", "tags"); private Response handleRegisterTaskDefinition(JsonNode req, String region) { RegisterTaskDefinitionRequest request = new RegisterTaskDefinitionRequest(); @@ -235,17 +256,24 @@ public class EcsJsonHandler { request.setCpu(req.has("cpu") ? req.path("cpu").asText() : null); request.setMemory(req.has("memory") ? req.path("memory").asText() : null); request.setTaskRoleArn(req.hasNonNull("taskRoleArn") ? req.path("taskRoleArn").asText() : null); - request.setExecutionRoleArn( - req.hasNonNull("executionRoleArn") ? req.path("executionRoleArn").asText() : null); - request.setRequiresCompatibilities(jsonArrayToList(req.path("requiresCompatibilities"))); + request.setExecutionRoleArn(req.hasNonNull("executionRoleArn") + ? req.path("executionRoleArn").asText() : null); + request.setRequiresCompatibilities(parseCompatibilities(req.path("requiresCompatibilities"))); request.setVolumes(parseVolumes(req.path("volumes"))); request.setRuntimePlatform(parseRuntimePlatform(req.path("runtimePlatform"))); + request.setEphemeralStorage(parseEphemeralStorage(req.path("ephemeralStorage"))); + request.setPidMode(parseChoice(req, "pidMode", PID_MODES)); + request.setIpcMode(parseChoice(req, "ipcMode", IPC_MODES)); request.setTags(parseTagMap(req.path("tags"))); + request.setUnparsed(EcsJsonPassthrough.capture(req, objectMapper, TASK_DEFINITION_CONSUMED)); TaskDefinition td = service.registerTaskDefinition(request, region); ObjectNode resp = objectMapper.createObjectNode(); resp.set("taskDefinition", writer.taskDefinitionNode(td)); + if (td.getTags() != null && !td.getTags().isEmpty()) { + resp.set("tags", writer.tagsNode(td.getTags())); + } return Response.ok(resp).build(); } @@ -254,6 +282,11 @@ public class EcsJsonHandler { TaskDefinition td = service.describeTaskDefinition(tdRef, region); ObjectNode resp = objectMapper.createObjectNode(); resp.set("taskDefinition", writer.taskDefinitionNode(td)); + // DescribeTaskDefinition reports tags at the top level, and only when asked for them. + if (jsonArrayToList(req.path("include")).contains("TAGS") + && td.getTags() != null && !td.getTags().isEmpty()) { + resp.set("tags", writer.tagsNode(td.getTags())); + } return Response.ok(resp).build(); } @@ -300,17 +333,7 @@ public class EcsJsonHandler { // ── Tasks ───────────────────────────────────────────────────────────────── private Response handleRunTask(JsonNode req, String region) { - RunTaskRequest request = new RunTaskRequest(); - request.setCluster(req.has("cluster") ? req.path("cluster").asText() : null); - request.setTaskDefinition(req.path("taskDefinition").asText()); - request.setCount(req.path("count").asInt(1)); - request.setLaunchType(parseEnum(req, "launchType", LaunchType.class)); - request.setGroup(req.has("group") ? req.path("group").asText() : null); - request.setStartedBy(req.has("startedBy") ? req.path("startedBy").asText() : null); - request.setContainerOverrides( - parseContainerOverrides(req.path("overrides").path("containerOverrides"))); - request.setNetworkConfiguration(parseNetworkConfiguration(req.path("networkConfiguration"))); - + RunTaskRequest request = parseRunTaskRequest(req); List launched = service.runTask(request, region); ObjectNode resp = objectMapper.createObjectNode(); @@ -322,13 +345,8 @@ public class EcsJsonHandler { } private Response handleStartTask(JsonNode req, String region) { - RunTaskRequest request = new RunTaskRequest(); - request.setCluster(req.has("cluster") ? req.path("cluster").asText() : null); + RunTaskRequest request = parseRunTaskRequest(req); request.setContainerInstances(jsonArrayToList(req.path("containerInstances"))); - request.setTaskDefinition(req.path("taskDefinition").asText()); - request.setGroup(req.has("group") ? req.path("group").asText() : null); - request.setStartedBy(req.has("startedBy") ? req.path("startedBy").asText() : null); - List launched = service.startTask(request, region); ObjectNode resp = objectMapper.createObjectNode(); @@ -339,6 +357,27 @@ public class EcsJsonHandler { return Response.ok(resp).build(); } + private RunTaskRequest parseRunTaskRequest(JsonNode req) { + RunTaskRequest request = new RunTaskRequest(); + request.setCluster(req.has("cluster") ? req.path("cluster").asText() : null); + request.setTaskDefinition(req.path("taskDefinition").asText()); + request.setCount(req.path("count").asInt(1)); + request.setLaunchType(parseEnum(req, "launchType", LaunchType.class)); + request.setCapacityProviderStrategy(parseCapacityProviderStrategy(req.path("capacityProviderStrategy"))); + request.setGroup(req.has("group") ? req.path("group").asText() : null); + request.setStartedBy(req.has("startedBy") ? req.path("startedBy").asText() : null); + request.setOverrides(parseTaskOverride(req.path("overrides"))); + request.setNetworkConfiguration(parseNetworkConfiguration(req.path("networkConfiguration"))); + request.setPlatformVersion(req.hasNonNull("platformVersion") + ? req.path("platformVersion").asText() : null); + request.setEnableExecuteCommand(req.path("enableExecuteCommand").asBoolean(false)); + request.setEnableECSManagedTags(req.path("enableECSManagedTags").asBoolean(false)); + request.setPropagateTags(parseChoice(req, "propagateTags", PROPAGATE_TAGS)); + request.setReferenceId(req.has("referenceId") ? req.path("referenceId").asText() : null); + request.setTags(parseTagMap(req.path("tags"))); + return request; + } + private Response handleStopTask(JsonNode req, String region) { String cluster = req.has("cluster") ? req.path("cluster").asText() : null; String task = req.path("task").asText(); @@ -354,13 +393,16 @@ public class EcsJsonHandler { private Response handleDescribeTasks(JsonNode req, String region) { String cluster = req.has("cluster") ? req.path("cluster").asText() : null; List taskRefs = jsonArrayToList(req.path("tasks")); - List found = service.describeTasks(cluster, taskRefs, region); + boolean includeTags = jsonArrayToList(req.path("include")).contains("TAGS"); + EcsService.DescribeTasksResult found = service.describeTasksDetailed(cluster, taskRefs, region); ObjectNode resp = objectMapper.createObjectNode(); ArrayNode arr = objectMapper.createArrayNode(); - found.forEach(t -> arr.add(writer.taskNode(t))); + found.tasks().forEach(t -> arr.add(writer.taskNode(t, includeTags))); resp.set("tasks", 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(); } @@ -420,16 +462,15 @@ public class EcsJsonHandler { request.setTaskDefinition(req.path("taskDefinition").asText()); request.setDesiredCount(req.path("desiredCount").asInt(1)); request.setLaunchType(parseEnum(req, "launchType", LaunchType.class)); + request.setCapacityProviderStrategy(parseCapacityProviderStrategy(req.path("capacityProviderStrategy"))); request.setLoadBalancers(parseLoadBalancers(req.path("loadBalancers"))); request.setNetworkConfiguration(parseNetworkConfiguration(req.path("networkConfiguration"))); request.setTags(parseTagMap(req.path("tags"))); request.setSchedulingStrategy(parseChoice(req, "schedulingStrategy", SCHEDULING_STRATEGIES)); request.setDeploymentControllerType(parseChoice(req.path("deploymentController"), "type", "deploymentController.type", DEPLOYMENT_CONTROLLER_TYPES)); - request.setAvailabilityZoneRebalancing( - parseChoice(req, "availabilityZoneRebalancing", AZ_REBALANCING)); - request.setServiceConnectConfiguration( - parseServiceConnectConfiguration(req.path("serviceConnectConfiguration"))); + request.setAvailabilityZoneRebalancing(parseChoice(req, "availabilityZoneRebalancing", AZ_REBALANCING)); + request.setServiceConnectConfiguration(parseRawObject(req.path("serviceConnectConfiguration"))); EcsServiceModel svc = service.createService(request, region); @@ -438,6 +479,25 @@ public class EcsJsonHandler { return Response.ok(resp).build(); } + private Response handleUpdateService(JsonNode req, String region) { + UpdateServiceRequest request = new UpdateServiceRequest(); + request.setCluster(req.has("cluster") ? req.path("cluster").asText() : null); + request.setService(req.path("service").asText()); + request.setTaskDefinition(req.has("taskDefinition") ? req.path("taskDefinition").asText() : null); + request.setDesiredCount(req.has("desiredCount") ? req.path("desiredCount").asInt() : null); + request.setNetworkConfiguration(parseNetworkConfiguration(req.path("networkConfiguration"))); + request.setAvailabilityZoneRebalancing(parseChoice(req, "availabilityZoneRebalancing", AZ_REBALANCING)); + request.setForceNewDeployment(req.path("forceNewDeployment").asBoolean(false)); + request.setServiceConnectConfiguration(parseRawObject(req.path("serviceConnectConfiguration"))); + request.setCapacityProviderStrategy(parseCapacityProviderStrategy(req.path("capacityProviderStrategy"))); + + EcsServiceModel svc = service.updateService(request, region); + + ObjectNode resp = objectMapper.createObjectNode(); + resp.set("service", writer.serviceNode(svc)); + return Response.ok(resp).build(); + } + private List parseLoadBalancers(JsonNode node) { List result = new ArrayList<>(); if (node == null || !node.isArray()) { @@ -476,6 +536,9 @@ public class EcsJsonHandler { m.setLoadBalancerName(loadBalancerName); m.setContainerName(containerName); m.setContainerPort(containerPort); + // The blue/green listener and alternate target group wiring, kept raw: Floci shifts no + // traffic, but a service created with it has to read back with it. + m.setAdvancedConfiguration(parseRawObject(lb.path("advancedConfiguration"))); result.add(m); } return result; @@ -500,26 +563,6 @@ public class EcsJsonHandler { return networkConfiguration; } - private Response handleUpdateService(JsonNode req, String region) { - UpdateServiceRequest request = new UpdateServiceRequest(); - request.setCluster(req.has("cluster") ? req.path("cluster").asText() : null); - request.setService(req.path("service").asText()); - request.setTaskDefinition(req.has("taskDefinition") ? req.path("taskDefinition").asText() : null); - request.setDesiredCount(req.has("desiredCount") ? req.path("desiredCount").asInt() : null); - request.setNetworkConfiguration(parseNetworkConfiguration(req.path("networkConfiguration"))); - request.setAvailabilityZoneRebalancing( - parseChoice(req, "availabilityZoneRebalancing", AZ_REBALANCING)); - request.setForceNewDeployment(req.path("forceNewDeployment").asBoolean(false)); - request.setServiceConnectConfiguration( - parseServiceConnectConfiguration(req.path("serviceConnectConfiguration"))); - - EcsServiceModel svc = service.updateService(request, region); - - ObjectNode resp = objectMapper.createObjectNode(); - resp.set("service", writer.serviceNode(svc)); - return Response.ok(resp).build(); - } - private Response handleDeleteService(JsonNode req, String region) { String cluster = req.has("cluster") ? req.path("cluster").asText() : null; String serviceName = req.path("service").asText(); @@ -933,43 +976,18 @@ public class EcsJsonHandler { return writer.taskNode(task); } - 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"); - - /** Optional enum-valued string field: absent → {@code null}; present but not in {@code allowed} → 400. */ - private static String parseChoice(JsonNode node, String field, Set allowed) { - return parseChoice(node, field, field, allowed); - } - - private static String parseChoice(JsonNode node, String field, String displayName, Set allowed) { - if (node == null || node.isMissingNode() || !node.hasNonNull(field)) { - return null; - } - String value = node.path(field).asText(); - if (!allowed.contains(value)) { - throw new AwsException("InvalidParameterException", - "Invalid " + displayName + ": " + value + ". Valid values: " - + String.join(", ", new java.util.TreeSet<>(allowed)) + ".", 400); - } - return value; - } - - /** - * Keeps the caller's Service Connect configuration as given. AWS's {@code Service} shape has - * no member for it, so DescribeServices reports it on each deployment rather than on the - * service, and a generated client drops anything written anywhere else. - */ - @SuppressWarnings("unchecked") - private Map parseServiceConnectConfiguration(JsonNode node) { - if (node == null || !node.isObject()) { - return null; - } - return objectMapper.convertValue(node, Map.class); - } - // ── Parsing helpers ─────────────────────────────────────────────────────── + /** Members of a container definition the parser consumes; the rest round-trips verbatim. */ + private static final Set CONTAINER_DEFINITION_CONSUMED = Set.of( + "name", "image", "essential", "cpu", "memory", "memoryReservation", "portMappings", + "environment", "environmentFiles", "secrets", "mountPoints", "volumesFrom", "dependsOn", + "logConfiguration", "firelensConfiguration", "healthCheck", "command", "entryPoint", + "startTimeout", "stopTimeout", "user", "workingDirectory", "hostname", + "readonlyRootFilesystem", "privileged", "disableNetworking", "interactive", + "pseudoTerminal", "links", "dnsServers", "dnsSearchDomains", "dockerSecurityOptions", + "dockerLabels", "repositoryCredentials"); + private List parseContainerDefinitions(JsonNode node) { List result = new ArrayList<>(); if (!node.isArray()) { @@ -986,11 +1004,17 @@ public class EcsJsonHandler { def.setPortMappings(parsePortMappings(item.path("portMappings"))); def.setEnvironment(parseKeyValuePairs(item.path("environment"))); + if (item.has("environmentFiles")) { + def.setEnvironmentFiles(parseEnvironmentFiles(item.path("environmentFiles"))); + } if (item.has("secrets")) { def.setSecrets(parseSecrets(item.path("secrets"))); } def.setMountPoints(parseMountPoints(item.path("mountPoints"))); def.setVolumesFrom(parseVolumesFrom(item.path("volumesFrom"))); + if (item.has("dependsOn")) { + def.setDependsOn(parseDependsOn(item.path("dependsOn"), def.getName())); + } def.setLogConfiguration(parseLogConfiguration(item.path("logConfiguration"))); def.setFirelensConfiguration(parseFirelensConfiguration( item.path("firelensConfiguration"), result.size() + 1)); @@ -999,16 +1023,50 @@ public class EcsJsonHandler { } if (item.has("command") && item.path("command").isArray()) { - List cmd = new ArrayList<>(); - item.path("command").forEach(c -> cmd.add(c.asText())); - def.setCommand(cmd); + def.setCommand(jsonArrayToList(item.path("command"))); } if (item.has("entryPoint") && item.path("entryPoint").isArray()) { - List ep = new ArrayList<>(); - item.path("entryPoint").forEach(e -> ep.add(e.asText())); - def.setEntryPoint(ep); + def.setEntryPoint(jsonArrayToList(item.path("entryPoint"))); } + if (item.hasNonNull("startTimeout")) { def.setStartTimeout(item.path("startTimeout").asInt()); } + if (item.hasNonNull("stopTimeout")) { def.setStopTimeout(item.path("stopTimeout").asInt()); } + if (item.hasNonNull("user")) { def.setUser(item.path("user").asText()); } + if (item.hasNonNull("workingDirectory")) { + def.setWorkingDirectory(item.path("workingDirectory").asText()); + } + if (item.hasNonNull("hostname")) { def.setHostname(item.path("hostname").asText()); } + if (item.hasNonNull("readonlyRootFilesystem")) { + def.setReadonlyRootFilesystem(item.path("readonlyRootFilesystem").asBoolean()); + } + if (item.hasNonNull("privileged")) { def.setPrivileged(item.path("privileged").asBoolean()); } + if (item.hasNonNull("disableNetworking")) { + def.setDisableNetworking(item.path("disableNetworking").asBoolean()); + } + if (item.hasNonNull("interactive")) { def.setInteractive(item.path("interactive").asBoolean()); } + if (item.hasNonNull("pseudoTerminal")) { + def.setPseudoTerminal(item.path("pseudoTerminal").asBoolean()); + } + if (item.has("links")) { def.setLinks(jsonArrayToList(item.path("links"))); } + if (item.has("dnsServers")) { def.setDnsServers(jsonArrayToList(item.path("dnsServers"))); } + if (item.has("dnsSearchDomains")) { + def.setDnsSearchDomains(jsonArrayToList(item.path("dnsSearchDomains"))); + } + if (item.has("dockerSecurityOptions")) { + def.setDockerSecurityOptions(jsonArrayToList(item.path("dockerSecurityOptions"))); + } + if (item.path("dockerLabels").isObject()) { + Map labels = new LinkedHashMap<>(); + item.path("dockerLabels").fields() + .forEachRemaining(entry -> labels.put(entry.getKey(), entry.getValue().asText())); + def.setDockerLabels(labels); + } + if (item.path("repositoryCredentials").hasNonNull("credentialsParameter")) { + def.setRepositoryCredentialsParameter( + item.path("repositoryCredentials").path("credentialsParameter").asText()); + } + def.setUnparsed(EcsJsonPassthrough.capture(item, objectMapper, CONTAINER_DEFINITION_CONSUMED)); + result.add(def); } return result; @@ -1023,7 +1081,12 @@ public class EcsJsonHandler { int containerPort = item.path("containerPort").asInt(0); int hostPort = item.path("hostPort").asInt(0); String protocol = item.path("protocol").asText("tcp"); - result.add(new PortMapping(containerPort, hostPort, protocol)); + String name = item.hasNonNull("name") ? item.path("name").asText() : null; + String appProtocol = item.hasNonNull("appProtocol") ? item.path("appProtocol").asText() : null; + String containerPortRange = item.hasNonNull("containerPortRange") + ? item.path("containerPortRange").asText() : null; + result.add(new PortMapping(containerPort, hostPort, protocol, name, appProtocol, + containerPortRange)); } return result; } @@ -1039,6 +1102,40 @@ public class EcsJsonHandler { return result; } + private List parseEnvironmentFiles(JsonNode node) { + List result = new ArrayList<>(); + if (!node.isArray()) { + return result; + } + for (JsonNode item : node) { + result.add(new EnvironmentFile(item.path("value").asText(), item.path("type").asText("s3"))); + } + return result; + } + + /** + * Parses {@code dependsOn}, rejecting a condition ECS does not define. An unknown condition + * would otherwise silently become a plain start-ordering edge. + */ + private List parseDependsOn(JsonNode node, String containerName) { + List result = new ArrayList<>(); + if (!node.isArray()) { + return result; + } + for (JsonNode item : node) { + String condition = item.path("condition").asText(); + if (!DEPENDENCY_CONDITIONS.contains(condition)) { + throw new AwsException("ClientException", + "Container '" + containerName + "' depends on container '" + + item.path("containerName").asText() + "' with an invalid condition: " + + condition + ". Valid values: " + + String.join(", ", new TreeSet<>(DEPENDENCY_CONDITIONS)) + ".", 400); + } + result.add(new ContainerDependency(item.path("containerName").asText(), condition)); + } + return result; + } + private List parseSecrets(JsonNode node) { List result = new ArrayList<>(); if (!node.isArray()) { @@ -1075,6 +1172,43 @@ public class EcsJsonHandler { return new RuntimePlatform(cpuArchitecture, operatingSystemFamily); } + private EphemeralStorage parseEphemeralStorage(JsonNode node) { + if (node == null || !node.isObject() || !node.hasNonNull("sizeInGiB")) { + return null; + } + return new EphemeralStorage(node.path("sizeInGiB").asInt()); + } + + private List parseCapacityProviderStrategy(JsonNode node) { + if (node == null || !node.isArray() || node.isEmpty()) { + return null; + } + List result = new ArrayList<>(); + for (JsonNode item : node) { + result.add(new CapacityProviderStrategyItem( + item.path("capacityProvider").asText(), + item.path("weight").asInt(0), + item.path("base").asInt(0))); + } + return result; + } + + private TaskOverride parseTaskOverride(JsonNode node) { + if (node == null || !node.isObject()) { + return null; + } + TaskOverride overrides = new TaskOverride(); + overrides.setContainerOverrides(parseContainerOverrides(node.path("containerOverrides"))); + if (node.hasNonNull("cpu")) { overrides.setCpu(node.path("cpu").asText()); } + if (node.hasNonNull("memory")) { overrides.setMemory(node.path("memory").asText()); } + if (node.hasNonNull("taskRoleArn")) { overrides.setTaskRoleArn(node.path("taskRoleArn").asText()); } + if (node.hasNonNull("executionRoleArn")) { + overrides.setExecutionRoleArn(node.path("executionRoleArn").asText()); + } + overrides.setEphemeralStorage(parseEphemeralStorage(node.path("ephemeralStorage"))); + return overrides.isEmpty() ? null : overrides; + } + private LogConfiguration parseLogConfiguration(JsonNode node) { if (node == null || !node.isObject()) { return null; @@ -1121,6 +1255,7 @@ public class EcsJsonHandler { } return new FirelensConfiguration(type, options); } + private HealthCheck parseHealthCheck(JsonNode node) { if (node == null || !node.isObject()) { return null; @@ -1147,11 +1282,18 @@ public class EcsJsonHandler { hostVolumePolicy.validate(hostSourcePath); } EfsVolumeConfiguration efs = parseEfsVolumeConfiguration(item.path("efsVolumeConfiguration")); - result.add(new Volume(item.path("name").asText(), hostSourcePath, efs)); + // "host" stays out of the consumed set so that a volume declaring an empty one reads + // back with it; a host that did carry a sourcePath is written from the typed field and + // the passthrough leaves it alone. + result.add(new Volume(item.path("name").asText(), hostSourcePath, efs, + EcsJsonPassthrough.capture(item, objectMapper, VOLUME_CONSUMED))); } return result; } + /** Volume members the parser consumes; the rest round-trips verbatim. */ + private static final Set VOLUME_CONSUMED = Set.of("name", "efsVolumeConfiguration"); + private EfsVolumeConfiguration parseEfsVolumeConfiguration(JsonNode node) { if (node == null || !node.isObject()) { return null; @@ -1205,11 +1347,17 @@ public class EcsJsonHandler { ContainerOverride co = new ContainerOverride(); co.setName(item.path("name").asText()); if (item.has("command") && item.path("command").isArray()) { - List cmd = new ArrayList<>(); - item.path("command").forEach(c -> cmd.add(c.asText())); - co.setCommand(cmd); + co.setCommand(jsonArrayToList(item.path("command"))); } co.setEnvironment(parseKeyValuePairs(item.path("environment"))); + if (item.has("environmentFiles")) { + co.setEnvironmentFiles(parseEnvironmentFiles(item.path("environmentFiles"))); + } + if (item.hasNonNull("cpu")) { co.setCpu(item.path("cpu").asInt()); } + if (item.hasNonNull("memory")) { co.setMemory(item.path("memory").asInt()); } + if (item.hasNonNull("memoryReservation")) { + co.setMemoryReservation(item.path("memoryReservation").asInt()); + } result.add(co); } return result; @@ -1242,24 +1390,53 @@ public class EcsJsonHandler { return result; } + /** + * Parses a {@code tags} list, holding it to the limits ECS documents for every operation that + * takes one: at most 50 tags, a key of 1 to 128 characters and a value of up to 256. The count + * is taken from the request rather than the parsed map, so 51 entries that collapse to fewer + * distinct keys are still rejected. + */ private Map parseTagMap(JsonNode node) { Map result = new HashMap<>(); if (!node.isArray()) { return result; } + if (node.size() > MAX_TAGS_PER_RESOURCE) { + throw new AwsException("InvalidParameterException", + "Too many tags specified. A resource takes at most " + + MAX_TAGS_PER_RESOURCE + " tags.", 400); + } for (JsonNode item : node) { - result.put(item.path("key").asText(), item.path("value").asText()); + String key = item.path("key").asText(); + String value = item.path("value").asText(); + if (key.isEmpty() || key.length() > MAX_TAG_KEY_LENGTH) { + throw new AwsException("InvalidParameterException", + "Tag keys must be between 1 and " + MAX_TAG_KEY_LENGTH + + " characters long.", 400); + } + if (value.length() > MAX_TAG_VALUE_LENGTH) { + throw new AwsException("InvalidParameterException", + "Tag values can be up to " + MAX_TAG_VALUE_LENGTH + + " characters long.", 400); + } + result.put(key, value); } return result; } + private static final int MAX_TAGS_PER_RESOURCE = 50; + private static final int MAX_TAG_KEY_LENGTH = 128; + private static final int MAX_TAG_VALUE_LENGTH = 256; + + @SuppressWarnings("unchecked") private Map parseRawObject(JsonNode node) { - if (node == null || node.isMissingNode()) { + if (node == null || node.isMissingNode() || !node.isObject()) { return null; } return objectMapper.convertValue(node, Map.class); } + @SuppressWarnings("unchecked") private List> parseRawObjectList(JsonNode node) { List> result = new ArrayList<>(); if (!node.isArray()) { @@ -1279,15 +1456,67 @@ public class EcsJsonHandler { return result; } + /** + * Parses an enum-typed member, rejecting a value the enum does not have. Treating an + * unrecognised value as absent is worse than it sounds: a {@code launchType} of {@code "EC22"} + * would silently fall through to Floci's default and place the task on Fargate, which is not + * what the caller asked for and not what AWS answers. + */ private > T parseEnum(JsonNode req, String field, Class enumClass) { - if (!req.has(field)) { + if (!req.hasNonNull(field)) { return null; } String val = req.path(field).asText(); try { return Enum.valueOf(enumClass, val); } catch (IllegalArgumentException e) { - return null; + List valid = Arrays.stream(enumClass.getEnumConstants()).map(Enum::name).toList(); + throw new AwsException("InvalidParameterException", + "Invalid " + field + ": " + val + ". Valid values: " + + String.join(", ", valid) + ".", 400); } } + + /** Rejects a compatibility the enum does not have, rather than carrying it into the model. */ + private List parseCompatibilities(JsonNode node) { + List requested = jsonArrayToList(node); + for (String value : requested) { + if (!COMPATIBILITIES.contains(value)) { + throw new AwsException("InvalidParameterException", + "Invalid requiresCompatibilities value: " + value + ". Valid values: " + + String.join(", ", new TreeSet<>(COMPATIBILITIES)) + ".", 400); + } + } + return requested; + } + + private static final Set COMPATIBILITIES = + 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 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 DEPENDENCY_CONDITIONS = Set.of( + ContainerDependency.START, ContainerDependency.COMPLETE, + ContainerDependency.SUCCESS, ContainerDependency.HEALTHY); + + /** Optional enum-valued string field: absent → {@code null}; present but not in {@code allowed} → 400. */ + private static String parseChoice(JsonNode node, String field, Set allowed) { + return parseChoice(node, field, field, allowed); + } + + private static String parseChoice(JsonNode node, String field, String displayName, Set allowed) { + if (node == null || node.isMissingNode() || !node.hasNonNull(field)) { + return null; + } + String value = node.path(field).asText(); + if (!allowed.contains(value)) { + throw new AwsException("InvalidParameterException", + "Invalid " + displayName + ": " + value + ". Valid values: " + + String.join(", ", new TreeSet<>(allowed)) + ".", 400); + } + return value; + } } diff --git a/src/main/java/io/github/hectorvent/floci/services/ecs/EcsJsonPassthrough.java b/src/main/java/io/github/hectorvent/floci/services/ecs/EcsJsonPassthrough.java new file mode 100644 index 0000000000..9ef66f0c51 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/ecs/EcsJsonPassthrough.java @@ -0,0 +1,62 @@ +package io.github.hectorvent.floci.services.ecs; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; + +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Set; + +/** + * Keeps the members of a request that Floci has no behaviour for, so a describe returns what the + * caller registered instead of a subset of it. + * + *

ECS's task definition and service shapes carry a long tail of members that only have to + * survive a round trip: {@code proxyConfiguration}, {@code linuxParameters}, {@code ulimits}, + * {@code resourceRequirements}, placement constraints and so on. A client that writes one and + * reads it back, such as Terraform or CDK, treats a dropped member as drift and proposes the same + * change on every plan. Capturing whatever the parser did not consume covers the whole tail at + * once, including members AWS adds later. + */ +final class EcsJsonPassthrough { + + private EcsJsonPassthrough() { + } + + /** + * The members of {@code node} that are not in {@code consumed}, in the order they arrived, or + * {@code null} when there are none. + */ + static Map capture(JsonNode node, ObjectMapper objectMapper, Set consumed) { + if (node == null || !node.isObject()) { + return null; + } + Map result = new LinkedHashMap<>(); + Iterator> fields = node.fields(); + while (fields.hasNext()) { + Map.Entry field = fields.next(); + if (consumed.contains(field.getKey())) { + continue; + } + result.put(field.getKey(), objectMapper.convertValue(field.getValue(), Object.class)); + } + return result.isEmpty() ? null : result; + } + + /** + * Writes the captured members onto a response node. A member the serializer already wrote from + * a typed field wins, so a value Floci normalizes is never overwritten by the raw input. + */ + static void write(ObjectNode target, Map passthrough, ObjectMapper objectMapper) { + if (passthrough == null || passthrough.isEmpty()) { + return; + } + passthrough.forEach((key, value) -> { + if (!target.has(key)) { + target.set(key, objectMapper.valueToTree(value)); + } + }); + } +} 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 b85c155b70..44ad307af5 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 @@ -3,20 +3,26 @@ package io.github.hectorvent.floci.services.ecs; import io.github.hectorvent.floci.services.ecs.model.Attribute; import io.github.hectorvent.floci.services.ecs.model.AwsVpcConfiguration; import io.github.hectorvent.floci.services.ecs.model.CapacityProvider; +import io.github.hectorvent.floci.services.ecs.model.CapacityProviderStrategyItem; import io.github.hectorvent.floci.services.ecs.model.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.ContainerInstance; +import io.github.hectorvent.floci.services.ecs.model.ContainerOverride; import io.github.hectorvent.floci.services.ecs.model.Deployment; import io.github.hectorvent.floci.services.ecs.model.EcsCluster; 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.EfsVolumeConfiguration; +import io.github.hectorvent.floci.services.ecs.model.EnvironmentFile; +import io.github.hectorvent.floci.services.ecs.model.EphemeralStorage; import io.github.hectorvent.floci.services.ecs.model.Failure; import io.github.hectorvent.floci.services.ecs.model.FirelensConfiguration; import io.github.hectorvent.floci.services.ecs.model.HealthCheck; import io.github.hectorvent.floci.services.ecs.model.KeyValuePair; import io.github.hectorvent.floci.services.ecs.model.LogConfiguration; +import io.github.hectorvent.floci.services.ecs.model.ManagedAgent; import io.github.hectorvent.floci.services.ecs.model.MountPoint; import io.github.hectorvent.floci.services.ecs.model.NetworkBinding; import io.github.hectorvent.floci.services.ecs.model.PortMapping; @@ -26,6 +32,8 @@ 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.ServiceRevision; import io.github.hectorvent.floci.services.ecs.model.TaskDefinition; +import io.github.hectorvent.floci.services.ecs.model.TaskNetworkInterface; +import io.github.hectorvent.floci.services.ecs.model.TaskOverride; import io.github.hectorvent.floci.services.ecs.model.TaskSet; import io.github.hectorvent.floci.services.ecs.model.Volume; import io.github.hectorvent.floci.services.ecs.model.VolumeFrom; @@ -35,6 +43,8 @@ import com.fasterxml.jackson.databind.node.ObjectNode; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; +import java.time.Instant; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @@ -104,6 +114,11 @@ public class EcsResponseWriter { if (td.getMemory() != null) { n.put("memory", td.getMemory()); } if (td.getTaskRoleArn() != null) { n.put("taskRoleArn", td.getTaskRoleArn()); } if (td.getExecutionRoleArn() != null) { n.put("executionRoleArn", td.getExecutionRoleArn()); } + if (td.getPidMode() != null) { n.put("pidMode", td.getPidMode()); } + if (td.getIpcMode() != null) { n.put("ipcMode", td.getIpcMode()); } + if (td.getEphemeralStorage() != null) { + n.set("ephemeralStorage", ephemeralStorageNode(td.getEphemeralStorage())); + } if (td.getRuntimePlatform() != null) { RuntimePlatform platform = td.getRuntimePlatform(); ObjectNode platformNode = objectMapper.createObjectNode(); @@ -125,6 +140,11 @@ public class EcsResponseWriter { td.getCompatibilities().forEach(arr::add); n.set("compatibilities", arr); } + if (td.getRequiresAttributes() != null && !td.getRequiresAttributes().isEmpty()) { + ArrayNode arr = objectMapper.createArrayNode(); + td.getRequiresAttributes().forEach(a -> arr.add(attributeNode(a))); + n.set("requiresAttributes", arr); + } ArrayNode containers = objectMapper.createArrayNode(); if (td.getContainerDefinitions() != null) { @@ -136,9 +156,14 @@ public class EcsResponseWriter { if (td.getVolumes() != null && !td.getVolumes().isEmpty()) { n.set("volumes", volumesNode(td.getVolumes())); } + putInstant(n, "registeredAt", td.getRegisteredAt()); + putInstant(n, "deregisteredAt", td.getDeregisteredAt()); + putInstant(n, "deleteRequestedAt", td.getDeleteRequestedAt()); + if (td.getRegisteredBy() != null) { n.put("registeredBy", td.getRegisteredBy()); } if (td.getTags() != null && !td.getTags().isEmpty()) { n.set("tags", tagsNode(td.getTags())); } + EcsJsonPassthrough.write(n, td.getUnparsed(), objectMapper); return n; } @@ -177,6 +202,7 @@ public class EcsResponseWriter { } vNode.set("efsVolumeConfiguration", efs); } + EcsJsonPassthrough.write(vNode, v.unparsed(), objectMapper); vols.add(vNode); } return vols; @@ -189,6 +215,7 @@ public class EcsResponseWriter { n.put("essential", def.isEssential()); if (def.getCpu() != null) { n.put("cpu", def.getCpu()); } if (def.getMemory() != null) { n.put("memory", def.getMemory()); } + if (def.getMemoryReservation() != null) { n.put("memoryReservation", def.getMemoryReservation()); } if (def.getPortMappings() != null && !def.getPortMappings().isEmpty()) { ArrayNode pms = objectMapper.createArrayNode(); @@ -197,6 +224,11 @@ public class EcsResponseWriter { pmNode.put("containerPort", pm.containerPort()); pmNode.put("hostPort", pm.hostPort()); pmNode.put("protocol", pm.protocol()); + if (pm.name() != null) { pmNode.put("name", pm.name()); } + if (pm.appProtocol() != null) { pmNode.put("appProtocol", pm.appProtocol()); } + if (pm.containerPortRange() != null) { + pmNode.put("containerPortRange", pm.containerPortRange()); + } pms.add(pmNode); } n.set("portMappings", pms); @@ -211,6 +243,9 @@ public class EcsResponseWriter { if (def.getEnvironment() != null && !def.getEnvironment().isEmpty()) { n.set("environment", keyValuePairsNode(def.getEnvironment())); } + if (def.getEnvironmentFiles() != null && !def.getEnvironmentFiles().isEmpty()) { + n.set("environmentFiles", environmentFilesNode(def.getEnvironmentFiles())); + } if (def.getSecrets() != null && !def.getSecrets().isEmpty()) { n.set("secrets", secretsNode(def.getSecrets())); } @@ -235,6 +270,16 @@ public class EcsResponseWriter { } n.set("volumesFrom", volumesFrom); } + if (def.getDependsOn() != null && !def.getDependsOn().isEmpty()) { + ArrayNode dependsOn = objectMapper.createArrayNode(); + for (ContainerDependency dependency : def.getDependsOn()) { + ObjectNode dependencyNode = objectMapper.createObjectNode(); + dependencyNode.put("containerName", dependency.containerName()); + dependencyNode.put("condition", dependency.condition()); + dependsOn.add(dependencyNode); + } + n.set("dependsOn", dependsOn); + } if (def.getLogConfiguration() != null) { LogConfiguration logConfig = def.getLogConfiguration(); @@ -279,11 +324,57 @@ public class EcsResponseWriter { n.set("healthCheck", hcNode); } + if (def.getStartTimeout() != null) { n.put("startTimeout", def.getStartTimeout()); } + if (def.getStopTimeout() != null) { n.put("stopTimeout", def.getStopTimeout()); } + if (def.getUser() != null) { n.put("user", def.getUser()); } + if (def.getWorkingDirectory() != null) { n.put("workingDirectory", def.getWorkingDirectory()); } + if (def.getHostname() != null) { n.put("hostname", def.getHostname()); } + if (def.getReadonlyRootFilesystem() != null) { + n.put("readonlyRootFilesystem", def.getReadonlyRootFilesystem()); + } + if (def.getPrivileged() != null) { n.put("privileged", def.getPrivileged()); } + if (def.getDisableNetworking() != null) { n.put("disableNetworking", def.getDisableNetworking()); } + if (def.getInteractive() != null) { n.put("interactive", def.getInteractive()); } + if (def.getPseudoTerminal() != null) { n.put("pseudoTerminal", def.getPseudoTerminal()); } + if (def.getLinks() != null && !def.getLinks().isEmpty()) { + n.set("links", stringArray(def.getLinks())); + } + if (def.getDnsServers() != null && !def.getDnsServers().isEmpty()) { + n.set("dnsServers", stringArray(def.getDnsServers())); + } + if (def.getDnsSearchDomains() != null && !def.getDnsSearchDomains().isEmpty()) { + n.set("dnsSearchDomains", stringArray(def.getDnsSearchDomains())); + } + if (def.getDockerSecurityOptions() != null && !def.getDockerSecurityOptions().isEmpty()) { + n.set("dockerSecurityOptions", stringArray(def.getDockerSecurityOptions())); + } + if (def.getDockerLabels() != null && !def.getDockerLabels().isEmpty()) { + ObjectNode labels = objectMapper.createObjectNode(); + def.getDockerLabels().forEach(labels::put); + n.set("dockerLabels", labels); + } + if (def.getRepositoryCredentialsParameter() != null) { + n.putObject("repositoryCredentials") + .put("credentialsParameter", def.getRepositoryCredentialsParameter()); + } + EcsJsonPassthrough.write(n, def.getUnparsed(), objectMapper); return n; } // ── Tasks ───────────────────────────────────────────────────────────────── + /** + * Renders a task for a describe, where its tags are reported only when the caller asked for + * them with {@code include: ["TAGS"]}. + */ + public ObjectNode taskNode(EcsTask t, boolean includeTags) { + ObjectNode n = taskNode(t); + if (!includeTags) { + n.remove("tags"); + } + return n; + } + /** Renders an ECS task to its data-plane JSON shape. Reused by the Step Functions * ecs:runTask integration ({@link io.github.hectorvent.floci.services.stepfunctions.AslExecutor}). */ public ObjectNode taskNode(EcsTask t) { @@ -293,16 +384,52 @@ public class EcsResponseWriter { n.put("taskDefinitionArn", t.getTaskDefinitionArn()); n.put("lastStatus", t.getLastStatus()); n.put("desiredStatus", t.getDesiredStatus()); - if (t.getLaunchType() != null) { n.put("launchType", t.getLaunchType().name()); } + // A task placed through a capacity provider reports both: the provider it was placed + // through and the launch type that provider resolves to. (A service reports only one of + // the two, which is why serviceNode does it differently.) + if (t.getCapacityProviderName() != null) { + n.put("capacityProviderName", t.getCapacityProviderName()); + } + if (t.getLaunchType() != null) { + n.put("launchType", t.getLaunchType().name()); + } + if (t.getPlatformVersion() != null) { n.put("platformVersion", t.getPlatformVersion()); } + if (t.getPlatformFamily() != null) { n.put("platformFamily", t.getPlatformFamily()); } if (t.getCpu() != null) { n.put("cpu", t.getCpu()); } if (t.getMemory() != null) { n.put("memory", t.getMemory()); } + if (t.getEphemeralStorage() != null) { + n.set("ephemeralStorage", ephemeralStorageNode(t.getEphemeralStorage())); + // A Fargate task also reports the storage it actually got, which is the same size here. + if (t.getPlatformVersion() != null) { + n.set("fargateEphemeralStorage", ephemeralStorageNode(t.getEphemeralStorage())); + } + } if (t.getGroup() != null) { n.put("group", t.getGroup()); } if (t.getStartedBy() != null) { n.put("startedBy", t.getStartedBy()); } if (t.getContainerInstanceArn() != null) { n.put("containerInstanceArn", t.getContainerInstanceArn()); } - if (t.getCreatedAt() != null) { n.put("createdAt", t.getCreatedAt().toEpochMilli() / 1000.0); } - if (t.getStartedAt() != null) { n.put("startedAt", t.getStartedAt().toEpochMilli() / 1000.0); } - if (t.getStoppedAt() != null) { n.put("stoppedAt", t.getStoppedAt().toEpochMilli() / 1000.0); } + if (t.getAvailabilityZone() != null) { n.put("availabilityZone", t.getAvailabilityZone()); } + if (t.getConnectivity() != null) { n.put("connectivity", t.getConnectivity()); } + putInstant(n, "connectivityAt", t.getConnectivityAt()); + if (t.getHealthStatus() != null) { n.put("healthStatus", t.getHealthStatus()); } + if (t.getStopCode() != null) { n.put("stopCode", t.getStopCode()); } + n.put("enableExecuteCommand", t.isEnableExecuteCommand()); + n.put("version", t.getVersion()); + putInstant(n, "createdAt", t.getCreatedAt()); + putInstant(n, "startedAt", t.getStartedAt()); + putInstant(n, "stoppingAt", t.getStoppingAt()); + putInstant(n, "stoppedAt", t.getStoppedAt()); + putInstant(n, "pullStartedAt", t.getPullStartedAt()); + putInstant(n, "pullStoppedAt", t.getPullStoppedAt()); + putInstant(n, "executionStoppedAt", t.getExecutionStoppedAt()); if (t.getStoppedReason() != null) { n.put("stoppedReason", t.getStoppedReason()); } + // A task always reports overrides, with one containerOverrides entry per container even + // when the request overrode nothing, which is what DescribeTasks answers with. + n.set("overrides", taskOverrideNode(t)); + if (t.getAttributes() != null && !t.getAttributes().isEmpty()) { + ArrayNode attrs = objectMapper.createArrayNode(); + t.getAttributes().forEach(a -> attrs.add(attributeNode(a))); + n.set("attributes", attrs); + } if (t.getNetworkInterfaceId() != null) { n.putArray("attachments").add(eniAttachmentNode(t)); } @@ -322,9 +449,10 @@ public class EcsResponseWriter { private ObjectNode eniAttachmentNode(EcsTask t) { ObjectNode attachment = objectMapper.createObjectNode(); - attachment.put("id", "eni-attach-" + t.getNetworkInterfaceId()); + attachment.put("id", t.getAttachmentId() != null + ? t.getAttachmentId() : "eni-attach-" + t.getNetworkInterfaceId()); attachment.put("type", "ElasticNetworkInterface"); - attachment.put("status", "ATTACHED"); + attachment.put("status", t.getAttachmentStatus() != null ? t.getAttachmentStatus() : "ATTACHED"); ArrayNode details = objectMapper.createArrayNode(); if (t.getNetworkConfiguration() != null && t.getNetworkConfiguration().getAwsvpcConfiguration() != null @@ -333,6 +461,12 @@ public class EcsResponseWriter { t.getNetworkConfiguration().getAwsvpcConfiguration().getSubnets().getFirst()); } details.addObject().put("name", "networkInterfaceId").put("value", t.getNetworkInterfaceId()); + if (t.getMacAddress() != null) { + details.addObject().put("name", "macAddress").put("value", t.getMacAddress()); + } + if (t.getPrivateDnsName() != null) { + details.addObject().put("name", "privateDnsName").put("value", t.getPrivateDnsName()); + } details.addObject().put("name", "privateIPv4Address").put("value", t.getPrivateIpAddress()); attachment.set("details", details); return attachment; @@ -347,6 +481,13 @@ public class EcsResponseWriter { cn.put("lastStatus", c.getLastStatus()); if (c.getExitCode() != null) { cn.put("exitCode", c.getExitCode()); } if (c.getReason() != null) { cn.put("reason", c.getReason()); } + if (c.getHealthStatus() != null) { cn.put("healthStatus", c.getHealthStatus()); } + if (c.getRuntimeId() != null) { cn.put("runtimeId", c.getRuntimeId()); } + if (c.getImageDigest() != null) { cn.put("imageDigest", c.getImageDigest()); } + // A container definition that asked for no CPU units reports zero, not nothing. + cn.put("cpu", c.getCpu() != null ? c.getCpu() : "0"); + if (c.getMemory() != null) { cn.put("memory", c.getMemory()); } + if (c.getMemoryReservation() != null) { cn.put("memoryReservation", c.getMemoryReservation()); } ArrayNode bindings = objectMapper.createArrayNode(); if (c.getNetworkBindings() != null) { @@ -360,11 +501,91 @@ public class EcsResponseWriter { } } cn.set("networkBindings", bindings); + if (c.getNetworkInterfaces() != null && !c.getNetworkInterfaces().isEmpty()) { + ArrayNode interfaces = objectMapper.createArrayNode(); + for (TaskNetworkInterface ni : c.getNetworkInterfaces()) { + ObjectNode in = objectMapper.createObjectNode(); + if (ni.attachmentId() != null) { in.put("attachmentId", ni.attachmentId()); } + if (ni.privateIpv4Address() != null) { in.put("privateIpv4Address", ni.privateIpv4Address()); } + if (ni.ipv6Address() != null) { in.put("ipv6Address", ni.ipv6Address()); } + interfaces.add(in); + } + cn.set("networkInterfaces", interfaces); + } + if (c.getManagedAgents() != null && !c.getManagedAgents().isEmpty()) { + ArrayNode agents = objectMapper.createArrayNode(); + for (ManagedAgent agent : c.getManagedAgents()) { + ObjectNode an = objectMapper.createObjectNode(); + an.put("name", agent.name()); + an.put("lastStatus", agent.lastStatus()); + if (agent.reason() != null) { an.put("reason", agent.reason()); } + putInstant(an, "lastStartedAt", agent.lastStartedAt()); + agents.add(an); + } + cn.set("managedAgents", agents); + } return cn; } + /** + * The task's overrides. Every container is listed, carrying whatever the request overrode for + * it and nothing more, so a client that walks {@code containerOverrides} sees the same entries + * AWS returns rather than an empty list for a task nobody overrode. + */ + private ObjectNode taskOverrideNode(EcsTask task) { + TaskOverride overrides = task.getOverrides() != null ? task.getOverrides() : new TaskOverride(); + Map byName = new LinkedHashMap<>(); + if (task.getContainers() != null) { + task.getContainers().forEach(container -> { + ContainerOverride placeholder = new ContainerOverride(); + placeholder.setName(container.getName()); + byName.put(container.getName(), placeholder); + }); + } + if (overrides.getContainerOverrides() != null) { + overrides.getContainerOverrides().forEach(override -> byName.put(override.getName(), override)); + } + return taskOverrideNode(overrides, List.copyOf(byName.values())); + } + + private ObjectNode taskOverrideNode(TaskOverride overrides, List perContainer) { + ObjectNode n = objectMapper.createObjectNode(); + ArrayNode containerOverrides = objectMapper.createArrayNode(); + for (ContainerOverride co : perContainer) { + ObjectNode con = objectMapper.createObjectNode(); + con.put("name", co.getName()); + if (co.getCommand() != null && !co.getCommand().isEmpty()) { + con.set("command", stringArray(co.getCommand())); + } + if (co.getEnvironment() != null && !co.getEnvironment().isEmpty()) { + con.set("environment", keyValuePairsNode(co.getEnvironment())); + } + if (co.getEnvironmentFiles() != null && !co.getEnvironmentFiles().isEmpty()) { + con.set("environmentFiles", environmentFilesNode(co.getEnvironmentFiles())); + } + if (co.getCpu() != null) { con.put("cpu", co.getCpu()); } + if (co.getMemory() != null) { con.put("memory", co.getMemory()); } + if (co.getMemoryReservation() != null) { + con.put("memoryReservation", co.getMemoryReservation()); + } + containerOverrides.add(con); + } + n.set("containerOverrides", containerOverrides); + if (overrides.getCpu() != null) { n.put("cpu", overrides.getCpu()); } + if (overrides.getMemory() != null) { n.put("memory", overrides.getMemory()); } + if (overrides.getTaskRoleArn() != null) { n.put("taskRoleArn", overrides.getTaskRoleArn()); } + if (overrides.getExecutionRoleArn() != null) { + n.put("executionRoleArn", overrides.getExecutionRoleArn()); + } + if (overrides.getEphemeralStorage() != null) { + n.set("ephemeralStorage", ephemeralStorageNode(overrides.getEphemeralStorage())); + } + return n; + } + // ── Services ────────────────────────────────────────────────────────────── + /** Renders a service for a describe, gating its tags on {@code include: ["TAGS"]}. */ public ObjectNode serviceNode(EcsServiceModel s) { ObjectNode n = objectMapper.createObjectNode(); n.put("serviceArn", s.getServiceArn()); @@ -375,8 +596,13 @@ public class EcsResponseWriter { n.put("runningCount", s.getRunningCount()); n.put("pendingCount", s.getPendingCount()); n.put("status", s.getStatus()); - if (s.getLaunchType() != null) { n.put("launchType", s.getLaunchType().name()); } - if (s.getCreatedAt() != null) { n.put("createdAt", s.getCreatedAt().toEpochMilli() / 1000.0); } + if (s.getCapacityProviderStrategy() != null && !s.getCapacityProviderStrategy().isEmpty()) { + n.set("capacityProviderStrategy", + capacityProviderStrategyNode(s.getCapacityProviderStrategy())); + } else if (s.getLaunchType() != null) { + n.put("launchType", s.getLaunchType().name()); + } + putInstant(n, "createdAt", s.getCreatedAt()); if (s.getNamespace() != null) { n.put("namespace", s.getNamespace()); } // Services persisted before these fields existed read back with the AWS defaults. n.put("schedulingStrategy", s.getSchedulingStrategy() != null @@ -407,12 +633,15 @@ public class EcsResponseWriter { } private ObjectNode loadBalancerNode(EcsLoadBalancer lb) { - ObjectNode ln = objectMapper.createObjectNode(); - if (lb.getTargetGroupArn() != null) { ln.put("targetGroupArn", lb.getTargetGroupArn()); } - if (lb.getLoadBalancerName() != null) { ln.put("loadBalancerName", lb.getLoadBalancerName()); } - if (lb.getContainerName() != null) { ln.put("containerName", lb.getContainerName()); } - if (lb.getContainerPort() != null) { ln.put("containerPort", lb.getContainerPort()); } - return ln; + ObjectNode n = objectMapper.createObjectNode(); + if (lb.getTargetGroupArn() != null) { n.put("targetGroupArn", lb.getTargetGroupArn()); } + if (lb.getLoadBalancerName() != null) { n.put("loadBalancerName", lb.getLoadBalancerName()); } + if (lb.getContainerName() != null) { n.put("containerName", lb.getContainerName()); } + if (lb.getContainerPort() != null) { n.put("containerPort", lb.getContainerPort()); } + if (lb.getAdvancedConfiguration() != null) { + n.set("advancedConfiguration", objectMapper.valueToTree(lb.getAdvancedConfiguration())); + } + return n; } private ObjectNode networkConfigurationNode(AwsVpcConfiguration awsvpc) { @@ -455,8 +684,6 @@ public class EcsResponseWriter { return n; } - // ── Container instances ─────────────────────────────────────────────────── - public ObjectNode containerInstanceNode(ContainerInstance ci) { ObjectNode n = objectMapper.createObjectNode(); n.put("containerInstanceArn", ci.getContainerInstanceArn()); @@ -477,8 +704,7 @@ public class EcsResponseWriter { return n; } - // ── Capacity providers ──────────────────────────────────────────────────── - + /** @param includeTags DescribeCapacityProviders returns tags only for {@code include: ["TAGS"]}. */ public ObjectNode capacityProviderNode(CapacityProvider cp) { ObjectNode n = objectMapper.createObjectNode(); n.put("name", cp.getName()); @@ -490,8 +716,6 @@ public class EcsResponseWriter { return n; } - // ── Task sets ───────────────────────────────────────────────────────────── - public ObjectNode taskSetNode(TaskSet ts) { ObjectNode n = objectMapper.createObjectNode(); n.put("id", ts.getId()); @@ -518,8 +742,6 @@ public class EcsResponseWriter { return n; } - // ── Service deployments and revisions ───────────────────────────────────── - public ObjectNode serviceDeploymentNode(ServiceDeployment d) { ObjectNode n = objectMapper.createObjectNode(); n.put("serviceDeploymentArn", d.getServiceDeploymentArn()); @@ -543,15 +765,11 @@ public class EcsResponseWriter { return n; } - // ── Shared members ──────────────────────────────────────────────────────── - public ObjectNode protectedTaskNode(ProtectedTask pt) { ObjectNode n = objectMapper.createObjectNode(); n.put("taskArn", pt.taskArn()); n.put("protectionEnabled", pt.protectionEnabled()); - if (pt.expirationDate() != null) { - n.put("expirationDate", pt.expirationDate().toEpochMilli() / 1000.0); - } + putInstant(n, "expirationDate", pt.expirationDate()); return n; } @@ -582,6 +800,24 @@ public class EcsResponseWriter { return arr; } + public ArrayNode capacityProviderStrategyNode(List strategy) { + ArrayNode arr = objectMapper.createArrayNode(); + for (CapacityProviderStrategyItem item : strategy) { + ObjectNode n = objectMapper.createObjectNode(); + n.put("capacityProvider", item.capacityProvider()); + n.put("weight", item.weight()); + n.put("base", item.base()); + arr.add(n); + } + return arr; + } + + private ObjectNode ephemeralStorageNode(EphemeralStorage storage) { + ObjectNode n = objectMapper.createObjectNode(); + n.put("sizeInGiB", storage.sizeInGiB()); + return n; + } + private ArrayNode keyValuePairsNode(List pairs) { ArrayNode arr = objectMapper.createArrayNode(); for (KeyValuePair kv : pairs) { @@ -593,6 +829,17 @@ public class EcsResponseWriter { return arr; } + private ArrayNode environmentFilesNode(List files) { + ArrayNode arr = objectMapper.createArrayNode(); + for (EnvironmentFile file : files) { + ObjectNode fileNode = objectMapper.createObjectNode(); + fileNode.put("value", file.value()); + fileNode.put("type", file.type()); + arr.add(fileNode); + } + return arr; + } + private ArrayNode secretsNode(List secrets) { ArrayNode arr = objectMapper.createArrayNode(); for (Secret secret : secrets) { @@ -606,7 +853,16 @@ public class EcsResponseWriter { private ArrayNode stringArray(List values) { ArrayNode arr = objectMapper.createArrayNode(); - values.forEach(arr::add); + if (values != null) { + values.forEach(arr::add); + } return arr; } + + /** ECS timestamps go on the wire as epoch seconds with a fractional part. */ + private static void putInstant(ObjectNode target, String field, Instant value) { + if (value != null) { + target.put(field, value.toEpochMilli() / 1000.0); + } + } } 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 6403b934f5..ff9509791c 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 @@ -15,13 +15,17 @@ import io.github.hectorvent.floci.services.ecs.container.EcsContainerManager; import io.github.hectorvent.floci.services.ecs.container.EcsTaskHandle; import io.github.hectorvent.floci.services.ecs.model.Attribute; import io.github.hectorvent.floci.services.ecs.model.CapacityProvider; +import io.github.hectorvent.floci.services.ecs.model.CapacityProviderStrategyItem; 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.ContainerInstance; 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.Deployment; +import io.github.hectorvent.floci.services.ecs.model.EphemeralStorage; import io.github.hectorvent.floci.services.ecs.model.Failure; import io.github.hectorvent.floci.services.ecs.model.ContainerOverride; import io.github.hectorvent.floci.services.ecs.model.EcsCluster; @@ -31,17 +35,22 @@ 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.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.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.ServiceRevision; import io.github.hectorvent.floci.services.ecs.model.TaskDefinition; +import io.github.hectorvent.floci.services.ecs.model.TaskNetworkInterface; +import io.github.hectorvent.floci.services.ecs.model.TaskOverride; import io.github.hectorvent.floci.services.ecs.model.TaskSet; import io.github.hectorvent.floci.services.ecs.model.TaskStatus; import io.github.hectorvent.floci.services.ecs.model.UpdateServiceRequest; +import io.github.hectorvent.floci.services.ecs.model.Volume; import jakarta.annotation.PostConstruct; import jakarta.annotation.PreDestroy; import jakarta.enterprise.context.ApplicationScoped; @@ -51,6 +60,8 @@ import org.jboss.logging.Logger; import java.time.Instant; import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; @@ -109,6 +120,34 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab public static final String DEFAULT_AZ_REBALANCING_ON_CREATE = "ENABLED"; /** A service that never had a value (persisted before the field existed) reads as DISABLED. */ public static final String DEFAULT_AZ_REBALANCING_UNSET = "DISABLED"; + /** The Fargate platform version {@code LATEST} resolves to. */ + public static final String DEFAULT_PLATFORM_VERSION = "1.4.0"; + public static final String PLATFORM_VERSION_LATEST = "LATEST"; + /** The platform family a Linux task reports, as DescribeTasks answers it. */ + public static final String DEFAULT_PLATFORM_FAMILY = "Linux"; + public static final String CONNECTIVITY_CONNECTED = "CONNECTED"; + public static final String HEALTH_STATUS_UNKNOWN = "UNKNOWN"; + public static final String HEALTH_STATUS_HEALTHY = "HEALTHY"; + public static final String HEALTH_STATUS_UNHEALTHY = "UNHEALTHY"; + public static final String STOP_CODE_TASK_FAILED_TO_START = "TaskFailedToStart"; + public static final String STOP_CODE_ESSENTIAL_CONTAINER_EXITED = "EssentialContainerExited"; + public static final String STOP_CODE_USER_INITIATED = "UserInitiated"; + public static final String STOP_CODE_SERVICE_SCHEDULER_INITIATED = "ServiceSchedulerInitiated"; + public static final String PROPAGATE_TAGS_SERVICE = "SERVICE"; + public static final String PROPAGATE_TAGS_TASK_DEFINITION = "TASK_DEFINITION"; + /** RunTask places at most ten tasks in one call, and StartTask at most ten instances. */ + public static final int MAX_TASKS_PER_RUN = 10; + public static final String STATUS_ACTIVE = "ACTIVE"; + public static final String STATUS_INACTIVE = "INACTIVE"; + public static final String STATUS_DELETE_IN_PROGRESS = "DELETE_IN_PROGRESS"; + /** The attribute every task carries, naming the architecture it actually runs on. */ + private static final String CPU_ARCHITECTURE_ATTRIBUTE = "ecs.cpu-architecture"; + /** The two built-in capacity providers, which place Fargate tasks rather than EC2 ones. */ + private static final Set FARGATE_CAPACITY_PROVIDERS = Set.of("FARGATE", "FARGATE_SPOT"); + /** The bounds the ECS model puts on a capacity provider strategy and on its entries. */ + private static final int MAX_CAPACITY_PROVIDERS_PER_STRATEGY = 20; + private static final int MAX_CAPACITY_PROVIDER_WEIGHT = 1000; + private static final int MAX_CAPACITY_PROVIDER_BASE = 100_000; // region::clusterArn/instanceArn → ContainerInstance private final Map containerInstances = new ConcurrentHashMap<>(); // name → CapacityProvider (excludes built-ins FARGATE, FARGATE_SPOT) @@ -122,6 +161,8 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab // targetArn → List private Map> attributes = new ConcurrentHashMap<>(); // name → value (account-level settings) + // principalArn::name → value. The root principal's row doubles as the account default, which + // is how AWS describes it: "the account settings for the root user or the default setting". private Map accountSettings = new ConcurrentHashMap<>(); // deploymentIds for which SERVICE_DEPLOYMENT_IN_PROGRESS has already been emitted this process. private final Set inProgressEmitted = java.util.concurrent.ConcurrentHashMap.newKeySet(); @@ -237,6 +278,16 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab LOG.warnv("Failed to stop ECS task {0} on shutdown: {1}", taskArn, e.getMessage()); } } + // Task state is memory-only, so an ENI left behind here would outlive every task that + // could claim it and reload from EC2's store as an orphan on the next start. + for (EcsTask task : tasks.values()) { + try { + containerManager.releaseTaskNetwork(task, taskRegion(task)); + } catch (Exception e) { + LOG.warnv("Failed to release the ENI of ECS task {0} on shutdown: {1}", + task.getTaskArn(), e.getMessage()); + } + } } @Override @@ -304,13 +355,15 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab EcsCluster cluster = new EcsCluster(); cluster.setClusterName(name); cluster.setClusterArn(regionResolver.buildArn("ecs", region, "cluster/" + name)); - cluster.setStatus("ACTIVE"); + cluster.setStatus(STATUS_ACTIVE); if (request.getTags() != null && !request.getTags().isEmpty()) { cluster.setTags(new LinkedHashMap<>(request.getTags())); } if (request.getSettings() != null && !request.getSettings().isEmpty()) { cluster.setSettings(new ArrayList<>(request.getSettings())); } + cluster.setCapacityProviders(request.getCapacityProviders()); + cluster.setDefaultCapacityProviderStrategy(request.getDefaultCapacityProviderStrategy()); clusters.put(key, cluster); LOG.infov("Created ECS cluster: {0} in {1}", name, region); return cluster; @@ -409,23 +462,14 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab public TaskDefinition registerTaskDefinition(RegisterTaskDefinitionRequest request, String region) { List containerDefs = request.getContainerDefinitions(); - List requiresCompatibilities = request.getRequiresCompatibilities(); boolean fargate = request.isFargate(); - if (fargate) { - if (request.getNetworkMode() != NetworkMode.awsvpc) { - throw new AwsException("ClientException", "Fargate only supports network mode 'awsvpc'.", 400); - } - if (request.getCpu() == null) { - throw new AwsException("ClientException", "Fargate requires that 'cpu' be defined at the task level.", 400); - } - if (request.getMemory() == null) { - throw new AwsException("ClientException", "Fargate requires that 'memory' be defined at the task level.", 400); - } - if (!isValidFargateCpuMemory(request.getCpu(), request.getMemory())) { - throw new AwsException("ClientException", "No Fargate configuration exists for given values.", 400); - } - } + validateTaskSize(request, fargate); + validateEphemeralStorage(request.getEphemeralStorage()); + validateContainerDependencies(containerDefs); validateFirelensS3Config(containerDefs, fargate); + if (fargate) { + validateFargateUnsupportedParameters(request); + } String family = request.getFamily(); int revision = latestRevisions.merge(family, 1, Integer::sum); @@ -439,15 +483,18 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab td.setTaskRoleArn(request.getTaskRoleArn()); td.setExecutionRoleArn(request.getExecutionRoleArn()); td.setContainerDefinitions(containerDefs != null ? containerDefs : List.of()); - td.setRequiresCompatibilities(requiresCompatibilities); + td.setRequiresCompatibilities(request.getRequiresCompatibilities()); td.setVolumes(request.getVolumes()); td.setRuntimePlatform(request.getRuntimePlatform()); + td.setEphemeralStorage(request.getEphemeralStorage()); + td.setPidMode(request.getPidMode()); + td.setIpcMode(request.getIpcMode()); + td.setUnparsed(request.getUnparsed()); + td.setRegisteredAt(Instant.now()); + td.setRegisteredBy(regionResolver.buildArn("iam", region, "root")); - if (requiresCompatibilities != null && !requiresCompatibilities.isEmpty()) { - td.setCompatibilities(new ArrayList<>(requiresCompatibilities)); - } else { - td.setCompatibilities(List.of("EC2")); - } + td.setCompatibilities(deriveCompatibilities(request, fargate)); + td.setRequiresAttributes(deriveRequiresAttributes(request)); td.setTaskDefinitionArn(regionResolver.buildArn("ecs", region, "task-definition/" + family + ":" + revision)); @@ -460,6 +507,276 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab return td; } + /** + * The launch types a registered definition is actually compatible with, which is not the same + * as the {@code requiresCompatibilities} it was validated against: "Amazon ECS validates the + * task definition parameters with those supported by the launch type", so a definition that + * satisfies Fargate's rules reports FARGATE even when it never asked for it. + * + *

EXTERNAL covers the same ground as EC2 minus {@code awsvpc}, which ECS Anywhere instances + * do not support. + */ + private List deriveCompatibilities(RegisterTaskDefinitionRequest request, boolean fargate) { + List compatibilities = new ArrayList<>(); + compatibilities.add("EC2"); + if (fargate || isFargateCompatible(request)) { + compatibilities.add("FARGATE"); + } + if (request.getNetworkMode() != NetworkMode.awsvpc) { + compatibilities.add("EXTERNAL"); + } + return compatibilities; + } + + /** Runs Fargate's own rules over a definition that did not ask for them, to see if it passes. */ + private boolean isFargateCompatible(RegisterTaskDefinitionRequest request) { + if (request.getNetworkMode() != NetworkMode.awsvpc) { + return false; + } + try { + validateTaskSize(request, true); + validateEphemeralStorage(request.getEphemeralStorage()); + validateFirelensS3Config(request.getContainerDefinitions(), true); + validateFargateUnsupportedParameters(request); + return true; + } catch (AwsException notFargateCompatible) { + LOG.debugv("Task definition {0} is not Fargate compatible: {1}", + request.getFamily(), notFargateCompatible.getMessage()); + return false; + } + } + + /** The Docker remote API version every task definition needs, per the RegisterTaskDefinition sample. */ + private static final String BASE_AGENT_CAPABILITY = "com.amazonaws.ecs.capability.docker-remote-api.1.18"; + + /** + * The container instance capabilities a definition needs to be placed on EC2. + * + *

ECS derives these from the agent's capability model, which AWS does not publish in full. + * Floci derives the subset whose names appear verbatim in the AWS documentation: the base + * Docker remote API version, the log driver, ECR authentication, the task IAM role (which has + * a separate name under {@code host} networking), privileged containers, and the task ENI + * capability that {@code awsvpc} placement requires. + */ + private List deriveRequiresAttributes(RegisterTaskDefinitionRequest request) { + Set names = new LinkedHashSet<>(); + names.add(BASE_AGENT_CAPABILITY); + NetworkMode networkMode = request.getNetworkMode() != null + ? request.getNetworkMode() : NetworkMode.bridge; + if (networkMode == NetworkMode.awsvpc) { + names.add("ecs.capability.task-eni"); + } + if (request.getTaskRoleArn() != null) { + names.add(networkMode == NetworkMode.host + ? "com.amazonaws.ecs.capability.task-iam-role-network-host" + : "com.amazonaws.ecs.capability.task-iam-role"); + } + if (request.getContainerDefinitions() != null) { + for (ContainerDefinition def : request.getContainerDefinitions()) { + if (def.getLogConfiguration() != null && def.getLogConfiguration().logDriver() != null) { + names.add("com.amazonaws.ecs.capability.logging-driver." + + def.getLogConfiguration().logDriver()); + } + if (def.getImage() != null && def.getImage().contains(".dkr.ecr.")) { + names.add("com.amazonaws.ecs.capability.ecr-auth"); + } + if (Boolean.TRUE.equals(def.getPrivileged())) { + names.add("com.amazonaws.ecs.capability.privileged-container"); + } + } + } + return names.stream().map(name -> new Attribute(name, null, null, null)).toList(); + } + + /** + * The task-level size rules. Fargate requires both values and accepts only the documented + * pairs; Windows on Fargate additionally has no sub-vCPU size. + */ + private void validateTaskSize(RegisterTaskDefinitionRequest request, boolean fargate) { + if (!fargate) { + return; + } + if (request.getNetworkMode() != NetworkMode.awsvpc) { + throw new AwsException("ClientException", "Fargate only supports network mode 'awsvpc'.", 400); + } + if (request.getCpu() == null) { + throw new AwsException("ClientException", + "Fargate requires that 'cpu' be defined at the task level.", 400); + } + if (request.getMemory() == null) { + throw new AwsException("ClientException", + "Fargate requires that 'memory' be defined at the task level.", 400); + } + if (!isValidFargateCpuMemory(request.getCpu(), request.getMemory())) { + throw new AwsException("ClientException", "No Fargate configuration exists for given values.", 400); + } + RuntimePlatform platform = request.getRuntimePlatform(); + boolean windows = platform != null && platform.operatingSystemFamily() != null + && platform.operatingSystemFamily().startsWith("WINDOWS"); + if (windows && parseCpu(request.getCpu()) < 1024) { + throw new AwsException("ClientException", "No Fargate configuration exists for given values.", 400); + } + } + + /** + * Fargate's ephemeral storage is 20 GiB by default and can be expanded up to 200 GiB, so an + * explicit request below the default or above the ceiling is rejected the way AWS rejects it. + */ + private static void validateEphemeralStorage(EphemeralStorage storage) { + if (storage == null) { + return; + } + if (storage.sizeInGiB() <= EphemeralStorage.DEFAULT_SIZE_IN_GIB + || storage.sizeInGiB() > EphemeralStorage.MAX_SIZE_IN_GIB) { + throw new AwsException("ClientException", + "Invalid setting for ephemeral storage. Size must be between " + + (EphemeralStorage.DEFAULT_SIZE_IN_GIB + 1) + " GiB and " + + EphemeralStorage.MAX_SIZE_IN_GIB + " GiB.", 400); + } + } + + /** + * A {@code dependsOn} entry may only name another container of the same task definition, and + * the graph they form has to be acyclic: a cycle would leave every container in it waiting for + * another, so ECS rejects it at registration rather than at launch. + */ + private static void validateContainerDependencies(List containerDefs) { + if (containerDefs == null) { + return; + } + Map byName = new LinkedHashMap<>(); + containerDefs.forEach(def -> byName.put(def.getName(), def)); + for (ContainerDefinition def : containerDefs) { + if (def.getDependsOn() == null) { + continue; + } + for (ContainerDependency dependency : def.getDependsOn()) { + if (dependency.containerName().equals(def.getName())) { + throw new AwsException("ClientException", + "Container '" + def.getName() + "' cannot depend on itself.", 400); + } + if (!byName.containsKey(dependency.containerName())) { + throw new AwsException("ClientException", + "Container '" + def.getName() + "' depends on container '" + + dependency.containerName() + "' which does not exist.", 400); + } + } + } + Set resolved = new HashSet<>(); + Set visiting = new LinkedHashSet<>(); + for (ContainerDefinition def : containerDefs) { + rejectDependencyCycle(def, byName, visiting, resolved); + } + } + + private static void rejectDependencyCycle(ContainerDefinition def, + Map byName, + Set visiting, Set resolved) { + if (resolved.contains(def.getName())) { + return; + } + if (!visiting.add(def.getName())) { + throw new AwsException("ClientException", + "The container dependencies form a cycle: " + + String.join(" -> ", visiting) + " -> " + def.getName() + ".", 400); + } + if (def.getDependsOn() != null) { + for (ContainerDependency dependency : def.getDependsOn()) { + rejectDependencyCycle(byName.get(dependency.containerName()), byName, visiting, resolved); + } + } + visiting.remove(def.getName()); + resolved.add(def.getName()); + } + + /** + * The task definition parameters that are not valid in a Fargate task, as the Fargate task + * definition differences document lists them: {@code disableNetworking}, + * {@code dnsSearchDomains}, {@code dnsServers}, {@code dockerSecurityOptions}, + * {@code extraHosts}, {@code gpu}, {@code ipcMode}, {@code links}, + * {@code placementConstraints}, {@code privileged}, {@code maxSwap} and {@code swappiness}, + * plus the {@code pidMode} values other than {@code task} and the host bind mounts Fargate + * cannot provide. ECS rejects each of them at registration rather than failing the task later. + */ + private static void validateFargateUnsupportedParameters(RegisterTaskDefinitionRequest request) { + if (request.getIpcMode() != null) { + throw new AwsException("ClientException", + "Fargate compatible task definitions do not support ipcMode.", 400); + } + if (request.getPidMode() != null && !"task".equals(request.getPidMode())) { + throw new AwsException("ClientException", + "Fargate compatible task definitions only support the 'task' pidMode.", 400); + } + if (notEmpty(request.getUnparsed(), "placementConstraints")) { + throw new AwsException("ClientException", + "Fargate compatible task definitions do not support placementConstraints.", 400); + } + if (request.getVolumes() != null) { + for (Volume volume : request.getVolumes()) { + if (volume.hostSourcePath() != null && !volume.hostSourcePath().isBlank()) { + throw new AwsException("ClientException", + "Fargate compatible task definitions do not support host volume sourcePath.", 400); + } + } + } + if (request.getContainerDefinitions() == null) { + return; + } + for (ContainerDefinition def : request.getContainerDefinitions()) { + rejectOnFargate(Boolean.TRUE.equals(def.getPrivileged()), "privileged"); + rejectOnFargate(Boolean.TRUE.equals(def.getDisableNetworking()), "disableNetworking"); + rejectOnFargate(def.getLinks() != null && !def.getLinks().isEmpty(), "links"); + rejectOnFargate(def.getDnsServers() != null && !def.getDnsServers().isEmpty(), "dnsServers"); + rejectOnFargate(def.getDnsSearchDomains() != null && !def.getDnsSearchDomains().isEmpty(), + "dnsSearchDomains"); + rejectOnFargate(def.getDockerSecurityOptions() != null && !def.getDockerSecurityOptions().isEmpty(), + "dockerSecurityOptions"); + rejectOnFargate(notEmpty(def.getUnparsed(), "extraHosts"), "extraHosts"); + validateFargateLinuxParameters(def); + validateFargateResourceRequirements(def); + } + } + + private static void rejectOnFargate(boolean present, String parameter) { + if (present) { + throw new AwsException("ClientException", + "Fargate compatible task definitions do not support " + parameter + ".", 400); + } + } + + /** {@code maxSwap} and {@code swappiness} have no meaning on Fargate's managed kernel. */ + @SuppressWarnings("unchecked") + private static void validateFargateLinuxParameters(ContainerDefinition def) { + Object linuxParameters = def.getUnparsed() == null ? null : def.getUnparsed().get("linuxParameters"); + if (!(linuxParameters instanceof Map parameters)) { + return; + } + rejectOnFargate(parameters.get("maxSwap") != null, "maxSwap"); + rejectOnFargate(parameters.get("swappiness") != null, "swappiness"); + } + + /** A Fargate task cannot ask for a GPU; only {@code InferenceAccelerator} requirements remain. */ + private static void validateFargateResourceRequirements(ContainerDefinition def) { + Object requirements = def.getUnparsed() == null ? null : def.getUnparsed().get("resourceRequirements"); + if (!(requirements instanceof List entries)) { + return; + } + for (Object entry : entries) { + if (entry instanceof Map requirement && "GPU".equals(requirement.get("type"))) { + throw new AwsException("ClientException", + "Fargate compatible task definitions do not support gpu.", 400); + } + } + } + + private static boolean notEmpty(Map members, String key) { + Object value = members == null ? null : members.get(key); + if (value instanceof Collection collection) { + return !collection.isEmpty(); + } + return value != null; + } + /** * RegisterTaskDefinition-time validation of a FireLens config that comes from S3, in the * order ECS applies it. @@ -507,6 +824,8 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab if (cpu == 4096) return memory >= 8192 && memory <= 30720 && memory % 1024 == 0; if (cpu == 8192) return memory >= 16384 && memory <= 61440 && memory % 4096 == 0; if (cpu == 16384) return memory >= 32768 && memory <= 122880 && memory % 8192 == 0; + // 32 vCPU offers three fixed sizes rather than a range: 60 GB, 120 GB and 244 GB. + if (cpu == 32768) return memory == 61440 || memory == 122880 || memory == 249856; return false; } @@ -582,25 +901,62 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab public TaskDefinition deregisterTaskDefinition(String taskDefinitionRef, String region) { TaskDefinition td = resolveTaskDefinitionOrThrow(taskDefinitionRef, region); - td.setStatus("INACTIVE"); + td.setStatus(STATUS_INACTIVE); + td.setDeregisteredAt(Instant.now()); taskDefinitions.put(td.getFamily() + ":" + td.getRevision(), td); return td; } + /** + * Moves task definition revisions to {@code DELETE_IN_PROGRESS}. + * + *

A revision has to be deregistered first, and has to be named with its revision rather + * than by family. The revision is not dropped from the store: AWS keeps describing a + * {@code DELETE_IN_PROGRESS} revision, and tasks and services already on it keep running, + * which is also why it can no longer be used to start anything new. + */ public List deleteTaskDefinitions(List taskDefinitionRefs, String region) { + if (taskDefinitionRefs.size() > MAX_TASKS_PER_RUN) { + throw new AwsException("InvalidParameterException", + "You can specify up to " + MAX_TASKS_PER_RUN + " task definitions.", 400); + } List deleted = new ArrayList<>(); for (String ref : taskDefinitionRefs) { + if (!namesARevision(ref)) { + throw new AwsException("InvalidParameterException", + "You must specify a revision to delete a task definition: " + ref, 400); + } TaskDefinition td = resolveTaskDefinitionOrThrow(ref, region); - if (!"INACTIVE".equals(td.getStatus())) { + if (!STATUS_INACTIVE.equals(td.getStatus())) { throw new AwsException("InvalidParameterException", "Task definition " + ref + " must be INACTIVE before deletion.", 400); } - taskDefinitions.remove(td.getFamily() + ":" + td.getRevision()); + td.setStatus(STATUS_DELETE_IN_PROGRESS); + td.setDeleteRequestedAt(Instant.now()); + taskDefinitions.put(td.getFamily() + ":" + td.getRevision(), td); deleted.add(td); } return deleted; } + /** A reference names a revision when it carries one, as {@code family:1} or an ARN does. */ + private static boolean namesARevision(String ref) { + if (ref == null) { + return false; + } + String tail = ref.startsWith("arn:") ? ref.substring(ref.lastIndexOf('/') + 1) : ref; + int colon = tail.lastIndexOf(':'); + if (colon < 0) { + return false; + } + try { + Integer.parseInt(tail.substring(colon + 1)); + return true; + } catch (NumberFormatException e) { + return false; + } + } + // ── Tasks ───────────────────────────────────────────────────────────────── public List runTask(String clusterRef, String taskDefinitionRef, int count, @@ -614,14 +970,28 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab request.setLaunchType(launchType); request.setGroup(group); request.setStartedBy(startedBy); - request.setContainerOverrides(containerOverrides); request.setNetworkConfiguration(networkConfiguration); + if (containerOverrides != null && !containerOverrides.isEmpty()) { + TaskOverride overrides = new TaskOverride(); + overrides.setContainerOverrides(containerOverrides); + request.setOverrides(overrides); + } return runTask(request, region); } public List runTask(RunTaskRequest request, String region) { + // RunTask places at most 10 tasks per call, and propagating a service's tags is a service + // concept: both are rejected rather than quietly ignored. + if (request.getCount() < 1 || request.getCount() > MAX_TASKS_PER_RUN) { + throw new AwsException("InvalidParameterException", + "count must be between 1 and " + MAX_TASKS_PER_RUN + ".", 400); + } + if (PROPAGATE_TAGS_SERVICE.equals(request.getPropagateTags())) { + throw new AwsException("InvalidParameterException", + "The SERVICE option is not supported when running a task.", 400); + } EcsCluster cluster = resolveClusterOrDefault(request.getCluster(), region); - TaskDefinition taskDef = resolveTaskDefinitionOrThrow(request.getTaskDefinition(), region); + TaskDefinition taskDef = resolveLaunchableTaskDefinition(request.getTaskDefinition(), region); return launchTasks(cluster, taskDef, request, null, null, region); } @@ -639,14 +1009,23 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab public List startTask(RunTaskRequest request, String region) { List instanceRefs = request.getContainerInstances() != null ? request.getContainerInstances() : List.of(); + // StartTask places onto instances the caller names, so naming none is a malformed request, + // and ECS takes at most ten of them per call. + if (instanceRefs.isEmpty()) { + throw new AwsException("InvalidParameterException", + "containerInstances is required and cannot be empty.", 400); + } + if (instanceRefs.size() > MAX_TASKS_PER_RUN) { + throw new AwsException("InvalidParameterException", + "You can specify up to " + MAX_TASKS_PER_RUN + " container instances.", 400); + } EcsCluster cluster = resolveClusterOrDefault(request.getCluster(), region); - TaskDefinition taskDef = resolveTaskDefinitionOrThrow(request.getTaskDefinition(), region); + TaskDefinition taskDef = resolveLaunchableTaskDefinition(request.getTaskDefinition(), region); List result = new ArrayList<>(); // StartTask places one task onto each named container instance, which is EC2 by definition. request.setCount(1); request.setLaunchType(LaunchType.EC2); - request.setContainerOverrides(null); - request.setNetworkConfiguration(null); + request.setCapacityProviderStrategy(null); for (String instanceRef : instanceRefs) { ContainerInstance instance = resolveContainerInstanceOrThrow(cluster.getClusterArn(), instanceRef); result.addAll(launchTasks(cluster, taskDef, request, @@ -673,41 +1052,58 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab throw new AwsException("ClientException", "Task definition " + taskDef.getTaskDefinitionArn() + " has no container definitions.", 400); } - int count = request.getCount(); - LaunchType launchType = request.getLaunchType(); - String group = request.getGroup(); - String startedBy = request.getStartedBy(); - List containerOverrides = request.getContainerOverrides(); + int count = Math.max(1, request.getCount()); NetworkConfiguration networkConfiguration = request.getNetworkConfiguration(); + validateLaunchNetworking(taskDef, networkConfiguration); + List placements = resolvePlacements(cluster, request, count); + List containerOverrides = request.getContainerOverrides(); List launched = new ArrayList<>(); for (int i = 0; i < count; i++) { String taskId = UUID.randomUUID().toString().replace("-", ""); String taskArn = regionResolver.buildArn("ecs", region, "task/" + cluster.getClusterName() + "/" + taskId); + Placement placement = placements.get(i); EcsTask task = new EcsTask(); task.setTaskArn(taskArn); task.setClusterArn(cluster.getClusterArn()); task.setTaskDefinitionArn(taskDef.getTaskDefinitionArn()); - task.setLaunchType(launchType != null ? launchType : LaunchType.FARGATE); - task.setGroup(group); - task.setStartedBy(startedBy); + task.setLaunchType(placement.launchType()); + task.setCapacityProviderName(placement.capacityProviderName()); + task.setGroup(request.getGroup() != null ? request.getGroup() : "family:" + taskDef.getFamily()); + task.setStartedBy(request.getStartedBy()); task.setOwningServiceArn(owningServiceArn); task.setLastStatus(TaskStatus.PENDING.name()); task.setDesiredStatus(TaskStatus.RUNNING.name()); - task.setCpu(taskDef.getCpu()); - task.setMemory(taskDef.getMemory()); + task.setCpu(effectiveCpu(taskDef, request)); + task.setMemory(effectiveMemory(taskDef, request)); task.setCreatedAt(Instant.now()); task.setContainers(List.of()); task.setContainerInstanceArn(containerInstanceArn); task.setNetworkConfiguration(networkConfiguration); + task.setOverrides(request.getOverrides()); + task.setEnableExecuteCommand(request.isEnableExecuteCommand()); + task.setAttributes(List.of(new Attribute(CPU_ARCHITECTURE_ATTRIBUTE, hostCpuArchitecture(), + null, null))); + applyPlatform(task, taskDef, request); + Map taskTags = PROPAGATE_TAGS_TASK_DEFINITION.equals(request.getPropagateTags()) + ? taskDef.getTags() : request.getTags(); + if (taskTags != null && !taskTags.isEmpty()) { + task.setTags(new LinkedHashMap<>(taskTags)); + } + // Before the task is visible: an awsvpc task that cannot get its ENI (an unknown + // subnet, say) never existed, the way AWS rejects the request rather than placing it. + containerManager.attachTaskNetwork(task, taskDef, region); tasks.put(taskArn, task); if (dockerMode) { try { + task.setPullStartedAt(Instant.now()); EcsTaskHandle handle = containerManager.startTask(task, taskDef, containerOverrides, region); + task.setPullStoppedAt(Instant.now()); taskHandles.put(taskArn, handle); + markTaskRunning(task); cluster.setRunningTasksCount(cluster.getRunningTasksCount() + 1); LOG.infov("Started ECS task (docker): {0}", taskArn); registerTaskWithLoadBalancers(task, cluster, region); @@ -726,14 +1122,17 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab task.setStoppedReason(resourceInitError ? e.getMessage() : "Failed to start: " + e.getMessage()); + task.setStopCode(STOP_CODE_TASK_FAILED_TO_START); task.setStoppedAt(Instant.now()); + task.bumpVersion(); + containerManager.releaseTaskNetwork(task, region); if (eventPublisher != null) { eventPublisher.emitTaskLadder(task, TaskStatus.PENDING, TaskStatus.STOPPED, region); } } } else { - task.setLastStatus(TaskStatus.RUNNING.name()); - task.setStartedAt(Instant.now()); + task.setContainers(mockContainers(task, taskDef, region)); + markTaskRunning(task); cluster.setRunningTasksCount(cluster.getRunningTasksCount() + 1); LOG.infov("Started ECS task (mock): {0}", taskArn); if (eventPublisher != null) { @@ -747,6 +1146,55 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab return launched; } + /** + * The container models a mock-mode task reports. Nothing is running behind them, so they carry + * no runtime id, but a task with an empty {@code containers} list is unlike anything AWS + * returns and breaks every client that reads the list. + */ + private List mockContainers(EcsTask task, TaskDefinition taskDef, String region) { + String taskId = task.getTaskArn().substring(task.getTaskArn().lastIndexOf('/') + 1); + List containers = new ArrayList<>(); + for (ContainerDefinition def : taskDef.getContainerDefinitions()) { + Container container = new Container(); + container.setTaskArn(task.getTaskArn()); + container.setName(def.getName()); + container.setImage(def.getImage()); + container.setLastStatus(TaskStatus.RUNNING.name()); + container.setContainerArn(regionResolver.buildArn("ecs", region, + "container/" + taskId + "/" + def.getName())); + container.setNetworkBindings(List.of()); + if (def.getCpu() != null) { + container.setCpu(String.valueOf(def.getCpu())); + } + if (def.getMemory() != null) { + container.setMemory(String.valueOf(def.getMemory())); + } + if (task.getNetworkInterfaceId() != null) { + container.setNetworkInterfaces(List.of(new TaskNetworkInterface( + task.getAttachmentId(), task.getPrivateIpAddress(), null))); + } + if (task.isEnableExecuteCommand()) { + container.setManagedAgents(List.of(ManagedAgent.executeCommandAgent(Instant.now()))); + } + containers.add(container); + } + return containers; + } + + /** + * The state a task reaches once its containers are up: RUNNING, connected, and healthy as far + * as ECS can tell. {@code healthStatus} stays UNKNOWN unless a container declares a health + * check, which is what AWS reports for a task nothing is probing. + */ + private static void markTaskRunning(EcsTask task) { + task.setLastStatus(TaskStatus.RUNNING.name()); + task.setStartedAt(Instant.now()); + task.setConnectivity(CONNECTIVITY_CONNECTED); + task.setConnectivityAt(Instant.now()); + task.setHealthStatus(HEALTH_STATUS_UNKNOWN); + task.bumpVersion(); + } + /** * Launches one task on behalf of a service, stamping it with the service's ARN so later * reconciliation can recognize it as service-owned without trusting the caller-settable @@ -758,23 +1206,272 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab RunTaskRequest request = new RunTaskRequest(); request.setCount(1); request.setLaunchType(launchType); - request.setGroup(svc.getServiceName()); - request.setStartedBy("ecs-svc"); + // AWS labels a service's tasks "service:" and attributes them to the deployment. + request.setGroup("service:" + svc.getServiceName()); + request.setStartedBy(deploymentId(svc)); request.setNetworkConfiguration(svc.getNetworkConfiguration()); + // A service pinned to a capacity provider places its tasks through it, unless the + // reconciler is placing a DAEMON task on a named container instance. + if (containerInstanceArn == null) { + request.setCapacityProviderStrategy(svc.getCapacityProviderStrategy()); + } EcsTask task = launchTasks(cluster, taskDef, request, containerInstanceArn, svc.getServiceArn(), region).getFirst(); task.setDeploymentId(deploymentId(svc)); return task; } + /** Where a task runs: a launch type, or the capacity provider that chose one for it. */ + private record Placement(LaunchType launchType, String capacityProviderName) {} + + /** + * Decides where each of {@code count} tasks runs, in request order. + * + *

A capacity provider strategy wins over a launch type (the two are mutually exclusive on + * the wire), and an absent strategy falls back to the cluster's default one. With neither, + * the task keeps Floci's FARGATE default: a local cluster has no container instances, so EC2 + * would have nowhere to place it. + */ + private List resolvePlacements(EcsCluster cluster, RunTaskRequest request, int count) { + List strategy = request.getCapacityProviderStrategy(); + if (strategy != null && !strategy.isEmpty() && request.getLaunchType() != null) { + throw new AwsException("InvalidParameterException", + "You cannot specify both a launch type and a capacity provider strategy in the " + + "same request. Specify only one.", 400); + } + if ((strategy == null || strategy.isEmpty()) && request.getLaunchType() == null) { + strategy = clusterDefaultStrategy(cluster); + } + if (strategy == null || strategy.isEmpty()) { + LaunchType launchType = request.getLaunchType() != null ? request.getLaunchType() : LaunchType.FARGATE; + return Collections.nCopies(count, new Placement(launchType, null)); + } + return distribute(strategy, count); + } + + /** The cluster's {@code defaultCapacityProviderStrategy}, which is stored as raw JSON. */ + private List clusterDefaultStrategy(EcsCluster cluster) { + List> raw = cluster.getDefaultCapacityProviderStrategy(); + if (raw == null || raw.isEmpty()) { + return List.of(); + } + List result = new ArrayList<>(); + for (Map entry : raw) { + Object provider = entry.get("capacityProvider"); + if (provider == null) { + continue; + } + result.add(new CapacityProviderStrategyItem(provider.toString(), + intValue(entry.get("weight")), intValue(entry.get("base")))); + } + return result; + } + + private static int intValue(Object value) { + return value instanceof Number number ? number.intValue() : 0; + } + + /** + * Checks a strategy against the bounds the ECS model puts on it: at most twenty providers, + * each entry's {@code weight} between 0 and 1,000 and its {@code base} between 0 and 100,000, + * and only one entry carrying a base. + * + *

A provider weighing 0 places nothing beyond its base, so a strategy of several providers + * that all weigh 0 has nowhere to put the tasks no base covers and the model has RunTask and + * CreateService fail on it. A lone entry weighing 0 is left alone: the model scopes that rule + * to a strategy naming more than one provider. + */ + private void validateCapacityProviderStrategy(List strategy) { + if (strategy.size() > MAX_CAPACITY_PROVIDERS_PER_STRATEGY) { + throw new AwsException("InvalidParameterException", + "A capacity provider strategy can contain a maximum of " + + MAX_CAPACITY_PROVIDERS_PER_STRATEGY + " capacity providers.", 400); + } + for (CapacityProviderStrategyItem item : strategy) { + if (item.weight() < 0 || item.weight() > MAX_CAPACITY_PROVIDER_WEIGHT) { + throw new AwsException("InvalidParameterException", + "The weight of a capacity provider strategy entry must be between 0 and " + + MAX_CAPACITY_PROVIDER_WEIGHT + ".", 400); + } + if (item.base() < 0 || item.base() > MAX_CAPACITY_PROVIDER_BASE) { + throw new AwsException("InvalidParameterException", + "The base of a capacity provider strategy entry must be between 0 and " + + MAX_CAPACITY_PROVIDER_BASE + ".", 400); + } + } + if (strategy.stream().filter(item -> item.base() > 0).count() > 1) { + throw new AwsException("InvalidParameterException", + "Only one capacity provider in a capacity provider strategy can have a base defined.", 400); + } + if (strategy.size() > 1 && strategy.stream().allMatch(item -> item.weight() == 0)) { + throw new AwsException("InvalidParameterException", + "At least one capacity provider in a capacity provider strategy must have a " + + "weight greater than zero.", 400); + } + strategy.forEach(item -> requireCapacityProvider(item.capacityProvider())); + } + + /** + * Spreads {@code count} tasks over a strategy the way ECS does: the single entry that declares + * a {@code base} is filled first, then whatever is left is split by weight. Leftovers from the + * integer split go to the heaviest entries, so a 1:1 strategy with an odd count still places + * every task. + */ + private List distribute(List strategy, int count) { + validateCapacityProviderStrategy(strategy); + + List placements = new ArrayList<>(); + for (CapacityProviderStrategyItem item : strategy) { + for (int i = 0; i < item.base() && placements.size() < count; i++) { + placements.add(placementFor(item.capacityProvider())); + } + } + int remaining = count - placements.size(); + if (remaining <= 0) { + return placements; + } + int totalWeight = strategy.stream().mapToInt(CapacityProviderStrategyItem::weight).sum(); + if (totalWeight <= 0) { + // Validation already rejected a multi-entry strategy whose weights are all 0, so the + // only way to get here is a lone entry that carries no weight: it is the one provider + // the request named, and the tasks its base did not cover go on it. + for (int i = 0; i < remaining; i++) { + placements.add(placementFor(strategy.getFirst().capacityProvider())); + } + return placements; + } + int[] shares = new int[strategy.size()]; + int assigned = 0; + for (int i = 0; i < strategy.size(); i++) { + shares[i] = remaining * strategy.get(i).weight() / totalWeight; + assigned += shares[i]; + } + List byWeightDescending = new ArrayList<>(); + for (int i = 0; i < strategy.size(); i++) { + byWeightDescending.add(i); + } + byWeightDescending.sort(Comparator.comparingInt((Integer i) -> strategy.get(i).weight()).reversed()); + for (int i = 0; assigned < remaining; i++) { + shares[byWeightDescending.get(i % byWeightDescending.size())]++; + assigned++; + } + for (int i = 0; i < strategy.size(); i++) { + for (int placed = 0; placed < shares[i]; placed++) { + placements.add(placementFor(strategy.get(i).capacityProvider())); + } + } + return placements; + } + + /** FARGATE and FARGATE_SPOT place Fargate tasks; any other provider is backed by an ASG. */ + private static Placement placementFor(String capacityProvider) { + LaunchType launchType = FARGATE_CAPACITY_PROVIDERS.contains(capacityProvider) + ? LaunchType.FARGATE : LaunchType.EC2; + return new Placement(launchType, capacityProvider); + } + + /** Accepts the two built-in Fargate providers as well as anything CreateCapacityProvider made. */ + private void requireCapacityProvider(String name) { + if (name == null || name.isBlank()) { + throw new AwsException("InvalidParameterException", + "A capacity provider strategy entry must name a capacity provider.", 400); + } + if (FARGATE_CAPACITY_PROVIDERS.contains(name) || capacityProviders.containsKey(name)) { + return; + } + boolean knownByArn = capacityProviders.values().stream() + .anyMatch(cp -> name.equals(cp.getCapacityProviderArn())); + if (!knownByArn) { + throw new AwsException("ClientException", + "The specified capacity provider '" + name + "' was not found. " + + "Specify a valid capacity provider and try again.", 400); + } + } + + /** An awsvpc task cannot be placed without the subnets its ENI goes into. */ + private static void validateLaunchNetworking(TaskDefinition taskDef, NetworkConfiguration networkConfiguration) { + if (taskDef.getNetworkMode() != NetworkMode.awsvpc) { + return; + } + boolean hasSubnets = networkConfiguration != null + && networkConfiguration.getAwsvpcConfiguration() != null + && networkConfiguration.getAwsvpcConfiguration().getSubnets() != null + && !networkConfiguration.getAwsvpcConfiguration().getSubnets().isEmpty(); + if (!hasSubnets) { + throw new AwsException("InvalidParameterException", + "Network Configuration must be provided when networkMode 'awsvpc' is specified.", 400); + } + } + + private static String effectiveCpu(TaskDefinition taskDef, RunTaskRequest request) { + TaskOverride overrides = request.getOverrides(); + if (overrides != null && overrides.getCpu() != null) { + return overrides.getCpu(); + } + return taskDef.getCpu(); + } + + private static String effectiveMemory(TaskDefinition taskDef, RunTaskRequest request) { + TaskOverride overrides = request.getOverrides(); + if (overrides != null && overrides.getMemory() != null) { + return overrides.getMemory(); + } + return taskDef.getMemory(); + } + + /** + * The architecture a task reports running on. A task definition's {@code runtimePlatform} does + * not move it anywhere: every local task runs on the host, so the host's architecture is what + * the attribute says. + */ + private static String hostCpuArchitecture() { + String architecture = System.getProperty("os.arch", ""); + return switch (architecture) { + case "aarch64", "arm64" -> "arm64"; + default -> "x86_64"; + }; + } + + /** + * Stamps the Fargate platform members. {@code LATEST} resolves to a concrete version the way + * AWS resolves it, since a client that asked for LATEST still reads back the version it got. + * An EC2 task has neither member. + */ + private static void applyPlatform(EcsTask task, TaskDefinition taskDef, RunTaskRequest request) { + if (task.getLaunchType() != LaunchType.FARGATE) { + return; + } + String requested = request.getPlatformVersion(); + task.setPlatformVersion(requested == null || requested.isBlank() || PLATFORM_VERSION_LATEST.equals(requested) + ? DEFAULT_PLATFORM_VERSION : requested); + task.setPlatformFamily(platformFamilyOf(taskDef)); + TaskOverride overrides = request.getOverrides(); + EphemeralStorage ephemeralStorage = overrides != null && overrides.getEphemeralStorage() != null + ? overrides.getEphemeralStorage() : taskDef.getEphemeralStorage(); + task.setEphemeralStorage(ephemeralStorage != null + ? ephemeralStorage : new EphemeralStorage(EphemeralStorage.DEFAULT_SIZE_IN_GIB)); + } + public EcsTask stopTask(String clusterRef, String taskRef, String reason, String region) { + return stopTask(clusterRef, taskRef, reason, STOP_CODE_USER_INITIATED, region); + } + + /** + * @param stopCode why the task is going away, as the {@code stopCode} AWS reports: a caller's + * StopTask is {@code UserInitiated}, anything the reconciler decides is + * {@code ServiceSchedulerInitiated}. + */ + private EcsTask stopTask(String clusterRef, String taskRef, String reason, String stopCode, String region) { EcsTask task = resolveTaskOrThrow(taskRef, region); if (TaskStatus.STOPPED.name().equals(task.getLastStatus())) { return task; } task.setDesiredStatus(TaskStatus.STOPPED.name()); task.setLastStatus(TaskStatus.STOPPING.name()); + task.setStoppingAt(Instant.now()); task.setStoppedReason(reason != null ? reason : "Stopped by user"); + task.setStopCode(stopCode); + task.bumpVersion(); deregisterTaskFromLoadBalancers(task, region); @@ -790,6 +1487,9 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab task.setLastStatus(TaskStatus.STOPPED.name()); task.setStoppedAt(Instant.now()); + task.setExecutionStoppedAt(Instant.now()); + task.bumpVersion(); + containerManager.releaseTaskNetwork(task, region); if (task.getContainers() != null) { final Map codes = exitCodes; task.getContainers().forEach(c -> { @@ -856,14 +1556,34 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab } public List describeTasks(String clusterRef, List taskRefs, String region) { + return describeTasksDetailed(clusterRef, taskRefs, region).tasks(); + } + + public record DescribeTasksResult(List tasks, List failures) {} + + /** + * Resolves each reference, reporting the ones that do not exist as {@code MISSING} failures. + * ECS answers a describe for an unknown task with a failure entry rather than an error, and the + * {@code TasksRunning} and {@code TasksStopped} waiters treat a MISSING failure as terminal: a + * describe that returns neither the task nor a failure leaves them polling until they time out. + */ + public DescribeTasksResult describeTasksDetailed(String clusterRef, List taskRefs, + String region) { + EcsCluster cluster = resolveClusterOrDefault(clusterRef, region); List result = new ArrayList<>(); + List failures = new ArrayList<>(); for (String ref : taskRefs) { EcsTask task = resolveTask(ref, region); if (task != null) { result.add(task); + } else { + failures.add(Failure.missing(ref != null && ref.startsWith("arn:") + ? ref + : regionResolver.buildArn("ecs", region, + "task/" + cluster.getClusterName() + "/" + ref))); } } - return result; + return new DescribeTasksResult(result, failures); } public List listTasks(String clusterRef, String family, String desiredStatus, @@ -1000,13 +1720,12 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab } public EcsServiceModel createService(CreateServiceRequest request, String region) { - String serviceName = request.getServiceName(); - int desiredCount = request.getDesiredCount(); EcsCluster cluster = resolveClusterOrDefault(request.getCluster(), region); // AWS resolves family / family:revision at create time and stores the ARN; the // reconciler compares it with each task's taskDefinitionArn, so pin it here. - String taskDefinition = - resolveTaskDefinitionOrThrow(request.getTaskDefinition(), region).getTaskDefinitionArn(); + TaskDefinition taskDef = resolveLaunchableTaskDefinition(request.getTaskDefinition(), region); + String taskDefinition = taskDef.getTaskDefinitionArn(); + String serviceName = request.getServiceName(); String key = serviceKey(region, cluster.getClusterName(), serviceName); if (services.containsKey(key)) { @@ -1017,6 +1736,13 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab "Creation of service was not idempotent.", 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 in the " + + "same request. Specify only one.", 400); + } + validateLaunchNetworking(taskDef, request.getNetworkConfiguration()); EcsServiceModel svc = new EcsServiceModel(); svc.setServiceArn(regionResolver.buildArn("ecs", region, @@ -1024,7 +1750,9 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab svc.setServiceName(serviceName); svc.setClusterArn(cluster.getClusterArn()); svc.setTaskDefinition(taskDefinition); - svc.setLaunchType(request.getLaunchType() != null ? request.getLaunchType() : LaunchType.FARGATE); + svc.setCapacityProviderStrategy(request.getCapacityProviderStrategy()); + svc.setLaunchType(serviceLaunchType(cluster, request)); + int desiredCount = request.getDesiredCount(); if (desiredCount < 0) { throw new AwsException("InvalidParameterException", "desiredCount cannot be a negative number.", 400); } @@ -1112,6 +1840,7 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab EcsCluster cluster = resolveClusterOrDefault(request.getCluster(), region); String serviceName = extractServiceName(request.getService()); + boolean forceNewDeployment = request.isForceNewDeployment(); String key = serviceKey(region, cluster.getClusterName(), serviceName); EcsServiceModel svc = services.get(key); @@ -1122,12 +1851,11 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab throw new AwsException("ServiceNotActiveException", "Service " + serviceName + " is not active.", 400); } - Integer desiredCount = request.getDesiredCount(); - if (desiredCount != null) { - if (desiredCount < 0) { + if (request.getDesiredCount() != null) { + if (request.getDesiredCount() < 0) { throw new AwsException("InvalidParameterException", "desiredCount cannot be a negative number.", 400); } - svc.setDesiredCount(desiredCount); + svc.setDesiredCount(request.getDesiredCount()); } if (request.getNetworkConfiguration() != null) { svc.setNetworkConfiguration(request.getNetworkConfiguration()); @@ -1135,6 +1863,12 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab if (request.getAvailabilityZoneRebalancing() != null) { svc.setAvailabilityZoneRebalancing(request.getAvailabilityZoneRebalancing()); } + if (request.getCapacityProviderStrategy() != null) { + svc.setCapacityProviderStrategy(request.getCapacityProviderStrategy()); + svc.setLaunchType(request.getCapacityProviderStrategy().isEmpty() + ? svc.getLaunchType() + : placementFor(request.getCapacityProviderStrategy().getFirst().capacityProvider()).launchType()); + } // UpdateServiceRequest.serviceConnectConfiguration is documented as "This parameter // triggers a new service deployment", so a real change rolls the deployment the way a // task-definition change does. An omitted parameter is not a change and rolls nothing. @@ -1146,12 +1880,11 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab } boolean taskDefChanged = false; if (request.getTaskDefinition() != null) { - String resolvedArn = - resolveTaskDefinitionOrThrow(request.getTaskDefinition(), region).getTaskDefinitionArn(); - taskDefChanged = !resolvedArn.equals(svc.getTaskDefinition()); - svc.setTaskDefinition(resolvedArn); + TaskDefinition resolved = resolveLaunchableTaskDefinition(request.getTaskDefinition(), region); + taskDefChanged = !resolved.getTaskDefinitionArn().equals(svc.getTaskDefinition()); + svc.setTaskDefinition(resolved.getTaskDefinitionArn()); } - if (taskDefChanged || request.isForceNewDeployment() || serviceConnectChanged) { + if (taskDefChanged || forceNewDeployment || serviceConnectChanged) { svc.setDeploymentId(newDeploymentId()); svc.setLastDeploymentAt(Instant.now()); recordServiceDeployment(svc, svc.getTaskDefinition(), region); @@ -1164,6 +1897,44 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab return svc; } + /** + * The launch type a service's tasks get. An explicit one wins; otherwise the first entry of + * the service's own capacity provider strategy, then the cluster's default strategy, decides + * it, and with neither the service keeps Floci's FARGATE default. + */ + private LaunchType serviceLaunchType(EcsCluster cluster, CreateServiceRequest request) { + 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.FARGATE; + } + validateCapacityProviderStrategy(strategy); + return placementFor(strategy.getFirst().capacityProvider()).launchType(); + } + + /** + * The platform family a Fargate task or service reports. + * + *

A Linux task reports {@code Linux}, which is what DescribeTasks answers with. A Windows + * task reports the Windows Server family from the task definition's + * {@code runtimePlatform.operatingSystemFamily}, because that is the value a Windows task has + * to match against its container image. + */ + private static String platformFamilyOf(TaskDefinition taskDef) { + String operatingSystemFamily = taskDef != null && taskDef.getRuntimePlatform() != null + ? taskDef.getRuntimePlatform().operatingSystemFamily() : null; + if (operatingSystemFamily == null || operatingSystemFamily.isBlank() + || operatingSystemFamily.startsWith("LINUX")) { + return DEFAULT_PLATFORM_FAMILY; + } + return operatingSystemFamily; + } + public EcsServiceModel deleteService(String clusterRef, String serviceName, boolean force, String region) { EcsCluster cluster = resolveClusterOrDefault(clusterRef, region); @@ -1193,7 +1964,8 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab .filter(t -> !TaskStatus.STOPPED.name().equals(t.getLastStatus())) .forEach(t -> { try { - stopTask(cluster.getClusterName(), t.getTaskArn(), "Service deleted", region); + stopTask(cluster.getClusterName(), t.getTaskArn(), "Service deleted", + STOP_CODE_SERVICE_SCHEDULER_INITIATED, region); } catch (Exception e) { LOG.warnv("Failed to stop task {0} on service delete: {1}", t.getTaskArn(), e.getMessage()); @@ -1246,8 +2018,9 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab String prefix = serviceKeyPrefix(region, cluster.getClusterName()); return services.entrySet().stream() .filter(e -> e.getKey().startsWith(prefix)) - .filter(e -> !"INACTIVE".equals(e.getValue().getStatus())) - .map(e -> e.getValue().getServiceArn()) + .map(Map.Entry::getValue) + .filter(svc -> !"INACTIVE".equals(svc.getStatus())) + .map(EcsServiceModel::getServiceArn) .toList(); } @@ -1902,6 +2675,8 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab return; } + updateHealth(task, handle); + // Inspect every container; abort if any are still running. Map exitCodes = new LinkedHashMap<>(); for (Map.Entry entry : handle.getContainerIds().entrySet()) { @@ -1934,8 +2709,12 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab task.setLastStatus(TaskStatus.STOPPED.name()); task.setDesiredStatus(TaskStatus.STOPPED.name()); + task.setStoppingAt(Instant.now()); task.setStoppedAt(Instant.now()); + task.setExecutionStoppedAt(Instant.now()); task.setStoppedReason("Essential container in task exited"); + task.setStopCode(STOP_CODE_ESSENTIAL_CONTAINER_EXITED); + task.bumpVersion(); EcsCluster cluster = resolveClusterByArn(task.getClusterArn()); if (cluster != null && cluster.getRunningTasksCount() > 0) { @@ -1943,22 +2722,58 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab } LOG.infov("ECS task {0} reconciled to STOPPED (all containers exited)", taskArn); + String region = taskRegion(task); + containerManager.releaseTaskNetwork(task, region); if (eventPublisher != null) { - String region = null; - if (task.getTaskArn() != null) { - try { - region = AwsArnUtils.parse(task.getTaskArn()).region(); - } catch (Exception e) { - LOG.warnv(e, "Could not parse region from task ARN {0}, falling back to default region", task.getTaskArn()); - } - } - if (region == null || region.isBlank()) { - region = regionResolver != null ? regionResolver.getDefaultRegion() : "us-east-1"; - } eventPublisher.emitTaskLadder(task, TaskStatus.RUNNING, TaskStatus.STOPPED, region); } } + /** + * Refreshes a running task's health from its containers' health checks. The task is HEALTHY + * only when every container that has a health check reports healthy, UNHEALTHY as soon as one + * does not, and UNKNOWN when nothing is being probed, which is how ECS aggregates it. + */ + private void updateHealth(EcsTask task, EcsTaskHandle handle) { + if (task.getContainers() == null || task.getContainers().isEmpty()) { + return; + } + boolean anyUnhealthy = false; + boolean anyHealthy = false; + for (Container container : task.getContainers()) { + String dockerId = handle.getContainerIds().get(container.getName()); + if (dockerId == null) { + continue; + } + String health = containerManager.ecsHealthStatus(dockerId); + container.setHealthStatus(health); + anyUnhealthy |= HEALTH_STATUS_UNHEALTHY.equals(health); + anyHealthy |= HEALTH_STATUS_HEALTHY.equals(health); + } + String aggregate = anyUnhealthy ? HEALTH_STATUS_UNHEALTHY + : anyHealthy ? HEALTH_STATUS_HEALTHY : HEALTH_STATUS_UNKNOWN; + if (!aggregate.equals(task.getHealthStatus())) { + task.setHealthStatus(aggregate); + task.bumpVersion(); + } + } + + /** The region a task lives in, read off its ARN, falling back to the default region. */ + private String taskRegion(EcsTask task) { + if (task.getTaskArn() != null) { + try { + String region = AwsArnUtils.parse(task.getTaskArn()).region(); + if (region != null && !region.isBlank()) { + return region; + } + } catch (Exception e) { + LOG.warnv(e, "Could not parse region from task ARN {0}, falling back to default region", + task.getTaskArn()); + } + } + return regionResolver != null ? regionResolver.getDefaultRegion() : "us-east-1"; + } + private void reconcileStoppedTask(String taskArn) { EcsTaskHandle claimed = taskHandles.remove(taskArn); if (claimed == null) { @@ -2025,7 +2840,8 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab try { stopTask(clusterName, t.getTaskArn(), instanceArn == null || !activeArns.contains(instanceArn) ? "Daemon task's container instance is no longer active" - : "Daemon service already has a task on this container instance", region); + : "Daemon service already has a task on this container instance", + STOP_CODE_SERVICE_SCHEDULER_INITIATED, region); } catch (Exception e) { LOG.warnv("Service reconciler failed to stop daemon task {0}: {1}", t.getTaskArn(), e.getMessage()); } @@ -2194,7 +3010,8 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab try { stopTask(clusterName, t.getTaskArn(), stale ? "Service deployment replaced task definition " + t.getTaskDefinitionArn() - : "Service scale-in", region); + : "Service scale-in", + STOP_CODE_SERVICE_SCHEDULER_INITIATED, region); } catch (Exception e) { LOG.warnv("Service reconciler failed to stop task {0}: {1}", t.getTaskArn(), e.getMessage()); @@ -2266,6 +3083,21 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab throw new AwsException("ClientException", "Unable to describe task definition: " + ref, 400); } + /** + * Resolves a task definition for something that is about to run on it. A revision on its way + * out cannot start new work: AWS refuses to run a task or create a service on a + * {@code DELETE_IN_PROGRESS} revision, while the tasks already on it keep running. + */ + private TaskDefinition resolveLaunchableTaskDefinition(String ref, String region) { + TaskDefinition td = resolveTaskDefinitionOrThrow(ref, region); + if (STATUS_DELETE_IN_PROGRESS.equals(td.getStatus())) { + throw new AwsException("ClientException", + "The task definition " + td.getTaskDefinitionArn() + " is being deleted and " + + "cannot be used to start new tasks.", 400); + } + return td; + } + private EcsTask resolveTask(String ref, String region) { EcsTask task = tasks.get(ref); if (task != null) { return task; } diff --git a/src/main/java/io/github/hectorvent/floci/services/ecs/container/EcsContainerManager.java b/src/main/java/io/github/hectorvent/floci/services/ecs/container/EcsContainerManager.java index c58554a71c..c880776c41 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ecs/container/EcsContainerManager.java +++ b/src/main/java/io/github/hectorvent/floci/services/ecs/container/EcsContainerManager.java @@ -22,17 +22,20 @@ import io.github.hectorvent.floci.services.ec2.model.SecurityGroup; import io.github.hectorvent.floci.services.ecs.model.AwsVpcConfiguration; 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.ContainerOverride; import io.github.hectorvent.floci.services.ecs.model.EcsTask; import io.github.hectorvent.floci.services.ecs.model.EfsVolumeConfiguration; import io.github.hectorvent.floci.services.ecs.model.FirelensConfiguration; import io.github.hectorvent.floci.services.ecs.model.LogConfiguration; +import io.github.hectorvent.floci.services.ecs.model.ManagedAgent; import io.github.hectorvent.floci.services.ecs.model.MountPoint; import io.github.hectorvent.floci.services.ecs.model.NetworkBinding; import io.github.hectorvent.floci.services.ecs.model.NetworkMode; import io.github.hectorvent.floci.services.ecs.model.PortMapping; import io.github.hectorvent.floci.services.ecs.model.Secret; import io.github.hectorvent.floci.services.ecs.model.TaskDefinition; +import io.github.hectorvent.floci.services.ecs.model.TaskNetworkInterface; import io.github.hectorvent.floci.services.ecs.model.Volume; import io.github.hectorvent.floci.services.ecs.model.VolumeFrom; import io.github.hectorvent.floci.services.s3.S3Service; @@ -67,6 +70,7 @@ import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; +import java.util.concurrent.TimeUnit; import java.util.stream.Stream; /** @@ -78,6 +82,17 @@ public class EcsContainerManager { private static final Logger LOG = Logger.getLogger(EcsContainerManager.class); + private static final String ATTACHMENT_DELETED = "DELETED"; + + /** EC2 error codes the task ENI path can raise, none of which RunTask declares. */ + private static final Set EC2_NETWORK_LOOKUP_FAILURES = + Set.of("InvalidSubnetID.NotFound", "InvalidGroup.NotFound"); + /** How long a container waits for a dependency that has to COMPLETE, SUCCEED or get HEALTHY. */ + private static final int DEPENDENCY_WAIT_SECONDS = 60; + private static final long DEPENDENCY_POLL_MILLIS = 200; + /** How long a killed container gets to register as exited before its code is read. */ + private static final int KILL_SETTLE_SECONDS = 5; + private final ContainerBuilder containerBuilder; private final ContainerLifecycleManager lifecycleManager; private final ContainerLogStreamer logStreamer; @@ -210,6 +225,7 @@ public class EcsContainerManager { try { for (ContainerDefinition def : launchOrder) { + awaitDependencies(def, containerIds); String containerName = ContainerStorageHelper.dockerName(config, "floci-ecs-" + taskId + "-" + def.getName()); // RunTask containerOverrides matched by container name: command replaces @@ -252,9 +268,33 @@ public class EcsContainerManager { specBuilder.withNamedVolume(firelensVolumeName, "/var/run"); } - // Add memory limit if specified + // Resource limits. A container-level memory is its own hard limit; without one the + // container is capped at the task's memory, which is what a Fargate task gets + // (the whole task shares one allocation). The task's cpu becomes a quota and a + // container-level cpu becomes its share of that quota, as on ECS. if (def.getMemory() != null) { specBuilder.withMemoryMb(def.getMemory()); + } else { + Integer taskMemoryMb = parseTaskMemoryMb(task.getMemory()); + if (taskMemoryMb != null) { + specBuilder.withMemoryMb(taskMemoryMb); + } + } + Integer taskCpuUnits = parseTaskCpuUnits(task.getCpu()); + if (taskCpuUnits != null) { + specBuilder.withCpuUnits(taskCpuUnits); + } + if (def.getCpu() != null && def.getCpu() > 0) { + specBuilder.withCpuShares(def.getCpu()); + } + if (def.getUser() != null) { + specBuilder.withUser(def.getUser()); + } + if (def.getWorkingDirectory() != null) { + specBuilder.withWorkingDir(def.getWorkingDirectory()); + } + if (Boolean.TRUE.equals(def.getReadonlyRootFilesystem())) { + specBuilder.withReadonlyRootfs(); } // Add port mappings. In bridge/host mode an explicit hostPort is @@ -394,8 +434,7 @@ public class EcsContainerManager { lifecycleManager.removeVolume(firelensVolumeName); } if (protectedNetwork != null) { - firewallManager.unregister(protectedNetwork.eni().getNetworkInterfaceId()); - ec2Service.deleteNetworkInterface(region, protectedNetwork.eni().getNetworkInterfaceId()); + releaseTaskNetwork(task, region); } throw e; } @@ -411,14 +450,160 @@ public class EcsContainerManager { containersInDefinitionOrder.add(container); } } + // An awsvpc task's containers share the task ENI, and each reports it. + if (task.getNetworkInterfaceId() != null) { + List taskInterfaces = List.of(new TaskNetworkInterface( + task.getAttachmentId(), task.getPrivateIpAddress(), null)); + containersInDefinitionOrder.forEach(container -> container.setNetworkInterfaces(taskInterfaces)); + } + // ECS Exec is gated on the agent reporting RUNNING, which a client checks before it tries + // to open a session. + if (task.isEnableExecuteCommand()) { + List agents = List.of(ManagedAgent.executeCommandAgent(Instant.now())); + containersInDefinitionOrder.forEach(container -> container.setManagedAgents(agents)); + } task.setContainers(containersInDefinitionOrder); task.setLastStatus(TaskStatus.RUNNING.name()); task.setDesiredStatus(TaskStatus.RUNNING.name()); task.setStartedAt(Instant.now()); + Map stopTimeouts = new LinkedHashMap<>(); + for (ContainerDefinition def : taskDef.getContainerDefinitions()) { + if (def.getStopTimeout() != null) { + stopTimeouts.put(def.getName(), def.getStopTimeout()); + } + } return new EcsTaskHandle(task.getTaskArn(), containerIds, logStreamsByContainerId, firelensVolumeName, - protectedNetwork == null ? null : protectedNetwork.eni().getNetworkInterfaceId(), region); + protectedNetwork == null ? null : protectedNetwork.eni().getNetworkInterfaceId(), region, + stopTimeouts); + } + + /** A task-level {@code memory} is MiB as a plain number, or a {@code "1GB"}-style string. */ + private static Integer parseTaskMemoryMb(String memory) { + if (memory == null || memory.isBlank()) { + return null; + } + String trimmed = memory.trim().toUpperCase(); + try { + if (trimmed.endsWith("GB")) { + return (int) Math.round(Double.parseDouble(trimmed.substring(0, trimmed.length() - 2).trim()) * 1024); + } + return Integer.parseInt(trimmed.replaceAll("(?i)mib|mb", "").trim()); + } catch (NumberFormatException e) { + LOG.debugv("Ignoring unparseable task memory {0}", memory); + return null; + } + } + + /** A task-level {@code cpu} is CPU units as a plain number, or a {@code "0.5vCPU"}-style string. */ + private static Integer parseTaskCpuUnits(String cpu) { + if (cpu == null || cpu.isBlank()) { + return null; + } + String trimmed = cpu.trim().toUpperCase(); + try { + if (trimmed.endsWith("VCPU")) { + return (int) Math.round( + Double.parseDouble(trimmed.substring(0, trimmed.length() - 4).trim()) * 1024); + } + return Integer.parseInt(trimmed); + } catch (NumberFormatException e) { + LOG.debugv("Ignoring unparseable task cpu {0}", cpu); + return null; + } + } + + /** + * Holds a container's start until the containers it declared a {@code dependsOn} on have + * reached the state it asked for. {@code START} is satisfied by the launch order alone; + * {@code COMPLETE} and {@code SUCCESS} wait for the dependency to exit (and {@code SUCCESS} + * additionally requires it to have exited cleanly); {@code HEALTHY} waits for its health check + * to pass. + * + *

The wait is bounded by the dependent container's {@code startTimeout}, defaulting to + * {@value #DEPENDENCY_WAIT_SECONDS} seconds rather than AWS's longer agent default, because + * RunTask here is synchronous and a caller is holding the request open. A dependency that does + * not get there in time fails the task. + */ + private void awaitDependencies(ContainerDefinition definition, Map startedContainerIds) { + if (definition.getDependsOn() == null || definition.getDependsOn().isEmpty()) { + return; + } + long timeoutSeconds = definition.getStartTimeout() != null + ? definition.getStartTimeout() : DEPENDENCY_WAIT_SECONDS; + for (ContainerDependency dependency : definition.getDependsOn()) { + String condition = dependency.condition(); + if (ContainerDependency.START.equals(condition)) { + continue; + } + String dockerId = startedContainerIds.get(dependency.containerName()); + if (dockerId == null) { + continue; + } + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(timeoutSeconds); + while (!dependencySatisfied(dockerId, condition)) { + if (System.nanoTime() > deadline) { + throw new AwsException("ClientException", + "Container '" + definition.getName() + "' did not start because container '" + + dependency.containerName() + "' did not reach " + condition + + " within " + timeoutSeconds + " seconds.", 400); + } + try { + TimeUnit.MILLISECONDS.sleep(DEPENDENCY_POLL_MILLIS); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Interrupted while waiting for ECS container dependency " + + dependency.containerName(), e); + } + } + } + } + + private boolean dependencySatisfied(String dockerId, String condition) { + if (ContainerDependency.HEALTHY.equals(condition)) { + return "healthy".equals(inspectHealthStatus(dockerId)); + } + Integer exitCode = getExitCodeIfStopped(dockerId); + if (exitCode == null) { + return false; + } + if (ContainerDependency.SUCCESS.equals(condition) && exitCode != 0) { + throw new AwsException("ClientException", + "A dependency container exited with code " + exitCode + + ", so the containers depending on its SUCCESS were not started.", 400); + } + return true; + } + + /** + * A container's health in ECS's vocabulary: {@code HEALTHY} or {@code UNHEALTHY} once its + * health check has reported, {@code UNKNOWN} while it is still starting or when the container + * declares no health check at all. + */ + public String ecsHealthStatus(String dockerId) { + String status = inspectHealthStatus(dockerId); + if (status == null) { + return "UNKNOWN"; + } + return switch (status) { + case "healthy" -> "HEALTHY"; + case "unhealthy" -> "UNHEALTHY"; + default -> "UNKNOWN"; + }; + } + + /** The Docker health status of a container, or null when it declares no health check. */ + private String inspectHealthStatus(String dockerId) { + try { + InspectContainerResponse inspect = lifecycleManager.getDockerClient() + .inspectContainerCmd(dockerId).exec(); + return inspect.getState() != null && inspect.getState().getHealth() != null + ? inspect.getState().getHealth().getStatus() : null; + } catch (Exception e) { + LOG.debugv("Could not read the health of container {0}: {1}", dockerId, e.getMessage()); + return null; + } } private List orderForDependencies(List definitions, @@ -463,11 +648,121 @@ public class EcsContainerManager { addAfterDependencies(source, definitionsByName, firelensRouter, visiting, visited, ordered); } } + if (definition.getDependsOn() != null) { + for (ContainerDependency dependency : definition.getDependsOn()) { + ContainerDefinition source = definitionsByName.get(dependency.containerName()); + if (source == null) { + throw new IllegalArgumentException("ECS dependsOn references unknown container " + + dependency.containerName()); + } + addAfterDependencies(source, definitionsByName, firelensRouter, visiting, visited, ordered); + } + } visiting.remove(definition); visited.add(definition); ordered.add(definition); } + /** + * Gives an {@code awsvpc} task the elastic network interface AWS gives it: its own ENI in the + * requested subnet, with a private address of its own and the task's security groups. + * + *

Called for every {@code awsvpc} task, in Docker and in mock mode alike, because the ENI is + * control-plane state that DescribeTasks reports (a client waits on + * {@code attachments[].details[?name=='privateIPv4Address']} to find the task) rather than a + * property of the containers. Security-group enforcement, which additionally puts the task's + * containers in a protected network namespace, stays opt-in on top of it. + * + *

A subnet or security group that does not exist fails the task, reported as the + * {@code InvalidParameterException} RunTask declares rather than the EC2 code + * {@link Ec2Service#createNetworkInterface} raises. + */ + public void attachTaskNetwork(EcsTask task, TaskDefinition definition, String region) { + if (definition.getNetworkMode() != NetworkMode.awsvpc || ec2Service == null) { + return; + } + AwsVpcConfiguration awsvpc = task.getNetworkConfiguration() == null ? null + : task.getNetworkConfiguration().getAwsvpcConfiguration(); + if (awsvpc == null || awsvpc.getSubnets() == null || awsvpc.getSubnets().isEmpty()) { + throw new AwsException("InvalidParameterException", + "Network Configuration must be provided when networkMode 'awsvpc' is specified.", 400); + } + String subnetId = awsvpc.getSubnets().getFirst(); + NetworkInterface eni; + try { + eni = ec2Service.createNetworkInterface(region, subnetId, + "ECS task " + task.getTaskArn(), null, List.of(), awsvpc.getSecurityGroups(), List.of()); + } catch (AwsException e) { + throw asEcsNetworkRejection(e); + } + // A running task holds its interface, so EC2 must report it "in-use" rather than + // "available" as a fresh one starts out, and must refuse to delete it under the task. + ec2Service.holdNetworkInterfaceForService(region, eni.getNetworkInterfaceId()); + task.setNetworkInterfaceId(eni.getNetworkInterfaceId()); + task.setPrivateIpAddress(eni.getPrivateIpAddress()); + task.setMacAddress(eni.getMacAddress()); + task.setPrivateDnsName(eni.getPrivateDnsName()); + task.setAttachmentId("eni-attach-" + eni.getNetworkInterfaceId()); + ec2Service.describeSubnets(region, List.of(subnetId), Map.of()).stream() + .findFirst() + .ifPresent(subnet -> task.setAvailabilityZone(subnet.getAvailabilityZone())); + } + + /** + * Restates an EC2 lookup failure as the error RunTask declares. A caller naming a subnet or a + * security group that is not there asked for something the task cannot have, and + * {@code InvalidSubnetID.NotFound} is not in RunTask's error list, so an SDK sees it as an + * unmodelled failure rather than the InvalidParameterException AWS returns. Anything else the + * ENI path raises is already an ECS-shaped error and travels unchanged. + */ + private static AwsException asEcsNetworkRejection(AwsException e) { + if (!EC2_NETWORK_LOOKUP_FAILURES.contains(e.getErrorCode())) { + return e; + } + return new AwsException("InvalidParameterException", e.getMessage(), 400); + } + + /** + * Releases a stopped task's ENI. The interface id stays on the task, with its attachment + * reported as {@code DELETED}, because AWS keeps describing a stopped task's attachment. + * Idempotent: the status is flipped first, so a second teardown path does nothing. + */ + public void releaseTaskNetwork(EcsTask task, String region) { + String eniId = task.getNetworkInterfaceId(); + if (eniId == null || ec2Service == null || ATTACHMENT_DELETED.equals(task.getAttachmentStatus())) { + return; + } + task.setAttachmentStatus(ATTACHMENT_DELETED); + if (firewallManager != null) { + firewallManager.unregister(eniId); + } + try { + // EC2 refuses to delete an interface that is in use, and attachTaskNetwork marked + // this one as held by the task, so the hold goes before the interface does. + ec2Service.releaseNetworkInterfaceFromService(region, eniId); + ec2Service.deleteNetworkInterface(region, eniId); + } catch (RuntimeException e) { + LOG.debugv("Could not delete the ENI {0} of task {1}: {2}", + eniId, task.getTaskArn(), e.getMessage()); + } + } + + /** The ENI {@link #attachTaskNetwork} allocated for this task, or null if it is already gone. */ + private NetworkInterface existingTaskEni(EcsTask task, String region) { + if (task.getNetworkInterfaceId() == null) { + return null; + } + try { + return ec2Service.describeNetworkInterfaces(region, List.of(task.getNetworkInterfaceId()), + Map.of(), 0, null) + .networkInterfaces().stream().findFirst().orElse(null); + } catch (RuntimeException e) { + LOG.debugv("Could not resolve the ENI {0} of task {1}, allocating a new one: {2}", + task.getNetworkInterfaceId(), task.getTaskArn(), e.getMessage()); + return null; + } + } + private PreparedNetwork prepareNetwork(EcsTask task, TaskDefinition definition, String region, String taskId) { if (definition.getNetworkMode() != NetworkMode.awsvpc || firewallManager == null || !firewallManager.enabled()) { @@ -478,8 +773,13 @@ public class EcsContainerManager { if (awsvpc == null || awsvpc.getSubnets() == null || awsvpc.getSubnets().isEmpty()) { throw new AwsException("ClientException", "awsvpc tasks require a subnet", 400); } - NetworkInterface eni = ec2Service.createNetworkInterface(region, awsvpc.getSubnets().getFirst(), - "ECS task " + task.getTaskArn(), null, List.of(), awsvpc.getSecurityGroups(), List.of()); + // attachTaskNetwork already allocated the task ENI; the namespace is built around it. + NetworkInterface eni = existingTaskEni(task, region); + if (eni == null) { + eni = ec2Service.createNetworkInterface(region, awsvpc.getSubnets().getFirst(), + "ECS task " + task.getTaskArn(), null, List.of(), awsvpc.getSecurityGroups(), List.of()); + ec2Service.holdNetworkInterfaceForService(region, eni.getNetworkInterfaceId()); + } String eniId = eni.getNetworkInterfaceId(); SecurityGroupFirewallManager.Namespace namespace = null; try { @@ -514,6 +814,7 @@ public class EcsContainerManager { if (namespace != null) { lifecycleManager.removeIfExists(namespace.helperId()); } + ec2Service.releaseNetworkInterfaceFromService(region, eniId); ec2Service.deleteNetworkInterface(region, eniId); throw e; } @@ -576,17 +877,21 @@ public class EcsContainerManager { return exitCodes; } - // Phase 1: stop all containers (no-op for those already exited). + // Phase 1: stop all containers (no-op for those already exited), each given the grace + // period its container definition asked for. Set terminatedContainerIds = new HashSet<>(); - for (String dockerId : handle.getContainerIds().values()) { + for (Map.Entry entry : handle.getContainerIds().entrySet()) { + String dockerId = entry.getValue(); try { - lifecycleManager.getDockerClient().stopContainerCmd(dockerId).withTimeout(5).exec(); + lifecycleManager.getDockerClient().stopContainerCmd(dockerId) + .withTimeout(handle.stopTimeoutFor(entry.getKey())).exec(); terminatedContainerIds.add(dockerId); } catch (NotFoundException ignored) { terminatedContainerIds.add(dockerId); } catch (Exception e) { LOG.warnv("Error stopping ECS container {0}: {1}", dockerId, e.getMessage()); } + killIfStillRunning(dockerId); } // Phase 2: inspect exit codes, then remove. @@ -611,6 +916,37 @@ public class EcsContainerManager { return exitCodes; } + /** + * Makes sure a container really is stopped before its exit code is read. + * + *

A container that ignores SIGTERM only dies when its {@code stopTimeout} elapses, and the + * Docker client can give up on the stop request before the daemon gets there. Either way the + * container would still be running when the exit code is collected, and the task would report + * no exit code at all, so it is killed here. + */ + private void killIfStillRunning(String dockerId) { + if (getExitCodeIfStopped(dockerId) != null) { + return; + } + try { + lifecycleManager.getDockerClient().killContainerCmd(dockerId).exec(); + } catch (NotFoundException ignored) { + return; // already gone, and its exit code is whatever the earlier inspect saw + } catch (Exception e) { + LOG.warnv("Error killing ECS container {0}: {1}", dockerId, e.getMessage()); + return; + } + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(KILL_SETTLE_SECONDS); + while (System.nanoTime() < deadline && getExitCodeIfStopped(dockerId) == null) { + try { + TimeUnit.MILLISECONDS.sleep(DEPENDENCY_POLL_MILLIS); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + return; + } + } + } + private void removeFirelensVolume(EcsTaskHandle handle) { if (handle == null || handle.getFirelensVolumeName() == null) { return; @@ -856,10 +1192,14 @@ public class EcsContainerManager { } return "127.0.0.1"; } + /** + * Tears down the firewall registration of a protected task. The ENI itself outlives this: + * it belongs to the task, not to its containers, and {@link #releaseTaskNetwork} frees it when + * the task reaches STOPPED. + */ private void cleanupProtectedNetwork(EcsTaskHandle handle) { if (firewallManager != null && handle.getNetworkInterfaceId() != null) { firewallManager.unregister(handle.getNetworkInterfaceId()); - ec2Service.deleteNetworkInterface(handle.getRegion(), handle.getNetworkInterfaceId()); } } @@ -1108,6 +1448,17 @@ public class EcsContainerManager { container.setLastStatus("RUNNING"); container.setNetworkBindings(networkBindings); container.setDockerId(dockerId); + container.setRuntimeId(dockerId); + container.setHealthStatus(def.getHealthCheck() != null ? "UNKNOWN" : null); + if (def.getCpu() != null) { + container.setCpu(String.valueOf(def.getCpu())); + } + if (def.getMemory() != null) { + container.setMemory(String.valueOf(def.getMemory())); + } + if (def.getMemoryReservation() != null) { + container.setMemoryReservation(String.valueOf(def.getMemoryReservation())); + } container.setContainerArn(regionResolver.buildArn("ecs", region, "container/" + extractTaskId(taskArn) + "/" + def.getName())); return container; diff --git a/src/main/java/io/github/hectorvent/floci/services/ecs/container/EcsTaskHandle.java b/src/main/java/io/github/hectorvent/floci/services/ecs/container/EcsTaskHandle.java index e1db6786c8..deb19ccd0f 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ecs/container/EcsTaskHandle.java +++ b/src/main/java/io/github/hectorvent/floci/services/ecs/container/EcsTaskHandle.java @@ -10,12 +10,24 @@ import java.util.Map; */ public class EcsTaskHandle { + /** + * The grace period a container gets when its definition does not ask for one. + * + *

ECS defaults to 30 seconds. Floci answers StopTask synchronously, and a container that + * ignores SIGTERM (anything running as PID 1 without a signal handler, which is most of them) + * would hold the caller for the whole period, so the implicit default stays short. A + * {@code stopTimeout} the task definition asks for is honoured as given. + */ + public static final int DEFAULT_STOP_TIMEOUT_SECONDS = 5; + private final String taskArn; private final Map containerIds; // containerName → dockerId private final Map logStreamsByContainerId; private final String firelensVolumeName; private final String networkInterfaceId; private final String region; + /** Per-container {@code stopTimeout}, so teardown waits as long as the task definition asked. */ + private final Map stopTimeouts; public EcsTaskHandle(String taskArn, Map containerIds, Map logStreamsByContainerId) { @@ -25,12 +37,21 @@ public class EcsTaskHandle { public EcsTaskHandle(String taskArn, Map containerIds, Map logStreamsByContainerId, String firelensVolumeName, String networkInterfaceId, String region) { + this(taskArn, containerIds, logStreamsByContainerId, firelensVolumeName, + networkInterfaceId, region, Map.of()); + } + + public EcsTaskHandle(String taskArn, Map containerIds, + Map logStreamsByContainerId, + String firelensVolumeName, String networkInterfaceId, String region, + Map stopTimeouts) { this.taskArn = taskArn; this.containerIds = new LinkedHashMap<>(containerIds); this.logStreamsByContainerId = new LinkedHashMap<>(logStreamsByContainerId); this.firelensVolumeName = firelensVolumeName; this.networkInterfaceId = networkInterfaceId; this.region = region; + this.stopTimeouts = new LinkedHashMap<>(stopTimeouts); } public String getTaskArn() { return taskArn; } @@ -40,6 +61,12 @@ public class EcsTaskHandle { public String getNetworkInterfaceId() { return networkInterfaceId; } public String getRegion() { return region; } + /** The container's {@code stopTimeout} in seconds, or {@link #DEFAULT_STOP_TIMEOUT_SECONDS}. */ + public int stopTimeoutFor(String containerName) { + Integer configured = stopTimeouts.get(containerName); + return configured != null ? configured : DEFAULT_STOP_TIMEOUT_SECONDS; + } + /** Removes and returns the log stream that no longer needs task-level ownership. */ public Closeable removeLogStream(String containerId) { return logStreamsByContainerId.remove(containerId); diff --git a/src/main/java/io/github/hectorvent/floci/services/ecs/model/CapacityProviderStrategyItem.java b/src/main/java/io/github/hectorvent/floci/services/ecs/model/CapacityProviderStrategyItem.java new file mode 100644 index 0000000000..210e7eb9b6 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/ecs/model/CapacityProviderStrategyItem.java @@ -0,0 +1,19 @@ +package io.github.hectorvent.floci.services.ecs.model; + +import io.quarkus.runtime.annotations.RegisterForReflection; + +/** + * One entry of a {@code capacityProviderStrategy}: + * {@code {"capacityProvider": "FARGATE_SPOT", "weight": 1, "base": 0}}. + * + *

{@code base} is the number of tasks placed on the provider before any weighting applies, and + * at most one entry of a strategy may set it. {@code weight} is that provider's share of whatever + * is left. + */ +@RegisterForReflection +public record CapacityProviderStrategyItem(String capacityProvider, int weight, int base) { + + public CapacityProviderStrategyItem(String capacityProvider) { + this(capacityProvider, 0, 0); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/ecs/model/Container.java b/src/main/java/io/github/hectorvent/floci/services/ecs/model/Container.java index 5a14e047bd..1a2e3ce270 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ecs/model/Container.java +++ b/src/main/java/io/github/hectorvent/floci/services/ecs/model/Container.java @@ -15,6 +15,14 @@ public class Container { private Integer exitCode; private String reason; private List networkBindings; + private List networkInterfaces; + private List managedAgents; + private String healthStatus; + private String runtimeId; + private String imageDigest; + private String cpu; + private String memory; + private String memoryReservation; // transient — not persisted private transient String dockerId; @@ -43,6 +51,32 @@ public class Container { public List getNetworkBindings() { return networkBindings; } public void setNetworkBindings(List networkBindings) { this.networkBindings = networkBindings; } + public List getNetworkInterfaces() { return networkInterfaces; } + public void setNetworkInterfaces(List networkInterfaces) { + this.networkInterfaces = networkInterfaces; + } + + public List getManagedAgents() { return managedAgents; } + public void setManagedAgents(List managedAgents) { this.managedAgents = managedAgents; } + + public String getHealthStatus() { return healthStatus; } + public void setHealthStatus(String healthStatus) { this.healthStatus = healthStatus; } + + public String getRuntimeId() { return runtimeId; } + public void setRuntimeId(String runtimeId) { this.runtimeId = runtimeId; } + + public String getImageDigest() { return imageDigest; } + public void setImageDigest(String imageDigest) { this.imageDigest = imageDigest; } + + public String getCpu() { return cpu; } + public void setCpu(String cpu) { this.cpu = cpu; } + + public String getMemory() { return memory; } + public void setMemory(String memory) { this.memory = memory; } + + public String getMemoryReservation() { return memoryReservation; } + public void setMemoryReservation(String memoryReservation) { this.memoryReservation = memoryReservation; } + public String getDockerId() { return dockerId; } public void setDockerId(String dockerId) { this.dockerId = dockerId; } } diff --git a/src/main/java/io/github/hectorvent/floci/services/ecs/model/ContainerDefinition.java b/src/main/java/io/github/hectorvent/floci/services/ecs/model/ContainerDefinition.java index 3b30f13cb5..f5dca15de9 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ecs/model/ContainerDefinition.java +++ b/src/main/java/io/github/hectorvent/floci/services/ecs/model/ContainerDefinition.java @@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.ecs.model; import io.quarkus.runtime.annotations.RegisterForReflection; import java.util.List; +import java.util.Map; @RegisterForReflection public class ContainerDefinition { @@ -15,14 +16,33 @@ public class ContainerDefinition { private boolean essential = true; private List portMappings; private List environment; + private List environmentFiles; private List secrets; private List command; private List entryPoint; private List mountPoints; private List volumesFrom; + private List dependsOn; private LogConfiguration logConfiguration; private FirelensConfiguration firelensConfiguration; private HealthCheck healthCheck; + private Integer startTimeout; + private Integer stopTimeout; + private String user; + private String workingDirectory; + private String hostname; + private Boolean readonlyRootFilesystem; + private Boolean privileged; + private Boolean disableNetworking; + private Boolean interactive; + private Boolean pseudoTerminal; + private List links; + private List dnsServers; + private List dnsSearchDomains; + private List dockerSecurityOptions; + private Map dockerLabels; + private String repositoryCredentialsParameter; + private Map unparsed; public String getName() { return name; } public void setName(String name) { this.name = name; } @@ -72,4 +92,69 @@ public class ContainerDefinition { } public HealthCheck getHealthCheck() { return healthCheck; } public void setHealthCheck(HealthCheck healthCheck) { this.healthCheck = healthCheck; } + + public List getEnvironmentFiles() { return environmentFiles; } + public void setEnvironmentFiles(List environmentFiles) { + this.environmentFiles = environmentFiles; + } + + public List getDependsOn() { return dependsOn; } + public void setDependsOn(List dependsOn) { this.dependsOn = dependsOn; } + + public Integer getStartTimeout() { return startTimeout; } + public void setStartTimeout(Integer startTimeout) { this.startTimeout = startTimeout; } + + public Integer getStopTimeout() { return stopTimeout; } + public void setStopTimeout(Integer stopTimeout) { this.stopTimeout = stopTimeout; } + + public String getUser() { return user; } + public void setUser(String user) { this.user = user; } + + public String getWorkingDirectory() { return workingDirectory; } + public void setWorkingDirectory(String workingDirectory) { this.workingDirectory = workingDirectory; } + + public String getHostname() { return hostname; } + public void setHostname(String hostname) { this.hostname = hostname; } + + public Boolean getReadonlyRootFilesystem() { return readonlyRootFilesystem; } + public void setReadonlyRootFilesystem(Boolean readonlyRootFilesystem) { + this.readonlyRootFilesystem = readonlyRootFilesystem; + } + + public Boolean getPrivileged() { return privileged; } + public void setPrivileged(Boolean privileged) { this.privileged = privileged; } + + public Boolean getDisableNetworking() { return disableNetworking; } + public void setDisableNetworking(Boolean disableNetworking) { this.disableNetworking = disableNetworking; } + + public Boolean getInteractive() { return interactive; } + public void setInteractive(Boolean interactive) { this.interactive = interactive; } + + public Boolean getPseudoTerminal() { return pseudoTerminal; } + public void setPseudoTerminal(Boolean pseudoTerminal) { this.pseudoTerminal = pseudoTerminal; } + + public List getLinks() { return links; } + public void setLinks(List links) { this.links = links; } + + public List getDnsServers() { return dnsServers; } + public void setDnsServers(List dnsServers) { this.dnsServers = dnsServers; } + + public List getDnsSearchDomains() { return dnsSearchDomains; } + public void setDnsSearchDomains(List dnsSearchDomains) { this.dnsSearchDomains = dnsSearchDomains; } + + public List getDockerSecurityOptions() { return dockerSecurityOptions; } + public void setDockerSecurityOptions(List dockerSecurityOptions) { + this.dockerSecurityOptions = dockerSecurityOptions; + } + + public Map getDockerLabels() { return dockerLabels; } + public void setDockerLabels(Map dockerLabels) { this.dockerLabels = dockerLabels; } + + public String getRepositoryCredentialsParameter() { return repositoryCredentialsParameter; } + public void setRepositoryCredentialsParameter(String repositoryCredentialsParameter) { + this.repositoryCredentialsParameter = repositoryCredentialsParameter; + } + + public Map getUnparsed() { return unparsed; } + public void setUnparsed(Map unparsed) { this.unparsed = unparsed; } } diff --git a/src/main/java/io/github/hectorvent/floci/services/ecs/model/ContainerDependency.java b/src/main/java/io/github/hectorvent/floci/services/ecs/model/ContainerDependency.java new file mode 100644 index 0000000000..049d2f08a2 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/ecs/model/ContainerDependency.java @@ -0,0 +1,18 @@ +package io.github.hectorvent.floci.services.ecs.model; + +import io.quarkus.runtime.annotations.RegisterForReflection; + +/** + * A {@code dependsOn} entry of an ECS container definition: + * {@code {"containerName": ..., "condition": "START"|"COMPLETE"|"SUCCESS"|"HEALTHY"}}. + * + *

The condition decides how far the named container must get before the dependent one starts. + */ +@RegisterForReflection +public record ContainerDependency(String containerName, String condition) { + + public static final String START = "START"; + public static final String COMPLETE = "COMPLETE"; + public static final String SUCCESS = "SUCCESS"; + public static final String HEALTHY = "HEALTHY"; +} diff --git a/src/main/java/io/github/hectorvent/floci/services/ecs/model/ContainerOverride.java b/src/main/java/io/github/hectorvent/floci/services/ecs/model/ContainerOverride.java index e6aaec5958..529b88b856 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ecs/model/ContainerOverride.java +++ b/src/main/java/io/github/hectorvent/floci/services/ecs/model/ContainerOverride.java @@ -16,6 +16,10 @@ public class ContainerOverride { private String name; private List command; private List environment; + private List environmentFiles; + private Integer cpu; + private Integer memory; + private Integer memoryReservation; public String getName() { return name; } public void setName(String name) { this.name = name; } @@ -25,4 +29,18 @@ public class ContainerOverride { public List getEnvironment() { return environment; } public void setEnvironment(List environment) { this.environment = environment; } + + public List getEnvironmentFiles() { return environmentFiles; } + public void setEnvironmentFiles(List environmentFiles) { + this.environmentFiles = environmentFiles; + } + + public Integer getCpu() { return cpu; } + public void setCpu(Integer cpu) { this.cpu = cpu; } + + public Integer getMemory() { return memory; } + public void setMemory(Integer memory) { this.memory = memory; } + + public Integer getMemoryReservation() { return memoryReservation; } + public void setMemoryReservation(Integer memoryReservation) { this.memoryReservation = memoryReservation; } } 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 758bae3acb..5d0b44efee 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 List capacityProviders; + private List> defaultCapacityProviderStrategy; public String getClusterName() { return clusterName; } public void setClusterName(String clusterName) { this.clusterName = clusterName; } @@ -21,4 +23,15 @@ public class CreateClusterRequest { public List getSettings() { return settings; } public void setSettings(List settings) { this.settings = settings; } + + public List getCapacityProviders() { return capacityProviders; } + public void setCapacityProviders(List capacityProviders) { this.capacityProviders = capacityProviders; } + + public List> getDefaultCapacityProviderStrategy() { + return defaultCapacityProviderStrategy; + } + + public void setDefaultCapacityProviderStrategy(List> strategy) { + this.defaultCapacityProviderStrategy = strategy; + } } diff --git a/src/main/java/io/github/hectorvent/floci/services/ecs/model/CreateServiceRequest.java b/src/main/java/io/github/hectorvent/floci/services/ecs/model/CreateServiceRequest.java index b164f83c92..a1d9a8753e 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ecs/model/CreateServiceRequest.java +++ b/src/main/java/io/github/hectorvent/floci/services/ecs/model/CreateServiceRequest.java @@ -14,6 +14,7 @@ public class CreateServiceRequest { private String taskDefinition; private int desiredCount = 1; private LaunchType launchType; + private List capacityProviderStrategy; private List loadBalancers; private NetworkConfiguration networkConfiguration; private Map tags; @@ -37,6 +38,11 @@ public class CreateServiceRequest { 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 List getLoadBalancers() { return loadBalancers; } public void setLoadBalancers(List loadBalancers) { this.loadBalancers = loadBalancers; } @@ -65,4 +71,5 @@ public class CreateServiceRequest { public void setServiceConnectConfiguration(Map serviceConnectConfiguration) { this.serviceConnectConfiguration = serviceConnectConfiguration; } + } diff --git a/src/main/java/io/github/hectorvent/floci/services/ecs/model/EcsLoadBalancer.java b/src/main/java/io/github/hectorvent/floci/services/ecs/model/EcsLoadBalancer.java index afa023baa6..b25febe7d0 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ecs/model/EcsLoadBalancer.java +++ b/src/main/java/io/github/hectorvent/floci/services/ecs/model/EcsLoadBalancer.java @@ -2,6 +2,8 @@ package io.github.hectorvent.floci.services.ecs.model; import io.quarkus.runtime.annotations.RegisterForReflection; +import java.util.Map; + /** * A load balancer association on an ECS service ({@code CreateService}'s * {@code loadBalancers} block). Links a container port on the service's tasks @@ -14,9 +16,16 @@ public class EcsLoadBalancer { private String loadBalancerName; private String containerName; private Integer containerPort; + /** {@code advancedConfiguration}, kept raw: Floci runs no blue/green traffic shifting. */ + private Map advancedConfiguration; public EcsLoadBalancer() {} + public Map getAdvancedConfiguration() { return advancedConfiguration; } + public void setAdvancedConfiguration(Map advancedConfiguration) { + this.advancedConfiguration = advancedConfiguration; + } + public String getTargetGroupArn() { return targetGroupArn; } public void setTargetGroupArn(String targetGroupArn) { this.targetGroupArn = targetGroupArn; } diff --git a/src/main/java/io/github/hectorvent/floci/services/ecs/model/EcsServiceModel.java b/src/main/java/io/github/hectorvent/floci/services/ecs/model/EcsServiceModel.java index 448bd057b1..a04c05a71f 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ecs/model/EcsServiceModel.java +++ b/src/main/java/io/github/hectorvent/floci/services/ecs/model/EcsServiceModel.java @@ -40,6 +40,7 @@ public class EcsServiceModel { * it; the Service shape itself has no member for it. */ private Map serviceConnectConfiguration; + private List capacityProviderStrategy; public String getServiceArn() { return serviceArn; } public void setServiceArn(String serviceArn) { this.serviceArn = serviceArn; } @@ -112,4 +113,10 @@ public class EcsServiceModel { public void setServiceConnectConfiguration(Map serviceConnectConfiguration) { this.serviceConnectConfiguration = serviceConnectConfiguration; } + + public List getCapacityProviderStrategy() { return capacityProviderStrategy; } + public void setCapacityProviderStrategy(List capacityProviderStrategy) { + this.capacityProviderStrategy = capacityProviderStrategy; + } + } diff --git a/src/main/java/io/github/hectorvent/floci/services/ecs/model/EcsTask.java b/src/main/java/io/github/hectorvent/floci/services/ecs/model/EcsTask.java index ffdd541925..c5422330e1 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ecs/model/EcsTask.java +++ b/src/main/java/io/github/hectorvent/floci/services/ecs/model/EcsTask.java @@ -41,6 +41,30 @@ public class EcsTask { private NetworkConfiguration networkConfiguration; private String networkInterfaceId; private String privateIpAddress; + private String macAddress; + private String privateDnsName; + private String attachmentId; + /** {@code ATTACHED} while the task holds its ENI, {@code DELETED} once it has been released. */ + private String attachmentStatus = "ATTACHED"; + private String platformVersion; + private String platformFamily; + /** Set instead of {@link #launchType} when the task was placed through a capacity provider. */ + private String capacityProviderName; + private String connectivity; + private Instant connectivityAt; + private String healthStatus; + private String stopCode; + private String availabilityZone; + private Instant pullStartedAt; + private Instant pullStoppedAt; + private Instant executionStoppedAt; + private Instant stoppingAt; + private EphemeralStorage ephemeralStorage; + private boolean enableExecuteCommand; + private TaskOverride overrides; + private List attributes; + /** Bumped on every state change, the way AWS advances a task's optimistic-locking version. */ + private long version = 1; public EcsTask() { } @@ -76,6 +100,27 @@ public class EcsTask { this.networkConfiguration = other.networkConfiguration; this.networkInterfaceId = other.networkInterfaceId; this.privateIpAddress = other.privateIpAddress; + this.macAddress = other.macAddress; + this.privateDnsName = other.privateDnsName; + this.attachmentId = other.attachmentId; + this.attachmentStatus = other.attachmentStatus; + this.platformVersion = other.platformVersion; + this.platformFamily = other.platformFamily; + this.capacityProviderName = other.capacityProviderName; + this.connectivity = other.connectivity; + this.connectivityAt = other.connectivityAt; + this.healthStatus = other.healthStatus; + this.stopCode = other.stopCode; + this.availabilityZone = other.availabilityZone; + this.pullStartedAt = other.pullStartedAt; + this.pullStoppedAt = other.pullStoppedAt; + this.executionStoppedAt = other.executionStoppedAt; + this.stoppingAt = other.stoppingAt; + this.ephemeralStorage = other.ephemeralStorage; + this.enableExecuteCommand = other.enableExecuteCommand; + this.overrides = other.overrides; + this.attributes = other.attributes; + this.version = other.version; } public String getTaskArn() { return taskArn; } @@ -136,6 +181,12 @@ public class EcsTask { public String getPrivateIpAddress() { return privateIpAddress; } public void setPrivateIpAddress(String privateIpAddress) { this.privateIpAddress = privateIpAddress; } + public String getMacAddress() { return macAddress; } + public void setMacAddress(String macAddress) { this.macAddress = macAddress; } + + public String getPrivateDnsName() { return privateDnsName; } + public void setPrivateDnsName(String privateDnsName) { this.privateDnsName = privateDnsName; } + public String getStoppedReason() { return stoppedReason; } public void setStoppedReason(String stoppedReason) { this.stoppedReason = stoppedReason; } @@ -153,4 +204,69 @@ public class EcsTask { public Map getTags() { return tags; } public void setTags(Map tags) { this.tags = tags; } + + public String getAttachmentId() { return attachmentId; } + public void setAttachmentId(String attachmentId) { this.attachmentId = attachmentId; } + + public String getAttachmentStatus() { return attachmentStatus; } + public void setAttachmentStatus(String attachmentStatus) { this.attachmentStatus = attachmentStatus; } + + 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 getCapacityProviderName() { return capacityProviderName; } + public void setCapacityProviderName(String capacityProviderName) { + this.capacityProviderName = capacityProviderName; + } + + public String getConnectivity() { return connectivity; } + public void setConnectivity(String connectivity) { this.connectivity = connectivity; } + + public Instant getConnectivityAt() { return connectivityAt; } + public void setConnectivityAt(Instant connectivityAt) { this.connectivityAt = connectivityAt; } + + public String getHealthStatus() { return healthStatus; } + public void setHealthStatus(String healthStatus) { this.healthStatus = healthStatus; } + + public String getStopCode() { return stopCode; } + public void setStopCode(String stopCode) { this.stopCode = stopCode; } + + public String getAvailabilityZone() { return availabilityZone; } + public void setAvailabilityZone(String availabilityZone) { this.availabilityZone = availabilityZone; } + + public Instant getPullStartedAt() { return pullStartedAt; } + public void setPullStartedAt(Instant pullStartedAt) { this.pullStartedAt = pullStartedAt; } + + public Instant getPullStoppedAt() { return pullStoppedAt; } + public void setPullStoppedAt(Instant pullStoppedAt) { this.pullStoppedAt = pullStoppedAt; } + + public Instant getExecutionStoppedAt() { return executionStoppedAt; } + public void setExecutionStoppedAt(Instant executionStoppedAt) { this.executionStoppedAt = executionStoppedAt; } + + /** When the task left RUNNING for STOPPING, which AWS reports alongside {@code stoppedAt}. */ + public Instant getStoppingAt() { return stoppingAt; } + public void setStoppingAt(Instant stoppingAt) { this.stoppingAt = stoppingAt; } + + public EphemeralStorage getEphemeralStorage() { return ephemeralStorage; } + public void setEphemeralStorage(EphemeralStorage ephemeralStorage) { this.ephemeralStorage = ephemeralStorage; } + + public boolean isEnableExecuteCommand() { return enableExecuteCommand; } + public void setEnableExecuteCommand(boolean enableExecuteCommand) { + this.enableExecuteCommand = enableExecuteCommand; + } + + public TaskOverride getOverrides() { return overrides; } + public void setOverrides(TaskOverride overrides) { this.overrides = overrides; } + + public List getAttributes() { return attributes; } + public void setAttributes(List attributes) { this.attributes = attributes; } + + public long getVersion() { return version; } + public void setVersion(long version) { this.version = version; } + + /** Advances the version AWS bumps on every task state transition. */ + public void bumpVersion() { this.version++; } } diff --git a/src/main/java/io/github/hectorvent/floci/services/ecs/model/EnvironmentFile.java b/src/main/java/io/github/hectorvent/floci/services/ecs/model/EnvironmentFile.java new file mode 100644 index 0000000000..baa0eb0894 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/ecs/model/EnvironmentFile.java @@ -0,0 +1,11 @@ +package io.github.hectorvent.floci.services.ecs.model; + +import io.quarkus.runtime.annotations.RegisterForReflection; + +/** + * An {@code environmentFiles} entry of an ECS container definition: + * {@code {"value": "", "type": "s3"}}. + */ +@RegisterForReflection +public record EnvironmentFile(String value, String type) { +} diff --git a/src/main/java/io/github/hectorvent/floci/services/ecs/model/EphemeralStorage.java b/src/main/java/io/github/hectorvent/floci/services/ecs/model/EphemeralStorage.java new file mode 100644 index 0000000000..d577bef7bd --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/ecs/model/EphemeralStorage.java @@ -0,0 +1,17 @@ +package io.github.hectorvent.floci.services.ecs.model; + +import io.quarkus.runtime.annotations.RegisterForReflection; + +/** + * The {@code ephemeralStorage} of a Fargate task definition or a RunTask override: + * {@code {"sizeInGiB": 21}}. + * + *

Floci reports the requested size but does not cap the container's writable layer at it. + */ +@RegisterForReflection +public record EphemeralStorage(int sizeInGiB) { + + /** The storage a Fargate task gets without asking, and the floor for an explicit request. */ + public static final int DEFAULT_SIZE_IN_GIB = 20; + public static final int MAX_SIZE_IN_GIB = 200; +} diff --git a/src/main/java/io/github/hectorvent/floci/services/ecs/model/LaunchType.java b/src/main/java/io/github/hectorvent/floci/services/ecs/model/LaunchType.java index f6a78b80fb..c8e1984ece 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ecs/model/LaunchType.java +++ b/src/main/java/io/github/hectorvent/floci/services/ecs/model/LaunchType.java @@ -4,5 +4,5 @@ import io.quarkus.runtime.annotations.RegisterForReflection; @RegisterForReflection public enum LaunchType { - EC2, FARGATE, EXTERNAL + EC2, FARGATE, EXTERNAL, MANAGED_INSTANCES } \ No newline at end of file diff --git a/src/main/java/io/github/hectorvent/floci/services/ecs/model/ManagedAgent.java b/src/main/java/io/github/hectorvent/floci/services/ecs/model/ManagedAgent.java new file mode 100644 index 0000000000..7b7c551b31 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/ecs/model/ManagedAgent.java @@ -0,0 +1,24 @@ +package io.github.hectorvent.floci.services.ecs.model; + +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.time.Instant; + +/** + * A {@code managedAgents} entry of a described container: + * {@code {"name": "ExecuteCommandAgent", "lastStatus": "RUNNING", "lastStartedAt": ...}}. + * + *

ECS Exec is gated on this agent reporting {@code RUNNING}, which is what + * {@code aws ecs execute-command} and the {@code TasksRunning} waiter read. + */ +@RegisterForReflection +public record ManagedAgent(String name, String lastStatus, String reason, Instant lastStartedAt) { + + public static final String EXECUTE_COMMAND_AGENT = "ExecuteCommandAgent"; + public static final String RUNNING = "RUNNING"; + public static final String STOPPED = "STOPPED"; + + public static ManagedAgent executeCommandAgent(Instant startedAt) { + return new ManagedAgent(EXECUTE_COMMAND_AGENT, RUNNING, null, startedAt); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/ecs/model/PortMapping.java b/src/main/java/io/github/hectorvent/floci/services/ecs/model/PortMapping.java index 7b3eb2863c..b87dca800f 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ecs/model/PortMapping.java +++ b/src/main/java/io/github/hectorvent/floci/services/ecs/model/PortMapping.java @@ -2,10 +2,22 @@ package io.github.hectorvent.floci.services.ecs.model; import io.quarkus.runtime.annotations.RegisterForReflection; +/** + * A container's port mapping. + * + *

{@code name} and {@code appProtocol} carry no behaviour here, but they are what a service's + * {@code serviceConnectConfiguration} and {@code vpcLatticeConfigurations} reference by name, so a + * definition registered for Service Connect has to read back with them intact. + */ @RegisterForReflection -public record PortMapping(int containerPort, int hostPort, String protocol) { +public record PortMapping(int containerPort, int hostPort, String protocol, String name, + String appProtocol, String containerPortRange) { public PortMapping(int containerPort) { this(containerPort, 0, "tcp"); } + + public PortMapping(int containerPort, int hostPort, String protocol) { + this(containerPort, hostPort, protocol, null, null, null); + } } diff --git a/src/main/java/io/github/hectorvent/floci/services/ecs/model/RegisterTaskDefinitionRequest.java b/src/main/java/io/github/hectorvent/floci/services/ecs/model/RegisterTaskDefinitionRequest.java index 96bf12bf17..14a6bddec5 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ecs/model/RegisterTaskDefinitionRequest.java +++ b/src/main/java/io/github/hectorvent/floci/services/ecs/model/RegisterTaskDefinitionRequest.java @@ -26,7 +26,12 @@ public class RegisterTaskDefinitionRequest { private List requiresCompatibilities; private List volumes; private RuntimePlatform runtimePlatform; + private EphemeralStorage ephemeralStorage; + private String pidMode; + private String ipcMode; private Map tags; + /** Members Floci does not act on, such as proxyConfiguration and placementConstraints. */ + private Map unparsed; public String getFamily() { return family; } public void setFamily(String family) { this.family = family; } @@ -62,9 +67,23 @@ public class RegisterTaskDefinitionRequest { public RuntimePlatform getRuntimePlatform() { return runtimePlatform; } public void setRuntimePlatform(RuntimePlatform runtimePlatform) { this.runtimePlatform = runtimePlatform; } + public EphemeralStorage getEphemeralStorage() { return ephemeralStorage; } + public void setEphemeralStorage(EphemeralStorage ephemeralStorage) { + this.ephemeralStorage = ephemeralStorage; + } + + public String getPidMode() { return pidMode; } + public void setPidMode(String pidMode) { this.pidMode = pidMode; } + + public String getIpcMode() { return ipcMode; } + public void setIpcMode(String ipcMode) { this.ipcMode = ipcMode; } + public Map getTags() { return tags; } public void setTags(Map tags) { this.tags = tags; } + public Map getUnparsed() { return unparsed; } + public void setUnparsed(Map unparsed) { this.unparsed = unparsed; } + public boolean isFargate() { return requiresCompatibilities != null && requiresCompatibilities.contains("FARGATE"); } diff --git a/src/main/java/io/github/hectorvent/floci/services/ecs/model/RunTaskRequest.java b/src/main/java/io/github/hectorvent/floci/services/ecs/model/RunTaskRequest.java index 631f195c50..f02f931fea 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ecs/model/RunTaskRequest.java +++ b/src/main/java/io/github/hectorvent/floci/services/ecs/model/RunTaskRequest.java @@ -3,6 +3,7 @@ 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 RunTask} (or {@code StartTask}) request. @@ -19,10 +20,17 @@ public class RunTaskRequest { private String taskDefinition; private int count = 1; private LaunchType launchType; + private List capacityProviderStrategy; private String group; private String startedBy; - private List containerOverrides; + private TaskOverride overrides; private NetworkConfiguration networkConfiguration; + private String platformVersion; + private boolean enableExecuteCommand; + private boolean enableECSManagedTags; + private String propagateTags; + private String referenceId; + private Map tags; private List containerInstances; public String getCluster() { return cluster; } @@ -37,15 +45,22 @@ public class RunTaskRequest { 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 getGroup() { return group; } public void setGroup(String group) { this.group = group; } public String getStartedBy() { return startedBy; } public void setStartedBy(String startedBy) { this.startedBy = startedBy; } - public List getContainerOverrides() { return containerOverrides; } - public void setContainerOverrides(List containerOverrides) { - this.containerOverrides = containerOverrides; + public TaskOverride getOverrides() { return overrides; } + public void setOverrides(TaskOverride overrides) { this.overrides = overrides; } + + public List getContainerOverrides() { + return overrides == null ? null : overrides.getContainerOverrides(); } public NetworkConfiguration getNetworkConfiguration() { return networkConfiguration; } @@ -53,6 +68,28 @@ public class RunTaskRequest { this.networkConfiguration = networkConfiguration; } + public String getPlatformVersion() { return platformVersion; } + public void setPlatformVersion(String platformVersion) { this.platformVersion = platformVersion; } + + public boolean isEnableExecuteCommand() { return enableExecuteCommand; } + public void setEnableExecuteCommand(boolean enableExecuteCommand) { + this.enableExecuteCommand = enableExecuteCommand; + } + + public boolean isEnableECSManagedTags() { return enableECSManagedTags; } + public void setEnableECSManagedTags(boolean enableECSManagedTags) { + this.enableECSManagedTags = enableECSManagedTags; + } + + public String getPropagateTags() { return propagateTags; } + public void setPropagateTags(String propagateTags) { this.propagateTags = propagateTags; } + + public String getReferenceId() { return referenceId; } + public void setReferenceId(String referenceId) { this.referenceId = referenceId; } + + public Map getTags() { return tags; } + public void setTags(Map tags) { this.tags = tags; } + public List getContainerInstances() { return containerInstances; } public void setContainerInstances(List containerInstances) { this.containerInstances = containerInstances; diff --git a/src/main/java/io/github/hectorvent/floci/services/ecs/model/TaskDefinition.java b/src/main/java/io/github/hectorvent/floci/services/ecs/model/TaskDefinition.java index 3b3e9ae625..0ad3055d21 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ecs/model/TaskDefinition.java +++ b/src/main/java/io/github/hectorvent/floci/services/ecs/model/TaskDefinition.java @@ -1,7 +1,9 @@ package io.github.hectorvent.floci.services.ecs.model; +import com.fasterxml.jackson.annotation.JsonIgnore; import io.quarkus.runtime.annotations.RegisterForReflection; +import java.time.Instant; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -23,7 +25,18 @@ public class TaskDefinition { private RuntimePlatform runtimePlatform; private List requiresCompatibilities; private List compatibilities; + /** The container instance capabilities the definition needs, derived at registration. */ + private List requiresAttributes; + private EphemeralStorage ephemeralStorage; + private String pidMode; + private String ipcMode; + private Instant registeredAt; + private String registeredBy; + private Instant deregisteredAt; + private Instant deleteRequestedAt; private Map tags = new HashMap<>(); + /** Members Floci does not act on, kept verbatim so DescribeTaskDefinition round-trips. */ + private Map unparsed; public String getTaskDefinitionArn() { return taskDefinitionArn; } public void setTaskDefinitionArn(String taskDefinitionArn) { this.taskDefinitionArn = taskDefinitionArn; } @@ -66,9 +79,43 @@ public class TaskDefinition { public List getRequiresCompatibilities() { return requiresCompatibilities; } public void setRequiresCompatibilities(List requiresCompatibilities) { this.requiresCompatibilities = requiresCompatibilities; } + public List getRequiresAttributes() { return requiresAttributes; } + public void setRequiresAttributes(List requiresAttributes) { this.requiresAttributes = requiresAttributes; } + public List getCompatibilities() { return compatibilities; } public void setCompatibilities(List compatibilities) { this.compatibilities = compatibilities; } + public EphemeralStorage getEphemeralStorage() { return ephemeralStorage; } + public void setEphemeralStorage(EphemeralStorage ephemeralStorage) { this.ephemeralStorage = ephemeralStorage; } + + public String getPidMode() { return pidMode; } + public void setPidMode(String pidMode) { this.pidMode = pidMode; } + + public String getIpcMode() { return ipcMode; } + public void setIpcMode(String ipcMode) { this.ipcMode = ipcMode; } + + public Instant getRegisteredAt() { return registeredAt; } + public void setRegisteredAt(Instant registeredAt) { this.registeredAt = registeredAt; } + + public String getRegisteredBy() { return registeredBy; } + public void setRegisteredBy(String registeredBy) { this.registeredBy = registeredBy; } + + public Instant getDeregisteredAt() { return deregisteredAt; } + public void setDeregisteredAt(Instant deregisteredAt) { this.deregisteredAt = deregisteredAt; } + + /** When deletion was asked for, which is when the revision entered DELETE_IN_PROGRESS. */ + public Instant getDeleteRequestedAt() { return deleteRequestedAt; } + public void setDeleteRequestedAt(Instant deleteRequestedAt) { this.deleteRequestedAt = deleteRequestedAt; } + public Map getTags() { return tags; } public void setTags(Map tags) { this.tags = tags; } + + public Map getUnparsed() { return unparsed; } + public void setUnparsed(Map unparsed) { this.unparsed = unparsed; } + + /** Whether the definition declares Fargate compatibility, which gates the Fargate-only rules. */ + @JsonIgnore + public boolean isFargateCompatible() { + return requiresCompatibilities != null && requiresCompatibilities.contains("FARGATE"); + } } diff --git a/src/main/java/io/github/hectorvent/floci/services/ecs/model/TaskNetworkInterface.java b/src/main/java/io/github/hectorvent/floci/services/ecs/model/TaskNetworkInterface.java new file mode 100644 index 0000000000..d428c60654 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/ecs/model/TaskNetworkInterface.java @@ -0,0 +1,14 @@ +package io.github.hectorvent.floci.services.ecs.model; + +import io.quarkus.runtime.annotations.RegisterForReflection; + +/** + * A {@code networkInterfaces} entry of a described container: + * {@code {"attachmentId": ..., "privateIpv4Address": ...}}. + * + *

An {@code awsvpc} task reports the same interface on each of its containers, since they + * share the task ENI. + */ +@RegisterForReflection +public record TaskNetworkInterface(String attachmentId, String privateIpv4Address, String ipv6Address) { +} diff --git a/src/main/java/io/github/hectorvent/floci/services/ecs/model/TaskOverride.java b/src/main/java/io/github/hectorvent/floci/services/ecs/model/TaskOverride.java new file mode 100644 index 0000000000..8e1ab5bebc --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/ecs/model/TaskOverride.java @@ -0,0 +1,53 @@ +package io.github.hectorvent.floci.services.ecs.model; + +import com.fasterxml.jackson.annotation.JsonIgnore; +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.util.List; + +/** + * The {@code overrides} of a RunTask or StartTask request, echoed back on the task. + * + *

The task-level members replace the task definition's own {@code cpu}, {@code memory}, + * roles and {@code ephemeralStorage} for this task only; {@code containerOverrides} carries the + * per-container half. + */ +@RegisterForReflection +public class TaskOverride { + + private List containerOverrides; + private String cpu; + private String memory; + private String taskRoleArn; + private String executionRoleArn; + private EphemeralStorage ephemeralStorage; + + public List getContainerOverrides() { return containerOverrides; } + public void setContainerOverrides(List containerOverrides) { + this.containerOverrides = containerOverrides; + } + + public String getCpu() { return cpu; } + public void setCpu(String cpu) { this.cpu = cpu; } + + public String getMemory() { return memory; } + public void setMemory(String memory) { this.memory = memory; } + + public String getTaskRoleArn() { return taskRoleArn; } + public void setTaskRoleArn(String taskRoleArn) { this.taskRoleArn = taskRoleArn; } + + public String getExecutionRoleArn() { return executionRoleArn; } + public void setExecutionRoleArn(String executionRoleArn) { this.executionRoleArn = executionRoleArn; } + + public EphemeralStorage getEphemeralStorage() { return ephemeralStorage; } + public void setEphemeralStorage(EphemeralStorage ephemeralStorage) { + this.ephemeralStorage = ephemeralStorage; + } + + @JsonIgnore + public boolean isEmpty() { + return (containerOverrides == null || containerOverrides.isEmpty()) + && cpu == null && memory == null && taskRoleArn == null + && executionRoleArn == null && ephemeralStorage == null; + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/ecs/model/UpdateServiceRequest.java b/src/main/java/io/github/hectorvent/floci/services/ecs/model/UpdateServiceRequest.java index 24c385cb59..0f6202ab49 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ecs/model/UpdateServiceRequest.java +++ b/src/main/java/io/github/hectorvent/floci/services/ecs/model/UpdateServiceRequest.java @@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.ecs.model; import io.quarkus.runtime.annotations.RegisterForReflection; +import java.util.List; import java.util.Map; /** @@ -21,6 +22,7 @@ public class UpdateServiceRequest { private String availabilityZoneRebalancing; private boolean forceNewDeployment; private Map serviceConnectConfiguration; + private List capacityProviderStrategy; public String getCluster() { return cluster; } public void setCluster(String cluster) { this.cluster = cluster; } @@ -51,4 +53,10 @@ public class UpdateServiceRequest { public void setServiceConnectConfiguration(Map serviceConnectConfiguration) { this.serviceConnectConfiguration = serviceConnectConfiguration; } + + public List getCapacityProviderStrategy() { return capacityProviderStrategy; } + public void setCapacityProviderStrategy(List capacityProviderStrategy) { + this.capacityProviderStrategy = capacityProviderStrategy; + } + } diff --git a/src/main/java/io/github/hectorvent/floci/services/ecs/model/Volume.java b/src/main/java/io/github/hectorvent/floci/services/ecs/model/Volume.java index 9b56a49bef..601dc7ca9e 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ecs/model/Volume.java +++ b/src/main/java/io/github/hectorvent/floci/services/ecs/model/Volume.java @@ -2,22 +2,35 @@ package io.github.hectorvent.floci.services.ecs.model; import io.quarkus.runtime.annotations.RegisterForReflection; +import java.util.Map; + /** * A task-level volume in an ECS task definition. Two shapes are modelled: *

    - *
  • EC2-launch-type {@code host} volume — {@code {"name": ..., "host": {"sourcePath": ...}}}; + *
  • EC2-launch-type {@code host} volume: {@code {"name": ..., "host": {"sourcePath": ...}}}; * {@code hostSourcePath} is the absolute path on the Docker host that the volume binds to.
  • - *
  • {@code efsVolumeConfiguration} volume — {@code {"name": ..., "efsVolumeConfiguration": {...}}}; + *
  • {@code efsVolumeConfiguration} volume: {@code {"name": ..., "efsVolumeConfiguration": {...}}}; * see {@link EfsVolumeConfiguration}.
  • *
* The two are mutually exclusive. A container references the volume by {@code name} via a * {@link MountPoint}. + * + *

{@code unparsed} keeps the volume members Floci backs with nothing, which is the rest of + * AWS's {@code Volume} shape: {@code dockerVolumeConfiguration}, + * {@code fsxWindowsFileServerVolumeConfiguration}, {@code s3filesVolumeConfiguration} and + * {@code configuredAtLaunch}. They have to survive the round trip or a client that registered one + * reads the definition back without it and proposes the same change forever. */ @RegisterForReflection -public record Volume(String name, String hostSourcePath, EfsVolumeConfiguration efs) { +public record Volume(String name, String hostSourcePath, EfsVolumeConfiguration efs, + Map unparsed) { /** Convenience constructor for a {@code host} volume (no EFS configuration). */ public Volume(String name, String hostSourcePath) { - this(name, hostSourcePath, null); + this(name, hostSourcePath, null, null); + } + + public Volume(String name, String hostSourcePath, EfsVolumeConfiguration efs) { + this(name, hostSourcePath, efs, null); } } diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationEcsDeleteAfterRestoreIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationEcsDeleteAfterRestoreIntegrationTest.java index 5f56a8a193..efdb2015ba 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationEcsDeleteAfterRestoreIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationEcsDeleteAfterRestoreIntegrationTest.java @@ -41,7 +41,8 @@ class CloudFormationEcsDeleteAfterRestoreIntegrationTest { // it through the ECS API so ECS no longer has the record the stack still references. These // run unauthenticated, like CreateStack/DeleteStack, so they share the same account namespace. ecs("DeregisterTaskDefinition", "{\"taskDefinition\":\"" + family + "\"}"); - ecs("DeleteTaskDefinitions", "{\"taskDefinitions\":[\"" + family + "\"]}"); + // DeleteTaskDefinitions takes a revision, never a bare family. + ecs("DeleteTaskDefinitions", "{\"taskDefinitions\":[\"" + family + ":1\"]}"); deleteStack(stack); @@ -62,7 +63,9 @@ class CloudFormationEcsDeleteAfterRestoreIntegrationTest { // The cluster still has a running task at delete time (a genuine ClusterContainsTasksException), // which must NOT be treated as already-gone. ECS runs in mock mode under test, so the task is // in-memory RUNNING with no container behind it. - ecs("RunTask", "{\"cluster\":\"" + cluster + "\",\"taskDefinition\":\"" + family + "\",\"count\":1}"); + ecs("RunTask", "{\"cluster\":\"" + cluster + "\",\"taskDefinition\":\"" + family + "\",\"count\":1," + + "\"networkConfiguration\":{\"awsvpcConfiguration\":" + + "{\"subnets\":[\"subnet-default-us-east-1-a\"]}}}"); deleteStack(stack); diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServiceTest.java index ef4354e7b7..bcbd75fff7 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServiceTest.java @@ -491,6 +491,84 @@ class Ec2ServiceTest { assertEquals(1, retry.getInstances().size()); } + /** + * An interface a service holds on the caller's behalf, an ECS task's ENI being the one this + * emulator allocates, is {@code in-use}: DescribeNetworkInterfaces documents an unattached + * interface as {@code available} and an attached one as {@code in-use}, so left + * {@code available} it would answer a caller looking for a free interface. No attachment is + * synthesised, every member AWS documents on one naming an instance the task does not have, + * and the read-time reconciliation that frees an interface whose instance died therefore has + * nothing to act on here. + */ + @Test + void aServiceHeldInterfaceStaysInUseUntilItIsReleased() { + Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class), + mock(Ec2PortForwardManager.class), mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class), + new Ec2InstanceTypeCatalog(), new InMemoryStorageFactory()); + String subnetId = service.describeSubnets("us-east-1", List.of(), Map.of()) + .getFirst().getSubnetId(); + NetworkInterface eni = service.createNetworkInterface("us-east-1", subnetId, null, + null, List.of(), List.of(), List.of()); + String eniId = eni.getNetworkInterfaceId(); + assertEquals("available", eni.getStatus()); + + service.holdNetworkInterfaceForService("us-east-1", eniId); + + assertEquals("in-use", readInterface(service, eniId).getStatus()); + assertNull(readInterface(service, eniId).getAttachment()); + assertTrue(service.describeNetworkInterfaces("us-east-1", List.of(), + Map.of("status", List.of("available")), 0, null) + .networkInterfaces().stream() + .noneMatch(n -> eniId.equals(n.getNetworkInterfaceId()))); + + // AWS does not let the account delete an interface a task holds, so a teardown has to + // release it first. + AwsException inUse = assertThrows(AwsException.class, + () -> service.deleteNetworkInterface("us-east-1", eniId)); + assertEquals("InvalidParameterValue", inUse.getErrorCode()); + + service.releaseNetworkInterfaceFromService("us-east-1", eniId); + + assertEquals("available", readInterface(service, eniId).getStatus()); + assertDoesNotThrow(() -> service.deleteNetworkInterface("us-east-1", eniId)); + // Releasing an interface that is already gone is a no-op, so a second teardown is harmless. + assertDoesNotThrow(() -> service.releaseNetworkInterfaceFromService("us-east-1", eniId)); + } + + /** + * The service hold must not reach an interface an instance owns: releasing one of those is + * DetachNetworkInterface's job, and it has an instance-side copy to clear as well. + */ + @Test + void aServiceHoldLeavesAnInstanceHeldInterfaceAlone() { + Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class), + mock(Ec2PortForwardManager.class), mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class), + new Ec2InstanceTypeCatalog(), new InMemoryStorageFactory()); + String subnetId = service.describeSubnets("us-east-1", List.of(), Map.of()) + .getFirst().getSubnetId(); + NetworkInterface eni = service.createNetworkInterface("us-east-1", subnetId, null, + null, List.of(), List.of(), List.of()); + Reservation reservation = service.runInstances("us-east-1", "ami-1234567890abcdef0", "t3.micro", + 1, 1, null, List.of(), null, null, List.of(), null, null, null, + eni.getNetworkInterfaceId(), 0); + String instanceId = reservation.getInstances().getFirst().getInstanceId(); + + AwsException held = assertThrows(AwsException.class, + () -> service.holdNetworkInterfaceForService("us-east-1", eni.getNetworkInterfaceId())); + assertEquals("InvalidNetworkInterface.InUse", held.getErrorCode()); + + service.releaseNetworkInterfaceFromService("us-east-1", eni.getNetworkInterfaceId()); + + NetworkInterface after = readInterface(service, eni.getNetworkInterfaceId()); + assertEquals("in-use", after.getStatus()); + assertEquals(instanceId, after.getAttachment().getInstanceId()); + } + + private static NetworkInterface readInterface(Ec2Service service, String networkInterfaceId) { + return service.describeNetworkInterfaces("us-east-1", List.of(networkInterfaceId), Map.of(), 0, null) + .networkInterfaces().getFirst(); + } + /** * A NetworkInterface can carry a real GroupIdentifier entry whose groupId is null (a name-only * association). The group-id filter must skip that entry instead of NPE-ing on 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 new file mode 100644 index 0000000000..f466162fa9 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/ecs/EcsFargateEdgeCaseIntegrationTest.java @@ -0,0 +1,609 @@ +package io.github.hectorvent.floci.services.ecs; + +import io.github.hectorvent.floci.testing.RestAssuredJsonUtils; +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.response.Response; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.util.Map; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasItems; +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.not; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.nullValue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * The edges of the Fargate rules: the boundary values of the documented ranges, the parameters + * that are only invalid in combination, and the limits AWS puts on a single call. + */ +@QuarkusTest +class EcsFargateEdgeCaseIntegrationTest { + + private static final String TARGET = "AmazonEC2ContainerServiceV20141113."; + private static final String CT = "application/x-amz-json-1.1"; + private static final String CLUSTER = "fargate-edge-cluster"; + private static final String NETWORK = + "\"networkConfiguration\":{\"awsvpcConfiguration\":{\"subnets\":" + + "[\"subnet-default-us-east-1-a\"]}}"; + + @BeforeAll + static void configure() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + private static Response call(String action, String body, int expectedStatus) { + return given().contentType(CT).header("X-Amz-Target", TARGET + action) + .body(body) + .when().post("/") + .then().statusCode(expectedStatus) + .extract().response(); + } + + private static void registerSize(String family, String cpu, String memory, int expectedStatus) { + call("RegisterTaskDefinition", "{\"family\":\"" + family + "\"," + + "\"requiresCompatibilities\":[\"FARGATE\"],\"networkMode\":\"awsvpc\"," + + "\"cpu\":\"" + cpu + "\",\"memory\":\"" + memory + "\"," + + "\"containerDefinitions\":[{\"name\":\"app\",\"image\":\"nginx:latest\"}]}", + expectedStatus); + } + + private static String seed(String family) { + call("CreateCluster", "{\"clusterName\":\"" + CLUSTER + "\"}", 200); + registerSize(family, "256", "512", 200); + return family; + } + + // ── Task size ───────────────────────────────────────────────────────────── + + @Test + void theEdgesOfEveryFargateSizeRangeAreAccepted() { + registerSize("edge-256-low", "256", "512", 200); + registerSize("edge-256-high", "256", "2048", 200); + registerSize("edge-512-low", "512", "1024", 200); + registerSize("edge-512-high", "512", "4096", 200); + registerSize("edge-2048-low", "2048", "4096", 200); + registerSize("edge-2048-high", "2048", "16384", 200); + registerSize("edge-4096-high", "4096", "30720", 200); + registerSize("edge-8192-low", "8192", "16384", 200); + registerSize("edge-16384-high", "16384", "122880", 200); + } + + @Test + void justOutsideEveryFargateSizeRangeIsRejected() { + registerSize("edge-256-below", "256", "256", 400); + registerSize("edge-256-above", "256", "3072", 400); + registerSize("edge-512-below", "512", "512", 400); + registerSize("edge-512-above", "512", "5120", 400); + registerSize("edge-4096-above", "4096", "31744", 400); + registerSize("edge-16384-above", "16384", "131072", 400); + registerSize("edge-unknown-cpu", "384", "1024", 400); + } + + @Test + void theThirtyTwoVcpuSizesAreTheThreeFargateOffers() { + registerSize("edge-32vcpu-60", "32768", "61440", 200); + registerSize("edge-32vcpu-120", "32768", "122880", 200); + registerSize("edge-32vcpu-244", "32768", "249856", 200); + // 32 vCPU is not a range: anything between the three offers is not a configuration. + registerSize("edge-32vcpu-between", "32768", "65536", 400); + } + + @Test + void theStringFormsOfCpuAndMemoryAreAccepted() { + registerSize("edge-vcpu-string", "0.5 vCPU", "1 GB", 200); + registerSize("edge-vcpu-lowercase", "1 vcpu", "2GB", 200); + } + + // ── Ephemeral storage ───────────────────────────────────────────────────── + + @Test + void ephemeralStorageIsAcceptedAtBothEndsOfItsRange() { + String body = "{\"family\":\"edge-storage-%s\",\"requiresCompatibilities\":[\"FARGATE\"]," + + "\"networkMode\":\"awsvpc\",\"cpu\":\"256\",\"memory\":\"512\"," + + "\"ephemeralStorage\":{\"sizeInGiB\":%d}," + + "\"containerDefinitions\":[{\"name\":\"app\",\"image\":\"nginx:latest\"}]}"; + + call("RegisterTaskDefinition", body.formatted("min", 21), 200); + call("RegisterTaskDefinition", body.formatted("max", 200), 200); + call("RegisterTaskDefinition", body.formatted("below", 20), 400); + call("RegisterTaskDefinition", body.formatted("above", 201), 400); + } + + // ── Parameters Fargate does not support ─────────────────────────────────── + + @Test + void everyFargateUnsupportedParameterIsRejected() { + String container = "{\"family\":\"edge-unsupported-%s\"," + + "\"requiresCompatibilities\":[\"FARGATE\"],\"networkMode\":\"awsvpc\"," + + "\"cpu\":\"256\",\"memory\":\"512\",\"containerDefinitions\":" + + "[{\"name\":\"app\",\"image\":\"nginx:latest\",%s}]}"; + + call("RegisterTaskDefinition", + container.formatted("dso", "\"dockerSecurityOptions\":[\"label:user:jdoe\"]"), 400) + .then().body("message", containsString("dockerSecurityOptions")); + call("RegisterTaskDefinition", + container.formatted("hosts", "\"extraHosts\":[{\"hostname\":\"db\",\"ipAddress\":\"10.0.0.9\"}]"), 400) + .then().body("message", containsString("extraHosts")); + call("RegisterTaskDefinition", + container.formatted("gpu", "\"resourceRequirements\":[{\"type\":\"GPU\",\"value\":\"1\"}]"), 400) + .then().body("message", containsString("gpu")); + call("RegisterTaskDefinition", + container.formatted("swap", "\"linuxParameters\":{\"maxSwap\":128}"), 400) + .then().body("message", containsString("maxSwap")); + call("RegisterTaskDefinition", + container.formatted("swappiness", "\"linuxParameters\":{\"swappiness\":10}"), 400) + .then().body("message", containsString("swappiness")); + + call("RegisterTaskDefinition", "{\"family\":\"edge-unsupported-placement\"," + + "\"requiresCompatibilities\":[\"FARGATE\"],\"networkMode\":\"awsvpc\"," + + "\"cpu\":\"256\",\"memory\":\"512\"," + + "\"placementConstraints\":[{\"type\":\"memberOf\",\"expression\":\"attribute:ecs.os-type==linux\"}]," + + "\"containerDefinitions\":[{\"name\":\"app\",\"image\":\"nginx:latest\"}]}", 400) + .then().body("message", containsString("placementConstraints")); + } + + @Test + void pidModeTaskIsTheOnlyOneFargateAccepts() { + String body = "{\"family\":\"edge-pidmode-%s\",\"requiresCompatibilities\":[\"FARGATE\"]," + + "\"networkMode\":\"awsvpc\",\"cpu\":\"256\",\"memory\":\"512\",\"pidMode\":\"%s\"," + + "\"containerDefinitions\":[{\"name\":\"app\",\"image\":\"nginx:latest\"}]}"; + + call("RegisterTaskDefinition", body.formatted("task", "task"), 200); + call("RegisterTaskDefinition", body.formatted("host", "host"), 400) + .then().body("message", containsString("pidMode")); + } + + @Test + void aDependencyCycleIsRejectedAtRegistration() { + call("RegisterTaskDefinition", "{\"family\":\"edge-cycle\"," + + "\"requiresCompatibilities\":[\"FARGATE\"],\"networkMode\":\"awsvpc\"," + + "\"cpu\":\"256\",\"memory\":\"512\",\"containerDefinitions\":[" + + "{\"name\":\"a\",\"image\":\"busybox\"," + + "\"dependsOn\":[{\"containerName\":\"b\",\"condition\":\"START\"}]}," + + "{\"name\":\"b\",\"image\":\"busybox\"," + + "\"dependsOn\":[{\"containerName\":\"a\",\"condition\":\"START\"}]}]}", 400) + .then().body("message", containsString("cycle")); + } + + // ── RunTask limits ──────────────────────────────────────────────────────── + + @Test + void runTaskPlacesAtMostTenTasksPerCall() { + String family = seed("edge-count"); + + Response ten = call("RunTask", "{\"cluster\":\"" + CLUSTER + "\",\"taskDefinition\":\"" + + family + "\",\"count\":10,\"launchType\":\"FARGATE\"," + NETWORK + "}", 200); + ten.then().body("tasks", hasSize(10)); + + call("RunTask", "{\"cluster\":\"" + CLUSTER + "\",\"taskDefinition\":\"" + family + + "\",\"count\":11,\"launchType\":\"FARGATE\"," + NETWORK + "}", 400) + .then().body("message", containsString("between 1 and 10")); + call("RunTask", "{\"cluster\":\"" + CLUSTER + "\",\"taskDefinition\":\"" + family + + "\",\"count\":0,\"launchType\":\"FARGATE\"," + NETWORK + "}", 400); + + ten.jsonPath().getList("tasks.taskArn", String.class).forEach(taskArn -> + call("StopTask", "{\"cluster\":\"" + CLUSTER + "\",\"task\":\"" + taskArn + "\"}", 200)); + } + + @Test + void propagatingServiceTagsIsRefusedForAStandaloneTask() { + String family = seed("edge-propagate"); + + call("RunTask", "{\"cluster\":\"" + CLUSTER + "\",\"taskDefinition\":\"" + family + + "\",\"launchType\":\"FARGATE\"," + NETWORK + ",\"propagateTags\":\"SERVICE\"}", 400) + .then().body("message", containsString("SERVICE")); + } + + @Test + void propagatingTaskDefinitionTagsCopiesThemOntoTheTask() { + call("CreateCluster", "{\"clusterName\":\"" + CLUSTER + "\"}", 200); + call("RegisterTaskDefinition", "{\"family\":\"edge-td-tags\"," + + "\"requiresCompatibilities\":[\"FARGATE\"],\"networkMode\":\"awsvpc\"," + + "\"cpu\":\"256\",\"memory\":\"512\",\"tags\":[{\"key\":\"owner\",\"value\":\"platform\"}]," + + "\"containerDefinitions\":[{\"name\":\"app\",\"image\":\"nginx:latest\"}]}", 200); + + call("RunTask", "{\"cluster\":\"" + CLUSTER + "\",\"taskDefinition\":\"edge-td-tags\"," + + "\"launchType\":\"FARGATE\"," + NETWORK + ",\"propagateTags\":\"TASK_DEFINITION\"}", 200) + .then() + .body("tasks[0].tags[0].key", equalTo("owner")) + .body("tasks[0].tags[0].value", equalTo("platform")); + } + + /** + * The ENI allocation reaches into EC2, whose not-found codes RunTask does not declare. An SDK + * given {@code InvalidSubnetID.NotFound} sees an unmodelled failure instead of the + * InvalidParameterException AWS returns for a subnet that is not there. + */ + @Test + void runTaskRejectsAnUnknownSubnetAsAnInvalidParameter() { + String family = seed("edge-unknown-subnet"); + + call("RunTask", "{\"cluster\":\"" + CLUSTER + "\",\"taskDefinition\":\"" + family + + "\",\"launchType\":\"FARGATE\",\"networkConfiguration\":{\"awsvpcConfiguration\":" + + "{\"subnets\":[\"subnet-does-not-exist\"]}}}", 400) + .then() + .body("__type", containsString("InvalidParameterException")) + .body("message", containsString("subnet-does-not-exist")); + } + + @Test + void runTaskRejectsAnUnknownSecurityGroupAsAnInvalidParameter() { + String family = seed("edge-unknown-sg"); + + call("RunTask", "{\"cluster\":\"" + CLUSTER + "\",\"taskDefinition\":\"" + family + + "\",\"launchType\":\"FARGATE\",\"networkConfiguration\":{\"awsvpcConfiguration\":" + + "{\"subnets\":[\"subnet-default-us-east-1-a\"],\"securityGroups\":[\"sg-nope\"]}}}", 400) + .then() + .body("__type", containsString("InvalidParameterException")) + .body("message", containsString("sg-nope")); + } + + /** + * MANAGED_INSTANCES joined LaunchType and Compatibility in the ECS model. Rejecting it would + * 400 a request the SDK considers valid. + */ + @Test + void managedInstancesIsAcceptedAsACompatibilityAndALaunchType() { + call("CreateCluster", "{\"clusterName\":\"" + CLUSTER + "\"}", 200); + call("RegisterTaskDefinition", "{\"family\":\"edge-managed-instances\"," + + "\"requiresCompatibilities\":[\"EC2\",\"MANAGED_INSTANCES\"]," + + "\"containerDefinitions\":[{\"name\":\"app\",\"image\":\"nginx:latest\"," + + "\"memory\":512}]}", 200) + .then().body("taskDefinition.requiresCompatibilities", hasItems("MANAGED_INSTANCES")); + + call("RunTask", "{\"cluster\":\"" + CLUSTER + "\",\"taskDefinition\":\"edge-managed-instances\"," + + "\"launchType\":\"MANAGED_INSTANCES\"}", 200) + .then().body("tasks[0].launchType", equalTo("MANAGED_INSTANCES")); + } + + // ── Capacity provider strategy ──────────────────────────────────────────── + + @Test + void aStrategyWithTwoBasesIsRejected() { + String family = seed("edge-two-bases"); + + call("RunTask", "{\"cluster\":\"" + CLUSTER + "\",\"taskDefinition\":\"" + family + "\"," + + NETWORK + ",\"capacityProviderStrategy\":[" + + "{\"capacityProvider\":\"FARGATE\",\"base\":1,\"weight\":1}," + + "{\"capacityProvider\":\"FARGATE_SPOT\",\"base\":1,\"weight\":1}]}", 400) + .then().body("message", containsString("base")); + } + + @Test + void aLoneProviderOfWeightZeroStillPlacesEveryTask() { + String family = seed("edge-zero-weight"); + + Response response = call("RunTask", "{\"cluster\":\"" + CLUSTER + "\",\"taskDefinition\":\"" + + family + "\",\"count\":3," + NETWORK + ",\"capacityProviderStrategy\":" + + "[{\"capacityProvider\":\"FARGATE_SPOT\",\"weight\":0}]}", 200); + + List providers = response.jsonPath().getList("tasks.capacityProviderName"); + assertEquals(3, providers.size(), "a weightless strategy must still place every task"); + assertTrue(providers.stream().allMatch("FARGATE_SPOT"::equals), providers.toString()); + } + + @Test + void aStrategyWhoseProvidersAllWeighZeroIsRejected() { + String family = seed("edge-all-zero-weights"); + + call("RunTask", "{\"cluster\":\"" + CLUSTER + "\",\"taskDefinition\":\"" + family + "\"," + + NETWORK + ",\"capacityProviderStrategy\":[" + + "{\"capacityProvider\":\"FARGATE\",\"weight\":0}," + + "{\"capacityProvider\":\"FARGATE_SPOT\",\"weight\":0}]}", 400) + .then().body("message", containsString("weight greater than zero")); + } + + @Test + void aStrategyEntryOutsideTheWeightAndBaseRangesIsRejected() { + String family = seed("edge-strategy-ranges"); + + call("RunTask", "{\"cluster\":\"" + CLUSTER + "\",\"taskDefinition\":\"" + family + "\"," + + NETWORK + ",\"capacityProviderStrategy\":" + + "[{\"capacityProvider\":\"FARGATE\",\"weight\":1001}]}", 400) + .then().body("message", containsString("between 0 and 1000")); + call("RunTask", "{\"cluster\":\"" + CLUSTER + "\",\"taskDefinition\":\"" + family + "\"," + + NETWORK + ",\"capacityProviderStrategy\":" + + "[{\"capacityProvider\":\"FARGATE\",\"weight\":1,\"base\":100001}]}", 400) + .then().body("message", containsString("between 0 and 100000")); + + call("RunTask", "{\"cluster\":\"" + CLUSTER + "\",\"taskDefinition\":\"" + family + "\"," + + NETWORK + ",\"capacityProviderStrategy\":" + + "[{\"capacityProvider\":\"FARGATE\",\"weight\":1000,\"base\":100000}]}", 200) + .then().body("tasks[0].capacityProviderName", equalTo("FARGATE")); + } + + @Test + void aStrategyOfMoreThanTwentyProvidersIsRejected() { + String family = seed("edge-strategy-size"); + StringBuilder strategy = new StringBuilder(); + for (int i = 0; i < 21; i++) { + strategy.append(i == 0 ? "" : ",") + .append("{\"capacityProvider\":\"FARGATE\",\"weight\":1}"); + } + + call("RunTask", "{\"cluster\":\"" + CLUSTER + "\",\"taskDefinition\":\"" + family + "\"," + + NETWORK + ",\"capacityProviderStrategy\":[" + strategy + "]}", 400) + .then().body("message", containsString("maximum of 20 capacity providers")); + } + + @Test + void anEmptyStrategyFallsBackToTheLaunchType() { + String family = seed("edge-empty-strategy"); + + call("RunTask", "{\"cluster\":\"" + CLUSTER + "\",\"taskDefinition\":\"" + family + + "\",\"launchType\":\"FARGATE\"," + NETWORK + ",\"capacityProviderStrategy\":[]}", 200) + .then().body("tasks[0].launchType", equalTo("FARGATE")); + } + + // ── Task shape ──────────────────────────────────────────────────────────── + + @Test + void aStoppedTaskReportsTheTimestampsAndCodesAwsReports() { + String family = seed("edge-stopped-shape"); + String taskArn = call("RunTask", "{\"cluster\":\"" + CLUSTER + "\",\"taskDefinition\":\"" + + family + "\",\"launchType\":\"FARGATE\"," + NETWORK + "}", 200) + .jsonPath().getString("tasks[0].taskArn"); + + Response stopped = call("StopTask", "{\"cluster\":\"" + CLUSTER + "\",\"task\":\"" + + taskArn + "\",\"reason\":\"edge\"}", 200); + + stopped.then() + .body("task.stopCode", equalTo("UserInitiated")) + .body("task.lastStatus", equalTo("STOPPED")); + assertTrue(stopped.jsonPath().getDouble("task.stoppingAt") > 0, + "stoppingAt must be reported for a task that went through STOPPING"); + assertTrue(stopped.jsonPath().getDouble("task.executionStoppedAt") > 0, + "executionStoppedAt must be reported"); + } + + @Test + void aFargateTaskReportsBothEphemeralStorageMembersAndZeroCpuContainers() { + String family = seed("edge-storage-members"); + + call("RunTask", "{\"cluster\":\"" + CLUSTER + "\",\"taskDefinition\":\"" + family + + "\",\"launchType\":\"FARGATE\"," + NETWORK + "}", 200) + .then() + .body("tasks[0].ephemeralStorage.sizeInGiB", equalTo(20)) + .body("tasks[0].fargateEphemeralStorage.sizeInGiB", equalTo(20)) + // A container definition without cpu units reports zero, not nothing. + .body("tasks[0].containers[0].cpu", equalTo("0")); + } + + @Test + void describeTasksReportsTagsOnlyWhenTheyAreAskedFor() { + String family = seed("edge-describe-tags"); + String taskArn = call("RunTask", "{\"cluster\":\"" + CLUSTER + "\",\"taskDefinition\":\"" + + family + "\",\"launchType\":\"FARGATE\"," + NETWORK + + ",\"tags\":[{\"key\":\"owner\",\"value\":\"platform\"}]}", 200) + .jsonPath().getString("tasks[0].taskArn"); + + call("DescribeTasks", "{\"cluster\":\"" + CLUSTER + "\",\"tasks\":[\"" + taskArn + "\"]}", 200) + .then().body("tasks[0].tags", nullValue()); + + call("DescribeTasks", "{\"cluster\":\"" + CLUSTER + "\",\"tasks\":[\"" + taskArn + + "\"],\"include\":[\"TAGS\"]}", 200) + .then().body("tasks[0].tags[0].key", equalTo("owner")); + } + + @Test + void aTaskAlwaysReportsAnOverrideEntryPerContainer() { + call("CreateCluster", "{\"clusterName\":\"" + CLUSTER + "\"}", 200); + call("RegisterTaskDefinition", "{\"family\":\"edge-overrides\"," + + "\"requiresCompatibilities\":[\"FARGATE\"],\"networkMode\":\"awsvpc\"," + + "\"cpu\":\"256\",\"memory\":\"512\",\"containerDefinitions\":[" + + "{\"name\":\"app\",\"image\":\"nginx:latest\"}," + + "{\"name\":\"sidecar\",\"image\":\"busybox\",\"essential\":false}]}", 200); + + // Nothing was overridden, and AWS still lists every container under overrides. + call("RunTask", "{\"cluster\":\"" + CLUSTER + "\",\"taskDefinition\":\"edge-overrides\"," + + "\"launchType\":\"FARGATE\"," + NETWORK + "}", 200) + .then() + .body("tasks[0].overrides.containerOverrides", hasSize(2)) + .body("tasks[0].overrides.containerOverrides[0].name", equalTo("app")) + .body("tasks[0].overrides.containerOverrides[1].name", equalTo("sidecar")); + } + + @Test + void anAwsvpcTaskReportsTheAttachmentDetailsAwsReports() { + String family = seed("edge-attachment-details"); + Response response = call("RunTask", "{\"cluster\":\"" + CLUSTER + "\",\"taskDefinition\":\"" + + family + "\",\"launchType\":\"FARGATE\"," + NETWORK + "}", 200); + + List names = response.jsonPath().getList("tasks[0].attachments[0].details.name"); + assertTrue(names.containsAll(List.of("subnetId", "networkInterfaceId", "macAddress", + "privateDnsName", "privateIPv4Address")), + "the attachment must carry the details AWS reports, got: " + names); + } + + // ── Service updates ────────────────────────────────────────────────────── + + private static String deploymentId(String serviceName) { + return call("DescribeServices", "{\"cluster\":\"" + CLUSTER + "\",\"services\":[\"" + + serviceName + "\"]}", 200) + .jsonPath().getString("services[0].deployments[0].id"); + } + + // ── Task definition lifecycle ───────────────────────────────────────────── + + @Test + void aDeletedRevisionStaysDescribableAsDeleteInProgress() { + registerSize("edge-delete-lifecycle", "256", "512", 200); + + // Deleting before deregistering is refused, and a family without a revision is not a + // reference this API takes. + call("DeleteTaskDefinitions", "{\"taskDefinitions\":[\"edge-delete-lifecycle:1\"]}", 400) + .then().body("message", containsString("INACTIVE")); + call("DeregisterTaskDefinition", "{\"taskDefinition\":\"edge-delete-lifecycle:1\"}", 200) + .then().body("taskDefinition.status", equalTo("INACTIVE")); + call("DeleteTaskDefinitions", "{\"taskDefinitions\":[\"edge-delete-lifecycle\"]}", 400) + .then().body("message", containsString("revision")); + + call("DeleteTaskDefinitions", "{\"taskDefinitions\":[\"edge-delete-lifecycle:1\"]}", 200) + .then().body("taskDefinitions[0].status", equalTo("DELETE_IN_PROGRESS")); + + // The revision is still describable, and carries the lifecycle timestamps. + Response described = call("DescribeTaskDefinition", + "{\"taskDefinition\":\"edge-delete-lifecycle:1\"}", 200); + described.then().body("taskDefinition.status", equalTo("DELETE_IN_PROGRESS")); + assertTrue(described.jsonPath().getDouble("taskDefinition.deregisteredAt") > 0, + "a deregistered revision reports deregisteredAt"); + assertTrue(described.jsonPath().getDouble("taskDefinition.deleteRequestedAt") > 0, + "a revision being deleted reports deleteRequestedAt"); + + // And it can no longer start anything new. + call("RunTask", "{\"cluster\":\"" + CLUSTER + "\",\"taskDefinition\":\"edge-delete-lifecycle:1\"," + + "\"launchType\":\"FARGATE\"," + NETWORK + "}", 400) + .then().body("message", containsString("being deleted")); + } + + @Test + void describeTasksReportsAnUnknownTaskAsMissingRatherThanDroppingIt() { + call("CreateCluster", "{\"clusterName\":\"" + CLUSTER + "\"}", 200); + + call("DescribeTasks", "{\"cluster\":\"" + CLUSTER + "\",\"tasks\":[\"00000000000000000000000000000000\"]}", 200) + .then() + .body("tasks", hasSize(0)) + .body("failures", hasSize(1)) + .body("failures[0].reason", equalTo("MISSING")); + } + + // ── Derived compatibilities and requiresAttributes ──────────────────────── + + @Test + void compatibilitiesAreDerivedFromTheDefinitionNotJustEchoed() { + // Fargate-valid but never asked for FARGATE: ECS still reports the launch types it works on. + call("RegisterTaskDefinition", "{\"family\":\"edge-compat-implicit\",\"networkMode\":\"awsvpc\"," + + "\"cpu\":\"256\",\"memory\":\"512\",\"containerDefinitions\":" + + "[{\"name\":\"app\",\"image\":\"nginx:latest\"}]}", 200) + .then().body("taskDefinition.compatibilities", equalTo(List.of("EC2", "FARGATE"))); + + // awsvpc rules out EXTERNAL; bridge rules out FARGATE and allows EXTERNAL. + call("RegisterTaskDefinition", "{\"family\":\"edge-compat-bridge\",\"networkMode\":\"bridge\"," + + "\"containerDefinitions\":[{\"name\":\"app\",\"image\":\"nginx:latest\",\"memory\":128}]}", 200) + .then().body("taskDefinition.compatibilities", equalTo(List.of("EC2", "EXTERNAL"))); + + // awsvpc without a Fargate size pair is EC2 only. + call("RegisterTaskDefinition", "{\"family\":\"edge-compat-nosize\",\"networkMode\":\"awsvpc\"," + + "\"containerDefinitions\":[{\"name\":\"app\",\"image\":\"nginx:latest\",\"memory\":128}]}", 200) + .then().body("taskDefinition.compatibilities", equalTo(List.of("EC2"))); + } + + @Test + void requiresAttributesNamesTheCapabilitiesTheDefinitionUses() { + call("RegisterTaskDefinition", "{\"family\":\"edge-attrs\",\"networkMode\":\"awsvpc\"," + + "\"cpu\":\"256\",\"memory\":\"512\"," + + "\"taskRoleArn\":\"arn:aws:iam::000000000000:role/task\"," + + "\"containerDefinitions\":[{\"name\":\"app\"," + + "\"image\":\"000000000000.dkr.ecr.us-east-1.amazonaws.com/app:1\"," + + "\"logConfiguration\":{\"logDriver\":\"awslogs\",\"options\":{}}}]}", 200) + .then() + .body("taskDefinition.requiresAttributes.name", hasItems( + "com.amazonaws.ecs.capability.docker-remote-api.1.18", + "ecs.capability.task-eni", + "com.amazonaws.ecs.capability.task-iam-role", + "com.amazonaws.ecs.capability.ecr-auth", + "com.amazonaws.ecs.capability.logging-driver.awslogs")); + + // A task role under host networking has its own capability name. + call("RegisterTaskDefinition", "{\"family\":\"edge-attrs-host\",\"networkMode\":\"host\"," + + "\"taskRoleArn\":\"arn:aws:iam::000000000000:role/task\"," + + "\"containerDefinitions\":[{\"name\":\"app\",\"image\":\"nginx:latest\",\"memory\":128}]}", 200) + .then() + .body("taskDefinition.requiresAttributes.name", hasItems( + "com.amazonaws.ecs.capability.task-iam-role-network-host")) + .body("taskDefinition.requiresAttributes.name", not(hasItems("ecs.capability.task-eni"))); + } + + @Test + void startTaskRequiresContainerInstances() { + String family = seed("edge-start-task"); + + call("StartTask", "{\"cluster\":\"" + CLUSTER + "\",\"taskDefinition\":\"" + family + "\"}", 400) + .then().body("message", containsString("containerInstances")); + } + + // ── Capacity providers ─────────────────────────────────────────────────── + + // ── Round trips the parser used to drop ────────────────────────────────── + + @Test + void aPortMappingRoundTripsItsServiceConnectMembers() { + call("CreateCluster", "{\"clusterName\":\"" + CLUSTER + "\"}", 200); + call("RegisterTaskDefinition", "{\"family\":\"edge-portmapping\"," + + "\"requiresCompatibilities\":[\"FARGATE\"],\"networkMode\":\"awsvpc\"," + + "\"cpu\":\"256\",\"memory\":\"512\"," + + "\"containerDefinitions\":[{\"name\":\"app\",\"image\":\"nginx:latest\"," + + "\"portMappings\":[{\"containerPort\":8080,\"protocol\":\"tcp\"," + + "\"name\":\"api\",\"appProtocol\":\"http\"}]}]}", 200); + + // name and appProtocol are what a service's serviceConnectConfiguration references, so + // losing them on the round trip breaks Service Connect. + call("DescribeTaskDefinition", "{\"taskDefinition\":\"edge-portmapping\"}", 200) + .then() + .body("taskDefinition.containerDefinitions[0].portMappings[0].name", equalTo("api")) + .body("taskDefinition.containerDefinitions[0].portMappings[0].appProtocol", + equalTo("http")) + .body("taskDefinition.containerDefinitions[0].portMappings[0].containerPort", + equalTo(8080)); + } + + @Test + void aVolumeRoundTripsTheConfigurationsFlociDoesNotBack() { + call("CreateCluster", "{\"clusterName\":\"" + CLUSTER + "\"}", 200); + call("RegisterTaskDefinition", "{\"family\":\"edge-volume-roundtrip\"," + + "\"containerDefinitions\":[{\"name\":\"app\",\"image\":\"nginx:latest\"}]," + + "\"volumes\":[{\"name\":\"docker-vol\",\"configuredAtLaunch\":false," + + "\"dockerVolumeConfiguration\":{\"scope\":\"shared\",\"autoprovision\":true," + + "\"driver\":\"local\"}}]}", 200); + + call("DescribeTaskDefinition", "{\"taskDefinition\":\"edge-volume-roundtrip\"}", 200) + .then() + .body("taskDefinition.volumes[0].name", equalTo("docker-vol")) + .body("taskDefinition.volumes[0].dockerVolumeConfiguration.scope", equalTo("shared")) + .body("taskDefinition.volumes[0].dockerVolumeConfiguration.driver", equalTo("local")) + .body("taskDefinition.volumes[0].configuredAtLaunch", equalTo(false)); + } + + // ── Request validation ─────────────────────────────────────────────────── + + @Test + void anEnumValueTheApiDoesNotHaveIsRejectedRatherThanIgnored() { + String family = seed("edge-bad-enum"); + + // Silently treating this as absent would place the task on Floci's default launch type, + // which is not what the caller asked for. + call("RunTask", "{\"cluster\":\"" + CLUSTER + "\",\"taskDefinition\":\"" + family + + "\",\"launchType\":\"EC22\"," + NETWORK + "}", 400) + .then().body("message", containsString("launchType")); + + call("RegisterTaskDefinition", "{\"family\":\"edge-bad-network-mode\"," + + "\"networkMode\":\"AWSVPC\"," + + "\"containerDefinitions\":[{\"name\":\"app\",\"image\":\"nginx:latest\"}]}", 400) + .then().body("message", containsString("networkMode")); + } + + @Test + void aResourceTakesAtMostFiftyTags() { + StringBuilder tags = new StringBuilder(); + for (int i = 0; i < 51; i++) { + tags.append(i > 0 ? "," : "") + .append("{\"key\":\"k").append(i).append("\",\"value\":\"v\"}"); + } + call("CreateCluster", "{\"clusterName\":\"edge-too-many-tags\",\"tags\":[" + tags + "]}", 400) + .then().body("message", containsString("50")); + + call("CreateCluster", "{\"clusterName\":\"edge-empty-tag-key\"," + + "\"tags\":[{\"key\":\"\",\"value\":\"v\"}]}", 400) + .then().body("message", containsString("Tag keys")); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/ecs/EcsFargateTaskDefinitionIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ecs/EcsFargateTaskDefinitionIntegrationTest.java new file mode 100644 index 0000000000..469970c161 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/ecs/EcsFargateTaskDefinitionIntegrationTest.java @@ -0,0 +1,220 @@ +package io.github.hectorvent.floci.services.ecs; + +import io.github.hectorvent.floci.testing.RestAssuredJsonUtils; +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.response.Response; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasSize; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * RegisterTaskDefinition for the Fargate launch type: the members a Fargate task definition + * carries must survive a round trip, and the ones Fargate has no equivalent for must be rejected + * at registration rather than at launch. + */ +@QuarkusTest +class EcsFargateTaskDefinitionIntegrationTest { + + private static final String TARGET = "AmazonEC2ContainerServiceV20141113."; + private static final String CT = "application/x-amz-json-1.1"; + + @BeforeAll + static void configure() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + private static Response call(String action, String body, int expectedStatus) { + return given().contentType(CT).header("X-Amz-Target", TARGET + action) + .body(body) + .when().post("/") + .then().statusCode(expectedStatus) + .extract().response(); + } + + private static Response register(String body, int expectedStatus) { + return call("RegisterTaskDefinition", body, expectedStatus); + } + + /** A Fargate-compatible definition with everything filled in but the named members replaced. */ + private static String fargateTaskDefinition(String family, String extraMembers) { + return "{\"family\":\"" + family + "\",\"requiresCompatibilities\":[\"FARGATE\"]," + + "\"networkMode\":\"awsvpc\",\"cpu\":\"256\",\"memory\":\"512\"," + + "\"containerDefinitions\":[{\"name\":\"app\",\"image\":\"nginx:latest\"}]" + + extraMembers + "}"; + } + + @Test + void registerTaskDefinitionRoundTripsEphemeralStorageAndPidMode() { + register(fargateTaskDefinition("fargate-ephemeral", + ",\"ephemeralStorage\":{\"sizeInGiB\":50},\"pidMode\":\"task\""), 200); + + call("DescribeTaskDefinition", "{\"taskDefinition\":\"fargate-ephemeral\"}", 200) + .then() + .body("taskDefinition.ephemeralStorage.sizeInGiB", equalTo(50)) + .body("taskDefinition.pidMode", equalTo("task")); + } + + @Test + void registerTaskDefinitionRoundTripsMembersFlociDoesNotActOn() { + // proxyConfiguration and the container's ulimits, linuxParameters and resourceRequirements + // have no local behaviour, but a client that wrote them reads them back or sees drift. + register("{\"family\":\"fargate-passthrough\",\"requiresCompatibilities\":[\"FARGATE\"]," + + "\"networkMode\":\"awsvpc\",\"cpu\":\"512\",\"memory\":\"1024\"," + + "\"proxyConfiguration\":{\"type\":\"APPMESH\",\"containerName\":\"envoy\"," + + "\"properties\":[{\"name\":\"AppPorts\",\"value\":\"8080\"}]}," + + "\"containerDefinitions\":[{\"name\":\"app\",\"image\":\"nginx:latest\"," + + "\"ulimits\":[{\"name\":\"nofile\",\"softLimit\":1024,\"hardLimit\":4096}]," + + "\"linuxParameters\":{\"initProcessEnabled\":true}," + + "\"systemControls\":[{\"namespace\":\"net.core.somaxconn\",\"value\":\"1024\"}]}]}", 200); + + call("DescribeTaskDefinition", "{\"taskDefinition\":\"fargate-passthrough\"}", 200) + .then() + .body("taskDefinition.proxyConfiguration.type", equalTo("APPMESH")) + .body("taskDefinition.proxyConfiguration.properties[0].name", equalTo("AppPorts")) + .body("taskDefinition.containerDefinitions[0].ulimits[0].name", equalTo("nofile")) + .body("taskDefinition.containerDefinitions[0].ulimits[0].softLimit", equalTo(1024)) + .body("taskDefinition.containerDefinitions[0].linuxParameters.initProcessEnabled", + equalTo(true)) + .body("taskDefinition.containerDefinitions[0].systemControls[0].namespace", + equalTo("net.core.somaxconn")); + } + + @Test + void registerTaskDefinitionRoundTripsTypedContainerMembers() { + register("{\"family\":\"fargate-container-members\",\"requiresCompatibilities\":[\"FARGATE\"]," + + "\"networkMode\":\"awsvpc\",\"cpu\":\"256\",\"memory\":\"512\"," + + "\"containerDefinitions\":[" + + "{\"name\":\"init\",\"image\":\"busybox\",\"essential\":false}," + + "{\"name\":\"app\",\"image\":\"nginx:latest\",\"user\":\"1000:1000\"," + + "\"workingDirectory\":\"/srv\",\"readonlyRootFilesystem\":true,\"stopTimeout\":30," + + "\"startTimeout\":120,\"dockerLabels\":{\"team\":\"platform\"}," + + "\"environmentFiles\":[{\"value\":\"arn:aws:s3:::cfg/app.env\",\"type\":\"s3\"}]," + + "\"repositoryCredentials\":{\"credentialsParameter\":\"arn:aws:secretsmanager:us-east-1:" + + "000000000000:secret:registry\"}," + + "\"dependsOn\":[{\"containerName\":\"init\",\"condition\":\"SUCCESS\"}]}]}", 200); + + call("DescribeTaskDefinition", "{\"taskDefinition\":\"fargate-container-members\"}", 200) + .then() + .body("taskDefinition.containerDefinitions[1].user", equalTo("1000:1000")) + .body("taskDefinition.containerDefinitions[1].workingDirectory", equalTo("/srv")) + .body("taskDefinition.containerDefinitions[1].readonlyRootFilesystem", equalTo(true)) + .body("taskDefinition.containerDefinitions[1].stopTimeout", equalTo(30)) + .body("taskDefinition.containerDefinitions[1].startTimeout", equalTo(120)) + .body("taskDefinition.containerDefinitions[1].dockerLabels.team", equalTo("platform")) + .body("taskDefinition.containerDefinitions[1].environmentFiles", hasSize(1)) + .body("taskDefinition.containerDefinitions[1].environmentFiles[0].type", equalTo("s3")) + .body("taskDefinition.containerDefinitions[1].repositoryCredentials.credentialsParameter", + containsString("secret:registry")) + .body("taskDefinition.containerDefinitions[1].dependsOn[0].containerName", equalTo("init")) + .body("taskDefinition.containerDefinitions[1].dependsOn[0].condition", equalTo("SUCCESS")); + } + + @Test + void registerTaskDefinitionReportsRegistrationMetadata() { + Response response = register(fargateTaskDefinition("fargate-registered-at", ""), 200); + assertTrue(response.jsonPath().getDouble("taskDefinition.registeredAt") > 0, + "registeredAt must be reported as an epoch timestamp"); + assertTrue(response.jsonPath().getString("taskDefinition.registeredBy").startsWith("arn:"), + "registeredBy must be an ARN"); + } + + @Test + void registerTaskDefinitionRejectsEphemeralStorageOutsideTheFargateRange() { + register(fargateTaskDefinition("fargate-storage-small", ",\"ephemeralStorage\":{\"sizeInGiB\":10}"), 400) + .then().body("message", containsString("ephemeral storage")); + register(fargateTaskDefinition("fargate-storage-large", ",\"ephemeralStorage\":{\"sizeInGiB\":300}"), 400) + .then().body("message", containsString("ephemeral storage")); + } + + @Test + void registerTaskDefinitionRejectsParametersFargateDoesNotSupport() { + String prefix = "{\"family\":\"fargate-unsupported\",\"requiresCompatibilities\":[\"FARGATE\"]," + + "\"networkMode\":\"awsvpc\",\"cpu\":\"256\",\"memory\":\"512\",\"containerDefinitions\":" + + "[{\"name\":\"app\",\"image\":\"nginx:latest\","; + + register(prefix + "\"privileged\":true}]}", 400) + .then().body("message", containsString("privileged")); + register(prefix + "\"links\":[\"other\"]}]}", 400) + .then().body("message", containsString("links")); + register(prefix + "\"disableNetworking\":true}]}", 400) + .then().body("message", containsString("disableNetworking")); + register(prefix + "\"dnsServers\":[\"10.0.0.2\"]}]}", 400) + .then().body("message", containsString("dnsServers")); + register(fargateTaskDefinition("fargate-ipc", ",\"ipcMode\":\"host\""), 400) + .then().body("message", containsString("ipcMode")); + register(fargateTaskDefinition("fargate-host-volume", + ",\"volumes\":[{\"name\":\"data\",\"host\":{\"sourcePath\":\"/srv/data\"}}]"), 400); + } + + @Test + void registerTaskDefinitionAllowsThoseParametersOnEc2() { + // The same members are legal on an EC2-compatible definition, so the rejection above must + // be scoped to Fargate rather than applied to every task definition. + register("{\"family\":\"ec2-unsupported-on-fargate\",\"networkMode\":\"bridge\"," + + "\"containerDefinitions\":[{\"name\":\"app\",\"image\":\"nginx:latest\"," + + "\"privileged\":true,\"dnsServers\":[\"10.0.0.2\"]," + + "\"resourceRequirements\":[{\"type\":\"GPU\",\"value\":\"1\"}]}]}", 200) + .then() + .body("taskDefinition.containerDefinitions[0].privileged", equalTo(true)) + .body("taskDefinition.containerDefinitions[0].dnsServers[0]", equalTo("10.0.0.2")) + .body("taskDefinition.containerDefinitions[0].resourceRequirements[0].type", + equalTo("GPU")); + } + + @Test + void registerTaskDefinitionRejectsADependencyOnAContainerThatIsNotThere() { + register("{\"family\":\"fargate-bad-dependency\",\"requiresCompatibilities\":[\"FARGATE\"]," + + "\"networkMode\":\"awsvpc\",\"cpu\":\"256\",\"memory\":\"512\"," + + "\"containerDefinitions\":[{\"name\":\"app\",\"image\":\"nginx:latest\"," + + "\"dependsOn\":[{\"containerName\":\"sidecar\",\"condition\":\"START\"}]}]}", 400) + .then().body("message", containsString("sidecar")); + } + + @Test + void registerTaskDefinitionRejectsAnUnknownDependencyCondition() { + register("{\"family\":\"fargate-bad-condition\",\"requiresCompatibilities\":[\"FARGATE\"]," + + "\"networkMode\":\"awsvpc\",\"cpu\":\"256\",\"memory\":\"512\"," + + "\"containerDefinitions\":[{\"name\":\"init\",\"image\":\"busybox\"}," + + "{\"name\":\"app\",\"image\":\"nginx:latest\"," + + "\"dependsOn\":[{\"containerName\":\"init\",\"condition\":\"READY\"}]}]}", 400) + .then().body("message", containsString("READY")); + } + + @Test + void registerTaskDefinitionAcceptsTheLargestFargateTaskSize() { + register("{\"family\":\"fargate-16vcpu\",\"requiresCompatibilities\":[\"FARGATE\"]," + + "\"networkMode\":\"awsvpc\",\"cpu\":\"16384\",\"memory\":\"122880\"," + + "\"containerDefinitions\":[{\"name\":\"app\",\"image\":\"nginx:latest\"}]}", 200); + } + + @Test + void registerTaskDefinitionRejectsAMemorySizeOffTheFargateStep() { + // 8 vCPU goes from 16 GB up in 4 GB steps, so 18 GB is not a configuration that exists. + Response response = register("{\"family\":\"fargate-8vcpu-bad\",\"requiresCompatibilities\":[\"FARGATE\"]," + + "\"networkMode\":\"awsvpc\",\"cpu\":\"8192\",\"memory\":\"18432\"," + + "\"containerDefinitions\":[{\"name\":\"app\",\"image\":\"nginx:latest\"}]}", 400); + assertEquals("No Fargate configuration exists for given values.", + response.jsonPath().getString("message")); + } + + @Test + void registerTaskDefinitionRejectsSubVcpuSizesForWindowsOnFargate() { + register("{\"family\":\"fargate-windows\",\"requiresCompatibilities\":[\"FARGATE\"]," + + "\"networkMode\":\"awsvpc\",\"cpu\":\"512\",\"memory\":\"1024\"," + + "\"runtimePlatform\":{\"operatingSystemFamily\":\"WINDOWS_SERVER_2019_CORE\"," + + "\"cpuArchitecture\":\"X86_64\"}," + + "\"containerDefinitions\":[{\"name\":\"app\",\"image\":\"nginx:latest\"}]}", 400); + + register("{\"family\":\"fargate-windows-ok\",\"requiresCompatibilities\":[\"FARGATE\"]," + + "\"networkMode\":\"awsvpc\",\"cpu\":\"1024\",\"memory\":\"2048\"," + + "\"runtimePlatform\":{\"operatingSystemFamily\":\"WINDOWS_SERVER_2019_CORE\"," + + "\"cpuArchitecture\":\"X86_64\"}," + + "\"containerDefinitions\":[{\"name\":\"app\",\"image\":\"nginx:latest\"}]}", 200); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/ecs/EcsFargateTaskIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ecs/EcsFargateTaskIntegrationTest.java new file mode 100644 index 0000000000..3fa89e6928 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/ecs/EcsFargateTaskIntegrationTest.java @@ -0,0 +1,264 @@ +package io.github.hectorvent.floci.services.ecs; + +import io.github.hectorvent.floci.testing.RestAssuredJsonUtils; +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.response.Response; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.not; +import static org.hamcrest.Matchers.nullValue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * RunTask and DescribeTasks for the Fargate launch type: the members an SDK client, a waiter or + * the CLI reads off a task, and the placement rules that decide whether a task runs on FARGATE or + * FARGATE_SPOT. + */ +@QuarkusTest +class EcsFargateTaskIntegrationTest { + + private static final String TARGET = "AmazonEC2ContainerServiceV20141113."; + private static final String CT = "application/x-amz-json-1.1"; + private static final String CLUSTER = "fargate-task-cluster"; + private static final String SUBNET = "subnet-default-us-east-1-a"; + private static final String NETWORK = + "\"networkConfiguration\":{\"awsvpcConfiguration\":{\"subnets\":[\"" + SUBNET + "\"]}}"; + + @BeforeAll + static void configure() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + private static Response call(String action, String body, int expectedStatus) { + return given().contentType(CT).header("X-Amz-Target", TARGET + action) + .body(body) + .when().post("/") + .then().statusCode(expectedStatus) + .extract().response(); + } + + private static String seed(String family) { + call("CreateCluster", "{\"clusterName\":\"" + CLUSTER + "\"}", 200); + call("RegisterTaskDefinition", "{\"family\":\"" + family + "\"," + + "\"requiresCompatibilities\":[\"FARGATE\"],\"networkMode\":\"awsvpc\"," + + "\"cpu\":\"256\",\"memory\":\"512\"," + + "\"containerDefinitions\":[{\"name\":\"app\",\"image\":\"nginx:latest\"}]}", 200); + return family; + } + + private static Response runTask(String family, String extraMembers) { + return call("RunTask", "{\"cluster\":\"" + CLUSTER + "\",\"taskDefinition\":\"" + family + "\"," + + "\"launchType\":\"FARGATE\"," + NETWORK + extraMembers + "}", 200); + } + + @Test + void runTaskReportsThePlatformAndConnectivityMembersOfAFargateTask() { + String family = seed("fargate-task-platform"); + Response response = runTask(family, ""); + + response.then() + .body("tasks", hasSize(1)) + .body("tasks[0].launchType", equalTo("FARGATE")) + .body("tasks[0].platformVersion", equalTo("1.4.0")) + .body("tasks[0].platformFamily", equalTo("Linux")) + .body("tasks[0].connectivity", equalTo("CONNECTED")) + .body("tasks[0].healthStatus", equalTo("UNKNOWN")) + .body("tasks[0].enableExecuteCommand", equalTo(false)) + .body("tasks[0].ephemeralStorage.sizeInGiB", equalTo(20)) + .body("tasks[0].group", equalTo("family:" + family)) + .body("tasks[0].cpu", equalTo("256")) + .body("tasks[0].memory", equalTo("512")) + .body("tasks[0].attributes[0].name", equalTo("ecs.cpu-architecture")); + assertTrue(response.jsonPath().getLong("tasks[0].version") >= 1, "version must be reported"); + assertTrue(response.jsonPath().getDouble("tasks[0].connectivityAt") > 0, + "connectivityAt must be reported"); + } + + @Test + void runTaskGivesAnAwsvpcTaskItsOwnEni() { + String family = seed("fargate-task-eni"); + Response response = runTask(family, ""); + + // The ENI is what a client waits on to find a Fargate task's address, so it is reported + // whether or not security-group enforcement is on and whether or not Docker is in play. + response.then() + .body("tasks[0].attachments", hasSize(1)) + .body("tasks[0].attachments[0].type", equalTo("ElasticNetworkInterface")) + .body("tasks[0].attachments[0].status", equalTo("ATTACHED")) + .body("tasks[0].availabilityZone", equalTo("us-east-1a")); + + String eniId = attachmentDetail(response, "networkInterfaceId"); + String privateIp = attachmentDetail(response, "privateIPv4Address"); + assertTrue(eniId != null && eniId.startsWith("eni-"), "the task must report its ENI id"); + assertTrue(privateIp != null && !privateIp.isBlank(), "the task must report a private address"); + assertEquals(SUBNET, attachmentDetail(response, "subnetId")); + + // The ENI is a real one in EC2, in the subnet the task asked for, and the running task + // holds it: DescribeNetworkInterfaces reports an interface that is not attached as + // available and one that is as in-use, and a task's is not free for a caller to take. + given().contentType("application/x-www-form-urlencoded") + .formParam("Action", "DescribeNetworkInterfaces") + .formParam("Version", "2016-11-15") + .formParam("NetworkInterfaceId.1", eniId) + .when().post("/") + .then().statusCode(200) + .body(containsString(SUBNET)) + .body("DescribeNetworkInterfacesResponse.networkInterfaceSet.item.status", + equalTo("in-use")) + // No attachment is reported: every member of one names an instance, and a Fargate + // task has none in the account. + .body(not(containsString(""))); + + String taskArn = response.jsonPath().getString("tasks[0].taskArn"); + call("StopTask", "{\"cluster\":\"" + CLUSTER + "\",\"task\":\"" + taskArn + "\"}", 200) + .then().body("task.attachments[0].status", equalTo("DELETED")); + + // Stopping the task releases the interface rather than leaving it behind in the account. + given().contentType("application/x-www-form-urlencoded") + .formParam("Action", "DescribeNetworkInterfaces") + .formParam("Version", "2016-11-15") + .formParam("NetworkInterfaceId.1", eniId) + .when().post("/") + .then().statusCode(400) + .body(containsString("InvalidNetworkInterfaceID.NotFound")); + } + + private static String attachmentDetail(Response response, String name) { + List values = response.jsonPath() + .getList("tasks[0].attachments[0].details.findAll { it.name == '" + name + "' }.value"); + return values.isEmpty() ? null : values.getFirst(); + } + + @Test + void runTaskRejectsASubnetThatDoesNotExist() { + String family = seed("fargate-task-bad-subnet"); + call("RunTask", "{\"cluster\":\"" + CLUSTER + "\",\"taskDefinition\":\"" + family + + "\",\"launchType\":\"FARGATE\",\"networkConfiguration\":{\"awsvpcConfiguration\":" + + "{\"subnets\":[\"subnet-does-not-exist\"]}}}", 400) + .then().body("message", containsString("subnet-does-not-exist")); + } + + @Test + void runTaskResolvesTheLatestPlatformVersionToAConcreteOne() { + String family = seed("fargate-task-latest"); + runTask(family, ",\"platformVersion\":\"LATEST\"").then() + .body("tasks[0].platformVersion", equalTo("1.4.0")); + runTask(family, ",\"platformVersion\":\"1.3.0\"").then() + .body("tasks[0].platformVersion", equalTo("1.3.0")); + } + + @Test + void runTaskEchoesTheOverridesItWasGiven() { + String family = seed("fargate-task-overrides"); + runTask(family, ",\"overrides\":{\"cpu\":\"512\",\"memory\":\"1024\"," + + "\"ephemeralStorage\":{\"sizeInGiB\":40}," + + "\"containerOverrides\":[{\"name\":\"app\",\"command\":[\"sleep\",\"1\"]," + + "\"environment\":[{\"name\":\"MODE\",\"value\":\"test\"}]}]}").then() + .body("tasks[0].cpu", equalTo("512")) + .body("tasks[0].memory", equalTo("1024")) + .body("tasks[0].ephemeralStorage.sizeInGiB", equalTo(40)) + .body("tasks[0].overrides.cpu", equalTo("512")) + .body("tasks[0].overrides.ephemeralStorage.sizeInGiB", equalTo(40)) + .body("tasks[0].overrides.containerOverrides[0].name", equalTo("app")) + .body("tasks[0].overrides.containerOverrides[0].command[0]", equalTo("sleep")) + .body("tasks[0].overrides.containerOverrides[0].environment[0].name", equalTo("MODE")); + } + + @Test + void runTaskCarriesEnableExecuteCommandAndTags() { + String family = seed("fargate-task-exec"); + runTask(family, ",\"enableExecuteCommand\":true,\"tags\":[{\"key\":\"owner\",\"value\":\"platform\"}]") + .then() + .body("tasks[0].enableExecuteCommand", equalTo(true)) + .body("tasks[0].tags[0].key", equalTo("owner")) + .body("tasks[0].tags[0].value", equalTo("platform")); + } + + @Test + void stopTaskReportsTheStopCodeAndAdvancesTheVersion() { + String family = seed("fargate-task-stop"); + Response launched = runTask(family, ""); + String taskArn = launched.jsonPath().getString("tasks[0].taskArn"); + long versionWhenRunning = launched.jsonPath().getLong("tasks[0].version"); + + call("StopTask", "{\"cluster\":\"" + CLUSTER + "\",\"task\":\"" + taskArn + + "\",\"reason\":\"done\"}", 200).then() + .body("task.stopCode", equalTo("UserInitiated")) + .body("task.stoppedReason", equalTo("done")); + + Response described = call("DescribeTasks", "{\"cluster\":\"" + CLUSTER + "\",\"tasks\":[\"" + + taskArn + "\"]}", 200); + described.then() + .body("tasks[0].lastStatus", equalTo("STOPPED")) + .body("tasks[0].stopCode", equalTo("UserInitiated")); + assertTrue(described.jsonPath().getLong("tasks[0].version") > versionWhenRunning, + "stopping a task must advance its version"); + assertTrue(described.jsonPath().getDouble("tasks[0].executionStoppedAt") > 0, + "executionStoppedAt must be reported once the task has stopped"); + } + + @Test + void runTaskPlacesThroughACapacityProviderStrategyByBaseThenWeight() { + String family = seed("fargate-task-strategy"); + Response response = call("RunTask", "{\"cluster\":\"" + CLUSTER + "\",\"taskDefinition\":\"" + + family + "\",\"count\":5," + NETWORK + ",\"capacityProviderStrategy\":[" + + "{\"capacityProvider\":\"FARGATE\",\"base\":1,\"weight\":1}," + + "{\"capacityProvider\":\"FARGATE_SPOT\",\"weight\":3}]}", 200); + + List providers = response.jsonPath().getList("tasks.capacityProviderName"); + assertEquals(5, providers.size()); + assertEquals(2, providers.stream().filter("FARGATE"::equals).count(), + "one task for the base plus its quarter of the remaining four"); + assertEquals(3, providers.stream().filter("FARGATE_SPOT"::equals).count(), + "three quarters of the remaining four"); + // A task reports both the provider it was placed through and the launch type that + // provider resolves to, unlike a service, which reports only one of the two. + response.then().body("tasks[0].launchType", equalTo("FARGATE")); + } + + @Test + void runTaskRejectsALaunchTypeAndACapacityProviderStrategyTogether() { + String family = seed("fargate-task-both"); + call("RunTask", "{\"cluster\":\"" + CLUSTER + "\",\"taskDefinition\":\"" + family + + "\",\"launchType\":\"FARGATE\"," + NETWORK + ",\"capacityProviderStrategy\":" + + "[{\"capacityProvider\":\"FARGATE_SPOT\",\"weight\":1}]}", 400) + .then().body("message", containsString("cannot specify both")); + } + + @Test + void runTaskRejectsAnUnknownCapacityProvider() { + String family = seed("fargate-task-unknown-provider"); + call("RunTask", "{\"cluster\":\"" + CLUSTER + "\",\"taskDefinition\":\"" + family + "\"," + + NETWORK + ",\"capacityProviderStrategy\":" + + "[{\"capacityProvider\":\"NOT_A_PROVIDER\",\"weight\":1}]}", 400) + .then().body("message", containsString("NOT_A_PROVIDER")); + } + + @Test + void runTaskRejectsAnAwsvpcTaskWithNoNetworkConfiguration() { + String family = seed("fargate-task-no-network"); + call("RunTask", "{\"cluster\":\"" + CLUSTER + "\",\"taskDefinition\":\"" + family + + "\",\"launchType\":\"FARGATE\"}", 400) + .then().body("message", containsString("Network Configuration must be provided")); + } + + @Test + void createServiceOnACapacityProviderStrategyReportsItInsteadOfALaunchType() { + String family = seed("fargate-service-strategy"); + call("CreateService", "{\"cluster\":\"" + CLUSTER + "\",\"serviceName\":\"fargate-spot-svc\"," + + "\"taskDefinition\":\"" + family + "\",\"desiredCount\":0," + NETWORK + "," + + "\"capacityProviderStrategy\":[{\"capacityProvider\":\"FARGATE_SPOT\",\"weight\":1}]}", 200) + .then() + .body("service.capacityProviderStrategy[0].capacityProvider", equalTo("FARGATE_SPOT")) + .body("service.capacityProviderStrategy[0].weight", equalTo(1)) + .body("service.launchType", nullValue()); + } +} 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 eab2f56b0d..fd1bb6d2f6 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 @@ -452,6 +452,7 @@ class EcsIntegrationTest { "cluster": "%s", "taskDefinition": "%s", "launchType": "FARGATE", + "networkConfiguration": {"awsvpcConfiguration": {"subnets": ["subnet-default-us-east-1-a"]}}, "count": 1 } """.formatted(CLUSTER_NAME, TASK_DEF_FAMILY)) @@ -541,6 +542,7 @@ class EcsIntegrationTest { "cluster": "%s", "taskDefinition": "empty-containers-task", "launchType": "FARGATE", + "networkConfiguration": {"awsvpcConfiguration": {"subnets": ["subnet-default-us-east-1-a"]}}, "count": 1 } """.formatted(CLUSTER_NAME)) @@ -694,6 +696,7 @@ class EcsIntegrationTest { "taskDefinition": "%s", "desiredCount": 1, "launchType": "FARGATE", + "networkConfiguration": {"awsvpcConfiguration": {"subnets": ["subnet-default-us-east-1-a"]}}, "tags": [ {"key": "Environment", "value": "dev"}, {"key": "Project", "value": "project1"} @@ -787,7 +790,8 @@ class EcsIntegrationTest { "serviceName": "%s", "taskDefinition": "%s", "desiredCount": 2, - "launchType": "FARGATE" + "launchType": "FARGATE", + "networkConfiguration": {"awsvpcConfiguration": {"subnets": ["subnet-default-us-east-1-a"]}} } """.formatted(CLUSTER_NAME, SERVICE_NAME, TASK_DEF_FAMILY)) .when() @@ -808,7 +812,8 @@ class EcsIntegrationTest { "serviceName": "%s", "taskDefinition": "%s", "desiredCount": 99, - "launchType": "FARGATE" + "launchType": "FARGATE", + "networkConfiguration": {"awsvpcConfiguration": {"subnets": ["subnet-default-us-east-1-a"]}} } """.formatted(CLUSTER_NAME, SERVICE_NAME, TASK_DEF_FAMILY)) .when() @@ -831,7 +836,8 @@ class EcsIntegrationTest { "serviceName": "negative-count-svc", "taskDefinition": "%s", "desiredCount": -5, - "launchType": "FARGATE" + "launchType": "FARGATE", + "networkConfiguration": {"awsvpcConfiguration": {"subnets": ["subnet-default-us-east-1-a"]}} } """.formatted(CLUSTER_NAME, TASK_DEF_FAMILY)) .when() @@ -873,7 +879,8 @@ class EcsIntegrationTest { "serviceName": "zero-count-svc", "taskDefinition": "%s", "desiredCount": 0, - "launchType": "FARGATE" + "launchType": "FARGATE", + "networkConfiguration": {"awsvpcConfiguration": {"subnets": ["subnet-default-us-east-1-a"]}} } """.formatted(CLUSTER_NAME, TASK_DEF_FAMILY)) .when() @@ -1074,7 +1081,8 @@ class EcsIntegrationTest { "serviceName": "%s", "taskDefinition": "review-td", "desiredCount": 1, - "launchType": "FARGATE" + "launchType": "FARGATE", + "networkConfiguration": {"awsvpcConfiguration": {"subnets": ["subnet-default-us-east-1-a"]}} } """.formatted(REVIEW_CLUSTER, REVIEW_SERVICE)) .when() @@ -1160,6 +1168,7 @@ class EcsIntegrationTest { "taskDefinition": "review-td", "desiredCount": 1, "launchType": "FARGATE", + "networkConfiguration": {"awsvpcConfiguration": {"subnets": ["subnet-default-us-east-1-a"]}}, "loadBalancers": [ { "targetGroupArn": "arn:aws:elasticloadbalancing:us-east-1:000000000000:targetgroup/tg-a/1234", @@ -1184,6 +1193,7 @@ class EcsIntegrationTest { "taskDefinition": "review-td", "desiredCount": 1, "launchType": "FARGATE", + "networkConfiguration": {"awsvpcConfiguration": {"subnets": ["subnet-default-us-east-1-a"]}}, "loadBalancers": [ { "targetGroupArn": "arn:aws:elasticloadbalancing:us-east-1:000000000000:targetgroup/tg-DIFFERENT/9999", 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 5b79f18388..abd7b960a9 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 @@ -7,12 +7,15 @@ import io.github.hectorvent.floci.core.storage.InMemoryStorage; import io.github.hectorvent.floci.core.storage.StorageBackend; import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend; import io.github.hectorvent.floci.core.storage.StorageFactory; +import io.github.hectorvent.floci.services.ec2.Ec2Service; import io.github.hectorvent.floci.services.ecs.container.EcsContainerManager; import io.github.hectorvent.floci.services.ecs.model.Attribute; +import io.github.hectorvent.floci.services.ecs.model.AwsVpcConfiguration; import io.github.hectorvent.floci.services.ecs.model.ContainerDefinition; import io.github.hectorvent.floci.services.ecs.model.EcsCluster; import io.github.hectorvent.floci.services.ecs.model.EcsServiceModel; import io.github.hectorvent.floci.services.ecs.model.LaunchType; +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.TaskDefinition; import org.junit.jupiter.api.Test; @@ -47,7 +50,7 @@ class EcsServicePersistenceTest { NetworkMode.awsvpc, "256", "512", null, null, List.of("FARGATE"), Map.of("tier", "web"), REGION); EcsServiceModel svc = first.createService("app-cluster", "web-svc", td.getTaskDefinitionArn(), - 0, LaunchType.FARGATE, List.of(), null, Map.of("team", "payments"), REGION); + 0, LaunchType.FARGATE, List.of(), awsvpcConfiguration(), Map.of("team", "payments"), REGION); first.putAttributes("app-cluster", List.of(new Attribute("stack", "prod", "container-instance", "ci-1")), REGION); first.putAccountSetting("containerInsights", "enabled"); @@ -104,6 +107,15 @@ class EcsServicePersistenceTest { return cd; } + /** An awsvpc service needs the subnets its tasks get an ENI in, as it does on AWS. */ + private static NetworkConfiguration awsvpcConfiguration() { + AwsVpcConfiguration awsvpc = new AwsVpcConfiguration(); + awsvpc.setSubnets(List.of(Ec2Service.defaultSubnetId(REGION, "a"))); + NetworkConfiguration networkConfiguration = new NetworkConfiguration(); + networkConfiguration.setAwsvpcConfiguration(awsvpc); + return networkConfiguration; + } + private static EcsService serviceWithStorage(StorageFactory storage) { EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS); when(config.services().ecs().mock()).thenReturn(true); diff --git a/src/test/java/io/github/hectorvent/floci/services/ecs/container/EcsContainerManagerSecurityGroupTest.java b/src/test/java/io/github/hectorvent/floci/services/ecs/container/EcsContainerManagerSecurityGroupTest.java index b307de3174..1f8fcbe9f0 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ecs/container/EcsContainerManagerSecurityGroupTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ecs/container/EcsContainerManagerSecurityGroupTest.java @@ -36,6 +36,7 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.RETURNS_DEEP_STUBS; import static org.mockito.Mockito.RETURNS_SELF; import static org.mockito.Mockito.mock; @@ -141,7 +142,7 @@ class EcsContainerManagerSecurityGroupTest { } @Test - void stopTaskUnregistersEni() { + void stopTaskUnregistersEniAndReleasingTheTaskNetworkDeletesIt() { when(containerDetector.isRunningInContainer()).thenReturn(false); when(firewallManager.enabled()).thenReturn(true); when(firewallManager.createNamespace(eq("ecs"), eq("abc123"), any(), any(), any(), any())) @@ -162,11 +163,17 @@ class EcsContainerManagerSecurityGroupTest { DockerClient stopClient = mock(DockerClient.class, RETURNS_DEEP_STUBS); when(lifecycleManager.getDockerClient()).thenReturn(dockerClient, dockerClient, stopClient); - EcsTaskHandle handle = manager.startTask(awsvpcTask(), awsvpcTaskDef(List.of()), + EcsTask task = awsvpcTask(); + EcsTaskHandle handle = manager.startTask(task, awsvpcTaskDef(List.of()), List.of(), "us-east-1"); manager.stopTaskAndCollectExitCodes(handle); - verify(firewallManager).unregister("eni-1"); + // Stopping the containers tears down their firewall registration, but the ENI belongs to + // the task: it lives until the task itself is released. + verify(firewallManager, atLeastOnce()).unregister("eni-1"); + verify(ec2Service, never()).deleteNetworkInterface(any(), any()); + + manager.releaseTaskNetwork(task, "us-east-1"); verify(ec2Service).deleteNetworkInterface("us-east-1", "eni-1"); } diff --git a/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeEcsRunTaskIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeEcsRunTaskIntegrationTest.java index 7a7cc19c57..cddf994fb7 100644 --- a/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeEcsRunTaskIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeEcsRunTaskIntegrationTest.java @@ -69,8 +69,8 @@ class EventBridgeEcsRunTaskIntegrationTest { "Group": "eb-ecs-group-%s", "NetworkConfiguration": { "awsvpcConfiguration": { - "Subnets": ["subnet-1", "subnet-2"], - "SecurityGroups": ["sg-1"], + "Subnets": ["subnet-default-us-east-1-a", "subnet-default-us-east-1-b"], + "SecurityGroups": ["sg-default-us-east-1"], "AssignPublicIp": "ENABLED" } } @@ -100,9 +100,9 @@ class EventBridgeEcsRunTaskIntegrationTest { .body("Targets[0].EcsParameters.LaunchType", equalTo("FARGATE")) .body("Targets[0].EcsParameters.Group", equalTo("eb-ecs-group-" + suffix)) .body("Targets[0].EcsParameters.NetworkConfiguration.awsvpcConfiguration.Subnets", - hasItem("subnet-1")) + hasItem("subnet-default-us-east-1-a")) .body("Targets[0].EcsParameters.NetworkConfiguration.awsvpcConfiguration.SecurityGroups", - hasItem("sg-1")) + hasItem("sg-default-us-east-1")) .body("Targets[0].EcsParameters.NetworkConfiguration.awsvpcConfiguration.AssignPublicIp", equalTo("ENABLED"));