feat(ecs): honor UpdateService forceNewDeployment and emit EventBridge lifecycle events (#2938)

* feat(ecs): honor UpdateService forceNewDeployment (#2557)

* feat(ecs): add EcsEventPublisher for aws.ecs lifecycle events (#2557)

* feat(ecs): emit ECS Task State Change events on task start/stop (#2557)

* feat(ecs): emit ECS Deployment State Change events (#2557)

* test(ecs): end-to-end ECS EventBridge lifecycle events + docs (#2557)

* fix(ecs): log diagnostic when task ARN region parse fails (#2557)

* fix(ecs): synthesize lifecycle events from a task snapshot, not the shared instance

emitTaskLadder toggled the live task's lastStatus in place to synthesize
each phase, so a concurrent DescribeTasks/ListTasks could observe a
status the task never actually occupied while the four-phase ladder
was in flight. Build the ladder from a shallow copy instead.

Also bump the ARN region-parse fallback log from debug to warn, since
debug is off by default and made the fallback effectively invisible.
This commit is contained in:
Vũ Thế Huy authored and GitHub committed 2026-09-02 23:09:37 -04:00
1 parent 58b2e5ff96
commit 14ca62d9f7
15 files changed
+772 -22

No files matched your search

@@ -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.
*
* <p>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 <em>synthesized</em> 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<TaskStatus> START_LADDER =
List.of(TaskStatus.PROVISIONING, TaskStatus.PENDING, TaskStatus.ACTIVATING, TaskStatus.RUNNING);
private static final List<TaskStatus> 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<TaskStatus> 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<String, Object> 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;
}
}
@@ -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));
@@ -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<String, List<Attribute>> attributes = new ConcurrentHashMap<>();
// name → value (account-level settings)
private Map<String, String> accountSettings = new ConcurrentHashMap<>();
// deploymentIds for which SERVICE_DEPLOYMENT_IN_PROGRESS has already been emitted this process.
private final Set<String> 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/<id>} 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<EcsTask> 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++) {
@@ -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/<hex>"). 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; }
@@ -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<Container> containers;
private String containerInstanceArn;
@@ -38,6 +40,40 @@ public class EcsTask {
private Map<String, String> 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. */