mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(ecs): roll a load-balanced service healthy-first and drain the old task before stopping it (#8256)
* fix(ecs): keep a load-balanced service task running while its targets drain * fix(ecs): stop a replaced task only once its replacement's targets are healthy * fix(ecs): drain a load-balanced task as DEACTIVATING and hold a deployment on unhealthy replacements
This commit is contained in:
1 parent
16cb752444
commit
a56739ca30
6 files changed
+270
-34
No files matched your search
@@ -19,8 +19,10 @@ import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.Comparator;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
@@ -88,11 +90,8 @@ public class EcsLoadBalancerRegistrar {
|
||||
if (taskArn == null || registered.size() == planned.size()) {
|
||||
return;
|
||||
}
|
||||
if (registered.isEmpty()) {
|
||||
ledger.delete(taskArn);
|
||||
} else {
|
||||
ledger.put(taskArn, new EcsRegisteredTargets(region, List.copyOf(registered)));
|
||||
}
|
||||
// An empty record, rather than none, tells targetsHealthy the task has targets that never registered.
|
||||
ledger.put(taskArn, new EcsRegisteredTargets(region, List.copyOf(registered)));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -100,17 +99,53 @@ public class EcsLoadBalancerRegistrar {
|
||||
* with no record registered nothing, as when none of its containers had a reachable binding.
|
||||
* Only a task without an ARN, which {@link #registerTask} cannot record, falls back to the
|
||||
* targets its containers resolve to now.
|
||||
*
|
||||
* @return how long the deregistered targets drain: the longest
|
||||
* {@code deregistration_delay.timeout_seconds} of their target groups, during which
|
||||
* AWS keeps the task running for the requests already in flight
|
||||
*/
|
||||
public void deregisterTask(EcsTask task, EcsServiceModel svc, String region) {
|
||||
public Duration deregisterTask(EcsTask task, EcsServiceModel svc, String region) {
|
||||
List<Duration> drains = new ArrayList<>();
|
||||
if (task.getTaskArn() == null) {
|
||||
forEachTarget(task, svc, (tgArn, td) -> deregister(region, tgArn, td));
|
||||
return;
|
||||
forEachTarget(task, svc, (tgArn, td) -> drains.add(deregister(region, tgArn, td)));
|
||||
} else {
|
||||
Optional<EcsRegisteredTargets> recorded = ledger.get(task.getTaskArn());
|
||||
if (recorded.isPresent()) {
|
||||
drains.addAll(deregister(recorded.get()));
|
||||
ledger.delete(task.getTaskArn());
|
||||
}
|
||||
}
|
||||
Optional<EcsRegisteredTargets> recorded = ledger.get(task.getTaskArn());
|
||||
if (recorded.isPresent()) {
|
||||
deregister(recorded.get());
|
||||
ledger.delete(task.getTaskArn());
|
||||
return drains.stream().max(Comparator.naturalOrder()).orElse(Duration.ZERO);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether every target {@link #registerTask} recorded for the task reports {@code healthy}. A
|
||||
* task with no load-balanced container has nothing to wait for; one whose targets failed to
|
||||
* register, or whose health cannot be read, is not healthy yet.
|
||||
*/
|
||||
public boolean targetsHealthy(EcsTask task) {
|
||||
Optional<EcsRegisteredTargets> recorded = task.getTaskArn() == null
|
||||
? Optional.empty() : ledger.get(task.getTaskArn());
|
||||
if (recorded.isEmpty()) {
|
||||
return true;
|
||||
}
|
||||
List<EcsRegisteredTargets.Target> targets = recorded.get().targets();
|
||||
if (targets == null || targets.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
for (EcsRegisteredTargets.Target target : targets) {
|
||||
try {
|
||||
List<TargetHealth> health = elbV2Service.describeTargetHealth(recorded.get().region(),
|
||||
target.targetGroupArn(), List.of(target.toDescription()));
|
||||
if (health.isEmpty() || health.stream().anyMatch(th -> !"healthy".equals(th.getState()))) {
|
||||
return false;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
LOG.warnv("Could not read the health of {0}: {1}", target.targetGroupArn(), e.getMessage());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -175,22 +210,36 @@ public class EcsLoadBalancerRegistrar {
|
||||
}
|
||||
}
|
||||
|
||||
private void deregister(EcsRegisteredTargets recorded) {
|
||||
private List<Duration> deregister(EcsRegisteredTargets recorded) {
|
||||
List<Duration> drains = new ArrayList<>();
|
||||
if (recorded.targets() == null) {
|
||||
return;
|
||||
return drains;
|
||||
}
|
||||
for (EcsRegisteredTargets.Target target : recorded.targets()) {
|
||||
deregister(recorded.region(), target.targetGroupArn(), target.toDescription());
|
||||
drains.add(deregister(recorded.region(), target.targetGroupArn(), target.toDescription()));
|
||||
}
|
||||
return drains;
|
||||
}
|
||||
|
||||
private void deregister(String region, String tgArn, TargetDescription td) {
|
||||
/** @return the target group's deregistration delay, or zero when the target could not be deregistered */
|
||||
private Duration deregister(String region, String tgArn, TargetDescription td) {
|
||||
try {
|
||||
elbV2Service.deregisterTargets(region, tgArn, List.of(td));
|
||||
LOG.infov("Deregistered ECS task target {0}:{1} from target group {2}",
|
||||
td.getId(), td.getPort(), tgArn);
|
||||
} catch (Exception e) {
|
||||
LOG.warnv("Could not deregister ECS target from {0}: {1}", tgArn, e.getMessage());
|
||||
return Duration.ZERO;
|
||||
}
|
||||
String delay = null;
|
||||
try {
|
||||
delay = elbV2Service.describeTargetGroupAttributes(region, tgArn)
|
||||
.get("deregistration_delay.timeout_seconds");
|
||||
return delay == null ? Duration.ZERO : Duration.ofSeconds(Long.parseLong(delay));
|
||||
} catch (Exception e) {
|
||||
LOG.warnv("Not draining target group {0}: could not read its deregistration delay {1}: {2}",
|
||||
tgArn, delay, e.getMessage());
|
||||
return Duration.ZERO;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -290,7 +290,7 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
|
||||
execSessions, discoveryRegistrar, cloudWatchMetricsService, Clock.systemUTC());
|
||||
}
|
||||
|
||||
/** With the clock for Container Insights samples and task protection deadlines. */
|
||||
/** With the clock for Container Insights samples, task protection deadlines and target drains. */
|
||||
EcsService(RegionResolver regionResolver, EcsContainerManager containerManager,
|
||||
EmulatorConfig config, EcsLoadBalancerRegistrar lbRegistrar,
|
||||
StorageFactory storageFactory, EcsEventPublisher eventPublisher,
|
||||
@@ -2255,15 +2255,29 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
|
||||
task.bumpVersion();
|
||||
return task;
|
||||
}
|
||||
if (!TaskStatus.STOPPING.name().equals(task.getLastStatus())) {
|
||||
boolean deactivating = TaskStatus.DEACTIVATING.name().equals(task.getLastStatus());
|
||||
if (!deactivating && !TaskStatus.STOPPING.name().equals(task.getLastStatus())) {
|
||||
task.setDesiredStatus(TaskStatus.STOPPED.name());
|
||||
task.setLastStatus(TaskStatus.STOPPING.name());
|
||||
task.setStoppingAt(Instant.now());
|
||||
task.setStoppedReason(reason != null ? reason : "Stopped by user");
|
||||
task.setStopCode(stopCode);
|
||||
task.bumpVersion();
|
||||
deregisterTaskFromLoadBalancers(task, region);
|
||||
Duration drain = deregisterTaskFromLoadBalancers(task, region);
|
||||
deregisterTaskFromServiceDiscovery(task, region);
|
||||
if (inBackground && !drain.isZero()) {
|
||||
// As on AWS, the task stays DEACTIVATING, serving its in-flight requests, until its
|
||||
// targets have drained; the first reconciliation tick after that stops it.
|
||||
task.setLastStatus(TaskStatus.DEACTIVATING.name());
|
||||
task.setTargetsDrainedAt(clock.instant().plus(drain));
|
||||
task.bumpVersion();
|
||||
return task;
|
||||
}
|
||||
} else if (deactivating && inBackground && task.getTargetsDrainedAt() != null
|
||||
&& clock.instant().isBefore(task.getTargetsDrainedAt())) {
|
||||
return task; // StopTask does not wait for the drain
|
||||
}
|
||||
if (!TaskStatus.STOPPING.name().equals(task.getLastStatus())) {
|
||||
task.setLastStatus(TaskStatus.STOPPING.name());
|
||||
task.setStoppingAt(Instant.now());
|
||||
task.bumpVersion();
|
||||
}
|
||||
|
||||
if (!dockerMode) {
|
||||
@@ -2537,21 +2551,26 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
|
||||
.orElse(null);
|
||||
}
|
||||
|
||||
/** Deregisters a stopping task's containers from any ELBv2 target groups its service declared. */
|
||||
private void deregisterTaskFromLoadBalancers(EcsTask task, String region) {
|
||||
/**
|
||||
* Deregisters a stopping task's containers from any ELBv2 target groups its service declared.
|
||||
*
|
||||
* @return how long those targets drain, as {@link EcsLoadBalancerRegistrar#deregisterTask} reports
|
||||
*/
|
||||
private Duration deregisterTaskFromLoadBalancers(EcsTask task, String region) {
|
||||
// Gated on dockerMode for symmetry with the register hook (inside launchTasks'
|
||||
// dockerMode branch): mock-mode tasks have no containers and never registered.
|
||||
if (!dockerMode || task.getOwningServiceArn() == null) {
|
||||
return;
|
||||
return Duration.ZERO;
|
||||
}
|
||||
EcsCluster cluster = resolveClusterByArn(task.getClusterArn());
|
||||
if (cluster == null) {
|
||||
return;
|
||||
return Duration.ZERO;
|
||||
}
|
||||
EcsServiceModel svc = owningService(task, cluster);
|
||||
if (svc != null && !svc.getLoadBalancers().isEmpty()) {
|
||||
lbRegistrar.deregisterTask(task, svc, region);
|
||||
return lbRegistrar.deregisterTask(task, svc, region);
|
||||
}
|
||||
return Duration.ZERO;
|
||||
}
|
||||
|
||||
/** Deregisters a stopping task from the Cloud Map services it actually joined. */
|
||||
@@ -2884,6 +2903,18 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a task's load balancer targets pass their health checks, as ECS waits for before it
|
||||
* stops the task a rolling deployment replaces. As on AWS, a replacement that never turns
|
||||
* healthy holds the deployment.
|
||||
*/
|
||||
private boolean loadBalancerTargetsHealthy(EcsTask task, EcsServiceModel svc) {
|
||||
if (!dockerMode || lbRegistrar == null || svc.getLoadBalancers().isEmpty()) {
|
||||
return true;
|
||||
}
|
||||
return lbRegistrar.targetsHealthy(task);
|
||||
}
|
||||
|
||||
private boolean eligibleForServiceStop(EcsTask task) {
|
||||
return !isProtectedTask(task);
|
||||
}
|
||||
@@ -5370,7 +5401,8 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
|
||||
}
|
||||
|
||||
private void reconcileTaskLocked(String taskArn, EcsTask task) {
|
||||
if (TaskStatus.STOPPING.name().equals(task.getLastStatus())) {
|
||||
if (TaskStatus.STOPPING.name().equals(task.getLastStatus())
|
||||
|| TaskStatus.DEACTIVATING.name().equals(task.getLastStatus())) {
|
||||
// Never stopTask(...), which waits for a stop already running: that stop lands under
|
||||
// this task's monitor, held here.
|
||||
stopTaskLocked(task, task.getStoppedReason(), task.getStopCode(), taskRegion(task), true);
|
||||
@@ -5950,11 +5982,16 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
|
||||
}
|
||||
}
|
||||
} else if (running > svc.getDesiredCount()) {
|
||||
// Drain stale tasks first: once their replacements are RUNNING this is the second
|
||||
// half of the rolling deployment. Protected stale tasks cannot displace the
|
||||
// desired number of current-revision tasks.
|
||||
// Drain stale tasks first: once their replacements are RUNNING, and healthy behind
|
||||
// the service's load balancers, this is the second half of the rolling deployment.
|
||||
// Protected stale tasks cannot displace the desired number of current-revision tasks.
|
||||
int currentToStop = Math.max(0, (int) current - svc.getDesiredCount());
|
||||
Stream.concat(staleTasks.stream().filter(this::eligibleForServiceStop),
|
||||
boolean replacementsHealthy = runningTasks.stream()
|
||||
.filter(t -> !staleTasks.contains(t))
|
||||
.allMatch(t -> loadBalancerTargetsHealthy(t, svc));
|
||||
Stream.concat(staleTasks.stream()
|
||||
.filter(t -> replacementsHealthy)
|
||||
.filter(this::eligibleForServiceStop),
|
||||
runningTasks.stream()
|
||||
.filter(t -> !staleTasks.contains(t))
|
||||
.filter(this::eligibleForServiceStop)
|
||||
|
||||
@@ -61,6 +61,11 @@ public class EcsTask {
|
||||
private Instant pullStoppedAt;
|
||||
private Instant executionStoppedAt;
|
||||
private Instant stoppingAt;
|
||||
/**
|
||||
* When the load balancer targets of this DEACTIVATING task finish draining, the earliest the
|
||||
* service scheduler stops its containers. Internal: never serialized.
|
||||
*/
|
||||
private Instant targetsDrainedAt;
|
||||
private EphemeralStorage ephemeralStorage;
|
||||
private boolean enableExecuteCommand;
|
||||
private TaskOverride overrides;
|
||||
@@ -118,6 +123,7 @@ public class EcsTask {
|
||||
this.pullStoppedAt = other.pullStoppedAt;
|
||||
this.executionStoppedAt = other.executionStoppedAt;
|
||||
this.stoppingAt = other.stoppingAt;
|
||||
this.targetsDrainedAt = other.targetsDrainedAt;
|
||||
this.ephemeralStorage = other.ephemeralStorage;
|
||||
this.enableExecuteCommand = other.enableExecuteCommand;
|
||||
this.overrides = other.overrides;
|
||||
@@ -257,6 +263,9 @@ public class EcsTask {
|
||||
public Instant getStoppingAt() { return stoppingAt; }
|
||||
public void setStoppingAt(Instant stoppingAt) { this.stoppingAt = stoppingAt; }
|
||||
|
||||
public Instant getTargetsDrainedAt() { return targetsDrainedAt; }
|
||||
public void setTargetsDrainedAt(Instant targetsDrainedAt) { this.targetsDrainedAt = targetsDrainedAt; }
|
||||
|
||||
public EphemeralStorage getEphemeralStorage() { return ephemeralStorage; }
|
||||
public void setEphemeralStorage(EphemeralStorage ephemeralStorage) { this.ephemeralStorage = ephemeralStorage; }
|
||||
|
||||
|
||||
Reference in new issue
Block a user