mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
feat(ecs): add FireLens task logging support (#3768)
* feat(ecs): add FireLens task logging support * fix(docker): omit extra hosts for container network mode * fix(ecs): bind FireLens router port to loopback
This commit is contained in:
1 parent
172bfb32b0
commit
6f87973649
11 files changed
+527
-17
No files matched your search
+14
-3
@@ -32,9 +32,20 @@ ECS emulates clusters, task definitions, tasks, and services. In the default con
|
||||
|
||||
`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.
|
||||
own `RegisterTaskDefinition`) sees no drift. FireLens task definitions are also used at runtime:
|
||||
Floci starts the configured `fluentbit` or `fluentd` router first, places routed containers in its
|
||||
network namespace, and sends their output to the task-local forward port `24224` through Docker's
|
||||
Fluentd log driver. The router container's output continues to be forwarded by Floci's existing
|
||||
CloudWatch Logs integration. Custom S3 configuration files are not downloaded by Floci.
|
||||
The `awsfirelens` output options are preserved in the task definition, but Floci does not generate
|
||||
or inject a Fluent Bit or Fluentd output configuration from those options.
|
||||
|
||||
#### FireLens
|
||||
|
||||
A task using `awsfirelens` must contain exactly one container with `firelensConfiguration` and a
|
||||
supported type of `fluentbit` or `fluentd`. The router must not publish port `24224`. Docker-backed
|
||||
tasks require a router image configured to accept the Fluent Forward protocol on
|
||||
`127.0.0.1:24224`; mock mode preserves the JSON fields without starting containers.
|
||||
|
||||
### Tasks
|
||||
|
||||
|
||||
+27
-4
@@ -86,12 +86,13 @@ public class ContainerLifecycleManager {
|
||||
* filesystem modifications are needed between creation and start.
|
||||
*
|
||||
* @param spec the container specification
|
||||
* @return information about the created container including resolved endpoints
|
||||
* @return information about the created container including resolved endpoints and published ports
|
||||
*/
|
||||
public ContainerInfo createAndStart(ContainerSpec spec) {
|
||||
String containerId = create(spec);
|
||||
try {
|
||||
return startCreated(containerId, spec);
|
||||
ContainerInfo info = startCreated(containerId, spec);
|
||||
return withPublishedHostPorts(info, spec);
|
||||
} catch (Exception e) {
|
||||
// A failed start (e.g. host-port conflict) must not leak the created
|
||||
// container: retrying callers would accumulate Created containers and
|
||||
@@ -247,6 +248,22 @@ public class ContainerLifecycleManager {
|
||||
return new ContainerInfo(containerId, endpoints);
|
||||
}
|
||||
|
||||
private ContainerInfo withPublishedHostPorts(ContainerInfo info, ContainerSpec spec) {
|
||||
if (spec.portBindings() == null || spec.portBindings().isEmpty()) {
|
||||
return info;
|
||||
}
|
||||
|
||||
InspectContainerResponse inspect = dockerClient.inspectContainerCmd(info.containerId()).exec();
|
||||
Map<Integer, Integer> publishedHostPorts = new HashMap<>();
|
||||
for (Integer containerPort : spec.portBindings().keySet()) {
|
||||
OptionalInt published = readPublishedHostPort(inspect, containerPort);
|
||||
if (published.isPresent()) {
|
||||
publishedHostPorts.put(containerPort, published.getAsInt());
|
||||
}
|
||||
}
|
||||
return new ContainerInfo(info.containerId(), info.endpoints(), publishedHostPorts);
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts a container, translating crun/runc's kernel-keyring-quota error into a message that
|
||||
* names the actual cause and a fix, instead of the misleading "Disk quota exceeded" the OCI
|
||||
@@ -937,8 +954,10 @@ public class ContainerLifecycleManager {
|
||||
hostConfig.withBinds(spec.binds().toArray(new Bind[0]));
|
||||
}
|
||||
|
||||
// Extra hosts (e.g., host.docker.internal on Linux)
|
||||
if (spec.extraHosts() != null && !spec.extraHosts().isEmpty()) {
|
||||
// Docker rejects extra_hosts together with container:<id> network mode. Containers
|
||||
// sharing another container's network namespace already inherit its network path.
|
||||
if (spec.extraHosts() != null && !spec.extraHosts().isEmpty()
|
||||
&& !isContainerNetworkMode(spec.networkMode())) {
|
||||
hostConfig.withExtraHosts(spec.extraHosts().toArray(new String[0]));
|
||||
}
|
||||
|
||||
@@ -963,6 +982,10 @@ public class ContainerLifecycleManager {
|
||||
return hostConfig;
|
||||
}
|
||||
|
||||
private static boolean isContainerNetworkMode(String networkMode) {
|
||||
return networkMode != null && networkMode.startsWith("container:");
|
||||
}
|
||||
|
||||
private Map<Integer, EndpointInfo> resolveEndpoints(String containerId, ContainerSpec spec) {
|
||||
if (spec.exposedPorts() == null || spec.exposedPorts().isEmpty()) {
|
||||
return Map.of();
|
||||
|
||||
@@ -9,10 +9,11 @@ import io.github.hectorvent.floci.services.ecs.model.CapacityProvider;
|
||||
import io.github.hectorvent.floci.services.ecs.model.ClusterSetting;
|
||||
import io.github.hectorvent.floci.services.ecs.model.ContainerDefinition;
|
||||
import io.github.hectorvent.floci.services.ecs.model.ContainerInstance;
|
||||
import io.github.hectorvent.floci.services.ecs.model.ContainerOverride;
|
||||
import io.github.hectorvent.floci.services.ecs.model.Deployment;
|
||||
import io.github.hectorvent.floci.services.ecs.model.Failure;
|
||||
import io.github.hectorvent.floci.services.ecs.model.FirelensConfiguration;
|
||||
import io.github.hectorvent.floci.services.ecs.model.HealthCheck;
|
||||
import io.github.hectorvent.floci.services.ecs.model.ContainerOverride;
|
||||
import io.github.hectorvent.floci.services.ecs.model.EcsCluster;
|
||||
import io.github.hectorvent.floci.services.ecs.model.EcsLoadBalancer;
|
||||
import io.github.hectorvent.floci.services.ecs.model.EcsServiceModel;
|
||||
@@ -1124,6 +1125,20 @@ public class EcsJsonHandler {
|
||||
n.set("logConfiguration", logNode);
|
||||
}
|
||||
|
||||
if (def.getFirelensConfiguration() != null) {
|
||||
FirelensConfiguration firelens = def.getFirelensConfiguration();
|
||||
ObjectNode firelensNode = objectMapper.createObjectNode();
|
||||
if (firelens.type() != null) {
|
||||
firelensNode.put("type", firelens.type());
|
||||
}
|
||||
if (firelens.options() != null) {
|
||||
ObjectNode options = objectMapper.createObjectNode();
|
||||
firelens.options().forEach(options::put);
|
||||
firelensNode.set("options", options);
|
||||
}
|
||||
n.set("firelensConfiguration", firelensNode);
|
||||
}
|
||||
|
||||
if (def.getHealthCheck() != null) {
|
||||
HealthCheck hc = def.getHealthCheck();
|
||||
ObjectNode hcNode = objectMapper.createObjectNode();
|
||||
@@ -1482,6 +1497,7 @@ public class EcsJsonHandler {
|
||||
}
|
||||
def.setMountPoints(parseMountPoints(item.path("mountPoints")));
|
||||
def.setLogConfiguration(parseLogConfiguration(item.path("logConfiguration")));
|
||||
def.setFirelensConfiguration(parseFirelensConfiguration(item.path("firelensConfiguration")));
|
||||
if (item.has("healthCheck")) {
|
||||
def.setHealthCheck(parseHealthCheck(item.path("healthCheck")));
|
||||
}
|
||||
@@ -1569,6 +1585,20 @@ public class EcsJsonHandler {
|
||||
return new LogConfiguration(logDriver, options, secretOptions);
|
||||
}
|
||||
|
||||
private FirelensConfiguration parseFirelensConfiguration(JsonNode node) {
|
||||
if (node == null || !node.isObject() || !node.has("type")) {
|
||||
return null;
|
||||
}
|
||||
Map<String, String> options = null;
|
||||
if (node.path("options").isObject()) {
|
||||
Map<String, String> parsed = new LinkedHashMap<>();
|
||||
node.path("options").fields()
|
||||
.forEachRemaining(entry -> parsed.put(entry.getKey(), entry.getValue().asText()));
|
||||
options = parsed;
|
||||
}
|
||||
return new FirelensConfiguration(node.path("type").asText(), options);
|
||||
}
|
||||
|
||||
private HealthCheck parseHealthCheck(JsonNode node) {
|
||||
if (node == null || !node.isObject()) {
|
||||
return null;
|
||||
|
||||
+93
-9
@@ -37,6 +37,7 @@ import io.github.hectorvent.floci.services.ssm.SsmService;
|
||||
import com.github.dockerjava.api.DockerClient;
|
||||
import com.github.dockerjava.api.exception.NotFoundException;
|
||||
import com.github.dockerjava.api.model.ExposedPort;
|
||||
import com.github.dockerjava.api.model.LogConfig;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
@@ -53,6 +54,7 @@ import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.OptionalInt;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
@@ -79,6 +81,55 @@ public class EcsContainerManager {
|
||||
private Ec2Service ec2Service;
|
||||
private SecurityGroupFirewallManager firewallManager;
|
||||
|
||||
static LogConfig firelensLogConfig(String taskId, String containerName, int fluentdPort) {
|
||||
return new LogConfig(LogConfig.LoggingType.FLUENTD, Map.of(
|
||||
"fluentd-address", "127.0.0.1:" + fluentdPort,
|
||||
"tag", taskId + "." + containerName,
|
||||
"fluentd-async", "true"));
|
||||
}
|
||||
|
||||
static List<ContainerDefinition> orderFirelensContainers(List<ContainerDefinition> definitions) {
|
||||
ContainerDefinition router = firelensRouter(definitions);
|
||||
boolean hasFirelensApplication = definitions.stream().anyMatch(EcsContainerManager::usesFirelens);
|
||||
if (router == null) {
|
||||
if (hasFirelensApplication) {
|
||||
throw new AwsException("ClientException",
|
||||
"An awsfirelens log configuration requires a FireLens log router.", 400);
|
||||
}
|
||||
return definitions;
|
||||
}
|
||||
String type = router.getFirelensConfiguration().type();
|
||||
if (!"fluentbit".equalsIgnoreCase(type) && !"fluentd".equalsIgnoreCase(type)) {
|
||||
throw new AwsException("ClientException",
|
||||
"FireLens configuration type must be fluentbit or fluentd.", 400);
|
||||
}
|
||||
if (router.getPortMappings() != null && router.getPortMappings().stream()
|
||||
.anyMatch(port -> port.containerPort() == 24224)) {
|
||||
throw new AwsException("ClientException",
|
||||
"FireLens port 24224 must not be exposed.", 400);
|
||||
}
|
||||
List<ContainerDefinition> ordered = new ArrayList<>(definitions.size());
|
||||
ordered.add(router);
|
||||
definitions.stream().filter(definition -> definition != router).forEach(ordered::add);
|
||||
return ordered;
|
||||
}
|
||||
|
||||
private static ContainerDefinition firelensRouter(List<ContainerDefinition> definitions) {
|
||||
List<ContainerDefinition> routers = definitions.stream()
|
||||
.filter(definition -> definition.getFirelensConfiguration() != null)
|
||||
.toList();
|
||||
if (routers.size() > 1) {
|
||||
throw new AwsException("ClientException",
|
||||
"A task definition can have only one FireLens log router.", 400);
|
||||
}
|
||||
return routers.isEmpty() ? null : routers.getFirst();
|
||||
}
|
||||
|
||||
private static boolean usesFirelens(ContainerDefinition definition) {
|
||||
return definition.getLogConfiguration() != null
|
||||
&& "awsfirelens".equalsIgnoreCase(definition.getLogConfiguration().logDriver());
|
||||
}
|
||||
|
||||
@Inject
|
||||
public EcsContainerManager(ContainerBuilder containerBuilder,
|
||||
ContainerLifecycleManager lifecycleManager,
|
||||
@@ -154,10 +205,19 @@ public class EcsContainerManager {
|
||||
}
|
||||
|
||||
Map<String, ContainerOverride> overridesByName = overridesByName(containerOverrides);
|
||||
List<ContainerDefinition> orderedDefinitions = orderFirelensContainers(
|
||||
taskDef.getContainerDefinitions());
|
||||
ContainerDefinition firelensRouter = firelensRouter(orderedDefinitions);
|
||||
if (firelensRouter != null && taskDef.getNetworkMode() == NetworkMode.awsvpc
|
||||
&& firewallManager != null && firewallManager.enabled()) {
|
||||
throw new AwsException("ClientException",
|
||||
"FireLens is not supported with security-group enforcement.", 400);
|
||||
}
|
||||
OptionalInt firelensHostPort = OptionalInt.empty();
|
||||
Map<ContainerDefinition, List<String>> envVarsByContainer = new LinkedHashMap<>();
|
||||
// Resolved before any container is created, so a registry-startup failure can't leak one already started.
|
||||
Map<ContainerDefinition, String> imagesByContainer = new LinkedHashMap<>();
|
||||
for (ContainerDefinition def : taskDef.getContainerDefinitions()) {
|
||||
for (ContainerDefinition def : orderedDefinitions) {
|
||||
envVarsByContainer.put(def, buildEnvVars(def, overridesByName.get(def.getName()), region));
|
||||
imagesByContainer.put(def, ecrRegistryManager.rewriteImageUri(def.getImage()));
|
||||
}
|
||||
@@ -165,7 +225,7 @@ public class EcsContainerManager {
|
||||
PreparedNetwork protectedNetwork = prepareNetwork(task, taskDef, region, taskId);
|
||||
|
||||
try {
|
||||
for (ContainerDefinition def : taskDef.getContainerDefinitions()) {
|
||||
for (ContainerDefinition def : orderedDefinitions) {
|
||||
String containerName = ContainerStorageHelper.dockerName(config, "floci-ecs-" + taskId + "-" + def.getName());
|
||||
|
||||
// RunTask containerOverrides matched by container name: command replaces
|
||||
@@ -183,12 +243,21 @@ public class EcsContainerManager {
|
||||
// own loopback.
|
||||
.withHostDockerInternalOnLinux()
|
||||
.withEmbeddedDns()
|
||||
.withLogRotation()
|
||||
.withLabels(ContainerStorageHelper.resourceIdentityLabels(
|
||||
"ecs", taskId, regionResolver.getAccountId(), region));
|
||||
boolean firelensApplication = usesFirelens(def);
|
||||
if (!firelensApplication) {
|
||||
specBuilder.withLogRotation();
|
||||
}
|
||||
if (protectedNetwork != null) {
|
||||
specBuilder.withNetworkMode("container:" + protectedNetwork.namespace().helperId());
|
||||
specBuilder.withLabels(Map.of("floci.security-group-workload", "true"));
|
||||
} else if (firelensApplication) {
|
||||
String routerId = containerIds.get(firelensRouter.getName());
|
||||
specBuilder.withNetworkMode("container:" + routerId);
|
||||
}
|
||||
if (def == firelensRouter) {
|
||||
specBuilder.withLoopbackPortBinding(24224, 0);
|
||||
}
|
||||
|
||||
// Add memory limit if specified
|
||||
@@ -204,7 +273,7 @@ public class EcsContainerManager {
|
||||
// local Docker host (#1778) — awsvpc mappings always get a dynamic
|
||||
// host port in native mode, or expose-only in Docker mode where ECS
|
||||
// consumers reach containers via the docker network IP.
|
||||
if (protectedNetwork == null && def.getPortMappings() != null) {
|
||||
if (protectedNetwork == null && !firelensApplication && def.getPortMappings() != null) {
|
||||
boolean awsvpc = taskDef.getNetworkMode() == NetworkMode.awsvpc;
|
||||
boolean publishToHost = !containerDetector.isRunningInContainer();
|
||||
for (PortMapping pm : def.getPortMappings()) {
|
||||
@@ -231,6 +300,11 @@ public class EcsContainerManager {
|
||||
specBuilder.withEntrypoint(def.getEntryPoint());
|
||||
}
|
||||
|
||||
if (firelensApplication) {
|
||||
specBuilder.withLogConfig(firelensLogConfig(
|
||||
taskId, def.getName(), firelensHostPort.orElseThrow()));
|
||||
}
|
||||
|
||||
// Bind-mount task-level volumes referenced by this container's mountPoints.
|
||||
// The host source path resolves on the Docker daemon (sibling-container launch),
|
||||
// so it must be an absolute host path. Unresolved volume references are skipped.
|
||||
@@ -269,6 +343,14 @@ public class EcsContainerManager {
|
||||
ContainerInfo info = lifecycleManager.createAndStart(spec);
|
||||
String dockerId = info.containerId();
|
||||
|
||||
if (def == firelensRouter) {
|
||||
firelensHostPort = info.publishedHostPort(24224);
|
||||
if (firelensHostPort.isEmpty()) {
|
||||
throw new AwsException("ClientException",
|
||||
"The FireLens log router did not publish port 24224.", 400);
|
||||
}
|
||||
}
|
||||
|
||||
LOG.infov("Created ECS container {0} for task {1} container {2}", dockerId, taskId, def.getName());
|
||||
|
||||
// Resolve network bindings for ECS-specific model
|
||||
@@ -284,11 +366,13 @@ public class EcsContainerManager {
|
||||
String logGroup = "/ecs/" + taskDef.getFamily();
|
||||
String logStream = logStreamer.generateLogStreamName(def.getName() + "/" + taskId);
|
||||
|
||||
Closeable logHandle = logStreamer.attach(
|
||||
dockerId, logGroup, logStream, region,
|
||||
"ecs:" + taskDef.getFamily() + ":" + def.getName());
|
||||
if (logHandle != null) {
|
||||
logStreamsByContainerId.put(dockerId, logHandle);
|
||||
if (!firelensApplication) {
|
||||
Closeable logHandle = logStreamer.attach(
|
||||
dockerId, logGroup, logStream, region,
|
||||
"ecs:" + taskDef.getFamily() + ":" + def.getName());
|
||||
if (logHandle != null) {
|
||||
logStreamsByContainerId.put(dockerId, logHandle);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
|
||||
@@ -20,6 +20,7 @@ public class ContainerDefinition {
|
||||
private List<String> entryPoint;
|
||||
private List<MountPoint> mountPoints;
|
||||
private LogConfiguration logConfiguration;
|
||||
private FirelensConfiguration firelensConfiguration;
|
||||
private HealthCheck healthCheck;
|
||||
|
||||
public String getName() { return name; }
|
||||
@@ -61,6 +62,11 @@ public class ContainerDefinition {
|
||||
public LogConfiguration getLogConfiguration() { return logConfiguration; }
|
||||
public void setLogConfiguration(LogConfiguration logConfiguration) { this.logConfiguration = logConfiguration; }
|
||||
|
||||
public FirelensConfiguration getFirelensConfiguration() { return firelensConfiguration; }
|
||||
public void setFirelensConfiguration(FirelensConfiguration firelensConfiguration) {
|
||||
this.firelensConfiguration = firelensConfiguration;
|
||||
}
|
||||
|
||||
public HealthCheck getHealthCheck() { return healthCheck; }
|
||||
public void setHealthCheck(HealthCheck healthCheck) { this.healthCheck = healthCheck; }
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package io.github.hectorvent.floci.services.ecs.model;
|
||||
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
@RegisterForReflection
|
||||
public record FirelensConfiguration(String type, Map<String, String> options) {
|
||||
}
|
||||
+16
@@ -165,6 +165,22 @@ class ContainerLifecycleManagerLabelsTest {
|
||||
verify(createCmd, never()).withPlatform(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void createOmitsExtraHostsForContainerNetworkMode() {
|
||||
CreateContainerCmd createCmd = stubCreateContainer();
|
||||
ContainerSpec spec = new ContainerSpec(
|
||||
"busybox:stable", null, List.of(), null, null, null, Map.of(), List.of(),
|
||||
"container:router-id", List.of(), List.of(), List.of("host.docker.internal:host-gateway"),
|
||||
Map.of(), null, false, null, List.of(), null, null, List.of());
|
||||
|
||||
manager().create(spec);
|
||||
|
||||
ArgumentCaptor<HostConfig> hostConfig = ArgumentCaptor.forClass(HostConfig.class);
|
||||
verify(createCmd).withHostConfig(hostConfig.capture());
|
||||
assertTrue(hostConfig.getValue().getExtraHosts() == null
|
||||
|| hostConfig.getValue().getExtraHosts().length == 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
void createIncludesNamespaceLabelWhenConfigured() {
|
||||
when(dockerConfig.resourceNamespace()).thenReturn(Optional.of("run-one"));
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
package io.github.hectorvent.floci.services.ecs;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.services.ecs.container.HostVolumePolicy;
|
||||
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.RETURNS_DEEP_STUBS;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class EcsJsonHandlerFirelensTest {
|
||||
|
||||
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(invocation -> {
|
||||
TaskDefinition taskDefinition = new TaskDefinition();
|
||||
taskDefinition.setFamily(invocation.getArgument(0));
|
||||
taskDefinition.setRevision(1);
|
||||
taskDefinition.setStatus("ACTIVE");
|
||||
taskDefinition.setContainerDefinitions(invocation.getArgument(1, List.class));
|
||||
return taskDefinition;
|
||||
});
|
||||
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
|
||||
handler = new EcsJsonHandler(service, objectMapper, new HostVolumePolicy(config));
|
||||
}
|
||||
|
||||
@Test
|
||||
void registerTaskDefinitionRoundTripsFirelensConfiguration() throws Exception {
|
||||
JsonNode request = objectMapper.readTree("""
|
||||
{
|
||||
"family": "firelens-family",
|
||||
"containerDefinitions": [
|
||||
{
|
||||
"name": "log_router",
|
||||
"image": "public.ecr.aws/aws-observability/aws-for-fluent-bit:3",
|
||||
"firelensConfiguration": {
|
||||
"type": "fluentbit",
|
||||
"options": {"enable-ecs-log-metadata": "false"}
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "app",
|
||||
"image": "alpine:latest",
|
||||
"logConfiguration": {
|
||||
"logDriver": "awsfirelens",
|
||||
"options": {"Name": "cloudwatch_logs", "log_group_name": "/ecs/app"}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
""");
|
||||
|
||||
Response response = handler.handle("RegisterTaskDefinition", request, "us-east-1");
|
||||
JsonNode taskDefinition = objectMapper.valueToTree(response.getEntity()).path("taskDefinition");
|
||||
|
||||
JsonNode firelens = taskDefinition.path("containerDefinitions").get(0).path("firelensConfiguration");
|
||||
assertEquals("fluentbit", firelens.path("type").asText());
|
||||
assertEquals("false", firelens.path("options").path("enable-ecs-log-metadata").asText());
|
||||
JsonNode logConfiguration = taskDefinition.path("containerDefinitions").get(1).path("logConfiguration");
|
||||
assertEquals("awsfirelens", logConfiguration.path("logDriver").asText());
|
||||
assertEquals("cloudwatch_logs", logConfiguration.path("options").path("Name").asText());
|
||||
assertTrue(logConfiguration.path("options").path("log_group_name").isTextual());
|
||||
}
|
||||
}
|
||||
+158
@@ -0,0 +1,158 @@
|
||||
package io.github.hectorvent.floci.services.ecs.container;
|
||||
|
||||
import com.github.dockerjava.api.DockerClient;
|
||||
import com.github.dockerjava.api.model.Frame;
|
||||
import com.github.dockerjava.api.model.StreamType;
|
||||
import com.github.dockerjava.core.command.ExecStartResultCallback;
|
||||
import com.github.dockerjava.core.command.WaitContainerResultCallback;
|
||||
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.FirelensConfiguration;
|
||||
import io.github.hectorvent.floci.services.ecs.model.LogConfiguration;
|
||||
import io.github.hectorvent.floci.services.ecs.model.TaskDefinition;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Assumptions;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.Closeable;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
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.assertTrue;
|
||||
|
||||
@QuarkusTest
|
||||
class EcsContainerManagerFirelensDockerIntegrationTest {
|
||||
|
||||
private static final String IMAGE = "public.ecr.aws/docker/library/busybox:latest";
|
||||
|
||||
@Inject
|
||||
EcsContainerManager containerManager;
|
||||
|
||||
@Inject
|
||||
DockerClient dockerClient;
|
||||
|
||||
private EcsTaskHandle taskHandle;
|
||||
|
||||
@BeforeEach
|
||||
void requireDocker() {
|
||||
Assumptions.assumeTrue(isDockerAvailable(),
|
||||
"Docker daemon must be available for FireLens integration tests");
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void cleanUpTask() {
|
||||
if (taskHandle != null) {
|
||||
containerManager.stopTask(taskHandle);
|
||||
taskHandle = null;
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void applicationStdoutReachesFirelensRouterThroughPublishedHostPort() throws Exception {
|
||||
String marker = "firelens-marker-" + UUID.randomUUID();
|
||||
|
||||
ContainerDefinition app = new ContainerDefinition();
|
||||
app.setName("app");
|
||||
app.setImage(IMAGE);
|
||||
app.setCommand(List.of("sh", "-c", "echo " + marker + "; sleep 2"));
|
||||
app.setLogConfiguration(new LogConfiguration("awsfirelens", Map.of(), null));
|
||||
|
||||
ContainerDefinition router = new ContainerDefinition();
|
||||
router.setName("router");
|
||||
router.setImage(IMAGE);
|
||||
router.setCommand(List.of("sh", "-c", "while true; do nc -l -p 24224 >> /tmp/received; done"));
|
||||
router.setFirelensConfiguration(new FirelensConfiguration("fluentbit", Map.of()));
|
||||
|
||||
TaskDefinition taskDefinition = new TaskDefinition();
|
||||
taskDefinition.setFamily("firelens-integration");
|
||||
taskDefinition.setContainerDefinitions(List.of(app, router));
|
||||
|
||||
EcsTask task = new EcsTask();
|
||||
task.setTaskArn("arn:aws:ecs:us-east-1:000000000000:task/firelens/" + marker);
|
||||
|
||||
taskHandle = containerManager.startTask(task, taskDefinition, List.of(), "us-east-1");
|
||||
|
||||
assertEquals(List.of("router", "app"), taskHandle.getContainerIds().keySet().stream().toList());
|
||||
String appId = taskHandle.getContainerIds().get("app");
|
||||
String routerId = taskHandle.getContainerIds().get("router");
|
||||
dockerClient.waitContainerCmd(appId)
|
||||
.exec(new WaitContainerResultCallback())
|
||||
.awaitStatusCode(30, TimeUnit.SECONDS);
|
||||
|
||||
String received = awaitRouterBuffer(routerId, marker);
|
||||
assertTrue(received.contains(marker), "FireLens router did not receive the app stdout record");
|
||||
}
|
||||
|
||||
private String awaitRouterBuffer(String routerId, String marker) throws Exception {
|
||||
for (int attempt = 0; attempt < 30; attempt++) {
|
||||
ExecResult result = readRouterBuffer(routerId, marker);
|
||||
if (result.exitCode() == 0 && result.output().contains(marker)) {
|
||||
return result.output();
|
||||
}
|
||||
Thread.sleep(1000);
|
||||
}
|
||||
return readRouterBuffer(routerId, marker).output();
|
||||
}
|
||||
|
||||
private ExecResult readRouterBuffer(String routerId, String marker) throws Exception {
|
||||
String execId = dockerClient.execCreateCmd(routerId)
|
||||
.withCmd("sh", "-c", "grep -a " + marker + " /tmp/received")
|
||||
.withAttachStdout(true)
|
||||
.withAttachStderr(true)
|
||||
.exec()
|
||||
.getId();
|
||||
ByteArrayOutputStream output = new ByteArrayOutputStream();
|
||||
CountDownLatch complete = new CountDownLatch(1);
|
||||
Closeable callback = dockerClient.execStartCmd(execId).exec(new ExecStartResultCallback() {
|
||||
@Override
|
||||
public void onNext(Frame frame) {
|
||||
try {
|
||||
if (frame.getStreamType() == StreamType.STDOUT) {
|
||||
output.write(frame.getPayload());
|
||||
}
|
||||
} catch (IOException e) {
|
||||
throw new IllegalStateException("Failed to capture FireLens output", e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onComplete() {
|
||||
complete.countDown();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onError(Throwable throwable) {
|
||||
complete.countDown();
|
||||
}
|
||||
});
|
||||
try {
|
||||
assertTrue(complete.await(10, TimeUnit.SECONDS), "Timed out reading FireLens router buffer");
|
||||
long exitCode = dockerClient.inspectExecCmd(execId).exec().getExitCodeLong();
|
||||
return new ExecResult(exitCode, output.toString(StandardCharsets.UTF_8));
|
||||
} finally {
|
||||
callback.close();
|
||||
}
|
||||
}
|
||||
|
||||
private boolean isDockerAvailable() {
|
||||
try {
|
||||
dockerClient.pingCmd().exec();
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private record ExecResult(long exitCode, String output) {
|
||||
}
|
||||
}
|
||||
+59
@@ -0,0 +1,59 @@
|
||||
package io.github.hectorvent.floci.services.ecs.container;
|
||||
|
||||
import com.github.dockerjava.api.model.LogConfig;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.services.ecs.model.ContainerDefinition;
|
||||
import io.github.hectorvent.floci.services.ecs.model.FirelensConfiguration;
|
||||
import io.github.hectorvent.floci.services.ecs.model.LogConfiguration;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
class EcsContainerManagerFirelensTest {
|
||||
|
||||
@Test
|
||||
void createsFluentdLogConfigForAwsFirelensApplication() {
|
||||
LogConfig logConfig = EcsContainerManager.firelensLogConfig("task-123", "app", 32768);
|
||||
|
||||
assertEquals(LogConfig.LoggingType.FLUENTD, logConfig.getType());
|
||||
assertEquals("127.0.0.1:32768", logConfig.getConfig().get("fluentd-address"));
|
||||
assertEquals("task-123.app", logConfig.getConfig().get("tag"));
|
||||
assertEquals("true", logConfig.getConfig().get("fluentd-async"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void ordersRouterBeforeAwsFirelensApplications() {
|
||||
ContainerDefinition app = container("app", "awsfirelens", null);
|
||||
ContainerDefinition router = container("router", null,
|
||||
new FirelensConfiguration("fluentbit", Map.of()));
|
||||
|
||||
List<ContainerDefinition> ordered = EcsContainerManager.orderFirelensContainers(List.of(app, router));
|
||||
|
||||
assertEquals("router", ordered.get(0).getName());
|
||||
assertEquals("app", ordered.get(1).getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsAwsFirelensApplicationWithoutRouter() {
|
||||
ContainerDefinition app = container("app", "awsfirelens", null);
|
||||
|
||||
assertThrows(AwsException.class,
|
||||
() -> EcsContainerManager.orderFirelensContainers(List.of(app)));
|
||||
}
|
||||
|
||||
private static ContainerDefinition container(String name, String driver,
|
||||
FirelensConfiguration firelensConfiguration) {
|
||||
ContainerDefinition definition = new ContainerDefinition();
|
||||
definition.setName(name);
|
||||
definition.setImage("alpine:latest");
|
||||
definition.setFirelensConfiguration(firelensConfiguration);
|
||||
if (driver != null) {
|
||||
definition.setLogConfiguration(new LogConfiguration(driver, Map.of(), null));
|
||||
}
|
||||
return definition;
|
||||
}
|
||||
}
|
||||
+33
@@ -12,6 +12,8 @@ import io.github.hectorvent.floci.core.common.docker.LaunchedContainerAwsEnv;
|
||||
import io.github.hectorvent.floci.services.ecr.registry.EcrRegistryManager;
|
||||
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.FirelensConfiguration;
|
||||
import io.github.hectorvent.floci.services.ecs.model.LogConfiguration;
|
||||
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.TaskDefinition;
|
||||
@@ -221,4 +223,35 @@ class EcsContainerManagerPortMappingsTest {
|
||||
verify(builder, never()).withDynamicPort(9090);
|
||||
verify(builder, never()).withPortBinding(eq(9090), anyInt());
|
||||
}
|
||||
|
||||
@Test
|
||||
void firelensRouterUsesLoopbackOnlyDynamicPortBinding() {
|
||||
when(containerDetector.isRunningInContainer()).thenReturn(false);
|
||||
|
||||
ContainerDefinition router = new ContainerDefinition();
|
||||
router.setName("router");
|
||||
router.setImage("fluent/fluent-bit:latest");
|
||||
router.setFirelensConfiguration(new FirelensConfiguration("fluentbit", Map.of()));
|
||||
|
||||
ContainerDefinition app = new ContainerDefinition();
|
||||
app.setName("app");
|
||||
app.setImage("app:latest");
|
||||
app.setLogConfiguration(new LogConfiguration("awsfirelens", Map.of(), null));
|
||||
|
||||
TaskDefinition taskDef = new TaskDefinition();
|
||||
taskDef.setFamily("test-family");
|
||||
taskDef.setContainerDefinitions(List.of(app, router));
|
||||
|
||||
EcsTask task = new EcsTask();
|
||||
task.setTaskArn("arn:aws:ecs:us-east-1:000000000000:task/test-cluster/abc123");
|
||||
|
||||
when(lifecycleManager.createAndStart(any()))
|
||||
.thenReturn(new ContainerInfo("router-id", Map.of(), Map.of(24224, 32768)))
|
||||
.thenReturn(new ContainerInfo("app-id", Map.of()));
|
||||
|
||||
manager.startTask(task, taskDef, List.of(), "us-east-1");
|
||||
|
||||
verify(builder).withLoopbackPortBinding(24224, 0);
|
||||
verify(builder, never()).withDynamicPort(24224);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user