feat(ecs): support fluentd FireLens routers and s3-hosted FireLens config (#3790)

* feat(ecs): route awsfirelens logs through a generated Fluent Bit router

Start the router first, point awsfirelens containers at the generated unix socket, and store firelensConfiguration as registered.

* feat(ecs): carry FireLens config through CloudFormation and aim outputs at Floci

AWS::ECS::TaskDefinition provisioning now keeps each container LogConfiguration and FirelensConfiguration, so a stack that registers a FireLens router reaches the same launch path as RegisterTaskDefinition.

The generated router points each awsfirelens output at Floci container-reachable base URL through Endpoint, and the app container awsfirelens log config uses fluentd-async, which Docker 28 accepts, instead of the removed fluentd-async-connect.

Only s3, cloudwatch and firehose receive that endpoint: they are the AWS-written Go plugins and parse the value as a URL. The upstream C plugins (cloudwatch_logs, kinesis_firehose, kinesis_streams) hand it to getaddrinfo as a bare host name and always dial TLS, with no output-level switch for either, so a URL is a guaranteed DNS failure on Fluent Bit 1.9 and 5.0.9 alike, and a bare host plus port only reaches Floci plain HTTP port before certificate verification fails. Those outputs keep whatever the task definition gave them.

* feat(ecs): support fluentd FireLens routers and s3-hosted FireLens config

A fluentd FireLens router is now acted on at launch instead of being stored and ignored. Floci generates the config the ECS agent generates for that type: unix and forward sources, a grep filter per include-pattern and exclude-pattern, a record_transformer filter for the ECS metadata, the include of an external config, and one match block per awsfirelens container keyed on its @type. Fluentd takes its output plugin name from the log option @type rather than Name, its tags end in ** rather than *, and it gets neither the healthcheck sections nor Mem_Buf_Limit, both of which the agent emits for Fluent Bit only. The router image is handed /fluentd/etc/fluent.conf, so the config archive contents and its destination directory are now chosen per router type.

config-file-type=s3 now reads the object from Floci's own S3 instead of ignoring the option, and writes it to the fixed external.conf path next to the generated config, /fluent-bit/etc/external.conf or /fluentd/etc/external.conf, which is where the agent mounts what it downloads. The object is read before any container is created, so a missing bucket or key stops the task with the agent's own wording as the stopped reason, Unable to download firelens s3 config file: unable to download s3 config <key> from bucket <bucket>: <detail>, rather than leaving a router running behind a task that already failed.

RegisterTaskDefinition enforces the same split ECS does. A Fargate-compatible task definition cannot take its config from S3, and is rejected with Fargate launch type does not support FirelensConfiguration config file from 's3'; a config-file-value that does not name an S3 object is rejected as Invalid arn syntax. An EC2-compatible task definition keeps s3, and a Fargate task can still source its config from S3 the way AWS documents, through the aws-for-fluent-bit init process and its aws_fluent_bit_init_s3_* environment variables, which ECS never inspects and Floci passes through. Floci serves no ECS task metadata endpoint, so that init path fetches nothing locally yet, which docs/services/ecs.md now states.

* fix(ecs): rejoin awsvpc tasks to the security-group namespace

The FireLens launch loop stopped calling withNetworkMode(container:<helper>)
and dropped the workload label, so prepareNetwork's ENI/nftables had nothing
to isolate. Cover the join with a firewallManager-wired unit test.

* test(ecs): assert FireLens router and app both join the SG namespace

* test(ecs): verify FireLens router and app lifecycle in SG namespace test

* refactor(ecs): reuse extractTaskId for FireLens cluster name

* docs(ecs): note the launchType/compatibilities gap next to FireLens S3

* docs(ecs): scope the FireLens TCP-listen rationale to non-shared namespaces

* fix(ecs): reject a FireLens type that is missing or not fluentd/fluentbit

AWS requires firelensConfiguration.type and accepts only fluentd or
fluentbit. parseFirelensConfiguration returned null for a missing type,
registering the container as if FireLens were absent, and persisted any
other string, so an unknown type only became ineffective later when
findFirelensRouter recognized neither value.

Both are now rejected at the RegisterTaskDefinition JSON boundary with
the smithy validation wording, and are covered in
EcsJsonHandlerRuntimePlatformLogConfigurationTest.
This commit is contained in:
z9rtm authored and GitHub committed 2026-09-18 11:54:32 -04:00
1 parent caab63c602
commit e32266537e
28 files changed
+2346 -333

No files matched your search

@@ -7,6 +7,7 @@ import org.junit.jupiter.params.provider.ValueSource;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -200,6 +201,29 @@ class AwsArnUtilsTest {
assertFalse(AwsArnUtils.isArnFor(null, "dynamodb"));
}
@Test
void s3ObjectArnSplitsBucketAndKey() {
assertEquals(new AwsArnUtils.S3ObjectRef("logs", "firelens/extra.conf"),
AwsArnUtils.parseS3ObjectArn("arn:aws:s3:::logs/firelens/extra.conf"));
assertEquals(new AwsArnUtils.S3ObjectRef("logs", "extra.conf"),
AwsArnUtils.parseS3ObjectArn("arn:aws:s3:us-east-1:000000000000:logs/extra.conf"));
}
/**
* Everything ECS rejects as "Invalid arn syntax" for a FireLens {@code config-file-value}:
* not an ARN at all (the {@code s3://bucket/key} form users try), another service's ARN, and
* an ARN with no key or no bucket. Null rather than an exception, because the same helper
* backs the defensive path at task launch.
*/
@Test
void s3ObjectArnIsNullForAnythingThatIsNotAnS3Object() {
assertNull(AwsArnUtils.parseS3ObjectArn("s3://logs/extra.conf"));
assertNull(AwsArnUtils.parseS3ObjectArn("arn:aws:s3:::logs"));
assertNull(AwsArnUtils.parseS3ObjectArn("arn:aws:s3:::logs/"));
assertNull(AwsArnUtils.parseS3ObjectArn("arn:aws:sqs:us-east-1:000000000000:my-queue"));
assertNull(AwsArnUtils.parseS3ObjectArn(null));
}
@Test
void queueUrlIsAccountThenQueueName() {
assertEquals("http://localhost:4566/000000000000/my-queue",
@@ -153,6 +153,10 @@ class EcsCfnProvisionerTest {
container.putArray("Environment").addObject().put("Name", "MODE").put("Value", "prod");
container.putArray("Secrets").addObject().put("Name", "DB").put("ValueFrom", "arn:aws:secretsmanager:x");
container.putArray("Command").add("run").add("--fast");
ObjectNode log = container.putObject("LogConfiguration");
log.put("LogDriver", "awsfirelens");
log.putObject("Options").put("Name", "s3").put("bucket", "logs");
container.putObject("FirelensConfiguration").put("Type", "fluentbit");
StackResource r = resource("AWS::ECS::TaskDefinition", "TaskDef");
provisioner.provision(r, props, ctx());
@@ -174,6 +178,10 @@ class EcsCfnProvisionerTest {
assertEquals("prod", def.getEnvironment().get(0).value());
assertEquals("arn:aws:secretsmanager:x", def.getSecrets().get(0).valueFrom());
assertEquals(List.of("run", "--fast"), def.getCommand());
assertEquals("awsfirelens", def.getLogConfiguration().logDriver());
assertEquals("s3", def.getLogConfiguration().options().get("Name"));
assertEquals("logs", def.getLogConfiguration().options().get("bucket"));
assertEquals("fluentbit", def.getFirelensConfiguration().type());
}
@Test
@@ -0,0 +1,150 @@
package io.github.hectorvent.floci.services.ecs;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.services.ecs.container.EcsContainerManager;
import io.github.hectorvent.floci.services.ecs.model.ContainerDefinition;
import io.github.hectorvent.floci.services.ecs.model.EcsTask;
import io.github.hectorvent.floci.services.ecs.model.FirelensConfiguration;
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.NetworkMode;
import io.github.hectorvent.floci.services.ecs.model.TaskDefinition;
import io.github.hectorvent.floci.services.ecs.model.TaskStatus;
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.assertTrue;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* FireLens config that comes from S3, on both sides of the split ECS draws:
*
* <p>{@code RegisterTaskDefinition} rejects the combination for Fargate (the platform cannot pull
* the object) and rejects a {@code config-file-value} that is not an S3 object ARN, while an
* EC2-compatible task definition keeps it and the agent pulls it at launch. A failed pull becomes
* the task's stopped reason in the agent's own wording.
*
* <p>A Fargate task can still take its config from S3 the way AWS documents, by giving the
* aws-for-fluent-bit init process its {@code aws_fluent_bit_init_s3_*} environment variables,
* which ECS never inspects; the last test pins that Floci does not over-reach and reject it.
*/
class EcsFirelensS3ConfigTest {
private static final String S3_CONFIG_ARN = "arn:aws:s3:::firelens-configs/extra.conf";
@Test
void registerTaskDefinitionRejectsS3FirelensConfigForFargate() {
AwsException failure = assertThrows(AwsException.class, () -> service("us-east-1")
.registerTaskDefinition("fluentbit-s3", List.of(firelensRouter("fluentbit", S3_CONFIG_ARN)),
NetworkMode.awsvpc, "256", "512", null, null, List.of("FARGATE"), "us-east-1"));
assertEquals("ClientException", failure.getErrorCode());
assertEquals(400, failure.getHttpStatus());
assertEquals("Fargate launch type does not support FirelensConfiguration config file from 's3'",
failure.getMessage());
}
@Test
void registerTaskDefinitionRejectsS3FirelensConfigForFargateWithAFluentdRouter() {
AwsException failure = assertThrows(AwsException.class, () -> service("us-east-1")
.registerTaskDefinition("fluentd-s3", List.of(firelensRouter("fluentd", S3_CONFIG_ARN)),
NetworkMode.awsvpc, "256", "512", null, null, List.of("FARGATE"), "us-east-1"));
assertEquals("Fargate launch type does not support FirelensConfiguration config file from 's3'",
failure.getMessage());
}
@Test
void registerTaskDefinitionRejectsAConfigFileValueThatIsNotAnS3ObjectArn() {
AwsException failure = assertThrows(AwsException.class, () -> service("us-east-1")
.registerTaskDefinition("bad-arn", List.of(firelensRouter("fluentbit", "s3://logs/extra.conf")),
NetworkMode.bridge, null, null, null, null, List.of("EC2"), "us-east-1"));
assertEquals("ClientException", failure.getErrorCode());
assertEquals("Invalid arn syntax", failure.getMessage());
}
@Test
void ec2TaskDefinitionKeepsItsS3FirelensConfig() {
TaskDefinition td = service("us-east-1").registerTaskDefinition("ec2-s3",
List.of(firelensRouter("fluentbit", S3_CONFIG_ARN)),
NetworkMode.bridge, null, null, null, null, List.of("EC2"), "us-east-1");
FirelensConfiguration firelens = td.getContainerDefinitions().getFirst().getFirelensConfiguration();
assertEquals("s3", firelens.options().get("config-file-type"));
assertEquals(S3_CONFIG_ARN, firelens.options().get("config-file-value"));
}
@Test
void fargateTaskDefinitionAcceptsS3ConfigThroughTheInitProcessEnvironment() {
ContainerDefinition router = new ContainerDefinition();
router.setName("log_router");
router.setImage("public.ecr.aws/aws-observability/aws-for-fluent-bit:init-latest");
router.setFirelensConfiguration(new FirelensConfiguration("fluentbit", Map.of()));
router.setEnvironment(List.of(new KeyValuePair("aws_fluent_bit_init_s3_1", S3_CONFIG_ARN)));
TaskDefinition td = service("us-east-1").registerTaskDefinition("init-s3", List.of(router),
NetworkMode.awsvpc, "256", "512", null, null, List.of("FARGATE"), "us-east-1");
assertEquals("init-s3", td.getFamily());
}
@Test
void runTaskStopsWithTheAgentReasonWhenTheS3ConfigCannotBeDownloaded() {
EcsContainerManager containerManager = mock(EcsContainerManager.class);
// EcsContainerManager reads the object before creating any container and reports the
// failure with the agent's wording under a ResourceInitializationError code; EcsService
// keys off that code to use the message as the stopped reason verbatim.
when(containerManager.startTask(any(), any(), any(), eq("us-east-1")))
.thenThrow(new AwsException("ResourceInitializationError",
"Unable to download firelens s3 config file: unable to download s3 config "
+ "extra.conf from bucket firelens-configs: The specified key does not exist.",
404));
EcsService service = service(containerManager, false);
service.createCluster("test-cluster", "us-east-1");
service.registerTaskDefinition("ec2-s3", List.of(firelensRouter("fluentbit", S3_CONFIG_ARN)),
NetworkMode.bridge, null, null, null, null, List.of("EC2"), "us-east-1");
List<EcsTask> tasks = service.runTask("test-cluster", "ec2-s3", 1,
LaunchType.EC2, null, null, List.of(), null, "us-east-1");
EcsTask task = tasks.getFirst();
assertEquals(TaskStatus.STOPPED.name(), task.getLastStatus());
assertEquals("Unable to download firelens s3 config file: unable to download s3 config "
+ "extra.conf from bucket firelens-configs: The specified key does not exist.",
task.getStoppedReason());
}
private static ContainerDefinition firelensRouter(String type, String configFileValue) {
ContainerDefinition router = new ContainerDefinition();
router.setName("log_router");
router.setImage("public.ecr.aws/aws-observability/aws-for-fluent-bit:stable");
router.setFirelensConfiguration(new FirelensConfiguration(type, Map.of(
"config-file-type", "s3",
"config-file-value", configFileValue)));
return router;
}
private static EcsService service(String region) {
return service(mock(EcsContainerManager.class), true);
}
private static EcsService service(EcsContainerManager containerManager, boolean mockMode) {
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
when(config.services().ecs().mock()).thenReturn(mockMode);
when(config.effectiveBaseUrl()).thenReturn("http://localhost:4566");
return new EcsService(new RegionResolver("us-east-1", "000000000000"),
containerManager, config, mock(EcsLoadBalancerRegistrar.class), null, null);
}
}
@@ -3,6 +3,7 @@ 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.core.common.AwsException;
import io.github.hectorvent.floci.services.ecs.container.HostVolumePolicy;
import io.github.hectorvent.floci.services.ecs.model.TaskDefinition;
import jakarta.ws.rs.core.Response;
@@ -12,6 +13,7 @@ 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.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
@@ -149,4 +151,89 @@ class EcsJsonHandlerRuntimePlatformLogConfigurationTest {
assertTrue(td.path("containerDefinitions").get(0).path("logConfiguration").isMissingNode(),
"logConfiguration must stay absent for a container that never set it");
}
@Test
void registerTaskDefinitionRoundTripsFirelensConfiguration() throws Exception {
String requestJson = """
{
"family": "firelens-family",
"containerDefinitions": [
{
"name": "log_router",
"image": "amazon/aws-for-fluent-bit:stable",
"firelensConfiguration": {
"type": "fluentbit",
"options": {
"enable-ecs-log-metadata": "true",
"config-file-type": "file",
"config-file-value": "/extra.conf"
}
}
}
]
}
""";
JsonNode request = objectMapper.readTree(requestJson);
Response response = handler.handle("RegisterTaskDefinition", request, "us-east-1");
JsonNode firelens = objectMapper.valueToTree(response.getEntity())
.path("taskDefinition").path("containerDefinitions").get(0).path("firelensConfiguration");
assertEquals("fluentbit", firelens.path("type").asText());
assertEquals("true", firelens.path("options").path("enable-ecs-log-metadata").asText());
assertEquals("file", firelens.path("options").path("config-file-type").asText());
assertEquals("/extra.conf", firelens.path("options").path("config-file-value").asText());
}
@Test
void registerTaskDefinitionRejectsFirelensConfigurationWithMissingType() throws Exception {
JsonNode request = objectMapper.readTree("""
{
"family": "missing-type",
"containerDefinitions": [
{
"name": "log_router",
"image": "amazon/aws-for-fluent-bit:stable",
"firelensConfiguration": {
"options": {"enable-ecs-log-metadata": "true"}
}
}
]
}
""");
AwsException ex = assertThrows(AwsException.class, () ->
handler.handle("RegisterTaskDefinition", request, "us-east-1"));
assertEquals("ClientException", ex.getErrorCode());
assertEquals(400, ex.getHttpStatus());
assertEquals("1 validation error detected: Value null at "
+ "'containerDefinitions.1.member.firelensConfiguration.type' failed to satisfy "
+ "constraint: Member must not be null",
ex.getMessage());
}
@Test
void registerTaskDefinitionRejectsFirelensConfigurationWithUnknownType() throws Exception {
JsonNode request = objectMapper.readTree("""
{
"family": "unknown-type",
"containerDefinitions": [
{
"name": "log_router",
"image": "amazon/aws-for-fluent-bit:stable",
"firelensConfiguration": {"type": "foo"}
}
]
}
""");
AwsException ex = assertThrows(AwsException.class, () ->
handler.handle("RegisterTaskDefinition", request, "us-east-1"));
assertEquals("ClientException", ex.getErrorCode());
assertEquals(400, ex.getHttpStatus());
assertEquals("1 validation error detected: Value 'foo' at "
+ "'containerDefinitions.1.member.firelensConfiguration.type' failed to satisfy "
+ "constraint: Member must satisfy enum value set: [fluentd, fluentbit]",
ex.getMessage());
}
}
@@ -11,6 +11,7 @@ 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.container.HostVolumePolicy;
import io.github.hectorvent.floci.services.ecs.model.FirelensConfiguration;
import io.github.hectorvent.floci.services.ecs.model.LaunchType;
import io.github.hectorvent.floci.services.ecs.model.TaskDefinition;
import jakarta.ws.rs.core.Response;
@@ -67,6 +68,10 @@ class EcsJsonHandlerTaskDefinitionPersistenceTest {
"logConfiguration": {
"logDriver": "awslogs",
"options": {"awslogs-group": "/ecs/restart-family"}
},
"firelensConfiguration": {
"type": "fluentbit",
"options": {"enable-ecs-log-metadata": "true"}
}
}
],
@@ -89,6 +94,11 @@ class EcsJsonHandlerTaskDefinitionPersistenceTest {
assertEquals("awslogs", logConfiguration.logDriver());
assertEquals("/ecs/restart-family", logConfiguration.options().get("awslogs-group"));
FirelensConfiguration firelens = td.getContainerDefinitions().getFirst().getFirelensConfiguration();
assertNotNull(firelens, "firelensConfiguration must survive a restart");
assertEquals("fluentbit", firelens.type());
assertEquals("true", firelens.options().get("enable-ecs-log-metadata"));
assertEquals(1, td.getVolumes().size(), "task-level volumes must survive a restart");
assertEquals("/host/data", td.getVolumes().getFirst().hostSourcePath());
}
@@ -15,6 +15,7 @@ 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.TaskDefinition;
import io.github.hectorvent.floci.services.secretsmanager.SecretsManagerService;
import io.github.hectorvent.floci.services.s3.S3Service;
import io.github.hectorvent.floci.services.ssm.SsmService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@@ -79,7 +80,7 @@ class EcsContainerManagerAwsBaselineTest {
manager = new EcsContainerManager(containerBuilder, lifecycleManager, logStreamer,
containerDetector, config, regionResolver, awsEnv, mock(SsmService.class),
mock(SecretsManagerService.class), ecrRegistryManager, mock(HostVolumePolicy.class));
mock(SecretsManagerService.class), mock(S3Service.class), ecrRegistryManager, mock(HostVolumePolicy.class));
}
@Test
@@ -14,6 +14,7 @@ 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.github.hectorvent.floci.services.secretsmanager.SecretsManagerService;
import io.github.hectorvent.floci.services.s3.S3Service;
import io.github.hectorvent.floci.services.ssm.SsmService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@@ -79,7 +80,7 @@ class EcsContainerManagerEcrRewriteTest {
when(ecrRegistryManager.rewriteImageUri("sidecar:latest")).thenReturn("sidecar:latest");
manager = new EcsContainerManager(containerBuilder, lifecycleManager, logStreamer,
containerDetector, config, regionResolver, awsEnv, ssmService, secretsManagerService,
containerDetector, config, regionResolver, awsEnv, ssmService, secretsManagerService, mock(S3Service.class),
ecrRegistryManager, mock(HostVolumePolicy.class));
}
@@ -4,7 +4,7 @@ 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 com.github.dockerjava.core.command.LogContainerResultCallback;
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;
@@ -34,6 +34,9 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
class EcsContainerManagerFirelensDockerIntegrationTest {
private static final String IMAGE = "public.ecr.aws/docker/library/busybox:latest";
/** A real FireLens router image: Floci writes the generated config to its own
* {@code /fluent-bit/etc}, which no minimal image carries. */
private static final String ROUTER_IMAGE = "public.ecr.aws/aws-observability/aws-for-fluent-bit:3";
@Inject
EcsContainerManager containerManager;
@@ -58,19 +61,18 @@ class EcsContainerManagerFirelensDockerIntegrationTest {
}
@Test
void applicationStdoutReachesFirelensRouterThroughPublishedHostPort() throws Exception {
void applicationRecordReachesTheRouterThroughTheGeneratedConfig() 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));
app.setCommand(List.of("sh", "-c", "while true; do echo " + marker + "; sleep 1; done"));
app.setLogConfiguration(new LogConfiguration("awsfirelens", Map.of("Name", "stdout"), 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.setImage(ROUTER_IMAGE);
router.setFirelensConfiguration(new FirelensConfiguration("fluentbit", Map.of()));
TaskDefinition taskDefinition = new TaskDefinition();
@@ -78,67 +80,86 @@ class EcsContainerManagerFirelensDockerIntegrationTest {
taskDefinition.setContainerDefinitions(List.of(app, router));
EcsTask task = new EcsTask();
task.setTaskArn("arn:aws:ecs:us-east-1:000000000000:task/firelens/" + marker);
task.setTaskArn("arn:aws:ecs:us-east-1:000000000000:task/firelens/" + UUID.randomUUID());
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");
// The Docker daemon, not the application container, makes this connection, so the
// address has to be a path on the host: the socket the router creates inside the
// task's own volume, which the daemon reaches at the volume's mountpoint.
assertEquals("unix://" + firelensVolumeMountpoint() + "/fluent.sock", appLogDriverAddress(appId));
String routerLogs = awaitRouterLogs(routerId, marker);
assertTrue(routerLogs.contains(marker),
"FireLens router did not print the application record routed by the generated config: "
+ routerLogs);
assertTrue(routerLogs.contains("ecs_task_arn"),
"The generated config's ECS metadata filter did not run: " + routerLogs);
}
private String awaitRouterBuffer(String routerId, String marker) throws Exception {
private String firelensVolumeMountpoint() throws Exception {
return dockerClient.inspectVolumeCmd(taskHandle.getFirelensVolumeName())
.exec()
.getMountpoint();
}
private String appLogDriverAddress(String appId) {
return dockerClient.inspectContainerCmd(appId)
.exec()
.getHostConfig()
.getLogConfig()
.getConfig()
.get("fluentd-address");
}
private String awaitRouterLogs(String routerId, String marker) throws Exception {
String logs = "";
for (int attempt = 0; attempt < 30; attempt++) {
ExecResult result = readRouterBuffer(routerId, marker);
if (result.exitCode() == 0 && result.output().contains(marker)) {
return result.output();
logs = readContainerLogs(routerId);
if (logs.contains(marker)) {
return logs;
}
Thread.sleep(1000);
}
return readRouterBuffer(routerId, marker).output();
return logs;
}
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();
private String readContainerLogs(String containerId) throws Exception {
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());
Closeable callback = dockerClient.logContainerCmd(containerId)
.withStdOut(true)
.withStdErr(true)
.exec(new LogContainerResultCallback() {
@Override
public void onNext(Frame frame) {
try {
if (frame.getStreamType() == StreamType.STDOUT
|| frame.getStreamType() == StreamType.STDERR) {
output.write(frame.getPayload());
}
} catch (IOException e) {
throw new IllegalStateException("Failed to capture router logs", e);
}
}
} catch (IOException e) {
throw new IllegalStateException("Failed to capture FireLens output", e);
}
}
@Override
public void onComplete() {
complete.countDown();
}
@Override
public void onComplete() {
complete.countDown();
}
@Override
public void onError(Throwable throwable) {
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));
complete.await(10, TimeUnit.SECONDS);
return output.toString(StandardCharsets.UTF_8);
} finally {
callback.close();
}
@@ -153,6 +174,4 @@ class EcsContainerManagerFirelensDockerIntegrationTest {
}
}
private record ExecResult(long exitCode, String output) {
}
}
@@ -1,59 +1,421 @@
package io.github.hectorvent.floci.services.ecs.container;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.command.CopyArchiveToContainerCmd;
import com.github.dockerjava.api.command.InspectVolumeCmd;
import com.github.dockerjava.api.command.InspectVolumeResponse;
import com.github.dockerjava.api.model.LogConfig;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.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.ContainerLifecycleManager.ContainerInfo;
import io.github.hectorvent.floci.core.common.docker.ContainerLogStreamer;
import io.github.hectorvent.floci.core.common.docker.ContainerSpec;
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;
import io.github.hectorvent.floci.services.s3.S3Service;
import io.github.hectorvent.floci.services.s3.model.S3Object;
import io.github.hectorvent.floci.services.secretsmanager.SecretsManagerService;
import io.github.hectorvent.floci.services.ssm.SsmService;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.InOrder;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.RETURNS_SELF;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class EcsContainerManagerFirelensTest {
@Test
void createsFluentdLogConfigForAwsFirelensApplication() {
LogConfig logConfig = EcsContainerManager.firelensLogConfig("task-123", "app", 32768);
private ContainerBuilder.Builder builder;
private ContainerLifecycleManager lifecycleManager;
private S3Service s3Service;
private ContainerLogStreamer logStreamer;
private DockerClient dockerClient;
private CopyArchiveToContainerCmd copyCmd;
private EcsContainerManager manager;
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"));
@BeforeEach
void setUp() {
builder = mock(ContainerBuilder.Builder.class, RETURNS_SELF);
when(builder.build()).thenReturn(new ContainerSpec("image"));
ContainerBuilder containerBuilder = mock(ContainerBuilder.class);
when(containerBuilder.newContainer(anyString())).thenReturn(builder);
lifecycleManager = mock(ContainerLifecycleManager.class);
when(lifecycleManager.createAndStart(any())).thenReturn(new ContainerInfo("app-id", Map.of()));
when(lifecycleManager.create(any())).thenReturn("router-id");
when(lifecycleManager.startCreated(anyString(), any())).thenReturn(new ContainerInfo("router-id", Map.of()));
dockerClient = mock(DockerClient.class, RETURNS_DEEP_STUBS);
when(lifecycleManager.getDockerClient()).thenReturn(dockerClient);
InspectVolumeCmd inspectVolumeCmd = mock(InspectVolumeCmd.class);
InspectVolumeResponse volume = mock(InspectVolumeResponse.class);
when(dockerClient.inspectVolumeCmd(anyString())).thenReturn(inspectVolumeCmd);
when(inspectVolumeCmd.exec()).thenReturn(volume);
when(volume.getMountpoint()).thenReturn("/var/lib/docker/volumes/floci-ecs-firelens-abc123/_data");
copyCmd = mock(CopyArchiveToContainerCmd.class, RETURNS_SELF);
when(dockerClient.copyArchiveToContainerCmd("router-id")).thenReturn(copyCmd);
logStreamer = mock(ContainerLogStreamer.class);
when(logStreamer.generateLogStreamName(anyString())).thenReturn("stream");
ContainerDetector containerDetector = mock(ContainerDetector.class);
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
RegionResolver regionResolver = mock(RegionResolver.class);
LaunchedContainerAwsEnv awsEnv = mock(LaunchedContainerAwsEnv.class);
when(awsEnv.sdkBaselineEnv(any(), any())).thenReturn(List.of());
when(awsEnv.flociEndpoint()).thenReturn("http://host.docker.internal:4566");
EcrRegistryManager ecrRegistryManager = mock(EcrRegistryManager.class);
when(ecrRegistryManager.rewriteImageUri(anyString())).thenAnswer(inv -> inv.getArgument(0));
s3Service = mock(S3Service.class);
manager = new EcsContainerManager(containerBuilder, lifecycleManager, logStreamer,
containerDetector, config, regionResolver, awsEnv, mock(SsmService.class),
mock(SecretsManagerService.class), s3Service, ecrRegistryManager, new HostVolumePolicy(config));
}
@Test
void ordersRouterBeforeAwsFirelensApplications() {
ContainerDefinition app = container("app", "awsfirelens", null);
ContainerDefinition router = container("router", null,
new FirelensConfiguration("fluentbit", Map.of()));
void startsRouterFirstAndWiresAwsfirelensToUnixSocket() {
ContainerDefinition router = new ContainerDefinition();
router.setName("log_router");
router.setImage("amazon/aws-for-fluent-bit:stable");
router.setFirelensConfiguration(new FirelensConfiguration("fluentbit", Map.of()));
List<ContainerDefinition> ordered = EcsContainerManager.orderFirelensContainers(List.of(app, router));
ContainerDefinition app = new ContainerDefinition();
app.setName("app");
app.setImage("app:latest");
app.setLogConfiguration(new LogConfiguration("awsfirelens",
Map.of("Name", "cloudwatch", "region", "us-east-1"), null));
assertEquals("router", ordered.get(0).getName());
assertEquals("app", ordered.get(1).getName());
TaskDefinition taskDef = new TaskDefinition();
taskDef.setFamily("firelens-family");
taskDef.setRevision(1);
taskDef.setNetworkMode(NetworkMode.awsvpc);
taskDef.setContainerDefinitions(List.of(app, router));
EcsTask task = new EcsTask();
task.setTaskArn("arn:aws:ecs:us-east-1:000000000000:task/test-cluster/abc123");
task.setClusterArn("arn:aws:ecs:us-east-1:000000000000:cluster/test-cluster");
EcsTaskHandle handle = manager.startTask(task, taskDef, null, "us-east-1");
InOrder order = inOrder(lifecycleManager);
order.verify(lifecycleManager).create(any(ContainerSpec.class));
order.verify(lifecycleManager).startCreated(anyString(), any());
order.verify(lifecycleManager).createAndStart(any(ContainerSpec.class));
ArgumentCaptor<LogConfig> logConfig = ArgumentCaptor.forClass(LogConfig.class);
verify(builder).withLogConfig(logConfig.capture());
assertEquals(LogConfig.LoggingType.FLUENTD, logConfig.getValue().getType());
assertEquals("unix:///var/lib/docker/volumes/floci-ecs-firelens-abc123/_data/fluent.sock",
logConfig.getValue().getConfig().get("fluentd-address"));
assertEquals("app-firelens-abc123", logConfig.getValue().getConfig().get("tag"));
assertEquals("true", logConfig.getValue().getConfig().get("fluentd-async"));
assertTrue(logConfig.getValue().getConfig().get("fluentd-async-connect") == null,
"fluentd-async-connect was removed by Docker 28");
verify(logStreamer).attach(eq("router-id"), anyString(), anyString(), anyString(), anyString());
verify(logStreamer, never()).attach(eq("app-id"), anyString(), anyString(), anyString(), anyString());
assertTrue(handle.getFirelensVolumeName().contains("firelens"));
verify(copyCmd).withRemotePath("/fluent-bit/etc");
ArgumentCaptor<InputStream> configArchive = ArgumentCaptor.forClass(InputStream.class);
verify(copyCmd).withTarInputStream(configArchive.capture());
assertTrue(readFluentBitConf(configArchive.getValue()).contains(
" Endpoint http://host.docker.internal:4566"));
}
@Test
void rejectsAwsFirelensApplicationWithoutRouter() {
ContainerDefinition app = container("app", "awsfirelens", null);
void startsFluentdRouterAndWritesFluentConf() {
ContainerDefinition router = new ContainerDefinition();
router.setName("log_router");
router.setImage("fluent/fluentd:v1.16");
router.setFirelensConfiguration(new FirelensConfiguration("fluentd", Map.of()));
assertThrows(AwsException.class,
() -> EcsContainerManager.orderFirelensContainers(List.of(app)));
ContainerDefinition app = new ContainerDefinition();
app.setName("app");
app.setImage("app:latest");
app.setLogConfiguration(new LogConfiguration("awsfirelens",
Map.of("@type", "stdout"), null));
TaskDefinition taskDef = new TaskDefinition();
taskDef.setFamily("firelens-fluentd");
taskDef.setRevision(1);
taskDef.setNetworkMode(NetworkMode.bridge);
taskDef.setContainerDefinitions(List.of(app, router));
EcsTask task = new EcsTask();
task.setTaskArn("arn:aws:ecs:us-east-1:000000000000:task/test-cluster/abc123");
task.setClusterArn("arn:aws:ecs:us-east-1:000000000000:cluster/test-cluster");
manager.startTask(task, taskDef, null, "us-east-1");
InOrder order = inOrder(lifecycleManager);
order.verify(lifecycleManager).create(any(ContainerSpec.class));
order.verify(lifecycleManager).startCreated(anyString(), any());
order.verify(lifecycleManager).createAndStart(any(ContainerSpec.class));
ArgumentCaptor<LogConfig> logConfig = ArgumentCaptor.forClass(LogConfig.class);
verify(builder).withLogConfig(logConfig.capture());
assertEquals(LogConfig.LoggingType.FLUENTD, logConfig.getValue().getType());
assertEquals("unix:///var/lib/docker/volumes/floci-ecs-firelens-abc123/_data/fluent.sock",
logConfig.getValue().getConfig().get("fluentd-address"));
verify(copyCmd).withRemotePath("/fluentd/etc");
ArgumentCaptor<InputStream> configArchive = ArgumentCaptor.forClass(InputStream.class);
verify(copyCmd).withTarInputStream(configArchive.capture());
String conf = readFluentBitConf(configArchive.getValue());
assertTrue(conf.contains("@type unix"));
assertTrue(conf.contains("<match app-firelens**>"));
assertTrue(conf.contains("@type stdout"));
assertTrue(!conf.contains("Endpoint"));
}
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));
@Test
void writesS3ExternalConfigBesideTheGeneratedFluentBitConfig() {
ContainerDefinition router = new ContainerDefinition();
router.setName("log_router");
router.setImage("amazon/aws-for-fluent-bit:stable");
router.setFirelensConfiguration(new FirelensConfiguration("fluentbit", Map.of(
"config-file-type", "s3",
"config-file-value", "arn:aws:s3:::firelens-configs/extra.conf")));
ContainerDefinition app = new ContainerDefinition();
app.setName("app");
app.setImage("app:latest");
app.setLogConfiguration(new LogConfiguration("awsfirelens",
Map.of("Name", "cloudwatch", "region", "us-east-1"), null));
TaskDefinition taskDef = new TaskDefinition();
taskDef.setFamily("firelens-s3");
taskDef.setRevision(1);
taskDef.setNetworkMode(NetworkMode.awsvpc);
taskDef.setContainerDefinitions(List.of(app, router));
EcsTask task = new EcsTask();
task.setTaskArn("arn:aws:ecs:us-east-1:000000000000:task/test-cluster/abc123");
task.setClusterArn("arn:aws:ecs:us-east-1:000000000000:cluster/test-cluster");
String extra = "[OUTPUT]\n Name stdout\n Match app-firelens*\n";
S3Object object = new S3Object();
object.setData(extra.getBytes(StandardCharsets.UTF_8));
when(s3Service.getObject("firelens-configs", "extra.conf")).thenReturn(object);
manager.startTask(task, taskDef, null, "us-east-1");
verify(s3Service).getObject("firelens-configs", "extra.conf");
verify(copyCmd).withRemotePath("/fluent-bit/etc");
ArgumentCaptor<InputStream> configArchive = ArgumentCaptor.forClass(InputStream.class);
verify(copyCmd).withTarInputStream(configArchive.capture());
Map<String, String> files = readFirelensArchive(configArchive.getValue());
assertEquals(2, files.size(), files::toString);
assertTrue(files.get("fluent-bit.conf").contains(
"@INCLUDE /fluent-bit/etc/external.conf"), files.get("fluent-bit.conf"));
assertEquals(extra, files.get("external.conf"));
}
@Test
void fluentdS3ExternalConfigUsesTheFluentdPath() {
ContainerDefinition router = new ContainerDefinition();
router.setName("log_router");
router.setImage("fluent/fluentd:v1.16");
router.setFirelensConfiguration(new FirelensConfiguration("fluentd", Map.of(
"config-file-type", "s3",
"config-file-value", "arn:aws:s3:::firelens-configs/extra.conf")));
ContainerDefinition app = new ContainerDefinition();
app.setName("app");
app.setImage("app:latest");
app.setLogConfiguration(new LogConfiguration("awsfirelens", Map.of("@type", "stdout"), null));
TaskDefinition taskDef = new TaskDefinition();
taskDef.setFamily("firelens-s3-fluentd");
taskDef.setRevision(1);
taskDef.setNetworkMode(NetworkMode.bridge);
taskDef.setContainerDefinitions(List.of(app, router));
EcsTask task = new EcsTask();
task.setTaskArn("arn:aws:ecs:us-east-1:000000000000:task/test-cluster/abc123");
task.setClusterArn("arn:aws:ecs:us-east-1:000000000000:cluster/test-cluster");
S3Object object = new S3Object();
object.setData("<match **>\n @type stdout\n</match>\n".getBytes(StandardCharsets.UTF_8));
when(s3Service.getObject("firelens-configs", "extra.conf")).thenReturn(object);
manager.startTask(task, taskDef, null, "us-east-1");
verify(copyCmd).withRemotePath("/fluentd/etc");
ArgumentCaptor<InputStream> configArchive = ArgumentCaptor.forClass(InputStream.class);
verify(copyCmd).withTarInputStream(configArchive.capture());
Map<String, String> files = readFirelensArchive(configArchive.getValue());
assertTrue(files.get("fluent.conf").contains(
"@include /fluentd/etc/external.conf"), files.get("fluent.conf"));
assertTrue(files.containsKey("external.conf"), files::toString);
}
@Test
void missingS3ConfigFailsTheTaskBeforeAnyContainerIsCreated() {
ContainerDefinition router = new ContainerDefinition();
router.setName("log_router");
router.setImage("amazon/aws-for-fluent-bit:stable");
router.setFirelensConfiguration(new FirelensConfiguration("fluentbit", Map.of(
"config-file-type", "s3",
"config-file-value", "arn:aws:s3:::firelens-configs/missing.conf")));
TaskDefinition taskDef = new TaskDefinition();
taskDef.setFamily("firelens-s3-missing");
taskDef.setRevision(1);
taskDef.setNetworkMode(NetworkMode.awsvpc);
taskDef.setContainerDefinitions(List.of(router));
EcsTask task = new EcsTask();
task.setTaskArn("arn:aws:ecs:us-east-1:000000000000:task/test-cluster/abc123");
task.setClusterArn("arn:aws:ecs:us-east-1:000000000000:cluster/test-cluster");
when(s3Service.getObject("firelens-configs", "missing.conf"))
.thenThrow(new AwsException("NoSuchKey", "The specified key does not exist.", 404));
AwsException failure = assertThrows(AwsException.class,
() -> manager.startTask(task, taskDef, null, "us-east-1"));
assertEquals("ResourceInitializationError", failure.getErrorCode());
assertEquals("Unable to download firelens s3 config file: unable to download s3 config "
+ "missing.conf from bucket firelens-configs: The specified key does not exist.",
failure.getMessage());
verify(lifecycleManager, never()).create(any(ContainerSpec.class));
verify(lifecycleManager, never()).createAndStart(any());
}
@Test
void rejectsAwsfirelensApplicationWithoutRouter() {
ContainerDefinition app = new ContainerDefinition();
app.setName("app");
app.setImage("app:latest");
app.setLogConfiguration(new LogConfiguration("awsfirelens", Map.of(), null));
AwsException failure = assertThrows(AwsException.class,
() -> manager.startTask(task(), taskDefinition(List.of(app)), null, "us-east-1"));
assertEquals("ClientException", failure.getErrorCode());
assertEquals("awsfirelens log driver requires a firelensConfiguration container",
failure.getMessage());
verify(lifecycleManager, never()).createAndStart(any());
}
@Test
void rejectsTwoFirelensRouters() {
AwsException failure = assertThrows(AwsException.class, () -> manager.startTask(
task(),
taskDefinition(List.of(
router("fluentbit", List.of()),
router("fluentd", List.of()))),
null, "us-east-1"));
assertEquals("ClientException", failure.getErrorCode());
assertEquals("A task definition can have only one FireLens log router.", failure.getMessage());
verify(lifecycleManager, never()).create(any(ContainerSpec.class));
verify(lifecycleManager, never()).createAndStart(any());
}
@Test
void rejectsFirelensRouterExposingPort24224() {
AwsException failure = assertThrows(AwsException.class, () -> manager.startTask(
task(),
taskDefinition(List.of(router("fluentbit", List.of(new PortMapping(24224, 0, "tcp"))))),
null, "us-east-1"));
assertEquals("ClientException", failure.getErrorCode());
assertEquals("FireLens port 24224 must not be exposed.", failure.getMessage());
verify(lifecycleManager, never()).create(any(ContainerSpec.class));
}
@Test
void rejectsUnsupportedFirelensRouterType() {
AwsException failure = assertThrows(AwsException.class, () -> manager.startTask(
task(),
taskDefinition(List.of(router("fluent-plugin", List.of()))),
null, "us-east-1"));
assertEquals("ClientException", failure.getErrorCode());
assertEquals("FireLens configuration type must be fluentbit or fluentd.", failure.getMessage());
verify(lifecycleManager, never()).create(any(ContainerSpec.class));
}
private static ContainerDefinition router(String type, List<PortMapping> portMappings) {
ContainerDefinition router = new ContainerDefinition();
router.setName("log_router");
router.setImage("amazon/aws-for-fluent-bit:stable");
router.setFirelensConfiguration(new FirelensConfiguration(type, Map.of()));
router.setPortMappings(portMappings);
return router;
}
private static TaskDefinition taskDefinition(List<ContainerDefinition> definitions) {
TaskDefinition taskDef = new TaskDefinition();
taskDef.setFamily("firelens-family");
taskDef.setRevision(1);
taskDef.setNetworkMode(NetworkMode.awsvpc);
taskDef.setContainerDefinitions(definitions);
return taskDef;
}
private static EcsTask task() {
EcsTask task = new EcsTask();
task.setTaskArn("arn:aws:ecs:us-east-1:000000000000:task/test-cluster/abc123");
task.setClusterArn("arn:aws:ecs:us-east-1:000000000000:cluster/test-cluster");
return task;
}
private static Map<String, String> readFirelensArchive(InputStream archive) {
LinkedHashMap<String, String> files = new LinkedHashMap<>();
try (TarArchiveInputStream tar = new TarArchiveInputStream(archive)) {
TarArchiveEntry entry;
while ((entry = tar.getNextEntry()) != null) {
files.put(entry.getName(), new String(tar.readAllBytes(), StandardCharsets.UTF_8));
}
} catch (Exception e) {
throw new IllegalStateException(e);
}
return files;
}
private static String readFluentBitConf(InputStream archive) {
try (TarArchiveInputStream tar = new TarArchiveInputStream(archive)) {
tar.getNextEntry();
// TarArchiveInputStream.read stops at the end of the current entry.
return new String(tar.readAllBytes(), StandardCharsets.UTF_8);
} catch (Exception e) {
throw new IllegalStateException(e);
}
return definition;
}
}
@@ -12,6 +12,7 @@ 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.secretsmanager.SecretsManagerService;
import io.github.hectorvent.floci.services.s3.S3Service;
import io.github.hectorvent.floci.services.ssm.SsmService;
import org.junit.jupiter.api.Test;
@@ -117,7 +118,7 @@ class EcsContainerManagerLifecycleTest {
return new EcsContainerManager(
mock(ContainerBuilder.class), lifecycleManager, mock(ContainerLogStreamer.class),
mock(ContainerDetector.class), mock(EmulatorConfig.class), mock(RegionResolver.class),
mock(LaunchedContainerAwsEnv.class), mock(SsmService.class), mock(SecretsManagerService.class),
mock(LaunchedContainerAwsEnv.class), mock(SsmService.class), mock(SecretsManagerService.class), mock(S3Service.class),
mock(EcrRegistryManager.class), mock(HostVolumePolicy.class));
}
}
@@ -15,6 +15,7 @@ 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.TaskDefinition;
import io.github.hectorvent.floci.services.secretsmanager.SecretsManagerService;
import io.github.hectorvent.floci.services.s3.S3Service;
import io.github.hectorvent.floci.services.ssm.SsmService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@@ -75,7 +76,7 @@ class EcsContainerManagerOverridesTest {
when(ecrRegistryManager.rewriteImageUri(anyString())).thenAnswer(inv -> inv.getArgument(0));
manager = new EcsContainerManager(containerBuilder, lifecycleManager, logStreamer,
containerDetector, config, regionResolver, awsEnv, ssmService, secretsManagerService,
containerDetector, config, regionResolver, awsEnv, ssmService, secretsManagerService, mock(S3Service.class),
ecrRegistryManager, mock(HostVolumePolicy.class));
}
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.ecs.container;
import com.github.dockerjava.api.DockerClient;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.docker.ContainerBuilder;
import io.github.hectorvent.floci.core.common.docker.ContainerDetector;
@@ -18,6 +19,7 @@ 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;
import io.github.hectorvent.floci.services.secretsmanager.SecretsManagerService;
import io.github.hectorvent.floci.services.s3.S3Service;
import io.github.hectorvent.floci.services.ssm.SsmService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@@ -25,6 +27,8 @@ 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;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyString;
@@ -92,7 +96,7 @@ class EcsContainerManagerPortMappingsTest {
when(ecrRegistryManager.rewriteImageUri(anyString())).thenAnswer(inv -> inv.getArgument(0));
manager = new EcsContainerManager(containerBuilder, lifecycleManager, logStreamer,
containerDetector, config, regionResolver, awsEnv, ssmService, secretsManagerService,
containerDetector, config, regionResolver, awsEnv, ssmService, secretsManagerService, mock(S3Service.class),
ecrRegistryManager, mock(HostVolumePolicy.class));
}
@@ -225,12 +229,13 @@ class EcsContainerManagerPortMappingsTest {
}
@Test
void firelensRouterUsesLoopbackOnlyDynamicPortBinding() {
void firelensRouterDeclaringTheForwardPortIsRejected() {
when(containerDetector.isRunningInContainer()).thenReturn(false);
ContainerDefinition router = new ContainerDefinition();
router.setName("router");
router.setImage("fluent/fluent-bit:latest");
router.setPortMappings(List.of(new PortMapping(24224)));
router.setFirelensConfiguration(new FirelensConfiguration("fluentbit", Map.of()));
ContainerDefinition app = new ContainerDefinition();
@@ -245,13 +250,10 @@ class EcsContainerManagerPortMappingsTest {
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()));
AwsException failure = assertThrows(AwsException.class,
() -> manager.startTask(task, taskDef, List.of(), "us-east-1"));
manager.startTask(task, taskDef, List.of(), "us-east-1");
verify(builder).withLoopbackPortBinding(24224, 0);
assertEquals("FireLens port 24224 must not be exposed.", failure.getMessage());
verify(builder, never()).withDynamicPort(24224);
}
}
@@ -17,6 +17,7 @@ import io.github.hectorvent.floci.services.ecs.model.KeyValuePair;
import io.github.hectorvent.floci.services.ecs.model.Secret;
import io.github.hectorvent.floci.services.ecs.model.TaskDefinition;
import io.github.hectorvent.floci.services.secretsmanager.SecretsManagerService;
import io.github.hectorvent.floci.services.s3.S3Service;
import io.github.hectorvent.floci.services.secretsmanager.model.SecretVersion;
import io.github.hectorvent.floci.services.ssm.SsmService;
import io.github.hectorvent.floci.services.ssm.model.Parameter;
@@ -69,7 +70,7 @@ class EcsContainerManagerSecretsTest {
when(ecrRegistryManager.rewriteImageUri(anyString())).thenAnswer(inv -> inv.getArgument(0));
manager = new EcsContainerManager(containerBuilder, lifecycleManager, logStreamer,
containerDetector, config, regionResolver, awsEnv, ssmService, secretsManagerService,
containerDetector, config, regionResolver, awsEnv, ssmService, secretsManagerService, mock(S3Service.class),
ecrRegistryManager, mock(HostVolumePolicy.class));
}
@@ -0,0 +1,254 @@
package io.github.hectorvent.floci.services.ecs.container;
import com.github.dockerjava.api.DockerClient;
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.ContainerLifecycleManager.ContainerInfo;
import io.github.hectorvent.floci.core.common.docker.ContainerLogStreamer;
import io.github.hectorvent.floci.core.common.docker.LaunchedContainerAwsEnv;
import io.github.hectorvent.floci.services.ec2.Ec2Service;
import io.github.hectorvent.floci.services.ec2.SecurityGroupFirewallManager;
import io.github.hectorvent.floci.services.ec2.model.GroupIdentifier;
import io.github.hectorvent.floci.services.ec2.model.NetworkInterface;
import io.github.hectorvent.floci.services.ec2.model.SecurityGroup;
import io.github.hectorvent.floci.services.ecr.registry.EcrRegistryManager;
import io.github.hectorvent.floci.services.ecs.model.AwsVpcConfiguration;
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.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.TaskDefinition;
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 java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.RETURNS_SELF;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* Regression for the FireLens launch-loop rewrite dropping the awsvpc
* security-group namespace join. prepareNetwork still creates the ENI;
* this asserts the per-container loop actually joins it.
*/
class EcsContainerManagerSecurityGroupTest {
private ContainerBuilder.Builder builder;
private ContainerLifecycleManager lifecycleManager;
private DockerClient dockerClient;
private ContainerDetector containerDetector;
private RegionResolver regionResolver;
private Ec2Service ec2Service;
private SecurityGroupFirewallManager firewallManager;
private EcsContainerManager manager;
@BeforeEach
void setUp() {
builder = mock(ContainerBuilder.Builder.class, RETURNS_SELF);
ContainerBuilder containerBuilder = mock(ContainerBuilder.class);
when(containerBuilder.newContainer(anyString())).thenReturn(builder);
lifecycleManager = mock(ContainerLifecycleManager.class);
when(lifecycleManager.createAndStart(any())).thenReturn(new ContainerInfo("docker-id", Map.of()));
dockerClient = mock(DockerClient.class, RETURNS_DEEP_STUBS);
when(lifecycleManager.getDockerClient()).thenReturn(dockerClient);
containerDetector = mock(ContainerDetector.class);
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
regionResolver = mock(RegionResolver.class);
when(regionResolver.getAccountId()).thenReturn("000000000000");
LaunchedContainerAwsEnv awsEnv = mock(LaunchedContainerAwsEnv.class);
when(awsEnv.sdkBaselineEnv(any(), any())).thenReturn(List.of());
EcrRegistryManager ecrRegistryManager = mock(EcrRegistryManager.class);
when(ecrRegistryManager.rewriteImageUri(anyString())).thenAnswer(inv -> inv.getArgument(0));
ec2Service = mock(Ec2Service.class);
firewallManager = mock(SecurityGroupFirewallManager.class);
manager = new EcsContainerManager(
containerBuilder, lifecycleManager, mock(ContainerLogStreamer.class),
containerDetector, config, regionResolver, awsEnv,
mock(SsmService.class), mock(SecretsManagerService.class), mock(S3Service.class),
ecrRegistryManager, mock(HostVolumePolicy.class),
ec2Service, firewallManager);
}
@Test
void awsvpcTaskWithFirewallJoinsHelperNamespaceAndSkipsHostPorts() {
when(containerDetector.isRunningInContainer()).thenReturn(false);
when(firewallManager.enabled()).thenReturn(true);
when(firewallManager.createNamespace(eq("ecs"), eq("abc123"), any(), any(), any(), any()))
.thenReturn(new SecurityGroupFirewallManager.Namespace("helper-id", "10.0.0.5"));
NetworkInterface eni = new NetworkInterface();
eni.setNetworkInterfaceId("eni-1");
eni.setVpcId("vpc-1");
eni.setPrivateIpAddress("10.0.0.10");
eni.setGroups(List.of(new GroupIdentifier("sg-1", "default")));
when(ec2Service.createNetworkInterface(any(), eq("subnet-1"), any(), any(), any(), any(), any()))
.thenReturn(eni);
SecurityGroup sg = new SecurityGroup();
sg.setGroupId("sg-1");
when(ec2Service.describeSecurityGroups(any(), eq(List.of("sg-1")), any(), any()))
.thenReturn(List.of(sg));
EcsTaskHandle handle = manager.startTask(awsvpcTask(), awsvpcTaskDef(List.of(new PortMapping(80, 80, "tcp"))),
List.of(), "us-east-1");
verify(builder).withNetworkMode("container:helper-id");
verify(builder).withLabels(Map.of("floci.security-group-workload", "true"));
verify(builder, never()).withPortBinding(anyInt(), anyInt());
verify(builder, never()).withDynamicPort(anyInt());
verify(builder, never()).withExposedPort(anyInt());
verify(dockerClient).inspectContainerCmd("helper-id");
verify(dockerClient, never()).inspectContainerCmd("docker-id");
verify(firewallManager).register(any(), eq("helper-id"), any());
assertEquals("eni-1", handle.getNetworkInterfaceId());
assertEquals("us-east-1", handle.getRegion());
}
@Test
void disabledFirewallDoesNotJoinNamespace() {
when(containerDetector.isRunningInContainer()).thenReturn(false);
when(firewallManager.enabled()).thenReturn(false);
manager.startTask(awsvpcTask(), awsvpcTaskDef(List.of(new PortMapping(80, 80, "tcp"))),
List.of(), "us-east-1");
verify(builder, never()).withNetworkMode(anyString());
verify(builder, never()).withLabels(Map.of("floci.security-group-workload", "true"));
verify(ec2Service, never()).createNetworkInterface(any(), any(), any(), any(), any(), any(), any());
verify(builder).withDynamicPort(80);
}
@Test
void stopTaskUnregistersEni() {
when(containerDetector.isRunningInContainer()).thenReturn(false);
when(firewallManager.enabled()).thenReturn(true);
when(firewallManager.createNamespace(eq("ecs"), eq("abc123"), any(), any(), any(), any()))
.thenReturn(new SecurityGroupFirewallManager.Namespace("helper-id", "10.0.0.5"));
NetworkInterface eni = new NetworkInterface();
eni.setNetworkInterfaceId("eni-1");
eni.setVpcId("vpc-1");
eni.setPrivateIpAddress("10.0.0.10");
eni.setGroups(List.of(new GroupIdentifier("sg-1", "default")));
when(ec2Service.createNetworkInterface(any(), eq("subnet-1"), any(), any(), any(), any(), any()))
.thenReturn(eni);
SecurityGroup sg = new SecurityGroup();
sg.setGroupId("sg-1");
when(ec2Service.describeSecurityGroups(any(), eq(List.of("sg-1")), any(), any()))
.thenReturn(List.of(sg));
DockerClient stopClient = mock(DockerClient.class, RETURNS_DEEP_STUBS);
when(lifecycleManager.getDockerClient()).thenReturn(dockerClient, dockerClient, stopClient);
EcsTaskHandle handle = manager.startTask(awsvpcTask(), awsvpcTaskDef(List.of()),
List.of(), "us-east-1");
manager.stopTaskAndCollectExitCodes(handle);
verify(firewallManager).unregister("eni-1");
verify(ec2Service).deleteNetworkInterface("us-east-1", "eni-1");
}
@Test
void firelensRouterAndAppBothJoinTheHelperNamespace() {
when(containerDetector.isRunningInContainer()).thenReturn(false);
when(firewallManager.enabled()).thenReturn(true);
when(firewallManager.createNamespace(eq("ecs"), eq("abc123"), any(), any(), any(), any()))
.thenReturn(new SecurityGroupFirewallManager.Namespace("helper-id", "10.0.0.5"));
NetworkInterface eni = new NetworkInterface();
eni.setNetworkInterfaceId("eni-1");
eni.setVpcId("vpc-1");
eni.setPrivateIpAddress("10.0.0.10");
eni.setGroups(List.of(new GroupIdentifier("sg-1", "default")));
when(ec2Service.createNetworkInterface(any(), eq("subnet-1"), any(), any(), any(), any(), any()))
.thenReturn(eni);
SecurityGroup sg = new SecurityGroup();
sg.setGroupId("sg-1");
when(ec2Service.describeSecurityGroups(any(), eq(List.of("sg-1")), any(), any()))
.thenReturn(List.of(sg));
when(lifecycleManager.create(any())).thenReturn("router-id");
when(lifecycleManager.startCreated(anyString(), any()))
.thenReturn(new ContainerInfo("router-id", Map.of()));
var inspectVolumeCmd = mock(com.github.dockerjava.api.command.InspectVolumeCmd.class);
var volume = mock(com.github.dockerjava.api.command.InspectVolumeResponse.class);
when(dockerClient.inspectVolumeCmd(anyString())).thenReturn(inspectVolumeCmd);
when(inspectVolumeCmd.exec()).thenReturn(volume);
when(volume.getMountpoint()).thenReturn("/var/lib/docker/volumes/floci-ecs-firelens-abc123/_data");
var copyCmd = mock(com.github.dockerjava.api.command.CopyArchiveToContainerCmd.class, RETURNS_SELF);
when(dockerClient.copyArchiveToContainerCmd("router-id")).thenReturn(copyCmd);
ContainerDefinition router = new ContainerDefinition();
router.setName("log_router");
router.setImage("amazon/aws-for-fluent-bit:stable");
router.setFirelensConfiguration(new io.github.hectorvent.floci.services.ecs.model.FirelensConfiguration(
"fluentbit", Map.of()));
ContainerDefinition app = new ContainerDefinition();
app.setName("app");
app.setImage("app:latest");
app.setLogConfiguration(new io.github.hectorvent.floci.services.ecs.model.LogConfiguration(
"awsfirelens", Map.of("Name", "cloudwatch"), null));
TaskDefinition taskDef = new TaskDefinition();
taskDef.setFamily("firelens-family");
taskDef.setRevision(1);
taskDef.setNetworkMode(NetworkMode.awsvpc);
taskDef.setContainerDefinitions(List.of(app, router));
manager.startTask(awsvpcTask(), taskDef, List.of(), "us-east-1");
verify(builder, times(2)).withNetworkMode("container:helper-id");
verify(builder, times(2)).withLabels(Map.of("floci.security-group-workload", "true"));
verify(firewallManager).createNamespace(eq("ecs"), eq("abc123"), any(), any(), any(), any());
verify(lifecycleManager).create(any());
verify(lifecycleManager).startCreated(eq("router-id"), any());
verify(lifecycleManager).createAndStart(any());
}
private static EcsTask awsvpcTask() {
AwsVpcConfiguration awsvpc = new AwsVpcConfiguration();
awsvpc.setSubnets(List.of("subnet-1"));
awsvpc.setSecurityGroups(List.of("sg-1"));
NetworkConfiguration network = new NetworkConfiguration();
network.setAwsvpcConfiguration(awsvpc);
EcsTask task = new EcsTask();
task.setTaskArn("arn:aws:ecs:us-east-1:000000000000:task/test-cluster/abc123");
task.setNetworkConfiguration(network);
return task;
}
private static TaskDefinition awsvpcTaskDef(List<PortMapping> ports) {
ContainerDefinition app = new ContainerDefinition();
app.setName("app");
app.setImage("app:latest");
app.setPortMappings(ports);
TaskDefinition taskDef = new TaskDefinition();
taskDef.setFamily("test-family");
taskDef.setNetworkMode(NetworkMode.awsvpc);
taskDef.setContainerDefinitions(List.of(app));
return taskDef;
}
}
@@ -17,6 +17,7 @@ import io.github.hectorvent.floci.services.ecs.model.MountPoint;
import io.github.hectorvent.floci.services.ecs.model.TaskDefinition;
import io.github.hectorvent.floci.services.ecs.model.Volume;
import io.github.hectorvent.floci.services.secretsmanager.SecretsManagerService;
import io.github.hectorvent.floci.services.s3.S3Service;
import io.github.hectorvent.floci.services.ssm.SsmService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@@ -87,7 +88,7 @@ class EcsContainerManagerVolumesTest {
manager = new EcsContainerManager(containerBuilder, lifecycleManager, logStreamer,
containerDetector, config, regionResolver, awsEnv, ssmService, secretsManagerService,
ecrRegistryManager, new HostVolumePolicy(config));
mock(S3Service.class), ecrRegistryManager, new HostVolumePolicy(config));
}
@Test
@@ -182,7 +183,7 @@ class EcsContainerManagerVolumesTest {
EcsContainerManager configured = new EcsContainerManager(containerBuilder, lifecycleManager,
mock(ContainerLogStreamer.class), mock(ContainerDetector.class), cfg,
mock(RegionResolver.class), awsEnv, mock(SsmService.class),
mock(SecretsManagerService.class), ecrRegistryManager, new HostVolumePolicy(cfg));
mock(SecretsManagerService.class), mock(S3Service.class), ecrRegistryManager, new HostVolumePolicy(cfg));
ContainerDefinition app = new ContainerDefinition();
app.setName("app");
@@ -217,7 +218,8 @@ class EcsContainerManagerVolumesTest {
EcsContainerManager configured = new EcsContainerManager(containerBuilder, lifecycleManager,
mock(ContainerLogStreamer.class), mock(ContainerDetector.class), cfg,
mock(RegionResolver.class), awsEnv, mock(SsmService.class),
mock(SecretsManagerService.class), ecrRegistryManager, new HostVolumePolicy(cfg));
mock(SecretsManagerService.class), mock(S3Service.class),
ecrRegistryManager, new HostVolumePolicy(cfg));
ContainerDefinition app = new ContainerDefinition();
app.setName("app");
@@ -0,0 +1,331 @@
package io.github.hectorvent.floci.services.ecs.container;
import org.junit.jupiter.api.Test;
import java.util.LinkedHashMap;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
class FirelensConfigGeneratorTest {
@Test
void fluentBitConfigMatchesEcsAgentShape() {
LinkedHashMap<String, String> options = new LinkedHashMap<>();
options.put("Name", "cloudwatch");
options.put("region", "us-east-1");
options.put("log_group_name", "app");
options.put("include-pattern", "*failure*");
options.put("exclude-pattern", "*success*");
options.put("log-driver-buffer-limit", "123");
LinkedHashMap<String, Map<String, String>> byContainer = new LinkedHashMap<>();
byContainer.put("app", options);
String config = FirelensConfigGenerator.fluentBitConfig(new FirelensConfigGenerator.Context(
"awsvpc", true, "mycluster",
"arn:aws:ecs:us-east-1:000000000000:task/mycluster/abc",
"taskdefinition:1", 100, "/extra.conf", null, byContainer));
assertEquals("""
[INPUT]
Name forward
unix_path /var/run/fluent.sock
Mem_Buf_Limit 50MB
[INPUT]
Name forward
Listen 0.0.0.0
Port 24224
[INPUT]
Name tcp
Tag firelens-healthcheck
Listen 127.0.0.1
Port 8877
[FILTER]
Name grep
Match app-firelens*
Regex log *failure*
[FILTER]
Name grep
Match app-firelens*
Exclude log *success*
[FILTER]
Name record_modifier
Match *
Record ecs_cluster mycluster
Record ecs_task_arn arn:aws:ecs:us-east-1:000000000000:task/mycluster/abc
Record ecs_task_definition taskdefinition:1
@INCLUDE /extra.conf
[OUTPUT]
Name null
Match firelens-healthcheck
[OUTPUT]
Name cloudwatch
Match app-firelens*
region us-east-1
log_group_name app
""", config);
}
@Test
void skipsGeneratedOutputWhenOnlyCustomFileIsUsed() {
LinkedHashMap<String, Map<String, String>> byContainer = new LinkedHashMap<>();
byContainer.put("app", Map.of());
String config = FirelensConfigGenerator.fluentBitConfig(new FirelensConfigGenerator.Context(
"bridge", false, "c", "arn", "fam:1", 0, null, null, byContainer));
assertTrue(config.contains("Listen 0.0.0.0"));
assertTrue(config.contains("Mem_Buf_Limit 25MB"));
assertTrue(!config.contains("record_modifier"));
assertTrue(!config.contains("Match app-firelens*"));
}
@Test
void rejectsPluginOptionsWithoutName() {
LinkedHashMap<String, Map<String, String>> byContainer = new LinkedHashMap<>();
byContainer.put("app", Map.of("region", "us-east-1"));
assertThrows(IllegalArgumentException.class, () -> FirelensConfigGenerator.fluentBitConfig(
new FirelensConfigGenerator.Context(
"bridge", false, "c", "arn", "fam:1", 0, null, null, byContainer)));
}
@Test
void pointsAwsOutputsAtFlociUnlessTheTaskDefinitionSetAnEndpoint() {
LinkedHashMap<String, String> app = new LinkedHashMap<>();
app.put("Name", "s3");
app.put("region", "us-east-1");
app.put("bucket", "logs");
LinkedHashMap<String, String> explicit = new LinkedHashMap<>();
explicit.put("Name", "s3");
explicit.put("endpoint", "https://real.example.com");
LinkedHashMap<String, String> http = new LinkedHashMap<>();
http.put("Name", "s3");
http.put("endpoint", "http://minio:9000");
LinkedHashMap<String, String> metrics = new LinkedHashMap<>();
metrics.put("Name", "stdout");
LinkedHashMap<String, Map<String, String>> byContainer = new LinkedHashMap<>();
byContainer.put("app", app);
byContainer.put("explicit", explicit);
byContainer.put("http", http);
byContainer.put("metrics", metrics);
String config = FirelensConfigGenerator.fluentBitConfig(new FirelensConfigGenerator.Context(
"bridge", false, "c", "arn", "fam:1", 0, null, "http://host.docker.internal:4566",
byContainer));
assertEquals("""
[INPUT]
Name forward
unix_path /var/run/fluent.sock
Mem_Buf_Limit 25MB
[INPUT]
Name forward
Listen 0.0.0.0
Port 24224
[INPUT]
Name tcp
Tag firelens-healthcheck
Listen 127.0.0.1
Port 8877
[OUTPUT]
Name null
Match firelens-healthcheck
[OUTPUT]
Name s3
Match app-firelens*
region us-east-1
bucket logs
Endpoint http://host.docker.internal:4566
tls Off
[OUTPUT]
Name s3
Match explicit-firelens*
endpoint https://real.example.com
[OUTPUT]
Name s3
Match http-firelens*
endpoint http://minio:9000
tls Off
[OUTPUT]
Name stdout
Match metrics-firelens*
""", config);
}
/**
* The upstream C plugins read {@code endpoint} as a bare host name and always dial TLS, so a
* Floci URL is a guaranteed DNS failure and a bare Floci host is a certificate failure. The
* Go plugins parse a URL, so those are still pointed at Floci.
*/
@Test
void injectsEndpointOnlyIntoPluginsThatReadAUrl() {
LinkedHashMap<String, String> kinesis = new LinkedHashMap<>();
kinesis.put("Name", "kinesis_streams");
kinesis.put("region", "us-east-1");
kinesis.put("stream", "logs");
LinkedHashMap<String, String> cwLogs = new LinkedHashMap<>();
cwLogs.put("Name", "cloudwatch_logs");
cwLogs.put("region", "us-east-1");
cwLogs.put("log_group_name", "app");
LinkedHashMap<String, String> goCloudwatch = new LinkedHashMap<>();
goCloudwatch.put("Name", "cloudwatch");
goCloudwatch.put("region", "us-east-1");
goCloudwatch.put("log_group_name", "app");
LinkedHashMap<String, Map<String, String>> byContainer = new LinkedHashMap<>();
byContainer.put("kinesis", kinesis);
byContainer.put("cwlogs", cwLogs);
byContainer.put("gocw", goCloudwatch);
String config = FirelensConfigGenerator.fluentBitConfig(new FirelensConfigGenerator.Context(
"bridge", false, "c", "arn", "fam:1", 0, null, "http://host.docker.internal:4566",
byContainer));
assertTrue(config.contains("""
[OUTPUT]
Name kinesis_streams
Match kinesis-firelens*
region us-east-1
stream logs
"""), config);
assertTrue(config.contains("""
[OUTPUT]
Name cloudwatch_logs
Match cwlogs-firelens*
region us-east-1
log_group_name app
"""), config);
assertTrue(config.contains("""
[OUTPUT]
Name cloudwatch
Match gocw-firelens*
region us-east-1
log_group_name app
Endpoint http://host.docker.internal:4566
tls Off
"""), config);
}
@Test
void fluentdConfigMatchesEcsAgentShape() {
LinkedHashMap<String, String> options = new LinkedHashMap<>();
options.put("@type", "kinesis_firehose");
options.put("region", "us-east-1");
options.put("delivery_stream_name", "demo-stream");
options.put("include-pattern", "*failure*");
options.put("exclude-pattern", "*success*");
options.put("log-driver-buffer-limit", "123");
LinkedHashMap<String, Map<String, String>> byContainer = new LinkedHashMap<>();
byContainer.put("app", options);
String config = FirelensConfigGenerator.fluentdConfig(new FirelensConfigGenerator.Context(
"awsvpc", true, "mycluster",
"arn:aws:ecs:us-east-1:000000000000:task/mycluster/abc",
"taskdefinition:1", 100, "/fluentd/etc/extra.conf",
"http://host.docker.internal:4566", byContainer));
assertEquals("""
<source>
@type unix
path /var/run/fluent.sock
</source>
<source>
@type forward
bind 0.0.0.0
port 24224
</source>
<filter app-firelens**>
@type grep
<regexp>
key log
pattern *failure*
</regexp>
</filter>
<filter app-firelens**>
@type grep
<exclude>
key log
pattern *success*
</exclude>
</filter>
<filter **>
@type record_transformer
<record>
ecs_cluster mycluster
ecs_task_arn arn:aws:ecs:us-east-1:000000000000:task/mycluster/abc
ecs_task_definition taskdefinition:1
</record>
</filter>
@include /fluentd/etc/extra.conf
<match app-firelens**>
@type kinesis_firehose
region us-east-1
delivery_stream_name demo-stream
</match>
""", config);
assertTrue(!config.contains("Endpoint"));
assertTrue(!config.contains("firelens-healthcheck"));
}
@Test
void fluentdSkipsGeneratedOutputWhenOnlyCustomFileIsUsed() {
LinkedHashMap<String, Map<String, String>> byContainer = new LinkedHashMap<>();
byContainer.put("app", Map.of());
String config = FirelensConfigGenerator.fluentdConfig(new FirelensConfigGenerator.Context(
"bridge", false, "c", "arn", "fam:1", 0, null, null, byContainer));
assertTrue(config.contains("@type unix"));
assertTrue(config.contains("@type forward"));
assertTrue(!config.contains("record_transformer"));
assertTrue(!config.contains("<match app-firelens**>"));
}
@Test
void fluentdRejectsPluginOptionsWithoutType() {
LinkedHashMap<String, Map<String, String>> byContainer = new LinkedHashMap<>();
byContainer.put("app", Map.of("region", "us-east-1"));
assertThrows(IllegalArgumentException.class, () -> FirelensConfigGenerator.fluentdConfig(
new FirelensConfigGenerator.Context(
"bridge", false, "c", "arn", "fam:1", 0, null, null, byContainer)));
}
}