Light, fluffy, and always free - The AWS Local Emulator alternative
fix(amazonmq): add configuration for AMQP and console host port ranges (#3315)
Matheus André2d5a8f705b75
diff --git a/docs/configuration/environment-variables.md b/docs/configuration/environment-variables.mdindex 85bff0c889..4ab178986c 100644--- a/docs/configuration/environment-variables.md+++ b/docs/configuration/environment-variables.md@@ -389,6 +389,18 @@ These services spawn Docker containers. They require access to the Docker socket| `FLOCI_SERVICES_MSK_MOCK` | `false` | When `true`, clusters are created instantly without a real Redpanda container || `FLOCI_SERVICES_MSK_DEFAULT_IMAGE` | `redpandadata/redpanda:latest` | Docker image for Kafka/Redpanda brokers |+### Amazon MQ++| Variable | Default | Description |+|---|---|---|+| `FLOCI_SERVICES_AMAZONMQ_ENABLED` | `true` | Enable the Amazon MQ service |+| `FLOCI_SERVICES_AMAZONMQ_MOCK` | `false` | When `true`, brokers are created instantly without a real RabbitMQ container |+| `FLOCI_SERVICES_AMAZONMQ_DEFAULT_IMAGE` | `rabbitmq:3-management` | Docker image for RabbitMQ broker containers |+| `FLOCI_SERVICES_AMAZONMQ_AMQP_HOST_PORT_BASE` | `5672` | First host port in the range the AMQP listener is published on |+| `FLOCI_SERVICES_AMAZONMQ_AMQP_HOST_PORT_MAX` | `5699` | Last host port in the AMQP range |+| `FLOCI_SERVICES_AMAZONMQ_CONSOLE_HOST_PORT_BASE` | `15672` | First host port in the range the management console is published on |+| `FLOCI_SERVICES_AMAZONMQ_CONSOLE_HOST_PORT_MAX` | `15699` | Last host port in the console range |+### Managed Service for Apache Flink (Kinesis Analytics V2)| Variable | Default | Description |diff --git a/docs/configuration/ports.md b/docs/configuration/ports.mdindex 5a07a8a61d..500a60b920 100644--- a/docs/configuration/ports.md+++ b/docs/configuration/ports.md@@ -6,6 +6,7 @@|---|---|---|---|| `4566` | HTTP | All AWS API calls (every service) | Yes || `5100–5199` | HTTP | ECR Registry sidecar — bound directly by the `registry:2` container | **No** (see note) |+| `5672–5699` | AMQP | Amazon MQ (RabbitMQ) AMQP listener, bound directly by each broker container | **No** || `6379–6399` | TCP | ElastiCache Redis proxy (inside Floci) | Yes || `6400–6419` | TCP | MemoryDB proxy (inside Floci) | Yes || `6500–6599` | HTTPS | EKS k3s API server — bound directly by each k3s container | **No** |@@ -14,6 +15,7 @@| `8700–8799` | HTTP | MWAA Airflow webserver proxy (inside Floci) | Yes || `9400–9499` | HTTP | OpenSearch data-plane — bound directly by each OpenSearch container | **No** || `12000–12499` | HTTP | Lambda Runtime API (internal, Docker-network only) | **No** |+| `15672–15699` | HTTP | Amazon MQ (RabbitMQ) management console, bound directly by each broker container | **No** |## Why some ports don't need docker-compose mapping@@ -29,7 +31,7 @@ host:6379 → [docker-compose ports mapping] → Floci container:6379 →Because the listener is inside the Floci container, `ports:` in `docker-compose.yml` is required to make it reachable from the host.-### Direct container binding (ECR, EKS, OpenSearch)+### Direct container binding (ECR, EKS, OpenSearch, Amazon MQ)Floci tells the Docker daemon to start a sidecar/service container and bind its port **directly on the host**. Floci itself communicates with the container via the shared Docker network (container name + internal port). The host port is bound by Docker, not by Floci.@@ -135,6 +137,27 @@ curl http://localhost:9400/_cluster/health!!! noteConfigure the range with `FLOCI_SERVICES_OPENSEARCH_PROXY_BASE_PORT` and `FLOCI_SERVICES_OPENSEARCH_PROXY_MAX_PORT`.+## Ports 5672–5699 and 15672–15699: Amazon MQ (RabbitMQ, real mode)++When you create an Amazon MQ broker in real mode, Floci starts a `rabbitmq:3-management` container and binds its AMQP port (5672) to the next available host port in `5672–5699`, and its management console (15672) to the next available host port in `15672–15699`. Both are bound directly on the host by Docker, in every topology. No `docker-compose.yml` mapping is needed, and adding one on the `floci` service would only conflict with the broker container's binding.++The `BrokerInstances[].Endpoints` returned by `DescribeBroker` point to `amqp://localhost:<hostPort>` when Floci runs outside a container, or to the broker container's Docker-network IP when Floci runs inside Docker. In the second case, host clients should use the published host port instead (`docker ps` shows it); the first broker normally lands on `5672` / `15672`.++```bash+aws mq create-broker --broker-name my-broker --engine-type RABBITMQ \+ --engine-version "3.13" --deployment-mode SINGLE_INSTANCE \+ --host-instance-type mq.t3.micro --no-publicly-accessible --auto-minor-version-upgrade \+ --users '[{"Username":"admin","Password":"AdminPass123","ConsoleAccess":true}]' \+ --endpoint-url http://localhost:4566++# From the host, once the broker is RUNNING:+# amqp://admin:AdminPass123@localhost:5672/+# http://localhost:15672 (management console)+```++!!! note+ Configure the ranges with `FLOCI_SERVICES_AMAZONMQ_AMQP_HOST_PORT_BASE` / `_MAX` and `FLOCI_SERVICES_AMAZONMQ_CONSOLE_HOST_PORT_BASE` / `_MAX`.+## Ports 5100–5199 — ECR RegistryECR is backed by a separate `registry:2` sidecar container (`floci-ecr-registry`) that Floci starts on the first ECR API call. That container binds its port directly on the host — **do not** add `5100-5199` to the floci service's `ports` in Docker Compose. Doing so pre-allocates those ports on the Floci container and prevents the sidecar from binding them.@@ -150,7 +173,7 @@ host:5100 ←── floci-ecr-registry (registry:2 container, started by Floci## Exposing Ports in Docker Compose-Only the proxy-based services (ElastiCache, MemoryDB, RDS, Neptune, MWAA) need port mappings in `docker-compose.yml`. Direct-binding services (ECR, EKS, OpenSearch) bind their ports on the host automatically via Docker:+Only the proxy-based services (ElastiCache, MemoryDB, RDS, Neptune, MWAA) need port mappings in `docker-compose.yml`. Direct-binding services (ECR, EKS, OpenSearch, Amazon MQ) bind their ports on the host automatically via Docker:```yamlservices:@@ -167,6 +190,6 @@ services:- /var/run/docker.sock:/var/run/docker.sock```-EKS (6500–6599) and OpenSearch (9400–9499) ports are bound directly on the host by Docker and are accessible without any `ports:` entry. ECR (5100–5199) must not be added.+EKS (6500–6599), OpenSearch (9400–9499) and Amazon MQ (5672–5699, 15672–15699) ports are bound directly on the host by Docker and are accessible without any `ports:` entry. ECR (5100–5199) must not be added.If your application runs inside the same Docker Compose network, it can reach Floci directly on container port `4566` — the host port mapping is only needed for tools running on the host (CLI, IDE plugins, etc.).diff --git a/docs/services/amazonmq.md b/docs/services/amazonmq.mdindex c88eccbf47..5b853c44e8 100644--- a/docs/services/amazonmq.md+++ b/docs/services/amazonmq.md@@ -36,6 +36,10 @@ container.| `FLOCI_SERVICES_AMAZONMQ_ENABLED` | `true` | Enable or disable the service || `FLOCI_SERVICES_AMAZONMQ_MOCK` | `false` | `true` = metadata-only CRUD, no Docker containers || `FLOCI_SERVICES_AMAZONMQ_DEFAULT_IMAGE` | `rabbitmq:3-management` | Docker image for RabbitMQ broker containers |+| `FLOCI_SERVICES_AMAZONMQ_AMQP_HOST_PORT_BASE` | `5672` | First host port in the range the AMQP listener (5672) is published on |+| `FLOCI_SERVICES_AMAZONMQ_AMQP_HOST_PORT_MAX` | `5699` | Last host port in the AMQP range |+| `FLOCI_SERVICES_AMAZONMQ_CONSOLE_HOST_PORT_BASE` | `15672` | First host port in the range the management console (15672) is published on |+| `FLOCI_SERVICES_AMAZONMQ_CONSOLE_HOST_PORT_MAX` | `15699` | Last host port in the console range |## How it works@@ -43,9 +47,17 @@ When `mock` is set to `false` (default), Floci uses the Docker API to start a Racontainer for each created broker. For Docker socket setup, private registryauthentication, and other Docker settings see [Docker Configuration](../configuration/docker.md).-- **Port Mapping**: The AMQP port (5672) and the management UI (15672) are each mapped to- a dynamic host port. Use the endpoints returned by `DescribeBroker` rather than a fixed- port.+- **Port Mapping**: The AMQP port (5672) and the management UI (15672) are each bound+ directly on the Docker host to the next free port in their configured ranges+ (`5672–5699` and `15672–15699` by default), so the first broker is normally reachable+ at `amqp://localhost:5672` and `http://localhost:15672`. This binding is made whether+ Floci runs natively or inside Docker: no Floci-internal proxy fronts the broker, so it is+ the only way a client on the host can reach a broker started by a containerized Floci+ (no `ports:` entry on the `floci` service is needed, or should be added, for these ranges).+ `DescribeBroker` reports the address Floci itself uses: `localhost:<hostPort>` when Floci+ runs natively, or the broker container's Docker-network IP when Floci runs inside Docker.+ In that second case, use `docker ps` to see the host port a given broker container is+ published on.- **Admin user**: The `CreateBroker` user is seeded via `RABBITMQ_DEFAULT_USER` /`RABBITMQ_DEFAULT_PASS`. Unlike the built-in `guest` user (which RabbitMQ restricts toloopback connections), this user can authenticate over the mapped port.diff --git a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.javaindex e4ee656d08..66e0a25040 100644--- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java+++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java@@ -1172,6 +1172,31 @@ public interface EmulatorConfig {@WithDefault("rabbitmq:3-management")String defaultImage();++ /**+ * Host port range the AMQP listener (container port 5672) is published on, one+ * port per broker. Published in both topologies: no Floci-internal proxy fronts+ * the broker, so the Docker host-port binding is the only way a client outside+ * the Docker network (e.g. on the host, with Floci itself containerized) can+ * reach it (#3240). Env: FLOCI_SERVICES_AMAZONMQ_AMQP_HOST_PORT_BASE+ */+ @WithDefault("5672")+ int amqpHostPortBase();++ /** Env: FLOCI_SERVICES_AMAZONMQ_AMQP_HOST_PORT_MAX */+ @WithDefault("5699")+ int amqpHostPortMax();++ /**+ * Host port range the RabbitMQ management console (container port 15672) is+ * published on. Env: FLOCI_SERVICES_AMAZONMQ_CONSOLE_HOST_PORT_BASE+ */+ @WithDefault("15672")+ int consoleHostPortBase();++ /** Env: FLOCI_SERVICES_AMAZONMQ_CONSOLE_HOST_PORT_MAX */+ @WithDefault("15699")+ int consoleHostPortMax();}interface KinesisAnalyticsServiceConfig {diff --git a/src/main/java/io/github/hectorvent/floci/services/amazonmq/container/RabbitMqManager.java b/src/main/java/io/github/hectorvent/floci/services/amazonmq/container/RabbitMqManager.javaindex d37d0b8942..0dffb2bea5 100644--- a/src/main/java/io/github/hectorvent/floci/services/amazonmq/container/RabbitMqManager.java+++ b/src/main/java/io/github/hectorvent/floci/services/amazonmq/container/RabbitMqManager.java@@ -10,6 +10,7 @@ import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager.Eimport io.github.hectorvent.floci.core.common.docker.ContainerLogStreamer;import io.github.hectorvent.floci.core.common.docker.ContainerSpec;import io.github.hectorvent.floci.core.common.docker.ContainerStorageHelper;+import io.github.hectorvent.floci.core.common.docker.PortAllocator;import io.github.hectorvent.floci.services.amazonmq.model.Broker;import io.github.hectorvent.floci.services.amazonmq.model.BrokerInstance;import io.github.hectorvent.floci.services.amazonmq.model.MqUser;@@ -27,13 +28,17 @@ import java.util.concurrent.ConcurrentHashMap;/*** Manages the backing RabbitMQ Docker container for an Amazon MQ broker.- * In native (dev) mode it publishes the AMQP (5672) and management (15672)- * ports to dynamic host ports; in Docker mode sibling containers reach the- * broker over the docker network.+ * The AMQP (5672) and management (15672) ports are each published to a host+ * port allocated from the configured ranges, in both topologies. Unlike the+ * proxy-fronted services (RDS, ElastiCache), nothing inside Floci relays AMQP+ * traffic, so when Floci itself runs in Docker the host-port binding is the only+ * way a client on the host can reach the broker (#3240), the same reasoning as+ * {@code OpenSearchDomainManager}. Sibling containers keep reaching the broker+ * over the docker network via the endpoints reported by {@code DescribeBroker}.** <p>Unlike {@code RedpandaManager}, RabbitMQ does not advertise a self-perceived- * address back to clients, so no pre-allocated/advertised port is needed —- * dynamic ports (the ElastiCache pattern) are enough.+ * address back to clients, so the host port does not need to be passed to the+ * container as a startup argument.*/@ApplicationScopedpublic class RabbitMqManager {@@ -46,22 +51,32 @@ public class RabbitMqManager {private final ContainerLifecycleManager lifecycleManager;private final ContainerLogStreamer logStreamer;private final ContainerDetector containerDetector;+ private final PortAllocator portAllocator;private final EmulatorConfig config;private final RegionResolver regionResolver;private final Map<String, Closeable> logStreams = new ConcurrentHashMap<>();private final Map<String, String> containerIds = new ConcurrentHashMap<>();+ // Host ports reserved for each running broker (in-memory only, like containerIds):+ // released when the container goes away so repeated create/delete cycles do not+ // exhaust the configured ranges.+ private final Map<String, HostPorts> hostPorts = new ConcurrentHashMap<>();++ /** The pair of host ports a broker's container is published on. */+ record HostPorts(int amqp, int console) {}@Injectpublic RabbitMqManager(ContainerBuilder containerBuilder,ContainerLifecycleManager lifecycleManager,ContainerLogStreamer logStreamer,ContainerDetector containerDetector,+ PortAllocator portAllocator,EmulatorConfig config,RegionResolver regionResolver) {this.containerBuilder = containerBuilder;this.lifecycleManager = lifecycleManager;this.logStreamer = logStreamer;this.containerDetector = containerDetector;+ this.portAllocator = portAllocator;this.config = config;this.regionResolver = regionResolver;}@@ -106,38 +121,46 @@ public class RabbitMqManager {specBuilder.withEnv("RABBITMQ_DEFAULT_PASS", admin.getPassword());}- if (!containerDetector.isRunningInContainer()) {- specBuilder.withDynamicPort(AMQP_PORT).withDynamicPort(MGMT_PORT);- } else {- specBuilder.withExposedPort(AMQP_PORT).withExposedPort(MGMT_PORT);- }+ // A re-provision of the same broker has just removed its old container, so any+ // reservation held for it is stale; hand the ports back before allocating anew.+ releaseHostPorts(broker.getBrokerId());+ HostPorts ports = allocateHostPorts();- if (ContainerStorageHelper.isNamedVolumeMode(config)) {- ContainerStorageHelper.applyStorage(specBuilder, lifecycleManager, config,- "amazonmq", broker.getVolumeId(), broker.getBrokerId(),- "/var/lib/rabbitmq");- } else {- String hostDataPath = ContainerStorageHelper.hostResourcePath(config, "amazonmq", broker.getBrokerId())- .toAbsolutePath().toString();- if (!containerDetector.isRunningInContainer()) {- ContainerStorageHelper.ensureHostDir(hostDataPath);- }- specBuilder.withBind(hostDataPath, "/var/lib/rabbitmq");- }-- ContainerSpec spec = specBuilder.build();+ // Publish both ports on the host in every topology (see class javadoc). The+ // endpoints resolved below stay topology-aware: localhost:<hostPort> natively,+ // the container's network IP when Floci runs in Docker.+ specBuilder.withPortBinding(AMQP_PORT, ports.amqp())+ .withPortBinding(MGMT_PORT, ports.console());ContainerInfo info;try {+ if (ContainerStorageHelper.isNamedVolumeMode(config)) {+ ContainerStorageHelper.applyStorage(specBuilder, lifecycleManager, config,+ "amazonmq", broker.getVolumeId(), broker.getBrokerId(),+ "/var/lib/rabbitmq");+ } else {+ String hostDataPath = ContainerStorageHelper.hostResourcePath(config, "amazonmq", broker.getBrokerId())+ .toAbsolutePath().toString();+ if (!containerDetector.isRunningInContainer()) {+ ContainerStorageHelper.ensureHostDir(hostDataPath);+ }+ specBuilder.withBind(hostDataPath, "/var/lib/rabbitmq");+ }++ ContainerSpec spec = specBuilder.build();info = lifecycleManager.createAndStart(spec);} catch (RuntimeException e) {// Roll back a partially-created container so a failed CreateBroker- // does not leave an orphaned container behind.+ // does not leave an orphaned container behind, and hand the reserved+ // ports back so the failure does not leak them.lifecycleManager.removeIfExists(containerName);+ portAllocator.release(ports.amqp());+ portAllocator.release(ports.console());throw e;}broker.setContainerId(info.containerId());containerIds.put(broker.getBrokerId(), info.containerId());+ hostPorts.put(broker.getBrokerId(), ports);EndpointInfo amqp = info.getEndpoint(AMQP_PORT);EndpointInfo mgmt = info.getEndpoint(MGMT_PORT);@@ -146,8 +169,9 @@ public class RabbitMqManager {List.of("amqp://" + amqp.host() + ":" + amqp.port()),amqp.host());broker.setBrokerInstances(new java.util.ArrayList<>(List.of(instance)));- LOG.infov("RabbitMQ container {0} started for broker {1}: amqp={2}",- info.containerId(), broker.getBrokerName(), instance.getEndpoints().get(0));+ LOG.infov("RabbitMQ container {0} started for broker {1}: amqp={2} (host ports amqp={3}, console={4})",+ info.containerId(), broker.getBrokerName(), instance.getEndpoints().get(0),+ String.valueOf(ports.amqp()), String.valueOf(ports.console()));String shortId = info.containerId().length() >= 8? info.containerId().substring(0, 8)@@ -199,6 +223,7 @@ public class RabbitMqManager {public void stopContainer(Broker broker) {containerIds.remove(broker.getBrokerId());+ releaseHostPorts(broker.getBrokerId());Closeable logHandle = logStreams.remove(broker.getBrokerId());String containerId = broker.getContainerId();if (containerId != null) {@@ -224,6 +249,7 @@ public class RabbitMqManager {}for (String brokerId : new ArrayList<>(containerIds.keySet())) {String containerId = containerIds.remove(brokerId);+ releaseHostPorts(brokerId);if (containerId == null) {continue;}@@ -232,6 +258,27 @@ public class RabbitMqManager {}}+ private HostPorts allocateHostPorts() {+ EmulatorConfig.AmazonMqServiceConfig mq = config.services().amazonmq();+ int amqp = portAllocator.allocate(mq.amqpHostPortBase(), mq.amqpHostPortMax());+ int console;+ try {+ console = portAllocator.allocate(mq.consoleHostPortBase(), mq.consoleHostPortMax());+ } catch (RuntimeException e) {+ portAllocator.release(amqp);+ throw e;+ }+ return new HostPorts(amqp, console);+ }++ private void releaseHostPorts(String brokerId) {+ HostPorts ports = hostPorts.remove(brokerId);+ if (ports != null) {+ portAllocator.release(ports.amqp());+ portAllocator.release(ports.console());+ }+ }+public void removeBrokerStorage(Broker broker) {ContainerStorageHelper.removeStorage(config, lifecycleManager,"amazonmq", broker.getVolumeId(), broker.getBrokerId());diff --git a/src/main/resources/application.yml b/src/main/resources/application.ymlindex fe9d9f5c55..6fb0f8241e 100644--- a/src/main/resources/application.yml+++ b/src/main/resources/application.yml@@ -322,6 +322,10 @@ floci:enabled: truemock: falsedefault-image: "rabbitmq:3-management"+ amqp-host-port-base: 5672+ amqp-host-port-max: 5699+ console-host-port-base: 15672+ console-host-port-max: 15699kinesis-analytics:enabled: truemock: falsediff --git a/src/test/java/io/github/hectorvent/floci/services/amazonmq/container/RabbitMqManagerTest.java b/src/test/java/io/github/hectorvent/floci/services/amazonmq/container/RabbitMqManagerTest.javaindex 5a7aef1eec..37483a5d0b 100644--- a/src/test/java/io/github/hectorvent/floci/services/amazonmq/container/RabbitMqManagerTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/amazonmq/container/RabbitMqManagerTest.java@@ -7,6 +7,7 @@ import io.github.hectorvent.floci.core.common.docker.ContainerDetector;import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager;import io.github.hectorvent.floci.core.common.docker.ContainerLogStreamer;import io.github.hectorvent.floci.core.common.docker.ContainerSpec;+import io.github.hectorvent.floci.core.common.docker.PortAllocator;import io.github.hectorvent.floci.services.amazonmq.model.Broker;import org.junit.jupiter.api.BeforeEach;import org.junit.jupiter.api.Test;@@ -15,8 +16,11 @@ import org.mockito.Mockito;import java.util.Map;import java.util.Optional;+import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertThrows;import static org.mockito.ArgumentMatchers.any;import static org.mockito.ArgumentMatchers.anyString;+import static org.mockito.Mockito.never;import static org.mockito.Mockito.verify;import static org.mockito.Mockito.verifyNoMoreInteractions;import static org.mockito.Mockito.when;@@ -24,27 +28,24 @@ import static org.mockito.Mockito.when;class RabbitMqManagerTest {private ContainerLifecycleManager lifecycleManager;+ private PortAllocator portAllocator;private RabbitMqManager manager;@BeforeEachvoid setUp() {lifecycleManager = Mockito.mock(ContainerLifecycleManager.class);+ portAllocator = Mockito.mock(PortAllocator.class);manager = new RabbitMqManager(Mockito.mock(ContainerBuilder.class),lifecycleManager,Mockito.mock(ContainerLogStreamer.class),Mockito.mock(ContainerDetector.class),+ portAllocator,Mockito.mock(EmulatorConfig.class),Mockito.mock(RegionResolver.class));}- private Broker broker(String brokerId) {- return new Broker(brokerId, "arn", "name", "RABBITMQ", "3.13",- "SINGLE_INSTANCE", "mq.t3.micro");- }-- @Test- void startContainerLabelsContainerWithResourceIdentity() {+ private static EmulatorConfig configWithDefaultPortRanges() {EmulatorConfig config = Mockito.mock(EmulatorConfig.class);EmulatorConfig.ServicesConfig services = Mockito.mock(EmulatorConfig.ServicesConfig.class);EmulatorConfig.AmazonMqServiceConfig amazonmq = Mockito.mock(EmulatorConfig.AmazonMqServiceConfig.class);@@ -52,6 +53,10 @@ class RabbitMqManagerTest {when(services.amazonmq()).thenReturn(amazonmq);when(services.dockerNetwork()).thenReturn(Optional.empty());when(amazonmq.defaultImage()).thenReturn("rabbitmq:3.13-management");+ when(amazonmq.amqpHostPortBase()).thenReturn(5672);+ when(amazonmq.amqpHostPortMax()).thenReturn(5699);+ when(amazonmq.consoleHostPortBase()).thenReturn(15672);+ when(amazonmq.consoleHostPortMax()).thenReturn(15699);EmulatorConfig.DockerConfig docker = Mockito.mock(EmulatorConfig.DockerConfig.class);when(config.docker()).thenReturn(docker);when(docker.logMaxSize()).thenReturn("10m");@@ -59,6 +64,31 @@ class RabbitMqManagerTest {EmulatorConfig.StorageConfig storage = Mockito.mock(EmulatorConfig.StorageConfig.class);when(config.storage()).thenReturn(storage);when(storage.hostPersistentPath()).thenReturn("floci-data");+ return config;+ }++ private static ContainerBuilder.Builder selfReturningBuilder(ContainerBuilder containerBuilder) {+ ContainerBuilder.Builder builder = Mockito.mock(ContainerBuilder.Builder.class, Mockito.RETURNS_SELF);+ when(containerBuilder.newContainer(anyString())).thenReturn(builder);+ when(builder.build()).thenReturn(Mockito.mock(ContainerSpec.class));+ return builder;+ }++ private static RegionResolver regionResolver() {+ RegionResolver regionResolver = Mockito.mock(RegionResolver.class);+ when(regionResolver.getAccountId()).thenReturn("000000000000");+ when(regionResolver.getDefaultRegion()).thenReturn("us-east-1");+ return regionResolver;+ }++ private Broker broker(String brokerId) {+ return new Broker(brokerId, "arn", "name", "RABBITMQ", "3.13",+ "SINGLE_INSTANCE", "mq.t3.micro");+ }++ @Test+ void startContainerLabelsContainerWithResourceIdentity() {+ EmulatorConfig config = configWithDefaultPortRanges();ContainerLifecycleManager lifecycleManager = Mockito.mock(ContainerLifecycleManager.class);when(lifecycleManager.createAndStart(any())).thenReturn(@@ -67,17 +97,15 @@ class RabbitMqManagerTest {15672, new ContainerLifecycleManager.EndpointInfo("localhost", 15672))));ContainerBuilder containerBuilder = Mockito.mock(ContainerBuilder.class);- ContainerBuilder.Builder builder = Mockito.mock(ContainerBuilder.Builder.class, Mockito.RETURNS_SELF);- when(containerBuilder.newContainer(anyString())).thenReturn(builder);- when(builder.build()).thenReturn(Mockito.mock(ContainerSpec.class));+ ContainerBuilder.Builder builder = selfReturningBuilder(containerBuilder);- RegionResolver regionResolver = Mockito.mock(RegionResolver.class);- when(regionResolver.getAccountId()).thenReturn("000000000000");- when(regionResolver.getDefaultRegion()).thenReturn("us-east-1");+ PortAllocator portAllocator = Mockito.mock(PortAllocator.class);+ when(portAllocator.allocate(5672, 5699)).thenReturn(5672);+ when(portAllocator.allocate(15672, 15699)).thenReturn(15672);RabbitMqManager manager = new RabbitMqManager(containerBuilder, lifecycleManager,Mockito.mock(ContainerLogStreamer.class), Mockito.mock(ContainerDetector.class),- config, regionResolver);+ portAllocator, config, regionResolver());manager.startContainer(broker("b-1"));@@ -89,6 +117,112 @@ class RabbitMqManagerTest {"io.floci.region", "us-east-1"));}+ /**+ * Regression for #3240: with Floci itself running in Docker, the AMQP and console+ * ports used to be expose-only, so a client on the host (e.g. a local app dialing+ * amqp://localhost:5672) could never reach the broker. No Floci-internal proxy+ * fronts RabbitMQ, so the host-port binding must be published in that topology+ * too, from the configured ranges, while DescribeBroker keeps reporting the+ * container-network address sibling containers use.+ */+ @Test+ void startContainerPublishesHostPortsWhenRunningInContainer() {+ EmulatorConfig config = configWithDefaultPortRanges();++ ContainerLifecycleManager lifecycleManager = Mockito.mock(ContainerLifecycleManager.class);+ when(lifecycleManager.createAndStart(any())).thenReturn(+ new ContainerLifecycleManager.ContainerInfo("container-id", Map.of(+ 5672, new ContainerLifecycleManager.EndpointInfo("172.17.0.5", 5672),+ 15672, new ContainerLifecycleManager.EndpointInfo("172.17.0.5", 15672))));++ ContainerBuilder containerBuilder = Mockito.mock(ContainerBuilder.class);+ ContainerBuilder.Builder builder = selfReturningBuilder(containerBuilder);++ PortAllocator portAllocator = Mockito.mock(PortAllocator.class);+ when(portAllocator.allocate(5672, 5699)).thenReturn(5673);+ when(portAllocator.allocate(15672, 15699)).thenReturn(15673);++ ContainerDetector containerDetector = Mockito.mock(ContainerDetector.class);+ when(containerDetector.isRunningInContainer()).thenReturn(true);++ RabbitMqManager manager = new RabbitMqManager(containerBuilder, lifecycleManager,+ Mockito.mock(ContainerLogStreamer.class), containerDetector,+ portAllocator, config, regionResolver());++ Broker broker = broker("b-1");+ manager.startContainer(broker);++ verify(builder).withPortBinding(5672, 5673);+ verify(builder).withPortBinding(15672, 15673);+ verify(builder, never()).withExposedPort(Mockito.anyInt());+ verify(builder, never()).withDynamicPort(Mockito.anyInt());+ assertEquals(java.util.List.of("amqp://172.17.0.5:5672"),+ broker.getBrokerInstances().get(0).getEndpoints());+ assertEquals("http://172.17.0.5:15672", broker.getBrokerInstances().get(0).getConsoleURL());+ }++ /**+ * The reservation must die with the container: without the release, repeated+ * create/delete cycles exhaust the configured ranges and later brokers can+ * never start.+ */+ @Test+ void stopContainerReleasesReservedHostPorts() {+ EmulatorConfig config = configWithDefaultPortRanges();++ ContainerLifecycleManager lifecycleManager = Mockito.mock(ContainerLifecycleManager.class);+ when(lifecycleManager.createAndStart(any())).thenReturn(+ new ContainerLifecycleManager.ContainerInfo("container-id", Map.of(+ 5672, new ContainerLifecycleManager.EndpointInfo("localhost", 5674),+ 15672, new ContainerLifecycleManager.EndpointInfo("localhost", 15674))));++ ContainerBuilder containerBuilder = Mockito.mock(ContainerBuilder.class);+ selfReturningBuilder(containerBuilder);++ PortAllocator portAllocator = Mockito.mock(PortAllocator.class);+ when(portAllocator.allocate(5672, 5699)).thenReturn(5674);+ when(portAllocator.allocate(15672, 15699)).thenReturn(15674);++ RabbitMqManager manager = new RabbitMqManager(containerBuilder, lifecycleManager,+ Mockito.mock(ContainerLogStreamer.class), Mockito.mock(ContainerDetector.class),+ portAllocator, config, regionResolver());++ Broker broker = broker("b-1");+ manager.startContainer(broker);+ verify(portAllocator, never()).release(Mockito.anyInt());++ manager.stopContainer(broker);++ verify(portAllocator).release(5674);+ verify(portAllocator).release(15674);+ }++ @Test+ void startContainerReleasesReservedHostPortsWhenContainerFailsToStart() {+ EmulatorConfig config = configWithDefaultPortRanges();++ ContainerLifecycleManager lifecycleManager = Mockito.mock(ContainerLifecycleManager.class);+ when(lifecycleManager.createAndStart(any())).thenThrow(new RuntimeException("docker down"));++ ContainerBuilder containerBuilder = Mockito.mock(ContainerBuilder.class);+ selfReturningBuilder(containerBuilder);++ PortAllocator portAllocator = Mockito.mock(PortAllocator.class);+ when(portAllocator.allocate(5672, 5699)).thenReturn(5672);+ when(portAllocator.allocate(15672, 15699)).thenReturn(15672);++ RabbitMqManager manager = new RabbitMqManager(containerBuilder, lifecycleManager,+ Mockito.mock(ContainerLogStreamer.class), Mockito.mock(ContainerDetector.class),+ portAllocator, config, regionResolver());++ assertThrows(RuntimeException.class, () -> manager.startContainer(broker("b-1")));++ // Once for the stale-container sweep before create, once for the rollback.+ verify(lifecycleManager, Mockito.times(2)).removeIfExists("floci-amazonmq-b-1");+ verify(portAllocator).release(5672);+ verify(portAllocator).release(15672);+ }+@Testvoid stopContainerUsesContainerIdWhenPresent() {Broker broker = broker("b-1");diff --git a/src/test/resources/application.yml b/src/test/resources/application.ymlindex ed7d8b546c..90263e4774 100644--- a/src/test/resources/application.yml+++ b/src/test/resources/application.yml@@ -150,6 +150,10 @@ floci:amazonmq:enabled: truemock: true+ amqp-host-port-base: 5672+ amqp-host-port-max: 5699+ console-host-port-base: 15672+ console-host-port-max: 15699kinesis-analytics:enabled: truemock: true