mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(ecs): give an awsvpc task the address it reports (#7645)
With Docker-backed VPC networks, one container of an awsvpc task joins its VPC's Docker network at the task ENI address, so the address DescribeTasks reports answers. A Lambda function with VpcConfig joins the same network at an address leased from its first subnet, skipping addresses an interface already holds, and returns it once its container is removed. Peer and Cloud Map addresses still resolve on the network a container was created on. Closes #7639
This commit is contained in:
1 parent
dba4a4fc52
commit
2df2a1e149
13 files changed
+827
-69
No files matched your search
@@ -4779,18 +4779,16 @@ class Ec2ServiceTest {
|
||||
|
||||
@Test
|
||||
void aRefusedLeaseDoesNotTurnAFreeAddressIntoOneInUse() {
|
||||
// DeleteNetworkInterface does not return its lease, so the lease table can outlive the
|
||||
// resource that took one. With nothing in any account holding the address any more, the
|
||||
// stale lease must not fail the launch.
|
||||
// A failed launch gives its lease back only once its container is detached, so the lease
|
||||
// table can hold an address nothing stored in any account stands behind. That lease must
|
||||
// not fail the launch.
|
||||
RequestContext context = new RequestContext();
|
||||
Ec2Service service = realVpcNetworkService(context);
|
||||
RealVpcNetworkFixture fixture = realVpcNetworkFixture(context, Map.of());
|
||||
Ec2Service service = fixture.service();
|
||||
String subnetId = Ec2Service.defaultSubnetId("us-east-1", "a");
|
||||
context.setAccountId("111122223333");
|
||||
service.describeSubnets("us-east-1", List.of(), Map.of());
|
||||
NetworkInterface deleted = service.createNetworkInterface("us-east-1", subnetId, "deleted", null,
|
||||
List.of(), List.of(), List.of());
|
||||
service.deleteNetworkInterface("us-east-1", deleted.getNetworkInterfaceId());
|
||||
String stale = deleted.getPrivateIpAddress();
|
||||
String stale = fixture.vpcNetworks().allocatePrivateIp("us-east-1", subnetId).orElseThrow();
|
||||
|
||||
context.setAccountId("000000000000");
|
||||
|
||||
@@ -4974,8 +4972,7 @@ class Ec2ServiceTest {
|
||||
|
||||
@Test
|
||||
void anAddressTheWalkSkipsIsGivenBackToTheVpcNetwork() {
|
||||
// Its holder took no lease, and deleting an interface returns none, so a lease the walk
|
||||
// kept would outlive the holder.
|
||||
// Its holder took no lease, so the network must not count one for it.
|
||||
MockedNetworkFixture fixture = mockedNetworkFixture("10.50.1.0/24", "10.50.1.10", "10.50.1.11");
|
||||
fixture.service().createNetworkInterface("us-east-1", fixture.subnetId(), "holder", "10.50.1.10",
|
||||
List.of(), List.of(), List.of());
|
||||
@@ -4984,6 +4981,17 @@ class Ec2ServiceTest {
|
||||
assertEquals(List.of("10.50.1.10"), fixture.released());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deletingAnInterfaceGivesBackTheLeaseOfItsAddress() {
|
||||
MockedNetworkFixture fixture = mockedNetworkFixture("10.50.1.0/24", "10.50.1.10");
|
||||
String eniId = fixture.service().createNetworkInterface("us-east-1", fixture.subnetId(), "task", null,
|
||||
List.of(), List.of(), List.of()).getNetworkInterfaceId();
|
||||
|
||||
fixture.service().deleteNetworkInterface("us-east-1", eniId);
|
||||
|
||||
assertEquals(List.of("10.50.1.10"), fixture.released());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anInterfaceRefusedForAHeldSecondaryLeasesNoPrimaryOnTheVpcNetwork() {
|
||||
MockedNetworkFixture fixture = mockedNetworkFixture("10.50.1.0/24", "10.50.1.10");
|
||||
@@ -5053,6 +5061,69 @@ class Ec2ServiceTest {
|
||||
assertEquals(List.of("172.31.0.11"), launchAddresses(service, subnetId, 1));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aVpcAddressLeasedOutsideEc2SkipsAnAddressAnInterfaceHolds() {
|
||||
RequestContext context = new RequestContext();
|
||||
VpcNetworkManager vpcNetworks = mock(VpcNetworkManager.class);
|
||||
Ec2Service service = mockedVpcNetworkService(context, Map.of(), vpcNetworks);
|
||||
String subnetId = Ec2Service.defaultSubnetId("us-east-1", "a");
|
||||
service.describeSubnets("us-east-1", List.of(), Map.of());
|
||||
service.createNetworkInterface("us-east-1", subnetId, "holder", "172.31.0.10",
|
||||
List.of(), List.of(), List.of());
|
||||
when(vpcNetworks.allocatePrivateIp("us-east-1", subnetId))
|
||||
.thenReturn(Optional.of("172.31.0.10"), Optional.of("172.31.0.11"));
|
||||
|
||||
assertEquals(Optional.of("172.31.0.11"), service.allocateVpcPrivateIp("us-east-1", subnetId));
|
||||
verify(vpcNetworks).releasePrivateIp("us-east-1", subnetId, "172.31.0.10");
|
||||
}
|
||||
|
||||
@Test
|
||||
void anAddressAContainerLeasedIsInUseUntilItIsGivenBack() {
|
||||
VpcNetworkManager vpcNetworks = mock(VpcNetworkManager.class);
|
||||
Ec2Service service = mockedVpcNetworkService(new RequestContext(), Map.of(), vpcNetworks);
|
||||
String subnetId = Ec2Service.defaultSubnetId("us-east-1", "a");
|
||||
service.describeSubnets("us-east-1", List.of(), Map.of());
|
||||
when(vpcNetworks.allocatePrivateIp("us-east-1", subnetId))
|
||||
.thenReturn(Optional.of("172.31.0.10"), Optional.empty());
|
||||
service.allocateVpcPrivateIp("us-east-1", subnetId);
|
||||
|
||||
AwsException inUse = assertThrows(AwsException.class, () -> service.createNetworkInterface("us-east-1",
|
||||
subnetId, "named", "172.31.0.10", List.of(), List.of(), List.of()));
|
||||
assertEquals("InvalidIPAddress.InUse", inUse.getErrorCode());
|
||||
// The network's range is exhausted, so the address is synthesised.
|
||||
assertEquals("172.31.0.11", service.createNetworkInterface("us-east-1", subnetId, "automatic", null,
|
||||
List.of(), List.of(), List.of()).getPrivateIpAddress());
|
||||
|
||||
service.releaseVpcPrivateIp("us-east-1", subnetId, "172.31.0.10");
|
||||
assertEquals("172.31.0.10", service.createNetworkInterface("us-east-1", subnetId, "named", "172.31.0.10",
|
||||
List.of(), List.of(), List.of()).getPrivateIpAddress());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anInterfaceEndpointCreatedAfterContainerLeasesTakesAnAddressNoContainerHolds() {
|
||||
// Ten of a /28's eleven assignable addresses leased to containers, so whatever the endpoint
|
||||
// id prefers, its interface must land on the one left over.
|
||||
List<String> leased = new ArrayList<>();
|
||||
for (int host = 4; host <= 13; host++) {
|
||||
leased.add("10.50.1." + host);
|
||||
}
|
||||
MockedNetworkFixture fixture = mockedNetworkFixture("10.50.1.0/28", leased.toArray(String[]::new));
|
||||
Ec2Service service = fixture.service();
|
||||
for (int i = 0; i < leased.size(); i++) {
|
||||
service.allocateVpcPrivateIp("us-east-1", fixture.subnetId());
|
||||
}
|
||||
String vpcId = service.describeSubnets("us-east-1", List.of(fixture.subnetId()), Map.of())
|
||||
.getFirst().getVpcId();
|
||||
|
||||
service.createVpcEndpoint("us-east-1", vpcId, "com.amazonaws.us-east-1.ecs", "Interface", List.of(),
|
||||
List.of(fixture.subnetId()), List.of(), null, null, List.of());
|
||||
|
||||
assertEquals("10.50.1.14", endpointAddressesBySubnet(service).get(fixture.subnetId()));
|
||||
AwsException inUse = assertThrows(AwsException.class, () -> service.createNetworkInterface("us-east-1",
|
||||
fixture.subnetId(), "named", "10.50.1.14", List.of(), List.of(), List.of()));
|
||||
assertEquals("InvalidIPAddress.InUse", inUse.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anAddressALaunchNamedWithoutLeasingItIsNotHandedOutAgain() {
|
||||
// A failed launch is marked terminated before its container is detached and its lease given
|
||||
@@ -5124,13 +5195,18 @@ class Ec2ServiceTest {
|
||||
return realVpcNetworkService(context, Map.of());
|
||||
}
|
||||
|
||||
private static Ec2Service realVpcNetworkService(RequestContext context,
|
||||
Map<String, AccountAwareStorageBackend<?>> stores) {
|
||||
return realVpcNetworkFixture(context, stores).service();
|
||||
}
|
||||
|
||||
/**
|
||||
* Ec2Service in container mode over a real VpcNetworkManager, whose Docker daemon has no
|
||||
* networks yet, with the caller's account taken from {@code context} and {@code stores}
|
||||
* standing in for what a previous run persisted.
|
||||
*/
|
||||
private static Ec2Service realVpcNetworkService(RequestContext context,
|
||||
Map<String, AccountAwareStorageBackend<?>> stores) {
|
||||
private static RealVpcNetworkFixture realVpcNetworkFixture(RequestContext context,
|
||||
Map<String, AccountAwareStorageBackend<?>> stores) {
|
||||
EmulatorConfig config = mockConfig(false);
|
||||
EmulatorConfig.VpcNetworksConfig networks = mock(EmulatorConfig.VpcNetworksConfig.class);
|
||||
when(config.services().ec2().vpcNetworks()).thenReturn(networks);
|
||||
@@ -5142,9 +5218,14 @@ class Ec2ServiceTest {
|
||||
AmiImageResolver images = mock(AmiImageResolver.class);
|
||||
when(images.resolveImage(any())).thenReturn(ResolvedAmiImage.minimal("floci/base:latest"));
|
||||
jakarta.enterprise.inject.Instance<RequestContext> contexts = requestContexts(context);
|
||||
return new Ec2Service(config, mock(Ec2ContainerManager.class), mock(Ec2PortForwardManager.class), images,
|
||||
mock(Ec2ImageCatalog.class), new Ec2InstanceTypeCatalog(), new InMemoryStorageFactory(stores, contexts),
|
||||
contexts, new VpcNetworkManager(config, docker, null), null, null, null);
|
||||
VpcNetworkManager vpcNetworks = new VpcNetworkManager(config, docker, null);
|
||||
Ec2Service service = new Ec2Service(config, mock(Ec2ContainerManager.class), mock(Ec2PortForwardManager.class),
|
||||
images, mock(Ec2ImageCatalog.class), new Ec2InstanceTypeCatalog(),
|
||||
new InMemoryStorageFactory(stores, contexts), contexts, vpcNetworks, null, null, null);
|
||||
return new RealVpcNetworkFixture(service, vpcNetworks);
|
||||
}
|
||||
|
||||
private record RealVpcNetworkFixture(Ec2Service service, VpcNetworkManager vpcNetworks) {
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+152
@@ -0,0 +1,152 @@
|
||||
package io.floci.aws.services.ecs;
|
||||
|
||||
import com.github.dockerjava.api.DockerClient;
|
||||
import com.github.dockerjava.api.model.ContainerNetwork;
|
||||
import com.github.dockerjava.api.model.HostConfig;
|
||||
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.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.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assumptions.assumeTrue;
|
||||
|
||||
/**
|
||||
* An awsvpc task answers at the address DescribeTasks reports for it, for a peer on its VPC's
|
||||
* Docker network: the stand-in for a Lambda function or an instance in the same VPC.
|
||||
*/
|
||||
@QuarkusTest
|
||||
@TestProfile(EcsAwsvpcTaskAddressDockerIntegrationTest.VpcNetworksProfile.class)
|
||||
class EcsAwsvpcTaskAddressDockerIntegrationTest {
|
||||
|
||||
private static final String REGION = "us-east-1";
|
||||
private static final String SUBNET = "subnet-default-us-east-1-a";
|
||||
private static final int PORT = 8080;
|
||||
|
||||
/**
|
||||
* Docker-backed ECS and VPC networks, which need EC2 unmocked. Security-group enforcement keeps
|
||||
* its shipped default of off, and a namespace of its own keeps the VPC network this test
|
||||
* creates apart from any other Floci on the daemon.
|
||||
*/
|
||||
public static final class VpcNetworksProfile 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.docker.resource-namespace", "ecs-awsvpc-address-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 awsvpc address test");
|
||||
}
|
||||
|
||||
@Test
|
||||
void peerOnTheVpcNetworkReachesTheAddressDescribeTasksReports() throws InterruptedException {
|
||||
String clusterName = unique("awsvpc-address");
|
||||
ecsService.createCluster(clusterName, REGION);
|
||||
EcsTask task = ecsService.runTask(clusterName, registerWebServer().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 {
|
||||
EcsTask described = ecsService.describeTasks(clusterName, List.of(task.getTaskArn()), REGION).getFirst();
|
||||
assertEquals("RUNNING", described.getLastStatus(), "the task must start: " + described.getStoppedReason());
|
||||
String address = described.getPrivateIpAddress();
|
||||
assertNotNull(address, "an awsvpc task must report its ENI address");
|
||||
network = vpcNetworkManager.networkNameFor(REGION, vpcId).orElseThrow();
|
||||
String dockerId = described.getContainers().getFirst().getDockerId();
|
||||
ContainerNetwork onVpc = dockerClient.inspectContainerCmd(dockerId).exec()
|
||||
.getNetworkSettings().getNetworks().get(network);
|
||||
assertNotNull(onVpc, "the task container must join the VPC network " + network);
|
||||
assertEquals(address, onVpc.getIpAddress(), "the task container must hold its ENI address");
|
||||
|
||||
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 + ":" + PORT + "/)\" = ok ] && 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 the task at " + address);
|
||||
|
||||
ecsService.stopTask(clusterName, task.getTaskArn(), "awsvpc address test", REGION);
|
||||
task = null;
|
||||
assertFalse(dockerClient.inspectNetworkCmd().withNetworkId(network).exec()
|
||||
.getContainers().containsKey(dockerId),
|
||||
"a stopped task must leave the VPC network");
|
||||
} 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(REGION, vpcId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private TaskDefinition registerWebServer() {
|
||||
ContainerDefinition web = new ContainerDefinition();
|
||||
web.setName("web");
|
||||
web.setImage(TestImages.BUSYBOX);
|
||||
web.setCommand(List.of("sh", "-c",
|
||||
"mkdir -p /www && echo ok > /www/index.html && exec httpd -f -p " + PORT + " -h /www"));
|
||||
web.setPortMappings(List.of(new PortMapping(PORT)));
|
||||
return ecsService.registerTaskDefinition(unique("awsvpc-address-td"), List.of(web), NetworkMode.awsvpc,
|
||||
null, null, null, null, null, REGION);
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
+227
@@ -0,0 +1,227 @@
|
||||
package io.floci.aws.services.ecs.container;
|
||||
|
||||
import com.github.dockerjava.api.DockerClient;
|
||||
import com.github.dockerjava.api.command.InspectContainerResponse;
|
||||
import com.github.dockerjava.api.model.ContainerNetwork;
|
||||
import com.github.dockerjava.api.model.HostConfig;
|
||||
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.SecurityGroup;
|
||||
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.Container;
|
||||
import io.floci.aws.services.ecs.model.ContainerDefinition;
|
||||
import io.floci.aws.services.ecs.model.EcsTask;
|
||||
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.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
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.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
|
||||
import static org.mockito.Mockito.RETURNS_SELF;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* An awsvpc task reports its ENI address, so one of its containers has to hold that address on
|
||||
* the VPC's Docker network. Peers that reach the task through Cloud Map or ELBv2 keep using the
|
||||
* address on the network the container was created on.
|
||||
*/
|
||||
class EcsContainerManagerTaskAddressTest {
|
||||
|
||||
private static final String REGION = "us-east-1";
|
||||
|
||||
private ContainerLifecycleManager lifecycleManager;
|
||||
private DockerClient dockerClient;
|
||||
private Ec2Service ec2Service;
|
||||
private SecurityGroupFirewallManager firewallManager;
|
||||
private ContainerBuilder containerBuilder;
|
||||
private EcsContainerManager manager;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
ContainerBuilder.Builder builder = mock(ContainerBuilder.Builder.class, RETURNS_SELF);
|
||||
containerBuilder = mock(ContainerBuilder.class);
|
||||
when(containerBuilder.newContainer(anyString())).thenReturn(builder);
|
||||
when(containerBuilder.resolveImage(anyString())).thenAnswer(invocation -> invocation.getArgument(0));
|
||||
|
||||
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("sidecar-id", Map.of()), new ContainerInfo("web-id", Map.of()));
|
||||
dockerClient = mock(DockerClient.class, RETURNS_DEEP_STUBS);
|
||||
when(lifecycleManager.getDockerClient()).thenReturn(dockerClient);
|
||||
|
||||
ContainerDetector containerDetector = mock(ContainerDetector.class);
|
||||
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
|
||||
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);
|
||||
Subnet subnet = new Subnet();
|
||||
subnet.setSubnetId("subnet-1");
|
||||
subnet.setVpcId("vpc-1");
|
||||
when(ec2Service.describeSubnets(eq(REGION), eq(List.of("subnet-1")), any())).thenReturn(List.of(subnet));
|
||||
firewallManager = mock(SecurityGroupFirewallManager.class);
|
||||
|
||||
manager = new EcsContainerManager(
|
||||
containerBuilder, lifecycleManager, mock(ContainerLogStreamer.class),
|
||||
containerDetector, config, regionResolver, awsEnv,
|
||||
mock(SsmService.class), mock(SecretsManagerService.class), mock(S3Service.class),
|
||||
ecrRegistryManager, mock(HostVolumePolicy.class),
|
||||
ec2Service, firewallManager,
|
||||
mock(EcsTaskRoleCredentials.class), mock(EcsCredentialsProxy.class),
|
||||
new EcsTaskLinkLocalAddresses());
|
||||
}
|
||||
|
||||
@Test
|
||||
void awsvpcTaskGivesItsEniAddressToTheFirstContainerThatMapsAPort() {
|
||||
manager.startTask(taskWithEni(), taskDefinition(NetworkMode.awsvpc,
|
||||
container("sidecar", List.of()), container("web", List.of(new PortMapping(80, 80, "tcp")))),
|
||||
List.of(), REGION);
|
||||
|
||||
verify(ec2Service).attachContainerToVpc(REGION, "vpc-1", "subnet-1", "web-id", "10.0.0.10");
|
||||
}
|
||||
|
||||
@Test
|
||||
void awsvpcTaskWithoutPortMappingsGivesItsEniAddressToItsFirstContainer() {
|
||||
manager.startTask(taskWithEni(), taskDefinition(NetworkMode.awsvpc,
|
||||
container("sidecar", List.of()), container("web", List.of())), List.of(), REGION);
|
||||
|
||||
verify(ec2Service).attachContainerToVpc(REGION, "vpc-1", "subnet-1", "sidecar-id", "10.0.0.10");
|
||||
}
|
||||
|
||||
@Test
|
||||
void bridgeTaskJoinsNoVpcNetwork() {
|
||||
EcsTask task = new EcsTask();
|
||||
task.setTaskArn("arn:aws:ecs:us-east-1:000000000000:task/test-cluster/abc123");
|
||||
|
||||
manager.startTask(task, taskDefinition(NetworkMode.bridge,
|
||||
container("web", List.of(new PortMapping(80, 80, "tcp")))), List.of(), REGION);
|
||||
|
||||
verify(ec2Service, never()).attachContainerToVpc(any(), any(), any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void securityGroupProtectedTaskKeepsItsOwnNamespace() {
|
||||
when(firewallManager.enabled()).thenReturn(true);
|
||||
when(firewallManager.createNamespace(eq("ecs"), eq("abc123"), any(), any(), any(), any(), any(), any()))
|
||||
.thenReturn(new SecurityGroupFirewallManager.Namespace("helper-id", "10.0.0.5"));
|
||||
NetworkInterface eni = new NetworkInterface();
|
||||
eni.setNetworkInterfaceId("eni-1");
|
||||
eni.setVpcId("vpc-1");
|
||||
eni.setPrivateIpAddress("10.0.0.10");
|
||||
eni.setGroups(List.of(new GroupIdentifier("sg-1", "default")));
|
||||
when(ec2Service.createNetworkInterface(any(), eq("subnet-1"), any(), any(), any(), any(), any()))
|
||||
.thenReturn(eni);
|
||||
SecurityGroup sg = new SecurityGroup();
|
||||
sg.setGroupId("sg-1");
|
||||
when(ec2Service.describeSecurityGroups(any(), eq(List.of("sg-1")), any(), any())).thenReturn(List.of(sg));
|
||||
EcsTask task = taskWithEni();
|
||||
task.setNetworkInterfaceId(null);
|
||||
|
||||
manager.startTask(task, taskDefinition(NetworkMode.awsvpc,
|
||||
container("web", List.of(new PortMapping(80, 80, "tcp")))), List.of(), REGION);
|
||||
|
||||
assertEquals("eni-1", task.getNetworkInterfaceId());
|
||||
verify(ec2Service, never()).attachContainerToVpc(any(), any(), any(), any(), any());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"bridge", "default"})
|
||||
void peerAddressStaysOnTheNetworkTheContainerWasCreatedOn(String networkMode) {
|
||||
InspectContainerResponse inspect = mock(InspectContainerResponse.class, RETURNS_DEEP_STUBS);
|
||||
when(inspect.getHostConfig()).thenReturn(new HostConfig().withNetworkMode(networkMode));
|
||||
Map<String, ContainerNetwork> networks = new LinkedHashMap<>();
|
||||
networks.put("floci-vpc-4566-us-east-1-vpc-1", new ContainerNetwork().withIpv4Address("10.0.0.10"));
|
||||
networks.put("bridge", new ContainerNetwork().withIpv4Address("172.17.0.5"));
|
||||
when(inspect.getNetworkSettings().getNetworks()).thenReturn(networks);
|
||||
when(dockerClient.inspectContainerCmd("web-id").exec()).thenReturn(inspect);
|
||||
Container container = new Container();
|
||||
container.setDockerId("web-id");
|
||||
|
||||
assertEquals(Optional.of("172.17.0.5"), manager.resolvePeerAddress(container));
|
||||
}
|
||||
|
||||
@Test
|
||||
void peerAddressPrefersTheNetworkEcsContainersJoin() {
|
||||
when(containerBuilder.resolveDockerNetwork(any())).thenReturn(Optional.of("floci-net"));
|
||||
InspectContainerResponse inspect = mock(InspectContainerResponse.class, RETURNS_DEEP_STUBS);
|
||||
// Created on the default bridge to publish its ports, then connected to Floci's network.
|
||||
when(inspect.getHostConfig()).thenReturn(new HostConfig().withNetworkMode("default"));
|
||||
Map<String, ContainerNetwork> networks = new LinkedHashMap<>();
|
||||
networks.put("bridge", new ContainerNetwork().withIpv4Address("172.17.0.5"));
|
||||
networks.put("floci-net", new ContainerNetwork().withIpv4Address("172.20.0.5"));
|
||||
when(inspect.getNetworkSettings().getNetworks()).thenReturn(networks);
|
||||
when(dockerClient.inspectContainerCmd("web-id").exec()).thenReturn(inspect);
|
||||
Container container = new Container();
|
||||
container.setDockerId("web-id");
|
||||
|
||||
assertEquals(Optional.of("172.20.0.5"), manager.resolvePeerAddress(container));
|
||||
}
|
||||
|
||||
private static EcsTask taskWithEni() {
|
||||
AwsVpcConfiguration awsvpc = new AwsVpcConfiguration();
|
||||
awsvpc.setSubnets(List.of("subnet-1"));
|
||||
awsvpc.setSecurityGroups(List.of("sg-1"));
|
||||
NetworkConfiguration network = new NetworkConfiguration();
|
||||
network.setAwsvpcConfiguration(awsvpc);
|
||||
EcsTask task = new EcsTask();
|
||||
task.setTaskArn("arn:aws:ecs:us-east-1:000000000000:task/test-cluster/abc123");
|
||||
task.setNetworkConfiguration(network);
|
||||
task.setNetworkInterfaceId("eni-1");
|
||||
task.setPrivateIpAddress("10.0.0.10");
|
||||
return task;
|
||||
}
|
||||
|
||||
private static ContainerDefinition container(String name, List<PortMapping> ports) {
|
||||
ContainerDefinition definition = new ContainerDefinition();
|
||||
definition.setName(name);
|
||||
definition.setImage(name + ":latest");
|
||||
definition.setPortMappings(ports);
|
||||
return definition;
|
||||
}
|
||||
|
||||
private static TaskDefinition taskDefinition(NetworkMode mode, ContainerDefinition... containers) {
|
||||
TaskDefinition taskDef = new TaskDefinition();
|
||||
taskDef.setFamily("test-family");
|
||||
taskDef.setNetworkMode(mode);
|
||||
taskDef.setContainerDefinitions(List.of(containers));
|
||||
return taskDef;
|
||||
}
|
||||
}
|
||||
@@ -255,7 +255,7 @@ class LambdaImageConfigTest {
|
||||
launcher = new ContainerLauncher(containerBuilder, lifecycleManager, logStreamer, imageResolver,
|
||||
runtimeApiServerFactory, dockerHostResolver, config, ecrRegistryManager,
|
||||
mock(LambdaLayerService.class), awsEnv,
|
||||
mock(LambdaExecutionRoleCredentials.class));
|
||||
mock(LambdaExecutionRoleCredentials.class), null);
|
||||
|
||||
when(runtimeApiServerFactory.create()).thenReturn(runtimeApiServer);
|
||||
when(runtimeApiServer.getPort()).thenReturn(9000);
|
||||
|
||||
+2
-2
@@ -68,7 +68,7 @@ class ContainerLauncherCodeVolumeReuseTest {
|
||||
mock(ImageResolver.class), mock(RuntimeApiServerFactory.class),
|
||||
mock(DockerHostResolver.class), config, mock(EcrRegistryManager.class),
|
||||
mock(LambdaLayerService.class), mock(LaunchedContainerAwsEnv.class),
|
||||
mock(LambdaExecutionRoleCredentials.class));
|
||||
mock(LambdaExecutionRoleCredentials.class), null);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -283,7 +283,7 @@ class ContainerLauncherCodeVolumeReuseTest {
|
||||
mock(ContainerLogStreamer.class), mock(ImageResolver.class),
|
||||
mock(RuntimeApiServerFactory.class), mock(DockerHostResolver.class), config,
|
||||
mock(EcrRegistryManager.class), mock(LambdaLayerService.class),
|
||||
mock(LaunchedContainerAwsEnv.class), mock(LambdaExecutionRoleCredentials.class));
|
||||
mock(LaunchedContainerAwsEnv.class), mock(LambdaExecutionRoleCredentials.class), null);
|
||||
|
||||
assertThrows(IllegalStateException.class,
|
||||
() -> real.populateCodeVolume("vol", fn("sha"), "img"));
|
||||
|
||||
+1
-1
@@ -33,7 +33,7 @@ class ContainerLauncherCopyRetryTest {
|
||||
// no longer builds; the copy paths under test read nothing else from it.
|
||||
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
|
||||
when(config.services().lambda().codeVolumePopulateConcurrency()).thenReturn(Optional.empty());
|
||||
return new ContainerLauncher(null, null, null, null, null, null, config, null, null, null, null);
|
||||
return new ContainerLauncher(null, null, null, null, null, null, config, null, null, null, null, null);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -15,6 +15,7 @@ import com.github.dockerjava.api.model.MountType;
|
||||
import com.github.dockerjava.api.model.StreamType;
|
||||
import com.github.dockerjava.api.model.VersionComponent;
|
||||
import io.floci.aws.config.EmulatorConfig;
|
||||
import io.floci.aws.core.common.RequestScopes;
|
||||
import io.floci.aws.core.common.dns.EmbeddedDnsServer;
|
||||
import io.floci.aws.core.common.docker.ContainerBuilder;
|
||||
import io.floci.aws.core.common.docker.ContainerEngineDetector;
|
||||
@@ -26,6 +27,7 @@ import io.floci.aws.core.common.docker.CurrentContainerNetworkResolver;
|
||||
import io.floci.aws.core.common.docker.DockerHostResolver;
|
||||
import io.floci.aws.core.common.docker.LaunchedContainerAwsEnv;
|
||||
import io.floci.aws.services.cloudwatch.logs.CloudWatchLogsService;
|
||||
import io.floci.aws.services.ec2.Ec2Service;
|
||||
import io.floci.aws.services.ecr.registry.EcrRegistryManager;
|
||||
import io.floci.aws.services.iam.model.SessionCreds;
|
||||
import io.floci.aws.services.lambda.LambdaLayerFixtures;
|
||||
@@ -49,6 +51,8 @@ import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.InOrder;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.MockMakers;
|
||||
import org.mockito.MockedStatic;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
@@ -70,6 +74,7 @@ import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static io.floci.aws.testing.DockerDaemonVersionFixtures.stubDaemonVersion;
|
||||
@@ -101,6 +106,7 @@ class ContainerLauncherTest {
|
||||
@Mock DockerClient dockerClient;
|
||||
@Mock LambdaExecutionRoleCredentials executionRoleCredentials;
|
||||
@Mock LambdaLayerService layerService;
|
||||
@Mock Ec2Service ec2Service;
|
||||
|
||||
@TempDir
|
||||
Path tempDir;
|
||||
@@ -242,7 +248,7 @@ class ContainerLauncherTest {
|
||||
new ContainerBuilder(config, dockerHostResolver, embeddedDnsServer),
|
||||
lifecycleManager, logStreamer, imageResolver, runtimeApiServerFactory,
|
||||
dockerHostResolver, config, ecrRegistryManager, layers,
|
||||
new LaunchedContainerAwsEnv(endpoint), executionRoleCredentials);
|
||||
new LaunchedContainerAwsEnv(endpoint), executionRoleCredentials, ec2Service);
|
||||
LambdaFunction fn = new LambdaFunction();
|
||||
fn.setFunctionName("background-layer");
|
||||
fn.setFunctionArn("arn:aws:lambda:" + region + ":" + account + ":function:background-layer");
|
||||
@@ -463,7 +469,7 @@ class ContainerLauncherTest {
|
||||
return new ContainerLauncher(builder, lifecycleManager, logStreamer, selectedResolver,
|
||||
runtimeApiServerFactory, dockerHostResolver, config, ecrRegistryManager,
|
||||
layerService, new LaunchedContainerAwsEnv(endpoint),
|
||||
executionRoleCredentials);
|
||||
executionRoleCredentials, ec2Service);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@@ -854,7 +860,7 @@ class ContainerLauncherTest {
|
||||
|
||||
// No populate helper is created/discarded for small code.
|
||||
verify(lifecycleManager, times(1)).create(any());
|
||||
verify(lifecycleManager, never()).stopAndRemove(any(), any());
|
||||
verify(lifecycleManager, never()).stopAndRemoveStrict(any(), any());
|
||||
|
||||
// createAndStart must NOT be called — Lambda uses the split path
|
||||
verify(lifecycleManager, never()).createAndStart(any());
|
||||
@@ -984,7 +990,7 @@ class ContainerLauncherTest {
|
||||
() -> launcher.launchProvisioned(fn));
|
||||
assertTrue(error.getMessage().startsWith("Configured layer is unavailable for provisioned initialization:"));
|
||||
verify(lifecycleManager, never()).startCreated(anyString(), any());
|
||||
verify(lifecycleManager).stopAndRemove("container-123", null);
|
||||
verify(lifecycleManager).stopAndRemoveStrict("container-123", null);
|
||||
verify(runtimeApiServerFactory).release(runtimeApiServer);
|
||||
verify(runtimeApiServer, never()).expectExtensions(anyInt());
|
||||
verify(runtimeApiServer, never()).enqueue(any());
|
||||
@@ -1258,7 +1264,7 @@ class ContainerLauncherTest {
|
||||
|
||||
// No populate helper for small code.
|
||||
verify(lifecycleManager, times(1)).create(any());
|
||||
verify(lifecycleManager, never()).stopAndRemove(any(), any());
|
||||
verify(lifecycleManager, never()).stopAndRemoveStrict(any(), any());
|
||||
verify(lifecycleManager, never()).createAndStart(any());
|
||||
}
|
||||
|
||||
@@ -1407,6 +1413,140 @@ class ContainerLauncherTest {
|
||||
verify(executionRoleCredentials).unregister("222233334444", "ASIAFAILEDSESSION");
|
||||
}
|
||||
|
||||
@Test
|
||||
void vpcFunctionJoinsItsVpcNetworkBeforeStartAndReturnsTheAddressAfterRemoval() throws Exception {
|
||||
LambdaFunction fn = vpcFunction("vpc-join-fn");
|
||||
when(ec2Service.allocateVpcPrivateIp("us-east-1", "subnet-a")).thenReturn(Optional.of("172.31.0.20"));
|
||||
when(ec2Service.attachContainerToVpc("us-east-1", "vpc-1", "subnet-a", "container-123", "172.31.0.20"))
|
||||
.thenReturn(Optional.of("floci-vpc-1"));
|
||||
|
||||
ContainerHandle handle = launcher.launch(fn);
|
||||
verify(ec2Service, never()).releaseVpcPrivateIp(any(), any(), any());
|
||||
launcher.stop(handle);
|
||||
|
||||
InOrder order = inOrder(ec2Service, lifecycleManager);
|
||||
order.verify(ec2Service).allocateVpcPrivateIp("us-east-1", "subnet-a");
|
||||
order.verify(ec2Service).attachContainerToVpc("us-east-1", "vpc-1", "subnet-a", "container-123",
|
||||
"172.31.0.20");
|
||||
order.verify(lifecycleManager).startCreated(eq("container-123"), any());
|
||||
order.verify(lifecycleManager).stopAndRemoveStrict("container-123", null, 1);
|
||||
order.verify(ec2Service).releaseVpcPrivateIp("us-east-1", "subnet-a", "172.31.0.20");
|
||||
}
|
||||
|
||||
@Test
|
||||
void vpcFunctionKeepsItsAddressUntilARetriedRemovalSucceeds() throws Exception {
|
||||
LambdaFunction fn = vpcFunction("vpc-retry-fn");
|
||||
when(ec2Service.allocateVpcPrivateIp("us-east-1", "subnet-a")).thenReturn(Optional.of("172.31.0.23"));
|
||||
when(ec2Service.attachContainerToVpc("us-east-1", "vpc-1", "subnet-a", "container-123", "172.31.0.23"))
|
||||
.thenReturn(Optional.of("floci-vpc-1"));
|
||||
ContainerHandle handle = launcher.launch(fn);
|
||||
doThrow(new RuntimeException("removal failed")).doNothing()
|
||||
.when(lifecycleManager).stopAndRemoveStrict("container-123", null, 1);
|
||||
|
||||
assertThrows(RuntimeException.class, () -> launcher.stop(handle));
|
||||
verify(ec2Service, never()).releaseVpcPrivateIp(any(), any(), any());
|
||||
|
||||
launcher.stop(handle);
|
||||
verify(ec2Service).releaseVpcPrivateIp("us-east-1", "subnet-a", "172.31.0.23");
|
||||
}
|
||||
|
||||
@Test
|
||||
void vpcFunctionReturnsTheAddressOnceAFailedLaunchRemovesItsContainer() throws Exception {
|
||||
LambdaFunction fn = vpcFunction("vpc-launch-failure-fn");
|
||||
when(ec2Service.allocateVpcPrivateIp("us-east-1", "subnet-a")).thenReturn(Optional.of("172.31.0.21"));
|
||||
when(ec2Service.attachContainerToVpc("us-east-1", "vpc-1", "subnet-a", "container-123", "172.31.0.21"))
|
||||
.thenReturn(Optional.of("floci-vpc-1"));
|
||||
doThrow(new RuntimeException("start failed")).when(lifecycleManager).startCreated(eq("container-123"), any());
|
||||
|
||||
assertThrows(RuntimeException.class, () -> launcher.launch(fn));
|
||||
|
||||
InOrder order = inOrder(lifecycleManager, ec2Service);
|
||||
order.verify(lifecycleManager).stopAndRemoveStrict("container-123", null);
|
||||
order.verify(ec2Service).releaseVpcPrivateIp("us-east-1", "subnet-a", "172.31.0.21");
|
||||
}
|
||||
|
||||
@Test
|
||||
void vpcFunctionKeepsTheAddressWhenAFailedLaunchCannotRemoveItsContainer() throws Exception {
|
||||
LambdaFunction fn = vpcFunction("vpc-launch-removal-failure-fn");
|
||||
when(ec2Service.allocateVpcPrivateIp("us-east-1", "subnet-a")).thenReturn(Optional.of("172.31.0.24"));
|
||||
when(ec2Service.attachContainerToVpc("us-east-1", "vpc-1", "subnet-a", "container-123", "172.31.0.24"))
|
||||
.thenReturn(Optional.of("floci-vpc-1"));
|
||||
doThrow(new RuntimeException("start failed")).when(lifecycleManager).startCreated(eq("container-123"), any());
|
||||
doThrow(new IllegalStateException("removal failed"))
|
||||
.when(lifecycleManager).stopAndRemoveStrict("container-123", null);
|
||||
|
||||
assertThrows(RuntimeException.class, () -> launcher.launch(fn));
|
||||
|
||||
verify(ec2Service, never()).releaseVpcPrivateIp(any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void vpcFunctionReturnsTheAddressAtOnceWhenItCannotJoinTheNetwork() throws Exception {
|
||||
LambdaFunction fn = vpcFunction("vpc-attach-failure-fn");
|
||||
when(ec2Service.allocateVpcPrivateIp("us-east-1", "subnet-a")).thenReturn(Optional.of("172.31.0.22"));
|
||||
when(ec2Service.attachContainerToVpc("us-east-1", "vpc-1", "subnet-a", "container-123", "172.31.0.22"))
|
||||
.thenReturn(Optional.empty());
|
||||
|
||||
ContainerHandle handle = launcher.launch(fn);
|
||||
launcher.stop(handle);
|
||||
|
||||
InOrder order = inOrder(ec2Service, lifecycleManager);
|
||||
order.verify(ec2Service).releaseVpcPrivateIp("us-east-1", "subnet-a", "172.31.0.22");
|
||||
order.verify(lifecycleManager).startCreated(eq("container-123"), any());
|
||||
verify(ec2Service, times(1)).releaseVpcPrivateIp(any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void vpcFunctionLeasesItsAddressInTheFunctionsAccountOutsideARequest() throws Exception {
|
||||
// A provisioned or cross-account launch has no caller scope of the function's owner, and
|
||||
// the allocator reads the owner's endpoint interfaces from the ambient account.
|
||||
LambdaFunction fn = vpcFunction("vpc-account-fn");
|
||||
fn.setFunctionArn("arn:aws:lambda:eu-west-1:222233334444:function:vpc-account-fn");
|
||||
AtomicBoolean inOwnerScope = new AtomicBoolean();
|
||||
when(ec2Service.allocateVpcPrivateIp("eu-west-1", "subnet-a"))
|
||||
.thenAnswer(invocation -> inOwnerScope.get() ? Optional.of("172.31.0.25") : Optional.empty());
|
||||
when(ec2Service.attachContainerToVpc("eu-west-1", "vpc-1", "subnet-a", "container-123", "172.31.0.25"))
|
||||
.thenReturn(Optional.of("floci-vpc-1"));
|
||||
try (MockedStatic<RequestScopes> scopes =
|
||||
mockStatic(RequestScopes.class, withSettings().mockMaker(MockMakers.INLINE))) {
|
||||
scopes.when(() -> RequestScopes.callAs(eq("222233334444"), eq("eu-west-1"), any(Supplier.class)))
|
||||
.thenAnswer(invocation -> {
|
||||
inOwnerScope.set(true);
|
||||
try {
|
||||
return invocation.<Supplier<?>>getArgument(2).get();
|
||||
} finally {
|
||||
inOwnerScope.set(false);
|
||||
}
|
||||
});
|
||||
|
||||
launcher.launch(fn);
|
||||
}
|
||||
|
||||
verify(ec2Service).attachContainerToVpc("eu-west-1", "vpc-1", "subnet-a", "container-123", "172.31.0.25");
|
||||
}
|
||||
|
||||
@Test
|
||||
void functionWithoutVpcConfigNeverCallsEc2() throws Exception {
|
||||
LambdaFunction fn = vpcFunction("no-vpc-fn");
|
||||
fn.setVpcId(null);
|
||||
fn.setVpcConfig(null);
|
||||
|
||||
launcher.stop(launcher.launch(fn));
|
||||
|
||||
verifyNoInteractions(ec2Service);
|
||||
}
|
||||
|
||||
private LambdaFunction vpcFunction(String name) throws IOException {
|
||||
LambdaFunction fn = new LambdaFunction();
|
||||
fn.setFunctionName(name);
|
||||
fn.setRuntime("nodejs20.x");
|
||||
fn.setHandler("index.handler");
|
||||
fn.setCodeLocalPath(Files.createDirectory(tempDir.resolve(name)).toString());
|
||||
fn.setVpcId("vpc-1");
|
||||
fn.setVpcConfig(Map.of("SubnetIds", List.of("subnet-a", "subnet-b"), "SecurityGroupIds", List.of("sg-1")));
|
||||
return fn;
|
||||
}
|
||||
|
||||
@Test
|
||||
void publishedVersionUnregistersUnderTheAccountItRegisteredWith() throws Exception {
|
||||
// A published version has no accountId, so both the handle stamp and the revoke must take
|
||||
@@ -1552,7 +1692,7 @@ class ContainerLauncherTest {
|
||||
verify(lifecycleManager, times(2)).create(any());
|
||||
verify(lifecycleManager, atLeastOnce()).ensureVolume(any());
|
||||
verify(lifecycleManager).stopAndRemove("helper-123", null, 0);
|
||||
verify(lifecycleManager, never()).stopAndRemove(any(), any());
|
||||
verify(lifecycleManager, never()).stopAndRemoveStrict(any(), any());
|
||||
InOrder order = inOrder(lifecycleManager);
|
||||
order.verify(lifecycleManager).stopAndRemove("helper-123", null, 0);
|
||||
order.verify(lifecycleManager).create(any());
|
||||
@@ -1587,7 +1727,7 @@ class ContainerLauncherTest {
|
||||
order.verify(dockerClient).copyArchiveToContainerCmd("helper-123");
|
||||
order.verify(lifecycleManager).stopAndRemove("helper-123", null, 0);
|
||||
verify(lifecycleManager, times(1)).create(any());
|
||||
verify(lifecycleManager, never()).stopAndRemove(any(), any());
|
||||
verify(lifecycleManager, never()).stopAndRemoveStrict(any(), any());
|
||||
verify(lifecycleManager, never()).removeVolume(any());
|
||||
verify(runtimeApiServerFactory).release(runtimeApiServer);
|
||||
assertFalse(Files.exists(tempDir.resolve("lambda-codevol-markers")
|
||||
@@ -2259,7 +2399,7 @@ class ContainerLauncherTest {
|
||||
ecrRegistryManager,
|
||||
mock(LambdaLayerService.class),
|
||||
new LaunchedContainerAwsEnv(reachableEndpoint),
|
||||
executionRoleCredentials);
|
||||
executionRoleCredentials, ec2Service);
|
||||
|
||||
stubExtensionDiscovery("otel-collector");
|
||||
// Feed a real stdout frame through whatever callback the launcher hands to execStartCmd.
|
||||
|
||||
Reference in new issue
Block a user