Light, fluffy, and always free - The AWS Local Emulator alternative
fix(ecs): retain inactive services for terraform draining and recreation with correct idempotency (#1166)
Samarth Tikotkarf359ae854d0b
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.javaindex 0dfa13ffee..a60a767fb3 100644--- a/src/main/java/io/github/hectorvent/floci/services/ecs/EcsService.java+++ b/src/main/java/io/github/hectorvent/floci/services/ecs/EcsService.java@@ -31,11 +31,13 @@ import jakarta.inject.Inject;import org.jboss.logging.Logger;import java.time.Instant;+import java.util.ArrayList;import java.util.LinkedHashMap;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;@@ -492,8 +494,12 @@ public class EcsService {String key = serviceKey(region, cluster.getClusterName(), serviceName);if (services.containsKey(key)) {- throw new AwsException("InvalidParameterException",- "Creation of service was not idempotent.", 400);+ EcsServiceModel existingSvc = services.get(key);++ if ("ACTIVE".equals(existingSvc.getStatus())) {+ throw new AwsException("InvalidParameterException",+ "Creation of service was not idempotent.", 400);+ }}EcsServiceModel svc = new EcsServiceModel();@@ -523,11 +529,18 @@ public class EcsService {Integer desiredCount, NetworkConfiguration networkConfiguration,String region) {EcsCluster cluster = resolveClusterOrDefault(clusterRef, region);++ serviceName = extractServiceName(serviceName);+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 ("INACTIVE".equals(svc.getStatus())) {+ throw new AwsException("ServiceNotActiveException",+ "Service " + serviceName + " is not active.", 400);+ }if (desiredCount != null) {svc.setDesiredCount(desiredCount);}@@ -544,11 +557,17 @@ public class EcsService {public EcsServiceModel deleteService(String clusterRef, String serviceName, boolean force, String region) {EcsCluster cluster = resolveClusterOrDefault(clusterRef, region);++ serviceName = extractServiceName(serviceName);+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 ("INACTIVE".equals(svc.getStatus())) {+ return svc;+ }if (!force && svc.getDesiredCount() > 0) {throw new AwsException("InvalidParameterException","The service cannot be stopped. Update the service to 0 tasks or use the force flag.", 400);@@ -571,7 +590,6 @@ public class EcsService {t.getTaskArn(), e.getMessage());}});- services.remove(key);return svc;}@@ -592,6 +610,7 @@ public class EcsService {String prefix = serviceKeyPrefix(region, cluster.getClusterName());return services.entrySet().stream().filter(e -> e.getKey().startsWith(prefix))+ .filter(e -> !"INACTIVE".equals(e.getValue().getStatus())).map(e -> e.getValue().getServiceArn()).toList();}@@ -599,6 +618,7 @@ public class EcsService {public List<String> listServicesByNamespace(String namespace, String region) {return services.values().stream().filter(s -> namespace.equals(s.getNamespace()))+ .filter(s -> !"INACTIVE".equals(s.getStatus())).map(EcsServiceModel::getServiceArn).toList();}@@ -1352,6 +1372,13 @@ public class EcsService {return key.substring(0, key.indexOf("::"));}+ private static String extractServiceName(String serviceName) {+ if (serviceName != null && serviceName.contains("/")) {+ return serviceName.substring(serviceName.lastIndexOf("/") + 1);+ }+ return serviceName;+ }+private static String extractClusterNameFromServiceKey(String key) {String after = key.substring(key.indexOf("::") + 2);int slash = after.indexOf('/');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.javaindex 0d81e56424..7a3fc54f72 100644--- a/src/test/java/io/github/hectorvent/floci/services/ecs/EcsIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/ecs/EcsIntegrationTest.java@@ -37,6 +37,10 @@ class EcsIntegrationTest {private static final String TASK_DEF_FAMILY = "test-task";private static final String SERVICE_NAME = "test-service";+ private static final String REVIEW_CLUSTER = "review-cluster";+ private static final String REVIEW_SERVICE = "review-svc";+ private static final String REVIEW_LB_SERVICE = "review-lb-svc";+private static final String CONTENT_TYPE = "application/x-amz-json-1.1";private static String taskArn;@@ -462,6 +466,48 @@ class EcsIntegrationTest {.body("service.desiredCount", equalTo(2));}+ @Test+ @Order(34)+ void createServiceDuplicateActiveNameAlwaysFails() {+ ecs("CreateService")+ .body("""+ {+ "cluster": "%s",+ "serviceName": "%s",+ "taskDefinition": "%s",+ "desiredCount": 2,+ "launchType": "FARGATE"+ }+ """.formatted(CLUSTER_NAME, SERVICE_NAME, TASK_DEF_FAMILY))+ .when()+ .post("/")+ .then()+ .statusCode(400)+ .body("__type", containsString("InvalidParameterException"))+ .body("message", containsString("Creation of service was not idempotent."));+ }++ @Test+ @Order(35)+ void createServiceWithDifferentParametersFailsIdempotency() {+ ecs("CreateService")+ .body("""+ {+ "cluster": "%s",+ "serviceName": "%s",+ "taskDefinition": "%s",+ "desiredCount": 99,+ "launchType": "FARGATE"+ }+ """.formatted(CLUSTER_NAME, SERVICE_NAME, TASK_DEF_FAMILY))+ .when()+ .post("/")+ .then()+ .statusCode(400)+ .body("__type", containsString("InvalidParameterException"))+ .body("message", containsString("Creation of service was not idempotent."));+ }+// ── Tags ─────────────────────────────────────────────────────────────────@Test@@ -549,6 +595,26 @@ class EcsIntegrationTest {@Test@Order(51)+ void updateInactiveServiceReturnsServiceNotActiveException() {+ String fullServiceArn = "arn:aws:ecs:" + REGION + ":" + ACCOUNT + ":service/" + CLUSTER_NAME + "/" + SERVICE_NAME;++ ecs("UpdateService")+ .body("""+ {+ "cluster": "%s",+ "service": "%s",+ "desiredCount": 0+ }+ """.formatted(CLUSTER_NAME, fullServiceArn))+ .when()+ .post("/")+ .then()+ .statusCode(400)+ .body("__type", containsString("ServiceNotActiveException"));+ }++ @Test+ @Order(52)void deregisterTaskDefinition() {ecs("DeregisterTaskDefinition").body("""@@ -562,7 +628,7 @@ class EcsIntegrationTest {}@Test- @Order(52)+ @Order(53)void deleteCluster() {ecs("DeleteCluster").body("""@@ -577,7 +643,7 @@ class EcsIntegrationTest {}@Test- @Order(53)+ @Order(54)void deleteClusterNotFound() {ecs("DeleteCluster").body("""@@ -588,4 +654,203 @@ class EcsIntegrationTest {.then().statusCode(400);}++ @Test+ @Order(60)+ void reviewSetup_createClusterAndService() {+ ecs("CreateCluster")+ .body("""+ {"clusterName": "%s"}+ """.formatted(REVIEW_CLUSTER))+ .when()+ .post("/")+ .then()+ .statusCode(200);++ ecs("RegisterTaskDefinition")+ .body("""+ {+ "family": "review-td",+ "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"+ }+ """)+ .when()+ .post("/")+ .then()+ .statusCode(200);++ ecs("CreateService")+ .body("""+ {+ "cluster": "%s",+ "serviceName": "%s",+ "taskDefinition": "review-td",+ "desiredCount": 1,+ "launchType": "FARGATE"+ }+ """.formatted(REVIEW_CLUSTER, REVIEW_SERVICE))+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body("service.status", equalTo("ACTIVE"));+ }++ @Test+ @Order(61)+ void deleteServiceHidesFromListServices() {+ ecs("DeleteService")+ .body("""+ {+ "cluster": "%s",+ "service": "%s",+ "force": true+ }+ """.formatted(REVIEW_CLUSTER, REVIEW_SERVICE))+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body("service.status", equalTo("INACTIVE"));++ ecs("ListServices")+ .body("""+ {"cluster": "%s"}+ """.formatted(REVIEW_CLUSTER))+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body("serviceArns", not(hasItem(containsString(REVIEW_SERVICE))));+ }++ @Test+ @Order(62)+ void deleteServiceStillDescribableAsInactive() {+ ecs("DescribeServices")+ .body("""+ {+ "cluster": "%s",+ "services": ["%s"]+ }+ """.formatted(REVIEW_CLUSTER, REVIEW_SERVICE))+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body("services", hasSize(1))+ .body("services[0].serviceName", equalTo(REVIEW_SERVICE))+ .body("services[0].status", equalTo("INACTIVE"));+ }++ @Test+ @Order(63)+ void updateInactiveServiceShouldReturnError() {+ ecs("UpdateService")+ .body("""+ {+ "cluster": "%s",+ "service": "%s",+ "desiredCount": 5+ }+ """.formatted(REVIEW_CLUSTER, REVIEW_SERVICE))+ .when()+ .post("/")+ .then()+ .statusCode(400)+ .body("__type", containsString("ServiceNotActiveException"));+ }++ @Test+ @Order(64)+ void createServiceIgnoresLoadBalancersInIdempotencyCheck() {+ ecs("CreateService")+ .body("""+ {+ "cluster": "%s",+ "serviceName": "%s",+ "taskDefinition": "review-td",+ "desiredCount": 1,+ "launchType": "FARGATE",+ "loadBalancers": [+ {+ "targetGroupArn": "arn:aws:elasticloadbalancing:us-east-1:000000000000:targetgroup/tg-a/1234",+ "containerName": "app",+ "containerPort": 80+ }+ ]+ }+ """.formatted(REVIEW_CLUSTER, REVIEW_LB_SERVICE))+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body("service.serviceName", equalTo(REVIEW_LB_SERVICE))+ .body("service.status", equalTo("ACTIVE"));++ ecs("CreateService")+ .body("""+ {+ "cluster": "%s",+ "serviceName": "%s",+ "taskDefinition": "review-td",+ "desiredCount": 1,+ "launchType": "FARGATE",+ "loadBalancers": [+ {+ "targetGroupArn": "arn:aws:elasticloadbalancing:us-east-1:000000000000:targetgroup/tg-DIFFERENT/9999",+ "containerName": "app",+ "containerPort": 8080+ }+ ]+ }+ """.formatted(REVIEW_CLUSTER, REVIEW_LB_SERVICE))+ .when()+ .post("/")+ .then()+ .statusCode(400)+ .body("__type", containsString("InvalidParameterException"))+ .body("message", containsString("Creation of service was not idempotent."));+ }++ // ── PR Review: Cleanup ───────────────────────────────────────────────────++ @Test+ @Order(69)+ void reviewCleanup() {+ ecs("DeleteService")+ .body("""+ {+ "cluster": "%s",+ "service": "%s",+ "force": true+ }+ """.formatted(REVIEW_CLUSTER, REVIEW_LB_SERVICE))+ .when()+ .post("/")+ .then()+ .statusCode(200);++ ecs("DeleteCluster")+ .body("""+ {"cluster": "%s"}+ """.formatted(REVIEW_CLUSTER))+ .when()+ .post("/")+ .then()+ .statusCode(200);+ }}