diff --git a/docs/services/ecs.md b/docs/services/ecs.md index 1860880184..639d932cff 100644 --- a/docs/services/ecs.md +++ b/docs/services/ecs.md @@ -30,6 +30,12 @@ ECS emulates clusters, task definitions, tasks, and services. In the default con | `DeregisterTaskDefinition` | Mark a revision INACTIVE | | `DeleteTaskDefinitions` | Delete one or more task definitions | +`runtimePlatform` and a container's `logConfiguration` are stored and returned exactly as +registered, so a client that reads back what it wrote (Terraform, or a deploy tool verifying its +own `RegisterTaskDefinition`) sees no drift. Neither changes how a local task runs: Floci launches +every task on the host's own architecture, and a task's output stays with its Docker container +rather than being routed to the configured log driver. + ### Tasks | Operation | Description | 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 7d3eb0288a..08de0bdb00 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 @@ -17,12 +17,14 @@ 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.KeyValuePair; import io.github.hectorvent.floci.services.ecs.model.LaunchType; +import io.github.hectorvent.floci.services.ecs.model.LogConfiguration; import io.github.hectorvent.floci.services.ecs.model.MountPoint; import io.github.hectorvent.floci.services.ecs.model.NetworkBinding; import io.github.hectorvent.floci.services.ecs.model.NetworkConfiguration; import io.github.hectorvent.floci.services.ecs.model.NetworkMode; import io.github.hectorvent.floci.services.ecs.model.PortMapping; import io.github.hectorvent.floci.services.ecs.model.ProtectedTask; +import io.github.hectorvent.floci.services.ecs.model.RuntimePlatform; import io.github.hectorvent.floci.services.ecs.model.ServiceDeployment; import io.github.hectorvent.floci.services.ecs.model.ServiceRevision; import io.github.hectorvent.floci.services.ecs.model.Secret; @@ -40,6 +42,7 @@ import jakarta.ws.rs.core.Response; import java.util.ArrayList; import java.util.HashMap; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @@ -216,9 +219,12 @@ public class EcsJsonHandler { TaskDefinition td = service.registerTaskDefinition(family, containerDefs, networkMode, cpu, memory, taskRoleArn, executionRoleArn, requiresCompatibilities, tags, region); - // Task-level volumes are not part of registerTaskDefinition's signature; set them on the - // returned (and stored) task definition so they round-trip and reach RunTask launches. + // Task-level volumes and runtimePlatform are not part of registerTaskDefinition's signature; + // set them on the returned (and stored) task definition so they round-trip and reach RunTask + // launches, then write the mutated definition back so it also survives a restart. td.setVolumes(parseVolumes(req.path("volumes"))); + td.setRuntimePlatform(parseRuntimePlatform(req.path("runtimePlatform"))); + service.persistTaskDefinition(td); ObjectNode resp = objectMapper.createObjectNode(); resp.set("taskDefinition", taskDefinitionNode(td)); @@ -935,6 +941,17 @@ public class EcsJsonHandler { if (td.getMemory() != null) { n.put("memory", td.getMemory()); } if (td.getTaskRoleArn() != null) { n.put("taskRoleArn", td.getTaskRoleArn()); } if (td.getExecutionRoleArn() != null) { n.put("executionRoleArn", td.getExecutionRoleArn()); } + if (td.getRuntimePlatform() != null) { + RuntimePlatform platform = td.getRuntimePlatform(); + ObjectNode platformNode = objectMapper.createObjectNode(); + if (platform.cpuArchitecture() != null) { + platformNode.put("cpuArchitecture", platform.cpuArchitecture()); + } + if (platform.operatingSystemFamily() != null) { + platformNode.put("operatingSystemFamily", platform.operatingSystemFamily()); + } + n.set("runtimePlatform", platformNode); + } if (td.getRequiresCompatibilities() != null && !td.getRequiresCompatibilities().isEmpty()) { ArrayNode arr = objectMapper.createArrayNode(); td.getRequiresCompatibilities().forEach(arr::add); @@ -1052,6 +1069,30 @@ public class EcsJsonHandler { n.set("mountPoints", mps); } + if (def.getLogConfiguration() != null) { + LogConfiguration logConfig = def.getLogConfiguration(); + ObjectNode logNode = objectMapper.createObjectNode(); + if (logConfig.logDriver() != null) { + logNode.put("logDriver", logConfig.logDriver()); + } + if (logConfig.options() != null) { + ObjectNode options = objectMapper.createObjectNode(); + logConfig.options().forEach(options::put); + logNode.set("options", options); + } + if (logConfig.secretOptions() != null) { + ArrayNode secretOptions = objectMapper.createArrayNode(); + for (Secret secret : logConfig.secretOptions()) { + ObjectNode secretNode = objectMapper.createObjectNode(); + secretNode.put("name", secret.name()); + secretNode.put("valueFrom", secret.valueFrom()); + secretOptions.add(secretNode); + } + logNode.set("secretOptions", secretOptions); + } + n.set("logConfiguration", logNode); + } + return n; } @@ -1324,6 +1365,7 @@ public class EcsJsonHandler { def.setSecrets(parseSecrets(item.path("secrets"))); } def.setMountPoints(parseMountPoints(item.path("mountPoints"))); + def.setLogConfiguration(parseLogConfiguration(item.path("logConfiguration"))); if (item.has("command") && item.path("command").isArray()) { List cmd = new ArrayList<>(); @@ -1377,6 +1419,37 @@ public class EcsJsonHandler { return result; } + private RuntimePlatform parseRuntimePlatform(JsonNode node) { + if (node == null || !node.isObject()) { + return null; + } + String cpuArchitecture = node.path("cpuArchitecture").asText(null); + String operatingSystemFamily = node.path("operatingSystemFamily").asText(null); + if (cpuArchitecture == null && operatingSystemFamily == null) { + return null; + } + return new RuntimePlatform(cpuArchitecture, operatingSystemFamily); + } + + private LogConfiguration parseLogConfiguration(JsonNode node) { + if (node == null || !node.isObject()) { + return null; + } + String logDriver = node.path("logDriver").asText(null); + if (logDriver == null) { + return null; + } + Map options = null; + if (node.path("options").isObject()) { + Map parsed = new LinkedHashMap<>(); + node.path("options").fields() + .forEachRemaining(entry -> parsed.put(entry.getKey(), entry.getValue().asText())); + options = parsed; + } + List secretOptions = node.has("secretOptions") ? parseSecrets(node.path("secretOptions")) : null; + return new LogConfiguration(logDriver, options, secretOptions); + } + private List parseVolumes(JsonNode node) { List result = new ArrayList<>(); if (!node.isArray()) { 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 e7649471e5..a1b6257ec8 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 @@ -402,6 +402,15 @@ public class EcsService implements ContainerTeardown { } } + /** + * Writes back a task definition mutated after {@link #registerTaskDefinition} returned it. + * A backend that serializes on {@code put} (persistent, hybrid, WAL) stored the value as it was + * at registration, so fields set on the returned instance need this to survive a restart. + */ + public void persistTaskDefinition(TaskDefinition td) { + taskDefinitions.put(td.getFamily() + ":" + td.getRevision(), td); + } + public TaskDefinition describeTaskDefinition(String taskDefinitionRef, String region) { return resolveTaskDefinitionOrThrow(taskDefinitionRef, region); } diff --git a/src/main/java/io/github/hectorvent/floci/services/ecs/model/ContainerDefinition.java b/src/main/java/io/github/hectorvent/floci/services/ecs/model/ContainerDefinition.java index ab76fe09c1..8a18ef9d34 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ecs/model/ContainerDefinition.java +++ b/src/main/java/io/github/hectorvent/floci/services/ecs/model/ContainerDefinition.java @@ -19,6 +19,7 @@ public class ContainerDefinition { private List command; private List entryPoint; private List mountPoints; + private LogConfiguration logConfiguration; public String getName() { return name; } public void setName(String name) { this.name = name; } @@ -55,4 +56,7 @@ public class ContainerDefinition { public List getMountPoints() { return mountPoints; } public void setMountPoints(List mountPoints) { this.mountPoints = mountPoints; } + + public LogConfiguration getLogConfiguration() { return logConfiguration; } + public void setLogConfiguration(LogConfiguration logConfiguration) { this.logConfiguration = logConfiguration; } } diff --git a/src/main/java/io/github/hectorvent/floci/services/ecs/model/LogConfiguration.java b/src/main/java/io/github/hectorvent/floci/services/ecs/model/LogConfiguration.java new file mode 100644 index 0000000000..7a9c6c251f --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/ecs/model/LogConfiguration.java @@ -0,0 +1,18 @@ +package io.github.hectorvent.floci.services.ecs.model; + +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.util.List; +import java.util.Map; + +/** + * The {@code logConfiguration} of an ECS container definition: + * {@code {"logDriver": "awslogs", "options": {...}, "secretOptions": [{"name": ..., "valueFrom": ...}]}}. + * + *

Modelled for RegisterTaskDefinition/DescribeTaskDefinition round-trip fidelity. Floci does not + * route container output to the configured driver — a local task's logs stay with its Docker + * container — so the {@code awslogs} options are stored and returned rather than acted upon. + */ +@RegisterForReflection +public record LogConfiguration(String logDriver, Map options, List secretOptions) { +} diff --git a/src/main/java/io/github/hectorvent/floci/services/ecs/model/RuntimePlatform.java b/src/main/java/io/github/hectorvent/floci/services/ecs/model/RuntimePlatform.java new file mode 100644 index 0000000000..edb213ef44 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/ecs/model/RuntimePlatform.java @@ -0,0 +1,16 @@ +package io.github.hectorvent.floci.services.ecs.model; + +import io.quarkus.runtime.annotations.RegisterForReflection; + +/** + * The {@code runtimePlatform} of an ECS task definition: + * {@code {"cpuArchitecture": "X86_64"|"ARM64", "operatingSystemFamily": "LINUX"|"WINDOWS_SERVER_*"}}. + * + *

Modelled for RegisterTaskDefinition/DescribeTaskDefinition round-trip fidelity — a client that + * reads back what it registered (Terraform, or a deploy tool verifying its own write) must see the + * platform it asked for. Floci runs every task on the host's own architecture, so the value has no + * effect on where a local task is placed. + */ +@RegisterForReflection +public record RuntimePlatform(String cpuArchitecture, String operatingSystemFamily) { +} diff --git a/src/main/java/io/github/hectorvent/floci/services/ecs/model/TaskDefinition.java b/src/main/java/io/github/hectorvent/floci/services/ecs/model/TaskDefinition.java index 08e1b3b5ba..3b3e9ae625 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ecs/model/TaskDefinition.java +++ b/src/main/java/io/github/hectorvent/floci/services/ecs/model/TaskDefinition.java @@ -20,6 +20,7 @@ public class TaskDefinition { private String executionRoleArn; private List containerDefinitions; private List volumes; + private RuntimePlatform runtimePlatform; private List requiresCompatibilities; private List compatibilities; private Map tags = new HashMap<>(); @@ -59,6 +60,9 @@ public class TaskDefinition { public List getVolumes() { return volumes; } public void setVolumes(List volumes) { this.volumes = volumes; } + public RuntimePlatform getRuntimePlatform() { return runtimePlatform; } + public void setRuntimePlatform(RuntimePlatform runtimePlatform) { this.runtimePlatform = runtimePlatform; } + public List getRequiresCompatibilities() { return requiresCompatibilities; } public void setRequiresCompatibilities(List requiresCompatibilities) { this.requiresCompatibilities = requiresCompatibilities; } diff --git a/src/test/java/io/github/hectorvent/floci/services/ecs/EcsIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ecs/EcsIntegrationTest.java index ff9690c28e..f358b52776 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ecs/EcsIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ecs/EcsIntegrationTest.java @@ -563,6 +563,82 @@ class EcsIntegrationTest { .body("taskArns", empty()); } + @Test + @Order(25) + void registerTaskDefinitionRoundTripsRuntimePlatformAndLogConfiguration() { + String platformTaskDefArn = ecs("RegisterTaskDefinition") + .body(""" + { + "family": "task-with-runtime-platform", + "requiresCompatibilities": ["FARGATE"], + "networkMode": "awsvpc", + "cpu": "256", + "memory": "512", + "runtimePlatform": {"cpuArchitecture": "ARM64", "operatingSystemFamily": "LINUX"}, + "containerDefinitions": [ + { + "name": "app", + "image": "nginx:latest", + "essential": true, + "logConfiguration": { + "logDriver": "awslogs", + "options": { + "awslogs-group": "/ecs/task-with-runtime-platform", + "awslogs-region": "%s", + "awslogs-stream-prefix": "ecs" + }, + "secretOptions": [] + } + } + ] + } + """.formatted(REGION)) + .when() + .post("/") + .then() + .statusCode(200) + .body("taskDefinition.runtimePlatform.cpuArchitecture", equalTo("ARM64")) + .body("taskDefinition.runtimePlatform.operatingSystemFamily", equalTo("LINUX")) + .body("taskDefinition.containerDefinitions[0].logConfiguration.logDriver", equalTo("awslogs")) + .body("taskDefinition.containerDefinitions[0].logConfiguration.options.'awslogs-group'", + equalTo("/ecs/task-with-runtime-platform")) + .body("taskDefinition.containerDefinitions[0].logConfiguration.options.'awslogs-region'", equalTo(REGION)) + .body("taskDefinition.containerDefinitions[0].logConfiguration.options.'awslogs-stream-prefix'", equalTo("ecs")) + .extract() + .path("taskDefinition.taskDefinitionArn"); + + ecs("DescribeTaskDefinition") + .body(""" + {"taskDefinition": "%s"} + """.formatted(platformTaskDefArn)) + .when() + .post("/") + .then() + .statusCode(200) + .body("taskDefinition.runtimePlatform.cpuArchitecture", equalTo("ARM64")) + .body("taskDefinition.runtimePlatform.operatingSystemFamily", equalTo("LINUX")) + .body("taskDefinition.containerDefinitions[0].logConfiguration.logDriver", equalTo("awslogs")) + .body("taskDefinition.containerDefinitions[0].logConfiguration.options.'awslogs-group'", + equalTo("/ecs/task-with-runtime-platform")) + .body("taskDefinition.containerDefinitions[0].logConfiguration.options.'awslogs-region'", equalTo(REGION)) + .body("taskDefinition.containerDefinitions[0].logConfiguration.options.'awslogs-stream-prefix'", equalTo("ecs")); + } + + @Test + @Order(26) + void describeTaskDefinitionWithoutRuntimePlatformOrLogConfigurationOmitsBothKeys() { + ecs("DescribeTaskDefinition") + .body(""" + {"taskDefinition": "%s:1"} + """.formatted(TASK_DEF_FAMILY)) + .when() + .post("/") + .then() + .statusCode(200) + .body("taskDefinition", not(hasKey("runtimePlatform"))) + .body("taskDefinition.containerDefinitions[0]", not(hasKey("logConfiguration"))); + } + // ── Services ────────────────────────────────────────────────────────────── @Test diff --git a/src/test/java/io/github/hectorvent/floci/services/ecs/EcsJsonHandlerRuntimePlatformLogConfigurationTest.java b/src/test/java/io/github/hectorvent/floci/services/ecs/EcsJsonHandlerRuntimePlatformLogConfigurationTest.java new file mode 100644 index 0000000000..b17eed954c --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/ecs/EcsJsonHandlerRuntimePlatformLogConfigurationTest.java @@ -0,0 +1,148 @@ +package io.github.hectorvent.floci.services.ecs; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.github.hectorvent.floci.services.ecs.model.TaskDefinition; +import jakarta.ws.rs.core.Response; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.List; + +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.mock; +import static org.mockito.Mockito.when; + +/** + * Unit tests for the RegisterTaskDefinition JSON wire path in {@link EcsJsonHandler}: + * the task-level {@code runtimePlatform} and per-container {@code logConfiguration} must be + * parsed from the request, stored on the task definition, and serialized back in the response + * with the AWS wire shape — and must stay absent from the response when the request omitted + * them, so existing callers see no new keys. + * + *

{@link EcsService} is mocked to echo the parsed container definitions back inside a + * task definition, so the test exercises parse + serialize without any Docker/Quarkus context. + */ +class EcsJsonHandlerRuntimePlatformLogConfigurationTest { + + private ObjectMapper objectMapper; + private EcsJsonHandler handler; + + @BeforeEach + void setUp() { + objectMapper = new ObjectMapper(); + EcsService service = mock(EcsService.class); + when(service.registerTaskDefinition(anyString(), any(), any(), any(), any(), any(), any(), any(), any(), anyString())) + .thenAnswer(inv -> { + TaskDefinition td = new TaskDefinition(); + td.setFamily(inv.getArgument(0)); + td.setRevision(1); + td.setStatus("ACTIVE"); + td.setContainerDefinitions(inv.getArgument(1, List.class)); + return td; + }); + + handler = new EcsJsonHandler(service, objectMapper); + } + + @Test + void registerTaskDefinitionRoundTripsRuntimePlatformAndLogConfiguration() throws Exception { + String requestJson = """ + { + "family": "arm-family", + "runtimePlatform": {"cpuArchitecture": "ARM64", "operatingSystemFamily": "LINUX"}, + "containerDefinitions": [ + { + "name": "app", + "image": "alpine:latest", + "logConfiguration": { + "logDriver": "awslogs", + "options": { + "awslogs-group": "/ecs/arm-family", + "awslogs-region": "us-east-1", + "awslogs-stream-prefix": "ecs" + }, + "secretOptions": [ + {"name": "splunk-token", "valueFrom": "arn:aws:ssm:us-east-1:000000000000:parameter/splunk"} + ] + } + } + ] + } + """; + JsonNode request = objectMapper.readTree(requestJson); + + Response response = handler.handle("RegisterTaskDefinition", request, "us-east-1"); + JsonNode td = objectMapper.valueToTree(response.getEntity()).path("taskDefinition"); + + JsonNode platform = td.path("runtimePlatform"); + assertEquals("ARM64", platform.path("cpuArchitecture").asText()); + assertEquals("LINUX", platform.path("operatingSystemFamily").asText()); + + JsonNode logConfig = td.path("containerDefinitions").get(0).path("logConfiguration"); + assertEquals("awslogs", logConfig.path("logDriver").asText()); + assertEquals("/ecs/arm-family", logConfig.path("options").path("awslogs-group").asText()); + assertEquals("us-east-1", logConfig.path("options").path("awslogs-region").asText()); + assertEquals("ecs", logConfig.path("options").path("awslogs-stream-prefix").asText()); + JsonNode secretOptions = logConfig.path("secretOptions"); + assertTrue(secretOptions.isArray() && secretOptions.size() == 1, "one secretOption expected"); + assertEquals("splunk-token", secretOptions.get(0).path("name").asText()); + assertEquals("arn:aws:ssm:us-east-1:000000000000:parameter/splunk", + secretOptions.get(0).path("valueFrom").asText()); + } + + @Test + void registerTaskDefinitionSerializesOnlyTheRuntimePlatformKeysThatWereSent() throws Exception { + String requestJson = """ + { + "family": "arch-only-family", + "runtimePlatform": {"cpuArchitecture": "X86_64"}, + "containerDefinitions": [ + { + "name": "app", + "image": "alpine:latest", + "logConfiguration": {"logDriver": "json-file"} + } + ] + } + """; + JsonNode request = objectMapper.readTree(requestJson); + + Response response = handler.handle("RegisterTaskDefinition", request, "us-east-1"); + JsonNode td = objectMapper.valueToTree(response.getEntity()).path("taskDefinition"); + + JsonNode platform = td.path("runtimePlatform"); + assertEquals("X86_64", platform.path("cpuArchitecture").asText()); + assertTrue(platform.path("operatingSystemFamily").isMissingNode(), + "operatingSystemFamily must not be invented when the request omitted it"); + + JsonNode logConfig = td.path("containerDefinitions").get(0).path("logConfiguration"); + assertEquals("json-file", logConfig.path("logDriver").asText()); + assertTrue(logConfig.path("options").isMissingNode(), "options must not be emitted when omitted"); + assertTrue(logConfig.path("secretOptions").isMissingNode(), "secretOptions must not be emitted when omitted"); + } + + @Test + void registerTaskDefinitionWithoutRuntimePlatformOrLogConfigurationEmitsNeitherKey() throws Exception { + String requestJson = """ + { + "family": "plain-family", + "containerDefinitions": [ + {"name": "app", "image": "alpine:latest"} + ] + } + """; + JsonNode request = objectMapper.readTree(requestJson); + + Response response = handler.handle("RegisterTaskDefinition", request, "us-east-1"); + JsonNode td = objectMapper.valueToTree(response.getEntity()).path("taskDefinition"); + + assertTrue(td.path("runtimePlatform").isMissingNode(), + "runtimePlatform must stay absent for a task definition that never set it"); + assertTrue(td.path("containerDefinitions").get(0).path("logConfiguration").isMissingNode(), + "logConfiguration must stay absent for a container that never set it"); + } +} 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 new file mode 100644 index 0000000000..1aa6b8b2a3 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/ecs/EcsJsonHandlerTaskDefinitionPersistenceTest.java @@ -0,0 +1,124 @@ +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.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.TaskDefinition; +import jakarta.ws.rs.core.Response; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import java.nio.file.Path; +import java.util.HashMap; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.mockito.Mockito.RETURNS_DEEP_STUBS; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** + * RegisterTaskDefinition sets {@code volumes} and {@code runtimePlatform} on the task definition + * after {@link EcsService#registerTaskDefinition} has already stored it. A storage backend + * that serializes on {@code put} (persistent, hybrid, WAL) captured the pre-mutation value, so + * without an explicit write-back those fields are lost on restart. + * + *

Backed by a real {@link PersistentStorage} over a temp directory, so a second service instance + * reloads from the file the first one wrote — the in-memory backend used elsewhere keeps the live + * object reference and cannot detect the miss. + */ +class EcsJsonHandlerTaskDefinitionPersistenceTest { + + private static final String REGION = "us-east-1"; + + @Test + void taskDefinitionFieldsSetAfterRegistrationSurviveRestart(@TempDir Path dataDir) throws Exception { + FileStorageFactory storage = new FileStorageFactory(dataDir); + ObjectMapper objectMapper = new ObjectMapper(); + + EcsJsonHandler handler = new EcsJsonHandler(serviceWithStorage(storage), objectMapper); + JsonNode request = objectMapper.readTree(""" + { + "family": "restart-family", + "runtimePlatform": {"cpuArchitecture": "ARM64", "operatingSystemFamily": "LINUX"}, + "containerDefinitions": [ + { + "name": "app", + "image": "alpine:latest", + "mountPoints": [{"sourceVolume": "data", "containerPath": "/data", "readOnly": false}], + "logConfiguration": { + "logDriver": "awslogs", + "options": {"awslogs-group": "/ecs/restart-family"} + } + } + ], + "volumes": [{"name": "data", "host": {"sourcePath": "/host/data"}}] + } + """); + Response response = handler.handle("RegisterTaskDefinition", request, REGION); + assertEquals(200, response.getStatus()); + + // Simulate a restart: a fresh service reloading from the files the first one wrote. + EcsService reloaded = serviceWithStorage(new FileStorageFactory(dataDir)); + TaskDefinition td = reloaded.describeTaskDefinition("restart-family:1", REGION); + + assertNotNull(td.getRuntimePlatform(), "runtimePlatform must survive a restart"); + assertEquals("ARM64", td.getRuntimePlatform().cpuArchitecture()); + assertEquals("LINUX", td.getRuntimePlatform().operatingSystemFamily()); + + var logConfiguration = td.getContainerDefinitions().getFirst().getLogConfiguration(); + assertNotNull(logConfiguration, "logConfiguration must survive a restart"); + assertEquals("awslogs", logConfiguration.logDriver()); + assertEquals("/ecs/restart-family", logConfiguration.options().get("awslogs-group")); + + assertEquals(1, td.getVolumes().size(), "task-level volumes must survive a restart"); + assertEquals("/host/data", td.getVolumes().getFirst().hostSourcePath()); + } + + private static EcsService serviceWithStorage(StorageFactory storage) { + 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), + storage); + service.initializeStorage(); + return service; + } + + /** Backs every store with a real {@link PersistentStorage} file, so values are serialized on put. */ + private static final class FileStorageFactory extends StorageFactory { + + private final Path dataDir; + private final Map> stores = new HashMap<>(); + + private FileStorageFactory(Path dataDir) { + super(null, null); + this.dataDir = dataDir; + } + + @Override + @SuppressWarnings("unchecked") + public AccountAwareStorageBackend create(String serviceName, + String fileName, + TypeReference> typeReference) { + return (AccountAwareStorageBackend) stores.computeIfAbsent(fileName, ignored -> { + PersistentStorage persistent = + new PersistentStorage<>(dataDir.resolve(fileName), typeReference); + persistent.load(); + return new AccountAwareStorageBackend<>(persistent, null, "000000000000"); + }); + } + } +}