diff --git a/docs/services/ecs.md b/docs/services/ecs.md index 5164a27c5c..ef272706f4 100644 --- a/docs/services/ecs.md +++ b/docs/services/ecs.md @@ -89,10 +89,38 @@ Known differences from AWS: `desiredCount` from that count; it is rejected for the Fargate launch type and for the `CODE_DEPLOY` / `EXTERNAL` controllers, as on AWS. Placement constraints are not evaluated. - `pendingCount` is always `0`, matching the top-level service field. -- `forceNewDeployment` does not mint a new deployment `id`. +- `forceNewDeployment` (with an unchanged task definition) mints a new deployment `id` + and rolls the running tasks: a replacement on the new deployment starts first, then + the task from the previous deployment is drained one reconciler tick later. The + `deployments` list still reports a single `PRIMARY` throughout. - `updatedAt` equals `createdAt`. AWS advances it as a rollout progresses; Floci has no intermediate rollout state to report. +#### ECS EventBridge events + +Floci publishes AWS-shaped lifecycle events to the **default** EventBridge bus +(`source: aws.ecs`). Rules matching `aws.ecs` fire from ECS activity, in both docker +and mock mode. + +| `detail-type` | When | Key `detail` fields | +|---|---|---| +| `ECS Task State Change` | a task starts or stops | `lastStatus`, `desiredStatus`, `taskDefinitionArn`, `group`, `startedBy`, `stoppedReason`, `containers[].exitCode` | +| `ECS Deployment State Change` | a service deployment starts, is in progress, or reaches steady state | `eventType` (always `INFO`), `eventName`, `deploymentId` | + +`eventName` is one of `SERVICE_DEPLOYMENT_STARTED`, `SERVICE_DEPLOYMENT_IN_PROGRESS`, +`SERVICE_DEPLOYMENT_COMPLETED`. + +Known differences from AWS: + +- The task phase ladder is **synthesized**. Floci's task model only occupies + `PENDING`, `RUNNING` and `STOPPED`, but a start emits + `PROVISIONING -> PENDING -> ACTIVATING -> RUNNING` and a stop emits + `DEACTIVATING -> STOPPING -> DEPROVISIONING -> STOPPED`, one `ECS Task State Change` + per phase, so rules that filter on `detail.lastStatus` behave as on AWS. +- `SERVICE_DEPLOYMENT_FAILED` and the deployment circuit breaker are not emitted. +- `SubmitTaskStateChange` / `SubmitContainerStateChange` remain ACK-only; Floci drives + the task lifecycle itself rather than via agent submissions. + #### Unknown services A service reference that does not resolve is returned in `failures` with diff --git a/src/main/java/io/github/hectorvent/floci/services/ecs/EcsEventPublisher.java b/src/main/java/io/github/hectorvent/floci/services/ecs/EcsEventPublisher.java new file mode 100644 index 0000000000..2d76b89431 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/ecs/EcsEventPublisher.java @@ -0,0 +1,142 @@ +package io.github.hectorvent.floci.services.ecs; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import io.github.hectorvent.floci.core.common.RegionResolver; +import io.github.hectorvent.floci.services.ecs.model.Container; +import io.github.hectorvent.floci.services.ecs.model.EcsServiceModel; +import io.github.hectorvent.floci.services.ecs.model.EcsTask; +import io.github.hectorvent.floci.services.ecs.model.TaskStatus; +import io.github.hectorvent.floci.services.eventbridge.EventBridgeService; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import org.jboss.logging.Logger; + +import java.time.Instant; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * Publishes AWS-shaped {@code aws.ecs} lifecycle events to the default EventBridge bus. + * + *

Floci's task model only ever occupies PENDING, RUNNING and STOPPED. AWS reports a + * fuller phase ladder, and EventBridge rules filter on {@code detail.lastStatus}, so the + * intermediate phases are synthesized here: one event per phase, each carrying the + * task's real fields with only {@code lastStatus} varied. The task object is restored to its + * caller-visible status before this method returns. + */ +@ApplicationScoped +public class EcsEventPublisher { + + private static final Logger LOG = Logger.getLogger(EcsEventPublisher.class); + private static final String SOURCE = "aws.ecs"; + private static final String TASK_DETAIL_TYPE = "ECS Task State Change"; + private static final String DEPLOYMENT_DETAIL_TYPE = "ECS Deployment State Change"; + + private static final List START_LADDER = + List.of(TaskStatus.PROVISIONING, TaskStatus.PENDING, TaskStatus.ACTIVATING, TaskStatus.RUNNING); + private static final List STOP_LADDER = + List.of(TaskStatus.DEACTIVATING, TaskStatus.STOPPING, TaskStatus.DEPROVISIONING, TaskStatus.STOPPED); + + private final EventBridgeService eventBridgeService; + private final RegionResolver regionResolver; + private final ObjectMapper objectMapper; + + @Inject + public EcsEventPublisher(EventBridgeService eventBridgeService, + RegionResolver regionResolver, + ObjectMapper objectMapper) { + this.eventBridgeService = eventBridgeService; + this.regionResolver = regionResolver; + this.objectMapper = objectMapper; + } + + /** Emits the synthesized phase sequence for a start (to RUNNING) or a stop (to STOPPED). */ + public void emitTaskLadder(EcsTask task, TaskStatus from, TaskStatus to, String region) { + List ladder = to == TaskStatus.STOPPED ? STOP_LADDER : START_LADDER; + // Synthesize the ladder on a snapshot, not the shared task instance: that instance lives + // in EcsService's live task map and stays visible to a concurrent DescribeTasks/ListTasks + // call for the whole synthesis, which would otherwise observe a lastStatus this task never + // actually occupies. + EcsTask snapshot = new EcsTask(task); + for (TaskStatus phase : ladder) { + snapshot.setLastStatus(phase.name()); + emitTaskStateChange(snapshot, region); + } + } + + /** Emits one ECS Task State Change reflecting the task's current fields. */ + public void emitTaskStateChange(EcsTask task, String region) { + try { + ObjectNode detail = objectMapper.createObjectNode(); + detail.put("clusterArn", task.getClusterArn()); + detail.put("taskArn", task.getTaskArn()); + detail.put("lastStatus", task.getLastStatus()); + detail.put("desiredStatus", task.getDesiredStatus()); + detail.put("taskDefinitionArn", task.getTaskDefinitionArn()); + detail.put("group", task.getGroup()); + detail.put("startedBy", task.getStartedBy()); + detail.put("launchType", task.getLaunchType() != null ? task.getLaunchType().name() : null); + detail.put("createdAt", asIso(task.getCreatedAt())); + detail.put("startedAt", asIso(task.getStartedAt())); + detail.put("stoppedAt", asIso(task.getStoppedAt())); + detail.put("stoppedReason", task.getStoppedReason()); + detail.put("updatedAt", Instant.now().toString()); + ArrayNode containers = detail.putArray("containers"); + if (task.getContainers() != null) { + for (Container c : task.getContainers()) { + ObjectNode cn = containers.addObject(); + cn.put("name", c.getName()); + cn.put("lastStatus", c.getLastStatus()); + cn.put("image", c.getImage()); + if (c.getExitCode() != null) { + cn.put("exitCode", c.getExitCode()); + } + } + } + putEvent(TASK_DETAIL_TYPE, task.getTaskArn(), detail, region); + } catch (Exception e) { + LOG.warnv("Failed to emit ECS Task State Change for {0}: {1}", task.getTaskArn(), e.getMessage()); + } + } + + /** Emits one ECS Deployment State Change (eventType INFO). */ + public void emitDeploymentStateChange(EcsServiceModel svc, String eventName, String reason, String region) { + try { + ObjectNode detail = objectMapper.createObjectNode(); + detail.put("eventType", "INFO"); + detail.put("eventName", eventName); + detail.put("deploymentId", svc.getDeploymentId()); + detail.put("updatedAt", Instant.now().toString()); + detail.put("reason", reason); + putEvent(DEPLOYMENT_DETAIL_TYPE, svc.getServiceArn(), detail, region); + } catch (Exception e) { + LOG.warnv("Failed to emit ECS Deployment State Change for {0}: {1}", + svc.getServiceArn(), e.getMessage()); + } + } + + private void putEvent(String detailType, String resourceArn, ObjectNode detail, String region) + throws Exception { + ArrayNode resources = objectMapper.createArrayNode(); + if (resourceArn != null) { + resources.add(resourceArn); + } + Map entry = new HashMap<>(); + entry.put("Source", SOURCE); + entry.put("DetailType", detailType); + entry.put("Detail", objectMapper.writeValueAsString(detail)); + entry.put("Resources", resources); + eventBridgeService.putEvents(List.of(entry), effectiveRegion(region)); + } + + private String effectiveRegion(String region) { + return region != null && !region.isBlank() ? region : regionResolver.getDefaultRegion(); + } + + private static String asIso(Instant instant) { + return instant != null ? instant.toString() : null; + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/ecs/EcsJsonHandler.java b/src/main/java/io/github/hectorvent/floci/services/ecs/EcsJsonHandler.java index fab1bde7cb..3e2d580b80 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ecs/EcsJsonHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/ecs/EcsJsonHandler.java @@ -488,9 +488,10 @@ public class EcsJsonHandler { Integer desiredCount = req.has("desiredCount") ? req.path("desiredCount").asInt() : null; NetworkConfiguration networkConfiguration = parseNetworkConfiguration(req.path("networkConfiguration")); String availabilityZoneRebalancing = parseChoice(req, "availabilityZoneRebalancing", AZ_REBALANCING); + boolean forceNewDeployment = req.path("forceNewDeployment").asBoolean(false); EcsServiceModel svc = service.updateService(cluster, serviceName, taskDefinition, desiredCount, - networkConfiguration, availabilityZoneRebalancing, region); + networkConfiguration, availabilityZoneRebalancing, forceNewDeployment, region); ObjectNode resp = objectMapper.createObjectNode(); resp.set("service", serviceNode(svc)); diff --git a/src/main/java/io/github/hectorvent/floci/services/ecs/EcsService.java b/src/main/java/io/github/hectorvent/floci/services/ecs/EcsService.java index 634829caa4..9750437b8f 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 @@ -69,6 +69,7 @@ public class EcsService implements ContainerTeardown, ResourceProvider { private final EcsContainerManager containerManager; private final EcsLoadBalancerRegistrar lbRegistrar; private final StorageFactory storageFactory; + private final EcsEventPublisher eventPublisher; private final boolean dockerMode; private final String baseUrl; private final ScheduledExecutorService reconciler = Executors.newSingleThreadScheduledExecutor( @@ -108,17 +109,20 @@ public class EcsService implements ContainerTeardown, ResourceProvider { private Map> attributes = new ConcurrentHashMap<>(); // name → value (account-level settings) private Map accountSettings = new ConcurrentHashMap<>(); + // deploymentIds for which SERVICE_DEPLOYMENT_IN_PROGRESS has already been emitted this process. + private final Set inProgressEmitted = java.util.concurrent.ConcurrentHashMap.newKeySet(); @Inject public EcsService(RegionResolver regionResolver, EcsContainerManager containerManager, EmulatorConfig config, EcsLoadBalancerRegistrar lbRegistrar, - StorageFactory storageFactory) { + StorageFactory storageFactory, EcsEventPublisher eventPublisher) { this.regionResolver = regionResolver; this.containerManager = containerManager; this.dockerMode = !config.services().ecs().mock(); this.baseUrl = config.effectiveBaseUrl(); this.lbRegistrar = lbRegistrar; this.storageFactory = storageFactory; + this.eventPublisher = eventPublisher; } @PostConstruct @@ -564,6 +568,9 @@ public class EcsService implements ContainerTeardown, ResourceProvider { cluster.setRunningTasksCount(cluster.getRunningTasksCount() + 1); LOG.infov("Started ECS task (docker): {0}", taskArn); registerTaskWithLoadBalancers(task, cluster, region); + if (eventPublisher != null) { + eventPublisher.emitTaskLadder(task, TaskStatus.PENDING, TaskStatus.RUNNING, region); + } } catch (Exception e) { LOG.errorv("Failed to start ECS task {0}: {1}", taskArn, e.getMessage()); task.setLastStatus(TaskStatus.STOPPED.name()); @@ -577,12 +584,18 @@ public class EcsService implements ContainerTeardown, ResourceProvider { ? e.getMessage() : "Failed to start: " + e.getMessage()); task.setStoppedAt(Instant.now()); + if (eventPublisher != null) { + eventPublisher.emitTaskLadder(task, TaskStatus.PENDING, TaskStatus.STOPPED, region); + } } } else { task.setLastStatus(TaskStatus.RUNNING.name()); task.setStartedAt(Instant.now()); cluster.setRunningTasksCount(cluster.getRunningTasksCount() + 1); LOG.infov("Started ECS task (mock): {0}", taskArn); + if (eventPublisher != null) { + eventPublisher.emitTaskLadder(task, TaskStatus.PENDING, TaskStatus.RUNNING, region); + } } launched.add(task); @@ -599,9 +612,11 @@ public class EcsService implements ContainerTeardown, ResourceProvider { private EcsTask launchServiceTask(EcsCluster cluster, EcsServiceModel svc, LaunchType launchType, String containerInstanceArn, String region) { TaskDefinition taskDef = resolveTaskDefinitionOrThrow(svc.getTaskDefinition(), region); - return launchTasks(cluster, taskDef, 1, launchType, svc.getServiceName(), "ecs-svc", + EcsTask task = launchTasks(cluster, taskDef, 1, launchType, svc.getServiceName(), "ecs-svc", containerInstanceArn, null, svc.getNetworkConfiguration(), svc.getServiceArn(), region).getFirst(); + task.setDeploymentId(deploymentId(svc)); + return task; } public EcsTask stopTask(String clusterRef, String taskRef, String reason, String region) { @@ -645,6 +660,9 @@ public class EcsService implements ContainerTeardown, ResourceProvider { } LOG.infov("Stopped ECS task: {0}", task.getTaskArn()); + if (eventPublisher != null) { + eventPublisher.emitTaskLadder(task, TaskStatus.RUNNING, TaskStatus.STOPPED, region); + } return task; } @@ -832,6 +850,7 @@ public class EcsService implements ContainerTeardown, ResourceProvider { svc.setStatus("ACTIVE"); svc.setCreatedAt(Instant.now()); svc.setLastDeploymentAt(svc.getCreatedAt()); + svc.setDeploymentId(newDeploymentId()); if (tags != null && !tags.isEmpty()) { svc.setTags(new LinkedHashMap<>(tags)); } @@ -840,6 +859,10 @@ public class EcsService implements ContainerTeardown, ResourceProvider { cluster.setActiveServicesCount(cluster.getActiveServicesCount() + 1); persistCluster(region, cluster); recordServiceDeployment(svc, taskDefinition, region); + if (eventPublisher != null) { + eventPublisher.emitDeploymentStateChange(svc, "SERVICE_DEPLOYMENT_STARTED", + "ECS deployment " + svc.getDeploymentId() + " started.", region); + } LOG.infov("Created ECS service: {0} in cluster {1}", serviceName, cluster.getClusterName()); return svc; } @@ -854,6 +877,14 @@ public class EcsService implements ContainerTeardown, ResourceProvider { public EcsServiceModel updateService(String clusterRef, String serviceName, String taskDefinition, Integer desiredCount, NetworkConfiguration networkConfiguration, String availabilityZoneRebalancing, String region) { + return updateService(clusterRef, serviceName, taskDefinition, desiredCount, networkConfiguration, + availabilityZoneRebalancing, false, region); + } + + public EcsServiceModel updateService(String clusterRef, String serviceName, String taskDefinition, + Integer desiredCount, NetworkConfiguration networkConfiguration, + String availabilityZoneRebalancing, boolean forceNewDeployment, + String region) { EcsCluster cluster = resolveClusterOrDefault(clusterRef, region); serviceName = extractServiceName(serviceName); @@ -879,11 +910,20 @@ public class EcsService implements ContainerTeardown, ResourceProvider { if (availabilityZoneRebalancing != null) { svc.setAvailabilityZoneRebalancing(availabilityZoneRebalancing); } + boolean taskDefChanged = false; if (taskDefinition != null) { - taskDefinition = resolveTaskDefinitionOrThrow(taskDefinition, region).getTaskDefinitionArn(); - svc.setTaskDefinition(taskDefinition); + String resolvedArn = resolveTaskDefinitionOrThrow(taskDefinition, region).getTaskDefinitionArn(); + taskDefChanged = !resolvedArn.equals(svc.getTaskDefinition()); + svc.setTaskDefinition(resolvedArn); + } + if (taskDefChanged || forceNewDeployment) { + svc.setDeploymentId(newDeploymentId()); svc.setLastDeploymentAt(Instant.now()); - recordServiceDeployment(svc, taskDefinition, region); + recordServiceDeployment(svc, svc.getTaskDefinition(), region); + if (eventPublisher != null) { + eventPublisher.emitDeploymentStateChange(svc, "SERVICE_DEPLOYMENT_STARTED", + "ECS deployment " + svc.getDeploymentId() + " started.", region); + } } services.put(key, svc); return svc; @@ -1462,6 +1502,10 @@ public class EcsService implements ContainerTeardown, ResourceProvider { return List.of(d); } + private static String newDeploymentId() { + return "ecs-svc/" + java.util.UUID.randomUUID().toString().replace("-", ""); + } + /** * A stable {@code ecs-svc/} identifier derived from the service ARN and its task * definition. Deployments are derived per request, so a random id would differ on every @@ -1470,6 +1514,11 @@ public class EcsService implements ContainerTeardown, ResourceProvider { * while still rolling over when the task definition changes. */ private String deploymentId(EcsServiceModel svc) { + if (svc.getDeploymentId() != null) { + return svc.getDeploymentId(); + } + // Legacy fallback: services persisted before deploymentId was stored derive a stable + // id from the service ARN and task definition, so it still rolls over on a task-def change. String seed = svc.getServiceArn() + ":" + svc.getTaskDefinition(); long hash = 0xcbf29ce484222325L; for (int i = 0; i < seed.length(); i++) { @@ -1602,6 +1651,20 @@ public class EcsService implements ContainerTeardown, ResourceProvider { } LOG.infov("ECS task {0} reconciled to STOPPED (all containers exited)", taskArn); + if (eventPublisher != null) { + String region = null; + if (task.getTaskArn() != null) { + try { + region = AwsArnUtils.parse(task.getTaskArn()).region(); + } catch (Exception e) { + LOG.warnv(e, "Could not parse region from task ARN {0}, falling back to default region", task.getTaskArn()); + } + } + if (region == null || region.isBlank()) { + region = regionResolver != null ? regionResolver.getDefaultRegion() : "us-east-1"; + } + eventPublisher.emitTaskLadder(task, TaskStatus.RUNNING, TaskStatus.STOPPED, region); + } } private void reconcileStoppedTask(String taskArn) { @@ -1751,6 +1814,20 @@ public class EcsService implements ContainerTeardown, ResourceProvider { * than by a name suffix, which would otherwise conflate same-named clusters across regions * or accounts. */ + /** + * A task belongs to a superseded deployment. New tasks carry the service's deploymentId and + * are compared on that; tasks launched before the id was stamped (legacy state) fall back to + * the task-definition-ARN comparison, preserving the pre-existing rollout on a task-def change. + */ + private static boolean isStaleForDeployment(EcsTask t, String currentDeploymentId, + String currentTaskDefinitionArn) { + if (t.getDeploymentId() != null) { + return !currentDeploymentId.equals(t.getDeploymentId()); + } + return currentTaskDefinitionArn != null + && !currentTaskDefinitionArn.equals(t.getTaskDefinitionArn()); + } + private static boolean ownedBy(EcsTask task, EcsServiceModel svc, EcsCluster cluster) { return svc.getServiceArn() != null && svc.getServiceArn().equals(task.getOwningServiceArn()) @@ -1776,19 +1853,31 @@ public class EcsService implements ContainerTeardown, ResourceProvider { .filter(t -> TaskStatus.RUNNING.name().equals(t.getLastStatus())) .toList(); long running = runningTasks.size(); - // Tasks still on a previous task definition. AWS's ECS deployment controller rolls - // them: replacements on the service's current revision come up first, then the - // stale ones are drained, so UpdateService with a new taskDefinition actually - // changes what runs. Counting only current-revision tasks as "running" below is - // what makes the reconciler start the replacements. + String currentDeploymentId = deploymentId(svc); String currentTaskDefinitionArn = pinnedTaskDefinitionArn(svc, key, region); List staleTasks = runningTasks.stream() - .filter(t -> !currentTaskDefinitionArn.equals(t.getTaskDefinitionArn())) + .filter(t -> isStaleForDeployment(t, currentDeploymentId, currentTaskDefinitionArn)) .toList(); long current = running - staleTasks.size(); svc.setRunningCount((int) running); + if (eventPublisher != null) { + String deploymentId = currentDeploymentId; + boolean converged = current >= svc.getDesiredCount(); + if (converged) { + if (!deploymentId.equals(svc.getLastCompletedDeploymentId())) { + svc.setLastCompletedDeploymentId(deploymentId); + services.put(key, svc); + eventPublisher.emitDeploymentStateChange(svc, "SERVICE_DEPLOYMENT_COMPLETED", + "ECS deployment " + deploymentId + " completed.", region); + } + } else if (inProgressEmitted.add(deploymentId)) { + eventPublisher.emitDeploymentStateChange(svc, "SERVICE_DEPLOYMENT_IN_PROGRESS", + "ECS deployment " + deploymentId + " in progress.", region); + } + } + if (current < svc.getDesiredCount()) { int toStart = svc.getDesiredCount() - (int) current; for (int i = 0; i < toStart; i++) { diff --git a/src/main/java/io/github/hectorvent/floci/services/ecs/model/EcsServiceModel.java b/src/main/java/io/github/hectorvent/floci/services/ecs/model/EcsServiceModel.java index f50130b372..16a7e59b93 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ecs/model/EcsServiceModel.java +++ b/src/main/java/io/github/hectorvent/floci/services/ecs/model/EcsServiceModel.java @@ -23,6 +23,10 @@ public class EcsServiceModel { private Instant createdAt; /** When the current deployment began: service creation, or the last task-definition change. */ private Instant lastDeploymentAt; + /** Current deployment identifier ("ecs-svc/"). Rolls on a task-definition change or forceNewDeployment. */ + private String deploymentId; + /** The deploymentId last observed to reach steady state; guards against re-emitting COMPLETED. */ + private String lastCompletedDeploymentId; private String namespace; private String deploymentController; private String schedulingStrategy; @@ -63,6 +67,14 @@ public class EcsServiceModel { public Instant getLastDeploymentAt() { return lastDeploymentAt; } public void setLastDeploymentAt(Instant lastDeploymentAt) { this.lastDeploymentAt = lastDeploymentAt; } + public String getDeploymentId() { return deploymentId; } + public void setDeploymentId(String deploymentId) { this.deploymentId = deploymentId; } + + public String getLastCompletedDeploymentId() { return lastCompletedDeploymentId; } + public void setLastCompletedDeploymentId(String lastCompletedDeploymentId) { + this.lastCompletedDeploymentId = lastCompletedDeploymentId; + } + public String getNamespace() { return namespace; } public void setNamespace(String namespace) { this.namespace = namespace; } diff --git a/src/main/java/io/github/hectorvent/floci/services/ecs/model/EcsTask.java b/src/main/java/io/github/hectorvent/floci/services/ecs/model/EcsTask.java index 672f1c9030..b38c9213dc 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ecs/model/EcsTask.java +++ b/src/main/java/io/github/hectorvent/floci/services/ecs/model/EcsTask.java @@ -30,6 +30,8 @@ public class EcsTask { private Instant startedAt; private Instant stoppedAt; private String startedBy; + /** The owning service's deploymentId when this task was launched; null for RunTask/StartTask and legacy tasks. */ + private String deploymentId; private String stoppedReason; private List containers; private String containerInstanceArn; @@ -38,6 +40,40 @@ public class EcsTask { private Map tags = new HashMap<>(); private NetworkConfiguration networkConfiguration; + public EcsTask() { + } + + /** + * Shallow copy, used to synthesize a phase ladder of lifecycle events without mutating the + * shared task instance held in the live task map — that instance stays visible to concurrent + * DescribeTasks/ListTasks calls for the whole synthesis, so events must be built from a + * snapshot instead of toggling {@link #lastStatus} back and forth on the original. + */ + public EcsTask(EcsTask other) { + this.taskArn = other.taskArn; + this.clusterArn = other.clusterArn; + this.taskDefinitionArn = other.taskDefinitionArn; + this.group = other.group; + this.owningServiceArn = other.owningServiceArn; + this.launchType = other.launchType; + this.lastStatus = other.lastStatus; + this.desiredStatus = other.desiredStatus; + this.cpu = other.cpu; + this.memory = other.memory; + this.createdAt = other.createdAt; + this.startedAt = other.startedAt; + this.stoppedAt = other.stoppedAt; + this.startedBy = other.startedBy; + this.deploymentId = other.deploymentId; + this.stoppedReason = other.stoppedReason; + this.containers = other.containers; + this.containerInstanceArn = other.containerInstanceArn; + this.protectionEnabled = other.protectionEnabled; + this.protectedUntil = other.protectedUntil; + this.tags = other.tags; + this.networkConfiguration = other.networkConfiguration; + } + public String getTaskArn() { return taskArn; } public void setTaskArn(String taskArn) { this.taskArn = taskArn; } @@ -80,6 +116,9 @@ public class EcsTask { public String getStartedBy() { return startedBy; } public void setStartedBy(String startedBy) { this.startedBy = startedBy; } + public String getDeploymentId() { return deploymentId; } + public void setDeploymentId(String deploymentId) { this.deploymentId = deploymentId; } + /** The awsvpc network configuration the task was launched with, or null. Carried through from * the RunTask request (including the ecs:runTask Step Functions integration) so it survives the * launch; awsvpc ENI attachments are not emulated in the local mock profile. */ diff --git a/src/test/java/io/github/hectorvent/floci/services/ecs/EcsEventBridgeIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ecs/EcsEventBridgeIntegrationTest.java new file mode 100644 index 0000000000..90540d1e8a --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/ecs/EcsEventBridgeIntegrationTest.java @@ -0,0 +1,211 @@ +package io.github.hectorvent.floci.services.ecs; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.github.hectorvent.floci.config.EmulatorConfig; +import io.github.hectorvent.floci.core.common.RegionResolver; +import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend; +import io.github.hectorvent.floci.core.storage.StorageBackend; +import io.github.hectorvent.floci.core.storage.StorageFactory; +import io.github.hectorvent.floci.services.ecs.container.EcsContainerManager; +import io.github.hectorvent.floci.services.ecs.model.ContainerDefinition; +import io.github.hectorvent.floci.services.ecs.model.EcsTask; +import io.github.hectorvent.floci.services.ecs.model.LaunchType; +import io.github.hectorvent.floci.services.ecs.model.TaskDefinition; +import io.github.hectorvent.floci.services.eventbridge.EventBridgeInvoker; +import io.github.hectorvent.floci.services.eventbridge.EventBridgeService; +import io.github.hectorvent.floci.services.eventbridge.model.RuleState; +import io.github.hectorvent.floci.services.eventbridge.model.Target; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CopyOnWriteArrayList; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.RETURNS_DEEP_STUBS; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +class EcsEventBridgeIntegrationTest { + + private static final String REGION = "us-east-1"; + private final ObjectMapper objectMapper = new ObjectMapper(); + + private EventBridgeService eventBridgeService; + private EventBridgeInvoker invoker; + private EcsService ecsService; + private List deliveredEvents; + + @BeforeEach + void setUp() { + deliveredEvents = new CopyOnWriteArrayList<>(); + invoker = mock(EventBridgeInvoker.class); + doAnswer(invocation -> { + String eventJson = invocation.getArgument(1); + deliveredEvents.add(eventJson); + return null; + }).when(invoker).invokeTarget(any(), anyString(), anyString()); + + RegionResolver regionResolver = new RegionResolver(REGION, "000000000000"); + InMemoryStorageFactory storageFactory = new InMemoryStorageFactory(); + EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS); + when(config.services().ecs().mock()).thenReturn(true); + when(config.effectiveBaseUrl()).thenReturn("http://localhost:4566"); + + eventBridgeService = new EventBridgeService( + storageFactory, + config, + regionResolver, + objectMapper, + null, + invoker, + null, + null + ); + + EcsEventPublisher eventPublisher = new EcsEventPublisher(eventBridgeService, regionResolver, objectMapper); + + ecsService = new EcsService( + regionResolver, + mock(EcsContainerManager.class), + config, + mock(EcsLoadBalancerRegistrar.class), + storageFactory, + eventPublisher + ); + ecsService.initializeStorage(); + } + + private static TaskDefinition registerTaskDef(EcsService service, String family, String image) { + ContainerDefinition cd = new ContainerDefinition(); + cd.setName("app"); + cd.setImage(image); + return service.registerTaskDefinition(family, List.of(cd), null, null, null, + null, null, List.of(), REGION); + } + + @Test + void deploymentStateChangeDeliveredToEventBridgeOnServiceReconcile() { + eventBridgeService.putRule( + "ecs-deploy-rule", + null, + "{\"source\":[\"aws.ecs\"],\"detail-type\":[\"ECS Deployment State Change\"]}", + null, + RuleState.ENABLED, + "ECS deployment rule", + null, + null, + REGION + ); + + Target target = new Target(); + target.setId("deploy-target-1"); + target.setArn("arn:aws:sqs:us-east-1:000000000000:deploy-queue"); + eventBridgeService.putTargets("ecs-deploy-rule", null, List.of(target), REGION); + + ecsService.createCluster("deploy-cluster", REGION); + registerTaskDef(ecsService, "deploy-fam", "app:1"); + + ecsService.createService("deploy-cluster", "deploy-svc", "deploy-fam", 1, + LaunchType.FARGATE, List.of(), null, REGION); + + // Tick 1: task launched, desiredCount is being satisfied + ecsService.reconcileServices(); + // Tick 2: converged to steady state + ecsService.reconcileServices(); + + List events = deliveredEvents.stream().map(json -> { + try { + return objectMapper.readTree(json); + } catch (Exception e) { + throw new RuntimeException(e); + } + }).toList(); + + assertTrue(events.stream().anyMatch(evt -> + "aws.ecs".equals(evt.path("source").asText()) + && "ECS Deployment State Change".equals(evt.path("detail-type").asText()) + && "SERVICE_DEPLOYMENT_COMPLETED".equals(evt.path("detail").path("eventName").asText()) + && "INFO".equals(evt.path("detail").path("eventType").asText()) + && evt.path("detail").path("deploymentId").asText().startsWith("ecs-svc/") + ), "Expected SERVICE_DEPLOYMENT_COMPLETED event in delivered events"); + } + + @Test + void taskStateChangeDeliveredToEventBridgeOnTaskStop() { + eventBridgeService.putRule( + "ecs-task-rule", + null, + "{\"source\":[\"aws.ecs\"],\"detail-type\":[\"ECS Task State Change\"]}", + null, + RuleState.ENABLED, + "ECS task rule", + null, + null, + REGION + ); + + Target target = new Target(); + target.setId("task-target-1"); + target.setArn("arn:aws:sqs:us-east-1:000000000000:task-queue"); + eventBridgeService.putTargets("ecs-task-rule", null, List.of(target), REGION); + + ecsService.createCluster("task-cluster", REGION); + registerTaskDef(ecsService, "task-fam", "app:1"); + + ecsService.createService("task-cluster", "task-svc", "task-fam", 1, + LaunchType.FARGATE, List.of(), null, REGION); + + ecsService.reconcileServices(); + + List runningTasks = ecsService.describeTasks( + "task-cluster", + ecsService.listTasks("task-cluster", null, null, null, REGION), + REGION + ); + assertEquals(1, runningTasks.size()); + String taskArn = runningTasks.getFirst().getTaskArn(); + + ecsService.stopTask("task-cluster", taskArn, "test-stop", REGION); + + List events = deliveredEvents.stream().map(json -> { + try { + return objectMapper.readTree(json); + } catch (Exception e) { + throw new RuntimeException(e); + } + }).toList(); + + assertTrue(events.stream().anyMatch(evt -> + "aws.ecs".equals(evt.path("source").asText()) + && "ECS Task State Change".equals(evt.path("detail-type").asText()) + && "STOPPED".equals(evt.path("detail").path("lastStatus").asText()) + && taskArn.equals(evt.path("detail").path("taskArn").asText()) + ), "Expected STOPPED ECS Task State Change event with matching taskArn in delivered events"); + } + + private static final class InMemoryStorageFactory extends StorageFactory { + private final Map> stores = new HashMap<>(); + + private InMemoryStorageFactory() { + super(null, null); + } + + @Override + @SuppressWarnings("unchecked") + public AccountAwareStorageBackend create(String serviceName, + String fileName, + TypeReference> typeReference) { + return (AccountAwareStorageBackend) stores.computeIfAbsent(fileName, + ignored -> AccountAwareStorageBackend.inMemory("000000000000")); + } + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/ecs/EcsEventPublisherTest.java b/src/test/java/io/github/hectorvent/floci/services/ecs/EcsEventPublisherTest.java new file mode 100644 index 0000000000..4fc9349822 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/ecs/EcsEventPublisherTest.java @@ -0,0 +1,101 @@ +package io.github.hectorvent.floci.services.ecs; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.github.hectorvent.floci.core.common.RegionResolver; +import io.github.hectorvent.floci.services.ecs.model.Container; +import io.github.hectorvent.floci.services.ecs.model.EcsTask; +import io.github.hectorvent.floci.services.ecs.model.TaskStatus; +import io.github.hectorvent.floci.services.eventbridge.EventBridgeService; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; + +import java.util.List; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +class EcsEventPublisherTest { + + private static final String REGION = "us-east-1"; + private final ObjectMapper objectMapper = new ObjectMapper(); + + private EcsTask runningTask() { + EcsTask t = new EcsTask(); + t.setTaskArn("arn:aws:ecs:us-east-1:000000000000:task/c/abc"); + t.setClusterArn("arn:aws:ecs:us-east-1:000000000000:cluster/c"); + t.setTaskDefinitionArn("arn:aws:ecs:us-east-1:000000000000:task-definition/fam:1"); + t.setLastStatus("RUNNING"); + t.setDesiredStatus("RUNNING"); + Container c = new Container(); + c.setName("app"); + c.setLastStatus("RUNNING"); + c.setExitCode(0); + t.setContainers(List.of(c)); + return t; + } + + @SuppressWarnings("unchecked") + private List> capture(EventBridgeService eb, int times) { + ArgumentCaptor>> cap = ArgumentCaptor.forClass(List.class); + verify(eb, times(times)).putEvents(cap.capture(), eq(REGION)); + return cap.getAllValues().stream().map(List::getFirst).toList(); + } + + @Test + void startLadderEmitsProvisioningPendingActivatingRunning() throws Exception { + EventBridgeService eb = mock(EventBridgeService.class); + RegionResolver rr = new RegionResolver(REGION, "000000000000"); + EcsEventPublisher publisher = new EcsEventPublisher(eb, rr, objectMapper); + + EcsTask task = runningTask(); + publisher.emitTaskLadder(task, TaskStatus.PENDING, TaskStatus.RUNNING, REGION); + + List> entries = capture(eb, 4); + assertEquals(List.of("PROVISIONING", "PENDING", "ACTIVATING", "RUNNING"), + entries.stream().map(e -> { + try { + return objectMapper.readTree((String) e.get("Detail")).path("lastStatus").asText(); + } catch (Exception ex) { throw new RuntimeException(ex); } + }).toList()); + Map first = entries.getFirst(); + assertEquals("aws.ecs", first.get("Source")); + assertEquals("ECS Task State Change", first.get("DetailType")); + assertEquals("RUNNING", task.getLastStatus(), "task status is restored after the ladder"); + } + + @Test + void stopLadderEmitsDeactivatingStoppingDeprovisioningStopped() throws Exception { + EventBridgeService eb = mock(EventBridgeService.class); + RegionResolver rr = new RegionResolver(REGION, "000000000000"); + EcsEventPublisher publisher = new EcsEventPublisher(eb, rr, objectMapper); + + EcsTask task = runningTask(); + task.setLastStatus("STOPPED"); + task.getContainers().getFirst().setExitCode(137); + publisher.emitTaskLadder(task, TaskStatus.RUNNING, TaskStatus.STOPPED, REGION); + + List> entries = capture(eb, 4); + JsonNode lastDetail = objectMapper.readTree((String) entries.get(3).get("Detail")); + assertEquals("STOPPED", lastDetail.path("lastStatus").asText()); + assertEquals(137, lastDetail.path("containers").path(0).path("exitCode").asInt()); + } + + @Test + void putEventsFailureIsSwallowed() { + EventBridgeService eb = mock(EventBridgeService.class); + when(eb.putEvents(any(), any())).thenThrow(new RuntimeException("boom")); + RegionResolver rr = new RegionResolver(REGION, "000000000000"); + EcsEventPublisher publisher = new EcsEventPublisher(eb, rr, objectMapper); + + publisher.emitTaskLadder(runningTask(), TaskStatus.PENDING, TaskStatus.RUNNING, REGION); + // no exception propagates + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/ecs/EcsJsonHandlerTaskDefinitionPersistenceTest.java b/src/test/java/io/github/hectorvent/floci/services/ecs/EcsJsonHandlerTaskDefinitionPersistenceTest.java index 1aa6b8b2a3..9ead08b2a6 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ecs/EcsJsonHandlerTaskDefinitionPersistenceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ecs/EcsJsonHandlerTaskDefinitionPersistenceTest.java @@ -3,12 +3,14 @@ package io.github.hectorvent.floci.services.ecs; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; import io.github.hectorvent.floci.config.EmulatorConfig; import io.github.hectorvent.floci.core.common.RegionResolver; import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend; import io.github.hectorvent.floci.core.storage.PersistentStorage; import io.github.hectorvent.floci.core.storage.StorageFactory; import io.github.hectorvent.floci.services.ecs.container.EcsContainerManager; +import io.github.hectorvent.floci.services.ecs.model.LaunchType; import io.github.hectorvent.floci.services.ecs.model.TaskDefinition; import jakarta.ws.rs.core.Response; import org.junit.jupiter.api.Test; @@ -16,9 +18,11 @@ import org.junit.jupiter.api.io.TempDir; import java.nio.file.Path; import java.util.HashMap; +import java.util.List; import java.util.Map; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.mockito.Mockito.RETURNS_DEEP_STUBS; import static org.mockito.Mockito.mock; @@ -82,6 +86,35 @@ class EcsJsonHandlerTaskDefinitionPersistenceTest { assertEquals("/host/data", td.getVolumes().getFirst().hostSourcePath()); } + @Test + void updateServiceForceNewDeploymentMintsNewDeploymentId(@TempDir Path dataDir) throws Exception { + FileStorageFactory storage = new FileStorageFactory(dataDir); + ObjectMapper objectMapper = new ObjectMapper(); + EcsService service = serviceWithStorage(storage); + EcsJsonHandler handler = new EcsJsonHandler(service, objectMapper); + + JsonNode registerReq = objectMapper.readTree(""" + { + "family": "force-fam", + "containerDefinitions": [{"name": "app", "image": "alpine:latest"}] + } + """); + handler.handle("RegisterTaskDefinition", registerReq, REGION); + + var created = service.createService(null, "force-svc", "force-fam:1", 0, + LaunchType.FARGATE, List.of(), null, REGION); + String firstId = created.getDeploymentId(); + + ObjectNode req = objectMapper.createObjectNode(); + req.put("service", "force-svc"); + req.put("forceNewDeployment", true); + Response resp = handler.handle("UpdateService", req, REGION); + + JsonNode svc = objectMapper.readTree(resp.getEntity().toString()).path("service"); + String newId = svc.path("deployments").path(0).path("id").asText(); + assertNotEquals(firstId, newId); + } + private static EcsService serviceWithStorage(StorageFactory storage) { EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS); when(config.services().ecs().mock()).thenReturn(true); @@ -92,7 +125,8 @@ class EcsJsonHandlerTaskDefinitionPersistenceTest { mock(EcsContainerManager.class), config, mock(EcsLoadBalancerRegistrar.class), - storage); + storage, + null); service.initializeStorage(); return service; } diff --git a/src/test/java/io/github/hectorvent/floci/services/ecs/EcsServiceContainerSecretsTest.java b/src/test/java/io/github/hectorvent/floci/services/ecs/EcsServiceContainerSecretsTest.java index 8052145125..d4dd2f98f3 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ecs/EcsServiceContainerSecretsTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ecs/EcsServiceContainerSecretsTest.java @@ -39,7 +39,7 @@ class EcsServiceContainerSecretsTest { when(config.effectiveBaseUrl()).thenReturn("http://localhost:4566"); EcsService service = new EcsService(new RegionResolver("us-east-1", "000000000000"), - containerManager, config, mock(EcsLoadBalancerRegistrar.class), null); + containerManager, config, mock(EcsLoadBalancerRegistrar.class), null, null); service.createCluster("test-cluster", "us-east-1"); ContainerDefinition app = new ContainerDefinition(); diff --git a/src/test/java/io/github/hectorvent/floci/services/ecs/EcsServiceDaemonSchedulingTest.java b/src/test/java/io/github/hectorvent/floci/services/ecs/EcsServiceDaemonSchedulingTest.java index ea4b45967a..6523a5ef5e 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ecs/EcsServiceDaemonSchedulingTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ecs/EcsServiceDaemonSchedulingTest.java @@ -77,7 +77,7 @@ class EcsServiceDaemonSchedulingTest { when(containerManager.startTask(any(), any(), any(), anyString())) .thenThrow(new RuntimeException("no docker here")); EcsService service = new EcsService(new RegionResolver(REGION, "000000000000"), containerManager, - config, mock(EcsLoadBalancerRegistrar.class), new InMemoryStorageFactory()); + config, mock(EcsLoadBalancerRegistrar.class), new InMemoryStorageFactory(), null); service.initializeStorage(); service.createCluster("daemon-fail", REGION); service.registerContainerInstance("daemon-fail", null, List.of(), REGION); @@ -161,7 +161,8 @@ class EcsServiceDaemonSchedulingTest { mock(EcsContainerManager.class), config, mock(EcsLoadBalancerRegistrar.class), - new InMemoryStorageFactory()); + new InMemoryStorageFactory(), + null); service.initializeStorage(); return service; } diff --git a/src/test/java/io/github/hectorvent/floci/services/ecs/EcsServicePersistenceTest.java b/src/test/java/io/github/hectorvent/floci/services/ecs/EcsServicePersistenceTest.java index 794f574ae2..5b79f18388 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ecs/EcsServicePersistenceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ecs/EcsServicePersistenceTest.java @@ -114,7 +114,8 @@ class EcsServicePersistenceTest { mock(EcsContainerManager.class), config, mock(EcsLoadBalancerRegistrar.class), - storage); + storage, + null); service.initializeStorage(); return service; } diff --git a/src/test/java/io/github/hectorvent/floci/services/ecs/EcsServiceRolloutTest.java b/src/test/java/io/github/hectorvent/floci/services/ecs/EcsServiceRolloutTest.java index d01839c4da..06a30cb1e3 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ecs/EcsServiceRolloutTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ecs/EcsServiceRolloutTest.java @@ -11,6 +11,7 @@ import io.github.hectorvent.floci.services.ecs.model.ContainerDefinition; import io.github.hectorvent.floci.services.ecs.model.EcsTask; import io.github.hectorvent.floci.services.ecs.model.LaunchType; import io.github.hectorvent.floci.services.ecs.model.TaskDefinition; +import io.github.hectorvent.floci.services.ecs.model.TaskStatus; import org.junit.jupiter.api.Test; import java.util.HashMap; @@ -18,9 +19,16 @@ import java.util.List; import java.util.Map; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.RETURNS_DEEP_STUBS; +import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; /** @@ -122,6 +130,81 @@ class EcsServiceRolloutTest { second.stream().map(EcsTask::getTaskArn).sorted().toList()); } + @Test + void forceNewDeploymentSameTaskDefinitionMintsNewIdAndReplacesTasks() { + EcsService service = newMockModeService(); + service.createCluster("force-cluster", REGION); + TaskDefinition rev1 = registerTaskDef(service, "force-fam", "app:1"); + var created = service.createService("force-cluster", "force-svc", "force-fam", 1, + LaunchType.FARGATE, List.of(), null, REGION); + String firstDeploymentId = created.getDeploymentId(); + assertNotNull(firstDeploymentId, "createService assigns a deploymentId"); + + service.reconcileServices(); + List before = runningTasks(service); + assertEquals(1, before.size()); + assertEquals(firstDeploymentId, before.getFirst().getDeploymentId()); + + // Same task definition, force flag set. + var updated = service.updateService("force-cluster", "force-svc", null, null, null, + null, true, REGION); + assertNotEquals(firstDeploymentId, updated.getDeploymentId(), + "forceNewDeployment mints a new deployment id"); + + // Tick 1: replacement on the new deployment comes up while desiredCount is still met. + service.reconcileServices(); + assertEquals(2, runningTasks(service).size()); + + // Tick 2: the task from the old deployment is drained. + service.reconcileServices(); + List after = runningTasks(service); + assertEquals(1, after.size()); + assertEquals(updated.getDeploymentId(), after.getFirst().getDeploymentId()); + + EcsTask stopped = service.describeTasks("force-cluster", + List.of(before.getFirst().getTaskArn()), REGION).getFirst(); + assertEquals("STOPPED", stopped.getLastStatus()); + } + + @Test + void serviceTaskStartAndStopEmitTaskStateChangeLadders() { + EcsEventPublisher publisher = mock(EcsEventPublisher.class); + EcsService service = newMockModeService(publisher); + service.createCluster("evt-cluster", REGION); + registerTaskDef(service, "evt-fam", "app:1"); + service.createService("evt-cluster", "evt-svc", "evt-fam", 1, + LaunchType.FARGATE, List.of(), null, REGION); + + service.reconcileServices(); + verify(publisher).emitTaskLadder(any(), eq(TaskStatus.PENDING), eq(TaskStatus.RUNNING), eq(REGION)); + + String taskArn = runningTasks(service).getFirst().getTaskArn(); + service.stopTask("evt-cluster", taskArn, "test", REGION); + verify(publisher).emitTaskLadder(any(), eq(TaskStatus.RUNNING), eq(TaskStatus.STOPPED), eq(REGION)); + } + + @Test + void deploymentEmitsStartedThenCompleted() { + EcsEventPublisher publisher = mock(EcsEventPublisher.class); + EcsService service = newMockModeService(publisher); + service.createCluster("dep-cluster", REGION); + registerTaskDef(service, "dep-fam", "app:1"); + + service.createService("dep-cluster", "dep-svc", "dep-fam", 1, + LaunchType.FARGATE, List.of(), null, REGION); + verify(publisher).emitDeploymentStateChange(any(), eq("SERVICE_DEPLOYMENT_STARTED"), any(), eq(REGION)); + + service.reconcileServices(); // task starts, still converging or converged same tick + service.reconcileServices(); // converged + verify(publisher, atLeastOnce()) + .emitDeploymentStateChange(any(), eq("SERVICE_DEPLOYMENT_COMPLETED"), any(), eq(REGION)); + + // COMPLETED is not re-emitted on further steady-state ticks. + service.reconcileServices(); + verify(publisher, times(1)) + .emitDeploymentStateChange(any(), eq("SERVICE_DEPLOYMENT_COMPLETED"), any(), eq(REGION)); + } + private static List runningTasks(EcsService service) { return service.describeTasks(null, service.listTasks(null, null, null, null, REGION), REGION).stream() .filter(t -> "RUNNING".equals(t.getLastStatus())) @@ -137,6 +220,10 @@ class EcsServiceRolloutTest { } private static EcsService newMockModeService() { + return newMockModeService(null); + } + + private static EcsService newMockModeService(EcsEventPublisher publisher) { EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS); when(config.services().ecs().mock()).thenReturn(true); when(config.effectiveBaseUrl()).thenReturn("http://localhost:4566"); @@ -145,7 +232,8 @@ class EcsServiceRolloutTest { mock(EcsContainerManager.class), config, mock(EcsLoadBalancerRegistrar.class), - new InMemoryStorageFactory()); + new InMemoryStorageFactory(), + publisher); service.initializeStorage(); return service; } diff --git a/src/test/java/io/github/hectorvent/floci/services/ecs/EcsServiceTaskOwnershipTest.java b/src/test/java/io/github/hectorvent/floci/services/ecs/EcsServiceTaskOwnershipTest.java index a53386fcdf..32a12e20c9 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ecs/EcsServiceTaskOwnershipTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ecs/EcsServiceTaskOwnershipTest.java @@ -225,7 +225,8 @@ class EcsServiceTaskOwnershipTest { mock(EcsContainerManager.class), config, mock(EcsLoadBalancerRegistrar.class), - new InMemoryStorageFactory()); + new InMemoryStorageFactory(), + null); service.initializeStorage(); return service; } diff --git a/src/test/java/io/github/hectorvent/floci/services/ecs/EcsServiceTeardownTest.java b/src/test/java/io/github/hectorvent/floci/services/ecs/EcsServiceTeardownTest.java index 30bedf7546..454a64e4d0 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ecs/EcsServiceTeardownTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ecs/EcsServiceTeardownTest.java @@ -52,7 +52,8 @@ class EcsServiceTeardownTest { containerManager, config, mock(EcsLoadBalancerRegistrar.class), - new SingleUseStorageFactory()); + new SingleUseStorageFactory(), + null); service.initializeStorage(); ContainerDefinition cd = new ContainerDefinition(); @@ -98,7 +99,8 @@ class EcsServiceTeardownTest { containerManager, config, mock(EcsLoadBalancerRegistrar.class), - new SingleUseStorageFactory()); + new SingleUseStorageFactory(), + null); service.initializeStorage(); ContainerDefinition cd = new ContainerDefinition();