diff --git a/.github/ci/prefetch-images.sh b/.github/ci/prefetch-images.sh index e43d63caeb..71a8bc06c6 100755 --- a/.github/ci/prefetch-images.sh +++ b/.github/ci/prefetch-images.sh @@ -231,6 +231,10 @@ INFLUX_IMAGE="$(grep -oE 'default-image: *"influxdb:[^"]+"' src/main/resources/a grep -q '/timestreaminfluxdb/' "$SHARD_FILE" && [ -n "$INFLUX_IMAGE" ] && pull "$INFLUX_IMAGE" K3S_IMAGE="$(grep -oE 'default-image: *"rancher/k3s:[^"]+"' src/main/resources/application.yml | grep -oE '"[^"]+"' | tr -d '"')" grep -q '/eks/' "$SHARD_FILE" && [ -n "$K3S_IMAGE" ] && pull "$K3S_IMAGE" +# The nightly AmazonMqBrokerRestartNightlyIntegrationTest runs a broker in the RabbitMQ image Amazon MQ defaults to, +# pinned in application.yml too. +RABBITMQ_IMAGE="$(grep -oE 'default-image: *"rabbitmq:[^"]+"' src/main/resources/application.yml | grep -oE '"[^"]+"' | tr -d '"')" +starts AmazonMqBrokerRestartNightlyIntegrationTest && [ -n "$RABBITMQ_IMAGE" ] && pull "$RABBITMQ_IMAGE" if [ -n "$ECR_PUBLIC_IMAGES" ]; then { for image in $ECR_PUBLIC_IMAGES; do pull_and_log "$image"; sleep 1; done; } & fi diff --git a/docs/services/amazonmq.md b/docs/services/amazonmq.md index 4a7f062631..57fa7d5fc9 100644 --- a/docs/services/amazonmq.md +++ b/docs/services/amazonmq.md @@ -71,6 +71,21 @@ authentication, and other Docker settings see [Docker Configuration](../configur `FLOCI_STORAGE_PRUNE_VOLUMES_ON_DELETE=true`. - **Readiness**: The broker state transitions to `RUNNING` once the RabbitMQ management API answers on its port. +- **Restarts**: Floci removes broker containers when it shuts down. With persistent storage, + each broker that was `RUNNING`, or still starting, goes back to `CREATION_IN_PROGRESS` when + Floci starts again, and its container starts in the background, so Floci reports itself + ready without waiting for it. A container that outlived Floci, as when Floci is killed + rather than shut down, is kept when it still answers. Otherwise the broker gets a new + container on its volume, published on the host ports it had when they are still free, and + turns `RUNNING` once the management API answers. Broker containers run as the fixed + RabbitMQ node name `rabbit@localhost`, which names the node's data directory, so the new + container keeps the broker's users, vhosts and messages. The admin password Floci never + stores isn't needed. A broker whose container can't be started is reported + `CREATION_FAILED` and tried again the next time Floci starts. A broker created before node + names were fixed kept its data under its old container's hostname, which no new container + can find, so with no surviving container it is reported `CREATION_FAILED`; delete and + create it again. A broker `CreateBroker` failed for stays as it is, and one a crash left + `DELETION_IN_PROGRESS` is deleted with its container and volume. ## Examples diff --git a/src/main/java/io/floci/aws/lifecycle/EmulatorLifecycle.java b/src/main/java/io/floci/aws/lifecycle/EmulatorLifecycle.java index be6f2abbd5..72dfd8d972 100644 --- a/src/main/java/io/floci/aws/lifecycle/EmulatorLifecycle.java +++ b/src/main/java/io/floci/aws/lifecycle/EmulatorLifecycle.java @@ -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(); } diff --git a/src/main/java/io/floci/aws/services/amazonmq/AmazonMqService.java b/src/main/java/io/floci/aws/services/amazonmq/AmazonMqService.java index aae47cccf5..9a2d12281e 100644 --- a/src/main/java/io/floci/aws/services/amazonmq/AmazonMqService.java +++ b/src/main/java/io/floci/aws/services/amazonmq/AmazonMqService.java @@ -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 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. + * + *

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 restorePersistedRuntime() { + if (config.services().amazonmq().mock()) { + return CompletableFuture.completedFuture(null); + } + List pending = new ArrayList<>(); + RuntimeException failure = null; + for (AccountEntry 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 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 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 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 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 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); diff --git a/src/main/java/io/floci/aws/services/amazonmq/container/RabbitMqManager.java b/src/main/java/io/floci/aws/services/amazonmq/container/RabbitMqManager.java index f856eac69b..d9e7ee782c 100644 --- a/src/main/java/io/floci/aws/services/amazonmq/container/RabbitMqManager.java +++ b/src/main/java/io/floci/aws/services/amazonmq/container/RabbitMqManager.java @@ -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/}, 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 logStreams = new ConcurrentHashMap<>(); private final Map 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 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: 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 = 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) { diff --git a/src/main/java/io/floci/aws/services/amazonmq/model/Broker.java b/src/main/java/io/floci/aws/services/amazonmq/model/Broker.java index 2e8a9ee975..cade1b06f1 100644 --- a/src/main/java/io/floci/aws/services/amazonmq/model/Broker.java +++ b/src/main/java/io/floci/aws/services/amazonmq/model/Broker.java @@ -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; } } diff --git a/src/test/java/io/floci/aws/lifecycle/EmulatorLifecycleTest.java b/src/test/java/io/floci/aws/lifecycle/EmulatorLifecycleTest.java index cea2edad06..47a8d35cee 100644 --- a/src/test/java/io/floci/aws/lifecycle/EmulatorLifecycleTest.java +++ b/src/test/java/io/floci/aws/lifecycle/EmulatorLifecycleTest.java @@ -7,6 +7,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; @@ -123,6 +124,8 @@ class EmulatorLifecycleTest { @Mock private ElbClassicService elbClassicService; @Mock private EcsService ecsService; @Mock private SageMakerService sageMakerService; + @Mock private AmazonMqService amazonMqService; + @Mock private EmulatorConfig.AmazonMqServiceConfig amazonMqServiceConfig; @Mock private EmulatorConfig.SageMakerServiceConfig sageMakerServiceConfig; @Mock private EksService eksService; @Mock private CodeArtifactService codeArtifactService; @@ -171,6 +174,8 @@ class EmulatorLifecycleTest { Mockito.lenient().when(eksServiceConfig.enabled()).thenReturn(false); Mockito.lenient().when(servicesConfig.codeartifact()).thenReturn(codeArtifactServiceConfig); Mockito.lenient().when(codeArtifactServiceConfig.enabled()).thenReturn(true); + Mockito.lenient().when(servicesConfig.amazonmq()).thenReturn(amazonMqServiceConfig); + Mockito.lenient().when(amazonMqServiceConfig.enabled()).thenReturn(false); Mockito.lenient().when(servicesConfig.sagemaker()).thenReturn(sageMakerServiceConfig); Mockito.lenient().when(sageMakerServiceConfig.enabled()).thenReturn(false); Mockito.lenient().when(servicesConfig.timestreamInfluxdb()).thenReturn(timestreamInfluxDbServiceConfig); @@ -188,7 +193,7 @@ class EmulatorLifecycleTest { elastiCacheProxyManager, rdsContainerManager, rdsProxyManager, memoryDbContainerManager, memoryDbProxyManager, memoryDbService, docDbContainerManager, neptuneContainerManager, neptuneProxyManager, - rabbitMqManager, flinkContainerManager, sageMakerService, rdsService, timestreamInfluxDbService, + rabbitMqManager, amazonMqService, flinkContainerManager, sageMakerService, rdsService, timestreamInfluxDbService, elbV2Service, elbClassicService, ecsService, initializationHooksRunner, sqsPoller, kinesisPoller, dynamodbStreamsPoller, pipesService, ec2MetadataServer, ecsTaskRoleCredentialsServer, ecrRegistryManager, flociUiManager, initLifecycleState, @@ -517,6 +522,48 @@ class EmulatorLifecycleTest { verify(initLifecycleState).markReadyCompleted(); } + @Test + void restoresPersistedAmazonMqBrokersAfterStorageLoad() { + stubStorageConfig(); + when(amazonMqServiceConfig.enabled()).thenReturn(true); + when(amazonMqService.restorePersistedRuntime()).thenReturn(CompletableFuture.completedFuture(null)); + when(initializationHooksRunner.hasHooks(InitializationHook.START)).thenReturn(false); + when(initializationHooksRunner.hasHooks(InitializationHook.READY)).thenReturn(false); + + emulatorLifecycle.onStart(Mockito.mock(StartupEvent.class)); + + InOrder inOrder = Mockito.inOrder(storageFactory, amazonMqService); + inOrder.verify(storageFactory).loadAll(); + inOrder.verify(amazonMqService).restorePersistedRuntime(); + } + + @Test + void aFailedAmazonMqRestoreDoesNotStopTheOtherRestores() { + stubStorageConfig(); + when(amazonMqServiceConfig.enabled()).thenReturn(true); + when(elbv2ServiceConfig.enabled()).thenReturn(true); + when(amazonMqService.restorePersistedRuntime()).thenReturn(CompletableFuture.failedFuture( + new IllegalStateException("Could not restore Amazon MQ broker us-east-1::b-1 of account 000000000000"))); + when(initializationHooksRunner.hasHooks(InitializationHook.START)).thenReturn(false); + when(initializationHooksRunner.hasHooks(InitializationHook.READY)).thenReturn(false); + + emulatorLifecycle.onStart(Mockito.mock(StartupEvent.class)); + + verify(elbV2Service).restorePersistedRuntime(); + verify(initLifecycleState).markReadyCompleted(); + } + + @Test + void leavesAmazonMqBrokersUntouchedWhenAmazonMqIsDisabled() { + stubStorageConfig(); + when(initializationHooksRunner.hasHooks(InitializationHook.START)).thenReturn(false); + when(initializationHooksRunner.hasHooks(InitializationHook.READY)).thenReturn(false); + + emulatorLifecycle.onStart(Mockito.mock(StartupEvent.class)); + + verify(amazonMqService, never()).restorePersistedRuntime(); + } + @Test void leavesSageMakerEndpointsUntouchedWhenSageMakerIsDisabled() { stubStorageConfig(); diff --git a/src/test/java/io/floci/aws/services/amazonmq/AmazonMqBrokerRestartNightlyIntegrationTest.java b/src/test/java/io/floci/aws/services/amazonmq/AmazonMqBrokerRestartNightlyIntegrationTest.java new file mode 100644 index 0000000000..7ff6f1f7af --- /dev/null +++ b/src/test/java/io/floci/aws/services/amazonmq/AmazonMqBrokerRestartNightlyIntegrationTest.java @@ -0,0 +1,140 @@ +package io.floci.aws.services.amazonmq; + +import com.github.dockerjava.api.DockerClient; +import com.github.dockerjava.api.model.Container; +import io.floci.aws.config.EmulatorConfig; +import io.floci.aws.core.common.docker.ContainerStorageHelper; +import io.floci.aws.testing.DockerAvailability; +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.QuarkusTestProfile; +import io.quarkus.test.junit.TestProfile; +import io.restassured.specification.RequestSpecification; +import jakarta.inject.Inject; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; + +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.util.Base64; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.TimeUnit; + +import static io.restassured.RestAssured.given; +import static org.awaitility.Awaitility.await; +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * #5664: an Amazon MQ broker comes back after Floci restarts with what its RabbitMQ node holds. Shutdown removes the + * broker's container; the startup restore starts a new one on the broker's volume, under the same node name, so the + * admin user, whose password Floci never stored, and a vhost created through the console are still there. Removing + * the container stands in for the shutdown, and the restore is what startup calls. + * + *

A nightly check: it runs a real RabbitMQ broker, which the shared test configuration mocks. + */ +@QuarkusTest +@TestProfile(AmazonMqBrokerRestartNightlyIntegrationTest.Profile.class) +@EnabledIfSystemProperty(named = "nightly.checks.enabled", matches = "true") +// Bounded waits: the RabbitMQ image's pull, then the broker starting twice. +@Timeout(value = 10, unit = TimeUnit.MINUTES) +class AmazonMqBrokerRestartNightlyIntegrationTest { + + /** Real RabbitMQ brokers. */ + public static final class Profile implements QuarkusTestProfile { + @Override + public Map getConfigOverrides() { + return Map.of("floci.services.amazonmq.mock", "false"); + } + } + + private static final String AUTH = "AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/mq/aws4_request"; + private static final String ADMIN = "admin"; + private static final String PASSWORD = "RestartCheck1234"; + private static final String VHOST = "restart-check"; + private static final Duration BROKER_TIMEOUT = Duration.ofMinutes(4); + + // HTTP/1.1: the RabbitMQ console closes the connection on the h2c upgrade the client otherwise offers. + private final HttpClient http = HttpClient.newBuilder().version(HttpClient.Version.HTTP_1_1) + .connectTimeout(Duration.ofSeconds(5)).build(); + + @Inject + DockerClient dockerClient; + + @Inject + EmulatorConfig config; + + @Inject + AmazonMqService amazonMqService; + + @BeforeEach + void requireDocker() { + Assumptions.assumeTrue(DockerAvailability.answers(dockerClient), + "Docker daemon must be available for the Amazon MQ restart check"); + } + + @Test + void aBrokerKeepsItsUsersAndVhostsAcrossARestart() throws Exception { + String brokerId = mq().contentType("application/json").body(""" + {"brokerName": "restart-%s", "engineType": "RABBITMQ", "deploymentMode": "SINGLE_INSTANCE", + "hostInstanceType": "mq.t3.micro", "publiclyAccessible": false, + "users": [{"username": "%s", "password": "%s", "consoleAccess": true}]} + """.formatted(UUID.randomUUID().toString().substring(0, 8), ADMIN, PASSWORD)) + .when().post("/v1/brokers") + .then().statusCode(200).extract().path("brokerId"); + try { + String console = awaitRunning(brokerId); + assertEquals(201, console(console, "PUT", "/api/vhosts/" + VHOST).statusCode()); + + for (Container container : dockerClient.listContainersCmd().withShowAll(true) + .withNameFilter(List.of(ContainerStorageHelper.dockerName(config, "amazonmq-" + brokerId))).exec()) { + dockerClient.removeContainerCmd(container.getId()).withForce(true).exec(); + } + amazonMqService.restorePersistedRuntime(); + + String restoredConsole = awaitRunning(brokerId); + assertEquals(200, console(restoredConsole, "GET", "/api/vhosts/" + VHOST).statusCode()); + } finally { + mq().when().delete("/v1/brokers/{id}", brokerId); + } + } + + /** Waits for the broker to be RUNNING and returns its console URL. */ + private String awaitRunning(String brokerId) { + await("broker " + brokerId + " running").atMost(BROKER_TIMEOUT).pollInterval(Duration.ofSeconds(2)) + .until(() -> mq().when().get("/v1/brokers/{id}", brokerId).then().statusCode(200) + .extract().path("brokerState"), state -> { + if ("CREATION_FAILED".equals(state)) { + throw new AssertionError("broker " + brokerId + " failed to start"); + } + return "RUNNING".equals(state); + }); + return mq().when().get("/v1/brokers/{id}", brokerId).then().statusCode(200) + .extract().path("brokerInstances[0].consoleURL"); + } + + /** Calls the broker's RabbitMQ management API as its admin user. */ + private HttpResponse console(String consoleUrl, String method, String path) throws Exception { + String credentials = Base64.getEncoder().encodeToString( + (ADMIN + ":" + PASSWORD).getBytes(StandardCharsets.UTF_8)); + HttpRequest request = HttpRequest.newBuilder(URI.create(consoleUrl + path)) + .header("Authorization", "Basic " + credentials) + .header("Content-Type", "application/json") + .method(method, "PUT".equals(method) + ? HttpRequest.BodyPublishers.ofString("{}") : HttpRequest.BodyPublishers.noBody()) + .timeout(Duration.ofSeconds(10)) + .build(); + return http.send(request, HttpResponse.BodyHandlers.ofString()); + } + + private static RequestSpecification mq() { + return given().header("Authorization", AUTH); + } +} diff --git a/src/test/java/io/floci/aws/services/amazonmq/AmazonMqServiceTest.java b/src/test/java/io/floci/aws/services/amazonmq/AmazonMqServiceTest.java index 37cfe6e957..2ae93cc128 100644 --- a/src/test/java/io/floci/aws/services/amazonmq/AmazonMqServiceTest.java +++ b/src/test/java/io/floci/aws/services/amazonmq/AmazonMqServiceTest.java @@ -7,6 +7,7 @@ import io.floci.aws.core.storage.AccountAwareStorageBackend; import io.floci.aws.core.storage.StorageFactory; import io.floci.aws.services.amazonmq.container.RabbitMqManager; import io.floci.aws.services.amazonmq.model.Broker; +import io.floci.aws.services.amazonmq.model.BrokerInstance; import io.floci.aws.services.amazonmq.model.BrokerState; import io.floci.aws.services.amazonmq.model.MqUser; import io.floci.aws.testing.ParkingStore; @@ -16,7 +17,9 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.function.Executable; import org.mockito.Mockito; +import java.util.ArrayList; import java.util.List; +import java.util.concurrent.CompletionException; import static io.floci.aws.testing.ParkingStoreAssertions.assertOperationWaitsForParkedStore; import static org.junit.jupiter.api.Assertions.*; @@ -345,6 +348,300 @@ class AmazonMqServiceTest { } /** A broker still being created, stored in the caller's account and Region; its id. */ + /** + * #5664: shutdown removes every broker's container. After a restart a broker that was running or starting goes + * back to CREATION_IN_PROGRESS and gets a new container, written back in its own account with the new + * container's endpoints; a failed one stays as it is. The readiness poller leaves a broker alone while its + * restore runs: its stored endpoints are still the old container's. + */ + @Test + void restoringStartsARunningOrStartingBrokerAgainInItsOwnAccount() { + RabbitMqManager manager = Mockito.mock(RabbitMqManager.class); + Mockito.doAnswer(start -> { + Broker broker = start.getArgument(0); + assertEquals(BrokerState.CREATION_IN_PROGRESS, broker.getBrokerState()); + service.pollReadiness(); + // The poller must not probe the old console of a broker whose restore is running. + Mockito.verify(manager, Mockito.never()).isReady( + Mockito.argThat(probed -> broker.getBrokerId().equals(probed.getBrokerId()))); + broker.setContainerId("restored-container"); + broker.setBrokerInstances(List.of(new BrokerInstance("http://broker-host:15673", + List.of("amqp://broker-host:5673"), "broker-host"))); + return null; + }).when(manager).restoreContainer(Mockito.any()); + service = newService(false, manager); + String running = storedBroker("111111111111", "eu-west-1", "b-running", BrokerState.RUNNING, true); + String starting = storedBroker(ACCOUNT, "us-east-1", "b-starting", BrokerState.CREATION_IN_PROGRESS, true); + // CreateBroker failed for it, so it never ran under a node name. + String failed = storedBroker("111111111111", "eu-west-1", "b-failed", BrokerState.CREATION_FAILED, false); + + service.restorePersistedRuntime().join(); + + Broker restored = brokers.getForAccount("111111111111", running).orElseThrow(); + assertEquals(BrokerState.CREATION_IN_PROGRESS, restored.getBrokerState()); + assertEquals("restored-container", restored.getContainerId()); + assertEquals("amqp://broker-host:5673", restored.getBrokerInstances().get(0).getEndpoints().get(0)); + assertEquals(BrokerState.CREATION_IN_PROGRESS, + brokers.getForAccount(ACCOUNT, starting).orElseThrow().getBrokerState()); + assertEquals(BrokerState.CREATION_FAILED, + brokers.getForAccount("111111111111", failed).orElseThrow().getBrokerState()); + Mockito.verify(manager, Mockito.times(2)).restoreContainer(Mockito.any()); + Mockito.verify(manager, Mockito.never()).restoreContainer( + Mockito.argThat(broker -> "b-failed".equals(broker.getBrokerId()))); + } + + /** + * A broker whose container ran under Docker's own hostname keeps its data under a node no new container can + * find, and its admin password was never stored, so it is reported failed rather than running without its users. + */ + @Test + void aBrokerFromBeforeFixedNodeNamesIsReportedFailed() { + RabbitMqManager manager = Mockito.mock(RabbitMqManager.class); + service = newService(false, manager); + String legacy = storedBroker(ACCOUNT, "us-east-1", "b-legacy", BrokerState.RUNNING, false); + + service.restorePersistedRuntime().join(); + + Broker broker = brokers.getForAccount(ACCOUNT, legacy).orElseThrow(); + assertEquals(BrokerState.CREATION_FAILED, broker.getBrokerState()); + assertTrue(broker.getBrokerInstances().isEmpty()); + Mockito.verify(manager, Mockito.never()).restoreContainer(Mockito.any()); + } + + /** A broker a crash left being deleted is deleted with its container and volume. */ + @Test + void aBrokerLeftBeingDeletedIsDeleted() { + RabbitMqManager manager = Mockito.mock(RabbitMqManager.class); + service = newService(false, manager); + String deleting = storedBroker(ACCOUNT, "us-east-1", "b-deleting", BrokerState.DELETION_IN_PROGRESS, true); + + service.restorePersistedRuntime().join(); + + assertTrue(brokers.getForAccount(ACCOUNT, deleting).isEmpty()); + Mockito.verify(manager).stopContainer(Mockito.argThat(broker -> "b-deleting".equals(broker.getBrokerId()))); + Mockito.verify(manager).removeBrokerStorage( + Mockito.argThat(broker -> "b-deleting".equals(broker.getBrokerId()))); + Mockito.verify(manager, Mockito.never()).restoreContainer(Mockito.any()); + } + + /** + * One broker whose container cannot be started is reported failed and leaves the others to restore; its failure + * is thrown at the end. + */ + @Test + void aBrokerThatCannotBeRestoredIsReportedFailedAndLeavesTheOthers() { + RabbitMqManager manager = Mockito.mock(RabbitMqManager.class); + IllegalStateException cause = new IllegalStateException("docker unavailable"); + Mockito.doThrow(cause).when(manager).restoreContainer( + Mockito.argThat(broker -> "b-first".equals(broker.getBrokerId()))); + service = newService(false, manager); + String first = storedBroker(ACCOUNT, "us-east-1", "b-first", BrokerState.RUNNING, true); + String second = storedBroker(ACCOUNT, "us-east-1", "b-second", BrokerState.RUNNING, true); + + CompletionException thrown = assertThrows(CompletionException.class, + () -> service.restorePersistedRuntime().join()); + + assertEquals("Could not restore Amazon MQ broker us-east-1::b-first of account " + ACCOUNT, + thrown.getCause().getMessage()); + assertSame(cause, thrown.getCause().getCause()); + Broker failedBroker = brokers.getForAccount(ACCOUNT, first).orElseThrow(); + assertEquals(BrokerState.CREATION_FAILED, failedBroker.getBrokerState()); + assertTrue(failedBroker.getBrokerInstances().isEmpty()); + Mockito.verify(manager).restoreContainer(Mockito.argThat(broker -> "b-second".equals(broker.getBrokerId()))); + assertEquals(BrokerState.CREATION_IN_PROGRESS, + brokers.getForAccount(ACCOUNT, second).orElseThrow().getBrokerState()); + } + + /** + * A broker whose container outlived Floci, as when Floci is killed, keeps that container when it answers on the + * console its record names, whatever its node name: its node holds the broker's data. + */ + @Test + void aBrokerWhoseContainerSurvivedKeepsIt() { + RabbitMqManager manager = Mockito.mock(RabbitMqManager.class); + when(manager.adoptRunningContainer(Mockito.any())).thenAnswer(adopt -> { + Broker candidate = adopt.getArgument(0); + assertEquals("http://broker-host:15672", candidate.getBrokerInstances().get(0).getConsoleURL()); + candidate.setContainerId("survivor"); + return true; + }); + service = newService(false, manager); + String legacy = storedBroker(ACCOUNT, "us-east-1", "b-legacy", BrokerState.RUNNING, false); + String fixed = storedBroker(ACCOUNT, "us-east-1", "b-fixed", BrokerState.RUNNING, true); + + service.restorePersistedRuntime().join(); + + for (String key : List.of(legacy, fixed)) { + Broker broker = brokers.getForAccount(ACCOUNT, key).orElseThrow(); + assertEquals(BrokerState.RUNNING, broker.getBrokerState()); + assertEquals("survivor", broker.getContainerId()); + assertEquals("http://broker-host:15672", broker.getBrokerInstances().get(0).getConsoleURL()); + } + Mockito.verify(manager, Mockito.never()).restoreContainer(Mockito.any()); + } + + /** + * A broker whose restore failed, as when Docker was not ready yet, ran under the fixed node name before, so the + * next start tries it again; a broker CreateBroker failed for never ran and stays failed. + */ + @Test + void aBrokerWhoseRestoreFailedIsTriedAgainAtTheNextStart() { + RabbitMqManager manager = Mockito.mock(RabbitMqManager.class); + service = newService(false, manager); + String restoreFailed = storedBroker(ACCOUNT, "us-east-1", "b-retry", BrokerState.CREATION_FAILED, true); + + service.restorePersistedRuntime().join(); + + assertEquals(BrokerState.CREATION_IN_PROGRESS, + brokers.getForAccount(ACCOUNT, restoreFailed).orElseThrow().getBrokerState()); + Mockito.verify(manager).restoreContainer(Mockito.argThat(broker -> "b-retry".equals(broker.getBrokerId()))); + } + + /** + * The poller's readiness answer counts only for the console it probed: a restore that cleared or changed the + * broker's endpoints meanwhile leaves it starting, and the poller probes the new console next. + */ + @Test + void aReadinessAnswerFromAConsoleTheBrokerNoLongerHasIsIgnored() { + RabbitMqManager manager = Mockito.mock(RabbitMqManager.class); + service = newService(false, manager); + String key = storedBroker(ACCOUNT, "us-east-1", "b-moved", BrokerState.CREATION_IN_PROGRESS, true); + Broker stored = brokers.getForAccount(ACCOUNT, key).orElseThrow(); + when(manager.isReady(Mockito.any())).thenAnswer(check -> { + stored.setBrokerInstances(List.of(new BrokerInstance("http://broker-host:15699", + List.of("amqp://broker-host:5699"), "broker-host"))); + return true; + }); + + service.pollReadiness(); + + assertEquals(BrokerState.CREATION_IN_PROGRESS, + brokers.getForAccount(ACCOUNT, key).orElseThrow().getBrokerState()); + } + + /** + * A shutdown during the restore stops it: brokers it has not started yet, and one whose start shutdown overtook, + * stay starting for the next start, rather than being reported failed. + */ + @Test + void aShutdownDuringTheRestoreLeavesItsBrokersStarting() { + RabbitMqManager stopped = Mockito.mock(RabbitMqManager.class); + when(stopped.isShuttingDown()).thenReturn(true); + service = newService(false, stopped); + String notReached = storedBroker(ACCOUNT, "us-east-1", "b-not-reached", BrokerState.RUNNING, true); + + service.restorePersistedRuntime().join(); + + Broker interrupted = brokers.getForAccount(ACCOUNT, notReached).orElseThrow(); + assertEquals(BrokerState.CREATION_IN_PROGRESS, interrupted.getBrokerState()); + // Its endpoints are kept, so the next start can still probe a container that outlived Floci on them. + assertEquals("http://broker-host:15672", interrupted.getBrokerInstances().get(0).getConsoleURL()); + Mockito.verify(stopped, Mockito.never()).restoreContainer(Mockito.any()); + RabbitMqManager nextStart = Mockito.mock(RabbitMqManager.class); + when(nextStart.adoptRunningContainer(Mockito.argThat(candidate -> + "http://broker-host:15672".equals(candidate.getBrokerInstances().get(0).getConsoleURL())))) + .thenReturn(true); + service = newService(false, nextStart); + service.restorePersistedRuntime().join(); + assertEquals(BrokerState.RUNNING, brokers.getForAccount(ACCOUNT, notReached).orElseThrow().getBrokerState()); + + RabbitMqManager overtaken = Mockito.mock(RabbitMqManager.class); + Mockito.doThrow(new RabbitMqManager.ShuttingDownException("b-overtaken")) + .when(overtaken).restoreContainer(Mockito.any()); + service = newService(false, overtaken); + String overtakenKey = storedBroker(ACCOUNT, "us-east-1", "b-overtaken", BrokerState.RUNNING, true); + brokers.deleteForAccount(ACCOUNT, notReached); + + service.restorePersistedRuntime().join(); + + assertEquals(BrokerState.CREATION_IN_PROGRESS, + brokers.getForAccount(ACCOUNT, overtakenKey).orElseThrow().getBrokerState()); + } + + /** A broker deleted while its new container starts has that container stopped and its volume removed. */ + @Test + void aBrokerDeletedWhileItsContainerStartsLosesThatContainer() { + RabbitMqManager manager = Mockito.mock(RabbitMqManager.class); + Mockito.doAnswer(start -> { + Broker broker = start.getArgument(0); + service.deleteBroker(broker.getBrokerId()); + broker.setContainerId("started-after-the-delete"); + return null; + }).when(manager).restoreContainer(Mockito.any()); + List stopped = new ArrayList<>(); + Mockito.doAnswer(stop -> stopped.add(((Broker) stop.getArgument(0)).getContainerId())) + .when(manager).stopContainer(Mockito.any()); + service = newService(false, manager); + storedBroker(ACCOUNT, "us-east-1", "b-raced", BrokerState.RUNNING, true); + + service.restorePersistedRuntime().join(); + + assertTrue(brokers.scanAllAccounts().isEmpty()); + // The delete stops what the record names; the restore then stops the container it started. + assertEquals(List.of("removed-on-shutdown", "started-after-the-delete"), stopped); + Mockito.verify(manager, Mockito.times(2)).removeBrokerStorage(Mockito.any()); + } + + /** + * The readiness poller leaves a broker alone while its restore runs, and reports it RUNNING once the restore has + * given it the new container's console and that console answers. + */ + @Test + void aRestoredBrokerTurnsRunningOnceItsNewConsoleAnswers() { + RabbitMqManager manager = Mockito.mock(RabbitMqManager.class); + when(manager.isReady(Mockito.any())).thenReturn(true); + Mockito.doAnswer(start -> { + Broker broker = start.getArgument(0); + broker.setContainerId("restored-container"); + broker.setBrokerInstances(List.of(new BrokerInstance("http://broker-host:15673", + List.of("amqp://broker-host:5673"), "broker-host"))); + service.pollReadiness(); + return null; + }).when(manager).restoreContainer(Mockito.any()); + service = newService(false, manager); + String key = storedBroker(ACCOUNT, "us-east-1", "b-quick", BrokerState.RUNNING, true); + + service.restorePersistedRuntime().join(); + assertEquals(BrokerState.CREATION_IN_PROGRESS, + brokers.getForAccount(ACCOUNT, key).orElseThrow().getBrokerState()); + service.pollReadiness(); + + Broker broker = brokers.getForAccount(ACCOUNT, key).orElseThrow(); + assertEquals(BrokerState.RUNNING, broker.getBrokerState()); + assertEquals("http://broker-host:15673", broker.getBrokerInstances().get(0).getConsoleURL()); + Mockito.verify(manager, Mockito.never()).stopContainer(Mockito.any()); + } + + @Test + void restoringLeavesMockBrokersAsTheyAre() { + RabbitMqManager manager = Mockito.mock(RabbitMqManager.class); + service = newService(true, manager); + String key = storedBroker(ACCOUNT, "us-east-1", "b-mock", BrokerState.RUNNING, false); + + service.restorePersistedRuntime().join(); + + assertEquals(BrokerState.RUNNING, brokers.getForAccount(ACCOUNT, key).orElseThrow().getBrokerState()); + Mockito.verifyNoInteractions(manager); + } + + /** Stores a broker in {@code account} and {@code region}, with a fixed node name or without one. */ + private String storedBroker(String account, String region, String brokerId, BrokerState state, + boolean fixedNodeName) { + Broker broker = new Broker(brokerId, "arn:aws:mq:" + region + ":" + account + ":broker:" + brokerId + ":" + + brokerId, brokerId, "RABBITMQ", "3.13", "SINGLE_INSTANCE", "mq.t3.micro"); + broker.setBrokerState(state); + broker.setAccountId(account); + broker.setContainerId("removed-on-shutdown"); + broker.setBrokerInstances(List.of(new BrokerInstance("http://broker-host:15672", + List.of("amqp://broker-host:5672"), "broker-host"))); + if (fixedNodeName) { + broker.setNodeName("rabbit@localhost"); + } + String key = AmazonMqService.brokerKey(region, brokerId); + brokers.putForAccount(account, key, broker); + return key; + } + private String startingBroker() { Broker starting = new Broker("b-starting", "arn:aws:mq:us-east-1:" + ACCOUNT + ":broker:starting:b-starting", "starting", "RABBITMQ", "3.13", "SINGLE_INSTANCE", "mq.t3.micro"); diff --git a/src/test/java/io/floci/aws/services/amazonmq/container/RabbitMqManagerTest.java b/src/test/java/io/floci/aws/services/amazonmq/container/RabbitMqManagerTest.java index feb04656d2..dcd6702b70 100644 --- a/src/test/java/io/floci/aws/services/amazonmq/container/RabbitMqManagerTest.java +++ b/src/test/java/io/floci/aws/services/amazonmq/container/RabbitMqManagerTest.java @@ -1,5 +1,7 @@ package io.floci.aws.services.amazonmq.container; +import com.github.dockerjava.api.model.Container; +import com.sun.net.httpserver.HttpServer; import io.floci.aws.config.EmulatorConfig; import io.floci.aws.core.common.RegionResolver; import io.floci.aws.core.common.docker.ContainerBuilder; @@ -7,20 +9,31 @@ import io.floci.aws.core.common.docker.ContainerDetector; import io.floci.aws.core.common.docker.ContainerLifecycleManager; import io.floci.aws.core.common.docker.ContainerLogStreamer; import io.floci.aws.core.common.docker.ContainerSpec; +import io.floci.aws.core.common.docker.ContainerStorageHelper; import io.floci.aws.core.common.docker.PortAllocator; import io.floci.aws.services.amazonmq.model.Broker; +import io.floci.aws.services.amazonmq.model.BrokerInstance; +import io.floci.aws.services.amazonmq.model.MqUser; import io.floci.aws.testing.ParallelLocks; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.parallel.ResourceLock; import org.mockito.Mockito; +import java.io.IOException; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.net.ServerSocket; import java.util.List; import java.util.Map; import java.util.Optional; +import java.util.OptionalInt; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; 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.anyString; import static org.mockito.ArgumentMatchers.eq; @@ -88,6 +101,272 @@ class RabbitMqManagerTest { "SINGLE_INSTANCE", "mq.t3.micro"); } + /** A manager over {@code portAllocator} whose containers answer on the given host ports. */ + private static RabbitMqManager startingManager(ContainerBuilder containerBuilder, PortAllocator portAllocator, + int amqpPort, int consolePort) { + ContainerLifecycleManager lifecycleManager = Mockito.mock(ContainerLifecycleManager.class); + when(lifecycleManager.createAndStart(any())).thenReturn( + new ContainerLifecycleManager.ContainerInfo("container-id", Map.of( + 5672, new ContainerLifecycleManager.EndpointInfo("localhost", amqpPort), + 15672, new ContainerLifecycleManager.EndpointInfo("localhost", consolePort)))); + return new RabbitMqManager(containerBuilder, lifecycleManager, Mockito.mock(ContainerLogStreamer.class), + Mockito.mock(ContainerDetector.class), portAllocator, configWithDefaultPortRanges(), regionResolver()); + } + + /** + * #5664: every broker container runs as one fixed node name, which names its data directory, so a later + * container on the volume finds the same node; the broker records it and the host ports it was published on. + */ + @Test + void aBrokerContainerRunsAsAFixedNodeName() { + ContainerBuilder containerBuilder = Mockito.mock(ContainerBuilder.class); + ContainerBuilder.Builder builder = selfReturningBuilder(containerBuilder); + PortAllocator portAllocator = Mockito.mock(PortAllocator.class); + when(portAllocator.allocate(5672, 5699)).thenReturn(5680); + when(portAllocator.allocate(15672, 15699)).thenReturn(15680); + Broker broker = broker("b-1"); + broker.setUsers(List.of(new MqUser("admin", "AdminPass123", true, null))); + + startingManager(containerBuilder, portAllocator, 5680, 15680).startContainer(broker); + + verify(builder).withEnv("RABBITMQ_NODENAME", "rabbit@localhost"); + verify(builder).withEnv("RABBITMQ_DEFAULT_USER", "admin"); + assertEquals("rabbit@localhost", broker.getNodeName()); + assertEquals(5680, broker.getAmqpHostPort()); + assertEquals(15680, broker.getConsoleHostPort()); + } + + /** + * A restored broker's node already holds its users, and its admin password was never stored: its container is + * started without seeding anyone, on the host ports it had. + */ + @Test + void aRestoredBrokerSeedsNoUserAndGetsItsHostPortsBack() { + ContainerBuilder containerBuilder = Mockito.mock(ContainerBuilder.class); + ContainerBuilder.Builder builder = selfReturningBuilder(containerBuilder); + PortAllocator portAllocator = Mockito.mock(PortAllocator.class); + when(portAllocator.allocateIfFree(5680)).thenReturn(OptionalInt.of(5680)); + when(portAllocator.allocateIfFree(15680)).thenReturn(OptionalInt.of(15680)); + Broker broker = restoredBroker(5680, 15680); + + startingManager(containerBuilder, portAllocator, 5680, 15680).restoreContainer(broker); + + verify(builder).withEnv("RABBITMQ_NODENAME", "rabbit@localhost"); + verify(builder, never()).withEnv(eq("RABBITMQ_DEFAULT_USER"), anyString()); + verify(builder, never()).withEnv(eq("RABBITMQ_DEFAULT_PASS"), anyString()); + verify(builder).withPortBinding(5672, 5680); + verify(builder).withPortBinding(15672, 15680); + verify(portAllocator, never()).allocate(Mockito.anyInt(), Mockito.anyInt()); + assertEquals("amqp://localhost:5680", broker.getBrokerInstances().get(0).getEndpoints().get(0)); + } + + /** A host port taken meanwhile, or outside today's range, is replaced by a new one. */ + @Test + void aRestoredBrokerGetsNewHostPortsForOnesTakenOrOutOfRange() { + ContainerBuilder containerBuilder = Mockito.mock(ContainerBuilder.class); + ContainerBuilder.Builder builder = selfReturningBuilder(containerBuilder); + PortAllocator portAllocator = Mockito.mock(PortAllocator.class); + when(portAllocator.allocateIfFree(5680)).thenReturn(OptionalInt.empty()); + when(portAllocator.allocate(5672, 5699)).thenReturn(5681); + when(portAllocator.allocate(15672, 15699)).thenReturn(15681); + Broker broker = restoredBroker(5680, 25000); + + startingManager(containerBuilder, portAllocator, 5681, 15681).restoreContainer(broker); + + verify(builder).withPortBinding(5672, 5681); + verify(builder).withPortBinding(15672, 15681); + verify(portAllocator, never()).allocateIfFree(25000); + assertEquals(5681, broker.getAmqpHostPort()); + assertEquals(15681, broker.getConsoleHostPort()); + } + + /** + * A restore runs outside any request, where the resolver answers the default account: the container's label and + * the log group take the account the broker belongs to. + */ + @Test + void aRestoredBrokerOfAnotherAccountIsLabelledAndLoggedInIt() { + ContainerBuilder containerBuilder = Mockito.mock(ContainerBuilder.class); + ContainerBuilder.Builder builder = selfReturningBuilder(containerBuilder); + PortAllocator portAllocator = Mockito.mock(PortAllocator.class); + when(portAllocator.allocateIfFree(Mockito.anyInt())).thenAnswer(free -> OptionalInt.of(free.getArgument(0))); + ContainerLifecycleManager lifecycleManager = Mockito.mock(ContainerLifecycleManager.class); + when(lifecycleManager.createAndStart(any())).thenReturn(new ContainerLifecycleManager.ContainerInfo( + "container-id", Map.of(5672, new ContainerLifecycleManager.EndpointInfo("localhost", 5680), + 15672, new ContainerLifecycleManager.EndpointInfo("localhost", 15680)))); + ContainerLogStreamer logStreamer = Mockito.mock(ContainerLogStreamer.class); + Broker broker = restoredBroker(5680, 15680); + broker.setAccountId("111111111111"); + broker.setBrokerArn("arn:aws:mq:eu-west-1:111111111111:broker:name:b-1"); + + new RabbitMqManager(containerBuilder, lifecycleManager, logStreamer, Mockito.mock(ContainerDetector.class), + portAllocator, configWithDefaultPortRanges(), regionResolver()).restoreContainer(broker); + + verify(builder).withLabels(Map.of("io.floci", "aws", "io.floci.service", "amazonmq", + "io.floci.resource-id", "b-1", "io.floci.account", "111111111111", "io.floci.region", "eu-west-1")); + verify(logStreamer).attachPolledForAccount(eq("111111111111"), eq("container-id"), anyString(), any(), + eq("eu-west-1"), anyString()); + } + + /** + * A container that started but could not be wired up is removed and its host ports handed back, and the broker + * records no node name, so a failed broker is not taken for one that ran. + */ + @Test + void aContainerThatCannotBeWiredUpIsRemoved() { + ContainerBuilder containerBuilder = Mockito.mock(ContainerBuilder.class); + selfReturningBuilder(containerBuilder); + PortAllocator portAllocator = Mockito.mock(PortAllocator.class); + when(portAllocator.allocate(5672, 5699)).thenReturn(5680); + when(portAllocator.allocate(15672, 15699)).thenReturn(15680); + ContainerLifecycleManager lifecycleManager = Mockito.mock(ContainerLifecycleManager.class); + when(lifecycleManager.createAndStart(any())).thenReturn(new ContainerLifecycleManager.ContainerInfo( + "container-id", Map.of(5672, new ContainerLifecycleManager.EndpointInfo("localhost", 5680), + 15672, new ContainerLifecycleManager.EndpointInfo("localhost", 15680)))); + ContainerLogStreamer logStreamer = Mockito.mock(ContainerLogStreamer.class); + when(logStreamer.attachPolledForAccount(any(), any(), any(), any(), any(), any())) + .thenThrow(new IllegalStateException("log group refused")); + RabbitMqManager manager = new RabbitMqManager(containerBuilder, lifecycleManager, logStreamer, + Mockito.mock(ContainerDetector.class), portAllocator, configWithDefaultPortRanges(), regionResolver()); + Broker broker = broker("b-1"); + + assertThrows(IllegalStateException.class, () -> manager.startContainer(broker)); + + verify(lifecycleManager).stopAndRemove("container-id", null); + verify(portAllocator).release(5680); + verify(portAllocator).release(15680); + assertNull(broker.getNodeName()); + assertNull(broker.getContainerId()); + manager.stopAll(); + verify(lifecycleManager, Mockito.times(1)).stopAndRemove(anyString(), any()); + } + + /** + * A container that outlived Floci is kept when it is running and answers on the console the broker's record + * names, and shutdown then removes it; one that is gone, stopped or not answering is not. + */ + @Test + void aRunningContainerAnsweringOnTheBrokersConsoleIsKept() throws Exception { + HttpServer console = HttpServer.create(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0), 0); + console.createContext("/", exchange -> { + exchange.sendResponseHeaders(200, -1); + exchange.close(); + }); + console.start(); + try { + ContainerLifecycleManager lifecycleManager = Mockito.mock(ContainerLifecycleManager.class); + Container running = Mockito.mock(Container.class); + when(running.getState()).thenReturn("running"); + when(running.getId()).thenReturn("survivor"); + Container stopped = Mockito.mock(Container.class); + when(stopped.getState()).thenReturn("exited"); + EmulatorConfig config = configWithDefaultPortRanges(); + when(lifecycleManager.findByName(ContainerStorageHelper.dockerName(config, "amazonmq-b-running"))) + .thenReturn(Optional.of(running)); + when(lifecycleManager.findByName(ContainerStorageHelper.dockerName(config, "amazonmq-b-stopped"))) + .thenReturn(Optional.of(stopped)); + Container silent = Mockito.mock(Container.class); + when(silent.getState()).thenReturn("running"); + when(silent.getId()).thenReturn("silent"); + when(lifecycleManager.findByName(ContainerStorageHelper.dockerName(config, "amazonmq-b-silent"))) + .thenReturn(Optional.of(silent)); + Container legacy = Mockito.mock(Container.class); + when(legacy.getState()).thenReturn("running"); + when(legacy.getId()).thenReturn("legacy-survivor"); + when(lifecycleManager.findByName(ContainerStorageHelper.legacyDockerName(config, + ContainerStorageHelper.dockerName(config, "amazonmq-b-legacy")))).thenReturn(Optional.of(legacy)); + RabbitMqManager manager = new RabbitMqManager(Mockito.mock(ContainerBuilder.class), lifecycleManager, + Mockito.mock(ContainerLogStreamer.class), Mockito.mock(ContainerDetector.class), + Mockito.mock(PortAllocator.class), config, regionResolver()); + String consoleUrl = "http://127.0.0.1:" + console.getAddress().getPort(); + + assertTrue(manager.adoptRunningContainer(brokerAnswering("b-running", consoleUrl))); + assertFalse(manager.adoptRunningContainer(brokerAnswering("b-stopped", consoleUrl))); + assertFalse(manager.adoptRunningContainer(brokerAnswering("b-gone", consoleUrl))); + assertFalse(manager.adoptRunningContainer(brokerAnswering("b-silent", "http://127.0.0.1:" + closedPort()))); + // A broker created before the floci-aws- prefix runs in a container of the old name. + assertTrue(manager.adoptRunningContainer(brokerAnswering("b-legacy", consoleUrl))); + + manager.stopAll(); + verify(lifecycleManager).stopAndRemove(eq("survivor"), any()); + verify(lifecycleManager).stopAndRemove(eq("legacy-survivor"), any()); + assertFalse(manager.adoptRunningContainer(brokerAnswering("b-running", consoleUrl)), + "nothing is adopted once shutdown removed the containers"); + } finally { + console.stop(0); + } + } + + private static int closedPort() throws IOException { + try (ServerSocket socket = new ServerSocket(0, 1, InetAddress.getLoopbackAddress())) { + return socket.getLocalPort(); + } + } + + /** Once shutdown has removed the containers, no broker container starts. */ + @Test + void noContainerStartsAfterShutdown() { + ContainerBuilder containerBuilder = Mockito.mock(ContainerBuilder.class); + selfReturningBuilder(containerBuilder); + ContainerLifecycleManager lifecycleManager = Mockito.mock(ContainerLifecycleManager.class); + RabbitMqManager manager = new RabbitMqManager(containerBuilder, lifecycleManager, + Mockito.mock(ContainerLogStreamer.class), Mockito.mock(ContainerDetector.class), + Mockito.mock(PortAllocator.class), configWithDefaultPortRanges(), regionResolver()); + + manager.stopAll(); + + assertThrows(RabbitMqManager.ShuttingDownException.class, + () -> manager.restoreContainer(restoredBroker(5680, 15680))); + verify(lifecycleManager, never()).createAndStart(any()); + } + + /** + * A start still running when shutdown removes the containers, as a restore's can be while its image pulls, + * removes its own container and hands its host ports back, rather than leave the container behind. + */ + @Test + void aStartShutdownOvertakesRemovesItsContainer() { + ContainerBuilder containerBuilder = Mockito.mock(ContainerBuilder.class); + selfReturningBuilder(containerBuilder); + PortAllocator portAllocator = Mockito.mock(PortAllocator.class); + when(portAllocator.allocateIfFree(Mockito.anyInt())).thenAnswer(free -> OptionalInt.of(free.getArgument(0))); + ContainerLifecycleManager lifecycleManager = Mockito.mock(ContainerLifecycleManager.class); + RabbitMqManager[] manager = new RabbitMqManager[1]; + when(lifecycleManager.createAndStart(any())).thenAnswer(create -> { + manager[0].stopAll(); + return new ContainerLifecycleManager.ContainerInfo("container-id", Map.of( + 5672, new ContainerLifecycleManager.EndpointInfo("localhost", 5680), + 15672, new ContainerLifecycleManager.EndpointInfo("localhost", 15680))); + }); + manager[0] = new RabbitMqManager(containerBuilder, lifecycleManager, Mockito.mock(ContainerLogStreamer.class), + Mockito.mock(ContainerDetector.class), portAllocator, configWithDefaultPortRanges(), regionResolver()); + + assertThrows(RabbitMqManager.ShuttingDownException.class, + () -> manager[0].restoreContainer(restoredBroker(5680, 15680))); + + verify(lifecycleManager).stopAndRemove("container-id", null); + verify(portAllocator).release(5680); + verify(portAllocator).release(15680); + manager[0].stopAll(); + verify(lifecycleManager, Mockito.times(1)).stopAndRemove(anyString(), any()); + } + + private Broker brokerAnswering(String brokerId, String consoleUrl) { + Broker broker = broker(brokerId); + broker.setBrokerInstances(List.of(new BrokerInstance(consoleUrl, List.of(), "127.0.0.1"))); + return broker; + } + + /** A broker reloaded from storage: its admin user has no password, and it had the given host ports. */ + private Broker restoredBroker(int amqpPort, int consolePort) { + Broker broker = broker("b-1"); + broker.setUsers(List.of(new MqUser("admin", null, true, null))); + broker.setNodeName("rabbit@localhost"); + broker.setAmqpHostPort(amqpPort); + broker.setConsoleHostPort(consolePort); + return broker; + } + @Test void startContainerLabelsContainerWithResourceIdentity() { EmulatorConfig config = configWithDefaultPortRanges(); @@ -190,8 +469,8 @@ class RabbitMqManagerTest { manager.startContainer(broker); assertEquals("/aws/amazonmq/broker/b-1/general", broker.generalLogGroup()); - verify(logStreamer).attachPolled(eq("container-id"), eq(broker.generalLogGroup()), - any(), any(), eq("amazonmq:b-1")); + verify(logStreamer).attachPolledForAccount(eq("000000000000"), eq("container-id"), + eq(broker.generalLogGroup()), any(), any(), eq("amazonmq:b-1")); } /** diff --git a/src/test/java/io/floci/aws/services/amazonmq/model/BrokerTest.java b/src/test/java/io/floci/aws/services/amazonmq/model/BrokerTest.java index 332c840a8a..773a1c5ae7 100644 --- a/src/test/java/io/floci/aws/services/amazonmq/model/BrokerTest.java +++ b/src/test/java/io/floci/aws/services/amazonmq/model/BrokerTest.java @@ -12,7 +12,7 @@ import static org.junit.jupiter.api.Assertions.assertNull; class BrokerTest { /** - * containerId / accountId / volumeId are internal bookkeeping but must survive a + * containerId / accountId / volumeId / nodeName / host ports are internal bookkeeping but must survive a * serialize -> deserialize round-trip so the broker stays manageable after an * emulator restart (volume cleanup, container teardown, account-aware routing). * They are kept out of the API by the controller's explicit DescribeBroker @@ -26,12 +26,18 @@ class BrokerTest { broker.setContainerId("container-xyz"); broker.setAccountId("000000000000"); broker.setVolumeId("a1b2c3"); + broker.setNodeName("rabbit@localhost"); + broker.setAmqpHostPort(5680); + broker.setConsoleHostPort(15680); Broker roundTripped = mapper.readValue(mapper.writeValueAsString(broker), Broker.class); assertEquals("container-xyz", roundTripped.getContainerId()); assertEquals("000000000000", roundTripped.getAccountId()); assertEquals("a1b2c3", roundTripped.getVolumeId()); + assertEquals("rabbit@localhost", roundTripped.getNodeName()); + assertEquals(5680, roundTripped.getAmqpHostPort()); + assertEquals(15680, roundTripped.getConsoleHostPort()); } @Test