Commit Graph
8 Commits
Author SHA1 Message Date
dkatavic a318dc7b90 fix(msk): publish a host listener when Floci runs in a container (#5651)
* fix(msk): publish a host listener when Floci runs in a container

* fix(msk): list both listeners in GetBootstrapBrokers when a bootstrap hostname is set

With floci.services.msk.bootstrap-hostname set, GetBootstrapBrokers
returned only the host listener's address, <hostname>:<port>. Inside a
sibling container that is usually the container itself, so the setting
broke broker discovery for containers on the Docker network, the case the
Docker-network default exists to keep working.

It now returns both listeners, <container-name>:9092,<hostname>:<port>.
Kafka clients try bootstrap entries until one connects, and the broker then
advertises the address of the listener they came in on, so host and
sibling-container clients can each discover the broker through the MSK
API. The broker's listeners and advertised addresses are unchanged; only
the API response is.

The container name is used rather than its IP because it fails fast on the
host, where it does not resolve, while an IP the host cannot route to waits
for a connect timeout. It goes first for callers that read only the first
entry, such as isReady's fallback after a restart.

A blank bootstrap hostname is now treated as unset in both places that read
it. Before, the advertised address fell back to localhost while the
bootstrap response still switched to the host form.

* fix(msk): resolve broker readiness from the container id, not an in-memory map

* fix(msk): release the Kafka host port when setup fails before the container starts

* docs(msk): document the bootstrap-hostname setting

* fix(msk): probe broker readiness on the broker's own Docker network

* test: import LinkedHashMap instead of qualifying it inline

* fix(msk): try the next Kafka host port when Docker reports it in use

When Floci runs in a container, PortAllocator.allocate() probes ports in
Floci's own network namespace, so it cannot see a host process that
already holds one, such as a local Kafka or a second Floci. Docker then
refuses the bind, and startContainer released the port and failed the
cluster even though the rest of the kafka-host-port range was free.
Before the host listener, container mode published no Kafka port, so
this is new with it.

startContainer now goes through PortAllocator.allocateAndStart, as the
ECR registry and EC2 instances do: a port Docker reports as in use moves
on to the next one, and the Redpanda listener args and container spec
are rebuilt for each candidate. allocateAndStart also releases the port
on any other failure before the container runs, volume setup included,
so it replaces the hand-written try.
2026-10-15 11:06:27 -04:00
MAN$I VERMAandPriamo Germosen 0205e4ed7e fix(msk): persist CreateCluster broker node groups, encryption, client auth, logging, configuration and tags (#2366)
* fix(msk): persist CreateCluster broker node group, encryption, client auth, logging, configuration and tags

* fix(msk): return the v2 Provisioned envelope and keep internal cluster state persistable

Addresses the two review findings on #2366, plus adjacent parity gaps.

Persistence: MskCluster is the shape WalStorage/PersistentStorage/HybridStorage
serialize, all with a plain ObjectMapper. Marking bootstrapBrokers, containerId
and volumeId @JsonIgnore to keep them out of API responses also stripped them
from the store, so a restart on non-mock storage came back with no bootstrap
brokers (breaking GetBootstrapBrokers and the Pipes Kafka source) and no
container or volume ID (orphaning the Docker resources). Those fields are
serializable again - as is accountId, which putCluster needs to write back to
the right account partition - and the API-facing exclusion moved to explicit
response views in MskController, matching toConfigurationView.

V2 shape: DescribeClusterV2/ListClustersV2 returned the flat v1 ClusterInfo.
The real v2 Cluster nests broker node group, encryption, client auth, monitoring,
logging, broker count and kafka version under Provisioned, with a top-level
ClusterType. An AWS SDK v2 client - what terraform-provider-aws calls - reads
them only there, so the flat shape left them invisible to exactly the callers
this fix is for.

Also:
- configurationInfo is a request-only member; the configuration is now reported
  on currentBrokerSoftwareInfo as configurationArn/configurationRevision, where
  the Terraform provider reads it from. It has no top-level response member on
  either API version.
- Apply AWS's server-side defaults for enhancedMonitoring (DEFAULT) and
  encryptionInTransit (TLS_PLAINTEXT / inCluster true), so an omitted member
  does not read back as drift.
- Omit absent optional members instead of serializing them as null.
- Cover the v2 envelope through the real AWS SDK in the compatibility suite, and
  add a plain-ObjectMapper round-trip test guarding the persistence regression.

* test(msk): mirror the storage mapper's configuration in the round-trip test

* fix(msk): round-trip openMonitoring, storageMode and rebalancing too

Three more CreateCluster request members that were discarded the same way, and
that AWS echoes on DescribeCluster (flat) and DescribeClusterV2 (under
Provisioned). openMonitoring and storageMode both map to terraform-provider-aws
attributes on aws_msk_cluster, so dropping them left the same non-converging
plan this change set is about.

* feat(msk): add the tag API, serverless clusters and CreateCluster validation

Closes the four gaps left open by the metadata round-trip work.

Tags: MSK had no tag endpoints at all, so tags could be set at create time and
read back from Describe but never updated. AWS puts them on /v1/tags/{arn},
which AppSync already owned - and two JAX-RS resource methods cannot claim the
same path and method. Resolved the way /tags/{arn} already was: the dispatch and
wire-shape logic moved out of SharedTagsController into a shared TagDispatcher,
a V1TagsController serves /v1/tags/{arn} on top of it, and the two handler sets
are kept apart by a @V1Tags qualifier so each service stays reachable only on
the path AWS defines for it. AppSync's three controller methods became
AppSyncTagHandler with its wire shape unchanged; MskTagHandler is new. MSK tags
clusters and configurations, so MskConfiguration gained a persisted tags map.

Serverless: CreateClusterV2 silently flattened a serverless request into a
provisioned cluster, which then reported itself as provisioned and echoed broker
metadata the caller never sent. It is now a first-class shape - clusterType,
a serverless envelope on the v2 response, and exactly one of provisioned and
serverless per request. The v1 API predates serverless and its ClusterInfo
cannot represent one, so DescribeCluster rejects it the way AWS does and
ListClusters omits it.

Validation: a create with no clusterName built an ARN containing
cluster/null/<uuid> and stored a cluster unaddressable by name. clusterName is
now required and length-checked, and the members AWS documents a range or an
enum for are checked too. The presence of kafkaVersion, numberOfBrokerNodes and
brokerNodeGroupInfo is deliberately still not required - the emulator has always
defaulted those, and tightening it is a separate, deliberate break.

Also: MskConfiguration.accountId was @JsonIgnore, the same persistence bug the
cluster model had - an async write-back after a reload had no account to target.
ConnectivityInfo gained the networkType member it was missing on both shapes.

* test(msk): point the v2 kafkaVersion assertions at the provisioned envelope

These two predate the v2 shape fix and asserted
clusterInfo.currentBrokerSoftwareInfo.kafkaVersion - the flat v1 layout on a v2
response, which is exactly what that fix corrected. They were codifying the bug,
so they moved to clusterInfo.provisioned.currentBrokerSoftwareInfo.kafkaVersion
rather than the view changing back.

* fix(msk): drop the broker-count ceiling and name the invalid parameter

Applies the two findings from the #2571 review to the code that is actually
going to land.

The 1-15 range came from the SDK/CLI reference, which carries an
__integerMin1Max15 shape for numberOfBrokerNodes. Two other AWS sources
contradict it: the REST API reference documents no minimum or maximum for that
member - on a page that does give ranges for its neighbours, volumeSize 1-16384
and revision min 1 - and the quota page allows 30 brokers per ZooKeeper cluster
and 60 per KRaft cluster, both adjustable upward. Capping at 15 rejected
clusters real MSK creates, turning "converges on the wrong number" into an
outright apply failure for every count from 16 up. The floor stays: a zero or
negative broker count is nonsense and every source agrees.

MSK's Error schema is message plus invalidParameter, "the parameter that caused
the error". Every validation failure now names the member it rejected, via the
four-argument AwsException the mapper already splats into the body. The
pre-existing configuration validations are left as they are - that is merged
code, not this change's.

---------

Co-authored-by: Priamo Germosen <6233424+pgermosen@users.noreply.github.com>
2026-08-26 23:17:03 -04:00
Priamo Germosen 7505110ed9 feat(msk): add configuration revision actions (#2344)
* fix(core): extract shared pagination helper, reject maxResults=0

Closes #2339, #2340.

ListResult<T> and its paginate()/encode()/decode() helpers existed as
five near-identical private copies (BedrockAgentCoreGatewayService,
BedrockAgentCoreIdentityService, BedrockAgentCoreMemoryService,
BedrockAgentCoreControlService's three list methods, and MskService),
not the two originally scoped in #2340 - the ListResult<T> record was
already shared within bedrockagentcorecontrol, which is what earlier
scoping missed. Extracts core.common.Pagination + PaginatedResult<T>
and migrates every one of them, deleting both now-unused per-service
ListResult model classes.

Every duplicate collapsed "maxResults omitted" and "maxResults=0"
onto the same primitive int, defaulting both to the full page instead
of rejecting the explicit zero the way AWS's MaxResults min:1
constraint requires (confirmed against botocore's real kafka and
verified live: botocore itself refuses to send MaxResults=0
client-side). Pagination.paginate/parseMaxResults take a boxed
Integer so the two cases are distinguishable, and every migrated
service now rejects 0 with its own existing error code
(ValidationException for the bedrockagentcorecontrol services,
BadRequestException for MSK) - the fix lands once, not five times.

Also carries over the MskController fix from #2336: an
Integer-typed @QueryParam converts before the resource method runs,
so a non-numeric maxResults was a bare 404 instead of an AWS-shaped
400. Every migrated REST controller now binds maxResults as a String
and calls Pagination.parseMaxResults, closing the same gap in
BedrockAgentCoreGatewayController/ControlController/MemoryController
that MSK already had fixed.

* feat(msk): add configuration revision actions

Closes #2338.

Adds UpdateConfiguration, ListConfigurationRevisions, and
DescribeConfigurationRevision, the three actions #2299 explicitly
scoped out ("a separate follow-up issue"). MskConfiguration now
stores a full revision history (revisions + serverPropertiesByRevision
keyed by revision number) instead of a single latest-revision field -
UpdateConfiguration appends rather than overwrites, and
DescribeConfigurationRevision is the only action that returns
serverProperties (base64), matching AWS's real shapes: Configuration/
DescribeConfigurationResponse/CreateConfigurationResponse never
include it, verified against botocore's kafka service model the same
way as #2336/#2343 rather than trusting the docs page.

ListConfigurationRevisions builds on the shared Pagination.paginate
helper from #2343 (cursor = zero-padded revision number) instead of
introducing a sixth duplicate of that logic.

getLatestRevision() is now derived from the revision list rather than
a separately-stored field, so it can never drift out of sync with it.

* fix(msk): guard configuration schema upgrade and update-race in UpdateConfiguration

Old (pre-revision-history) persisted configurations have latestRevision/
serverProperties keys this class no longer maps, which previously threw and
failed the entire msk-configurations.json load; ignore them instead and
reject updates against such an entry with a 400 rather than NPE-ing.

Also serialize UpdateConfiguration's read-modify-write behind a lock so two
concurrent updates for the same ARN can no longer derive the same revision
number and silently overwrite each other's serverProperties.

* fix(msk): stop leaking mutable revision state through getters

MskConfiguration#getRevisions/getServerPropertiesByRevision returned the
live internal List/Map, which is why MskService#updateConfiguration was
mutating through them directly - and in an order (revision appended,
then its properties inserted) that let an unsynchronized reader observe
a revision with no server properties yet and NPE on Base64-encoding it.

Add MskConfiguration#addRevision to own both writes in the safe order,
and have the getters return copies so callers can no longer bypass it.

* fix(msk): guard revision reads with the same lock updateConfiguration writes under

listConfigurationRevisions/describeConfigurationRevision read revisions
and serverPropertiesByRevision - plain, non-thread-safe collections -
without holding configurationUpdateLock, so a concurrent updateConfiguration
could race the reader's iteration/copy, not just return stale data.

* fix(msk): close remaining unsynchronized-read races on configuration revisions

Two more gaps in the same family as the last fix:

- deleteConfiguration didn't take configurationUpdateLock, so it could
  race updateConfiguration and get resurrected by the update's trailing
  put(arn, ...) after the delete already removed the entry.
- getLatestRevision() is read directly from MskController with no access
  to the service's lock at all, so no per-call-site synchronized block
  can close that gap. Make revisions/serverPropertiesByRevision
  CopyOnWriteArrayList/ConcurrentHashMap instead, so every current and
  future reader is safe by construction rather than by remembering to
  take a lock it may not have access to.

* fix(msk): migrate pre-revision-history configurations onto revision 1

A configuration persisted before this PR's schema change stored a single
"latestRevision" object plus a flat "serverProperties" string. Those keys
were only being swallowed by ignoreUnknown, so the entry loaded with an
empty revision list and getLatestRevision() == null. AWS marks
Configuration's LatestRevision required, and toConfigurationView builds
into a HashMap - which keeps a key with a null value, unlike Map.of - with
no NON_NULL inclusion configured anywhere in the application. So
DescribeConfiguration and ListConfigurations emitted a required member as
an explicit "latestRevision": null for those entries, and
UpdateConfiguration rejected them permanently.

Map both old keys back onto revision 1 at load time instead. The data was
always still there, so this is a migration rather than a degradation, and
it un-breaks UpdateConfiguration for those configurations as well.

- The setters are deserialize-only: @JsonSetter is an explicit marker, so
  it survives the @JsonIgnore split on getLatestRevision() without
  re-enabling the write side. The old shape is read, never written back.
- Jackson calls the two setters in whatever order the keys sit in the
  file, so neither can assemble the revision alone; each buffers its half
  and the pair completes the migration.
- A legacy entry with no serverProperties migrates to an empty string, not
  null: serverPropertiesByRevision is a ConcurrentHashMap, which rejects
  null values, and DescribeConfigurationRevision base64-encodes what it
  finds without a null check.
- The updateConfiguration guard stays, now covering only an entry with no
  revision data at all rather than every pre-schema configuration.

Also corrects the comment in listConfigurationRevisions, which still
justified its lock by calling the collections plain and non-concurrent.
That was true when it was written but stopped being true in 93bc30e7; the
lock is kept, for consistency with describeConfigurationRevision reading
both collections, not to prevent a torn read.

Verified locally: MskServiceTest 34, MskControllerTest 2,
MskControllerIntegrationTest 20 - 0 failures, 0 errors. Reverting only the
MskConfiguration change fails 6 of the new tests, confirming they bite.
2026-08-19 21:53:33 -05:00
Priamo Germosen 4c510e576c feat(msk): add configuration CRUD (Create/List/Describe/Delete) (#2336)
* feat(msk): add configuration CRUD (Create/List/Describe/Delete)

MskController only served /v1/clusters and /api/v2/clusters, so every
configuration action 404s. An MSK configuration is the only supported
way to set broker-level server_properties, and aws_msk_configuration /
aws_msk_domain_policy are first-class Terraform resources - any stack
setting broker properties failed before the cluster was even attempted.

Adds a second StorageBackend on MskService (msk-configurations.json,
mirroring msk-clusters.json), a new MskConfiguration model, and four
endpoints on MskController mirroring the existing cluster handlers.
serverProperties is base64 on the wire; decoded and kept internal
(@JsonIgnore) since AWS only returns it via DescribeConfigurationRevision,
which is a separate follow-up issue - this stays plain CRUD.

Field names verified against botocore's actual kafka service model
rather than trusting the API reference docs verbatim: every field is
lowerCamelCase, including DeleteConfigurationResponse's `arn` (the
public API reference page shows "Arn" capitalized, which does not
match the real wire format).

* fix(msk): validate request field types and persist serverProperties

CreateConfiguration cast request fields directly (String)/(List<String>),
so a wrong-typed field threw ClassCastException instead of an AWS-shaped
BadRequestException, surfacing as an internal server error.

serverProperties was @JsonIgnore, which excludes it from Jackson
serialization entirely - not just REST responses, but also the
persistent/hybrid/wal StorageBackend serialization that uses the same
model. A configuration would silently lose its broker properties on
reload under any non-memory storage mode. The field now serializes
normally; the controller instead builds explicit response views for
Describe/List/Create so serverProperties still never appears on the
wire outside CreateConfiguration's own request, matching AWS (which
only returns it via the out-of-scope DescribeConfigurationRevision).

* fix(msk): default kafkaVersions to an empty array when omitted

kafkaVersions is optional on CreateConfigurationRequest, but
asStringList returns null when it's absent, and toConfigurationView
put that null straight into the response - AWS's Configuration shape
always populates it as an array. Default it the same way description
already is. No existing test created a configuration without the
field, which is why it slipped through.

* feat(msk): support maxResults/nextToken pagination on ListConfigurations

ListConfigurations previously returned every configuration in one
response, ignoring the maxResults/nextToken query parameters the
model declares. Mirrors the existing pagination pattern from
BedrockAgentCoreGatewayService (ListResult<T> + a private paginate()
helper): the cursor is the last returned item's ARN, base64
URL-encoded, resumed by scanning the ARN-sorted list past that value.
maxResults is bounded to [1, 100] and an undecodable token both throw
BadRequestException, matching CreateConfiguration's existing error
family for this service.
2026-08-15 21:50:20 -04: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
Hector Ventura 01dbc76fc8 feat(docker): named-volume storage for child containers (#743)
Replace the FLOCI_STORAGE_HOST_PERSISTENT_PATH footgun with automatic
named Docker volume management for RDS, OpenSearch, MSK, and ECR.

- Each resource gets a collision-free 6-char hex volumeId generated once
  at creation and stored in the model. Container and volume names both use
  it: floci-{service}-{volumeId}
- Volumes are labelled floci=true for easy pruning
- Memory mode always removes volumes on resource delete. Persistent modes
  retain by default; set prune-volumes-on-delete: true to remove on delete
- Mode detection: FLOCI_STORAGE_HOST_PERSISTENT_PATH set to an absolute
  path → host bind-mount mode (legacy); unset or non-absolute → named-
  volume mode. Volume names in host-persistent-path are not supported
- Removed the container-storage config key — no longer needed
- Updated docker-compose.yml, and all docs
2026-05-08 17:12:36 -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 91071aaae7 feat: implement Amazon MSK service with Redpanda orchestration (#419)
* feat: implement Amazon MSK service with Redpanda orchestration
* fix: adding missing msk service on the test
2026-04-13 20:22:37 -05:00