diff --git a/README.md b/README.md index 081978f498..199c1101bd 100644 --- a/README.md +++ b/README.md @@ -50,9 +50,10 @@ | STS (all 7 operations) | ✅ | ⚠️ Partial | | Kinesis (streams, shards, fan-out) | ✅ | ⚠️ Partial | | KMS (sign, verify, re-encrypt) | ✅ | ⚠️ Partial | +| ECS (clusters, services, tasks) | ✅ | ❌ | | Native binary | ✅ ~40 MB | ❌ | -**25 services. 1,873 automated compatibility tests. Free forever.** +**26 services. 1,873 automated compatibility tests. Free forever.** ## Architecture Overview @@ -72,7 +73,7 @@ flowchart LR end subgraph Containers ["Container Services 🐳"] - C["Lambda\nElastiCache\nRDS"] + C["Lambda\nElastiCache\nRDS\nECS"] end Router --> Stateless @@ -112,11 +113,12 @@ flowchart LR | **CloudWatch Metrics** | 5 | In-process | Custom metrics, statistics, alarms | | **ElastiCache** | 9 | **Real Docker containers** | Redis / Valkey, IAM auth, SigV4 validation | | **RDS** | 14 | **Real Docker containers** | PostgreSQL & MySQL, IAM auth, JDBC-compatible | +| **ECS** | 58 | **Real Docker containers** | Clusters, task definitions, tasks, services, capacity providers, task sets | | **ACM** | 8 | In-process | Certificate issuance, validation lifecycle | | **SES** | 14 | In-process | Send email / raw email, identity verification, DKIM attributes | | **OpenSearch** | 24 | In-process | Domain CRUD, tags, versions, instance types, upgrade stubs | -> **Lambda, ElastiCache, and RDS** spin up real Docker containers and support IAM authentication and SigV4 request signing — the same auth flow as production AWS. +> **Lambda, ElastiCache, RDS, and ECS** spin up real Docker containers and support IAM authentication and SigV4 request signing — the same auth flow as production AWS. ## Quick Start diff --git a/docs/configuration/application-yml.md b/docs/configuration/application-yml.md index 62bf4ca997..5c11455c01 100644 --- a/docs/configuration/application-yml.md +++ b/docs/configuration/application-yml.md @@ -137,6 +137,13 @@ floci: default-image: "opensearchproject/opensearch:2" proxy-base-port: 9400 proxy-max-port: 9499 + + ecs: + enabled: true + mock: false # true = tasks go to RUNNING without Docker (useful for CI) + docker-network: "" # Docker network for task containers + default-memory-mb: 512 + default-cpu-units: 256 ``` ## Service Limits @@ -152,6 +159,10 @@ floci: | `FLOCI_SERVICES_S3_DEFAULT_PRESIGN_EXPIRY_SECONDS` | `3600` | Pre-signed URL expiry | | `FLOCI_SERVICES_DYNAMODB_MAX_ITEM_SIZE` | `400000` | Max item size (bytes) | | `FLOCI_SERVICES_DOCKER_NETWORK` | | Shared Docker network for Lambda, RDS, ElastiCache containers | +| `FLOCI_SERVICES_ECS_MOCK` | `false` | Skip Docker; tasks go straight to RUNNING (useful for CI) | +| `FLOCI_SERVICES_ECS_DOCKER_NETWORK` | | Docker network for ECS task containers | +| `FLOCI_SERVICES_ECS_DEFAULT_MEMORY_MB` | `512` | Default memory (MB) when task definition omits it | +| `FLOCI_SERVICES_ECS_DEFAULT_CPU_UNITS` | `256` | Default CPU units when task definition omits it | ## Disabling Services diff --git a/docs/services/ecs.md b/docs/services/ecs.md new file mode 100644 index 0000000000..2e44e2736a --- /dev/null +++ b/docs/services/ecs.md @@ -0,0 +1,284 @@ +# ECS (Elastic Container Service) + +**Protocol:** JSON 1.1 +**Endpoint:** `POST /` + `X-Amz-Target: AmazonEC2ContainerServiceV20141113.` + +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. + +## Supported Operations + +### Clusters + +| Operation | Description | +|---|---| +| `CreateCluster` | Create a cluster (idempotent) | +| `DescribeClusters` | Describe one or more clusters | +| `ListClusters` | List cluster ARNs | +| `UpdateCluster` | Update cluster settings | +| `UpdateClusterSettings` | Update `containerInsights` and other settings | +| `PutClusterCapacityProviders` | Associate capacity providers with a cluster | +| `DeleteCluster` | Delete an empty cluster | + +### Task Definitions + +| Operation | Description | +|---|---| +| `RegisterTaskDefinition` | Register a new revision of a task definition | +| `DescribeTaskDefinition` | Describe a task definition by family:revision or ARN | +| `ListTaskDefinitions` | List task definition ARNs | +| `ListTaskDefinitionFamilies` | List task definition family names | +| `DeregisterTaskDefinition` | Mark a revision INACTIVE | +| `DeleteTaskDefinitions` | Delete one or more task definitions | + +### Tasks + +| Operation | Description | +|---|---| +| `RunTask` | Launch one or more task instances | +| `StartTask` | Start a task on specific container instances | +| `StopTask` | Stop a running task | +| `DescribeTasks` | Describe one or more tasks | +| `ListTasks` | List task ARNs (filterable by cluster, family, service, status) | +| `UpdateTaskProtection` | Set scale-in protection for tasks | +| `GetTaskProtection` | Get current task protection state | + +### Services + +| Operation | Description | +|---|---| +| `CreateService` | Create a long-running service | +| `UpdateService` | Update desired count, task definition, or deployment config | +| `DeleteService` | Delete a service (supports `force`) | +| `DescribeServices` | Describe one or more services | +| `ListServices` | List service ARNs in a cluster | +| `ListServicesByNamespace` | List services filtered by Cloud Map namespace | + +### Task Sets + +| Operation | Description | +|---|---| +| `CreateTaskSet` | Create a task set inside a service | +| `UpdateTaskSet` | Update a task set's scale | +| `DeleteTaskSet` | Delete a task set | +| `DescribeTaskSets` | Describe task sets for a service | +| `UpdateServicePrimaryTaskSet` | Promote a task set to primary | + +### Container Instances + +| Operation | Description | +|---|---| +| `RegisterContainerInstance` | Register a container instance with a cluster | +| `DeregisterContainerInstance` | Deregister a container instance | +| `DescribeContainerInstances` | Describe container instances | +| `ListContainerInstances` | List container instance ARNs | +| `UpdateContainerAgent` | Trigger agent update (stub) | +| `UpdateContainerInstancesState` | Drain or activate container instances | + +### Capacity Providers + +| Operation | Description | +|---|---| +| `CreateCapacityProvider` | Create a custom capacity provider | +| `UpdateCapacityProvider` | Update a capacity provider | +| `DeleteCapacityProvider` | Delete a capacity provider | +| `DescribeCapacityProviders` | Describe capacity providers (includes FARGATE built-ins) | + +### Service Deployments & Revisions + +| Operation | Description | +|---|---| +| `DescribeServiceDeployments` | Describe service deployments | +| `ListServiceDeployments` | List service deployment ARNs | +| `DescribeServiceRevisions` | Describe service revisions | + +### Tags + +| Operation | Description | +|---|---| +| `TagResource` | Add tags to a cluster, service, task, or task definition | +| `UntagResource` | Remove tags from a resource | +| `ListTagsForResource` | List tags on a resource | + +### Account Settings & Attributes + +| Operation | Description | +|---|---| +| `PutAccountSetting` | Set an account-level setting for the calling user | +| `PutAccountSettingDefault` | Set the default account-level setting | +| `DeleteAccountSetting` | Delete an account setting | +| `ListAccountSettings` | List account settings | +| `PutAttributes` | Set custom key-value attributes on resources | +| `DeleteAttributes` | Remove attributes from resources | +| `ListAttributes` | List resources with a given attribute | + +### Agent / State Change Stubs + +| Operation | Description | +|---|---| +| `SubmitTaskStateChange` | Agent callback stub | +| `SubmitContainerStateChange` | Agent callback stub | +| `SubmitAttachmentStateChanges` | Agent callback stub | +| `DiscoverPollEndpoint` | Returns the agent polling endpoint | + +## Configuration + +```yaml +floci: + services: + ecs: + enabled: true + mock: false # Set true to skip Docker and run tasks as in-process stubs + docker-network: "" # Docker network for task containers + default-memory-mb: 512 + default-cpu-units: 256 +``` + +### Environment Variables + +| Variable | Default | Description | +|---|---|---| +| `FLOCI_SERVICES_ECS_ENABLED` | `true` | Enable or disable the ECS service | +| `FLOCI_SERVICES_ECS_MOCK` | `false` | Skip Docker; tasks go straight to `RUNNING` (useful for CI) | +| `FLOCI_SERVICES_ECS_DOCKER_NETWORK` | *(unset)* | Docker network for task containers | +| `FLOCI_SERVICES_ECS_DEFAULT_MEMORY_MB` | `512` | Default memory (MB) when the task definition omits it | +| `FLOCI_SERVICES_ECS_DEFAULT_CPU_UNITS` | `256` | Default CPU units when the task definition omits it | + +### 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. + +```yaml +# docker-compose.yml — CI / test environment +services: + floci: + image: hectorvent/floci:latest + environment: + FLOCI_SERVICES_ECS_MOCK: "true" +``` + +```yaml +# docker-compose.yml — local development (real containers) +services: + floci: + image: hectorvent/floci:latest + volumes: + - /var/run/docker.sock:/var/run/docker.sock + environment: + FLOCI_SERVICES_ECS_MOCK: "false" + FLOCI_SERVICES_ECS_DOCKER_NETWORK: my_network +``` + +### Docker socket requirement + +When `mock: false` (the default), ECS launches real Docker containers and requires the Docker socket. Mount it and set the network so containers can reach each other: + +```yaml +services: + floci: + image: hectorvent/floci:latest + volumes: + - /var/run/docker.sock:/var/run/docker.sock + environment: + FLOCI_SERVICES_ECS_DOCKER_NETWORK: aws-local_default +``` + +## Examples + +```bash +export AWS_ENDPOINT_URL=http://localhost:4566 +export AWS_DEFAULT_REGION=us-east-1 +export AWS_ACCESS_KEY_ID=test +export AWS_SECRET_ACCESS_KEY=test + +# Create a cluster +aws ecs create-cluster --cluster-name my-cluster \ + --endpoint-url $AWS_ENDPOINT_URL + +# Register a task definition +aws ecs register-task-definition \ + --family my-task \ + --container-definitions '[ + { + "name": "app", + "image": "nginx:latest", + "cpu": 256, + "memory": 512, + "essential": true, + "portMappings": [{"containerPort": 80, "protocol": "tcp"}] + } + ]' \ + --requires-compatibilities FARGATE \ + --cpu 256 --memory 512 \ + --network-mode awsvpc \ + --endpoint-url $AWS_ENDPOINT_URL + +# Run a task +aws ecs run-task \ + --cluster my-cluster \ + --task-definition my-task \ + --launch-type FARGATE \ + --endpoint-url $AWS_ENDPOINT_URL + +# Create a service +aws ecs create-service \ + --cluster my-cluster \ + --service-name my-service \ + --task-definition my-task \ + --desired-count 1 \ + --launch-type FARGATE \ + --endpoint-url $AWS_ENDPOINT_URL + +# List running tasks +aws ecs list-tasks --cluster my-cluster \ + --endpoint-url $AWS_ENDPOINT_URL + +# Stop a task +aws ecs stop-task \ + --cluster my-cluster \ + --task \ + --endpoint-url $AWS_ENDPOINT_URL + +# Delete a service +aws ecs delete-service \ + --cluster my-cluster \ + --service my-service \ + --force \ + --endpoint-url $AWS_ENDPOINT_URL +``` + +## Java SDK Example + +```java +EcsClient ecs = EcsClient.builder() + .endpointOverride(URI.create("http://localhost:4566")) + .region(Region.US_EAST_1) + .credentialsProvider(StaticCredentialsProvider.create( + AwsBasicCredentials.create("test", "test"))) + .build(); + +// Create cluster +ecs.createCluster(r -> r.clusterName("my-cluster")); + +// Register task definition +ecs.registerTaskDefinition(r -> r + .family("my-task") + .containerDefinitions(c -> c + .name("app") + .image("nginx:latest") + .cpu(256) + .memory(512) + .essential(true)) + .requiresCompatibilities(Compatibility.FARGATE) + .cpu("256") + .memory("512") + .networkMode(NetworkMode.AWSVPC)); + +// Run a task +RunTaskResponse response = ecs.runTask(r -> r + .cluster("my-cluster") + .taskDefinition("my-task") + .launchType(LaunchType.FARGATE) + .count(1)); + +String taskArn = response.tasks().get(0).taskArn(); +``` diff --git a/docs/services/index.md b/docs/services/index.md index 3198ad4b5f..c08ab29a4b 100644 --- a/docs/services/index.md +++ b/docs/services/index.md @@ -1,6 +1,6 @@ # Services Overview -Floci emulates 25 AWS services on a single port (`4566`). All services use the real AWS wire protocol — your existing AWS CLI commands and SDK clients work without modification. +Floci emulates 26 AWS services on a single port (`4566`). All services use the real AWS wire protocol — your existing AWS CLI commands and SDK clients work without modification. ## Service Matrix @@ -30,6 +30,7 @@ Floci emulates 25 AWS services on a single port (`4566`). All services use the r | [CloudWatch Logs](cloudwatch.md) | `POST /` + `X-Amz-Target: Logs.*` | JSON 1.1 | 14 | | [CloudWatch Metrics](cloudwatch.md#metrics) | `POST /` with `Action=` or JSON 1.1 | Query / JSON | 8 | | [ACM](acm.md) | `POST /` + `X-Amz-Target: CertificateManager.*` | JSON 1.1 | 12 | +| [ECS](ecs.md) | `POST /` + `X-Amz-Target: AmazonEC2ContainerServiceV20141113.*` | JSON 1.1 | 58 | | [SES](ses.md) | `POST /` with `Action=` param | Query | 14 | | [OpenSearch](opensearch.md) | `/2021-01-01/opensearch/...` | REST JSON | 24 | diff --git a/mkdocs.yml b/mkdocs.yml index aacea05edd..a7cd2cda5f 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -88,5 +88,6 @@ nav: - EventBridge: services/eventbridge.md - CloudWatch: services/cloudwatch.md - ACM: services/acm.md + - ECS: services/ecs.md - OpenSearch: services/opensearch.md - Contributing: contributing.md \ No newline at end of file diff --git a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java index ba5dc65330..349340fd9a 100644 --- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java +++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java @@ -190,6 +190,7 @@ public interface EmulatorConfig { AcmServiceConfig acm(); SesServiceConfig ses(); OpenSearchServiceConfig opensearch(); + EcsServiceConfig ecs(); } interface SsmServiceConfig { @@ -368,6 +369,23 @@ public interface EmulatorConfig { Optional dockerNetwork(); } + interface EcsServiceConfig { + @WithDefault("true") + boolean enabled(); + + /** When true, tasks go straight to RUNNING without starting real Docker containers. */ + @WithDefault("false") + boolean mock(); + + Optional dockerNetwork(); + + @WithDefault("512") + int defaultMemoryMb(); + + @WithDefault("256") + int defaultCpuUnits(); + } + interface LambdaServiceConfig { @WithDefault("true") boolean enabled(); diff --git a/src/main/java/io/github/hectorvent/floci/core/common/AwsJson11Controller.java b/src/main/java/io/github/hectorvent/floci/core/common/AwsJson11Controller.java index 9aeacb97d3..27109b5d05 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/AwsJson11Controller.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/AwsJson11Controller.java @@ -1,6 +1,7 @@ package io.github.hectorvent.floci.core.common; import io.github.hectorvent.floci.services.acm.AcmJsonHandler; +import io.github.hectorvent.floci.services.ecs.EcsJsonHandler; import io.github.hectorvent.floci.services.apigatewayv2.ApiGatewayV2JsonHandler; import io.github.hectorvent.floci.services.cloudwatch.logs.CloudWatchLogsHandler; import io.github.hectorvent.floci.services.cognito.CognitoJsonHandler; @@ -42,6 +43,7 @@ public class AwsJson11Controller { private static final String KMS_TARGET_PREFIX = "TrentService."; private static final String COGNITO_TARGET_PREFIX = "AWSCognitoIdentityProviderService."; private static final String ACM_TARGET_PREFIX = "CertificateManager."; + private static final String ECS_TARGET_PREFIX = "AmazonEC2ContainerServiceV20141113."; private final ObjectMapper objectMapper; private final RegionResolver regionResolver; @@ -54,6 +56,7 @@ public class AwsJson11Controller { private final KmsJsonHandler kmsJsonHandler; private final CognitoJsonHandler cognitoJsonHandler; private final AcmJsonHandler acmJsonHandler; + private final EcsJsonHandler ecsJsonHandler; @Inject public AwsJson11Controller(ObjectMapper objectMapper, RegionResolver regionResolver, @@ -63,7 +66,7 @@ public class AwsJson11Controller { KinesisJsonHandler kinesisJsonHandler, ApiGatewayV2JsonHandler apigwV2JsonHandler, KmsJsonHandler kmsJsonHandler, CognitoJsonHandler cognitoJsonHandler, - AcmJsonHandler acmJsonHandler) { + AcmJsonHandler acmJsonHandler, EcsJsonHandler ecsJsonHandler) { this.objectMapper = objectMapper; this.regionResolver = regionResolver; this.ssmJsonHandler = ssmJsonHandler; @@ -75,6 +78,7 @@ public class AwsJson11Controller { this.kmsJsonHandler = kmsJsonHandler; this.cognitoJsonHandler = cognitoJsonHandler; this.acmJsonHandler = acmJsonHandler; + this.ecsJsonHandler = ecsJsonHandler; } @POST @@ -119,6 +123,9 @@ public class AwsJson11Controller { } else if (target.startsWith(ACM_TARGET_PREFIX)) { prefix = ACM_TARGET_PREFIX; serviceName = "ACM"; + } else if (target.startsWith(ECS_TARGET_PREFIX)) { + prefix = ECS_TARGET_PREFIX; + serviceName = "ECS"; } else { return Response.status(400) .entity(new AwsErrorResponse("UnknownOperationException", @@ -143,6 +150,7 @@ public class AwsJson11Controller { case "KMS" -> kmsJsonHandler.handle(action, request, region); case "Cognito" -> cognitoJsonHandler.handle(action, request, region); case "ACM" -> acmJsonHandler.handle(action, request, region); + case "ECS" -> ecsJsonHandler.handle(action, request, region); default -> null; }; } catch (AwsException e) { diff --git a/src/main/java/io/github/hectorvent/floci/core/common/ServiceRegistry.java b/src/main/java/io/github/hectorvent/floci/core/common/ServiceRegistry.java index a53334add8..f9dc5c1edd 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/ServiceRegistry.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/ServiceRegistry.java @@ -50,6 +50,7 @@ public class ServiceRegistry { case "acm" -> config.services().acm().enabled(); case "email" -> config.services().ses().enabled(); case "es" -> config.services().opensearch().enabled(); + case "ecs" -> config.services().ecs().enabled(); default -> true; }; } @@ -79,6 +80,7 @@ public class ServiceRegistry { if (config.services().acm().enabled()) enabled.add("acm"); if (config.services().ses().enabled()) enabled.add("email"); if (config.services().opensearch().enabled()) enabled.add("es"); + if (config.services().ecs().enabled()) enabled.add("ecs"); return enabled; } @@ -110,6 +112,7 @@ public class ServiceRegistry { services.put("acm", status(config.services().acm().enabled())); services.put("email", status(config.services().ses().enabled())); services.put("es", status(config.services().opensearch().enabled())); + services.put("ecs", status(config.services().ecs().enabled())); return services; } 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 new file mode 100644 index 0000000000..e4ab4d4abb --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/ecs/EcsJsonHandler.java @@ -0,0 +1,1212 @@ +package io.github.hectorvent.floci.services.ecs; + +import io.github.hectorvent.floci.core.common.AwsErrorResponse; +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.ClusterSetting; +import io.github.hectorvent.floci.services.ecs.model.ContainerDefinition; +import io.github.hectorvent.floci.services.ecs.model.ContainerInstance; +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.EcsTask; +import io.github.hectorvent.floci.services.ecs.model.KeyValuePair; +import io.github.hectorvent.floci.services.ecs.model.LaunchType; +import io.github.hectorvent.floci.services.ecs.model.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.ProtectedTask; +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.TaskSet; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import jakarta.ws.rs.core.Response; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@ApplicationScoped +public class EcsJsonHandler { + + private final EcsService service; + private final ObjectMapper objectMapper; + + @Inject + public EcsJsonHandler(EcsService service, ObjectMapper objectMapper) { + this.service = service; + this.objectMapper = objectMapper; + } + + public Response handle(String action, JsonNode request, String region) { + return switch (action) { + // Clusters + case "CreateCluster" -> handleCreateCluster(request, region); + case "DescribeClusters" -> handleDescribeClusters(request, region); + case "ListClusters" -> handleListClusters(request, region); + case "DeleteCluster" -> handleDeleteCluster(request, region); + 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); + case "DescribeTasks" -> handleDescribeTasks(request, region); + 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.")) + .build(); + }; + } + + // ── Clusters ────────────────────────────────────────────────────────────── + + private Response handleCreateCluster(JsonNode req, String region) { + String name = req.path("clusterName").asText(null); + EcsCluster cluster = service.createCluster(name, region); + ObjectNode resp = objectMapper.createObjectNode(); + resp.set("cluster", clusterNode(cluster)); + return Response.ok(resp).build(); + } + + private Response handleDescribeClusters(JsonNode req, String region) { + List ids = jsonArrayToList(req.path("clusters")); + List found = service.describeClusters(ids, region); + ObjectNode resp = objectMapper.createObjectNode(); + ArrayNode arr = objectMapper.createArrayNode(); + found.forEach(c -> arr.add(clusterNode(c))); + resp.set("clusters", arr); + resp.set("failures", objectMapper.createArrayNode()); + return Response.ok(resp).build(); + } + + private Response handleListClusters(JsonNode req, String region) { + List arns = service.listClusters(region); + ObjectNode resp = objectMapper.createObjectNode(); + ArrayNode arr = objectMapper.createArrayNode(); + arns.forEach(arr::add); + resp.set("clusterArns", arr); + return Response.ok(resp).build(); + } + + private Response handleDeleteCluster(JsonNode req, String region) { + String clusterId = req.path("cluster").asText(); + EcsCluster cluster = service.deleteCluster(clusterId, region); + ObjectNode resp = objectMapper.createObjectNode(); + resp.set("cluster", clusterNode(cluster)); + return Response.ok(resp).build(); + } + + private Response handleUpdateCluster(JsonNode req, String region) { + String clusterRef = req.path("cluster").asText(); + List settings = parseClusterSettings(req.path("settings")); + EcsCluster cluster = service.updateCluster(clusterRef, settings, region); + ObjectNode resp = objectMapper.createObjectNode(); + resp.set("cluster", clusterNode(cluster)); + return Response.ok(resp).build(); + } + + private Response handleUpdateClusterSettings(JsonNode req, String region) { + String clusterRef = req.path("cluster").asText(); + List settings = parseClusterSettings(req.path("settings")); + EcsCluster cluster = service.updateClusterSettings(clusterRef, settings, region); + ObjectNode resp = objectMapper.createObjectNode(); + resp.set("cluster", clusterNode(cluster)); + return Response.ok(resp).build(); + } + + private Response handlePutClusterCapacityProviders(JsonNode req, String region) { + String clusterRef = req.path("cluster").asText(); + List providers = jsonArrayToList(req.path("capacityProviders")); + List> defaultStrategy = parseRawObjectList(req.path("defaultCapacityProviderStrategy")); + EcsCluster cluster = service.putClusterCapacityProviders(clusterRef, providers, defaultStrategy, region); + ObjectNode resp = objectMapper.createObjectNode(); + resp.set("cluster", clusterNode(cluster)); + return Response.ok(resp).build(); + } + + // ── Task Definitions ────────────────────────────────────────────────────── + + private Response handleRegisterTaskDefinition(JsonNode req, String region) { + String family = req.path("family").asText(); + List containerDefs = parseContainerDefinitions(req.path("containerDefinitions")); + NetworkMode networkMode = parseEnum(req, "networkMode", NetworkMode.class); + String cpu = req.has("cpu") ? req.path("cpu").asText() : null; + String memory = req.has("memory") ? req.path("memory").asText() : null; + + TaskDefinition td = service.registerTaskDefinition(family, containerDefs, networkMode, cpu, memory, region); + + ObjectNode resp = objectMapper.createObjectNode(); + resp.set("taskDefinition", taskDefinitionNode(td)); + return Response.ok(resp).build(); + } + + private Response handleDescribeTaskDefinition(JsonNode req, String region) { + String tdRef = req.path("taskDefinition").asText(); + TaskDefinition td = service.describeTaskDefinition(tdRef, region); + ObjectNode resp = objectMapper.createObjectNode(); + resp.set("taskDefinition", taskDefinitionNode(td)); + return Response.ok(resp).build(); + } + + private Response handleListTaskDefinitions(JsonNode req, String region) { + String familyPrefix = req.has("familyPrefix") ? req.path("familyPrefix").asText() : null; + String status = req.has("status") ? req.path("status").asText() : null; + List arns = service.listTaskDefinitions(familyPrefix, status); + ObjectNode resp = objectMapper.createObjectNode(); + ArrayNode arr = objectMapper.createArrayNode(); + arns.forEach(arr::add); + resp.set("taskDefinitionArns", arr); + return Response.ok(resp).build(); + } + + private Response handleListTaskDefinitionFamilies(JsonNode req, String region) { + String familyPrefix = req.has("familyPrefix") ? req.path("familyPrefix").asText() : null; + List families = service.listTaskDefinitionFamilies(familyPrefix); + ObjectNode resp = objectMapper.createObjectNode(); + ArrayNode arr = objectMapper.createArrayNode(); + families.forEach(arr::add); + resp.set("families", arr); + return Response.ok(resp).build(); + } + + private Response handleDeregisterTaskDefinition(JsonNode req, String region) { + String tdRef = req.path("taskDefinition").asText(); + TaskDefinition td = service.deregisterTaskDefinition(tdRef, region); + ObjectNode resp = objectMapper.createObjectNode(); + resp.set("taskDefinition", taskDefinitionNode(td)); + return Response.ok(resp).build(); + } + + private Response handleDeleteTaskDefinitions(JsonNode req, String region) { + List refs = jsonArrayToList(req.path("taskDefinitions")); + List deleted = service.deleteTaskDefinitions(refs, region); + ObjectNode resp = objectMapper.createObjectNode(); + ArrayNode arr = objectMapper.createArrayNode(); + deleted.forEach(td -> arr.add(taskDefinitionNode(td))); + resp.set("taskDefinitions", arr); + resp.set("failures", objectMapper.createArrayNode()); + return Response.ok(resp).build(); + } + + // ── Tasks ───────────────────────────────────────────────────────────────── + + private Response handleRunTask(JsonNode req, String region) { + String cluster = req.has("cluster") ? req.path("cluster").asText() : null; + String taskDefinition = req.path("taskDefinition").asText(); + int count = req.path("count").asInt(1); + LaunchType launchType = parseEnum(req, "launchType", LaunchType.class); + String group = req.has("group") ? req.path("group").asText() : null; + String startedBy = req.has("startedBy") ? req.path("startedBy").asText() : null; + + List launched = service.runTask(cluster, taskDefinition, count, + launchType, group, startedBy, region); + + ObjectNode resp = objectMapper.createObjectNode(); + ArrayNode arr = objectMapper.createArrayNode(); + launched.forEach(t -> arr.add(taskNode(t))); + resp.set("tasks", arr); + resp.set("failures", objectMapper.createArrayNode()); + return Response.ok(resp).build(); + } + + private Response handleStartTask(JsonNode req, String region) { + String cluster = req.has("cluster") ? req.path("cluster").asText() : null; + List instances = jsonArrayToList(req.path("containerInstances")); + String taskDefinition = req.path("taskDefinition").asText(); + String group = req.has("group") ? req.path("group").asText() : null; + String startedBy = req.has("startedBy") ? req.path("startedBy").asText() : null; + + List launched = service.startTask(cluster, instances, taskDefinition, group, startedBy, region); + + ObjectNode resp = objectMapper.createObjectNode(); + ArrayNode arr = objectMapper.createArrayNode(); + launched.forEach(t -> arr.add(taskNode(t))); + resp.set("tasks", arr); + resp.set("failures", objectMapper.createArrayNode()); + return Response.ok(resp).build(); + } + + private Response handleStopTask(JsonNode req, String region) { + String cluster = req.has("cluster") ? req.path("cluster").asText() : null; + String task = req.path("task").asText(); + String reason = req.has("reason") ? req.path("reason").asText() : null; + + EcsTask stopped = service.stopTask(cluster, task, reason, region); + + ObjectNode resp = objectMapper.createObjectNode(); + resp.set("task", taskNode(stopped)); + return Response.ok(resp).build(); + } + + 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); + + ObjectNode resp = objectMapper.createObjectNode(); + ArrayNode arr = objectMapper.createArrayNode(); + found.forEach(t -> arr.add(taskNode(t))); + resp.set("tasks", arr); + resp.set("failures", objectMapper.createArrayNode()); + return Response.ok(resp).build(); + } + + private Response handleListTasks(JsonNode req, String region) { + String cluster = req.has("cluster") ? req.path("cluster").asText() : null; + String family = req.has("family") ? req.path("family").asText() : null; + String desiredStatus = req.has("desiredStatus") ? req.path("desiredStatus").asText() : null; + String serviceName = req.has("serviceName") ? req.path("serviceName").asText() : null; + + List arns = service.listTasks(cluster, family, desiredStatus, serviceName, region); + + ObjectNode resp = objectMapper.createObjectNode(); + ArrayNode arr = objectMapper.createArrayNode(); + arns.forEach(arr::add); + resp.set("taskArns", arr); + return Response.ok(resp).build(); + } + + private Response handleUpdateTaskProtection(JsonNode req, String region) { + String cluster = req.has("cluster") ? req.path("cluster").asText() : null; + List taskRefs = jsonArrayToList(req.path("tasks")); + boolean protectionEnabled = req.path("protectionEnabled").asBoolean(false); + Integer expiresInMinutes = req.has("expiresInMinutes") ? req.path("expiresInMinutes").asInt() : null; + + List result = service.updateTaskProtection(cluster, taskRefs, protectionEnabled, + expiresInMinutes, region); + + ObjectNode resp = objectMapper.createObjectNode(); + ArrayNode arr = objectMapper.createArrayNode(); + result.forEach(pt -> arr.add(protectedTaskNode(pt))); + resp.set("protectedTasks", arr); + resp.set("failures", objectMapper.createArrayNode()); + return Response.ok(resp).build(); + } + + private Response handleGetTaskProtection(JsonNode req, String region) { + String cluster = req.has("cluster") ? req.path("cluster").asText() : null; + List taskRefs = jsonArrayToList(req.path("tasks")); + + List result = service.getTaskProtection(cluster, taskRefs, region); + + ObjectNode resp = objectMapper.createObjectNode(); + ArrayNode arr = objectMapper.createArrayNode(); + result.forEach(pt -> arr.add(protectedTaskNode(pt))); + resp.set("protectedTasks", arr); + resp.set("failures", objectMapper.createArrayNode()); + return Response.ok(resp).build(); + } + + // ── Services ────────────────────────────────────────────────────────────── + + private Response handleCreateService(JsonNode req, String region) { + String cluster = req.has("cluster") ? req.path("cluster").asText() : null; + String serviceName = req.path("serviceName").asText(); + String taskDefinition = req.path("taskDefinition").asText(); + int desiredCount = req.path("desiredCount").asInt(1); + LaunchType launchType = parseEnum(req, "launchType", LaunchType.class); + + EcsServiceModel svc = service.createService(cluster, serviceName, taskDefinition, + desiredCount, launchType, region); + + ObjectNode resp = objectMapper.createObjectNode(); + resp.set("service", serviceNode(svc)); + return Response.ok(resp).build(); + } + + private Response handleUpdateService(JsonNode req, String region) { + String cluster = req.has("cluster") ? req.path("cluster").asText() : null; + String serviceName = req.path("service").asText(); + String taskDefinition = req.has("taskDefinition") ? req.path("taskDefinition").asText() : null; + Integer desiredCount = req.has("desiredCount") ? req.path("desiredCount").asInt() : null; + + EcsServiceModel svc = service.updateService(cluster, serviceName, taskDefinition, desiredCount, region); + + ObjectNode resp = objectMapper.createObjectNode(); + resp.set("service", 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(); + + EcsServiceModel svc = service.deleteService(cluster, serviceName, region); + + ObjectNode resp = objectMapper.createObjectNode(); + resp.set("service", serviceNode(svc)); + return Response.ok(resp).build(); + } + + private Response handleDescribeServices(JsonNode req, String region) { + String cluster = req.has("cluster") ? req.path("cluster").asText() : null; + List serviceIds = jsonArrayToList(req.path("services")); + + List found = service.describeServices(cluster, serviceIds, region); + + ObjectNode resp = objectMapper.createObjectNode(); + ArrayNode arr = objectMapper.createArrayNode(); + found.forEach(s -> arr.add(serviceNode(s))); + resp.set("services", arr); + resp.set("failures", objectMapper.createArrayNode()); + return Response.ok(resp).build(); + } + + private Response handleListServices(JsonNode req, String region) { + String cluster = req.has("cluster") ? req.path("cluster").asText() : null; + List arns = service.listServices(cluster, region); + + ObjectNode resp = objectMapper.createObjectNode(); + ArrayNode arr = objectMapper.createArrayNode(); + arns.forEach(arr::add); + resp.set("serviceArns", arr); + return Response.ok(resp).build(); + } + + private Response handleListServicesByNamespace(JsonNode req, String region) { + String namespace = req.path("namespace").asText(); + List arns = service.listServicesByNamespace(namespace, region); + + ObjectNode resp = objectMapper.createObjectNode(); + ArrayNode arr = objectMapper.createArrayNode(); + arns.forEach(arr::add); + resp.set("serviceArns", arr); + return Response.ok(resp).build(); + } + + // ── Tags ────────────────────────────────────────────────────────────────── + + private Response handleTagResource(JsonNode req, String region) { + String resourceArn = req.path("resourceArn").asText(); + Map tags = parseTagMap(req.path("tags")); + service.tagResource(resourceArn, tags); + return Response.ok(objectMapper.createObjectNode()).build(); + } + + private Response handleUntagResource(JsonNode req, String region) { + String resourceArn = req.path("resourceArn").asText(); + List tagKeys = jsonArrayToList(req.path("tagKeys")); + service.untagResource(resourceArn, tagKeys); + return Response.ok(objectMapper.createObjectNode()).build(); + } + + private Response handleListTagsForResource(JsonNode req, String region) { + String resourceArn = req.path("resourceArn").asText(); + Map tags = service.listTagsForResource(resourceArn); + ObjectNode resp = objectMapper.createObjectNode(); + resp.set("tags", tagsNode(tags)); + return Response.ok(resp).build(); + } + + // ── Account Settings ────────────────────────────────────────────────────── + + private Response handlePutAccountSetting(JsonNode req, String region) { + String name = req.path("name").asText(); + String value = req.path("value").asText(); + var entry = service.putAccountSetting(name, value); + ObjectNode resp = objectMapper.createObjectNode(); + resp.set("setting", settingNode(entry.getKey(), entry.getValue())); + return Response.ok(resp).build(); + } + + private Response handlePutAccountSettingDefault(JsonNode req, String region) { + String name = req.path("name").asText(); + String value = req.path("value").asText(); + var entry = service.putAccountSettingDefault(name, value); + ObjectNode resp = objectMapper.createObjectNode(); + resp.set("setting", settingNode(entry.getKey(), entry.getValue())); + return Response.ok(resp).build(); + } + + private Response handleDeleteAccountSetting(JsonNode req, String region) { + String name = req.path("name").asText(); + var entry = service.deleteAccountSetting(name); + ObjectNode resp = objectMapper.createObjectNode(); + resp.set("setting", settingNode(entry.getKey(), entry.getValue())); + return Response.ok(resp).build(); + } + + private Response handleListAccountSettings(JsonNode req, String region) { + String filterName = req.has("name") ? req.path("name").asText() : null; + String filterValue = req.has("value") ? req.path("value").asText() : null; + var settings = service.listAccountSettings(filterName, filterValue); + ObjectNode resp = objectMapper.createObjectNode(); + ArrayNode arr = objectMapper.createArrayNode(); + settings.forEach(e -> arr.add(settingNode(e.getKey(), e.getValue()))); + resp.set("settings", arr); + return Response.ok(resp).build(); + } + + // ── Attributes ──────────────────────────────────────────────────────────── + + private Response handlePutAttributes(JsonNode req, String region) { + String cluster = req.has("cluster") ? req.path("cluster").asText() : null; + List attrs = parseAttributes(req.path("attributes")); + List stored = service.putAttributes(cluster, attrs, region); + ObjectNode resp = objectMapper.createObjectNode(); + ArrayNode arr = objectMapper.createArrayNode(); + stored.forEach(a -> arr.add(attributeNode(a))); + resp.set("attributes", arr); + return Response.ok(resp).build(); + } + + private Response handleDeleteAttributes(JsonNode req, String region) { + String cluster = req.has("cluster") ? req.path("cluster").asText() : null; + List attrs = parseAttributes(req.path("attributes")); + List deleted = service.deleteAttributes(cluster, attrs, region); + ObjectNode resp = objectMapper.createObjectNode(); + ArrayNode arr = objectMapper.createArrayNode(); + deleted.forEach(a -> arr.add(attributeNode(a))); + resp.set("attributes", arr); + return Response.ok(resp).build(); + } + + private Response handleListAttributes(JsonNode req, String region) { + String cluster = req.has("cluster") ? req.path("cluster").asText() : null; + String targetType = req.has("targetType") ? req.path("targetType").asText() : null; + String attributeName = req.has("attributeName") ? req.path("attributeName").asText() : null; + String attributeValue = req.has("attributeValue") ? req.path("attributeValue").asText() : null; + List result = service.listAttributes(cluster, targetType, attributeName, attributeValue, region); + ObjectNode resp = objectMapper.createObjectNode(); + ArrayNode arr = objectMapper.createArrayNode(); + result.forEach(a -> arr.add(attributeNode(a))); + resp.set("attributes", arr); + return Response.ok(resp).build(); + } + + // ── Container Instances ─────────────────────────────────────────────────── + + private Response handleRegisterContainerInstance(JsonNode req, String region) { + String cluster = req.has("cluster") ? req.path("cluster").asText() : null; + String instanceIdentityDocument = req.has("instanceIdentityDocument") + ? req.path("instanceIdentityDocument").asText() : null; + List attrs = parseAttributes(req.path("attributes")); + ContainerInstance instance = service.registerContainerInstance(cluster, instanceIdentityDocument, attrs, region); + ObjectNode resp = objectMapper.createObjectNode(); + resp.set("containerInstance", containerInstanceNode(instance)); + return Response.ok(resp).build(); + } + + private Response handleDeregisterContainerInstance(JsonNode req, String region) { + String cluster = req.has("cluster") ? req.path("cluster").asText() : null; + String containerInstance = req.path("containerInstance").asText(); + boolean force = req.path("force").asBoolean(false); + ContainerInstance instance = service.deregisterContainerInstance(cluster, containerInstance, force, region); + ObjectNode resp = objectMapper.createObjectNode(); + resp.set("containerInstance", containerInstanceNode(instance)); + return Response.ok(resp).build(); + } + + private Response handleDescribeContainerInstances(JsonNode req, String region) { + String cluster = req.has("cluster") ? req.path("cluster").asText() : null; + List instanceRefs = jsonArrayToList(req.path("containerInstances")); + List found = service.describeContainerInstances(cluster, instanceRefs, region); + ObjectNode resp = objectMapper.createObjectNode(); + ArrayNode arr = objectMapper.createArrayNode(); + found.forEach(ci -> arr.add(containerInstanceNode(ci))); + resp.set("containerInstances", arr); + resp.set("failures", objectMapper.createArrayNode()); + return Response.ok(resp).build(); + } + + private Response handleListContainerInstances(JsonNode req, String region) { + String cluster = req.has("cluster") ? req.path("cluster").asText() : null; + String status = req.has("status") ? req.path("status").asText() : null; + List arns = service.listContainerInstances(cluster, status, region); + ObjectNode resp = objectMapper.createObjectNode(); + ArrayNode arr = objectMapper.createArrayNode(); + arns.forEach(arr::add); + resp.set("containerInstanceArns", arr); + return Response.ok(resp).build(); + } + + private Response handleUpdateContainerAgent(JsonNode req, String region) { + String cluster = req.has("cluster") ? req.path("cluster").asText() : null; + String containerInstance = req.path("containerInstance").asText(); + ContainerInstance instance = service.updateContainerAgent(cluster, containerInstance, region); + ObjectNode resp = objectMapper.createObjectNode(); + resp.set("containerInstance", containerInstanceNode(instance)); + return Response.ok(resp).build(); + } + + private Response handleUpdateContainerInstancesState(JsonNode req, String region) { + String cluster = req.has("cluster") ? req.path("cluster").asText() : null; + List instanceRefs = jsonArrayToList(req.path("containerInstances")); + String status = req.path("status").asText(); + List updated = service.updateContainerInstancesState(cluster, instanceRefs, status, region); + ObjectNode resp = objectMapper.createObjectNode(); + ArrayNode arr = objectMapper.createArrayNode(); + updated.forEach(ci -> arr.add(containerInstanceNode(ci))); + resp.set("containerInstances", arr); + resp.set("failures", objectMapper.createArrayNode()); + return Response.ok(resp).build(); + } + + // ── Capacity Providers ──────────────────────────────────────────────────── + + private Response handleCreateCapacityProvider(JsonNode req, String region) { + String name = req.path("name").asText(); + Map asgProvider = parseRawObject(req.path("autoScalingGroupProvider")); + Map tags = parseTagMap(req.path("tags")); + CapacityProvider cp = service.createCapacityProvider(name, asgProvider, tags, region); + ObjectNode resp = objectMapper.createObjectNode(); + resp.set("capacityProvider", capacityProviderNode(cp)); + return Response.ok(resp).build(); + } + + private Response handleUpdateCapacityProvider(JsonNode req, String region) { + String name = req.path("name").asText(); + Map asgProvider = parseRawObject(req.path("autoScalingGroupProvider")); + CapacityProvider cp = service.updateCapacityProvider(name, asgProvider); + ObjectNode resp = objectMapper.createObjectNode(); + resp.set("capacityProvider", capacityProviderNode(cp)); + return Response.ok(resp).build(); + } + + private Response handleDeleteCapacityProvider(JsonNode req, String region) { + String nameOrArn = req.path("capacityProvider").asText(); + CapacityProvider cp = service.deleteCapacityProvider(nameOrArn); + ObjectNode resp = objectMapper.createObjectNode(); + resp.set("capacityProvider", capacityProviderNode(cp)); + return Response.ok(resp).build(); + } + + private Response handleDescribeCapacityProviders(JsonNode req, String region) { + List providers = req.has("capacityProviders") ? jsonArrayToList(req.path("capacityProviders")) : null; + List found = service.describeCapacityProviders(providers); + ObjectNode resp = objectMapper.createObjectNode(); + ArrayNode arr = objectMapper.createArrayNode(); + found.forEach(cp -> arr.add(capacityProviderNode(cp))); + resp.set("capacityProviders", arr); + return Response.ok(resp).build(); + } + + // ── Task Sets ───────────────────────────────────────────────────────────── + + private Response handleCreateTaskSet(JsonNode req, String region) { + String cluster = req.has("cluster") ? req.path("cluster").asText() : null; + String service = req.path("service").asText(); + String taskDefinition = req.path("taskDefinition").asText(); + LaunchType launchType = parseEnum(req, "launchType", LaunchType.class); + double scaleValue = req.path("scale").path("value").asDouble(100.0); + String scaleUnit = req.path("scale").path("unit").asText("PERCENT"); + String externalId = req.has("externalId") ? req.path("externalId").asText() : null; + + TaskSet ts = this.service.createTaskSet(cluster, service, taskDefinition, launchType, + scaleValue, scaleUnit, externalId, region); + + ObjectNode resp = objectMapper.createObjectNode(); + resp.set("taskSet", taskSetNode(ts)); + return Response.ok(resp).build(); + } + + private Response handleUpdateTaskSet(JsonNode req, String region) { + String cluster = req.has("cluster") ? req.path("cluster").asText() : null; + String svc = req.path("service").asText(); + String taskSet = req.path("taskSet").asText(); + double scaleValue = req.path("scale").path("value").asDouble(100.0); + String scaleUnit = req.path("scale").path("unit").asText("PERCENT"); + + TaskSet ts = service.updateTaskSet(cluster, svc, taskSet, scaleValue, scaleUnit, region); + + ObjectNode resp = objectMapper.createObjectNode(); + resp.set("taskSet", taskSetNode(ts)); + return Response.ok(resp).build(); + } + + private Response handleDeleteTaskSet(JsonNode req, String region) { + String cluster = req.has("cluster") ? req.path("cluster").asText() : null; + String svc = req.path("service").asText(); + String taskSet = req.path("taskSet").asText(); + boolean force = req.path("force").asBoolean(false); + + TaskSet ts = service.deleteTaskSet(cluster, svc, taskSet, force, region); + + ObjectNode resp = objectMapper.createObjectNode(); + resp.set("taskSet", taskSetNode(ts)); + return Response.ok(resp).build(); + } + + private Response handleDescribeTaskSets(JsonNode req, String region) { + String cluster = req.has("cluster") ? req.path("cluster").asText() : null; + String svc = req.path("service").asText(); + List taskSetRefs = req.has("taskSets") ? jsonArrayToList(req.path("taskSets")) : null; + + List found = service.describeTaskSets(cluster, svc, taskSetRefs, region); + + ObjectNode resp = objectMapper.createObjectNode(); + ArrayNode arr = objectMapper.createArrayNode(); + found.forEach(ts -> arr.add(taskSetNode(ts))); + resp.set("taskSets", arr); + return Response.ok(resp).build(); + } + + private Response handleUpdateServicePrimaryTaskSet(JsonNode req, String region) { + String cluster = req.has("cluster") ? req.path("cluster").asText() : null; + String svc = req.path("service").asText(); + String primaryTaskSet = req.path("primaryTaskSet").asText(); + + TaskSet ts = service.updateServicePrimaryTaskSet(cluster, svc, primaryTaskSet, region); + + ObjectNode resp = objectMapper.createObjectNode(); + resp.set("taskSet", taskSetNode(ts)); + return Response.ok(resp).build(); + } + + // ── Service Deployments & Revisions ─────────────────────────────────────── + + private Response handleDescribeServiceDeployments(JsonNode req, String region) { + List arns = jsonArrayToList(req.path("serviceDeploymentArns")); + List found = service.describeServiceDeployments(arns); + ObjectNode resp = objectMapper.createObjectNode(); + ArrayNode arr = objectMapper.createArrayNode(); + found.forEach(d -> arr.add(serviceDeploymentNode(d))); + resp.set("serviceDeployments", arr); + return Response.ok(resp).build(); + } + + private Response handleListServiceDeployments(JsonNode req, String region) { + String svc = req.path("service").asText(); + String cluster = req.has("cluster") ? req.path("cluster").asText() : null; + List statusFilter = req.has("status") ? jsonArrayToList(req.path("status")) : null; + + List deployments = service.listServiceDeploymentsDetailed(svc, cluster, statusFilter, region); + + ObjectNode resp = objectMapper.createObjectNode(); + ArrayNode arr = objectMapper.createArrayNode(); + deployments.forEach(d -> { + ObjectNode brief = objectMapper.createObjectNode(); + brief.put("serviceDeploymentArn", d.getServiceDeploymentArn()); + brief.put("serviceArn", d.getServiceArn()); + brief.put("clusterArn", d.getClusterArn()); + brief.put("status", d.getStatus()); + if (d.getCreatedAt() != null) { brief.put("createdAt", d.getCreatedAt().toEpochMilli() / 1000.0); } + if (d.getUpdatedAt() != null) { brief.put("finishedAt", d.getUpdatedAt().toEpochMilli() / 1000.0); } + arr.add(brief); + }); + resp.set("serviceDeployments", arr); + return Response.ok(resp).build(); + } + + private Response handleDescribeServiceRevisions(JsonNode req, String region) { + List arns = jsonArrayToList(req.path("serviceRevisionArns")); + List found = service.describeServiceRevisions(arns); + ObjectNode resp = objectMapper.createObjectNode(); + ArrayNode arr = objectMapper.createArrayNode(); + found.forEach(r -> arr.add(serviceRevisionNode(r))); + resp.set("serviceRevisions", arr); + return Response.ok(resp).build(); + } + + // ── Stubs ───────────────────────────────────────────────────────────────── + + private Response handleSubmitTaskStateChange(JsonNode req, String region) { + String ack = service.submitTaskStateChange(); + ObjectNode resp = objectMapper.createObjectNode(); + resp.put("acknowledgment", ack); + return Response.ok(resp).build(); + } + + private Response handleSubmitContainerStateChange(JsonNode req, String region) { + String ack = service.submitContainerStateChange(); + ObjectNode resp = objectMapper.createObjectNode(); + resp.put("acknowledgment", ack); + return Response.ok(resp).build(); + } + + private Response handleSubmitAttachmentStateChanges(JsonNode req, String region) { + String ack = service.submitAttachmentStateChanges(); + ObjectNode resp = objectMapper.createObjectNode(); + resp.put("acknowledgment", ack); + return Response.ok(resp).build(); + } + + private Response handleDiscoverPollEndpoint(JsonNode req, String region) { + String baseUrl = service.getBaseUrl(); + ObjectNode resp = objectMapper.createObjectNode(); + resp.put("endpoint", baseUrl); + resp.put("telemetryEndpoint", baseUrl); + resp.put("serviceConnectEndpoint", baseUrl); + return Response.ok(resp).build(); + } + + // ── JSON serialization ──────────────────────────────────────────────────── + + private ObjectNode clusterNode(EcsCluster c) { + ObjectNode n = objectMapper.createObjectNode(); + n.put("clusterArn", c.getClusterArn()); + n.put("clusterName", c.getClusterName()); + n.put("status", c.getStatus()); + n.put("registeredContainerInstancesCount", c.getRegisteredContainerInstancesCount()); + n.put("runningTasksCount", c.getRunningTasksCount()); + n.put("pendingTasksCount", c.getPendingTasksCount()); + n.put("activeServicesCount", c.getActiveServicesCount()); + if (c.getSettings() != null && !c.getSettings().isEmpty()) { + ArrayNode settings = objectMapper.createArrayNode(); + c.getSettings().forEach(s -> { + ObjectNode sn = objectMapper.createObjectNode(); + sn.put("name", s.name()); + sn.put("value", s.value()); + settings.add(sn); + }); + n.set("settings", settings); + } + if (c.getCapacityProviders() != null) { + ArrayNode cp = objectMapper.createArrayNode(); + c.getCapacityProviders().forEach(cp::add); + n.set("capacityProviders", cp); + } + if (c.getTags() != null && !c.getTags().isEmpty()) { + n.set("tags", tagsNode(c.getTags())); + } + return n; + } + + private ObjectNode taskDefinitionNode(TaskDefinition td) { + ObjectNode n = objectMapper.createObjectNode(); + n.put("taskDefinitionArn", td.getTaskDefinitionArn()); + n.put("family", td.getFamily()); + n.put("revision", td.getRevision()); + n.put("status", td.getStatus()); + if (td.getNetworkMode() != null) { + n.put("networkMode", td.getNetworkMode().name()); + } + if (td.getCpu() != null) { n.put("cpu", td.getCpu()); } + if (td.getMemory() != null) { n.put("memory", td.getMemory()); } + + ArrayNode containers = objectMapper.createArrayNode(); + if (td.getContainerDefinitions() != null) { + for (var def : td.getContainerDefinitions()) { + containers.add(containerDefinitionNode(def)); + } + } + n.set("containerDefinitions", containers); + if (td.getTags() != null && !td.getTags().isEmpty()) { + n.set("tags", tagsNode(td.getTags())); + } + return n; + } + + private ObjectNode containerDefinitionNode(ContainerDefinition def) { + ObjectNode n = objectMapper.createObjectNode(); + n.put("name", def.getName()); + n.put("image", def.getImage()); + 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.getPortMappings() != null && !def.getPortMappings().isEmpty()) { + ArrayNode pms = objectMapper.createArrayNode(); + for (PortMapping pm : def.getPortMappings()) { + ObjectNode pmNode = objectMapper.createObjectNode(); + pmNode.put("containerPort", pm.containerPort()); + pmNode.put("hostPort", pm.hostPort()); + pmNode.put("protocol", pm.protocol()); + pms.add(pmNode); + } + n.set("portMappings", pms); + } + + if (def.getEnvironment() != null && !def.getEnvironment().isEmpty()) { + ArrayNode envArr = objectMapper.createArrayNode(); + for (KeyValuePair kv : def.getEnvironment()) { + ObjectNode kvNode = objectMapper.createObjectNode(); + kvNode.put("name", kv.name()); + kvNode.put("value", kv.value()); + envArr.add(kvNode); + } + n.set("environment", envArr); + } + + return n; + } + + private ObjectNode taskNode(EcsTask t) { + ObjectNode n = objectMapper.createObjectNode(); + n.put("taskArn", t.getTaskArn()); + n.put("clusterArn", t.getClusterArn()); + 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()); } + if (t.getCpu() != null) { n.put("cpu", t.getCpu()); } + if (t.getMemory() != null) { n.put("memory", t.getMemory()); } + 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.getStoppedReason() != null) { n.put("stoppedReason", t.getStoppedReason()); } + + ArrayNode containers = objectMapper.createArrayNode(); + if (t.getContainers() != null) { + for (var c : t.getContainers()) { + ObjectNode cn = objectMapper.createObjectNode(); + cn.put("containerArn", c.getContainerArn()); + cn.put("taskArn", c.getTaskArn()); + cn.put("name", c.getName()); + cn.put("image", c.getImage()); + cn.put("lastStatus", c.getLastStatus()); + if (c.getExitCode() != null) { cn.put("exitCode", c.getExitCode()); } + if (c.getReason() != null) { cn.put("reason", c.getReason()); } + + ArrayNode bindings = objectMapper.createArrayNode(); + if (c.getNetworkBindings() != null) { + for (NetworkBinding nb : c.getNetworkBindings()) { + ObjectNode bn = objectMapper.createObjectNode(); + bn.put("bindIP", nb.bindIP()); + bn.put("containerPort", nb.containerPort()); + bn.put("hostPort", nb.hostPort()); + bn.put("protocol", nb.protocol()); + bindings.add(bn); + } + } + cn.set("networkBindings", bindings); + containers.add(cn); + } + } + n.set("containers", containers); + if (t.getTags() != null && !t.getTags().isEmpty()) { + n.set("tags", tagsNode(t.getTags())); + } + return n; + } + + private ObjectNode serviceNode(EcsServiceModel s) { + ObjectNode n = objectMapper.createObjectNode(); + n.put("serviceArn", s.getServiceArn()); + n.put("serviceName", s.getServiceName()); + n.put("clusterArn", s.getClusterArn()); + n.put("taskDefinition", s.getTaskDefinition()); + n.put("desiredCount", s.getDesiredCount()); + 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.getNamespace() != null) { n.put("namespace", s.getNamespace()); } + if (s.getTags() != null && !s.getTags().isEmpty()) { + n.set("tags", tagsNode(s.getTags())); + } + return n; + } + + private ObjectNode containerInstanceNode(ContainerInstance ci) { + ObjectNode n = objectMapper.createObjectNode(); + n.put("containerInstanceArn", ci.getContainerInstanceArn()); + n.put("ec2InstanceId", ci.getEc2InstanceId()); + n.put("status", ci.getStatus()); + n.put("runningTasksCount", ci.getRunningTasksCount()); + n.put("pendingTasksCount", ci.getPendingTasksCount()); + n.put("agentVersion", ci.getAgentVersion()); + n.put("agentConnected", ci.isAgentConnected()); + if (ci.getAttributes() != null && !ci.getAttributes().isEmpty()) { + ArrayNode attrs = objectMapper.createArrayNode(); + ci.getAttributes().forEach(a -> attrs.add(attributeNode(a))); + n.set("attributes", attrs); + } + if (ci.getTags() != null && !ci.getTags().isEmpty()) { + n.set("tags", tagsNode(ci.getTags())); + } + return n; + } + + private ObjectNode capacityProviderNode(CapacityProvider cp) { + ObjectNode n = objectMapper.createObjectNode(); + n.put("name", cp.getName()); + n.put("status", cp.getStatus()); + if (cp.getCapacityProviderArn() != null) { n.put("capacityProviderArn", cp.getCapacityProviderArn()); } + if (cp.getTags() != null && !cp.getTags().isEmpty()) { + n.set("tags", tagsNode(cp.getTags())); + } + return n; + } + + private ObjectNode taskSetNode(TaskSet ts) { + ObjectNode n = objectMapper.createObjectNode(); + n.put("id", ts.getId()); + n.put("taskSetArn", ts.getTaskSetArn()); + n.put("serviceArn", ts.getServiceArn()); + n.put("clusterArn", ts.getClusterArn()); + n.put("taskDefinition", ts.getTaskDefinition()); + n.put("status", ts.getStatus()); + n.put("computedDesiredCount", ts.getComputedDesiredCount()); + n.put("pendingCount", ts.getPendingCount()); + n.put("runningCount", ts.getRunningCount()); + n.put("stabilityStatus", ts.getStabilityStatus()); + if (ts.getLaunchType() != null) { n.put("launchType", ts.getLaunchType().name()); } + if (ts.getExternalId() != null) { n.put("externalId", ts.getExternalId()); } + ObjectNode scale = objectMapper.createObjectNode(); + scale.put("value", ts.getScaleValue()); + scale.put("unit", ts.getScaleUnit()); + n.set("scale", scale); + if (ts.getCreatedAt() != null) { n.put("createdAt", ts.getCreatedAt().toEpochMilli() / 1000.0); } + if (ts.getUpdatedAt() != null) { n.put("updatedAt", ts.getUpdatedAt().toEpochMilli() / 1000.0); } + if (ts.getTags() != null && !ts.getTags().isEmpty()) { + n.set("tags", tagsNode(ts.getTags())); + } + return n; + } + + private ObjectNode serviceDeploymentNode(ServiceDeployment d) { + ObjectNode n = objectMapper.createObjectNode(); + n.put("serviceDeploymentArn", d.getServiceDeploymentArn()); + n.put("serviceArn", d.getServiceArn()); + n.put("clusterArn", d.getClusterArn()); + n.put("taskDefinition", d.getTaskDefinition()); + n.put("status", d.getStatus()); + if (d.getCreatedAt() != null) { n.put("createdAt", d.getCreatedAt().toEpochMilli() / 1000.0); } + if (d.getUpdatedAt() != null) { n.put("updatedAt", d.getUpdatedAt().toEpochMilli() / 1000.0); } + return n; + } + + private ObjectNode serviceRevisionNode(ServiceRevision r) { + ObjectNode n = objectMapper.createObjectNode(); + n.put("serviceRevisionArn", r.getServiceRevisionArn()); + n.put("serviceArn", r.getServiceArn()); + n.put("clusterArn", r.getClusterArn()); + n.put("taskDefinition", r.getTaskDefinition()); + if (r.getLaunchType() != null) { n.put("launchType", r.getLaunchType().name()); } + if (r.getCreatedAt() != null) { n.put("createdAt", r.getCreatedAt().toEpochMilli() / 1000.0); } + return n; + } + + private 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); + } + return n; + } + + private ObjectNode attributeNode(Attribute a) { + ObjectNode n = objectMapper.createObjectNode(); + n.put("name", a.name()); + if (a.value() != null) { n.put("value", a.value()); } + if (a.targetType() != null) { n.put("targetType", a.targetType()); } + if (a.targetId() != null) { n.put("targetId", a.targetId()); } + return n; + } + + private ObjectNode settingNode(String name, String value) { + ObjectNode n = objectMapper.createObjectNode(); + n.put("name", name); + n.put("value", value); + return n; + } + + private ArrayNode tagsNode(Map tags) { + ArrayNode arr = objectMapper.createArrayNode(); + tags.forEach((k, v) -> { + ObjectNode tag = objectMapper.createObjectNode(); + tag.put("key", k); + tag.put("value", v); + arr.add(tag); + }); + return arr; + } + + // ── Parsing helpers ─────────────────────────────────────────────────────── + + private List parseContainerDefinitions(JsonNode node) { + List result = new ArrayList<>(); + if (!node.isArray()) { + return result; + } + for (JsonNode item : node) { + ContainerDefinition def = new ContainerDefinition(); + def.setName(item.path("name").asText()); + def.setImage(item.path("image").asText()); + def.setEssential(item.path("essential").asBoolean(true)); + if (item.has("cpu")) { def.setCpu(item.path("cpu").asInt()); } + if (item.has("memory")) { def.setMemory(item.path("memory").asInt()); } + if (item.has("memoryReservation")) { def.setMemoryReservation(item.path("memoryReservation").asInt()); } + + def.setPortMappings(parsePortMappings(item.path("portMappings"))); + def.setEnvironment(parseKeyValuePairs(item.path("environment"))); + + if (item.has("command") && item.path("command").isArray()) { + List cmd = new ArrayList<>(); + item.path("command").forEach(c -> cmd.add(c.asText())); + def.setCommand(cmd); + } + if (item.has("entryPoint") && item.path("entryPoint").isArray()) { + List ep = new ArrayList<>(); + item.path("entryPoint").forEach(e -> ep.add(e.asText())); + def.setEntryPoint(ep); + } + + result.add(def); + } + return result; + } + + private List parsePortMappings(JsonNode node) { + List result = new ArrayList<>(); + if (!node.isArray()) { + return result; + } + for (JsonNode item : node) { + 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)); + } + return result; + } + + private List parseKeyValuePairs(JsonNode node) { + List result = new ArrayList<>(); + if (!node.isArray()) { + return result; + } + for (JsonNode item : node) { + result.add(new KeyValuePair(item.path("name").asText(), item.path("value").asText())); + } + return result; + } + + private List parseClusterSettings(JsonNode node) { + List result = new ArrayList<>(); + if (!node.isArray()) { + return result; + } + for (JsonNode item : node) { + result.add(new ClusterSetting(item.path("name").asText(), item.path("value").asText())); + } + return result; + } + + private List parseAttributes(JsonNode node) { + List result = new ArrayList<>(); + if (!node.isArray()) { + return result; + } + for (JsonNode item : node) { + result.add(new Attribute( + item.path("name").asText(), + item.has("value") ? item.path("value").asText() : null, + item.has("targetType") ? item.path("targetType").asText() : null, + item.has("targetId") ? item.path("targetId").asText() : null + )); + } + return result; + } + + private Map parseTagMap(JsonNode node) { + Map result = new HashMap<>(); + if (!node.isArray()) { + return result; + } + for (JsonNode item : node) { + result.put(item.path("key").asText(), item.path("value").asText()); + } + return result; + } + + private Map parseRawObject(JsonNode node) { + if (node == null || node.isMissingNode()) { + return null; + } + return objectMapper.convertValue(node, Map.class); + } + + private List> parseRawObjectList(JsonNode node) { + List> result = new ArrayList<>(); + if (!node.isArray()) { + return result; + } + for (JsonNode item : node) { + result.add(objectMapper.convertValue(item, Map.class)); + } + return result; + } + + private List jsonArrayToList(JsonNode node) { + List result = new ArrayList<>(); + if (node.isArray()) { + node.forEach(n -> result.add(n.asText())); + } + return result; + } + + private > T parseEnum(JsonNode req, String field, Class enumClass) { + if (!req.has(field)) { + return null; + } + String val = req.path(field).asText(); + try { + return Enum.valueOf(enumClass, val); + } catch (IllegalArgumentException e) { + return null; + } + } +} 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 new file mode 100644 index 0000000000..e06d72ec83 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/ecs/EcsService.java @@ -0,0 +1,1181 @@ +package io.github.hectorvent.floci.services.ecs; + +import io.github.hectorvent.floci.config.EmulatorConfig; +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.common.RegionResolver; +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.ClusterSetting; +import io.github.hectorvent.floci.services.ecs.model.ContainerDefinition; +import io.github.hectorvent.floci.services.ecs.model.ContainerInstance; +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.EcsTask; +import io.github.hectorvent.floci.services.ecs.model.LaunchType; +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.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.TaskSet; +import io.github.hectorvent.floci.services.ecs.model.TaskStatus; +import jakarta.annotation.PostConstruct; +import jakarta.annotation.PreDestroy; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import org.jboss.logging.Logger; + +import java.time.Instant; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; +import java.util.stream.Stream; + +@ApplicationScoped +public class EcsService { + + private static final Logger LOG = Logger.getLogger(EcsService.class); + private static final String DEFAULT_CLUSTER = "default"; + + private final RegionResolver regionResolver; + private final EcsContainerManager containerManager; + private final boolean dockerMode; + private final String baseUrl; + private final ScheduledExecutorService reconciler = Executors.newSingleThreadScheduledExecutor( + r -> { Thread t = new Thread(r, "ecs-reconciler"); t.setDaemon(true); return t; }); + + // region::clusterName → EcsCluster + private final Map clusters = new ConcurrentHashMap<>(); + // family:revision → TaskDefinition + private final Map taskDefinitions = new ConcurrentHashMap<>(); + // family → latest revision number + private final Map latestRevisions = new ConcurrentHashMap<>(); + // taskArn → EcsTask + private final Map tasks = new ConcurrentHashMap<>(); + // taskArn → EcsTaskHandle (running containers) + private final Map taskHandles = new ConcurrentHashMap<>(); + // region::clusterName/serviceName → EcsServiceModel + private final Map services = new ConcurrentHashMap<>(); + // region::clusterArn/instanceArn → ContainerInstance + private final Map containerInstances = new ConcurrentHashMap<>(); + // name → CapacityProvider (excludes built-ins FARGATE, FARGATE_SPOT) + private final Map capacityProviders = new ConcurrentHashMap<>(); + // taskSetArn → TaskSet + private final Map taskSets = new ConcurrentHashMap<>(); + // serviceDeploymentArn → ServiceDeployment + private final Map serviceDeployments = new ConcurrentHashMap<>(); + // serviceRevisionArn → ServiceRevision + private final Map serviceRevisions = new ConcurrentHashMap<>(); + // targetArn → List + private final Map> attributes = new ConcurrentHashMap<>(); + // name → value (account-level settings) + private final Map accountSettings = new ConcurrentHashMap<>(); + + @Inject + public EcsService(RegionResolver regionResolver, EcsContainerManager containerManager, + EmulatorConfig config) { + this(regionResolver, containerManager, !config.services().ecs().mock(), + config.effectiveBaseUrl()); + } + + EcsService(RegionResolver regionResolver, EcsContainerManager containerManager) { + this(regionResolver, containerManager, false, "http://localhost:4566"); + } + + EcsService(RegionResolver regionResolver, EcsContainerManager containerManager, boolean dockerMode, + String baseUrl) { + this.regionResolver = regionResolver; + this.containerManager = containerManager; + this.dockerMode = dockerMode; + this.baseUrl = baseUrl; + } + + @PostConstruct + void init() { + reconciler.scheduleAtFixedRate(this::reconcileServices, 5, 5, TimeUnit.SECONDS); + } + + @PreDestroy + void shutdown() { + reconciler.shutdownNow(); + } + + // ── Clusters ───────────────────────────────────────────────────────────── + + public EcsCluster createCluster(String clusterName, String region) { + String name = (clusterName == null || clusterName.isBlank()) ? DEFAULT_CLUSTER : clusterName; + String key = clusterKey(region, name); + if (clusters.containsKey(key)) { + return clusters.get(key); + } + EcsCluster cluster = new EcsCluster(); + cluster.setClusterName(name); + cluster.setClusterArn(regionResolver.buildArn("ecs", region, "cluster/" + name)); + cluster.setStatus("ACTIVE"); + clusters.put(key, cluster); + LOG.infov("Created ECS cluster: {0} in {1}", name, region); + return cluster; + } + + public List describeClusters(List clusterIds, String region) { + if (clusterIds == null || clusterIds.isEmpty()) { + return List.of(getOrCreateDefaultCluster(region)); + } + List result = new ArrayList<>(); + for (String id : clusterIds) { + EcsCluster cluster = resolveCluster(id, region); + if (cluster != null) { + result.add(cluster); + } + } + return result; + } + + public List listClusters(String region) { + String prefix = region + "::"; + return clusters.entrySet().stream() + .filter(e -> e.getKey().startsWith(prefix)) + .map(e -> e.getValue().getClusterArn()) + .toList(); + } + + public EcsCluster deleteCluster(String clusterId, String region) { + EcsCluster cluster = resolveClusterOrThrow(clusterId, region); + long runningTasks = tasks.values().stream() + .filter(t -> t.getClusterArn().equals(cluster.getClusterArn())) + .filter(t -> !TaskStatus.STOPPED.name().equals(t.getLastStatus())) + .count(); + if (runningTasks > 0) { + throw new AwsException("ClusterContainsTasksException", + "The cluster cannot be deleted because it contains running tasks.", 400); + } + clusters.remove(clusterKey(region, cluster.getClusterName())); + cluster.setStatus("INACTIVE"); + return cluster; + } + + public EcsCluster updateCluster(String clusterRef, List settings, String region) { + EcsCluster cluster = resolveClusterOrThrow(clusterRef, region); + if (settings != null) { + cluster.setSettings(settings); + } + return cluster; + } + + public EcsCluster updateClusterSettings(String clusterRef, List settings, String region) { + EcsCluster cluster = resolveClusterOrThrow(clusterRef, region); + cluster.setSettings(settings); + return cluster; + } + + public EcsCluster putClusterCapacityProviders(String clusterRef, List providers, + List> defaultStrategy, String region) { + EcsCluster cluster = resolveClusterOrThrow(clusterRef, region); + cluster.setCapacityProviders(providers); + cluster.setDefaultCapacityProviderStrategy(defaultStrategy); + return cluster; + } + + // ── Task Definitions ────────────────────────────────────────────────────── + + public TaskDefinition registerTaskDefinition(String family, List containerDefs, + NetworkMode networkMode, String cpu, String memory, + String region) { + int revision = latestRevisions.merge(family, 1, Integer::sum); + + TaskDefinition td = new TaskDefinition(); + td.setFamily(family); + td.setRevision(revision); + td.setStatus("ACTIVE"); + td.setNetworkMode(networkMode != null ? networkMode : NetworkMode.bridge); + td.setCpu(cpu); + td.setMemory(memory); + td.setContainerDefinitions(containerDefs != null ? containerDefs : List.of()); + td.setTaskDefinitionArn(regionResolver.buildArn("ecs", region, + "task-definition/" + family + ":" + revision)); + + taskDefinitions.put(family + ":" + revision, td); + LOG.infov("Registered task definition: {0}:{1}", family, revision); + return td; + } + + public TaskDefinition describeTaskDefinition(String taskDefinitionRef, String region) { + return resolveTaskDefinitionOrThrow(taskDefinitionRef, region); + } + + public List listTaskDefinitions(String familyPrefix, String status) { + return taskDefinitions.values().stream() + .filter(td -> familyPrefix == null || td.getFamily().startsWith(familyPrefix)) + .filter(td -> status == null || status.equals(td.getStatus())) + .map(TaskDefinition::getTaskDefinitionArn) + .sorted() + .toList(); + } + + public List listTaskDefinitionFamilies(String familyPrefix) { + return latestRevisions.keySet().stream() + .filter(f -> familyPrefix == null || f.startsWith(familyPrefix)) + .sorted() + .toList(); + } + + public TaskDefinition deregisterTaskDefinition(String taskDefinitionRef, String region) { + TaskDefinition td = resolveTaskDefinitionOrThrow(taskDefinitionRef, region); + td.setStatus("INACTIVE"); + return td; + } + + public List deleteTaskDefinitions(List taskDefinitionRefs, String region) { + List deleted = new ArrayList<>(); + for (String ref : taskDefinitionRefs) { + TaskDefinition td = resolveTaskDefinitionOrThrow(ref, region); + if (!"INACTIVE".equals(td.getStatus())) { + throw new AwsException("InvalidParameterException", + "Task definition " + ref + " must be INACTIVE before deletion.", 400); + } + taskDefinitions.remove(td.getFamily() + ":" + td.getRevision()); + deleted.add(td); + } + return deleted; + } + + // ── Tasks ───────────────────────────────────────────────────────────────── + + public List runTask(String clusterRef, String taskDefinitionRef, int count, + LaunchType launchType, String group, String startedBy, String region) { + EcsCluster cluster = resolveClusterOrDefault(clusterRef, region); + TaskDefinition taskDef = resolveTaskDefinitionOrThrow(taskDefinitionRef, region); + return launchTasks(cluster, taskDef, count, launchType, group, startedBy, null, region); + } + + public List startTask(String clusterRef, List containerInstanceRefs, + String taskDefinitionRef, String group, String startedBy, String region) { + EcsCluster cluster = resolveClusterOrDefault(clusterRef, region); + TaskDefinition taskDef = resolveTaskDefinitionOrThrow(taskDefinitionRef, region); + List result = new ArrayList<>(); + for (String instanceRef : containerInstanceRefs) { + ContainerInstance instance = resolveContainerInstanceOrThrow(cluster.getClusterArn(), instanceRef); + List launched = launchTasks(cluster, taskDef, 1, LaunchType.EC2, + group, startedBy, instance.getContainerInstanceArn(), region); + result.addAll(launched); + } + return result; + } + + private List launchTasks(EcsCluster cluster, TaskDefinition taskDef, int count, + LaunchType launchType, String group, String startedBy, + String containerInstanceArn, String region) { + 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); + + 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.setLastStatus(TaskStatus.PENDING.name()); + task.setDesiredStatus(TaskStatus.RUNNING.name()); + task.setCpu(taskDef.getCpu()); + task.setMemory(taskDef.getMemory()); + task.setCreatedAt(Instant.now()); + task.setContainers(List.of()); + task.setContainerInstanceArn(containerInstanceArn); + + tasks.put(taskArn, task); + + if (dockerMode) { + try { + EcsTaskHandle handle = containerManager.startTask(task, taskDef, region); + taskHandles.put(taskArn, handle); + cluster.setRunningTasksCount(cluster.getRunningTasksCount() + 1); + LOG.infov("Started ECS task (docker): {0}", taskArn); + } catch (Exception e) { + LOG.errorv("Failed to start ECS task {0}: {1}", taskArn, e.getMessage()); + task.setLastStatus(TaskStatus.STOPPED.name()); + task.setDesiredStatus(TaskStatus.STOPPED.name()); + task.setStoppedReason("Failed to start: " + e.getMessage()); + task.setStoppedAt(Instant.now()); + } + } else { + task.setLastStatus(TaskStatus.RUNNING.name()); + task.setStartedAt(Instant.now()); + cluster.setRunningTasksCount(cluster.getRunningTasksCount() + 1); + LOG.infov("Started ECS task (mock): {0}", taskArn); + } + + launched.add(task); + } + return launched; + } + + public EcsTask stopTask(String clusterRef, String taskRef, String reason, String region) { + EcsTask task = resolveTaskOrThrow(taskRef, region); + task.setDesiredStatus(TaskStatus.STOPPED.name()); + task.setLastStatus(TaskStatus.STOPPING.name()); + task.setStoppedReason(reason != null ? reason : "Stopped by user"); + + if (dockerMode) { + EcsTaskHandle handle = taskHandles.remove(task.getTaskArn()); + containerManager.stopTask(handle); + } + + task.setLastStatus(TaskStatus.STOPPED.name()); + task.setStoppedAt(Instant.now()); + if (task.getContainers() != null) { + task.getContainers().forEach(c -> c.setLastStatus("STOPPED")); + } + + EcsCluster cluster = resolveClusterByArn(task.getClusterArn()); + if (cluster != null && cluster.getRunningTasksCount() > 0) { + cluster.setRunningTasksCount(cluster.getRunningTasksCount() - 1); + } + + LOG.infov("Stopped ECS task: {0}", task.getTaskArn()); + return task; + } + + public List describeTasks(String clusterRef, List taskRefs, String region) { + List result = new ArrayList<>(); + for (String ref : taskRefs) { + EcsTask task = resolveTask(ref, region); + if (task != null) { + result.add(task); + } + } + return result; + } + + public List listTasks(String clusterRef, String family, String desiredStatus, + String serviceName, String region) { + String clusterArn = clusterRef != null + ? resolveClusterOrDefault(clusterRef, region).getClusterArn() + : null; + + return tasks.values().stream() + .filter(t -> clusterArn == null || t.getClusterArn().equals(clusterArn)) + .filter(t -> family == null || t.getTaskDefinitionArn().contains("/" + family + ":")) + .filter(t -> desiredStatus == null || desiredStatus.equals(t.getDesiredStatus())) + .filter(t -> serviceName == null || serviceName.equals(t.getGroup())) + .map(EcsTask::getTaskArn) + .toList(); + } + + // ── Task Protection ─────────────────────────────────────────────────────── + + public List updateTaskProtection(String clusterRef, List taskRefs, + boolean protectionEnabled, Integer expiresInMinutes, + String region) { + List result = new ArrayList<>(); + for (String ref : taskRefs) { + EcsTask task = resolveTaskOrThrow(ref, region); + task.setProtectionEnabled(protectionEnabled); + Instant expiration = null; + if (protectionEnabled && expiresInMinutes != null) { + expiration = Instant.now().plusSeconds(expiresInMinutes * 60L); + task.setProtectedUntil(expiration); + } else { + task.setProtectedUntil(null); + } + result.add(new ProtectedTask(task.getTaskArn(), protectionEnabled, expiration)); + } + return result; + } + + public List getTaskProtection(String clusterRef, List taskRefs, String region) { + List result = new ArrayList<>(); + for (String ref : taskRefs) { + EcsTask task = resolveTaskOrThrow(ref, region); + result.add(new ProtectedTask(task.getTaskArn(), task.isProtectionEnabled(), task.getProtectedUntil())); + } + return result; + } + + // ── Services ────────────────────────────────────────────────────────────── + + public EcsServiceModel createService(String clusterRef, String serviceName, String taskDefinition, + int desiredCount, LaunchType launchType, String region) { + EcsCluster cluster = resolveClusterOrDefault(clusterRef, region); + resolveTaskDefinitionOrThrow(taskDefinition, region); + + String key = serviceKey(region, cluster.getClusterName(), serviceName); + if (services.containsKey(key)) { + throw new AwsException("InvalidParameterException", + "Creation of service was not idempotent.", 400); + } + + EcsServiceModel svc = new EcsServiceModel(); + svc.setServiceArn(regionResolver.buildArn("ecs", region, + "service/" + cluster.getClusterName() + "/" + serviceName)); + svc.setServiceName(serviceName); + svc.setClusterArn(cluster.getClusterArn()); + svc.setTaskDefinition(taskDefinition); + svc.setLaunchType(launchType != null ? launchType : LaunchType.FARGATE); + svc.setDesiredCount(desiredCount); + svc.setStatus("ACTIVE"); + svc.setCreatedAt(Instant.now()); + + services.put(key, svc); + cluster.setActiveServicesCount(cluster.getActiveServicesCount() + 1); + recordServiceDeployment(svc, taskDefinition, region); + LOG.infov("Created ECS service: {0} in cluster {1}", serviceName, cluster.getClusterName()); + return svc; + } + + public EcsServiceModel updateService(String clusterRef, String serviceName, String taskDefinition, + Integer desiredCount, String region) { + EcsCluster cluster = resolveClusterOrDefault(clusterRef, region); + String key = serviceKey(region, cluster.getClusterName(), serviceName); + EcsServiceModel svc = services.get(key); + if (svc == null) { + throw new AwsException("ServiceNotFoundException", "Service " + serviceName + " not found.", 404); + } + if (desiredCount != null) { + svc.setDesiredCount(desiredCount); + } + if (taskDefinition != null) { + resolveTaskDefinitionOrThrow(taskDefinition, region); + svc.setTaskDefinition(taskDefinition); + recordServiceDeployment(svc, taskDefinition, region); + } + return svc; + } + + public EcsServiceModel deleteService(String clusterRef, String serviceName, String region) { + EcsCluster cluster = resolveClusterOrDefault(clusterRef, region); + String key = serviceKey(region, cluster.getClusterName(), serviceName); + EcsServiceModel svc = services.remove(key); + if (svc == null) { + throw new AwsException("ServiceNotFoundException", "Service " + serviceName + " not found.", 404); + } + svc.setStatus("INACTIVE"); + svc.setDesiredCount(0); + cluster.setActiveServicesCount(Math.max(0, cluster.getActiveServicesCount() - 1)); + return svc; + } + + public List describeServices(String clusterRef, List serviceIds, String region) { + EcsCluster cluster = resolveClusterOrDefault(clusterRef, region); + List result = new ArrayList<>(); + for (String id : serviceIds) { + EcsServiceModel svc = resolveService(cluster.getClusterName(), id, region); + if (svc != null) { + result.add(svc); + } + } + return result; + } + + public List listServices(String clusterRef, String region) { + EcsCluster cluster = resolveClusterOrDefault(clusterRef, region); + String prefix = serviceKeyPrefix(region, cluster.getClusterName()); + return services.entrySet().stream() + .filter(e -> e.getKey().startsWith(prefix)) + .map(e -> e.getValue().getServiceArn()) + .toList(); + } + + public List listServicesByNamespace(String namespace, String region) { + return services.values().stream() + .filter(s -> namespace.equals(s.getNamespace())) + .map(EcsServiceModel::getServiceArn) + .toList(); + } + + // ── Tags ────────────────────────────────────────────────────────────────── + + public void tagResource(String resourceArn, Map tags) { + Object resource = findByArn(resourceArn); + if (resource == null) { + throw new AwsException("InvalidParameterException", "Resource not found: " + resourceArn, 400); + } + mergeTagsOnResource(resource, tags); + } + + public void untagResource(String resourceArn, List tagKeys) { + Object resource = findByArn(resourceArn); + if (resource == null) { + throw new AwsException("InvalidParameterException", "Resource not found: " + resourceArn, 400); + } + removeTagsFromResource(resource, tagKeys); + } + + public Map listTagsForResource(String resourceArn) { + Object resource = findByArn(resourceArn); + if (resource == null) { + throw new AwsException("InvalidParameterException", "Resource not found: " + resourceArn, 400); + } + return getTagsFromResource(resource); + } + + private Object findByArn(String arn) { + for (EcsCluster c : clusters.values()) { + if (arn.equals(c.getClusterArn())) { return c; } + } + for (TaskDefinition td : taskDefinitions.values()) { + if (arn.equals(td.getTaskDefinitionArn())) { return td; } + } + for (EcsTask t : tasks.values()) { + if (arn.equals(t.getTaskArn())) { return t; } + } + for (EcsServiceModel s : services.values()) { + if (arn.equals(s.getServiceArn())) { return s; } + } + for (ContainerInstance ci : containerInstances.values()) { + if (arn.equals(ci.getContainerInstanceArn())) { return ci; } + } + for (CapacityProvider cp : capacityProviders.values()) { + if (arn.equals(cp.getCapacityProviderArn())) { return cp; } + } + return null; + } + + private void mergeTagsOnResource(Object resource, Map tags) { + if (resource instanceof EcsCluster c) { c.getTags().putAll(tags); } + else if (resource instanceof TaskDefinition td) { td.getTags().putAll(tags); } + else if (resource instanceof EcsTask t) { t.getTags().putAll(tags); } + else if (resource instanceof EcsServiceModel s) { s.getTags().putAll(tags); } + else if (resource instanceof ContainerInstance ci) { ci.getTags().putAll(tags); } + else if (resource instanceof CapacityProvider cp) { cp.getTags().putAll(tags); } + } + + private void removeTagsFromResource(Object resource, List tagKeys) { + if (resource instanceof EcsCluster c) { tagKeys.forEach(c.getTags()::remove); } + else if (resource instanceof TaskDefinition td) { tagKeys.forEach(td.getTags()::remove); } + else if (resource instanceof EcsTask t) { tagKeys.forEach(t.getTags()::remove); } + else if (resource instanceof EcsServiceModel s) { tagKeys.forEach(s.getTags()::remove); } + else if (resource instanceof ContainerInstance ci) { tagKeys.forEach(ci.getTags()::remove); } + else if (resource instanceof CapacityProvider cp) { tagKeys.forEach(cp.getTags()::remove); } + } + + private Map getTagsFromResource(Object resource) { + return switch (resource) { + case EcsCluster c -> c.getTags(); + case TaskDefinition td -> td.getTags(); + case EcsTask t -> t.getTags(); + case EcsServiceModel s -> s.getTags(); + case ContainerInstance ci -> ci.getTags(); + case CapacityProvider cp -> cp.getTags(); + default -> Map.of(); + }; + } + + // ── Account Settings ────────────────────────────────────────────────────── + + public Map.Entry putAccountSetting(String name, String value) { + accountSettings.put(name, value); + return Map.entry(name, value); + } + + public Map.Entry putAccountSettingDefault(String name, String value) { + accountSettings.put(name, value); + return Map.entry(name, value); + } + + public Map.Entry deleteAccountSetting(String name) { + String removed = accountSettings.remove(name); + return Map.entry(name, removed != null ? removed : ""); + } + + public List> listAccountSettings(String filterName, String filterValue) { + return accountSettings.entrySet().stream() + .filter(e -> filterName == null || filterName.equals(e.getKey())) + .filter(e -> filterValue == null || filterValue.equals(e.getValue())) + .toList(); + } + + // ── Attributes ──────────────────────────────────────────────────────────── + + public List putAttributes(String clusterRef, List attrs, String region) { + List stored = new ArrayList<>(); + for (Attribute attr : attrs) { + String targetId = attr.targetId(); + List existing = attributes.computeIfAbsent(targetId, k -> new ArrayList<>()); + existing.removeIf(a -> a.name().equals(attr.name())); + existing.add(attr); + stored.add(attr); + } + return stored; + } + + public List deleteAttributes(String clusterRef, List attrs, String region) { + List deleted = new ArrayList<>(); + for (Attribute attr : attrs) { + String targetId = attr.targetId(); + List existing = attributes.get(targetId); + if (existing != null) { + existing.removeIf(a -> { + if (a.name().equals(attr.name())) { + deleted.add(a); + return true; + } + return false; + }); + } + } + return deleted; + } + + public List listAttributes(String clusterRef, String targetType, + String attributeName, String attributeValue, String region) { + return attributes.values().stream() + .flatMap(List::stream) + .filter(a -> targetType == null || targetType.equals(a.targetType())) + .filter(a -> attributeName == null || attributeName.equals(a.name())) + .filter(a -> attributeValue == null || attributeValue.equals(a.value())) + .toList(); + } + + // ── Container Instances ─────────────────────────────────────────────────── + + public ContainerInstance registerContainerInstance(String clusterRef, String instanceIdentityDocument, + List instanceAttributes, String region) { + EcsCluster cluster = resolveClusterOrDefault(clusterRef, region); + String instanceId = "i-floci-" + UUID.randomUUID().toString().substring(0, 8); + String instanceArn = regionResolver.buildArn("ecs", region, + "container-instance/" + cluster.getClusterName() + "/" + UUID.randomUUID()); + + ContainerInstance instance = new ContainerInstance(); + instance.setContainerInstanceArn(instanceArn); + instance.setEc2InstanceId(instanceId); + instance.setStatus("ACTIVE"); + instance.setAgentVersion("1.0.0"); + instance.setAgentConnected(true); + if (instanceAttributes != null) { + instance.setAttributes(new ArrayList<>(instanceAttributes)); + } + + String key = containerInstanceKey(cluster.getClusterArn(), instanceArn); + containerInstances.put(key, instance); + cluster.setRegisteredContainerInstancesCount(cluster.getRegisteredContainerInstancesCount() + 1); + LOG.infov("Registered container instance: {0} in cluster {1}", instanceArn, cluster.getClusterName()); + return instance; + } + + public ContainerInstance deregisterContainerInstance(String clusterRef, String instanceRef, + boolean force, String region) { + EcsCluster cluster = resolveClusterOrDefault(clusterRef, region); + ContainerInstance instance = resolveContainerInstanceOrThrow(cluster.getClusterArn(), instanceRef); + + if (!force) { + long running = tasks.values().stream() + .filter(t -> instance.getContainerInstanceArn().equals(t.getContainerInstanceArn())) + .filter(t -> TaskStatus.RUNNING.name().equals(t.getLastStatus())) + .count(); + if (running > 0) { + throw new AwsException("InvalidParameterException", + "Container instance has running tasks. Use force=true to deregister.", 400); + } + } + + String key = containerInstanceKey(cluster.getClusterArn(), instance.getContainerInstanceArn()); + containerInstances.remove(key); + instance.setStatus("INACTIVE"); + cluster.setRegisteredContainerInstancesCount( + Math.max(0, cluster.getRegisteredContainerInstancesCount() - 1)); + return instance; + } + + public List describeContainerInstances(String clusterRef, + List instanceRefs, String region) { + EcsCluster cluster = resolveClusterOrDefault(clusterRef, region); + List result = new ArrayList<>(); + for (String ref : instanceRefs) { + ContainerInstance instance = resolveContainerInstance(cluster.getClusterArn(), ref); + if (instance != null) { + result.add(instance); + } + } + return result; + } + + public List listContainerInstances(String clusterRef, String status, String region) { + EcsCluster cluster = resolveClusterOrDefault(clusterRef, region); + String prefix = containerInstanceKey(cluster.getClusterArn(), ""); + return containerInstances.entrySet().stream() + .filter(e -> e.getKey().startsWith(prefix)) + .filter(e -> status == null || status.equals(e.getValue().getStatus())) + .map(e -> e.getValue().getContainerInstanceArn()) + .toList(); + } + + public ContainerInstance updateContainerAgent(String clusterRef, String instanceRef, String region) { + EcsCluster cluster = resolveClusterOrDefault(clusterRef, region); + return resolveContainerInstanceOrThrow(cluster.getClusterArn(), instanceRef); + } + + public List updateContainerInstancesState(String clusterRef, + List instanceRefs, + String status, String region) { + EcsCluster cluster = resolveClusterOrDefault(clusterRef, region); + List updated = new ArrayList<>(); + for (String ref : instanceRefs) { + ContainerInstance instance = resolveContainerInstanceOrThrow(cluster.getClusterArn(), ref); + instance.setStatus(status); + updated.add(instance); + } + return updated; + } + + // ── Capacity Providers ──────────────────────────────────────────────────── + + public CapacityProvider createCapacityProvider(String name, Map asgProvider, + Map tags, String region) { + if (capacityProviders.containsKey(name)) { + throw new AwsException("InvalidParameterException", + "A capacity provider with name " + name + " already exists.", 400); + } + CapacityProvider cp = new CapacityProvider(); + cp.setName(name); + cp.setCapacityProviderArn(regionResolver.buildArn("ecs", region, "capacity-provider/" + name)); + cp.setStatus("ACTIVE"); + cp.setAutoScalingGroupProvider(asgProvider); + if (tags != null) { + cp.setTags(tags); + } + capacityProviders.put(name, cp); + return cp; + } + + public CapacityProvider updateCapacityProvider(String name, Map asgProvider) { + CapacityProvider cp = resolveCapacityProviderOrThrow(name); + cp.setAutoScalingGroupProvider(asgProvider); + return cp; + } + + public CapacityProvider deleteCapacityProvider(String nameOrArn) { + CapacityProvider cp = resolveCapacityProviderOrThrow(nameOrArn); + cp.setStatus("DELETE_IN_PROGRESS"); + capacityProviders.remove(cp.getName()); + return cp; + } + + public List describeCapacityProviders(List providers) { + if (providers == null || providers.isEmpty()) { + List result = new ArrayList<>(List.of(builtInFargate(), builtInFargateSpot())); + result.addAll(capacityProviders.values()); + return result; + } + return providers.stream() + .map(p -> { + if ("FARGATE".equals(p)) { return builtInFargate(); } + if ("FARGATE_SPOT".equals(p)) { return builtInFargateSpot(); } + return capacityProviders.getOrDefault(p, + capacityProviders.values().stream() + .filter(cp -> cp.getCapacityProviderArn().equals(p)) + .findFirst().orElse(null)); + }) + .filter(cp -> cp != null) + .toList(); + } + + private CapacityProvider builtInFargate() { + CapacityProvider cp = new CapacityProvider(); + cp.setName("FARGATE"); + cp.setStatus("ACTIVE"); + return cp; + } + + private CapacityProvider builtInFargateSpot() { + CapacityProvider cp = new CapacityProvider(); + cp.setName("FARGATE_SPOT"); + cp.setStatus("ACTIVE"); + return cp; + } + + // ── Task Sets ───────────────────────────────────────────────────────────── + + public TaskSet createTaskSet(String clusterRef, String serviceRef, String taskDefinitionRef, + LaunchType launchType, double scaleValue, String scaleUnit, + String externalId, String region) { + EcsCluster cluster = resolveClusterOrDefault(clusterRef, region); + EcsServiceModel svc = resolveServiceOrThrow(cluster.getClusterName(), serviceRef, region); + TaskDefinition taskDef = resolveTaskDefinitionOrThrow(taskDefinitionRef, region); + + String setId = "ecs-svc/" + UUID.randomUUID().toString().replace("-", ""); + String taskSetArn = regionResolver.buildArn("ecs", region, "task-set/" + + cluster.getClusterName() + "/" + svc.getServiceName() + "/" + setId); + + TaskSet ts = new TaskSet(); + ts.setId(setId); + ts.setTaskSetArn(taskSetArn); + ts.setServiceArn(svc.getServiceArn()); + ts.setClusterArn(cluster.getClusterArn()); + ts.setTaskDefinition(taskDef.getTaskDefinitionArn()); + ts.setStatus("ACTIVE"); + ts.setScaleValue(scaleValue); + ts.setScaleUnit(scaleUnit != null ? scaleUnit : "PERCENT"); + ts.setLaunchType(launchType != null ? launchType : LaunchType.FARGATE); + ts.setExternalId(externalId); + ts.setStabilityStatus("STEADY_STATE"); + ts.setCreatedAt(Instant.now()); + ts.setUpdatedAt(Instant.now()); + + taskSets.put(taskSetArn, ts); + return ts; + } + + public TaskSet updateTaskSet(String clusterRef, String serviceRef, String taskSetRef, + double scaleValue, String scaleUnit, String region) { + TaskSet ts = resolveTaskSetOrThrow(taskSetRef); + ts.setScaleValue(scaleValue); + ts.setScaleUnit(scaleUnit != null ? scaleUnit : "PERCENT"); + ts.setUpdatedAt(Instant.now()); + return ts; + } + + public TaskSet deleteTaskSet(String clusterRef, String serviceRef, String taskSetRef, + boolean force, String region) { + TaskSet ts = resolveTaskSetOrThrow(taskSetRef); + ts.setStatus("DRAINING"); + taskSets.remove(ts.getTaskSetArn()); + return ts; + } + + public List describeTaskSets(String clusterRef, String serviceRef, + List taskSetRefs, String region) { + EcsCluster cluster = resolveClusterOrDefault(clusterRef, region); + EcsServiceModel svc = resolveServiceOrThrow(cluster.getClusterName(), serviceRef, region); + Stream stream = taskSets.values().stream() + .filter(ts -> ts.getServiceArn().equals(svc.getServiceArn())); + if (taskSetRefs != null && !taskSetRefs.isEmpty()) { + stream = stream.filter(ts -> taskSetRefs.contains(ts.getTaskSetArn()) + || taskSetRefs.contains(ts.getId())); + } + return stream.toList(); + } + + public TaskSet updateServicePrimaryTaskSet(String clusterRef, String serviceRef, + String primaryTaskSetRef, String region) { + EcsCluster cluster = resolveClusterOrDefault(clusterRef, region); + EcsServiceModel svc = resolveServiceOrThrow(cluster.getClusterName(), serviceRef, region); + TaskSet primary = resolveTaskSetOrThrow(primaryTaskSetRef); + + taskSets.values().stream() + .filter(ts -> ts.getServiceArn().equals(svc.getServiceArn())) + .forEach(ts -> ts.setStatus(ts.getTaskSetArn().equals(primary.getTaskSetArn()) + ? "PRIMARY" : "ACTIVE")); + + primary.setUpdatedAt(Instant.now()); + return primary; + } + + // ── Service Deployments & Revisions ─────────────────────────────────────── + + public List describeServiceDeployments(List deploymentArns) { + return deploymentArns.stream() + .map(arn -> serviceDeployments.get(arn)) + .filter(d -> d != null) + .toList(); + } + + public List listServiceDeployments(String serviceRef, String clusterRef, + List statusFilter, String region) { + return listServiceDeploymentsDetailed(serviceRef, clusterRef, statusFilter, region) + .stream().map(ServiceDeployment::getServiceDeploymentArn).toList(); + } + + public List listServiceDeploymentsDetailed(String serviceRef, String clusterRef, + List statusFilter, String region) { + EcsCluster cluster = resolveClusterOrDefault(clusterRef, region); + EcsServiceModel svc = resolveServiceOrThrow(cluster.getClusterName(), serviceRef, region); + + return serviceDeployments.values().stream() + .filter(d -> d.getServiceArn().equals(svc.getServiceArn())) + .filter(d -> statusFilter == null || statusFilter.isEmpty() + || statusFilter.contains(d.getStatus())) + .sorted((a, b) -> b.getCreatedAt().compareTo(a.getCreatedAt())) + .toList(); + } + + public List describeServiceRevisions(List revisionArns) { + return revisionArns.stream() + .map(arn -> serviceRevisions.get(arn)) + .filter(r -> r != null) + .toList(); + } + + private void recordServiceDeployment(EcsServiceModel svc, String taskDefinition, String region) { + String deploymentId = UUID.randomUUID().toString().replace("-", ""); + String deploymentArn = regionResolver.buildArn("ecs", region, + "service-deployment/" + deploymentId); + String revisionId = UUID.randomUUID().toString().replace("-", ""); + String revisionArn = regionResolver.buildArn("ecs", region, + "service-revision/" + revisionId); + + ServiceDeployment deployment = new ServiceDeployment(); + deployment.setServiceDeploymentArn(deploymentArn); + deployment.setServiceArn(svc.getServiceArn()); + deployment.setClusterArn(svc.getClusterArn()); + deployment.setTaskDefinition(taskDefinition); + deployment.setStatus("SUCCESSFUL"); + deployment.setCreatedAt(Instant.now()); + deployment.setUpdatedAt(Instant.now()); + serviceDeployments.put(deploymentArn, deployment); + + ServiceRevision revision = new ServiceRevision(); + revision.setServiceRevisionArn(revisionArn); + revision.setServiceArn(svc.getServiceArn()); + revision.setClusterArn(svc.getClusterArn()); + revision.setTaskDefinition(taskDefinition); + revision.setLaunchType(svc.getLaunchType()); + revision.setCreatedAt(Instant.now()); + serviceRevisions.put(revisionArn, revision); + } + + // ── Stub operations ──────────────────────────────────────────────────────── + + public String submitTaskStateChange() { + return "ACK_" + UUID.randomUUID().toString().replace("-", "").substring(0, 16); + } + + public String submitContainerStateChange() { + return "ACK_" + UUID.randomUUID().toString().replace("-", "").substring(0, 16); + } + + public String submitAttachmentStateChanges() { + return "ACK_" + UUID.randomUUID().toString().replace("-", "").substring(0, 16); + } + + public String getBaseUrl() { + return baseUrl; + } + + // ── Service Reconciliation ──────────────────────────────────────────────── + + void reconcileServices() { + for (Map.Entry entry : services.entrySet()) { + try { + reconcileService(entry.getKey(), entry.getValue()); + } catch (Exception e) { + LOG.debugv("Error reconciling ECS service {0}: {1}", entry.getKey(), e.getMessage()); + } + } + } + + private void reconcileService(String key, EcsServiceModel svc) { + if (!"ACTIVE".equals(svc.getStatus())) { + return; + } + + String region = extractRegionFromServiceKey(key); + String clusterName = extractClusterNameFromServiceKey(key); + + long running = tasks.values().stream() + .filter(t -> t.getClusterArn().endsWith(":cluster/" + clusterName)) + .filter(t -> svc.getServiceArn().equals(t.getGroup()) + || svc.getServiceName().equals(t.getGroup())) + .filter(t -> TaskStatus.RUNNING.name().equals(t.getLastStatus())) + .count(); + + svc.setRunningCount((int) running); + + if (running < svc.getDesiredCount()) { + int toStart = svc.getDesiredCount() - (int) running; + for (int i = 0; i < toStart; i++) { + try { + List launched = runTask(clusterName, svc.getTaskDefinition(), 1, + svc.getLaunchType(), svc.getServiceName(), "ecs-svc", region); + LOG.infov("Service reconciler started task {0} for service {1}", + launched.getFirst().getTaskArn(), svc.getServiceName()); + } catch (Exception e) { + LOG.warnv("Service reconciler failed to start task for {0}: {1}", + svc.getServiceName(), e.getMessage()); + } + } + } else if (running > svc.getDesiredCount()) { + int toStop = (int) running - svc.getDesiredCount(); + tasks.values().stream() + .filter(t -> t.getClusterArn().endsWith(":cluster/" + clusterName)) + .filter(t -> svc.getServiceName().equals(t.getGroup())) + .filter(t -> TaskStatus.RUNNING.name().equals(t.getLastStatus())) + .limit(toStop) + .forEach(t -> { + try { + stopTask(clusterName, t.getTaskArn(), "Service scale-in", region); + } catch (Exception e) { + LOG.warnv("Service reconciler failed to stop task {0}: {1}", + t.getTaskArn(), e.getMessage()); + } + }); + } + } + + // ── Resolution helpers ──────────────────────────────────────────────────── + + private EcsCluster getOrCreateDefaultCluster(String region) { + String key = clusterKey(region, DEFAULT_CLUSTER); + return clusters.computeIfAbsent(key, k -> { + EcsCluster c = new EcsCluster(); + c.setClusterName(DEFAULT_CLUSTER); + c.setClusterArn(regionResolver.buildArn("ecs", region, "cluster/" + DEFAULT_CLUSTER)); + c.setStatus("ACTIVE"); + return c; + }); + } + + private EcsCluster resolveClusterOrDefault(String clusterRef, String region) { + if (clusterRef == null || clusterRef.isBlank() || DEFAULT_CLUSTER.equals(clusterRef)) { + return getOrCreateDefaultCluster(region); + } + EcsCluster cluster = resolveCluster(clusterRef, region); + if (cluster == null) { + throw new AwsException("ClusterNotFoundException", "Cluster not found: " + clusterRef, 400); + } + return cluster; + } + + private EcsCluster resolveCluster(String clusterRef, String region) { + EcsCluster byName = clusters.get(clusterKey(region, clusterRef)); + if (byName != null) { + return byName; + } + return clusters.values().stream() + .filter(c -> c.getClusterArn().equals(clusterRef)) + .findFirst().orElse(null); + } + + private EcsCluster resolveClusterOrThrow(String clusterRef, String region) { + EcsCluster cluster = resolveCluster(clusterRef, region); + if (cluster == null) { + throw new AwsException("ClusterNotFoundException", "Cluster not found: " + clusterRef, 400); + } + return cluster; + } + + private EcsCluster resolveClusterByArn(String clusterArn) { + return clusters.values().stream() + .filter(c -> c.getClusterArn().equals(clusterArn)) + .findFirst().orElse(null); + } + + private TaskDefinition resolveTaskDefinitionOrThrow(String ref, String region) { + TaskDefinition td = taskDefinitions.get(ref); + if (td != null) { return td; } + td = taskDefinitions.values().stream() + .filter(d -> d.getTaskDefinitionArn().equals(ref)) + .findFirst().orElse(null); + if (td != null) { return td; } + Integer latest = latestRevisions.get(ref); + if (latest != null) { + td = taskDefinitions.get(ref + ":" + latest); + if (td != null) { return td; } + } + throw new AwsException("ClientException", "Unable to describe task definition: " + ref, 400); + } + + private EcsTask resolveTask(String ref, String region) { + EcsTask task = tasks.get(ref); + if (task != null) { return task; } + return tasks.values().stream() + .filter(t -> t.getTaskArn().endsWith("/" + ref)) + .findFirst().orElse(null); + } + + private EcsTask resolveTaskOrThrow(String ref, String region) { + EcsTask task = resolveTask(ref, region); + if (task == null) { + throw new AwsException("InvalidParameterException", "Task not found: " + ref, 400); + } + return task; + } + + private EcsServiceModel resolveService(String clusterName, String serviceId, String region) { + EcsServiceModel svc = services.get(serviceKey(region, clusterName, serviceId)); + if (svc != null) { return svc; } + return services.values().stream() + .filter(s -> s.getServiceArn().equals(serviceId) || s.getServiceName().equals(serviceId)) + .findFirst().orElse(null); + } + + private EcsServiceModel resolveServiceOrThrow(String clusterName, String serviceId, String region) { + EcsServiceModel svc = resolveService(clusterName, serviceId, region); + if (svc == null) { + throw new AwsException("ServiceNotFoundException", "Service not found: " + serviceId, 404); + } + return svc; + } + + private ContainerInstance resolveContainerInstance(String clusterArn, String ref) { + String prefix = containerInstanceKey(clusterArn, ""); + return containerInstances.entrySet().stream() + .filter(e -> e.getKey().startsWith(prefix)) + .map(Map.Entry::getValue) + .filter(ci -> ci.getContainerInstanceArn().equals(ref) + || ci.getContainerInstanceArn().endsWith("/" + ref)) + .findFirst().orElse(null); + } + + private ContainerInstance resolveContainerInstanceOrThrow(String clusterArn, String ref) { + ContainerInstance instance = resolveContainerInstance(clusterArn, ref); + if (instance == null) { + throw new AwsException("InvalidParameterException", + "Container instance not found: " + ref, 400); + } + return instance; + } + + private CapacityProvider resolveCapacityProviderOrThrow(String nameOrArn) { + CapacityProvider cp = capacityProviders.get(nameOrArn); + if (cp != null) { return cp; } + cp = capacityProviders.values().stream() + .filter(p -> p.getCapacityProviderArn().equals(nameOrArn)) + .findFirst().orElse(null); + if (cp == null) { + throw new AwsException("InvalidParameterException", + "Capacity provider not found: " + nameOrArn, 400); + } + return cp; + } + + private TaskSet resolveTaskSetOrThrow(String ref) { + TaskSet ts = taskSets.get(ref); + if (ts != null) { return ts; } + ts = taskSets.values().stream() + .filter(t -> t.getId().equals(ref)) + .findFirst().orElse(null); + if (ts == null) { + throw new AwsException("InvalidParameterException", "Task set not found: " + ref, 400); + } + return ts; + } + + // ── Key helpers ─────────────────────────────────────────────────────────── + + private static String clusterKey(String region, String clusterName) { + return region + "::" + clusterName; + } + + private static String serviceKey(String region, String clusterName, String serviceName) { + return region + "::" + clusterName + "/" + serviceName; + } + + private static String serviceKeyPrefix(String region, String clusterName) { + return region + "::" + clusterName + "/"; + } + + private static String containerInstanceKey(String clusterArn, String instanceArn) { + return clusterArn + "/" + instanceArn; + } + + private static String extractRegionFromServiceKey(String key) { + return key.substring(0, key.indexOf("::")); + } + + private static String extractClusterNameFromServiceKey(String key) { + String after = key.substring(key.indexOf("::") + 2); + int slash = after.indexOf('/'); + return slash >= 0 ? after.substring(0, slash) : after; + } +} 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 new file mode 100644 index 0000000000..563e6bf2fa --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/ecs/container/EcsContainerManager.java @@ -0,0 +1,313 @@ +package io.github.hectorvent.floci.services.ecs.container; + +import io.github.hectorvent.floci.config.EmulatorConfig; +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.common.RegionResolver; +import io.github.hectorvent.floci.services.cloudwatch.logs.CloudWatchLogsService; +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.EcsTask; +import io.github.hectorvent.floci.services.ecs.model.NetworkBinding; +import io.github.hectorvent.floci.services.ecs.model.PortMapping; +import io.github.hectorvent.floci.services.ecs.model.TaskDefinition; +import io.github.hectorvent.floci.services.lambda.launcher.DockerHostResolver; +import io.github.hectorvent.floci.services.lambda.launcher.ImageCacheService; +import com.github.dockerjava.api.DockerClient; +import com.github.dockerjava.api.async.ResultCallback; +import com.github.dockerjava.api.command.CreateContainerResponse; +import com.github.dockerjava.api.model.ExposedPort; +import com.github.dockerjava.api.model.Frame; +import com.github.dockerjava.api.model.HostConfig; +import com.github.dockerjava.api.model.Ports; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import org.jboss.logging.Logger; + +import java.io.Closeable; +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.time.LocalDate; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** + * Manages Docker container lifecycle for ECS tasks. + * Starts one Docker container per ContainerDefinition in a task and attaches logs to CloudWatch. + */ +@ApplicationScoped +public class EcsContainerManager { + + private static final Logger LOG = Logger.getLogger(EcsContainerManager.class); + private static final String HOST_DOCKER_INTERNAL = "host.docker.internal"; + private static final DateTimeFormatter LOG_STREAM_DATE_FMT = DateTimeFormatter.ofPattern("yyyy/MM/dd"); + + private final DockerClient dockerClient; + private final ImageCacheService imageCacheService; + private final DockerHostResolver dockerHostResolver; + private final EmulatorConfig config; + private final CloudWatchLogsService cloudWatchLogsService; + private final RegionResolver regionResolver; + + @Inject + public EcsContainerManager(DockerClient dockerClient, + ImageCacheService imageCacheService, + DockerHostResolver dockerHostResolver, + EmulatorConfig config, + CloudWatchLogsService cloudWatchLogsService, + RegionResolver regionResolver) { + this.dockerClient = dockerClient; + this.imageCacheService = imageCacheService; + this.dockerHostResolver = dockerHostResolver; + this.config = config; + this.cloudWatchLogsService = cloudWatchLogsService; + this.regionResolver = regionResolver; + } + + /** + * Starts Docker containers for all container definitions in a task. + * Updates the task's container list in-place with runtime network bindings and docker IDs. + */ + public EcsTaskHandle startTask(EcsTask task, TaskDefinition taskDef, String region) { + String taskId = extractTaskId(task.getTaskArn()); + boolean nativeMode = HOST_DOCKER_INTERNAL.equals(dockerHostResolver.resolve()); + + Map containerIds = new LinkedHashMap<>(); + List logStreams = new ArrayList<>(); + List runtimeContainers = new ArrayList<>(); + + for (ContainerDefinition def : taskDef.getContainerDefinitions()) { + imageCacheService.ensureImageExists(def.getImage()); + + List exposedPorts = buildExposedPorts(def); + HostConfig hostConfig = buildHostConfig(nativeMode, def, exposedPorts); + + applyDockerNetwork(hostConfig); + + List envVars = buildEnvVars(def); + String containerName = "floci-ecs-" + taskId + "-" + def.getName(); + + var createCmd = dockerClient.createContainerCmd(def.getImage()) + .withName(containerName) + .withEnv(envVars) + .withHostConfig(hostConfig); + + if (!exposedPorts.isEmpty()) { + createCmd.withExposedPorts(exposedPorts); + } + if (def.getCommand() != null && !def.getCommand().isEmpty()) { + createCmd.withCmd(def.getCommand()); + } + if (def.getEntryPoint() != null && !def.getEntryPoint().isEmpty()) { + createCmd.withEntrypoint(def.getEntryPoint()); + } + + CreateContainerResponse created = createCmd.exec(); + String dockerId = created.getId(); + LOG.infov("Created ECS container {0} for task {1} container {2}", dockerId, taskId, def.getName()); + + dockerClient.startContainerCmd(dockerId).exec(); + LOG.infov("Started ECS container {0}", dockerId); + + List networkBindings = resolveNetworkBindings(dockerId, def, nativeMode); + + Container container = buildContainer(task.getTaskArn(), def, dockerId, networkBindings, region); + runtimeContainers.add(container); + containerIds.put(def.getName(), dockerId); + + Closeable logStream = attachLogStream(dockerId, def.getName(), taskDef.getFamily(), taskId, region); + if (logStream != null) { + logStreams.add(logStream); + } + } + + task.setContainers(runtimeContainers); + task.setLastStatus(TaskStatus.RUNNING.name()); + task.setDesiredStatus(TaskStatus.RUNNING.name()); + task.setStartedAt(Instant.now()); + + return new EcsTaskHandle(task.getTaskArn(), containerIds, logStreams); + } + + /** + * Stops and removes all Docker containers for a task. + */ + public void stopTask(EcsTaskHandle handle) { + if (handle == null) { + return; + } + + for (Closeable logStream : handle.getLogStreams()) { + try { logStream.close(); } catch (Exception ignored) {} + } + + for (Map.Entry entry : handle.getContainerIds().entrySet()) { + String dockerId = entry.getValue(); + try { + dockerClient.stopContainerCmd(dockerId).withTimeout(5).exec(); + } catch (Exception e) { + LOG.warnv("Error stopping ECS container {0}: {1}", dockerId, e.getMessage()); + } + try { + dockerClient.removeContainerCmd(dockerId).withForce(true).exec(); + } catch (Exception e) { + LOG.warnv("Error removing ECS container {0}: {1}", dockerId, e.getMessage()); + } + } + } + + private List buildExposedPorts(ContainerDefinition def) { + List exposed = new ArrayList<>(); + if (def.getPortMappings() != null) { + for (PortMapping pm : def.getPortMappings()) { + exposed.add(ExposedPort.tcp(pm.containerPort())); + } + } + return exposed; + } + + private HostConfig buildHostConfig(boolean nativeMode, ContainerDefinition def, List exposedPorts) { + HostConfig hostConfig = HostConfig.newHostConfig(); + + if (def.getMemory() != null) { + hostConfig.withMemory((long) def.getMemory() * 1024 * 1024); + } + + if (nativeMode && !exposedPorts.isEmpty()) { + Ports portBindings = new Ports(); + for (ExposedPort ep : exposedPorts) { + portBindings.bind(ep, Ports.Binding.bindPort(0)); // 0 = dynamic host port + } + hostConfig.withPortBindings(portBindings); + } + + return hostConfig; + } + + private void applyDockerNetwork(HostConfig hostConfig) { + config.services().ecs().dockerNetwork() + .or(() -> config.services().dockerNetwork()) + .filter(n -> !n.isBlank()) + .ifPresent(network -> { + hostConfig.withNetworkMode(network); + LOG.debugv("Attaching ECS container to network: {0}", network); + }); + } + + private List buildEnvVars(ContainerDefinition def) { + List envVars = new ArrayList<>(); + if (def.getEnvironment() != null) { + for (var kv : def.getEnvironment()) { + envVars.add(kv.name() + "=" + kv.value()); + } + } + return envVars; + } + + private List resolveNetworkBindings(String dockerId, ContainerDefinition def, boolean nativeMode) { + List bindings = new ArrayList<>(); + if (def.getPortMappings() == null || def.getPortMappings().isEmpty()) { + return bindings; + } + + var inspect = dockerClient.inspectContainerCmd(dockerId).exec(); + var portBindingsMap = inspect.getNetworkSettings().getPorts().getBindings(); + + for (PortMapping pm : def.getPortMappings()) { + ExposedPort ep = ExposedPort.tcp(pm.containerPort()); + var binding = portBindingsMap.get(ep); + int hostPort = pm.containerPort(); + String bindIp = "0.0.0.0"; + + if (nativeMode && binding != null && binding.length > 0) { + hostPort = Integer.parseInt(binding[0].getHostPortSpec()); + if (binding[0].getHostIp() != null && !binding[0].getHostIp().isBlank()) { + bindIp = binding[0].getHostIp(); + } + } + + bindings.add(new NetworkBinding(bindIp, pm.containerPort(), hostPort, pm.protocol())); + } + return bindings; + } + + private Container buildContainer(String taskArn, ContainerDefinition def, String dockerId, + List networkBindings, String region) { + Container container = new Container(); + container.setTaskArn(taskArn); + container.setName(def.getName()); + container.setImage(def.getImage()); + container.setLastStatus("RUNNING"); + container.setNetworkBindings(networkBindings); + container.setDockerId(dockerId); + container.setContainerArn(regionResolver.buildArn("ecs", region, + "container/" + extractTaskId(taskArn) + "/" + def.getName())); + return container; + } + + private Closeable attachLogStream(String dockerId, String containerName, + String family, String taskId, String region) { + String logGroup = "/ecs/" + family; + String logStream = LOG_STREAM_DATE_FMT.format(LocalDate.now()) + "/" + containerName + "/" + taskId; + ensureLogGroupAndStream(logGroup, logStream, region); + + try { + ResultCallback.Adapter callback = dockerClient.logContainerCmd(dockerId) + .withStdOut(true) + .withStdErr(true) + .withFollowStream(true) + .withTimestamps(false) + .exec(new ResultCallback.Adapter<>() { + @Override + public void onNext(Frame frame) { + String line = new String(frame.getPayload(), StandardCharsets.UTF_8).stripTrailing(); + if (!line.isEmpty()) { + LOG.infov("[ecs:{0}:{1}] {2}", family, containerName, line); + forwardToCloudWatchLogs(logGroup, logStream, region, line); + } + } + }); + return callback; + } catch (Exception e) { + LOG.warnv("Could not attach log stream for ECS container {0}: {1}", dockerId, e.getMessage()); + return null; + } + } + + private void ensureLogGroupAndStream(String logGroup, String logStream, String region) { + try { + cloudWatchLogsService.createLogGroup(logGroup, null, null, region); + } catch (AwsException ignored) { + } catch (Exception e) { + LOG.warnv("Could not create CW log group {0}: {1}", logGroup, e.getMessage()); + } + try { + cloudWatchLogsService.createLogStream(logGroup, logStream, region); + } catch (AwsException ignored) { + } catch (Exception e) { + LOG.warnv("Could not create CW log stream {0}/{1}: {2}", logGroup, logStream, e.getMessage()); + } + } + + private void forwardToCloudWatchLogs(String logGroup, String logStream, String region, String line) { + try { + Map event = new HashMap<>(); + event.put("timestamp", System.currentTimeMillis()); + event.put("message", line); + cloudWatchLogsService.putLogEvents(logGroup, logStream, List.of(event), region); + } catch (Exception e) { + LOG.debugv("Could not forward ECS log line to CloudWatch Logs: {0}", e.getMessage()); + } + } + + private static String extractTaskId(String taskArn) { + int slash = taskArn.lastIndexOf('/'); + return slash >= 0 ? taskArn.substring(slash + 1) : taskArn; + } + + // Inner enum to avoid import cycle — mirrors model.TaskStatus for readability + private enum TaskStatus { RUNNING } +} 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 new file mode 100644 index 0000000000..9127f3bbbb --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/ecs/container/EcsTaskHandle.java @@ -0,0 +1,26 @@ +package io.github.hectorvent.floci.services.ecs.container; + +import java.io.Closeable; +import java.util.List; +import java.util.Map; + +/** + * Holds the runtime Docker container IDs for a running ECS task. + * Maps container name → Docker container ID and log stream handle. + */ +public class EcsTaskHandle { + + private final String taskArn; + private final Map containerIds; // containerName → dockerId + private final List logStreams; + + public EcsTaskHandle(String taskArn, Map containerIds, List logStreams) { + this.taskArn = taskArn; + this.containerIds = containerIds; + this.logStreams = logStreams; + } + + public String getTaskArn() { return taskArn; } + public Map getContainerIds() { return containerIds; } + public List getLogStreams() { return logStreams; } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/ecs/model/Attribute.java b/src/main/java/io/github/hectorvent/floci/services/ecs/model/Attribute.java new file mode 100644 index 0000000000..8f080771b9 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/ecs/model/Attribute.java @@ -0,0 +1,6 @@ +package io.github.hectorvent.floci.services.ecs.model; + +import io.quarkus.runtime.annotations.RegisterForReflection; + +@RegisterForReflection +public record Attribute(String name, String value, String targetType, String targetId) {} diff --git a/src/main/java/io/github/hectorvent/floci/services/ecs/model/CapacityProvider.java b/src/main/java/io/github/hectorvent/floci/services/ecs/model/CapacityProvider.java new file mode 100644 index 0000000000..080124da3c --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/ecs/model/CapacityProvider.java @@ -0,0 +1,33 @@ +package io.github.hectorvent.floci.services.ecs.model; + +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.util.HashMap; +import java.util.Map; + +@RegisterForReflection +public class CapacityProvider { + + private String capacityProviderArn; + private String name; + private String status; + private Map autoScalingGroupProvider; + private Map tags = new HashMap<>(); + + public String getCapacityProviderArn() { return capacityProviderArn; } + public void setCapacityProviderArn(String capacityProviderArn) { this.capacityProviderArn = capacityProviderArn; } + + public String getName() { return name; } + public void setName(String name) { this.name = name; } + + public String getStatus() { return status; } + public void setStatus(String status) { this.status = status; } + + public Map getAutoScalingGroupProvider() { return autoScalingGroupProvider; } + public void setAutoScalingGroupProvider(Map autoScalingGroupProvider) { + this.autoScalingGroupProvider = autoScalingGroupProvider; + } + + public Map getTags() { return tags; } + public void setTags(Map tags) { this.tags = tags; } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/ecs/model/ClusterSetting.java b/src/main/java/io/github/hectorvent/floci/services/ecs/model/ClusterSetting.java new file mode 100644 index 0000000000..7aa551ba1d --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/ecs/model/ClusterSetting.java @@ -0,0 +1,6 @@ +package io.github.hectorvent.floci.services.ecs.model; + +import io.quarkus.runtime.annotations.RegisterForReflection; + +@RegisterForReflection +public record ClusterSetting(String name, String value) {} 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 new file mode 100644 index 0000000000..5a14e047bd --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/ecs/model/Container.java @@ -0,0 +1,48 @@ +package io.github.hectorvent.floci.services.ecs.model; + +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.util.List; + +@RegisterForReflection +public class Container { + + private String containerArn; + private String taskArn; + private String name; + private String image; + private String lastStatus; + private Integer exitCode; + private String reason; + private List networkBindings; + + // transient — not persisted + private transient String dockerId; + + public String getContainerArn() { return containerArn; } + public void setContainerArn(String containerArn) { this.containerArn = containerArn; } + + public String getTaskArn() { return taskArn; } + public void setTaskArn(String taskArn) { this.taskArn = taskArn; } + + public String getName() { return name; } + public void setName(String name) { this.name = name; } + + public String getImage() { return image; } + public void setImage(String image) { this.image = image; } + + public String getLastStatus() { return lastStatus; } + public void setLastStatus(String lastStatus) { this.lastStatus = lastStatus; } + + public Integer getExitCode() { return exitCode; } + public void setExitCode(Integer exitCode) { this.exitCode = exitCode; } + + public String getReason() { return reason; } + public void setReason(String reason) { this.reason = reason; } + + public List getNetworkBindings() { return networkBindings; } + public void setNetworkBindings(List networkBindings) { this.networkBindings = networkBindings; } + + 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 new file mode 100644 index 0000000000..053f61b338 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/ecs/model/ContainerDefinition.java @@ -0,0 +1,50 @@ +package io.github.hectorvent.floci.services.ecs.model; + +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.util.List; + +@RegisterForReflection +public class ContainerDefinition { + + private String name; + private String image; + private Integer cpu; + private Integer memory; + private Integer memoryReservation; + private boolean essential = true; + private List portMappings; + private List environment; + private List command; + private List entryPoint; + + public String getName() { return name; } + public void setName(String name) { this.name = name; } + + public String getImage() { return image; } + public void setImage(String image) { this.image = image; } + + 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; } + + public boolean isEssential() { return essential; } + public void setEssential(boolean essential) { this.essential = essential; } + + public List getPortMappings() { return portMappings; } + public void setPortMappings(List portMappings) { this.portMappings = portMappings; } + + public List getEnvironment() { return environment; } + public void setEnvironment(List environment) { this.environment = environment; } + + public List getCommand() { return command; } + public void setCommand(List command) { this.command = command; } + + public List getEntryPoint() { return entryPoint; } + public void setEntryPoint(List entryPoint) { this.entryPoint = entryPoint; } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/ecs/model/ContainerInstance.java b/src/main/java/io/github/hectorvent/floci/services/ecs/model/ContainerInstance.java new file mode 100644 index 0000000000..7ed33cb63e --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/ecs/model/ContainerInstance.java @@ -0,0 +1,49 @@ +package io.github.hectorvent.floci.services.ecs.model; + +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@RegisterForReflection +public class ContainerInstance { + + private String containerInstanceArn; + private String ec2InstanceId; + private String status; + private int runningTasksCount; + private int pendingTasksCount; + private String agentVersion; + private boolean agentConnected; + private List attributes = new ArrayList<>(); + private Map tags = new HashMap<>(); + + public String getContainerInstanceArn() { return containerInstanceArn; } + public void setContainerInstanceArn(String containerInstanceArn) { this.containerInstanceArn = containerInstanceArn; } + + public String getEc2InstanceId() { return ec2InstanceId; } + public void setEc2InstanceId(String ec2InstanceId) { this.ec2InstanceId = ec2InstanceId; } + + public String getStatus() { return status; } + public void setStatus(String status) { this.status = status; } + + public int getRunningTasksCount() { return runningTasksCount; } + public void setRunningTasksCount(int runningTasksCount) { this.runningTasksCount = runningTasksCount; } + + public int getPendingTasksCount() { return pendingTasksCount; } + public void setPendingTasksCount(int pendingTasksCount) { this.pendingTasksCount = pendingTasksCount; } + + public String getAgentVersion() { return agentVersion; } + public void setAgentVersion(String agentVersion) { this.agentVersion = agentVersion; } + + public boolean isAgentConnected() { return agentConnected; } + public void setAgentConnected(boolean agentConnected) { this.agentConnected = agentConnected; } + + public List getAttributes() { return attributes; } + public void setAttributes(List attributes) { this.attributes = attributes; } + + public Map getTags() { return tags; } + public void setTags(Map tags) { this.tags = tags; } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/ecs/model/EcsCluster.java b/src/main/java/io/github/hectorvent/floci/services/ecs/model/EcsCluster.java new file mode 100644 index 0000000000..55c578fd58 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/ecs/model/EcsCluster.java @@ -0,0 +1,56 @@ +package io.github.hectorvent.floci.services.ecs.model; + +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@RegisterForReflection +public class EcsCluster { + + private String clusterArn; + private String clusterName; + private String status; + private int registeredContainerInstancesCount; + private int runningTasksCount; + private int pendingTasksCount; + private int activeServicesCount; + private List settings; + private List capacityProviders; + private List> defaultCapacityProviderStrategy; + private Map tags = new HashMap<>(); + + public String getClusterArn() { return clusterArn; } + public void setClusterArn(String clusterArn) { this.clusterArn = clusterArn; } + + public String getClusterName() { return clusterName; } + public void setClusterName(String clusterName) { this.clusterName = clusterName; } + + public String getStatus() { return status; } + public void setStatus(String status) { this.status = status; } + + public int getRegisteredContainerInstancesCount() { return registeredContainerInstancesCount; } + public void setRegisteredContainerInstancesCount(int count) { this.registeredContainerInstancesCount = count; } + + public int getRunningTasksCount() { return runningTasksCount; } + public void setRunningTasksCount(int count) { this.runningTasksCount = count; } + + public int getPendingTasksCount() { return pendingTasksCount; } + public void setPendingTasksCount(int count) { this.pendingTasksCount = count; } + + public int getActiveServicesCount() { return activeServicesCount; } + public void setActiveServicesCount(int count) { this.activeServicesCount = count; } + + 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> s) { this.defaultCapacityProviderStrategy = s; } + + public Map getTags() { return tags; } + public void setTags(Map tags) { this.tags = tags; } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/ecs/model/EcsServiceModel.java b/src/main/java/io/github/hectorvent/floci/services/ecs/model/EcsServiceModel.java new file mode 100644 index 0000000000..8bb94651c9 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/ecs/model/EcsServiceModel.java @@ -0,0 +1,64 @@ +package io.github.hectorvent.floci.services.ecs.model; + +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.time.Instant; +import java.util.HashMap; +import java.util.Map; + +@RegisterForReflection +public class EcsServiceModel { + + private String serviceArn; + private String serviceName; + private String clusterArn; + private String taskDefinition; + private LaunchType launchType; + private int desiredCount; + private int runningCount; + private int pendingCount; + private String status; + private Instant createdAt; + private String namespace; + private String deploymentController; + private Map tags = new HashMap<>(); + + public String getServiceArn() { return serviceArn; } + public void setServiceArn(String serviceArn) { this.serviceArn = serviceArn; } + + public String getServiceName() { return serviceName; } + public void setServiceName(String serviceName) { this.serviceName = serviceName; } + + public String getClusterArn() { return clusterArn; } + public void setClusterArn(String clusterArn) { this.clusterArn = clusterArn; } + + public String getTaskDefinition() { return taskDefinition; } + public void setTaskDefinition(String taskDefinition) { this.taskDefinition = taskDefinition; } + + public LaunchType getLaunchType() { return launchType; } + public void setLaunchType(LaunchType launchType) { this.launchType = launchType; } + + public int getDesiredCount() { return desiredCount; } + public void setDesiredCount(int desiredCount) { this.desiredCount = desiredCount; } + + public int getRunningCount() { return runningCount; } + public void setRunningCount(int runningCount) { this.runningCount = runningCount; } + + public int getPendingCount() { return pendingCount; } + public void setPendingCount(int pendingCount) { this.pendingCount = pendingCount; } + + public String getStatus() { return status; } + public void setStatus(String status) { this.status = status; } + + public Instant getCreatedAt() { return createdAt; } + public void setCreatedAt(Instant createdAt) { this.createdAt = createdAt; } + + public String getNamespace() { return namespace; } + public void setNamespace(String namespace) { this.namespace = namespace; } + + public String getDeploymentController() { return deploymentController; } + public void setDeploymentController(String deploymentController) { this.deploymentController = deploymentController; } + + public Map getTags() { return tags; } + public void setTags(Map tags) { this.tags = tags; } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/ecs/model/EcsTask.java b/src/main/java/io/github/hectorvent/floci/services/ecs/model/EcsTask.java new file mode 100644 index 0000000000..a01fca5be8 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/ecs/model/EcsTask.java @@ -0,0 +1,89 @@ +package io.github.hectorvent.floci.services.ecs.model; + +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.time.Instant; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@RegisterForReflection +public class EcsTask { + + private String taskArn; + private String clusterArn; + private String taskDefinitionArn; + private String group; + private LaunchType launchType; + private String lastStatus; + private String desiredStatus; + private String cpu; + private String memory; + private Instant createdAt; + private Instant startedAt; + private Instant stoppedAt; + private String startedBy; + private String stoppedReason; + private List containers; + private String containerInstanceArn; + private boolean protectionEnabled; + private Instant protectedUntil; + private Map tags = new HashMap<>(); + + public String getTaskArn() { return taskArn; } + public void setTaskArn(String taskArn) { this.taskArn = taskArn; } + + public String getClusterArn() { return clusterArn; } + public void setClusterArn(String clusterArn) { this.clusterArn = clusterArn; } + + public String getTaskDefinitionArn() { return taskDefinitionArn; } + public void setTaskDefinitionArn(String taskDefinitionArn) { this.taskDefinitionArn = taskDefinitionArn; } + + public String getGroup() { return group; } + public void setGroup(String group) { this.group = group; } + + public LaunchType getLaunchType() { return launchType; } + public void setLaunchType(LaunchType launchType) { this.launchType = launchType; } + + public String getLastStatus() { return lastStatus; } + public void setLastStatus(String lastStatus) { this.lastStatus = lastStatus; } + + public String getDesiredStatus() { return desiredStatus; } + public void setDesiredStatus(String desiredStatus) { this.desiredStatus = desiredStatus; } + + 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 Instant getCreatedAt() { return createdAt; } + public void setCreatedAt(Instant createdAt) { this.createdAt = createdAt; } + + public Instant getStartedAt() { return startedAt; } + public void setStartedAt(Instant startedAt) { this.startedAt = startedAt; } + + public Instant getStoppedAt() { return stoppedAt; } + public void setStoppedAt(Instant stoppedAt) { this.stoppedAt = stoppedAt; } + + public String getStartedBy() { return startedBy; } + public void setStartedBy(String startedBy) { this.startedBy = startedBy; } + + public String getStoppedReason() { return stoppedReason; } + public void setStoppedReason(String stoppedReason) { this.stoppedReason = stoppedReason; } + + public List getContainers() { return containers; } + public void setContainers(List containers) { this.containers = containers; } + + public String getContainerInstanceArn() { return containerInstanceArn; } + public void setContainerInstanceArn(String containerInstanceArn) { this.containerInstanceArn = containerInstanceArn; } + + public boolean isProtectionEnabled() { return protectionEnabled; } + public void setProtectionEnabled(boolean protectionEnabled) { this.protectionEnabled = protectionEnabled; } + + public Instant getProtectedUntil() { return protectedUntil; } + public void setProtectedUntil(Instant protectedUntil) { this.protectedUntil = protectedUntil; } + + public Map getTags() { return tags; } + public void setTags(Map tags) { this.tags = tags; } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/ecs/model/KeyValuePair.java b/src/main/java/io/github/hectorvent/floci/services/ecs/model/KeyValuePair.java new file mode 100644 index 0000000000..44425c99a7 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/ecs/model/KeyValuePair.java @@ -0,0 +1,4 @@ +package io.github.hectorvent.floci.services.ecs.model; + +public record KeyValuePair(String name, String value) { +} \ No newline at end of file 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 new file mode 100644 index 0000000000..162ae547ab --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/ecs/model/LaunchType.java @@ -0,0 +1,5 @@ +package io.github.hectorvent.floci.services.ecs.model; + +public enum LaunchType { + EC2, FARGATE, EXTERNAL +} \ No newline at end of file diff --git a/src/main/java/io/github/hectorvent/floci/services/ecs/model/NetworkBinding.java b/src/main/java/io/github/hectorvent/floci/services/ecs/model/NetworkBinding.java new file mode 100644 index 0000000000..ff11244df1 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/ecs/model/NetworkBinding.java @@ -0,0 +1,4 @@ +package io.github.hectorvent.floci.services.ecs.model; + +public record NetworkBinding(String bindIP, int containerPort, int hostPort, String protocol) { +} diff --git a/src/main/java/io/github/hectorvent/floci/services/ecs/model/NetworkMode.java b/src/main/java/io/github/hectorvent/floci/services/ecs/model/NetworkMode.java new file mode 100644 index 0000000000..a29493b715 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/ecs/model/NetworkMode.java @@ -0,0 +1,5 @@ +package io.github.hectorvent.floci.services.ecs.model; + +public enum NetworkMode { + bridge, host, awsvpc, none +} \ No newline at end of file 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 new file mode 100644 index 0000000000..0a609e519c --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/ecs/model/PortMapping.java @@ -0,0 +1,8 @@ +package io.github.hectorvent.floci.services.ecs.model; + +public record PortMapping(int containerPort, int hostPort, String protocol) { + + public PortMapping(int containerPort) { + this(containerPort, 0, "tcp"); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/ecs/model/ProtectedTask.java b/src/main/java/io/github/hectorvent/floci/services/ecs/model/ProtectedTask.java new file mode 100644 index 0000000000..183348155f --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/ecs/model/ProtectedTask.java @@ -0,0 +1,8 @@ +package io.github.hectorvent.floci.services.ecs.model; + +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.time.Instant; + +@RegisterForReflection +public record ProtectedTask(String taskArn, boolean protectionEnabled, Instant expirationDate) {} diff --git a/src/main/java/io/github/hectorvent/floci/services/ecs/model/ServiceDeployment.java b/src/main/java/io/github/hectorvent/floci/services/ecs/model/ServiceDeployment.java new file mode 100644 index 0000000000..ca31b680c1 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/ecs/model/ServiceDeployment.java @@ -0,0 +1,38 @@ +package io.github.hectorvent.floci.services.ecs.model; + +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.time.Instant; + +@RegisterForReflection +public class ServiceDeployment { + + private String serviceDeploymentArn; + private String serviceArn; + private String clusterArn; + private String taskDefinition; + private String status; + private Instant createdAt; + private Instant updatedAt; + + public String getServiceDeploymentArn() { return serviceDeploymentArn; } + public void setServiceDeploymentArn(String serviceDeploymentArn) { this.serviceDeploymentArn = serviceDeploymentArn; } + + public String getServiceArn() { return serviceArn; } + public void setServiceArn(String serviceArn) { this.serviceArn = serviceArn; } + + public String getClusterArn() { return clusterArn; } + public void setClusterArn(String clusterArn) { this.clusterArn = clusterArn; } + + public String getTaskDefinition() { return taskDefinition; } + public void setTaskDefinition(String taskDefinition) { this.taskDefinition = taskDefinition; } + + public String getStatus() { return status; } + public void setStatus(String status) { this.status = status; } + + public Instant getCreatedAt() { return createdAt; } + public void setCreatedAt(Instant createdAt) { this.createdAt = createdAt; } + + public Instant getUpdatedAt() { return updatedAt; } + public void setUpdatedAt(Instant updatedAt) { this.updatedAt = updatedAt; } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/ecs/model/ServiceRevision.java b/src/main/java/io/github/hectorvent/floci/services/ecs/model/ServiceRevision.java new file mode 100644 index 0000000000..3e90bc159b --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/ecs/model/ServiceRevision.java @@ -0,0 +1,34 @@ +package io.github.hectorvent.floci.services.ecs.model; + +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.time.Instant; + +@RegisterForReflection +public class ServiceRevision { + + private String serviceRevisionArn; + private String serviceArn; + private String clusterArn; + private String taskDefinition; + private LaunchType launchType; + private Instant createdAt; + + public String getServiceRevisionArn() { return serviceRevisionArn; } + public void setServiceRevisionArn(String serviceRevisionArn) { this.serviceRevisionArn = serviceRevisionArn; } + + public String getServiceArn() { return serviceArn; } + public void setServiceArn(String serviceArn) { this.serviceArn = serviceArn; } + + public String getClusterArn() { return clusterArn; } + public void setClusterArn(String clusterArn) { this.clusterArn = clusterArn; } + + public String getTaskDefinition() { return taskDefinition; } + public void setTaskDefinition(String taskDefinition) { this.taskDefinition = taskDefinition; } + + public LaunchType getLaunchType() { return launchType; } + public void setLaunchType(LaunchType launchType) { this.launchType = launchType; } + + public Instant getCreatedAt() { return createdAt; } + public void setCreatedAt(Instant createdAt) { this.createdAt = createdAt; } +} 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 new file mode 100644 index 0000000000..8e031ce7df --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/ecs/model/TaskDefinition.java @@ -0,0 +1,50 @@ +package io.github.hectorvent.floci.services.ecs.model; + +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@RegisterForReflection +public class TaskDefinition { + + private String taskDefinitionArn; + private String family; + private int revision; + private String status; // ACTIVE or INACTIVE + private NetworkMode networkMode; + private String cpu; + private String memory; + private List containerDefinitions; + private Map tags = new HashMap<>(); + + public String getTaskDefinitionArn() { return taskDefinitionArn; } + public void setTaskDefinitionArn(String taskDefinitionArn) { this.taskDefinitionArn = taskDefinitionArn; } + + public String getFamily() { return family; } + public void setFamily(String family) { this.family = family; } + + public int getRevision() { return revision; } + public void setRevision(int revision) { this.revision = revision; } + + public String getStatus() { return status; } + public void setStatus(String status) { this.status = status; } + + public NetworkMode getNetworkMode() { return networkMode; } + public void setNetworkMode(NetworkMode networkMode) { this.networkMode = networkMode; } + + 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 List getContainerDefinitions() { return containerDefinitions; } + public void setContainerDefinitions(List containerDefinitions) { + this.containerDefinitions = containerDefinitions; + } + + public Map getTags() { return tags; } + public void setTags(Map tags) { this.tags = tags; } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/ecs/model/TaskSet.java b/src/main/java/io/github/hectorvent/floci/services/ecs/model/TaskSet.java new file mode 100644 index 0000000000..677bd85030 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/ecs/model/TaskSet.java @@ -0,0 +1,80 @@ +package io.github.hectorvent.floci.services.ecs.model; + +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.time.Instant; +import java.util.HashMap; +import java.util.Map; + +@RegisterForReflection +public class TaskSet { + + private String id; + private String taskSetArn; + private String serviceArn; + private String clusterArn; + private String taskDefinition; + private String status; + private int computedDesiredCount; + private int pendingCount; + private int runningCount; + private double scaleValue; + private String scaleUnit; + private String stabilityStatus; + private LaunchType launchType; + private String externalId; + private Instant createdAt; + private Instant updatedAt; + private Map tags = new HashMap<>(); + + public String getId() { return id; } + public void setId(String id) { this.id = id; } + + public String getTaskSetArn() { return taskSetArn; } + public void setTaskSetArn(String taskSetArn) { this.taskSetArn = taskSetArn; } + + public String getServiceArn() { return serviceArn; } + public void setServiceArn(String serviceArn) { this.serviceArn = serviceArn; } + + public String getClusterArn() { return clusterArn; } + public void setClusterArn(String clusterArn) { this.clusterArn = clusterArn; } + + public String getTaskDefinition() { return taskDefinition; } + public void setTaskDefinition(String taskDefinition) { this.taskDefinition = taskDefinition; } + + public String getStatus() { return status; } + public void setStatus(String status) { this.status = status; } + + public int getComputedDesiredCount() { return computedDesiredCount; } + public void setComputedDesiredCount(int computedDesiredCount) { this.computedDesiredCount = computedDesiredCount; } + + public int getPendingCount() { return pendingCount; } + public void setPendingCount(int pendingCount) { this.pendingCount = pendingCount; } + + public int getRunningCount() { return runningCount; } + public void setRunningCount(int runningCount) { this.runningCount = runningCount; } + + public double getScaleValue() { return scaleValue; } + public void setScaleValue(double scaleValue) { this.scaleValue = scaleValue; } + + public String getScaleUnit() { return scaleUnit; } + public void setScaleUnit(String scaleUnit) { this.scaleUnit = scaleUnit; } + + public String getStabilityStatus() { return stabilityStatus; } + public void setStabilityStatus(String stabilityStatus) { this.stabilityStatus = stabilityStatus; } + + public LaunchType getLaunchType() { return launchType; } + public void setLaunchType(LaunchType launchType) { this.launchType = launchType; } + + public String getExternalId() { return externalId; } + public void setExternalId(String externalId) { this.externalId = externalId; } + + public Instant getCreatedAt() { return createdAt; } + public void setCreatedAt(Instant createdAt) { this.createdAt = createdAt; } + + public Instant getUpdatedAt() { return updatedAt; } + public void setUpdatedAt(Instant updatedAt) { this.updatedAt = updatedAt; } + + public Map getTags() { return tags; } + public void setTags(Map tags) { this.tags = tags; } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/ecs/model/TaskStatus.java b/src/main/java/io/github/hectorvent/floci/services/ecs/model/TaskStatus.java new file mode 100644 index 0000000000..2d701572fa --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/ecs/model/TaskStatus.java @@ -0,0 +1,5 @@ +package io.github.hectorvent.floci.services.ecs.model; + +public enum TaskStatus { + PROVISIONING, PENDING, ACTIVATING, RUNNING, DEACTIVATING, STOPPING, DEPROVISIONING, STOPPED +} \ No newline at end of file diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index 81f3796472..2cd1141bd8 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -125,3 +125,6 @@ floci: default-image: "opensearchproject/opensearch:2" proxy-base-port: 9400 proxy-max-port: 9499 + ecs: + enabled: true + mock: false diff --git a/src/test/java/io/github/hectorvent/floci/lifecycle/HealthControllerIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/lifecycle/HealthControllerIntegrationTest.java index a8db15e494..66734364de 100644 --- a/src/test/java/io/github/hectorvent/floci/lifecycle/HealthControllerIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/lifecycle/HealthControllerIntegrationTest.java @@ -38,7 +38,8 @@ class HealthControllerIntegrationTest { "cloudformation": "running", "acm": "running", "email": "running", - "es": "running" + "es": "running", + "ecs": "running" }, "edition": "floci-always-free", "version": "dev" 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 new file mode 100644 index 0000000000..a353d588f6 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/ecs/EcsIntegrationTest.java @@ -0,0 +1,485 @@ +package io.github.hectorvent.floci.services.ecs; + +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.RestAssured; +import io.restassured.config.EncoderConfig; +import io.restassured.http.ContentType; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.MethodOrderer; +import org.junit.jupiter.api.Order; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.*; + +/** + * Integration tests for the ECS service (mock mode — no Docker required). + * + * Coverage: + * - Clusters: Create, Describe, List, Update, Delete + * - Task Definitions: Register, Describe, List, ListFamilies, Deregister + * - Tasks: RunTask, DescribeTask, ListTasks, StopTask + * - Services: Create, Describe, List, Update, Delete + * - Tags: TagResource, ListTagsForResource, UntagResource + */ +@QuarkusTest +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class EcsIntegrationTest { + + private static final String TARGET_PREFIX = "AmazonEC2ContainerServiceV20141113."; + private static final String REGION = "us-east-1"; + private static final String ACCOUNT = "000000000000"; + private static final String CLUSTER_NAME = "test-cluster"; + private static final String CLUSTER_ARN = + "arn:aws:ecs:" + REGION + ":" + ACCOUNT + ":cluster/" + CLUSTER_NAME; + private static final String TASK_DEF_FAMILY = "test-task"; + private static final String SERVICE_NAME = "test-service"; + + private static final String CONTENT_TYPE = "application/x-amz-json-1.1"; + + private static String taskArn; + private static String serviceArn; + private static String taskDefArn; + + @BeforeAll + static void configureRestAssured() { + RestAssured.config = RestAssured.config().encoderConfig( + EncoderConfig.encoderConfig() + .encodeContentTypeAs(CONTENT_TYPE, ContentType.TEXT)); + } + + // ── Helpers ─────────────────────────────────────────────────────────────── + + private static io.restassured.specification.RequestSpecification ecs(String action) { + return given() + .contentType(CONTENT_TYPE) + .header("X-Amz-Target", TARGET_PREFIX + action); + } + + // ── Clusters ────────────────────────────────────────────────────────────── + + @Test + @Order(1) + void createCluster() { + ecs("CreateCluster") + .body(""" + {"clusterName": "%s"} + """.formatted(CLUSTER_NAME)) + .when() + .post("/") + .then() + .statusCode(200) + .body("cluster.clusterName", equalTo(CLUSTER_NAME)) + .body("cluster.clusterArn", containsString(CLUSTER_NAME)) + .body("cluster.status", equalTo("ACTIVE")); + } + + @Test + @Order(2) + void createClusterIdempotent() { + ecs("CreateCluster") + .body(""" + {"clusterName": "%s"} + """.formatted(CLUSTER_NAME)) + .when() + .post("/") + .then() + .statusCode(200) + .body("cluster.clusterName", equalTo(CLUSTER_NAME)); + } + + @Test + @Order(3) + void describeCluster() { + ecs("DescribeClusters") + .body(""" + {"clusters": ["%s"]} + """.formatted(CLUSTER_NAME)) + .when() + .post("/") + .then() + .statusCode(200) + .body("clusters", hasSize(1)) + .body("clusters[0].clusterName", equalTo(CLUSTER_NAME)) + .body("clusters[0].status", equalTo("ACTIVE")) + .body("failures", empty()); + } + + @Test + @Order(4) + void listClusters() { + ecs("ListClusters") + .body("{}") + .when() + .post("/") + .then() + .statusCode(200) + .body("clusterArns", hasItem(containsString(CLUSTER_NAME))); + } + + // ── Task Definitions ────────────────────────────────────────────────────── + + @Test + @Order(10) + void registerTaskDefinition() { + taskDefArn = ecs("RegisterTaskDefinition") + .body(""" + { + "family": "%s", + "containerDefinitions": [ + { + "name": "app", + "image": "nginx:latest", + "cpu": 256, + "memory": 512, + "essential": true, + "portMappings": [{"containerPort": 80, "protocol": "tcp"}] + } + ], + "requiresCompatibilities": ["FARGATE"], + "cpu": "256", + "memory": "512", + "networkMode": "awsvpc" + } + """.formatted(TASK_DEF_FAMILY)) + .when() + .post("/") + .then() + .statusCode(200) + .body("taskDefinition.family", equalTo(TASK_DEF_FAMILY)) + .body("taskDefinition.revision", equalTo(1)) + .body("taskDefinition.status", equalTo("ACTIVE")) + .body("taskDefinition.taskDefinitionArn", containsString(TASK_DEF_FAMILY)) + .body("taskDefinition.containerDefinitions", hasSize(1)) + .body("taskDefinition.containerDefinitions[0].name", equalTo("app")) + .extract() + .path("taskDefinition.taskDefinitionArn"); + } + + @Test + @Order(11) + void describeTaskDefinition() { + ecs("DescribeTaskDefinition") + .body(""" + {"taskDefinition": "%s:1"} + """.formatted(TASK_DEF_FAMILY)) + .when() + .post("/") + .then() + .statusCode(200) + .body("taskDefinition.family", equalTo(TASK_DEF_FAMILY)) + .body("taskDefinition.revision", equalTo(1)) + .body("taskDefinition.status", equalTo("ACTIVE")); + } + + @Test + @Order(12) + void listTaskDefinitions() { + ecs("ListTaskDefinitions") + .body("{}") + .when() + .post("/") + .then() + .statusCode(200) + .body("taskDefinitionArns", hasItem(containsString(TASK_DEF_FAMILY))); + } + + @Test + @Order(13) + void listTaskDefinitionFamilies() { + ecs("ListTaskDefinitionFamilies") + .body("{}") + .when() + .post("/") + .then() + .statusCode(200) + .body("families", hasItem(TASK_DEF_FAMILY)); + } + + // ── Tasks ───────────────────────────────────────────────────────────────── + + @Test + @Order(20) + void runTask() { + taskArn = ecs("RunTask") + .body(""" + { + "cluster": "%s", + "taskDefinition": "%s", + "launchType": "FARGATE", + "count": 1 + } + """.formatted(CLUSTER_NAME, TASK_DEF_FAMILY)) + .when() + .post("/") + .then() + .statusCode(200) + .body("tasks", hasSize(1)) + .body("tasks[0].taskArn", containsString("task/")) + .body("tasks[0].clusterArn", containsString(CLUSTER_NAME)) + .body("tasks[0].lastStatus", notNullValue()) + .body("failures", empty()) + .extract() + .path("tasks[0].taskArn"); + } + + @Test + @Order(21) + void describeTask() { + ecs("DescribeTasks") + .body(""" + { + "cluster": "%s", + "tasks": ["%s"] + } + """.formatted(CLUSTER_NAME, taskArn)) + .when() + .post("/") + .then() + .statusCode(200) + .body("tasks", hasSize(1)) + .body("tasks[0].taskArn", equalTo(taskArn)) + .body("failures", empty()); + } + + @Test + @Order(22) + void listTasks() { + ecs("ListTasks") + .body(""" + {"cluster": "%s"} + """.formatted(CLUSTER_NAME)) + .when() + .post("/") + .then() + .statusCode(200) + .body("taskArns", hasItem(taskArn)); + } + + @Test + @Order(23) + void stopTask() { + ecs("StopTask") + .body(""" + { + "cluster": "%s", + "task": "%s", + "reason": "integration-test" + } + """.formatted(CLUSTER_NAME, taskArn)) + .when() + .post("/") + .then() + .statusCode(200) + .body("task.taskArn", equalTo(taskArn)) + .body("task.lastStatus", equalTo("STOPPED")); + } + + // ── Services ────────────────────────────────────────────────────────────── + + @Test + @Order(30) + void createService() { + serviceArn = ecs("CreateService") + .body(""" + { + "cluster": "%s", + "serviceName": "%s", + "taskDefinition": "%s", + "desiredCount": 1, + "launchType": "FARGATE" + } + """.formatted(CLUSTER_NAME, SERVICE_NAME, TASK_DEF_FAMILY)) + .when() + .post("/") + .then() + .statusCode(200) + .body("service.serviceName", equalTo(SERVICE_NAME)) + .body("service.serviceArn", containsString(SERVICE_NAME)) + .body("service.clusterArn", containsString(CLUSTER_NAME)) + .body("service.desiredCount", equalTo(1)) + .body("service.status", equalTo("ACTIVE")) + .extract() + .path("service.serviceArn"); + } + + @Test + @Order(31) + void describeService() { + ecs("DescribeServices") + .body(""" + { + "cluster": "%s", + "services": ["%s"] + } + """.formatted(CLUSTER_NAME, SERVICE_NAME)) + .when() + .post("/") + .then() + .statusCode(200) + .body("services", hasSize(1)) + .body("services[0].serviceName", equalTo(SERVICE_NAME)) + .body("services[0].status", equalTo("ACTIVE")) + .body("failures", empty()); + } + + @Test + @Order(32) + void listServices() { + ecs("ListServices") + .body(""" + {"cluster": "%s"} + """.formatted(CLUSTER_NAME)) + .when() + .post("/") + .then() + .statusCode(200) + .body("serviceArns", hasItem(containsString(SERVICE_NAME))); + } + + @Test + @Order(33) + void updateService() { + ecs("UpdateService") + .body(""" + { + "cluster": "%s", + "service": "%s", + "desiredCount": 2 + } + """.formatted(CLUSTER_NAME, SERVICE_NAME)) + .when() + .post("/") + .then() + .statusCode(200) + .body("service.desiredCount", equalTo(2)); + } + + // ── Tags ───────────────────────────────────────────────────────────────── + + @Test + @Order(40) + void tagResource() { + ecs("TagResource") + .body(""" + { + "resourceArn": "%s", + "tags": [ + {"key": "env", "value": "test"}, + {"key": "team", "value": "platform"} + ] + } + """.formatted(CLUSTER_ARN)) + .when() + .post("/") + .then() + .statusCode(200); + } + + @Test + @Order(41) + void listTagsForResource() { + ecs("ListTagsForResource") + .body(""" + {"resourceArn": "%s"} + """.formatted(CLUSTER_ARN)) + .when() + .post("/") + .then() + .statusCode(200) + .body("tags", hasSize(2)) + .body("tags.find { it.key == 'env' }.value", equalTo("test")) + .body("tags.find { it.key == 'team' }.value", equalTo("platform")); + } + + @Test + @Order(42) + void untagResource() { + ecs("UntagResource") + .body(""" + { + "resourceArn": "%s", + "tagKeys": ["env"] + } + """.formatted(CLUSTER_ARN)) + .when() + .post("/") + .then() + .statusCode(200); + + ecs("ListTagsForResource") + .body(""" + {"resourceArn": "%s"} + """.formatted(CLUSTER_ARN)) + .when() + .post("/") + .then() + .statusCode(200) + .body("tags", hasSize(1)) + .body("tags[0].key", equalTo("team")); + } + + // ── Cleanup ─────────────────────────────────────────────────────────────── + + @Test + @Order(50) + void deleteService() { + ecs("DeleteService") + .body(""" + { + "cluster": "%s", + "service": "%s", + "force": true + } + """.formatted(CLUSTER_NAME, SERVICE_NAME)) + .when() + .post("/") + .then() + .statusCode(200) + .body("service.serviceName", equalTo(SERVICE_NAME)) + .body("service.status", equalTo("INACTIVE")); + } + + @Test + @Order(51) + void deregisterTaskDefinition() { + ecs("DeregisterTaskDefinition") + .body(""" + {"taskDefinition": "%s:1"} + """.formatted(TASK_DEF_FAMILY)) + .when() + .post("/") + .then() + .statusCode(200) + .body("taskDefinition.status", equalTo("INACTIVE")); + } + + @Test + @Order(52) + void deleteCluster() { + ecs("DeleteCluster") + .body(""" + {"cluster": "%s"} + """.formatted(CLUSTER_NAME)) + .when() + .post("/") + .then() + .statusCode(200) + .body("cluster.clusterName", equalTo(CLUSTER_NAME)) + .body("cluster.status", equalTo("INACTIVE")); + } + + @Test + @Order(53) + void deleteClusterNotFound() { + ecs("DeleteCluster") + .body(""" + {"cluster": "non-existent-cluster"} + """) + .when() + .post("/") + .then() + .statusCode(400); + } +} diff --git a/src/test/resources/application.yml b/src/test/resources/application.yml index da8aa02549..7f76a523f8 100644 --- a/src/test/resources/application.yml +++ b/src/test/resources/application.yml @@ -96,4 +96,7 @@ floci: enabled: true opensearch: enabled: true - mode: mock \ No newline at end of file + mode: mock + ecs: + enabled: true + mock: true \ No newline at end of file