mirror of
https://github.com/floci-io/floci.git
synced 2026-11-23 06:00:46 -05:00
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.
This commit is contained in:
1 parent
7f8383db38
commit
a318dc7b90
7 files changed
+368
-110
No files matched your search
@@ -35,12 +35,17 @@ Floci emulates Amazon MSK by orchestrating **Redpanda** containers. This provide
|
||||
| `FLOCI_SERVICES_MSK_ENABLED` | `true` | Enable or disable the service |
|
||||
| `FLOCI_SERVICES_MSK_MOCK` | `false` | `true` = metadata-only CRUD, no Docker containers |
|
||||
| `FLOCI_SERVICES_MSK_DEFAULT_IMAGE` | `redpandadata/redpanda:latest` | Docker image for Redpanda (Kafka) containers |
|
||||
| `FLOCI_SERVICES_MSK_KAFKA_HOST_PORT_BASE` | `9300` | First host port a broker's Kafka listener can be published on |
|
||||
| `FLOCI_SERVICES_MSK_KAFKA_HOST_PORT_MAX` | `9399` | Last host port a broker's Kafka listener can be published on |
|
||||
| `FLOCI_SERVICES_MSK_BOOTSTRAP_HOSTNAME` | _(unset)_ | Floci in a container only: hostname the host listener advertises, and when set, `GetBootstrapBrokers` returns `<container-name>:9092,<hostname>:<host port>` instead of the Docker-network address |
|
||||
|
||||
## How it works
|
||||
|
||||
When `mock` is set to `false` (default), Floci uses the Docker API to start a Redpanda container for each created cluster. For Docker socket setup, private registry authentication, and other Docker settings see [Docker Configuration](../configuration/docker.md).
|
||||
|
||||
- **Port Mapping**: The Kafka API (9092) is mapped to a dynamic host port.
|
||||
- **Networking**: Kafka clients connect to whatever address the broker advertises, so the advertised address has to be reachable from the client.
|
||||
- Floci on the host: the Kafka API (9092) is published on a host port from the `kafka-host-port` range and advertised as `localhost:<port>`.
|
||||
- Floci in a container: the broker has two listeners. `internal` (9092) advertises `<container-name>:9092` for containers on the same Docker network. `host` (9093) is published on a host port from the `kafka-host-port` range and advertised as `<bootstrap-hostname or localhost>:<port>` for clients on the Docker host. `GetBootstrapBrokers` returns the Docker-network address. When `FLOCI_SERVICES_MSK_BOOTSTRAP_HOSTNAME` is set, it returns both listeners, `<container-name>:9092,<hostname>:<port>`: a client connects through whichever entry it can reach, and the broker then advertises that listener's address. The two entries are two listeners on the same broker, not two brokers.
|
||||
- **Persistence**: Each cluster gets a named Docker volume (`floci-msk-{volumeId}`). In memory mode the volume is removed on cluster delete; in persistent modes it is retained unless `FLOCI_STORAGE_PRUNE_VOLUMES_ON_DELETE=true`.
|
||||
- **Readiness**: The cluster state transitions to `ACTIVE` once the Redpanda `/ready` endpoint is reachable.
|
||||
|
||||
|
||||
@@ -1477,6 +1477,20 @@ public interface EmulatorConfig {
|
||||
|
||||
@WithDefault("9399")
|
||||
int kafkaHostPortMax();
|
||||
|
||||
/**
|
||||
* Only applies when Floci runs in a container. Each broker then has a second Kafka
|
||||
* listener, published to a host port from the kafka-host-port range so clients on the
|
||||
* Docker host can reach it, and advertised as {@code <this hostname>:<port>}
|
||||
* ({@code localhost} when unset).
|
||||
*
|
||||
* <p>When set, GetBootstrapBrokers returns both listeners,
|
||||
* {@code <container-name>:9092,<this hostname>:<port>}, so clients on the Docker host
|
||||
* and in sibling containers can each discover the broker. When unset or blank, it
|
||||
* returns the broker's Docker-network address, which sibling containers use.
|
||||
* Env: FLOCI_SERVICES_MSK_BOOTSTRAP_HOSTNAME
|
||||
*/
|
||||
Optional<String> bootstrapHostname();
|
||||
}
|
||||
|
||||
interface AmazonMqServiceConfig {
|
||||
|
||||
+12
@@ -1043,6 +1043,18 @@ public class ContainerLifecycleManager {
|
||||
return resolveEndpoint(inspect, containerPort);
|
||||
}
|
||||
|
||||
/**
|
||||
* Like {@link #resolveEndpoint(String, int)}, but prefers the container's address on
|
||||
* {@code preferredNetwork}, as {@link #createAndStart} does with the spec's network. A
|
||||
* container that publishes ports is created on the default bridge and connected to its
|
||||
* service network after start, so without a preference the bridge address, which Floci
|
||||
* usually cannot reach, can be returned instead.
|
||||
*/
|
||||
public EndpointInfo resolveEndpoint(String containerId, int containerPort, String preferredNetwork) {
|
||||
InspectContainerResponse inspect = dockerClient.inspectContainerCmd(containerId).exec();
|
||||
return resolveEndpoint(inspect, containerPort, preferredNetwork);
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves the container's IP on its Docker network, independent of whether Floci runs
|
||||
* natively or in a container. Used for addresses that sibling containers (not Floci itself)
|
||||
|
||||
@@ -1,9 +1,5 @@
|
||||
package io.github.hectorvent.floci.services.msk;
|
||||
|
||||
import com.github.dockerjava.api.DockerClient;
|
||||
import com.github.dockerjava.api.command.InspectContainerResponse;
|
||||
import com.github.dockerjava.api.model.ExposedPort;
|
||||
import com.github.dockerjava.api.model.Ports;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
@@ -29,6 +25,7 @@ import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
@ApplicationScoped
|
||||
@@ -36,11 +33,17 @@ public class RedpandaManager {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(RedpandaManager.class);
|
||||
private static final int KAFKA_PORT = 9092;
|
||||
// Second Kafka listener, only used when Floci runs in a container: published to a host port
|
||||
// and advertised with a host-reachable address, for clients outside the Docker network.
|
||||
static final int KAFKA_HOST_LISTENER_PORT = 9093;
|
||||
static final int ADMIN_PORT = 9644;
|
||||
|
||||
// Redpanda's Admin API exposes readiness at /v1/status/ready. /ready always returns 404
|
||||
private static final String ADMIN_READY_PATH = "/v1/status/ready";
|
||||
|
||||
private record StartedBroker(int hostPort, ContainerInfo info) {
|
||||
}
|
||||
|
||||
private final ContainerBuilder containerBuilder;
|
||||
private final ContainerLifecycleManager lifecycleManager;
|
||||
private final ContainerLogStreamer logStreamer;
|
||||
@@ -49,6 +52,9 @@ public class RedpandaManager {
|
||||
private final RegionResolver regionResolver;
|
||||
private final PortAllocator portAllocator;
|
||||
private final Map<String, Closeable> logStreams = new ConcurrentHashMap<>();
|
||||
// Container mode only, keyed like logStreams: the host port the host listener is published
|
||||
// on (not recoverable from the bootstrap string, which may be the Docker-network address).
|
||||
private final Map<String, Integer> hostListenerPorts = new ConcurrentHashMap<>();
|
||||
private volatile boolean dockerUnavailableLogged;
|
||||
|
||||
@Inject
|
||||
@@ -128,75 +134,50 @@ public class RedpandaManager {
|
||||
// reachable address up front. The host port has to be known before the
|
||||
// container starts (the flag is a startup arg), so in native mode we
|
||||
// pre-allocate it ourselves instead of letting Docker assign one dynamically.
|
||||
String kafkaAdvertiseAddr;
|
||||
int kafkaHostPort = 0;
|
||||
if (!containerDetector.isRunningInContainer()) {
|
||||
kafkaHostPort = portAllocator.allocate(
|
||||
config.services().msk().kafkaHostPortBase(),
|
||||
config.services().msk().kafkaHostPortMax());
|
||||
kafkaAdvertiseAddr = "localhost:" + kafkaHostPort;
|
||||
} else {
|
||||
// Sibling containers on the docker network resolve the broker via its
|
||||
// container name through Docker's embedded DNS.
|
||||
kafkaAdvertiseAddr = containerName + ":" + KAFKA_PORT;
|
||||
}
|
||||
|
||||
// Build command
|
||||
List<String> cmd = new ArrayList<>(List.of(
|
||||
"redpanda", "start", "--overprovisioned", "--smp", "1",
|
||||
"--memory", "512M", "--reserve-memory", "0M",
|
||||
"--advertise-kafka-addr", kafkaAdvertiseAddr));
|
||||
|
||||
// Build container spec. Publish Kafka/admin ports to the host only in
|
||||
// native mode; in Docker mode producers/consumers reach the broker via
|
||||
// the docker network IP resolved from container inspect.
|
||||
ContainerBuilder.Builder specBuilder = containerBuilder.newContainer(image)
|
||||
.withName(containerName)
|
||||
.withDockerNetwork(config.services().dockerNetwork())
|
||||
.withLogRotation()
|
||||
.withLabels(ContainerStorageHelper.resourceIdentityLabels(
|
||||
"msk", cluster.getClusterName(),
|
||||
AwsArnUtils.accountOrDefault(cluster.getClusterArn(), regionResolver.getAccountId()),
|
||||
AwsArnUtils.regionOrDefault(cluster.getClusterArn(), regionResolver.getDefaultRegion())));
|
||||
|
||||
if (!containerDetector.isRunningInContainer()) {
|
||||
specBuilder.withPortBinding(KAFKA_PORT, kafkaHostPort).withDynamicPort(ADMIN_PORT);
|
||||
} else {
|
||||
specBuilder.withExposedPort(KAFKA_PORT).withExposedPort(ADMIN_PORT);
|
||||
}
|
||||
|
||||
// Handle persistence mounting
|
||||
if (ContainerStorageHelper.isNamedVolumeMode(config)) {
|
||||
ContainerStorageHelper.applyNamedVolume(specBuilder, lifecycleManager,
|
||||
resolveVolumeName(cluster), "/var/lib/redpanda/data");
|
||||
} else {
|
||||
// Legacy host-path mode: host-persistent-path is an absolute path
|
||||
String hostDataPath = legacyCompatibleHostPath(cluster).toAbsolutePath().toString();
|
||||
if (!containerDetector.isRunningInContainer()) {
|
||||
ContainerStorageHelper.ensureHostDir(hostDataPath);
|
||||
}
|
||||
specBuilder.withBind(hostDataPath, "/var/lib/redpanda/data");
|
||||
}
|
||||
|
||||
specBuilder.withCmd(cmd);
|
||||
ContainerSpec spec = specBuilder.build();
|
||||
|
||||
// Create and start container
|
||||
ContainerInfo info;
|
||||
try {
|
||||
info = lifecycleManager.createAndStart(spec);
|
||||
} catch (RuntimeException e) {
|
||||
if (!containerDetector.isRunningInContainer()) {
|
||||
portAllocator.release(kafkaHostPort);
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
//
|
||||
// When Floci itself runs in a container, one advertised address cannot serve both
|
||||
// sibling containers and the host, so Redpanda gets two listeners. A Kafka client is
|
||||
// always handed the address of the listener it connected through:
|
||||
// internal (9092): <containerName>:9092, resolved by sibling containers through
|
||||
// Docker's embedded DNS
|
||||
// host (9093): published to a pre-allocated host port and advertised as
|
||||
// <bootstrap-hostname or localhost>:<port>, for clients on the Docker host
|
||||
boolean inContainer = containerDetector.isRunningInContainer();
|
||||
// allocate() cannot see a non-Docker process holding a host port when Floci runs in a
|
||||
// container, so Docker can still refuse the port it picked. allocateAndStart then moves on
|
||||
// to the next port in the range, and releases the port when anything else fails before
|
||||
// the container starts, volume setup included. Once it returns, the running container
|
||||
// holds the port until stopContainer releases it.
|
||||
StartedBroker started = portAllocator.allocateAndStart(
|
||||
config.services().msk().kafkaHostPortBase(),
|
||||
config.services().msk().kafkaHostPortMax(),
|
||||
port -> new StartedBroker(port, lifecycleManager.createAndStart(
|
||||
brokerSpec(cluster, image, containerName, inContainer, port))));
|
||||
int kafkaHostPort = started.hostPort();
|
||||
ContainerInfo info = started.info();
|
||||
String hostListenerAddr = hostListenerHostname() + ":" + kafkaHostPort;
|
||||
cluster.setContainerId(info.containerId());
|
||||
|
||||
// Resolve endpoints
|
||||
EndpointInfo kafkaEndpoint = info.getEndpoint(KAFKA_PORT);
|
||||
|
||||
cluster.setBootstrapBrokers(kafkaEndpoint.host() + ":" + kafkaEndpoint.port());
|
||||
if (inContainer) {
|
||||
hostListenerPorts.put(clusterIdentityKey(cluster), kafkaHostPort);
|
||||
// GetBootstrapBrokers reports the Docker-network address unless the host listener
|
||||
// was asked for explicitly, which keeps sibling containers working by default. When
|
||||
// it was, both listeners are listed: a client connects through whichever entry it can
|
||||
// reach, and the broker then advertises that listener's address. The container name
|
||||
// (not its IP) fails fast on the host, where it does not resolve, while an unroutable
|
||||
// IP would wait for a connect timeout. It goes first for callers that read only the
|
||||
// first entry.
|
||||
cluster.setBootstrapBrokers(explicitBootstrapHostname().isPresent()
|
||||
? containerName + ":" + KAFKA_PORT + "," + hostListenerAddr
|
||||
: kafkaEndpoint.host() + ":" + kafkaEndpoint.port());
|
||||
LOG.infov("Redpanda host listener for MSK cluster {0} published at {1}",
|
||||
cluster.getClusterName(), hostListenerAddr);
|
||||
} else {
|
||||
cluster.setBootstrapBrokers(kafkaEndpoint.host() + ":" + kafkaEndpoint.port());
|
||||
}
|
||||
LOG.infov("Redpanda container {0} started. Bootstrap: {1}", info.containerId(), cluster.getBootstrapBrokers());
|
||||
|
||||
// Attach log streaming (new feature)
|
||||
@@ -215,30 +196,73 @@ public class RedpandaManager {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds the broker's container spec for one candidate host port. The port is part of the
|
||||
* Redpanda startup args, so the spec is rebuilt for each port {@link PortAllocator#allocateAndStart}
|
||||
* tries.
|
||||
*/
|
||||
private ContainerSpec brokerSpec(MskCluster cluster, String image, String containerName,
|
||||
boolean inContainer, int kafkaHostPort) {
|
||||
String hostListenerAddr = hostListenerHostname() + ":" + kafkaHostPort;
|
||||
|
||||
// Build command
|
||||
List<String> cmd = new ArrayList<>(List.of(
|
||||
"redpanda", "start", "--overprovisioned", "--smp", "1",
|
||||
"--memory", "512M", "--reserve-memory", "0M"));
|
||||
if (inContainer) {
|
||||
cmd.addAll(List.of(
|
||||
"--kafka-addr",
|
||||
"internal://0.0.0.0:" + KAFKA_PORT + ",host://0.0.0.0:" + KAFKA_HOST_LISTENER_PORT,
|
||||
"--advertise-kafka-addr",
|
||||
"internal://" + containerName + ":" + KAFKA_PORT + ",host://" + hostListenerAddr));
|
||||
} else {
|
||||
cmd.addAll(List.of("--advertise-kafka-addr", "localhost:" + kafkaHostPort));
|
||||
}
|
||||
|
||||
// Build container spec. In native mode the Kafka port itself is published. In
|
||||
// container mode the internal listener stays on the Docker network and only the
|
||||
// host listener is published.
|
||||
ContainerBuilder.Builder specBuilder = containerBuilder.newContainer(image)
|
||||
.withName(containerName)
|
||||
.withDockerNetwork(config.services().dockerNetwork())
|
||||
.withLogRotation()
|
||||
.withLabels(ContainerStorageHelper.resourceIdentityLabels(
|
||||
"msk", cluster.getClusterName(),
|
||||
AwsArnUtils.accountOrDefault(cluster.getClusterArn(), regionResolver.getAccountId()),
|
||||
AwsArnUtils.regionOrDefault(cluster.getClusterArn(), regionResolver.getDefaultRegion())));
|
||||
|
||||
if (!inContainer) {
|
||||
specBuilder.withPortBinding(KAFKA_PORT, kafkaHostPort).withDynamicPort(ADMIN_PORT);
|
||||
} else {
|
||||
specBuilder.withExposedPort(KAFKA_PORT)
|
||||
.withPortBinding(KAFKA_HOST_LISTENER_PORT, kafkaHostPort)
|
||||
.withExposedPort(ADMIN_PORT);
|
||||
}
|
||||
|
||||
// Handle persistence mounting
|
||||
if (ContainerStorageHelper.isNamedVolumeMode(config)) {
|
||||
ContainerStorageHelper.applyNamedVolume(specBuilder, lifecycleManager,
|
||||
resolveVolumeName(cluster), "/var/lib/redpanda/data");
|
||||
} else {
|
||||
// Legacy host-path mode: host-persistent-path is an absolute path
|
||||
String hostDataPath = legacyCompatibleHostPath(cluster).toAbsolutePath().toString();
|
||||
if (!containerDetector.isRunningInContainer()) {
|
||||
ContainerStorageHelper.ensureHostDir(hostDataPath);
|
||||
}
|
||||
specBuilder.withBind(hostDataPath, "/var/lib/redpanda/data");
|
||||
}
|
||||
|
||||
specBuilder.withCmd(cmd);
|
||||
return specBuilder.build();
|
||||
}
|
||||
|
||||
public boolean isReady(MskCluster cluster) {
|
||||
String bootstrap = cluster.getBootstrapBrokers();
|
||||
if (bootstrap == null) {
|
||||
if (cluster.getBootstrapBrokers() == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Derive admin URL from the container
|
||||
String adminUrl;
|
||||
if (!containerDetector.isRunningInContainer()) {
|
||||
DockerClient dockerClient = lifecycleManager.getDockerClient();
|
||||
InspectContainerResponse inspect = dockerClient.inspectContainerCmd(cluster.getContainerId()).exec();
|
||||
Map<ExposedPort, Ports.Binding[]> bindings = inspect.getNetworkSettings().getPorts().getBindings();
|
||||
Ports.Binding[] binding = bindings.get(ExposedPort.tcp(ADMIN_PORT));
|
||||
if (binding != null && binding.length > 0) {
|
||||
adminUrl = "http://localhost:" + binding[0].getHostPortSpec() + ADMIN_READY_PATH;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
String containerIp = bootstrap.split(":")[0];
|
||||
adminUrl = "http://" + containerIp + ":" + ADMIN_PORT + ADMIN_READY_PATH;
|
||||
}
|
||||
|
||||
try {
|
||||
String adminUrl = adminReadyUrl(cluster);
|
||||
HttpURLConnection conn = (HttpURLConnection) URI.create(adminUrl).toURL().openConnection();
|
||||
conn.setRequestMethod("GET");
|
||||
conn.setConnectTimeout(1000);
|
||||
@@ -263,8 +287,29 @@ public class RedpandaManager {
|
||||
releaseKafkaHostPort(cluster);
|
||||
}
|
||||
|
||||
/**
|
||||
* The broker's admin readiness URL, resolved from the persisted container id the same way
|
||||
* container start resolves endpoints: the bound host port in native mode, the container's
|
||||
* reachable address in container mode. Nothing is kept in memory, so it still works for a
|
||||
* cluster left in CREATING by a Floci process that was killed and restarted, and an IP is
|
||||
* used rather than the container name, which Docker's default bridge network does not resolve.
|
||||
*
|
||||
* <p>The network startContainer put the broker on is preferred, as it was when createAndStart
|
||||
* resolved the Kafka endpoint: in container mode the broker publishes the host listener, so
|
||||
* it is on the default bridge as well, and the bridge address is not one Floci can reach.
|
||||
*/
|
||||
String adminReadyUrl(MskCluster cluster) {
|
||||
String network = containerBuilder.resolveDockerNetwork(config.services().dockerNetwork()).orElse(null);
|
||||
EndpointInfo admin = lifecycleManager.resolveEndpoint(cluster.getContainerId(), ADMIN_PORT, network);
|
||||
return "http://" + admin.host() + ":" + admin.port() + ADMIN_READY_PATH;
|
||||
}
|
||||
|
||||
private void releaseKafkaHostPort(MskCluster cluster) {
|
||||
if (containerDetector.isRunningInContainer()) {
|
||||
Integer hostPort = hostListenerPorts.remove(clusterIdentityKey(cluster));
|
||||
if (hostPort != null) {
|
||||
portAllocator.release(hostPort);
|
||||
}
|
||||
return;
|
||||
}
|
||||
String bootstrap = cluster.getBootstrapBrokers();
|
||||
@@ -286,6 +331,19 @@ public class RedpandaManager {
|
||||
ContainerStorageHelper.removeNamedVolume(config, lifecycleManager, resolveVolumeName(cluster));
|
||||
}
|
||||
|
||||
/**
|
||||
* The hostname the host listener advertises: the configured bootstrap hostname, else
|
||||
* {@code localhost}, which is where the published port lands on the Docker host.
|
||||
*/
|
||||
private String hostListenerHostname() {
|
||||
return explicitBootstrapHostname().orElse("localhost");
|
||||
}
|
||||
|
||||
/** The configured bootstrap hostname, treating a blank value as unset. */
|
||||
private Optional<String> explicitBootstrapHostname() {
|
||||
return config.services().msk().bootstrapHostname().filter(h -> !h.isBlank());
|
||||
}
|
||||
|
||||
private String clusterIdentityKey(MskCluster cluster) {
|
||||
return cluster.getClusterArn() != null ? cluster.getClusterArn() : cluster.getClusterName();
|
||||
}
|
||||
|
||||
@@ -436,6 +436,13 @@ floci:
|
||||
default-image: "redpandadata/redpanda:latest"
|
||||
kafka-host-port-base: 9300
|
||||
kafka-host-port-max: 9399
|
||||
# bootstrap-hostname: unset by default, so GetBootstrapBrokers returns the broker's
|
||||
# Docker-network address. Only applies when Floci runs in a container: each broker then
|
||||
# also has a host listener, published on a port from the kafka-host-port range and
|
||||
# advertised as <this hostname, else localhost>:<port>. When set, GetBootstrapBrokers
|
||||
# returns both listeners, <container-name>:9092,<hostname>:<port>, so clients on the
|
||||
# Docker host and in sibling containers can each discover the broker.
|
||||
# Env var: FLOCI_SERVICES_MSK_BOOTSTRAP_HOSTNAME=localhost
|
||||
amazonmq:
|
||||
enabled: true
|
||||
mock: false
|
||||
|
||||
+18
@@ -27,6 +27,7 @@ import org.mockito.InOrder;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
@@ -235,6 +236,23 @@ class ContainerLifecycleManagerNetworkTest {
|
||||
assertEquals(new EndpointInfo("localhost", 9200), info.getEndpoint(9200));
|
||||
}
|
||||
|
||||
@Test
|
||||
void resolveEndpointPrefersTheServiceNetworkOverTheDefaultBridge() {
|
||||
when(containerDetector.isRunningInContainer()).thenReturn(true);
|
||||
InspectContainerResponse inspect = inspectOf("container-id");
|
||||
NetworkSettings networks = mock(NetworkSettings.class);
|
||||
when(inspect.getHostConfig()).thenReturn(HostConfig.newHostConfig().withNetworkMode("bridge"));
|
||||
when(inspect.getNetworkSettings()).thenReturn(networks);
|
||||
// Docker lists a container's networks by name, so the default bridge usually comes first.
|
||||
Map<String, ContainerNetwork> attached = new LinkedHashMap<>();
|
||||
attached.put("bridge", new ContainerNetwork().withIpv4Address("172.17.0.4"));
|
||||
attached.put("floci-net", new ContainerNetwork().withIpv4Address("172.20.0.4"));
|
||||
when(networks.getNetworks()).thenReturn(attached);
|
||||
|
||||
assertEquals(new EndpointInfo("172.20.0.4", 9644),
|
||||
manager().resolveEndpoint("container-id", 9644, "floci-net"));
|
||||
}
|
||||
|
||||
private InspectContainerResponse inspectOf(String containerId) {
|
||||
InspectContainerCmd inspectCmd = mock(InspectContainerCmd.class, RETURNS_SELF);
|
||||
InspectContainerResponse inspect = mock(InspectContainerResponse.class);
|
||||
|
||||
@@ -1,10 +1,6 @@
|
||||
package io.github.hectorvent.floci.services.msk;
|
||||
|
||||
import com.github.dockerjava.api.DockerClient;
|
||||
import com.github.dockerjava.api.command.InspectContainerCmd;
|
||||
import com.github.dockerjava.api.command.InspectContainerResponse;
|
||||
import com.github.dockerjava.api.model.ExposedPort;
|
||||
import com.github.dockerjava.api.model.Ports;
|
||||
import com.github.dockerjava.api.exception.NotFoundException;
|
||||
import com.sun.net.httpserver.HttpServer;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
@@ -36,13 +32,16 @@ import java.util.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.lenient;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
@@ -96,6 +95,8 @@ class RedpandaManagerTest {
|
||||
lenient().when(storage.hostPersistentPath()).thenReturn(tempDir.toAbsolutePath().toString());
|
||||
|
||||
lenient().when(embeddedDnsServer.getServerIp()).thenReturn(Optional.empty());
|
||||
// The real retry loop, driven by the stubbed allocate() and verified release().
|
||||
lenient().when(portAllocator.allocateAndStart(eq(9300), eq(9399), any())).thenCallRealMethod();
|
||||
|
||||
ContainerBuilder containerBuilder = new ContainerBuilder(config, dockerHostResolver, embeddedDnsServer);
|
||||
manager = new RedpandaManager(containerBuilder, lifecycleManager, logStreamer, containerDetector,
|
||||
@@ -183,18 +184,8 @@ class RedpandaManagerTest {
|
||||
void isReadyPollsTheCorrectAdminReadinessPathInNativeMode() throws Exception {
|
||||
int adminHostPort = startFakeAdminServer();
|
||||
|
||||
when(containerDetector.isRunningInContainer()).thenReturn(false);
|
||||
|
||||
DockerClient dockerClient = mock(DockerClient.class);
|
||||
InspectContainerCmd inspectCmd = mock(InspectContainerCmd.class);
|
||||
InspectContainerResponse inspect = mock(InspectContainerResponse.class, RETURNS_DEEP_STUBS);
|
||||
|
||||
when(lifecycleManager.getDockerClient()).thenReturn(dockerClient);
|
||||
when(dockerClient.inspectContainerCmd("container-id")).thenReturn(inspectCmd);
|
||||
when(inspectCmd.exec()).thenReturn(inspect);
|
||||
when(inspect.getNetworkSettings().getPorts().getBindings()).thenReturn(Map.of(
|
||||
ExposedPort.tcp(RedpandaManager.ADMIN_PORT),
|
||||
new Ports.Binding[] { new Ports.Binding("0.0.0.0", String.valueOf(adminHostPort)) }));
|
||||
when(lifecycleManager.resolveEndpoint("container-id", RedpandaManager.ADMIN_PORT, null))
|
||||
.thenReturn(new EndpointInfo("localhost", adminHostPort));
|
||||
|
||||
MskCluster cluster = newCluster();
|
||||
cluster.setContainerId("container-id");
|
||||
@@ -205,6 +196,36 @@ class RedpandaManagerTest {
|
||||
+ "if it regresses to polling /ready (which always 404s), this assertion fails");
|
||||
}
|
||||
|
||||
@Test
|
||||
void adminReadyUrlResolvesFromThePersistedContainerIdOnTheBrokersNetworkAfterRestart() {
|
||||
when(config.services().dockerNetwork()).thenReturn(Optional.of("floci-net"));
|
||||
when(lifecycleManager.resolveEndpoint("container-460", RedpandaManager.ADMIN_PORT, "floci-net"))
|
||||
.thenReturn(new EndpointInfo("172.18.0.9", RedpandaManager.ADMIN_PORT));
|
||||
|
||||
// A cluster record as a killed Floci left it: still CREATING, with a host-form bootstrap
|
||||
// string, and nothing in this freshly constructed manager's memory about its container.
|
||||
MskCluster cluster = newCluster();
|
||||
cluster.setContainerId("container-460");
|
||||
cluster.setBootstrapBrokers("localhost:9300");
|
||||
|
||||
assertEquals("http://172.18.0.9:9644/v1/status/ready", manager.adminReadyUrl(cluster),
|
||||
"readiness must not depend on in-memory state or on the bootstrap string's format");
|
||||
}
|
||||
|
||||
@Test
|
||||
void isReadyReportsNotReadyWhenTheContainerIsGone() {
|
||||
when(lifecycleManager.resolveEndpoint("container-461", RedpandaManager.ADMIN_PORT, null))
|
||||
.thenThrow(new NotFoundException("No such container: container-461"));
|
||||
|
||||
MskCluster cluster = newCluster();
|
||||
cluster.setContainerId("container-461");
|
||||
cluster.setBootstrapBrokers("172.18.0.10:9092");
|
||||
|
||||
assertFalse(manager.isReady(cluster),
|
||||
"a failed endpoint lookup must not escape into the readiness poller, "
|
||||
+ "which would abandon its pass over the remaining clusters");
|
||||
}
|
||||
|
||||
@Test
|
||||
void nativeModeAdvertisesPreAllocatedLocalhostAddress() {
|
||||
when(containerDetector.isRunningInContainer()).thenReturn(false);
|
||||
@@ -229,8 +250,9 @@ class RedpandaManagerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void containerModeAdvertisesContainerNameAddress() {
|
||||
void containerModeAdvertisesContainerNameOnInternalListenerAndHostPortOnHostListener() {
|
||||
when(containerDetector.isRunningInContainer()).thenReturn(true);
|
||||
when(portAllocator.allocate(9300, 9399)).thenReturn(9301);
|
||||
|
||||
ContainerInfo info = new ContainerInfo("container-456",
|
||||
Map.of(KAFKA_PORT, new EndpointInfo("172.18.0.5", KAFKA_PORT)));
|
||||
@@ -238,22 +260,144 @@ class RedpandaManagerTest {
|
||||
|
||||
ArgumentCaptor<ContainerSpec> specCaptor = ArgumentCaptor.forClass(ContainerSpec.class);
|
||||
|
||||
manager.startContainer(newCluster());
|
||||
MskCluster cluster = newCluster();
|
||||
manager.startContainer(cluster);
|
||||
|
||||
verify(lifecycleManager).createAndStart(specCaptor.capture());
|
||||
ContainerSpec spec = specCaptor.getValue();
|
||||
|
||||
int listenIndex = spec.cmd().indexOf("--kafka-addr");
|
||||
assertTrue(listenIndex >= 0, "cmd should contain --kafka-addr");
|
||||
assertEquals("internal://0.0.0.0:9092,host://0.0.0.0:9093", spec.cmd().get(listenIndex + 1));
|
||||
int flagIndex = spec.cmd().indexOf("--advertise-kafka-addr");
|
||||
assertTrue(flagIndex >= 0, "cmd should contain --advertise-kafka-addr");
|
||||
assertEquals("floci-aws-msk-abc123:9092", spec.cmd().get(flagIndex + 1));
|
||||
assertEquals("internal://floci-aws-msk-abc123:9092,host://localhost:9301",
|
||||
spec.cmd().get(flagIndex + 1));
|
||||
|
||||
assertFalse(spec.portBindings().containsKey(KAFKA_PORT), "container mode should not publish ports to host");
|
||||
assertFalse(spec.portBindings().containsKey(KAFKA_PORT),
|
||||
"the internal listener stays on the Docker network");
|
||||
assertEquals(Integer.valueOf(9301), spec.portBindings().get(RedpandaManager.KAFKA_HOST_LISTENER_PORT),
|
||||
"the host listener is published so clients on the Docker host can reach the broker");
|
||||
assertTrue(spec.exposedPorts().contains(KAFKA_PORT));
|
||||
assertTrue(spec.exposedPorts().contains(RedpandaManager.ADMIN_PORT));
|
||||
assertFalse(Files.exists(tempDir.resolve("msk").resolve("test-cluster")),
|
||||
"container mode must not create host directories from inside the emulator container");
|
||||
|
||||
verifyNoInteractions(portAllocator);
|
||||
assertEquals("172.18.0.5:9092", cluster.getBootstrapBrokers(),
|
||||
"without a bootstrap hostname, GetBootstrapBrokers keeps the Docker-network address");
|
||||
}
|
||||
|
||||
@Test
|
||||
void containerModeListsBothListenersWhenBootstrapHostnameIsSet() {
|
||||
when(containerDetector.isRunningInContainer()).thenReturn(true);
|
||||
when(config.services().msk().bootstrapHostname()).thenReturn(Optional.of("kafka.local"));
|
||||
when(portAllocator.allocate(9300, 9399)).thenReturn(9302);
|
||||
|
||||
ContainerInfo info = new ContainerInfo("container-457",
|
||||
Map.of(KAFKA_PORT, new EndpointInfo("172.18.0.6", KAFKA_PORT)));
|
||||
when(lifecycleManager.createAndStart(any())).thenReturn(info);
|
||||
|
||||
ArgumentCaptor<ContainerSpec> specCaptor = ArgumentCaptor.forClass(ContainerSpec.class);
|
||||
|
||||
MskCluster cluster = newCluster();
|
||||
manager.startContainer(cluster);
|
||||
|
||||
verify(lifecycleManager).createAndStart(specCaptor.capture());
|
||||
ContainerSpec spec = specCaptor.getValue();
|
||||
int flagIndex = spec.cmd().indexOf("--advertise-kafka-addr");
|
||||
assertEquals("internal://floci-aws-msk-abc123:9092,host://kafka.local:9302",
|
||||
spec.cmd().get(flagIndex + 1));
|
||||
assertEquals("floci-aws-msk-abc123:9092,kafka.local:9302", cluster.getBootstrapBrokers(),
|
||||
"both listeners are listed, the internal one first, so host and sibling-container "
|
||||
+ "clients can each discover the broker");
|
||||
}
|
||||
|
||||
@Test
|
||||
void containerModeTreatsBlankBootstrapHostnameAsUnset() {
|
||||
when(containerDetector.isRunningInContainer()).thenReturn(true);
|
||||
when(config.services().msk().bootstrapHostname()).thenReturn(Optional.of(" "));
|
||||
when(portAllocator.allocate(9300, 9399)).thenReturn(9305);
|
||||
when(lifecycleManager.createAndStart(any())).thenReturn(new ContainerInfo("container-459",
|
||||
Map.of(KAFKA_PORT, new EndpointInfo("172.18.0.8", KAFKA_PORT))));
|
||||
|
||||
ArgumentCaptor<ContainerSpec> specCaptor = ArgumentCaptor.forClass(ContainerSpec.class);
|
||||
|
||||
MskCluster cluster = newCluster();
|
||||
manager.startContainer(cluster);
|
||||
|
||||
verify(lifecycleManager).createAndStart(specCaptor.capture());
|
||||
ContainerSpec spec = specCaptor.getValue();
|
||||
int flagIndex = spec.cmd().indexOf("--advertise-kafka-addr");
|
||||
assertEquals("internal://floci-aws-msk-abc123:9092,host://localhost:9305",
|
||||
spec.cmd().get(flagIndex + 1));
|
||||
assertEquals("172.18.0.8:9092", cluster.getBootstrapBrokers());
|
||||
}
|
||||
|
||||
@Test
|
||||
void containerModeReleasesHostListenerPortWhenStartFails() {
|
||||
when(containerDetector.isRunningInContainer()).thenReturn(true);
|
||||
when(portAllocator.allocate(9300, 9399)).thenReturn(9303);
|
||||
when(lifecycleManager.createAndStart(any())).thenThrow(new RuntimeException("boom"));
|
||||
|
||||
assertThrows(RuntimeException.class, () -> manager.startContainer(newCluster()));
|
||||
|
||||
verify(portAllocator).release(9303);
|
||||
}
|
||||
|
||||
@Test
|
||||
void releasesHostPortWhenVolumeSetupFailsBeforeStart() {
|
||||
when(config.storage().hostPersistentPath()).thenReturn("");
|
||||
when(containerDetector.isRunningInContainer()).thenReturn(true);
|
||||
when(portAllocator.allocate(9300, 9399)).thenReturn(9306);
|
||||
doThrow(new RuntimeException("Docker unreachable"))
|
||||
.when(lifecycleManager).ensureVolume("floci-aws-msk-abc123");
|
||||
|
||||
assertThrows(RuntimeException.class, () -> manager.startContainer(newCluster()));
|
||||
|
||||
verify(portAllocator).release(9306);
|
||||
verify(lifecycleManager, never()).createAndStart(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void movesToTheNextHostPortWhenDockerReportsTheChosenOneInUse() {
|
||||
// From inside a container, allocate() cannot see a host process holding a port, so the
|
||||
// collision only shows up when Docker tries to bind it.
|
||||
when(containerDetector.isRunningInContainer()).thenReturn(true);
|
||||
when(portAllocator.allocate(9300, 9399)).thenReturn(9307, 9308);
|
||||
when(lifecycleManager.createAndStart(any()))
|
||||
.thenThrow(new RuntimeException("listen tcp4 0.0.0.0:9307: bind: address already in use"))
|
||||
.thenReturn(new ContainerInfo("container-461",
|
||||
Map.of(KAFKA_PORT, new EndpointInfo("172.18.0.9", KAFKA_PORT))));
|
||||
|
||||
ArgumentCaptor<ContainerSpec> specCaptor = ArgumentCaptor.forClass(ContainerSpec.class);
|
||||
|
||||
MskCluster cluster = newCluster();
|
||||
manager.startContainer(cluster);
|
||||
|
||||
verify(lifecycleManager, times(2)).createAndStart(specCaptor.capture());
|
||||
ContainerSpec retried = specCaptor.getAllValues().get(1);
|
||||
assertEquals("internal://floci-aws-msk-abc123:9092,host://localhost:9308",
|
||||
retried.cmd().get(retried.cmd().indexOf("--advertise-kafka-addr") + 1),
|
||||
"the listener args are rebuilt for the new port");
|
||||
assertEquals(Integer.valueOf(9308), retried.portBindings().get(RedpandaManager.KAFKA_HOST_LISTENER_PORT));
|
||||
assertEquals("container-461", cluster.getContainerId());
|
||||
verify(portAllocator).release(9307);
|
||||
verify(portAllocator, never()).release(9308);
|
||||
}
|
||||
|
||||
@Test
|
||||
void stopContainerInContainerModeReleasesHostListenerPort() {
|
||||
when(containerDetector.isRunningInContainer()).thenReturn(true);
|
||||
when(portAllocator.allocate(9300, 9399)).thenReturn(9304);
|
||||
when(lifecycleManager.createAndStart(any())).thenReturn(new ContainerInfo("container-458",
|
||||
Map.of(KAFKA_PORT, new EndpointInfo("172.18.0.7", KAFKA_PORT))));
|
||||
|
||||
MskCluster cluster = newCluster();
|
||||
manager.startContainer(cluster);
|
||||
manager.stopContainer(cluster);
|
||||
|
||||
verify(lifecycleManager).stopAndRemove("container-458", null);
|
||||
verify(portAllocator).release(9304);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
Reference in new issue
Block a user