fix(amazonmq): start broker containers again when Floci restarts (#9377)

Floci's shutdown removes every broker container, and nothing started
them again, so after a restart with persistent storage a broker still
reported RUNNING while nothing answered on its endpoints. A new
container would not have helped either: RabbitMQ keeps its data under
the node name, which defaults to the hostname Docker sets to the
container id, so a new container on the same volume started an empty
node without the broker's users.

Broker containers now run as the fixed node name rabbit@localhost. At
startup, each broker that was RUNNING or still starting goes back to
CREATION_IN_PROGRESS, and its container starts in the background. A
container that outlived Floci is kept when it still answers. Otherwise
the broker gets a new container on its volume, without seeding the
admin user, whose password is never stored, and on the host ports it
had when they are free. The readiness poller reports it RUNNING once
the console it probed answers.

A broker from before fixed node names with no surviving container is
reported CREATION_FAILED. One whose restore fails is reported
CREATION_FAILED and tried again at the next start, one CreateBroker
failed for is left as it is, and one a crash left DELETION_IN_PROGRESS
is deleted.

Part of #5664.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-11-24 16:17:21 -04:00
1 parent 08b6339a6a
commit 4a9ae4a569
11 files changed
+1179 -41

No files matched your search

@@ -8,6 +8,7 @@ import io.floci.aws.core.storage.PersistentPathValidator;
import io.floci.aws.core.storage.StorageFactory;
import io.floci.aws.lifecycle.inithook.InitializationHook;
import io.floci.aws.lifecycle.inithook.InitializationHooksRunner;
import io.floci.aws.services.amazonmq.AmazonMqService;
import io.floci.aws.services.amazonmq.container.RabbitMqManager;
import io.floci.aws.services.appsync.graphql.SchemaCreationWorker;
import io.floci.aws.services.cloudwatch.metrics.CloudWatchMetricsService;
@@ -102,6 +103,7 @@ public class EmulatorLifecycle {
private final NeptuneContainerManager neptuneContainerManager;
private final NeptuneProxyManager neptuneProxyManager;
private final RabbitMqManager rabbitMqManager;
private final AmazonMqService amazonMqService;
private final FlinkContainerManager flinkContainerManager;
private final SageMakerService sageMakerService;
private final RdsService rdsService;
@@ -150,6 +152,7 @@ public class EmulatorLifecycle {
NeptuneContainerManager neptuneContainerManager,
NeptuneProxyManager neptuneProxyManager,
RabbitMqManager rabbitMqManager,
AmazonMqService amazonMqService,
FlinkContainerManager flinkContainerManager,
SageMakerService sageMakerService,
RdsService rdsService,
@@ -195,6 +198,7 @@ public class EmulatorLifecycle {
this.neptuneContainerManager = neptuneContainerManager;
this.neptuneProxyManager = neptuneProxyManager;
this.rabbitMqManager = rabbitMqManager;
this.amazonMqService = amazonMqService;
this.flinkContainerManager = flinkContainerManager;
this.sageMakerService = sageMakerService;
this.rdsService = rdsService;
@@ -306,6 +310,13 @@ public class EmulatorLifecycle {
LOG.error("Failed to restore persisted SageMaker endpoints at startup", e);
}
}
if (config.services().amazonmq().enabled()) {
// Starts the brokers' containers in the background, failing the future with the ones it could not.
amazonMqService.restorePersistedRuntime().exceptionally(ex -> {
LOG.error("Failed to restore persisted Amazon MQ brokers at startup", ex);
return null;
});
}
if (config.services().elbv2().enabled()) {
elbV2Service.restorePersistedRuntime();
}
@@ -30,8 +30,11 @@ import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
@@ -57,6 +60,12 @@ public class AmazonMqService implements ResourceProvider {
*/
private final StripedLocks storedBrokerLocks = new StripedLocks(256);
private final ScheduledExecutorService poller = Executors.newSingleThreadScheduledExecutor();
/**
* The brokers a restore is bringing back, by {@code account:key}, which the readiness poller leaves alone: their
* stored endpoints are the old container's until the restore keeps that container or starts a new one. In memory
* only, so after a crash the record keeps the endpoints the next start probes a surviving container on.
*/
private final Set<String> restoringBrokers = ConcurrentHashMap.newKeySet();
@Inject
public AmazonMqService(StorageFactory storageFactory, EmulatorConfig config,
@@ -265,6 +274,190 @@ public class AmazonMqService implements ResourceProvider {
return broker;
}
/**
* Brings the persisted brokers back after Floci restarts. Shutdown removes their containers
* ({@link RabbitMqManager#stopAll}), so a broker stored {@code RUNNING}, or still starting, has nothing behind
* it. Each goes back to {@code CREATION_IN_PROGRESS} at once, and the containers start in the background, so
* Floci does not wait for them to report itself ready.
*
* <p>The poller leaves a broker alone while its restore runs, so its stored endpoints stay the old container's
* meanwhile. A broker whose container outlived Floci, as when Floci is killed, keeps that container when it still
* answers. Otherwise it gets a new container on its volume, where its node keeps its users, vhosts and messages,
* published on the host ports it had when they are free, and the poller reports it {@code RUNNING} once the
* console answers. A broker whose container ran under Docker's own hostname, before brokers had a fixed node
* name, keeps its data under a node no new container can find, and its admin password was never stored, so with
* no surviving container it is reported {@code CREATION_FAILED}. One whose container cannot be started is
* reported {@code CREATION_FAILED} too, and tried again at the next start; one {@code CreateBroker} failed for
* stays as it is, and one a crash left {@code DELETION_IN_PROGRESS} is deleted with its container and volume.
* Every broker is tried, and the ones that could not be restored fail the returned future together. A shutdown
* during the restore leaves the brokers not started yet {@code CREATION_IN_PROGRESS}, for the next start.
*/
public CompletableFuture<Void> restorePersistedRuntime() {
if (config.services().amazonmq().mock()) {
return CompletableFuture.completedFuture(null);
}
List<RestoringBroker> pending = new ArrayList<>();
RuntimeException failure = null;
for (AccountEntry<Broker> entry : storage.scanAllAccountEntries(key -> true)) {
try {
RestoringBroker restoring = prepareRestore(entry.accountId(), entry.key());
if (restoring != null) {
pending.add(restoring);
}
} catch (RuntimeException e) {
failure = addRestoreFailure(failure, entry.accountId(), entry.key(), e);
}
}
RuntimeException prepareFailure = failure;
return CompletableFuture.runAsync(() -> {
RuntimeException restoreFailure = prepareFailure;
for (RestoringBroker restoring : pending) {
if (rabbitMqManager.isShuttingDown()) {
// Brokers not reached yet stay starting, which the next start restores.
break;
}
try {
finishRestore(restoring);
} catch (RabbitMqManager.ShuttingDownException e) {
LOG.debugv("Amazon MQ broker {0} not restored: {1}", restoring.key(), e.getMessage());
} catch (RuntimeException e) {
restoreFailure = addRestoreFailure(restoreFailure, restoring.accountId(), restoring.key(), e);
} finally {
restoringBrokers.remove(restoring.accountId() + ":" + restoring.key());
}
}
if (restoreFailure != null) {
throw restoreFailure;
}
});
}
/** A broker the restore brings back, with the endpoints it had for keeping a container that outlived Floci. */
private record RestoringBroker(String accountId, String key, Broker broker, List<BrokerInstance> endpoints,
boolean deleting) {}
private static RuntimeException addRestoreFailure(RuntimeException failure, String accountId, String key,
RuntimeException e) {
RuntimeException restoreFailure = new IllegalStateException("Could not restore Amazon MQ broker " + key
+ " of account " + accountId, e);
if (failure == null) {
return restoreFailure;
}
failure.addSuppressed(restoreFailure);
return failure;
}
/** Marks a broker the restore brings back, under its lock; null for one it leaves as it is. */
private RestoringBroker prepareRestore(String accountId, String key) {
synchronized (storedBrokerLock(accountId, key)) {
Broker broker = storage.getForAccount(accountId, key).orElse(null);
if (broker == null) {
return null;
}
if (broker.getBrokerState() == BrokerState.DELETION_IN_PROGRESS) {
return new RestoringBroker(accountId, key, broker, List.of(), true);
}
// A failed broker with a node name ran before and failed to come back; one without never ran.
if (broker.getBrokerState() == BrokerState.CREATION_FAILED && broker.getNodeName() == null) {
return null;
}
List<BrokerInstance> endpoints = broker.getBrokerInstances() == null
? List.of() : List.copyOf(broker.getBrokerInstances());
restoringBrokers.add(accountId + ":" + key);
broker.setBrokerState(BrokerState.CREATION_IN_PROGRESS);
storage.putForAccount(accountId, key, broker);
return new RestoringBroker(accountId, key, broker, endpoints, false);
}
}
private void finishRestore(RestoringBroker restoring) {
String accountId = restoring.accountId();
String key = restoring.key();
Object lock = storedBrokerLock(accountId, key);
Broker broker = restoring.broker();
if (restoring.deleting()) {
rabbitMqManager.stopContainer(broker);
rabbitMqManager.removeBrokerStorage(broker);
synchronized (lock) {
storage.deleteForAccount(accountId, key);
}
return;
}
Broker candidate = copyForAdoption(broker, restoring.endpoints());
if (rabbitMqManager.adoptRunningContainer(candidate)) {
synchronized (lock) {
Broker current = storage.getForAccount(accountId, key).orElse(null);
if (current == null || current.getBrokerState() == BrokerState.DELETION_IN_PROGRESS) {
rabbitMqManager.stopContainer(candidate);
return;
}
current.setContainerId(candidate.getContainerId());
current.setBrokerState(BrokerState.RUNNING);
storage.putForAccount(accountId, key, current);
}
return;
}
if (broker.getNodeName() == null) {
synchronized (lock) {
Broker current = storage.getForAccount(accountId, key).orElse(null);
if (current != null && current.getBrokerState() == BrokerState.CREATION_IN_PROGRESS) {
LOG.warnv("Amazon MQ broker {0} ({1}) predates fixed RabbitMQ node names, so its data cannot be "
+ "found again after a restart; reporting it CREATION_FAILED", current.getBrokerName(),
current.getBrokerId());
current.setBrokerState(BrokerState.CREATION_FAILED);
current.setBrokerInstances(new ArrayList<>());
storage.putForAccount(accountId, key, current);
}
}
return;
}
try {
rabbitMqManager.restoreContainer(broker);
} catch (RabbitMqManager.ShuttingDownException e) {
throw e;
} catch (RuntimeException e) {
synchronized (lock) {
Broker current = storage.getForAccount(accountId, key).orElse(null);
if (current != null && current.getBrokerState() == BrokerState.CREATION_IN_PROGRESS) {
current.setBrokerState(BrokerState.CREATION_FAILED);
current.setBrokerInstances(new ArrayList<>());
storage.putForAccount(accountId, key, current);
}
}
throw e;
}
synchronized (lock) {
Broker current = storage.getForAccount(accountId, key).orElse(null);
if (current == null || current.getBrokerState() == BrokerState.DELETION_IN_PROGRESS) {
// Deleted while its container started, which the delete could not stop yet.
rabbitMqManager.stopContainer(broker);
if (current == null) {
rabbitMqManager.removeBrokerStorage(broker);
}
return;
}
current.setContainerId(broker.getContainerId());
current.setBrokerInstances(broker.getBrokerInstances());
current.setNodeName(broker.getNodeName());
current.setAmqpHostPort(broker.getAmqpHostPort());
current.setConsoleHostPort(broker.getConsoleHostPort());
storage.putForAccount(accountId, key, current);
}
}
/**
* The broker as its record named it before the restore cleared its endpoints, which the readiness check of a
* container that outlived Floci probes, kept apart from the stored broker until the container is kept.
*/
private static Broker copyForAdoption(Broker broker, List<BrokerInstance> endpoints) {
Broker candidate = new Broker(broker.getBrokerId(), broker.getBrokerArn(), broker.getBrokerName(),
broker.getEngineType(), broker.getEngineVersion(), broker.getDeploymentMode(),
broker.getHostInstanceType());
candidate.setAccountId(broker.getAccountId());
candidate.setBrokerInstances(new ArrayList<>(endpoints));
return candidate;
}
private void applyLocalEndpoints(Broker broker) {
BrokerInstance instance = new BrokerInstance(
"http://localhost:15672",
@@ -288,9 +481,13 @@ public class AmazonMqService implements ResourceProvider {
// account. Brokers stored under a bare id have moved to their Region's key at startup.
for (AccountEntry<Broker> entry : storage.scanAllAccountEntries(key -> true)) {
Broker broker = entry.value();
if (broker.getBrokerState() == BrokerState.CREATION_IN_PROGRESS
&& rabbitMqManager.isReady(broker)) {
markRunning(entry.accountId(), entry.key());
if (broker.getBrokerState() != BrokerState.CREATION_IN_PROGRESS
|| restoringBrokers.contains(entry.accountId() + ":" + entry.key())) {
continue;
}
String console = consoleUrl(broker);
if (rabbitMqManager.isReady(broker)) {
markRunning(entry.accountId(), entry.key(), console);
}
}
} catch (Exception e) {
@@ -301,12 +498,14 @@ public class AmazonMqService implements ResourceProvider {
/**
* Stores a broker that turned ready as RUNNING, read again under its lock first. The readiness check is a
* blocking call to the broker's container, long enough for a DeleteBroker, which marks the broker under the same
* lock, to land in the meantime, and a broker deleted or being deleted is not written back.
* lock, to land in the meantime, and a broker deleted or being deleted is not written back. Nor is one whose
* console has changed since the check, as a restore changes it: the answer came from the console it had.
*/
private void markRunning(String accountId, String key) {
private void markRunning(String accountId, String key, String probedConsole) {
synchronized (storedBrokerLock(accountId, key)) {
Broker broker = storage.getForAccount(accountId, key).orElse(null);
if (broker == null || broker.getBrokerState() != BrokerState.CREATION_IN_PROGRESS) {
if (broker == null || broker.getBrokerState() != BrokerState.CREATION_IN_PROGRESS
|| !Objects.equals(probedConsole, consoleUrl(broker))) {
return;
}
LOG.infov("Amazon MQ broker {0} is now RUNNING", broker.getBrokerName());
@@ -315,6 +514,11 @@ public class AmazonMqService implements ResourceProvider {
}
}
private static String consoleUrl(Broker broker) {
List<BrokerInstance> instances = broker.getBrokerInstances();
return instances == null || instances.isEmpty() ? null : instances.get(0).getConsoleURL();
}
/** The lock of the broker stored under {@code key} in {@code accountId}. */
private Object storedBrokerLock(String accountId, String key) {
return storedBrokerLocks.lockFor(accountId + ":" + key);
@@ -1,5 +1,6 @@
package io.floci.aws.services.amazonmq.container;
import com.github.dockerjava.api.model.Container;
import io.floci.aws.config.EmulatorConfig;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.common.docker.ContainerBuilder;
@@ -24,6 +25,8 @@ import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.OptionalInt;
import java.util.concurrent.ConcurrentHashMap;
/**
@@ -46,6 +49,12 @@ public class RabbitMqManager {
private static final Logger LOG = Logger.getLogger(RabbitMqManager.class);
private static final int AMQP_PORT = 5672;
private static final int MGMT_PORT = 15672;
/**
* The node name every broker container runs as. RabbitMQ keeps its data under
* {@code /var/lib/rabbitmq/mnesia/<node name>}, and the name defaults to the hostname, which Docker sets to the
* container's id: without a fixed name, a new container on the same volume starts an empty node.
*/
static final String NODE_NAME = "rabbit@localhost";
private final ContainerBuilder containerBuilder;
private final ContainerLifecycleManager lifecycleManager;
@@ -56,14 +65,25 @@ public class RabbitMqManager {
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.
// Host ports this process reserved for each running broker: released when the container
// goes away so repeated create/delete cycles do not exhaust the configured ranges. The
// broker records them too, so a restart can publish the broker on the same ones.
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) {}
// Set by stopAll(). A start still running when shutdown removes the containers, as a restore's can be while an
// image pulls, removes its own container rather than leave it behind after the cleanup.
private boolean shuttingDown;
/** Thrown by a start that shutdown overtook; its container, if any, is already removed. */
public static final class ShuttingDownException extends IllegalStateException {
public ShuttingDownException(String brokerId) {
super("Floci is shutting down; not starting the RabbitMQ container of broker " + brokerId);
}
}
@Inject
public RabbitMqManager(ContainerBuilder containerBuilder,
ContainerLifecycleManager lifecycleManager,
@@ -86,7 +106,24 @@ public class RabbitMqManager {
return ContainerStorageHelper.dockerName(config, "amazonmq-" + brokerId);
}
/** Starts the container of a new broker, seeding its admin user. */
public void startContainer(Broker broker) {
start(broker, true);
}
/**
* Starts the container of a broker that ran before Floci restarted, on its volume, where its node already holds
* its users, vhosts and messages, so nothing is seeded: the admin password is never stored. It is published on
* the host ports it had when they are still free.
*/
public void restoreContainer(Broker broker) {
start(broker, false);
}
private void start(Broker broker, boolean seedAdmin) {
if (isShuttingDown()) {
throw new ShuttingDownException(broker.getBrokerId());
}
String image = config.services().amazonmq().defaultImage();
String containerName = containerName(broker.getBrokerId());
LOG.infov("Starting RabbitMQ container for broker {0} using image {1}",
@@ -100,14 +137,14 @@ public class RabbitMqManager {
.withDockerNetwork(config.services().dockerNetwork())
.withLogRotation()
.withPushedLogs()
.withEnv("RABBITMQ_NODENAME", NODE_NAME)
.withLabels(ContainerStorageHelper.resourceIdentityLabels(
"amazonmq", broker.getBrokerId(), regionResolver.getAccountId(),
brokerRegion(broker)));
"amazonmq", broker.getBrokerId(), brokerAccount(broker), brokerRegion(broker)));
// Seed the broker's admin user. RabbitMQ's built-in `guest` user is
// loopback-only, so it cannot authenticate over the mapped host port; a user
// created via RABBITMQ_DEFAULT_USER/PASS is not loopback-restricted and can.
if (!broker.getUsers().isEmpty()) {
if (seedAdmin && !broker.getUsers().isEmpty()) {
MqUser admin = broker.getUsers().get(0);
if (admin.getPassword() == null) {
// The password is in-memory only (a secret we do not persist). It is
@@ -125,7 +162,7 @@ public class RabbitMqManager {
// 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();
HostPorts ports = allocateHostPorts(broker);
// Publish both ports on the host in every topology (see class javadoc). The
// endpoints resolved below stay topology-aware: localhost:<hostPort> natively,
@@ -156,39 +193,100 @@ public class RabbitMqManager {
portAllocator.release(ports.console());
throw e;
}
broker.setContainerId(info.containerId());
containerIds.put(broker.getBrokerId(), info.containerId());
hostPorts.put(broker.getBrokerId(), ports);
synchronized (this) {
if (shuttingDown) {
lifecycleManager.stopAndRemove(info.containerId(), null);
portAllocator.release(ports.amqp());
portAllocator.release(ports.console());
throw new ShuttingDownException(broker.getBrokerId());
}
containerIds.put(broker.getBrokerId(), info.containerId());
hostPorts.put(broker.getBrokerId(), ports);
}
try {
EndpointInfo amqp = info.getEndpoint(AMQP_PORT);
EndpointInfo mgmt = info.getEndpoint(MGMT_PORT);
BrokerInstance instance = new BrokerInstance(
"http://" + mgmt.host() + ":" + mgmt.port(),
List.of("amqp://" + amqp.host() + ":" + amqp.port()),
amqp.host());
attachLogs(broker, info.containerId());
broker.setContainerId(info.containerId());
broker.setBrokerInstances(new ArrayList<>(List.of(instance)));
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()));
} catch (RuntimeException e) {
// A container that started but could not be wired up is not left running behind a failed broker.
containerIds.remove(broker.getBrokerId());
releaseHostPorts(broker.getBrokerId());
lifecycleManager.stopAndRemove(info.containerId(), logStreams.remove(broker.getBrokerId()));
throw e;
}
// Recorded only once the container is up and wired: a broker that has them ran under the fixed node name.
broker.setNodeName(NODE_NAME);
broker.setAmqpHostPort(ports.amqp());
broker.setConsoleHostPort(ports.console());
}
EndpointInfo amqp = info.getEndpoint(AMQP_PORT);
EndpointInfo mgmt = info.getEndpoint(MGMT_PORT);
BrokerInstance instance = new BrokerInstance(
"http://" + mgmt.host() + ":" + mgmt.port(),
List.of("amqp://" + amqp.host() + ":" + amqp.port()),
amqp.host());
broker.setBrokerInstances(new ArrayList<>(List.of(instance)));
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()));
/**
* Keeps a broker's container that outlived Floci, as one does when Floci is killed rather than shut down,
* when it still answers on the console its record names: whatever its node name, its node is the one holding
* the broker's data. The container is tracked again, so shutdown removes it, and its logs are streamed again.
* Returns whether the container was kept.
*/
public boolean adoptRunningContainer(Broker broker) {
String name = containerName(broker.getBrokerId());
Optional<Container> container = lifecycleManager.findByName(name);
String legacyName = ContainerStorageHelper.legacyDockerName(config, name);
if (container.isEmpty() && !legacyName.equals(name)) {
// A broker created before the floci-aws- prefix runs in a container of the old name.
container = lifecycleManager.findByName(legacyName);
}
if (container.isEmpty() || !"running".equals(container.get().getState()) || !isReady(broker)) {
return false;
}
String containerId = container.get().getId();
synchronized (this) {
if (shuttingDown) {
return false;
}
containerIds.put(broker.getBrokerId(), containerId);
}
broker.setContainerId(containerId);
attachLogs(broker, containerId);
LOG.infov("Kept the running RabbitMQ container {0} of broker {1}", containerId, broker.getBrokerName());
return true;
}
String shortId = info.containerId().length() >= 8
? info.containerId().substring(0, 8)
: info.containerId();
String logGroup = broker.generalLogGroup();
String logStream = logStreamer.generateLogStreamName(shortId);
String region = brokerRegion(broker);
Closeable logHandle = logStreamer.attachPolled(
info.containerId(), logGroup, logStream, region, "amazonmq:" + broker.getBrokerId());
private void attachLogs(Broker broker, String containerId) {
String shortId = containerId.length() >= 8 ? containerId.substring(0, 8) : containerId;
Closeable logHandle = logStreamer.attachPolledForAccount(brokerAccount(broker), containerId,
broker.generalLogGroup(), logStreamer.generateLogStreamName(shortId), brokerRegion(broker),
"amazonmq:" + broker.getBrokerId());
if (logHandle != null) {
logStreams.put(broker.getBrokerId(), logHandle);
}
}
/**
* The account that owns the broker. A restore runs outside any request, where the resolver answers the default
* account; a broker recorded without its account is the request's.
*/
private String brokerAccount(Broker broker) {
return broker.getAccountId() != null ? broker.getAccountId() : regionResolver.getAccountId();
}
/** The Region the broker's ARN names, and the default Region for a broker recorded without one. */
private String brokerRegion(Broker broker) {
return regionResolver.regionOf(broker.getBrokerArn());
}
/** Whether shutdown has removed the containers, after which no broker container starts. */
public synchronized boolean isShuttingDown() {
return shuttingDown;
}
/**
* Ready once the RabbitMQ management UI answers on its port. The management
* plugin starts after the broker core, so a 200 here implies AMQP is also up.
@@ -247,6 +345,9 @@ public class RabbitMqManager {
* alongside the other container managers.
*/
public void stopAll() {
synchronized (this) {
shuttingDown = true;
}
if (!containerIds.isEmpty()) {
LOG.infov("Stopping {0} RabbitMQ container(s) on shutdown", containerIds.size());
}
@@ -261,12 +362,16 @@ public class RabbitMqManager {
}
}
private HostPorts allocateHostPorts() {
/**
* The broker's host ports: the ones it had, each that is still free and in its range, as a restored broker has,
* and new ones otherwise, as a new broker, which has none, always gets.
*/
private HostPorts allocateHostPorts(Broker broker) {
EmulatorConfig.AmazonMqServiceConfig mq = config.services().amazonmq();
int amqp = portAllocator.allocate(mq.amqpHostPortBase(), mq.amqpHostPortMax());
int amqp = reuseOrAllocate(broker.getAmqpHostPort(), mq.amqpHostPortBase(), mq.amqpHostPortMax());
int console;
try {
console = portAllocator.allocate(mq.consoleHostPortBase(), mq.consoleHostPortMax());
console = reuseOrAllocate(broker.getConsoleHostPort(), mq.consoleHostPortBase(), mq.consoleHostPortMax());
} catch (RuntimeException e) {
portAllocator.release(amqp);
throw e;
@@ -274,6 +379,16 @@ public class RabbitMqManager {
return new HostPorts(amqp, console);
}
private int reuseOrAllocate(Integer previous, int base, int max) {
if (previous != null && previous >= base && previous <= max) {
OptionalInt reused = portAllocator.allocateIfFree(previous);
if (reused.isPresent()) {
return reused.getAsInt();
}
}
return portAllocator.allocate(base, max);
}
private void releaseHostPorts(String brokerId) {
HostPorts ports = hostPorts.remove(brokerId);
if (ports != null) {
@@ -110,6 +110,17 @@ public class Broker {
*/
private String dockerVolumeName;
/**
* The RabbitMQ node name the broker's container runs as, which names its data directory in the volume, so a
* later container finds the same users, vhosts and messages. Null on a broker whose container ran under
* Docker's own hostname, whose data no later container can find.
*/
private String nodeName;
/** The host ports the broker's AMQP and console ports were published on, which a restart publishes again. */
private Integer amqpHostPort;
private Integer consoleHostPort;
public Broker() {}
public Broker(String brokerId, String brokerArn, String brokerName,
@@ -210,4 +221,13 @@ public class Broker {
public String getDockerVolumeName() { return dockerVolumeName; }
public void setDockerVolumeName(String dockerVolumeName) { this.dockerVolumeName = dockerVolumeName; }
public String getNodeName() { return nodeName; }
public void setNodeName(String nodeName) { this.nodeName = nodeName; }
public Integer getAmqpHostPort() { return amqpHostPort; }
public void setAmqpHostPort(Integer amqpHostPort) { this.amqpHostPort = amqpHostPort; }
public Integer getConsoleHostPort() { return consoleHostPort; }
public void setConsoleHostPort(Integer consoleHostPort) { this.consoleHostPort = consoleHostPort; }
}