feat(ecs): serve the task metadata endpoint v4 (#4120)

An application in an ECS task, the AWS SDK integrations that read task
identity, and the aws-for-fluent-bit init process all expect
ECS_CONTAINER_METADATA_URI_V4 to resolve. Under Floci it was never set,
so any of them fell back or failed.

AWS serves the endpoint on the link-local address 169.254.170.2, which a
local container cannot be given. Floci serves the same paths on its own
port instead: clients read the environment variable rather than the
address, so nothing has to know the difference.

The id is minted per container before the container is created, the way
the ECS agent mints one, because the container's own environment has to
carry the URI and so it cannot be derived from the Docker id the daemon
returns afterwards. EcsService.findByMetadataId resolves an id back to
its container and task.

The task document carries Cluster, TaskARN, Family, Revision, the
statuses, Limits in vCPUs, the pull timestamps, AvailabilityZone,
LaunchType, ServiceName for a service's task, VPCID for an EC2 task,
and, on Fargate, ClockDrift and EphemeralStorageMetrics. Floci has no
clock drift and does not meter the disk, so those report a synchronized
clock and zero usage. An awsvpc container's Networks object describes
the task ENI and the subnet it sits in; a local ENI has no DHCP option
set behind it, so the gateway, the resolver and the search domain are
derived the way a real VPC assigns them.

The stats paths read the daemon when the request arrives and return
Docker's own ContainerStats document, plus the network_rate_stats the
agent adds. Docker reports cumulative counters only, so the rates are a
delta across two consecutive samples, which is also why AWS documents a
container as having to run for about a second before its stats appear. A
container with no running Docker container behind it reports an empty
document rather than an error.

Because that pair costs a collection tick, task/stats samples the task's
containers in one pass: every stream is opened before any of them is
waited on, and the waits share one deadline. A sidecar polls that path
for network metrics, so the response has to cost about one tick however
many containers the task has, not one tick per container.
This commit is contained in:
Abhigya authored and GitHub committed 2026-09-22 08:18:55 -04:00
1 parent 93f8d1421a
commit 7cd441231f
12 files changed
+1918 -7

No files matched your search

@@ -0,0 +1,397 @@
package io.github.hectorvent.floci.services.ecs;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.ec2.Ec2Service;
import io.github.hectorvent.floci.services.ec2.model.Subnet;
import io.github.hectorvent.floci.services.ec2.model.Vpc;
import io.github.hectorvent.floci.services.ecs.container.EcsContainerManager;
import io.github.hectorvent.floci.services.ecs.model.AwsVpcConfiguration;
import io.github.hectorvent.floci.services.ecs.model.Container;
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.EphemeralStorage;
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.NetworkConfiguration;
import io.github.hectorvent.floci.services.ecs.model.NetworkMode;
import io.github.hectorvent.floci.services.ecs.model.TaskDefinition;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.json.JsonMapper;
import com.github.dockerjava.api.model.Statistics;
import jakarta.ws.rs.core.Response;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.time.Instant;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.anyList;
import static org.mockito.ArgumentMatchers.anyMap;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* The task metadata endpoint's response shapes. A workload reads these through
* {@code ECS_CONTAINER_METADATA_URI_V4} expecting AWS's exact PascalCase members, so the mapping
* from Floci's task model onto them is what this pins down.
*/
class EcsTaskMetadataControllerTest {
private static final String METADATA_ID = "9e2b1f0c4d5e4a1b8c7d6e5f4a3b2c1d";
private static final String TASK_ARN =
"arn:aws:ecs:us-east-1:000000000000:task/metadata-cluster/abc123";
private ObjectMapper objectMapper;
private EcsService service;
private EcsContainerManager containerManager;
private Ec2Service ec2Service;
private EcsTask task;
private EcsTaskMetadataController controller;
@BeforeEach
void setUp() {
objectMapper = new ObjectMapper();
service = mock(EcsService.class);
containerManager = mock(EcsContainerManager.class);
ec2Service = mock(Ec2Service.class);
when(containerManager.sampleContainerStats(anyString())).thenReturn(Optional.empty());
when(containerManager.sampleContainerStats(anyList())).thenReturn(Map.of());
when(ec2Service.describeSubnets(anyString(), anyList(), anyMap())).thenReturn(List.of(subnet()));
when(ec2Service.describeVpcs(anyString(), anyList(), anyMap())).thenReturn(List.of(vpc()));
task = task();
TaskDefinition taskDef = taskDefinition();
when(service.findByMetadataId(anyString())).thenAnswer(inv ->
METADATA_ID.equals(inv.getArgument(0))
? Optional.of(new EcsService.MetadataTarget(task,
task.getContainers().getFirst(), taskDef))
: Optional.empty());
controller = new EcsTaskMetadataController(service, containerManager, ec2Service, objectMapper);
}
private static Subnet subnet() {
Subnet subnet = new Subnet();
subnet.setSubnetId("subnet-default-us-east-1-a");
subnet.setVpcId("vpc-0a1b2c3d");
subnet.setCidrBlock("172.31.32.0/20");
subnet.setAvailabilityZone("us-east-1a");
return subnet;
}
private static Vpc vpc() {
Vpc vpc = new Vpc();
vpc.setVpcId("vpc-0a1b2c3d");
vpc.setCidrBlock("172.31.0.0/16");
return vpc;
}
private static EcsTask task() {
EcsTask task = new EcsTask();
task.setTaskArn(TASK_ARN);
task.setClusterArn("arn:aws:ecs:us-east-1:000000000000:cluster/metadata-cluster");
task.setTaskDefinitionArn("arn:aws:ecs:us-east-1:000000000000:task-definition/web:3");
task.setLastStatus("RUNNING");
task.setDesiredStatus("RUNNING");
task.setLaunchType(LaunchType.FARGATE);
task.setPlatformVersion("1.4.0");
task.setPlatformFamily("Linux");
task.setCpu("256");
task.setMemory("512");
task.setEphemeralStorage(new EphemeralStorage(20));
task.setAvailabilityZone("us-east-1a");
task.setCreatedAt(Instant.parse("2026-01-01T10:00:00Z"));
task.setStartedAt(Instant.parse("2026-01-01T10:00:05Z"));
task.setPullStartedAt(Instant.parse("2026-01-01T10:00:01Z"));
task.setPullStoppedAt(Instant.parse("2026-01-01T10:00:04Z"));
task.setPrivateIpAddress("172.31.0.42");
task.setMacAddress("0e:98:9f:33:76:d3");
task.setPrivateDnsName("ip-172-31-0-42.ec2.internal");
AwsVpcConfiguration awsvpc = new AwsVpcConfiguration();
awsvpc.setSubnets(List.of("subnet-default-us-east-1-a"));
NetworkConfiguration networkConfiguration = new NetworkConfiguration();
networkConfiguration.setAwsvpcConfiguration(awsvpc);
task.setNetworkConfiguration(networkConfiguration);
Container container = new Container();
container.setName("app");
container.setImage("nginx:latest");
container.setLastStatus("RUNNING");
container.setDockerId("docker-id-1");
container.setMetadataId(METADATA_ID);
container.setContainerArn("arn:aws:ecs:us-east-1:000000000000:container/abc123/app");
container.setCreatedAt(Instant.parse("2026-01-01T10:00:03Z"));
container.setStartedAt(Instant.parse("2026-01-01T10:00:07Z"));
task.setContainers(List.of(container));
return task;
}
private static TaskDefinition taskDefinition() {
ContainerDefinition app = new ContainerDefinition();
app.setName("app");
app.setImage("nginx:latest");
app.setCpu(128);
app.setMemory(256);
app.setLogConfiguration(new LogConfiguration("awslogs",
Map.of("awslogs-group", "/ecs/web"), null));
TaskDefinition taskDef = new TaskDefinition();
taskDef.setFamily("web");
taskDef.setRevision(3);
taskDef.setNetworkMode(NetworkMode.awsvpc);
taskDef.setContainerDefinitions(List.of(app));
return taskDef;
}
private JsonNode body(Response response) {
return objectMapper.valueToTree(response.getEntity());
}
@Test
void containerMetadataReportsTheAwsMembers() {
Response response = controller.container(METADATA_ID);
assertEquals(200, response.getStatus());
JsonNode container = body(response);
assertEquals("docker-id-1", container.path("DockerId").asText());
assertEquals("app", container.path("Name").asText());
assertEquals("nginx:latest", container.path("Image").asText());
assertEquals("RUNNING", container.path("KnownStatus").asText());
assertEquals("NORMAL", container.path("Type").asText());
assertEquals(128, container.path("Limits").path("CPU").asInt());
assertEquals(256, container.path("Limits").path("Memory").asInt());
// SubnetId is not a member of the v4 network object; only the documented ones are written.
assertTrue(container.path("Networks").get(0).path("SubnetId").isMissingNode(),
"the network object must carry only the members AWS documents");
assertEquals("awslogs", container.path("LogDriver").asText());
assertEquals("/ecs/web", container.path("LogOptions").path("awslogs-group").asText());
assertEquals("web", container.path("Labels").path("com.amazonaws.ecs.task-definition-family").asText());
assertEquals("3", container.path("Labels").path("com.amazonaws.ecs.task-definition-version").asText());
assertEquals(TASK_ARN, container.path("Labels").path("com.amazonaws.ecs.task-arn").asText());
assertEquals("awsvpc", container.path("Networks").get(0).path("NetworkMode").asText());
assertEquals("172.31.0.42", container.path("Networks").get(0).path("IPv4Addresses").get(0).asText());
assertEquals(0, container.path("Networks").get(0).path("AttachmentIndex").asInt());
assertEquals("0e:98:9f:33:76:d3", container.path("Networks").get(0).path("MACAddress").asText());
assertEquals("ip-172-31-0-42.ec2.internal",
container.path("Networks").get(0).path("PrivateDNSName").asText());
// A container's own clock, not the task's: they start one at a time behind dependsOn.
assertEquals("2026-01-01T10:00:03Z", container.path("CreatedAt").asText());
assertEquals("2026-01-01T10:00:07Z", container.path("StartedAt").asText());
}
@Test
void aContainerWithoutItsOwnClockFallsBackToTheTasks() {
Container container = task.getContainers().getFirst();
container.setCreatedAt(null);
container.setStartedAt(null);
JsonNode node = body(controller.container(METADATA_ID));
assertEquals("2026-01-01T10:00:00Z", node.path("CreatedAt").asText());
assertEquals("2026-01-01T10:00:05Z", node.path("StartedAt").asText());
}
@Test
void aStoppedContainerReportsWhenItFinished() {
task.getContainers().getFirst().setFinishedAt(Instant.parse("2026-01-01T10:30:00Z"));
assertEquals("2026-01-01T10:30:00Z",
body(controller.container(METADATA_ID)).path("FinishedAt").asText());
}
/**
* The subnet half of the network object. AWS derives the gateway from the subnet's own CIDR,
* the resolver from the VPC's, and names us-east-1's search domain {@code ec2.internal}.
*/
@Test
void theNetworkObjectDescribesTheSubnetTheTaskSitsIn() {
JsonNode network = body(controller.container(METADATA_ID)).path("Networks").get(0);
assertEquals("172.31.32.0/20", network.path("IPv4SubnetCIDRBlock").asText());
assertEquals("172.31.32.1/20", network.path("SubnetGatewayIpv4Address").asText());
assertEquals("172.31.0.2", network.path("DomainNameServers").get(0).asText());
assertEquals("ec2.internal", network.path("DomainNameSearchList").get(0).asText());
}
@Test
void aTaskWithNoNetworkConfigurationReportsNoSubnetMembers() {
task.setNetworkConfiguration(null);
JsonNode network = body(controller.container(METADATA_ID)).path("Networks").get(0);
assertTrue(network.path("AttachmentIndex").isMissingNode());
assertTrue(network.path("IPv4SubnetCIDRBlock").isMissingNode());
assertTrue(network.path("DomainNameServers").isMissingNode());
}
@Test
void taskMetadataReportsTheTaskAndItsContainers() {
Response response = controller.task(METADATA_ID);
assertEquals(200, response.getStatus());
JsonNode task = body(response);
assertEquals(TASK_ARN, task.path("TaskARN").asText());
assertEquals("web", task.path("Family").asText());
assertEquals("3", task.path("Revision").asText());
assertEquals("FARGATE", task.path("LaunchType").asText());
assertEquals("us-east-1a", task.path("AvailabilityZone").asText());
// The task's CPU limit is a vCPU count, not the CPU units the API takes.
assertEquals(0.25, task.path("Limits").path("CPU").asDouble(), 0.0001);
assertEquals(512, task.path("Limits").path("Memory").asInt());
assertEquals("2026-01-01T10:00:01Z", task.path("PullStartedAt").asText());
assertEquals(1, task.path("Containers").size());
assertEquals("app", task.path("Containers").get(0).path("Name").asText());
// Fargate reports the clock's accuracy and the task's ephemeral storage alongside it.
assertEquals("SYNCHRONIZED", task.path("ClockDrift").path("ClockSynchronizationStatus").asText());
assertTrue(task.path("ClockDrift").has("ReferenceTimestamp"));
assertEquals(20 * 1024, task.path("EphemeralStorageMetrics").path("Reserved").asInt());
// VPCID is the container instance's, which a Fargate task does not have.
assertTrue(task.path("VPCID").isMissingNode());
}
@Test
void anEc2TaskReportsTheVpcItsSubnetBelongsTo() {
task.setLaunchType(LaunchType.EC2);
assertEquals("vpc-0a1b2c3d", body(controller.task(METADATA_ID)).path("VPCID").asText());
}
@Test
void taskWithTagsAddsTheTaskAndContainerInstanceTags() {
task.setLaunchType(LaunchType.EC2);
task.setContainerInstanceArn(
"arn:aws:ecs:us-east-1:000000000000:container-instance/metadata-cluster/ci-1");
when(service.listTagsForResource(TASK_ARN)).thenReturn(Map.of("owner", "platform"));
when(service.listTagsForResource(task.getContainerInstanceArn()))
.thenReturn(Map.of("fleet", "spot"));
JsonNode withTags = body(controller.taskWithTags(METADATA_ID));
assertEquals(TASK_ARN, withTags.path("TaskARN").asText(), "the task document is carried whole");
assertEquals("platform", withTags.path("TaskTags").path("owner").asText());
assertEquals("spot", withTags.path("ContainerInstanceTags").path("fleet").asText());
assertTrue(withTags.path("Errors").isMissingNode());
}
/** The container agent serves taskWithTags, and a Fargate task has no agent behind it. */
@Test
void taskWithTagsIsNotFoundForAFargateTask() {
assertEquals(404, controller.taskWithTags(METADATA_ID).getStatus());
}
@Test
void taskWithTagsReportsAFailedTagLookupUnderErrors() {
task.setLaunchType(LaunchType.EC2);
when(service.listTagsForResource(TASK_ARN))
.thenThrow(new AwsException("InvalidParameterException", "Resource not found", 400));
JsonNode withTags = body(controller.taskWithTags(METADATA_ID));
assertTrue(withTags.path("TaskTags").isMissingNode());
assertEquals("TaskTags", withTags.path("Errors").get(0).path("ErrorField").asText());
assertEquals("InvalidParameterException",
withTags.path("Errors").get(0).path("ErrorCode").asText());
assertEquals(400, withTags.path("Errors").get(0).path("StatusCode").asInt());
}
@Test
void aContainerWithoutLimitsReportsNoneRatherThanZeroes() {
EcsService limitlessService = mock(EcsService.class);
EcsTask limitlessTask = task();
TaskDefinition taskDef = taskDefinition();
taskDef.getContainerDefinitions().getFirst().setCpu(null);
taskDef.getContainerDefinitions().getFirst().setMemory(null);
when(limitlessService.findByMetadataId(anyString())).thenReturn(Optional.of(
new EcsService.MetadataTarget(limitlessTask, limitlessTask.getContainers().getFirst(), taskDef)));
JsonNode container = body(new EcsTaskMetadataController(limitlessService, containerManager,
ec2Service, objectMapper).container(METADATA_ID));
assertTrue(container.path("Limits").isMissingNode(),
"Limits is omitted when the container definition sets none");
assertTrue(container.path("ImageID").isMissingNode(),
"ImageID is omitted until the image digest is known");
}
@Test
void statsReportTheSampleDockerGaveUnderItsOwnMemberNames() throws JsonProcessingException {
EcsContainerManager.ContainerStats stats1 =
new EcsContainerManager.ContainerStats(sample(), 43.5, 215.25);
when(containerManager.sampleContainerStats("docker-id-1")).thenReturn(Optional.of(stats1));
when(containerManager.sampleContainerStats(List.of("docker-id-1")))
.thenReturn(Map.of("docker-id-1", stats1));
JsonNode stats = body(controller.containerStats(METADATA_ID));
assertEquals("2026-01-01T10:05:00.000000000Z", stats.path("read").asText());
assertEquals(42000000, stats.path("cpu_stats").path("cpu_usage").path("total_usage").asLong());
assertEquals(1048576, stats.path("memory_stats").path("usage").asLong());
assertEquals(84, stats.path("networks").path("eth0").path("rx_bytes").asLong());
// The rates are the agent's, derived from consecutive samples; Docker reports only totals.
assertEquals(43.5, stats.path("network_rate_stats").path("rx_bytes_per_sec").asDouble(), 0.0001);
assertEquals(215.25, stats.path("network_rate_stats").path("tx_bytes_per_sec").asDouble(), 0.0001);
// docker-java's model carries a field per API version; the ones this daemon left out are
// dropped rather than written as nulls onto a document a client parses as Docker's.
assertFalse(stats.has("network"), "a member the daemon did not send must not appear as null");
JsonNode taskStats = body(controller.taskStats(METADATA_ID));
assertEquals(1048576, taskStats.path("docker-id-1").path("memory_stats").path("usage").asLong(),
"task stats are keyed by Docker id, each carrying that container's sample");
}
@Test
void statsOmitTheRatesWhenOnlyOneSampleArrived() throws JsonProcessingException {
when(containerManager.sampleContainerStats("docker-id-1")).thenReturn(Optional.of(
new EcsContainerManager.ContainerStats(sample(), null, null)));
JsonNode stats = body(controller.containerStats(METADATA_ID));
assertEquals(1048576, stats.path("memory_stats").path("usage").asLong());
assertTrue(stats.path("network_rate_stats").isMissingNode(),
"a rate that could not be measured is left out rather than reported as zero");
}
@Test
void statsAnswerWithAnEmptyDocumentWhenTheDaemonHasNoSample() {
JsonNode stats = body(controller.containerStats(METADATA_ID));
assertTrue(stats.isObject() && stats.isEmpty(), "an unsampled container reports {}");
JsonNode taskStats = body(controller.taskStats(METADATA_ID));
assertTrue(taskStats.path("docker-id-1").isObject() && taskStats.path("docker-id-1").isEmpty(),
"every container in the task keeps an entry, empty rather than null");
}
/** A trimmed Docker stats response, read through docker-java's model the way the daemon's is. */
private static Statistics sample() throws JsonProcessingException {
String json = """
{
"read": "2026-01-01T10:05:00.000000000Z",
"preread": "2026-01-01T10:04:59.000000000Z",
"num_procs": 3,
"cpu_stats": {"cpu_usage": {"total_usage": 42000000}, "system_cpu_usage": 90000000},
"precpu_stats": {"cpu_usage": {"total_usage": 41000000}, "system_cpu_usage": 89000000},
"memory_stats": {"usage": 1048576, "limit": 268435456},
"pids_stats": {"current": 3},
"networks": {"eth0": {"rx_bytes": 84, "tx_bytes": 120}}
}
""";
return JsonMapper.builder()
.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
.build()
.readValue(json, Statistics.class);
}
@Test
void anUnknownIdIsNotFound() {
Response response = controller.container("not-a-metadata-id");
assertEquals(404, response.getStatus());
assertTrue(body(response).path("error").asText().contains("Unable to get metadata"));
}
}
@@ -0,0 +1,172 @@
package io.github.hectorvent.floci.services.ecs;
import io.github.hectorvent.floci.services.ecs.container.EcsContainerManager;
import io.github.hectorvent.floci.services.ecs.model.Container;
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.NetworkMode;
import io.github.hectorvent.floci.services.ecs.model.TaskDefinition;
import io.quarkus.test.InjectMock;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.anEmptyMap;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.mockito.ArgumentMatchers.anyList;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.when;
/**
* The task metadata endpoint over the wire. Floci serves it at the root, next to S3's
* {@code /{bucket}/{key}} catch-all, so route registration and precedence are what these cover:
* a miss would hand a workload S3's XML instead of the document it read the endpoint for. The
* response shapes themselves are pinned down in {@link EcsTaskMetadataControllerTest}.
*/
@QuarkusTest
class EcsTaskMetadataIntegrationTest {
private static final String METADATA_ID = "4c1b0a9e8d7f4a3b9c2d1e0f5a4b3c2d";
private static final String DOCKER_ID = "0f9a8b7c6d5e";
private static final String TASK_ARN =
"arn:aws:ecs:us-east-1:000000000000:task/metadata-cluster/route123";
@InjectMock
EcsService ecsService;
@InjectMock
EcsContainerManager containerManager;
private EcsTask task;
@BeforeEach
void resolveOneMetadataId() {
task = task();
when(ecsService.findByMetadataId(anyString())).thenAnswer(invocation ->
METADATA_ID.equals(invocation.getArgument(0))
? Optional.of(new EcsService.MetadataTarget(task,
task.getContainers().getFirst(), taskDefinition()))
: Optional.empty());
when(containerManager.sampleContainerStats(anyString())).thenReturn(Optional.empty());
when(containerManager.sampleContainerStats(anyList())).thenReturn(Map.of());
}
@Test
void containerDocumentIsServedAtTheRoot() {
given()
.when()
.get("/v4/" + METADATA_ID)
.then()
.statusCode(200)
.contentType(containsString("json"))
.body("DockerId", equalTo(DOCKER_ID))
.body("Name", equalTo("app"))
.body("Labels.'com.amazonaws.ecs.task-arn'", equalTo(TASK_ARN));
}
@Test
void taskDocumentIsServedUnderTheContainerPath() {
given()
.when()
.get("/v4/" + METADATA_ID + "/task")
.then()
.statusCode(200)
.contentType(containsString("json"))
.body("TaskARN", equalTo(TASK_ARN))
.body("Family", equalTo("web"))
.body("Revision", equalTo("3"))
.body("Containers[0].Name", equalTo("app"));
}
@Test
void taskWithTagsIsRoutedAlongsideTheTaskPath() {
when(ecsService.listTagsForResource(TASK_ARN)).thenReturn(Map.of("owner", "platform"));
// taskWithTags is the container agent's path, so only an EC2 task has it.
task.setLaunchType(LaunchType.EC2);
given()
.when()
.get("/v4/" + METADATA_ID + "/taskWithTags")
.then()
.statusCode(200)
.contentType(containsString("json"))
.body("TaskARN", equalTo(TASK_ARN))
.body("TaskTags.owner", equalTo("platform"));
}
@Test
void bothStatsPathsAreRoutedAndAnswerWithJson() {
given()
.when()
.get("/v4/" + METADATA_ID + "/stats")
.then()
.statusCode(200)
.contentType(containsString("json"))
.body("$", anEmptyMap());
given()
.when()
.get("/v4/" + METADATA_ID + "/task/stats")
.then()
.statusCode(200)
.contentType(containsString("json"))
.body(DOCKER_ID, anEmptyMap());
}
/**
* An unknown id must reach the endpoint and get its JSON error, not fall through to S3 and
* come back as {@code NoSuchBucket} XML for a bucket named {@code v4}.
*/
@Test
void anUnknownIdAnswersWithTheEndpointsOwnNotFound() {
given()
.when()
.get("/v4/not-a-metadata-id")
.then()
.statusCode(404)
.contentType(containsString("json"))
.body("error", containsString("Unable to get metadata"));
}
private static EcsTask task() {
EcsTask task = new EcsTask();
task.setTaskArn(TASK_ARN);
task.setClusterArn("arn:aws:ecs:us-east-1:000000000000:cluster/metadata-cluster");
task.setTaskDefinitionArn("arn:aws:ecs:us-east-1:000000000000:task-definition/web:3");
task.setLastStatus("RUNNING");
task.setDesiredStatus("RUNNING");
task.setLaunchType(LaunchType.FARGATE);
task.setCpu("256");
task.setMemory("512");
Container container = new Container();
container.setName("app");
container.setImage("nginx:latest");
container.setLastStatus("RUNNING");
container.setDockerId(DOCKER_ID);
container.setMetadataId(METADATA_ID);
container.setContainerArn("arn:aws:ecs:us-east-1:000000000000:container/route123/app");
task.setContainers(List.of(container));
return task;
}
private static TaskDefinition taskDefinition() {
ContainerDefinition app = new ContainerDefinition();
app.setName("app");
app.setImage("nginx:latest");
TaskDefinition taskDef = new TaskDefinition();
taskDef.setFamily("web");
taskDef.setRevision(3);
taskDef.setNetworkMode(NetworkMode.awsvpc);
taskDef.setContainerDefinitions(List.of(app));
return taskDef;
}
}
@@ -24,7 +24,9 @@ import org.mockito.ArgumentCaptor;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
@@ -149,6 +151,36 @@ class EcsContainerManagerAwsBaselineTest {
"overridden baseline endpoint should not remain");
}
@Test
void injectsTheTaskMetadataEndpointEachContainerCanReach() {
when(awsEnv.flociEndpoint()).thenReturn("http://host.docker.internal:4566");
ContainerDefinition app = containerDef("app", "app:latest", List.of());
TaskDefinition taskDef = new TaskDefinition();
taskDef.setFamily("test-family");
taskDef.setContainerDefinitions(List.of(app));
EcsTask task = new EcsTask();
task.setTaskArn("arn:aws:ecs:us-east-1:000000000000:task/test-cluster/abc123");
manager.startTask(task, taskDef, null, "us-east-1");
@SuppressWarnings("unchecked")
ArgumentCaptor<List<String>> envCaptor = ArgumentCaptor.forClass(List.class);
verify(builder).withEnv(envCaptor.capture());
String metadataUri = envCaptor.getValue().stream()
.filter(entry -> entry.startsWith("ECS_CONTAINER_METADATA_URI_V4="))
.findFirst()
.orElse(null);
assertNotNull(metadataUri, "every launched container is told where its metadata lives");
assertTrue(metadataUri.startsWith("ECS_CONTAINER_METADATA_URI_V4=http://host.docker.internal:4566/v4/"),
"the metadata URI must point at Floci's own v4 path: " + metadataUri);
// The id in the URI is the one the container is then found by.
String id = metadataUri.substring(metadataUri.lastIndexOf('/') + 1);
assertEquals(id, task.getContainers().getFirst().getMetadataId());
}
private static ContainerDefinition containerDef(String name, String image, List<KeyValuePair> env) {
ContainerDefinition def = new ContainerDefinition();
def.setName(name);
@@ -120,8 +120,10 @@ class EcsContainerManagerSecurityGroupTest {
verify(builder, never()).withPortBinding(anyInt(), anyInt());
verify(builder, never()).withDynamicPort(anyInt());
verify(builder, never()).withExposedPort(anyInt());
// Port bindings come off the helper, whose namespace holds them; the workload container
// shares that namespace and publishes none, and is inspected only for its launch clock.
verify(dockerClient).inspectContainerCmd("helper-id");
verify(dockerClient, never()).inspectContainerCmd("docker-id");
verify(dockerClient, times(1)).inspectContainerCmd("docker-id");
verify(firewallManager).register(any(), eq("helper-id"), any());
assertEquals("eni-1", handle.getNetworkInterfaceId());
assertEquals("us-east-1", handle.getRegion());
@@ -0,0 +1,133 @@
package io.github.hectorvent.floci.services.ecs.container;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.model.Statistics;
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.TaskDefinition;
import io.quarkus.test.junit.QuarkusTest;
import jakarta.inject.Inject;
import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* The sample behind the task metadata endpoint's {@code /stats} paths, taken from a real daemon.
* AWS returns Docker's own stats document there, so what matters is that a sample arrives at all
* and carries the counters a client reads; the serialized member names are pinned down in
* {@code EcsTaskMetadataControllerTest}.
*/
@QuarkusTest
class EcsContainerManagerStatsDockerIntegrationTest {
private static final String BUSYBOX_IMAGE = "public.ecr.aws/docker/library/busybox:latest";
@Inject
EcsContainerManager containerManager;
@Inject
DockerClient dockerClient;
@BeforeEach
void requireDocker() {
Assumptions.assumeTrue(isDockerAvailable(),
"Docker daemon must be available for ECS stats integration tests");
}
@Test
void aRunningContainerReportsTheDaemonsStats() {
String suffix = UUID.randomUUID().toString().substring(0, 8);
TaskDefinition taskDefinition = new TaskDefinition();
taskDefinition.setFamily("stats-docker-" + suffix);
taskDefinition.setContainerDefinitions(List.of(sleeper("app")));
EcsTask task = new EcsTask();
task.setTaskArn("arn:aws:ecs:us-east-1:000000000000:task/stats/" + suffix);
EcsTaskHandle handle = containerManager.startTask(task, taskDefinition, List.of(), "us-east-1");
try {
Optional<EcsContainerManager.ContainerStats> sample =
containerManager.sampleContainerStats(handle.getContainerIds().get("app"));
assertTrue(sample.isPresent(), "a running container must have stats to sample");
Statistics statistics = sample.get().statistics();
assertNotNull(statistics.getRead(), "the sample carries the instant Docker read it");
assertNotNull(statistics.getCpuStats(), "the sample carries the container's CPU stats");
assertNotNull(statistics.getMemoryStats(), "the sample carries the container's memory stats");
assertNotNull(statistics.getPreCpuStats(),
"the second sample carries the previous CPU reading a client computes against");
// A container on a Docker network reports interfaces, so the rate delta is measurable.
assertNotNull(sample.get().rxBytesPerSecond(), "two samples make the receive rate measurable");
assertNotNull(sample.get().txBytesPerSecond(), "two samples make the transmit rate measurable");
} finally {
containerManager.stopTask(handle);
}
}
/**
* The daemon holds a stats stream open per container, so a task's containers are sampled in one
* pass with every stream open at once. That the real daemon serves them alongside each other is
* what this covers; the cost of the pass is pinned down in {@code EcsContainerManagerStatsSamplingTest}.
*/
@Test
void aTasksContainersAreAllSampledInOnePass() {
String suffix = UUID.randomUUID().toString().substring(0, 8);
TaskDefinition taskDefinition = new TaskDefinition();
taskDefinition.setFamily("stats-pass-" + suffix);
taskDefinition.setContainerDefinitions(List.of(
sleeper("app"), sleeper("sidecar"), sleeper("logger")));
EcsTask task = new EcsTask();
task.setTaskArn("arn:aws:ecs:us-east-1:000000000000:task/stats/" + suffix);
EcsTaskHandle handle = containerManager.startTask(task, taskDefinition, List.of(), "us-east-1");
try {
List<String> dockerIds = List.of(handle.getContainerIds().get("app"),
handle.getContainerIds().get("sidecar"),
handle.getContainerIds().get("logger"));
Map<String, EcsContainerManager.ContainerStats> sampled =
containerManager.sampleContainerStats(dockerIds);
assertEquals(dockerIds.size(), sampled.size(), "every container in the task is sampled");
for (String dockerId : dockerIds) {
assertNotNull(sampled.get(dockerId).statistics().getRead(),
"each sample carries the instant Docker read it");
}
} finally {
containerManager.stopTask(handle);
}
}
@Test
void aContainerThatIsGoneReportsNoSampleRatherThanFailing() {
assertTrue(containerManager.sampleContainerStats("floci-no-such-container").isEmpty());
assertTrue(containerManager.sampleContainerStats((String) null).isEmpty());
}
private static ContainerDefinition sleeper(String name) {
ContainerDefinition definition = new ContainerDefinition();
definition.setName(name);
definition.setImage(BUSYBOX_IMAGE);
definition.setCommand(List.of("sleep", "60"));
return definition;
}
private boolean isDockerAvailable() {
try {
dockerClient.pingCmd().exec();
return true;
} catch (Exception e) {
return false;
}
}
}
@@ -0,0 +1,185 @@
package io.github.hectorvent.floci.services.ecs.container;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.json.JsonMapper;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.async.ResultCallback;
import com.github.dockerjava.api.command.StatsCmd;
import com.github.dockerjava.api.model.Statistics;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.docker.ContainerBuilder;
import io.github.hectorvent.floci.core.common.docker.ContainerDetector;
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager;
import io.github.hectorvent.floci.core.common.docker.ContainerLogStreamer;
import io.github.hectorvent.floci.core.common.docker.LaunchedContainerAwsEnv;
import io.github.hectorvent.floci.services.ecr.registry.EcrRegistryManager;
import io.github.hectorvent.floci.services.s3.S3Service;
import io.github.hectorvent.floci.services.secretsmanager.SecretsManagerService;
import io.github.hectorvent.floci.services.ssm.SsmService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
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.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* How the task metadata endpoint's {@code /stats} paths sample the daemon. Docker only sends its
* second stats sample on the next collection tick, so a task's containers have to be sampled
* alongside each other: {@code /task/stats} is the path a sidecar polls, and sampling one
* container after another would cost it a tick per container.
*
* <p>The daemon is mocked. A stream sends its first sample as soon as it is opened and holds its
* second one back until every stream the pass opens is open, which is what a serial implementation
* could never satisfy.
*/
class EcsContainerManagerStatsSamplingTest {
private static final String FIRST_READ = "2026-01-01T10:05:00.000000000Z";
private static final String SECOND_READ = "2026-01-01T10:05:01.000000000Z";
private final Map<String, StatsCmd> commands = new ConcurrentHashMap<>();
private EcsContainerManager manager;
/**
* Trips once every stream a pass is expected to open has been opened. Only the pass that is
* about the ordering raises it: the other tests leave it open so their samples flow at once.
*/
private CountDownLatch allStreamsOpen;
@BeforeEach
void setUp() {
allStreamsOpen = new CountDownLatch(0);
DockerClient dockerClient = mock(DockerClient.class);
when(dockerClient.statsCmd(anyString())).thenAnswer(invocation ->
commands.computeIfAbsent(invocation.getArgument(0), id -> tickingStatsCmd()));
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
when(lifecycleManager.getDockerClient()).thenReturn(dockerClient);
manager = new EcsContainerManager(mock(ContainerBuilder.class), lifecycleManager,
mock(ContainerLogStreamer.class), mock(ContainerDetector.class),
mock(EmulatorConfig.class, RETURNS_DEEP_STUBS), mock(RegionResolver.class),
mock(LaunchedContainerAwsEnv.class), mock(SsmService.class),
mock(SecretsManagerService.class), mock(S3Service.class),
mock(EcrRegistryManager.class), mock(HostVolumePolicy.class));
}
@Test
@Timeout(10)
void aTasksContainersAreSampledAlongsideEachOtherRatherThanOneAfterAnother() {
List<String> dockerIds = List.of("docker-1", "docker-2", "docker-3", "docker-4");
// No stream sends its second sample until all four are open, so a pass that waits on one
// stream before opening the next cannot collect a pair for any of them.
allStreamsOpen = new CountDownLatch(dockerIds.size());
Map<String, EcsContainerManager.ContainerStats> sampled = manager.sampleContainerStats(dockerIds);
assertEquals(dockerIds.size(), sampled.size(), "every container in the task reports a sample");
for (String dockerId : dockerIds) {
EcsContainerManager.ContainerStats stats = sampled.get(dockerId);
assertEquals(SECOND_READ, stats.statistics().getRead(), "the later sample is the one reported");
assertNotNull(stats.rxBytesPerSecond(), "a pair arrived for " + dockerId + ", so it has rates");
assertEquals(100.0, stats.rxBytesPerSecond(), 0.0001, "the rate is the delta across the pair");
assertEquals(200.0, stats.txBytesPerSecond(), 0.0001);
}
}
@Test
void everyStreamIsClosedOnceThePassIsDone() throws IOException {
manager.sampleContainerStats(List.of("docker-1", "docker-2"));
for (StatsCmd command : commands.values()) {
verify(command).close();
}
}
@Test
void aContainerTheDaemonRefusesIsLeftOutWithoutFailingTheRest() {
commands.put("docker-gone", failingStatsCmd());
Map<String, EcsContainerManager.ContainerStats> sampled =
manager.sampleContainerStats(List.of("docker-gone", "docker-1"));
assertFalse(sampled.containsKey("docker-gone"), "a container with no stream reports no sample");
assertTrue(sampled.containsKey("docker-1"), "the containers alongside it are still sampled");
}
@Test
void oneContainerIsSampledThroughTheSamePass() {
Optional<EcsContainerManager.ContainerStats> stats = manager.sampleContainerStats("docker-1");
assertTrue(stats.isPresent());
assertEquals(SECOND_READ, stats.get().statistics().getRead());
assertTrue(manager.sampleContainerStats((String) null).isEmpty(), "no id means no sample");
}
/**
* A stats stream that sends its first sample as soon as it is opened and its second one only
* once every stream of the pass is open, standing in for Docker's collection tick.
*/
private StatsCmd tickingStatsCmd() {
StatsCmd command = mock(StatsCmd.class);
when(command.exec(any())).thenAnswer(invocation -> {
ResultCallback<Statistics> callback = invocation.getArgument(0);
allStreamsOpen.countDown();
Thread emitter = new Thread(() -> {
try {
callback.onNext(sample(FIRST_READ, 100));
if (allStreamsOpen.await(5, TimeUnit.SECONDS)) {
callback.onNext(sample(SECOND_READ, 200));
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} catch (JsonProcessingException e) {
throw new IllegalStateException("the fixed stats sample must parse", e);
}
});
emitter.setDaemon(true);
emitter.start();
return callback;
});
return command;
}
/** A container the daemon has already forgotten: opening its stream throws. */
private static StatsCmd failingStatsCmd() {
StatsCmd command = mock(StatsCmd.class);
when(command.exec(any())).thenThrow(new IllegalStateException("no such container"));
return command;
}
private static Statistics sample(String read, long rxBytes) throws JsonProcessingException {
String json = """
{
"read": "%s",
"cpu_stats": {"cpu_usage": {"total_usage": 42000000}},
"memory_stats": {"usage": 1048576},
"networks": {"eth0": {"rx_bytes": %d, "tx_bytes": %d}}
}
""".formatted(read, rxBytes, rxBytes * 2);
return JsonMapper.builder()
.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
.build()
.readValue(json, Statistics.class);
}
}