fix(ecs): persist durable resources via StorageBackedMap (#1514)

Back clusters, task definitions, latest revisions, services, capacity
providers, attributes and account settings with StorageFactory-backed
maps so they survive a restart instead of living only in memory. Add
write-backs at in-place mutation sites (cluster config/counters, service
config/status, task-definition status, tags, attributes) so the periodic
flush captures them; transient runtime state (tasks, task sets,
deployments, container instances) stays in memory. Wire EcsStorageConfig
+ catalog descriptor + application.yml.
This commit is contained in:
Hector Ventura authored and GitHub committed 2026-06-22 23:18:39 -05:00
1 parent f725a38969
commit cc2cbb48e0
6 files changed
+248 -9

No files matched your search

@@ -177,6 +177,7 @@ public interface EmulatorConfig {
BatchStorageConfig batch();
CodePipelineStorageConfig codepipeline();
S3VectorsStorageConfig s3vectors();
EcsStorageConfig ecs();
}
interface SsmStorageConfig {
@@ -329,6 +330,13 @@ public interface EmulatorConfig {
long flushIntervalMs();
}
interface EcsStorageConfig {
Optional<String> mode();
@WithDefault("5000")
long flushIntervalMs();
}
interface WalConfig {
@WithDefault("30000")
long compactionIntervalMs();
@@ -206,7 +206,8 @@ public class ResolvedServiceCatalog {
protocols(ServiceProtocol.QUERY),
Set.of(), Set.of("ec2"), Set.of(), Set.of()),
descriptor("ecs", "ecs", config.services().ecs().enabled(), true,
null, null, 5000L, null, ServiceProtocol.JSON,
"ecs", storageMode(config.storage().services().ecs().mode(), config.storage().mode()),
config.storage().services().ecs().flushIntervalMs(), null, ServiceProtocol.JSON,
protocols(ServiceProtocol.JSON),
Set.of("AmazonEC2ContainerServiceV20141113."), Set.of("ecs"), Set.of(), Set.of()),
descriptor("appconfig", "appconfig", config.services().appconfig().enabled(), true,
@@ -1,8 +1,11 @@
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.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.StorageBackedMap;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.ecs.container.EcsContainerManager;
import io.github.hectorvent.floci.services.ecs.container.EcsTaskHandle;
import io.github.hectorvent.floci.services.ecs.model.Attribute;
@@ -37,6 +40,7 @@ import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.function.Function;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
@@ -53,27 +57,28 @@ public class EcsService {
private final RegionResolver regionResolver;
private final EcsContainerManager containerManager;
private final EcsLoadBalancerRegistrar lbRegistrar;
private final StorageFactory storageFactory;
private final boolean dockerMode;
private final String baseUrl;
private final ScheduledExecutorService reconciler = Executors.newSingleThreadScheduledExecutor(
r -> { Thread t = new Thread(r, "ecs-reconciler"); t.setDaemon(true); return t; });
// region::clusterName → EcsCluster
private final Map<String, EcsCluster> clusters = new ConcurrentHashMap<>();
private Map<String, EcsCluster> clusters = new ConcurrentHashMap<>();
// family:revision → TaskDefinition
private final Map<String, TaskDefinition> taskDefinitions = new ConcurrentHashMap<>();
private Map<String, TaskDefinition> taskDefinitions = new ConcurrentHashMap<>();
// family → latest revision number
private final Map<String, Integer> latestRevisions = new ConcurrentHashMap<>();
private Map<String, Integer> latestRevisions = new ConcurrentHashMap<>();
// taskArn → EcsTask
private final Map<String, EcsTask> tasks = new ConcurrentHashMap<>();
// taskArn → EcsTaskHandle (running containers)
private final Map<String, EcsTaskHandle> taskHandles = new ConcurrentHashMap<>();
// region::clusterName/serviceName → EcsServiceModel
private final Map<String, EcsServiceModel> services = new ConcurrentHashMap<>();
private Map<String, EcsServiceModel> services = new ConcurrentHashMap<>();
// region::clusterArn/instanceArn → ContainerInstance
private final Map<String, ContainerInstance> containerInstances = new ConcurrentHashMap<>();
// name → CapacityProvider (excludes built-ins FARGATE, FARGATE_SPOT)
private final Map<String, CapacityProvider> capacityProviders = new ConcurrentHashMap<>();
private Map<String, CapacityProvider> capacityProviders = new ConcurrentHashMap<>();
// taskSetArn → TaskSet
private final Map<String, TaskSet> taskSets = new ConcurrentHashMap<>();
// serviceDeploymentArn → ServiceDeployment
@@ -81,25 +86,77 @@ public class EcsService {
// serviceRevisionArn → ServiceRevision
private final Map<String, ServiceRevision> serviceRevisions = new ConcurrentHashMap<>();
// targetArn → List<Attribute>
private final Map<String, List<Attribute>> attributes = new ConcurrentHashMap<>();
private Map<String, List<Attribute>> attributes = new ConcurrentHashMap<>();
// name → value (account-level settings)
private final Map<String, String> accountSettings = new ConcurrentHashMap<>();
private Map<String, String> accountSettings = new ConcurrentHashMap<>();
@Inject
public EcsService(RegionResolver regionResolver, EcsContainerManager containerManager,
EmulatorConfig config, EcsLoadBalancerRegistrar lbRegistrar) {
EmulatorConfig config, EcsLoadBalancerRegistrar lbRegistrar,
StorageFactory storageFactory) {
this.regionResolver = regionResolver;
this.containerManager = containerManager;
this.dockerMode = !config.services().ecs().mock();
this.baseUrl = config.effectiveBaseUrl();
this.lbRegistrar = lbRegistrar;
this.storageFactory = storageFactory;
}
@PostConstruct
void init() {
initializeStorage();
reconciler.scheduleAtFixedRate(this::reconcile, 5, 5, TimeUnit.SECONDS);
}
void initializeStorage() {
if (storageFactory == null) {
return; // keeps non-CDI unit tests working
}
this.clusters = storageBacked("ecs-clusters.json",
new TypeReference<Map<String, EcsCluster>>() {});
this.taskDefinitions = storageBacked("ecs-task-definitions.json",
new TypeReference<Map<String, TaskDefinition>>() {});
this.latestRevisions = storageBacked("ecs-latest-revisions.json",
new TypeReference<Map<String, Integer>>() {});
this.services = storageBacked("ecs-services.json",
new TypeReference<Map<String, EcsServiceModel>>() {});
this.capacityProviders = storageBacked("ecs-capacity-providers.json",
new TypeReference<Map<String, CapacityProvider>>() {});
this.attributes = storageBacked("ecs-attributes.json",
new TypeReference<Map<String, List<Attribute>>>() {});
this.accountSettings = storageBacked("ecs-account-settings.json",
new TypeReference<Map<String, String>>() {});
}
private <V> Map<String, V> storageBacked(String fileName, TypeReference<Map<String, V>> typeReference) {
return new StorageBackedMap<>(storageFactory.create("ecs", fileName, typeReference));
}
/**
* Re-persists a durable entity whose fields were mutated in place. {@link StorageBackedMap}
* only flags the backend dirty on {@code put}/{@code remove}, so an in-place mutation of a
* value obtained via {@code get}/{@code values()} must be written back to be captured by the
* periodic flush. The entry is located by ARN so callers don't need to recompute its key.
*/
private static <V> void persistByArn(Map<String, V> map, V value, Function<V, String> arnFn) {
String arn = arnFn.apply(value);
if (arn == null) {
return;
}
for (Map.Entry<String, V> entry : map.entrySet()) {
if (arn.equals(arnFn.apply(entry.getValue()))) {
map.put(entry.getKey(), value);
return;
}
}
}
private void persistCluster(String region, EcsCluster cluster) {
if (cluster != null) {
clusters.put(clusterKey(region, cluster.getClusterName()), cluster);
}
}
@PreDestroy
void shutdown() {
reconciler.shutdownNow();
@@ -171,12 +228,14 @@ public class EcsService {
if (settings != null) {
cluster.setSettings(settings);
}
persistCluster(region, cluster);
return cluster;
}
public EcsCluster updateClusterSettings(String clusterRef, List<ClusterSetting> settings, String region) {
EcsCluster cluster = resolveClusterOrThrow(clusterRef, region);
cluster.setSettings(settings);
persistCluster(region, cluster);
return cluster;
}
@@ -185,6 +244,7 @@ public class EcsService {
EcsCluster cluster = resolveClusterOrThrow(clusterRef, region);
cluster.setCapacityProviders(providers);
cluster.setDefaultCapacityProviderStrategy(defaultStrategy);
persistCluster(region, cluster);
return cluster;
}
@@ -329,6 +389,7 @@ public class EcsService {
public TaskDefinition deregisterTaskDefinition(String taskDefinitionRef, String region) {
TaskDefinition td = resolveTaskDefinitionOrThrow(taskDefinitionRef, region);
td.setStatus("INACTIVE");
taskDefinitions.put(td.getFamily() + ":" + td.getRevision(), td);
return td;
}
@@ -429,6 +490,7 @@ public class EcsService {
launched.add(task);
}
persistCluster(region, cluster);
return launched;
}
@@ -465,6 +527,7 @@ public class EcsService {
EcsCluster cluster = resolveClusterByArn(task.getClusterArn());
if (cluster != null && cluster.getRunningTasksCount() > 0) {
cluster.setRunningTasksCount(cluster.getRunningTasksCount() - 1);
persistCluster(region, cluster);
}
LOG.infov("Stopped ECS task: {0}", task.getTaskArn());
@@ -604,6 +667,7 @@ public class EcsService {
services.put(key, svc);
cluster.setActiveServicesCount(cluster.getActiveServicesCount() + 1);
persistCluster(region, cluster);
recordServiceDeployment(svc, taskDefinition, region);
LOG.infov("Created ECS service: {0} in cluster {1}", serviceName, cluster.getClusterName());
return svc;
@@ -639,6 +703,7 @@ public class EcsService {
svc.setTaskDefinition(taskDefinition);
recordServiceDeployment(svc, taskDefinition, region);
}
services.put(key, svc);
return svc;
}
@@ -662,6 +727,8 @@ public class EcsService {
svc.setStatus("INACTIVE");
svc.setDesiredCount(0);
cluster.setActiveServicesCount(Math.max(0, cluster.getActiveServicesCount() - 1));
services.put(key, svc);
persistCluster(region, cluster);
// Stop tasks before removing the service from the map, so the per-task
// ELBv2 deregistration hook can still resolve the service's loadBalancers.
tasks.values().stream()
@@ -765,6 +832,7 @@ public class EcsService {
else if (resource instanceof EcsServiceModel s) { s.getTags().putAll(tags); }
else if (resource instanceof ContainerInstance ci) { ci.getTags().putAll(tags); }
else if (resource instanceof CapacityProvider cp) { cp.getTags().putAll(tags); }
persistTaggedResource(resource);
}
private void removeTagsFromResource(Object resource, List<String> tagKeys) {
@@ -774,6 +842,19 @@ public class EcsService {
else if (resource instanceof EcsServiceModel s) { tagKeys.forEach(s.getTags()::remove); }
else if (resource instanceof ContainerInstance ci) { tagKeys.forEach(ci.getTags()::remove); }
else if (resource instanceof CapacityProvider cp) { tagKeys.forEach(cp.getTags()::remove); }
persistTaggedResource(resource);
}
/** Writes back a tag mutation to the owning durable map. Tasks and container instances are
* transient (not persisted), so they need no write-back. */
private void persistTaggedResource(Object resource) {
switch (resource) {
case EcsCluster c -> persistByArn(clusters, c, EcsCluster::getClusterArn);
case TaskDefinition td -> persistByArn(taskDefinitions, td, TaskDefinition::getTaskDefinitionArn);
case EcsServiceModel s -> persistByArn(services, s, EcsServiceModel::getServiceArn);
case CapacityProvider cp -> persistByArn(capacityProviders, cp, CapacityProvider::getCapacityProviderArn);
default -> { /* EcsTask / ContainerInstance are transient */ }
}
}
private Map<String, String> getTagsFromResource(Object resource) {
@@ -821,6 +902,7 @@ public class EcsService {
List<Attribute> existing = attributes.computeIfAbsent(targetId, k -> new ArrayList<>());
existing.removeIf(a -> a.name().equals(attr.name()));
existing.add(attr);
attributes.put(targetId, existing);
stored.add(attr);
}
return stored;
@@ -839,6 +921,11 @@ public class EcsService {
}
return false;
});
if (existing.isEmpty()) {
attributes.remove(targetId);
} else {
attributes.put(targetId, existing);
}
}
}
return deleted;
@@ -876,6 +963,7 @@ public class EcsService {
String key = containerInstanceKey(cluster.getClusterArn(), instanceArn);
containerInstances.put(key, instance);
cluster.setRegisteredContainerInstancesCount(cluster.getRegisteredContainerInstancesCount() + 1);
persistCluster(region, cluster);
LOG.infov("Registered container instance: {0} in cluster {1}", instanceArn, cluster.getClusterName());
return instance;
}
@@ -901,6 +989,7 @@ public class EcsService {
instance.setStatus("INACTIVE");
cluster.setRegisteredContainerInstancesCount(
Math.max(0, cluster.getRegisteredContainerInstancesCount() - 1));
persistCluster(region, cluster);
return instance;
}
@@ -968,6 +1057,7 @@ public class EcsService {
public CapacityProvider updateCapacityProvider(String name, Map<String, Object> asgProvider) {
CapacityProvider cp = resolveCapacityProviderOrThrow(name);
cp.setAutoScalingGroupProvider(asgProvider);
capacityProviders.put(cp.getName(), cp);
return cp;
}