mirror of
https://github.com/floci-io/floci.git
synced 2026-11-23 22:11:36 -05:00
feat(ecs): add FireLens task logging support (#3768)
* feat(ecs): add FireLens task logging support * fix(docker): omit extra hosts for container network mode * fix(ecs): bind FireLens router port to loopback
This commit is contained in:
1 parent
172bfb32b0
commit
6f87973649
11 files changed
+527
-17
No files matched your search
+27
-4
@@ -86,12 +86,13 @@ public class ContainerLifecycleManager {
|
||||
* filesystem modifications are needed between creation and start.
|
||||
*
|
||||
* @param spec the container specification
|
||||
* @return information about the created container including resolved endpoints
|
||||
* @return information about the created container including resolved endpoints and published ports
|
||||
*/
|
||||
public ContainerInfo createAndStart(ContainerSpec spec) {
|
||||
String containerId = create(spec);
|
||||
try {
|
||||
return startCreated(containerId, spec);
|
||||
ContainerInfo info = startCreated(containerId, spec);
|
||||
return withPublishedHostPorts(info, spec);
|
||||
} catch (Exception e) {
|
||||
// A failed start (e.g. host-port conflict) must not leak the created
|
||||
// container: retrying callers would accumulate Created containers and
|
||||
@@ -247,6 +248,22 @@ public class ContainerLifecycleManager {
|
||||
return new ContainerInfo(containerId, endpoints);
|
||||
}
|
||||
|
||||
private ContainerInfo withPublishedHostPorts(ContainerInfo info, ContainerSpec spec) {
|
||||
if (spec.portBindings() == null || spec.portBindings().isEmpty()) {
|
||||
return info;
|
||||
}
|
||||
|
||||
InspectContainerResponse inspect = dockerClient.inspectContainerCmd(info.containerId()).exec();
|
||||
Map<Integer, Integer> publishedHostPorts = new HashMap<>();
|
||||
for (Integer containerPort : spec.portBindings().keySet()) {
|
||||
OptionalInt published = readPublishedHostPort(inspect, containerPort);
|
||||
if (published.isPresent()) {
|
||||
publishedHostPorts.put(containerPort, published.getAsInt());
|
||||
}
|
||||
}
|
||||
return new ContainerInfo(info.containerId(), info.endpoints(), publishedHostPorts);
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts a container, translating crun/runc's kernel-keyring-quota error into a message that
|
||||
* names the actual cause and a fix, instead of the misleading "Disk quota exceeded" the OCI
|
||||
@@ -937,8 +954,10 @@ public class ContainerLifecycleManager {
|
||||
hostConfig.withBinds(spec.binds().toArray(new Bind[0]));
|
||||
}
|
||||
|
||||
// Extra hosts (e.g., host.docker.internal on Linux)
|
||||
if (spec.extraHosts() != null && !spec.extraHosts().isEmpty()) {
|
||||
// Docker rejects extra_hosts together with container:<id> network mode. Containers
|
||||
// sharing another container's network namespace already inherit its network path.
|
||||
if (spec.extraHosts() != null && !spec.extraHosts().isEmpty()
|
||||
&& !isContainerNetworkMode(spec.networkMode())) {
|
||||
hostConfig.withExtraHosts(spec.extraHosts().toArray(new String[0]));
|
||||
}
|
||||
|
||||
@@ -963,6 +982,10 @@ public class ContainerLifecycleManager {
|
||||
return hostConfig;
|
||||
}
|
||||
|
||||
private static boolean isContainerNetworkMode(String networkMode) {
|
||||
return networkMode != null && networkMode.startsWith("container:");
|
||||
}
|
||||
|
||||
private Map<Integer, EndpointInfo> resolveEndpoints(String containerId, ContainerSpec spec) {
|
||||
if (spec.exposedPorts() == null || spec.exposedPorts().isEmpty()) {
|
||||
return Map.of();
|
||||
|
||||
@@ -9,10 +9,11 @@ import io.github.hectorvent.floci.services.ecs.model.CapacityProvider;
|
||||
import io.github.hectorvent.floci.services.ecs.model.ClusterSetting;
|
||||
import io.github.hectorvent.floci.services.ecs.model.ContainerDefinition;
|
||||
import io.github.hectorvent.floci.services.ecs.model.ContainerInstance;
|
||||
import io.github.hectorvent.floci.services.ecs.model.ContainerOverride;
|
||||
import io.github.hectorvent.floci.services.ecs.model.Deployment;
|
||||
import io.github.hectorvent.floci.services.ecs.model.Failure;
|
||||
import io.github.hectorvent.floci.services.ecs.model.FirelensConfiguration;
|
||||
import io.github.hectorvent.floci.services.ecs.model.HealthCheck;
|
||||
import io.github.hectorvent.floci.services.ecs.model.ContainerOverride;
|
||||
import io.github.hectorvent.floci.services.ecs.model.EcsCluster;
|
||||
import io.github.hectorvent.floci.services.ecs.model.EcsLoadBalancer;
|
||||
import io.github.hectorvent.floci.services.ecs.model.EcsServiceModel;
|
||||
@@ -1124,6 +1125,20 @@ public class EcsJsonHandler {
|
||||
n.set("logConfiguration", logNode);
|
||||
}
|
||||
|
||||
if (def.getFirelensConfiguration() != null) {
|
||||
FirelensConfiguration firelens = def.getFirelensConfiguration();
|
||||
ObjectNode firelensNode = objectMapper.createObjectNode();
|
||||
if (firelens.type() != null) {
|
||||
firelensNode.put("type", firelens.type());
|
||||
}
|
||||
if (firelens.options() != null) {
|
||||
ObjectNode options = objectMapper.createObjectNode();
|
||||
firelens.options().forEach(options::put);
|
||||
firelensNode.set("options", options);
|
||||
}
|
||||
n.set("firelensConfiguration", firelensNode);
|
||||
}
|
||||
|
||||
if (def.getHealthCheck() != null) {
|
||||
HealthCheck hc = def.getHealthCheck();
|
||||
ObjectNode hcNode = objectMapper.createObjectNode();
|
||||
@@ -1482,6 +1497,7 @@ public class EcsJsonHandler {
|
||||
}
|
||||
def.setMountPoints(parseMountPoints(item.path("mountPoints")));
|
||||
def.setLogConfiguration(parseLogConfiguration(item.path("logConfiguration")));
|
||||
def.setFirelensConfiguration(parseFirelensConfiguration(item.path("firelensConfiguration")));
|
||||
if (item.has("healthCheck")) {
|
||||
def.setHealthCheck(parseHealthCheck(item.path("healthCheck")));
|
||||
}
|
||||
@@ -1569,6 +1585,20 @@ public class EcsJsonHandler {
|
||||
return new LogConfiguration(logDriver, options, secretOptions);
|
||||
}
|
||||
|
||||
private FirelensConfiguration parseFirelensConfiguration(JsonNode node) {
|
||||
if (node == null || !node.isObject() || !node.has("type")) {
|
||||
return null;
|
||||
}
|
||||
Map<String, String> options = null;
|
||||
if (node.path("options").isObject()) {
|
||||
Map<String, String> parsed = new LinkedHashMap<>();
|
||||
node.path("options").fields()
|
||||
.forEachRemaining(entry -> parsed.put(entry.getKey(), entry.getValue().asText()));
|
||||
options = parsed;
|
||||
}
|
||||
return new FirelensConfiguration(node.path("type").asText(), options);
|
||||
}
|
||||
|
||||
private HealthCheck parseHealthCheck(JsonNode node) {
|
||||
if (node == null || !node.isObject()) {
|
||||
return null;
|
||||
|
||||
+93
-9
@@ -37,6 +37,7 @@ import io.github.hectorvent.floci.services.ssm.SsmService;
|
||||
import com.github.dockerjava.api.DockerClient;
|
||||
import com.github.dockerjava.api.exception.NotFoundException;
|
||||
import com.github.dockerjava.api.model.ExposedPort;
|
||||
import com.github.dockerjava.api.model.LogConfig;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
@@ -53,6 +54,7 @@ import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.OptionalInt;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
@@ -79,6 +81,55 @@ public class EcsContainerManager {
|
||||
private Ec2Service ec2Service;
|
||||
private SecurityGroupFirewallManager firewallManager;
|
||||
|
||||
static LogConfig firelensLogConfig(String taskId, String containerName, int fluentdPort) {
|
||||
return new LogConfig(LogConfig.LoggingType.FLUENTD, Map.of(
|
||||
"fluentd-address", "127.0.0.1:" + fluentdPort,
|
||||
"tag", taskId + "." + containerName,
|
||||
"fluentd-async", "true"));
|
||||
}
|
||||
|
||||
static List<ContainerDefinition> orderFirelensContainers(List<ContainerDefinition> definitions) {
|
||||
ContainerDefinition router = firelensRouter(definitions);
|
||||
boolean hasFirelensApplication = definitions.stream().anyMatch(EcsContainerManager::usesFirelens);
|
||||
if (router == null) {
|
||||
if (hasFirelensApplication) {
|
||||
throw new AwsException("ClientException",
|
||||
"An awsfirelens log configuration requires a FireLens log router.", 400);
|
||||
}
|
||||
return definitions;
|
||||
}
|
||||
String type = router.getFirelensConfiguration().type();
|
||||
if (!"fluentbit".equalsIgnoreCase(type) && !"fluentd".equalsIgnoreCase(type)) {
|
||||
throw new AwsException("ClientException",
|
||||
"FireLens configuration type must be fluentbit or fluentd.", 400);
|
||||
}
|
||||
if (router.getPortMappings() != null && router.getPortMappings().stream()
|
||||
.anyMatch(port -> port.containerPort() == 24224)) {
|
||||
throw new AwsException("ClientException",
|
||||
"FireLens port 24224 must not be exposed.", 400);
|
||||
}
|
||||
List<ContainerDefinition> ordered = new ArrayList<>(definitions.size());
|
||||
ordered.add(router);
|
||||
definitions.stream().filter(definition -> definition != router).forEach(ordered::add);
|
||||
return ordered;
|
||||
}
|
||||
|
||||
private static ContainerDefinition firelensRouter(List<ContainerDefinition> definitions) {
|
||||
List<ContainerDefinition> routers = definitions.stream()
|
||||
.filter(definition -> definition.getFirelensConfiguration() != null)
|
||||
.toList();
|
||||
if (routers.size() > 1) {
|
||||
throw new AwsException("ClientException",
|
||||
"A task definition can have only one FireLens log router.", 400);
|
||||
}
|
||||
return routers.isEmpty() ? null : routers.getFirst();
|
||||
}
|
||||
|
||||
private static boolean usesFirelens(ContainerDefinition definition) {
|
||||
return definition.getLogConfiguration() != null
|
||||
&& "awsfirelens".equalsIgnoreCase(definition.getLogConfiguration().logDriver());
|
||||
}
|
||||
|
||||
@Inject
|
||||
public EcsContainerManager(ContainerBuilder containerBuilder,
|
||||
ContainerLifecycleManager lifecycleManager,
|
||||
@@ -154,10 +205,19 @@ public class EcsContainerManager {
|
||||
}
|
||||
|
||||
Map<String, ContainerOverride> overridesByName = overridesByName(containerOverrides);
|
||||
List<ContainerDefinition> orderedDefinitions = orderFirelensContainers(
|
||||
taskDef.getContainerDefinitions());
|
||||
ContainerDefinition firelensRouter = firelensRouter(orderedDefinitions);
|
||||
if (firelensRouter != null && taskDef.getNetworkMode() == NetworkMode.awsvpc
|
||||
&& firewallManager != null && firewallManager.enabled()) {
|
||||
throw new AwsException("ClientException",
|
||||
"FireLens is not supported with security-group enforcement.", 400);
|
||||
}
|
||||
OptionalInt firelensHostPort = OptionalInt.empty();
|
||||
Map<ContainerDefinition, List<String>> envVarsByContainer = new LinkedHashMap<>();
|
||||
// Resolved before any container is created, so a registry-startup failure can't leak one already started.
|
||||
Map<ContainerDefinition, String> imagesByContainer = new LinkedHashMap<>();
|
||||
for (ContainerDefinition def : taskDef.getContainerDefinitions()) {
|
||||
for (ContainerDefinition def : orderedDefinitions) {
|
||||
envVarsByContainer.put(def, buildEnvVars(def, overridesByName.get(def.getName()), region));
|
||||
imagesByContainer.put(def, ecrRegistryManager.rewriteImageUri(def.getImage()));
|
||||
}
|
||||
@@ -165,7 +225,7 @@ public class EcsContainerManager {
|
||||
PreparedNetwork protectedNetwork = prepareNetwork(task, taskDef, region, taskId);
|
||||
|
||||
try {
|
||||
for (ContainerDefinition def : taskDef.getContainerDefinitions()) {
|
||||
for (ContainerDefinition def : orderedDefinitions) {
|
||||
String containerName = ContainerStorageHelper.dockerName(config, "floci-ecs-" + taskId + "-" + def.getName());
|
||||
|
||||
// RunTask containerOverrides matched by container name: command replaces
|
||||
@@ -183,12 +243,21 @@ public class EcsContainerManager {
|
||||
// own loopback.
|
||||
.withHostDockerInternalOnLinux()
|
||||
.withEmbeddedDns()
|
||||
.withLogRotation()
|
||||
.withLabels(ContainerStorageHelper.resourceIdentityLabels(
|
||||
"ecs", taskId, regionResolver.getAccountId(), region));
|
||||
boolean firelensApplication = usesFirelens(def);
|
||||
if (!firelensApplication) {
|
||||
specBuilder.withLogRotation();
|
||||
}
|
||||
if (protectedNetwork != null) {
|
||||
specBuilder.withNetworkMode("container:" + protectedNetwork.namespace().helperId());
|
||||
specBuilder.withLabels(Map.of("floci.security-group-workload", "true"));
|
||||
} else if (firelensApplication) {
|
||||
String routerId = containerIds.get(firelensRouter.getName());
|
||||
specBuilder.withNetworkMode("container:" + routerId);
|
||||
}
|
||||
if (def == firelensRouter) {
|
||||
specBuilder.withLoopbackPortBinding(24224, 0);
|
||||
}
|
||||
|
||||
// Add memory limit if specified
|
||||
@@ -204,7 +273,7 @@ public class EcsContainerManager {
|
||||
// local Docker host (#1778) — awsvpc mappings always get a dynamic
|
||||
// host port in native mode, or expose-only in Docker mode where ECS
|
||||
// consumers reach containers via the docker network IP.
|
||||
if (protectedNetwork == null && def.getPortMappings() != null) {
|
||||
if (protectedNetwork == null && !firelensApplication && def.getPortMappings() != null) {
|
||||
boolean awsvpc = taskDef.getNetworkMode() == NetworkMode.awsvpc;
|
||||
boolean publishToHost = !containerDetector.isRunningInContainer();
|
||||
for (PortMapping pm : def.getPortMappings()) {
|
||||
@@ -231,6 +300,11 @@ public class EcsContainerManager {
|
||||
specBuilder.withEntrypoint(def.getEntryPoint());
|
||||
}
|
||||
|
||||
if (firelensApplication) {
|
||||
specBuilder.withLogConfig(firelensLogConfig(
|
||||
taskId, def.getName(), firelensHostPort.orElseThrow()));
|
||||
}
|
||||
|
||||
// Bind-mount task-level volumes referenced by this container's mountPoints.
|
||||
// The host source path resolves on the Docker daemon (sibling-container launch),
|
||||
// so it must be an absolute host path. Unresolved volume references are skipped.
|
||||
@@ -269,6 +343,14 @@ public class EcsContainerManager {
|
||||
ContainerInfo info = lifecycleManager.createAndStart(spec);
|
||||
String dockerId = info.containerId();
|
||||
|
||||
if (def == firelensRouter) {
|
||||
firelensHostPort = info.publishedHostPort(24224);
|
||||
if (firelensHostPort.isEmpty()) {
|
||||
throw new AwsException("ClientException",
|
||||
"The FireLens log router did not publish port 24224.", 400);
|
||||
}
|
||||
}
|
||||
|
||||
LOG.infov("Created ECS container {0} for task {1} container {2}", dockerId, taskId, def.getName());
|
||||
|
||||
// Resolve network bindings for ECS-specific model
|
||||
@@ -284,11 +366,13 @@ public class EcsContainerManager {
|
||||
String logGroup = "/ecs/" + taskDef.getFamily();
|
||||
String logStream = logStreamer.generateLogStreamName(def.getName() + "/" + taskId);
|
||||
|
||||
Closeable logHandle = logStreamer.attach(
|
||||
dockerId, logGroup, logStream, region,
|
||||
"ecs:" + taskDef.getFamily() + ":" + def.getName());
|
||||
if (logHandle != null) {
|
||||
logStreamsByContainerId.put(dockerId, logHandle);
|
||||
if (!firelensApplication) {
|
||||
Closeable logHandle = logStreamer.attach(
|
||||
dockerId, logGroup, logStream, region,
|
||||
"ecs:" + taskDef.getFamily() + ":" + def.getName());
|
||||
if (logHandle != null) {
|
||||
logStreamsByContainerId.put(dockerId, logHandle);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
|
||||
@@ -20,6 +20,7 @@ public class ContainerDefinition {
|
||||
private List<String> entryPoint;
|
||||
private List<MountPoint> mountPoints;
|
||||
private LogConfiguration logConfiguration;
|
||||
private FirelensConfiguration firelensConfiguration;
|
||||
private HealthCheck healthCheck;
|
||||
|
||||
public String getName() { return name; }
|
||||
@@ -61,6 +62,11 @@ public class ContainerDefinition {
|
||||
public LogConfiguration getLogConfiguration() { return logConfiguration; }
|
||||
public void setLogConfiguration(LogConfiguration logConfiguration) { this.logConfiguration = logConfiguration; }
|
||||
|
||||
public FirelensConfiguration getFirelensConfiguration() { return firelensConfiguration; }
|
||||
public void setFirelensConfiguration(FirelensConfiguration firelensConfiguration) {
|
||||
this.firelensConfiguration = firelensConfiguration;
|
||||
}
|
||||
|
||||
public HealthCheck getHealthCheck() { return healthCheck; }
|
||||
public void setHealthCheck(HealthCheck healthCheck) { this.healthCheck = healthCheck; }
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package io.github.hectorvent.floci.services.ecs.model;
|
||||
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
@RegisterForReflection
|
||||
public record FirelensConfiguration(String type, Map<String, String> options) {
|
||||
}
|
||||
Reference in new issue
Block a user