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

@@ -8309,16 +8309,57 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
return ni;
}
/** Deletes a standalone ENI. AWS refuses while it is still attached, floci-kt9. */
/**
* Deletes a standalone ENI. AWS refuses while it is still attached, floci-kt9, and equally
* while a service holds it: {@link #holdNetworkInterfaceForService} leaves no attachment
* behind, so the status is what says the interface is spoken for.
*/
public void deleteNetworkInterface(String region, String networkInterfaceId) {
NetworkInterface ni = requireStandaloneNetworkInterface(region, networkInterfaceId);
if (ni.getAttachment() != null) {
if (ni.getAttachment() != null || "in-use".equals(ni.getStatus())) {
throw new AwsException("InvalidParameterValue",
"Network interface '" + networkInterfaceId + "' is currently in use", 400);
}
networkInterfaces.delete(key(region, networkInterfaceId));
}
/**
* Marks an ENI as held by an AWS service rather than by an instance in this account, the state
* a running ECS task's interface is in. DescribeNetworkInterfaces documents the status rule
* this rests on: an interface that is not attached is {@code available}, one that is attached
* is {@code in-use}, and AWS does not let the account delete a task's interface while the task
* runs.
*
* <p>No attachment is synthesised. Every member AWS documents on one describes an instance
* ({@code instanceId}, {@code instanceOwnerId} "The AWS account ID of the owner of the
* instance", {@code deviceIndex} "The device index ... on the instance"), and a task has no
* instance in the account to name there.
*/
public void holdNetworkInterfaceForService(String region, String networkInterfaceId) {
NetworkInterface ni = requireStandaloneNetworkInterface(region, networkInterfaceId);
if (ni.getAttachment() != null) {
throw new AwsException("InvalidNetworkInterface.InUse",
"Interface: '" + networkInterfaceId + "' is currently in use.", 400);
}
ni.setStatus("in-use");
networkInterfaces.put(key(region, networkInterfaceId), ni);
}
/**
* Returns a service-held ENI to {@code available}, the mirror of
* {@link #holdNetworkInterfaceForService}. Silent on an interface that is already gone, or one
* an instance holds, so a teardown that runs twice is harmless and cannot free an attachment
* that AttachNetworkInterface owns.
*/
public void releaseNetworkInterfaceFromService(String region, String networkInterfaceId) {
NetworkInterface ni = networkInterfaces.get(key(region, networkInterfaceId)).orElse(null);
if (ni == null || ni.getAttachment() != null) {
return;
}
ni.setStatus("available");
networkInterfaces.put(key(region, networkInterfaceId), ni);
}
/**
* Attaches a standalone ENI to a running/stopped instance at the given device index,
* the attach-eni example's runtime pattern (its user-data script calls this via the AWS CLI
@@ -6,13 +6,17 @@ import io.github.hectorvent.floci.services.ecs.container.HostVolumePolicy;
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.CapacityProvider;
import io.github.hectorvent.floci.services.ecs.model.CapacityProviderStrategyItem;
import io.github.hectorvent.floci.services.ecs.model.ClusterSetting;
import io.github.hectorvent.floci.services.ecs.model.ContainerDefinition;
import io.github.hectorvent.floci.services.ecs.model.ContainerDependency;
import io.github.hectorvent.floci.services.ecs.model.ContainerInstance;
import io.github.hectorvent.floci.services.ecs.model.ContainerOverride;
import io.github.hectorvent.floci.services.ecs.model.CreateClusterRequest;
import io.github.hectorvent.floci.services.ecs.model.CreateServiceRequest;
import io.github.hectorvent.floci.services.ecs.model.CreateTaskSetRequest;
import io.github.hectorvent.floci.services.ecs.model.EnvironmentFile;
import io.github.hectorvent.floci.services.ecs.model.EphemeralStorage;
import io.github.hectorvent.floci.services.ecs.model.FirelensConfiguration;
import io.github.hectorvent.floci.services.ecs.model.HealthCheck;
import io.github.hectorvent.floci.services.ecs.model.EcsCluster;
@@ -35,9 +39,10 @@ import io.github.hectorvent.floci.services.ecs.model.ServiceDeployment;
import io.github.hectorvent.floci.services.ecs.model.ServiceRevision;
import io.github.hectorvent.floci.services.ecs.model.Secret;
import io.github.hectorvent.floci.services.ecs.model.TaskDefinition;
import io.github.hectorvent.floci.services.ecs.model.TaskOverride;
import io.github.hectorvent.floci.services.ecs.model.TaskSet;
import io.github.hectorvent.floci.services.ecs.model.UpdateServiceRequest;
import io.github.hectorvent.floci.services.ecs.model.EfsVolumeConfiguration;
import io.github.hectorvent.floci.services.ecs.model.UpdateServiceRequest;
import io.github.hectorvent.floci.services.ecs.model.Volume;
import io.github.hectorvent.floci.services.ecs.model.VolumeFrom;
import com.fasterxml.jackson.databind.JsonNode;
@@ -49,11 +54,13 @@ import jakarta.inject.Inject;
import jakarta.ws.rs.core.Response;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
@ApplicationScoped
public class EcsJsonHandler {
@@ -87,14 +94,14 @@ public class EcsJsonHandler {
case "UpdateCluster" -> handleUpdateCluster(request, region);
case "UpdateClusterSettings" -> handleUpdateClusterSettings(request, region);
case "PutClusterCapacityProviders" -> handlePutClusterCapacityProviders(request, region);
// Task Definitions
case "RegisterTaskDefinition" -> handleRegisterTaskDefinition(request, region);
case "DescribeTaskDefinition" -> handleDescribeTaskDefinition(request, region);
case "ListTaskDefinitions" -> handleListTaskDefinitions(request, region);
case "ListTaskDefinitionFamilies" -> handleListTaskDefinitionFamilies(request, region);
case "DeregisterTaskDefinition" -> handleDeregisterTaskDefinition(request, region);
case "DeleteTaskDefinitions" -> handleDeleteTaskDefinitions(request, region);
// Tasks
case "RunTask" -> handleRunTask(request, region);
case "StartTask" -> handleStartTask(request, region);
case "StopTask" -> handleStopTask(request, region);
@@ -102,53 +109,54 @@ public class EcsJsonHandler {
case "ListTasks" -> handleListTasks(request, region);
case "UpdateTaskProtection" -> handleUpdateTaskProtection(request, region);
case "GetTaskProtection" -> handleGetTaskProtection(request, region);
// Services
case "CreateService" -> handleCreateService(request, region);
case "UpdateService" -> handleUpdateService(request, region);
case "DeleteService" -> handleDeleteService(request, region);
case "DescribeServices" -> handleDescribeServices(request, region);
case "ListServices" -> handleListServices(request, region);
case "ListServicesByNamespace" -> handleListServicesByNamespace(request, region);
// Tags
case "TagResource" -> handleTagResource(request, region);
case "UntagResource" -> handleUntagResource(request, region);
case "ListTagsForResource" -> handleListTagsForResource(request, region);
// Account Settings
case "PutAccountSetting" -> handlePutAccountSetting(request, region);
case "PutAccountSettingDefault" -> handlePutAccountSettingDefault(request, region);
case "DeleteAccountSetting" -> handleDeleteAccountSetting(request, region);
case "ListAccountSettings" -> handleListAccountSettings(request, region);
// Attributes
case "PutAttributes" -> handlePutAttributes(request, region);
case "DeleteAttributes" -> handleDeleteAttributes(request, region);
case "ListAttributes" -> handleListAttributes(request, region);
// Container Instances
case "RegisterContainerInstance" -> handleRegisterContainerInstance(request, region);
case "DeregisterContainerInstance" -> handleDeregisterContainerInstance(request, region);
case "DescribeContainerInstances" -> handleDescribeContainerInstances(request, region);
case "ListContainerInstances" -> handleListContainerInstances(request, region);
case "UpdateContainerAgent" -> handleUpdateContainerAgent(request, region);
case "UpdateContainerInstancesState" -> handleUpdateContainerInstancesState(request, region);
// Capacity Providers
case "CreateCapacityProvider" -> handleCreateCapacityProvider(request, region);
case "UpdateCapacityProvider" -> handleUpdateCapacityProvider(request, region);
case "DeleteCapacityProvider" -> handleDeleteCapacityProvider(request, region);
case "DescribeCapacityProviders" -> handleDescribeCapacityProviders(request, region);
// Task Sets
case "CreateTaskSet" -> handleCreateTaskSet(request, region);
case "UpdateTaskSet" -> handleUpdateTaskSet(request, region);
case "DeleteTaskSet" -> handleDeleteTaskSet(request, region);
case "DescribeTaskSets" -> handleDescribeTaskSets(request, region);
case "UpdateServicePrimaryTaskSet" -> handleUpdateServicePrimaryTaskSet(request, region);
// Service Deployments & Revisions
case "DescribeServiceDeployments" -> handleDescribeServiceDeployments(request, region);
case "ListServiceDeployments" -> handleListServiceDeployments(request, region);
case "DescribeServiceRevisions" -> handleDescribeServiceRevisions(request, region);
// Stubs
case "SubmitTaskStateChange" -> handleSubmitTaskStateChange(request, region);
case "SubmitContainerStateChange" -> handleSubmitContainerStateChange(request, region);
case "SubmitAttachmentStateChanges" -> handleSubmitAttachmentStateChanges(request, region);
case "DiscoverPollEndpoint" -> handleDiscoverPollEndpoint(request, region);
default -> Response.status(400)
.entity(new AwsErrorResponse("UnsupportedOperation",
"Operation " + action + " is not supported."))
@@ -160,9 +168,16 @@ public class EcsJsonHandler {
private Response handleCreateCluster(JsonNode req, String region) {
CreateClusterRequest request = new CreateClusterRequest();
request.setClusterName(req.path("clusterName").asText(null));
request.setClusterName(req.has("clusterName") ? req.path("clusterName").asText() : null);
request.setTags(parseTagMap(req.path("tags")));
request.setSettings(parseClusterSettings(req.path("settings")));
if (req.has("capacityProviders")) {
request.setCapacityProviders(jsonArrayToList(req.path("capacityProviders")));
}
if (req.has("defaultCapacityProviderStrategy")) {
request.setDefaultCapacityProviderStrategy(
parseRawObjectList(req.path("defaultCapacityProviderStrategy")));
}
EcsCluster cluster = service.createCluster(request, region);
ObjectNode resp = objectMapper.createObjectNode();
resp.set("cluster", writer.clusterNode(cluster));
@@ -198,34 +213,40 @@ public class EcsJsonHandler {
}
private Response handleUpdateCluster(JsonNode req, String region) {
String clusterRef = req.path("cluster").asText();
String clusterId = req.path("cluster").asText();
List<ClusterSetting> settings = parseClusterSettings(req.path("settings"));
EcsCluster cluster = service.updateCluster(clusterRef, settings, region);
EcsCluster cluster = service.updateCluster(clusterId, settings, region);
ObjectNode resp = objectMapper.createObjectNode();
resp.set("cluster", writer.clusterNode(cluster));
return Response.ok(resp).build();
}
private Response handleUpdateClusterSettings(JsonNode req, String region) {
String clusterRef = req.path("cluster").asText();
String clusterId = req.path("cluster").asText();
List<ClusterSetting> settings = parseClusterSettings(req.path("settings"));
EcsCluster cluster = service.updateClusterSettings(clusterRef, settings, region);
EcsCluster cluster = service.updateClusterSettings(clusterId, settings, region);
ObjectNode resp = objectMapper.createObjectNode();
resp.set("cluster", writer.clusterNode(cluster));
return Response.ok(resp).build();
}
private Response handlePutClusterCapacityProviders(JsonNode req, String region) {
String clusterRef = req.path("cluster").asText();
String clusterId = req.path("cluster").asText();
List<String> providers = jsonArrayToList(req.path("capacityProviders"));
List<Map<String, Object>> defaultStrategy = parseRawObjectList(req.path("defaultCapacityProviderStrategy"));
EcsCluster cluster = service.putClusterCapacityProviders(clusterRef, providers, defaultStrategy, region);
EcsCluster cluster = service.putClusterCapacityProviders(clusterId, providers, defaultStrategy, region);
ObjectNode resp = objectMapper.createObjectNode();
resp.set("cluster", writer.clusterNode(cluster));
return Response.ok(resp).build();
}
// ── Task Definitions ──────────────────────────────────────────────────────
// ── Task definitions ──────────────────────────────────────────────────────
/** Members of RegisterTaskDefinition the parser consumes; the rest round-trips verbatim. */
private static final Set<String> TASK_DEFINITION_CONSUMED = Set.of(
"family", "containerDefinitions", "networkMode", "cpu", "memory", "taskRoleArn",
"executionRoleArn", "requiresCompatibilities", "volumes", "runtimePlatform",
"ephemeralStorage", "pidMode", "ipcMode", "tags");
private Response handleRegisterTaskDefinition(JsonNode req, String region) {
RegisterTaskDefinitionRequest request = new RegisterTaskDefinitionRequest();
@@ -235,17 +256,24 @@ public class EcsJsonHandler {
request.setCpu(req.has("cpu") ? req.path("cpu").asText() : null);
request.setMemory(req.has("memory") ? req.path("memory").asText() : null);
request.setTaskRoleArn(req.hasNonNull("taskRoleArn") ? req.path("taskRoleArn").asText() : null);
request.setExecutionRoleArn(
req.hasNonNull("executionRoleArn") ? req.path("executionRoleArn").asText() : null);
request.setRequiresCompatibilities(jsonArrayToList(req.path("requiresCompatibilities")));
request.setExecutionRoleArn(req.hasNonNull("executionRoleArn")
? req.path("executionRoleArn").asText() : null);
request.setRequiresCompatibilities(parseCompatibilities(req.path("requiresCompatibilities")));
request.setVolumes(parseVolumes(req.path("volumes")));
request.setRuntimePlatform(parseRuntimePlatform(req.path("runtimePlatform")));
request.setEphemeralStorage(parseEphemeralStorage(req.path("ephemeralStorage")));
request.setPidMode(parseChoice(req, "pidMode", PID_MODES));
request.setIpcMode(parseChoice(req, "ipcMode", IPC_MODES));
request.setTags(parseTagMap(req.path("tags")));
request.setUnparsed(EcsJsonPassthrough.capture(req, objectMapper, TASK_DEFINITION_CONSUMED));
TaskDefinition td = service.registerTaskDefinition(request, region);
ObjectNode resp = objectMapper.createObjectNode();
resp.set("taskDefinition", writer.taskDefinitionNode(td));
if (td.getTags() != null && !td.getTags().isEmpty()) {
resp.set("tags", writer.tagsNode(td.getTags()));
}
return Response.ok(resp).build();
}
@@ -254,6 +282,11 @@ public class EcsJsonHandler {
TaskDefinition td = service.describeTaskDefinition(tdRef, region);
ObjectNode resp = objectMapper.createObjectNode();
resp.set("taskDefinition", writer.taskDefinitionNode(td));
// DescribeTaskDefinition reports tags at the top level, and only when asked for them.
if (jsonArrayToList(req.path("include")).contains("TAGS")
&& td.getTags() != null && !td.getTags().isEmpty()) {
resp.set("tags", writer.tagsNode(td.getTags()));
}
return Response.ok(resp).build();
}
@@ -300,17 +333,7 @@ public class EcsJsonHandler {
// ── Tasks ─────────────────────────────────────────────────────────────────
private Response handleRunTask(JsonNode req, String region) {
RunTaskRequest request = new RunTaskRequest();
request.setCluster(req.has("cluster") ? req.path("cluster").asText() : null);
request.setTaskDefinition(req.path("taskDefinition").asText());
request.setCount(req.path("count").asInt(1));
request.setLaunchType(parseEnum(req, "launchType", LaunchType.class));
request.setGroup(req.has("group") ? req.path("group").asText() : null);
request.setStartedBy(req.has("startedBy") ? req.path("startedBy").asText() : null);
request.setContainerOverrides(
parseContainerOverrides(req.path("overrides").path("containerOverrides")));
request.setNetworkConfiguration(parseNetworkConfiguration(req.path("networkConfiguration")));
RunTaskRequest request = parseRunTaskRequest(req);
List<EcsTask> launched = service.runTask(request, region);
ObjectNode resp = objectMapper.createObjectNode();
@@ -322,13 +345,8 @@ public class EcsJsonHandler {
}
private Response handleStartTask(JsonNode req, String region) {
RunTaskRequest request = new RunTaskRequest();
request.setCluster(req.has("cluster") ? req.path("cluster").asText() : null);
RunTaskRequest request = parseRunTaskRequest(req);
request.setContainerInstances(jsonArrayToList(req.path("containerInstances")));
request.setTaskDefinition(req.path("taskDefinition").asText());
request.setGroup(req.has("group") ? req.path("group").asText() : null);
request.setStartedBy(req.has("startedBy") ? req.path("startedBy").asText() : null);
List<EcsTask> launched = service.startTask(request, region);
ObjectNode resp = objectMapper.createObjectNode();
@@ -339,6 +357,27 @@ public class EcsJsonHandler {
return Response.ok(resp).build();
}
private RunTaskRequest parseRunTaskRequest(JsonNode req) {
RunTaskRequest request = new RunTaskRequest();
request.setCluster(req.has("cluster") ? req.path("cluster").asText() : null);
request.setTaskDefinition(req.path("taskDefinition").asText());
request.setCount(req.path("count").asInt(1));
request.setLaunchType(parseEnum(req, "launchType", LaunchType.class));
request.setCapacityProviderStrategy(parseCapacityProviderStrategy(req.path("capacityProviderStrategy")));
request.setGroup(req.has("group") ? req.path("group").asText() : null);
request.setStartedBy(req.has("startedBy") ? req.path("startedBy").asText() : null);
request.setOverrides(parseTaskOverride(req.path("overrides")));
request.setNetworkConfiguration(parseNetworkConfiguration(req.path("networkConfiguration")));
request.setPlatformVersion(req.hasNonNull("platformVersion")
? req.path("platformVersion").asText() : null);
request.setEnableExecuteCommand(req.path("enableExecuteCommand").asBoolean(false));
request.setEnableECSManagedTags(req.path("enableECSManagedTags").asBoolean(false));
request.setPropagateTags(parseChoice(req, "propagateTags", PROPAGATE_TAGS));
request.setReferenceId(req.has("referenceId") ? req.path("referenceId").asText() : null);
request.setTags(parseTagMap(req.path("tags")));
return request;
}
private Response handleStopTask(JsonNode req, String region) {
String cluster = req.has("cluster") ? req.path("cluster").asText() : null;
String task = req.path("task").asText();
@@ -354,13 +393,16 @@ public class EcsJsonHandler {
private Response handleDescribeTasks(JsonNode req, String region) {
String cluster = req.has("cluster") ? req.path("cluster").asText() : null;
List<String> taskRefs = jsonArrayToList(req.path("tasks"));
List<EcsTask> found = service.describeTasks(cluster, taskRefs, region);
boolean includeTags = jsonArrayToList(req.path("include")).contains("TAGS");
EcsService.DescribeTasksResult found = service.describeTasksDetailed(cluster, taskRefs, region);
ObjectNode resp = objectMapper.createObjectNode();
ArrayNode arr = objectMapper.createArrayNode();
found.forEach(t -> arr.add(writer.taskNode(t)));
found.tasks().forEach(t -> arr.add(writer.taskNode(t, includeTags)));
resp.set("tasks", arr);
resp.set("failures", objectMapper.createArrayNode());
ArrayNode failures = objectMapper.createArrayNode();
found.failures().forEach(f -> failures.add(writer.failureNode(f)));
resp.set("failures", failures);
return Response.ok(resp).build();
}
@@ -420,16 +462,15 @@ public class EcsJsonHandler {
request.setTaskDefinition(req.path("taskDefinition").asText());
request.setDesiredCount(req.path("desiredCount").asInt(1));
request.setLaunchType(parseEnum(req, "launchType", LaunchType.class));
request.setCapacityProviderStrategy(parseCapacityProviderStrategy(req.path("capacityProviderStrategy")));
request.setLoadBalancers(parseLoadBalancers(req.path("loadBalancers")));
request.setNetworkConfiguration(parseNetworkConfiguration(req.path("networkConfiguration")));
request.setTags(parseTagMap(req.path("tags")));
request.setSchedulingStrategy(parseChoice(req, "schedulingStrategy", SCHEDULING_STRATEGIES));
request.setDeploymentControllerType(parseChoice(req.path("deploymentController"), "type",
"deploymentController.type", DEPLOYMENT_CONTROLLER_TYPES));
request.setAvailabilityZoneRebalancing(
parseChoice(req, "availabilityZoneRebalancing", AZ_REBALANCING));
request.setServiceConnectConfiguration(
parseServiceConnectConfiguration(req.path("serviceConnectConfiguration")));
request.setAvailabilityZoneRebalancing(parseChoice(req, "availabilityZoneRebalancing", AZ_REBALANCING));
request.setServiceConnectConfiguration(parseRawObject(req.path("serviceConnectConfiguration")));
EcsServiceModel svc = service.createService(request, region);
@@ -438,6 +479,25 @@ public class EcsJsonHandler {
return Response.ok(resp).build();
}
private Response handleUpdateService(JsonNode req, String region) {
UpdateServiceRequest request = new UpdateServiceRequest();
request.setCluster(req.has("cluster") ? req.path("cluster").asText() : null);
request.setService(req.path("service").asText());
request.setTaskDefinition(req.has("taskDefinition") ? req.path("taskDefinition").asText() : null);
request.setDesiredCount(req.has("desiredCount") ? req.path("desiredCount").asInt() : null);
request.setNetworkConfiguration(parseNetworkConfiguration(req.path("networkConfiguration")));
request.setAvailabilityZoneRebalancing(parseChoice(req, "availabilityZoneRebalancing", AZ_REBALANCING));
request.setForceNewDeployment(req.path("forceNewDeployment").asBoolean(false));
request.setServiceConnectConfiguration(parseRawObject(req.path("serviceConnectConfiguration")));
request.setCapacityProviderStrategy(parseCapacityProviderStrategy(req.path("capacityProviderStrategy")));
EcsServiceModel svc = service.updateService(request, region);
ObjectNode resp = objectMapper.createObjectNode();
resp.set("service", writer.serviceNode(svc));
return Response.ok(resp).build();
}
private List<EcsLoadBalancer> parseLoadBalancers(JsonNode node) {
List<EcsLoadBalancer> result = new ArrayList<>();
if (node == null || !node.isArray()) {
@@ -476,6 +536,9 @@ public class EcsJsonHandler {
m.setLoadBalancerName(loadBalancerName);
m.setContainerName(containerName);
m.setContainerPort(containerPort);
// The blue/green listener and alternate target group wiring, kept raw: Floci shifts no
// traffic, but a service created with it has to read back with it.
m.setAdvancedConfiguration(parseRawObject(lb.path("advancedConfiguration")));
result.add(m);
}
return result;
@@ -500,26 +563,6 @@ public class EcsJsonHandler {
return networkConfiguration;
}
private Response handleUpdateService(JsonNode req, String region) {
UpdateServiceRequest request = new UpdateServiceRequest();
request.setCluster(req.has("cluster") ? req.path("cluster").asText() : null);
request.setService(req.path("service").asText());
request.setTaskDefinition(req.has("taskDefinition") ? req.path("taskDefinition").asText() : null);
request.setDesiredCount(req.has("desiredCount") ? req.path("desiredCount").asInt() : null);
request.setNetworkConfiguration(parseNetworkConfiguration(req.path("networkConfiguration")));
request.setAvailabilityZoneRebalancing(
parseChoice(req, "availabilityZoneRebalancing", AZ_REBALANCING));
request.setForceNewDeployment(req.path("forceNewDeployment").asBoolean(false));
request.setServiceConnectConfiguration(
parseServiceConnectConfiguration(req.path("serviceConnectConfiguration")));
EcsServiceModel svc = service.updateService(request, region);
ObjectNode resp = objectMapper.createObjectNode();
resp.set("service", writer.serviceNode(svc));
return Response.ok(resp).build();
}
private Response handleDeleteService(JsonNode req, String region) {
String cluster = req.has("cluster") ? req.path("cluster").asText() : null;
String serviceName = req.path("service").asText();
@@ -933,43 +976,18 @@ public class EcsJsonHandler {
return writer.taskNode(task);
}
private static final Set<String> SCHEDULING_STRATEGIES = Set.of("REPLICA", "DAEMON");
private static final Set<String> DEPLOYMENT_CONTROLLER_TYPES = Set.of("ECS", "CODE_DEPLOY", "EXTERNAL");
private static final Set<String> AZ_REBALANCING = Set.of("ENABLED", "DISABLED");
/** Optional enum-valued string field: absent → {@code null}; present but not in {@code allowed} → 400. */
private static String parseChoice(JsonNode node, String field, Set<String> allowed) {
return parseChoice(node, field, field, allowed);
}
private static String parseChoice(JsonNode node, String field, String displayName, Set<String> allowed) {
if (node == null || node.isMissingNode() || !node.hasNonNull(field)) {
return null;
}
String value = node.path(field).asText();
if (!allowed.contains(value)) {
throw new AwsException("InvalidParameterException",
"Invalid " + displayName + ": " + value + ". Valid values: "
+ String.join(", ", new java.util.TreeSet<>(allowed)) + ".", 400);
}
return value;
}
/**
* Keeps the caller's Service Connect configuration as given. AWS's {@code Service} shape has
* no member for it, so DescribeServices reports it on each deployment rather than on the
* service, and a generated client drops anything written anywhere else.
*/
@SuppressWarnings("unchecked")
private Map<String, Object> parseServiceConnectConfiguration(JsonNode node) {
if (node == null || !node.isObject()) {
return null;
}
return objectMapper.convertValue(node, Map.class);
}
// ── Parsing helpers ───────────────────────────────────────────────────────
/** Members of a container definition the parser consumes; the rest round-trips verbatim. */
private static final Set<String> CONTAINER_DEFINITION_CONSUMED = Set.of(
"name", "image", "essential", "cpu", "memory", "memoryReservation", "portMappings",
"environment", "environmentFiles", "secrets", "mountPoints", "volumesFrom", "dependsOn",
"logConfiguration", "firelensConfiguration", "healthCheck", "command", "entryPoint",
"startTimeout", "stopTimeout", "user", "workingDirectory", "hostname",
"readonlyRootFilesystem", "privileged", "disableNetworking", "interactive",
"pseudoTerminal", "links", "dnsServers", "dnsSearchDomains", "dockerSecurityOptions",
"dockerLabels", "repositoryCredentials");
private List<ContainerDefinition> parseContainerDefinitions(JsonNode node) {
List<ContainerDefinition> result = new ArrayList<>();
if (!node.isArray()) {
@@ -986,11 +1004,17 @@ public class EcsJsonHandler {
def.setPortMappings(parsePortMappings(item.path("portMappings")));
def.setEnvironment(parseKeyValuePairs(item.path("environment")));
if (item.has("environmentFiles")) {
def.setEnvironmentFiles(parseEnvironmentFiles(item.path("environmentFiles")));
}
if (item.has("secrets")) {
def.setSecrets(parseSecrets(item.path("secrets")));
}
def.setMountPoints(parseMountPoints(item.path("mountPoints")));
def.setVolumesFrom(parseVolumesFrom(item.path("volumesFrom")));
if (item.has("dependsOn")) {
def.setDependsOn(parseDependsOn(item.path("dependsOn"), def.getName()));
}
def.setLogConfiguration(parseLogConfiguration(item.path("logConfiguration")));
def.setFirelensConfiguration(parseFirelensConfiguration(
item.path("firelensConfiguration"), result.size() + 1));
@@ -999,16 +1023,50 @@ public class EcsJsonHandler {
}
if (item.has("command") && item.path("command").isArray()) {
List<String> cmd = new ArrayList<>();
item.path("command").forEach(c -> cmd.add(c.asText()));
def.setCommand(cmd);
def.setCommand(jsonArrayToList(item.path("command")));
}
if (item.has("entryPoint") && item.path("entryPoint").isArray()) {
List<String> ep = new ArrayList<>();
item.path("entryPoint").forEach(e -> ep.add(e.asText()));
def.setEntryPoint(ep);
def.setEntryPoint(jsonArrayToList(item.path("entryPoint")));
}
if (item.hasNonNull("startTimeout")) { def.setStartTimeout(item.path("startTimeout").asInt()); }
if (item.hasNonNull("stopTimeout")) { def.setStopTimeout(item.path("stopTimeout").asInt()); }
if (item.hasNonNull("user")) { def.setUser(item.path("user").asText()); }
if (item.hasNonNull("workingDirectory")) {
def.setWorkingDirectory(item.path("workingDirectory").asText());
}
if (item.hasNonNull("hostname")) { def.setHostname(item.path("hostname").asText()); }
if (item.hasNonNull("readonlyRootFilesystem")) {
def.setReadonlyRootFilesystem(item.path("readonlyRootFilesystem").asBoolean());
}
if (item.hasNonNull("privileged")) { def.setPrivileged(item.path("privileged").asBoolean()); }
if (item.hasNonNull("disableNetworking")) {
def.setDisableNetworking(item.path("disableNetworking").asBoolean());
}
if (item.hasNonNull("interactive")) { def.setInteractive(item.path("interactive").asBoolean()); }
if (item.hasNonNull("pseudoTerminal")) {
def.setPseudoTerminal(item.path("pseudoTerminal").asBoolean());
}
if (item.has("links")) { def.setLinks(jsonArrayToList(item.path("links"))); }
if (item.has("dnsServers")) { def.setDnsServers(jsonArrayToList(item.path("dnsServers"))); }
if (item.has("dnsSearchDomains")) {
def.setDnsSearchDomains(jsonArrayToList(item.path("dnsSearchDomains")));
}
if (item.has("dockerSecurityOptions")) {
def.setDockerSecurityOptions(jsonArrayToList(item.path("dockerSecurityOptions")));
}
if (item.path("dockerLabels").isObject()) {
Map<String, String> labels = new LinkedHashMap<>();
item.path("dockerLabels").fields()
.forEachRemaining(entry -> labels.put(entry.getKey(), entry.getValue().asText()));
def.setDockerLabels(labels);
}
if (item.path("repositoryCredentials").hasNonNull("credentialsParameter")) {
def.setRepositoryCredentialsParameter(
item.path("repositoryCredentials").path("credentialsParameter").asText());
}
def.setUnparsed(EcsJsonPassthrough.capture(item, objectMapper, CONTAINER_DEFINITION_CONSUMED));
result.add(def);
}
return result;
@@ -1023,7 +1081,12 @@ public class EcsJsonHandler {
int containerPort = item.path("containerPort").asInt(0);
int hostPort = item.path("hostPort").asInt(0);
String protocol = item.path("protocol").asText("tcp");
result.add(new PortMapping(containerPort, hostPort, protocol));
String name = item.hasNonNull("name") ? item.path("name").asText() : null;
String appProtocol = item.hasNonNull("appProtocol") ? item.path("appProtocol").asText() : null;
String containerPortRange = item.hasNonNull("containerPortRange")
? item.path("containerPortRange").asText() : null;
result.add(new PortMapping(containerPort, hostPort, protocol, name, appProtocol,
containerPortRange));
}
return result;
}
@@ -1039,6 +1102,40 @@ public class EcsJsonHandler {
return result;
}
private List<EnvironmentFile> parseEnvironmentFiles(JsonNode node) {
List<EnvironmentFile> result = new ArrayList<>();
if (!node.isArray()) {
return result;
}
for (JsonNode item : node) {
result.add(new EnvironmentFile(item.path("value").asText(), item.path("type").asText("s3")));
}
return result;
}
/**
* Parses {@code dependsOn}, rejecting a condition ECS does not define. An unknown condition
* would otherwise silently become a plain start-ordering edge.
*/
private List<ContainerDependency> parseDependsOn(JsonNode node, String containerName) {
List<ContainerDependency> result = new ArrayList<>();
if (!node.isArray()) {
return result;
}
for (JsonNode item : node) {
String condition = item.path("condition").asText();
if (!DEPENDENCY_CONDITIONS.contains(condition)) {
throw new AwsException("ClientException",
"Container '" + containerName + "' depends on container '"
+ item.path("containerName").asText() + "' with an invalid condition: "
+ condition + ". Valid values: "
+ String.join(", ", new TreeSet<>(DEPENDENCY_CONDITIONS)) + ".", 400);
}
result.add(new ContainerDependency(item.path("containerName").asText(), condition));
}
return result;
}
private List<Secret> parseSecrets(JsonNode node) {
List<Secret> result = new ArrayList<>();
if (!node.isArray()) {
@@ -1075,6 +1172,43 @@ public class EcsJsonHandler {
return new RuntimePlatform(cpuArchitecture, operatingSystemFamily);
}
private EphemeralStorage parseEphemeralStorage(JsonNode node) {
if (node == null || !node.isObject() || !node.hasNonNull("sizeInGiB")) {
return null;
}
return new EphemeralStorage(node.path("sizeInGiB").asInt());
}
private List<CapacityProviderStrategyItem> parseCapacityProviderStrategy(JsonNode node) {
if (node == null || !node.isArray() || node.isEmpty()) {
return null;
}
List<CapacityProviderStrategyItem> result = new ArrayList<>();
for (JsonNode item : node) {
result.add(new CapacityProviderStrategyItem(
item.path("capacityProvider").asText(),
item.path("weight").asInt(0),
item.path("base").asInt(0)));
}
return result;
}
private TaskOverride parseTaskOverride(JsonNode node) {
if (node == null || !node.isObject()) {
return null;
}
TaskOverride overrides = new TaskOverride();
overrides.setContainerOverrides(parseContainerOverrides(node.path("containerOverrides")));
if (node.hasNonNull("cpu")) { overrides.setCpu(node.path("cpu").asText()); }
if (node.hasNonNull("memory")) { overrides.setMemory(node.path("memory").asText()); }
if (node.hasNonNull("taskRoleArn")) { overrides.setTaskRoleArn(node.path("taskRoleArn").asText()); }
if (node.hasNonNull("executionRoleArn")) {
overrides.setExecutionRoleArn(node.path("executionRoleArn").asText());
}
overrides.setEphemeralStorage(parseEphemeralStorage(node.path("ephemeralStorage")));
return overrides.isEmpty() ? null : overrides;
}
private LogConfiguration parseLogConfiguration(JsonNode node) {
if (node == null || !node.isObject()) {
return null;
@@ -1121,6 +1255,7 @@ public class EcsJsonHandler {
}
return new FirelensConfiguration(type, options);
}
private HealthCheck parseHealthCheck(JsonNode node) {
if (node == null || !node.isObject()) {
return null;
@@ -1147,11 +1282,18 @@ public class EcsJsonHandler {
hostVolumePolicy.validate(hostSourcePath);
}
EfsVolumeConfiguration efs = parseEfsVolumeConfiguration(item.path("efsVolumeConfiguration"));
result.add(new Volume(item.path("name").asText(), hostSourcePath, efs));
// "host" stays out of the consumed set so that a volume declaring an empty one reads
// back with it; a host that did carry a sourcePath is written from the typed field and
// the passthrough leaves it alone.
result.add(new Volume(item.path("name").asText(), hostSourcePath, efs,
EcsJsonPassthrough.capture(item, objectMapper, VOLUME_CONSUMED)));
}
return result;
}
/** Volume members the parser consumes; the rest round-trips verbatim. */
private static final Set<String> VOLUME_CONSUMED = Set.of("name", "efsVolumeConfiguration");
private EfsVolumeConfiguration parseEfsVolumeConfiguration(JsonNode node) {
if (node == null || !node.isObject()) {
return null;
@@ -1205,11 +1347,17 @@ public class EcsJsonHandler {
ContainerOverride co = new ContainerOverride();
co.setName(item.path("name").asText());
if (item.has("command") && item.path("command").isArray()) {
List<String> cmd = new ArrayList<>();
item.path("command").forEach(c -> cmd.add(c.asText()));
co.setCommand(cmd);
co.setCommand(jsonArrayToList(item.path("command")));
}
co.setEnvironment(parseKeyValuePairs(item.path("environment")));
if (item.has("environmentFiles")) {
co.setEnvironmentFiles(parseEnvironmentFiles(item.path("environmentFiles")));
}
if (item.hasNonNull("cpu")) { co.setCpu(item.path("cpu").asInt()); }
if (item.hasNonNull("memory")) { co.setMemory(item.path("memory").asInt()); }
if (item.hasNonNull("memoryReservation")) {
co.setMemoryReservation(item.path("memoryReservation").asInt());
}
result.add(co);
}
return result;
@@ -1242,24 +1390,53 @@ public class EcsJsonHandler {
return result;
}
/**
* Parses a {@code tags} list, holding it to the limits ECS documents for every operation that
* takes one: at most 50 tags, a key of 1 to 128 characters and a value of up to 256. The count
* is taken from the request rather than the parsed map, so 51 entries that collapse to fewer
* distinct keys are still rejected.
*/
private Map<String, String> parseTagMap(JsonNode node) {
Map<String, String> result = new HashMap<>();
if (!node.isArray()) {
return result;
}
if (node.size() > MAX_TAGS_PER_RESOURCE) {
throw new AwsException("InvalidParameterException",
"Too many tags specified. A resource takes at most "
+ MAX_TAGS_PER_RESOURCE + " tags.", 400);
}
for (JsonNode item : node) {
result.put(item.path("key").asText(), item.path("value").asText());
String key = item.path("key").asText();
String value = item.path("value").asText();
if (key.isEmpty() || key.length() > MAX_TAG_KEY_LENGTH) {
throw new AwsException("InvalidParameterException",
"Tag keys must be between 1 and " + MAX_TAG_KEY_LENGTH
+ " characters long.", 400);
}
if (value.length() > MAX_TAG_VALUE_LENGTH) {
throw new AwsException("InvalidParameterException",
"Tag values can be up to " + MAX_TAG_VALUE_LENGTH
+ " characters long.", 400);
}
result.put(key, value);
}
return result;
}
private static final int MAX_TAGS_PER_RESOURCE = 50;
private static final int MAX_TAG_KEY_LENGTH = 128;
private static final int MAX_TAG_VALUE_LENGTH = 256;
@SuppressWarnings("unchecked")
private Map<String, Object> parseRawObject(JsonNode node) {
if (node == null || node.isMissingNode()) {
if (node == null || node.isMissingNode() || !node.isObject()) {
return null;
}
return objectMapper.convertValue(node, Map.class);
}
@SuppressWarnings("unchecked")
private List<Map<String, Object>> parseRawObjectList(JsonNode node) {
List<Map<String, Object>> result = new ArrayList<>();
if (!node.isArray()) {
@@ -1279,15 +1456,67 @@ public class EcsJsonHandler {
return result;
}
/**
* Parses an enum-typed member, rejecting a value the enum does not have. Treating an
* unrecognised value as absent is worse than it sounds: a {@code launchType} of {@code "EC22"}
* would silently fall through to Floci's default and place the task on Fargate, which is not
* what the caller asked for and not what AWS answers.
*/
private <T extends Enum<T>> T parseEnum(JsonNode req, String field, Class<T> enumClass) {
if (!req.has(field)) {
if (!req.hasNonNull(field)) {
return null;
}
String val = req.path(field).asText();
try {
return Enum.valueOf(enumClass, val);
} catch (IllegalArgumentException e) {
return null;
List<String> valid = Arrays.stream(enumClass.getEnumConstants()).map(Enum::name).toList();
throw new AwsException("InvalidParameterException",
"Invalid " + field + ": " + val + ". Valid values: "
+ String.join(", ", valid) + ".", 400);
}
}
/** Rejects a compatibility the enum does not have, rather than carrying it into the model. */
private List<String> parseCompatibilities(JsonNode node) {
List<String> requested = jsonArrayToList(node);
for (String value : requested) {
if (!COMPATIBILITIES.contains(value)) {
throw new AwsException("InvalidParameterException",
"Invalid requiresCompatibilities value: " + value + ". Valid values: "
+ String.join(", ", new TreeSet<>(COMPATIBILITIES)) + ".", 400);
}
}
return requested;
}
private static final Set<String> COMPATIBILITIES =
Set.of("EC2", "FARGATE", "EXTERNAL", "MANAGED_INSTANCES");
private static final Set<String> PID_MODES = Set.of("host", "task");
private static final Set<String> IPC_MODES = Set.of("host", "task", "none");
private static final Set<String> SCHEDULING_STRATEGIES = Set.of("REPLICA", "DAEMON");
private static final Set<String> DEPLOYMENT_CONTROLLER_TYPES = Set.of("ECS", "CODE_DEPLOY", "EXTERNAL");
private static final Set<String> AZ_REBALANCING = Set.of("ENABLED", "DISABLED");
private static final Set<String> PROPAGATE_TAGS = Set.of("TASK_DEFINITION", "SERVICE", "NONE");
private static final Set<String> DEPENDENCY_CONDITIONS = Set.of(
ContainerDependency.START, ContainerDependency.COMPLETE,
ContainerDependency.SUCCESS, ContainerDependency.HEALTHY);
/** Optional enum-valued string field: absent → {@code null}; present but not in {@code allowed} → 400. */
private static String parseChoice(JsonNode node, String field, Set<String> allowed) {
return parseChoice(node, field, field, allowed);
}
private static String parseChoice(JsonNode node, String field, String displayName, Set<String> allowed) {
if (node == null || node.isMissingNode() || !node.hasNonNull(field)) {
return null;
}
String value = node.path(field).asText();
if (!allowed.contains(value)) {
throw new AwsException("InvalidParameterException",
"Invalid " + displayName + ": " + value + ". Valid values: "
+ String.join(", ", new TreeSet<>(allowed)) + ".", 400);
}
return value;
}
}
@@ -0,0 +1,62 @@
package io.github.hectorvent.floci.services.ecs;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
/**
* Keeps the members of a request that Floci has no behaviour for, so a describe returns what the
* caller registered instead of a subset of it.
*
* <p>ECS's task definition and service shapes carry a long tail of members that only have to
* survive a round trip: {@code proxyConfiguration}, {@code linuxParameters}, {@code ulimits},
* {@code resourceRequirements}, placement constraints and so on. A client that writes one and
* reads it back, such as Terraform or CDK, treats a dropped member as drift and proposes the same
* change on every plan. Capturing whatever the parser did not consume covers the whole tail at
* once, including members AWS adds later.
*/
final class EcsJsonPassthrough {
private EcsJsonPassthrough() {
}
/**
* The members of {@code node} that are not in {@code consumed}, in the order they arrived, or
* {@code null} when there are none.
*/
static Map<String, Object> capture(JsonNode node, ObjectMapper objectMapper, Set<String> consumed) {
if (node == null || !node.isObject()) {
return null;
}
Map<String, Object> result = new LinkedHashMap<>();
Iterator<Map.Entry<String, JsonNode>> fields = node.fields();
while (fields.hasNext()) {
Map.Entry<String, JsonNode> field = fields.next();
if (consumed.contains(field.getKey())) {
continue;
}
result.put(field.getKey(), objectMapper.convertValue(field.getValue(), Object.class));
}
return result.isEmpty() ? null : result;
}
/**
* Writes the captured members onto a response node. A member the serializer already wrote from
* a typed field wins, so a value Floci normalizes is never overwritten by the raw input.
*/
static void write(ObjectNode target, Map<String, Object> passthrough, ObjectMapper objectMapper) {
if (passthrough == null || passthrough.isEmpty()) {
return;
}
passthrough.forEach((key, value) -> {
if (!target.has(key)) {
target.set(key, objectMapper.valueToTree(value));
}
});
}
}
@@ -3,20 +3,26 @@ package io.github.hectorvent.floci.services.ecs;
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.CapacityProvider;
import io.github.hectorvent.floci.services.ecs.model.CapacityProviderStrategyItem;
import io.github.hectorvent.floci.services.ecs.model.Container;
import io.github.hectorvent.floci.services.ecs.model.ContainerDefinition;
import io.github.hectorvent.floci.services.ecs.model.ContainerDependency;
import io.github.hectorvent.floci.services.ecs.model.ContainerInstance;
import io.github.hectorvent.floci.services.ecs.model.ContainerOverride;
import io.github.hectorvent.floci.services.ecs.model.Deployment;
import io.github.hectorvent.floci.services.ecs.model.EcsCluster;
import io.github.hectorvent.floci.services.ecs.model.EcsLoadBalancer;
import io.github.hectorvent.floci.services.ecs.model.EcsServiceModel;
import io.github.hectorvent.floci.services.ecs.model.EcsTask;
import io.github.hectorvent.floci.services.ecs.model.EfsVolumeConfiguration;
import io.github.hectorvent.floci.services.ecs.model.EnvironmentFile;
import io.github.hectorvent.floci.services.ecs.model.EphemeralStorage;
import io.github.hectorvent.floci.services.ecs.model.Failure;
import io.github.hectorvent.floci.services.ecs.model.FirelensConfiguration;
import io.github.hectorvent.floci.services.ecs.model.HealthCheck;
import io.github.hectorvent.floci.services.ecs.model.KeyValuePair;
import io.github.hectorvent.floci.services.ecs.model.LogConfiguration;
import io.github.hectorvent.floci.services.ecs.model.ManagedAgent;
import io.github.hectorvent.floci.services.ecs.model.MountPoint;
import io.github.hectorvent.floci.services.ecs.model.NetworkBinding;
import io.github.hectorvent.floci.services.ecs.model.PortMapping;
@@ -26,6 +32,8 @@ import io.github.hectorvent.floci.services.ecs.model.Secret;
import io.github.hectorvent.floci.services.ecs.model.ServiceDeployment;
import io.github.hectorvent.floci.services.ecs.model.ServiceRevision;
import io.github.hectorvent.floci.services.ecs.model.TaskDefinition;
import io.github.hectorvent.floci.services.ecs.model.TaskNetworkInterface;
import io.github.hectorvent.floci.services.ecs.model.TaskOverride;
import io.github.hectorvent.floci.services.ecs.model.TaskSet;
import io.github.hectorvent.floci.services.ecs.model.Volume;
import io.github.hectorvent.floci.services.ecs.model.VolumeFrom;
@@ -35,6 +43,8 @@ import com.fasterxml.jackson.databind.node.ObjectNode;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import java.time.Instant;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
@@ -104,6 +114,11 @@ public class EcsResponseWriter {
if (td.getMemory() != null) { n.put("memory", td.getMemory()); }
if (td.getTaskRoleArn() != null) { n.put("taskRoleArn", td.getTaskRoleArn()); }
if (td.getExecutionRoleArn() != null) { n.put("executionRoleArn", td.getExecutionRoleArn()); }
if (td.getPidMode() != null) { n.put("pidMode", td.getPidMode()); }
if (td.getIpcMode() != null) { n.put("ipcMode", td.getIpcMode()); }
if (td.getEphemeralStorage() != null) {
n.set("ephemeralStorage", ephemeralStorageNode(td.getEphemeralStorage()));
}
if (td.getRuntimePlatform() != null) {
RuntimePlatform platform = td.getRuntimePlatform();
ObjectNode platformNode = objectMapper.createObjectNode();
@@ -125,6 +140,11 @@ public class EcsResponseWriter {
td.getCompatibilities().forEach(arr::add);
n.set("compatibilities", arr);
}
if (td.getRequiresAttributes() != null && !td.getRequiresAttributes().isEmpty()) {
ArrayNode arr = objectMapper.createArrayNode();
td.getRequiresAttributes().forEach(a -> arr.add(attributeNode(a)));
n.set("requiresAttributes", arr);
}
ArrayNode containers = objectMapper.createArrayNode();
if (td.getContainerDefinitions() != null) {
@@ -136,9 +156,14 @@ public class EcsResponseWriter {
if (td.getVolumes() != null && !td.getVolumes().isEmpty()) {
n.set("volumes", volumesNode(td.getVolumes()));
}
putInstant(n, "registeredAt", td.getRegisteredAt());
putInstant(n, "deregisteredAt", td.getDeregisteredAt());
putInstant(n, "deleteRequestedAt", td.getDeleteRequestedAt());
if (td.getRegisteredBy() != null) { n.put("registeredBy", td.getRegisteredBy()); }
if (td.getTags() != null && !td.getTags().isEmpty()) {
n.set("tags", tagsNode(td.getTags()));
}
EcsJsonPassthrough.write(n, td.getUnparsed(), objectMapper);
return n;
}
@@ -177,6 +202,7 @@ public class EcsResponseWriter {
}
vNode.set("efsVolumeConfiguration", efs);
}
EcsJsonPassthrough.write(vNode, v.unparsed(), objectMapper);
vols.add(vNode);
}
return vols;
@@ -189,6 +215,7 @@ public class EcsResponseWriter {
n.put("essential", def.isEssential());
if (def.getCpu() != null) { n.put("cpu", def.getCpu()); }
if (def.getMemory() != null) { n.put("memory", def.getMemory()); }
if (def.getMemoryReservation() != null) { n.put("memoryReservation", def.getMemoryReservation()); }
if (def.getPortMappings() != null && !def.getPortMappings().isEmpty()) {
ArrayNode pms = objectMapper.createArrayNode();
@@ -197,6 +224,11 @@ public class EcsResponseWriter {
pmNode.put("containerPort", pm.containerPort());
pmNode.put("hostPort", pm.hostPort());
pmNode.put("protocol", pm.protocol());
if (pm.name() != null) { pmNode.put("name", pm.name()); }
if (pm.appProtocol() != null) { pmNode.put("appProtocol", pm.appProtocol()); }
if (pm.containerPortRange() != null) {
pmNode.put("containerPortRange", pm.containerPortRange());
}
pms.add(pmNode);
}
n.set("portMappings", pms);
@@ -211,6 +243,9 @@ public class EcsResponseWriter {
if (def.getEnvironment() != null && !def.getEnvironment().isEmpty()) {
n.set("environment", keyValuePairsNode(def.getEnvironment()));
}
if (def.getEnvironmentFiles() != null && !def.getEnvironmentFiles().isEmpty()) {
n.set("environmentFiles", environmentFilesNode(def.getEnvironmentFiles()));
}
if (def.getSecrets() != null && !def.getSecrets().isEmpty()) {
n.set("secrets", secretsNode(def.getSecrets()));
}
@@ -235,6 +270,16 @@ public class EcsResponseWriter {
}
n.set("volumesFrom", volumesFrom);
}
if (def.getDependsOn() != null && !def.getDependsOn().isEmpty()) {
ArrayNode dependsOn = objectMapper.createArrayNode();
for (ContainerDependency dependency : def.getDependsOn()) {
ObjectNode dependencyNode = objectMapper.createObjectNode();
dependencyNode.put("containerName", dependency.containerName());
dependencyNode.put("condition", dependency.condition());
dependsOn.add(dependencyNode);
}
n.set("dependsOn", dependsOn);
}
if (def.getLogConfiguration() != null) {
LogConfiguration logConfig = def.getLogConfiguration();
@@ -279,11 +324,57 @@ public class EcsResponseWriter {
n.set("healthCheck", hcNode);
}
if (def.getStartTimeout() != null) { n.put("startTimeout", def.getStartTimeout()); }
if (def.getStopTimeout() != null) { n.put("stopTimeout", def.getStopTimeout()); }
if (def.getUser() != null) { n.put("user", def.getUser()); }
if (def.getWorkingDirectory() != null) { n.put("workingDirectory", def.getWorkingDirectory()); }
if (def.getHostname() != null) { n.put("hostname", def.getHostname()); }
if (def.getReadonlyRootFilesystem() != null) {
n.put("readonlyRootFilesystem", def.getReadonlyRootFilesystem());
}
if (def.getPrivileged() != null) { n.put("privileged", def.getPrivileged()); }
if (def.getDisableNetworking() != null) { n.put("disableNetworking", def.getDisableNetworking()); }
if (def.getInteractive() != null) { n.put("interactive", def.getInteractive()); }
if (def.getPseudoTerminal() != null) { n.put("pseudoTerminal", def.getPseudoTerminal()); }
if (def.getLinks() != null && !def.getLinks().isEmpty()) {
n.set("links", stringArray(def.getLinks()));
}
if (def.getDnsServers() != null && !def.getDnsServers().isEmpty()) {
n.set("dnsServers", stringArray(def.getDnsServers()));
}
if (def.getDnsSearchDomains() != null && !def.getDnsSearchDomains().isEmpty()) {
n.set("dnsSearchDomains", stringArray(def.getDnsSearchDomains()));
}
if (def.getDockerSecurityOptions() != null && !def.getDockerSecurityOptions().isEmpty()) {
n.set("dockerSecurityOptions", stringArray(def.getDockerSecurityOptions()));
}
if (def.getDockerLabels() != null && !def.getDockerLabels().isEmpty()) {
ObjectNode labels = objectMapper.createObjectNode();
def.getDockerLabels().forEach(labels::put);
n.set("dockerLabels", labels);
}
if (def.getRepositoryCredentialsParameter() != null) {
n.putObject("repositoryCredentials")
.put("credentialsParameter", def.getRepositoryCredentialsParameter());
}
EcsJsonPassthrough.write(n, def.getUnparsed(), objectMapper);
return n;
}
// ── Tasks ─────────────────────────────────────────────────────────────────
/**
* Renders a task for a describe, where its tags are reported only when the caller asked for
* them with {@code include: ["TAGS"]}.
*/
public ObjectNode taskNode(EcsTask t, boolean includeTags) {
ObjectNode n = taskNode(t);
if (!includeTags) {
n.remove("tags");
}
return n;
}
/** Renders an ECS task to its data-plane JSON shape. Reused by the Step Functions
* ecs:runTask integration ({@link io.github.hectorvent.floci.services.stepfunctions.AslExecutor}). */
public ObjectNode taskNode(EcsTask t) {
@@ -293,16 +384,52 @@ public class EcsResponseWriter {
n.put("taskDefinitionArn", t.getTaskDefinitionArn());
n.put("lastStatus", t.getLastStatus());
n.put("desiredStatus", t.getDesiredStatus());
if (t.getLaunchType() != null) { n.put("launchType", t.getLaunchType().name()); }
// A task placed through a capacity provider reports both: the provider it was placed
// through and the launch type that provider resolves to. (A service reports only one of
// the two, which is why serviceNode does it differently.)
if (t.getCapacityProviderName() != null) {
n.put("capacityProviderName", t.getCapacityProviderName());
}
if (t.getLaunchType() != null) {
n.put("launchType", t.getLaunchType().name());
}
if (t.getPlatformVersion() != null) { n.put("platformVersion", t.getPlatformVersion()); }
if (t.getPlatformFamily() != null) { n.put("platformFamily", t.getPlatformFamily()); }
if (t.getCpu() != null) { n.put("cpu", t.getCpu()); }
if (t.getMemory() != null) { n.put("memory", t.getMemory()); }
if (t.getEphemeralStorage() != null) {
n.set("ephemeralStorage", ephemeralStorageNode(t.getEphemeralStorage()));
// A Fargate task also reports the storage it actually got, which is the same size here.
if (t.getPlatformVersion() != null) {
n.set("fargateEphemeralStorage", ephemeralStorageNode(t.getEphemeralStorage()));
}
}
if (t.getGroup() != null) { n.put("group", t.getGroup()); }
if (t.getStartedBy() != null) { n.put("startedBy", t.getStartedBy()); }
if (t.getContainerInstanceArn() != null) { n.put("containerInstanceArn", t.getContainerInstanceArn()); }
if (t.getCreatedAt() != null) { n.put("createdAt", t.getCreatedAt().toEpochMilli() / 1000.0); }
if (t.getStartedAt() != null) { n.put("startedAt", t.getStartedAt().toEpochMilli() / 1000.0); }
if (t.getStoppedAt() != null) { n.put("stoppedAt", t.getStoppedAt().toEpochMilli() / 1000.0); }
if (t.getAvailabilityZone() != null) { n.put("availabilityZone", t.getAvailabilityZone()); }
if (t.getConnectivity() != null) { n.put("connectivity", t.getConnectivity()); }
putInstant(n, "connectivityAt", t.getConnectivityAt());
if (t.getHealthStatus() != null) { n.put("healthStatus", t.getHealthStatus()); }
if (t.getStopCode() != null) { n.put("stopCode", t.getStopCode()); }
n.put("enableExecuteCommand", t.isEnableExecuteCommand());
n.put("version", t.getVersion());
putInstant(n, "createdAt", t.getCreatedAt());
putInstant(n, "startedAt", t.getStartedAt());
putInstant(n, "stoppingAt", t.getStoppingAt());
putInstant(n, "stoppedAt", t.getStoppedAt());
putInstant(n, "pullStartedAt", t.getPullStartedAt());
putInstant(n, "pullStoppedAt", t.getPullStoppedAt());
putInstant(n, "executionStoppedAt", t.getExecutionStoppedAt());
if (t.getStoppedReason() != null) { n.put("stoppedReason", t.getStoppedReason()); }
// A task always reports overrides, with one containerOverrides entry per container even
// when the request overrode nothing, which is what DescribeTasks answers with.
n.set("overrides", taskOverrideNode(t));
if (t.getAttributes() != null && !t.getAttributes().isEmpty()) {
ArrayNode attrs = objectMapper.createArrayNode();
t.getAttributes().forEach(a -> attrs.add(attributeNode(a)));
n.set("attributes", attrs);
}
if (t.getNetworkInterfaceId() != null) {
n.putArray("attachments").add(eniAttachmentNode(t));
}
@@ -322,9 +449,10 @@ public class EcsResponseWriter {
private ObjectNode eniAttachmentNode(EcsTask t) {
ObjectNode attachment = objectMapper.createObjectNode();
attachment.put("id", "eni-attach-" + t.getNetworkInterfaceId());
attachment.put("id", t.getAttachmentId() != null
? t.getAttachmentId() : "eni-attach-" + t.getNetworkInterfaceId());
attachment.put("type", "ElasticNetworkInterface");
attachment.put("status", "ATTACHED");
attachment.put("status", t.getAttachmentStatus() != null ? t.getAttachmentStatus() : "ATTACHED");
ArrayNode details = objectMapper.createArrayNode();
if (t.getNetworkConfiguration() != null
&& t.getNetworkConfiguration().getAwsvpcConfiguration() != null
@@ -333,6 +461,12 @@ public class EcsResponseWriter {
t.getNetworkConfiguration().getAwsvpcConfiguration().getSubnets().getFirst());
}
details.addObject().put("name", "networkInterfaceId").put("value", t.getNetworkInterfaceId());
if (t.getMacAddress() != null) {
details.addObject().put("name", "macAddress").put("value", t.getMacAddress());
}
if (t.getPrivateDnsName() != null) {
details.addObject().put("name", "privateDnsName").put("value", t.getPrivateDnsName());
}
details.addObject().put("name", "privateIPv4Address").put("value", t.getPrivateIpAddress());
attachment.set("details", details);
return attachment;
@@ -347,6 +481,13 @@ public class EcsResponseWriter {
cn.put("lastStatus", c.getLastStatus());
if (c.getExitCode() != null) { cn.put("exitCode", c.getExitCode()); }
if (c.getReason() != null) { cn.put("reason", c.getReason()); }
if (c.getHealthStatus() != null) { cn.put("healthStatus", c.getHealthStatus()); }
if (c.getRuntimeId() != null) { cn.put("runtimeId", c.getRuntimeId()); }
if (c.getImageDigest() != null) { cn.put("imageDigest", c.getImageDigest()); }
// A container definition that asked for no CPU units reports zero, not nothing.
cn.put("cpu", c.getCpu() != null ? c.getCpu() : "0");
if (c.getMemory() != null) { cn.put("memory", c.getMemory()); }
if (c.getMemoryReservation() != null) { cn.put("memoryReservation", c.getMemoryReservation()); }
ArrayNode bindings = objectMapper.createArrayNode();
if (c.getNetworkBindings() != null) {
@@ -360,11 +501,91 @@ public class EcsResponseWriter {
}
}
cn.set("networkBindings", bindings);
if (c.getNetworkInterfaces() != null && !c.getNetworkInterfaces().isEmpty()) {
ArrayNode interfaces = objectMapper.createArrayNode();
for (TaskNetworkInterface ni : c.getNetworkInterfaces()) {
ObjectNode in = objectMapper.createObjectNode();
if (ni.attachmentId() != null) { in.put("attachmentId", ni.attachmentId()); }
if (ni.privateIpv4Address() != null) { in.put("privateIpv4Address", ni.privateIpv4Address()); }
if (ni.ipv6Address() != null) { in.put("ipv6Address", ni.ipv6Address()); }
interfaces.add(in);
}
cn.set("networkInterfaces", interfaces);
}
if (c.getManagedAgents() != null && !c.getManagedAgents().isEmpty()) {
ArrayNode agents = objectMapper.createArrayNode();
for (ManagedAgent agent : c.getManagedAgents()) {
ObjectNode an = objectMapper.createObjectNode();
an.put("name", agent.name());
an.put("lastStatus", agent.lastStatus());
if (agent.reason() != null) { an.put("reason", agent.reason()); }
putInstant(an, "lastStartedAt", agent.lastStartedAt());
agents.add(an);
}
cn.set("managedAgents", agents);
}
return cn;
}
/**
* The task's overrides. Every container is listed, carrying whatever the request overrode for
* it and nothing more, so a client that walks {@code containerOverrides} sees the same entries
* AWS returns rather than an empty list for a task nobody overrode.
*/
private ObjectNode taskOverrideNode(EcsTask task) {
TaskOverride overrides = task.getOverrides() != null ? task.getOverrides() : new TaskOverride();
Map<String, ContainerOverride> byName = new LinkedHashMap<>();
if (task.getContainers() != null) {
task.getContainers().forEach(container -> {
ContainerOverride placeholder = new ContainerOverride();
placeholder.setName(container.getName());
byName.put(container.getName(), placeholder);
});
}
if (overrides.getContainerOverrides() != null) {
overrides.getContainerOverrides().forEach(override -> byName.put(override.getName(), override));
}
return taskOverrideNode(overrides, List.copyOf(byName.values()));
}
private ObjectNode taskOverrideNode(TaskOverride overrides, List<ContainerOverride> perContainer) {
ObjectNode n = objectMapper.createObjectNode();
ArrayNode containerOverrides = objectMapper.createArrayNode();
for (ContainerOverride co : perContainer) {
ObjectNode con = objectMapper.createObjectNode();
con.put("name", co.getName());
if (co.getCommand() != null && !co.getCommand().isEmpty()) {
con.set("command", stringArray(co.getCommand()));
}
if (co.getEnvironment() != null && !co.getEnvironment().isEmpty()) {
con.set("environment", keyValuePairsNode(co.getEnvironment()));
}
if (co.getEnvironmentFiles() != null && !co.getEnvironmentFiles().isEmpty()) {
con.set("environmentFiles", environmentFilesNode(co.getEnvironmentFiles()));
}
if (co.getCpu() != null) { con.put("cpu", co.getCpu()); }
if (co.getMemory() != null) { con.put("memory", co.getMemory()); }
if (co.getMemoryReservation() != null) {
con.put("memoryReservation", co.getMemoryReservation());
}
containerOverrides.add(con);
}
n.set("containerOverrides", containerOverrides);
if (overrides.getCpu() != null) { n.put("cpu", overrides.getCpu()); }
if (overrides.getMemory() != null) { n.put("memory", overrides.getMemory()); }
if (overrides.getTaskRoleArn() != null) { n.put("taskRoleArn", overrides.getTaskRoleArn()); }
if (overrides.getExecutionRoleArn() != null) {
n.put("executionRoleArn", overrides.getExecutionRoleArn());
}
if (overrides.getEphemeralStorage() != null) {
n.set("ephemeralStorage", ephemeralStorageNode(overrides.getEphemeralStorage()));
}
return n;
}
// ── Services ──────────────────────────────────────────────────────────────
/** Renders a service for a describe, gating its tags on {@code include: ["TAGS"]}. */
public ObjectNode serviceNode(EcsServiceModel s) {
ObjectNode n = objectMapper.createObjectNode();
n.put("serviceArn", s.getServiceArn());
@@ -375,8 +596,13 @@ public class EcsResponseWriter {
n.put("runningCount", s.getRunningCount());
n.put("pendingCount", s.getPendingCount());
n.put("status", s.getStatus());
if (s.getLaunchType() != null) { n.put("launchType", s.getLaunchType().name()); }
if (s.getCreatedAt() != null) { n.put("createdAt", s.getCreatedAt().toEpochMilli() / 1000.0); }
if (s.getCapacityProviderStrategy() != null && !s.getCapacityProviderStrategy().isEmpty()) {
n.set("capacityProviderStrategy",
capacityProviderStrategyNode(s.getCapacityProviderStrategy()));
} else if (s.getLaunchType() != null) {
n.put("launchType", s.getLaunchType().name());
}
putInstant(n, "createdAt", s.getCreatedAt());
if (s.getNamespace() != null) { n.put("namespace", s.getNamespace()); }
// Services persisted before these fields existed read back with the AWS defaults.
n.put("schedulingStrategy", s.getSchedulingStrategy() != null
@@ -407,12 +633,15 @@ public class EcsResponseWriter {
}
private ObjectNode loadBalancerNode(EcsLoadBalancer lb) {
ObjectNode ln = objectMapper.createObjectNode();
if (lb.getTargetGroupArn() != null) { ln.put("targetGroupArn", lb.getTargetGroupArn()); }
if (lb.getLoadBalancerName() != null) { ln.put("loadBalancerName", lb.getLoadBalancerName()); }
if (lb.getContainerName() != null) { ln.put("containerName", lb.getContainerName()); }
if (lb.getContainerPort() != null) { ln.put("containerPort", lb.getContainerPort()); }
return ln;
ObjectNode n = objectMapper.createObjectNode();
if (lb.getTargetGroupArn() != null) { n.put("targetGroupArn", lb.getTargetGroupArn()); }
if (lb.getLoadBalancerName() != null) { n.put("loadBalancerName", lb.getLoadBalancerName()); }
if (lb.getContainerName() != null) { n.put("containerName", lb.getContainerName()); }
if (lb.getContainerPort() != null) { n.put("containerPort", lb.getContainerPort()); }
if (lb.getAdvancedConfiguration() != null) {
n.set("advancedConfiguration", objectMapper.valueToTree(lb.getAdvancedConfiguration()));
}
return n;
}
private ObjectNode networkConfigurationNode(AwsVpcConfiguration awsvpc) {
@@ -455,8 +684,6 @@ public class EcsResponseWriter {
return n;
}
// ── Container instances ───────────────────────────────────────────────────
public ObjectNode containerInstanceNode(ContainerInstance ci) {
ObjectNode n = objectMapper.createObjectNode();
n.put("containerInstanceArn", ci.getContainerInstanceArn());
@@ -477,8 +704,7 @@ public class EcsResponseWriter {
return n;
}
// ── Capacity providers ────────────────────────────────────────────────────
/** @param includeTags DescribeCapacityProviders returns tags only for {@code include: ["TAGS"]}. */
public ObjectNode capacityProviderNode(CapacityProvider cp) {
ObjectNode n = objectMapper.createObjectNode();
n.put("name", cp.getName());
@@ -490,8 +716,6 @@ public class EcsResponseWriter {
return n;
}
// ── Task sets ─────────────────────────────────────────────────────────────
public ObjectNode taskSetNode(TaskSet ts) {
ObjectNode n = objectMapper.createObjectNode();
n.put("id", ts.getId());
@@ -518,8 +742,6 @@ public class EcsResponseWriter {
return n;
}
// ── Service deployments and revisions ─────────────────────────────────────
public ObjectNode serviceDeploymentNode(ServiceDeployment d) {
ObjectNode n = objectMapper.createObjectNode();
n.put("serviceDeploymentArn", d.getServiceDeploymentArn());
@@ -543,15 +765,11 @@ public class EcsResponseWriter {
return n;
}
// ── Shared members ────────────────────────────────────────────────────────
public ObjectNode protectedTaskNode(ProtectedTask pt) {
ObjectNode n = objectMapper.createObjectNode();
n.put("taskArn", pt.taskArn());
n.put("protectionEnabled", pt.protectionEnabled());
if (pt.expirationDate() != null) {
n.put("expirationDate", pt.expirationDate().toEpochMilli() / 1000.0);
}
putInstant(n, "expirationDate", pt.expirationDate());
return n;
}
@@ -582,6 +800,24 @@ public class EcsResponseWriter {
return arr;
}
public ArrayNode capacityProviderStrategyNode(List<CapacityProviderStrategyItem> strategy) {
ArrayNode arr = objectMapper.createArrayNode();
for (CapacityProviderStrategyItem item : strategy) {
ObjectNode n = objectMapper.createObjectNode();
n.put("capacityProvider", item.capacityProvider());
n.put("weight", item.weight());
n.put("base", item.base());
arr.add(n);
}
return arr;
}
private ObjectNode ephemeralStorageNode(EphemeralStorage storage) {
ObjectNode n = objectMapper.createObjectNode();
n.put("sizeInGiB", storage.sizeInGiB());
return n;
}
private ArrayNode keyValuePairsNode(List<KeyValuePair> pairs) {
ArrayNode arr = objectMapper.createArrayNode();
for (KeyValuePair kv : pairs) {
@@ -593,6 +829,17 @@ public class EcsResponseWriter {
return arr;
}
private ArrayNode environmentFilesNode(List<EnvironmentFile> files) {
ArrayNode arr = objectMapper.createArrayNode();
for (EnvironmentFile file : files) {
ObjectNode fileNode = objectMapper.createObjectNode();
fileNode.put("value", file.value());
fileNode.put("type", file.type());
arr.add(fileNode);
}
return arr;
}
private ArrayNode secretsNode(List<Secret> secrets) {
ArrayNode arr = objectMapper.createArrayNode();
for (Secret secret : secrets) {
@@ -606,7 +853,16 @@ public class EcsResponseWriter {
private ArrayNode stringArray(List<String> values) {
ArrayNode arr = objectMapper.createArrayNode();
values.forEach(arr::add);
if (values != null) {
values.forEach(arr::add);
}
return arr;
}
/** ECS timestamps go on the wire as epoch seconds with a fractional part. */
private static void putInstant(ObjectNode target, String field, Instant value) {
if (value != null) {
target.put(field, value.toEpochMilli() / 1000.0);
}
}
}
File diff suppressed because it is too large. Load diff
@@ -22,17 +22,20 @@ import io.github.hectorvent.floci.services.ec2.model.SecurityGroup;
import io.github.hectorvent.floci.services.ecs.model.AwsVpcConfiguration;
import io.github.hectorvent.floci.services.ecs.model.Container;
import io.github.hectorvent.floci.services.ecs.model.ContainerDefinition;
import io.github.hectorvent.floci.services.ecs.model.ContainerDependency;
import io.github.hectorvent.floci.services.ecs.model.ContainerOverride;
import io.github.hectorvent.floci.services.ecs.model.EcsTask;
import io.github.hectorvent.floci.services.ecs.model.EfsVolumeConfiguration;
import io.github.hectorvent.floci.services.ecs.model.FirelensConfiguration;
import io.github.hectorvent.floci.services.ecs.model.LogConfiguration;
import io.github.hectorvent.floci.services.ecs.model.ManagedAgent;
import io.github.hectorvent.floci.services.ecs.model.MountPoint;
import io.github.hectorvent.floci.services.ecs.model.NetworkBinding;
import io.github.hectorvent.floci.services.ecs.model.NetworkMode;
import io.github.hectorvent.floci.services.ecs.model.PortMapping;
import io.github.hectorvent.floci.services.ecs.model.Secret;
import io.github.hectorvent.floci.services.ecs.model.TaskDefinition;
import io.github.hectorvent.floci.services.ecs.model.TaskNetworkInterface;
import io.github.hectorvent.floci.services.ecs.model.Volume;
import io.github.hectorvent.floci.services.ecs.model.VolumeFrom;
import io.github.hectorvent.floci.services.s3.S3Service;
@@ -67,6 +70,7 @@ import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Stream;
/**
@@ -78,6 +82,17 @@ public class EcsContainerManager {
private static final Logger LOG = Logger.getLogger(EcsContainerManager.class);
private static final String ATTACHMENT_DELETED = "DELETED";
/** EC2 error codes the task ENI path can raise, none of which RunTask declares. */
private static final Set<String> EC2_NETWORK_LOOKUP_FAILURES =
Set.of("InvalidSubnetID.NotFound", "InvalidGroup.NotFound");
/** How long a container waits for a dependency that has to COMPLETE, SUCCEED or get HEALTHY. */
private static final int DEPENDENCY_WAIT_SECONDS = 60;
private static final long DEPENDENCY_POLL_MILLIS = 200;
/** How long a killed container gets to register as exited before its code is read. */
private static final int KILL_SETTLE_SECONDS = 5;
private final ContainerBuilder containerBuilder;
private final ContainerLifecycleManager lifecycleManager;
private final ContainerLogStreamer logStreamer;
@@ -210,6 +225,7 @@ public class EcsContainerManager {
try {
for (ContainerDefinition def : launchOrder) {
awaitDependencies(def, containerIds);
String containerName = ContainerStorageHelper.dockerName(config, "floci-ecs-" + taskId + "-" + def.getName());
// RunTask containerOverrides matched by container name: command replaces
@@ -252,9 +268,33 @@ public class EcsContainerManager {
specBuilder.withNamedVolume(firelensVolumeName, "/var/run");
}
// Add memory limit if specified
// Resource limits. A container-level memory is its own hard limit; without one the
// container is capped at the task's memory, which is what a Fargate task gets
// (the whole task shares one allocation). The task's cpu becomes a quota and a
// container-level cpu becomes its share of that quota, as on ECS.
if (def.getMemory() != null) {
specBuilder.withMemoryMb(def.getMemory());
} else {
Integer taskMemoryMb = parseTaskMemoryMb(task.getMemory());
if (taskMemoryMb != null) {
specBuilder.withMemoryMb(taskMemoryMb);
}
}
Integer taskCpuUnits = parseTaskCpuUnits(task.getCpu());
if (taskCpuUnits != null) {
specBuilder.withCpuUnits(taskCpuUnits);
}
if (def.getCpu() != null && def.getCpu() > 0) {
specBuilder.withCpuShares(def.getCpu());
}
if (def.getUser() != null) {
specBuilder.withUser(def.getUser());
}
if (def.getWorkingDirectory() != null) {
specBuilder.withWorkingDir(def.getWorkingDirectory());
}
if (Boolean.TRUE.equals(def.getReadonlyRootFilesystem())) {
specBuilder.withReadonlyRootfs();
}
// Add port mappings. In bridge/host mode an explicit hostPort is
@@ -394,8 +434,7 @@ public class EcsContainerManager {
lifecycleManager.removeVolume(firelensVolumeName);
}
if (protectedNetwork != null) {
firewallManager.unregister(protectedNetwork.eni().getNetworkInterfaceId());
ec2Service.deleteNetworkInterface(region, protectedNetwork.eni().getNetworkInterfaceId());
releaseTaskNetwork(task, region);
}
throw e;
}
@@ -411,14 +450,160 @@ public class EcsContainerManager {
containersInDefinitionOrder.add(container);
}
}
// An awsvpc task's containers share the task ENI, and each reports it.
if (task.getNetworkInterfaceId() != null) {
List<TaskNetworkInterface> taskInterfaces = List.of(new TaskNetworkInterface(
task.getAttachmentId(), task.getPrivateIpAddress(), null));
containersInDefinitionOrder.forEach(container -> container.setNetworkInterfaces(taskInterfaces));
}
// ECS Exec is gated on the agent reporting RUNNING, which a client checks before it tries
// to open a session.
if (task.isEnableExecuteCommand()) {
List<ManagedAgent> agents = List.of(ManagedAgent.executeCommandAgent(Instant.now()));
containersInDefinitionOrder.forEach(container -> container.setManagedAgents(agents));
}
task.setContainers(containersInDefinitionOrder);
task.setLastStatus(TaskStatus.RUNNING.name());
task.setDesiredStatus(TaskStatus.RUNNING.name());
task.setStartedAt(Instant.now());
Map<String, Integer> stopTimeouts = new LinkedHashMap<>();
for (ContainerDefinition def : taskDef.getContainerDefinitions()) {
if (def.getStopTimeout() != null) {
stopTimeouts.put(def.getName(), def.getStopTimeout());
}
}
return new EcsTaskHandle(task.getTaskArn(), containerIds, logStreamsByContainerId,
firelensVolumeName,
protectedNetwork == null ? null : protectedNetwork.eni().getNetworkInterfaceId(), region);
protectedNetwork == null ? null : protectedNetwork.eni().getNetworkInterfaceId(), region,
stopTimeouts);
}
/** A task-level {@code memory} is MiB as a plain number, or a {@code "1GB"}-style string. */
private static Integer parseTaskMemoryMb(String memory) {
if (memory == null || memory.isBlank()) {
return null;
}
String trimmed = memory.trim().toUpperCase();
try {
if (trimmed.endsWith("GB")) {
return (int) Math.round(Double.parseDouble(trimmed.substring(0, trimmed.length() - 2).trim()) * 1024);
}
return Integer.parseInt(trimmed.replaceAll("(?i)mib|mb", "").trim());
} catch (NumberFormatException e) {
LOG.debugv("Ignoring unparseable task memory {0}", memory);
return null;
}
}
/** A task-level {@code cpu} is CPU units as a plain number, or a {@code "0.5vCPU"}-style string. */
private static Integer parseTaskCpuUnits(String cpu) {
if (cpu == null || cpu.isBlank()) {
return null;
}
String trimmed = cpu.trim().toUpperCase();
try {
if (trimmed.endsWith("VCPU")) {
return (int) Math.round(
Double.parseDouble(trimmed.substring(0, trimmed.length() - 4).trim()) * 1024);
}
return Integer.parseInt(trimmed);
} catch (NumberFormatException e) {
LOG.debugv("Ignoring unparseable task cpu {0}", cpu);
return null;
}
}
/**
* Holds a container's start until the containers it declared a {@code dependsOn} on have
* reached the state it asked for. {@code START} is satisfied by the launch order alone;
* {@code COMPLETE} and {@code SUCCESS} wait for the dependency to exit (and {@code SUCCESS}
* additionally requires it to have exited cleanly); {@code HEALTHY} waits for its health check
* to pass.
*
* <p>The wait is bounded by the dependent container's {@code startTimeout}, defaulting to
* {@value #DEPENDENCY_WAIT_SECONDS} seconds rather than AWS's longer agent default, because
* RunTask here is synchronous and a caller is holding the request open. A dependency that does
* not get there in time fails the task.
*/
private void awaitDependencies(ContainerDefinition definition, Map<String, String> startedContainerIds) {
if (definition.getDependsOn() == null || definition.getDependsOn().isEmpty()) {
return;
}
long timeoutSeconds = definition.getStartTimeout() != null
? definition.getStartTimeout() : DEPENDENCY_WAIT_SECONDS;
for (ContainerDependency dependency : definition.getDependsOn()) {
String condition = dependency.condition();
if (ContainerDependency.START.equals(condition)) {
continue;
}
String dockerId = startedContainerIds.get(dependency.containerName());
if (dockerId == null) {
continue;
}
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(timeoutSeconds);
while (!dependencySatisfied(dockerId, condition)) {
if (System.nanoTime() > deadline) {
throw new AwsException("ClientException",
"Container '" + definition.getName() + "' did not start because container '"
+ dependency.containerName() + "' did not reach " + condition
+ " within " + timeoutSeconds + " seconds.", 400);
}
try {
TimeUnit.MILLISECONDS.sleep(DEPENDENCY_POLL_MILLIS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new IllegalStateException("Interrupted while waiting for ECS container dependency "
+ dependency.containerName(), e);
}
}
}
}
private boolean dependencySatisfied(String dockerId, String condition) {
if (ContainerDependency.HEALTHY.equals(condition)) {
return "healthy".equals(inspectHealthStatus(dockerId));
}
Integer exitCode = getExitCodeIfStopped(dockerId);
if (exitCode == null) {
return false;
}
if (ContainerDependency.SUCCESS.equals(condition) && exitCode != 0) {
throw new AwsException("ClientException",
"A dependency container exited with code " + exitCode
+ ", so the containers depending on its SUCCESS were not started.", 400);
}
return true;
}
/**
* A container's health in ECS's vocabulary: {@code HEALTHY} or {@code UNHEALTHY} once its
* health check has reported, {@code UNKNOWN} while it is still starting or when the container
* declares no health check at all.
*/
public String ecsHealthStatus(String dockerId) {
String status = inspectHealthStatus(dockerId);
if (status == null) {
return "UNKNOWN";
}
return switch (status) {
case "healthy" -> "HEALTHY";
case "unhealthy" -> "UNHEALTHY";
default -> "UNKNOWN";
};
}
/** The Docker health status of a container, or null when it declares no health check. */
private String inspectHealthStatus(String dockerId) {
try {
InspectContainerResponse inspect = lifecycleManager.getDockerClient()
.inspectContainerCmd(dockerId).exec();
return inspect.getState() != null && inspect.getState().getHealth() != null
? inspect.getState().getHealth().getStatus() : null;
} catch (Exception e) {
LOG.debugv("Could not read the health of container {0}: {1}", dockerId, e.getMessage());
return null;
}
}
private List<ContainerDefinition> orderForDependencies(List<ContainerDefinition> definitions,
@@ -463,11 +648,121 @@ public class EcsContainerManager {
addAfterDependencies(source, definitionsByName, firelensRouter, visiting, visited, ordered);
}
}
if (definition.getDependsOn() != null) {
for (ContainerDependency dependency : definition.getDependsOn()) {
ContainerDefinition source = definitionsByName.get(dependency.containerName());
if (source == null) {
throw new IllegalArgumentException("ECS dependsOn references unknown container "
+ dependency.containerName());
}
addAfterDependencies(source, definitionsByName, firelensRouter, visiting, visited, ordered);
}
}
visiting.remove(definition);
visited.add(definition);
ordered.add(definition);
}
/**
* Gives an {@code awsvpc} task the elastic network interface AWS gives it: its own ENI in the
* requested subnet, with a private address of its own and the task's security groups.
*
* <p>Called for every {@code awsvpc} task, in Docker and in mock mode alike, because the ENI is
* control-plane state that DescribeTasks reports (a client waits on
* {@code attachments[].details[?name=='privateIPv4Address']} to find the task) rather than a
* property of the containers. Security-group enforcement, which additionally puts the task's
* containers in a protected network namespace, stays opt-in on top of it.
*
* <p>A subnet or security group that does not exist fails the task, reported as the
* {@code InvalidParameterException} RunTask declares rather than the EC2 code
* {@link Ec2Service#createNetworkInterface} raises.
*/
public void attachTaskNetwork(EcsTask task, TaskDefinition definition, String region) {
if (definition.getNetworkMode() != NetworkMode.awsvpc || ec2Service == null) {
return;
}
AwsVpcConfiguration awsvpc = task.getNetworkConfiguration() == null ? null
: task.getNetworkConfiguration().getAwsvpcConfiguration();
if (awsvpc == null || awsvpc.getSubnets() == null || awsvpc.getSubnets().isEmpty()) {
throw new AwsException("InvalidParameterException",
"Network Configuration must be provided when networkMode 'awsvpc' is specified.", 400);
}
String subnetId = awsvpc.getSubnets().getFirst();
NetworkInterface eni;
try {
eni = ec2Service.createNetworkInterface(region, subnetId,
"ECS task " + task.getTaskArn(), null, List.of(), awsvpc.getSecurityGroups(), List.of());
} catch (AwsException e) {
throw asEcsNetworkRejection(e);
}
// A running task holds its interface, so EC2 must report it "in-use" rather than
// "available" as a fresh one starts out, and must refuse to delete it under the task.
ec2Service.holdNetworkInterfaceForService(region, eni.getNetworkInterfaceId());
task.setNetworkInterfaceId(eni.getNetworkInterfaceId());
task.setPrivateIpAddress(eni.getPrivateIpAddress());
task.setMacAddress(eni.getMacAddress());
task.setPrivateDnsName(eni.getPrivateDnsName());
task.setAttachmentId("eni-attach-" + eni.getNetworkInterfaceId());
ec2Service.describeSubnets(region, List.of(subnetId), Map.of()).stream()
.findFirst()
.ifPresent(subnet -> task.setAvailabilityZone(subnet.getAvailabilityZone()));
}
/**
* Restates an EC2 lookup failure as the error RunTask declares. A caller naming a subnet or a
* security group that is not there asked for something the task cannot have, and
* {@code InvalidSubnetID.NotFound} is not in RunTask's error list, so an SDK sees it as an
* unmodelled failure rather than the InvalidParameterException AWS returns. Anything else the
* ENI path raises is already an ECS-shaped error and travels unchanged.
*/
private static AwsException asEcsNetworkRejection(AwsException e) {
if (!EC2_NETWORK_LOOKUP_FAILURES.contains(e.getErrorCode())) {
return e;
}
return new AwsException("InvalidParameterException", e.getMessage(), 400);
}
/**
* Releases a stopped task's ENI. The interface id stays on the task, with its attachment
* reported as {@code DELETED}, because AWS keeps describing a stopped task's attachment.
* Idempotent: the status is flipped first, so a second teardown path does nothing.
*/
public void releaseTaskNetwork(EcsTask task, String region) {
String eniId = task.getNetworkInterfaceId();
if (eniId == null || ec2Service == null || ATTACHMENT_DELETED.equals(task.getAttachmentStatus())) {
return;
}
task.setAttachmentStatus(ATTACHMENT_DELETED);
if (firewallManager != null) {
firewallManager.unregister(eniId);
}
try {
// EC2 refuses to delete an interface that is in use, and attachTaskNetwork marked
// this one as held by the task, so the hold goes before the interface does.
ec2Service.releaseNetworkInterfaceFromService(region, eniId);
ec2Service.deleteNetworkInterface(region, eniId);
} catch (RuntimeException e) {
LOG.debugv("Could not delete the ENI {0} of task {1}: {2}",
eniId, task.getTaskArn(), e.getMessage());
}
}
/** The ENI {@link #attachTaskNetwork} allocated for this task, or null if it is already gone. */
private NetworkInterface existingTaskEni(EcsTask task, String region) {
if (task.getNetworkInterfaceId() == null) {
return null;
}
try {
return ec2Service.describeNetworkInterfaces(region, List.of(task.getNetworkInterfaceId()),
Map.of(), 0, null)
.networkInterfaces().stream().findFirst().orElse(null);
} catch (RuntimeException e) {
LOG.debugv("Could not resolve the ENI {0} of task {1}, allocating a new one: {2}",
task.getNetworkInterfaceId(), task.getTaskArn(), e.getMessage());
return null;
}
}
private PreparedNetwork prepareNetwork(EcsTask task, TaskDefinition definition, String region, String taskId) {
if (definition.getNetworkMode() != NetworkMode.awsvpc
|| firewallManager == null || !firewallManager.enabled()) {
@@ -478,8 +773,13 @@ public class EcsContainerManager {
if (awsvpc == null || awsvpc.getSubnets() == null || awsvpc.getSubnets().isEmpty()) {
throw new AwsException("ClientException", "awsvpc tasks require a subnet", 400);
}
NetworkInterface eni = ec2Service.createNetworkInterface(region, awsvpc.getSubnets().getFirst(),
"ECS task " + task.getTaskArn(), null, List.of(), awsvpc.getSecurityGroups(), List.of());
// attachTaskNetwork already allocated the task ENI; the namespace is built around it.
NetworkInterface eni = existingTaskEni(task, region);
if (eni == null) {
eni = ec2Service.createNetworkInterface(region, awsvpc.getSubnets().getFirst(),
"ECS task " + task.getTaskArn(), null, List.of(), awsvpc.getSecurityGroups(), List.of());
ec2Service.holdNetworkInterfaceForService(region, eni.getNetworkInterfaceId());
}
String eniId = eni.getNetworkInterfaceId();
SecurityGroupFirewallManager.Namespace namespace = null;
try {
@@ -514,6 +814,7 @@ public class EcsContainerManager {
if (namespace != null) {
lifecycleManager.removeIfExists(namespace.helperId());
}
ec2Service.releaseNetworkInterfaceFromService(region, eniId);
ec2Service.deleteNetworkInterface(region, eniId);
throw e;
}
@@ -576,17 +877,21 @@ public class EcsContainerManager {
return exitCodes;
}
// Phase 1: stop all containers (no-op for those already exited).
// Phase 1: stop all containers (no-op for those already exited), each given the grace
// period its container definition asked for.
Set<String> terminatedContainerIds = new HashSet<>();
for (String dockerId : handle.getContainerIds().values()) {
for (Map.Entry<String, String> entry : handle.getContainerIds().entrySet()) {
String dockerId = entry.getValue();
try {
lifecycleManager.getDockerClient().stopContainerCmd(dockerId).withTimeout(5).exec();
lifecycleManager.getDockerClient().stopContainerCmd(dockerId)
.withTimeout(handle.stopTimeoutFor(entry.getKey())).exec();
terminatedContainerIds.add(dockerId);
} catch (NotFoundException ignored) {
terminatedContainerIds.add(dockerId);
} catch (Exception e) {
LOG.warnv("Error stopping ECS container {0}: {1}", dockerId, e.getMessage());
}
killIfStillRunning(dockerId);
}
// Phase 2: inspect exit codes, then remove.
@@ -611,6 +916,37 @@ public class EcsContainerManager {
return exitCodes;
}
/**
* Makes sure a container really is stopped before its exit code is read.
*
* <p>A container that ignores SIGTERM only dies when its {@code stopTimeout} elapses, and the
* Docker client can give up on the stop request before the daemon gets there. Either way the
* container would still be running when the exit code is collected, and the task would report
* no exit code at all, so it is killed here.
*/
private void killIfStillRunning(String dockerId) {
if (getExitCodeIfStopped(dockerId) != null) {
return;
}
try {
lifecycleManager.getDockerClient().killContainerCmd(dockerId).exec();
} catch (NotFoundException ignored) {
return; // already gone, and its exit code is whatever the earlier inspect saw
} catch (Exception e) {
LOG.warnv("Error killing ECS container {0}: {1}", dockerId, e.getMessage());
return;
}
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(KILL_SETTLE_SECONDS);
while (System.nanoTime() < deadline && getExitCodeIfStopped(dockerId) == null) {
try {
TimeUnit.MILLISECONDS.sleep(DEPENDENCY_POLL_MILLIS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return;
}
}
}
private void removeFirelensVolume(EcsTaskHandle handle) {
if (handle == null || handle.getFirelensVolumeName() == null) {
return;
@@ -856,10 +1192,14 @@ public class EcsContainerManager {
}
return "127.0.0.1";
}
/**
* Tears down the firewall registration of a protected task. The ENI itself outlives this:
* it belongs to the task, not to its containers, and {@link #releaseTaskNetwork} frees it when
* the task reaches STOPPED.
*/
private void cleanupProtectedNetwork(EcsTaskHandle handle) {
if (firewallManager != null && handle.getNetworkInterfaceId() != null) {
firewallManager.unregister(handle.getNetworkInterfaceId());
ec2Service.deleteNetworkInterface(handle.getRegion(), handle.getNetworkInterfaceId());
}
}
@@ -1108,6 +1448,17 @@ public class EcsContainerManager {
container.setLastStatus("RUNNING");
container.setNetworkBindings(networkBindings);
container.setDockerId(dockerId);
container.setRuntimeId(dockerId);
container.setHealthStatus(def.getHealthCheck() != null ? "UNKNOWN" : null);
if (def.getCpu() != null) {
container.setCpu(String.valueOf(def.getCpu()));
}
if (def.getMemory() != null) {
container.setMemory(String.valueOf(def.getMemory()));
}
if (def.getMemoryReservation() != null) {
container.setMemoryReservation(String.valueOf(def.getMemoryReservation()));
}
container.setContainerArn(regionResolver.buildArn("ecs", region,
"container/" + extractTaskId(taskArn) + "/" + def.getName()));
return container;
@@ -10,12 +10,24 @@ import java.util.Map;
*/
public class EcsTaskHandle {
/**
* The grace period a container gets when its definition does not ask for one.
*
* <p>ECS defaults to 30 seconds. Floci answers StopTask synchronously, and a container that
* ignores SIGTERM (anything running as PID 1 without a signal handler, which is most of them)
* would hold the caller for the whole period, so the implicit default stays short. A
* {@code stopTimeout} the task definition asks for is honoured as given.
*/
public static final int DEFAULT_STOP_TIMEOUT_SECONDS = 5;
private final String taskArn;
private final Map<String, String> containerIds; // containerName → dockerId
private final Map<String, Closeable> logStreamsByContainerId;
private final String firelensVolumeName;
private final String networkInterfaceId;
private final String region;
/** Per-container {@code stopTimeout}, so teardown waits as long as the task definition asked. */
private final Map<String, Integer> stopTimeouts;
public EcsTaskHandle(String taskArn, Map<String, String> containerIds,
Map<String, Closeable> logStreamsByContainerId) {
@@ -25,12 +37,21 @@ public class EcsTaskHandle {
public EcsTaskHandle(String taskArn, Map<String, String> containerIds,
Map<String, Closeable> logStreamsByContainerId,
String firelensVolumeName, String networkInterfaceId, String region) {
this(taskArn, containerIds, logStreamsByContainerId, firelensVolumeName,
networkInterfaceId, region, Map.of());
}
public EcsTaskHandle(String taskArn, Map<String, String> containerIds,
Map<String, Closeable> logStreamsByContainerId,
String firelensVolumeName, String networkInterfaceId, String region,
Map<String, Integer> stopTimeouts) {
this.taskArn = taskArn;
this.containerIds = new LinkedHashMap<>(containerIds);
this.logStreamsByContainerId = new LinkedHashMap<>(logStreamsByContainerId);
this.firelensVolumeName = firelensVolumeName;
this.networkInterfaceId = networkInterfaceId;
this.region = region;
this.stopTimeouts = new LinkedHashMap<>(stopTimeouts);
}
public String getTaskArn() { return taskArn; }
@@ -40,6 +61,12 @@ public class EcsTaskHandle {
public String getNetworkInterfaceId() { return networkInterfaceId; }
public String getRegion() { return region; }
/** The container's {@code stopTimeout} in seconds, or {@link #DEFAULT_STOP_TIMEOUT_SECONDS}. */
public int stopTimeoutFor(String containerName) {
Integer configured = stopTimeouts.get(containerName);
return configured != null ? configured : DEFAULT_STOP_TIMEOUT_SECONDS;
}
/** Removes and returns the log stream that no longer needs task-level ownership. */
public Closeable removeLogStream(String containerId) {
return logStreamsByContainerId.remove(containerId);
@@ -0,0 +1,19 @@
package io.github.hectorvent.floci.services.ecs.model;
import io.quarkus.runtime.annotations.RegisterForReflection;
/**
* One entry of a {@code capacityProviderStrategy}:
* {@code {"capacityProvider": "FARGATE_SPOT", "weight": 1, "base": 0}}.
*
* <p>{@code base} is the number of tasks placed on the provider before any weighting applies, and
* at most one entry of a strategy may set it. {@code weight} is that provider's share of whatever
* is left.
*/
@RegisterForReflection
public record CapacityProviderStrategyItem(String capacityProvider, int weight, int base) {
public CapacityProviderStrategyItem(String capacityProvider) {
this(capacityProvider, 0, 0);
}
}
@@ -15,6 +15,14 @@ public class Container {
private Integer exitCode;
private String reason;
private List<NetworkBinding> networkBindings;
private List<TaskNetworkInterface> networkInterfaces;
private List<ManagedAgent> managedAgents;
private String healthStatus;
private String runtimeId;
private String imageDigest;
private String cpu;
private String memory;
private String memoryReservation;
// transient — not persisted
private transient String dockerId;
@@ -43,6 +51,32 @@ public class Container {
public List<NetworkBinding> getNetworkBindings() { return networkBindings; }
public void setNetworkBindings(List<NetworkBinding> networkBindings) { this.networkBindings = networkBindings; }
public List<TaskNetworkInterface> getNetworkInterfaces() { return networkInterfaces; }
public void setNetworkInterfaces(List<TaskNetworkInterface> networkInterfaces) {
this.networkInterfaces = networkInterfaces;
}
public List<ManagedAgent> getManagedAgents() { return managedAgents; }
public void setManagedAgents(List<ManagedAgent> managedAgents) { this.managedAgents = managedAgents; }
public String getHealthStatus() { return healthStatus; }
public void setHealthStatus(String healthStatus) { this.healthStatus = healthStatus; }
public String getRuntimeId() { return runtimeId; }
public void setRuntimeId(String runtimeId) { this.runtimeId = runtimeId; }
public String getImageDigest() { return imageDigest; }
public void setImageDigest(String imageDigest) { this.imageDigest = imageDigest; }
public String getCpu() { return cpu; }
public void setCpu(String cpu) { this.cpu = cpu; }
public String getMemory() { return memory; }
public void setMemory(String memory) { this.memory = memory; }
public String getMemoryReservation() { return memoryReservation; }
public void setMemoryReservation(String memoryReservation) { this.memoryReservation = memoryReservation; }
public String getDockerId() { return dockerId; }
public void setDockerId(String dockerId) { this.dockerId = dockerId; }
}
@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.ecs.model;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.util.List;
import java.util.Map;
@RegisterForReflection
public class ContainerDefinition {
@@ -15,14 +16,33 @@ public class ContainerDefinition {
private boolean essential = true;
private List<PortMapping> portMappings;
private List<KeyValuePair> environment;
private List<EnvironmentFile> environmentFiles;
private List<Secret> secrets;
private List<String> command;
private List<String> entryPoint;
private List<MountPoint> mountPoints;
private List<VolumeFrom> volumesFrom;
private List<ContainerDependency> dependsOn;
private LogConfiguration logConfiguration;
private FirelensConfiguration firelensConfiguration;
private HealthCheck healthCheck;
private Integer startTimeout;
private Integer stopTimeout;
private String user;
private String workingDirectory;
private String hostname;
private Boolean readonlyRootFilesystem;
private Boolean privileged;
private Boolean disableNetworking;
private Boolean interactive;
private Boolean pseudoTerminal;
private List<String> links;
private List<String> dnsServers;
private List<String> dnsSearchDomains;
private List<String> dockerSecurityOptions;
private Map<String, String> dockerLabels;
private String repositoryCredentialsParameter;
private Map<String, Object> unparsed;
public String getName() { return name; }
public void setName(String name) { this.name = name; }
@@ -72,4 +92,69 @@ public class ContainerDefinition {
}
public HealthCheck getHealthCheck() { return healthCheck; }
public void setHealthCheck(HealthCheck healthCheck) { this.healthCheck = healthCheck; }
public List<EnvironmentFile> getEnvironmentFiles() { return environmentFiles; }
public void setEnvironmentFiles(List<EnvironmentFile> environmentFiles) {
this.environmentFiles = environmentFiles;
}
public List<ContainerDependency> getDependsOn() { return dependsOn; }
public void setDependsOn(List<ContainerDependency> dependsOn) { this.dependsOn = dependsOn; }
public Integer getStartTimeout() { return startTimeout; }
public void setStartTimeout(Integer startTimeout) { this.startTimeout = startTimeout; }
public Integer getStopTimeout() { return stopTimeout; }
public void setStopTimeout(Integer stopTimeout) { this.stopTimeout = stopTimeout; }
public String getUser() { return user; }
public void setUser(String user) { this.user = user; }
public String getWorkingDirectory() { return workingDirectory; }
public void setWorkingDirectory(String workingDirectory) { this.workingDirectory = workingDirectory; }
public String getHostname() { return hostname; }
public void setHostname(String hostname) { this.hostname = hostname; }
public Boolean getReadonlyRootFilesystem() { return readonlyRootFilesystem; }
public void setReadonlyRootFilesystem(Boolean readonlyRootFilesystem) {
this.readonlyRootFilesystem = readonlyRootFilesystem;
}
public Boolean getPrivileged() { return privileged; }
public void setPrivileged(Boolean privileged) { this.privileged = privileged; }
public Boolean getDisableNetworking() { return disableNetworking; }
public void setDisableNetworking(Boolean disableNetworking) { this.disableNetworking = disableNetworking; }
public Boolean getInteractive() { return interactive; }
public void setInteractive(Boolean interactive) { this.interactive = interactive; }
public Boolean getPseudoTerminal() { return pseudoTerminal; }
public void setPseudoTerminal(Boolean pseudoTerminal) { this.pseudoTerminal = pseudoTerminal; }
public List<String> getLinks() { return links; }
public void setLinks(List<String> links) { this.links = links; }
public List<String> getDnsServers() { return dnsServers; }
public void setDnsServers(List<String> dnsServers) { this.dnsServers = dnsServers; }
public List<String> getDnsSearchDomains() { return dnsSearchDomains; }
public void setDnsSearchDomains(List<String> dnsSearchDomains) { this.dnsSearchDomains = dnsSearchDomains; }
public List<String> getDockerSecurityOptions() { return dockerSecurityOptions; }
public void setDockerSecurityOptions(List<String> dockerSecurityOptions) {
this.dockerSecurityOptions = dockerSecurityOptions;
}
public Map<String, String> getDockerLabels() { return dockerLabels; }
public void setDockerLabels(Map<String, String> dockerLabels) { this.dockerLabels = dockerLabels; }
public String getRepositoryCredentialsParameter() { return repositoryCredentialsParameter; }
public void setRepositoryCredentialsParameter(String repositoryCredentialsParameter) {
this.repositoryCredentialsParameter = repositoryCredentialsParameter;
}
public Map<String, Object> getUnparsed() { return unparsed; }
public void setUnparsed(Map<String, Object> unparsed) { this.unparsed = unparsed; }
}
@@ -0,0 +1,18 @@
package io.github.hectorvent.floci.services.ecs.model;
import io.quarkus.runtime.annotations.RegisterForReflection;
/**
* A {@code dependsOn} entry of an ECS container definition:
* {@code {"containerName": ..., "condition": "START"|"COMPLETE"|"SUCCESS"|"HEALTHY"}}.
*
* <p>The condition decides how far the named container must get before the dependent one starts.
*/
@RegisterForReflection
public record ContainerDependency(String containerName, String condition) {
public static final String START = "START";
public static final String COMPLETE = "COMPLETE";
public static final String SUCCESS = "SUCCESS";
public static final String HEALTHY = "HEALTHY";
}
@@ -16,6 +16,10 @@ public class ContainerOverride {
private String name;
private List<String> command;
private List<KeyValuePair> environment;
private List<EnvironmentFile> environmentFiles;
private Integer cpu;
private Integer memory;
private Integer memoryReservation;
public String getName() { return name; }
public void setName(String name) { this.name = name; }
@@ -25,4 +29,18 @@ public class ContainerOverride {
public List<KeyValuePair> getEnvironment() { return environment; }
public void setEnvironment(List<KeyValuePair> environment) { this.environment = environment; }
public List<EnvironmentFile> getEnvironmentFiles() { return environmentFiles; }
public void setEnvironmentFiles(List<EnvironmentFile> environmentFiles) {
this.environmentFiles = environmentFiles;
}
public Integer getCpu() { return cpu; }
public void setCpu(Integer cpu) { this.cpu = cpu; }
public Integer getMemory() { return memory; }
public void setMemory(Integer memory) { this.memory = memory; }
public Integer getMemoryReservation() { return memoryReservation; }
public void setMemoryReservation(Integer memoryReservation) { this.memoryReservation = memoryReservation; }
}
@@ -12,6 +12,8 @@ public class CreateClusterRequest {
private String clusterName;
private Map<String, String> tags;
private List<ClusterSetting> settings;
private List<String> capacityProviders;
private List<Map<String, Object>> defaultCapacityProviderStrategy;
public String getClusterName() { return clusterName; }
public void setClusterName(String clusterName) { this.clusterName = clusterName; }
@@ -21,4 +23,15 @@ public class CreateClusterRequest {
public List<ClusterSetting> getSettings() { return settings; }
public void setSettings(List<ClusterSetting> settings) { this.settings = settings; }
public List<String> getCapacityProviders() { return capacityProviders; }
public void setCapacityProviders(List<String> capacityProviders) { this.capacityProviders = capacityProviders; }
public List<Map<String, Object>> getDefaultCapacityProviderStrategy() {
return defaultCapacityProviderStrategy;
}
public void setDefaultCapacityProviderStrategy(List<Map<String, Object>> strategy) {
this.defaultCapacityProviderStrategy = strategy;
}
}
@@ -14,6 +14,7 @@ public class CreateServiceRequest {
private String taskDefinition;
private int desiredCount = 1;
private LaunchType launchType;
private List<CapacityProviderStrategyItem> capacityProviderStrategy;
private List<EcsLoadBalancer> loadBalancers;
private NetworkConfiguration networkConfiguration;
private Map<String, String> tags;
@@ -37,6 +38,11 @@ public class CreateServiceRequest {
public LaunchType getLaunchType() { return launchType; }
public void setLaunchType(LaunchType launchType) { this.launchType = launchType; }
public List<CapacityProviderStrategyItem> getCapacityProviderStrategy() { return capacityProviderStrategy; }
public void setCapacityProviderStrategy(List<CapacityProviderStrategyItem> capacityProviderStrategy) {
this.capacityProviderStrategy = capacityProviderStrategy;
}
public List<EcsLoadBalancer> getLoadBalancers() { return loadBalancers; }
public void setLoadBalancers(List<EcsLoadBalancer> loadBalancers) { this.loadBalancers = loadBalancers; }
@@ -65,4 +71,5 @@ public class CreateServiceRequest {
public void setServiceConnectConfiguration(Map<String, Object> serviceConnectConfiguration) {
this.serviceConnectConfiguration = serviceConnectConfiguration;
}
}
@@ -2,6 +2,8 @@ package io.github.hectorvent.floci.services.ecs.model;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.util.Map;
/**
* A load balancer association on an ECS service ({@code CreateService}'s
* {@code loadBalancers} block). Links a container port on the service's tasks
@@ -14,9 +16,16 @@ public class EcsLoadBalancer {
private String loadBalancerName;
private String containerName;
private Integer containerPort;
/** {@code advancedConfiguration}, kept raw: Floci runs no blue/green traffic shifting. */
private Map<String, Object> advancedConfiguration;
public EcsLoadBalancer() {}
public Map<String, Object> getAdvancedConfiguration() { return advancedConfiguration; }
public void setAdvancedConfiguration(Map<String, Object> advancedConfiguration) {
this.advancedConfiguration = advancedConfiguration;
}
public String getTargetGroupArn() { return targetGroupArn; }
public void setTargetGroupArn(String targetGroupArn) { this.targetGroupArn = targetGroupArn; }
@@ -40,6 +40,7 @@ public class EcsServiceModel {
* it; the Service shape itself has no member for it.
*/
private Map<String, Object> serviceConnectConfiguration;
private List<CapacityProviderStrategyItem> capacityProviderStrategy;
public String getServiceArn() { return serviceArn; }
public void setServiceArn(String serviceArn) { this.serviceArn = serviceArn; }
@@ -112,4 +113,10 @@ public class EcsServiceModel {
public void setServiceConnectConfiguration(Map<String, Object> serviceConnectConfiguration) {
this.serviceConnectConfiguration = serviceConnectConfiguration;
}
public List<CapacityProviderStrategyItem> getCapacityProviderStrategy() { return capacityProviderStrategy; }
public void setCapacityProviderStrategy(List<CapacityProviderStrategyItem> capacityProviderStrategy) {
this.capacityProviderStrategy = capacityProviderStrategy;
}
}
@@ -41,6 +41,30 @@ public class EcsTask {
private NetworkConfiguration networkConfiguration;
private String networkInterfaceId;
private String privateIpAddress;
private String macAddress;
private String privateDnsName;
private String attachmentId;
/** {@code ATTACHED} while the task holds its ENI, {@code DELETED} once it has been released. */
private String attachmentStatus = "ATTACHED";
private String platformVersion;
private String platformFamily;
/** Set instead of {@link #launchType} when the task was placed through a capacity provider. */
private String capacityProviderName;
private String connectivity;
private Instant connectivityAt;
private String healthStatus;
private String stopCode;
private String availabilityZone;
private Instant pullStartedAt;
private Instant pullStoppedAt;
private Instant executionStoppedAt;
private Instant stoppingAt;
private EphemeralStorage ephemeralStorage;
private boolean enableExecuteCommand;
private TaskOverride overrides;
private List<Attribute> attributes;
/** Bumped on every state change, the way AWS advances a task's optimistic-locking version. */
private long version = 1;
public EcsTask() {
}
@@ -76,6 +100,27 @@ public class EcsTask {
this.networkConfiguration = other.networkConfiguration;
this.networkInterfaceId = other.networkInterfaceId;
this.privateIpAddress = other.privateIpAddress;
this.macAddress = other.macAddress;
this.privateDnsName = other.privateDnsName;
this.attachmentId = other.attachmentId;
this.attachmentStatus = other.attachmentStatus;
this.platformVersion = other.platformVersion;
this.platformFamily = other.platformFamily;
this.capacityProviderName = other.capacityProviderName;
this.connectivity = other.connectivity;
this.connectivityAt = other.connectivityAt;
this.healthStatus = other.healthStatus;
this.stopCode = other.stopCode;
this.availabilityZone = other.availabilityZone;
this.pullStartedAt = other.pullStartedAt;
this.pullStoppedAt = other.pullStoppedAt;
this.executionStoppedAt = other.executionStoppedAt;
this.stoppingAt = other.stoppingAt;
this.ephemeralStorage = other.ephemeralStorage;
this.enableExecuteCommand = other.enableExecuteCommand;
this.overrides = other.overrides;
this.attributes = other.attributes;
this.version = other.version;
}
public String getTaskArn() { return taskArn; }
@@ -136,6 +181,12 @@ public class EcsTask {
public String getPrivateIpAddress() { return privateIpAddress; }
public void setPrivateIpAddress(String privateIpAddress) { this.privateIpAddress = privateIpAddress; }
public String getMacAddress() { return macAddress; }
public void setMacAddress(String macAddress) { this.macAddress = macAddress; }
public String getPrivateDnsName() { return privateDnsName; }
public void setPrivateDnsName(String privateDnsName) { this.privateDnsName = privateDnsName; }
public String getStoppedReason() { return stoppedReason; }
public void setStoppedReason(String stoppedReason) { this.stoppedReason = stoppedReason; }
@@ -153,4 +204,69 @@ public class EcsTask {
public Map<String, String> getTags() { return tags; }
public void setTags(Map<String, String> tags) { this.tags = tags; }
public String getAttachmentId() { return attachmentId; }
public void setAttachmentId(String attachmentId) { this.attachmentId = attachmentId; }
public String getAttachmentStatus() { return attachmentStatus; }
public void setAttachmentStatus(String attachmentStatus) { this.attachmentStatus = attachmentStatus; }
public String getPlatformVersion() { return platformVersion; }
public void setPlatformVersion(String platformVersion) { this.platformVersion = platformVersion; }
public String getPlatformFamily() { return platformFamily; }
public void setPlatformFamily(String platformFamily) { this.platformFamily = platformFamily; }
public String getCapacityProviderName() { return capacityProviderName; }
public void setCapacityProviderName(String capacityProviderName) {
this.capacityProviderName = capacityProviderName;
}
public String getConnectivity() { return connectivity; }
public void setConnectivity(String connectivity) { this.connectivity = connectivity; }
public Instant getConnectivityAt() { return connectivityAt; }
public void setConnectivityAt(Instant connectivityAt) { this.connectivityAt = connectivityAt; }
public String getHealthStatus() { return healthStatus; }
public void setHealthStatus(String healthStatus) { this.healthStatus = healthStatus; }
public String getStopCode() { return stopCode; }
public void setStopCode(String stopCode) { this.stopCode = stopCode; }
public String getAvailabilityZone() { return availabilityZone; }
public void setAvailabilityZone(String availabilityZone) { this.availabilityZone = availabilityZone; }
public Instant getPullStartedAt() { return pullStartedAt; }
public void setPullStartedAt(Instant pullStartedAt) { this.pullStartedAt = pullStartedAt; }
public Instant getPullStoppedAt() { return pullStoppedAt; }
public void setPullStoppedAt(Instant pullStoppedAt) { this.pullStoppedAt = pullStoppedAt; }
public Instant getExecutionStoppedAt() { return executionStoppedAt; }
public void setExecutionStoppedAt(Instant executionStoppedAt) { this.executionStoppedAt = executionStoppedAt; }
/** When the task left RUNNING for STOPPING, which AWS reports alongside {@code stoppedAt}. */
public Instant getStoppingAt() { return stoppingAt; }
public void setStoppingAt(Instant stoppingAt) { this.stoppingAt = stoppingAt; }
public EphemeralStorage getEphemeralStorage() { return ephemeralStorage; }
public void setEphemeralStorage(EphemeralStorage ephemeralStorage) { this.ephemeralStorage = ephemeralStorage; }
public boolean isEnableExecuteCommand() { return enableExecuteCommand; }
public void setEnableExecuteCommand(boolean enableExecuteCommand) {
this.enableExecuteCommand = enableExecuteCommand;
}
public TaskOverride getOverrides() { return overrides; }
public void setOverrides(TaskOverride overrides) { this.overrides = overrides; }
public List<Attribute> getAttributes() { return attributes; }
public void setAttributes(List<Attribute> attributes) { this.attributes = attributes; }
public long getVersion() { return version; }
public void setVersion(long version) { this.version = version; }
/** Advances the version AWS bumps on every task state transition. */
public void bumpVersion() { this.version++; }
}
@@ -0,0 +1,11 @@
package io.github.hectorvent.floci.services.ecs.model;
import io.quarkus.runtime.annotations.RegisterForReflection;
/**
* An {@code environmentFiles} entry of an ECS container definition:
* {@code {"value": "<s3 object arn>", "type": "s3"}}.
*/
@RegisterForReflection
public record EnvironmentFile(String value, String type) {
}
@@ -0,0 +1,17 @@
package io.github.hectorvent.floci.services.ecs.model;
import io.quarkus.runtime.annotations.RegisterForReflection;
/**
* The {@code ephemeralStorage} of a Fargate task definition or a RunTask override:
* {@code {"sizeInGiB": 21}}.
*
* <p>Floci reports the requested size but does not cap the container's writable layer at it.
*/
@RegisterForReflection
public record EphemeralStorage(int sizeInGiB) {
/** The storage a Fargate task gets without asking, and the floor for an explicit request. */
public static final int DEFAULT_SIZE_IN_GIB = 20;
public static final int MAX_SIZE_IN_GIB = 200;
}
@@ -4,5 +4,5 @@ import io.quarkus.runtime.annotations.RegisterForReflection;
@RegisterForReflection
public enum LaunchType {
EC2, FARGATE, EXTERNAL
EC2, FARGATE, EXTERNAL, MANAGED_INSTANCES
}
@@ -0,0 +1,24 @@
package io.github.hectorvent.floci.services.ecs.model;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.time.Instant;
/**
* A {@code managedAgents} entry of a described container:
* {@code {"name": "ExecuteCommandAgent", "lastStatus": "RUNNING", "lastStartedAt": ...}}.
*
* <p>ECS Exec is gated on this agent reporting {@code RUNNING}, which is what
* {@code aws ecs execute-command} and the {@code TasksRunning} waiter read.
*/
@RegisterForReflection
public record ManagedAgent(String name, String lastStatus, String reason, Instant lastStartedAt) {
public static final String EXECUTE_COMMAND_AGENT = "ExecuteCommandAgent";
public static final String RUNNING = "RUNNING";
public static final String STOPPED = "STOPPED";
public static ManagedAgent executeCommandAgent(Instant startedAt) {
return new ManagedAgent(EXECUTE_COMMAND_AGENT, RUNNING, null, startedAt);
}
}
@@ -2,10 +2,22 @@ package io.github.hectorvent.floci.services.ecs.model;
import io.quarkus.runtime.annotations.RegisterForReflection;
/**
* A container's port mapping.
*
* <p>{@code name} and {@code appProtocol} carry no behaviour here, but they are what a service's
* {@code serviceConnectConfiguration} and {@code vpcLatticeConfigurations} reference by name, so a
* definition registered for Service Connect has to read back with them intact.
*/
@RegisterForReflection
public record PortMapping(int containerPort, int hostPort, String protocol) {
public record PortMapping(int containerPort, int hostPort, String protocol, String name,
String appProtocol, String containerPortRange) {
public PortMapping(int containerPort) {
this(containerPort, 0, "tcp");
}
public PortMapping(int containerPort, int hostPort, String protocol) {
this(containerPort, hostPort, protocol, null, null, null);
}
}
@@ -26,7 +26,12 @@ public class RegisterTaskDefinitionRequest {
private List<String> requiresCompatibilities;
private List<Volume> volumes;
private RuntimePlatform runtimePlatform;
private EphemeralStorage ephemeralStorage;
private String pidMode;
private String ipcMode;
private Map<String, String> tags;
/** Members Floci does not act on, such as proxyConfiguration and placementConstraints. */
private Map<String, Object> unparsed;
public String getFamily() { return family; }
public void setFamily(String family) { this.family = family; }
@@ -62,9 +67,23 @@ public class RegisterTaskDefinitionRequest {
public RuntimePlatform getRuntimePlatform() { return runtimePlatform; }
public void setRuntimePlatform(RuntimePlatform runtimePlatform) { this.runtimePlatform = runtimePlatform; }
public EphemeralStorage getEphemeralStorage() { return ephemeralStorage; }
public void setEphemeralStorage(EphemeralStorage ephemeralStorage) {
this.ephemeralStorage = ephemeralStorage;
}
public String getPidMode() { return pidMode; }
public void setPidMode(String pidMode) { this.pidMode = pidMode; }
public String getIpcMode() { return ipcMode; }
public void setIpcMode(String ipcMode) { this.ipcMode = ipcMode; }
public Map<String, String> getTags() { return tags; }
public void setTags(Map<String, String> tags) { this.tags = tags; }
public Map<String, Object> getUnparsed() { return unparsed; }
public void setUnparsed(Map<String, Object> unparsed) { this.unparsed = unparsed; }
public boolean isFargate() {
return requiresCompatibilities != null && requiresCompatibilities.contains("FARGATE");
}
@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.ecs.model;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.util.List;
import java.util.Map;
/**
* A parsed {@code RunTask} (or {@code StartTask}) request.
@@ -19,10 +20,17 @@ public class RunTaskRequest {
private String taskDefinition;
private int count = 1;
private LaunchType launchType;
private List<CapacityProviderStrategyItem> capacityProviderStrategy;
private String group;
private String startedBy;
private List<ContainerOverride> containerOverrides;
private TaskOverride overrides;
private NetworkConfiguration networkConfiguration;
private String platformVersion;
private boolean enableExecuteCommand;
private boolean enableECSManagedTags;
private String propagateTags;
private String referenceId;
private Map<String, String> tags;
private List<String> containerInstances;
public String getCluster() { return cluster; }
@@ -37,15 +45,22 @@ public class RunTaskRequest {
public LaunchType getLaunchType() { return launchType; }
public void setLaunchType(LaunchType launchType) { this.launchType = launchType; }
public List<CapacityProviderStrategyItem> getCapacityProviderStrategy() { return capacityProviderStrategy; }
public void setCapacityProviderStrategy(List<CapacityProviderStrategyItem> capacityProviderStrategy) {
this.capacityProviderStrategy = capacityProviderStrategy;
}
public String getGroup() { return group; }
public void setGroup(String group) { this.group = group; }
public String getStartedBy() { return startedBy; }
public void setStartedBy(String startedBy) { this.startedBy = startedBy; }
public List<ContainerOverride> getContainerOverrides() { return containerOverrides; }
public void setContainerOverrides(List<ContainerOverride> containerOverrides) {
this.containerOverrides = containerOverrides;
public TaskOverride getOverrides() { return overrides; }
public void setOverrides(TaskOverride overrides) { this.overrides = overrides; }
public List<ContainerOverride> getContainerOverrides() {
return overrides == null ? null : overrides.getContainerOverrides();
}
public NetworkConfiguration getNetworkConfiguration() { return networkConfiguration; }
@@ -53,6 +68,28 @@ public class RunTaskRequest {
this.networkConfiguration = networkConfiguration;
}
public String getPlatformVersion() { return platformVersion; }
public void setPlatformVersion(String platformVersion) { this.platformVersion = platformVersion; }
public boolean isEnableExecuteCommand() { return enableExecuteCommand; }
public void setEnableExecuteCommand(boolean enableExecuteCommand) {
this.enableExecuteCommand = enableExecuteCommand;
}
public boolean isEnableECSManagedTags() { return enableECSManagedTags; }
public void setEnableECSManagedTags(boolean enableECSManagedTags) {
this.enableECSManagedTags = enableECSManagedTags;
}
public String getPropagateTags() { return propagateTags; }
public void setPropagateTags(String propagateTags) { this.propagateTags = propagateTags; }
public String getReferenceId() { return referenceId; }
public void setReferenceId(String referenceId) { this.referenceId = referenceId; }
public Map<String, String> getTags() { return tags; }
public void setTags(Map<String, String> tags) { this.tags = tags; }
public List<String> getContainerInstances() { return containerInstances; }
public void setContainerInstances(List<String> containerInstances) {
this.containerInstances = containerInstances;
@@ -1,7 +1,9 @@
package io.github.hectorvent.floci.services.ecs.model;
import com.fasterxml.jackson.annotation.JsonIgnore;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.time.Instant;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@@ -23,7 +25,18 @@ public class TaskDefinition {
private RuntimePlatform runtimePlatform;
private List<String> requiresCompatibilities;
private List<String> compatibilities;
/** The container instance capabilities the definition needs, derived at registration. */
private List<Attribute> requiresAttributes;
private EphemeralStorage ephemeralStorage;
private String pidMode;
private String ipcMode;
private Instant registeredAt;
private String registeredBy;
private Instant deregisteredAt;
private Instant deleteRequestedAt;
private Map<String, String> tags = new HashMap<>();
/** Members Floci does not act on, kept verbatim so DescribeTaskDefinition round-trips. */
private Map<String, Object> unparsed;
public String getTaskDefinitionArn() { return taskDefinitionArn; }
public void setTaskDefinitionArn(String taskDefinitionArn) { this.taskDefinitionArn = taskDefinitionArn; }
@@ -66,9 +79,43 @@ public class TaskDefinition {
public List<String> getRequiresCompatibilities() { return requiresCompatibilities; }
public void setRequiresCompatibilities(List<String> requiresCompatibilities) { this.requiresCompatibilities = requiresCompatibilities; }
public List<Attribute> getRequiresAttributes() { return requiresAttributes; }
public void setRequiresAttributes(List<Attribute> requiresAttributes) { this.requiresAttributes = requiresAttributes; }
public List<String> getCompatibilities() { return compatibilities; }
public void setCompatibilities(List<String> compatibilities) { this.compatibilities = compatibilities; }
public EphemeralStorage getEphemeralStorage() { return ephemeralStorage; }
public void setEphemeralStorage(EphemeralStorage ephemeralStorage) { this.ephemeralStorage = ephemeralStorage; }
public String getPidMode() { return pidMode; }
public void setPidMode(String pidMode) { this.pidMode = pidMode; }
public String getIpcMode() { return ipcMode; }
public void setIpcMode(String ipcMode) { this.ipcMode = ipcMode; }
public Instant getRegisteredAt() { return registeredAt; }
public void setRegisteredAt(Instant registeredAt) { this.registeredAt = registeredAt; }
public String getRegisteredBy() { return registeredBy; }
public void setRegisteredBy(String registeredBy) { this.registeredBy = registeredBy; }
public Instant getDeregisteredAt() { return deregisteredAt; }
public void setDeregisteredAt(Instant deregisteredAt) { this.deregisteredAt = deregisteredAt; }
/** When deletion was asked for, which is when the revision entered DELETE_IN_PROGRESS. */
public Instant getDeleteRequestedAt() { return deleteRequestedAt; }
public void setDeleteRequestedAt(Instant deleteRequestedAt) { this.deleteRequestedAt = deleteRequestedAt; }
public Map<String, String> getTags() { return tags; }
public void setTags(Map<String, String> tags) { this.tags = tags; }
public Map<String, Object> getUnparsed() { return unparsed; }
public void setUnparsed(Map<String, Object> unparsed) { this.unparsed = unparsed; }
/** Whether the definition declares Fargate compatibility, which gates the Fargate-only rules. */
@JsonIgnore
public boolean isFargateCompatible() {
return requiresCompatibilities != null && requiresCompatibilities.contains("FARGATE");
}
}
@@ -0,0 +1,14 @@
package io.github.hectorvent.floci.services.ecs.model;
import io.quarkus.runtime.annotations.RegisterForReflection;
/**
* A {@code networkInterfaces} entry of a described container:
* {@code {"attachmentId": ..., "privateIpv4Address": ...}}.
*
* <p>An {@code awsvpc} task reports the same interface on each of its containers, since they
* share the task ENI.
*/
@RegisterForReflection
public record TaskNetworkInterface(String attachmentId, String privateIpv4Address, String ipv6Address) {
}
@@ -0,0 +1,53 @@
package io.github.hectorvent.floci.services.ecs.model;
import com.fasterxml.jackson.annotation.JsonIgnore;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.util.List;
/**
* The {@code overrides} of a RunTask or StartTask request, echoed back on the task.
*
* <p>The task-level members replace the task definition's own {@code cpu}, {@code memory},
* roles and {@code ephemeralStorage} for this task only; {@code containerOverrides} carries the
* per-container half.
*/
@RegisterForReflection
public class TaskOverride {
private List<ContainerOverride> containerOverrides;
private String cpu;
private String memory;
private String taskRoleArn;
private String executionRoleArn;
private EphemeralStorage ephemeralStorage;
public List<ContainerOverride> getContainerOverrides() { return containerOverrides; }
public void setContainerOverrides(List<ContainerOverride> containerOverrides) {
this.containerOverrides = containerOverrides;
}
public String getCpu() { return cpu; }
public void setCpu(String cpu) { this.cpu = cpu; }
public String getMemory() { return memory; }
public void setMemory(String memory) { this.memory = memory; }
public String getTaskRoleArn() { return taskRoleArn; }
public void setTaskRoleArn(String taskRoleArn) { this.taskRoleArn = taskRoleArn; }
public String getExecutionRoleArn() { return executionRoleArn; }
public void setExecutionRoleArn(String executionRoleArn) { this.executionRoleArn = executionRoleArn; }
public EphemeralStorage getEphemeralStorage() { return ephemeralStorage; }
public void setEphemeralStorage(EphemeralStorage ephemeralStorage) {
this.ephemeralStorage = ephemeralStorage;
}
@JsonIgnore
public boolean isEmpty() {
return (containerOverrides == null || containerOverrides.isEmpty())
&& cpu == null && memory == null && taskRoleArn == null
&& executionRoleArn == null && ephemeralStorage == null;
}
}
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.ecs.model;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.util.List;
import java.util.Map;
/**
@@ -21,6 +22,7 @@ public class UpdateServiceRequest {
private String availabilityZoneRebalancing;
private boolean forceNewDeployment;
private Map<String, Object> serviceConnectConfiguration;
private List<CapacityProviderStrategyItem> capacityProviderStrategy;
public String getCluster() { return cluster; }
public void setCluster(String cluster) { this.cluster = cluster; }
@@ -51,4 +53,10 @@ public class UpdateServiceRequest {
public void setServiceConnectConfiguration(Map<String, Object> serviceConnectConfiguration) {
this.serviceConnectConfiguration = serviceConnectConfiguration;
}
public List<CapacityProviderStrategyItem> getCapacityProviderStrategy() { return capacityProviderStrategy; }
public void setCapacityProviderStrategy(List<CapacityProviderStrategyItem> capacityProviderStrategy) {
this.capacityProviderStrategy = capacityProviderStrategy;
}
}
@@ -2,22 +2,35 @@ package io.github.hectorvent.floci.services.ecs.model;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.util.Map;
/**
* A task-level volume in an ECS task definition. Two shapes are modelled:
* <ul>
* <li>EC2-launch-type {@code host} volume — {@code {"name": ..., "host": {"sourcePath": ...}}};
* <li>EC2-launch-type {@code host} volume: {@code {"name": ..., "host": {"sourcePath": ...}}};
* {@code hostSourcePath} is the absolute path on the Docker host that the volume binds to.</li>
* <li>{@code efsVolumeConfiguration} volume — {@code {"name": ..., "efsVolumeConfiguration": {...}}};
* <li>{@code efsVolumeConfiguration} volume: {@code {"name": ..., "efsVolumeConfiguration": {...}}};
* see {@link EfsVolumeConfiguration}.</li>
* </ul>
* The two are mutually exclusive. A container references the volume by {@code name} via a
* {@link MountPoint}.
*
* <p>{@code unparsed} keeps the volume members Floci backs with nothing, which is the rest of
* AWS's {@code Volume} shape: {@code dockerVolumeConfiguration},
* {@code fsxWindowsFileServerVolumeConfiguration}, {@code s3filesVolumeConfiguration} and
* {@code configuredAtLaunch}. They have to survive the round trip or a client that registered one
* reads the definition back without it and proposes the same change forever.
*/
@RegisterForReflection
public record Volume(String name, String hostSourcePath, EfsVolumeConfiguration efs) {
public record Volume(String name, String hostSourcePath, EfsVolumeConfiguration efs,
Map<String, Object> unparsed) {
/** Convenience constructor for a {@code host} volume (no EFS configuration). */
public Volume(String name, String hostSourcePath) {
this(name, hostSourcePath, null);
this(name, hostSourcePath, null, null);
}
public Volume(String name, String hostSourcePath, EfsVolumeConfiguration efs) {
this(name, hostSourcePath, efs, null);
}
}