mirror of
https://github.com/floci-io/floci.git
synced 2026-12-02 09:47:56 -05:00
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:
1 parent
3007534104
commit
895981ac8d
14 files changed
+939
-52
No files matched your search
@@ -4,11 +4,13 @@ import com.github.dockerjava.api.DockerClient;
|
||||
import com.github.dockerjava.api.command.InspectImageResponse;
|
||||
import com.github.dockerjava.api.command.ListContainersCmd;
|
||||
import com.github.dockerjava.api.model.Container;
|
||||
import com.github.dockerjava.api.model.ContainerNetwork;
|
||||
import com.github.dockerjava.api.model.Info;
|
||||
import io.floci.aws.config.EmulatorConfig;
|
||||
import io.floci.aws.core.common.dns.EmbeddedDnsServer;
|
||||
import io.floci.aws.core.common.docker.ContainerBuilder;
|
||||
import io.floci.aws.core.common.docker.ContainerLifecycleManager;
|
||||
import io.floci.aws.core.common.docker.ContainerLifecycleManager.ContainerInfo;
|
||||
import io.floci.aws.core.common.docker.ContainerSpec;
|
||||
import io.floci.aws.core.common.docker.DockerHostResolver;
|
||||
import org.junit.jupiter.api.Test;
|
||||
@@ -20,6 +22,7 @@ import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
@@ -71,6 +74,57 @@ class SecurityGroupFirewallManagerTest {
|
||||
"the helper resolves host.docker.internal");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSharedHelperNeedsNeitherEnforcementNorRootfulDockerAndInstallsNoFirewall() {
|
||||
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
|
||||
when(config.network().securityGroupEnforcement().enabled()).thenReturn(false);
|
||||
when(config.network().securityGroupEnforcement().helperImage()).thenReturn("example/network-helper:test");
|
||||
when(config.port()).thenReturn(4566);
|
||||
when(config.docker().resourceNamespace()).thenReturn(Optional.empty());
|
||||
when(config.docker().imageRegistryBase()).thenReturn(Optional.empty());
|
||||
DockerClient dockerClient = mock(DockerClient.class, RETURNS_DEEP_STUBS);
|
||||
Info rootless = mock(Info.class);
|
||||
when(rootless.getOsType()).thenReturn("linux");
|
||||
when(rootless.getArchitecture()).thenReturn("amd64");
|
||||
when(rootless.getSecurityOptions()).thenReturn(List.of("name=seccomp,profile=builtin", "name=rootless"));
|
||||
when(dockerClient.infoCmd().exec()).thenReturn(rootless);
|
||||
when(dockerClient.inspectContainerCmd("helper-id").exec().getNetworkSettings().getNetworks())
|
||||
.thenReturn(Map.of("floci-net", new ContainerNetwork().withIpv4Address("172.18.0.9")));
|
||||
DockerHostResolver dockerHostResolver = mock(DockerHostResolver.class);
|
||||
when(dockerHostResolver.isLinuxHost()).thenReturn(true);
|
||||
EmbeddedDnsServer embeddedDnsServer = mock(EmbeddedDnsServer.class);
|
||||
when(embeddedDnsServer.getServerIp()).thenReturn(Optional.of("172.18.0.2"));
|
||||
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
|
||||
when(lifecycleManager.createAndStart(any())).thenReturn(new ContainerInfo("helper-id", Map.of()));
|
||||
SecurityGroupFirewallManager manager = new SecurityGroupFirewallManager(dockerClient,
|
||||
new ContainerBuilder(config, dockerHostResolver, embeddedDnsServer), lifecycleManager, config,
|
||||
embeddedDnsServer);
|
||||
|
||||
SecurityGroupFirewallManager.Namespace namespace = manager.createSharedNamespace("ecs", "abc123",
|
||||
"000000000000", "us-east-1", Optional.of("floci-net"), Map.of(80, 0),
|
||||
Map.of("io.floci.ecs.run", "run-1"), "127.0.0.1", List.of("169.254.170.1"));
|
||||
|
||||
assertEquals("helper-id", namespace.helperId());
|
||||
assertEquals("172.18.0.9", namespace.transportAddress());
|
||||
ArgumentCaptor<ContainerSpec> helper = ArgumentCaptor.forClass(ContainerSpec.class);
|
||||
verify(lifecycleManager).createAndStart(helper.capture());
|
||||
assertEquals("floci-aws-netns-abc123", helper.getValue().name());
|
||||
assertEquals("floci-net", helper.getValue().networkMode());
|
||||
assertEquals(List.of("169.254.170.1"), helper.getValue().linkLocalIps());
|
||||
assertEquals(Map.of(80, 0), helper.getValue().portBindings());
|
||||
assertEquals(Map.of(80, "127.0.0.1"), helper.getValue().portBindingHostIps());
|
||||
assertTrue(helper.getValue().dnsServers().contains("172.18.0.2"), "the helper uses Floci's DNS");
|
||||
assertEquals("ecs", helper.getValue().labels().get("io.floci.service"));
|
||||
assertEquals("4566", helper.getValue().labels().get("io.floci.owner"));
|
||||
assertEquals("run-1", helper.getValue().labels().get("io.floci.ecs.run"));
|
||||
// Not a protected helper: a startup with enforcement on must not quarantine it as one.
|
||||
assertFalse(helper.getValue().labels().containsKey("io.floci.security-group.helper"));
|
||||
verify(dockerClient, never()).execCreateCmd(anyString());
|
||||
|
||||
manager.removeSharedNamespaceStrict("abc123");
|
||||
verify(lifecycleManager).removeIfExistsStrict("floci-aws-netns-abc123");
|
||||
}
|
||||
|
||||
@Test
|
||||
void onlyFlocisDnsIsExemptFromTheSecurityGroups() {
|
||||
EmbeddedDnsServer embeddedDnsServer = mock(EmbeddedDnsServer.class);
|
||||
|
||||
@@ -279,6 +279,34 @@ class EcsEssentialContainerExitServiceTest {
|
||||
verify(manager, times(1)).releaseTaskNetwork(task, REGION);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aNamespaceHelperDockerKeptAfterTheContainersExitedIsRetried() {
|
||||
EcsTask task = runningTask(false);
|
||||
when(manager.getExitCodeIfStopped("app-id")).thenReturn(9);
|
||||
when(manager.getExitCodeIfStopped("sidecar-id")).thenReturn(0);
|
||||
doAnswer(invocation -> {
|
||||
EcsTaskHandle stopped = invocation.getArgument(0);
|
||||
stopped.getContainerIds().keySet().forEach(stopped::recordContainerRemoved);
|
||||
stopped.recordNamespaceHelperPending(true);
|
||||
return null;
|
||||
}).when(manager).cleanupStoppedTask(any());
|
||||
when(manager.stopTaskAndCollectExitCodes(any())).thenAnswer(invocation -> {
|
||||
handle.recordNamespaceHelperPending(false);
|
||||
return completeDockerStop();
|
||||
});
|
||||
|
||||
service.reconcile();
|
||||
service.reconcile();
|
||||
assertEquals("STOPPED", task.getLastStatus());
|
||||
verify(manager, times(1)).cleanupStoppedTask(handle);
|
||||
|
||||
// The helper still holds the task's host ports and link-local address, so its removal is retried
|
||||
// until Docker lets it go, and not after.
|
||||
service.reconcile();
|
||||
service.reconcile();
|
||||
verify(manager, times(1)).stopTaskAndCollectExitCodes(handle);
|
||||
}
|
||||
|
||||
private EcsTask runningTask(boolean explicitEssential) {
|
||||
ContainerDefinition app = new ContainerDefinition();
|
||||
app.setName("app");
|
||||
|
||||
+189
@@ -0,0 +1,189 @@
|
||||
package io.floci.aws.services.ecs;
|
||||
|
||||
import com.github.dockerjava.api.DockerClient;
|
||||
import com.github.dockerjava.api.exception.NotFoundException;
|
||||
import com.github.dockerjava.api.model.ContainerNetwork;
|
||||
import com.github.dockerjava.api.model.HostConfig;
|
||||
import io.floci.aws.core.common.docker.ContainerExec;
|
||||
import io.floci.aws.services.ec2.Ec2Service;
|
||||
import io.floci.aws.services.ec2.net.VpcNetworkManager;
|
||||
import io.floci.aws.services.ecs.model.AwsVpcConfiguration;
|
||||
import io.floci.aws.services.ecs.model.Container;
|
||||
import io.floci.aws.services.ecs.model.ContainerDefinition;
|
||||
import io.floci.aws.services.ecs.model.EcsTask;
|
||||
import io.floci.aws.services.ecs.model.LaunchType;
|
||||
import io.floci.aws.services.ecs.model.NetworkConfiguration;
|
||||
import io.floci.aws.services.ecs.model.NetworkMode;
|
||||
import io.floci.aws.services.ecs.model.PortMapping;
|
||||
import io.floci.aws.services.ecs.model.TaskDefinition;
|
||||
import io.floci.aws.testing.DockerAvailability;
|
||||
import io.floci.aws.testing.TestImages;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.QuarkusTestProfile;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static io.floci.aws.testing.EcsTaskWaits.awaitLastStatus;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.junit.jupiter.api.Assumptions.assumeTrue;
|
||||
|
||||
/**
|
||||
* With a shared task network and no security-group enforcement, the containers of an awsvpc task
|
||||
* reach each other on localhost, and every one of them answers at the task's ENI address.
|
||||
*/
|
||||
@QuarkusTest
|
||||
@TestProfile(EcsSharedTaskNetworkDockerIntegrationTest.SharedTaskNetworkProfile.class)
|
||||
class EcsSharedTaskNetworkDockerIntegrationTest {
|
||||
|
||||
private static final String REGION = "us-east-1";
|
||||
private static final String SUBNET = Ec2Service.defaultSubnetId("us-east-1", "a");
|
||||
private static final int FRONT_PORT = 8080;
|
||||
private static final int BACKEND_PORT = 8081;
|
||||
|
||||
/** Docker-backed ECS and VPC networks with a shared task network, enforcement left off. */
|
||||
public static final class SharedTaskNetworkProfile implements QuarkusTestProfile {
|
||||
@Override
|
||||
public Map<String, String> getConfigOverrides() {
|
||||
return Map.of("floci.services.ecs.mock", "false",
|
||||
"floci.services.ec2.mock", "false",
|
||||
"floci.services.ec2.vpc-networks.enabled", "true",
|
||||
"floci.network.security-group-enforcement.enabled", "false",
|
||||
"floci.services.ecs.shared-task-network", "true",
|
||||
"floci.docker.resource-namespace", "ecs-shared-netns-it");
|
||||
}
|
||||
}
|
||||
|
||||
@Inject
|
||||
EcsService ecsService;
|
||||
|
||||
@Inject
|
||||
Ec2Service ec2Service;
|
||||
|
||||
@Inject
|
||||
VpcNetworkManager vpcNetworkManager;
|
||||
|
||||
@Inject
|
||||
DockerClient dockerClient;
|
||||
|
||||
@BeforeEach
|
||||
void requireDocker() throws InterruptedException {
|
||||
assumeTrue(DockerAvailability.isAvailable(), "Docker must be available for the shared task network test");
|
||||
}
|
||||
|
||||
@Test
|
||||
void containersOfATaskReachEachOtherOnLocalhostAndAllAnswerAtTheEniAddress() throws InterruptedException {
|
||||
String clusterName = unique("shared-netns");
|
||||
ecsService.createCluster(clusterName, REGION);
|
||||
EcsTask task = ecsService.runTask(clusterName, registerFrontAndBackend().getTaskDefinitionArn(), 1,
|
||||
LaunchType.FARGATE, null, null, List.of(), awsvpcNetwork(), REGION).getFirst();
|
||||
String vpcId = ec2Service.describeSubnets(REGION, List.of(SUBNET), Map.of()).getFirst().getVpcId();
|
||||
String network = null;
|
||||
String probe = null;
|
||||
try {
|
||||
String taskArn = task.getTaskArn();
|
||||
EcsTask described = awaitLastStatus(
|
||||
() -> ecsService.describeTasks(clusterName, List.of(taskArn), REGION).getFirst(),
|
||||
EcsTask::getLastStatus, Duration.ofMinutes(2), "RUNNING", "STOPPED");
|
||||
assertEquals("RUNNING", described.getLastStatus(), "the task must start: " + described.getStoppedReason());
|
||||
Container front = container(described, "front");
|
||||
Container backend = container(described, "backend");
|
||||
|
||||
String frontMode = dockerClient.inspectContainerCmd(front.getDockerId()).exec().getHostConfig().getNetworkMode();
|
||||
String backendMode = dockerClient.inspectContainerCmd(backend.getDockerId()).exec().getHostConfig()
|
||||
.getNetworkMode();
|
||||
assertTrue(frontMode.startsWith("container:"), "the front container joins a namespace: " + frontMode);
|
||||
assertEquals(frontMode, backendMode, "both containers join the same namespace");
|
||||
String helperId = frontMode.substring("container:".length());
|
||||
assertNotEquals(front.getDockerId(), helperId, "a helper holds the namespace, not a task container");
|
||||
|
||||
ContainerExec.Result local = ContainerExec.run(dockerClient, front.getDockerId(), new String[] {"sh", "-c",
|
||||
"for i in 1 2 3 4 5 6 7 8 9 10; do wget -q -O- -T 1 http://127.0.0.1:" + BACKEND_PORT
|
||||
+ "/ && exit 0; sleep 0.2; done; exit 1"}, 30);
|
||||
assertEquals(0, local.exitCode(), "front must reach backend on localhost: " + local.summary());
|
||||
assertEquals("backend", local.stdout().trim());
|
||||
|
||||
String address = described.getPrivateIpAddress();
|
||||
assertNotNull(address, "an awsvpc task must report its ENI address");
|
||||
network = vpcNetworkManager.networkNameFor("000000000000", REGION, vpcId).orElseThrow();
|
||||
ContainerNetwork onVpc = dockerClient.inspectContainerCmd(helperId).exec()
|
||||
.getNetworkSettings().getNetworks().get(network);
|
||||
assertNotNull(onVpc, "the helper must join the VPC network " + network);
|
||||
assertEquals(address, onVpc.getIpAddress(), "the helper must hold the task's ENI address");
|
||||
|
||||
// backend maps no port, so it would not hold the ENI address with a namespace of its own.
|
||||
probe = dockerClient.createContainerCmd(TestImages.BUSYBOX)
|
||||
.withHostConfig(HostConfig.newHostConfig().withNetworkMode(network))
|
||||
.withCmd("sh", "-c", "for i in 1 2 3 4 5 6 7 8 9 10; do "
|
||||
+ "[ \"$(wget -q -O- -T 1 http://" + address + ":" + BACKEND_PORT + "/)\" = backend ] "
|
||||
+ "&& exit 0; sleep 0.1; done; exit 1")
|
||||
.exec().getId();
|
||||
dockerClient.startContainerCmd(probe).exec();
|
||||
assertEquals(0, dockerClient.waitContainerCmd(probe).start().awaitStatusCode(60, TimeUnit.SECONDS),
|
||||
"a peer on the VPC network must reach backend at " + address);
|
||||
|
||||
ecsService.stopTask(clusterName, task.getTaskArn(), "shared task network test", REGION);
|
||||
task = null;
|
||||
assertThrows(NotFoundException.class, () -> dockerClient.inspectContainerCmd(helperId).exec(),
|
||||
"a stopped task's helper must be removed");
|
||||
} finally {
|
||||
if (task != null) {
|
||||
ecsService.stopTask(clusterName, task.getTaskArn(), "test teardown", REGION);
|
||||
}
|
||||
if (probe != null) {
|
||||
dockerClient.removeContainerCmd(probe).withForce(true).exec();
|
||||
}
|
||||
if (network != null) {
|
||||
// Also disconnects the endpoint Floci gives itself on the network when it runs in a container.
|
||||
vpcNetworkManager.deleteVpcNetwork("000000000000", REGION, vpcId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private TaskDefinition registerFrontAndBackend() {
|
||||
ContainerDefinition front = server("front", FRONT_PORT);
|
||||
front.setPortMappings(List.of(new PortMapping(FRONT_PORT)));
|
||||
ContainerDefinition backend = server("backend", BACKEND_PORT);
|
||||
return ecsService.registerTaskDefinition(unique("shared-netns-td"), List.of(front, backend),
|
||||
NetworkMode.awsvpc, null, null, null, null, null, REGION);
|
||||
}
|
||||
|
||||
private static ContainerDefinition server(String name, int port) {
|
||||
ContainerDefinition container = new ContainerDefinition();
|
||||
container.setName(name);
|
||||
container.setImage(TestImages.BUSYBOX);
|
||||
container.setCommand(List.of("sh", "-c", "mkdir -p /www && echo " + name
|
||||
+ " > /www/index.html && exec httpd -f -p " + port + " -h /www"));
|
||||
return container;
|
||||
}
|
||||
|
||||
private static Container container(EcsTask task, String name) {
|
||||
return task.getContainers().stream()
|
||||
.filter(container -> name.equals(container.getName()))
|
||||
.findFirst()
|
||||
.orElseThrow(() -> new AssertionError("no container " + name + " in " + task.getContainers()));
|
||||
}
|
||||
|
||||
private static NetworkConfiguration awsvpcNetwork() {
|
||||
AwsVpcConfiguration awsvpc = new AwsVpcConfiguration();
|
||||
awsvpc.setSubnets(List.of(SUBNET));
|
||||
NetworkConfiguration networkConfiguration = new NetworkConfiguration();
|
||||
networkConfiguration.setAwsvpcConfiguration(awsvpc);
|
||||
return networkConfiguration;
|
||||
}
|
||||
|
||||
private static String unique(String prefix) {
|
||||
return prefix + "-" + UUID.randomUUID().toString().substring(0, 8);
|
||||
}
|
||||
}
|
||||
+396
@@ -0,0 +1,396 @@
|
||||
package io.floci.aws.services.ecs.container;
|
||||
|
||||
import com.github.dockerjava.api.DockerClient;
|
||||
import com.github.dockerjava.api.command.CopyArchiveToContainerCmd;
|
||||
import com.github.dockerjava.api.command.InspectVolumeCmd;
|
||||
import com.github.dockerjava.api.command.InspectVolumeResponse;
|
||||
import com.github.dockerjava.api.command.RemoveContainerCmd;
|
||||
import io.floci.aws.config.EmulatorConfig;
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
import io.floci.aws.core.common.docker.ContainerBuilder;
|
||||
import io.floci.aws.core.common.docker.ContainerDetector;
|
||||
import io.floci.aws.core.common.docker.ContainerLifecycleManager;
|
||||
import io.floci.aws.core.common.docker.ContainerLifecycleManager.ContainerInfo;
|
||||
import io.floci.aws.core.common.docker.ContainerLogStreamer;
|
||||
import io.floci.aws.core.common.docker.LaunchedContainerAwsEnv;
|
||||
import io.floci.aws.services.ec2.Ec2Service;
|
||||
import io.floci.aws.services.ec2.SecurityGroupFirewallManager;
|
||||
import io.floci.aws.services.ec2.model.GroupIdentifier;
|
||||
import io.floci.aws.services.ec2.model.NetworkInterface;
|
||||
import io.floci.aws.services.ec2.model.NetworkInterfaceListResult;
|
||||
import io.floci.aws.services.ec2.model.Subnet;
|
||||
import io.floci.aws.services.ecr.registry.EcrRegistryManager;
|
||||
import io.floci.aws.services.ecs.model.AwsVpcConfiguration;
|
||||
import io.floci.aws.services.ecs.model.ContainerDefinition;
|
||||
import io.floci.aws.services.ecs.model.EcsTask;
|
||||
import io.floci.aws.services.ecs.model.FirelensConfiguration;
|
||||
import io.floci.aws.services.ecs.model.LogConfiguration;
|
||||
import io.floci.aws.services.ecs.model.NetworkConfiguration;
|
||||
import io.floci.aws.services.ecs.model.NetworkMode;
|
||||
import io.floci.aws.services.ecs.model.PortMapping;
|
||||
import io.floci.aws.services.ecs.model.TaskDefinition;
|
||||
import io.floci.aws.services.lambda.launcher.ImageCacheService.LaunchImage;
|
||||
import io.floci.aws.services.s3.S3Service;
|
||||
import io.floci.aws.services.secretsmanager.SecretsManagerService;
|
||||
import io.floci.aws.services.ssm.SsmService;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyBoolean;
|
||||
import static org.mockito.ArgumentMatchers.anyInt;
|
||||
import static org.mockito.ArgumentMatchers.anyMap;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.ArgumentMatchers.isNull;
|
||||
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
|
||||
import static org.mockito.Mockito.RETURNS_SELF;
|
||||
import static org.mockito.Mockito.atLeastOnce;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* An awsvpc task's containers in one network namespace without security-group enforcement, held by
|
||||
* a helper the firewall manager starts with no firewall in it.
|
||||
*/
|
||||
class EcsContainerManagerSharedTaskNetworkTest {
|
||||
|
||||
private static final String TASK_ARN = "arn:aws:ecs:us-east-1:000000000000:task/test-cluster/abc123";
|
||||
private static final String NETWORK = "floci-net";
|
||||
private static final String ROLE_ARN = "arn:aws:iam::000000000000:role/task-role";
|
||||
private static final String RELATIVE_URI = "/v2/credentials/abc";
|
||||
private static final String OTHER_TASK = "arn:aws:ecs:us-east-1:000000000000:task/test-cluster/next";
|
||||
|
||||
private ContainerBuilder.Builder builder;
|
||||
private ContainerLifecycleManager lifecycleManager;
|
||||
private DockerClient dockerClient;
|
||||
private EmulatorConfig config;
|
||||
private Ec2Service ec2Service;
|
||||
private SecurityGroupFirewallManager firewallManager;
|
||||
private EcsTaskRoleCredentials taskRoleCredentials;
|
||||
private EcsTaskLinkLocalAddresses linkLocalAddresses;
|
||||
private EcsContainerManager manager;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
builder = mock(ContainerBuilder.Builder.class, RETURNS_SELF);
|
||||
ContainerBuilder containerBuilder = mock(ContainerBuilder.class);
|
||||
when(containerBuilder.newContainer(anyString())).thenReturn(builder);
|
||||
when(containerBuilder.resolveImage(anyString())).thenAnswer(invocation -> invocation.getArgument(0));
|
||||
when(containerBuilder.resolveDockerNetwork(any())).thenReturn(Optional.of(NETWORK));
|
||||
|
||||
lifecycleManager = mock(ContainerLifecycleManager.class);
|
||||
when(lifecycleManager.resolveImageForLaunch(any(), any(), any()))
|
||||
.thenAnswer(invocation -> new LaunchImage(invocation.getArgument(0), null));
|
||||
when(lifecycleManager.createAndStartEphemeral(any(), any())).thenReturn(new ContainerInfo("docker-id", Map.of()));
|
||||
dockerClient = mock(DockerClient.class, RETURNS_DEEP_STUBS);
|
||||
when(lifecycleManager.getDockerClient()).thenReturn(dockerClient);
|
||||
|
||||
config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
|
||||
when(config.services().ecs().sharedTaskNetwork()).thenReturn(true);
|
||||
RegionResolver regionResolver = mock(RegionResolver.class);
|
||||
when(regionResolver.getAccountId()).thenReturn("000000000000");
|
||||
LaunchedContainerAwsEnv awsEnv = mock(LaunchedContainerAwsEnv.class);
|
||||
when(awsEnv.sdkBaselineEnv(any(), any())).thenReturn(List.of());
|
||||
EcrRegistryManager ecrRegistryManager = mock(EcrRegistryManager.class);
|
||||
when(ecrRegistryManager.rewriteImageUri(anyString())).thenAnswer(inv -> inv.getArgument(0));
|
||||
|
||||
ec2Service = mock(Ec2Service.class);
|
||||
firewallManager = mock(SecurityGroupFirewallManager.class);
|
||||
when(firewallManager.enabled()).thenReturn(false);
|
||||
when(firewallManager.createSharedNamespace(eq("ecs"), eq("abc123"), any(), any(), any(), any(), any(),
|
||||
any(), any())).thenReturn(new SecurityGroupFirewallManager.Namespace("helper-id", "172.18.0.9"));
|
||||
taskRoleCredentials = mock(EcsTaskRoleCredentials.class);
|
||||
when(taskRoleCredentials.issue(any(), any(), any(), any())).thenReturn(Optional.of(RELATIVE_URI));
|
||||
linkLocalAddresses = new EcsTaskLinkLocalAddresses();
|
||||
|
||||
manager = new EcsContainerManager(
|
||||
containerBuilder, lifecycleManager, mock(ContainerLogStreamer.class),
|
||||
mock(ContainerDetector.class), config, regionResolver, awsEnv,
|
||||
mock(SsmService.class), mock(SecretsManagerService.class), mock(S3Service.class),
|
||||
ecrRegistryManager, mock(HostVolumePolicy.class),
|
||||
ec2Service, firewallManager, taskRoleCredentials, mock(EcsCredentialsProxy.class),
|
||||
linkLocalAddresses);
|
||||
}
|
||||
|
||||
@Test
|
||||
void everyContainerJoinsOneHelperThatHoldsTheTasksPorts() {
|
||||
EcsTaskHandle handle = manager.startTask(awsvpcTask(), taskDef(null,
|
||||
container("web", 8081), container("proxy", 80)), List.of(), "us-east-1");
|
||||
|
||||
verify(builder, times(2)).withNetworkMode("container:helper-id");
|
||||
verify(builder, never()).withLabels(Map.of("io.floci.security-group.workload", "true"));
|
||||
verify(builder, never()).withPortBinding(anyInt(), anyInt());
|
||||
verify(builder, never()).withPortBinding(anyInt(), anyInt(), anyString());
|
||||
verify(builder, never()).withDynamicPort(anyInt());
|
||||
verify(builder, never()).withExposedPort(anyInt());
|
||||
@SuppressWarnings("unchecked")
|
||||
ArgumentCaptor<Map<Integer, Integer>> ports = ArgumentCaptor.forClass(Map.class);
|
||||
verify(firewallManager).createSharedNamespace(eq("ecs"), eq("abc123"), eq("000000000000"),
|
||||
eq("us-east-1"), any(), ports.capture(), any(), eq("127.0.0.1"), eq(List.of()));
|
||||
Map<Integer, Integer> expected = new LinkedHashMap<>();
|
||||
expected.put(8081, 0);
|
||||
expected.put(80, 0);
|
||||
assertEquals(expected, ports.getValue());
|
||||
// Each container's network bindings are read off the helper, which publishes them.
|
||||
verify(dockerClient, atLeastOnce()).inspectContainerCmd("helper-id");
|
||||
verify(firewallManager, never()).createNamespace(any(), any(), any(), any(), any(), any(), any(), any());
|
||||
verify(firewallManager, never()).register(any(), any(), any());
|
||||
verify(ec2Service, never()).createNetworkInterface(any(), any(), any(), any(), any(), any(), any());
|
||||
assertEquals("eni-1", handle.getNetworkInterfaceId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void theHelperHoldsTheTasksOneCredentialAddress() {
|
||||
when(config.services().ecs().taskRoleCredentials().enabled()).thenReturn(true);
|
||||
|
||||
manager.startTask(awsvpcTask(), taskDef(ROLE_ARN, container("app", 80), container("sidecar", 9000)),
|
||||
List.of(), "us-east-1");
|
||||
|
||||
verify(firewallManager).createSharedNamespace(eq("ecs"), eq("abc123"), any(), any(), any(), any(), any(),
|
||||
any(), eq(List.of("169.254.170.1")));
|
||||
// A container joined to the helper has no network endpoint of its own to give an address to.
|
||||
verify(builder, never()).withLinkLocalIp(anyString());
|
||||
@SuppressWarnings("unchecked")
|
||||
ArgumentCaptor<List<String>> env = ArgumentCaptor.forClass(List.class);
|
||||
verify(builder, times(2)).withEnv(env.capture());
|
||||
for (List<String> containerEnv : env.getAllValues()) {
|
||||
assertTrue(containerEnv.contains("AWS_CONTAINER_CREDENTIALS_RELATIVE_URI=" + RELATIVE_URI),
|
||||
containerEnv.toString());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void theHelperHoldsTheEniAddressOnTheVpcNetwork() {
|
||||
Subnet subnet = new Subnet();
|
||||
subnet.setVpcId("vpc-1");
|
||||
when(ec2Service.describeSubnets(eq("us-east-1"), eq(List.of("subnet-1")), any())).thenReturn(List.of(subnet));
|
||||
|
||||
manager.startTask(awsvpcTask(), taskDef(null, container("web", 8081), container("proxy", 80)),
|
||||
List.of(), "us-east-1");
|
||||
|
||||
verify(ec2Service).attachContainerToVpc("000000000000", "us-east-1", "vpc-1", "subnet-1", "helper-id",
|
||||
"10.0.0.10");
|
||||
}
|
||||
|
||||
@Test
|
||||
void fireLensIsReachedOnLoopbackAsTheEcsAgentSetsItForAwsvpc() {
|
||||
when(lifecycleManager.create(any(), any())).thenReturn("router-id");
|
||||
when(lifecycleManager.startCreated(anyString(), any())).thenReturn(new ContainerInfo("router-id", Map.of()));
|
||||
InspectVolumeCmd inspectVolumeCmd = mock(InspectVolumeCmd.class);
|
||||
InspectVolumeResponse volume = mock(InspectVolumeResponse.class);
|
||||
when(dockerClient.inspectVolumeCmd(anyString())).thenReturn(inspectVolumeCmd);
|
||||
when(inspectVolumeCmd.exec()).thenReturn(volume);
|
||||
when(volume.getMountpoint()).thenReturn("/var/lib/docker/volumes/floci-ecs-firelens-abc123/_data");
|
||||
CopyArchiveToContainerCmd copyCmd = mock(CopyArchiveToContainerCmd.class, RETURNS_SELF);
|
||||
when(dockerClient.copyArchiveToContainerCmd("router-id")).thenReturn(copyCmd);
|
||||
ContainerDefinition router = container("log_router", 0);
|
||||
router.setFirelensConfiguration(new FirelensConfiguration("fluentbit", Map.of()));
|
||||
ContainerDefinition app = container("app", 0);
|
||||
app.setLogConfiguration(new LogConfiguration("awsfirelens", Map.of("Name", "cloudwatch"), null));
|
||||
|
||||
manager.startTask(awsvpcTask(), taskDef(null, app, router), List.of(), "us-east-1");
|
||||
|
||||
verify(builder, times(2)).withNetworkMode("container:helper-id");
|
||||
@SuppressWarnings("unchecked")
|
||||
ArgumentCaptor<List<String>> env = ArgumentCaptor.forClass(List.class);
|
||||
verify(builder, times(2)).withEnv(env.capture());
|
||||
assertTrue(env.getAllValues().stream().anyMatch(containerEnv -> containerEnv.contains("FLUENT_HOST=127.0.0.1")),
|
||||
env.getAllValues().toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void stoppingRemovesTheHelperOnceTheContainersAreGoneAndThenFreesItsAddress() {
|
||||
when(config.services().ecs().taskRoleCredentials().enabled()).thenReturn(true);
|
||||
EcsTaskHandle handle = manager.startTask(awsvpcTask(), taskDef(ROLE_ARN, container("app", 80)),
|
||||
List.of(), "us-east-1");
|
||||
|
||||
manager.stopTaskAndCollectExitCodes(handle);
|
||||
|
||||
verify(firewallManager).removeSharedNamespaceStrict("abc123");
|
||||
assertEquals("169.254.170.1", linkLocalAddresses.allocate(NETWORK, OTHER_TASK),
|
||||
"the stopped task's address is free again");
|
||||
}
|
||||
|
||||
@Test
|
||||
void theHelperOutlivesAContainerDockerWouldNotRemove() {
|
||||
EcsTaskHandle handle = manager.startTask(awsvpcTask(), taskDef(null, container("app", 80)),
|
||||
List.of(), "us-east-1");
|
||||
RemoveContainerCmd remove = mock(RemoveContainerCmd.class, RETURNS_SELF);
|
||||
when(dockerClient.removeContainerCmd("docker-id")).thenReturn(remove);
|
||||
doThrow(new IllegalStateException("removal in progress")).when(remove).exec();
|
||||
|
||||
manager.stopTaskAndCollectExitCodes(handle);
|
||||
|
||||
verify(firewallManager, never()).removeSharedNamespaceStrict(anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aHelperDockerKeepsIsTakenOffTheVpcNetworkAndRetriedBeforeItsAddressIsFreed() {
|
||||
when(config.services().ecs().taskRoleCredentials().enabled()).thenReturn(true);
|
||||
when(firewallManager.sharedNamespaceName("abc123")).thenReturn("floci-aws-netns-abc123");
|
||||
NetworkInterface eni = new NetworkInterface();
|
||||
eni.setNetworkInterfaceId("eni-1");
|
||||
eni.setVpcId("vpc-1");
|
||||
when(ec2Service.describeNetworkInterfaces(eq("us-east-1"), eq(List.of("eni-1")), anyMap(), eq(0), isNull()))
|
||||
.thenReturn(new NetworkInterfaceListResult(List.of(eni), null));
|
||||
doThrow(new IllegalStateException("helper busy")).doNothing()
|
||||
.when(firewallManager).removeSharedNamespaceStrict("abc123");
|
||||
EcsTaskHandle handle = manager.startTask(awsvpcTask(), taskDef(ROLE_ARN, container("app", 80)),
|
||||
List.of(), "us-east-1");
|
||||
|
||||
assertThrows(IllegalStateException.class, () -> manager.stopTaskAndCollectExitCodes(handle));
|
||||
|
||||
assertTrue(handle.isNamespaceHelperPending(), "the handle keeps the helper's removal to retry");
|
||||
// So the ENI address it holds there is free when the task's ENI is released.
|
||||
verify(ec2Service).detachContainerFromVpc("000000000000", "us-east-1", "vpc-1", "floci-aws-netns-abc123");
|
||||
verify(taskRoleCredentials).revoke(TASK_ARN);
|
||||
assertEquals("169.254.170.3", linkLocalAddresses.allocate(NETWORK, OTHER_TASK),
|
||||
"169.254.170.1 is still the helper's, and .2 is the endpoint's own");
|
||||
linkLocalAddresses.releaseAll(OTHER_TASK);
|
||||
|
||||
manager.stopTaskAndCollectExitCodes(handle);
|
||||
|
||||
assertFalse(handle.isNamespaceHelperPending());
|
||||
assertEquals("169.254.170.1", linkLocalAddresses.allocate(NETWORK, OTHER_TASK),
|
||||
"the retried removal frees the helper's address");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aHelperThatCannotStartFailsTheLaunchAndFreesItsAddressOnceItIsGone() {
|
||||
when(config.services().ecs().taskRoleCredentials().enabled()).thenReturn(true);
|
||||
when(firewallManager.createSharedNamespace(any(), any(), any(), any(), any(), any(), any(), any(), any()))
|
||||
.thenThrow(new IllegalStateException("cannot start the helper"));
|
||||
|
||||
assertThrows(IllegalStateException.class, () -> manager.startTask(awsvpcTask(),
|
||||
taskDef(ROLE_ARN, container("app", 80)), List.of(), "us-east-1"));
|
||||
|
||||
verify(lifecycleManager, never()).createAndStartEphemeral(any(), any());
|
||||
// Confirmed by name, since a failed start may have left the helper behind.
|
||||
verify(firewallManager).removeSharedNamespaceStrict("abc123");
|
||||
verify(taskRoleCredentials).revoke(TASK_ARN);
|
||||
assertEquals("169.254.170.1", linkLocalAddresses.allocate(NETWORK, OTHER_TASK));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aHelperAFailedStartLeftBehindKeepsItsAddressAndItsCleanup() {
|
||||
when(config.services().ecs().taskRoleCredentials().enabled()).thenReturn(true);
|
||||
when(firewallManager.createSharedNamespace(any(), any(), any(), any(), any(), any(), any(), any(), any()))
|
||||
.thenThrow(new IllegalStateException("inspect failed after the helper started"));
|
||||
doThrow(new IllegalStateException("helper busy")).when(firewallManager).removeSharedNamespaceStrict("abc123");
|
||||
|
||||
EcsTaskLaunchException failed = assertThrows(EcsTaskLaunchException.class, () -> manager.startTask(
|
||||
awsvpcTask(), taskDef(ROLE_ARN, container("app", 80)), List.of(), "us-east-1"));
|
||||
|
||||
assertTrue(failed.getHandle().isNamespaceHelperPending(), "the service keeps the handle to retry");
|
||||
assertEquals("169.254.170.3", linkLocalAddresses.allocate(NETWORK, OTHER_TASK),
|
||||
"the helper Docker kept still holds 169.254.170.1");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aFailedVpcAttachmentRemovesTheContainersAndTheHelper() {
|
||||
Subnet subnet = new Subnet();
|
||||
subnet.setVpcId("vpc-1");
|
||||
when(ec2Service.describeSubnets(eq("us-east-1"), eq(List.of("subnet-1")), any())).thenReturn(List.of(subnet));
|
||||
when(ec2Service.attachContainerToVpc(any(), any(), any(), any(), any(), any()))
|
||||
.thenThrow(new IllegalStateException("VPC network is gone"));
|
||||
|
||||
assertThrows(IllegalStateException.class, () -> manager.startTask(awsvpcTask(),
|
||||
taskDef(null, container("web", 8081)), List.of(), "us-east-1"));
|
||||
|
||||
verify(lifecycleManager).stopAndRemoveStrict(eq("docker-id"), any(), anyInt(), anyBoolean());
|
||||
verify(firewallManager).removeSharedNamespaceStrict("abc123");
|
||||
}
|
||||
|
||||
@Test
|
||||
void withTheSettingOffEachContainerKeepsANamespaceOfItsOwn() {
|
||||
when(config.services().ecs().sharedTaskNetwork()).thenReturn(false);
|
||||
|
||||
manager.startTask(awsvpcTask(), taskDef(null, container("app", 80)), List.of(), "us-east-1");
|
||||
|
||||
verify(firewallManager, never()).createSharedNamespace(any(), any(), any(), any(), any(), any(), any(), any(),
|
||||
any());
|
||||
verify(builder, never()).withNetworkMode(anyString());
|
||||
verify(builder).withPortBinding(80, 0, "127.0.0.1");
|
||||
}
|
||||
|
||||
@Test
|
||||
void enforcementGivesTheTaskItsProtectedNamespaceInstead() {
|
||||
when(firewallManager.enabled()).thenReturn(true);
|
||||
when(firewallManager.createNamespace(eq("ecs"), eq("abc123"), any(), any(), any(), any(), any(), any()))
|
||||
.thenThrow(new IllegalStateException("stop once the protected path is taken"));
|
||||
NetworkInterface eni = new NetworkInterface();
|
||||
eni.setNetworkInterfaceId("eni-1");
|
||||
eni.setGroups(List.of(new GroupIdentifier("sg-1", "default")));
|
||||
when(ec2Service.createNetworkInterface(any(), eq("subnet-1"), any(), any(), any(), any(), any()))
|
||||
.thenReturn(eni);
|
||||
|
||||
assertThrows(IllegalStateException.class, () -> manager.startTask(awsvpcTask(),
|
||||
taskDef(null, container("app", 80)), List.of(), "us-east-1"));
|
||||
|
||||
verify(firewallManager).createNamespace(eq("ecs"), eq("abc123"), any(), any(), any(), any(), any(), any());
|
||||
verify(firewallManager, never()).createSharedNamespace(any(), any(), any(), any(), any(), any(), any(), any(),
|
||||
any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aBridgeTaskKeepsANamespacePerContainer() {
|
||||
TaskDefinition bridge = taskDef(null, container("app", 80));
|
||||
bridge.setNetworkMode(NetworkMode.bridge);
|
||||
|
||||
manager.startTask(awsvpcTask(), bridge, List.of(), "us-east-1");
|
||||
|
||||
verify(firewallManager, never()).createSharedNamespace(any(), any(), any(), any(), any(), any(), any(), any(),
|
||||
any());
|
||||
verify(builder, never()).withNetworkMode(anyString());
|
||||
}
|
||||
|
||||
private static EcsTask awsvpcTask() {
|
||||
AwsVpcConfiguration awsvpc = new AwsVpcConfiguration();
|
||||
awsvpc.setSubnets(List.of("subnet-1"));
|
||||
awsvpc.setSecurityGroups(List.of("sg-1"));
|
||||
NetworkConfiguration network = new NetworkConfiguration();
|
||||
network.setAwsvpcConfiguration(awsvpc);
|
||||
EcsTask task = new EcsTask();
|
||||
task.setTaskArn(TASK_ARN);
|
||||
task.setNetworkConfiguration(network);
|
||||
// As attachTaskNetwork leaves it before the containers start.
|
||||
task.setNetworkInterfaceId("eni-1");
|
||||
task.setPrivateIpAddress("10.0.0.10");
|
||||
return task;
|
||||
}
|
||||
|
||||
private static ContainerDefinition container(String name, int port) {
|
||||
ContainerDefinition container = new ContainerDefinition();
|
||||
container.setName(name);
|
||||
container.setImage(name + ":latest");
|
||||
if (port > 0) {
|
||||
container.setPortMappings(List.of(new PortMapping(port, port, "tcp")));
|
||||
}
|
||||
return container;
|
||||
}
|
||||
|
||||
private static TaskDefinition taskDef(String taskRoleArn, ContainerDefinition... containers) {
|
||||
TaskDefinition taskDef = new TaskDefinition();
|
||||
taskDef.setFamily("shared-family");
|
||||
taskDef.setRevision(1);
|
||||
taskDef.setNetworkMode(NetworkMode.awsvpc);
|
||||
taskDef.setTaskRoleArn(taskRoleArn);
|
||||
taskDef.setContainerDefinitions(List.of(containers));
|
||||
return taskDef;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user