mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(ec2): give RunInstances the private address it asks for (#6099)
RunInstances ignored the private address it was given, so every instance got the subnet's next free address. It now reads PrivateIpAddress, NetworkInterface.1.PrivateIpAddress (Terraform), the primary NetworkInterface.1.PrivateIpAddresses entry (AWS CLI) and a launch template's primary interface address. The address is validated (inside the subnet, not reserved, not in use, including by another account's instance, interface or NAT gateway on a shared default VPC network, single instance with its own interface, no instance-level address with network interfaces), leased on the VPC's Docker network, and assigned to the instance and its primary interface. A CloudFormation AWS::EC2::Instance now launches at its declared PrivateIpAddress too. Closes #5830
This commit is contained in:
1 parent
61a42591a9
commit
50e515f17a
13 files changed
+1381
-86
No files matched your search
+99
-7
@@ -6,6 +6,7 @@ import io.quarkus.test.junit.QuarkusTest;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
@@ -15,6 +16,7 @@ import java.util.regex.Pattern;
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
@@ -317,6 +319,32 @@ class CloudFormationEc2InstanceIntegrationTest {
|
||||
.when().post("/").then().statusCode(200);
|
||||
}
|
||||
|
||||
@Test
|
||||
void createStackLaunchesTheInstanceAtItsDeclaredPrivateIpAddress() {
|
||||
String stackName = "cfn-ec2-private-ip-" + Long.toString(System.nanoTime(), 36);
|
||||
String template = """
|
||||
{"Resources": {
|
||||
"Vpc": {"Type": "AWS::EC2::VPC", "Properties": {"CidrBlock": "10.194.0.0/16"}},
|
||||
"Subnet": {"Type": "AWS::EC2::Subnet", "Properties": {
|
||||
"VpcId": {"Ref": "Vpc"}, "CidrBlock": "10.194.1.0/24"}},
|
||||
"Server": {"Type": "AWS::EC2::Instance", "Properties": {
|
||||
"ImageId": "ami-12345678", "InstanceType": "t3.micro",
|
||||
"SubnetId": {"Ref": "Subnet"}, "PrivateIpAddress": "10.194.1.50"}}
|
||||
}, "Outputs": {
|
||||
"InstanceId": {"Value": {"Ref": "Server"}},
|
||||
"PrivateIp": {"Value": {"Fn::GetAtt": ["Server", "PrivateIp"]}}
|
||||
}}
|
||||
""";
|
||||
cfn("CreateStack", stackName, template);
|
||||
try {
|
||||
String stack = describeStacks(stackName, "CREATE_COMPLETE");
|
||||
assertEquals("10.194.1.50", output(stack, "PrivateIp"));
|
||||
assertPrivateIpAddress(output(stack, "InstanceId"), "10.194.1.50");
|
||||
} finally {
|
||||
deleteStack(stackName);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void changingPrivateIpAddressReplacesTheInstance() {
|
||||
String suffix = Long.toString(System.nanoTime(), 36);
|
||||
@@ -324,10 +352,13 @@ class CloudFormationEc2InstanceIntegrationTest {
|
||||
String template = """
|
||||
{
|
||||
"Resources": {
|
||||
"Vpc": {"Type": "AWS::EC2::VPC", "Properties": {"CidrBlock": "10.195.0.0/16"}},
|
||||
"Subnet": {"Type": "AWS::EC2::Subnet", "Properties": {
|
||||
"VpcId": {"Ref": "Vpc"}, "CidrBlock": "10.195.1.0/24"}},
|
||||
"Server": {
|
||||
"Type": "AWS::EC2::Instance",
|
||||
"Properties": {"ImageId": "ami-12345678", "InstanceType": "t3.micro",
|
||||
"PrivateIpAddress": "%s"}
|
||||
"SubnetId": {"Ref": "Subnet"}, "PrivateIpAddress": "%s"}
|
||||
}
|
||||
},
|
||||
"Outputs": {
|
||||
@@ -336,23 +367,75 @@ class CloudFormationEc2InstanceIntegrationTest {
|
||||
}
|
||||
""";
|
||||
|
||||
cfn("CreateStack", stackName, template.formatted("10.0.0.5"));
|
||||
cfn("CreateStack", stackName, template.formatted("10.195.1.50"));
|
||||
String firstId = instanceIdFrom(describeStacks(stackName, "CREATE_COMPLETE"));
|
||||
|
||||
// PrivateIpAddress is createOnly, so changing it replaces the instance rather than reusing it.
|
||||
cfn("UpdateStack", stackName, template.formatted("10.0.0.6"));
|
||||
cfn("UpdateStack", stackName, template.formatted("10.195.1.60"));
|
||||
String secondId = instanceIdFrom(describeStacks(stackName, "UPDATE_COMPLETE"));
|
||||
|
||||
assertNotEquals(firstId, secondId, "PrivateIpAddress changed, so the instance must be replaced");
|
||||
|
||||
// The replacement instance really exists in EC2.
|
||||
given()
|
||||
// The replacement instance really exists in EC2, at the new address.
|
||||
assertPrivateIpAddress(secondId, "10.195.1.60");
|
||||
}
|
||||
|
||||
@Test
|
||||
void replacingAnInstanceThatKeepsItsPrivateIpAddressRollsTheUpdateBack() {
|
||||
String stackName = "cfn-ec2-keep-ip-" + Long.toString(System.nanoTime(), 36);
|
||||
String template = """
|
||||
{"Resources": {
|
||||
"Vpc": {"Type": "AWS::EC2::VPC", "Properties": {"CidrBlock": "10.196.0.0/16"}},
|
||||
"Subnet": {"Type": "AWS::EC2::Subnet", "Properties": {
|
||||
"VpcId": {"Ref": "Vpc"}, "CidrBlock": "10.196.1.0/24"}},
|
||||
"Server": {"Type": "AWS::EC2::Instance", "Properties": {
|
||||
"ImageId": "%s", "InstanceType": "t3.micro",
|
||||
"SubnetId": {"Ref": "Subnet"}, "PrivateIpAddress": "10.196.1.50"}}
|
||||
}, "Outputs": {
|
||||
"InstanceId": {"Value": {"Ref": "Server"}}
|
||||
}}
|
||||
""";
|
||||
cfn("CreateStack", stackName, template.formatted("ami-12345678"));
|
||||
try {
|
||||
String firstId = instanceIdFrom(describeStacks(stackName, "CREATE_COMPLETE"));
|
||||
|
||||
// A changed ImageId replaces the instance, and CloudFormation creates the replacement
|
||||
// before it deletes the original, so the address is still in use, as on AWS.
|
||||
cfn("UpdateStack", stackName, template.formatted("ami-87654321"));
|
||||
String rolledBack = describeStacks(stackName, "UPDATE_ROLLBACK_COMPLETE");
|
||||
|
||||
assertEquals(firstId, instanceIdFrom(rolledBack));
|
||||
assertPrivateIpAddress(firstId, "10.196.1.50");
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", CFN_AUTH)
|
||||
.formParam("Action", "DescribeStackEvents")
|
||||
.formParam("StackName", stackName)
|
||||
.when().post("/").then().statusCode(200)
|
||||
.body(containsString("Address 10.196.1.50 is in use."));
|
||||
} finally {
|
||||
deleteStack(stackName);
|
||||
}
|
||||
}
|
||||
|
||||
/** Every address DescribeInstances reports for the instance and its interface is {@code expected}. */
|
||||
private static void assertPrivateIpAddress(String instanceId, String expected) {
|
||||
String describeInstances = given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", EC2_AUTH)
|
||||
.formParam("Action", "DescribeInstances")
|
||||
.formParam("InstanceId.1", secondId)
|
||||
.formParam("InstanceId.1", instanceId)
|
||||
.when().post("/").then().statusCode(200)
|
||||
.body(containsString(secondId));
|
||||
.body(containsString(instanceId))
|
||||
.extract().asString();
|
||||
Matcher m = Pattern.compile("<privateIpAddress>([^<]*)</privateIpAddress>").matcher(describeInstances);
|
||||
List<String> reported = new ArrayList<>();
|
||||
while (m.find()) {
|
||||
reported.add(m.group(1));
|
||||
}
|
||||
assertFalse(reported.isEmpty(), "expected a private address in " + describeInstances);
|
||||
assertTrue(reported.stream().allMatch(expected::equals),
|
||||
"expected every reported private address to be " + expected + ", got " + reported);
|
||||
}
|
||||
|
||||
private static void cfn(String action, String stackName, String template) {
|
||||
@@ -365,6 +448,15 @@ class CloudFormationEc2InstanceIntegrationTest {
|
||||
.when().post("/").then().statusCode(200);
|
||||
}
|
||||
|
||||
private static void deleteStack(String stackName) {
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", CFN_AUTH)
|
||||
.formParam("Action", "DeleteStack")
|
||||
.formParam("StackName", stackName)
|
||||
.when().post("/").then().statusCode(200);
|
||||
}
|
||||
|
||||
private static String describeStacks(String stackName, String expectedStatus) {
|
||||
return given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
|
||||
+10
-3
@@ -20,6 +20,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
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.anyList;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
@@ -51,7 +52,9 @@ class CloudFormationEc2ProvisionerTest {
|
||||
Reservation reservation = new Reservation();
|
||||
reservation.getInstances().add(instance);
|
||||
when(ec2Service.runInstances(anyString(), anyString(), anyString(), anyInt(), anyInt(), any(), anyList(),
|
||||
any(), any(), anyList(), any(), any(), any(), any(), anyInt(), any(), any())).thenReturn(reservation);
|
||||
any(), any(), anyList(), any(), any(), any(),
|
||||
any(), anyInt(), any(), any(), any(), any(), anyBoolean(), any(), any(), any(), anyBoolean(), any()))
|
||||
.thenReturn(reservation);
|
||||
doThrow(new AwsException("InternalError", "EC2 instance i-launch-failed failed to launch because its container terminated during launch", 500))
|
||||
.when(ec2Service).awaitContainerLaunch(instance);
|
||||
|
||||
@@ -73,7 +76,9 @@ class CloudFormationEc2ProvisionerTest {
|
||||
Reservation reservation = new Reservation();
|
||||
reservation.getInstances().add(instance);
|
||||
when(ec2Service.runInstances(anyString(), anyString(), anyString(), anyInt(), anyInt(), any(), anyList(),
|
||||
any(), any(), anyList(), any(), any(), any(), any(), anyInt(), any(), any())).thenReturn(reservation);
|
||||
any(), any(), anyList(), any(), any(), any(),
|
||||
any(), anyInt(), any(), any(), any(), any(), anyBoolean(), any(), any(), any(), anyBoolean(), any()))
|
||||
.thenReturn(reservation);
|
||||
doThrow(new AwsException("InternalError",
|
||||
"EC2 instance i-launch-timed-out failed to launch because it did not reach running state before the launch timeout",
|
||||
500)).when(ec2Service).awaitContainerLaunch(instance);
|
||||
@@ -96,7 +101,9 @@ class CloudFormationEc2ProvisionerTest {
|
||||
Reservation reservation = new Reservation();
|
||||
reservation.getInstances().add(instance);
|
||||
when(ec2Service.runInstances(anyString(), anyString(), anyString(), anyInt(), anyInt(), any(), anyList(),
|
||||
any(), any(), anyList(), any(), any(), any(), any(), anyInt(), any(), any())).thenReturn(reservation);
|
||||
any(), any(), anyList(), any(), any(), any(),
|
||||
any(), anyInt(), any(), any(), any(), any(), anyBoolean(), any(), any(), any(), anyBoolean(), any()))
|
||||
.thenReturn(reservation);
|
||||
|
||||
StackResource resource = provisioner.provision("Server", "AWS::EC2::Instance", properties(), engine(),
|
||||
"us-east-1", "000000000000", "test-stack");
|
||||
|
||||
+72
-18
@@ -31,10 +31,12 @@ import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
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.anyList;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.ArgumentMatchers.isNull;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.inOrder;
|
||||
import static org.mockito.Mockito.mock;
|
||||
@@ -120,6 +122,39 @@ class Ec2InstanceCfnProvisionerTest {
|
||||
assertEquals(Set.of("InstanceId"), r.getAttributes().keySet());
|
||||
}
|
||||
|
||||
@Test
|
||||
void launchAppliesTheDeclaredPrivateIpAddress() throws Exception {
|
||||
Instance instance = new Instance();
|
||||
instance.setInstanceId("i-1");
|
||||
stubLaunch(instance);
|
||||
|
||||
provisioner.provision(resource("Server"), props("""
|
||||
{"ImageId": "ami-1", "SubnetId": "subnet-1", "UserData": "boot",
|
||||
"PrivateIpAddress": "10.0.1.50"}
|
||||
"""), ctx());
|
||||
|
||||
// Every other launch option keeps the value the shorter overloads default it to.
|
||||
ArgumentCaptor<String> privateIp = ArgumentCaptor.forClass(String.class);
|
||||
verify(ec2).runInstances(eq("us-east-1"), eq("ami-1"), eq("t3.micro"), eq(1), eq(1), isNull(),
|
||||
anyList(), eq("subnet-1"), isNull(), anyList(), eq("boot"), isNull(), isNull(), isNull(),
|
||||
eq(0), isNull(), isNull(), isNull(), eq("Ym9vdA=="), eq(false), isNull(), isNull(), isNull(),
|
||||
eq(false), privateIp.capture());
|
||||
assertEquals("10.0.1.50", privateIp.getValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
void launchWithoutAPrivateIpAddressLeavesItToTheSubnet() throws Exception {
|
||||
Instance instance = new Instance();
|
||||
instance.setInstanceId("i-1");
|
||||
stubLaunch(instance);
|
||||
|
||||
provisioner.provision(resource("Server"), props("{\"ImageId\": \"ami-1\"}"), ctx());
|
||||
|
||||
verify(ec2).runInstances(anyString(), any(), anyString(), anyInt(), anyInt(), any(), anyList(),
|
||||
any(), any(), anyList(), any(), any(), any(), any(), anyInt(), any(), any(), any(), any(),
|
||||
anyBoolean(), any(), any(), any(), anyBoolean(), isNull());
|
||||
}
|
||||
|
||||
@Test
|
||||
void launchTemplateFillsWhatThePropertiesLeaveUnset() throws Exception {
|
||||
LaunchTemplateData data = new LaunchTemplateData();
|
||||
@@ -136,7 +171,8 @@ class Ec2InstanceCfnProvisionerTest {
|
||||
"""), ctx());
|
||||
|
||||
verify(ec2).runInstances(eq("us-east-1"), eq("ami-from-template"), eq("m5.large"), eq(1), eq(1),
|
||||
eq("template-key"), anyList(), any(), any(), anyList(), any(), any(), any(), any(), anyInt(), any(), any());
|
||||
eq("template-key"), anyList(), any(), any(), anyList(), any(), any(), any(),
|
||||
any(), anyInt(), any(), any(), any(), any(), anyBoolean(), any(), any(), any(), anyBoolean(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -167,7 +203,8 @@ class Ec2InstanceCfnProvisionerTest {
|
||||
|
||||
assertEquals("i-nolt", r.getPhysicalId());
|
||||
verify(ec2).runInstances(eq("us-east-1"), any(), eq("t3.micro"), eq(1), eq(1), any(),
|
||||
anyList(), any(), any(), anyList(), any(), any(), any(), any(), anyInt(), any(), any());
|
||||
anyList(), any(), any(), anyList(), any(), any(), any(),
|
||||
any(), anyInt(), any(), any(), any(), any(), anyBoolean(), any(), any(), any(), anyBoolean(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -271,7 +308,8 @@ class Ec2InstanceCfnProvisionerTest {
|
||||
|
||||
assertEquals("i-1", r.getPhysicalId());
|
||||
verify(ec2, times(1)).runInstances(anyString(), any(), anyString(), anyInt(), anyInt(), any(),
|
||||
anyList(), any(), any(), anyList(), any(), any(), any(), any(), anyInt(), any(), any());
|
||||
anyList(), any(), any(), anyList(), any(), any(), any(),
|
||||
any(), anyInt(), any(), any(), any(), any(), anyBoolean(), any(), any(), any(), anyBoolean(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -380,7 +418,8 @@ class Ec2InstanceCfnProvisionerTest {
|
||||
|
||||
ArgumentCaptor<String> profile = ArgumentCaptor.forClass(String.class);
|
||||
verify(ec2).runInstances(anyString(), any(), anyString(), anyInt(), anyInt(), any(), anyList(),
|
||||
any(), any(), anyList(), any(), profile.capture(), any(), any(), anyInt(), any(), any());
|
||||
any(), any(), anyList(), any(), profile.capture(), any(),
|
||||
any(), anyInt(), any(), any(), any(), any(), anyBoolean(), any(), any(), any(), anyBoolean(), any());
|
||||
assertEquals(PROFILE_A, profile.getValue());
|
||||
assertEquals(PROFILE_A, r.getAttributes().get("__FlociDeclaredIamInstanceProfile"));
|
||||
}
|
||||
@@ -404,7 +443,8 @@ class Ec2InstanceCfnProvisionerTest {
|
||||
i2.setInstanceId("i-2");
|
||||
i2.setImageId("ami-2");
|
||||
when(ec2.runInstances(anyString(), any(), anyString(), anyInt(), anyInt(), any(), anyList(),
|
||||
any(), any(), anyList(), any(), any(), any(), any(), anyInt(), any(), any()))
|
||||
any(), any(), anyList(), any(), any(), any(),
|
||||
any(), anyInt(), any(), any(), any(), any(), anyBoolean(), any(), any(), any(), anyBoolean(), any()))
|
||||
.thenReturn(reservationOf(i1), reservationOf(i2));
|
||||
StackResource r = resource("Server");
|
||||
provisioner.provision(r, props("{\"ImageId\": \"ami-1\"}"), ctx(null));
|
||||
@@ -428,7 +468,8 @@ class Ec2InstanceCfnProvisionerTest {
|
||||
i2.setInstanceId("i-2");
|
||||
i2.setImageId("ami-1");
|
||||
when(ec2.runInstances(anyString(), any(), anyString(), anyInt(), anyInt(), any(), anyList(),
|
||||
any(), any(), anyList(), any(), any(), any(), any(), anyInt(), any(), any()))
|
||||
any(), any(), anyList(), any(), any(), any(),
|
||||
any(), anyInt(), any(), any(), any(), any(), anyBoolean(), any(), any(), any(), anyBoolean(), any()))
|
||||
.thenReturn(reservationOf(i1), reservationOf(i2));
|
||||
StackResource r = resource("Server");
|
||||
provisioner.provision(r, props("{\"ImageId\": \"ami-1\", \"PrivateIpAddress\": \"10.0.0.5\"}"), ctx(null));
|
||||
@@ -452,7 +493,8 @@ class Ec2InstanceCfnProvisionerTest {
|
||||
i2.setInstanceId("i-2");
|
||||
i2.setImageId("ami-1");
|
||||
when(ec2.runInstances(anyString(), any(), anyString(), anyInt(), anyInt(), any(), anyList(),
|
||||
any(), any(), anyList(), any(), any(), any(), any(), anyInt(), any(), any()))
|
||||
any(), any(), anyList(), any(), any(), any(),
|
||||
any(), anyInt(), any(), any(), any(), any(), anyBoolean(), any(), any(), any(), anyBoolean(), any()))
|
||||
.thenReturn(reservationOf(i1), reservationOf(i2));
|
||||
StackResource r = resource("Server");
|
||||
provisioner.provision(r, props("{\"ImageId\": \"ami-1\", \"AvailabilityZone\": \"us-east-1a\"}"), ctx(null));
|
||||
@@ -482,7 +524,8 @@ class Ec2InstanceCfnProvisionerTest {
|
||||
|
||||
assertEquals("i-1", r.getPhysicalId());
|
||||
verify(ec2, times(1)).runInstances(anyString(), any(), anyString(), anyInt(), anyInt(), any(),
|
||||
anyList(), any(), any(), anyList(), any(), any(), any(), any(), anyInt(), any(), any());
|
||||
anyList(), any(), any(), anyList(), any(), any(), any(),
|
||||
any(), anyInt(), any(), any(), any(), any(), anyBoolean(), any(), any(), any(), anyBoolean(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -502,7 +545,8 @@ class Ec2InstanceCfnProvisionerTest {
|
||||
|
||||
assertEquals("i-1", r.getPhysicalId());
|
||||
verify(ec2, times(1)).runInstances(anyString(), any(), anyString(), anyInt(), anyInt(), any(),
|
||||
anyList(), any(), any(), anyList(), any(), any(), any(), any(), anyInt(), any(), any());
|
||||
anyList(), any(), any(), anyList(), any(), any(), any(),
|
||||
any(), anyInt(), any(), any(), any(), any(), anyBoolean(), any(), any(), any(), anyBoolean(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -546,7 +590,8 @@ class Ec2InstanceCfnProvisionerTest {
|
||||
ArgumentCaptor<LaunchTemplateData.MetadataOptions> launched =
|
||||
ArgumentCaptor.forClass(LaunchTemplateData.MetadataOptions.class);
|
||||
verify(ec2).runInstances(anyString(), any(), anyString(), anyInt(), anyInt(), any(), anyList(),
|
||||
any(), any(), anyList(), any(), any(), any(), any(), anyInt(), any(), launched.capture());
|
||||
any(), any(), anyList(), any(), any(), any(), any(), anyInt(), any(), launched.capture(),
|
||||
any(), any(), anyBoolean(), any(), any(), any(), anyBoolean(), any());
|
||||
assertEquals("required", launched.getValue().getHttpTokens());
|
||||
|
||||
LaunchTemplateData.MetadataOptions applied = LaunchTemplateData.MetadataOptions.launchDefaults();
|
||||
@@ -567,7 +612,8 @@ class Ec2InstanceCfnProvisionerTest {
|
||||
verify(ec2).modifyInstanceMetadataOptions(eq("us-east-1"), eq("i-1"), modified.capture());
|
||||
assertEquals("optional", modified.getValue().getHttpTokens());
|
||||
verify(ec2, times(1)).runInstances(anyString(), any(), anyString(), anyInt(), anyInt(), any(), anyList(),
|
||||
any(), any(), anyList(), any(), any(), any(), any(), anyInt(), any(), any());
|
||||
any(), any(), anyList(), any(), any(), any(),
|
||||
any(), anyInt(), any(), any(), any(), any(), anyBoolean(), any(), any(), any(), anyBoolean(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -634,7 +680,8 @@ class Ec2InstanceCfnProvisionerTest {
|
||||
verify(ec2).modifyInstanceMetadataOptions(eq("us-east-1"), eq("i-1"), reset.capture());
|
||||
assertEquals("optional", reset.getValue().getHttpTokens());
|
||||
verify(ec2, times(1)).runInstances(anyString(), any(), anyString(), anyInt(), anyInt(), any(), anyList(),
|
||||
any(), any(), anyList(), any(), any(), any(), any(), anyInt(), any(), any());
|
||||
any(), any(), anyList(), any(), any(), any(),
|
||||
any(), anyInt(), any(), any(), any(), any(), anyBoolean(), any(), any(), any(), anyBoolean(), any());
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -912,7 +959,8 @@ class Ec2InstanceCfnProvisionerTest {
|
||||
|
||||
assertEquals("InvalidParameterValue", failure.getErrorCode());
|
||||
verify(ec2, never()).runInstances(anyString(), any(), anyString(), anyInt(), anyInt(), any(), anyList(),
|
||||
any(), any(), anyList(), any(), any(), any(), any(), anyInt(), any(), any());
|
||||
any(), any(), anyList(), any(), any(), any(),
|
||||
any(), anyInt(), any(), any(), any(), any(), anyBoolean(), any(), any(), any(), anyBoolean(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -1145,7 +1193,8 @@ class Ec2InstanceCfnProvisionerTest {
|
||||
|
||||
assertEquals("i-9", r.getPhysicalId());
|
||||
verify(ec2).runInstances(anyString(), any(), anyString(), anyInt(), anyInt(), any(),
|
||||
anyList(), any(), any(), anyList(), any(), any(), any(), any(), anyInt(), any(), any());
|
||||
anyList(), any(), any(), anyList(), any(), any(), any(),
|
||||
any(), anyInt(), any(), any(), any(), any(), anyBoolean(), any(), any(), any(), anyBoolean(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -1166,7 +1215,8 @@ class Ec2InstanceCfnProvisionerTest {
|
||||
|
||||
assertEquals("i-9", r.getPhysicalId());
|
||||
verify(ec2).runInstances(anyString(), any(), anyString(), anyInt(), anyInt(), any(),
|
||||
anyList(), any(), any(), anyList(), any(), any(), any(), any(), anyInt(), any(), any());
|
||||
anyList(), any(), any(), anyList(), any(), any(), any(),
|
||||
any(), anyInt(), any(), any(), any(), any(), anyBoolean(), any(), any(), any(), anyBoolean(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -1179,7 +1229,8 @@ class Ec2InstanceCfnProvisionerTest {
|
||||
withoutPublicIp.setInstanceId("i-2");
|
||||
withoutPublicIp.setImageId("ami-2");
|
||||
when(ec2.runInstances(anyString(), any(), anyString(), anyInt(), anyInt(), any(), anyList(),
|
||||
any(), any(), anyList(), any(), any(), any(), any(), anyInt(), any(), any()))
|
||||
any(), any(), anyList(), any(), any(), any(),
|
||||
any(), anyInt(), any(), any(), any(), any(), anyBoolean(), any(), any(), any(), anyBoolean(), any()))
|
||||
.thenReturn(reservationOf(withPublicIp), reservationOf(withoutPublicIp));
|
||||
StackResource r = resource("Server");
|
||||
provisioner.provision(r, props("{\"ImageId\": \"ami-1\"}"), ctx(null));
|
||||
@@ -1219,7 +1270,8 @@ class Ec2InstanceCfnProvisionerTest {
|
||||
.thenReturn(List.of(reservationOf(instance)));
|
||||
}
|
||||
when(ec2.runInstances(anyString(), any(), anyString(), anyInt(), anyInt(), any(), anyList(),
|
||||
any(), any(), anyList(), any(), any(), any(), any(), anyInt(), any(), any()))
|
||||
any(), any(), anyList(), any(), any(), any(),
|
||||
any(), anyInt(), any(), any(), any(), any(), anyBoolean(), any(), any(), any(), anyBoolean(), any()))
|
||||
.thenReturn(reservations.get(0), reservations.subList(1, reservations.size()).toArray(Reservation[]::new));
|
||||
return instances;
|
||||
}
|
||||
@@ -1236,7 +1288,9 @@ class Ec2InstanceCfnProvisionerTest {
|
||||
Reservation reservation = new Reservation();
|
||||
reservation.getInstances().add(instance);
|
||||
when(ec2.runInstances(anyString(), any(), anyString(), anyInt(), anyInt(), any(), anyList(),
|
||||
any(), any(), anyList(), any(), any(), any(), any(), anyInt(), any(), any())).thenReturn(reservation);
|
||||
any(), any(), anyList(), any(), any(), any(),
|
||||
any(), anyInt(), any(), any(), any(), any(), anyBoolean(), any(), any(), any(), anyBoolean(), any()))
|
||||
.thenReturn(reservation);
|
||||
}
|
||||
|
||||
private ProvisionContext ctx() {
|
||||
|
||||
+254
@@ -0,0 +1,254 @@
|
||||
package io.github.hectorvent.floci.services.ec2;
|
||||
|
||||
import io.github.hectorvent.floci.testing.EnforcementFixtures;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.specification.RequestSpecification;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
|
||||
@QuarkusTest
|
||||
class Ec2RunInstancesPrivateIpIntegrationTest {
|
||||
// A fresh account per test, so what one test launches never holds an address another asks for.
|
||||
private static final AtomicLong ACCOUNTS = new AtomicLong(725000000000L);
|
||||
private static final String INSTANCE = "DescribeInstancesResponse.reservationSet.item.instancesSet.item.";
|
||||
|
||||
@Test
|
||||
void topLevelPrivateIpAddressIsTheAddressTheInstanceGets() {
|
||||
String owner = Long.toString(ACCOUNTS.incrementAndGet());
|
||||
Network network = createSubnet(owner, "10.51.0.0/16", "10.51.1.0/24");
|
||||
|
||||
String id = runInstance(owner)
|
||||
.formParam("SubnetId", network.subnetId())
|
||||
.formParam("PrivateIpAddress", "10.51.1.50")
|
||||
.post("/").then().statusCode(200)
|
||||
.body("RunInstancesResponse.instancesSet.item.privateIpAddress", equalTo("10.51.1.50"))
|
||||
.extract().path("RunInstancesResponse.instancesSet.item.instanceId");
|
||||
|
||||
assertDescribedAddress(owner, id, "10.51.1.50");
|
||||
terminate(owner, id);
|
||||
delete(owner, network);
|
||||
}
|
||||
|
||||
@Test
|
||||
void networkInterfacePrivateIpAddressIsTheAddressTheInstanceGets() {
|
||||
// The shape Terraform's aws_instance sends for private_ip together with subnet_id.
|
||||
String owner = Long.toString(ACCOUNTS.incrementAndGet());
|
||||
Network network = createSubnet(owner, "10.52.0.0/16", "10.52.1.0/24");
|
||||
|
||||
String id = runInstance(owner)
|
||||
.formParam("NetworkInterface.1.DeviceIndex", "0")
|
||||
.formParam("NetworkInterface.1.SubnetId", network.subnetId())
|
||||
.formParam("NetworkInterface.1.PrivateIpAddress", "10.52.1.60")
|
||||
.post("/").then().statusCode(200)
|
||||
.body("RunInstancesResponse.instancesSet.item.privateIpAddress", equalTo("10.52.1.60"))
|
||||
.extract().path("RunInstancesResponse.instancesSet.item.instanceId");
|
||||
|
||||
assertDescribedAddress(owner, id, "10.52.1.60");
|
||||
terminate(owner, id);
|
||||
delete(owner, network);
|
||||
}
|
||||
|
||||
@Test
|
||||
void primaryPrivateIpAddressesEntryIsTheAddressTheInstanceGets() {
|
||||
// The shape AWS CLI v2 sends for --private-ip-address with --associate-public-ip-address.
|
||||
String owner = Long.toString(ACCOUNTS.incrementAndGet());
|
||||
Network network = createSubnet(owner, "10.56.0.0/16", "10.56.1.0/24");
|
||||
|
||||
String id = runInstance(owner)
|
||||
.formParam("NetworkInterface.1.DeviceIndex", "0")
|
||||
.formParam("NetworkInterface.1.SubnetId", network.subnetId())
|
||||
.formParam("NetworkInterface.1.AssociatePublicIpAddress", "true")
|
||||
.formParam("NetworkInterface.1.PrivateIpAddresses.1.PrivateIpAddress", "10.56.1.60")
|
||||
.formParam("NetworkInterface.1.PrivateIpAddresses.1.Primary", "true")
|
||||
.post("/").then().statusCode(200)
|
||||
.body("RunInstancesResponse.instancesSet.item.privateIpAddress", equalTo("10.56.1.60"))
|
||||
.extract().path("RunInstancesResponse.instancesSet.item.instanceId");
|
||||
|
||||
assertDescribedAddress(owner, id, "10.56.1.60");
|
||||
terminate(owner, id);
|
||||
delete(owner, network);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSecondaryPrivateIpAddressesEntryDoesNotPlaceTheInstance() {
|
||||
String owner = Long.toString(ACCOUNTS.incrementAndGet());
|
||||
Network network = createSubnet(owner, "10.57.0.0/16", "10.57.1.0/24");
|
||||
|
||||
String id = runInstance(owner)
|
||||
.formParam("NetworkInterface.1.DeviceIndex", "0")
|
||||
.formParam("NetworkInterface.1.SubnetId", network.subnetId())
|
||||
.formParam("NetworkInterface.1.PrivateIpAddresses.1.PrivateIpAddress", "10.57.1.70")
|
||||
.formParam("NetworkInterface.1.PrivateIpAddresses.1.Primary", "false")
|
||||
.formParam("NetworkInterface.1.PrivateIpAddresses.2.PrivateIpAddress", "10.57.1.60")
|
||||
.formParam("NetworkInterface.1.PrivateIpAddresses.2.Primary", "true")
|
||||
.post("/").then().statusCode(200)
|
||||
.extract().path("RunInstancesResponse.instancesSet.item.instanceId");
|
||||
|
||||
assertDescribedAddress(owner, id, "10.57.1.60");
|
||||
terminate(owner, id);
|
||||
delete(owner, network);
|
||||
}
|
||||
|
||||
@Test
|
||||
void launchTemplatePrimaryInterfacePrivateIpAddressIsTheAddressTheInstanceGets() {
|
||||
String owner = Long.toString(ACCOUNTS.incrementAndGet());
|
||||
Network network = createSubnet(owner, "10.58.0.0/16", "10.58.1.0/24");
|
||||
String template = request("CreateLaunchTemplate", owner)
|
||||
.formParam("LaunchTemplateName", "fixed-private-address")
|
||||
.formParam("LaunchTemplateData.ImageId", "ami-0abcdef1234567890")
|
||||
.formParam("LaunchTemplateData.InstanceType", "t3.micro")
|
||||
.formParam("LaunchTemplateData.NetworkInterface.1.DeviceIndex", 0)
|
||||
.formParam("LaunchTemplateData.NetworkInterface.1.SubnetId", network.subnetId())
|
||||
.formParam("LaunchTemplateData.NetworkInterface.1.PrivateIpAddress", "10.58.1.80")
|
||||
.post("/").then().statusCode(200)
|
||||
.extract().path("CreateLaunchTemplateResponse.launchTemplate.launchTemplateId");
|
||||
|
||||
String id = request("RunInstances", owner).formParam("MinCount", 1).formParam("MaxCount", 1)
|
||||
.formParam("LaunchTemplate.LaunchTemplateId", template)
|
||||
.post("/").then().statusCode(200)
|
||||
.body("RunInstancesResponse.instancesSet.item.privateIpAddress", equalTo("10.58.1.80"))
|
||||
.extract().path("RunInstancesResponse.instancesSet.item.instanceId");
|
||||
|
||||
assertDescribedAddress(owner, id, "10.58.1.80");
|
||||
terminate(owner, id);
|
||||
request("DeleteLaunchTemplate", owner).formParam("LaunchTemplateId", template).post("/").then().statusCode(200);
|
||||
delete(owner, network);
|
||||
}
|
||||
|
||||
@Test
|
||||
void privateIpAddressOutsideTheSubnetIsRejected() {
|
||||
String owner = Long.toString(ACCOUNTS.incrementAndGet());
|
||||
Network network = createSubnet(owner, "10.53.0.0/16", "10.53.1.0/24");
|
||||
|
||||
runInstance(owner).formParam("SubnetId", network.subnetId()).formParam("PrivateIpAddress", "10.53.2.50")
|
||||
.post("/").then().statusCode(400)
|
||||
.body("Response.Errors.Error.Code", equalTo("InvalidParameterValue"));
|
||||
|
||||
assertInstancesIn(owner, network.subnetId(), 0);
|
||||
delete(owner, network);
|
||||
}
|
||||
|
||||
@Test
|
||||
void privateIpAddressAnotherInstanceHoldsIsRejected() {
|
||||
String owner = Long.toString(ACCOUNTS.incrementAndGet());
|
||||
Network network = createSubnet(owner, "10.54.0.0/16", "10.54.1.0/24");
|
||||
String holder = runInstance(owner).formParam("SubnetId", network.subnetId())
|
||||
.formParam("PrivateIpAddress", "10.54.1.50")
|
||||
.post("/").then().statusCode(200)
|
||||
.extract().path("RunInstancesResponse.instancesSet.item.instanceId");
|
||||
|
||||
runInstance(owner).formParam("SubnetId", network.subnetId()).formParam("PrivateIpAddress", "10.54.1.50")
|
||||
.post("/").then().statusCode(400)
|
||||
.body("Response.Errors.Error.Code", equalTo("InvalidIPAddress.InUse"))
|
||||
.body("Response.Errors.Error.Message", equalTo("Address 10.54.1.50 is in use."));
|
||||
|
||||
assertInstancesIn(owner, network.subnetId(), 1);
|
||||
terminate(owner, holder);
|
||||
delete(owner, network);
|
||||
}
|
||||
|
||||
@Test
|
||||
void privateIpAddressForMoreThanOneInstanceIsRejected() {
|
||||
String owner = Long.toString(ACCOUNTS.incrementAndGet());
|
||||
Network network = createSubnet(owner, "10.55.0.0/16", "10.55.1.0/24");
|
||||
|
||||
request("RunInstances", owner)
|
||||
.formParam("ImageId", "ami-0abcdef1234567890").formParam("InstanceType", "t3.micro")
|
||||
.formParam("MinCount", "2").formParam("MaxCount", "2")
|
||||
.formParam("SubnetId", network.subnetId()).formParam("PrivateIpAddress", "10.55.1.50")
|
||||
.post("/").then().statusCode(400)
|
||||
.body("Response.Errors.Error.Code", equalTo("InvalidParameterCombination"));
|
||||
|
||||
assertInstancesIn(owner, network.subnetId(), 0);
|
||||
delete(owner, network);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {true, false})
|
||||
void networkInterfacesRejectAnInstanceLevelPrivateIpAddress(boolean fromTemplate) {
|
||||
String owner = Long.toString(ACCOUNTS.incrementAndGet());
|
||||
Network network = createSubnet(owner, "10.59.0.0/16", "10.59.1.0/24");
|
||||
RequestSpecification launch = request("RunInstances", owner).formParam("MinCount", 1)
|
||||
.formParam("MaxCount", 1).formParam("PrivateIpAddress", "10.59.1.50");
|
||||
String template = null;
|
||||
if (fromTemplate) {
|
||||
template = request("CreateLaunchTemplate", owner)
|
||||
.formParam("LaunchTemplateName", "invalid-private-address-combination")
|
||||
.formParam("LaunchTemplateData.ImageId", "ami-0abcdef1234567890")
|
||||
.formParam("LaunchTemplateData.InstanceType", "t3.micro")
|
||||
.formParam("LaunchTemplateData.NetworkInterface.1.DeviceIndex", 0)
|
||||
.formParam("LaunchTemplateData.NetworkInterface.1.SubnetId", network.subnetId())
|
||||
.post("/").then().statusCode(200)
|
||||
.extract().path("CreateLaunchTemplateResponse.launchTemplate.launchTemplateId");
|
||||
launch.formParam("LaunchTemplate.LaunchTemplateId", template);
|
||||
} else {
|
||||
launch.formParam("ImageId", "ami-0abcdef1234567890").formParam("InstanceType", "t3.micro")
|
||||
.formParam("NetworkInterface.1.DeviceIndex", 0)
|
||||
.formParam("NetworkInterface.1.SubnetId", network.subnetId());
|
||||
}
|
||||
|
||||
launch.post("/").then().statusCode(400)
|
||||
.body("Response.Errors.Error.Code", equalTo("InvalidParameterCombination"))
|
||||
.body("Response.Errors.Error.Message", equalTo("Network interfaces and an instance-level "
|
||||
+ "private IP address may not be specified on the same request"));
|
||||
|
||||
assertInstancesIn(owner, network.subnetId(), 0);
|
||||
if (template != null) {
|
||||
request("DeleteLaunchTemplate", owner).formParam("LaunchTemplateId", template)
|
||||
.post("/").then().statusCode(200);
|
||||
}
|
||||
delete(owner, network);
|
||||
}
|
||||
|
||||
private record Network(String vpcId, String subnetId) {}
|
||||
|
||||
private static RequestSpecification runInstance(String owner) {
|
||||
return request("RunInstances", owner)
|
||||
.formParam("ImageId", "ami-0abcdef1234567890").formParam("InstanceType", "t3.micro")
|
||||
.formParam("MinCount", "1").formParam("MaxCount", "1");
|
||||
}
|
||||
|
||||
private static RequestSpecification request(String action, String owner) {
|
||||
return given().formParam("Action", action).header("Authorization", EnforcementFixtures.auth(owner, "ec2"));
|
||||
}
|
||||
|
||||
private static void assertDescribedAddress(String owner, String instanceId, String address) {
|
||||
request("DescribeInstances", owner).formParam("InstanceId.1", instanceId)
|
||||
.post("/").then().statusCode(200)
|
||||
.body(INSTANCE + "privateIpAddress", equalTo(address))
|
||||
.body(INSTANCE + "networkInterfaceSet.item.privateIpAddress", equalTo(address));
|
||||
}
|
||||
|
||||
/** A rejected launch must not leave an instance behind in the subnet it named. */
|
||||
private static void assertInstancesIn(String owner, String subnetId, int expected) {
|
||||
request("DescribeInstances", owner)
|
||||
.formParam("Filter.1.Name", "subnet-id").formParam("Filter.1.Value.1", subnetId)
|
||||
.post("/").then().statusCode(200)
|
||||
.body("DescribeInstancesResponse.reservationSet.item.instancesSet.item.size()", equalTo(expected));
|
||||
}
|
||||
|
||||
private static void terminate(String owner, String instanceId) {
|
||||
request("TerminateInstances", owner).formParam("InstanceId.1", instanceId).post("/").then().statusCode(200);
|
||||
}
|
||||
|
||||
private static Network createSubnet(String owner, String vpcCidr, String subnetCidr) {
|
||||
String vpcId = request("CreateVpc", owner).formParam("CidrBlock", vpcCidr)
|
||||
.post("/").then().statusCode(200)
|
||||
.extract().path("CreateVpcResponse.vpc.vpcId");
|
||||
String subnetId = request("CreateSubnet", owner).formParam("VpcId", vpcId).formParam("CidrBlock", subnetCidr)
|
||||
.post("/").then().statusCode(200)
|
||||
.extract().path("CreateSubnetResponse.subnet.subnetId");
|
||||
return new Network(vpcId, subnetId);
|
||||
}
|
||||
|
||||
private static void delete(String owner, Network network) {
|
||||
request("DeleteSubnet", owner).formParam("SubnetId", network.subnetId()).post("/").then().statusCode(200);
|
||||
request("DeleteVpc", owner).formParam("VpcId", network.vpcId()).post("/").then().statusCode(200);
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -64,7 +64,7 @@ class Ec2RunInstancesPublicIpParamTest {
|
||||
nullable(String.class), anyList(), nullable(String.class), nullable(String.class),
|
||||
nullable(Boolean.class), nullable(String.class), anyInt(), nullable(String.class),
|
||||
nullable(LaunchTemplateData.MetadataOptions.class), nullable(String.class), nullable(String.class), eq(false),
|
||||
nullable(String.class), nullable(String.class), nullable(List.class), eq(false)))
|
||||
nullable(String.class), nullable(String.class), nullable(List.class), eq(false), nullable(String.class)))
|
||||
.thenReturn(new Reservation());
|
||||
|
||||
Ec2QueryHandler handler = new Ec2QueryHandler(service, mock(EmulatorConfig.class),
|
||||
@@ -79,7 +79,7 @@ class Ec2RunInstancesPublicIpParamTest {
|
||||
nullable(String.class), anyList(), nullable(String.class), nullable(String.class),
|
||||
associatePublicIp.capture(), nullable(String.class), anyInt(), nullable(String.class),
|
||||
nullable(LaunchTemplateData.MetadataOptions.class), nullable(String.class), nullable(String.class), eq(false),
|
||||
nullable(String.class), nullable(String.class), nullable(List.class), eq(false));
|
||||
nullable(String.class), nullable(String.class), nullable(List.class), eq(false), nullable(String.class));
|
||||
if (expected == null) {
|
||||
assertNull(associatePublicIp.getValue(),
|
||||
"an absent override must stay null so the subnet default decides");
|
||||
|
||||
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.ec2;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.github.dockerjava.api.DockerClient;
|
||||
import com.github.dockerjava.api.command.ListNetworksCmd;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.RequestContext;
|
||||
@@ -106,6 +107,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.argThat;
|
||||
import static org.mockito.Mockito.RETURNS_SELF;
|
||||
import static org.mockito.Mockito.doAnswer;
|
||||
import static org.mockito.Mockito.inOrder;
|
||||
import static org.mockito.Mockito.mock;
|
||||
@@ -3738,6 +3740,381 @@ class Ec2ServiceTest {
|
||||
assertFalse(Ipv4Cidrs.isSubnetReserved(cidr, address + "/32"), address + " is reserved in " + cidr);
|
||||
}
|
||||
|
||||
@Test
|
||||
void runInstancesGivesTheInstanceAndItsInterfaceTheRequestedPrivateIp() {
|
||||
Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),
|
||||
mock(Ec2PortForwardManager.class), mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class),
|
||||
new Ec2InstanceTypeCatalog(), new InMemoryStorageFactory());
|
||||
String subnetId = privateIpSubnet(service);
|
||||
|
||||
for (String requested : List.of("10.50.1.50", "10.50.1.60")) {
|
||||
String id = launchWithPrivateIp(service, subnetId, 1, requested).getInstances().getFirst().getInstanceId();
|
||||
|
||||
Instance described = service.describeInstances("us-east-1", List.of(id), Map.of())
|
||||
.getFirst().getInstances().getFirst();
|
||||
assertEquals(requested, described.getPrivateIpAddress());
|
||||
assertEquals("ip-" + requested.replace('.', '-') + ".ec2.internal", described.getPrivateDnsName());
|
||||
assertEquals(requested, described.getNetworkInterfaces().getFirst().getPrivateIpAddress());
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"10.50.2.50", "10.50.1.0", "10.50.1.3", "10.50.1.255", "10.50.1.256", "not-an-ip"})
|
||||
void runInstancesRejectsARequestedPrivateIpTheSubnetCannotAssign(String requested) {
|
||||
Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),
|
||||
mock(Ec2PortForwardManager.class), mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class),
|
||||
new Ec2InstanceTypeCatalog(), new InMemoryStorageFactory());
|
||||
String subnetId = privateIpSubnet(service);
|
||||
|
||||
AwsException error = assertThrows(AwsException.class,
|
||||
() -> launchWithPrivateIp(service, subnetId, 1, requested));
|
||||
|
||||
assertEquals("InvalidParameterValue", error.getErrorCode());
|
||||
assertTrue(instancesIn(service, subnetId).isEmpty(), "a rejected launch must store nothing");
|
||||
}
|
||||
|
||||
@Test
|
||||
void runInstancesRejectsARequestedPrivateIpAnotherResourceHolds() {
|
||||
Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),
|
||||
mock(Ec2PortForwardManager.class), mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class),
|
||||
new Ec2InstanceTypeCatalog(), new InMemoryStorageFactory());
|
||||
String vpcId = service.createVpc("us-east-1", "10.50.0.0/16", false).getVpcId();
|
||||
String subnetId = service.createSubnet("us-east-1", vpcId, "10.50.1.0/24", "us-east-1a").getSubnetId();
|
||||
launchWithPrivateIp(service, subnetId, 1, "10.50.1.50");
|
||||
String assigned = launchAddresses(service, subnetId, 1).getFirst();
|
||||
service.createNetworkInterface("us-east-1", subnetId, "holder", "10.50.1.70",
|
||||
List.of(), List.of(), List.of());
|
||||
service.createVpcEndpoint("us-east-1", vpcId, "com.amazonaws.us-east-1.ecs",
|
||||
"Interface", List.of(), List.of(subnetId), List.of(), null, null, List.of());
|
||||
String endpointAddress = endpointAddressesBySubnet(service).get(subnetId);
|
||||
assertNotNull(endpointAddress);
|
||||
|
||||
for (String taken : List.of("10.50.1.50", assigned, "10.50.1.70", endpointAddress)) {
|
||||
AwsException error = assertThrows(AwsException.class,
|
||||
() -> launchWithPrivateIp(service, subnetId, 1, taken));
|
||||
assertEquals("InvalidIPAddress.InUse", error.getErrorCode());
|
||||
assertEquals("Address " + taken + " is in use.", error.getMessage());
|
||||
}
|
||||
assertEquals(2, instancesIn(service, subnetId).size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aTerminatedInstancesPrivateIpCanBeRequestedAgain() {
|
||||
// Terraform replaces an aws_instance whose private_ip is fixed by terminating the old one
|
||||
// and launching its successor at the same address.
|
||||
Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),
|
||||
mock(Ec2PortForwardManager.class), mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class),
|
||||
new Ec2InstanceTypeCatalog(), new InMemoryStorageFactory());
|
||||
String subnetId = privateIpSubnet(service);
|
||||
String first = launchWithPrivateIp(service, subnetId, 1, "10.50.1.50").getInstances().getFirst().getInstanceId();
|
||||
|
||||
service.terminateInstances("us-east-1", List.of(first));
|
||||
|
||||
assertEquals("10.50.1.50", launchWithPrivateIp(service, subnetId, 1, "10.50.1.50")
|
||||
.getInstances().getFirst().getPrivateIpAddress());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anAddressPickedByTheSubnetStepsAroundARequestedOne() {
|
||||
Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),
|
||||
mock(Ec2PortForwardManager.class), mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class),
|
||||
new Ec2InstanceTypeCatalog(), new InMemoryStorageFactory());
|
||||
String subnetId = privateIpSubnet(service);
|
||||
// A fresh subnet hands out .10, .11, .12 on its own, so .11 is the next one but the first.
|
||||
launchWithPrivateIp(service, subnetId, 1, "10.50.1.11");
|
||||
|
||||
assertEquals(List.of("10.50.1.10"), launchAddresses(service, subnetId, 1));
|
||||
assertEquals(List.of("10.50.1.12"), launchAddresses(service, subnetId, 1));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aZeroPaddedRequestedPrivateIpIsStoredCanonicallySoItStillConflicts() {
|
||||
Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),
|
||||
mock(Ec2PortForwardManager.class), mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class),
|
||||
new Ec2InstanceTypeCatalog(), new InMemoryStorageFactory());
|
||||
String subnetId = privateIpSubnet(service);
|
||||
|
||||
assertEquals("10.50.1.50", launchWithPrivateIp(service, subnetId, 1, "10.50.1.050")
|
||||
.getInstances().getFirst().getPrivateIpAddress());
|
||||
assertEquals("InvalidIPAddress.InUse", assertThrows(AwsException.class,
|
||||
() -> launchWithPrivateIp(service, subnetId, 1, "10.50.1.50")).getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aZeroPaddedAddressAnInterfaceWasCreatedWithStillHoldsTheRequestedPrivateIp() {
|
||||
// CreateNetworkInterface keeps its address as given, so the in-use check compares
|
||||
// canonical forms or a zero-padded octet would make one address look like two.
|
||||
Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),
|
||||
mock(Ec2PortForwardManager.class), mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class),
|
||||
new Ec2InstanceTypeCatalog(), new InMemoryStorageFactory());
|
||||
String subnetId = privateIpSubnet(service);
|
||||
NetworkInterface padded = service.createNetworkInterface("us-east-1", subnetId, "padded", "10.50.1.050",
|
||||
List.of(), List.of(), List.of());
|
||||
|
||||
AwsException error = assertThrows(AwsException.class,
|
||||
() -> launchWithPrivateIp(service, subnetId, 1, "10.50.1.50"));
|
||||
|
||||
assertEquals("InvalidIPAddress.InUse", error.getErrorCode());
|
||||
assertEquals("10.50.1.050", padded.getPrivateIpAddress());
|
||||
assertTrue(instancesIn(service, subnetId).isEmpty(), "a rejected launch must store nothing");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRequestedPrivateIpNeedsASingleInstanceThatCreatesItsOwnInterface() {
|
||||
Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),
|
||||
mock(Ec2PortForwardManager.class), mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class),
|
||||
new Ec2InstanceTypeCatalog(), new InMemoryStorageFactory());
|
||||
String subnetId = privateIpSubnet(service);
|
||||
String eniId = service.createNetworkInterface("us-east-1", subnetId, "primary", null,
|
||||
List.of(), List.of(), List.of()).getNetworkInterfaceId();
|
||||
|
||||
AwsException twoInstances = assertThrows(AwsException.class,
|
||||
() -> launchWithPrivateIp(service, subnetId, 2, "10.50.1.50"));
|
||||
AwsException upToTwoInstances = assertThrows(AwsException.class,
|
||||
() -> service.runInstances("us-east-1", "ami-1234567890abcdef0", "t3.micro", 1, 2, null,
|
||||
List.of(), subnetId, null, List.of(), null, null, null, null, 0, null, null, null, null,
|
||||
false, null, null, null, false, "10.50.1.50"));
|
||||
AwsException existingInterface = assertThrows(AwsException.class,
|
||||
() -> service.runInstances("us-east-1", "ami-1234567890abcdef0", "t3.micro", 1, 1, null,
|
||||
List.of(), null, null, List.of(), null, null, null, eniId, 0, null, null, null, null,
|
||||
false, null, null, null, false, "10.50.1.50"));
|
||||
|
||||
assertEquals("InvalidParameterCombination", twoInstances.getErrorCode());
|
||||
assertEquals("InvalidParameterCombination", upToTwoInstances.getErrorCode());
|
||||
assertEquals("InvalidParameterCombination", existingInterface.getErrorCode());
|
||||
assertTrue(instancesIn(service, subnetId).isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRequestedPrivateIpIsLeasedOnTheVpcNetworkInsteadOfTheNextFreeAddress() {
|
||||
VpcNetworkManager vpcNetworks = mock(VpcNetworkManager.class);
|
||||
Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),
|
||||
mock(Ec2PortForwardManager.class), mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class),
|
||||
new Ec2InstanceTypeCatalog(), new InMemoryStorageFactory(), vpcNetworks);
|
||||
String subnetId = privateIpSubnet(service);
|
||||
when(vpcNetworks.effectiveSubnetCidr("us-east-1", subnetId)).thenReturn(Optional.of("10.50.1.0/24"));
|
||||
when(vpcNetworks.claimPrivateIp("us-east-1", subnetId, "10.50.1.50")).thenReturn(true);
|
||||
|
||||
assertEquals("10.50.1.50", launchWithPrivateIp(service, subnetId, 1, "10.50.1.50")
|
||||
.getInstances().getFirst().getPrivateIpAddress());
|
||||
|
||||
verify(vpcNetworks).claimPrivateIp("us-east-1", subnetId, "10.50.1.50");
|
||||
verify(vpcNetworks, never()).reservePrivateIp(anyString(), anyString(), anyString());
|
||||
verify(vpcNetworks, never()).allocatePrivateIp(anyString(), anyString());
|
||||
}
|
||||
|
||||
@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.
|
||||
RequestContext context = new RequestContext();
|
||||
Ec2Service service = realVpcNetworkService(context);
|
||||
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();
|
||||
|
||||
context.setAccountId("000000000000");
|
||||
|
||||
assertEquals(stale, launchWithPrivateIp(service, subnetId, 1, stale)
|
||||
.getInstances().getFirst().getPrivateIpAddress());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"instance", "network-interface", "nat-gateway"})
|
||||
void aRequestedPrivateIpAnotherAccountHoldsOnASharedVpcNetworkIsInUse(String holder) {
|
||||
// Default VPC and subnet ids are the same in every account, so their Docker network and
|
||||
// lease table are shared while the stored-resource check sees only the caller's account.
|
||||
// Claiming the address anyway would give the other account's lease away.
|
||||
RequestContext context = new RequestContext();
|
||||
Ec2Service service = realVpcNetworkService(context);
|
||||
String subnetId = Ec2Service.defaultSubnetId("us-east-1", "a");
|
||||
context.setAccountId("111122223333");
|
||||
service.describeSubnets("us-east-1", List.of(), Map.of());
|
||||
String held = switch (holder) {
|
||||
case "instance" -> launchAddresses(service, subnetId, 1).getFirst();
|
||||
case "network-interface" -> service.createNetworkInterface("us-east-1", subnetId, "holder", null,
|
||||
List.of(), List.of(), List.of()).getPrivateIpAddress();
|
||||
default -> service.createNatGateway("us-east-1", subnetId, null, "private", List.of())
|
||||
.getNatGatewayAddresses().getFirst().getPrivateIp();
|
||||
};
|
||||
assertEquals("172.31.0.10", held, "the shared network's first address, leased by the other account");
|
||||
|
||||
context.setAccountId("000000000000");
|
||||
AwsException error = assertThrows(AwsException.class,
|
||||
() -> launchWithPrivateIp(service, subnetId, 1, held));
|
||||
|
||||
assertEquals("InvalidIPAddress.InUse", error.getErrorCode());
|
||||
assertEquals("Address " + held + " is in use.", error.getMessage());
|
||||
assertTrue(instancesIn(service, subnetId).isEmpty(), "a rejected launch must store nothing");
|
||||
}
|
||||
|
||||
@Test
|
||||
void anAddressAnotherAccountsInterfaceWasCreatedWithIsInUseOnASharedVpcNetwork() {
|
||||
// CreateNetworkInterface with its own address takes no lease, so only the stored
|
||||
// interface says the shared network's address is held.
|
||||
RequestContext context = new RequestContext();
|
||||
Ec2Service service = realVpcNetworkService(context);
|
||||
String subnetId = Ec2Service.defaultSubnetId("us-east-1", "a");
|
||||
context.setAccountId("111122223333");
|
||||
service.describeSubnets("us-east-1", List.of(), Map.of());
|
||||
service.createNetworkInterface("us-east-1", subnetId, "holder", "172.31.0.50",
|
||||
List.of(), List.of(), List.of());
|
||||
|
||||
context.setAccountId("000000000000");
|
||||
AwsException error = assertThrows(AwsException.class,
|
||||
() -> launchWithPrivateIp(service, subnetId, 1, "172.31.0.50"));
|
||||
|
||||
assertEquals("InvalidIPAddress.InUse", error.getErrorCode());
|
||||
assertTrue(instancesIn(service, subnetId).isEmpty(), "a rejected launch must store nothing");
|
||||
}
|
||||
|
||||
@Test
|
||||
void anotherAccountsNatGatewayStillHoldsItsAddressAfterARestartEmptiesTheLeaseTable() {
|
||||
// A restart re-leases only instances' addresses, so a persisted NAT gateway's address is
|
||||
// held by the stored gateway alone.
|
||||
String subnetId = Ec2Service.defaultSubnetId("us-east-1", "a");
|
||||
NatGatewayAddress address = new NatGatewayAddress();
|
||||
address.setPrivateIp("172.31.0.10");
|
||||
NatGateway natGateway = new NatGateway();
|
||||
natGateway.setNatGatewayId("nat-other");
|
||||
natGateway.setSubnetId(subnetId);
|
||||
natGateway.setState("available");
|
||||
natGateway.setNatGatewayAddresses(List.of(address));
|
||||
AccountAwareStorageBackend<NatGateway> natGatewayStore = AccountAwareStorageBackend.inMemory("000000000000");
|
||||
natGatewayStore.putForAccount("111122223333", "us-east-1::nat-other", natGateway);
|
||||
RequestContext context = new RequestContext();
|
||||
context.setAccountId("000000000000");
|
||||
Ec2Service service = realVpcNetworkService(context, Map.of("ec2-nat-gateways.json", natGatewayStore));
|
||||
|
||||
AwsException error = assertThrows(AwsException.class,
|
||||
() -> launchWithPrivateIp(service, subnetId, 1, "172.31.0.10"));
|
||||
|
||||
assertEquals("InvalidIPAddress.InUse", error.getErrorCode());
|
||||
assertTrue(instancesIn(service, subnetId).isEmpty(), "a rejected launch must store nothing");
|
||||
}
|
||||
|
||||
@Test
|
||||
void anotherAccountsInstanceOutsideASubstitutedRangeDoesNotHoldTheRequestedPrivateIp() {
|
||||
// A substituted subnet never leases an address outside its effective range, so no
|
||||
// container holds it on the shared network and each account keeps it as it would on AWS.
|
||||
String subnetId = Ec2Service.defaultSubnetId("us-east-1", "a");
|
||||
AccountAwareStorageBackend<Instance> instanceStore = AccountAwareStorageBackend.inMemory("000000000000");
|
||||
instanceStore.putForAccount("111122223333", "us-east-1::i-other",
|
||||
defaultSubnetInstance("i-other", "172.31.0.50", InstanceState.running()));
|
||||
VpcNetworkManager vpcNetworks = mock(VpcNetworkManager.class);
|
||||
when(vpcNetworks.effectiveSubnetCidr("us-east-1", subnetId)).thenReturn(Optional.of("10.240.0.0/20"));
|
||||
Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),
|
||||
mock(Ec2PortForwardManager.class), mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class),
|
||||
new Ec2InstanceTypeCatalog(),
|
||||
new InMemoryStorageFactory(Map.of("ec2-instances.json", instanceStore)), vpcNetworks);
|
||||
|
||||
assertEquals("172.31.0.50", launchWithPrivateIp(service, subnetId, 1, "172.31.0.50")
|
||||
.getInstances().getFirst().getPrivateIpAddress());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRequestedPrivateIpIsLeasedSoTheRealVpcNetworkDoesNotHandItOutAgain() {
|
||||
// The manager's allocator consults only its own lease table. Without the lease it would
|
||||
// hand a fresh /24's first address, offset 10, to the next launch as well.
|
||||
Ec2Service service = realVpcNetworkService(new RequestContext());
|
||||
String subnetId = privateIpSubnet(service);
|
||||
|
||||
assertEquals("10.50.1.10", launchWithPrivateIp(service, subnetId, 1, "10.50.1.10")
|
||||
.getInstances().getFirst().getPrivateIpAddress());
|
||||
|
||||
assertEquals(List.of("10.50.1.11"), launchAddresses(service, subnetId, 1));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRequestedPrivateIpLeavesTheRealVpcNetworksAllocationOrderAlone() {
|
||||
// Claiming a high address must not move the network's cursor past it, or the next
|
||||
// automatic address would be .251 instead of a fresh /24's first one.
|
||||
Ec2Service service = realVpcNetworkService(new RequestContext());
|
||||
String subnetId = privateIpSubnet(service);
|
||||
|
||||
launchWithPrivateIp(service, subnetId, 1, "10.50.1.250");
|
||||
|
||||
assertEquals(List.of("10.50.1.10"), launchAddresses(service, subnetId, 1));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDryRunWithARequestedPrivateIpLeasesNothing() {
|
||||
VpcNetworkManager vpcNetworks = mock(VpcNetworkManager.class);
|
||||
Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),
|
||||
mock(Ec2PortForwardManager.class), mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class),
|
||||
new Ec2InstanceTypeCatalog(), new InMemoryStorageFactory(), vpcNetworks);
|
||||
String subnetId = privateIpSubnet(service);
|
||||
|
||||
AwsException dryRun = assertThrows(AwsException.class,
|
||||
() -> service.runInstances("us-east-1", "ami-1234567890abcdef0", "t3.micro", 1, 1, null,
|
||||
List.of(), subnetId, null, List.of(), null, null, null, null, 0, null, null, null, null,
|
||||
true, null, null, null, false, "10.50.1.50"));
|
||||
|
||||
assertEquals("DryRunOperation", dryRun.getErrorCode());
|
||||
verify(vpcNetworks, never()).claimPrivateIp(anyString(), anyString(), anyString());
|
||||
assertTrue(instancesIn(service, subnetId).isEmpty());
|
||||
}
|
||||
|
||||
private static String privateIpSubnet(Ec2Service service) {
|
||||
String vpcId = service.createVpc("us-east-1", "10.50.0.0/16", false).getVpcId();
|
||||
return service.createSubnet("us-east-1", vpcId, "10.50.1.0/24", "us-east-1a").getSubnetId();
|
||||
}
|
||||
|
||||
private static Reservation launchWithPrivateIp(Ec2Service service, String subnetId, int count,
|
||||
String privateIp) {
|
||||
return service.runInstances("us-east-1", "ami-1234567890abcdef0", "t3.micro", count, count, null,
|
||||
List.of(), subnetId, null, List.of(), null, null, null, null, 0, null, null, null, null,
|
||||
false, null, null, null, false, privateIp);
|
||||
}
|
||||
|
||||
private static Ec2Service realVpcNetworkService(RequestContext context) {
|
||||
return realVpcNetworkService(context, Map.of());
|
||||
}
|
||||
|
||||
/**
|
||||
* 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) {
|
||||
EmulatorConfig config = mockConfig(false);
|
||||
EmulatorConfig.VpcNetworksConfig networks = mock(EmulatorConfig.VpcNetworksConfig.class);
|
||||
when(config.services().ec2().vpcNetworks()).thenReturn(networks);
|
||||
when(networks.enabled()).thenReturn(true);
|
||||
DockerClient docker = mock(DockerClient.class);
|
||||
ListNetworksCmd listNetworks = mock(ListNetworksCmd.class, RETURNS_SELF);
|
||||
when(listNetworks.exec()).thenReturn(List.of());
|
||||
when(docker.listNetworksCmd()).thenReturn(listNetworks);
|
||||
AmiImageResolver images = mock(AmiImageResolver.class);
|
||||
when(images.resolveImage(any())).thenReturn(ResolvedAmiImage.minimal("floci/base:latest"));
|
||||
@SuppressWarnings("unchecked")
|
||||
jakarta.enterprise.inject.Instance<RequestContext> contexts = mock(jakarta.enterprise.inject.Instance.class);
|
||||
when(contexts.isResolvable()).thenReturn(true);
|
||||
when(contexts.get()).thenReturn(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);
|
||||
}
|
||||
|
||||
private static Instance defaultSubnetInstance(String instanceId, String privateIp, InstanceState state) {
|
||||
Instance instance = persistedInstance(instanceId, privateIp, state);
|
||||
instance.setVpcId(Ec2Service.defaultVpcId("us-east-1"));
|
||||
instance.setSubnetId(Ec2Service.defaultSubnetId("us-east-1", "a"));
|
||||
return instance;
|
||||
}
|
||||
|
||||
private static List<Instance> instancesIn(Ec2Service service, String subnetId) {
|
||||
return service.describeInstances("us-east-1", List.of(), Map.of("subnet-id", List.of(subnetId))).stream()
|
||||
.flatMap(reservation -> reservation.getInstances().stream())
|
||||
.toList();
|
||||
}
|
||||
|
||||
private static EndpointAddressFixture endpointAddressFixture(String firstCidr, String secondCidr) {
|
||||
AccountAwareStorageBackend<Subnet> subnetStore = AccountAwareStorageBackend.inMemory("000000000000");
|
||||
Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),
|
||||
|
||||
@@ -328,6 +328,37 @@ class VpcNetworkManagerTest {
|
||||
"a terminated restored instance's address must return to circulation");
|
||||
}
|
||||
|
||||
// ─── Launch: an address RunInstances names for itself ────────────────────
|
||||
|
||||
@Test
|
||||
void aClaimedAddressIsNeverHandedOutAndLeavesTheAllocationOrderAlone() {
|
||||
manager.declareVpc(REGION, "vpc-1", "10.0.0.0/16");
|
||||
manager.declareSubnet(REGION, "vpc-1", "subnet-a", "10.0.1.0/24");
|
||||
|
||||
assertTrue(manager.claimPrivateIp(REGION, "subnet-a", "10.0.1.250"));
|
||||
|
||||
assertEquals("10.0.1.10", manager.allocatePrivateIp(REGION, "subnet-a").orElseThrow(),
|
||||
"a claimed address must not move the cursor past it");
|
||||
List<String> allocated = new ArrayList<>();
|
||||
Optional<String> next;
|
||||
while ((next = manager.allocatePrivateIp(REGION, "subnet-a")).isPresent()) {
|
||||
allocated.add(next.get());
|
||||
}
|
||||
assertFalse(allocated.contains("10.0.1.250"), "the claimed address must never be handed out");
|
||||
assertTrue(allocated.contains("10.0.1.254"), "the addresses after it are still handed out");
|
||||
}
|
||||
|
||||
@Test
|
||||
void claimingALeasedOrOutOfRangeAddressRefusesWithoutThrowing() {
|
||||
manager.declareVpc(REGION, "vpc-1", "10.0.0.0/16");
|
||||
manager.declareSubnet(REGION, "vpc-1", "subnet-a", "10.0.1.0/24");
|
||||
String leased = manager.allocatePrivateIp(REGION, "subnet-a").orElseThrow();
|
||||
|
||||
assertFalse(manager.claimPrivateIp(REGION, "subnet-a", leased));
|
||||
assertFalse(manager.claimPrivateIp(REGION, "subnet-a", "172.31.4.9"));
|
||||
assertFalse(manager.claimPrivateIp(REGION, "subnet-unknown", "10.0.1.20"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void subnetsInTheSameVpcGetDisjointRangesOnOneNetwork() {
|
||||
manager.declareVpc(REGION, "vpc-1", "10.0.0.0/16");
|
||||
|
||||
Reference in new issue
Block a user