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

@@ -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();
@@ -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.
*
* <p>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<String, String> 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<String> 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);
}
}
@@ -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<String> 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");
@@ -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"));
}
/**
@@ -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