mirror of
https://github.com/floci-io/floci.git
synced 2026-11-24 06:20:24 -05:00
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:
1 parent
caab63c602
commit
e32266537e
28 files changed
+2346
-333
No files matched your search
@@ -159,6 +159,35 @@ public final class AwsArnUtils {
|
||||
return account != null && !account.isEmpty() && !account.equals(localAccountId);
|
||||
}
|
||||
|
||||
/**
|
||||
* The bucket and key named by an S3 object ARN ({@code arn:aws:s3:::bucket/key}, or the
|
||||
* region/account-bearing form {@code arn:aws:s3:region:account:bucket/key}).
|
||||
*
|
||||
* <p>Returns {@code null} rather than throwing when the value is not one: not an ARN, not
|
||||
* the {@code s3} service, or a resource without both a bucket and a key. Callers decide
|
||||
* whether that is a registration error (ECS rejecting a FireLens {@code config-file-value})
|
||||
* or a launch error.
|
||||
*/
|
||||
public static S3ObjectRef parseS3ObjectArn(String value) {
|
||||
if (!isArn(value)) {
|
||||
return null;
|
||||
}
|
||||
Arn arn = parse(value);
|
||||
if (!"s3".equals(arn.service())) {
|
||||
return null;
|
||||
}
|
||||
String resource = arn.resource();
|
||||
int slash = resource.indexOf('/');
|
||||
if (slash <= 0 || slash == resource.length() - 1) {
|
||||
return null;
|
||||
}
|
||||
return new S3ObjectRef(resource.substring(0, slash), resource.substring(slash + 1));
|
||||
}
|
||||
|
||||
/** The bucket and key of an S3 object ARN, as returned by {@link #parseS3ObjectArn}. */
|
||||
public record S3ObjectRef(String bucket, String key) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts an SQS ARN to a queue URL using the given base URL.
|
||||
* Example: arn:aws:sqs:us-east-1:000000000000:my-queue → http://localhost:4566/000000000000/my-queue
|
||||
|
||||
+10
@@ -62,6 +62,16 @@ public class LaunchedContainerAwsEnv {
|
||||
return sdkBaselineEnv(region, awsConfigMountDir, reachableEndpoint.baseUrl(), Optional.empty());
|
||||
}
|
||||
|
||||
/**
|
||||
* The Floci base URL this env points a launched container at, i.e. the value of the
|
||||
* {@code AWS_ENDPOINT_URL} entry above. Callers that configure something other than an
|
||||
* AWS SDK (a Fluent Bit output in a FireLens router, say) reuse it so both agree on how
|
||||
* the container reaches Floci.
|
||||
*/
|
||||
public String flociEndpoint() {
|
||||
return reachableEndpoint.baseUrl();
|
||||
}
|
||||
|
||||
/**
|
||||
* Variant for launchers whose workloads reach Floci at an address other than the
|
||||
* Docker-reachable one (e.g. Kubernetes pods reaching Floci's pod IP).
|
||||
|
||||
+30
@@ -10,8 +10,10 @@ import io.github.hectorvent.floci.services.ecs.model.ContainerDefinition;
|
||||
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;
|
||||
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.LogConfiguration;
|
||||
import io.github.hectorvent.floci.services.ecs.model.NetworkConfiguration;
|
||||
import io.github.hectorvent.floci.services.ecs.model.NetworkMode;
|
||||
import io.github.hectorvent.floci.services.ecs.model.PortMapping;
|
||||
@@ -22,6 +24,7 @@ import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
@@ -270,6 +273,8 @@ public class EcsCfnProvisioner implements CfnResourceProvisioner {
|
||||
def.setPortMappings(parsePortMappings(item.path("PortMappings")));
|
||||
def.setEnvironment(parseEnvironment(item.path("Environment")));
|
||||
def.setSecrets(parseSecrets(item.path("Secrets")));
|
||||
def.setLogConfiguration(parseLogConfiguration(item.path("LogConfiguration")));
|
||||
def.setFirelensConfiguration(parseFirelensConfiguration(item.path("FirelensConfiguration")));
|
||||
if (item.path("Command").isArray()) {
|
||||
def.setCommand(toStringList(item.path("Command")));
|
||||
}
|
||||
@@ -281,6 +286,31 @@ public class EcsCfnProvisioner implements CfnResourceProvisioner {
|
||||
return result;
|
||||
}
|
||||
|
||||
private static LogConfiguration parseLogConfiguration(JsonNode node) {
|
||||
if (node == null || !node.isObject() || !node.hasNonNull("LogDriver")) {
|
||||
return null;
|
||||
}
|
||||
return new LogConfiguration(node.path("LogDriver").asText(),
|
||||
parseOptions(node.path("Options")),
|
||||
node.has("SecretOptions") ? parseSecrets(node.path("SecretOptions")) : null);
|
||||
}
|
||||
|
||||
private static FirelensConfiguration parseFirelensConfiguration(JsonNode node) {
|
||||
if (node == null || !node.isObject() || !node.hasNonNull("Type")) {
|
||||
return null;
|
||||
}
|
||||
return new FirelensConfiguration(node.path("Type").asText(), parseOptions(node.path("Options")));
|
||||
}
|
||||
|
||||
private static LinkedHashMap<String, String> parseOptions(JsonNode node) {
|
||||
if (node == null || !node.isObject()) {
|
||||
return null;
|
||||
}
|
||||
LinkedHashMap<String, String> options = new LinkedHashMap<>();
|
||||
node.fields().forEachRemaining(entry -> options.put(entry.getKey(), entry.getValue().asText()));
|
||||
return options;
|
||||
}
|
||||
|
||||
private static List<PortMapping> parsePortMappings(JsonNode node) {
|
||||
List<PortMapping> result = new ArrayList<>();
|
||||
if (node == null || !node.isArray()) {
|
||||
|
||||
@@ -18,6 +18,7 @@ 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;
|
||||
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.LogConfiguration;
|
||||
@@ -1138,7 +1139,6 @@ public class EcsJsonHandler {
|
||||
}
|
||||
n.set("firelensConfiguration", firelensNode);
|
||||
}
|
||||
|
||||
if (def.getHealthCheck() != null) {
|
||||
HealthCheck hc = def.getHealthCheck();
|
||||
ObjectNode hcNode = objectMapper.createObjectNode();
|
||||
@@ -1497,7 +1497,8 @@ public class EcsJsonHandler {
|
||||
}
|
||||
def.setMountPoints(parseMountPoints(item.path("mountPoints")));
|
||||
def.setLogConfiguration(parseLogConfiguration(item.path("logConfiguration")));
|
||||
def.setFirelensConfiguration(parseFirelensConfiguration(item.path("firelensConfiguration")));
|
||||
def.setFirelensConfiguration(parseFirelensConfiguration(
|
||||
item.path("firelensConfiguration"), result.size() + 1));
|
||||
if (item.has("healthCheck")) {
|
||||
def.setHealthCheck(parseHealthCheck(item.path("healthCheck")));
|
||||
}
|
||||
@@ -1585,20 +1586,33 @@ public class EcsJsonHandler {
|
||||
return new LogConfiguration(logDriver, options, secretOptions);
|
||||
}
|
||||
|
||||
private FirelensConfiguration parseFirelensConfiguration(JsonNode node) {
|
||||
if (node == null || !node.isObject() || !node.has("type")) {
|
||||
private FirelensConfiguration parseFirelensConfiguration(JsonNode node, int containerIndex) {
|
||||
if (node == null || !node.isObject()) {
|
||||
return null;
|
||||
}
|
||||
if (!node.hasNonNull("type")) {
|
||||
throw new AwsException("ClientException",
|
||||
"1 validation error detected: Value null at 'containerDefinitions." + containerIndex
|
||||
+ ".member.firelensConfiguration.type' failed to satisfy constraint: Member must not be null",
|
||||
400);
|
||||
}
|
||||
String type = node.path("type").asText();
|
||||
if (!"fluentd".equals(type) && !"fluentbit".equals(type)) {
|
||||
throw new AwsException("ClientException",
|
||||
"1 validation error detected: Value '" + type + "' at 'containerDefinitions." + containerIndex
|
||||
+ ".member.firelensConfiguration.type' failed to satisfy constraint: "
|
||||
+ "Member must satisfy enum value set: [fluentd, fluentbit]",
|
||||
400);
|
||||
}
|
||||
Map<String, String> options = null;
|
||||
if (node.path("options").isObject()) {
|
||||
Map<String, String> parsed = new LinkedHashMap<>();
|
||||
LinkedHashMap<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);
|
||||
return new FirelensConfiguration(type, options);
|
||||
}
|
||||
|
||||
private HealthCheck parseHealthCheck(JsonNode node) {
|
||||
if (node == null || !node.isObject()) {
|
||||
return null;
|
||||
|
||||
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.ecs;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.ContainerTeardown;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
@@ -24,6 +25,7 @@ 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;
|
||||
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.LaunchType;
|
||||
import io.github.hectorvent.floci.services.ecs.model.NetworkConfiguration;
|
||||
import io.github.hectorvent.floci.services.ecs.model.NetworkMode;
|
||||
@@ -61,7 +63,6 @@ import java.util.stream.Stream;
|
||||
import io.github.hectorvent.floci.core.resource.ExplorerResource;
|
||||
import io.github.hectorvent.floci.core.resource.ResourceProvider;
|
||||
import io.github.hectorvent.floci.core.resource.SupportedResourceType;
|
||||
import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
|
||||
@ApplicationScoped
|
||||
public class EcsService implements ContainerTeardown, ResourceProvider, Resettable {
|
||||
@@ -370,7 +371,8 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
|
||||
String taskRoleArn, String executionRoleArn,
|
||||
List<String> requiresCompatibilities,
|
||||
Map<String, String> tags, String region) {
|
||||
if (requiresCompatibilities != null && requiresCompatibilities.contains("FARGATE")) {
|
||||
boolean fargate = requiresCompatibilities != null && requiresCompatibilities.contains("FARGATE");
|
||||
if (fargate) {
|
||||
if (networkMode != NetworkMode.awsvpc) {
|
||||
throw new AwsException("ClientException", "Fargate only supports network mode 'awsvpc'.", 400);
|
||||
}
|
||||
@@ -384,6 +386,7 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
|
||||
throw new AwsException("ClientException", "No Fargate configuration exists for given values.", 400);
|
||||
}
|
||||
}
|
||||
validateFirelensS3Config(containerDefs, fargate);
|
||||
int revision = latestRevisions.merge(family, 1, Integer::sum);
|
||||
|
||||
TaskDefinition td = new TaskDefinition();
|
||||
@@ -415,6 +418,40 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
|
||||
return td;
|
||||
}
|
||||
|
||||
/**
|
||||
* RegisterTaskDefinition-time validation of a FireLens config that comes from S3, in the
|
||||
* order ECS applies it.
|
||||
*
|
||||
* <p>The Fargate platform cannot pull the object itself, so ECS rejects the combination
|
||||
* outright with this exact wording. 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. An
|
||||
* EC2-compatible task definition keeps {@code s3}: the agent pulls it, and Floci reads the
|
||||
* object from its own S3 at launch.
|
||||
*
|
||||
* <p>A {@code config-file-value} that does not name an S3 object is rejected as an ARN syntax
|
||||
* error, which is what the RegisterTaskDefinition API returns for this field.
|
||||
*/
|
||||
private static void validateFirelensS3Config(List<ContainerDefinition> containerDefs, boolean fargate) {
|
||||
if (containerDefs == null) {
|
||||
return;
|
||||
}
|
||||
for (ContainerDefinition def : containerDefs) {
|
||||
FirelensConfiguration firelens = def.getFirelensConfiguration();
|
||||
if (firelens == null || firelens.options() == null
|
||||
|| !"s3".equals(firelens.options().get("config-file-type"))) {
|
||||
continue;
|
||||
}
|
||||
if (fargate) {
|
||||
throw new AwsException("ClientException",
|
||||
"Fargate launch type does not support FirelensConfiguration config file from 's3'", 400);
|
||||
}
|
||||
if (AwsArnUtils.parseS3ObjectArn(firelens.options().get("config-file-value")) == null) {
|
||||
throw new AwsException("ClientException", "Invalid arn syntax", 400);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private boolean isValidFargateCpuMemory(String cpuStr, String memStr) {
|
||||
if (cpuStr == null || memStr == null) return false;
|
||||
int cpu = parseCpu(cpuStr);
|
||||
|
||||
+458
-214
@@ -25,6 +25,8 @@ import io.github.hectorvent.floci.services.ecs.model.ContainerDefinition;
|
||||
import io.github.hectorvent.floci.services.ecs.model.ContainerOverride;
|
||||
import io.github.hectorvent.floci.services.ecs.model.EcsTask;
|
||||
import io.github.hectorvent.floci.services.ecs.model.EfsVolumeConfiguration;
|
||||
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.MountPoint;
|
||||
import io.github.hectorvent.floci.services.ecs.model.NetworkBinding;
|
||||
import io.github.hectorvent.floci.services.ecs.model.NetworkMode;
|
||||
@@ -32,17 +34,26 @@ import io.github.hectorvent.floci.services.ecs.model.PortMapping;
|
||||
import io.github.hectorvent.floci.services.ecs.model.Secret;
|
||||
import io.github.hectorvent.floci.services.ecs.model.TaskDefinition;
|
||||
import io.github.hectorvent.floci.services.ecs.model.Volume;
|
||||
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 com.github.dockerjava.api.DockerClient;
|
||||
import com.github.dockerjava.api.command.InspectContainerResponse;
|
||||
import com.github.dockerjava.api.exception.NotFoundException;
|
||||
import com.github.dockerjava.api.model.ContainerNetwork;
|
||||
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.apache.commons.compress.archivers.tar.TarArchiveEntry;
|
||||
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.io.Closeable;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
@@ -54,7 +65,6 @@ 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;
|
||||
|
||||
@@ -76,60 +86,12 @@ public class EcsContainerManager {
|
||||
private final LaunchedContainerAwsEnv awsEnv;
|
||||
private final SsmService ssmService;
|
||||
private final SecretsManagerService secretsManagerService;
|
||||
private final S3Service s3Service;
|
||||
private final EcrRegistryManager ecrRegistryManager;
|
||||
private final HostVolumePolicy hostVolumePolicy;
|
||||
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,
|
||||
@@ -140,12 +102,13 @@ public class EcsContainerManager {
|
||||
LaunchedContainerAwsEnv awsEnv,
|
||||
SsmService ssmService,
|
||||
SecretsManagerService secretsManagerService,
|
||||
S3Service s3Service,
|
||||
EcrRegistryManager ecrRegistryManager,
|
||||
HostVolumePolicy hostVolumePolicy,
|
||||
Ec2Service ec2Service,
|
||||
SecurityGroupFirewallManager firewallManager) {
|
||||
this(containerBuilder, lifecycleManager, logStreamer, containerDetector, config, regionResolver,
|
||||
awsEnv, ssmService, secretsManagerService, ecrRegistryManager, hostVolumePolicy);
|
||||
awsEnv, ssmService, secretsManagerService, s3Service, ecrRegistryManager, hostVolumePolicy);
|
||||
this.ec2Service = ec2Service;
|
||||
this.firewallManager = firewallManager;
|
||||
}
|
||||
@@ -159,6 +122,7 @@ public class EcsContainerManager {
|
||||
LaunchedContainerAwsEnv awsEnv,
|
||||
SsmService ssmService,
|
||||
SecretsManagerService secretsManagerService,
|
||||
S3Service s3Service,
|
||||
EcrRegistryManager ecrRegistryManager,
|
||||
HostVolumePolicy hostVolumePolicy) {
|
||||
this.containerBuilder = containerBuilder;
|
||||
@@ -170,6 +134,7 @@ public class EcsContainerManager {
|
||||
this.awsEnv = awsEnv;
|
||||
this.ssmService = ssmService;
|
||||
this.secretsManagerService = secretsManagerService;
|
||||
this.s3Service = s3Service;
|
||||
this.hostVolumePolicy = hostVolumePolicy;
|
||||
this.ecrRegistryManager = ecrRegistryManager;
|
||||
}
|
||||
@@ -205,180 +170,208 @@ 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 : orderedDefinitions) {
|
||||
for (ContainerDefinition def : taskDef.getContainerDefinitions()) {
|
||||
envVarsByContainer.put(def, buildEnvVars(def, overridesByName.get(def.getName()), region));
|
||||
imagesByContainer.put(def, ecrRegistryManager.rewriteImageUri(def.getImage()));
|
||||
}
|
||||
|
||||
ContainerDefinition firelensRouter = findFirelensRouter(taskDef.getContainerDefinitions());
|
||||
Map<String, Map<String, String>> firelensLogOptions =
|
||||
awsFirelensLogOptions(taskDef.getContainerDefinitions());
|
||||
if (!firelensLogOptions.isEmpty() && firelensRouter == null) {
|
||||
throw new AwsException("ClientException",
|
||||
"awsfirelens log driver requires a firelensConfiguration container", 400);
|
||||
}
|
||||
|
||||
PreparedNetwork protectedNetwork = prepareNetwork(task, taskDef, region, taskId);
|
||||
|
||||
try {
|
||||
for (ContainerDefinition def : orderedDefinitions) {
|
||||
String containerName = ContainerStorageHelper.dockerName(config, "floci-ecs-" + taskId + "-" + def.getName());
|
||||
|
||||
// RunTask containerOverrides matched by container name: command replaces
|
||||
// the task-def command; environment is merged over the task-def environment.
|
||||
ContainerOverride override = overridesByName.get(def.getName());
|
||||
|
||||
// Build container spec
|
||||
ContainerBuilder.Builder specBuilder = containerBuilder.newContainer(imagesByContainer.get(def))
|
||||
.withName(containerName)
|
||||
.withEnv(envVarsByContainer.get(def))
|
||||
.withDockerNetwork(config.services().ecs().dockerNetwork())
|
||||
// Resolve Floci's endpoint from inside the task container the same way Lambda
|
||||
// containers do: host.docker.internal on Linux, plus Floci's embedded DNS so the
|
||||
// reachable AWS_ENDPOINT_URL hostname resolves to Floci instead of the container's
|
||||
// own loopback.
|
||||
.withHostDockerInternalOnLinux()
|
||||
.withEmbeddedDns()
|
||||
.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
|
||||
if (def.getMemory() != null) {
|
||||
specBuilder.withMemoryMb(def.getMemory());
|
||||
}
|
||||
|
||||
// Add port mappings. In bridge/host mode an explicit hostPort is
|
||||
// published to the Docker host literally, matching AWS bridge mode
|
||||
// (mirrors the ECR registry's fixed-port publishing). In awsvpc mode
|
||||
// every AWS task gets its own ENI, so a literal hostPort carries no
|
||||
// host-binding semantics and would collide across tasks on the single
|
||||
// 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 && !firelensApplication && def.getPortMappings() != null) {
|
||||
boolean awsvpc = taskDef.getNetworkMode() == NetworkMode.awsvpc;
|
||||
boolean publishToHost = !containerDetector.isRunningInContainer();
|
||||
for (PortMapping pm : def.getPortMappings()) {
|
||||
if (!awsvpc && pm.hostPort() > 0) {
|
||||
specBuilder.withPortBinding(pm.containerPort(), pm.hostPort());
|
||||
} else if (publishToHost) {
|
||||
specBuilder.withDynamicPort(pm.containerPort());
|
||||
} else {
|
||||
specBuilder.withExposedPort(pm.containerPort());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Add command and entrypoint if specified. An override command (from
|
||||
// RunTask containerOverrides) takes precedence over the task-def command.
|
||||
List<String> effectiveCommand =
|
||||
(override != null && override.getCommand() != null && !override.getCommand().isEmpty())
|
||||
? override.getCommand()
|
||||
: def.getCommand();
|
||||
if (effectiveCommand != null && !effectiveCommand.isEmpty()) {
|
||||
specBuilder.withCmd(effectiveCommand);
|
||||
}
|
||||
if (def.getEntryPoint() != null && !def.getEntryPoint().isEmpty()) {
|
||||
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.
|
||||
if (def.getMountPoints() != null) {
|
||||
for (MountPoint mp : def.getMountPoints()) {
|
||||
if (mp.containerPath() == null) {
|
||||
continue;
|
||||
}
|
||||
String sourcePath = volumeSourcePaths.get(mp.sourceVolume());
|
||||
EfsVolumeConfiguration efs = efsVolumes.get(mp.sourceVolume());
|
||||
if (sourcePath != null) {
|
||||
// Host volume: bind-mount an absolute path on the Docker host. Re-validate
|
||||
// here (not just at RegisterTaskDefinition time): this narrows the window
|
||||
// between validation and mount for a symlink swapped in afterward, and
|
||||
// also covers task definitions persisted before this policy existed. A
|
||||
// rejection is not swallowed, it propagates out of startTask and is
|
||||
// surfaced by EcsService as the task's stoppedReason.
|
||||
hostVolumePolicy.validate(sourcePath);
|
||||
if (mp.readOnly()) {
|
||||
specBuilder.withReadOnlyBind(sourcePath, mp.containerPath());
|
||||
} else {
|
||||
specBuilder.withBind(sourcePath, mp.containerPath());
|
||||
}
|
||||
} else if (efs != null) {
|
||||
mountEfsVolume(specBuilder, efs, mp);
|
||||
} else {
|
||||
LOG.warnv("Skipping mountPoint with unresolved volume {0} on container {1}",
|
||||
mp.sourceVolume(), def.getName());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ContainerSpec spec = specBuilder.build();
|
||||
|
||||
// Create and start container
|
||||
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
|
||||
List<NetworkBinding> networkBindings = resolveNetworkBindings(
|
||||
protectedNetwork == null ? dockerId : protectedNetwork.namespace().helperId(), def);
|
||||
|
||||
// Build ECS container model
|
||||
Container container = buildContainer(task.getTaskArn(), def, dockerId, networkBindings, region);
|
||||
runtimeContainers.add(container);
|
||||
containerIds.put(def.getName(), dockerId);
|
||||
|
||||
// Attach log streaming
|
||||
String logGroup = "/ecs/" + taskDef.getFamily();
|
||||
String logStream = logStreamer.generateLogStreamName(def.getName() + "/" + taskId);
|
||||
|
||||
if (!firelensApplication) {
|
||||
Closeable logHandle = logStreamer.attach(
|
||||
dockerId, logGroup, logStream, region,
|
||||
"ecs:" + taskDef.getFamily() + ":" + def.getName());
|
||||
if (logHandle != null) {
|
||||
logStreamsByContainerId.put(dockerId, logHandle);
|
||||
}
|
||||
}
|
||||
String firelensVolumeName = null;
|
||||
String firelensSocketAddress = null;
|
||||
String firelensConfig = null;
|
||||
String firelensExternalConfig = null;
|
||||
if (firelensRouter != null) {
|
||||
firelensConfig = firelensConfig(task, taskDef, firelensRouter, firelensLogOptions);
|
||||
firelensExternalConfig = s3ExternalConfig(firelensRouter);
|
||||
firelensVolumeName = ContainerStorageHelper.dockerName(config, "floci-ecs-firelens-" + taskId);
|
||||
lifecycleManager.ensureVolume(firelensVolumeName);
|
||||
firelensSocketAddress = unixSocketAddress(firelensVolumeName);
|
||||
}
|
||||
|
||||
List<ContainerDefinition> launchOrder =
|
||||
launchOrder(taskDef.getContainerDefinitions(), firelensRouter);
|
||||
String fluentHost = null;
|
||||
String networkModeName = taskDef.getNetworkMode() != null
|
||||
? taskDef.getNetworkMode().name()
|
||||
: NetworkMode.bridge.name();
|
||||
|
||||
try {
|
||||
for (ContainerDefinition def : launchOrder) {
|
||||
String containerName = ContainerStorageHelper.dockerName(config, "floci-ecs-" + taskId + "-" + def.getName());
|
||||
|
||||
// RunTask containerOverrides matched by container name: command replaces
|
||||
// the task-def command; environment is merged over the task-def environment.
|
||||
ContainerOverride override = overridesByName.get(def.getName());
|
||||
|
||||
List<String> env = new ArrayList<>(envVarsByContainer.get(def));
|
||||
if (fluentHost != null && def != firelensRouter
|
||||
&& FirelensConfigGenerator.addsTcpForward(networkModeName)) {
|
||||
env.add("FLUENT_HOST=" + fluentHost);
|
||||
env.add("FLUENT_PORT=" + FirelensConfigGenerator.FORWARD_PORT);
|
||||
}
|
||||
|
||||
// Build container spec
|
||||
ContainerBuilder.Builder specBuilder = containerBuilder.newContainer(imagesByContainer.get(def))
|
||||
.withName(containerName)
|
||||
.withEnv(env)
|
||||
.withDockerNetwork(config.services().ecs().dockerNetwork())
|
||||
// Resolve Floci's endpoint from inside the task container the same way Lambda
|
||||
// containers do: host.docker.internal on Linux, plus Floci's embedded DNS so the
|
||||
// reachable AWS_ENDPOINT_URL hostname resolves to Floci instead of the container's
|
||||
// own loopback.
|
||||
.withHostDockerInternalOnLinux()
|
||||
.withEmbeddedDns()
|
||||
.withLabels(ContainerStorageHelper.resourceIdentityLabels(
|
||||
"ecs", taskId, regionResolver.getAccountId(), region));
|
||||
if (protectedNetwork != null) {
|
||||
specBuilder.withNetworkMode("container:" + protectedNetwork.namespace().helperId());
|
||||
specBuilder.withLabels(Map.of("floci.security-group-workload", "true"));
|
||||
}
|
||||
|
||||
boolean awsFirelens = isAwsFirelens(def);
|
||||
if (awsFirelens) {
|
||||
specBuilder.withLogConfig(awsFirelensLogConfig(def, taskId, firelensSocketAddress));
|
||||
} else {
|
||||
specBuilder.withLogRotation();
|
||||
}
|
||||
|
||||
if (def == firelensRouter && firelensVolumeName != null) {
|
||||
specBuilder.withNamedVolume(firelensVolumeName, "/var/run");
|
||||
}
|
||||
|
||||
// Add memory limit if specified
|
||||
if (def.getMemory() != null) {
|
||||
specBuilder.withMemoryMb(def.getMemory());
|
||||
}
|
||||
|
||||
// Add port mappings. In bridge/host mode an explicit hostPort is
|
||||
// published to the Docker host literally, matching AWS bridge mode
|
||||
// (mirrors the ECR registry's fixed-port publishing). In awsvpc mode
|
||||
// every AWS task gets its own ENI, so a literal hostPort carries no
|
||||
// host-binding semantics and would collide across tasks on the single
|
||||
// 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) {
|
||||
boolean awsvpc = taskDef.getNetworkMode() == NetworkMode.awsvpc;
|
||||
boolean publishToHost = !containerDetector.isRunningInContainer();
|
||||
for (PortMapping pm : def.getPortMappings()) {
|
||||
if (!awsvpc && pm.hostPort() > 0) {
|
||||
specBuilder.withPortBinding(pm.containerPort(), pm.hostPort());
|
||||
} else if (publishToHost) {
|
||||
specBuilder.withDynamicPort(pm.containerPort());
|
||||
} else {
|
||||
specBuilder.withExposedPort(pm.containerPort());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Add command and entrypoint if specified. An override command (from
|
||||
// RunTask containerOverrides) takes precedence over the task-def command.
|
||||
List<String> effectiveCommand =
|
||||
(override != null && override.getCommand() != null && !override.getCommand().isEmpty())
|
||||
? override.getCommand()
|
||||
: def.getCommand();
|
||||
if (effectiveCommand != null && !effectiveCommand.isEmpty()) {
|
||||
specBuilder.withCmd(effectiveCommand);
|
||||
}
|
||||
if (def.getEntryPoint() != null && !def.getEntryPoint().isEmpty()) {
|
||||
specBuilder.withEntrypoint(def.getEntryPoint());
|
||||
}
|
||||
|
||||
// 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.
|
||||
if (def.getMountPoints() != null) {
|
||||
for (MountPoint mp : def.getMountPoints()) {
|
||||
if (mp.containerPath() == null) {
|
||||
continue;
|
||||
}
|
||||
String sourcePath = volumeSourcePaths.get(mp.sourceVolume());
|
||||
EfsVolumeConfiguration efs = efsVolumes.get(mp.sourceVolume());
|
||||
if (sourcePath != null) {
|
||||
// Host volume: bind-mount an absolute path on the Docker host. Re-validate
|
||||
// here (not just at RegisterTaskDefinition time): this narrows the window
|
||||
// between validation and mount for a symlink swapped in afterward, and
|
||||
// also covers task definitions persisted before this policy existed. A
|
||||
// rejection is not swallowed, it propagates out of startTask and is
|
||||
// surfaced by EcsService as the task's stoppedReason.
|
||||
hostVolumePolicy.validate(sourcePath);
|
||||
if (mp.readOnly()) {
|
||||
specBuilder.withReadOnlyBind(sourcePath, mp.containerPath());
|
||||
} else {
|
||||
specBuilder.withBind(sourcePath, mp.containerPath());
|
||||
}
|
||||
} else if (efs != null) {
|
||||
mountEfsVolume(specBuilder, efs, mp);
|
||||
} else {
|
||||
LOG.warnv("Skipping mountPoint with unresolved volume {0} on container {1}",
|
||||
mp.sourceVolume(), def.getName());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ContainerSpec spec = specBuilder.build();
|
||||
|
||||
String dockerId;
|
||||
if (def == firelensRouter) {
|
||||
dockerId = lifecycleManager.create(spec);
|
||||
try {
|
||||
copyFirelensConfig(dockerId, firelensConfig, isFluentdRouter(firelensRouter),
|
||||
firelensExternalConfig);
|
||||
lifecycleManager.startCreated(dockerId, spec);
|
||||
} catch (RuntimeException e) {
|
||||
lifecycleManager.removeIfExists(dockerId);
|
||||
throw e;
|
||||
}
|
||||
fluentHost = inspectContainerIp(dockerId);
|
||||
} else {
|
||||
ContainerInfo info = lifecycleManager.createAndStart(spec);
|
||||
dockerId = info.containerId();
|
||||
}
|
||||
|
||||
LOG.infov("Created ECS container {0} for task {1} container {2}", dockerId, taskId, def.getName());
|
||||
|
||||
// Resolve network bindings for ECS-specific model
|
||||
List<NetworkBinding> networkBindings = resolveNetworkBindings(
|
||||
protectedNetwork == null ? dockerId : protectedNetwork.namespace().helperId(), def);
|
||||
|
||||
// Build ECS container model
|
||||
Container container = buildContainer(task.getTaskArn(), def, dockerId, networkBindings, region);
|
||||
runtimeContainers.add(container);
|
||||
containerIds.put(def.getName(), dockerId);
|
||||
|
||||
// awsfirelens containers are shipped to Fluent Bit by Docker; don't also scrape json-file.
|
||||
if (!awsFirelens) {
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
for (String dockerId : containerIds.values()) {
|
||||
lifecycleManager.stopAndRemove(dockerId, null);
|
||||
}
|
||||
if (firelensVolumeName != null) {
|
||||
lifecycleManager.removeVolume(firelensVolumeName);
|
||||
}
|
||||
if (protectedNetwork != null) {
|
||||
firewallManager.unregister(protectedNetwork.eni().getNetworkInterfaceId());
|
||||
ec2Service.deleteNetworkInterface(region, protectedNetwork.eni().getNetworkInterfaceId());
|
||||
@@ -392,6 +385,7 @@ public class EcsContainerManager {
|
||||
task.setStartedAt(Instant.now());
|
||||
|
||||
return new EcsTaskHandle(task.getTaskArn(), containerIds, logStreamsByContainerId,
|
||||
firelensVolumeName,
|
||||
protectedNetwork == null ? null : protectedNetwork.eni().getNetworkInterfaceId(), region);
|
||||
}
|
||||
|
||||
@@ -473,6 +467,7 @@ public class EcsContainerManager {
|
||||
cleanupProtectedNetwork(handle);
|
||||
new ArrayList<>(handle.getLogStreamsByContainerId().keySet())
|
||||
.forEach(dockerId -> finalizeLogStream(handle, dockerId));
|
||||
removeFirelensVolume(handle);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -517,9 +512,255 @@ public class EcsContainerManager {
|
||||
// Preserve handles for any container that still may be running after both operations failed.
|
||||
terminatedContainerIds.forEach(dockerId -> finalizeLogStream(handle, dockerId));
|
||||
cleanupProtectedNetwork(handle);
|
||||
removeFirelensVolume(handle);
|
||||
return exitCodes;
|
||||
}
|
||||
|
||||
private void removeFirelensVolume(EcsTaskHandle handle) {
|
||||
if (handle == null || handle.getFirelensVolumeName() == null) {
|
||||
return;
|
||||
}
|
||||
lifecycleManager.removeVolume(handle.getFirelensVolumeName());
|
||||
}
|
||||
|
||||
private static ContainerDefinition findFirelensRouter(List<ContainerDefinition> defs) {
|
||||
if (defs == null) {
|
||||
return null;
|
||||
}
|
||||
ContainerDefinition router = null;
|
||||
for (ContainerDefinition def : defs) {
|
||||
FirelensConfiguration firelens = def.getFirelensConfiguration();
|
||||
if (firelens == null) {
|
||||
continue;
|
||||
}
|
||||
if (!"fluentbit".equalsIgnoreCase(firelens.type()) && !"fluentd".equalsIgnoreCase(firelens.type())) {
|
||||
throw new AwsException("ClientException",
|
||||
"FireLens configuration type must be fluentbit or fluentd.", 400);
|
||||
}
|
||||
if (router != null) {
|
||||
throw new AwsException("ClientException",
|
||||
"A task definition can have only one FireLens log router.", 400);
|
||||
}
|
||||
if (def.getPortMappings() != null && def.getPortMappings().stream()
|
||||
.anyMatch(port -> port.containerPort() == 24224)) {
|
||||
throw new AwsException("ClientException",
|
||||
"FireLens port 24224 must not be exposed.", 400);
|
||||
}
|
||||
router = def;
|
||||
}
|
||||
return router;
|
||||
}
|
||||
|
||||
private static boolean isFluentdRouter(ContainerDefinition router) {
|
||||
return router != null
|
||||
&& router.getFirelensConfiguration() != null
|
||||
&& "fluentd".equalsIgnoreCase(router.getFirelensConfiguration().type());
|
||||
}
|
||||
|
||||
private static Map<String, Map<String, String>> awsFirelensLogOptions(List<ContainerDefinition> defs) {
|
||||
LinkedHashMap<String, Map<String, String>> options = new LinkedHashMap<>();
|
||||
if (defs == null) {
|
||||
return options;
|
||||
}
|
||||
for (ContainerDefinition def : defs) {
|
||||
if (!isAwsFirelens(def)) {
|
||||
continue;
|
||||
}
|
||||
LogConfiguration log = def.getLogConfiguration();
|
||||
options.put(def.getName(), log.options() != null ? log.options() : Map.of());
|
||||
}
|
||||
return options;
|
||||
}
|
||||
|
||||
private static boolean isAwsFirelens(ContainerDefinition def) {
|
||||
LogConfiguration log = def.getLogConfiguration();
|
||||
return log != null && "awsfirelens".equals(log.logDriver());
|
||||
}
|
||||
|
||||
private static List<ContainerDefinition> launchOrder(
|
||||
List<ContainerDefinition> defs, ContainerDefinition firelensRouter) {
|
||||
if (firelensRouter == null) {
|
||||
return defs;
|
||||
}
|
||||
List<ContainerDefinition> ordered = new ArrayList<>();
|
||||
ordered.add(firelensRouter);
|
||||
for (ContainerDefinition def : defs) {
|
||||
if (def != firelensRouter) {
|
||||
ordered.add(def);
|
||||
}
|
||||
}
|
||||
return ordered;
|
||||
}
|
||||
|
||||
private FirelensConfigGenerator.Context firelensContext(
|
||||
EcsTask task, TaskDefinition taskDef, ContainerDefinition router,
|
||||
Map<String, Map<String, String>> logOptions) {
|
||||
FirelensConfiguration firelens = router.getFirelensConfiguration();
|
||||
Map<String, String> options = firelens.options() != null ? firelens.options() : Map.of();
|
||||
boolean metadata = !"false".equalsIgnoreCase(options.get("enable-ecs-log-metadata"));
|
||||
String external = null;
|
||||
String externalType = options.get("config-file-type");
|
||||
if ("file".equals(externalType)) {
|
||||
external = options.get("config-file-value");
|
||||
} else if ("s3".equals(externalType)) {
|
||||
// The agent downloads the object to this fixed path and @INCLUDEs it; Floci
|
||||
// writes it there directly with the generated config.
|
||||
external = isFluentdRouter(router)
|
||||
? "/fluentd/etc/external.conf"
|
||||
: "/fluent-bit/etc/external.conf";
|
||||
}
|
||||
int memoryMb = 0;
|
||||
if (router.getMemoryReservation() != null) {
|
||||
memoryMb = router.getMemoryReservation();
|
||||
} else if (router.getMemory() != null) {
|
||||
memoryMb = router.getMemory();
|
||||
}
|
||||
String cluster = extractTaskId(task.getClusterArn());
|
||||
String familyRevision = taskDef.getFamily() + ":" + taskDef.getRevision();
|
||||
String networkMode = taskDef.getNetworkMode() != null
|
||||
? taskDef.getNetworkMode().name()
|
||||
: NetworkMode.bridge.name();
|
||||
return new FirelensConfigGenerator.Context(
|
||||
networkMode, metadata, cluster, task.getTaskArn(), familyRevision,
|
||||
memoryMb, external, awsEnv.flociEndpoint(), logOptions);
|
||||
}
|
||||
|
||||
private String firelensConfig(
|
||||
EcsTask task, TaskDefinition taskDef, ContainerDefinition router,
|
||||
Map<String, Map<String, String>> logOptions) {
|
||||
FirelensConfigGenerator.Context ctx = firelensContext(task, taskDef, router, logOptions);
|
||||
return isFluentdRouter(router)
|
||||
? FirelensConfigGenerator.fluentdConfig(ctx)
|
||||
: FirelensConfigGenerator.fluentBitConfig(ctx);
|
||||
}
|
||||
|
||||
private String unixSocketAddress(String volumeName) {
|
||||
try {
|
||||
String mountpoint = lifecycleManager.getDockerClient()
|
||||
.inspectVolumeCmd(volumeName).exec().getMountpoint();
|
||||
if (mountpoint == null || mountpoint.isBlank()) {
|
||||
throw new AwsException("ClientException",
|
||||
"FireLens socket volume has no mountpoint: " + volumeName, 500);
|
||||
}
|
||||
String path = mountpoint.endsWith("/")
|
||||
? mountpoint + "fluent.sock"
|
||||
: mountpoint + "/fluent.sock";
|
||||
return "unix://" + path;
|
||||
} catch (AwsException e) {
|
||||
throw e;
|
||||
} catch (Exception e) {
|
||||
throw new AwsException("ClientException",
|
||||
"unable to resolve FireLens socket path: " + e.getMessage(), 500);
|
||||
}
|
||||
}
|
||||
|
||||
private LogConfig awsFirelensLogConfig(ContainerDefinition def, String taskId, String socketAddress) {
|
||||
LinkedHashMap<String, String> opts = new LinkedHashMap<>();
|
||||
opts.put("fluentd-address", socketAddress);
|
||||
opts.put("fluentd-async", "true");
|
||||
opts.put("fluentd-sub-second-precision", "true");
|
||||
opts.put("tag", def.getName() + "-firelens-" + taskId);
|
||||
Map<String, String> logOptions = def.getLogConfiguration().options();
|
||||
if (logOptions != null && logOptions.get("log-driver-buffer-limit") != null) {
|
||||
opts.put("fluentd-buffer-limit", logOptions.get("log-driver-buffer-limit"));
|
||||
}
|
||||
return new LogConfig(LogConfig.LoggingType.FLUENTD, opts);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads a {@code config-file-type=s3} external config from Floci's S3, before any container is
|
||||
* created, so a missing object stops the task without leaking a started router.
|
||||
*
|
||||
* <p>Wording is the ECS agent's, and the error code is ResourceInitializationError so that
|
||||
* EcsService passes the message through verbatim as the task's stoppedReason rather than
|
||||
* wrapping it in its generic start-failure prefix.
|
||||
*/
|
||||
private String s3ExternalConfig(ContainerDefinition router) {
|
||||
FirelensConfiguration firelens = router.getFirelensConfiguration();
|
||||
Map<String, String> options = firelens.options() != null ? firelens.options() : Map.of();
|
||||
if (!"s3".equals(options.get("config-file-type"))) {
|
||||
return null;
|
||||
}
|
||||
String value = options.get("config-file-value");
|
||||
// Registration already rejected a value that is not an S3 object ARN; this covers task
|
||||
// definitions stored before that check existed.
|
||||
AwsArnUtils.S3ObjectRef ref = AwsArnUtils.parseS3ObjectArn(value);
|
||||
if (ref == null) {
|
||||
throw firelensS3Failure("unable to parse s3 arn: " + value, 400);
|
||||
}
|
||||
try {
|
||||
S3Object object = s3Service.getObject(ref.bucket(), ref.key());
|
||||
return new String(object.getData(), StandardCharsets.UTF_8);
|
||||
} catch (AwsException e) {
|
||||
throw firelensS3Failure("unable to download s3 config " + ref.key()
|
||||
+ " from bucket " + ref.bucket() + ": " + e.getMessage(), e.getHttpStatus());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A task-resource failure that never reaches a client: EcsService catches it and uses the
|
||||
* message as the task's stoppedReason, keying off the ResourceInitializationError code to
|
||||
* skip its generic "Failed to start:" prefix. The prefix on the message itself is the agent's.
|
||||
*/
|
||||
private static AwsException firelensS3Failure(String detail, int httpStatus) {
|
||||
return new AwsException("ResourceInitializationError",
|
||||
"Unable to download firelens s3 config file: " + detail, httpStatus);
|
||||
}
|
||||
|
||||
private void copyFirelensConfig(
|
||||
String containerId, String configText, boolean fluentd, String externalConfig) {
|
||||
byte[] content = configText.getBytes(StandardCharsets.UTF_8);
|
||||
String fileName = fluentd ? "fluent.conf" : "fluent-bit.conf";
|
||||
String remotePath = fluentd ? "/fluentd/etc" : "/fluent-bit/etc";
|
||||
ByteArrayOutputStream archive = new ByteArrayOutputStream(content.length + 1024);
|
||||
try (TarArchiveOutputStream tar = new TarArchiveOutputStream(archive)) {
|
||||
putTarEntry(tar, fileName, content);
|
||||
if (externalConfig != null) {
|
||||
putTarEntry(tar, "external.conf", externalConfig.getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
} catch (IOException e) {
|
||||
throw new AwsException("ClientException",
|
||||
"unable to write FireLens config: " + e.getMessage(), 500);
|
||||
}
|
||||
lifecycleManager.getDockerClient().copyArchiveToContainerCmd(containerId)
|
||||
.withRemotePath(remotePath)
|
||||
.withTarInputStream(new ByteArrayInputStream(archive.toByteArray()))
|
||||
.exec();
|
||||
}
|
||||
|
||||
private static void putTarEntry(TarArchiveOutputStream tar, String name, byte[] content) throws IOException {
|
||||
TarArchiveEntry entry = new TarArchiveEntry(name);
|
||||
entry.setSize(content.length);
|
||||
tar.putArchiveEntry(entry);
|
||||
tar.write(content);
|
||||
tar.closeArchiveEntry();
|
||||
}
|
||||
|
||||
private String inspectContainerIp(String dockerId) {
|
||||
try {
|
||||
InspectContainerResponse inspect = lifecycleManager.getDockerClient().inspectContainerCmd(dockerId).exec();
|
||||
Map<String, ContainerNetwork> networks = inspect.getNetworkSettings().getNetworks();
|
||||
String configured = config.services().ecs().dockerNetwork().orElse(null);
|
||||
if (configured != null && networks.get(configured) != null
|
||||
&& isUsableIp(networks.get(configured).getIpAddress())) {
|
||||
return networks.get(configured).getIpAddress();
|
||||
}
|
||||
for (Map.Entry<String, ContainerNetwork> entry : networks.entrySet()) {
|
||||
if (!isDefaultDockerNetwork(entry.getKey())
|
||||
&& isUsableIp(entry.getValue().getIpAddress())) {
|
||||
return entry.getValue().getIpAddress();
|
||||
}
|
||||
}
|
||||
for (ContainerNetwork net : networks.values()) {
|
||||
if (isUsableIp(net.getIpAddress())) {
|
||||
return net.getIpAddress();
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
LOG.warnv("Could not resolve FireLens container IP for {0}: {1}", dockerId, e.getMessage());
|
||||
}
|
||||
return "127.0.0.1";
|
||||
}
|
||||
private void cleanupProtectedNetwork(EcsTaskHandle handle) {
|
||||
if (firewallManager != null && handle.getNetworkInterfaceId() != null) {
|
||||
firewallManager.unregister(handle.getNetworkInterfaceId());
|
||||
@@ -777,9 +1018,12 @@ public class EcsContainerManager {
|
||||
return container;
|
||||
}
|
||||
|
||||
private static String extractTaskId(String taskArn) {
|
||||
int slash = taskArn.lastIndexOf('/');
|
||||
return slash >= 0 ? taskArn.substring(slash + 1) : taskArn;
|
||||
private static String extractTaskId(String arn) {
|
||||
if (arn == null) {
|
||||
return "";
|
||||
}
|
||||
int slash = arn.lastIndexOf('/');
|
||||
return slash >= 0 ? arn.substring(slash + 1) : arn;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -13,20 +13,22 @@ public class EcsTaskHandle {
|
||||
private final String taskArn;
|
||||
private final Map<String, String> containerIds; // containerName → dockerId
|
||||
private final Map<String, Closeable> logStreamsByContainerId;
|
||||
private final String firelensVolumeName;
|
||||
private final String networkInterfaceId;
|
||||
private final String region;
|
||||
|
||||
public EcsTaskHandle(String taskArn, Map<String, String> containerIds,
|
||||
Map<String, Closeable> logStreamsByContainerId) {
|
||||
this(taskArn, containerIds, logStreamsByContainerId, null, null);
|
||||
this(taskArn, containerIds, logStreamsByContainerId, null, null, null);
|
||||
}
|
||||
|
||||
public EcsTaskHandle(String taskArn, Map<String, String> containerIds,
|
||||
Map<String, Closeable> logStreamsByContainerId,
|
||||
String networkInterfaceId, String region) {
|
||||
String firelensVolumeName, String networkInterfaceId, String region) {
|
||||
this.taskArn = taskArn;
|
||||
this.containerIds = new LinkedHashMap<>(containerIds);
|
||||
this.logStreamsByContainerId = new LinkedHashMap<>(logStreamsByContainerId);
|
||||
this.firelensVolumeName = firelensVolumeName;
|
||||
this.networkInterfaceId = networkInterfaceId;
|
||||
this.region = region;
|
||||
}
|
||||
@@ -34,6 +36,7 @@ public class EcsTaskHandle {
|
||||
public String getTaskArn() { return taskArn; }
|
||||
public Map<String, String> getContainerIds() { return containerIds; }
|
||||
public Map<String, Closeable> getLogStreamsByContainerId() { return logStreamsByContainerId; }
|
||||
public String getFirelensVolumeName() { return firelensVolumeName; }
|
||||
public String getNetworkInterfaceId() { return networkInterfaceId; }
|
||||
public String getRegion() { return region; }
|
||||
|
||||
|
||||
+342
@@ -0,0 +1,342 @@
|
||||
package io.github.hectorvent.floci.services.ecs.container;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* Generates the FireLens config ECS would write for a task.
|
||||
*
|
||||
* <p>Fluent Bit shape is taken from amazon-ecs-agent {@code firelensconfig_unix.go}: unix-socket
|
||||
* input, optional TCP forward + healthcheck, ECS metadata {@code record_modifier}, optional
|
||||
* {@code @INCLUDE}, then one {@code [OUTPUT]} per {@code awsfirelens} container.
|
||||
* {@link #fluentdConfig} is the Fluentd equivalent ({@code unix}/{@code forward} sources,
|
||||
* {@code record_transformer}, {@code @include}, {@code <match>}; no healthcheck).
|
||||
*/
|
||||
final class FirelensConfigGenerator {
|
||||
|
||||
static final String SOCKET_PATH = "/var/run/fluent.sock";
|
||||
static final int FORWARD_PORT = 24224;
|
||||
static final int HEALTHCHECK_PORT = 8877;
|
||||
|
||||
/**
|
||||
* Output plugins that read a URL from their {@code endpoint} property.
|
||||
*
|
||||
* <p>Everything else is left alone. Fluent Bit fails at startup on a property the plugin
|
||||
* does not know, so an {@code Endpoint} line would break outputs such as {@code stdout},
|
||||
* {@code null}, {@code es} or {@code http} that name their destination with a different
|
||||
* key.
|
||||
*
|
||||
* <p>These three are the AWS-written Go plugins, which parse the value as a URL, so
|
||||
* Floci's {@code http://host:port} base URL reaches them. The upstream C plugins
|
||||
* ({@code cloudwatch_logs}, {@code kinesis_firehose}, {@code kinesis_streams}) hand the
|
||||
* value to {@code getaddrinfo} as a bare host name and always dial TLS: a URL fails as
|
||||
* "Misformatted domain name", and a bare host fails certificate verification against
|
||||
* Floci's plain HTTP port, with no output-level switch for either. Injecting an endpoint
|
||||
* there cannot work, so those outputs keep whatever the task definition gave them.
|
||||
*/
|
||||
private static final Set<String> ENDPOINT_PLUGINS = Set.of(
|
||||
"s3", "cloudwatch", "firehose");
|
||||
|
||||
private FirelensConfigGenerator() {
|
||||
}
|
||||
|
||||
record Context(
|
||||
String networkMode,
|
||||
boolean ecsMetadataEnabled,
|
||||
String cluster,
|
||||
String taskArn,
|
||||
String taskDefinition,
|
||||
int routerMemoryMb,
|
||||
String externalConfigPath,
|
||||
String pluginEndpoint,
|
||||
Map<String, Map<String, String>> containerLogOptions
|
||||
) {
|
||||
}
|
||||
|
||||
static String fluentBitConfig(Context ctx) {
|
||||
StringBuilder out = new StringBuilder();
|
||||
appendInput(out, "forward", null, options(
|
||||
"unix_path", SOCKET_PATH,
|
||||
"Mem_Buf_Limit", memBufLimit(ctx.routerMemoryMb())));
|
||||
|
||||
if (addsTcpForward(ctx.networkMode())) {
|
||||
appendInput(out, "forward", null, options(
|
||||
"Listen", tcpListen(ctx.networkMode()),
|
||||
"Port", String.valueOf(FORWARD_PORT)));
|
||||
appendInput(out, "tcp", "firelens-healthcheck", options(
|
||||
"Listen", "127.0.0.1",
|
||||
"Port", String.valueOf(HEALTHCHECK_PORT)));
|
||||
}
|
||||
|
||||
if (ctx.containerLogOptions() != null) {
|
||||
for (Map.Entry<String, Map<String, String>> entry : ctx.containerLogOptions().entrySet()) {
|
||||
String tag = entry.getKey() + "-firelens*";
|
||||
Map<String, String> options = entry.getValue();
|
||||
if (options == null) {
|
||||
continue;
|
||||
}
|
||||
String include = options.get("include-pattern");
|
||||
if (include != null) {
|
||||
appendGrep(out, tag, "Regex", include);
|
||||
}
|
||||
String exclude = options.get("exclude-pattern");
|
||||
if (exclude != null) {
|
||||
appendGrep(out, tag, "Exclude", exclude);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (ctx.ecsMetadataEnabled()) {
|
||||
out.append("[FILTER]\n");
|
||||
out.append(" Name record_modifier\n");
|
||||
out.append(" Match *\n");
|
||||
appendRecord(out, "ecs_cluster", ctx.cluster());
|
||||
appendRecord(out, "ecs_task_arn", ctx.taskArn());
|
||||
appendRecord(out, "ecs_task_definition", ctx.taskDefinition());
|
||||
out.append('\n');
|
||||
}
|
||||
|
||||
if (ctx.externalConfigPath() != null && !ctx.externalConfigPath().isBlank()) {
|
||||
out.append("@INCLUDE ").append(ctx.externalConfigPath()).append("\n\n");
|
||||
}
|
||||
|
||||
if (addsTcpForward(ctx.networkMode())) {
|
||||
appendOutput(out, "null", "firelens-healthcheck", Map.of());
|
||||
}
|
||||
|
||||
if (ctx.containerLogOptions() != null) {
|
||||
for (Map.Entry<String, Map<String, String>> entry : ctx.containerLogOptions().entrySet()) {
|
||||
Map<String, String> options = entry.getValue() == null ? Map.of() : entry.getValue();
|
||||
String plugin = options.get("Name");
|
||||
Map<String, String> pluginOptions = pluginOptions(options);
|
||||
if (plugin == null) {
|
||||
if (!pluginOptions.isEmpty()) {
|
||||
throw new IllegalArgumentException(
|
||||
"missing output key Name which is required for firelens configuration of type fluentbit");
|
||||
}
|
||||
continue;
|
||||
}
|
||||
pluginOptions = withPluginEndpoint(plugin, pluginOptions, ctx.pluginEndpoint());
|
||||
appendOutput(out, plugin, entry.getKey() + "-firelens*", pluginOptions);
|
||||
}
|
||||
}
|
||||
return out.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Fluentd FireLens config. Output plugin type comes from log option {@code @type}.
|
||||
* AWS plugins here are Ruby gems, not the Fluent Bit Go/C plugins, so Floci does
|
||||
* not inject an {@code Endpoint} line.
|
||||
*/
|
||||
static String fluentdConfig(Context ctx) {
|
||||
StringBuilder out = new StringBuilder();
|
||||
appendFluentdBlock(out, "source", null, "unix", options("path", SOCKET_PATH));
|
||||
|
||||
if (addsTcpForward(ctx.networkMode())) {
|
||||
appendFluentdBlock(out, "source", null, "forward", options(
|
||||
"bind", tcpListen(ctx.networkMode()),
|
||||
"port", String.valueOf(FORWARD_PORT)));
|
||||
}
|
||||
|
||||
if (ctx.containerLogOptions() != null) {
|
||||
for (Map.Entry<String, Map<String, String>> entry : ctx.containerLogOptions().entrySet()) {
|
||||
String tag = entry.getKey() + "-firelens**";
|
||||
Map<String, String> options = entry.getValue();
|
||||
if (options == null) {
|
||||
continue;
|
||||
}
|
||||
String include = options.get("include-pattern");
|
||||
if (include != null) {
|
||||
appendFluentdGrep(out, tag, "regexp", include);
|
||||
}
|
||||
String exclude = options.get("exclude-pattern");
|
||||
if (exclude != null) {
|
||||
appendFluentdGrep(out, tag, "exclude", exclude);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (ctx.ecsMetadataEnabled()) {
|
||||
out.append("<filter **>\n");
|
||||
out.append(" @type record_transformer\n");
|
||||
out.append(" <record>\n");
|
||||
appendFluentdRecord(out, "ecs_cluster", ctx.cluster());
|
||||
appendFluentdRecord(out, "ecs_task_arn", ctx.taskArn());
|
||||
appendFluentdRecord(out, "ecs_task_definition", ctx.taskDefinition());
|
||||
out.append(" </record>\n");
|
||||
out.append("</filter>\n\n");
|
||||
}
|
||||
|
||||
if (ctx.externalConfigPath() != null && !ctx.externalConfigPath().isBlank()) {
|
||||
out.append("@include ").append(ctx.externalConfigPath()).append("\n\n");
|
||||
}
|
||||
|
||||
if (ctx.containerLogOptions() != null) {
|
||||
for (Map.Entry<String, Map<String, String>> entry : ctx.containerLogOptions().entrySet()) {
|
||||
Map<String, String> options = entry.getValue() == null ? Map.of() : entry.getValue();
|
||||
String plugin = options.get("@type");
|
||||
Map<String, String> pluginOptions = pluginOptions(options);
|
||||
if (plugin == null) {
|
||||
if (!pluginOptions.isEmpty()) {
|
||||
throw new IllegalArgumentException(
|
||||
"missing output key @type which is required for firelens configuration of type fluentd");
|
||||
}
|
||||
continue;
|
||||
}
|
||||
appendFluentdBlock(out, "match", entry.getKey() + "-firelens**", plugin, pluginOptions);
|
||||
}
|
||||
}
|
||||
return out.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Points an AWS output at Floci. The Fluent Bit AWS plugins read a custom endpoint only
|
||||
* from their own configuration, so the {@code AWS_ENDPOINT_URL} Floci injects into the
|
||||
* container does not reach them and the output would otherwise go to the real service.
|
||||
* An endpoint the task definition set explicitly is never overwritten.
|
||||
*/
|
||||
private static Map<String, String> withPluginEndpoint(
|
||||
String plugin, Map<String, String> pluginOptions, String pluginEndpoint) {
|
||||
if (pluginEndpoint == null || !ENDPOINT_PLUGINS.contains(plugin)) {
|
||||
return pluginOptions;
|
||||
}
|
||||
String existingEndpoint = null;
|
||||
for (String key : pluginOptions.keySet()) {
|
||||
if ("endpoint".equalsIgnoreCase(key)) {
|
||||
existingEndpoint = pluginOptions.get(key);
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (existingEndpoint == null) {
|
||||
pluginOptions.put("Endpoint", pluginEndpoint);
|
||||
existingEndpoint = pluginEndpoint;
|
||||
}
|
||||
disableTlsForHttpEndpoint(pluginOptions, existingEndpoint);
|
||||
return pluginOptions;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fluent Bit 1.9 (the {@code aws-for-fluent-bit} 2.x / {@code :latest} line) still
|
||||
* calls {@code flb_tls_session_create} on an HTTP S3 endpoint and SIGSEGVs on a NULL
|
||||
* TLS context. {@code tls Off} is what that version actually honours; the {@code http://}
|
||||
* scheme alone is not enough.
|
||||
*/
|
||||
private static void disableTlsForHttpEndpoint(Map<String, String> pluginOptions, String endpoint) {
|
||||
if (endpoint == null || !endpoint.regionMatches(true, 0, "http://", 0, 7)) {
|
||||
return;
|
||||
}
|
||||
for (String key : pluginOptions.keySet()) {
|
||||
if ("tls".equalsIgnoreCase(key)) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
pluginOptions.put("tls", "Off");
|
||||
}
|
||||
|
||||
static boolean addsTcpForward(String networkMode) {
|
||||
return "bridge".equals(networkMode) || "awsvpc".equals(networkMode);
|
||||
}
|
||||
|
||||
static String tcpListen(String networkMode) {
|
||||
// AWS binds 127.0.0.1 in awsvpc because every container shares the task's network
|
||||
// namespace. Floci runs each container in its own namespace, so the router must listen
|
||||
// on all interfaces for the injected FLUENT_HOST to be reachable from sibling containers.
|
||||
return "0.0.0.0";
|
||||
}
|
||||
|
||||
static String memBufLimit(int routerMemoryMb) {
|
||||
int limit = routerMemoryMb / 2;
|
||||
if (limit <= 0) {
|
||||
limit = 25;
|
||||
}
|
||||
return limit + "MB";
|
||||
}
|
||||
|
||||
static Map<String, String> pluginOptions(Map<String, String> options) {
|
||||
LinkedHashMap<String, String> pluginOptions = new LinkedHashMap<>();
|
||||
for (Map.Entry<String, String> option : options.entrySet()) {
|
||||
String key = option.getKey();
|
||||
if ("Name".equals(key) || "@type".equals(key) || "include-pattern".equals(key)
|
||||
|| "exclude-pattern".equals(key) || "log-driver-buffer-limit".equals(key)) {
|
||||
continue;
|
||||
}
|
||||
pluginOptions.put(key, option.getValue());
|
||||
}
|
||||
return pluginOptions;
|
||||
}
|
||||
|
||||
private static Map<String, String> options(String... keyValues) {
|
||||
LinkedHashMap<String, String> options = new LinkedHashMap<>();
|
||||
for (int i = 0; i < keyValues.length; i += 2) {
|
||||
options.put(keyValues[i], keyValues[i + 1]);
|
||||
}
|
||||
return options;
|
||||
}
|
||||
|
||||
private static void appendInput(StringBuilder out, String name, String tag, Map<String, String> options) {
|
||||
out.append("[INPUT]\n");
|
||||
out.append(" Name ").append(name).append('\n');
|
||||
if (tag != null) {
|
||||
out.append(" Tag ").append(tag).append('\n');
|
||||
}
|
||||
for (Map.Entry<String, String> option : options.entrySet()) {
|
||||
out.append(" ").append(option.getKey()).append(' ').append(option.getValue()).append('\n');
|
||||
}
|
||||
out.append('\n');
|
||||
}
|
||||
|
||||
private static void appendGrep(StringBuilder out, String tag, String kind, String pattern) {
|
||||
out.append("[FILTER]\n");
|
||||
out.append(" Name grep\n");
|
||||
out.append(" Match ").append(tag).append('\n');
|
||||
out.append(" ").append(kind).append(" log ").append(pattern).append('\n');
|
||||
out.append('\n');
|
||||
}
|
||||
|
||||
private static void appendRecord(StringBuilder out, String key, String value) {
|
||||
if (value != null && !value.isBlank()) {
|
||||
out.append(" Record ").append(key).append(' ').append(value).append('\n');
|
||||
}
|
||||
}
|
||||
|
||||
private static void appendOutput(StringBuilder out, String name, String tag, Map<String, String> options) {
|
||||
out.append("[OUTPUT]\n");
|
||||
out.append(" Name ").append(name).append('\n');
|
||||
out.append(" Match ").append(tag).append('\n');
|
||||
for (Map.Entry<String, String> option : options.entrySet()) {
|
||||
out.append(" ").append(option.getKey()).append(' ').append(option.getValue()).append('\n');
|
||||
}
|
||||
out.append('\n');
|
||||
}
|
||||
|
||||
private static void appendFluentdBlock(
|
||||
StringBuilder out, String kind, String tag, String type, Map<String, String> options) {
|
||||
out.append('<').append(kind);
|
||||
if (tag != null) {
|
||||
out.append(' ').append(tag);
|
||||
}
|
||||
out.append(">\n");
|
||||
out.append(" @type ").append(type).append('\n');
|
||||
for (Map.Entry<String, String> option : options.entrySet()) {
|
||||
out.append(" ").append(option.getKey()).append(' ').append(option.getValue()).append('\n');
|
||||
}
|
||||
out.append("</").append(kind).append(">\n\n");
|
||||
}
|
||||
|
||||
private static void appendFluentdGrep(StringBuilder out, String tag, String kind, String pattern) {
|
||||
out.append("<filter ").append(tag).append(">\n");
|
||||
out.append(" @type grep\n");
|
||||
out.append(" <").append(kind).append(">\n");
|
||||
out.append(" key log\n");
|
||||
out.append(" pattern ").append(pattern).append('\n');
|
||||
out.append(" </").append(kind).append(">\n");
|
||||
out.append("</filter>\n\n");
|
||||
}
|
||||
|
||||
private static void appendFluentdRecord(StringBuilder out, String key, String value) {
|
||||
if (value != null && !value.isBlank()) {
|
||||
out.append(" ").append(key).append(' ').append(value).append('\n');
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -66,7 +66,6 @@ public class ContainerDefinition {
|
||||
public void setFirelensConfiguration(FirelensConfiguration firelensConfiguration) {
|
||||
this.firelensConfiguration = firelensConfiguration;
|
||||
}
|
||||
|
||||
public HealthCheck getHealthCheck() { return healthCheck; }
|
||||
public void setHealthCheck(HealthCheck healthCheck) { this.healthCheck = healthCheck; }
|
||||
}
|
||||
@@ -4,6 +4,14 @@ import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* The {@code firelensConfiguration} of an ECS container definition:
|
||||
* {@code {"type": "fluentbit"|"fluentd", "options": {...}}}.
|
||||
*
|
||||
* <p>Marks a container as the task's log router and, when {@code enable-ecs-log-metadata} is set,
|
||||
* has Floci append ECS metadata fields to routed records. {@code fluentbit} and {@code fluentd}
|
||||
* routers are both acted on at launch.
|
||||
*/
|
||||
@RegisterForReflection
|
||||
public record FirelensConfiguration(String type, Map<String, String> options) {
|
||||
}
|
||||
@@ -9,9 +9,9 @@ import java.util.Map;
|
||||
* The {@code logConfiguration} of an ECS container definition:
|
||||
* {@code {"logDriver": "awslogs", "options": {...}, "secretOptions": [{"name": ..., "valueFrom": ...}]}}.
|
||||
*
|
||||
* <p>Modelled for RegisterTaskDefinition/DescribeTaskDefinition round-trip fidelity. Floci does not
|
||||
* route container output to the configured driver — a local task's logs stay with its Docker
|
||||
* container — so the {@code awslogs} options are stored and returned rather than acted upon.
|
||||
* <p>Stored and returned for RegisterTaskDefinition/DescribeTaskDefinition round-trip. At launch,
|
||||
* {@code awsfirelens} is routed through the task's FireLens container. Other drivers
|
||||
* (including {@code awslogs}) stay with the Docker container and Floci's CloudWatch log streamer.
|
||||
*/
|
||||
@RegisterForReflection
|
||||
public record LogConfiguration(String logDriver, Map<String, String> options, List<Secret> secretOptions) {
|
||||
|
||||
Reference in new issue
Block a user