mirror of
https://github.com/floci-io/floci.git
synced 2026-11-23 14:10:49 -05:00
fee688bd051a5bde4e2e8a4d5e0f5d75c7ffe00a
46
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
2d3fb0ce87 |
fix(ecs): bound FireLens socket volume paths (#6787)
Bound the FireLens socket volume name while retaining full ownership labels and cleanup retries, and validate the inspected host path before creating containers. Signed-off-by: Andre Kurait <akurait@amazon.com> Signed-off-by: Andre Kurait <AndreKurait@gmail.com> |
||
|
|
a4ef9eaa6a | fix(ecs): renew task role credentials at the published URI (#6728) | ||
|
|
1bf019f89a | fix(ecs): honour privileged EC2 task containers (#6659) | ||
|
|
c910de57cc | fix(ecs): add opt-in dynamic awsvpc host ports (#6509) | ||
|
|
1b15299228 |
feat(ecs): publish Container Insights task counts (#6054)
* feat(ecs): publish Container Insights task counts A service on a cluster whose containerInsights setting is enabled or enhanced publishes RunningTaskCount, PendingTaskCount and DesiredTaskCount to ECS/ContainerInsights once a minute, with ClusterName and ServiceName dimensions, while it has a running task. The AWS::ECS::Cluster provisioner applies ClusterSettings and restores the prior settings when a stack update rolls back. * fix(ecs): resolve ClusterSettings as a whole before reading it A ClusterSettings list wrapped in Fn::If was iterated unresolved and stored a setting with no name or value. Resolve the property node first, as the provisioner does for its other list properties. * fix(ecs): resolve ClusterSettings before creating the cluster A ClusterSettings value that failed to resolve left a cluster the stack did not track. Resolve first, and skip an entry that resolved to AWS::NoValue. * fix(ecs): date Container Insights counts by the minute they were observed * fix(ecs): count Container Insights tasks when they are published The task counts came from the service's cached runningCount, which the reconcile sets before it scales the service in or out, and from a pendingCount nothing ever sets. They are now counted from the service's own tasks after the tick has started and stopped them, so a scale-in is reported in the tick that stops the task and a PENDING task is counted. A committed in-place cluster update now drops its settings snapshot in completeUpdate: the engine only calls clearUpdate after a replacement, so the snapshot outlived the update it belonged to. * docs(ecs): note that removing ClusterSettings keeps the cluster's settings * test(ecs): cover restoring null cluster settings and read the latest metric bucket A stack update that adds ClusterSettings to a cluster created without any rolls back to null settings, through the JSON null in the snapshot; the rollback test now covers that case alongside a prior disabled setting. The scale-in test reads the latest one-minute bucket, so a minute rollover between its two reconciles no longer splits the samples into two buckets and fails the test. * fix(ecs): log a failed Container Insights write as a warning The publish ran inside the reconcile's catch, which logs only the message at debug level, so a failed metric write left the minute's sample missing without a trace. It now has its own try and logs the exception at warn. * perf(ecs): write a Container Insights sample only when a count changes The reconciler ticks every five seconds and wrote all three counts each time, and a persistent metric store rewrites its file on every put. The last sample written per account and service is kept, and the minute's sample is written again only when a count changes. A reset clears it, since it wipes the samples too. * fix(cloudformation): restore ECS cluster settings when their own update fails A failed provision puts back the resource the stack held before the attempt, which never carried the settings snapshot, so the rollback walker skipped it and the new settings stayed. The provisioner now restores the snapshot itself, as the other in-place provisioners do, and records a restore that fails as a rollback failure. The physical id is set before the settings call, so the restore and a create rollback both find the cluster. * fix(ecs): repeat a Container Insights write that failed partway The last sample written was kept until the next one replaced it, so when one count landed and the next write failed, and the counts then went back to the ones last written, the next tick skipped the minute and left the partial value in place. The record is now dropped before writing and set again only once all three counts are written. * fix(cloudformation): keep an ECS settings snapshot whose restore failed When a cluster's settings update and its own restore both failed, the snapshot stayed on the attempted resource, and the engine put back the prior resource without it. The first rollback reported the failure, and ContinueUpdateRollback then found no snapshot and reported the rollback complete with the new settings still live. The snapshot is now carried onto the restored resource, so the continuation retries the restore. * fix(cloudformation): create an ECS cluster with its settings A new cluster was created and then given its ClusterSettings in a second call. When that call failed, on a stack create or a rename, nothing tracked the cluster: the create rollback skips a CREATE_FAILED resource it does not own, and a rename never reached the replacement record. The settings now go into CreateCluster itself, so a new cluster is never left without them. A cluster the idempotent create returned, which the stack did not create, still has them applied separately and is not deleted when that fails. * fix(cloudformation): set an ECS cluster's id only once its settings apply The physical id was set before the settings call. When an update added a cluster under the name of one created outside the stack, the idempotent create returned that cluster, and if its settings then failed, the update rollback deleted the added resource and with it a cluster the stack never created. The id is set after the settings again; an update of the resource's own cluster already carries its prior id for the restore. * fix(cloudformation): restore the settings of an ECS cluster the stack found Only a resource's own cluster had its prior settings put back when the settings call failed. A cluster the idempotent create returned for a resource the stack creates or adds kept whatever a failed call left on it, while the rollback, which drops the resource, reported a clean finish. A cluster whose settings still differ after CreateCluster existed before, so its prior settings are now captured and restored either way; the snapshot attribute for the rollback walker stays on the resource's own cluster only. * test(ecs): date Container Insights samples by a clock the test pins publishContainerInsights read the minute from the wall clock, so the test of an unchanged sample skipped itself when the minute rolled over between its ticks. The minute now comes from a Clock given to a package-private constructor, which the injected one calls with Clock.systemUTC(); the test pins it and asserts the sample is dated by it. * test(ecs): drive the reconciler instead of waiting on its ticks The CloudFormation integration test waited up to 30 seconds for the background reconciler to launch the task and publish its count. It now calls reconcileServices twice, as the other ECS integration tests do. |
||
|
|
17f32c9d04 |
fix(ecs): retry FireLens configuration uploads (#6075)
* fix(ecs): retry FireLens configuration archive uploads * test(ecs): cover FireLens upload failure boundaries * perf(ecs): avoid streaming pipes for prebuilt FireLens archives Reuse byte-backed archive retries without the 16 MiB pipe and writer thread per attempt. Preserve exact archive bytes and the shared retry policy. Warmed launch measurements dropped from 17.3 MB to 0.5-0.6 MB on the caller thread, with zero new writer threads. Add regression coverage for allocation path, consumed streams and failure boundaries. * test(ecs): make FireLens retry regressions sleep-free Add a package-private task-launch overload for the FireLens upload delay. The public entry point retains six attempts and the shared 500 ms initial backoff. Preserve real replay and cleanup assertions, and verify default, zero and nonzero delay selection. The expanded 32-case class runs in 0.54-0.68 seconds instead of 22.19 seconds. |
||
|
|
e38ec02d44 |
fix(cloudformation): register an ECS task definition's containers with their LinuxParameters (#6027)
* fix(cloudformation): register an ECS task definition's containers with their LinuxParameters An AWS::ECS::TaskDefinition dropped its containers' LinuxParameters, so a container CloudFormation registered ran without the init process, capabilities, devices, shared memory, swap or tmpfs mounts the template asked for, and the Fargate rules on them never applied. They are now read from the task definition as the ECS handler converts it and kept where RegisterTaskDefinition keeps them, among the container's unparsed members under linuxParameters, so DescribeTaskDefinition returns them in the API's shape and the same validation, normalisation and Fargate checks apply as for a definition registered through the API. As CloudFormation's handler does (measured), the devices and tmpfs lists are sent empty when the template has none. * test(compat): wait for the LinuxParameters stacks through TestFixtures Review of #6027: the test's private waitForTerminal and waitForDeleted repeated TestFixtures.awaitStackTerminal. It now waits through that, and deletes its two stacks with a plain DeleteStack after the class, as CloudFormationEcsTaskDefinitionModelTest does. * test(compat): give the ECS CloudFormation stacks Floci's and AWS's own timeouts Review of #6027: DEPLOY_TIMEOUT was 30 seconds against both targets. These stacks finish in milliseconds on Floci, so it is now 10 seconds there and 10 minutes on real AWS, as CloudFormationEventsRuleTargetTest splits it. CloudFormationEcsTaskDefinitionModelTest, from #6018, had the same single 60 seconds and splits the same way. |
||
|
|
98b2429e58 |
fix(ecs): launch a container with its linuxParameters, checked as RegisterTaskDefinition does (#5951)
* fix(ecs): launch a container with its linuxParameters, checked as RegisterTaskDefinition does
RegisterTaskDefinition kept a container's linuxParameters and
DescribeTaskDefinition returned them, but the container was launched
without any of them. A worker that set initProcessEnabled so its orphaned
browser processes would be reaped ran with its own command as PID 1, and
they stayed zombies until the container ended; capabilities, devices,
/dev/shm size, tmpfs mounts and swap limits were ignored the same way.
ECS documents each member as a docker run option, and the container is
now created with them: initProcessEnabled is --init (through
ContainerSpec.init, the flag main already has for it), capabilities are
--cap-add and --cap-drop, devices are --device (read, write and mknod when
no permissions are given, at the host path when no container path is),
sharedMemorySize is --shm-size in MiB, each tmpfs entry is a --tmpfs of
its size in MiB with its mount options, maxSwap is --memory-swap as the
container's hard limit plus that many MiB, and swappiness is
--memory-swappiness. ContainerSpec gains LinuxOptions for the rest,
applied in ContainerLifecycleManager's HostConfig; a constructor with the
former signature keeps every other caller unchanged.
A container behind a security group already had NET_ADMIN and NET_RAW
dropped, because the group is enforced by nftables in the namespace the
task's containers share. Docker applies a named --cap-add over a
--cap-drop, so those two are now also removed from what the container
asks to add; ALL can stay, since Docker grants every capability but the
dropped ones then (measured: docker run --cap-add ALL --cap-drop NET_ADMIN
--cap-drop NET_RAW reports CapEff 000001ffffffcfff, bits 12 and 13 clear).
Measured on RegisterTaskDefinition (eu-west-1, 2026-10-03 and 2026-10-16),
with the SDK's own validation off, and now checked the same way before
anything is stored:
- every capability must be one the KernelCapabilities reference lists, in
any case and without a CAP_ prefix ("Unrecognized Linux capabilities in
add: [CAP_NET_ADMIN]", likewise for drop);
- a device needs a hostPath ("Device cannot have empty hostPath") and only
read, write and mknod as permissions, as written ("Invalid permission:
READ for device /dev/null");
- a tmpfs mount needs a containerPath, a size above zero and options the
Tmpfs reference lists, as written ("The NOEXEC tmpfs mount option
specified is invalid.");
- sharedMemorySize must be above zero, maxSwap zero or more and needs a
swappiness ("When a container has a swap memory, it must also specify a
swappiness value."), from 0 to 100;
- the checks run capabilities, devices, tmpfs, then swap, all before the
Fargate rules;
- on Fargate a non-empty devices list, sharedMemorySize, maxSwap and
swappiness are refused in that order ("Fargate compatible task
definitions do not support devices", with no trailing period, unlike
AWS's other Fargate refusals), and any capability added but SYS_PTRACE
as written ("NET_ADMIN is not allowed on Fargate.");
- a swappiness without maxSwap is accepted and dropped, and capabilities
are stored with both an add and a drop list.
EcsLinuxParameters holds all of it, validation, the stored form and the
launch, and reads the members through one set of helpers, so EcsService
only calls it.
Not done: swap is not limited for a container with no hard memory limit,
since Docker cannot limit swap without one, and a daemon on cgroup v2
discards swappiness, as Amazon Linux 2023 does on ECS.
Tests: EcsLinuxParametersTest and ContainerLifecycleManagerLinuxOptionsTest
for what reaches Docker, EcsLinuxParametersDockerIntegrationTest for a
real container (PID 1, capabilities, device, /dev/shm, tmpfs),
EcsFargateEdgeCaseIntegrationTest for the measured refusals and the stored
form, and EcsLinuxParametersRegistrationTest in sdk-test-java for the
same through the SDK.
* fix(ecs): read linuxParameters as RegisterTaskDefinition does, and guard devices like host volumes
Review of #5951 (Qodo).
A device hands the container the host's hardware, and reached Docker with
no check, where a host volume at the same path is refused by default.
HostVolumePolicy now covers each device's hostPath too, naming the field
it checks: refused unless floci.services.ecs.host-volume-roots holds it or
allow-unsafe-host-volumes is set, at RegisterTaskDefinition after AWS's
own checks (so their messages still come first) and again at launch,
through EcsContainerManager.checkDeviceHostPaths. The registration check
sits in EcsService rather than beside the host volume one in
EcsJsonHandler, so a template's definition gets it too.
Measured with raw requests on RegisterTaskDefinition (eu-west-1,
2026-10-18):
- a member of the wrong JSON type is refused with an
InvalidParameterException from the deserializer, before any rule on the
values: "Unexpected field type" for a scalar where an object or a list
is expected, "Unexpected value type in payload" for a device or a tmpfs
mount that is not an object, "Start of structure or map found where not
expected" for an object where a list or a scalar is expected,
"NUMBER_VALUE cannot be converted to String", "STRING_VALUE cannot be
converted to Integer", "TRUE_VALUE ...", "NUMBER_VALUE cannot be
converted to Boolean", "Unexpected token received from parser" for text
that is not true or false, and no message at all for a list where none
is expected;
- numbers are read as integers, the fraction dropped (sharedMemorySize
1.9 is stored as 1, 0.5 as 0 and refused) and the range capped
(3000000000 is 2147483647); a boolean may come as text in any case; a
null member or list entry is absent, and a null device is an empty one.
Floci kept such values as written and silently skipped what it could not
read, so a definition stored one size and launched another. The stored
form now holds what AWS stores.
Tests: EcsFargateEdgeCaseIntegrationTest for every measured shape, the
stored numbers, booleans and nulls, and a device refused by default; the
Docker test allows /dev/null through host-volume-roots. All fail on the
previous head.
* refactor(ecs): check linuxParameters' JSON types against the vendored ECS model
Review of #5951. EcsLinuxParameters hand-wrote the deserializer's type
check member by member, where Floci already drives that check from
botocore for DynamoDB and SES v2 (RequestShapeModel, with the shapes
vendored by tools/aws/request_shapes.py).
tools/aws/regen_ecs_shapes.py vendors botocore's ECS model as
src/main/resources/aws/ecs-request-shapes.json (botocore 1.43.113, the
release requirements.txt pins), registered in make aws-data-sync and
aws-data-check and in the shared generator's tests. EcsRequestShapes
walks a container's linuxParameters against the LinuxParameters shape
with ECS's InvalidParameterException messages, the ones measured on
RegisterTaskDefinition; EcsLinuxParameters' own member list is gone.
The messages and their order are unchanged.
The device change named host volumes only in two more descriptions of
floci.services.ecs.host-volume-roots: docs/configuration/
environment-variables.md and the configuration table in
docs/services/ecs.md now name devices too, as does the host volume
section and the allow-unsafe-host-volumes Javadoc.
Tests: EcsRequestShapesTest for every measured message against the
vendored model; EcsFargateEdgeCaseIntegrationTest passes unchanged.
* refactor(core): walk request shapes once, with each service's messages
Review of #5951: EcsRequestShapes walked the vendored model the same way
DynamoDbRequestShapes and SesV2RequestShapes do (a null is absent, an
unknown member is skipped, a structure's values are read as members and a
list's or a map's as elements, a boolean reads from "true" or "false" in
any case, a scalar of the wrong kind is named by its JSON token), with only
the error code and a few messages apart. That walk is now
RequestShapeCheck, next to RequestShapeModel in core.common, and each
service hands it its deserializer's wording as RequestShapeCheck.Messages:
DynamoDB's SerializationException with DECIMAL_VALUE and the base-64
message for a blob, SES v2's SerializationException with its "can not be
converted to a" wording and only strings and blobs checked, as probed, and
ECS's InvalidParameterException with no message for a list where none is
expected.
The three services' tests pass unchanged. SES v2's wording becomes
constants in SesV2Json, which its member helpers and the walk share.
|
||
|
|
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 |
||
|
|
6e8a083d2b | fix(ecs): use caller endpoint for exec stream URLs (#5666) | ||
|
|
9f224e5760 | fix(ecs): preserve binary output in exec sessions (#5621) | ||
|
|
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 |
||
|
|
431748f740 | fix(ecs): launch service tasks through capacity provider strategies (#5500) | ||
|
|
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> |
||
|
|
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 |
||
|
|
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. |
||
|
|
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 |
||
|
|
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 |
||
|
|
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. |
||
|
|
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. |
||
|
|
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. |
||
|
|
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 |
||
|
|
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. |
||
|
|
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 |
||
|
|
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 |
||
|
|
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. |
||
|
|
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. |
||
|
|
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. |
||
|
|
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. |
||
|
|
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. |
||
|
|
869589e932 | feat(ecs): publish awsvpc ports on demand (#3766) | ||
|
|
de54409fc6 |
fix(ecs): apply volumesFrom to task containers (#3811)
Co-authored-by: xujiantop-crypto <265865031+xujiantop-crypto@users.noreply.github.com> |
||
|
|
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. |
||
|
|
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 |
||
|
|
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> |
||
|
|
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. |
||
|
|
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. |
||
|
|
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> |
||
|
|
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> |
||
|
|
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. |
||
|
|
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. |
||
|
|
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 |
||
|
|
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 |
||
|
|
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. |
||
|
|
4f0150870a | feat(docker): centralize Docker config and add private registry authentication (#549) | ||
|
|
07a7a97b47 |
feat(ecs): adding ecs service (#209)
* feat(ecs): adding ecs service * feat(ecs): adding ecs service |