feat(ecs): opt-in localhost between an awsvpc task's containers (#8654)

On Fargate the containers of an awsvpc task share one network namespace
and reach each other on localhost. Floci gave each container a namespace
of its own unless security-group enforcement was on, and enforcement
needs rootful Docker, so a sidecar task definition (nginx in front of
php-fpm on 127.0.0.1:9000) could not run unchanged on rootless Docker or
Podman.

floci.services.ecs.shared-task-network (FLOCI_SERVICES_ECS_SHARED_TASK_NETWORK),
off by default, gives such a task one namespace while enforcement is off.
A helper container holds it, as the ECS agent's pause container does. The
firewall manager starts it from the same code as a protected helper, with
no nftables table and no rootful requirement, and every container in the
task joins it. The helper holds what the task has once rather than per
container: its published ports, the link-local address its containers
reach the task-role credential endpoint from, and its ENI address on the
VPC's Docker network. FireLens's FLUENT_HOST is 127.0.0.1, the value the
ECS agent sets for awsvpc. The helper is removed once the task's
containers are, before its link-local address is handed on, and a helper
a previous run left behind is swept at startup with the task's other
containers. A helper Docker keeps is marked pending on the task's handle,
which the service keeps to retry the removal; its address stays reserved
until then, and it is taken off the VPC network so the ENI address is free
when the ENI is released. Launch cleanup removes a helper by name even when
its start failed part way, and now also covers the VPC attachment, so a
failed attachment no longer leaves the task's containers running. With
enforcement on, nothing changes.

The helper image now builds from docker.io/library/alpine: Podman refuses
a short name it cannot prompt about, and the task-role credentials proxy
builds from the same Dockerfile.

Closes #4331
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-11-16 19:23:57 -04:00
1 parent 3007534104
commit 895981ac8d
14 files changed
+939 -52

No files matched your search

@@ -2705,6 +2705,15 @@ public interface EmulatorConfig {
@WithDefault("127.0.0.1")
String hostPortBindAddress();
/**
* Opt-in: the containers of an {@code awsvpc} task share one network namespace, held by a helper
* container as the ECS agent's pause container holds it, so they reach each other on {@code localhost}
* as on Fargate. Applies while security-group enforcement is off, which already gives a task one
* namespace. Off by default: each container keeps a namespace and address of its own.
*/
@WithDefault("false")
boolean sharedTaskNetwork();
Optional<String> dockerNetwork();
@WithDefault("512")
@@ -34,13 +34,20 @@ import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.function.Function;
/** Owns the protected namespace and the Floci-only nftables table for each managed ENI. */
/**
* Owns the network-namespace helpers that EC2 instances and ECS tasks run in: the protected namespace and the
* Floci-only nftables table for each managed ENI, and the shared namespace of an ECS task that only needs its
* containers on one {@code localhost}.
*/
@ApplicationScoped
public class SecurityGroupFirewallManager {
private static final Logger LOG = Logger.getLogger(SecurityGroupFirewallManager.class);
private static final String PROTECTED_HELPER_PREFIX = "sg";
private static final String SHARED_HELPER_PREFIX = "netns";
private final DockerClient dockerClient;
private final ContainerBuilder containerBuilder;
private final ContainerLifecycleManager lifecycleManager;
@@ -121,21 +128,63 @@ public class SecurityGroupFirewallManager {
.anyMatch(option -> option.toLowerCase(Locale.ROOT).contains("rootless"))) {
throw new IllegalStateException("Security-group enforcement requires rootful Docker");
}
ensureHelperImage();
String name = ContainerStorageHelper.resourceName(config, "sg", null,
ContainerBuilder.Builder builder = helperBuilder(PROTECTED_HELPER_PREFIX, service, resourceId, accountId,
region, dockerNetwork, portBindings, hostIp)
.withLabels(Map.of(ContainerStorageHelper.SECURITY_GROUP_HELPER_LABEL, "true",
ContainerStorageHelper.OWNER_LABEL, ContainerStorageHelper.ownerIdentity(config)))
.withLabels(extraLabels);
return startHelper(builder, resourceId, "protected",
helperId -> apply(helperId, SecurityGroupNftCompiler.initialRuleset()));
}
/**
* Starts a namespace helper that filters nothing, for containers that only need to share one network
* namespace, as the containers of an {@code awsvpc} task do on Fargate. It needs neither security-group
* enforcement nor rootful Docker: the helper holds the namespace, its published ports and
* {@code linkLocalIps}, and no nftables table.
*/
public Namespace createSharedNamespace(String service, String resourceId, String accountId, String region,
Optional<String> dockerNetwork, Map<Integer, Integer> portBindings,
Map<String, String> extraLabels, String hostIp, List<String> linkLocalIps) {
ContainerBuilder.Builder builder = helperBuilder(SHARED_HELPER_PREFIX, service, resourceId, accountId,
region, dockerNetwork, portBindings, hostIp)
.withLabels(Map.of(ContainerStorageHelper.OWNER_LABEL, ContainerStorageHelper.ownerIdentity(config)))
.withLabels(extraLabels);
linkLocalIps.forEach(builder::withLinkLocalIp);
return startHelper(builder, resourceId, "shared", helperId -> { });
}
/**
* Removes the helper {@link #createSharedNamespace} started for {@code resourceId}, if there is one, and
* throws when Docker keeps it, since it may still hold host ports and a link-local address.
*/
public void removeSharedNamespaceStrict(String resourceId) {
lifecycleManager.removeIfExistsStrict(sharedNamespaceName(resourceId));
}
/** The container name of the helper {@link #createSharedNamespace} starts for {@code resourceId}. */
public String sharedNamespaceName(String resourceId) {
return helperName(SHARED_HELPER_PREFIX, resourceId);
}
private String helperName(String prefix, String resourceId) {
return ContainerStorageHelper.resourceName(config, prefix, null,
resourceId.replaceAll("[^a-zA-Z0-9_.-]", "-"));
}
private ContainerBuilder.Builder helperBuilder(String prefix, String service, String resourceId, String accountId,
String region, Optional<String> dockerNetwork,
Map<Integer, Integer> portBindings, String hostIp) {
ensureHelperImage();
ContainerBuilder.Builder builder = containerBuilder.newContainer(config.network().securityGroupEnforcement().helperImage())
.withName(name)
.withName(helperName(prefix, resourceId))
.withDockerNetwork(dockerNetwork)
// Workloads join this network namespace and use its resolver and hosts file.
.withEmbeddedDns()
.withHostDockerInternalOnLinux()
.withEntrypoint(List.of("sh", "-c"))
.withCmd(List.of("exec sleep 2147483647"))
.withLabels(ContainerStorageHelper.resourceIdentityLabels(service, resourceId, accountId, region))
.withLabels(Map.of(ContainerStorageHelper.SECURITY_GROUP_HELPER_LABEL, "true",
ContainerStorageHelper.OWNER_LABEL, ContainerStorageHelper.ownerIdentity(config)))
.withLabels(extraLabels);
.withLabels(ContainerStorageHelper.resourceIdentityLabels(service, resourceId, accountId, region));
if (portBindings != null) {
portBindings.forEach((containerPort, hostPort) -> {
if (hostIp == null) {
@@ -145,6 +194,12 @@ public class SecurityGroupFirewallManager {
}
});
}
return builder;
}
/** Starts the helper, then {@code prepare}s it; a helper that fails either step is removed. */
private Namespace startHelper(ContainerBuilder.Builder builder, String resourceId, String kind,
Consumer<String> prepare) {
ContainerSpec spec = builder.build();
String helperId = null;
try {
@@ -152,15 +207,15 @@ public class SecurityGroupFirewallManager {
Map<String, ContainerNetwork> networks = dockerClient.inspectContainerCmd(helperId).exec()
.getNetworkSettings().getNetworks();
String ip = firstAddress(networks, ContainerNetwork::getIpAddress)
.orElseThrow(() -> new IllegalStateException("Firewall helper has no Docker IP"));
apply(helperId, SecurityGroupNftCompiler.initialRuleset());
.orElseThrow(() -> new IllegalStateException("Namespace helper has no Docker IP"));
prepare.accept(helperId);
return new Namespace(helperId, ip, firstAddress(networks, ContainerNetwork::getGlobalIPv6Address)
.orElse(null));
} catch (Exception e) {
if (helperId != null) {
lifecycleManager.removeIfExists(helperId);
}
throw new IllegalStateException("Cannot prepare protected network namespace for " + resourceId, e);
throw new IllegalStateException("Cannot prepare " + kind + " network namespace for " + resourceId, e);
}
}
@@ -5711,7 +5711,7 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
private void retainPendingCleanupHandle(String taskArn, EcsTaskHandle handle) {
if (handle != null && (handle.hasOpenLogStreams() || handle.hasTaskVolumes()
|| !handle.allContainersRemoved())) {
|| !handle.allContainersRemoved() || handle.isNamespaceHelperPending())) {
taskHandles.put(taskArn, handle);
} else {
shutdownCleanupTasks.remove(taskArn);
@@ -130,6 +130,8 @@ public class EcsContainerManager {
* or before the Unix epoch is that zero value rather than a time a container reached.
*/
private static final Instant DOCKER_ZERO_TIMESTAMP = Instant.EPOCH;
/** The {@code FLUENT_HOST} the ECS agent gives an {@code awsvpc} task, whose containers share one namespace. */
private static final String FLUENT_AWSVPC_HOST = "127.0.0.1";
private final ContainerBuilder containerBuilder;
private final ContainerLifecycleManager lifecycleManager;
@@ -379,8 +381,18 @@ public class EcsContainerManager {
String networkModeName = taskDef.getNetworkMode() != null
? taskDef.getNetworkMode().name()
: NetworkMode.bridge.name();
SecurityGroupFirewallManager.Namespace sharedNamespace = null;
SecurityGroupFirewallManager.Namespace namespace = protectedNetwork == null ? null : protectedNetwork.namespace();
// The ENI a namespace helper is built around, which is how teardown finds the helper again.
String namespaceEniId = protectedNetwork == null ? null : protectedNetwork.eni().getNetworkInterfaceId();
try {
if (protectedNetwork == null && sharesTaskNetwork(task, taskDef)) {
// Set before the helper starts, so launch cleanup removes one a failed start left behind.
namespaceEniId = task.getNetworkInterfaceId();
sharedNamespace = prepareSharedNetwork(task, taskDef, region, taskId, taskRoleEndpoint);
namespace = sharedNamespace;
}
for (ContainerDefinition def : launchOrder) {
awaitDependencies(def, containerIds);
String containerName = ContainerStorageHelper.dockerName(config, "ecs-" + taskId + "-" + def.getName());
@@ -416,14 +428,17 @@ public class EcsContainerManager {
.withLabels(ContainerStorageHelper.resourceIdentityLabels(
"ecs", taskId, regionResolver.getAccountId(), region))
.withLabels(ownerLabels());
if (namespace != null) {
specBuilder.withNetworkMode("container:" + namespace.helperId());
}
if (protectedNetwork != null) {
specBuilder.withNetworkMode("container:" + protectedNetwork.namespace().helperId());
specBuilder.withLabels(Map.of(ContainerStorageHelper.SECURITY_GROUP_WORKLOAD_LABEL, "true"));
}
// Its own address in the credential endpoint's range, so this container has a
// connected route to 169.254.170.2 at all. One per container, not per task: each
// has its own network namespace and so its own routing table.
if (taskRoleEndpoint.vending()) {
// has its own network namespace and so its own routing table. A task sharing one
// namespace has one address, which its helper holds.
if (taskRoleEndpoint.vending() && namespace == null) {
specBuilder.withLinkLocalIp(
linkLocalAddresses.allocate(taskRoleEndpoint.network(), task.getTaskArn()));
}
@@ -478,7 +493,7 @@ public class EcsContainerManager {
// Stable publishing serves existing host clients; dynamic publishing lets
// tasks sharing an awsvpc container port coexist on the Docker host.
if (protectedNetwork == null && def.getPortMappings() != null) {
if (namespace == null && def.getPortMappings() != null) {
boolean awsvpc = taskDef.getNetworkMode() == NetworkMode.awsvpc;
boolean publishAwsvpcPorts = awsvpc && config.services().ecs().publishAwsvpcPortsToHost();
boolean publishToHost = !containerDetector.isRunningInContainer()
@@ -577,7 +592,9 @@ public class EcsContainerManager {
lifecycleManager.removeIfExists(dockerId);
throw e;
}
fluentHost = inspectContainerIp(dockerId);
// The ECS agent's FLUENT_HOST for awsvpc, where every container shares the task's
// namespace; a router joined to a helper has no address of its own to inspect.
fluentHost = namespace != null ? FLUENT_AWSVPC_HOST : inspectContainerIp(dockerId);
} else {
ContainerInfo info = lifecycleManager.createAndStartEphemeral(spec, platform);
dockerId = info.containerId();
@@ -589,7 +606,7 @@ public class EcsContainerManager {
// Resolve network bindings for ECS-specific model
List<NetworkBinding> networkBindings = resolveNetworkBindings(
protectedNetwork == null ? dockerId : protectedNetwork.namespace().helperId(), def);
namespace == null ? dockerId : namespace.helperId(), def);
// Build ECS container model
Container container = buildContainer(task.getTaskArn(), def, dockerId, networkBindings, region,
@@ -614,23 +631,24 @@ public class EcsContainerManager {
}
}
}
// Inside the launch cleanup: a failed attachment leaves containers and a helper to remove.
if (task.getNetworkInterfaceId() != null && protectedNetwork == null) {
joinTaskVpcNetwork(task, taskDef, containerIds,
sharedNamespace == null ? null : sharedNamespace.helperId(), region);
}
} catch (Exception e) {
EcsTaskHandle partial = new EcsTaskHandle(task.getTaskArn(), containerIds, logStreamsByContainerId,
firelensVolumeName,
protectedNetwork == null ? null : protectedNetwork.eni().getNetworkInterfaceId(), region,
stopTimeouts, taskVolumeNames);
firelensVolumeName, namespaceEniId, region, stopTimeouts, taskVolumeNames);
cleanupStoppedTask(partial);
if (protectedNetwork != null) {
releaseTaskNetwork(task, region);
}
if (!partial.allContainersRemoved() || partial.hasTaskVolumes() || partial.hasOpenLogStreams()) {
if (!partial.allContainersRemoved() || partial.hasTaskVolumes() || partial.hasOpenLogStreams()
|| partial.isNamespaceHelperPending()) {
throw new EcsTaskLaunchException(e, partial);
}
throw e;
}
if (task.getNetworkInterfaceId() != null && protectedNetwork == null) {
joinTaskVpcNetwork(task, taskDef, containerIds, region);
}
Map<String, Container> runtimeContainersByName = new LinkedHashMap<>();
for (Container container : runtimeContainers) {
@@ -658,9 +676,7 @@ public class EcsContainerManager {
task.setContainers(containersInDefinitionOrder);
return new EcsTaskHandle(task.getTaskArn(), containerIds, logStreamsByContainerId,
firelensVolumeName,
protectedNetwork == null ? null : protectedNetwork.eni().getNetworkInterfaceId(), region,
stopTimeouts, taskVolumeNames);
firelensVolumeName, namespaceEniId, region, stopTimeouts, taskVolumeNames);
}
private String taskVolumeName(EcsTask task, Volume volume) {
@@ -1156,27 +1172,32 @@ public class EcsContainerManager {
}
/**
* Puts one container of an awsvpc task on its VPC's Docker network at the task ENI address, so
* the address DescribeTasks reports answers. AWS gives the whole task that one address; here it
* goes to the first container that maps a port, else to the first container. Without
* Docker-backed VPC networks, or for an ENI address outside the subnet's planned range, the
* containers keep only the network they were created on. Removing the container disconnects
* it, before {@link #releaseTaskNetwork} returns the address.
* Puts the task ENI address on an awsvpc task's VPC Docker network, so the address DescribeTasks
* reports answers. AWS gives the whole task that one address. A task sharing one namespace gives
* it to the helper holding that namespace, so every container answers at it; otherwise it goes to
* the first container that maps a port, else to the first container. Without Docker-backed VPC
* networks, or for an ENI address outside the subnet's planned range, the containers keep only
* the network they were created on. Removing the holder disconnects it, before
* {@link #releaseTaskNetwork} returns the address.
*/
private void joinTaskVpcNetwork(EcsTask task, TaskDefinition taskDef, Map<String, String> containerIds,
String region) {
String namespaceHelperId, String region) {
String vpcId = taskVpcId(task, region);
if (vpcId == null) {
return;
}
List<ContainerDefinition> definitions = taskDef.getContainerDefinitions();
ContainerDefinition holder = definitions.stream()
.filter(def -> def.getPortMappings() != null && !def.getPortMappings().isEmpty())
.findFirst()
.orElse(definitions.getFirst());
String holderId = namespaceHelperId;
if (holderId == null) {
List<ContainerDefinition> definitions = taskDef.getContainerDefinitions();
ContainerDefinition holder = definitions.stream()
.filter(def -> def.getPortMappings() != null && !def.getPortMappings().isEmpty())
.findFirst()
.orElse(definitions.getFirst());
holderId = containerIds.get(holder.getName());
}
ec2Service.attachContainerToVpc(AwsArnUtils.accountOrDefault(task.getTaskArn(), regionResolver.getAccountId()),
region, vpcId, task.getNetworkConfiguration().getAwsvpcConfiguration().getSubnets().getFirst(),
containerIds.get(holder.getName()), task.getPrivateIpAddress());
holderId, task.getPrivateIpAddress());
}
/**
@@ -1391,6 +1412,84 @@ public class EcsContainerManager {
return address == null || address.isBlank() ? "127.0.0.1" : address;
}
/**
* Whether awsvpc tasks' containers share one namespace without security-group enforcement, which
* gives a task its own protected one instead.
*/
private boolean sharedTaskNetworkOn() {
return config.services().ecs().sharedTaskNetwork() && firewallManager != null && !firewallManager.enabled();
}
/**
* Whether this task's containers share one namespace: an awsvpc task, built around its ENI as a
* protected namespace is, so a task without one keeps a namespace per container.
*/
private boolean sharesTaskNetwork(EcsTask task, TaskDefinition definition) {
return definition.getNetworkMode() == NetworkMode.awsvpc && task.getNetworkInterfaceId() != null
&& sharedTaskNetworkOn();
}
/**
* Starts the helper holding an awsvpc task's one network namespace. The helper holds what the task
* has once rather than per container, as the ECS agent's pause container does: the published ports
* and the link-local address the credential endpoint is reached from.
*/
private SecurityGroupFirewallManager.Namespace prepareSharedNetwork(EcsTask task, TaskDefinition definition,
String region, String taskId,
TaskRoleCredentialEndpoint taskRoleEndpoint) {
Map<Integer, Integer> bindings = namespacePortBindings(
definition,
containerDetector.isRunningInContainer(),
config.services().ecs().publishAwsvpcPortsToHost(),
config.services().ecs().dynamicAwsvpcHostPorts());
List<String> linkLocalIps = taskRoleEndpoint.vending()
? List.of(linkLocalAddresses.allocate(taskRoleEndpoint.network(), task.getTaskArn()))
: List.of();
return firewallManager.createSharedNamespace("ecs", taskId, regionResolver.getAccountId(), region,
config.services().ecs().dockerNetwork(), bindings, Map.of(RUN_LABEL, runId), hostPortBindAddress(),
linkLocalIps);
}
/**
* Removes the helper of a task sharing one namespace, once its containers are gone. Throws when
* Docker keeps it, as the protected helper's removal does: the helper still holds the task's host
* ports and link-local address, which must not be handed on while it does. The handle then says the
* helper is pending, so the task's cleanup is retried, and the helper is taken off the VPC network
* so the ENI address it holds there is free when the ENI is released.
*/
private void removeSharedNetwork(EcsTaskHandle handle) {
if (handle.getNetworkInterfaceId() == null || !sharedTaskNetworkOn()) {
return;
}
String taskId = extractTaskId(handle.getTaskArn());
try {
firewallManager.removeSharedNamespaceStrict(taskId);
handle.recordNamespaceHelperPending(false);
} catch (RuntimeException e) {
handle.recordNamespaceHelperPending(true);
detachFromTaskVpc(handle, firewallManager.sharedNamespaceName(taskId));
throw e;
}
}
/** Best effort: a failure is logged, and the retried removal disconnects the helper anyway. */
private void detachFromTaskVpc(EcsTaskHandle handle, String containerName) {
if (ec2Service == null) {
return;
}
try {
ec2Service.describeNetworkInterfaces(handle.getRegion(), List.of(handle.getNetworkInterfaceId()),
Map.of(), 0, null)
.networkInterfaces().stream().findFirst()
.ifPresent(eni -> ec2Service.detachContainerFromVpc(
AwsArnUtils.accountOrDefault(handle.getTaskArn(), regionResolver.getAccountId()),
handle.getRegion(), eni.getVpcId(), containerName));
} catch (RuntimeException e) {
LOG.warnv(e, "Could not take the network namespace helper of ECS task {0} off its VPC network",
handle.getTaskArn());
}
}
static Map<Integer, Integer> namespacePortBindings(
TaskDefinition definition, boolean runningInContainer, boolean publishAwsvpcPortsToHost,
boolean dynamicAwsvpcHostPorts) {
@@ -1453,6 +1552,14 @@ public class EcsContainerManager {
revokeTaskRoleCredentials(handle.getTaskArn());
if (allRemoved) {
removeTaskVolumes(handle);
try {
removeSharedNetwork(handle);
} catch (RuntimeException e) {
// The handle now says the helper is pending, so the caller keeps it and the removal is
// retried; its address stays reserved until then, the cheaper mistake.
LOG.warnv(e, "Could not remove the network namespace helper of ECS task {0}", handle.getTaskArn());
return;
}
releaseTaskLinkLocalAddresses(handle.getTaskArn());
}
}
@@ -1547,6 +1654,7 @@ public class EcsContainerManager {
if (firewallManager != null && handle.getNetworkInterfaceId() != null) {
firewallManager.removeNamespaceStrict(handle.getNetworkInterfaceId());
}
removeSharedNetwork(handle);
cleanupProtectedNetwork(handle);
removeTaskVolumes(handle);
// Only now: a container that survived a failed removal still holds its address.
@@ -1989,7 +2097,8 @@ public class EcsContainerManager {
/**
* What a task's containers need to reach the credential endpoint: the relative URI to publish
* to them, and the network to give each of them an address on. Both are set or neither is,
* to them, and the network to give each of them, or the helper of a task sharing one namespace,
* an address on. Both are set or neither is,
* which {@link #vending()} answers. Absence is a null rather than an {@code Optional} field,
* which this codebase does not use.
*/
@@ -42,6 +42,11 @@ public class EcsTaskHandle {
private final Map<String, Integer> exitCodes = new LinkedHashMap<>();
/** Container names confirmed removed, including those whose exit code was unavailable. */
private final Set<String> removedContainers = new HashSet<>();
/**
* Whether Docker kept the helper holding the task's network namespace when it was removed, so its
* removal still has to be retried while it holds the task's host ports and link-local address.
*/
private boolean namespaceHelperPending;
public EcsTaskHandle(String taskArn, Map<String, String> containerIds,
Map<String, Closeable> logStreamsByContainerId) {
@@ -144,4 +149,12 @@ public class EcsTaskHandle {
public boolean hasOpenLogStreams() {
return !logStreamsByContainerId.isEmpty();
}
public boolean isNamespaceHelperPending() {
return namespaceHelperPending;
}
public void recordNamespaceHelperPending(boolean pending) {
namespaceHelperPending = pending;
}
}
@@ -240,8 +240,9 @@ final class FirelensConfigGenerator {
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.
// namespace. Floci gives each container a namespace of its own unless the task shares one,
// so the router listens on all interfaces for the injected FLUENT_HOST to be reachable from
// sibling containers either way.
return "0.0.0.0";
}