mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(mq): scope brokers by account and Region (#8433)
* fix(mq): scope brokers by account and Region * fix(mq): write a ready broker back under the account and key it is stored under * test(mq): check broker Regions over HTTP in an account of its own * fix(mq): check a broker's name and store the broker under one lock * fix(mq): keep a broker name unique across the account's Regions * refactor(mq): derive a broker's Region in one place * test(mq): race two broker creates on the shared parked-store helper * refactor(mq): run the readiness poller's pass from a method tests can call * test(mq): check the error type of each refusal from another Region * test(mq): run the other Region's refusals through one loop * refactor(storage): name the all-accounts migration like its neighbours * docs(mq): say that brokers are Regional and names unique in the account
This commit is contained in:
1 parent
adfe173764
commit
e9f842765d
11 files changed
+424
-140
No files matched your search
@@ -10,6 +10,10 @@ management console work against the published endpoints.
|
||||
Only the **RabbitMQ** engine and the `SINGLE_INSTANCE` deployment mode are supported;
|
||||
`CreateBroker` rejects `ACTIVEMQ` and the multi-AZ deployment modes.
|
||||
|
||||
Brokers are Regional, as on AWS: a broker is listed, described, rebooted and deleted only in the
|
||||
Region it was created in. Its name is unique in the account, across its Regions, so `CreateBroker`
|
||||
refuses a name another Region of the account already uses with a `ConflictException`.
|
||||
|
||||
## Supported Actions
|
||||
|
||||
| Action | Description |
|
||||
|
||||
@@ -15,6 +15,7 @@ import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.function.BiFunction;
|
||||
import java.util.function.BiPredicate;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Predicate;
|
||||
import java.util.stream.Collectors;
|
||||
@@ -219,9 +220,8 @@ public class AccountAwareStorageBackend<V> implements StorageBackend<String, V>
|
||||
public List<AccountEntry<V>> scanAllAccountEntries(Predicate<String> keyFilter) {
|
||||
List<AccountEntry<V>> result = new ArrayList<>();
|
||||
for (String rawKey : delegate.keys()) {
|
||||
boolean hasAccountPrefix = hasAccountPrefix(rawKey);
|
||||
String accountId = hasAccountPrefix ? rawKey.substring(0, 12) : defaultAccountId;
|
||||
String logicalKey = hasAccountPrefix ? rawKey.substring(13) : rawKey;
|
||||
String accountId = ownerOf(rawKey);
|
||||
String logicalKey = hasAccountPrefix(rawKey) ? rawKey.substring(13) : rawKey;
|
||||
if (!keyFilter.test(logicalKey)) {
|
||||
continue;
|
||||
}
|
||||
@@ -244,6 +244,34 @@ public class AccountAwareStorageBackend<V> implements StorageBackend<String, V>
|
||||
(ignored, value) -> destinationKey.apply(value), legacyOwner);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@link #migrateLegacyEntries(String, Predicate, Function, Predicate)} in every account that
|
||||
* holds an entry here, an unprefixed entry counting as the default account's, moving every legacy
|
||||
* entry. For a store moving every record onto new keys at startup, when no request names an account.
|
||||
*/
|
||||
public synchronized void migrateLegacyEntriesInAllAccounts(
|
||||
Predicate<String> legacyKeyFilter,
|
||||
Function<V, String> destinationKey) {
|
||||
migrateLegacyEntriesInAllAccounts(legacyKeyFilter, destinationKey, (accountId, value) -> true);
|
||||
}
|
||||
|
||||
/**
|
||||
* As above; only the legacy entries {@code legacyOwner} accepts, given the account holding each.
|
||||
*/
|
||||
public synchronized void migrateLegacyEntriesInAllAccounts(
|
||||
Predicate<String> legacyKeyFilter,
|
||||
Function<V, String> destinationKey,
|
||||
BiPredicate<String, V> legacyOwner) {
|
||||
Set<String> accounts = new LinkedHashSet<>();
|
||||
for (String rawKey : delegate.keys()) {
|
||||
accounts.add(ownerOf(rawKey));
|
||||
}
|
||||
for (String accountId : accounts) {
|
||||
migrateLegacyEntries(accountId, legacyKeyFilter, destinationKey,
|
||||
value -> legacyOwner.test(accountId, value));
|
||||
}
|
||||
}
|
||||
|
||||
private synchronized void migrateLegacyEntries(
|
||||
String accountId,
|
||||
Predicate<String> legacyKeyFilter,
|
||||
@@ -251,8 +279,7 @@ public class AccountAwareStorageBackend<V> implements StorageBackend<String, V>
|
||||
Predicate<V> legacyOwner) {
|
||||
for (String rawKey : new ArrayList<>(delegate.keys())) {
|
||||
boolean prefixed = hasAccountPrefix(rawKey);
|
||||
String owner = prefixed ? rawKey.substring(0, 12) : defaultAccountId;
|
||||
if (!accountId.equals(owner)) {
|
||||
if (!accountId.equals(ownerOf(rawKey))) {
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -700,6 +727,11 @@ public class AccountAwareStorageBackend<V> implements StorageBackend<String, V>
|
||||
return prefix() + "/" + key;
|
||||
}
|
||||
|
||||
/** The account owning {@code rawKey}: its account prefix, or the default account for an unprefixed key. */
|
||||
private String ownerOf(String rawKey) {
|
||||
return hasAccountPrefix(rawKey) ? rawKey.substring(0, 12) : defaultAccountId;
|
||||
}
|
||||
|
||||
/** Whether {@code key} starts with a 12-digit account id and a slash, as account-scoped keys do. */
|
||||
public static boolean hasAccountPrefix(String key) {
|
||||
if (key.length() < 13 || key.charAt(12) != '/') {
|
||||
|
||||
@@ -5,12 +5,13 @@ import io.floci.aws.config.EmulatorConfig;
|
||||
import io.floci.aws.core.common.AwsArnUtils;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
import io.floci.aws.core.common.StripedLocks;
|
||||
import io.floci.aws.core.common.docker.ContainerStorageHelper;
|
||||
import io.floci.aws.core.resource.ExplorerResource;
|
||||
import io.floci.aws.core.resource.ResourceProvider;
|
||||
import io.floci.aws.core.resource.SupportedResourceType;
|
||||
import io.floci.aws.core.storage.AccountAwareStorageBackend;
|
||||
import io.floci.aws.core.storage.StorageBackend;
|
||||
import io.floci.aws.core.storage.AccountAwareStorageBackend.AccountEntry;
|
||||
import io.floci.aws.core.storage.StorageFactory;
|
||||
import io.floci.aws.services.amazonmq.container.RabbitMqManager;
|
||||
import io.floci.aws.services.amazonmq.model.Broker;
|
||||
@@ -42,11 +43,14 @@ public class AmazonMqService implements ResourceProvider {
|
||||
private static final String ENGINE_RABBITMQ = "RABBITMQ";
|
||||
private static final String DEFAULT_ENGINE_VERSION = "3.13";
|
||||
private static final String DEPLOYMENT_SINGLE_INSTANCE = "SINGLE_INSTANCE";
|
||||
private static final String KEY_SEPARATOR = "::";
|
||||
|
||||
private final StorageBackend<String, Broker> storage;
|
||||
/** Brokers by {@code region::brokerId}, in their owner's account partition: brokers are Regional. */
|
||||
private final AccountAwareStorageBackend<Broker> storage;
|
||||
private final EmulatorConfig config;
|
||||
private final RegionResolver regionResolver;
|
||||
private final RabbitMqManager rabbitMqManager;
|
||||
private final StripedLocks brokerLocks = new StripedLocks(256);
|
||||
private final ScheduledExecutorService poller = Executors.newSingleThreadScheduledExecutor();
|
||||
|
||||
@Inject
|
||||
@@ -61,6 +65,7 @@ public class AmazonMqService implements ResourceProvider {
|
||||
|
||||
@PostConstruct
|
||||
public void init() {
|
||||
migrateLegacyKeys();
|
||||
startReadinessPoller();
|
||||
}
|
||||
|
||||
@@ -114,75 +119,83 @@ public class AmazonMqService implements ResourceProvider {
|
||||
}
|
||||
validateUserPassword(admin.getPassword());
|
||||
|
||||
if (storage.scan(k -> true).stream().anyMatch(b -> name.equals(b.getBrokerName()))) {
|
||||
throw new AwsException("ConflictException", "Broker already exists: " + name, 409);
|
||||
}
|
||||
|
||||
String brokerId = "b-" + UUID.randomUUID();
|
||||
String region = regionResolver.getRegion();
|
||||
String accountId = regionResolver.getAccountId();
|
||||
String brokerArn = AwsArnUtils.Arn.of("mq", regionResolver.getRegion(), accountId,
|
||||
"broker:" + name + ":" + brokerId).toString();
|
||||
String engineVersion = (params.engineVersion() == null || params.engineVersion().isBlank())
|
||||
? DEFAULT_ENGINE_VERSION : params.engineVersion();
|
||||
|
||||
Broker broker = new Broker(brokerId, brokerArn, name, ENGINE_RABBITMQ,
|
||||
engineVersion, deploymentMode, params.hostInstanceType());
|
||||
broker.setAccountId(accountId);
|
||||
broker.setVolumeId(String.format("%06x", new SecureRandom().nextInt(0xFFFFFF)));
|
||||
// Stamp the volume name now, with the current prefix, so it is persisted rather than
|
||||
// recomputed later. Only records predating this field fall back to the legacy name.
|
||||
broker.setDockerVolumeName(ContainerStorageHelper.resourceName(
|
||||
config, "amazonmq", broker.getVolumeId(), broker.getBrokerId()));
|
||||
broker.setPubliclyAccessible(params.publiclyAccessible());
|
||||
broker.setAutoMinorVersionUpgrade(params.autoMinorVersionUpgrade());
|
||||
if (params.users() != null) {
|
||||
broker.setUsers(new ArrayList<>(params.users()));
|
||||
}
|
||||
if (params.tags() != null) {
|
||||
broker.setTags(new HashMap<>(params.tags()));
|
||||
}
|
||||
broker.setSecurityGroups(params.securityGroups());
|
||||
broker.setSubnetIds(params.subnetIds());
|
||||
broker.setLogs(params.logs());
|
||||
broker.setMaintenanceWindowStartTime(params.maintenanceWindowStartTime());
|
||||
broker.setStorageType(params.storageType());
|
||||
broker.setAuthenticationStrategy(params.authenticationStrategy());
|
||||
broker.setEncryptionOptions(params.encryptionOptions());
|
||||
broker.setConfiguration(params.configuration());
|
||||
|
||||
if (config.services().amazonmq().mock()) {
|
||||
// No backing container: come up immediately with synthetic endpoints.
|
||||
applyLocalEndpoints(broker);
|
||||
broker.setBrokerState(BrokerState.RUNNING);
|
||||
} else {
|
||||
try {
|
||||
// Start the container; the broker stays CREATION_IN_PROGRESS until
|
||||
// the readiness poller observes the management API answering.
|
||||
rabbitMqManager.startContainer(broker);
|
||||
} catch (RuntimeException e) {
|
||||
broker.setBrokerState(BrokerState.CREATION_FAILED);
|
||||
storage.put(brokerId, broker);
|
||||
// Keep the cause in the logs; don't leak internal details (or a null
|
||||
// message) into the AWS error envelope returned to the client.
|
||||
LOG.errorv(e, "Failed to provision broker {0} ({1})", name, brokerId);
|
||||
throw new AwsException("InternalServerErrorException",
|
||||
"Failed to provision broker " + name, 500);
|
||||
// A broker name is unique in the account, across its Regions, as the CreateBroker reference documents.
|
||||
// The name check and the store hold one lock for the name in its account, so two creates of one name
|
||||
// can't both find it free.
|
||||
synchronized (brokerLocks.lockFor(accountId + ":" + name)) {
|
||||
if (storage.scan(key -> true).stream().anyMatch(b -> name.equals(b.getBrokerName()))) {
|
||||
throw new AwsException("ConflictException", "Broker already exists: " + name, 409);
|
||||
}
|
||||
}
|
||||
|
||||
storage.put(brokerId, broker);
|
||||
LOG.infov("Created Amazon MQ broker {0} ({1})", name, brokerId);
|
||||
return broker;
|
||||
String brokerId = "b-" + UUID.randomUUID();
|
||||
String brokerArn = AwsArnUtils.Arn.of("mq", region, accountId,
|
||||
"broker:" + name + ":" + brokerId).toString();
|
||||
String engineVersion = (params.engineVersion() == null || params.engineVersion().isBlank())
|
||||
? DEFAULT_ENGINE_VERSION : params.engineVersion();
|
||||
|
||||
Broker broker = new Broker(brokerId, brokerArn, name, ENGINE_RABBITMQ,
|
||||
engineVersion, deploymentMode, params.hostInstanceType());
|
||||
broker.setAccountId(accountId);
|
||||
broker.setVolumeId(String.format("%06x", new SecureRandom().nextInt(0xFFFFFF)));
|
||||
// Stamp the volume name now, with the current prefix, so it is persisted rather than
|
||||
// recomputed later. Only records predating this field fall back to the legacy name.
|
||||
broker.setDockerVolumeName(ContainerStorageHelper.resourceName(
|
||||
config, "amazonmq", broker.getVolumeId(), broker.getBrokerId()));
|
||||
broker.setPubliclyAccessible(params.publiclyAccessible());
|
||||
broker.setAutoMinorVersionUpgrade(params.autoMinorVersionUpgrade());
|
||||
if (params.users() != null) {
|
||||
broker.setUsers(new ArrayList<>(params.users()));
|
||||
}
|
||||
if (params.tags() != null) {
|
||||
broker.setTags(new HashMap<>(params.tags()));
|
||||
}
|
||||
broker.setSecurityGroups(params.securityGroups());
|
||||
broker.setSubnetIds(params.subnetIds());
|
||||
broker.setLogs(params.logs());
|
||||
broker.setMaintenanceWindowStartTime(params.maintenanceWindowStartTime());
|
||||
broker.setStorageType(params.storageType());
|
||||
broker.setAuthenticationStrategy(params.authenticationStrategy());
|
||||
broker.setEncryptionOptions(params.encryptionOptions());
|
||||
broker.setConfiguration(params.configuration());
|
||||
|
||||
if (config.services().amazonmq().mock()) {
|
||||
// No backing container: come up immediately with synthetic endpoints.
|
||||
applyLocalEndpoints(broker);
|
||||
broker.setBrokerState(BrokerState.RUNNING);
|
||||
} else {
|
||||
try {
|
||||
// Start the container; the broker stays CREATION_IN_PROGRESS until
|
||||
// the readiness poller observes the management API answering.
|
||||
rabbitMqManager.startContainer(broker);
|
||||
} catch (RuntimeException e) {
|
||||
broker.setBrokerState(BrokerState.CREATION_FAILED);
|
||||
storage.put(brokerKey(region, brokerId), broker);
|
||||
// Keep the cause in the logs; don't leak internal details (or a null
|
||||
// message) into the AWS error envelope returned to the client.
|
||||
LOG.errorv(e, "Failed to provision broker {0} ({1})", name, brokerId);
|
||||
throw new AwsException("InternalServerErrorException",
|
||||
"Failed to provision broker " + name, 500);
|
||||
}
|
||||
}
|
||||
|
||||
storage.put(brokerKey(region, brokerId), broker);
|
||||
LOG.infov("Created Amazon MQ broker {0} ({1})", name, brokerId);
|
||||
return broker;
|
||||
}
|
||||
}
|
||||
|
||||
public Broker describeBroker(String brokerId) {
|
||||
return storage.get(brokerId)
|
||||
return storage.get(brokerKey(regionResolver.getRegion(), brokerId))
|
||||
.orElseThrow(() -> new AwsException("NotFoundException",
|
||||
"Broker not found: " + brokerId, 404));
|
||||
}
|
||||
|
||||
/** The calling account's brokers in the request's Region. */
|
||||
public List<Broker> listBrokers() {
|
||||
return storage.scan(k -> true);
|
||||
String prefix = regionResolver.getRegion() + KEY_SEPARATOR;
|
||||
return storage.scan(key -> key.startsWith(prefix));
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -215,7 +228,7 @@ public class AmazonMqService implements ResourceProvider {
|
||||
rabbitMqManager.stopContainer(broker);
|
||||
rabbitMqManager.removeBrokerStorage(broker);
|
||||
}
|
||||
storage.delete(brokerId);
|
||||
storage.delete(brokerKey(regionResolver.getRegion(), brokerId));
|
||||
LOG.infov("Deleted Amazon MQ broker {0}", brokerId);
|
||||
}
|
||||
|
||||
@@ -244,38 +257,48 @@ public class AmazonMqService implements ResourceProvider {
|
||||
}
|
||||
|
||||
private void startReadinessPoller() {
|
||||
poller.scheduleAtFixedRate(() -> {
|
||||
try {
|
||||
if (config.services().amazonmq().mock()) {
|
||||
return;
|
||||
}
|
||||
for (Broker broker : allBrokers()) {
|
||||
if (broker.getBrokerState() == BrokerState.CREATION_IN_PROGRESS
|
||||
&& rabbitMqManager.isReady(broker)) {
|
||||
LOG.infov("Amazon MQ broker {0} is now RUNNING", broker.getBrokerName());
|
||||
broker.setBrokerState(BrokerState.RUNNING);
|
||||
putBroker(broker);
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
LOG.error("Error in Amazon MQ readiness poller", e);
|
||||
poller.scheduleAtFixedRate(this::pollReadiness, 1, 2, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
/** One pass of the readiness poller: marks each starting broker whose container answers {@code RUNNING}. */
|
||||
void pollReadiness() {
|
||||
try {
|
||||
if (config.services().amazonmq().mock()) {
|
||||
return;
|
||||
}
|
||||
}, 1, 2, TimeUnit.SECONDS);
|
||||
// Every account's brokers, each written back under the account and key it is stored
|
||||
// under: the poller has no request context, so a plain put would land in the default
|
||||
// account. Brokers stored under a bare id have moved to their Region's key at startup.
|
||||
for (AccountEntry<Broker> entry : storage.scanAllAccountEntries(key -> true)) {
|
||||
Broker broker = entry.value();
|
||||
if (broker.getBrokerState() == BrokerState.CREATION_IN_PROGRESS
|
||||
&& rabbitMqManager.isReady(broker)) {
|
||||
LOG.infov("Amazon MQ broker {0} is now RUNNING", broker.getBrokerName());
|
||||
broker.setBrokerState(BrokerState.RUNNING);
|
||||
storage.putForAccount(entry.accountId(), entry.key(), broker);
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
LOG.error("Error in Amazon MQ readiness poller", e);
|
||||
}
|
||||
}
|
||||
|
||||
private List<Broker> allBrokers() {
|
||||
if (storage instanceof AccountAwareStorageBackend<Broker> aware) {
|
||||
return aware.scanAllAccounts();
|
||||
}
|
||||
return storage.scan(k -> true);
|
||||
static String brokerKey(String region, String brokerId) {
|
||||
return region + KEY_SEPARATOR + brokerId;
|
||||
}
|
||||
|
||||
private void putBroker(Broker broker) {
|
||||
if (broker.getAccountId() != null && storage instanceof AccountAwareStorageBackend<Broker> aware) {
|
||||
aware.putForAccount(broker.getAccountId(), broker.getBrokerId(), broker);
|
||||
} else {
|
||||
storage.put(broker.getBrokerId(), broker);
|
||||
}
|
||||
/** A broker's key in its own Region, which its ARN has always named. */
|
||||
private String brokerKey(Broker broker) {
|
||||
return brokerKey(broker.region(regionResolver.getDefaultRegion()), broker.getBrokerId());
|
||||
}
|
||||
|
||||
/**
|
||||
* Moves brokers persisted before they were keyed by Region, in every account, from the bare
|
||||
* broker id onto the Region-scoped key, in the Region their ARN names. Each stays in the
|
||||
* account partition that stored it.
|
||||
*/
|
||||
private void migrateLegacyKeys() {
|
||||
storage.migrateLegacyEntriesInAllAccounts(key -> !key.contains(KEY_SEPARATOR), this::brokerKey);
|
||||
}
|
||||
|
||||
// --- Users ---
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
package io.floci.aws.services.amazonmq.container;
|
||||
|
||||
import io.floci.aws.config.EmulatorConfig;
|
||||
import io.floci.aws.core.common.AwsArnUtils;
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
import io.floci.aws.core.common.docker.ContainerBuilder;
|
||||
import io.floci.aws.core.common.docker.ContainerDetector;
|
||||
@@ -184,9 +183,9 @@ public class RabbitMqManager {
|
||||
}
|
||||
}
|
||||
|
||||
/** The region in the broker's ARN; a broker recorded without one counts as the default region's. */
|
||||
/** The broker's Region, {@link Broker#region} with the configured default Region. */
|
||||
private String brokerRegion(Broker broker) {
|
||||
return AwsArnUtils.regionOrDefault(broker.getBrokerArn(), regionResolver.getDefaultRegion());
|
||||
return broker.region(regionResolver.getDefaultRegion());
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -2,6 +2,7 @@ package io.floci.aws.services.amazonmq.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import io.floci.aws.core.common.AwsArnUtils;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
import java.time.Instant;
|
||||
@@ -138,6 +139,12 @@ public class Broker {
|
||||
public String getBrokerArn() { return brokerArn; }
|
||||
public void setBrokerArn(String brokerArn) { this.brokerArn = brokerArn; }
|
||||
|
||||
/**
|
||||
* The Region the broker's ARN names; a broker recorded without one counts as {@code defaultRegion}'s.
|
||||
* Not a getter, so Jackson neither persists nor returns it.
|
||||
*/
|
||||
public String region(String defaultRegion) { return AwsArnUtils.regionOrDefault(brokerArn, defaultRegion); }
|
||||
|
||||
public String getBrokerName() { return brokerName; }
|
||||
public void setBrokerName(String brokerName) { this.brokerName = brokerName; }
|
||||
|
||||
|
||||
@@ -665,14 +665,7 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun
|
||||
}
|
||||
return;
|
||||
}
|
||||
Set<String> accounts = new LinkedHashSet<>();
|
||||
for (String rawKey : aware.scanAllAccountsWithRawKeys().keySet()) {
|
||||
accounts.add(AccountAwareStorageBackend.hasAccountPrefix(rawKey)
|
||||
? rawKey.substring(0, 12) : config.defaultAccountId());
|
||||
}
|
||||
for (String accountId : accounts) {
|
||||
aware.migrateLegacyEntries(accountId, key -> !key.contains(KEY_SEPARATOR), destinationKey, value -> true);
|
||||
}
|
||||
aware.migrateLegacyEntriesInAllAccounts(key -> !key.contains(KEY_SEPARATOR), destinationKey);
|
||||
}
|
||||
|
||||
private static String randomHex(int len) {
|
||||
|
||||
@@ -33,7 +33,6 @@ import java.security.SecureRandom;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
@@ -627,13 +626,8 @@ public class OpenSearchService implements ResourceProvider {
|
||||
* own region; a record whose ARN cannot be parsed is left where it is.
|
||||
*/
|
||||
private void migrateLegacyDomainKeys() {
|
||||
Set<String> accounts = new LinkedHashSet<>();
|
||||
for (String rawKey : domainStore.scanAllAccountsWithRawKeys().keySet()) {
|
||||
accounts.add(AccountAwareStorageBackend.hasAccountPrefix(rawKey)
|
||||
? rawKey.substring(0, 12)
|
||||
: regionResolver.getDefaultAccountId());
|
||||
}
|
||||
accounts.forEach(this::migrateLegacyDomainKeys);
|
||||
domainStore.migrateLegacyEntriesInAllAccounts(key -> !key.contains("::"),
|
||||
this::legacyDomainDestinationKey, (accountId, domain) -> ownsAccount(domain, accountId));
|
||||
}
|
||||
|
||||
private void migrateLegacyDomainKeys(String accountId) {
|
||||
|
||||
@@ -4,6 +4,7 @@ import io.floci.aws.core.common.RequestContext;
|
||||
import jakarta.enterprise.inject.Instance;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
@@ -363,6 +364,48 @@ class AccountAwareStorageBackendTest {
|
||||
assertFalse(raw.get("111111111111/legacy").isPresent());
|
||||
}
|
||||
|
||||
/**
|
||||
* Every account's legacy entries move within that account, an unprefixed one counting as the default's,
|
||||
* and the owner check is handed the account holding each legacy entry.
|
||||
*/
|
||||
@Test
|
||||
void migrateLegacyEntriesInAllAccountsMovesEachWithinItsOwnAccount() {
|
||||
InMemoryStorage<String, String> raw = new InMemoryStorage<>();
|
||||
raw.put("gen0", "default-owned");
|
||||
raw.put("123456789012/gen1", "account-owned");
|
||||
raw.put("123456789012/kept", "not-owned");
|
||||
raw.put("123456789012/us-east-1::current", "current");
|
||||
AccountAwareStorageBackend<String> storage =
|
||||
new AccountAwareStorageBackend<>(raw, null, "000000000000");
|
||||
List<String> ownerChecks = new ArrayList<>();
|
||||
|
||||
storage.migrateLegacyEntriesInAllAccounts(key -> !key.contains("::"), value -> "us-east-1::" + value,
|
||||
(account, value) -> {
|
||||
ownerChecks.add(account + " " + value);
|
||||
return !value.equals("not-owned");
|
||||
});
|
||||
|
||||
assertEquals(List.of("000000000000 default-owned", "123456789012 account-owned", "123456789012 not-owned"),
|
||||
ownerChecks.stream().sorted().toList());
|
||||
assertEquals(Set.of("000000000000/us-east-1::default-owned", "123456789012/us-east-1::account-owned",
|
||||
"123456789012/kept", "123456789012/us-east-1::current"), Set.copyOf(raw.keys()));
|
||||
}
|
||||
|
||||
/** Without an owner check, every account's legacy entries move. */
|
||||
@Test
|
||||
void migrateLegacyEntriesInAllAccountsWithoutAnOwnerCheckMovesEveryLegacyEntry() {
|
||||
InMemoryStorage<String, String> raw = new InMemoryStorage<>();
|
||||
raw.put("gen0", "default");
|
||||
raw.put("123456789012/gen1", "account");
|
||||
AccountAwareStorageBackend<String> storage =
|
||||
new AccountAwareStorageBackend<>(raw, null, "000000000000");
|
||||
|
||||
storage.migrateLegacyEntriesInAllAccounts(key -> !key.contains("::"), value -> "us-east-1::" + value);
|
||||
|
||||
assertEquals(Set.of("000000000000/us-east-1::default", "123456789012/us-east-1::account"),
|
||||
Set.copyOf(raw.keys()));
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code get} and {@code getForAccountMigratingLegacy} both migrate a pre-multi-account entry, and
|
||||
* both delete the legacy key once they have copied it. Unless they hold the same monitor, two readers
|
||||
|
||||
+82
-4
@@ -1,10 +1,18 @@
|
||||
package io.floci.aws.services.amazonmq;
|
||||
|
||||
import io.floci.aws.testing.PartitionCleanup;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.response.Response;
|
||||
import io.restassured.response.ValidatableResponse;
|
||||
import io.restassured.specification.RequestSpecification;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
import java.util.function.Function;
|
||||
|
||||
import static io.floci.aws.testing.EnforcementFixtures.auth;
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.hasItem;
|
||||
@@ -16,8 +24,34 @@ import static org.hamcrest.Matchers.startsWith;
|
||||
@QuarkusTest
|
||||
class AmazonMqControllerIntegrationTest {
|
||||
|
||||
private static final AtomicLong ACCOUNTS = new AtomicLong(731300000000L);
|
||||
|
||||
@RegisterExtension
|
||||
final PartitionCleanup cleanup = new PartitionCleanup();
|
||||
|
||||
private String createRabbitBroker(String name) {
|
||||
return given()
|
||||
return createRabbitBroker(given(), name);
|
||||
}
|
||||
|
||||
/** A broker created for {@code account} in {@code region}, deleted after the test unless the test did. */
|
||||
private String createRabbitBroker(String account, String region, String name) {
|
||||
String brokerId = createRabbitBroker(mq(account, region), name);
|
||||
cleanup.register(() -> mq(account, region).when().delete("/v1/brokers/{id}", brokerId));
|
||||
return brokerId;
|
||||
}
|
||||
|
||||
private static RequestSpecification mq(String account, String region) {
|
||||
return given().header("Authorization", auth(account, region, "mq"));
|
||||
}
|
||||
|
||||
private static String createRabbitBroker(RequestSpecification request, String name) {
|
||||
return postRabbitBroker(request, name)
|
||||
.statusCode(200)
|
||||
.extract().path("brokerId");
|
||||
}
|
||||
|
||||
private static ValidatableResponse postRabbitBroker(RequestSpecification request, String name) {
|
||||
return request
|
||||
.contentType("application/json")
|
||||
.body("""
|
||||
{"brokerName": "%s", "engineType": "RABBITMQ",
|
||||
@@ -27,9 +61,7 @@ class AmazonMqControllerIntegrationTest {
|
||||
""".formatted(name))
|
||||
.when()
|
||||
.post("/v1/brokers")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.extract().path("brokerId");
|
||||
.then();
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -202,4 +234,50 @@ class AmazonMqControllerIntegrationTest {
|
||||
.then()
|
||||
.statusCode(400);
|
||||
}
|
||||
|
||||
/**
|
||||
* Brokers are Regional: another Region of the account neither lists, describes, reboots nor deletes
|
||||
* one, nor describes its shared resources. Its name is unique in the account, so another Region refuses
|
||||
* it too. The test works in an account of its own, so each listing holds only its brokers.
|
||||
*/
|
||||
@Test
|
||||
void aBrokerIsSeenOnlyInTheRegionItWasCreatedIn() {
|
||||
String account = Long.toString(ACCOUNTS.incrementAndGet());
|
||||
String inIreland = createRabbitBroker(account, "eu-west-1", "it-regional");
|
||||
|
||||
mq(account, "us-east-1")
|
||||
.when()
|
||||
.get("/v1/brokers")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("brokerSummaries.brokerId", equalTo(List.of()));
|
||||
for (Function<RequestSpecification, Response> call : List.<Function<RequestSpecification, Response>>of(
|
||||
request -> request.get("/v1/brokers/{id}", inIreland),
|
||||
request -> request.get("/v1/brokers/{id}/shared-resources", inIreland),
|
||||
request -> request.contentType("application/json").post("/v1/brokers/{id}/reboot", inIreland),
|
||||
request -> request.delete("/v1/brokers/{id}", inIreland))) {
|
||||
call.apply(mq(account, "us-east-1"))
|
||||
.then()
|
||||
.statusCode(404)
|
||||
.body("__type", equalTo("NotFoundException"));
|
||||
}
|
||||
|
||||
postRabbitBroker(mq(account, "us-east-1"), "it-regional")
|
||||
.statusCode(409)
|
||||
.body("__type", equalTo("ConflictException"));
|
||||
String inVirginia = createRabbitBroker(account, "us-east-1", "it-regional-virginia");
|
||||
|
||||
mq(account, "eu-west-1")
|
||||
.when()
|
||||
.get("/v1/brokers")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("brokerSummaries.brokerId", equalTo(List.of(inIreland)));
|
||||
mq(account, "us-east-1")
|
||||
.when()
|
||||
.get("/v1/brokers")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("brokerSummaries.brokerId", equalTo(List.of(inVirginia)));
|
||||
}
|
||||
}
|
||||
@@ -4,42 +4,42 @@ import io.floci.aws.config.EmulatorConfig;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
import io.floci.aws.core.storage.AccountAwareStorageBackend;
|
||||
import io.floci.aws.core.storage.InMemoryStorage;
|
||||
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.BrokerState;
|
||||
import io.floci.aws.services.amazonmq.model.MqUser;
|
||||
import io.floci.aws.testing.ParkingStore;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.function.Executable;
|
||||
import org.mockito.Mockito;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static io.floci.aws.testing.ParkingStoreAssertions.assertOperationWaitsForParkedStore;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class AmazonMqServiceTest {
|
||||
|
||||
private static final String ACCOUNT = "000000000000";
|
||||
|
||||
private AccountAwareStorageBackend<Broker> brokers;
|
||||
private RegionResolver regionResolver;
|
||||
private AmazonMqService service;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
StorageFactory storageFactory = Mockito.mock(StorageFactory.class);
|
||||
when(storageFactory.create(Mockito.anyString(), Mockito.anyString(), Mockito.any()))
|
||||
.thenReturn(AccountAwareStorageBackend.inMemory("000000000000"));
|
||||
brokers = AccountAwareStorageBackend.inMemory(ACCOUNT);
|
||||
regionResolver = Mockito.spy(new RegionResolver("us-east-1", ACCOUNT));
|
||||
service = newService(true, Mockito.mock(RabbitMqManager.class));
|
||||
}
|
||||
|
||||
EmulatorConfig config = Mockito.mock(EmulatorConfig.class);
|
||||
EmulatorConfig.ServicesConfig servicesConfig = Mockito.mock(EmulatorConfig.ServicesConfig.class);
|
||||
EmulatorConfig.AmazonMqServiceConfig mqConfig = Mockito.mock(EmulatorConfig.AmazonMqServiceConfig.class);
|
||||
when(config.services()).thenReturn(servicesConfig);
|
||||
when(servicesConfig.amazonmq()).thenReturn(mqConfig);
|
||||
when(mqConfig.mock()).thenReturn(true);
|
||||
when(config.defaultRegion()).thenReturn("us-east-1");
|
||||
|
||||
RegionResolver regionResolver = new RegionResolver("us-east-1", "000000000000");
|
||||
RabbitMqManager rabbitMqManager = Mockito.mock(RabbitMqManager.class);
|
||||
service = new AmazonMqService(storageFactory, config, regionResolver, rabbitMqManager);
|
||||
@AfterEach
|
||||
void stopPoller() {
|
||||
service.shutdown();
|
||||
}
|
||||
|
||||
private CreateBrokerParams rabbitParams(String name) {
|
||||
@@ -185,23 +185,123 @@ class AmazonMqServiceTest {
|
||||
assertThrows(AwsException.class, () -> realModeService.rebootBroker(failed.getBrokerId()));
|
||||
}
|
||||
|
||||
/** Brokers are Regional: another Region of the account neither lists, describes, reboots nor deletes one. */
|
||||
@Test
|
||||
void aBrokerIsSeenOnlyInItsOwnRegion() {
|
||||
String brokerId = service.createBroker(rabbitParams("orders")).getBrokerId();
|
||||
|
||||
inRegion("eu-west-1");
|
||||
assertEquals(List.of(), service.listBrokers());
|
||||
for (Executable call : List.<Executable>of(
|
||||
() -> service.describeBroker(brokerId),
|
||||
() -> service.rebootBroker(brokerId),
|
||||
() -> service.deleteBroker(brokerId))) {
|
||||
assertEquals("NotFoundException", assertThrows(AwsException.class, call).getErrorCode());
|
||||
}
|
||||
|
||||
inRegion("us-east-1");
|
||||
assertEquals(List.of(brokerId), service.listBrokers().stream().map(Broker::getBrokerId).toList());
|
||||
assertEquals("orders", service.describeBroker(brokerId).getBrokerName());
|
||||
}
|
||||
|
||||
/**
|
||||
* A broker name is unique in the account, across its Regions, as the CreateBroker reference documents: another
|
||||
* Region refuses it, and a broker created there under another name carries that Region's ARN.
|
||||
*/
|
||||
@Test
|
||||
void aBrokerNameIsUniqueAcrossTheAccountsRegions() {
|
||||
service.createBroker(rabbitParams("orders"));
|
||||
|
||||
inRegion("eu-west-1");
|
||||
assertEquals("ConflictException",
|
||||
assertThrows(AwsException.class, () -> service.createBroker(rabbitParams("orders"))).getErrorCode());
|
||||
assertEquals(List.of(), service.listBrokers());
|
||||
Broker inIreland = service.createBroker(rabbitParams("payments"));
|
||||
assertEquals("arn:aws:mq:eu-west-1:" + ACCOUNT + ":broker:payments:" + inIreland.getBrokerId(),
|
||||
inIreland.getBrokerArn());
|
||||
}
|
||||
|
||||
/** A broker stored before brokers were keyed by Region moves, at startup, to the Region its ARN names. */
|
||||
@Test
|
||||
void aBrokerStoredUnderItsBareIdMovesToItsArnsRegionOnStartup() {
|
||||
Broker legacy = new Broker("b-legacy", "arn:aws:mq:eu-west-1:" + ACCOUNT + ":broker:legacy:b-legacy",
|
||||
"legacy", "RABBITMQ", "3.13", "SINGLE_INSTANCE", "mq.t3.micro");
|
||||
legacy.setAccountId(ACCOUNT);
|
||||
legacy.setBrokerState(BrokerState.RUNNING);
|
||||
brokers.put("b-legacy", legacy);
|
||||
|
||||
service.init();
|
||||
|
||||
assertEquals(List.of(AmazonMqService.brokerKey("eu-west-1", "b-legacy")),
|
||||
List.copyOf(brokers.keys()));
|
||||
inRegion("eu-west-1");
|
||||
assertEquals("legacy", service.describeBroker("b-legacy").getBrokerName());
|
||||
inRegion("us-east-1");
|
||||
assertEquals(List.of(), service.listBrokers());
|
||||
}
|
||||
|
||||
/**
|
||||
* The readiness poller writes a broker back under the account and the key it is stored under, even
|
||||
* for a record that names no account, as one written before brokers carried theirs.
|
||||
*/
|
||||
@Test
|
||||
void aBrokerTurningReadyStaysInItsAccountAndRegion() {
|
||||
RabbitMqManager readyManager = Mockito.mock(RabbitMqManager.class);
|
||||
when(readyManager.isReady(Mockito.any())).thenReturn(true);
|
||||
service = newService(false, readyManager);
|
||||
Broker starting = new Broker("b-starting", "arn:aws:mq:eu-west-1:111111111111:broker:starting:b-starting",
|
||||
"starting", "RABBITMQ", "3.13", "SINGLE_INSTANCE", "mq.t3.micro");
|
||||
starting.setBrokerState(BrokerState.CREATION_IN_PROGRESS);
|
||||
String key = AmazonMqService.brokerKey("eu-west-1", "b-starting");
|
||||
brokers.putForAccount("111111111111", key, starting);
|
||||
|
||||
service.pollReadiness();
|
||||
|
||||
assertEquals(BrokerState.RUNNING,
|
||||
brokers.getForAccount("111111111111", key).map(Broker::getBrokerState).orElse(null));
|
||||
assertEquals(1, brokers.scanAllAccounts().size());
|
||||
}
|
||||
|
||||
/**
|
||||
* Two creates of one broker name in an account: the second waits for the first, parked as it stores its
|
||||
* broker, and then finds the name taken, so only one broker has it.
|
||||
*/
|
||||
@Test
|
||||
void aSecondCreateOfANameWaitsForTheFirstAndIsRefused() throws Exception {
|
||||
ParkingStore<Broker> parking = new ParkingStore<>();
|
||||
brokers = new AccountAwareStorageBackend<>(parking, null, ACCOUNT);
|
||||
service = newService(true, Mockito.mock(RabbitMqManager.class));
|
||||
parking.parkNextWrite();
|
||||
|
||||
assertOperationWaitsForParkedStore(parking,
|
||||
() -> service.createBroker(rabbitParams("orders")),
|
||||
() -> assertEquals("ConflictException", assertThrows(AwsException.class,
|
||||
() -> service.createBroker(rabbitParams("orders"))).getErrorCode()));
|
||||
assertEquals(1, service.listBrokers().size());
|
||||
}
|
||||
|
||||
private AmazonMqService realModeServiceWithFailingManager() {
|
||||
RabbitMqManager failingManager = Mockito.mock(RabbitMqManager.class);
|
||||
Mockito.doThrow(new RuntimeException("docker unavailable"))
|
||||
.when(failingManager).startContainer(Mockito.any());
|
||||
return newService(false, failingManager);
|
||||
}
|
||||
|
||||
/** A service over {@link #brokers} answering in the Region {@link #regionResolver} gives. */
|
||||
private AmazonMqService newService(boolean mock, RabbitMqManager rabbitMqManager) {
|
||||
StorageFactory storageFactory = Mockito.mock(StorageFactory.class);
|
||||
when(storageFactory.create(Mockito.anyString(), Mockito.anyString(), Mockito.any()))
|
||||
.thenReturn(AccountAwareStorageBackend.inMemory("000000000000"));
|
||||
Mockito.doReturn(brokers).when(storageFactory).create(Mockito.anyString(), Mockito.anyString(), Mockito.any());
|
||||
|
||||
EmulatorConfig config = Mockito.mock(EmulatorConfig.class);
|
||||
EmulatorConfig.ServicesConfig servicesConfig = Mockito.mock(EmulatorConfig.ServicesConfig.class);
|
||||
EmulatorConfig.AmazonMqServiceConfig mqConfig = Mockito.mock(EmulatorConfig.AmazonMqServiceConfig.class);
|
||||
when(config.services()).thenReturn(servicesConfig);
|
||||
when(servicesConfig.amazonmq()).thenReturn(mqConfig);
|
||||
when(mqConfig.mock()).thenReturn(false);
|
||||
when(config.defaultRegion()).thenReturn("us-east-1");
|
||||
when(mqConfig.mock()).thenReturn(mock);
|
||||
return new AmazonMqService(storageFactory, config, regionResolver, rabbitMqManager);
|
||||
}
|
||||
|
||||
RegionResolver regionResolver = new RegionResolver("us-east-1", "000000000000");
|
||||
RabbitMqManager failingManager = Mockito.mock(RabbitMqManager.class);
|
||||
Mockito.doThrow(new RuntimeException("docker unavailable"))
|
||||
.when(failingManager).startContainer(Mockito.any());
|
||||
return new AmazonMqService(storageFactory, config, regionResolver, failingManager);
|
||||
private void inRegion(String region) {
|
||||
Mockito.doReturn(region).when(regionResolver).getRegion();
|
||||
}
|
||||
}
|
||||
@@ -51,6 +51,17 @@ class BrokerTest {
|
||||
assertEquals("EBS", roundTripped.getStorageType());
|
||||
}
|
||||
|
||||
/** A broker's Region is the one its ARN names, and the default Region's for a broker recorded without one. */
|
||||
@Test
|
||||
void aBrokersRegionIsTheOneItsArnNames() {
|
||||
Broker inIreland = new Broker("b-1", "arn:aws:mq:eu-west-1:000000000000:broker:n:b-1",
|
||||
"n", "RABBITMQ", "3.13", "SINGLE_INSTANCE", "mq.t3.micro");
|
||||
Broker withoutArn = new Broker("b-2", null, "m", "RABBITMQ", "3.13", "SINGLE_INSTANCE", "mq.t3.micro");
|
||||
|
||||
assertEquals("eu-west-1", inIreland.region("us-east-1"));
|
||||
assertEquals("us-east-1", withoutArn.region("us-east-1"));
|
||||
}
|
||||
|
||||
/** A broker persisted before these members existed must still load, with them absent. */
|
||||
@Test
|
||||
void brokerPersistedWithoutNewMembersStillLoads() throws Exception {
|
||||
|
||||
Reference in new issue
Block a user