Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

feat(elbv2) alb proxy codedeploy ecs (#677)

Hector Ventura91ed829ea09e
diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CodeDeployEcsTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CodeDeployEcsTest.java
new file mode 100644
index 0000000000..9482ac5e22
--- /dev/null
+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CodeDeployEcsTest.java
@@ -0,0 +1,445 @@
+package com.floci.test;
+
+import org.junit.jupiter.api.AfterAll;
+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 software.amazon.awssdk.services.codedeploy.CodeDeployClient;
+import software.amazon.awssdk.services.codedeploy.model.AppSpecContent;
+import software.amazon.awssdk.services.codedeploy.model.BatchGetDeploymentTargetsResponse;
+import software.amazon.awssdk.services.codedeploy.model.ComputePlatform;
+import software.amazon.awssdk.services.codedeploy.model.CreateDeploymentGroupResponse;
+import software.amazon.awssdk.services.codedeploy.model.CreateDeploymentResponse;
+import software.amazon.awssdk.services.codedeploy.model.DeploymentOption;
+import software.amazon.awssdk.services.codedeploy.model.DeploymentStatus;
+import software.amazon.awssdk.services.codedeploy.model.DeploymentStyle;
+import software.amazon.awssdk.services.codedeploy.model.DeploymentType;
+import software.amazon.awssdk.services.codedeploy.model.ECSService;
+import software.amazon.awssdk.services.codedeploy.model.GetDeploymentResponse;
+import software.amazon.awssdk.services.codedeploy.model.ListDeploymentTargetsResponse;
+import software.amazon.awssdk.services.codedeploy.model.LoadBalancerInfo;
+import software.amazon.awssdk.services.codedeploy.model.RevisionLocation;
+import software.amazon.awssdk.services.codedeploy.model.RevisionLocationType;
+import software.amazon.awssdk.services.codedeploy.model.TargetGroupInfo;
+import software.amazon.awssdk.services.codedeploy.model.TargetGroupPairInfo;
+import software.amazon.awssdk.services.codedeploy.model.TrafficRoute;
+import software.amazon.awssdk.services.ecs.EcsClient;
+import software.amazon.awssdk.services.ecs.model.CreateClusterResponse;
+import software.amazon.awssdk.services.ecs.model.CreateServiceResponse;
+import software.amazon.awssdk.services.ecs.model.DeploymentControllerType;
+import software.amazon.awssdk.services.ecs.model.RegisterTaskDefinitionResponse;
+import software.amazon.awssdk.services.elasticloadbalancingv2.ElasticLoadBalancingV2Client;
+import software.amazon.awssdk.services.elasticloadbalancingv2.model.ActionTypeEnum;
+import software.amazon.awssdk.services.elasticloadbalancingv2.model.CreateListenerResponse;
+import software.amazon.awssdk.services.elasticloadbalancingv2.model.CreateLoadBalancerResponse;
+import software.amazon.awssdk.services.elasticloadbalancingv2.model.CreateTargetGroupResponse;
+import software.amazon.awssdk.services.elasticloadbalancingv2.model.DescribeRulesResponse;
+import software.amazon.awssdk.services.elasticloadbalancingv2.model.IpAddressType;
+import software.amazon.awssdk.services.elasticloadbalancingv2.model.LoadBalancerTypeEnum;
+import software.amazon.awssdk.services.elasticloadbalancingv2.model.ProtocolEnum;
+
+import java.util.List;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+/**
+ * Compatibility tests for CodeDeploy ECS blue/green deployments.
+ *
+ * Verifies the full lifecycle: ALB + blue/green TG setup → ECS cluster/service setup →
+ * CodeDeploy ECS app/group → deployment → traffic shifts to green TG.
+ */
+@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
+class CodeDeployEcsTest {
+
+ static CodeDeployClient codedeploy;
+ static EcsClient ecs;
+ static ElasticLoadBalancingV2Client elb;
+
+ static final String CLUSTER = "cd-ecs-cluster";
+ static final String SERVICE = "cd-ecs-service";
+ static final String TASK_FAMILY = "cd-ecs-task";
+ static final String LB_NAME = "cd-ecs-alb";
+ static final String BLUE_TG = "cd-blue-tg";
+ static final String GREEN_TG = "cd-green-tg";
+ static final String APP_NAME = "cd-ecs-app";
+ static final String DG_NAME = "cd-ecs-dg";
+ static final String ROLE = "arn:aws:iam::000000000000:role/codedeploy-role";
+
+ static String lbArn;
+ static String blueTgArn;
+ static String greenTgArn;
+ static String listenerArn;
+ static String taskDefArn;
+ static String deploymentId;
+
+ @BeforeAll
+ static void setup() {
+ codedeploy = TestFixtures.codeDeployClient();
+ ecs = TestFixtures.ecsClient();
+ elb = TestFixtures.elbV2Client();
+ }
+
+ @AfterAll
+ static void teardown() {
+ try { codedeploy.deleteDeploymentGroup(r -> r.applicationName(APP_NAME).deploymentGroupName(DG_NAME)); } catch (Exception ignored) {}
+ try { codedeploy.deleteApplication(r -> r.applicationName(APP_NAME)); } catch (Exception ignored) {}
+ try { ecs.deleteService(r -> r.cluster(CLUSTER).service(SERVICE).force(true)); } catch (Exception ignored) {}
+ try { ecs.deleteCluster(r -> r.cluster(CLUSTER)); } catch (Exception ignored) {}
+ try {
+ if (listenerArn != null) { elb.deleteListener(r -> r.listenerArn(listenerArn)); }
+ if (blueTgArn != null) { elb.deleteTargetGroup(r -> r.targetGroupArn(blueTgArn)); }
+ if (greenTgArn != null) { elb.deleteTargetGroup(r -> r.targetGroupArn(greenTgArn)); }
+ if (lbArn != null) { elb.deleteLoadBalancer(r -> r.loadBalancerArn(lbArn)); }
+ } catch (Exception ignored) {}
+ codedeploy.close();
+ ecs.close();
+ elb.close();
+ }
+
+ // ── ELB v2 setup ─────────────────────────────────────────────────────────
+
+ @Test
+ @Order(1)
+ void createLoadBalancer() {
+ CreateLoadBalancerResponse resp = elb.createLoadBalancer(r -> r
+ .name(LB_NAME)
+ .type(LoadBalancerTypeEnum.APPLICATION)
+ .ipAddressType(IpAddressType.IPV4));
+
+ assertThat(resp.loadBalancers()).hasSize(1);
+ lbArn = resp.loadBalancers().get(0).loadBalancerArn();
+ assertThat(lbArn).isNotBlank();
+ }
+
+ @Test
+ @Order(2)
+ void createBlueTargetGroup() {
+ CreateTargetGroupResponse resp = elb.createTargetGroup(r -> r
+ .name(BLUE_TG)
+ .protocol(ProtocolEnum.HTTP)
+ .port(80)
+ .vpcId("vpc-00000001"));
+
+ assertThat(resp.targetGroups()).hasSize(1);
+ blueTgArn = resp.targetGroups().get(0).targetGroupArn();
+ assertThat(blueTgArn).isNotBlank();
+ }
+
+ @Test
+ @Order(3)
+ void createGreenTargetGroup() {
+ CreateTargetGroupResponse resp = elb.createTargetGroup(r -> r
+ .name(GREEN_TG)
+ .protocol(ProtocolEnum.HTTP)
+ .port(80)
+ .vpcId("vpc-00000001"));
+
+ assertThat(resp.targetGroups()).hasSize(1);
+ greenTgArn = resp.targetGroups().get(0).targetGroupArn();
+ assertThat(greenTgArn).isNotBlank().isNotEqualTo(blueTgArn);
+ }
+
+ @Test
+ @Order(4)
+ void createListenerPointingToBlue() {
+ assertThat(lbArn).isNotNull();
+ assertThat(blueTgArn).isNotNull();
+
+ CreateListenerResponse resp = elb.createListener(r -> r
+ .loadBalancerArn(lbArn)
+ .protocol(ProtocolEnum.HTTP)
+ .port(18090)
+ .defaultActions(software.amazon.awssdk.services.elasticloadbalancingv2.model.Action.builder()
+ .type(ActionTypeEnum.FORWARD)
+ .targetGroupArn(blueTgArn)
+ .build()));
+
+ assertThat(resp.listeners()).hasSize(1);
+ listenerArn = resp.listeners().get(0).listenerArn();
+ assertThat(listenerArn).isNotBlank();
+ }
+
+ @Test
+ @Order(5)
+ void verifyListenerInitiallyPointsToBlue() {
+ assertThat(listenerArn).isNotNull();
+
+ DescribeRulesResponse resp = elb.describeRules(r -> r.listenerArn(listenerArn));
+ var defaultRule = resp.rules().stream()
+ .filter(rule -> rule.isDefault())
+ .findFirst();
+ assertThat(defaultRule).isPresent();
+ var forwardAction = defaultRule.get().actions().stream()
+ .filter(a -> ActionTypeEnum.FORWARD.equals(a.type()))
+ .findFirst();
+ assertThat(forwardAction).isPresent();
+ assertThat(forwardAction.get().targetGroupArn()).isEqualTo(blueTgArn);
+ }
+
+ // ── ECS setup ────────────────────────────────────────────────────────────
+
+ @Test
+ @Order(6)
+ void createEcsCluster() {
+ CreateClusterResponse resp = ecs.createCluster(r -> r.clusterName(CLUSTER));
+ assertThat(resp.cluster().clusterName()).isEqualTo(CLUSTER);
+ assertThat(resp.cluster().status()).isEqualTo("ACTIVE");
+ }
+
+ @Test
+ @Order(7)
+ void registerTaskDefinition() {
+ RegisterTaskDefinitionResponse resp = ecs.registerTaskDefinition(r -> r
+ .family(TASK_FAMILY)
+ .containerDefinitions(cd -> cd
+ .name("app")
+ .image("nginx:latest")
+ .portMappings(pm -> pm.containerPort(80))));
+
+ assertThat(resp.taskDefinition().family()).isEqualTo(TASK_FAMILY);
+ taskDefArn = resp.taskDefinition().taskDefinitionArn();
+ assertThat(taskDefArn).isNotBlank();
+ }
+
+ @Test
+ @Order(8)
+ void createEcsService() {
+ assertThat(taskDefArn).isNotNull();
+
+ CreateServiceResponse resp = ecs.createService(r -> r
+ .cluster(CLUSTER)
+ .serviceName(SERVICE)
+ .taskDefinition(TASK_FAMILY + ":1")
+ .desiredCount(1)
+ .deploymentController(dc -> dc.type(DeploymentControllerType.EXTERNAL)));
+
+ assertThat(resp.service().serviceName()).isEqualTo(SERVICE);
+ }
+
+ // ── CodeDeploy ECS deployment ─────────────────────────────────────────────
+
+ @Test
+ @Order(9)
+ void createEcsApplication() {
+ var resp = codedeploy.createApplication(r -> r
+ .applicationName(APP_NAME)
+ .computePlatform(ComputePlatform.ECS));
+
+ assertThat(resp.applicationId()).isNotBlank();
+ }
+
+ @Test
+ @Order(10)
+ void createEcsDeploymentGroup() {
+ assertThat(listenerArn).isNotNull();
+ assertThat(blueTgArn).isNotNull();
+ assertThat(greenTgArn).isNotNull();
+
+ CreateDeploymentGroupResponse resp = codedeploy.createDeploymentGroup(r -> r
+ .applicationName(APP_NAME)
+ .deploymentGroupName(DG_NAME)
+ .deploymentConfigName("CodeDeployDefault.ECSAllAtOnce")
+ .serviceRoleArn(ROLE)
+ .deploymentStyle(DeploymentStyle.builder()
+ .deploymentType(DeploymentType.BLUE_GREEN)
+ .deploymentOption(DeploymentOption.WITH_TRAFFIC_CONTROL)
+ .build())
+ .ecsServices(ECSService.builder()
+ .clusterName(CLUSTER)
+ .serviceName(SERVICE)
+ .build())
+ .loadBalancerInfo(LoadBalancerInfo.builder()
+ .targetGroupPairInfoList(TargetGroupPairInfo.builder()
+ .targetGroups(
+ TargetGroupInfo.builder().name(BLUE_TG).build(),
+ TargetGroupInfo.builder().name(GREEN_TG).build())
+ .prodTrafficRoute(TrafficRoute.builder()
+ .listenerArns(listenerArn)
+ .build())
+ .build())
+ .build()));
+
+ assertThat(resp.deploymentGroupId()).isNotBlank();
+ }
+
+ @Test
+ @Order(11)
+ void createEcsDeployment_allAtOnce() {
+ assertThat(taskDefArn).isNotNull();
+
+ String appSpec = """
+ {
+ "version": 0.0,
+ "Resources": [{
+ "TargetService": {
+ "Type": "AWS::ECS::Service",
+ "Properties": {
+ "TaskDefinition": "%s",
+ "LoadBalancerInfo": {
+ "ContainerName": "app",
+ "ContainerPort": 80
+ }
+ }
+ }
+ }]
+ }
+ """.formatted(taskDefArn);
+
+ CreateDeploymentResponse resp = codedeploy.createDeployment(r -> r
+ .applicationName(APP_NAME)
+ .deploymentGroupName(DG_NAME)
+ .deploymentConfigName("CodeDeployDefault.ECSAllAtOnce")
+ .revision(RevisionLocation.builder()
+ .revisionType(RevisionLocationType.APP_SPEC_CONTENT)
+ .appSpecContent(AppSpecContent.builder()
+ .content(appSpec)
+ .build())
+ .build()));
+
+ assertThat(resp.deploymentId()).startsWith("d-");
+ deploymentId = resp.deploymentId();
+ }
+
+ @Test
+ @Order(12)
+ void getDeployment_returnsEcsComputePlatform() {
+ assertThat(deploymentId).isNotNull();
+
+ GetDeploymentResponse resp = codedeploy.getDeployment(r -> r.deploymentId(deploymentId));
+ assertThat(resp.deploymentInfo().deploymentId()).isEqualTo(deploymentId);
+ assertThat(resp.deploymentInfo().applicationName()).isEqualTo(APP_NAME);
+ assertThat(resp.deploymentInfo().computePlatformAsString()).isEqualTo("ECS");
+ }
+
+ @Test
+ @Order(13)
+ void deployment_eventuallySucceeds() throws InterruptedException {
+ assertThat(deploymentId).isNotNull();
+
+ DeploymentStatus status = DeploymentStatus.QUEUED;
+ for (int i = 0; i < 30 && !DeploymentStatus.SUCCEEDED.equals(status)
+ && !DeploymentStatus.FAILED.equals(status); i++) {
+ Thread.sleep(500);
+ GetDeploymentResponse resp = codedeploy.getDeployment(r -> r.deploymentId(deploymentId));
+ status = resp.deploymentInfo().status();
+ }
+ assertThat(status).isEqualTo(DeploymentStatus.SUCCEEDED);
+ }
+
+ @Test
+ @Order(14)
+ void listDeploymentTargets_containsEcsTarget() {
+ assertThat(deploymentId).isNotNull();
+
+ ListDeploymentTargetsResponse resp = codedeploy.listDeploymentTargets(r -> r
+ .deploymentId(deploymentId));
+
+ assertThat(resp.targetIds()).hasSize(1);
+ assertThat(resp.targetIds().get(0)).contains(CLUSTER);
+ }
+
+ @Test
+ @Order(15)
+ void batchGetDeploymentTargets_returnsEcsTargetWithSucceededStatus() {
+ assertThat(deploymentId).isNotNull();
+
+ List<String> targetIds = codedeploy.listDeploymentTargets(r -> r
+ .deploymentId(deploymentId)).targetIds();
+
+ BatchGetDeploymentTargetsResponse resp = codedeploy.batchGetDeploymentTargets(r -> r
+ .deploymentId(deploymentId)
+ .targetIds(targetIds));
+
+ assertThat(resp.deploymentTargets()).hasSize(1);
+ var target = resp.deploymentTargets().get(0);
+ assertThat(target.deploymentTargetTypeAsString()).isEqualTo("ECSTarget");
+ assertThat(target.ecsTarget()).isNotNull();
+ assertThat(target.ecsTarget().statusAsString()).isEqualTo("Succeeded");
+ assertThat(target.ecsTarget().lifecycleEvents())
+ .anyMatch(e -> "Install".equals(e.lifecycleEventName()))
+ .anyMatch(e -> "AllowTraffic".equals(e.lifecycleEventName()));
+ }
+
+ @Test
+ @Order(16)
+ void listenerNowPointsToGreen_afterDeployment() {
+ assertThat(listenerArn).isNotNull();
+ assertThat(greenTgArn).isNotNull();
+
+ DescribeRulesResponse resp = elb.describeRules(r -> r.listenerArn(listenerArn));
+ var defaultRule = resp.rules().stream()
+ .filter(rule -> rule.isDefault())
+ .findFirst();
+
+ assertThat(defaultRule).isPresent();
+ var forwardAction = defaultRule.get().actions().stream()
+ .filter(a -> ActionTypeEnum.FORWARD.equals(a.type()))
+ .findFirst();
+ assertThat(forwardAction).isPresent();
+ assertThat(forwardAction.get().targetGroupArn()).isEqualTo(greenTgArn);
+ }
+
+ @Test
+ @Order(17)
+ void ecsTaskSetCreatedForGreenDeployment() {
+ // The green task set should exist and be PRIMARY after deployment
+ var taskSets = ecs.describeTaskSets(r -> r
+ .cluster(CLUSTER)
+ .service(SERVICE));
+
+ assertThat(taskSets.taskSets())
+ .anyMatch(ts -> "PRIMARY".equals(ts.status()));
+ }
+
+ // ── Canary deployment variant ─────────────────────────────────────────────
+
+ @Test
+ @Order(20)
+ void createCanaryDeployment() {
+ String appSpec = """
+ {
+ "version": 0.0,
+ "Resources": [{
+ "TargetService": {
+ "Type": "AWS::ECS::Service",
+ "Properties": {
+ "TaskDefinition": "%s",
+ "LoadBalancerInfo": {
+ "ContainerName": "app",
+ "ContainerPort": 80
+ }
+ }
+ }
+ }]
+ }
+ """.formatted(taskDefArn);
+
+ CreateDeploymentResponse resp = codedeploy.createDeployment(r -> r
+ .applicationName(APP_NAME)
+ .deploymentGroupName(DG_NAME)
+ .deploymentConfigName("CodeDeployDefault.ECSCanary10Percent5Minutes")
+ .revision(RevisionLocation.builder()
+ .revisionType(RevisionLocationType.APP_SPEC_CONTENT)
+ .appSpecContent(AppSpecContent.builder().content(appSpec).build())
+ .build()));
+
+ assertThat(resp.deploymentId()).startsWith("d-");
+ String canaryDeploymentId = resp.deploymentId();
+
+ // Poll until done (Floci caps wait times so this completes quickly)
+ DeploymentStatus status = DeploymentStatus.QUEUED;
+ try {
+ for (int i = 0; i < 40 && !DeploymentStatus.SUCCEEDED.equals(status)
+ && !DeploymentStatus.FAILED.equals(status); i++) {
+ Thread.sleep(500);
+ GetDeploymentResponse gr = codedeploy.getDeployment(r -> r.deploymentId(canaryDeploymentId));
+ status = gr.deploymentInfo().status();
+ }
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ }
+ assertThat(status).isEqualTo(DeploymentStatus.SUCCEEDED);
+ }
+}
diff --git a/docs/services/codedeploy.md b/docs/services/codedeploy.md
index ead41e06aa..8cb765bb53 100644
--- a/docs/services/codedeploy.md
+++ b/docs/services/codedeploy.md
@@ -1,6 +1,6 @@
# CodeDeploy
-Floci implements the CodeDeploy API — stored-state management for applications, deployment groups, and configs, plus real Lambda deployment execution with traffic shifting and lifecycle hooks.
+Floci implements the CodeDeploy API — stored-state management for applications, deployment groups, and configs, plus real Lambda and ECS deployment execution with traffic shifting and lifecycle hooks.
**Protocol:** JSON 1.1 — `POST /` with `X-Amz-Target: CodeDeploy_20141006.<Action>`
@@ -28,7 +28,7 @@ Floci implements the CodeDeploy API — stored-state management for applications
| Operation | Notes |
|---|---|
-| `CreateDeploymentGroup` | Stores group config; deployment config defaults to `CodeDeployDefault.OneAtATime` |
+| `CreateDeploymentGroup` | Stores group config; supports `ecsServices` and `loadBalancerInfo` for ECS blue/green; deployment config defaults to `CodeDeployDefault.OneAtATime` |
| `GetDeploymentGroup` | Returns group metadata |
| `UpdateDeploymentGroup` | Partial update; supports rename via `newDeploymentGroupName` |
| `DeleteDeploymentGroup` | Returns `hooksNotCleanedUp: []` |
@@ -48,7 +48,7 @@ Floci implements the CodeDeploy API — stored-state management for applications
| Operation | Notes |
|---|---|
-| `CreateDeployment` | Starts a real Lambda deployment: shifts alias `RoutingConfig` weights for canary/linear strategies; invokes lifecycle hooks |
+| `CreateDeployment` | Starts a real Lambda or ECS blue/green deployment; shifts traffic via alias weights (Lambda) or ELB listener rules (ECS); invokes lifecycle hooks |
| `GetDeployment` | Returns current deployment state; poll `status` until `Succeeded`, `Failed`, or `Stopped` |
| `StopDeployment` | Signals an in-progress deployment to stop; transitions to `Stopped` |
| `ContinueDeployment` | Accepted (no-op for fully automated deployments) |
@@ -100,6 +100,82 @@ The following 17 configurations are always available (matching real AWS):
- `CodeDeployDefault.ECSLinear10PercentEvery1Minutes`
- `CodeDeployDefault.ECSLinear10PercentEvery3Minutes`
+## ECS Deployment Model (Blue/Green)
+
+For `computePlatform: ECS`, `CreateDeployment` performs a full blue/green traffic shift against a real ECS service and ELB v2 listener:
+
+1. Parses the AppSpec (JSON, `revisionType: AppSpecContent`) to extract the target task definition, container name, and port
+2. Creates a **green task set** on the ECS service (via `CreateTaskSet`) pointing to the new task definition
+3. Runs lifecycle hook Lambdas in order: `BeforeInstall` → (install) → `AfterInstall` → `BeforeAllowTraffic` → (traffic shift) → `AfterAllowTraffic`
+4. **Traffic shift** — atomically updates the ELB v2 listener's default forward rule:
+ - `ECSAllAtOnce`: immediately shifts 100% of traffic to the green target group
+ - `ECSCanary*`: shifts the canary percentage first, waits a short interval (capped at 5 s in emulator), then shifts to 100%
+ - `ECSLinear*`: shifts traffic in equal increments (capped at 2 s per step in emulator)
+5. Promotes the green task set to **PRIMARY** on the ECS service and deletes the original blue task set
+6. Marks the deployment `Succeeded`; if any lifecycle hook reports `Failed`, the deployment is marked `Failed`
+
+**Compute platform resolution**: `computePlatform` is set on the Application at creation time. The deployment group inherits it — you do not pass `computePlatform` to `CreateDeploymentGroup`.
+
+### ECS AppSpec Format
+
+```json
+{
+ "version": 0.0,
+ "Resources": [{
+ "TargetService": {
+ "Type": "AWS::ECS::Service",
+ "Properties": {
+ "TaskDefinition": "my-task:2",
+ "LoadBalancerInfo": {
+ "ContainerName": "app",
+ "ContainerPort": 80
+ }
+ }
+ }
+ }],
+ "Hooks": [
+ { "BeforeInstall": "my-before-install-hook" },
+ { "AfterInstall": "my-after-install-hook" },
+ { "BeforeAllowTraffic": "my-before-traffic-hook" },
+ { "AfterAllowTraffic": "my-after-traffic-hook" }
+ ]
+}
+```
+
+All hook fields are optional.
+
+### ECS Deployment Group Configuration
+
+```json
+{
+ "applicationName": "my-ecs-app",
+ "deploymentGroupName": "my-ecs-group",
+ "deploymentConfigName": "CodeDeployDefault.ECSAllAtOnce",
+ "serviceRoleArn": "arn:aws:iam::000000000000:role/codedeploy-role",
+ "deploymentStyle": {
+ "deploymentType": "BLUE_GREEN",
+ "deploymentOption": "WITH_TRAFFIC_CONTROL"
+ },
+ "ecsServices": [{
+ "clusterName": "my-cluster",
+ "serviceName": "my-service"
+ }],
+ "loadBalancerInfo": {
+ "targetGroupPairInfoList": [{
+ "targetGroups": [
+ { "name": "my-blue-tg" },
+ { "name": "my-green-tg" }
+ ],
+ "prodTrafficRoute": {
+ "listenerArns": ["arn:aws:elasticloadbalancing:..."]
+ }
+ }]
+ }
+}
+```
+
+The ECS service must be created with `deploymentController.type: EXTERNAL`.
+
## Lambda Deployment Model
For `computePlatform: Lambda`, `CreateDeployment` performs real traffic shifting:
@@ -122,8 +198,10 @@ floci:
## CLI Examples
+### Lambda
+
```bash
-# Create an application
+# Create a Lambda application
aws --endpoint-url http://localhost:4566 deploy create-application \
--application-name my-app \
--compute-platform Lambda
@@ -136,15 +214,47 @@ aws --endpoint-url http://localhost:4566 deploy create-deployment-group \
--service-role-arn arn:aws:iam::000000000000:role/codedeploy-role \
--deployment-style deploymentType=BLUE_GREEN,deploymentOption=WITH_TRAFFIC_CONTROL
-# Start a deployment
+# Start a Lambda deployment
aws --endpoint-url http://localhost:4566 deploy create-deployment \
--application-name my-app \
--deployment-group-name my-group \
- --revision revisionType=AppSpecContent,appSpecContent={content='{"version":0.0,"Resources":[{"myFunction":{"Type":"AWS::Lambda::Function","Properties":{"Name":"my-function","Alias":"live","CurrentVersion":"1","TargetVersion":"2"}}}]}'}
+ --revision 'revisionType=AppSpecContent,appSpecContent={content="{\"version\":0.0,\"Resources\":[{\"myFunction\":{\"Type\":\"AWS::Lambda::Function\",\"Properties\":{\"Name\":\"my-function\",\"Alias\":\"live\",\"CurrentVersion\":\"1\",\"TargetVersion\":\"2\"}}}]}"}'
+```
+
+### ECS Blue/Green
+
+```bash
+# Create an ECS application
+aws --endpoint-url http://localhost:4566 deploy create-application \
+ --application-name my-ecs-app \
+ --compute-platform ECS
+
+# Create a deployment group (listener ARN from ELB v2)
+aws --endpoint-url http://localhost:4566 deploy create-deployment-group \
+ --application-name my-ecs-app \
+ --deployment-group-name my-ecs-group \
+ --deployment-config-name CodeDeployDefault.ECSAllAtOnce \
+ --service-role-arn arn:aws:iam::000000000000:role/codedeploy-role \
+ --ecs-services clusterName=my-cluster,serviceName=my-service \
+ --load-balancer-info 'targetGroupPairInfoList=[{targetGroups=[{name=blue-tg},{name=green-tg}],prodTrafficRoute={listenerArns=[<listener-arn>]}}]'
+
+# Start an ECS blue/green deployment
+aws --endpoint-url http://localhost:4566 deploy create-deployment \
+ --application-name my-ecs-app \
+ --deployment-group-name my-ecs-group \
+ --revision 'revisionType=AppSpecContent,appSpecContent={content="{\"version\":0.0,\"Resources\":[{\"TargetService\":{\"Type\":\"AWS::ECS::Service\",\"Properties\":{\"TaskDefinition\":\"my-task:2\",\"LoadBalancerInfo\":{\"ContainerName\":\"app\",\"ContainerPort\":80}}}}]}"}'
# Poll deployment status
aws --endpoint-url http://localhost:4566 deploy get-deployment --deployment-id <id>
+# List deployment targets
+aws --endpoint-url http://localhost:4566 deploy list-deployment-targets --deployment-id <id>
+
+# Get target details
+aws --endpoint-url http://localhost:4566 deploy batch-get-deployment-targets \
+ --deployment-id <id> \
+ --target-ids <target-id>
+
# List built-in deployment configs
aws --endpoint-url http://localhost:4566 deploy list-deployment-configs
```
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 1e2fa63a07..92bc2874df 100644
--- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java
+++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java
@@ -718,6 +718,9 @@ public interface EmulatorConfig {
interface ElbV2ServiceConfig {
@WithDefault("true")
boolean enabled();
+
+ @WithDefault("false")
+ boolean mock();
}
interface EksServiceConfig {
diff --git a/src/main/java/io/github/hectorvent/floci/services/codedeploy/CodeDeployService.java b/src/main/java/io/github/hectorvent/floci/services/codedeploy/CodeDeployService.java
index 540ca6093e..946ed3dbb2 100644
--- a/src/main/java/io/github/hectorvent/floci/services/codedeploy/CodeDeployService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/codedeploy/CodeDeployService.java
@@ -8,6 +8,10 @@ import io.github.hectorvent.floci.services.codedeploy.model.Application;
import io.github.hectorvent.floci.services.codedeploy.model.Deployment;
import io.github.hectorvent.floci.services.codedeploy.model.DeploymentConfig;
import io.github.hectorvent.floci.services.codedeploy.model.DeploymentGroup;
+import io.github.hectorvent.floci.services.ecs.EcsService;
+import io.github.hectorvent.floci.services.ecs.model.TaskSet;
+import io.github.hectorvent.floci.services.elbv2.ElbV2Service;
+import io.github.hectorvent.floci.services.elbv2.model.TargetGroup;
import io.github.hectorvent.floci.services.lambda.LambdaService;
import io.github.hectorvent.floci.services.lambda.model.InvocationType;
import io.github.hectorvent.floci.services.lambda.model.InvokeResult;
@@ -34,11 +38,16 @@ public class CodeDeployService {
private static final Logger LOG = Logger.getLogger(CodeDeployService.class);
private final LambdaService lambdaService;
+ private final EcsService ecsService;
+ private final ElbV2Service elbV2Service;
private final ObjectMapper mapper;
@Inject
- public CodeDeployService(LambdaService lambdaService, ObjectMapper mapper) {
+ public CodeDeployService(LambdaService lambdaService, EcsService ecsService,
+ ElbV2Service elbV2Service, ObjectMapper mapper) {
this.lambdaService = lambdaService;
+ this.ecsService = ecsService;
+ this.elbV2Service = elbV2Service;
this.mapper = mapper;
}
@@ -68,6 +77,16 @@ public class CodeDeployService {
String afterAllowTraffic;
}
+ private static final class EcsAppSpecInfo {
+ String taskDefinition;
+ String containerName;
+ int containerPort;
+ String beforeInstall;
+ String afterInstall;
+ String beforeAllowTraffic;
+ String afterAllowTraffic;
+ }
+
private static final class TrafficRoutingInfo {
final String type;
final int percentage;
@@ -400,11 +419,19 @@ public class CodeDeployService {
public String createDeployment(String region, String appName, String groupName,
String configName, Map<String, Object> revision, String description) {
- getApplication(region, appName);
- getDeploymentGroup(region, appName, groupName);
+ Application app = getApplication(region, appName);
+ DeploymentGroup group = getDeploymentGroup(region, appName, groupName);
+ // Compute platform is authoritative on the Application; the deployment group may also carry it
+ String computePlatform = group.getComputePlatform();
+ if (computePlatform == null) {
+ computePlatform = app.getComputePlatform();
+ }
+
+ if ("ECS".equals(computePlatform)) {
+ return createEcsDeployment(region, appName, groupName, group, configName, revision, description);
+ }
AppSpecInfo appSpec = parseAppSpec(revision);
- DeploymentGroup group = getDeploymentGroup(region, appName, groupName);
String effectiveConfig = configName != null ? configName : group.getDeploymentConfigName();
String deploymentId = generateDeploymentId();
@@ -500,9 +527,7 @@ public class CodeDeployService {
if (target == null) {
return List.of();
}
- @SuppressWarnings("unchecked")
- Map<String, Object> lambdaTarget = (Map<String, Object>) target.get("lambdaTarget");
- String targetId = lambdaTarget != null ? (String) lambdaTarget.get("targetId") : null;
+ String targetId = extractTargetId(target);
return targetId != null ? List.of(targetId) : List.of();
}
@@ -512,15 +537,24 @@ public class CodeDeployService {
if (target == null) {
return List.of();
}
- @SuppressWarnings("unchecked")
- Map<String, Object> lambdaTarget = (Map<String, Object>) target.get("lambdaTarget");
- String targetId = lambdaTarget != null ? (String) lambdaTarget.get("targetId") : null;
+ String targetId = extractTargetId(target);
if (targetId == null || (!targetIds.isEmpty() && !targetIds.contains(targetId))) {
return List.of();
}
return List.of(target);
}
+ @SuppressWarnings("unchecked")
+ private String extractTargetId(Map<String, Object> target) {
+ String type = (String) target.get("deploymentTargetType");
+ if ("ECSTarget".equals(type)) {
+ Map<String, Object> ecsTarget = (Map<String, Object>) target.get("ecsTarget");
+ return ecsTarget != null ? (String) ecsTarget.get("targetId") : null;
+ }
+ Map<String, Object> lambdaTarget = (Map<String, Object>) target.get("lambdaTarget");
+ return lambdaTarget != null ? (String) lambdaTarget.get("targetId") : null;
+ }
+
public String putLifecycleEventHookExecutionStatus(String deploymentId, String executionId, String status) {
CompletableFuture<String> future = hookFutures.get(executionId);
if (future != null && !future.isDone()) {
@@ -582,6 +616,383 @@ public class CodeDeployService {
return info;
}
+ @SuppressWarnings("unchecked")
+ private EcsAppSpecInfo parseEcsAppSpec(Map<String, Object> revision) {
+ if (revision == null) {
+ throw new AwsException("InvalidRevisionException", "Revision is required", 400);
+ }
+ Object appSpecContent = revision.get("appSpecContent");
+ if (!(appSpecContent instanceof Map)) {
+ throw new AwsException("InvalidRevisionException", "Missing appSpecContent in revision", 400);
+ }
+ String content = (String) ((Map<String, Object>) appSpecContent).get("content");
+ if (content == null || content.isBlank()) {
+ throw new AwsException("InvalidRevisionException", "Missing content in appSpecContent", 400);
+ }
+
+ EcsAppSpecInfo info = new EcsAppSpecInfo();
+ try {
+ JsonNode root = mapper.readTree(content);
+ JsonNode resources = root.get("Resources");
+ if (resources != null && resources.isArray() && !resources.isEmpty()) {
+ JsonNode firstResource = resources.get(0);
+ if (firstResource.isObject()) {
+ JsonNode resourceNode = firstResource.fields().next().getValue();
+ JsonNode props = resourceNode.path("Properties");
+ info.taskDefinition = props.path("TaskDefinition").asText(null);
+ JsonNode lbInfo = props.path("LoadBalancerInfo");
+ if (!lbInfo.isMissingNode()) {
+ info.containerName = lbInfo.path("ContainerName").asText(null);
+ info.containerPort = lbInfo.path("ContainerPort").asInt(80);
+ }
+ }
+ }
+ JsonNode hooks = root.get("Hooks");
+ if (hooks != null && hooks.isArray()) {
+ for (JsonNode hook : hooks) {
+ if (hook.has("BeforeInstall")) {
+ info.beforeInstall = hook.get("BeforeInstall").asText(null);
+ }
+ if (hook.has("AfterInstall")) {
+ info.afterInstall = hook.get("AfterInstall").asText(null);
+ }
+ if (hook.has("BeforeAllowTraffic")) {
+ info.beforeAllowTraffic = hook.get("BeforeAllowTraffic").asText(null);
+ }
+ if (hook.has("AfterAllowTraffic")) {
+ info.afterAllowTraffic = hook.get("AfterAllowTraffic").asText(null);
+ }
+ }
+ }
+ } catch (Exception e) {
+ throw new AwsException("InvalidRevisionException", "Failed to parse ECS AppSpec: " + e.getMessage(), 400);
+ }
+
+ if (info.taskDefinition == null) {
+ throw new AwsException("InvalidRevisionException", "ECS AppSpec must specify TaskDefinition", 400);
+ }
+ return info;
+ }
+
+ @SuppressWarnings("unchecked")
+ private String createEcsDeployment(String region, String appName, String groupName,
+ DeploymentGroup group, String configName,
+ Map<String, Object> revision, String description) {
+ EcsAppSpecInfo appSpec = parseEcsAppSpec(revision);
+ String effectiveConfig = configName != null ? configName : group.getDeploymentConfigName();
+
+ String deploymentId = generateDeploymentId();
+ double now = Instant.now().toEpochMilli() / 1000.0;
+
+ Deployment deployment = new Deployment();
+ deployment.setDeploymentId(deploymentId);
+ deployment.setApplicationName(appName);
+ deployment.setDeploymentGroupName(groupName);
+ deployment.setDeploymentConfigName(effectiveConfig);
+ deployment.setStatus("Queued");
+ deployment.setRevision(revision);
+ deployment.setCreateTime(now);
+ deployment.setDescription(description);
+ deployment.setCreator("user");
+ deployment.setComputePlatform("ECS");
+ deploymentsFor(region).put(deploymentId, deployment);
+
+ // Determine ECS cluster/service from deployment group
+ String clusterName = "default";
+ String serviceName = null;
+ List<Map<String, Object>> ecsSvcs = group.getEcsServices();
+ if (ecsSvcs != null && !ecsSvcs.isEmpty()) {
+ Map<String, Object> svc = ecsSvcs.get(0);
+ clusterName = (String) svc.getOrDefault("clusterName", "default");
+ serviceName = (String) svc.get("serviceName");
+ }
+ if (serviceName == null) {
+ throw new AwsException("InvalidDeploymentConfigException",
+ "ECS deployment group must specify ecsServices", 400);
+ }
+
+ // Determine blue/green TG ARNs from loadBalancerInfo
+ String blueTgArn = null;
+ String greenTgArn = null;
+ List<String> listenerArns = new ArrayList<>();
+ Map<String, Object> lbInfo = group.getLoadBalancerInfo();
+ if (lbInfo != null) {
+ List<Map<String, Object>> pairList = (List<Map<String, Object>>) lbInfo.get("targetGroupPairInfoList");
+ if (pairList != null && !pairList.isEmpty()) {
+ Map<String, Object> pair = pairList.get(0);
+ List<Map<String, Object>> tgList = (List<Map<String, Object>>) pair.get("targetGroups");
+ if (tgList != null && tgList.size() >= 2) {
+ String blueName = (String) tgList.get(0).get("name");
+ String greenName = (String) tgList.get(1).get("name");
+ TargetGroup blueTg = elbV2Service.getTargetGroupByName(region, blueName);
+ TargetGroup greenTg = elbV2Service.getTargetGroupByName(region, greenName);
+ if (blueTg != null) { blueTgArn = blueTg.getTargetGroupArn(); }
+ if (greenTg != null) { greenTgArn = greenTg.getTargetGroupArn(); }
+ }
+ Map<String, Object> prodRoute = (Map<String, Object>) pair.get("prodTrafficRoute");
+ if (prodRoute != null) {
+ List<String> arns = (List<String>) prodRoute.get("listenerArns");
+ if (arns != null) { listenerArns.addAll(arns); }
+ }
+ }
+ }
+
+ String targetId = clusterName + ":" + serviceName;
+ String targetArn = AwsArnUtils.Arn.of("ecs", region, "000000000000", "service/" + clusterName + "/" + serviceName).toString();
+
+ Map<String, Object> ecsTargetMap = new ConcurrentHashMap<>();
+ ecsTargetMap.put("deploymentId", deploymentId);
+ ecsTargetMap.put("targetId", targetId);
+ ecsTargetMap.put("targetArn", targetArn);
+ ecsTargetMap.put("status", "Pending");
+ ecsTargetMap.put("lastUpdatedAt", now);
+ ecsTargetMap.put("lifecycleEvents", new CopyOnWriteArrayList<>());
+ ecsTargetMap.put("taskSetsInfo", new CopyOnWriteArrayList<>());
+
+ Map<String, Object> targetMap = new ConcurrentHashMap<>();
+ targetMap.put("deploymentTargetType", "ECSTarget");
+ targetMap.put("ecsTarget", ecsTargetMap);
+ deploymentTargetsFor(region).put(deploymentId, targetMap);
+
+ AtomicBoolean stopFlag = new AtomicBoolean(false);
+ stopFlags.put(deploymentId, stopFlag);
+
+ final String finalCluster = clusterName;
+ final String finalService = serviceName;
+ final String finalBlueTgArn = blueTgArn;
+ final String finalGreenTgArn = greenTgArn;
+ final List<String> finalListenerArns = listenerArns;
+ Thread.ofVirtual().name("codedeploy-ecs-" + deploymentId).start(
+ () -> runEcsStateMachine(region, deployment, appSpec, ecsTargetMap, stopFlag,
+ effectiveConfig, finalCluster, finalService,
+ finalBlueTgArn, finalGreenTgArn, finalListenerArns));
+
+ return deploymentId;
+ }
+
+ private void runEcsStateMachine(String region, Deployment deployment, EcsAppSpecInfo appSpec,
+ Map<String, Object> ecsTargetMap, AtomicBoolean stopFlag,
+ String configName, String clusterName, String serviceName,
+ String blueTgArn, String greenTgArn,
+ List<String> listenerArns) {
+ String deploymentId = deployment.getDeploymentId();
+ TaskSet greenTaskSet = null;
+ TaskSet blueTaskSet = null;
+ try {
+ deployment.setStatus("InProgress");
+ deployment.setStartTime(Instant.now().toEpochMilli() / 1000.0);
+ updateEcsTargetStatus(ecsTargetMap, "InProgress");
+
+ if (stopFlag.get()) { finishEcsStopped(deployment, ecsTargetMap); return; }
+
+ // Find existing primary (blue) task set
+ List<TaskSet> existing = ecsService.describeTaskSets(clusterName, serviceName, null, region);
+ blueTaskSet = existing.stream()
+ .filter(ts -> "PRIMARY".equals(ts.getStatus()))
+ .findFirst()
+ .orElse(existing.isEmpty() ? null : existing.get(0));
+
+ if (appSpec.beforeInstall != null) {
+ boolean ok = invokeHook(region, deployment, appSpec.beforeInstall,
+ "BeforeInstall", ecsTargetMap, stopFlag);
+ if (!ok) {
+ finishEcsFailed(deployment, ecsTargetMap, "BeforeInstallHookFailed",
+ "Hook function reported failure: BeforeInstall");
+ return;
+ }
+ }
+
+ if (stopFlag.get()) { finishEcsStopped(deployment, ecsTargetMap); return; }
+
+ // Install: create green task set
+ Map<String, Object> installEvent = addLifecycleEvent(ecsTargetMap, "Install");
+ try {
+ greenTaskSet = ecsService.createTaskSet(clusterName, serviceName,
+ appSpec.taskDefinition, null, 100.0, "PERCENT", deploymentId, region);
+ appendTaskSetInfo(ecsTargetMap, greenTaskSet, greenTgArn, 0.0);
+ finishLifecycleEvent(installEvent, "Succeeded");
+ } catch (Exception e) {
+ finishLifecycleEvent(installEvent, "Failed");
+ finishEcsFailed(deployment, ecsTargetMap, "InstallFailed", e.getMessage());
+ return;
+ }
+
+ if (stopFlag.get()) { finishEcsStopped(deployment, ecsTargetMap); return; }
+
+ if (appSpec.afterInstall != null) {
+ boolean ok = invokeHook(region, deployment, appSpec.afterInstall,
+ "AfterInstall", ecsTargetMap, stopFlag);
+ if (!ok) {
+ finishEcsFailed(deployment, ecsTargetMap, "AfterInstallHookFailed",
+ "Hook function reported failure: AfterInstall");
+ return;
+ }
+ }
+
+ if (stopFlag.get()) { finishEcsStopped(deployment, ecsTargetMap); return; }
+
+ if (appSpec.beforeAllowTraffic != null) {
+ boolean ok = invokeHook(region, deployment, appSpec.beforeAllowTraffic,
+ "BeforeAllowTraffic", ecsTargetMap, stopFlag);
+ if (!ok) {
+ finishEcsFailed(deployment, ecsTargetMap, "BeforeAllowTrafficHookFailed",
+ "Hook function reported failure: BeforeAllowTraffic");
+ return;
+ }
+ }
+
+ if (stopFlag.get()) { finishEcsStopped(deployment, ecsTargetMap); return; }
+
+ // AllowTraffic: shift ELB traffic blue → green
+ if (!listenerArns.isEmpty() && blueTgArn != null && greenTgArn != null) {
+ executeEcsAllowTraffic(region, deployment, configName, ecsTargetMap,
+ listenerArns, blueTgArn, greenTgArn, stopFlag);
+ } else {
+ Map<String, Object> allowEvent = addLifecycleEvent(ecsTargetMap, "AllowTraffic");
+ finishLifecycleEvent(allowEvent, "Succeeded");
+ }
+
+ if (stopFlag.get()) { finishEcsStopped(deployment, ecsTargetMap); return; }
+
+ if (appSpec.afterAllowTraffic != null) {
+ boolean ok = invokeHook(region, deployment, appSpec.afterAllowTraffic,
+ "AfterAllowTraffic", ecsTargetMap, stopFlag);
+ if (!ok) {
+ finishEcsFailed(deployment, ecsTargetMap, "AfterAllowTrafficHookFailed",
+ "Hook function reported failure: AfterAllowTraffic");
+ return;
+ }
+ }
+
+ // Promote green as primary
+ if (greenTaskSet != null) {
+ ecsService.updateServicePrimaryTaskSet(clusterName, serviceName,
+ greenTaskSet.getTaskSetArn(), region);
+ }
+
+ // Terminate blue task set
+ if (blueTaskSet != null) {
+ Map<String, Object> terminateEvent = addLifecycleEvent(ecsTargetMap, "TerminateBlueInstances");
+ try {
+ ecsService.deleteTaskSet(clusterName, serviceName,
+ blueTaskSet.getTaskSetArn(), true, region);
+ finishLifecycleEvent(terminateEvent, "Succeeded");
+ } catch (Exception e) {
+ LOG.debugv("Could not delete blue task set: {0}", e.getMessage());
+ finishLifecycleEvent(terminateEvent, "Succeeded");
+ }
+ }
+
+ updateEcsTargetStatus(ecsTargetMap, "Succeeded");
+ deployment.setStatus("Succeeded");
+ deployment.setCompleteTime(Instant.now().toEpochMilli() / 1000.0);
+
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ finishEcsStopped(deployment, ecsTargetMap);
+ } catch (Exception e) {
+ LOG.warnv("ECS deployment {0} failed: {1}", deploymentId, e.getMessage());
+ finishEcsFailed(deployment, ecsTargetMap, "DeploymentFailed", e.getMessage());
+ } finally {
+ stopFlags.remove(deploymentId);
+ }
+ }
+
+ private void executeEcsAllowTraffic(String region, Deployment deployment, String configName,
+ Map<String, Object> ecsTargetMap, List<String> listenerArns,
+ String blueTgArn, String greenTgArn,
+ AtomicBoolean stopFlag) throws InterruptedException {
+ TrafficRoutingInfo trc = getTrafficRoutingInfo(region, configName);
+ Map<String, Object> event = addLifecycleEvent(ecsTargetMap, "AllowTraffic");
+ try {
+ switch (trc.type) {
+ case "TimeBasedCanary" -> {
+ for (String listenerArn : listenerArns) {
+ elbV2Service.shiftListenerForward(region, listenerArn,
+ blueTgArn, greenTgArn, trc.percentage);
+ }
+ long waitMs = Math.min(trc.intervalSeconds * 1000L, 5000L);
+ if (waitMs > 0 && !stopFlag.get()) {
+ Thread.sleep(waitMs);
+ }
+ if (!stopFlag.get()) {
+ for (String listenerArn : listenerArns) {
+ elbV2Service.shiftListenerForward(region, listenerArn,
+ blueTgArn, greenTgArn, 100);
+ }
+ }
+ }
+ case "TimeBasedLinear" -> {
+ int steps = (int) Math.ceil(100.0 / trc.percentage);
+ for (int step = 1; step <= steps && !stopFlag.get(); step++) {
+ int pct = Math.min(step * trc.percentage, 100);
+ for (String listenerArn : listenerArns) {
+ elbV2Service.shiftListenerForward(region, listenerArn,
+ blueTgArn, greenTgArn, pct);
+ }
+ if (pct < 100) {
+ long waitMs = Math.min(trc.intervalSeconds * 1000L, 2000L);
+ if (waitMs > 0) {
+ Thread.sleep(waitMs);
+ }
+ }
+ }
+ }
+ default -> {
+ for (String listenerArn : listenerArns) {
+ elbV2Service.shiftListenerForward(region, listenerArn,
+ blueTgArn, greenTgArn, 100);
+ }
+ }
+ }
+ finishLifecycleEvent(event, "Succeeded");
+ } catch (InterruptedException e) {
+ finishLifecycleEvent(event, "Failed");
+ throw e;
+ } catch (Exception e) {
+ finishLifecycleEvent(event, "Failed");
+ throw e;
+ }
+ }
+
+ @SuppressWarnings("unchecked")
+ private void appendTaskSetInfo(Map<String, Object> ecsTargetMap, TaskSet ts,
+ String tgArn, double trafficWeight) {
+ Map<String, Object> tsInfo = new ConcurrentHashMap<>();
+ tsInfo.put("identifer", ts.getId());
+ tsInfo.put("desiredCount", ts.getComputedDesiredCount());
+ tsInfo.put("pendingCount", ts.getPendingCount());
+ tsInfo.put("runningCount", ts.getRunningCount());
+ tsInfo.put("status", ts.getStatus());
+ tsInfo.put("trafficWeight", trafficWeight);
+ if (tgArn != null) {
+ tsInfo.put("targetGroup", Map.of("arn", tgArn));
+ }
+ List<Map<String, Object>> taskSetsInfo = (List<Map<String, Object>>) ecsTargetMap.get("taskSetsInfo");
+ if (taskSetsInfo != null) {
+ taskSetsInfo.add(tsInfo);
+ }
+ }
+
+ private void updateEcsTargetStatus(Map<String, Object> ecsTargetMap, String status) {
+ ecsTargetMap.put("status", status);
+ ecsTargetMap.put("lastUpdatedAt", Instant.now().toEpochMilli() / 1000.0);
+ }
+
+ private void finishEcsStopped(Deployment deployment, Map<String, Object> ecsTargetMap) {
+ updateEcsTargetStatus(ecsTargetMap, "Skipped");
+ deployment.setStatus("Stopped");
+ deployment.setCompleteTime(Instant.now().toEpochMilli() / 1000.0);
+ }
+
+ private void finishEcsFailed(Deployment deployment, Map<String, Object> ecsTargetMap,
+ String errorCode, String message) {
+ updateEcsTargetStatus(ecsTargetMap, "Failed");
+ deployment.setStatus("Failed");
+ deployment.setCompleteTime(Instant.now().toEpochMilli() / 1000.0);
+ deployment.setErrorInformation(Map.of("code", errorCode, "message", message != null ? message : ""));
+ }
+
@SuppressWarnings("unchecked")
private TrafficRoutingInfo getTrafficRoutingInfo(String region, String configName) {
if (configName == null) {
diff --git a/src/main/java/io/github/hectorvent/floci/services/elbv2/ElbV2DataPlane.java b/src/main/java/io/github/hectorvent/floci/services/elbv2/ElbV2DataPlane.java
new file mode 100644
index 0000000000..6da2988151
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/elbv2/ElbV2DataPlane.java
@@ -0,0 +1,430 @@
+package io.github.hectorvent.floci.services.elbv2;
+
+import io.github.hectorvent.floci.config.EmulatorConfig;
+import io.github.hectorvent.floci.services.elbv2.model.Action;
+import io.github.hectorvent.floci.services.elbv2.model.Listener;
+import io.github.hectorvent.floci.services.elbv2.model.Rule;
+import io.github.hectorvent.floci.services.elbv2.model.RuleCondition;
+import io.github.hectorvent.floci.services.elbv2.model.TargetDescription;
+import io.github.hectorvent.floci.services.elbv2.model.TargetGroup;
+import io.vertx.core.Vertx;
+import io.vertx.core.http.HttpClient;
+import io.vertx.core.http.HttpClientOptions;
+import io.vertx.core.http.HttpServer;
+import io.vertx.core.http.HttpServerOptions;
+import io.vertx.core.http.RequestOptions;
+import jakarta.annotation.PostConstruct;
+import jakarta.annotation.PreDestroy;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.inject.Inject;
+import org.jboss.logging.Logger;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.regex.Pattern;
+import java.util.stream.Collectors;
+
+@ApplicationScoped
+public class ElbV2DataPlane {
+
+ private static final Logger LOG = Logger.getLogger(ElbV2DataPlane.class);
+
+ private static final List<String> HOP_BY_HOP_HEADERS = List.of(
+ "connection", "keep-alive", "transfer-encoding", "upgrade", "te", "trailers", "proxy-authorization", "proxy-authenticate"
+ );
+
+ @Inject
+ Vertx vertx;
+
+ @Inject
+ ElbV2Service elbV2Service;
+
+ @Inject
+ ElbV2HealthChecker healthChecker;
+
+ @Inject
+ EmulatorConfig config;
+
+ private final Map<String, HttpServer> servers = new ConcurrentHashMap<>();
+ private final Map<String, AtomicReference<List<CompiledRule>>> ruleChains = new ConcurrentHashMap<>();
+ private final Map<String, AtomicInteger> rrCounters = new ConcurrentHashMap<>();
+ private final Map<String, String> listenerRegions = new ConcurrentHashMap<>();
+
+ private HttpClient proxyClient;
+
+ @PostConstruct
+ void init() {
+ proxyClient = vertx.createHttpClient(new HttpClientOptions()
+ .setMaxPoolSize(100)
+ .setConnectTimeout(5000)
+ .setKeepAlive(true));
+ }
+
+ @PreDestroy
+ void shutdown() {
+ for (Map.Entry<String, HttpServer> e : servers.entrySet()) {
+ e.getValue().close();
+ }
+ servers.clear();
+ ruleChains.clear();
+ rrCounters.clear();
+ listenerRegions.clear();
+ }
+
+ public void startListener(Listener listener, String region, List<Rule> rules) {
+ if (config.services().elbv2().mock()) {
+ return;
+ }
+ String listenerArn = listener.getListenerArn();
+ List<CompiledRule> compiled = compileRules(rules);
+ ruleChains.put(listenerArn, new AtomicReference<>(compiled));
+ listenerRegions.put(listenerArn, region);
+
+ HttpServer server = vertx.createHttpServer(new HttpServerOptions()
+ .setHost("0.0.0.0")
+ .setPort(listener.getPort()));
+
+ server.requestHandler(req -> handleRequest(req, listenerArn, region));
+ server.listen()
+ .onSuccess(s -> LOG.infov("ELBv2 listener started on port {0} for {1}", listener.getPort(), listenerArn))
+ .onFailure(err -> LOG.warnv("ELBv2 listener failed to start on port {0}: {1}", listener.getPort(), err.getMessage()));
+
+ servers.put(listenerArn, server);
+ }
+
+ public void stopListener(String listenerArn) {
+ HttpServer server = servers.remove(listenerArn);
+ if (server != null) {
+ server.close();
+ }
+ ruleChains.remove(listenerArn);
+ listenerRegions.remove(listenerArn);
+ }
+
+ public void recompileRules(String listenerArn, List<Rule> rules) {
+ AtomicReference<List<CompiledRule>> ref = ruleChains.get(listenerArn);
+ if (ref != null) {
+ ref.set(compileRules(rules));
+ }
+ }
+
+ private void handleRequest(io.vertx.core.http.HttpServerRequest req, String listenerArn, String region) {
+ AtomicReference<List<CompiledRule>> ref = ruleChains.get(listenerArn);
+ if (ref == null) {
+ req.response().setStatusCode(502).end("No rule chain");
+ return;
+ }
+ List<CompiledRule> chain = ref.get();
+ for (CompiledRule compiled : chain) {
+ if (compiled.matches(req)) {
+ executeAction(req, compiled.action, region);
+ return;
+ }
+ }
+ req.response().setStatusCode(502).end("No matching rule");
+ }
+
+ private void executeAction(io.vertx.core.http.HttpServerRequest req, Action action, String region) {
+ if (action == null) {
+ req.response().setStatusCode(502).end("No action");
+ return;
+ }
+ switch (action.getType() != null ? action.getType() : "") {
+ case "forward" -> executeForward(req, action, region);
+ case "redirect" -> executeRedirect(req, action);
+ case "fixed-response" -> executeFixedResponse(req, action);
+ default -> req.response().setStatusCode(502).end("Unsupported action type");
+ }
+ }
+
+ private void executeForward(io.vertx.core.http.HttpServerRequest req, Action action, String region) {
+ String tgArn = resolveTgArn(action);
+ if (tgArn == null) {
+ req.response().setStatusCode(502).end("No target group");
+ return;
+ }
+ TargetGroup tg = elbV2Service.getTargetGroup(region, tgArn);
+ if (tg == null) {
+ req.response().setStatusCode(502).end("Target group not found");
+ return;
+ }
+ List<TargetDescription> allTargets = tg.getTargets();
+ List<TargetDescription> healthy = allTargets.stream()
+ .filter(t -> healthChecker.isHealthy(tgArn, t, ElbV2HealthChecker.effectivePort(t, tg)))
+ .collect(Collectors.toList());
+ List<TargetDescription> candidates = healthy.isEmpty() ? allTargets : healthy;
+ if (candidates.isEmpty()) {
+ req.response().setStatusCode(503).end("No targets available");
+ return;
+ }
+ AtomicInteger counter = rrCounters.computeIfAbsent(tgArn, k -> new AtomicInteger(0));
+ int idx = Math.abs(counter.getAndIncrement() % candidates.size());
+ TargetDescription target = candidates.get(idx);
+ int targetPort = ElbV2HealthChecker.effectivePort(target, tg);
+ proxyRequest(req, target.getId(), targetPort);
+ }
+
+ private String resolveTgArn(Action action) {
+ if (action.getTargetGroupArn() != null) {
+ return action.getTargetGroupArn();
+ }
+ List<Action.TargetGroupTuple> tuples = action.getTargetGroups();
+ if (tuples == null || tuples.isEmpty()) {
+ return null;
+ }
+ double total = tuples.stream().mapToDouble(t -> t.getWeight() != null ? t.getWeight() : 1).sum();
+ double roll = Math.random() * total;
+ double cumulative = 0;
+ for (Action.TargetGroupTuple tuple : tuples) {
+ cumulative += (tuple.getWeight() != null ? tuple.getWeight() : 1);
+ if (roll < cumulative) {
+ return tuple.getTargetGroupArn();
+ }
+ }
+ return tuples.get(tuples.size() - 1).getTargetGroupArn();
+ }
+
+ private void proxyRequest(io.vertx.core.http.HttpServerRequest req, String host, int port) {
+ req.bodyHandler(body -> {
+ RequestOptions opts = new RequestOptions()
+ .setHost(host)
+ .setPort(port)
+ .setURI(req.uri())
+ .setMethod(req.method());
+ proxyClient.request(opts)
+ .onSuccess(clientReq -> {
+ req.headers().forEach(entry -> {
+ if (!HOP_BY_HOP_HEADERS.contains(entry.getKey().toLowerCase())) {
+ clientReq.putHeader(entry.getKey(), entry.getValue());
+ }
+ });
+ clientReq.putHeader("Host", host + ":" + port);
+ clientReq.send(body)
+ .onSuccess(resp -> {
+ req.response().setStatusCode(resp.statusCode());
+ resp.headers().forEach(entry -> {
+ if (!HOP_BY_HOP_HEADERS.contains(entry.getKey().toLowerCase())) {
+ req.response().putHeader(entry.getKey(), entry.getValue());
+ }
+ });
+ resp.body()
+ .onSuccess(req.response()::end)
+ .onFailure(err -> req.response().setStatusCode(502).end("Body error"));
+ })
+ .onFailure(err -> req.response().setStatusCode(502).end("Bad gateway"));
+ })
+ .onFailure(err -> req.response().setStatusCode(503).end("Service unavailable"));
+ });
+ }
+
+ private void executeRedirect(io.vertx.core.http.HttpServerRequest req, Action action) {
+ String reqHost = req.host();
+ String reqPort = "";
+ if (reqHost != null && reqHost.contains(":")) {
+ String[] parts = reqHost.split(":", 2);
+ reqHost = parts[0];
+ reqPort = parts[1];
+ }
+ String reqPath = req.path() != null ? req.path() : "/";
+ String reqQuery = req.query();
+ String reqProtocol = "HTTP";
+
+ String protocol = action.getRedirectProtocol() != null ? action.getRedirectProtocol() : reqProtocol;
+ String host = action.getRedirectHost() != null ? action.getRedirectHost() : reqHost;
+ String portStr = action.getRedirectPort() != null ? action.getRedirectPort() : reqPort;
+ String path = action.getRedirectPath() != null ? action.getRedirectPath() : reqPath;
+ String query = action.getRedirectQuery() != null ? action.getRedirectQuery() : (reqQuery != null ? reqQuery : "");
+
+ final String finalReqHost = reqHost;
+ final String finalReqPort = reqPort;
+
+ protocol = substitute(protocol, finalReqHost, finalReqPort, reqPath, reqProtocol, reqQuery);
+ host = substitute(host, finalReqHost, finalReqPort, reqPath, reqProtocol, reqQuery);
+ portStr = substitute(portStr, finalReqHost, finalReqPort, reqPath, reqProtocol, reqQuery);
+ path = substitute(path, finalReqHost, finalReqPort, reqPath, reqProtocol, reqQuery);
+ query = substitute(query, finalReqHost, finalReqPort, reqPath, reqProtocol, reqQuery);
+
+ StringBuilder location = new StringBuilder(protocol.toLowerCase()).append("://").append(host);
+ if (!portStr.isEmpty()) {
+ location.append(":").append(portStr);
+ }
+ location.append(path);
+ if (!query.isEmpty()) {
+ location.append("?").append(query);
+ }
+
+ int statusCode = "HTTP_301".equals(action.getRedirectStatusCode()) ? 301 : 302;
+ req.response()
+ .setStatusCode(statusCode)
+ .putHeader("Location", location.toString())
+ .end();
+ }
+
+ private String substitute(String template, String host, String port, String path, String protocol, String query) {
+ if (template == null) {
+ return "";
+ }
+ String result = template
+ .replace("#{host}", host != null ? host : "")
+ .replace("#{port}", port != null ? port : "")
+ .replace("#{path}", path != null ? path : "/")
+ .replace("#{protocol}", protocol != null ? protocol : "HTTP");
+ if (query != null && !query.isEmpty()) {
+ result = result.replace("#{query}", query);
+ } else {
+ result = result.replace("#{query}", "");
+ }
+ return result;
+ }
+
+ private void executeFixedResponse(io.vertx.core.http.HttpServerRequest req, Action action) {
+ int statusCode = 200;
+ try {
+ if (action.getFixedResponseStatusCode() != null) {
+ statusCode = Integer.parseInt(action.getFixedResponseStatusCode());
+ }
+ } catch (NumberFormatException ignored) {
+ }
+ req.response().setStatusCode(statusCode);
+ if (action.getFixedResponseContentType() != null) {
+ req.response().putHeader("Content-Type", action.getFixedResponseContentType());
+ }
+ String body = action.getFixedResponseMessageBody() != null ? action.getFixedResponseMessageBody() : "";
+ req.response().end(body);
+ }
+
+ private List<CompiledRule> compileRules(List<Rule> rules) {
+ return rules.stream()
+ .map(CompiledRule::new)
+ .collect(Collectors.toList());
+ }
+
+ private Action getRoutingAction(Rule rule) {
+ List<Action> actions = rule.getActions();
+ if (actions == null || actions.isEmpty()) {
+ return null;
+ }
+ Action last = null;
+ for (Action a : actions) {
+ String type = a.getType();
+ if ("forward".equals(type) || "redirect".equals(type) || "fixed-response".equals(type)) {
+ last = a;
+ }
+ }
+ return last;
+ }
+
+ private static boolean globMatches(String pattern, String text) {
+ if (text == null) {
+ return false;
+ }
+ StringBuilder regex = new StringBuilder("(?i)");
+ for (char c : pattern.toCharArray()) {
+ if (c == '*') {
+ regex.append(".*");
+ } else if (c == '?') {
+ regex.append('.');
+ } else {
+ regex.append(Pattern.quote(String.valueOf(c)));
+ }
+ }
+ return Pattern.matches(regex.toString(), text);
+ }
+
+ private class CompiledRule {
+ final Rule rule;
+ final Action action;
+
+ CompiledRule(Rule rule) {
+ this.rule = rule;
+ this.action = getRoutingAction(rule);
+ }
+
+ boolean matches(io.vertx.core.http.HttpServerRequest req) {
+ if (rule.isDefault()) {
+ return true;
+ }
+ for (RuleCondition condition : rule.getConditions()) {
+ if (!matchesCondition(condition, req)) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ private boolean matchesCondition(RuleCondition condition, io.vertx.core.http.HttpServerRequest req) {
+ String field = condition.getField();
+ if (field == null) {
+ return true;
+ }
+ return switch (field) {
+ case "host-header" -> {
+ List<String> patterns = condition.getHostHeaderValues().isEmpty()
+ ? condition.getValues()
+ : condition.getHostHeaderValues();
+ String host = req.host();
+ if (host != null && host.contains(":")) {
+ host = host.substring(0, host.indexOf(':'));
+ }
+ String effectiveHost = host;
+ yield patterns.stream().anyMatch(p -> globMatches(p, effectiveHost));
+ }
+ case "path-pattern" -> {
+ List<String> patterns = condition.getPathPatternValues().isEmpty()
+ ? condition.getValues()
+ : condition.getPathPatternValues();
+ String path = req.path();
+ yield patterns.stream().anyMatch(p -> globMatches(p, path));
+ }
+ case "http-header" -> {
+ String headerName = condition.getHttpHeaderName();
+ if (headerName == null) {
+ yield true;
+ }
+ String headerValue = req.getHeader(headerName);
+ yield condition.getHttpHeaderValues().stream().anyMatch(p -> globMatches(p, headerValue));
+ }
+ case "http-request-method" -> {
+ String method = req.method().name();
+ yield condition.getHttpMethodValues().stream()
+ .anyMatch(m -> m.equalsIgnoreCase(method));
+ }
+ case "query-string" -> {
+ String queryString = req.query();
+ Map<String, String> queryParams = parseQueryString(queryString);
+ yield condition.getQueryStringValues().stream().allMatch(pair -> {
+ String key = pair.getKey();
+ String valuePattern = pair.getValue();
+ if (key == null) {
+ return queryParams.values().stream().anyMatch(v -> globMatches(valuePattern, v));
+ }
+ String paramValue = queryParams.get(key);
+ return paramValue != null && globMatches(valuePattern, paramValue);
+ });
+ }
+ case "source-ip" -> true;
+ default -> true;
+ };
+ }
+
+ private Map<String, String> parseQueryString(String query) {
+ Map<String, String> params = new java.util.LinkedHashMap<>();
+ if (query == null || query.isEmpty()) {
+ return params;
+ }
+ for (String pair : query.split("&")) {
+ int eq = pair.indexOf('=');
+ if (eq >= 0) {
+ params.put(pair.substring(0, eq), pair.substring(eq + 1));
+ } else {
+ params.put(pair, "");
+ }
+ }
+ return params;
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/main/java/io/github/hectorvent/floci/services/elbv2/ElbV2HealthChecker.java b/src/main/java/io/github/hectorvent/floci/services/elbv2/ElbV2HealthChecker.java
new file mode 100644
index 0000000000..b176f5af31
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/elbv2/ElbV2HealthChecker.java
@@ -0,0 +1,202 @@
+package io.github.hectorvent.floci.services.elbv2;
+
+import io.github.hectorvent.floci.config.EmulatorConfig;
+import io.github.hectorvent.floci.services.elbv2.model.TargetDescription;
+import io.github.hectorvent.floci.services.elbv2.model.TargetGroup;
+import io.vertx.core.Vertx;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.inject.Inject;
+import org.jboss.logging.Logger;
+
+import java.io.IOException;
+import java.net.HttpURLConnection;
+import java.net.URL;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+
+@ApplicationScoped
+public class ElbV2HealthChecker {
+
+ private static final Logger LOG = Logger.getLogger(ElbV2HealthChecker.class);
+
+ private final Vertx vertx;
+ private final EmulatorConfig config;
+
+ // tgArn → (targetKey → TargetState)
+ private final Map<String, Map<String, TargetState>> states = new ConcurrentHashMap<>();
+ // tgArn → timerId
+ private final Map<String, Long> timers = new ConcurrentHashMap<>();
+
+ @Inject
+ public ElbV2HealthChecker(Vertx vertx, EmulatorConfig config) {
+ this.vertx = vertx;
+ this.config = config;
+ }
+
+ public static int effectivePort(TargetDescription target, TargetGroup tg) {
+ if (target.getPort() != null) {
+ return target.getPort();
+ }
+ if (tg.getPort() != null) {
+ return tg.getPort();
+ }
+ return 80;
+ }
+
+ public void startMonitoring(TargetGroup tg) {
+ if (config.services().elbv2().mock()) {
+ return;
+ }
+ String tgArn = tg.getTargetGroupArn();
+ states.computeIfAbsent(tgArn, k -> new ConcurrentHashMap<>());
+
+ long intervalMs = (tg.getHealthCheckIntervalSeconds() != null ? tg.getHealthCheckIntervalSeconds() : 30) * 1000L;
+ long timerId = vertx.setPeriodic(intervalMs, id -> probeAll(tgArn, tg));
+ timers.put(tgArn, timerId);
+ }
+
+ public void stopMonitoring(String tgArn) {
+ Long timerId = timers.remove(tgArn);
+ if (timerId != null) {
+ vertx.cancelTimer(timerId);
+ }
+ states.remove(tgArn);
+ }
+
+ public void addTargets(String tgArn, List<TargetDescription> targets, TargetGroup tg) {
+ if (config.services().elbv2().mock()) {
+ return;
+ }
+ Map<String, TargetState> tgStates = states.computeIfAbsent(tgArn, k -> new ConcurrentHashMap<>());
+ for (TargetDescription t : targets) {
+ int port = effectivePort(t, tg);
+ String key = stateKey(t.getId(), port);
+ tgStates.putIfAbsent(key, new TargetState());
+ }
+ }
+
+ public void removeTargets(String tgArn, List<TargetDescription> targets, TargetGroup tg) {
+ Map<String, TargetState> tgStates = states.get(tgArn);
+ if (tgStates == null) {
+ return;
+ }
+ for (TargetDescription t : targets) {
+ int port = effectivePort(t, tg);
+ tgStates.remove(stateKey(t.getId(), port));
+ }
+ }
+
+ public String getState(String tgArn, String targetId, int port) {
+ Map<String, TargetState> tgStates = states.get(tgArn);
+ if (tgStates == null) {
+ return "initial";
+ }
+ TargetState s = tgStates.get(stateKey(targetId, port));
+ if (s == null) {
+ return "initial";
+ }
+ return s.status;
+ }
+
+ public boolean isHealthy(String tgArn, TargetDescription target, int port) {
+ String state = getState(tgArn, target.getId(), port);
+ return "healthy".equals(state) || "initial".equals(state);
+ }
+
+ private void probeAll(String tgArn, TargetGroup tg) {
+ Map<String, TargetState> tgStates = states.get(tgArn);
+ if (tgStates == null || !Boolean.TRUE.equals(tg.getHealthCheckEnabled())) {
+ return;
+ }
+ for (Map.Entry<String, TargetState> entry : tgStates.entrySet()) {
+ String key = entry.getKey();
+ TargetState state = entry.getValue();
+ String[] parts = key.split(":", 2);
+ if (parts.length != 2) {
+ continue;
+ }
+ String host = parts[0];
+ int port;
+ try {
+ port = Integer.parseInt(parts[1]);
+ } catch (NumberFormatException e) {
+ continue;
+ }
+ String path = tg.getHealthCheckPath() != null ? tg.getHealthCheckPath() : "/";
+ String matcher = tg.getMatcher() != null ? tg.getMatcher() : "200";
+ int timeout = tg.getHealthCheckTimeoutSeconds() != null ? tg.getHealthCheckTimeoutSeconds() : 5;
+ int healthyThreshold = tg.getHealthyThresholdCount() != null ? tg.getHealthyThresholdCount() : 5;
+ int unhealthyThreshold = tg.getUnhealthyThresholdCount() != null ? tg.getUnhealthyThresholdCount() : 2;
+
+ vertx.executeBlocking(() -> {
+ return probe(host, port, path, timeout);
+ }).onSuccess(statusCode -> {
+ boolean success = matchesStatusCode(statusCode, matcher);
+ if (success) {
+ state.consecutiveFailures = 0;
+ state.consecutiveSuccesses++;
+ if (state.consecutiveSuccesses >= healthyThreshold) {
+ state.status = "healthy";
+ }
+ } else {
+ state.consecutiveSuccesses = 0;
+ state.consecutiveFailures++;
+ if (state.consecutiveFailures >= unhealthyThreshold) {
+ state.status = "unhealthy";
+ }
+ }
+ }).onFailure(err -> {
+ state.consecutiveSuccesses = 0;
+ state.consecutiveFailures++;
+ if (state.consecutiveFailures >= unhealthyThreshold) {
+ state.status = "unhealthy";
+ }
+ LOG.debugv("Health check failed for {0}:{1} - {2}", host, port, err.getMessage());
+ });
+ }
+ }
+
+ private int probe(String host, int port, String path, int timeoutSeconds) throws IOException {
+ URL url = new URL("http", host, port, path);
+ HttpURLConnection conn = (HttpURLConnection) url.openConnection();
+ conn.setConnectTimeout(timeoutSeconds * 1000);
+ conn.setReadTimeout(timeoutSeconds * 1000);
+ conn.setRequestMethod("GET");
+ conn.setInstanceFollowRedirects(false);
+ try {
+ conn.connect();
+ return conn.getResponseCode();
+ } finally {
+ conn.disconnect();
+ }
+ }
+
+ static boolean matchesStatusCode(int code, String matcher) {
+ String codeStr = String.valueOf(code);
+ if (matcher.contains("-")) {
+ String[] range = matcher.split("-", 2);
+ try {
+ int low = Integer.parseInt(range[0].trim());
+ int high = Integer.parseInt(range[1].trim());
+ return code >= low && code <= high;
+ } catch (NumberFormatException e) {
+ return false;
+ }
+ }
+ return Arrays.stream(matcher.split(","))
+ .map(String::trim)
+ .anyMatch(codeStr::equals);
+ }
+
+ private static String stateKey(String targetId, int port) {
+ return targetId + ":" + port;
+ }
+
+ private static class TargetState {
+ volatile String status = "initial";
+ volatile int consecutiveSuccesses = 0;
+ volatile int consecutiveFailures = 0;
+ }
+}
\ No newline at end of file
diff --git a/src/main/java/io/github/hectorvent/floci/services/elbv2/ElbV2Service.java b/src/main/java/io/github/hectorvent/floci/services/elbv2/ElbV2Service.java
index f1f23f6f55..9d208f6442 100644
--- a/src/main/java/io/github/hectorvent/floci/services/elbv2/ElbV2Service.java
+++ b/src/main/java/io/github/hectorvent/floci/services/elbv2/ElbV2Service.java
@@ -4,6 +4,7 @@ import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.elbv2.model.*;
import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.inject.Inject;
import java.time.Instant;
import java.util.*;
@@ -13,6 +14,12 @@ import java.util.stream.Collectors;
@ApplicationScoped
public class ElbV2Service {
+ @Inject
+ ElbV2DataPlane dataPlane;
+
+ @Inject
+ ElbV2HealthChecker healthChecker;
+
private static final String CANONICAL_HOSTED_ZONE_ID = "Z35SXDOTRQ7X7K";
private static final String DEFAULT_ACCOUNT = "000000000000";
@@ -112,6 +119,7 @@ public class ElbV2Service {
Map<String, Listener> regionListeners = listeners.getOrDefault(region, Map.of());
Map<String, Rule> regionRules = rules.getOrDefault(region, Map.of());
for (String listenerArn : listenerArns) {
+ dataPlane.stopListener(listenerArn);
regionListeners.remove(listenerArn);
List<String> ruleArns = listenerToRules.remove(listenerArn);
if (ruleArns != null) {
@@ -198,6 +206,7 @@ public class ElbV2Service {
if (!initialTags.isEmpty()) {
tags.put(arn, new LinkedHashMap<>(initialTags));
}
+ healthChecker.startMonitoring(tg);
return tg;
}
@@ -235,6 +244,7 @@ public class ElbV2Service {
throw new AwsException("ResourceInUse",
"Target group '" + tg.getTargetGroupName() + "' is currently in use by a listener or rule.", 400);
}
+ healthChecker.stopMonitoring(arn);
targetGroups.getOrDefault(region, Map.of()).remove(arn);
tgToLbs.remove(arn);
tags.remove(arn);
@@ -314,6 +324,7 @@ public class ElbV2Service {
if (!initialTags.isEmpty()) {
tags.put(listenerArn, new LinkedHashMap<>(initialTags));
}
+ dataPlane.startListener(listener, region, getListenerRules(region, listenerArn));
return listener;
}
@@ -339,6 +350,7 @@ public class ElbV2Service {
if (listener == null) {
return;
}
+ dataPlane.stopListener(listenerArn);
lbToListeners.getOrDefault(listener.getLoadBalancerArn(), List.of()).remove(listenerArn);
Map<String, Rule> regionRules = rules.getOrDefault(region, Map.of());
@@ -378,6 +390,8 @@ public class ElbV2Service {
.filter(r -> r != null && r.isDefault())
.forEach(r -> r.setActions(new ArrayList<>(defaultActions)));
}
+ dataPlane.stopListener(listenerArn);
+ dataPlane.startListener(requireListener(region, listenerArn), region, getListenerRules(region, listenerArn));
return listener;
}
@@ -430,6 +444,7 @@ public class ElbV2Service {
if (!initialTags.isEmpty()) {
tags.put(ruleArn, new LinkedHashMap<>(initialTags));
}
+ dataPlane.recompileRules(listenerArn, getListenerRules(region, listenerArn));
return rule;
}
@@ -462,15 +477,19 @@ public class ElbV2Service {
throw new AwsException("OperationNotPermitted",
"The default rule for a listener cannot be deleted.", 400);
}
+ String listenerArn = rule.getListenerArn();
regionRules.remove(ruleArn);
- listenerToRules.getOrDefault(rule.getListenerArn(), List.of()).remove(ruleArn);
+ listenerToRules.getOrDefault(listenerArn, List.of()).remove(ruleArn);
tags.remove(ruleArn);
+ dataPlane.recompileRules(listenerArn, getListenerRules(region, listenerArn));
}
public Rule modifyRule(String region, String ruleArn, List<RuleCondition> conditions, List<Action> actions) {
Rule rule = requireRule(region, ruleArn);
+ String listenerArn = rule.getListenerArn();
if (conditions != null) rule.setConditions(new ArrayList<>(conditions));
if (actions != null) rule.setActions(new ArrayList<>(actions));
+ dataPlane.recompileRules(listenerArn, getListenerRules(region, listenerArn));
return rule;
}
@@ -509,6 +528,11 @@ public class ElbV2Service {
// commit
arnToPriority.forEach((arn, priority) -> regionRules.get(arn).setPriority(String.valueOf(priority)));
+
+ Set<String> affectedListeners = arnToPriority.keySet().stream()
+ .map(arn -> regionRules.get(arn).getListenerArn())
+ .collect(Collectors.toSet());
+ affectedListeners.forEach(la -> dataPlane.recompileRules(la, getListenerRules(region, la)));
}
// ── Targets ───────────────────────────────────────────────────────────────
@@ -521,6 +545,7 @@ public class ElbV2Service {
existing.removeIf(e -> e.getId().equals(t.getId()) && Objects.equals(e.getPort(), t.getPort()));
existing.add(t);
}
+ healthChecker.addTargets(tgArn, targets, tg);
}
public void deregisterTargets(String region, String tgArn, List<TargetDescription> targets) {
@@ -528,6 +553,7 @@ public class ElbV2Service {
for (TargetDescription t : targets) {
tg.getTargets().removeIf(e -> e.getId().equals(t.getId()) && Objects.equals(e.getPort(), t.getPort()));
}
+ healthChecker.removeTargets(tgArn, targets, tg);
}
public List<TargetHealth> describeTargetHealth(String region, String tgArn,
@@ -539,10 +565,17 @@ public class ElbV2Service {
return candidates.stream().map(t -> {
TargetHealth th = new TargetHealth();
th.setTarget(t);
- th.setHealthCheckPort(tg.getHealthCheckPort() != null ? tg.getHealthCheckPort() : "traffic-port");
- th.setState("initial");
- th.setReason("Elb.RegistrationInProgress");
- th.setDescription("Target registration is in progress");
+ int port = ElbV2HealthChecker.effectivePort(t, tg);
+ th.setHealthCheckPort(String.valueOf(port));
+ String state = healthChecker.getState(tgArn, t.getId(), port);
+ th.setState(state);
+ if ("initial".equals(state)) {
+ th.setReason("Elb.RegistrationInProgress");
+ th.setDescription("Target registration is in progress");
+ } else if ("unhealthy".equals(state)) {
+ th.setReason("Target.FailedHealthChecks");
+ th.setDescription("Health checks failed");
+ }
return th;
}).collect(Collectors.toList());
}
@@ -630,6 +663,56 @@ public class ElbV2Service {
return r;
}
+ public TargetGroup getTargetGroup(String region, String arn) {
+ return targetGroups.getOrDefault(region, Map.of()).get(arn);
+ }
+
+ public TargetGroup getTargetGroupByName(String region, String name) {
+ return targetGroups.getOrDefault(region, Map.of()).values().stream()
+ .filter(tg -> tg.getTargetGroupName().equals(name))
+ .findFirst()
+ .orElse(null);
+ }
+
+ public void shiftListenerForward(String region, String listenerArn,
+ String blueTgArn, String greenTgArn, int greenWeightPct) {
+ Rule defaultRule = listenerToRules.getOrDefault(listenerArn, List.of()).stream()
+ .map(arn -> rules.getOrDefault(region, Map.of()).get(arn))
+ .filter(r -> r != null && r.isDefault())
+ .findFirst()
+ .orElse(null);
+ if (defaultRule == null) {
+ return;
+ }
+ Action action = new Action();
+ action.setType("forward");
+ if (greenWeightPct >= 100) {
+ action.setTargetGroupArn(greenTgArn);
+ } else {
+ Action.TargetGroupTuple blueTuple = new Action.TargetGroupTuple();
+ blueTuple.setTargetGroupArn(blueTgArn);
+ blueTuple.setWeight(100 - greenWeightPct);
+ Action.TargetGroupTuple greenTuple = new Action.TargetGroupTuple();
+ greenTuple.setTargetGroupArn(greenTgArn);
+ greenTuple.setWeight(greenWeightPct);
+ action.setTargetGroups(List.of(blueTuple, greenTuple));
+ }
+ defaultRule.setActions(List.of(action));
+ dataPlane.recompileRules(listenerArn, getListenerRules(region, listenerArn));
+ }
+
+ private List<Rule> getListenerRules(String region, String listenerArn) {
+ Map<String, Rule> regionRules = rules.getOrDefault(region, Map.of());
+ return listenerToRules.getOrDefault(listenerArn, List.of()).stream()
+ .map(regionRules::get)
+ .filter(Objects::nonNull)
+ .sorted(Comparator.comparingInt(r -> {
+ if ("default".equals(r.getPriority())) return Integer.MAX_VALUE;
+ try { return Integer.parseInt(r.getPriority()); } catch (NumberFormatException e) { return Integer.MAX_VALUE; }
+ }))
+ .collect(Collectors.toList());
+ }
+
private static void validateName(String name, String resource) {
if (name == null || name.isEmpty()) {
throw new AwsException("ValidationError", "Name is required for " + resource + ".", 400);
diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaService.java b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaService.java
index 18783cbd48..4cee9d4cef 100644
--- a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaService.java
@@ -548,6 +548,12 @@ public class LambdaService {
}
codeStore.delete(functionName);
functionStore.delete(region, functionName);
+ versionCounters.remove(region + "::" + functionName);
+ if (aliasStore != null) {
+ for (LambdaAlias alias : aliasStore.list(region, functionName)) {
+ aliasStore.delete(region, functionName, alias.getName());
+ }
+ }
}
LOG.infov("Deleted Lambda function: {0}", functionName);
}
diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml
index bf478a2f8b..e01554ee04 100644
--- a/src/main/resources/application.yml
+++ b/src/main/resources/application.yml
@@ -223,6 +223,7 @@ floci:
keep-running-on-shutdown: false
elbv2:
enabled: true
+ mock: false
codebuild:
enabled: true
# docker-network: floci-network
diff --git a/src/test/java/io/github/hectorvent/floci/services/codedeploy/CodeDeployEcsIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/codedeploy/CodeDeployEcsIntegrationTest.java
new file mode 100644
index 0000000000..bdba45b7bb
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/codedeploy/CodeDeployEcsIntegrationTest.java
@@ -0,0 +1,374 @@
+package io.github.hectorvent.floci.services.codedeploy;
+
+import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
+import io.quarkus.test.junit.QuarkusTest;
+import org.junit.jupiter.api.*;
+
+import java.util.concurrent.TimeUnit;
+
+import static io.restassured.RestAssured.given;
+import static org.hamcrest.Matchers.*;
+
+@QuarkusTest
+@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
+class CodeDeployEcsIntegrationTest {
+
+ private static final String CONTENT_TYPE = "application/x-amz-json-1.1";
+ private static final String ELBV2_CONTENT_TYPE = "application/x-www-form-urlencoded";
+
+ private static String lbArn;
+ private static String blueTgArn;
+ private static String greenTgArn;
+ private static String listenerArn;
+ private static String deploymentId;
+
+ @BeforeAll
+ static void configureRestAssured() {
+ RestAssuredJsonUtils.configureAwsContentTypes();
+ }
+
+ // ── ELB v2 setup ─────────────────────────────────────────────────────────
+
+ @Test
+ @Order(1)
+ void createLoadBalancer() {
+ lbArn = given()
+ .contentType(ELBV2_CONTENT_TYPE)
+ .formParam("Action", "CreateLoadBalancer")
+ .formParam("Version", "2015-12-01")
+ .formParam("Name", "ecs-alb")
+ .formParam("Type", "application")
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .extract().path("CreateLoadBalancerResponse.CreateLoadBalancerResult.LoadBalancers.member.LoadBalancerArn");
+ }
+
+ @Test
+ @Order(2)
+ void createBlueTargetGroup() {
+ blueTgArn = given()
+ .contentType(ELBV2_CONTENT_TYPE)
+ .formParam("Action", "CreateTargetGroup")
+ .formParam("Version", "2015-12-01")
+ .formParam("Name", "ecs-blue-tg")
+ .formParam("Protocol", "HTTP")
+ .formParam("Port", "80")
+ .formParam("VpcId", "vpc-00000001")
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .extract().path("CreateTargetGroupResponse.CreateTargetGroupResult.TargetGroups.member.TargetGroupArn");
+ }
+
+ @Test
+ @Order(3)
+ void createGreenTargetGroup() {
+ greenTgArn = given()
+ .contentType(ELBV2_CONTENT_TYPE)
+ .formParam("Action", "CreateTargetGroup")
+ .formParam("Version", "2015-12-01")
+ .formParam("Name", "ecs-green-tg")
+ .formParam("Protocol", "HTTP")
+ .formParam("Port", "80")
+ .formParam("VpcId", "vpc-00000001")
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .extract().path("CreateTargetGroupResponse.CreateTargetGroupResult.TargetGroups.member.TargetGroupArn");
+ }
+
+ @Test
+ @Order(4)
+ void createListenerPointingToBlue() {
+ Assumptions.assumeTrue(lbArn != null, "lbArn must be set");
+ Assumptions.assumeTrue(blueTgArn != null, "blueTgArn must be set");
+ listenerArn = given()
+ .contentType(ELBV2_CONTENT_TYPE)
+ .formParam("Action", "CreateListener")
+ .formParam("Version", "2015-12-01")
+ .formParam("LoadBalancerArn", lbArn)
+ .formParam("Protocol", "HTTP")
+ .formParam("Port", "18080")
+ .formParam("DefaultActions.member.1.Type", "forward")
+ .formParam("DefaultActions.member.1.TargetGroupArn", blueTgArn)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .extract().path("CreateListenerResponse.CreateListenerResult.Listeners.member.ListenerArn");
+ }
+
+ // ── ECS setup ─────────────────────────────────────────────────────────────
+
+ @Test
+ @Order(5)
+ void createEcsCluster() {
+ given()
+ .header("X-Amz-Target", "AmazonEC2ContainerServiceV20141113.CreateCluster")
+ .contentType(CONTENT_TYPE)
+ .body("""
+ {"clusterName": "ecs-deploy-cluster"}
+ """)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("cluster.clusterName", equalTo("ecs-deploy-cluster"));
+ }
+
+ @Test
+ @Order(6)
+ void registerTaskDefinition() {
+ given()
+ .header("X-Amz-Target", "AmazonEC2ContainerServiceV20141113.RegisterTaskDefinition")
+ .contentType(CONTENT_TYPE)
+ .body("""
+ {
+ "family": "ecs-deploy-task",
+ "containerDefinitions": [{
+ "name": "app",
+ "image": "nginx:latest",
+ "portMappings": [{"containerPort": 80}]
+ }]
+ }
+ """)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("taskDefinition.family", equalTo("ecs-deploy-task"));
+ }
+
+ @Test
+ @Order(7)
+ void createEcsService() {
+ given()
+ .header("X-Amz-Target", "AmazonEC2ContainerServiceV20141113.CreateService")
+ .contentType(CONTENT_TYPE)
+ .body("""
+ {
+ "cluster": "ecs-deploy-cluster",
+ "serviceName": "ecs-deploy-service",
+ "taskDefinition": "ecs-deploy-task:1",
+ "desiredCount": 1,
+ "deploymentController": {"type": "EXTERNAL"}
+ }
+ """)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("service.serviceName", equalTo("ecs-deploy-service"));
+ }
+
+ // ── CodeDeploy ECS deployment ─────────────────────────────────────────────
+
+ @Test
+ @Order(8)
+ void createEcsApplication() {
+ given()
+ .header("X-Amz-Target", "CodeDeploy_20141006.CreateApplication")
+ .contentType(CONTENT_TYPE)
+ .body("""
+ {
+ "applicationName": "ecs-deploy-app",
+ "computePlatform": "ECS"
+ }
+ """)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("applicationId", notNullValue());
+ }
+
+ @Test
+ @Order(9)
+ void createEcsDeploymentGroup() {
+ Assumptions.assumeTrue(blueTgArn != null, "blueTgArn must be set");
+ Assumptions.assumeTrue(greenTgArn != null, "greenTgArn must be set");
+ Assumptions.assumeTrue(listenerArn != null, "listenerArn must be set");
+
+ given()
+ .header("X-Amz-Target", "CodeDeploy_20141006.CreateDeploymentGroup")
+ .contentType(CONTENT_TYPE)
+ .body(String.format("""
+ {
+ "applicationName": "ecs-deploy-app",
+ "deploymentGroupName": "ecs-deploy-dg",
+ "deploymentConfigName": "CodeDeployDefault.ECSAllAtOnce",
+ "serviceRoleArn": "arn:aws:iam::000000000000:role/codedeploy-role",
+ "computePlatform": "ECS",
+ "deploymentStyle": {
+ "deploymentType": "BLUE_GREEN",
+ "deploymentOption": "WITH_TRAFFIC_CONTROL"
+ },
+ "ecsServices": [{
+ "clusterName": "ecs-deploy-cluster",
+ "serviceName": "ecs-deploy-service"
+ }],
+ "loadBalancerInfo": {
+ "targetGroupPairInfoList": [{
+ "targetGroups": [
+ {"name": "ecs-blue-tg"},
+ {"name": "ecs-green-tg"}
+ ],
+ "prodTrafficRoute": {
+ "listenerArns": ["%s"]
+ }
+ }]
+ }
+ }
+ """, listenerArn))
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("deploymentGroupId", notNullValue());
+ }
+
+ @Test
+ @Order(10)
+ void createEcsDeployment() {
+ Assumptions.assumeTrue(listenerArn != null, "listenerArn must be set");
+ String appSpec = """
+ {
+ "version": 0.0,
+ "Resources": [{
+ "TargetService": {
+ "Type": "AWS::ECS::Service",
+ "Properties": {
+ "TaskDefinition": "ecs-deploy-task:1",
+ "LoadBalancerInfo": {
+ "ContainerName": "app",
+ "ContainerPort": 80
+ }
+ }
+ }
+ }]
+ }
+ """;
+
+ // Escape the appSpec for embedding in JSON
+ String escapedAppSpec = appSpec.replace("\"", "\\\"").replace("\n", "\\n");
+
+ deploymentId = given()
+ .header("X-Amz-Target", "CodeDeploy_20141006.CreateDeployment")
+ .contentType(CONTENT_TYPE)
+ .body(String.format("""
+ {
+ "applicationName": "ecs-deploy-app",
+ "deploymentGroupName": "ecs-deploy-dg",
+ "revision": {
+ "revisionType": "AppSpecContent",
+ "appSpecContent": {
+ "content": "%s"
+ }
+ }
+ }
+ """, escapedAppSpec))
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("deploymentId", notNullValue())
+ .extract().path("deploymentId");
+ }
+
+ @Test
+ @Order(11)
+ void deploymentCompletesSuccessfully() throws InterruptedException {
+ Assumptions.assumeTrue(deploymentId != null, "deploymentId must be set");
+
+ String status = null;
+ for (int i = 0; i < 20; i++) {
+ status = given()
+ .header("X-Amz-Target", "CodeDeploy_20141006.GetDeployment")
+ .contentType(CONTENT_TYPE)
+ .body(String.format("{\"deploymentId\": \"%s\"}", deploymentId))
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .extract().path("deploymentInfo.status");
+
+ if ("Succeeded".equals(status) || "Failed".equals(status) || "Stopped".equals(status)) {
+ break;
+ }
+ TimeUnit.MILLISECONDS.sleep(500);
+ }
+
+ Assertions.assertEquals("Succeeded", status, "ECS deployment should succeed");
+ }
+
+ @Test
+ @Order(12)
+ void listDeploymentTargetsReturnsEcsTarget() {
+ Assumptions.assumeTrue(deploymentId != null, "deploymentId must be set");
+
+ given()
+ .header("X-Amz-Target", "CodeDeploy_20141006.ListDeploymentTargets")
+ .contentType(CONTENT_TYPE)
+ .body(String.format("{\"deploymentId\": \"%s\"}", deploymentId))
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("targetIds", hasItem(containsString("ecs-deploy-cluster")));
+ }
+
+ @Test
+ @Order(13)
+ void batchGetDeploymentTargetsReturnsEcsInfo() {
+ Assumptions.assumeTrue(deploymentId != null, "deploymentId must be set");
+
+ String targetId = given()
+ .header("X-Amz-Target", "CodeDeploy_20141006.ListDeploymentTargets")
+ .contentType(CONTENT_TYPE)
+ .body(String.format("{\"deploymentId\": \"%s\"}", deploymentId))
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .extract().path("targetIds[0]");
+
+ given()
+ .header("X-Amz-Target", "CodeDeploy_20141006.BatchGetDeploymentTargets")
+ .contentType(CONTENT_TYPE)
+ .body(String.format("""
+ {
+ "deploymentId": "%s",
+ "targetIds": ["%s"]
+ }
+ """, deploymentId, targetId))
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("deploymentTargets[0].deploymentTargetType", equalTo("ECSTarget"))
+ .body("deploymentTargets[0].ecsTarget.status", equalTo("Succeeded"));
+ }
+
+ @Test
+ @Order(14)
+ void listenerNowPointsToGreen() {
+ Assumptions.assumeTrue(listenerArn != null, "listenerArn must be set");
+ Assumptions.assumeTrue(greenTgArn != null, "greenTgArn must be set");
+
+ given()
+ .contentType(ELBV2_CONTENT_TYPE)
+ .formParam("Action", "DescribeRules")
+ .formParam("Version", "2015-12-01")
+ .formParam("ListenerArn", listenerArn)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("DescribeRulesResponse.DescribeRulesResult.Rules.member.Actions.member.TargetGroupArn",
+ equalTo(greenTgArn));
+ }
+}
diff --git a/src/test/resources/application.yml b/src/test/resources/application.yml
index 1fd7e4d3c0..4f58eb2f6e 100644
--- a/src/test/resources/application.yml
+++ b/src/test/resources/application.yml
@@ -153,6 +153,7 @@ floci:
enabled: true
elbv2:
enabled: true
+ mock: true
codebuild:
enabled: true
# docker-network: floci-network