feat(ecs): complete the fargate launch surface (#4017)

Floci accepted a Fargate task definition and ran it, but most of the
launch surface was dropped on the way through: members that AWS echoes
back went missing from responses, launch type resolution never validated
what it resolved, and the runtime ignored the sizing the task asked for.

Task definitions. A definition round-trips whole. Members that change
behaviour are typed (ephemeralStorage, dependsOn, environmentFiles, port
mapping name / appProtocol / containerPortRange, pidMode, ipcMode and the
container-level members the parser used to drop); members Floci does not
act on go through EcsJsonPassthrough, so an unimplemented volume
configuration comes back as it was sent rather than vanishing.
compatibilities is derived from the definition rather than echoed from
requiresCompatibilities, requiresAttributes names the capabilities the
definition needs, and a revision carries its registeredAt,
deregisteredAt and deleteRequestedAt through the ACTIVE / INACTIVE /
DELETE_IN_PROGRESS lifecycle.

Validation. Fargate task sizes are validated per CPU architecture and
operating system family, ephemeral storage against its 21-200 GiB range,
container dependencies for unknown names and cycles, and the parameters
Fargate does not support are rejected at registration with the exception
type AWS documents for them, ClientException; the message text is Floci's,
since AWS does not document the wording. Enum-typed members are validated
at parse time and raise InvalidParameterException instead of being
treated as absent, and
tag cardinality and character limits are enforced across the operations
that take tags.

Launch. capacityProviderStrategy is distributed across its providers the
way ECS distributes it, base first and the remainder by weight, with the
cluster's default strategy applying when a request carries neither it nor
a launch type. The strategy is validated against the bounds the ECS model
gives it: at most 20 providers, weight 0 to 1,000, base 0 to 100,000, one
base per strategy, and at least one provider of non-zero weight when a
strategy names more than one, since a provider of weight 0 places nothing
beyond its base. A task's CPU and memory reach the container, an awsvpc
task gets an ENI per task and releases it when it stops, container
dependencies are ordered with cycle detection, and mock mode reports
per-container detail so a client running without Docker sees the same
shape. The ENI allocation reaches into EC2, whose InvalidSubnetID.NotFound
and InvalidGroup.NotFound are not in RunTask's error list, so an unknown
subnet or security group is reported as the InvalidParameterException AWS
returns.

Verified against the AWS SDK for Java v2 and the AWS ECS API reference.
Adds EcsFargateTaskIntegrationTest, EcsFargateTaskDefinitionIntegrationTest
and EcsFargateEdgeCaseIntegrationTest, plus an SDK-based EcsFargateTest in
the compatibility suite.
This commit is contained in:
Abhigya authored and GitHub committed 2026-09-20 22:38:32 -04:00
1 parent 4906b7deed
commit bf1152e144
40 files changed
+4209 -267

No files matched your search

@@ -41,7 +41,8 @@ class CloudFormationEcsDeleteAfterRestoreIntegrationTest {
// it through the ECS API so ECS no longer has the record the stack still references. These
// run unauthenticated, like CreateStack/DeleteStack, so they share the same account namespace.
ecs("DeregisterTaskDefinition", "{\"taskDefinition\":\"" + family + "\"}");
ecs("DeleteTaskDefinitions", "{\"taskDefinitions\":[\"" + family + "\"]}");
// DeleteTaskDefinitions takes a revision, never a bare family.
ecs("DeleteTaskDefinitions", "{\"taskDefinitions\":[\"" + family + ":1\"]}");
deleteStack(stack);
@@ -62,7 +63,9 @@ class CloudFormationEcsDeleteAfterRestoreIntegrationTest {
// The cluster still has a running task at delete time (a genuine ClusterContainsTasksException),
// which must NOT be treated as already-gone. ECS runs in mock mode under test, so the task is
// in-memory RUNNING with no container behind it.
ecs("RunTask", "{\"cluster\":\"" + cluster + "\",\"taskDefinition\":\"" + family + "\",\"count\":1}");
ecs("RunTask", "{\"cluster\":\"" + cluster + "\",\"taskDefinition\":\"" + family + "\",\"count\":1,"
+ "\"networkConfiguration\":{\"awsvpcConfiguration\":"
+ "{\"subnets\":[\"subnet-default-us-east-1-a\"]}}}");
deleteStack(stack);
@@ -491,6 +491,84 @@ class Ec2ServiceTest {
assertEquals(1, retry.getInstances().size());
}
/**
* An interface a service holds on the caller's behalf, an ECS task's ENI being the one this
* emulator allocates, is {@code in-use}: DescribeNetworkInterfaces documents an unattached
* interface as {@code available} and an attached one as {@code in-use}, so left
* {@code available} it would answer a caller looking for a free interface. No attachment is
* synthesised, every member AWS documents on one naming an instance the task does not have,
* and the read-time reconciliation that frees an interface whose instance died therefore has
* nothing to act on here.
*/
@Test
void aServiceHeldInterfaceStaysInUseUntilItIsReleased() {
Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),
mock(Ec2PortForwardManager.class), mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class),
new Ec2InstanceTypeCatalog(), new InMemoryStorageFactory());
String subnetId = service.describeSubnets("us-east-1", List.of(), Map.of())
.getFirst().getSubnetId();
NetworkInterface eni = service.createNetworkInterface("us-east-1", subnetId, null,
null, List.of(), List.of(), List.of());
String eniId = eni.getNetworkInterfaceId();
assertEquals("available", eni.getStatus());
service.holdNetworkInterfaceForService("us-east-1", eniId);
assertEquals("in-use", readInterface(service, eniId).getStatus());
assertNull(readInterface(service, eniId).getAttachment());
assertTrue(service.describeNetworkInterfaces("us-east-1", List.of(),
Map.of("status", List.of("available")), 0, null)
.networkInterfaces().stream()
.noneMatch(n -> eniId.equals(n.getNetworkInterfaceId())));
// AWS does not let the account delete an interface a task holds, so a teardown has to
// release it first.
AwsException inUse = assertThrows(AwsException.class,
() -> service.deleteNetworkInterface("us-east-1", eniId));
assertEquals("InvalidParameterValue", inUse.getErrorCode());
service.releaseNetworkInterfaceFromService("us-east-1", eniId);
assertEquals("available", readInterface(service, eniId).getStatus());
assertDoesNotThrow(() -> service.deleteNetworkInterface("us-east-1", eniId));
// Releasing an interface that is already gone is a no-op, so a second teardown is harmless.
assertDoesNotThrow(() -> service.releaseNetworkInterfaceFromService("us-east-1", eniId));
}
/**
* The service hold must not reach an interface an instance owns: releasing one of those is
* DetachNetworkInterface's job, and it has an instance-side copy to clear as well.
*/
@Test
void aServiceHoldLeavesAnInstanceHeldInterfaceAlone() {
Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),
mock(Ec2PortForwardManager.class), mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class),
new Ec2InstanceTypeCatalog(), new InMemoryStorageFactory());
String subnetId = service.describeSubnets("us-east-1", List.of(), Map.of())
.getFirst().getSubnetId();
NetworkInterface eni = service.createNetworkInterface("us-east-1", subnetId, null,
null, List.of(), List.of(), List.of());
Reservation reservation = service.runInstances("us-east-1", "ami-1234567890abcdef0", "t3.micro",
1, 1, null, List.of(), null, null, List.of(), null, null, null,
eni.getNetworkInterfaceId(), 0);
String instanceId = reservation.getInstances().getFirst().getInstanceId();
AwsException held = assertThrows(AwsException.class,
() -> service.holdNetworkInterfaceForService("us-east-1", eni.getNetworkInterfaceId()));
assertEquals("InvalidNetworkInterface.InUse", held.getErrorCode());
service.releaseNetworkInterfaceFromService("us-east-1", eni.getNetworkInterfaceId());
NetworkInterface after = readInterface(service, eni.getNetworkInterfaceId());
assertEquals("in-use", after.getStatus());
assertEquals(instanceId, after.getAttachment().getInstanceId());
}
private static NetworkInterface readInterface(Ec2Service service, String networkInterfaceId) {
return service.describeNetworkInterfaces("us-east-1", List.of(networkInterfaceId), Map.of(), 0, null)
.networkInterfaces().getFirst();
}
/**
* A NetworkInterface can carry a real GroupIdentifier entry whose groupId is null (a name-only
* association). The group-id filter must skip that entry instead of NPE-ing on
@@ -0,0 +1,609 @@
package io.github.hectorvent.floci.services.ecs;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.Response;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Map;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasItems;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
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;
/**
* The edges of the Fargate rules: the boundary values of the documented ranges, the parameters
* that are only invalid in combination, and the limits AWS puts on a single call.
*/
@QuarkusTest
class EcsFargateEdgeCaseIntegrationTest {
private static final String TARGET = "AmazonEC2ContainerServiceV20141113.";
private static final String CT = "application/x-amz-json-1.1";
private static final String CLUSTER = "fargate-edge-cluster";
private static final String NETWORK =
"\"networkConfiguration\":{\"awsvpcConfiguration\":{\"subnets\":"
+ "[\"subnet-default-us-east-1-a\"]}}";
@BeforeAll
static void configure() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
private static Response call(String action, String body, int expectedStatus) {
return given().contentType(CT).header("X-Amz-Target", TARGET + action)
.body(body)
.when().post("/")
.then().statusCode(expectedStatus)
.extract().response();
}
private static void registerSize(String family, String cpu, String memory, int expectedStatus) {
call("RegisterTaskDefinition", "{\"family\":\"" + family + "\","
+ "\"requiresCompatibilities\":[\"FARGATE\"],\"networkMode\":\"awsvpc\","
+ "\"cpu\":\"" + cpu + "\",\"memory\":\"" + memory + "\","
+ "\"containerDefinitions\":[{\"name\":\"app\",\"image\":\"nginx:latest\"}]}",
expectedStatus);
}
private static String seed(String family) {
call("CreateCluster", "{\"clusterName\":\"" + CLUSTER + "\"}", 200);
registerSize(family, "256", "512", 200);
return family;
}
// ── Task size ─────────────────────────────────────────────────────────────
@Test
void theEdgesOfEveryFargateSizeRangeAreAccepted() {
registerSize("edge-256-low", "256", "512", 200);
registerSize("edge-256-high", "256", "2048", 200);
registerSize("edge-512-low", "512", "1024", 200);
registerSize("edge-512-high", "512", "4096", 200);
registerSize("edge-2048-low", "2048", "4096", 200);
registerSize("edge-2048-high", "2048", "16384", 200);
registerSize("edge-4096-high", "4096", "30720", 200);
registerSize("edge-8192-low", "8192", "16384", 200);
registerSize("edge-16384-high", "16384", "122880", 200);
}
@Test
void justOutsideEveryFargateSizeRangeIsRejected() {
registerSize("edge-256-below", "256", "256", 400);
registerSize("edge-256-above", "256", "3072", 400);
registerSize("edge-512-below", "512", "512", 400);
registerSize("edge-512-above", "512", "5120", 400);
registerSize("edge-4096-above", "4096", "31744", 400);
registerSize("edge-16384-above", "16384", "131072", 400);
registerSize("edge-unknown-cpu", "384", "1024", 400);
}
@Test
void theThirtyTwoVcpuSizesAreTheThreeFargateOffers() {
registerSize("edge-32vcpu-60", "32768", "61440", 200);
registerSize("edge-32vcpu-120", "32768", "122880", 200);
registerSize("edge-32vcpu-244", "32768", "249856", 200);
// 32 vCPU is not a range: anything between the three offers is not a configuration.
registerSize("edge-32vcpu-between", "32768", "65536", 400);
}
@Test
void theStringFormsOfCpuAndMemoryAreAccepted() {
registerSize("edge-vcpu-string", "0.5 vCPU", "1 GB", 200);
registerSize("edge-vcpu-lowercase", "1 vcpu", "2GB", 200);
}
// ── Ephemeral storage ─────────────────────────────────────────────────────
@Test
void ephemeralStorageIsAcceptedAtBothEndsOfItsRange() {
String body = "{\"family\":\"edge-storage-%s\",\"requiresCompatibilities\":[\"FARGATE\"],"
+ "\"networkMode\":\"awsvpc\",\"cpu\":\"256\",\"memory\":\"512\","
+ "\"ephemeralStorage\":{\"sizeInGiB\":%d},"
+ "\"containerDefinitions\":[{\"name\":\"app\",\"image\":\"nginx:latest\"}]}";
call("RegisterTaskDefinition", body.formatted("min", 21), 200);
call("RegisterTaskDefinition", body.formatted("max", 200), 200);
call("RegisterTaskDefinition", body.formatted("below", 20), 400);
call("RegisterTaskDefinition", body.formatted("above", 201), 400);
}
// ── Parameters Fargate does not support ───────────────────────────────────
@Test
void everyFargateUnsupportedParameterIsRejected() {
String container = "{\"family\":\"edge-unsupported-%s\","
+ "\"requiresCompatibilities\":[\"FARGATE\"],\"networkMode\":\"awsvpc\","
+ "\"cpu\":\"256\",\"memory\":\"512\",\"containerDefinitions\":"
+ "[{\"name\":\"app\",\"image\":\"nginx:latest\",%s}]}";
call("RegisterTaskDefinition",
container.formatted("dso", "\"dockerSecurityOptions\":[\"label:user:jdoe\"]"), 400)
.then().body("message", containsString("dockerSecurityOptions"));
call("RegisterTaskDefinition",
container.formatted("hosts", "\"extraHosts\":[{\"hostname\":\"db\",\"ipAddress\":\"10.0.0.9\"}]"), 400)
.then().body("message", containsString("extraHosts"));
call("RegisterTaskDefinition",
container.formatted("gpu", "\"resourceRequirements\":[{\"type\":\"GPU\",\"value\":\"1\"}]"), 400)
.then().body("message", containsString("gpu"));
call("RegisterTaskDefinition",
container.formatted("swap", "\"linuxParameters\":{\"maxSwap\":128}"), 400)
.then().body("message", containsString("maxSwap"));
call("RegisterTaskDefinition",
container.formatted("swappiness", "\"linuxParameters\":{\"swappiness\":10}"), 400)
.then().body("message", containsString("swappiness"));
call("RegisterTaskDefinition", "{\"family\":\"edge-unsupported-placement\","
+ "\"requiresCompatibilities\":[\"FARGATE\"],\"networkMode\":\"awsvpc\","
+ "\"cpu\":\"256\",\"memory\":\"512\","
+ "\"placementConstraints\":[{\"type\":\"memberOf\",\"expression\":\"attribute:ecs.os-type==linux\"}],"
+ "\"containerDefinitions\":[{\"name\":\"app\",\"image\":\"nginx:latest\"}]}", 400)
.then().body("message", containsString("placementConstraints"));
}
@Test
void pidModeTaskIsTheOnlyOneFargateAccepts() {
String body = "{\"family\":\"edge-pidmode-%s\",\"requiresCompatibilities\":[\"FARGATE\"],"
+ "\"networkMode\":\"awsvpc\",\"cpu\":\"256\",\"memory\":\"512\",\"pidMode\":\"%s\","
+ "\"containerDefinitions\":[{\"name\":\"app\",\"image\":\"nginx:latest\"}]}";
call("RegisterTaskDefinition", body.formatted("task", "task"), 200);
call("RegisterTaskDefinition", body.formatted("host", "host"), 400)
.then().body("message", containsString("pidMode"));
}
@Test
void aDependencyCycleIsRejectedAtRegistration() {
call("RegisterTaskDefinition", "{\"family\":\"edge-cycle\","
+ "\"requiresCompatibilities\":[\"FARGATE\"],\"networkMode\":\"awsvpc\","
+ "\"cpu\":\"256\",\"memory\":\"512\",\"containerDefinitions\":["
+ "{\"name\":\"a\",\"image\":\"busybox\","
+ "\"dependsOn\":[{\"containerName\":\"b\",\"condition\":\"START\"}]},"
+ "{\"name\":\"b\",\"image\":\"busybox\","
+ "\"dependsOn\":[{\"containerName\":\"a\",\"condition\":\"START\"}]}]}", 400)
.then().body("message", containsString("cycle"));
}
// ── RunTask limits ────────────────────────────────────────────────────────
@Test
void runTaskPlacesAtMostTenTasksPerCall() {
String family = seed("edge-count");
Response ten = call("RunTask", "{\"cluster\":\"" + CLUSTER + "\",\"taskDefinition\":\""
+ family + "\",\"count\":10,\"launchType\":\"FARGATE\"," + NETWORK + "}", 200);
ten.then().body("tasks", hasSize(10));
call("RunTask", "{\"cluster\":\"" + CLUSTER + "\",\"taskDefinition\":\"" + family
+ "\",\"count\":11,\"launchType\":\"FARGATE\"," + NETWORK + "}", 400)
.then().body("message", containsString("between 1 and 10"));
call("RunTask", "{\"cluster\":\"" + CLUSTER + "\",\"taskDefinition\":\"" + family
+ "\",\"count\":0,\"launchType\":\"FARGATE\"," + NETWORK + "}", 400);
ten.jsonPath().getList("tasks.taskArn", String.class).forEach(taskArn ->
call("StopTask", "{\"cluster\":\"" + CLUSTER + "\",\"task\":\"" + taskArn + "\"}", 200));
}
@Test
void propagatingServiceTagsIsRefusedForAStandaloneTask() {
String family = seed("edge-propagate");
call("RunTask", "{\"cluster\":\"" + CLUSTER + "\",\"taskDefinition\":\"" + family
+ "\",\"launchType\":\"FARGATE\"," + NETWORK + ",\"propagateTags\":\"SERVICE\"}", 400)
.then().body("message", containsString("SERVICE"));
}
@Test
void propagatingTaskDefinitionTagsCopiesThemOntoTheTask() {
call("CreateCluster", "{\"clusterName\":\"" + CLUSTER + "\"}", 200);
call("RegisterTaskDefinition", "{\"family\":\"edge-td-tags\","
+ "\"requiresCompatibilities\":[\"FARGATE\"],\"networkMode\":\"awsvpc\","
+ "\"cpu\":\"256\",\"memory\":\"512\",\"tags\":[{\"key\":\"owner\",\"value\":\"platform\"}],"
+ "\"containerDefinitions\":[{\"name\":\"app\",\"image\":\"nginx:latest\"}]}", 200);
call("RunTask", "{\"cluster\":\"" + CLUSTER + "\",\"taskDefinition\":\"edge-td-tags\","
+ "\"launchType\":\"FARGATE\"," + NETWORK + ",\"propagateTags\":\"TASK_DEFINITION\"}", 200)
.then()
.body("tasks[0].tags[0].key", equalTo("owner"))
.body("tasks[0].tags[0].value", equalTo("platform"));
}
/**
* The ENI allocation reaches into EC2, whose not-found codes RunTask does not declare. An SDK
* given {@code InvalidSubnetID.NotFound} sees an unmodelled failure instead of the
* InvalidParameterException AWS returns for a subnet that is not there.
*/
@Test
void runTaskRejectsAnUnknownSubnetAsAnInvalidParameter() {
String family = seed("edge-unknown-subnet");
call("RunTask", "{\"cluster\":\"" + CLUSTER + "\",\"taskDefinition\":\"" + family
+ "\",\"launchType\":\"FARGATE\",\"networkConfiguration\":{\"awsvpcConfiguration\":"
+ "{\"subnets\":[\"subnet-does-not-exist\"]}}}", 400)
.then()
.body("__type", containsString("InvalidParameterException"))
.body("message", containsString("subnet-does-not-exist"));
}
@Test
void runTaskRejectsAnUnknownSecurityGroupAsAnInvalidParameter() {
String family = seed("edge-unknown-sg");
call("RunTask", "{\"cluster\":\"" + CLUSTER + "\",\"taskDefinition\":\"" + family
+ "\",\"launchType\":\"FARGATE\",\"networkConfiguration\":{\"awsvpcConfiguration\":"
+ "{\"subnets\":[\"subnet-default-us-east-1-a\"],\"securityGroups\":[\"sg-nope\"]}}}", 400)
.then()
.body("__type", containsString("InvalidParameterException"))
.body("message", containsString("sg-nope"));
}
/**
* MANAGED_INSTANCES joined LaunchType and Compatibility in the ECS model. Rejecting it would
* 400 a request the SDK considers valid.
*/
@Test
void managedInstancesIsAcceptedAsACompatibilityAndALaunchType() {
call("CreateCluster", "{\"clusterName\":\"" + CLUSTER + "\"}", 200);
call("RegisterTaskDefinition", "{\"family\":\"edge-managed-instances\","
+ "\"requiresCompatibilities\":[\"EC2\",\"MANAGED_INSTANCES\"],"
+ "\"containerDefinitions\":[{\"name\":\"app\",\"image\":\"nginx:latest\","
+ "\"memory\":512}]}", 200)
.then().body("taskDefinition.requiresCompatibilities", hasItems("MANAGED_INSTANCES"));
call("RunTask", "{\"cluster\":\"" + CLUSTER + "\",\"taskDefinition\":\"edge-managed-instances\","
+ "\"launchType\":\"MANAGED_INSTANCES\"}", 200)
.then().body("tasks[0].launchType", equalTo("MANAGED_INSTANCES"));
}
// ── Capacity provider strategy ────────────────────────────────────────────
@Test
void aStrategyWithTwoBasesIsRejected() {
String family = seed("edge-two-bases");
call("RunTask", "{\"cluster\":\"" + CLUSTER + "\",\"taskDefinition\":\"" + family + "\","
+ NETWORK + ",\"capacityProviderStrategy\":["
+ "{\"capacityProvider\":\"FARGATE\",\"base\":1,\"weight\":1},"
+ "{\"capacityProvider\":\"FARGATE_SPOT\",\"base\":1,\"weight\":1}]}", 400)
.then().body("message", containsString("base"));
}
@Test
void aLoneProviderOfWeightZeroStillPlacesEveryTask() {
String family = seed("edge-zero-weight");
Response response = call("RunTask", "{\"cluster\":\"" + CLUSTER + "\",\"taskDefinition\":\""
+ family + "\",\"count\":3," + NETWORK + ",\"capacityProviderStrategy\":"
+ "[{\"capacityProvider\":\"FARGATE_SPOT\",\"weight\":0}]}", 200);
List<String> providers = response.jsonPath().getList("tasks.capacityProviderName");
assertEquals(3, providers.size(), "a weightless strategy must still place every task");
assertTrue(providers.stream().allMatch("FARGATE_SPOT"::equals), providers.toString());
}
@Test
void aStrategyWhoseProvidersAllWeighZeroIsRejected() {
String family = seed("edge-all-zero-weights");
call("RunTask", "{\"cluster\":\"" + CLUSTER + "\",\"taskDefinition\":\"" + family + "\","
+ NETWORK + ",\"capacityProviderStrategy\":["
+ "{\"capacityProvider\":\"FARGATE\",\"weight\":0},"
+ "{\"capacityProvider\":\"FARGATE_SPOT\",\"weight\":0}]}", 400)
.then().body("message", containsString("weight greater than zero"));
}
@Test
void aStrategyEntryOutsideTheWeightAndBaseRangesIsRejected() {
String family = seed("edge-strategy-ranges");
call("RunTask", "{\"cluster\":\"" + CLUSTER + "\",\"taskDefinition\":\"" + family + "\","
+ NETWORK + ",\"capacityProviderStrategy\":"
+ "[{\"capacityProvider\":\"FARGATE\",\"weight\":1001}]}", 400)
.then().body("message", containsString("between 0 and 1000"));
call("RunTask", "{\"cluster\":\"" + CLUSTER + "\",\"taskDefinition\":\"" + family + "\","
+ NETWORK + ",\"capacityProviderStrategy\":"
+ "[{\"capacityProvider\":\"FARGATE\",\"weight\":1,\"base\":100001}]}", 400)
.then().body("message", containsString("between 0 and 100000"));
call("RunTask", "{\"cluster\":\"" + CLUSTER + "\",\"taskDefinition\":\"" + family + "\","
+ NETWORK + ",\"capacityProviderStrategy\":"
+ "[{\"capacityProvider\":\"FARGATE\",\"weight\":1000,\"base\":100000}]}", 200)
.then().body("tasks[0].capacityProviderName", equalTo("FARGATE"));
}
@Test
void aStrategyOfMoreThanTwentyProvidersIsRejected() {
String family = seed("edge-strategy-size");
StringBuilder strategy = new StringBuilder();
for (int i = 0; i < 21; i++) {
strategy.append(i == 0 ? "" : ",")
.append("{\"capacityProvider\":\"FARGATE\",\"weight\":1}");
}
call("RunTask", "{\"cluster\":\"" + CLUSTER + "\",\"taskDefinition\":\"" + family + "\","
+ NETWORK + ",\"capacityProviderStrategy\":[" + strategy + "]}", 400)
.then().body("message", containsString("maximum of 20 capacity providers"));
}
@Test
void anEmptyStrategyFallsBackToTheLaunchType() {
String family = seed("edge-empty-strategy");
call("RunTask", "{\"cluster\":\"" + CLUSTER + "\",\"taskDefinition\":\"" + family
+ "\",\"launchType\":\"FARGATE\"," + NETWORK + ",\"capacityProviderStrategy\":[]}", 200)
.then().body("tasks[0].launchType", equalTo("FARGATE"));
}
// ── Task shape ────────────────────────────────────────────────────────────
@Test
void aStoppedTaskReportsTheTimestampsAndCodesAwsReports() {
String family = seed("edge-stopped-shape");
String taskArn = call("RunTask", "{\"cluster\":\"" + CLUSTER + "\",\"taskDefinition\":\""
+ family + "\",\"launchType\":\"FARGATE\"," + NETWORK + "}", 200)
.jsonPath().getString("tasks[0].taskArn");
Response stopped = call("StopTask", "{\"cluster\":\"" + CLUSTER + "\",\"task\":\""
+ taskArn + "\",\"reason\":\"edge\"}", 200);
stopped.then()
.body("task.stopCode", equalTo("UserInitiated"))
.body("task.lastStatus", equalTo("STOPPED"));
assertTrue(stopped.jsonPath().getDouble("task.stoppingAt") > 0,
"stoppingAt must be reported for a task that went through STOPPING");
assertTrue(stopped.jsonPath().getDouble("task.executionStoppedAt") > 0,
"executionStoppedAt must be reported");
}
@Test
void aFargateTaskReportsBothEphemeralStorageMembersAndZeroCpuContainers() {
String family = seed("edge-storage-members");
call("RunTask", "{\"cluster\":\"" + CLUSTER + "\",\"taskDefinition\":\"" + family
+ "\",\"launchType\":\"FARGATE\"," + NETWORK + "}", 200)
.then()
.body("tasks[0].ephemeralStorage.sizeInGiB", equalTo(20))
.body("tasks[0].fargateEphemeralStorage.sizeInGiB", equalTo(20))
// A container definition without cpu units reports zero, not nothing.
.body("tasks[0].containers[0].cpu", equalTo("0"));
}
@Test
void describeTasksReportsTagsOnlyWhenTheyAreAskedFor() {
String family = seed("edge-describe-tags");
String taskArn = call("RunTask", "{\"cluster\":\"" + CLUSTER + "\",\"taskDefinition\":\""
+ family + "\",\"launchType\":\"FARGATE\"," + NETWORK
+ ",\"tags\":[{\"key\":\"owner\",\"value\":\"platform\"}]}", 200)
.jsonPath().getString("tasks[0].taskArn");
call("DescribeTasks", "{\"cluster\":\"" + CLUSTER + "\",\"tasks\":[\"" + taskArn + "\"]}", 200)
.then().body("tasks[0].tags", nullValue());
call("DescribeTasks", "{\"cluster\":\"" + CLUSTER + "\",\"tasks\":[\"" + taskArn
+ "\"],\"include\":[\"TAGS\"]}", 200)
.then().body("tasks[0].tags[0].key", equalTo("owner"));
}
@Test
void aTaskAlwaysReportsAnOverrideEntryPerContainer() {
call("CreateCluster", "{\"clusterName\":\"" + CLUSTER + "\"}", 200);
call("RegisterTaskDefinition", "{\"family\":\"edge-overrides\","
+ "\"requiresCompatibilities\":[\"FARGATE\"],\"networkMode\":\"awsvpc\","
+ "\"cpu\":\"256\",\"memory\":\"512\",\"containerDefinitions\":["
+ "{\"name\":\"app\",\"image\":\"nginx:latest\"},"
+ "{\"name\":\"sidecar\",\"image\":\"busybox\",\"essential\":false}]}", 200);
// Nothing was overridden, and AWS still lists every container under overrides.
call("RunTask", "{\"cluster\":\"" + CLUSTER + "\",\"taskDefinition\":\"edge-overrides\","
+ "\"launchType\":\"FARGATE\"," + NETWORK + "}", 200)
.then()
.body("tasks[0].overrides.containerOverrides", hasSize(2))
.body("tasks[0].overrides.containerOverrides[0].name", equalTo("app"))
.body("tasks[0].overrides.containerOverrides[1].name", equalTo("sidecar"));
}
@Test
void anAwsvpcTaskReportsTheAttachmentDetailsAwsReports() {
String family = seed("edge-attachment-details");
Response response = call("RunTask", "{\"cluster\":\"" + CLUSTER + "\",\"taskDefinition\":\""
+ family + "\",\"launchType\":\"FARGATE\"," + NETWORK + "}", 200);
List<String> names = response.jsonPath().getList("tasks[0].attachments[0].details.name");
assertTrue(names.containsAll(List.of("subnetId", "networkInterfaceId", "macAddress",
"privateDnsName", "privateIPv4Address")),
"the attachment must carry the details AWS reports, got: " + names);
}
// ── Service updates ──────────────────────────────────────────────────────
private static String deploymentId(String serviceName) {
return call("DescribeServices", "{\"cluster\":\"" + CLUSTER + "\",\"services\":[\""
+ serviceName + "\"]}", 200)
.jsonPath().getString("services[0].deployments[0].id");
}
// ── Task definition lifecycle ─────────────────────────────────────────────
@Test
void aDeletedRevisionStaysDescribableAsDeleteInProgress() {
registerSize("edge-delete-lifecycle", "256", "512", 200);
// Deleting before deregistering is refused, and a family without a revision is not a
// reference this API takes.
call("DeleteTaskDefinitions", "{\"taskDefinitions\":[\"edge-delete-lifecycle:1\"]}", 400)
.then().body("message", containsString("INACTIVE"));
call("DeregisterTaskDefinition", "{\"taskDefinition\":\"edge-delete-lifecycle:1\"}", 200)
.then().body("taskDefinition.status", equalTo("INACTIVE"));
call("DeleteTaskDefinitions", "{\"taskDefinitions\":[\"edge-delete-lifecycle\"]}", 400)
.then().body("message", containsString("revision"));
call("DeleteTaskDefinitions", "{\"taskDefinitions\":[\"edge-delete-lifecycle:1\"]}", 200)
.then().body("taskDefinitions[0].status", equalTo("DELETE_IN_PROGRESS"));
// The revision is still describable, and carries the lifecycle timestamps.
Response described = call("DescribeTaskDefinition",
"{\"taskDefinition\":\"edge-delete-lifecycle:1\"}", 200);
described.then().body("taskDefinition.status", equalTo("DELETE_IN_PROGRESS"));
assertTrue(described.jsonPath().getDouble("taskDefinition.deregisteredAt") > 0,
"a deregistered revision reports deregisteredAt");
assertTrue(described.jsonPath().getDouble("taskDefinition.deleteRequestedAt") > 0,
"a revision being deleted reports deleteRequestedAt");
// And it can no longer start anything new.
call("RunTask", "{\"cluster\":\"" + CLUSTER + "\",\"taskDefinition\":\"edge-delete-lifecycle:1\","
+ "\"launchType\":\"FARGATE\"," + NETWORK + "}", 400)
.then().body("message", containsString("being deleted"));
}
@Test
void describeTasksReportsAnUnknownTaskAsMissingRatherThanDroppingIt() {
call("CreateCluster", "{\"clusterName\":\"" + CLUSTER + "\"}", 200);
call("DescribeTasks", "{\"cluster\":\"" + CLUSTER + "\",\"tasks\":[\"00000000000000000000000000000000\"]}", 200)
.then()
.body("tasks", hasSize(0))
.body("failures", hasSize(1))
.body("failures[0].reason", equalTo("MISSING"));
}
// ── Derived compatibilities and requiresAttributes ────────────────────────
@Test
void compatibilitiesAreDerivedFromTheDefinitionNotJustEchoed() {
// Fargate-valid but never asked for FARGATE: ECS still reports the launch types it works on.
call("RegisterTaskDefinition", "{\"family\":\"edge-compat-implicit\",\"networkMode\":\"awsvpc\","
+ "\"cpu\":\"256\",\"memory\":\"512\",\"containerDefinitions\":"
+ "[{\"name\":\"app\",\"image\":\"nginx:latest\"}]}", 200)
.then().body("taskDefinition.compatibilities", equalTo(List.of("EC2", "FARGATE")));
// awsvpc rules out EXTERNAL; bridge rules out FARGATE and allows EXTERNAL.
call("RegisterTaskDefinition", "{\"family\":\"edge-compat-bridge\",\"networkMode\":\"bridge\","
+ "\"containerDefinitions\":[{\"name\":\"app\",\"image\":\"nginx:latest\",\"memory\":128}]}", 200)
.then().body("taskDefinition.compatibilities", equalTo(List.of("EC2", "EXTERNAL")));
// awsvpc without a Fargate size pair is EC2 only.
call("RegisterTaskDefinition", "{\"family\":\"edge-compat-nosize\",\"networkMode\":\"awsvpc\","
+ "\"containerDefinitions\":[{\"name\":\"app\",\"image\":\"nginx:latest\",\"memory\":128}]}", 200)
.then().body("taskDefinition.compatibilities", equalTo(List.of("EC2")));
}
@Test
void requiresAttributesNamesTheCapabilitiesTheDefinitionUses() {
call("RegisterTaskDefinition", "{\"family\":\"edge-attrs\",\"networkMode\":\"awsvpc\","
+ "\"cpu\":\"256\",\"memory\":\"512\","
+ "\"taskRoleArn\":\"arn:aws:iam::000000000000:role/task\","
+ "\"containerDefinitions\":[{\"name\":\"app\","
+ "\"image\":\"000000000000.dkr.ecr.us-east-1.amazonaws.com/app:1\","
+ "\"logConfiguration\":{\"logDriver\":\"awslogs\",\"options\":{}}}]}", 200)
.then()
.body("taskDefinition.requiresAttributes.name", hasItems(
"com.amazonaws.ecs.capability.docker-remote-api.1.18",
"ecs.capability.task-eni",
"com.amazonaws.ecs.capability.task-iam-role",
"com.amazonaws.ecs.capability.ecr-auth",
"com.amazonaws.ecs.capability.logging-driver.awslogs"));
// A task role under host networking has its own capability name.
call("RegisterTaskDefinition", "{\"family\":\"edge-attrs-host\",\"networkMode\":\"host\","
+ "\"taskRoleArn\":\"arn:aws:iam::000000000000:role/task\","
+ "\"containerDefinitions\":[{\"name\":\"app\",\"image\":\"nginx:latest\",\"memory\":128}]}", 200)
.then()
.body("taskDefinition.requiresAttributes.name", hasItems(
"com.amazonaws.ecs.capability.task-iam-role-network-host"))
.body("taskDefinition.requiresAttributes.name", not(hasItems("ecs.capability.task-eni")));
}
@Test
void startTaskRequiresContainerInstances() {
String family = seed("edge-start-task");
call("StartTask", "{\"cluster\":\"" + CLUSTER + "\",\"taskDefinition\":\"" + family + "\"}", 400)
.then().body("message", containsString("containerInstances"));
}
// ── Capacity providers ───────────────────────────────────────────────────
// ── Round trips the parser used to drop ──────────────────────────────────
@Test
void aPortMappingRoundTripsItsServiceConnectMembers() {
call("CreateCluster", "{\"clusterName\":\"" + CLUSTER + "\"}", 200);
call("RegisterTaskDefinition", "{\"family\":\"edge-portmapping\","
+ "\"requiresCompatibilities\":[\"FARGATE\"],\"networkMode\":\"awsvpc\","
+ "\"cpu\":\"256\",\"memory\":\"512\","
+ "\"containerDefinitions\":[{\"name\":\"app\",\"image\":\"nginx:latest\","
+ "\"portMappings\":[{\"containerPort\":8080,\"protocol\":\"tcp\","
+ "\"name\":\"api\",\"appProtocol\":\"http\"}]}]}", 200);
// name and appProtocol are what a service's serviceConnectConfiguration references, so
// losing them on the round trip breaks Service Connect.
call("DescribeTaskDefinition", "{\"taskDefinition\":\"edge-portmapping\"}", 200)
.then()
.body("taskDefinition.containerDefinitions[0].portMappings[0].name", equalTo("api"))
.body("taskDefinition.containerDefinitions[0].portMappings[0].appProtocol",
equalTo("http"))
.body("taskDefinition.containerDefinitions[0].portMappings[0].containerPort",
equalTo(8080));
}
@Test
void aVolumeRoundTripsTheConfigurationsFlociDoesNotBack() {
call("CreateCluster", "{\"clusterName\":\"" + CLUSTER + "\"}", 200);
call("RegisterTaskDefinition", "{\"family\":\"edge-volume-roundtrip\","
+ "\"containerDefinitions\":[{\"name\":\"app\",\"image\":\"nginx:latest\"}],"
+ "\"volumes\":[{\"name\":\"docker-vol\",\"configuredAtLaunch\":false,"
+ "\"dockerVolumeConfiguration\":{\"scope\":\"shared\",\"autoprovision\":true,"
+ "\"driver\":\"local\"}}]}", 200);
call("DescribeTaskDefinition", "{\"taskDefinition\":\"edge-volume-roundtrip\"}", 200)
.then()
.body("taskDefinition.volumes[0].name", equalTo("docker-vol"))
.body("taskDefinition.volumes[0].dockerVolumeConfiguration.scope", equalTo("shared"))
.body("taskDefinition.volumes[0].dockerVolumeConfiguration.driver", equalTo("local"))
.body("taskDefinition.volumes[0].configuredAtLaunch", equalTo(false));
}
// ── Request validation ───────────────────────────────────────────────────
@Test
void anEnumValueTheApiDoesNotHaveIsRejectedRatherThanIgnored() {
String family = seed("edge-bad-enum");
// Silently treating this as absent would place the task on Floci's default launch type,
// which is not what the caller asked for.
call("RunTask", "{\"cluster\":\"" + CLUSTER + "\",\"taskDefinition\":\"" + family
+ "\",\"launchType\":\"EC22\"," + NETWORK + "}", 400)
.then().body("message", containsString("launchType"));
call("RegisterTaskDefinition", "{\"family\":\"edge-bad-network-mode\","
+ "\"networkMode\":\"AWSVPC\","
+ "\"containerDefinitions\":[{\"name\":\"app\",\"image\":\"nginx:latest\"}]}", 400)
.then().body("message", containsString("networkMode"));
}
@Test
void aResourceTakesAtMostFiftyTags() {
StringBuilder tags = new StringBuilder();
for (int i = 0; i < 51; i++) {
tags.append(i > 0 ? "," : "")
.append("{\"key\":\"k").append(i).append("\",\"value\":\"v\"}");
}
call("CreateCluster", "{\"clusterName\":\"edge-too-many-tags\",\"tags\":[" + tags + "]}", 400)
.then().body("message", containsString("50"));
call("CreateCluster", "{\"clusterName\":\"edge-empty-tag-key\","
+ "\"tags\":[{\"key\":\"\",\"value\":\"v\"}]}", 400)
.then().body("message", containsString("Tag keys"));
}
}
@@ -0,0 +1,220 @@
package io.github.hectorvent.floci.services.ecs;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.Response;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasSize;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* RegisterTaskDefinition for the Fargate launch type: the members a Fargate task definition
* carries must survive a round trip, and the ones Fargate has no equivalent for must be rejected
* at registration rather than at launch.
*/
@QuarkusTest
class EcsFargateTaskDefinitionIntegrationTest {
private static final String TARGET = "AmazonEC2ContainerServiceV20141113.";
private static final String CT = "application/x-amz-json-1.1";
@BeforeAll
static void configure() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
private static Response call(String action, String body, int expectedStatus) {
return given().contentType(CT).header("X-Amz-Target", TARGET + action)
.body(body)
.when().post("/")
.then().statusCode(expectedStatus)
.extract().response();
}
private static Response register(String body, int expectedStatus) {
return call("RegisterTaskDefinition", body, expectedStatus);
}
/** A Fargate-compatible definition with everything filled in but the named members replaced. */
private static String fargateTaskDefinition(String family, String extraMembers) {
return "{\"family\":\"" + family + "\",\"requiresCompatibilities\":[\"FARGATE\"],"
+ "\"networkMode\":\"awsvpc\",\"cpu\":\"256\",\"memory\":\"512\","
+ "\"containerDefinitions\":[{\"name\":\"app\",\"image\":\"nginx:latest\"}]"
+ extraMembers + "}";
}
@Test
void registerTaskDefinitionRoundTripsEphemeralStorageAndPidMode() {
register(fargateTaskDefinition("fargate-ephemeral",
",\"ephemeralStorage\":{\"sizeInGiB\":50},\"pidMode\":\"task\""), 200);
call("DescribeTaskDefinition", "{\"taskDefinition\":\"fargate-ephemeral\"}", 200)
.then()
.body("taskDefinition.ephemeralStorage.sizeInGiB", equalTo(50))
.body("taskDefinition.pidMode", equalTo("task"));
}
@Test
void registerTaskDefinitionRoundTripsMembersFlociDoesNotActOn() {
// proxyConfiguration and the container's ulimits, linuxParameters and resourceRequirements
// have no local behaviour, but a client that wrote them reads them back or sees drift.
register("{\"family\":\"fargate-passthrough\",\"requiresCompatibilities\":[\"FARGATE\"],"
+ "\"networkMode\":\"awsvpc\",\"cpu\":\"512\",\"memory\":\"1024\","
+ "\"proxyConfiguration\":{\"type\":\"APPMESH\",\"containerName\":\"envoy\","
+ "\"properties\":[{\"name\":\"AppPorts\",\"value\":\"8080\"}]},"
+ "\"containerDefinitions\":[{\"name\":\"app\",\"image\":\"nginx:latest\","
+ "\"ulimits\":[{\"name\":\"nofile\",\"softLimit\":1024,\"hardLimit\":4096}],"
+ "\"linuxParameters\":{\"initProcessEnabled\":true},"
+ "\"systemControls\":[{\"namespace\":\"net.core.somaxconn\",\"value\":\"1024\"}]}]}", 200);
call("DescribeTaskDefinition", "{\"taskDefinition\":\"fargate-passthrough\"}", 200)
.then()
.body("taskDefinition.proxyConfiguration.type", equalTo("APPMESH"))
.body("taskDefinition.proxyConfiguration.properties[0].name", equalTo("AppPorts"))
.body("taskDefinition.containerDefinitions[0].ulimits[0].name", equalTo("nofile"))
.body("taskDefinition.containerDefinitions[0].ulimits[0].softLimit", equalTo(1024))
.body("taskDefinition.containerDefinitions[0].linuxParameters.initProcessEnabled",
equalTo(true))
.body("taskDefinition.containerDefinitions[0].systemControls[0].namespace",
equalTo("net.core.somaxconn"));
}
@Test
void registerTaskDefinitionRoundTripsTypedContainerMembers() {
register("{\"family\":\"fargate-container-members\",\"requiresCompatibilities\":[\"FARGATE\"],"
+ "\"networkMode\":\"awsvpc\",\"cpu\":\"256\",\"memory\":\"512\","
+ "\"containerDefinitions\":["
+ "{\"name\":\"init\",\"image\":\"busybox\",\"essential\":false},"
+ "{\"name\":\"app\",\"image\":\"nginx:latest\",\"user\":\"1000:1000\","
+ "\"workingDirectory\":\"/srv\",\"readonlyRootFilesystem\":true,\"stopTimeout\":30,"
+ "\"startTimeout\":120,\"dockerLabels\":{\"team\":\"platform\"},"
+ "\"environmentFiles\":[{\"value\":\"arn:aws:s3:::cfg/app.env\",\"type\":\"s3\"}],"
+ "\"repositoryCredentials\":{\"credentialsParameter\":\"arn:aws:secretsmanager:us-east-1:"
+ "000000000000:secret:registry\"},"
+ "\"dependsOn\":[{\"containerName\":\"init\",\"condition\":\"SUCCESS\"}]}]}", 200);
call("DescribeTaskDefinition", "{\"taskDefinition\":\"fargate-container-members\"}", 200)
.then()
.body("taskDefinition.containerDefinitions[1].user", equalTo("1000:1000"))
.body("taskDefinition.containerDefinitions[1].workingDirectory", equalTo("/srv"))
.body("taskDefinition.containerDefinitions[1].readonlyRootFilesystem", equalTo(true))
.body("taskDefinition.containerDefinitions[1].stopTimeout", equalTo(30))
.body("taskDefinition.containerDefinitions[1].startTimeout", equalTo(120))
.body("taskDefinition.containerDefinitions[1].dockerLabels.team", equalTo("platform"))
.body("taskDefinition.containerDefinitions[1].environmentFiles", hasSize(1))
.body("taskDefinition.containerDefinitions[1].environmentFiles[0].type", equalTo("s3"))
.body("taskDefinition.containerDefinitions[1].repositoryCredentials.credentialsParameter",
containsString("secret:registry"))
.body("taskDefinition.containerDefinitions[1].dependsOn[0].containerName", equalTo("init"))
.body("taskDefinition.containerDefinitions[1].dependsOn[0].condition", equalTo("SUCCESS"));
}
@Test
void registerTaskDefinitionReportsRegistrationMetadata() {
Response response = register(fargateTaskDefinition("fargate-registered-at", ""), 200);
assertTrue(response.jsonPath().getDouble("taskDefinition.registeredAt") > 0,
"registeredAt must be reported as an epoch timestamp");
assertTrue(response.jsonPath().getString("taskDefinition.registeredBy").startsWith("arn:"),
"registeredBy must be an ARN");
}
@Test
void registerTaskDefinitionRejectsEphemeralStorageOutsideTheFargateRange() {
register(fargateTaskDefinition("fargate-storage-small", ",\"ephemeralStorage\":{\"sizeInGiB\":10}"), 400)
.then().body("message", containsString("ephemeral storage"));
register(fargateTaskDefinition("fargate-storage-large", ",\"ephemeralStorage\":{\"sizeInGiB\":300}"), 400)
.then().body("message", containsString("ephemeral storage"));
}
@Test
void registerTaskDefinitionRejectsParametersFargateDoesNotSupport() {
String prefix = "{\"family\":\"fargate-unsupported\",\"requiresCompatibilities\":[\"FARGATE\"],"
+ "\"networkMode\":\"awsvpc\",\"cpu\":\"256\",\"memory\":\"512\",\"containerDefinitions\":"
+ "[{\"name\":\"app\",\"image\":\"nginx:latest\",";
register(prefix + "\"privileged\":true}]}", 400)
.then().body("message", containsString("privileged"));
register(prefix + "\"links\":[\"other\"]}]}", 400)
.then().body("message", containsString("links"));
register(prefix + "\"disableNetworking\":true}]}", 400)
.then().body("message", containsString("disableNetworking"));
register(prefix + "\"dnsServers\":[\"10.0.0.2\"]}]}", 400)
.then().body("message", containsString("dnsServers"));
register(fargateTaskDefinition("fargate-ipc", ",\"ipcMode\":\"host\""), 400)
.then().body("message", containsString("ipcMode"));
register(fargateTaskDefinition("fargate-host-volume",
",\"volumes\":[{\"name\":\"data\",\"host\":{\"sourcePath\":\"/srv/data\"}}]"), 400);
}
@Test
void registerTaskDefinitionAllowsThoseParametersOnEc2() {
// The same members are legal on an EC2-compatible definition, so the rejection above must
// be scoped to Fargate rather than applied to every task definition.
register("{\"family\":\"ec2-unsupported-on-fargate\",\"networkMode\":\"bridge\","
+ "\"containerDefinitions\":[{\"name\":\"app\",\"image\":\"nginx:latest\","
+ "\"privileged\":true,\"dnsServers\":[\"10.0.0.2\"],"
+ "\"resourceRequirements\":[{\"type\":\"GPU\",\"value\":\"1\"}]}]}", 200)
.then()
.body("taskDefinition.containerDefinitions[0].privileged", equalTo(true))
.body("taskDefinition.containerDefinitions[0].dnsServers[0]", equalTo("10.0.0.2"))
.body("taskDefinition.containerDefinitions[0].resourceRequirements[0].type",
equalTo("GPU"));
}
@Test
void registerTaskDefinitionRejectsADependencyOnAContainerThatIsNotThere() {
register("{\"family\":\"fargate-bad-dependency\",\"requiresCompatibilities\":[\"FARGATE\"],"
+ "\"networkMode\":\"awsvpc\",\"cpu\":\"256\",\"memory\":\"512\","
+ "\"containerDefinitions\":[{\"name\":\"app\",\"image\":\"nginx:latest\","
+ "\"dependsOn\":[{\"containerName\":\"sidecar\",\"condition\":\"START\"}]}]}", 400)
.then().body("message", containsString("sidecar"));
}
@Test
void registerTaskDefinitionRejectsAnUnknownDependencyCondition() {
register("{\"family\":\"fargate-bad-condition\",\"requiresCompatibilities\":[\"FARGATE\"],"
+ "\"networkMode\":\"awsvpc\",\"cpu\":\"256\",\"memory\":\"512\","
+ "\"containerDefinitions\":[{\"name\":\"init\",\"image\":\"busybox\"},"
+ "{\"name\":\"app\",\"image\":\"nginx:latest\","
+ "\"dependsOn\":[{\"containerName\":\"init\",\"condition\":\"READY\"}]}]}", 400)
.then().body("message", containsString("READY"));
}
@Test
void registerTaskDefinitionAcceptsTheLargestFargateTaskSize() {
register("{\"family\":\"fargate-16vcpu\",\"requiresCompatibilities\":[\"FARGATE\"],"
+ "\"networkMode\":\"awsvpc\",\"cpu\":\"16384\",\"memory\":\"122880\","
+ "\"containerDefinitions\":[{\"name\":\"app\",\"image\":\"nginx:latest\"}]}", 200);
}
@Test
void registerTaskDefinitionRejectsAMemorySizeOffTheFargateStep() {
// 8 vCPU goes from 16 GB up in 4 GB steps, so 18 GB is not a configuration that exists.
Response response = register("{\"family\":\"fargate-8vcpu-bad\",\"requiresCompatibilities\":[\"FARGATE\"],"
+ "\"networkMode\":\"awsvpc\",\"cpu\":\"8192\",\"memory\":\"18432\","
+ "\"containerDefinitions\":[{\"name\":\"app\",\"image\":\"nginx:latest\"}]}", 400);
assertEquals("No Fargate configuration exists for given values.",
response.jsonPath().getString("message"));
}
@Test
void registerTaskDefinitionRejectsSubVcpuSizesForWindowsOnFargate() {
register("{\"family\":\"fargate-windows\",\"requiresCompatibilities\":[\"FARGATE\"],"
+ "\"networkMode\":\"awsvpc\",\"cpu\":\"512\",\"memory\":\"1024\","
+ "\"runtimePlatform\":{\"operatingSystemFamily\":\"WINDOWS_SERVER_2019_CORE\","
+ "\"cpuArchitecture\":\"X86_64\"},"
+ "\"containerDefinitions\":[{\"name\":\"app\",\"image\":\"nginx:latest\"}]}", 400);
register("{\"family\":\"fargate-windows-ok\",\"requiresCompatibilities\":[\"FARGATE\"],"
+ "\"networkMode\":\"awsvpc\",\"cpu\":\"1024\",\"memory\":\"2048\","
+ "\"runtimePlatform\":{\"operatingSystemFamily\":\"WINDOWS_SERVER_2019_CORE\","
+ "\"cpuArchitecture\":\"X86_64\"},"
+ "\"containerDefinitions\":[{\"name\":\"app\",\"image\":\"nginx:latest\"}]}", 200);
}
}
@@ -0,0 +1,264 @@
package io.github.hectorvent.floci.services.ecs;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.Response;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.util.List;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* RunTask and DescribeTasks for the Fargate launch type: the members an SDK client, a waiter or
* the CLI reads off a task, and the placement rules that decide whether a task runs on FARGATE or
* FARGATE_SPOT.
*/
@QuarkusTest
class EcsFargateTaskIntegrationTest {
private static final String TARGET = "AmazonEC2ContainerServiceV20141113.";
private static final String CT = "application/x-amz-json-1.1";
private static final String CLUSTER = "fargate-task-cluster";
private static final String SUBNET = "subnet-default-us-east-1-a";
private static final String NETWORK =
"\"networkConfiguration\":{\"awsvpcConfiguration\":{\"subnets\":[\"" + SUBNET + "\"]}}";
@BeforeAll
static void configure() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
private static Response call(String action, String body, int expectedStatus) {
return given().contentType(CT).header("X-Amz-Target", TARGET + action)
.body(body)
.when().post("/")
.then().statusCode(expectedStatus)
.extract().response();
}
private static String seed(String family) {
call("CreateCluster", "{\"clusterName\":\"" + CLUSTER + "\"}", 200);
call("RegisterTaskDefinition", "{\"family\":\"" + family + "\","
+ "\"requiresCompatibilities\":[\"FARGATE\"],\"networkMode\":\"awsvpc\","
+ "\"cpu\":\"256\",\"memory\":\"512\","
+ "\"containerDefinitions\":[{\"name\":\"app\",\"image\":\"nginx:latest\"}]}", 200);
return family;
}
private static Response runTask(String family, String extraMembers) {
return call("RunTask", "{\"cluster\":\"" + CLUSTER + "\",\"taskDefinition\":\"" + family + "\","
+ "\"launchType\":\"FARGATE\"," + NETWORK + extraMembers + "}", 200);
}
@Test
void runTaskReportsThePlatformAndConnectivityMembersOfAFargateTask() {
String family = seed("fargate-task-platform");
Response response = runTask(family, "");
response.then()
.body("tasks", hasSize(1))
.body("tasks[0].launchType", equalTo("FARGATE"))
.body("tasks[0].platformVersion", equalTo("1.4.0"))
.body("tasks[0].platformFamily", equalTo("Linux"))
.body("tasks[0].connectivity", equalTo("CONNECTED"))
.body("tasks[0].healthStatus", equalTo("UNKNOWN"))
.body("tasks[0].enableExecuteCommand", equalTo(false))
.body("tasks[0].ephemeralStorage.sizeInGiB", equalTo(20))
.body("tasks[0].group", equalTo("family:" + family))
.body("tasks[0].cpu", equalTo("256"))
.body("tasks[0].memory", equalTo("512"))
.body("tasks[0].attributes[0].name", equalTo("ecs.cpu-architecture"));
assertTrue(response.jsonPath().getLong("tasks[0].version") >= 1, "version must be reported");
assertTrue(response.jsonPath().getDouble("tasks[0].connectivityAt") > 0,
"connectivityAt must be reported");
}
@Test
void runTaskGivesAnAwsvpcTaskItsOwnEni() {
String family = seed("fargate-task-eni");
Response response = runTask(family, "");
// The ENI is what a client waits on to find a Fargate task's address, so it is reported
// whether or not security-group enforcement is on and whether or not Docker is in play.
response.then()
.body("tasks[0].attachments", hasSize(1))
.body("tasks[0].attachments[0].type", equalTo("ElasticNetworkInterface"))
.body("tasks[0].attachments[0].status", equalTo("ATTACHED"))
.body("tasks[0].availabilityZone", equalTo("us-east-1a"));
String eniId = attachmentDetail(response, "networkInterfaceId");
String privateIp = attachmentDetail(response, "privateIPv4Address");
assertTrue(eniId != null && eniId.startsWith("eni-"), "the task must report its ENI id");
assertTrue(privateIp != null && !privateIp.isBlank(), "the task must report a private address");
assertEquals(SUBNET, attachmentDetail(response, "subnetId"));
// The ENI is a real one in EC2, in the subnet the task asked for, and the running task
// holds it: DescribeNetworkInterfaces reports an interface that is not attached as
// available and one that is as in-use, and a task's is not free for a caller to take.
given().contentType("application/x-www-form-urlencoded")
.formParam("Action", "DescribeNetworkInterfaces")
.formParam("Version", "2016-11-15")
.formParam("NetworkInterfaceId.1", eniId)
.when().post("/")
.then().statusCode(200)
.body(containsString(SUBNET))
.body("DescribeNetworkInterfacesResponse.networkInterfaceSet.item.status",
equalTo("in-use"))
// No attachment is reported: every member of one names an instance, and a Fargate
// task has none in the account.
.body(not(containsString("<attachment>")));
String taskArn = response.jsonPath().getString("tasks[0].taskArn");
call("StopTask", "{\"cluster\":\"" + CLUSTER + "\",\"task\":\"" + taskArn + "\"}", 200)
.then().body("task.attachments[0].status", equalTo("DELETED"));
// Stopping the task releases the interface rather than leaving it behind in the account.
given().contentType("application/x-www-form-urlencoded")
.formParam("Action", "DescribeNetworkInterfaces")
.formParam("Version", "2016-11-15")
.formParam("NetworkInterfaceId.1", eniId)
.when().post("/")
.then().statusCode(400)
.body(containsString("InvalidNetworkInterfaceID.NotFound"));
}
private static String attachmentDetail(Response response, String name) {
List<String> values = response.jsonPath()
.getList("tasks[0].attachments[0].details.findAll { it.name == '" + name + "' }.value");
return values.isEmpty() ? null : values.getFirst();
}
@Test
void runTaskRejectsASubnetThatDoesNotExist() {
String family = seed("fargate-task-bad-subnet");
call("RunTask", "{\"cluster\":\"" + CLUSTER + "\",\"taskDefinition\":\"" + family
+ "\",\"launchType\":\"FARGATE\",\"networkConfiguration\":{\"awsvpcConfiguration\":"
+ "{\"subnets\":[\"subnet-does-not-exist\"]}}}", 400)
.then().body("message", containsString("subnet-does-not-exist"));
}
@Test
void runTaskResolvesTheLatestPlatformVersionToAConcreteOne() {
String family = seed("fargate-task-latest");
runTask(family, ",\"platformVersion\":\"LATEST\"").then()
.body("tasks[0].platformVersion", equalTo("1.4.0"));
runTask(family, ",\"platformVersion\":\"1.3.0\"").then()
.body("tasks[0].platformVersion", equalTo("1.3.0"));
}
@Test
void runTaskEchoesTheOverridesItWasGiven() {
String family = seed("fargate-task-overrides");
runTask(family, ",\"overrides\":{\"cpu\":\"512\",\"memory\":\"1024\","
+ "\"ephemeralStorage\":{\"sizeInGiB\":40},"
+ "\"containerOverrides\":[{\"name\":\"app\",\"command\":[\"sleep\",\"1\"],"
+ "\"environment\":[{\"name\":\"MODE\",\"value\":\"test\"}]}]}").then()
.body("tasks[0].cpu", equalTo("512"))
.body("tasks[0].memory", equalTo("1024"))
.body("tasks[0].ephemeralStorage.sizeInGiB", equalTo(40))
.body("tasks[0].overrides.cpu", equalTo("512"))
.body("tasks[0].overrides.ephemeralStorage.sizeInGiB", equalTo(40))
.body("tasks[0].overrides.containerOverrides[0].name", equalTo("app"))
.body("tasks[0].overrides.containerOverrides[0].command[0]", equalTo("sleep"))
.body("tasks[0].overrides.containerOverrides[0].environment[0].name", equalTo("MODE"));
}
@Test
void runTaskCarriesEnableExecuteCommandAndTags() {
String family = seed("fargate-task-exec");
runTask(family, ",\"enableExecuteCommand\":true,\"tags\":[{\"key\":\"owner\",\"value\":\"platform\"}]")
.then()
.body("tasks[0].enableExecuteCommand", equalTo(true))
.body("tasks[0].tags[0].key", equalTo("owner"))
.body("tasks[0].tags[0].value", equalTo("platform"));
}
@Test
void stopTaskReportsTheStopCodeAndAdvancesTheVersion() {
String family = seed("fargate-task-stop");
Response launched = runTask(family, "");
String taskArn = launched.jsonPath().getString("tasks[0].taskArn");
long versionWhenRunning = launched.jsonPath().getLong("tasks[0].version");
call("StopTask", "{\"cluster\":\"" + CLUSTER + "\",\"task\":\"" + taskArn
+ "\",\"reason\":\"done\"}", 200).then()
.body("task.stopCode", equalTo("UserInitiated"))
.body("task.stoppedReason", equalTo("done"));
Response described = call("DescribeTasks", "{\"cluster\":\"" + CLUSTER + "\",\"tasks\":[\""
+ taskArn + "\"]}", 200);
described.then()
.body("tasks[0].lastStatus", equalTo("STOPPED"))
.body("tasks[0].stopCode", equalTo("UserInitiated"));
assertTrue(described.jsonPath().getLong("tasks[0].version") > versionWhenRunning,
"stopping a task must advance its version");
assertTrue(described.jsonPath().getDouble("tasks[0].executionStoppedAt") > 0,
"executionStoppedAt must be reported once the task has stopped");
}
@Test
void runTaskPlacesThroughACapacityProviderStrategyByBaseThenWeight() {
String family = seed("fargate-task-strategy");
Response response = call("RunTask", "{\"cluster\":\"" + CLUSTER + "\",\"taskDefinition\":\""
+ family + "\",\"count\":5," + NETWORK + ",\"capacityProviderStrategy\":["
+ "{\"capacityProvider\":\"FARGATE\",\"base\":1,\"weight\":1},"
+ "{\"capacityProvider\":\"FARGATE_SPOT\",\"weight\":3}]}", 200);
List<String> providers = response.jsonPath().getList("tasks.capacityProviderName");
assertEquals(5, providers.size());
assertEquals(2, providers.stream().filter("FARGATE"::equals).count(),
"one task for the base plus its quarter of the remaining four");
assertEquals(3, providers.stream().filter("FARGATE_SPOT"::equals).count(),
"three quarters of the remaining four");
// A task reports both the provider it was placed through and the launch type that
// provider resolves to, unlike a service, which reports only one of the two.
response.then().body("tasks[0].launchType", equalTo("FARGATE"));
}
@Test
void runTaskRejectsALaunchTypeAndACapacityProviderStrategyTogether() {
String family = seed("fargate-task-both");
call("RunTask", "{\"cluster\":\"" + CLUSTER + "\",\"taskDefinition\":\"" + family
+ "\",\"launchType\":\"FARGATE\"," + NETWORK + ",\"capacityProviderStrategy\":"
+ "[{\"capacityProvider\":\"FARGATE_SPOT\",\"weight\":1}]}", 400)
.then().body("message", containsString("cannot specify both"));
}
@Test
void runTaskRejectsAnUnknownCapacityProvider() {
String family = seed("fargate-task-unknown-provider");
call("RunTask", "{\"cluster\":\"" + CLUSTER + "\",\"taskDefinition\":\"" + family + "\","
+ NETWORK + ",\"capacityProviderStrategy\":"
+ "[{\"capacityProvider\":\"NOT_A_PROVIDER\",\"weight\":1}]}", 400)
.then().body("message", containsString("NOT_A_PROVIDER"));
}
@Test
void runTaskRejectsAnAwsvpcTaskWithNoNetworkConfiguration() {
String family = seed("fargate-task-no-network");
call("RunTask", "{\"cluster\":\"" + CLUSTER + "\",\"taskDefinition\":\"" + family
+ "\",\"launchType\":\"FARGATE\"}", 400)
.then().body("message", containsString("Network Configuration must be provided"));
}
@Test
void createServiceOnACapacityProviderStrategyReportsItInsteadOfALaunchType() {
String family = seed("fargate-service-strategy");
call("CreateService", "{\"cluster\":\"" + CLUSTER + "\",\"serviceName\":\"fargate-spot-svc\","
+ "\"taskDefinition\":\"" + family + "\",\"desiredCount\":0," + NETWORK + ","
+ "\"capacityProviderStrategy\":[{\"capacityProvider\":\"FARGATE_SPOT\",\"weight\":1}]}", 200)
.then()
.body("service.capacityProviderStrategy[0].capacityProvider", equalTo("FARGATE_SPOT"))
.body("service.capacityProviderStrategy[0].weight", equalTo(1))
.body("service.launchType", nullValue());
}
}
@@ -452,6 +452,7 @@ class EcsIntegrationTest {
"cluster": "%s",
"taskDefinition": "%s",
"launchType": "FARGATE",
"networkConfiguration": {"awsvpcConfiguration": {"subnets": ["subnet-default-us-east-1-a"]}},
"count": 1
}
""".formatted(CLUSTER_NAME, TASK_DEF_FAMILY))
@@ -541,6 +542,7 @@ class EcsIntegrationTest {
"cluster": "%s",
"taskDefinition": "empty-containers-task",
"launchType": "FARGATE",
"networkConfiguration": {"awsvpcConfiguration": {"subnets": ["subnet-default-us-east-1-a"]}},
"count": 1
}
""".formatted(CLUSTER_NAME))
@@ -694,6 +696,7 @@ class EcsIntegrationTest {
"taskDefinition": "%s",
"desiredCount": 1,
"launchType": "FARGATE",
"networkConfiguration": {"awsvpcConfiguration": {"subnets": ["subnet-default-us-east-1-a"]}},
"tags": [
{"key": "Environment", "value": "dev"},
{"key": "Project", "value": "project1"}
@@ -787,7 +790,8 @@ class EcsIntegrationTest {
"serviceName": "%s",
"taskDefinition": "%s",
"desiredCount": 2,
"launchType": "FARGATE"
"launchType": "FARGATE",
"networkConfiguration": {"awsvpcConfiguration": {"subnets": ["subnet-default-us-east-1-a"]}}
}
""".formatted(CLUSTER_NAME, SERVICE_NAME, TASK_DEF_FAMILY))
.when()
@@ -808,7 +812,8 @@ class EcsIntegrationTest {
"serviceName": "%s",
"taskDefinition": "%s",
"desiredCount": 99,
"launchType": "FARGATE"
"launchType": "FARGATE",
"networkConfiguration": {"awsvpcConfiguration": {"subnets": ["subnet-default-us-east-1-a"]}}
}
""".formatted(CLUSTER_NAME, SERVICE_NAME, TASK_DEF_FAMILY))
.when()
@@ -831,7 +836,8 @@ class EcsIntegrationTest {
"serviceName": "negative-count-svc",
"taskDefinition": "%s",
"desiredCount": -5,
"launchType": "FARGATE"
"launchType": "FARGATE",
"networkConfiguration": {"awsvpcConfiguration": {"subnets": ["subnet-default-us-east-1-a"]}}
}
""".formatted(CLUSTER_NAME, TASK_DEF_FAMILY))
.when()
@@ -873,7 +879,8 @@ class EcsIntegrationTest {
"serviceName": "zero-count-svc",
"taskDefinition": "%s",
"desiredCount": 0,
"launchType": "FARGATE"
"launchType": "FARGATE",
"networkConfiguration": {"awsvpcConfiguration": {"subnets": ["subnet-default-us-east-1-a"]}}
}
""".formatted(CLUSTER_NAME, TASK_DEF_FAMILY))
.when()
@@ -1074,7 +1081,8 @@ class EcsIntegrationTest {
"serviceName": "%s",
"taskDefinition": "review-td",
"desiredCount": 1,
"launchType": "FARGATE"
"launchType": "FARGATE",
"networkConfiguration": {"awsvpcConfiguration": {"subnets": ["subnet-default-us-east-1-a"]}}
}
""".formatted(REVIEW_CLUSTER, REVIEW_SERVICE))
.when()
@@ -1160,6 +1168,7 @@ class EcsIntegrationTest {
"taskDefinition": "review-td",
"desiredCount": 1,
"launchType": "FARGATE",
"networkConfiguration": {"awsvpcConfiguration": {"subnets": ["subnet-default-us-east-1-a"]}},
"loadBalancers": [
{
"targetGroupArn": "arn:aws:elasticloadbalancing:us-east-1:000000000000:targetgroup/tg-a/1234",
@@ -1184,6 +1193,7 @@ class EcsIntegrationTest {
"taskDefinition": "review-td",
"desiredCount": 1,
"launchType": "FARGATE",
"networkConfiguration": {"awsvpcConfiguration": {"subnets": ["subnet-default-us-east-1-a"]}},
"loadBalancers": [
{
"targetGroupArn": "arn:aws:elasticloadbalancing:us-east-1:000000000000:targetgroup/tg-DIFFERENT/9999",
@@ -7,12 +7,15 @@ import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.ec2.Ec2Service;
import io.github.hectorvent.floci.services.ecs.container.EcsContainerManager;
import io.github.hectorvent.floci.services.ecs.model.Attribute;
import io.github.hectorvent.floci.services.ecs.model.AwsVpcConfiguration;
import io.github.hectorvent.floci.services.ecs.model.ContainerDefinition;
import io.github.hectorvent.floci.services.ecs.model.EcsCluster;
import io.github.hectorvent.floci.services.ecs.model.EcsServiceModel;
import io.github.hectorvent.floci.services.ecs.model.LaunchType;
import io.github.hectorvent.floci.services.ecs.model.NetworkConfiguration;
import io.github.hectorvent.floci.services.ecs.model.NetworkMode;
import io.github.hectorvent.floci.services.ecs.model.TaskDefinition;
import org.junit.jupiter.api.Test;
@@ -47,7 +50,7 @@ class EcsServicePersistenceTest {
NetworkMode.awsvpc, "256", "512", null, null, List.of("FARGATE"),
Map.of("tier", "web"), REGION);
EcsServiceModel svc = first.createService("app-cluster", "web-svc", td.getTaskDefinitionArn(),
0, LaunchType.FARGATE, List.of(), null, Map.of("team", "payments"), REGION);
0, LaunchType.FARGATE, List.of(), awsvpcConfiguration(), Map.of("team", "payments"), REGION);
first.putAttributes("app-cluster",
List.of(new Attribute("stack", "prod", "container-instance", "ci-1")), REGION);
first.putAccountSetting("containerInsights", "enabled");
@@ -104,6 +107,15 @@ class EcsServicePersistenceTest {
return cd;
}
/** An awsvpc service needs the subnets its tasks get an ENI in, as it does on AWS. */
private static NetworkConfiguration awsvpcConfiguration() {
AwsVpcConfiguration awsvpc = new AwsVpcConfiguration();
awsvpc.setSubnets(List.of(Ec2Service.defaultSubnetId(REGION, "a")));
NetworkConfiguration networkConfiguration = new NetworkConfiguration();
networkConfiguration.setAwsvpcConfiguration(awsvpc);
return networkConfiguration;
}
private static EcsService serviceWithStorage(StorageFactory storage) {
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
when(config.services().ecs().mock()).thenReturn(true);
@@ -36,6 +36,7 @@ import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.RETURNS_SELF;
import static org.mockito.Mockito.mock;
@@ -141,7 +142,7 @@ class EcsContainerManagerSecurityGroupTest {
}
@Test
void stopTaskUnregistersEni() {
void stopTaskUnregistersEniAndReleasingTheTaskNetworkDeletesIt() {
when(containerDetector.isRunningInContainer()).thenReturn(false);
when(firewallManager.enabled()).thenReturn(true);
when(firewallManager.createNamespace(eq("ecs"), eq("abc123"), any(), any(), any(), any()))
@@ -162,11 +163,17 @@ class EcsContainerManagerSecurityGroupTest {
DockerClient stopClient = mock(DockerClient.class, RETURNS_DEEP_STUBS);
when(lifecycleManager.getDockerClient()).thenReturn(dockerClient, dockerClient, stopClient);
EcsTaskHandle handle = manager.startTask(awsvpcTask(), awsvpcTaskDef(List.of()),
EcsTask task = awsvpcTask();
EcsTaskHandle handle = manager.startTask(task, awsvpcTaskDef(List.of()),
List.of(), "us-east-1");
manager.stopTaskAndCollectExitCodes(handle);
verify(firewallManager).unregister("eni-1");
// Stopping the containers tears down their firewall registration, but the ENI belongs to
// the task: it lives until the task itself is released.
verify(firewallManager, atLeastOnce()).unregister("eni-1");
verify(ec2Service, never()).deleteNetworkInterface(any(), any());
manager.releaseTaskNetwork(task, "us-east-1");
verify(ec2Service).deleteNetworkInterface("us-east-1", "eni-1");
}
@@ -69,8 +69,8 @@ class EventBridgeEcsRunTaskIntegrationTest {
"Group": "eb-ecs-group-%s",
"NetworkConfiguration": {
"awsvpcConfiguration": {
"Subnets": ["subnet-1", "subnet-2"],
"SecurityGroups": ["sg-1"],
"Subnets": ["subnet-default-us-east-1-a", "subnet-default-us-east-1-b"],
"SecurityGroups": ["sg-default-us-east-1"],
"AssignPublicIp": "ENABLED"
}
}
@@ -100,9 +100,9 @@ class EventBridgeEcsRunTaskIntegrationTest {
.body("Targets[0].EcsParameters.LaunchType", equalTo("FARGATE"))
.body("Targets[0].EcsParameters.Group", equalTo("eb-ecs-group-" + suffix))
.body("Targets[0].EcsParameters.NetworkConfiguration.awsvpcConfiguration.Subnets",
hasItem("subnet-1"))
hasItem("subnet-default-us-east-1-a"))
.body("Targets[0].EcsParameters.NetworkConfiguration.awsvpcConfiguration.SecurityGroups",
hasItem("sg-1"))
hasItem("sg-default-us-east-1"))
.body("Targets[0].EcsParameters.NetworkConfiguration.awsvpcConfiguration.AssignPublicIp",
equalTo("ENABLED"));