Commit Graph
38 Commits
Author SHA1 Message Date
Vũ Thế Huy b4c012fba4 fix(ecs): apply EFS access point PosixUser and CreationInfo to task volumes (#5606)
* fix(ecs): apply EFS access point PosixUser and CreationInfo to task volumes

An ECS task mounting EFS through an access point ignored the access
point's own settings, so the volume stayed root:root 0755 and a non-root
task could not write to it. Resolve the access point from EfsService and
initialise the volume root from RootDirectory.CreationInfo, and run the
container as PosixUser (uid:gid plus secondary gids). Each part falls
back independently to floci.storage.efs.*. An access point on another
file system, or with incomplete CreationInfo/PosixUser, rejects the launch.

Owner ids use long so unsigned 32-bit POSIX ids are not narrowed.

Closes #5480

* fix(ecs): attach PosixUser groups as supplementary groups instead of replacing container user

Preserve the container definition or image user when mounting an EFS access point, and attach the PosixUser gid and secondary gids as supplementary groups instead of overriding the container user.

Also stabilize ElbV2PreserveHostHeaderIntegrationTest socket connection to avoid public DNS resolution timeouts in CI.

* fix(ecs): validate CreationInfo permissions and filter null secondary GIDs

* revert(elbv2): revert listener test wait and loopback address change

* fix(ecs): share octal permissions check with ContainerLifecycleManager
2026-10-15 12:01:04 -04:00
Aniket Shukla 6e8a083d2b fix(ecs): use caller endpoint for exec stream URLs (#5666) 2026-10-14 15:04:18 -04:00
Aniket Shukla 9f224e5760 fix(ecs): preserve binary output in exec sessions (#5621) 2026-10-14 13:21:02 -04:00
Mohith 760c38ef99 fix(ecs): mount and clean up ephemeral task volumes (#5511)
* fix(ecs): mount and clean up ephemeral task volumes

* fix(ecs): retry orphan volume cleanup independently

* fix(ecs): quiet repeated orphan volume cleanup failures
2026-10-13 16:34:26 -04:00
Mohith 431748f740 fix(ecs): launch service tasks through capacity provider strategies (#5500) 2026-10-12 16:46:32 -04:00
Matheus Oliveira 30be71c56e fix(ecs): run ECS Exec sessions as root like the real agent (#5074)
The exec ignored the container's user; it now always runs as uid 0.

* Fix #4850

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>
2026-10-04 13:29:09 -04:00
Vũ Thế Huy 1d85e6bf6e fix(ecs): complete failed service deployment handling (#4874)
* fix(ecs): complete failed service deployment handling

* fix(ecs): address failed deployment review feedback

* fix(ecs): preserve rollback revisions across restarts

* fix(ecs): emit completion after service convergence

* fix(ecs): avoid duplicate completion events after upgrade

* fix(ecs): preserve completion event compatibility

* fix(ecs): read legacy deployment event state

* fix: report ECS rollback lifecycle and metadata

* fix: keep ECS deployment alarm metadata current
2026-10-02 14:09:33 -04:00
Hector Ventura 24c655050f feat(docker): give internal Docker labels io.floci.* names and keep the old keys as aliases (#4871)
* feat(docker): give internal Docker labels io.floci.* names and keep the old keys as aliases

Owner, ECS run, credentials-proxy, security-group and VPC network labels move to
io.floci.owner, io.floci.ecs.run, io.floci.ecs.credentials-proxy,
io.floci.security-group.helper/workload, io.floci.component and the standard
resource-identity keys. The previous keys (floci_owner_port, floci.ecs-run,
floci.ecs-task-role-credentials-proxy, floci.security-group-*, floci.component,
floci_component, floci_vpc_id, floci_vpc_region, floci_vpc_owner_port) are still
written as legacy aliases with the same value.

Readers take the new key first and fall back to the legacy one, label filters
query both key sets, and owner-scoped cleanup leaves an object alone when the two
disagree. All alias keys are reserved from extra-labels.

VPC networks are now owned by ownerIdentity (namespace and port) instead of the
bare API port, so two namespaced instances on the same port no longer reconcile
each other's networks.

* fix(ec2): keep pre-upgrade VPC networks of a namespaced deployment its own

Greptile and pgermosen on #4871: a VPC network created before the owner label
took the resource namespace carries only floci_vpc_owner_port with the bare API
port, so with a namespace set the deployment read its own surviving network as
a CIDR collision and the startup sweep left it behind. Such a legacy-only
network is now this deployment's when it holds this port and its
floci_namespace label names this deployment's namespace, the identity the new
io.floci.owner key encodes. Matching the bare port alone would also claim, and
let the sweep delete, the pre-upgrade networks of another namespace on the same
port.

Also imports List in ContainerStorageHelperTest instead of qualifying it inline.
2026-10-01 22:59:57 -04:00
Aymen JAMAAOUI bc2592e300 fix(ecs): send container logs to the awslogs group and stream from the task definition (#4808)
* fix(ecs): send container logs to the awslogs group and stream from the task definition

* fix(ecs): keep console output for containers without awslogs
2026-10-01 10:39:44 -04:00
Abhigya d73e33fe4b fix(ecs): pull task images at launch so a moved tag reaches the next task (#4583)
* fix(ecs): pull task images at launch so a moved tag reaches the next task

Floci resolved an image reference to an image id the first time it saw it and
reused that id for the life of the process, so a rebuilt :latest pushed to the
registry never reached a new task, even through a new task definition revision
and a forced deployment, and nothing reported the mismatch.

ECS now pulls every container image when a task starts, before creating any of
its containers, following the agent's ECS_IMAGE_PULL_BEHAVIOR (configurable as
floci.services.ecs.image-pull-behavior, default "default": pull, and fall back
to the cached image when the pull fails). The cached image is whatever the
local tag names at launch rather than a remembered id. Each container reports
the manifest digest it runs as containers[].imageDigest.

* fix(ecs): create task containers from the image id their pull resolved to

An overlapping RunTask could pull the same moved tag between this task's pull
and its container creation, so the container was created from whatever the
shared tag cache named by then while reporting the digest this task pulled.
resolveForLaunch now returns the resolved image id with its digest, and ECS
builds each container from that id, so the image a task runs and the digest it
reports always come from the same pull.

The pull also now uses the reference the container is created from, including
floci.docker.image-registry-base, instead of the unprefixed name.

* fix(ecs): launch image ids without a pull and report the digest the pull resolved

A bare sha256 image id under always, or on the first once launch, went to the
registry as if it were a repository reference and failed the task although the
image was local. resolveForLaunch now runs an image id as it is, like
ensureImageExists.

The reported digest took the first RepoDigests entry for the repository, which
is not necessarily the manifest the tag resolved to when the image holds more
than one (an index and a platform manifest). It now comes from the Digest line
the daemon streams for the pull, kept while the tag still names that image; a
cached image falls back to its repo digest only when there is exactly one.

The shared test config uses prefer-cached so the other ECS Docker suites stop
adding a registry round trip per launch; the image pull integration test pins
default in its own profile. ContainerBuilder imports are back in order.

* fix(ecs): report a pull's digest only for the launch that pulled

The digest a pull reported was kept per reference and reused while the tag
still named the same image id, but on the classic image store an id is the
config digest and several manifests can share it, so an outside pull could move
the tag to another manifest and leave the reused digest stale. Only the launch
that pulled now uses the streamed digest. A cached launch uses the image's
repo digest for the repository when there is one, or the one equal to the id
(the containerd store names an image by its manifest), and otherwise none.

Also sorts the ContainerLifecycleManager imports.

* fix(ecs): pull the image-pull test's busybox and registry from Docker Hub

EcsImagePullDockerIntegrationTest pulled both images through the
public.ecr.aws/docker/library mirror, whose anonymous quota is shared per
runner IP; shard 3 failed on toomanyrequests: Data limit exceeded. Take
them from TestImages like the other Docker-backed tests, pinning the
registry image there, and prefetch both for the shard that runs the class.

* test(ecs): name the registry readiness probe's tolerated exception expected
2026-09-30 22:14:50 -04:00
Abhigya 55d37cfc41 feat(ecs): let the startup container sweep be turned off, and derive the credentials proxy owner from the shared helper (#4696)
* feat(ecs): let the startup container sweep be turned off, and derive the credentials proxy owner from the shared helper

The ECS startup sweep removes every task container carrying this deployment's
floci_owner_port label, so two Flocis sharing a Docker daemon with the same API
port and no resource namespace remove each other's task containers. EC2's sweep
already has an opt-out; ECS now has the same one,
FLOCI_SERVICES_ECS_RECONCILE_CONTAINERS_ON_STARTUP (default true). With it off,
containers are left alone and tasks start at once. The recorded load balancer
targets and Cloud Map instances are still released, since each Floci releases
only what its own persisted state recorded.

EcsCredentialsProxy.owner() now uses ContainerStorageHelper.ownerIdentity and
OWNER_LABEL instead of its own copy of the rule.

* fix(ecs): leave task-role credentials proxies alone when the startup sweep is off

The credentials proxy removed every proxy carrying this deployment's owner label
at startup regardless of reconcile-containers-on-startup. With the sweep off for
two instances sharing an owner identity, the second instance's startup still
tore down the first's proxy, and its running tasks lost their credentials
endpoint. The proxy's startup reap now follows the same setting.
2026-09-30 17:22:46 -05:00
Abhigya 014156a546 fix(ecs): register reachable task addresses in Cloud Map and bound synthesised ENI addresses (#4509)
* fix(ecs): register reachable task addresses in Cloud Map and bound synthesised ENI addresses

ECS service discovery registered an awsvpc task's ENI address, but task
containers never join the subnet's network, so peers resolved a name and
then timed out. Register the address the task container holds on its
Docker network instead, falling back to the ENI address only when there
is no running container.

The synthesised private-address fallback in EC2 counted past the subnet
CIDR (10.70.1.549) and restarted at .10 on every boot. It now allocates
inside the subnet CIDR, skips the AWS-reserved addresses and every address
a persisted ENI, instance or NAT gateway still holds, and reports
InsufficientFreeAddressesInSubnet when the subnet is full.

* fix(ec2): hold the synthesised-address lock until the resource is persisted

The allocator chose a free address under its lock but released it before the
network interface, instance or NAT gateway holding the address was stored, and
it decides what is free from stored resources. Two concurrent creates could
both take the same address, most visibly at the end of a /28 where the cursor
clamps back onto the last one handed out.

A dedicated lock now covers allocation through persistence at each caller:
CreateNetworkInterface, CreateNatGateway and the RunInstances loop, where it
is taken inside imageRegistryLock.

* fix(ecs): advertise the container port for an awsvpc task registered at its container address

* docs(ecs): state which Cloud Map address and port each network mode registers

* fix(ecs): look for stale Cloud Map instances at an awsvpc task's container address

The registrar registers an awsvpc task at the address its container holds on
its Docker network, but the eviction from #4513 resolved the task's addresses
through resolveContainerHost, which is 127.0.0.1 when Floci runs natively, so a
stale instance at the container address was never found. Load balancer target
eviction is unchanged, since targets are still registered through
resolveContainerHost.

* refactor(ec2): nest the address allocation lock visibly inside runInstances

Scope privateIpAllocationLock to the instance-building loop, the only part that
allocates and persists addresses, and indent it under imageRegistryLock.

* fix(ec2): allocate a launch's addresses before storing any of its instances

A RunInstances larger than the subnet's free addresses failed with
InsufficientFreeAddressesInSubnet only after the instances that fit had been
stored with their root volumes. The launch now allocates every address first,
counting the ones it has already picked as taken, and releases any Docker
leases it took when the subnet runs out.
2026-09-29 14:36:28 -04:00
Abhigya 451a30f98e fix(ecs): release stale task containers and registrations, and evict ones that would misroute a reused address (#4513)
* fix(ecs): release a previous run's task containers and registrations at startup

Task state is memory-only, so a restarted Floci knows no task and the
service scheduler starts a replacement for each service. A run that ended
without a graceful shutdown left its task containers serving beside those
replacements, and even a graceful one left their load balancer targets and
Cloud Map instances registered, so a dead task's target followed its
address to whichever container Docker handed it to next.

At startup, before the scheduler runs, ECS now removes the containers this
Floci owns (task containers now carry the floci_owner_port label EC2 and
the security-group helpers already use), deregisters the IP targets in each
service's target groups, and deregisters the Cloud Map instances its tasks
registered. The owner identity is computed by one shared helper.

* fix(ecs): release only the registrations ECS recorded, and retry failed container removal

The startup sweep recognised a previous run's load balancer targets by
their address shape and its Cloud Map instances by their ECS attributes,
so it also removed a target or instance registered by hand into the same
target group or Cloud Map service. Both registrars now persist each
registration they make, keyed by task ARN, drop the record on
deregistration, and at startup release exactly what was recorded.

Removing a leftover container now uses strict removal, and the result
says whether every leftover is gone. Until it is, each reconciliation
tick retries the sweep and starts no service task. The sweep only
considers containers created before this process started, so a retry
never touches a task this run launched.

* fix(ecs): tell a previous run's containers apart by run label, and record registrations before making them

The startup sweep kept every container created in the same second this process started, so a run killed within that second left an orphan the sweep reported as gone. Containers now carry a per-process floci.ecs-run label, also stamped on security-group helpers, and the sweep keeps only the current run's.

Target and Cloud Map registrations are now written to the ledger before they are made, so a process killed in between still leaves a record for the next run to release.

* fix(ecs): leave a target already in its group to whoever registered it

ELBv2 registration is idempotent, so a task whose address and port matched a target registered by hand adopted it: the ledger recorded it, and a task stop or the startup release then removed it. The registrar now skips and never records a target that is already registered.

* fix(ecs): deregister only the targets a task recorded when it stops

A task whose targets were all already in their groups records nothing, and its stop fell back to deregistering the targets its containers resolve to, removing the ones registered by hand. Every task this process knows went through the recording registrar, so the fallback now serves only a task without an ARN, which cannot be recorded.

* fix(ecs): retry the leftover sweep only when a service needs a task, and warn once

With Docker unreachable, the boot sweep failed and every 5 second tick then
logged two WARNs forever, even with no service to run. The retry now runs only
where a service is about to start a task, and both the sweep failure and the
blocked-launch message are WARNs the first time and DEBUG after.

* fix(ecs): log a repeated blocked service launch at DEBUG

* fix(ecs): retry the leftover sweep before RunTask and StartTask launches too

A task started through RunTask or StartTask no longer bypasses a failed sweep:
the common launch path retries it and stops the task with TaskFailedToStart
while a previous run's containers remain. Sweep failures are tracked per kind,
a failed listing and each container that would not go, so a new failure is
still a WARN after an earlier one cleared.

* fix(ecs): evict unrecorded registrations at a starting task's address, and adopt its own target

A target already in its group when a task started was skipped and never recorded, so a registration no task recorded, as one a Floci version without the ledger made, survived every task stop and restart. When a task of the same service came up on its address it left it in place, and when another service's task took the address the target or Cloud Map instance routed the first service's traffic to it.

A target at the task's own address and port is now recorded as the task's, so its stop deregisters it, as ECS does on AWS. When a task starts, every target and Cloud Map instance at one of its addresses that no live task recorded is deregistered from the target groups and Cloud Map services the region's ECS services name, with a warning. A loopback address matches only on the task's host ports.

* fix(ecs): evict only registrations that actually point at a starting task

The eviction matched every unrecorded target at any of a task's addresses on any port, including its ENI address. ECS registers no target at the ENI address, and an ENI address is unique only within its VPC, so an IP target for something in another VPC could be removed; a target on a port the task does not publish sends it nothing either.

Targets are now matched only at a container's Docker address on the ports its bindings declare. Cloud Map instances still match a container address on any port, since a DNS answer carries none, and match the ENI address only in a namespace of the task's own VPC.
2026-09-28 23:25:48 -05:00
Abhigya 52225e2053 fix(ecs): reconcile persisted services at boot (#4501)
* fix(ecs): reconcile persisted services at boot

EcsService is ApplicationScoped, so Quarkus only creates it on the first
ECS request, and creating it is what loads the ECS stores and starts the
reconciler. After a restart every persisted service stayed without tasks,
load balancer targets or Cloud Map instances until something called the
ECS API.

EmulatorLifecycle now calls EcsService.restorePersistedRuntime() after
storage is loaded and the load balancers are restored, the way it already
restores RDS, ElastiCache and ELBv2.

* test(ecs): assert boot starts the ECS reconciler through CDI
2026-09-27 22:28:13 -05:00
Priamo Germosen 81e646b86d docs(ecs): document task-role credentials configuration (#4500)
The wiring landed in #4486 but none of the four
FLOCI_SERVICES_ECS_TASK_ROLE_CREDENTIALS_* settings were written down
anywhere, and nothing said the credentials proxy needs a user-defined
Docker network rather than the default bridge.

Adds them to the environment variable reference, the application.yml
example and the ECS service page, the last with a short section on how
the endpoint is reached and the two cases where a task does not get
credentials: one that sets its own, and one under security-group
enforcement.

Also fixes two things the same work left behind in the source. The
cleanupProtectedNetwork javadoc was orphaned when
prepareTaskRoleCredentials was inserted between it and its method, and
two config javadocs still described the wiring and the proxy as
follow-up work.
2026-09-27 22:14:50 -05:00
Abhigya 04878b8c57 feat(cloudmap): resolve DNS namespaces and register ECS tasks in them (#4122)
* feat(cloudmap): resolve DNS namespaces and register ECS tasks in them

Cloud Map's control plane already accepted namespaces, services and
instances and read them back correctly, but nothing answered DNS for
<service>.<namespace>. A container that registered successfully still
failed to resolve its peers, and the gap only surfaced at application
runtime because every API call looked right.

The embedded DNS server now consults DnsRecordSource implementations
before forwarding a query upstream, and Cloud Map provides one: a DNS
namespace resolves to the AWS_INSTANCE_IPV4 of the instances registered
under it, one A record each. The SPI keeps the direction right, since
core must not import a service. Which instances answer follows Route 53:
the healthy ones while any instance is healthy, all of them when none
is, and at most eight records either way. HTTP namespaces do not
resolve, matching AWS, where they are reachable only through
DiscoverInstances.

An ECS service that declares serviceRegistries now registers each running
task as an instance of the named Cloud Map service, and deregisters it
when the task stops, mirroring EcsLoadBalancerRegistrar. The address is
the task's ENI address on an awsvpc task and the container's Docker
network address otherwise, which is the one a peer container can reach.
Alongside it the instance carries the metadata attributes the ECS
service discovery documentation lists: AVAILABILITY_ZONE, REGION,
ECS_SERVICE_NAME, ECS_CLUSTER_NAME and ECS_TASK_DEFINITION_FAMILY.
serviceRegistries stays raw: registryArn, containerName and
containerPort are the only members anything acts on.

* test(ecs): pin the Cloud Map registration hooks with a docker mode test

EcsServiceDiscoveryRegistrarTest drives the registrar directly, so removing
EcsService's calls to it left every ECS test green. The registration only runs
in docker mode, which the suite mocks out, so nothing covered the wiring.

The new test runs ECS unmocked under a profile, creates a service that declares
serviceRegistries, and drives one reconciler tick to launch a real container. It
asserts the Cloud Map name resolves to the task's ENI address while it runs, and
that stopping the task removes the instance and the answer. Commenting out
either hook fails it: the register hook on the resolve assertion, the deregister
hook on the instance one.

Security-group enforcement goes back to its shipped default of off for the
profile. The suite turns it on and its helper needs rootful Docker, which is a
requirement of security groups rather than of service discovery.

Also corrects the health status deviation note. An instance registered without
AWS_INIT_HEALTH_STATUS starts HEALTHY on AWS too, so the deviation is not the
initial status but that Floci never moves it: AWS registers an ECS task
UNHEALTHY and promotes it once the container health check passes, for a service
that declares HealthCheckCustomConfig.

* fix(cloudmap): retain DNS ownership and ECS registry targets

* fix(cloudmap): keep namespace apex queries authoritative

* style(dns): remove em dash from test heading
2026-09-25 11:11:28 -04:00
Abhigya 76cc27f2f1 fix(ecs): retry teardown of redeployed task containers (#4280)
* fix(ecs): retry teardown of redeployed task containers

* test(ecs): wait for explicit task stop in SDK compatibility test

* fix(ecs): serialize teardown and align stop compatibility test

* test(ecs): observe blocked concurrent stop without delay

* fix(ecs): preserve unknown exits and serialize startup transition
2026-09-24 15:51:05 -04:00
Abhigya fcc89c0e8d feat(ecs): implement ExecuteCommand (#4121)
* feat(ecs): implement ExecuteCommand

ECS Exec was accepted at the API but opened nothing: a client got a
response it could not connect to. This implements the whole path, so
`aws ecs execute-command` gives a real shell in a task's container.

The gate matches AWS. The session must be interactive, which is the only
mode ECS supports; the task must belong to the cluster the request
names, must be RUNNING and must have been run with enableExecuteCommand;
and the container must have a runtime behind it, so a mock-mode task
answers TargetNotConnectedException.

The response carries a session with a single-use tokenValue and a
streamUrl pointing at Floci's own data channel, which is where
session-manager-plugin then connects. Floci plays the SSM agent's half
of the Session Manager protocol on that channel, the binary AgentMessage
framing, the handshake, sequenced acknowledgements and terminal resizes,
and bridges it to a docker exec with a TTY.

Two threads meet on that channel. Every call into the Docker daemon
blocks, so it runs on a worker rather than on the event loop, and the
daemon streams the container's output back on its own thread; frames are
written from the channel's Vert.x context only, which also keeps the
outbound sequence numbers in the order they reach the wire. The command
is attached to only once the client has accepted the handshake, so no
output can be written to a channel that is still being opened.

Deliberate limits, documented in docs/services/ecs.md:

- The command runs through /bin/sh -c, so an image without a shell
  cannot be exec'd into.
- Sessions are in memory, single use, and expire after five minutes if
  nobody connects.
- ExecuteCommand logging, the executeCommandConfiguration that sends
  session transcripts to S3 or CloudWatch, is not implemented. The
  cluster field still round-trips.

EcsExecSessionRegistry holds a SecureRandom, so it is registered under
--initialize-at-run-time for the native image.

AgentMessageTest covers the wire framing against a JDK-side encode and
decode, EcsExecuteCommandIntegrationTest covers the API gate, and
EcsExecChannelDockerIntegrationTest runs a real session end to end under
Docker.

* fix(ecs): compare the ECS Exec session token in constant time

The token is the single gate in front of an interactive shell in a
container, so compare it with MessageDigest.isEqual on the UTF-8 bytes
rather than String.equals, which returns on the first differing
character. Matches the constant-time comparison the repo already does in
ScimController, IamAuthValidator and LambdaLayerService.

A failed claim still leaves the session in place: dropping it would let
anyone holding a session id cancel somebody else's session.

* fix(ecs): expire an unclaimed ECS Exec session on read

Only create() swept the session map, and neither claim() nor find()
looked at createdAt, so a session nobody connected to stayed claimable,
token included, until the next ExecuteCommand call happened to come in.
On an idle emulator that is forever, which also made the five minute
expiry documented in docs/services/ecs.md untrue.

claim() and find() now go through liveSession(), which drops a session
past SESSION_TTL and reports it as gone: claim() rejects it before the
token comparison, and the WebSocket upgrade refuses to open a channel
for it. The registry takes the CDI Clock so the tests exercise expiry
without waiting out the TTL.
2026-09-22 23:47:40 -04:00
Abhigya 7cd441231f feat(ecs): serve the task metadata endpoint v4 (#4120)
An application in an ECS task, the AWS SDK integrations that read task
identity, and the aws-for-fluent-bit init process all expect
ECS_CONTAINER_METADATA_URI_V4 to resolve. Under Floci it was never set,
so any of them fell back or failed.

AWS serves the endpoint on the link-local address 169.254.170.2, which a
local container cannot be given. Floci serves the same paths on its own
port instead: clients read the environment variable rather than the
address, so nothing has to know the difference.

The id is minted per container before the container is created, the way
the ECS agent mints one, because the container's own environment has to
carry the URI and so it cannot be derived from the Docker id the daemon
returns afterwards. EcsService.findByMetadataId resolves an id back to
its container and task.

The task document carries Cluster, TaskARN, Family, Revision, the
statuses, Limits in vCPUs, the pull timestamps, AvailabilityZone,
LaunchType, ServiceName for a service's task, VPCID for an EC2 task,
and, on Fargate, ClockDrift and EphemeralStorageMetrics. Floci has no
clock drift and does not meter the disk, so those report a synchronized
clock and zero usage. An awsvpc container's Networks object describes
the task ENI and the subnet it sits in; a local ENI has no DHCP option
set behind it, so the gateway, the resolver and the search domain are
derived the way a real VPC assigns them.

The stats paths read the daemon when the request arrives and return
Docker's own ContainerStats document, plus the network_rate_stats the
agent adds. Docker reports cumulative counters only, so the rates are a
delta across two consecutive samples, which is also why AWS documents a
container as having to run for about a second before its stats appear. A
container with no running Docker container behind it reports an empty
document rather than an error.

Because that pair costs a collection tick, task/stats samples the task's
containers in one pass: every stream is opened before any of them is
waited on, and the waits share one deadline. A sidecar polls that path
for network metrics, so the response has to cost about one tick however
many containers the task has, not one tick per container.
2026-09-22 08:18:55 -04:00
Abhigya 7b29fdcf83 feat(ecs): complete the operations outside the launch path (#4019)
The operations that are not part of launching a task were the ones ECS
answered least like AWS: a listing returned everything at once, a
describe dropped what it could not resolve, and several stored less than
the request carried.

Clusters. CreateCluster and UpdateCluster carry configuration and
serviceConnectDefaults, UpdateCluster replaces only the members the
request named, and DescribeClusters gates settings, tags, statistics,
attachments and configuration on include, reporting the eight documented
statistics split by launch type. DeleteCluster refuses a cluster that
still has services, container instances or running tasks, with the
exception AWS reports for each.

Pagination. Every listing pages with maxResults and nextToken behind one
shared helper: a hundred per page, ten for ListServices, ten for
ListAccountSettings. ListTaskDefinitions lists only ACTIVE revisions by
default and orders by family then numeric revision; ListTasks defaults to
the running tasks and filters by launch type, container instance and
startedBy, which has to be the only filter alongside the cluster scope.

Container instances. RegisterContainerInstance keeps what the agent sent,
deregistration leaves the instance describable as INACTIVE,
UpdateContainerInstancesState moves only between ACTIVE and DRAINING,
and DescribeContainerInstances gates tags and health on include.

Account settings and attributes. A setting is validated per name, carries
its principal and type, and falls back from the principal's own value to
the account default to the built-in default under effectiveSettings. An
attribute belongs to a cluster and must name a container instance it has.

Task sets. A task set needs an EXTERNAL or CODE_DEPLOY service, computes
its desired count from the service's, round-trips its networking and load
balancers, and needs force to delete before it is scaled to zero.
CodeDeploy's call site reports the CODE_DEPLOY startedBy ECS reports.

Service deployments and revisions. A deployment is recorded with the
revision it targets, the two point at each other, and the service reports
the deployment and revision it is currently on.

Verified against the AWS SDK for Java v2 and the AWS ECS API reference.
2026-09-21 16:09:00 -04:00
Abhigya ace99b34b0 feat(ecs): service members, service role and capacity provider management (#4037)
CreateService and UpdateService carry the members AWS documents on the Service
shape, rather than dropping them: deploymentConfiguration, serviceRegistries,
platformVersion and platformFamily, enableExecuteCommand, enableECSManagedTags,
propagateTags, healthCheckGracePeriodSeconds, the role, and anything else the
request sent, which round-trips verbatim. A client that reads back what it wrote
sees no drift.

UpdateService rolls a new deployment only for the members UpdateService
documents as starting new tasks, a changed network configuration, load balancers,
service registries or platformVersion, and applies the rest in place. An update
replaces only the members it names, so a service created with
placementConstraints and updated with placementStrategy alone keeps its
constraints; a member the update does name is replaced outright, which is how an
empty array clears one.

A service role is accepted only where AWS accepts one: with a load balancer, and
not with awsvpc networking.

Capacity provider management follows the documented rules. A name is at most 255
letters, numbers, underscores and hyphens and is never prefixed with aws, ecs or
fargate. A provider reports its ARN, its type and the autoScalingGroupProvider it
was created with. DescribeCapacityProviders gates tags behind include: ["TAGS"]
and reports an unresolvable name as a MISSING failure. DeleteCapacityProvider
refuses the reserved FARGATE and FARGATE_SPOT providers, one still attached to a
cluster and one still named in an active service's capacity provider strategy,
and reports the deleted one through updateStatus so the SDK is never handed an
unmappable CapacityProviderStatus.

Split out of the Fargate launch surface PR, which keeps the capacity provider
strategy distribution and the service task launch.
2026-09-21 11:58:55 -04:00
Abhigya bf1152e144 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.
2026-09-20 22:38:32 -04:00
Aniket Shukla 869589e932 feat(ecs): publish awsvpc ports on demand (#3766) 2026-09-19 16:27:29 -04:00
XuJianandxujiantop-crypto de54409fc6 fix(ecs): apply volumesFrom to task containers (#3811)
Co-authored-by: xujiantop-crypto <265865031+xujiantop-crypto@users.noreply.github.com>
2026-09-18 14:38:13 -04:00
z9rtm e32266537e feat(ecs): support fluentd FireLens routers and s3-hosted FireLens config (#3790)
* feat(ecs): route awsfirelens logs through a generated Fluent Bit router

Start the router first, point awsfirelens containers at the generated unix socket, and store firelensConfiguration as registered.

* feat(ecs): carry FireLens config through CloudFormation and aim outputs at Floci

AWS::ECS::TaskDefinition provisioning now keeps each container LogConfiguration and FirelensConfiguration, so a stack that registers a FireLens router reaches the same launch path as RegisterTaskDefinition.

The generated router points each awsfirelens output at Floci container-reachable base URL through Endpoint, and the app container awsfirelens log config uses fluentd-async, which Docker 28 accepts, instead of the removed fluentd-async-connect.

Only s3, cloudwatch and firehose receive that endpoint: they are the AWS-written Go plugins and parse the value as a URL. The upstream C plugins (cloudwatch_logs, kinesis_firehose, kinesis_streams) hand it to getaddrinfo as a bare host name and always dial TLS, with no output-level switch for either, so a URL is a guaranteed DNS failure on Fluent Bit 1.9 and 5.0.9 alike, and a bare host plus port only reaches Floci plain HTTP port before certificate verification fails. Those outputs keep whatever the task definition gave them.

* feat(ecs): support fluentd FireLens routers and s3-hosted FireLens config

A fluentd FireLens router is now acted on at launch instead of being stored and ignored. Floci generates the config the ECS agent generates for that type: unix and forward sources, a grep filter per include-pattern and exclude-pattern, a record_transformer filter for the ECS metadata, the include of an external config, and one match block per awsfirelens container keyed on its @type. Fluentd takes its output plugin name from the log option @type rather than Name, its tags end in ** rather than *, and it gets neither the healthcheck sections nor Mem_Buf_Limit, both of which the agent emits for Fluent Bit only. The router image is handed /fluentd/etc/fluent.conf, so the config archive contents and its destination directory are now chosen per router type.

config-file-type=s3 now reads the object from Floci's own S3 instead of ignoring the option, and writes it to the fixed external.conf path next to the generated config, /fluent-bit/etc/external.conf or /fluentd/etc/external.conf, which is where the agent mounts what it downloads. The object is read before any container is created, so a missing bucket or key stops the task with the agent's own wording as the stopped reason, Unable to download firelens s3 config file: unable to download s3 config <key> from bucket <bucket>: <detail>, rather than leaving a router running behind a task that already failed.

RegisterTaskDefinition enforces the same split ECS does. A Fargate-compatible task definition cannot take its config from S3, and is rejected with Fargate launch type does not support FirelensConfiguration config file from 's3'; a config-file-value that does not name an S3 object is rejected as Invalid arn syntax. An EC2-compatible task definition keeps s3, and a Fargate task can still source its config from S3 the way AWS documents, through the aws-for-fluent-bit init process and its aws_fluent_bit_init_s3_* environment variables, which ECS never inspects and Floci passes through. Floci serves no ECS task metadata endpoint, so that init path fetches nothing locally yet, which docs/services/ecs.md now states.

* fix(ecs): rejoin awsvpc tasks to the security-group namespace

The FireLens launch loop stopped calling withNetworkMode(container:<helper>)
and dropped the workload label, so prepareNetwork's ENI/nftables had nothing
to isolate. Cover the join with a firewallManager-wired unit test.

* test(ecs): assert FireLens router and app both join the SG namespace

* test(ecs): verify FireLens router and app lifecycle in SG namespace test

* refactor(ecs): reuse extractTaskId for FireLens cluster name

* docs(ecs): note the launchType/compatibilities gap next to FireLens S3

* docs(ecs): scope the FireLens TCP-listen rationale to non-shared namespaces

* fix(ecs): reject a FireLens type that is missing or not fluentd/fluentbit

AWS requires firelensConfiguration.type and accepts only fluentd or
fluentbit. parseFirelensConfiguration returned null for a missing type,
registering the container as if FireLens were absent, and persisted any
other string, so an unknown type only became ineffective later when
findFirelensRouter recognized neither value.

Both are now rejected at the RegisterTaskDefinition JSON boundary with
the smithy validation wording, and are covered in
EcsJsonHandlerRuntimePlatformLogConfigurationTest.
2026-09-18 11:54:32 -04:00
Vũ Thế Huy 6f87973649 feat(ecs): add FireLens task logging support (#3768)
* feat(ecs): add FireLens task logging support

* fix(docker): omit extra hosts for container network mode

* fix(ecs): bind FireLens router port to loopback
2026-09-18 08:57:02 -04:00
Alexy GrabovandAlexy Grabov 7813d14ee4 feat(network): add opt-in security group enforcement (#3681)
* feat(network): add opt-in security group enforcement

* fix(ec2): make security group tests order independent

* fix(network): emit valid ICMP nft rules and restart protected instances

Three review findings on the opt-in security-group enforcement foundation:

- SecurityGroupNftCompiler built "icmp type 8 code 0 accept" for an AWS
  ICMP rule carrying both FromPort (type) and ToPort (code). nftables
  header fields are separate expressions, so nft rejected the whole
  compiled policy and the manager then quarantined every endpoint. Each
  field now repeats the protocol keyword, and a protocol rule with no
  type or code becomes "meta l4proto icmp accept", which was equally
  invalid as a bare "icmp accept".
- StartInstances followed the legacy restart path for a protected
  workload and waited for a Docker bridge IP on a container that shares
  the helper's network namespace and so has no attachment of its own.
  The helper survives the workload's stop, so start now reuses its
  transport address exactly as launch does, and skips the reachable
  private address rewrite the same way.
- Replaced the newly introduced var declarations with explicit types and
  imported the inline java.util/model FQCNs, per AGENTS.md.

* fix(network): scope the firewall helper to CAP_NET_ADMIN

The helper only has to program nftables inside the namespace Docker already
gave it, so full --privileged granted far more than the feature needs.
ContainerLifecycleManager now adds CAP_NET_ADMIN for the container carrying
the floci.security-group-helper label, mirroring the capability drop already
applied to protected workloads at the same choke point, and the helper spec
no longer asks for privileged mode.

Also replaces the inline java.util FQCNs the previous commit missed in
Ec2Service with imports, per AGENTS.md.

---------

Co-authored-by: Alexy Grabov <Alexy.Grabov@cyberark.com>
2026-09-15 14:30:49 -04:00
Niels Kootstra 126af73141 fix(ecs): enforce host-volume bind-mount safety fail-closed at register and run time (#3543)
* fix: enforce host-volume bind-mount safety fail-closed at register and run time

Reject volumes[].host.sourcePath by default unless an operator opts in via
floci.services.ecs.host-volume-roots or allow-unsafe-host-volumes. Block the
Docker socket and any ancestor directory that contains it (/var/run, /run,
/var) unconditionally, even with the unsafe flag set. Extract the check into
HostVolumePolicy and enforce it again immediately before each bind mount in
EcsContainerManager.startTask, not only once at RegisterTaskDefinition, to
narrow the window for a swapped-in symlink and to cover task definitions
persisted before this policy existed.

* fix(ecs): protect the Docker socket Floci actually connects to

The host-volume policy only blocked the literal /var/run/docker.sock
and /run/docker.sock paths, so a task definition could bind-mount the
daemon socket when Floci reached it through DOCKER_HOST or an active
Docker context (Colima, OrbStack, Rancher Desktop, Podman).

Resolve the daemon endpoint through the same DockerClientProducer path
the Docker client uses and add its unix:// socket path to the protected
candidates. The literal paths stay protected as defence in depth.
2026-09-13 18:23:07 -04:00
Vũ Thế Huy 14ca62d9f7 feat(ecs): honor UpdateService forceNewDeployment and emit EventBridge lifecycle events (#2938)
* feat(ecs): honor UpdateService forceNewDeployment (#2557)

* feat(ecs): add EcsEventPublisher for aws.ecs lifecycle events (#2557)

* feat(ecs): emit ECS Task State Change events on task start/stop (#2557)

* feat(ecs): emit ECS Deployment State Change events (#2557)

* test(ecs): end-to-end ECS EventBridge lifecycle events + docs (#2557)

* fix(ecs): log diagnostic when task ARN region parse fails (#2557)

* fix(ecs): synthesize lifecycle events from a task snapshot, not the shared instance

emitTaskLadder toggled the live task's lastStatus in place to synthesize
each phase, so a concurrent DescribeTasks/ListTasks could observe a
status the task never actually occupied while the four-phase ladder
was in flight. Build the ladder from a shallow copy instead.

Also bump the ARN region-parse fallback log from debug to warn, since
debug is off by default and made the fallback effectively invisible.
2026-09-02 23:09:37 -04:00
13664e7693 fix(ecs): report schedulingStrategy, deploymentController and availabilityZoneRebalancing on services (#2482)
AWS echoes all three on CreateService/UpdateService/DescribeServices; Floci
dropped them, so clients that persist them saw drift. Terraform's
aws_ecs_service reads all three and schedulingStrategy is ForceNew, which
replaced the service on every apply.

- EcsServiceModel: schedulingStrategy and availabilityZoneRebalancing
  alongside the existing deploymentController
- CreateService parses schedulingStrategy, deploymentController.type and
  availabilityZoneRebalancing (400 InvalidParameterException on unknown
  values); UpdateService parses availabilityZoneRebalancing
- Defaults match AWS: REPLICA / ECS, and availabilityZoneRebalancing is
  ENABLED on create; a service that never had a value reads as DISABLED
- DAEMON is honoured, not just stored: rejected for the Fargate launch type
  and the CODE_DEPLOY/EXTERNAL controllers (AWS's rule), otherwise the
  reconciler keeps exactly one task per ACTIVE container instance and
  derives desiredCount from the instance count

Co-authored-by: Hisham Mohammed <hisham.ma.mohammed@gmail.com>
Co-authored-by: Priamo <pgermosen@gmail.com>
2026-08-29 11:51:52 -04:00
hisham-coderandHisham Mohammed f3b22e7964 fix(ecs): roll service tasks onto a changed task definition (#2483)
UpdateService with a new taskDefinition recorded a deployment but left the
running tasks on the old revision forever: a redeploy (new image tag, new
environment) never reached the containers, and the only way to apply it was
to StopTask by hand so the reconciler relaunched.

The reconciler now counts only tasks on the service's current task
definition towards desiredCount, so replacements start first, and when the
service is over desiredCount it drains the stale tasks before anything
else — the shape of AWS's rolling deployment with the ECS deployment
controller. Stopped reason names the replaced task definition.

The service pins the resolved task-definition ARN on CreateService and
UpdateService (AWS stores and reports the ARN), so a family or
family:revision reference compares exactly with each task's
taskDefinitionArn; a service persisted with a raw reference is pinned on
its first reconciler tick.

Co-authored-by: Hisham Mohammed <hisham.ma.mohammed@gmail.com>
2026-08-23 16:19:01 -04:00
Davor Santic a2389e7733 fix(ecs): round-trip runtimePlatform and logConfiguration on task definitions (#2443)
RegisterTaskDefinition parsed a fixed field list and dropped everything
else, so a task definition registered with a runtimePlatform or a
container logConfiguration came back from DescribeTaskDefinition without
them. A client that verifies its own write — Terraform, or a deploy tool
comparing the registered revision against desired state — saw drift that
was not there.

Both are now parsed, stored on the task definition, and serialized back
with the AWS wire shape. A request that omits them still produces a
response without the keys, so nothing changes for existing callers.

The two fields are set on the task definition returned by
EcsService.registerTaskDefinition, following the pattern already used for
task-level volumes. That mutation happens after the value was stored, so
a backend that serializes on put (persistent, hybrid, WAL) had captured
the pre-mutation value; the definition is now written back, which also
makes the existing volumes round-trip survive a restart.
2026-08-22 00:22:32 -04:00
Hector Ventura 8b8f837728 fix(ecs): report service deployments and MISSING failures on DescribeServices (#2176)
* fix(ecs): report service deployments and MISSING failures on DescribeServices

DescribeServices omitted services[].deployments entirely and always returned an
empty failures list. Both are read by AWS's own ServicesStable waiter, which
accepts on

  length(services[?!(length(deployments) == `1` && runningCount == desiredCount)]) == `0`

and fails fast on failures[].reason == "MISSING" (botocore
ecs/2014-11-13/waiters-2.json). Because that file is codegen'd into every SDK,
`aws ecs wait services-stable` and every SDK waiter polled for the full
40 x 15s before giving up, and Terraform's aws_ecs_service never converged
(terraform-provider-aws internal/service/ecs/service.go:2206 applies the same
len(Deployments) == 1 test). Evaluating the acceptor against the old payload
raises JMESPathTypeError, so it could not even be evaluated.

An ACTIVE service now reports exactly one PRIMARY deployment derived from its
current state, with rolloutState COMPLETED once runningCount reaches
desiredCount. The deployment id is derived from the service ARN and task
definition rather than generated per request, so it is stable across calls and
restarts and rolls over when the task definition changes. An unresolvable
service reference is returned as a MISSING failure carrying the ARN it would
have had, instead of being dropped.

Known deviations are documented in docs/services/ecs.md: a single deployment
with no draining ACTIVE alongside it, no deploymentController gating, and
pendingCount always 0.

Closes #2174

* fix(ecs): stamp a deployment with its own start time, not the service's

A task-definition change mints a new deployment id, but both deployment
timestamps were still taken from the service's creation time, so the payload
contradicted itself: a new deployment claiming to have been created when the
service was. botocore documents Deployment.createdAt as "the time when the
service deployment was created", and moto stamps it at deployment construction
(moto/ecs/models.py:540) rather than reusing the service's.

Track when the current deployment began on the service model, set at creation
and on every task-definition change, and report that. Services persisted before
this field existed fall back to the service creation time.

Raised in review on #2176.
2026-08-08 21:37:59 -05:00
Alex Banna 45ed00ebc7 feat(ecs): apply EFS access point POSIX ownership to shared local volumes (#1686)
* feat(ecs): apply EFS access point POSIX ownership to shared local volumes

#1569 materialises an ECS task's efsVolumeConfiguration volume as a shared
local Docker named volume (floci-efs-<fileSystemId>). Docker creates a named
volume root:root 0755, so a task whose image runs as a non-root USER — as
containers mounting an EFS access point typically do — cannot create files on
it and fails with EACCES.

Real EFS initialises an access point's root directory per
RootDirectory.CreationInfo {OwnerUid, OwnerGid, Permissions} and applies the
access point's PosixUser to all I/O regardless of the process uid. This change
emulates that mechanism for the shared local volume, driven by generic config:

- New floci.storage.efs.* block (owner-uid, owner-gid, root-permissions,
  setgid, init-image, mount-user, mount-group-add). Every value is empty/false
  by default, so a shared volume behaves exactly as before (a plain named
  volume, no ownership change) unless explicitly configured.
- ContainerLifecycleManager.ensureSharedVolume(...) ensures the volume then, if
  ownership is configured, chowns/chmods the mount root once (run-once guard;
  optional setgid so subdirectories inherit the owner gid) inside a short-lived
  helper container.
- ContainerSpec/ContainerBuilder gain withUser/withGroupAdd; wired into
  createContainerCmd.withUser and HostConfig.withGroupAdd.
- EcsContainerManager initialises the EFS volume root via ensureSharedVolume
  before mounting it.

Unit tests cover the no-op default (no helper container, no image pull), the
one-off chown/chmod/setgid helper with the run-once guard, the builder
round-trip, and the EcsContainerManager wiring.

* fix(ecs): apply configured EFS PosixUser to containers mounting a shared volume

Wire the previously-inert floci.storage.efs.mount-user / mount-group-add config into the
ECS container spec: a container mounting an EFS-backed shared volume now runs under the
configured uid[:gid] and adds the supplementary group, emulating the access point's
PosixUser squashing. Without this a non-root image USER could not write a volume owned by
owner-uid/owner-gid. Also add the floci.storage.efs.* section to application.yml (the
source of truth for effective defaults) and correct the root-permissions Javadoc, which
implied leaving it empty always skips volume init even when owner/setgid are set.

* docs: regenerate action tables
2026-07-08 23:24:48 -05:00
Hector Ventura 9e35046647 Docs/enviroment instead yml (#764)
* docs: moving all config to env instead of yml
* docs: sync with main and new features
* docs: reverting docker-compose.yml
2026-05-10 11:53:31 -05:00
Kenshin Okinaka 88f40a839b docs: update Docker image references to floci/floci (#595)
* docs: update Docker image references to floci/floci
* docs: keep README Docker Hub badges pointing to hectorvent/floci

The hectorvent/floci image has accumulated pull and size metrics; switch
the badges to floci/floci once the new image has comparable numbers.
2026-04-25 09:29:39 -05:00
Hector Ventura 4f0150870a feat(docker): centralize Docker config and add private registry authentication (#549) 2026-04-21 08:45:37 -05:00
Hector Ventura 07a7a97b47 feat(ecs): adding ecs service (#209)
* feat(ecs): adding ecs service
* feat(ecs): adding ecs service
2026-04-05 10:25:41 -05:00