mirror of
https://github.com/floci-io/floci.git
synced 2026-11-23 14:10:49 -05:00
fix(ecs): roll service tasks onto a changed task definition (#2483)
UpdateService with a new taskDefinition recorded a deployment but left the running tasks on the old revision forever: a redeploy (new image tag, new environment) never reached the containers, and the only way to apply it was to StopTask by hand so the reconciler relaunched. The reconciler now counts only tasks on the service's current task definition towards desiredCount, so replacements start first, and when the service is over desiredCount it drains the stale tasks before anything else — the shape of AWS's rolling deployment with the ECS deployment controller. Stopped reason names the replaced task definition. The service pins the resolved task-definition ARN on CreateService and UpdateService (AWS stores and reports the ARN), so a family or family:revision reference compares exactly with each task's taskDefinitionArn; a service persisted with a raw reference is pinned on its first reconciler tick. Co-authored-by: Hisham Mohammed <hisham.ma.mohammed@gmail.com>
This commit is contained in:
1 parent
33374cacab
commit
f3b22e7964
3 files changed
+222
-13
No files matched your search
@@ -76,8 +76,10 @@ deployment, and moves with it thereafter.
|
||||
|
||||
Known differences from AWS:
|
||||
|
||||
- There is never a second `ACTIVE` deployment draining alongside the `PRIMARY` one;
|
||||
Floci swaps the task definition in place.
|
||||
- There is never a second `ACTIVE` deployment draining alongside the `PRIMARY` one.
|
||||
The running tasks *are* rolled onto a changed task definition (replacements on the new
|
||||
revision start first, then the stale tasks are drained, one reconciler tick apart), but
|
||||
the deployments list reports only the single `PRIMARY` throughout.
|
||||
- `deployments` is reported for every service. AWS omits it for services that use the
|
||||
`CODE_DEPLOY` or `EXTERNAL` deployment controller, but Floci does not yet record
|
||||
`deploymentController`, and `ECS` is the AWS default.
|
||||
|
||||
@@ -693,7 +693,9 @@ public class EcsService implements ContainerTeardown {
|
||||
NetworkConfiguration networkConfiguration,
|
||||
Map<String, String> tags, String region) {
|
||||
EcsCluster cluster = resolveClusterOrDefault(clusterRef, region);
|
||||
resolveTaskDefinitionOrThrow(taskDefinition, region);
|
||||
// AWS resolves family / family:revision at create time and stores the ARN; the
|
||||
// reconciler compares it with each task's taskDefinitionArn, so pin it here.
|
||||
taskDefinition = resolveTaskDefinitionOrThrow(taskDefinition, region).getTaskDefinitionArn();
|
||||
|
||||
String key = serviceKey(region, cluster.getClusterName(), serviceName);
|
||||
if (services.containsKey(key)) {
|
||||
@@ -759,7 +761,7 @@ public class EcsService implements ContainerTeardown {
|
||||
svc.setNetworkConfiguration(networkConfiguration);
|
||||
}
|
||||
if (taskDefinition != null) {
|
||||
resolveTaskDefinitionOrThrow(taskDefinition, region);
|
||||
taskDefinition = resolveTaskDefinitionOrThrow(taskDefinition, region).getTaskDefinitionArn();
|
||||
svc.setTaskDefinition(taskDefinition);
|
||||
svc.setLastDeploymentAt(Instant.now());
|
||||
recordServiceDeployment(svc, taskDefinition, region);
|
||||
@@ -1506,6 +1508,28 @@ public class EcsService implements ContainerTeardown {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The service's task definition as an ARN. Services created before the ARN was pinned at
|
||||
* create/update time may still hold a raw {@code family} / {@code family:revision}
|
||||
* reference; resolve it once and store the ARN so the comparison with
|
||||
* {@link EcsTask#getTaskDefinitionArn()} is exact. A dangling reference is left as-is and
|
||||
* simply matches nothing, which is the pre-existing behaviour for an unresolvable service.
|
||||
*/
|
||||
private String pinnedTaskDefinitionArn(EcsServiceModel svc, String key, String region) {
|
||||
String ref = svc.getTaskDefinition();
|
||||
if (ref == null || ref.startsWith("arn:")) {
|
||||
return ref;
|
||||
}
|
||||
try {
|
||||
String arn = resolveTaskDefinitionOrThrow(ref, region).getTaskDefinitionArn();
|
||||
svc.setTaskDefinition(arn);
|
||||
services.put(key, svc);
|
||||
return arn;
|
||||
} catch (AwsException e) {
|
||||
return ref;
|
||||
}
|
||||
}
|
||||
|
||||
void reconcileServices() {
|
||||
for (Map.Entry<String, EcsServiceModel> entry : services.entrySet()) {
|
||||
try {
|
||||
@@ -1524,17 +1548,28 @@ public class EcsService implements ContainerTeardown {
|
||||
String region = extractRegionFromServiceKey(key);
|
||||
String clusterName = extractClusterNameFromServiceKey(key);
|
||||
|
||||
long running = tasks.values().stream()
|
||||
List<EcsTask> runningTasks = tasks.values().stream()
|
||||
.filter(t -> t.getClusterArn().endsWith(":cluster/" + clusterName))
|
||||
.filter(t -> svc.getServiceArn().equals(t.getGroup())
|
||||
|| svc.getServiceName().equals(t.getGroup()))
|
||||
.filter(t -> TaskStatus.RUNNING.name().equals(t.getLastStatus()))
|
||||
.count();
|
||||
.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 currentTaskDefinitionArn = pinnedTaskDefinitionArn(svc, key, region);
|
||||
List<EcsTask> staleTasks = runningTasks.stream()
|
||||
.filter(t -> !currentTaskDefinitionArn.equals(t.getTaskDefinitionArn()))
|
||||
.toList();
|
||||
long current = running - staleTasks.size();
|
||||
|
||||
svc.setRunningCount((int) running);
|
||||
|
||||
if (running < svc.getDesiredCount()) {
|
||||
int toStart = svc.getDesiredCount() - (int) running;
|
||||
if (current < svc.getDesiredCount()) {
|
||||
int toStart = svc.getDesiredCount() - (int) current;
|
||||
for (int i = 0; i < toStart; i++) {
|
||||
try {
|
||||
List<EcsTask> launched = runTask(clusterName, svc.getTaskDefinition(), 1,
|
||||
@@ -1549,14 +1584,17 @@ public class EcsService implements ContainerTeardown {
|
||||
}
|
||||
} else if (running > svc.getDesiredCount()) {
|
||||
int toStop = (int) running - svc.getDesiredCount();
|
||||
tasks.values().stream()
|
||||
.filter(t -> t.getClusterArn().endsWith(":cluster/" + clusterName))
|
||||
.filter(t -> svc.getServiceName().equals(t.getGroup()))
|
||||
.filter(t -> TaskStatus.RUNNING.name().equals(t.getLastStatus()))
|
||||
// Drain stale tasks first: once their replacements are RUNNING this is the second
|
||||
// half of the rolling deployment, not a scale-in.
|
||||
Stream.concat(staleTasks.stream(),
|
||||
runningTasks.stream().filter(t -> !staleTasks.contains(t)))
|
||||
.limit(toStop)
|
||||
.forEach(t -> {
|
||||
boolean stale = staleTasks.contains(t);
|
||||
try {
|
||||
stopTask(clusterName, t.getTaskArn(), "Service scale-in", region);
|
||||
stopTask(clusterName, t.getTaskArn(),
|
||||
stale ? "Service deployment replaced task definition " + t.getTaskDefinitionArn()
|
||||
: "Service scale-in", region);
|
||||
} catch (Exception e) {
|
||||
LOG.warnv("Service reconciler failed to stop task {0}: {1}",
|
||||
t.getTaskArn(), e.getMessage());
|
||||
|
||||
@@ -0,0 +1,169 @@
|
||||
package io.github.hectorvent.floci.services.ecs;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
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 org.junit.jupiter.api.Test;
|
||||
|
||||
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.assertTrue;
|
||||
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* A service's running tasks must follow its task definition. {@code UpdateService} with a new
|
||||
* {@code taskDefinition} used to record a deployment and leave the old tasks running forever,
|
||||
* so a redeploy (new image tag, new environment) never reached the containers.
|
||||
*/
|
||||
class EcsServiceRolloutTest {
|
||||
|
||||
private static final String REGION = "us-east-1";
|
||||
|
||||
@Test
|
||||
void updatedTaskDefinitionReplacesRunningTasksReplacementsFirst() {
|
||||
EcsService service = newMockModeService();
|
||||
service.createCluster("roll-cluster", REGION);
|
||||
TaskDefinition rev1 = registerTaskDef(service, "roll-fam", "app:1");
|
||||
// A bare family reference, as the CLI and most clients send it: the service must pin
|
||||
// the resolved ARN, or every task would look stale on every tick.
|
||||
service.createService("roll-cluster", "roll-svc", "roll-fam", 1,
|
||||
LaunchType.FARGATE, List.of(), null, REGION);
|
||||
|
||||
service.reconcileServices();
|
||||
List<EcsTask> first = runningTasks(service);
|
||||
assertEquals(1, first.size());
|
||||
assertEquals(rev1.getTaskDefinitionArn(), first.getFirst().getTaskDefinitionArn());
|
||||
|
||||
TaskDefinition rev2 = registerTaskDef(service, "roll-fam", "app:2");
|
||||
service.updateService("roll-cluster", "roll-svc", "roll-fam:" + rev2.getRevision(), null, null, REGION);
|
||||
|
||||
// Tick 1: the replacement comes up before anything is drained (desiredCount 1 is still met).
|
||||
service.reconcileServices();
|
||||
List<EcsTask> during = runningTasks(service);
|
||||
assertEquals(2, during.size(), "replacement starts before the stale task is stopped");
|
||||
assertTrue(during.stream().anyMatch(t -> rev2.getTaskDefinitionArn().equals(t.getTaskDefinitionArn())));
|
||||
|
||||
// Tick 2: the stale task is drained, the replacement stays.
|
||||
service.reconcileServices();
|
||||
List<EcsTask> after = runningTasks(service);
|
||||
assertEquals(1, after.size());
|
||||
assertEquals(rev2.getTaskDefinitionArn(), after.getFirst().getTaskDefinitionArn());
|
||||
|
||||
EcsTask stopped = service.describeTasks("roll-cluster", List.of(first.getFirst().getTaskArn()), REGION).getFirst();
|
||||
assertEquals("STOPPED", stopped.getLastStatus());
|
||||
assertTrue(stopped.getStoppedReason().contains(rev1.getTaskDefinitionArn()),
|
||||
"stopped reason names the replaced task definition: " + stopped.getStoppedReason());
|
||||
|
||||
// Steady state: nothing else changes on later ticks.
|
||||
service.reconcileServices();
|
||||
assertEquals(1, runningTasks(service).size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void serviceReportsThePinnedTaskDefinitionArn() {
|
||||
EcsService service = newMockModeService();
|
||||
service.createCluster("pin-cluster", REGION);
|
||||
TaskDefinition rev1 = registerTaskDef(service, "pin-fam", "app:1");
|
||||
|
||||
var svc = service.createService("pin-cluster", "pin-svc", "pin-fam", 0,
|
||||
LaunchType.FARGATE, List.of(), null, REGION);
|
||||
|
||||
assertEquals(rev1.getTaskDefinitionArn(), svc.getTaskDefinition());
|
||||
}
|
||||
|
||||
@Test
|
||||
void serviceHoldingARawReferenceIsPinnedOnItsFirstTickInsteadOfRelaunchingForever() {
|
||||
EcsService service = newMockModeService();
|
||||
service.createCluster("legacy-cluster", REGION);
|
||||
TaskDefinition rev1 = registerTaskDef(service, "legacy-fam", "app:1");
|
||||
var svc = service.createService("legacy-cluster", "legacy-svc", "legacy-fam", 1,
|
||||
LaunchType.FARGATE, List.of(), null, REGION);
|
||||
service.reconcileServices();
|
||||
assertEquals(1, runningTasks(service).size());
|
||||
|
||||
// Simulate a service persisted before the ARN was pinned.
|
||||
svc.setTaskDefinition("legacy-fam:1");
|
||||
|
||||
service.reconcileServices();
|
||||
service.reconcileServices();
|
||||
|
||||
assertEquals(1, runningTasks(service).size(), "the raw reference must not read as stale");
|
||||
assertEquals(rev1.getTaskDefinitionArn(), svc.getTaskDefinition());
|
||||
}
|
||||
|
||||
@Test
|
||||
void unchangedTaskDefinitionIsNotTouchedByTheReconciler() {
|
||||
EcsService service = newMockModeService();
|
||||
service.createCluster("steady-cluster", REGION);
|
||||
TaskDefinition rev1 = registerTaskDef(service, "steady-fam", "app:1");
|
||||
service.createService("steady-cluster", "steady-svc", rev1.getTaskDefinitionArn(), 2,
|
||||
LaunchType.FARGATE, List.of(), null, REGION);
|
||||
|
||||
service.reconcileServices();
|
||||
List<EcsTask> first = runningTasks(service);
|
||||
service.reconcileServices();
|
||||
List<EcsTask> second = runningTasks(service);
|
||||
|
||||
assertEquals(2, second.size());
|
||||
assertEquals(first.stream().map(EcsTask::getTaskArn).sorted().toList(),
|
||||
second.stream().map(EcsTask::getTaskArn).sorted().toList());
|
||||
}
|
||||
|
||||
private static List<EcsTask> runningTasks(EcsService service) {
|
||||
return service.describeTasks(null, service.listTasks(null, null, null, null, REGION), REGION).stream()
|
||||
.filter(t -> "RUNNING".equals(t.getLastStatus()))
|
||||
.toList();
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
private static EcsService newMockModeService() {
|
||||
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
|
||||
when(config.services().ecs().mock()).thenReturn(true);
|
||||
when(config.effectiveBaseUrl()).thenReturn("http://localhost:4566");
|
||||
EcsService service = new EcsService(
|
||||
new RegionResolver(REGION, "000000000000"),
|
||||
mock(EcsContainerManager.class),
|
||||
config,
|
||||
mock(EcsLoadBalancerRegistrar.class),
|
||||
new InMemoryStorageFactory());
|
||||
service.initializeStorage();
|
||||
return service;
|
||||
}
|
||||
|
||||
private static final class InMemoryStorageFactory extends StorageFactory {
|
||||
private final Map<String, StorageBackend<String, ?>> stores = new HashMap<>();
|
||||
|
||||
private InMemoryStorageFactory() {
|
||||
super(null, null);
|
||||
}
|
||||
|
||||
@Override
|
||||
@SuppressWarnings("unchecked")
|
||||
public <V> AccountAwareStorageBackend<V> create(String serviceName,
|
||||
String fileName,
|
||||
TypeReference<Map<String, V>> typeReference) {
|
||||
return (AccountAwareStorageBackend<V>) stores.computeIfAbsent(fileName,
|
||||
ignored -> AccountAwareStorageBackend.inMemory("000000000000"));
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user