diff --git a/src/main/java/io/floci/aws/core/common/AvailabilityZoneIds.java b/src/main/java/io/floci/aws/core/common/AvailabilityZoneIds.java index 07e3f6bc16..2b2a2d88f3 100644 --- a/src/main/java/io/floci/aws/core/common/AvailabilityZoneIds.java +++ b/src/main/java/io/floci/aws/core/common/AvailabilityZoneIds.java @@ -46,6 +46,18 @@ public final class AvailabilityZoneIds { return forIndex(region, 1); } + /** + * The Region of zone {@code zoneName}, the name without its zone letter: {@code us-east-1} for + * {@code us-east-1a}. Null for a name that doesn't end in a letter. + */ + public static String regionOf(String zoneName) { + if (zoneName == null || zoneName.length() < 2 + || !Character.isLetter(zoneName.charAt(zoneName.length() - 1))) { + return null; + } + return zoneName.substring(0, zoneName.length() - 1); + } + /** The id of the {@code index}-th zone of {@code region}, counting from 1. */ public static String forIndex(String region, int index) { return prefix(region) + SEPARATOR + index; diff --git a/src/main/java/io/floci/aws/core/storage/HybridStorage.java b/src/main/java/io/floci/aws/core/storage/HybridStorage.java index 5084639658..649449fdd1 100644 --- a/src/main/java/io/floci/aws/core/storage/HybridStorage.java +++ b/src/main/java/io/floci/aws/core/storage/HybridStorage.java @@ -3,7 +3,6 @@ package io.floci.aws.core.storage; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; -import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import org.jboss.logging.Logger; import java.io.IOException; @@ -39,10 +38,7 @@ public class HybridStorage implements StorageBackend { public HybridStorage(Path filePath, TypeReference> typeReference, long flushIntervalMs) { this.filePath = filePath; this.typeReference = typeReference; - this.objectMapper = new ObjectMapper(); - this.objectMapper.registerModule(new JavaTimeModule()); - this.objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); - this.objectMapper.enable(SerializationFeature.INDENT_OUTPUT); + this.objectMapper = StorageJson.mapper().enable(SerializationFeature.INDENT_OUTPUT); this.scheduler = StorageFiles.scheduleEvery("hybrid-storage-flush", flushIntervalMs, this::flushIfDirty); } diff --git a/src/main/java/io/floci/aws/core/storage/PersistentStorage.java b/src/main/java/io/floci/aws/core/storage/PersistentStorage.java index 440a13142b..696c6ebb04 100644 --- a/src/main/java/io/floci/aws/core/storage/PersistentStorage.java +++ b/src/main/java/io/floci/aws/core/storage/PersistentStorage.java @@ -3,7 +3,6 @@ package io.floci.aws.core.storage; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; -import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import org.jboss.logging.Logger; import java.io.IOException; @@ -37,10 +36,7 @@ public class PersistentStorage implements StorageBackend { public PersistentStorage(Path filePath, TypeReference> typeReference) { this.filePath = filePath; this.typeReference = typeReference; - this.objectMapper = new ObjectMapper(); - this.objectMapper.registerModule(new JavaTimeModule()); - this.objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); - this.objectMapper.enable(SerializationFeature.INDENT_OUTPUT); + this.objectMapper = StorageJson.mapper().enable(SerializationFeature.INDENT_OUTPUT); } @Override diff --git a/src/main/java/io/floci/aws/core/storage/StorageJson.java b/src/main/java/io/floci/aws/core/storage/StorageJson.java new file mode 100644 index 0000000000..e138c88a6f --- /dev/null +++ b/src/main/java/io/floci/aws/core/storage/StorageJson.java @@ -0,0 +1,41 @@ +package io.floci.aws.core.storage; + +import com.fasterxml.jackson.core.JsonFactory; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; +import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; + +/** + * The JSON form the file storages keep records in: Java time types, written as ISO-8601 text rather than numbers. + * Their mappers are built here, and so are copies of a record through that form. + */ +public final class StorageJson { + + private static final ObjectMapper COPIES = mapper(); + + private StorageJson() { + } + + /** A mapper that reads and writes records as the file storages do. */ + public static ObjectMapper mapper() { + return configure(new ObjectMapper()); + } + + /** As above, over {@code factory}, as the write-ahead log's CBOR mapper is. */ + static ObjectMapper mapper(JsonFactory factory) { + return configure(new ObjectMapper(factory)); + } + + /** + * A copy of {@code record} through its stored form: a record of its own, as storage would read it back, so + * changing one doesn't change the other. + */ + @SuppressWarnings("unchecked") + public static V copy(V record) { + return (V) COPIES.convertValue(record, record.getClass()); + } + + private static ObjectMapper configure(ObjectMapper mapper) { + return mapper.registerModule(new JavaTimeModule()).disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); + } +} diff --git a/src/main/java/io/floci/aws/core/storage/WalStorage.java b/src/main/java/io/floci/aws/core/storage/WalStorage.java index 23ec8f16c7..8f13b118f3 100644 --- a/src/main/java/io/floci/aws/core/storage/WalStorage.java +++ b/src/main/java/io/floci/aws/core/storage/WalStorage.java @@ -5,7 +5,6 @@ import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.dataformat.cbor.CBORFactory; -import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import org.jboss.logging.Logger; import java.io.BufferedInputStream; @@ -90,14 +89,9 @@ public class WalStorage implements StorageBackend { this.walPath = walPath; this.typeReference = typeReference; - this.snapshotMapper = new ObjectMapper(); - this.snapshotMapper.registerModule(new JavaTimeModule()); - this.snapshotMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); - this.snapshotMapper.enable(SerializationFeature.INDENT_OUTPUT); + this.snapshotMapper = StorageJson.mapper().enable(SerializationFeature.INDENT_OUTPUT); - this.walMapper = new ObjectMapper(new CBORFactory()); - this.walMapper.registerModule(new JavaTimeModule()); - this.walMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); + this.walMapper = StorageJson.mapper(new CBORFactory()); this.scheduler = StorageFiles.scheduleEvery("wal-storage-compaction", compactionIntervalMs, this::compact); } diff --git a/src/main/java/io/floci/aws/services/appconfig/AppConfigService.java b/src/main/java/io/floci/aws/services/appconfig/AppConfigService.java index b0b36ce9ca..f8dedb103d 100644 --- a/src/main/java/io/floci/aws/services/appconfig/AppConfigService.java +++ b/src/main/java/io/floci/aws/services/appconfig/AppConfigService.java @@ -1,7 +1,6 @@ package io.floci.aws.services.appconfig; import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.ObjectMapper; import io.floci.aws.core.common.AwsArnUtils; import io.floci.aws.core.common.AwsException; import io.floci.aws.core.common.PaginatedResult; @@ -10,6 +9,7 @@ import io.floci.aws.core.common.RegionResolver; import io.floci.aws.core.storage.RegionScopedStorage; import io.floci.aws.core.storage.StorageBackend; import io.floci.aws.core.storage.StorageFactory; +import io.floci.aws.core.storage.StorageJson; import io.floci.aws.core.storage.StorageOperations; import io.floci.aws.services.appconfig.model.Application; import io.floci.aws.services.appconfig.model.ConfigurationProfile; @@ -56,7 +56,6 @@ public class AppConfigService { private static final int MAX_DEPLOYMENT_PAGE_TOKENS = 1000; private static final int MAX_MONITORS = 5; private static final int MAX_ARN_LENGTH = 2048; - private static final ObjectMapper COPIER = new ObjectMapper(); private static final Pattern ROLE_ARN = Pattern.compile("arn:" + AwsArnUtils.PARTITION_REGEX + ":iam::\\d{12}:role/.*"); @Inject @@ -892,9 +891,8 @@ public class AppConfigService { * such as one a GetApplication is still serializing, under that caller. The models are plain * Jackson beans, as storage persists them, so a round trip copies every field. */ - @SuppressWarnings("unchecked") private static T copy(T entity) { - return (T) COPIER.convertValue(entity, entity.getClass()); + return StorageJson.copy(entity); } private static String shortId(int length) { diff --git a/src/main/java/io/floci/aws/services/efs/model/MountTarget.java b/src/main/java/io/floci/aws/services/efs/model/MountTarget.java index 0dfd7ca7bc..4f8382ff81 100644 --- a/src/main/java/io/floci/aws/services/efs/model/MountTarget.java +++ b/src/main/java/io/floci/aws/services/efs/model/MountTarget.java @@ -30,12 +30,8 @@ public class MountTarget { * mount target persisted before zone ids took AWS's shape carries the old id. */ public String getAvailabilityZoneId() { - if (availabilityZoneName == null || availabilityZoneName.length() < 2 - || !Character.isLetter(availabilityZoneName.charAt(availabilityZoneName.length() - 1))) { - return availabilityZoneId; - } - String region = availabilityZoneName.substring(0, availabilityZoneName.length() - 1); - return AvailabilityZoneIds.forZoneName(region, availabilityZoneName); + String region = AvailabilityZoneIds.regionOf(availabilityZoneName); + return region == null ? availabilityZoneId : AvailabilityZoneIds.forZoneName(region, availabilityZoneName); } public void setAvailabilityZoneId(String availabilityZoneId) { diff --git a/src/main/java/io/floci/aws/services/eks/EksService.java b/src/main/java/io/floci/aws/services/eks/EksService.java index 332e06efb7..87da19ba3b 100644 --- a/src/main/java/io/floci/aws/services/eks/EksService.java +++ b/src/main/java/io/floci/aws/services/eks/EksService.java @@ -2,6 +2,7 @@ package io.floci.aws.services.eks; import com.fasterxml.jackson.core.type.TypeReference; import io.floci.aws.config.EmulatorConfig; +import io.floci.aws.core.common.AvailabilityZoneIds; import io.floci.aws.core.common.AwsArnUtils; import io.floci.aws.core.common.AwsException; import io.floci.aws.core.common.PaginatedResult; @@ -1039,11 +1040,8 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun private void validateInstanceRegion(Cluster cluster, Instance instance) { String clusterReg = resolveClusterRegion(cluster); String instReg = instance.getRegion(); - if (instReg == null && instance.getPlacement() != null && instance.getPlacement().getAvailabilityZone() != null) { - String az = instance.getPlacement().getAvailabilityZone(); - if (az.length() > 1 && Character.isLetter(az.charAt(az.length() - 1))) { - instReg = az.substring(0, az.length() - 1); - } + if (instReg == null && instance.getPlacement() != null) { + instReg = AvailabilityZoneIds.regionOf(instance.getPlacement().getAvailabilityZone()); } if (instReg != null && !instReg.equals(clusterReg)) { throw new AwsException("InvalidParameterException", "Cannot join instance " + instance.getInstanceId() diff --git a/src/main/java/io/floci/aws/services/redshift/RedshiftService.java b/src/main/java/io/floci/aws/services/redshift/RedshiftService.java index fb6a14886b..37f5dca412 100644 --- a/src/main/java/io/floci/aws/services/redshift/RedshiftService.java +++ b/src/main/java/io/floci/aws/services/redshift/RedshiftService.java @@ -3,6 +3,7 @@ package io.floci.aws.services.redshift; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import io.floci.aws.config.EmulatorConfig; +import io.floci.aws.core.common.AvailabilityZoneIds; import io.floci.aws.core.common.AwsArnUtils; import io.floci.aws.core.common.AwsException; import io.floci.aws.core.common.AwsRegions; @@ -14,6 +15,7 @@ import io.floci.aws.core.common.docker.ContainerRejectedException; import io.floci.aws.core.common.docker.DockerHostResolver; import io.floci.aws.core.storage.AccountAwareStorageBackend; import io.floci.aws.core.storage.StorageFactory; +import io.floci.aws.core.storage.StorageJson; import io.floci.aws.services.dynamodb.backend.DynamoDbStreamReader; import io.floci.aws.services.dynamodb.model.TableDefinition; import io.floci.aws.services.ec2.Ec2Service; @@ -44,6 +46,7 @@ import io.floci.aws.services.secretsmanager.RandomPasswordGenerator; import io.floci.aws.services.secretsmanager.SecretsManagerService; import io.floci.aws.services.secretsmanager.model.Secret; import io.quarkus.runtime.StartupEvent; +import jakarta.annotation.PostConstruct; import jakarta.enterprise.context.ApplicationScoped; import jakarta.enterprise.event.Observes; import jakarta.inject.Inject; @@ -77,6 +80,7 @@ import java.util.concurrent.locks.ReentrantLock; import java.util.function.BiConsumer; import java.util.function.BiPredicate; import java.util.function.Consumer; +import java.util.function.Function; import java.util.function.Predicate; import java.util.function.Supplier; import java.util.regex.Pattern; @@ -88,6 +92,8 @@ public class RedshiftService implements ManagedSecretRotator { // The group every cluster starts on until one is named. static final String DEFAULT_PARAMETER_GROUP_NAME = "default.redshift-1.0"; private static final int MAX_RESET_PARAMETERS = 20; + // The alias of the AWS-managed key a snapshot copy grant gets when it names none. + private static final String DEFAULT_SNAPSHOT_COPY_GRANT_KEY = "alias/aws/redshift"; private final AccountAwareStorageBackend clusters; private final AccountAwareStorageBackend snapshots; @@ -352,6 +358,27 @@ public class RedshiftService implements ManagedSecretRotator { credentialBroker, null, new ObjectMapper(), null); } + /** + * Moves the Regional records stored before they were Regional onto their Regional keys when the bean is made, as + * {@code AmazonMqService} moves its brokers: before {@link #onStart} and before any sweep runs, such as the + * snapshot-copy sweep that starts at startup on its own thread and reads a copy grant by its Regional key. + */ + @PostConstruct + void migrateRegionalRecords() { + // The clusters are read once, and only when a store has records to move. + migrateLegacyRegionalRecords(new Supplier<>() { + private List> read; + + @Override + public List> get() { + if (read == null) { + read = clusters.scanAllAccountEntries(k -> true); + } + return read; + } + }); + } + // Recreate Docker containers for persisted clusters on app restart (across every account, not just default) void onStart(@Observes StartupEvent event) { List> persistedClusters = @@ -729,6 +756,7 @@ public class RedshiftService implements ManagedSecretRotator { } boolean nameTaken = integrations.scan(k -> true).stream() + .filter(existing -> region.equals(integrationRegion(existing))) .anyMatch(existing -> integrationName.equals(existing.getIntegrationName())); if (nameTaken) { throw new AwsException("IntegrationAlreadyExistsFault", @@ -840,6 +868,7 @@ public class RedshiftService implements ManagedSecretRotator { public IntegrationPage describeIntegrations(String integrationArn, Integer maxRecords, String marker, List filters) { List all = integrations.scan(k -> true).stream() + .filter(this::isInRequestRegion) .sorted(Comparator.comparing(Integration::getIntegrationArn)) .toList(); @@ -1078,6 +1107,7 @@ public class RedshiftService implements ManagedSecretRotator { } if (autoCopyConsumer != null) { integrations.keys().stream().map(integrations::get).flatMap(Optional::stream) + .filter(this::isInRequestRegion) .filter(integration -> integrationArn.equals(integration.getIntegrationArn()) && S3_EVENT_SOURCE_TYPE.equals(integration.getSourceType())) .findFirst().ifPresent(autoCopyConsumer::disable); @@ -1093,7 +1123,8 @@ public class RedshiftService implements ManagedSecretRotator { } for (String key : integrations.keys()) { Optional stored = integrations.get(key); - if (stored.isPresent() && integrationArn.equals(stored.get().getIntegrationArn())) { + if (stored.isPresent() && integrationArn.equals(stored.get().getIntegrationArn()) + && isInRequestRegion(stored.get())) { integrations.delete(key); LOG.infov("Deleted Redshift zero-ETL integration: {0}", integrationArn); if (stored.get().getSourceType() == null) { @@ -2029,7 +2060,7 @@ public class RedshiftService implements ManagedSecretRotator { validateSnapshotIdentifier(snapshotIdentifier); String clusterIdentifier = cluster.getClusterIdentifier(); boolean shadowedByCopy = scheduledTime == null - && snapshotCopies.get(copyKey(regionResolver.getRegion(), snapshotIdentifier)).isPresent(); + && snapshotCopies.get(regionalKey(snapshotIdentifier)).isPresent(); if (shadowedByCopy || (scheduledTime == null ? snapshots.get(snapshotIdentifier) : snapshots.getForAccount(accountId, snapshotIdentifier)).isPresent()) { throw new AwsException("ClusterSnapshotAlreadyExists", "Snapshot " + snapshotIdentifier + " already exists", 400); @@ -2138,17 +2169,138 @@ public class RedshiftService implements ManagedSecretRotator { return visible; } - private static String copyKey(String region, String snapshotIdentifier) { - return region + "::" + snapshotIdentifier; + /** + * The storage key of the Regional record {@code name} in {@code region}: a snapshot copy, cluster parameter + * group, subnet group, snapshot copy grant or snapshot schedule. Each is Regional, so the same name can be + * used in each Region of an account. + */ + static String regionalKey(String region, String name) { + return region + KEY_SEPARATOR + name; + } + + /** Separates the Region from the name in a {@link #regionalKey}. */ + private static final String KEY_SEPARATOR = "::"; + + /** + * Moves the cluster parameter groups, subnet groups, snapshot schedules and snapshot copy grants stored before + * they became Regional from their bare name onto {@link #regionalKey} keys. They recorded no Region, and every + * Region saw them. Each moves to the Region it shows it was made in, when it shows one: a subnet group to its + * subnets' Region, a copy grant to its KMS key's. Any other moves to the default Region. Every other Region where + * one of its account's clusters uses it gets a copy of its own, so those clusters keep finding it. + */ + private void migrateLegacyRegionalRecords( + Supplier>> persistedClusters) { + migrateLegacyRegionalRecords(parameterGroups, ClusterParameterGroup::getParameterGroupName, group -> null, + persistedClusters, Cluster::getClusterParameterGroupName, this::clusterRegion, (copy, region) -> { }); + migrateLegacyRegionalRecords(subnetGroups, ClusterSubnetGroup::getClusterSubnetGroupName, + RedshiftService::regionOfSubnets, persistedClusters, Cluster::getClusterSubnetGroupName, + this::clusterRegion, (copy, region) -> { }); + migrateLegacyRegionalRecords(snapshotSchedules, SnapshotSchedule::getScheduleIdentifier, schedule -> null, + persistedClusters, Cluster::getSnapshotScheduleIdentifier, this::clusterRegion, (copy, region) -> { }); + migrateLegacyRegionalRecords(snapshotCopyGrants, SnapshotCopyGrant::getSnapshotCopyGrantName, + RedshiftService::regionOfKey, persistedClusters, Cluster::getSnapshotCopyGrantName, + Cluster::getSnapshotCopyDestinationRegion, this::useTheDefaultKeyOfItsRegion); + } + + /** The Region of the zones EC2 placed a subnet group's subnets in, when they are all in one. */ + private static String regionOfSubnets(ClusterSubnetGroup group) { + Map zones = group.getSubnetZones(); + if (zones == null || zones.isEmpty()) { + return null; + } + Set regions = new LinkedHashSet<>(); + for (String zone : zones.values()) { + String region = AvailabilityZoneIds.regionOf(zone); + regions.add(region != null && Ec2Service.isModelledAvailabilityZone(region, zone) ? region : null); + } + return regions.size() == 1 ? regions.iterator().next() : null; + } + + /** The Region of a copy grant's KMS key, when its key is a KMS ARN: a key is of one Region, the grant's. */ + private static String regionOfKey(SnapshotCopyGrant grant) { + String key = grant.getKmsKeyId(); + if (!AwsArnUtils.isArnFor(key, "kms")) { + return null; + } + String region = AwsArnUtils.parse(key).region(); + return region.isEmpty() ? null : region; + } + + /** + * A grant copied to {@code region} that holds another Region's AWS-managed Redshift key, the one a grant created + * without {@code KmsKeyId} gets, holds {@code region}'s instead, as a grant created there would. A stored grant + * records no difference between that key given and defaulted, so both are changed; any other key is kept. + */ + private void useTheDefaultKeyOfItsRegion(SnapshotCopyGrant grant, String region) { + String key = grant.getKmsKeyId(); + if (key == null || !AwsArnUtils.isArn(key)) { + return; + } + AwsArnUtils.Arn arn = AwsArnUtils.parse(key); + if ("kms".equals(arn.service()) && DEFAULT_SNAPSHOT_COPY_GRANT_KEY.equals(arn.resource()) + && !region.equals(arn.region())) { + grant.setKmsKeyId(regionResolver.buildArn("kms", region, arn.accountId(), DEFAULT_SNAPSHOT_COPY_GRANT_KEY)); + } + } + + /** + * Moves {@code store}'s records without a Region in their key to the Region {@code regionMadeIn} gives, or to the + * default Region. The clusters that use one name it through {@code nameUsed}, in the Region {@code regionOfUse} + * gives, and each of those Regions gets a copy, which {@code forRegion} fits to it. + */ + private void migrateLegacyRegionalRecords(AccountAwareStorageBackend store, Function name, + Function regionMadeIn, + Supplier>> persistedClusters, + Function nameUsed, + Function regionOfUse, + BiConsumer forRegion) { + Predicate legacy = key -> !key.contains(KEY_SEPARATOR); + List> entries = store.scanAllAccountEntries(legacy); + if (entries.isEmpty()) { + return; + } + String defaultRegion = regionResolver.getDefaultRegion(); + Function home = value -> Optional.ofNullable(regionMadeIn.apply(value)).orElse(defaultRegion); + for (AccountAwareStorageBackend.AccountEntry entry : entries) { + String recordName = name.apply(entry.value()); + String recordHome = home.apply(entry.value()); + for (AccountAwareStorageBackend.AccountEntry cluster : persistedClusters.get()) { + String region = regionOfUse.apply(cluster.value()); + if (recordName == null || region == null || region.equals(recordHome) + || !cluster.accountId().equals(entry.accountId()) + || !recordName.equals(nameUsed.apply(cluster.value()))) { + continue; + } + if (store.getForAccount(entry.accountId(), regionalKey(region, recordName)).isEmpty()) { + V copy = StorageJson.copy(entry.value()); + forRegion.accept(copy, region); + store.putForAccount(entry.accountId(), regionalKey(region, recordName), copy); + } + } + } + store.migrateLegacyEntriesInAllAccounts(legacy, + value -> name.apply(value) == null ? null : regionalKey(home.apply(value), name.apply(value))); + store.flush(); + } + + /** {@link #regionalKey(String, String)} in the request's Region. */ + private String regionalKey(String name) { + return regionalKey(regionResolver.getRegion(), name); + } + + /** Whether a key is of the request's Region, its prefix built once for a whole scan. */ + private Predicate inRequestRegion() { + String prefix = regionResolver.getRegion() + KEY_SEPARATOR; + return key -> key.startsWith(prefix); } private List copiesInRegion(String region) { - return snapshotCopies.scan(key -> key.startsWith(region + "::")); + return snapshotCopies.scan(key -> key.startsWith(region + KEY_SEPARATOR)); } /** The copy in this request's Region if there is one, otherwise the snapshot itself. */ private Optional findSnapshot(String snapshotIdentifier) { - return snapshotCopies.get(copyKey(regionResolver.getRegion(), snapshotIdentifier)) + return snapshotCopies.get(regionalKey(snapshotIdentifier)) .or(() -> snapshots.get(snapshotIdentifier)); } @@ -2208,6 +2360,15 @@ public class RedshiftService implements ManagedSecretRotator { return clusterRegion(cluster).equals(regionResolver.getRegion()); } + private boolean isInRequestRegion(Integration integration) { + return integrationRegion(integration).equals(regionResolver.getRegion()); + } + + /** The Region an integration was created in, which its ARN names. */ + private String integrationRegion(Integration integration) { + return AwsArnUtils.regionOrDefault(integration.getIntegrationArn(), regionResolver.getDefaultRegion()); + } + /** * The snapshot an ARN names in its account, as a restore finds it, a cluster the ARN leaves open ({@code *}) * matching any: in the caller's account the copy kept in the ARN's Region before the snapshot itself, and in @@ -2231,7 +2392,7 @@ public class RedshiftService implements ManagedSecretRotator { .filter(snapshot -> snapshot.getSnapshotArn() == null || AwsArnUtils.parse(snapshot.getSnapshotArn()).region().equals(arn.region())); } - return snapshotCopies.getForAccount(arn.accountId(), copyKey(arn.region(), identifier)).filter(ofCluster) + return snapshotCopies.getForAccount(arn.accountId(), regionalKey(arn.region(), identifier)).filter(ofCluster) .or(() -> snapshots.getForAccount(arn.accountId(), identifier).filter(ofCluster)); } @@ -2289,7 +2450,7 @@ public class RedshiftService implements ManagedSecretRotator { } private Snapshot shareableSnapshot(String snapshotIdentifier, String snapshotClusterIdentifier) { - String copyKey = copyKey(regionResolver.getRegion(), snapshotIdentifier); + String copyKey = regionalKey(snapshotIdentifier); if (snapshotCopies.get(copyKey).isPresent()) { throw new AwsException("InvalidClusterSnapshotState", "Snapshot " + snapshotIdentifier + " is not an available manual snapshot, which is the only kind" @@ -2365,7 +2526,7 @@ public class RedshiftService implements ManagedSecretRotator { } snapshot.setManualSnapshotRetentionPeriod(manualSnapshotRetentionPeriod); - String copyKey = copyKey(region, snapshotIdentifier); + String copyKey = regionalKey(region, snapshotIdentifier); if (snapshotCopies.get(copyKey).isPresent()) { snapshotCopies.putAllAtomically(Map.of(copyKey, snapshot)); snapshotCopies.flush(); @@ -2388,7 +2549,7 @@ public class RedshiftService implements ManagedSecretRotator { String region = regionResolver.getRegion(); return withResourceLock("snapshot", targetSnapshotIdentifier, () -> { - boolean shadowedByCopy = snapshotCopies.get(copyKey(region, targetSnapshotIdentifier)).isPresent(); + boolean shadowedByCopy = snapshotCopies.get(regionalKey(region, targetSnapshotIdentifier)).isPresent(); if (shadowedByCopy || snapshots.get(targetSnapshotIdentifier).isPresent()) { throw new AwsException("ClusterSnapshotAlreadyExists", "Snapshot " + targetSnapshotIdentifier + " already exists", 400); @@ -2472,7 +2633,7 @@ public class RedshiftService implements ManagedSecretRotator { } private Snapshot removeSnapshot(String snapshotIdentifier, String snapshotClusterIdentifier) { - String copyKey = copyKey(regionResolver.getRegion(), snapshotIdentifier); + String copyKey = regionalKey(snapshotIdentifier); Optional copyOpt = snapshotCopies.get(copyKey); Optional snapshotOpt = copyOpt.or(() -> snapshots.get(snapshotIdentifier)) .filter(found -> takenFrom(found, snapshotClusterIdentifier)); @@ -2733,7 +2894,7 @@ public class RedshiftService implements ManagedSecretRotator { if (DEFAULT_PARAMETER_GROUP_NAME.equals(parameterGroupName)) { throw new AwsException("InvalidParameterValue", "The default parameter group name is reserved.", 400); } - if (parameterGroups.get(parameterGroupName).isPresent()) { + if (parameterGroups.get(regionalKey(parameterGroupName)).isPresent()) { throw new AwsException("ClusterParameterGroupAlreadyExists", "Cluster parameter group " + parameterGroupName + " already exists", 400); } @@ -2741,7 +2902,7 @@ public class RedshiftService implements ManagedSecretRotator { if (tags != null) { group.setTags(new LinkedHashMap<>(tags)); } - parameterGroups.put(parameterGroupName, group); + parameterGroups.put(regionalKey(parameterGroupName), group); parameterGroups.flush(); emitEvent(RedshiftEventCatalog.PARAMETER_GROUP_CREATED, parameterGroupName, "Cluster parameter group '" + parameterGroupName + "' was created."); @@ -2750,7 +2911,7 @@ public class RedshiftService implements ManagedSecretRotator { public List describeClusterParameterGroups(String parameterGroupName) { if (parameterGroupName != null && !parameterGroupName.isBlank()) { - Optional group = parameterGroups.get(parameterGroupName); + Optional group = parameterGroups.get(regionalKey(parameterGroupName)); if (group.isEmpty() && DEFAULT_PARAMETER_GROUP_NAME.equals(parameterGroupName)) { return List.of(defaultParameterGroup()); } @@ -2759,7 +2920,7 @@ public class RedshiftService implements ManagedSecretRotator { } return List.of(group.get()); } - List all = new ArrayList<>(parameterGroups.scan(k -> true)); + List all = new ArrayList<>(parameterGroups.scan(inRequestRegion())); if (all.stream().noneMatch(g -> DEFAULT_PARAMETER_GROUP_NAME.equals(g.getParameterGroupName()))) { all.add(0, defaultParameterGroup()); } @@ -2773,11 +2934,11 @@ public class RedshiftService implements ManagedSecretRotator { } public Optional getClusterParameterGroup(String parameterGroupName) { - return parameterGroups.get(parameterGroupName); + return parameterGroups.get(regionalKey(parameterGroupName)); } public List describeClusterParameters(String parameterGroupName) { - ClusterParameterGroup group = parameterGroups.get(parameterGroupName) + ClusterParameterGroup group = parameterGroups.get(regionalKey(parameterGroupName)) .or(() -> DEFAULT_PARAMETER_GROUP_NAME.equals(parameterGroupName) ? Optional.of(defaultParameterGroup()) : Optional.empty()) .orElseThrow(() -> new AwsException("ClusterParameterGroupNotFound", @@ -2788,7 +2949,7 @@ public class RedshiftService implements ManagedSecretRotator { public synchronized ClusterParameterGroup modifyClusterParameterGroup( String parameterGroupName, List updates) { requireMutableParameterGroup(parameterGroupName); - ClusterParameterGroup group = parameterGroups.get(parameterGroupName) + ClusterParameterGroup group = parameterGroups.get(regionalKey(parameterGroupName)) .orElseThrow(() -> new AwsException("ClusterParameterGroupNotFound", "Cluster parameter group " + parameterGroupName + " not found", 404)); @@ -2819,7 +2980,7 @@ public class RedshiftService implements ManagedSecretRotator { } } group.setParameters(current); - parameterGroups.put(parameterGroupName, group); + parameterGroups.put(regionalKey(parameterGroupName), group); parameterGroups.flush(); refreshClustersForActivityParameter(parameterGroupName, group); emitParameterGroupUpdated(parameterGroupName); @@ -2832,7 +2993,7 @@ public class RedshiftService implements ManagedSecretRotator { } private boolean userActivityLoggingEnabled(String parameterGroupName) { - ClusterParameterGroup group = parameterGroups.get(parameterGroupName) + ClusterParameterGroup group = parameterGroups.get(regionalKey(parameterGroupName)) .or(() -> DEFAULT_PARAMETER_GROUP_NAME.equals(parameterGroupName) ? Optional.of(defaultParameterGroup()) : Optional.empty()) .orElse(null); @@ -2860,7 +3021,7 @@ public class RedshiftService implements ManagedSecretRotator { if (parameterNames.size() > MAX_RESET_PARAMETERS) { throw new AwsException("InvalidParameterValue", "A maximum of 20 parameters can be reset.", 400); } - ClusterParameterGroup group = parameterGroups.get(parameterGroupName) + ClusterParameterGroup group = parameterGroups.get(regionalKey(parameterGroupName)) .orElseThrow(() -> new AwsException("ClusterParameterGroupNotFound", "Cluster parameter group " + parameterGroupName + " not found", 404)); Set names = new LinkedHashSet<>(); @@ -2885,7 +3046,7 @@ public class RedshiftService implements ManagedSecretRotator { } } group.setParameters(reset); - parameterGroups.put(parameterGroupName, group); + parameterGroups.put(regionalKey(parameterGroupName), group); parameterGroups.flush(); refreshClustersForActivityParameter(parameterGroupName, group); emitParameterGroupUpdated(parameterGroupName); @@ -2894,7 +3055,7 @@ public class RedshiftService implements ManagedSecretRotator { private void refreshClustersForActivityParameter(String parameterGroupName, ClusterParameterGroup group) { boolean enabled = userActivityLoggingEnabled(group); String accountId = clusters.accountId(); - List affected = clusters.scan(key -> true).stream() + List affected = regionalClusters().stream() .filter(cluster -> parameterGroupName.equals(cluster.getClusterParameterGroupName())).toList(); for (Cluster cluster : affected) { cluster.setUserActivityLoggingEnabled(enabled); @@ -2915,7 +3076,7 @@ public class RedshiftService implements ManagedSecretRotator { if (name == null || name.isBlank()) { throw new AwsException("InvalidParameterValue", "ParameterGroupName is required", 400); } - if (DEFAULT_PARAMETER_GROUP_NAME.equals(name) && parameterGroups.get(name).isEmpty()) { + if (DEFAULT_PARAMETER_GROUP_NAME.equals(name) && parameterGroups.get(regionalKey(name)).isEmpty()) { throw new AwsException("InvalidParameterValue", "The default parameter group cannot be modified.", 400); } } @@ -2936,12 +3097,12 @@ public class RedshiftService implements ManagedSecretRotator { } public ClusterParameterGroup deleteClusterParameterGroup(String parameterGroupName) { - Optional groupOpt = parameterGroups.get(parameterGroupName); + Optional groupOpt = parameterGroups.get(regionalKey(parameterGroupName)); if (groupOpt.isEmpty()) { throw new AwsException("ClusterParameterGroupNotFound", "Cluster parameter group " + parameterGroupName + " not found", 404); } ClusterParameterGroup group = groupOpt.get(); - parameterGroups.delete(parameterGroupName); + parameterGroups.delete(regionalKey(parameterGroupName)); parameterGroups.flush(); emitEvent(RedshiftEventCatalog.PARAMETER_GROUP_DELETED, parameterGroupName, "Cluster parameter group '" + parameterGroupName + "' was deleted at " + eventTime() + "."); @@ -2968,7 +3129,7 @@ public class RedshiftService implements ManagedSecretRotator { return switch (sourceType) { case RedshiftEventCatalog.CLUSTER -> regionalCluster(sourceIdentifier).isPresent(); case RedshiftEventCatalog.PARAMETER_GROUP -> DEFAULT_PARAMETER_GROUP_NAME.equals(sourceIdentifier) - || parameterGroups.get(sourceIdentifier).isPresent(); + || parameterGroups.get(regionalKey(sourceIdentifier)).isPresent(); case RedshiftEventCatalog.SNAPSHOT -> findSnapshot(sourceIdentifier).isPresent(); default -> false; }; @@ -3032,7 +3193,7 @@ public class RedshiftService implements ManagedSecretRotator { public ClusterSubnetGroup createClusterSubnetGroup(String name, String description, String vpcId, List subnetIds, Map tags) { - if (subnetGroups.get(name).isPresent()) { + if (subnetGroups.get(regionalKey(name)).isPresent()) { throw new AwsException("ClusterSubnetGroupAlreadyExists", "Cluster subnet group " + name + " already exists", 400); } ClusterSubnetGroup group = new ClusterSubnetGroup(name, description, vpcId, subnetIds); @@ -3040,7 +3201,7 @@ public class RedshiftService implements ManagedSecretRotator { group.setTags(new LinkedHashMap<>(tags)); } resolveSubnets(group); - subnetGroups.put(name, group); + subnetGroups.put(regionalKey(name), group); subnetGroups.flush(); return group; } @@ -3066,15 +3227,15 @@ public class RedshiftService implements ManagedSecretRotator { public List describeClusterSubnetGroups(String name) { if (name != null && !name.isBlank()) { // The Terraform AWS provider matches this exact "...Fault" code to detect a missing group. - ClusterSubnetGroup group = subnetGroups.get(name) + ClusterSubnetGroup group = subnetGroups.get(regionalKey(name)) .orElseThrow(() -> new AwsException("ClusterSubnetGroupNotFoundFault", "Cluster subnet group " + name + " not found", 400)); return List.of(group); } - return subnetGroups.scan(k -> true); + return subnetGroups.scan(inRequestRegion()); } public synchronized ClusterSubnetGroup modifyClusterSubnetGroup(String name, String description, List subnetIds) { - ClusterSubnetGroup group = subnetGroups.get(name) + ClusterSubnetGroup group = subnetGroups.get(regionalKey(name)) .orElseThrow(() -> new AwsException("ClusterSubnetGroupNotFoundFault", "Cluster subnet group " + name + " not found", 400)); if (description != null) { group.setDescription(description); @@ -3084,15 +3245,15 @@ public class RedshiftService implements ManagedSecretRotator { group.setVpcId(null); resolveSubnets(group); } - subnetGroups.put(name, group); + subnetGroups.put(regionalKey(name), group); subnetGroups.flush(); return group; } public ClusterSubnetGroup deleteClusterSubnetGroup(String name) { - ClusterSubnetGroup group = subnetGroups.get(name) + ClusterSubnetGroup group = subnetGroups.get(regionalKey(name)) .orElseThrow(() -> new AwsException("ClusterSubnetGroupNotFoundFault", "Cluster subnet group " + name + " not found", 400)); - subnetGroups.delete(name); + subnetGroups.delete(regionalKey(name)); subnetGroups.flush(); return group; } @@ -3105,7 +3266,7 @@ public class RedshiftService implements ManagedSecretRotator { * has to round-trip through Describe, which is what Terraform reads back. */ private String defaultSnapshotCopyGrantKey() { - return regionResolver.buildArn("kms", regionResolver.getRegion(), "alias/aws/redshift"); + return regionResolver.buildArn("kms", regionResolver.getRegion(), DEFAULT_SNAPSHOT_COPY_GRANT_KEY); } /** @@ -3127,7 +3288,7 @@ public class RedshiftService implements ManagedSecretRotator { // or two concurrent creates of the same name both succeed and the second overwrites the first. public synchronized SnapshotCopyGrant createSnapshotCopyGrant(String name, String kmsKeyId, Map tags) { validateSnapshotCopyGrantName(name); - if (snapshotCopyGrants.get(name).isPresent()) { + if (snapshotCopyGrants.get(regionalKey(name)).isPresent()) { throw new AwsException("SnapshotCopyGrantAlreadyExistsFault", "Snapshot copy grant " + name + " already exists", 400); } @@ -3136,7 +3297,7 @@ public class RedshiftService implements ManagedSecretRotator { if (tags != null && !tags.isEmpty()) { grant.setTags(new LinkedHashMap<>(tags)); } - snapshotCopyGrants.put(name, grant); + snapshotCopyGrants.put(regionalKey(name), grant); snapshotCopyGrants.flush(); return grant; } @@ -3164,12 +3325,12 @@ public class RedshiftService implements ManagedSecretRotator { List matching; if (name != null && !name.isBlank()) { - SnapshotCopyGrant grant = snapshotCopyGrants.get(name) + SnapshotCopyGrant grant = snapshotCopyGrants.get(regionalKey(name)) .orElseThrow(() -> new AwsException("SnapshotCopyGrantNotFoundFault", "Snapshot copy grant " + name + " not found", 400)); matching = List.of(grant); } else { - matching = snapshotCopyGrants.scan(k -> true); + matching = snapshotCopyGrants.scan(inRequestRegion()); } return Pagination.paginate(matching, SnapshotCopyGrant::getSnapshotCopyGrantName, @@ -3178,16 +3339,17 @@ public class RedshiftService implements ManagedSecretRotator { } public synchronized SnapshotCopyGrant deleteSnapshotCopyGrant(String name) { - SnapshotCopyGrant grant = snapshotCopyGrants.get(name) + SnapshotCopyGrant grant = snapshotCopyGrants.get(regionalKey(name)) .orElseThrow(() -> new AwsException("SnapshotCopyGrantNotFoundFault", "Snapshot copy grant " + name + " not found", 400)); boolean inUse = clusters.scan(k -> true).stream() - .anyMatch(c -> name.equals(c.getSnapshotCopyGrantName())); + .anyMatch(c -> name.equals(c.getSnapshotCopyGrantName()) + && regionResolver.getRegion().equals(c.getSnapshotCopyDestinationRegion())); if (inUse) { throw new AwsException("InvalidSnapshotCopyGrantStateFault", "Snapshot copy grant " + name + " is used by one or more clusters", 400); } - snapshotCopyGrants.delete(name); + snapshotCopyGrants.delete(regionalKey(name)); snapshotCopyGrants.flush(); return grant; } @@ -3245,7 +3407,7 @@ public class RedshiftService implements ManagedSecretRotator { validateAutomatedRetention(retention); validateManualRetention(manualRetention); boolean hasGrant = snapshotCopyGrantName != null && !snapshotCopyGrantName.isBlank(); - if (hasGrant && snapshotCopyGrants.get(snapshotCopyGrantName).isEmpty()) { + if (hasGrant && snapshotCopyGrants.get(regionalKey(destinationRegion, snapshotCopyGrantName)).isEmpty()) { throw new AwsException("SnapshotCopyGrantNotFoundFault", "Snapshot copy grant " + snapshotCopyGrantName + " not found", 400); } @@ -3419,7 +3581,8 @@ public class RedshiftService implements ManagedSecretRotator { return; } SnapshotSchedule schedule = cluster.getSnapshotScheduleIdentifier() == null ? null - : snapshotSchedules.getForAccount(accountId, cluster.getSnapshotScheduleIdentifier()).orElseThrow( + : snapshotSchedules.getForAccount(accountId, + regionalKey(clusterRegion(cluster), cluster.getSnapshotScheduleIdentifier())).orElseThrow( () -> new AwsException("SnapshotScheduleNotFound", "The cluster's snapshot schedule is missing", 400)); List definitions = schedule == null ? List.of("rate(8 hours)") : List.copyOf(schedule.getScheduleDefinitions()); @@ -3579,7 +3742,7 @@ public class RedshiftService implements ManagedSecretRotator { || source.getSnapshotCreateTime().isBefore(current.getSnapshotCopyEnabledAt())) { return null; } - String key = copyKey(destination, snapshotId); + String key = regionalKey(destination, snapshotId); Snapshot existing = snapshotCopies.getForAccount(accountId, key).orElse(null); if (existing != null) { if (Objects.equals(source.getSnapshotCreateTime(), existing.getSourceSnapshotCreateTime())) { @@ -3649,7 +3812,8 @@ public class RedshiftService implements ManagedSecretRotator { copy.setTags(new LinkedHashMap<>()); copy.setAccountsWithRestoreAccess(new LinkedHashSet<>()); copy.setKmsKeyId(Optional.ofNullable(cluster.getSnapshotCopyGrantName()) - .flatMap(name -> snapshotCopyGrants.getForAccount(accountId, name)) + .flatMap(name -> snapshotCopyGrants.getForAccount(accountId, + regionalKey(cluster.getSnapshotCopyDestinationRegion(), name))) .map(SnapshotCopyGrant::getKmsKeyId).orElse(null)); if ("automated".equals(source.getSnapshotType())) { copy.setAutomatedSnapshotRetentionPeriod(cluster.getSnapshotCopyRetentionPeriod()); @@ -3700,7 +3864,7 @@ public class RedshiftService implements ManagedSecretRotator { } int retention; if ("automated".equals(copy.getSnapshotType())) { - String region = key.substring(0, key.indexOf("::")); + String region = key.substring(0, key.indexOf(KEY_SEPARATOR)); // A cluster recreated under the same name has a new generation and no say over the old copies. Integer current = clusters.getForAccount(accountId, copy.getClusterIdentifier()) .filter(cluster -> region.equals(cluster.getSnapshotCopyDestinationRegion())) @@ -3761,7 +3925,7 @@ public class RedshiftService implements ManagedSecretRotator { } private SnapshotSchedule requireSnapshotSchedule(String scheduleIdentifier) { - return snapshotSchedules.get(scheduleIdentifier) + return snapshotSchedules.get(regionalKey(scheduleIdentifier)) .orElseThrow(() -> new AwsException("SnapshotScheduleNotFound", "Snapshot schedule " + scheduleIdentifier + " not found", 400)); } @@ -3775,7 +3939,7 @@ public class RedshiftService implements ManagedSecretRotator { throw new AwsException("InvalidParameterValue", "ScheduleIdentifier may contain only letters, digits and hyphens: " + id, 400); } - if (snapshotSchedules.get(id).isPresent()) { + if (snapshotSchedules.get(regionalKey(id)).isPresent()) { throw new AwsException("SnapshotScheduleAlreadyExists", "Snapshot schedule " + id + " already exists", 400); } validateScheduleDefinitions(definitions); @@ -3784,7 +3948,7 @@ public class RedshiftService implements ManagedSecretRotator { if (tags != null && !tags.isEmpty()) { schedule.setTags(new LinkedHashMap<>(tags)); } - snapshotSchedules.put(id, schedule); + snapshotSchedules.put(regionalKey(id), schedule); snapshotSchedules.flush(); return schedule; } @@ -3805,7 +3969,7 @@ public class RedshiftService implements ManagedSecretRotator { } } String byCluster = clusterSchedule; - List matching = snapshotSchedules.scan(k -> true).stream() + List matching = snapshotSchedules.scan(inRequestRegion()).stream() .filter(s -> scheduleIdentifier == null || scheduleIdentifier.isBlank() || scheduleIdentifier.equals(s.getScheduleIdentifier())) .filter(s -> byCluster == null || byCluster.equals(s.getScheduleIdentifier())) @@ -3820,7 +3984,7 @@ public class RedshiftService implements ManagedSecretRotator { /** Identifiers of the clusters currently using the schedule, sorted for a stable response. */ public List clustersUsingSnapshotSchedule(String scheduleIdentifier) { - return clusters.scan(k -> true).stream() + return regionalClusters().stream() .filter(c -> scheduleIdentifier.equals(c.getSnapshotScheduleIdentifier())) .map(Cluster::getClusterIdentifier) .sorted() @@ -3833,7 +3997,7 @@ public class RedshiftService implements ManagedSecretRotator { SnapshotSchedule schedule = new SnapshotSchedule(scheduleIdentifier, current.getScheduleDescription(), definitions); schedule.setTags(new LinkedHashMap<>(current.getTags())); schedule.setUpdatedAt(Instant.now()); - snapshotSchedules.put(scheduleIdentifier, schedule); + snapshotSchedules.put(regionalKey(scheduleIdentifier), schedule); snapshotSchedules.flush(); return schedule; } @@ -3844,7 +4008,7 @@ public class RedshiftService implements ManagedSecretRotator { throw new AwsException("InvalidClusterSnapshotScheduleState", "Snapshot schedule " + scheduleIdentifier + " is associated with one or more clusters.", 400); } - snapshotSchedules.delete(scheduleIdentifier); + snapshotSchedules.delete(regionalKey(scheduleIdentifier)); snapshotSchedules.flush(); } @@ -3923,7 +4087,7 @@ public class RedshiftService implements ManagedSecretRotator { } if (resourceType == null || "snapshot".equalsIgnoreCase(resourceType)) { for (Snapshot s : snapshots.scan(k -> true)) { - if (snapshotCopies.get(copyKey(regionResolver.getRegion(), s.getSnapshotIdentifier())).isPresent()) { + if (snapshotCopies.get(regionalKey(s.getSnapshotIdentifier())).isPresent()) { continue; } addTaggedResources(result, snapshotArn(s.getClusterIdentifier(), s.getSnapshotIdentifier()), @@ -3934,25 +4098,25 @@ public class RedshiftService implements ManagedSecretRotator { } } if (resourceType == null || "parametergroup".equalsIgnoreCase(resourceType)) { - for (ClusterParameterGroup g : parameterGroups.scan(k -> true)) { + for (ClusterParameterGroup g : parameterGroups.scan(inRequestRegion())) { addTaggedResources(result, parameterGroupArn(g.getParameterGroupName()), "parametergroup", g.getTags(), tagKeysFilter); } } if (resourceType == null || "subnetgroup".equalsIgnoreCase(resourceType)) { - for (ClusterSubnetGroup g : subnetGroups.scan(k -> true)) { + for (ClusterSubnetGroup g : subnetGroups.scan(inRequestRegion())) { addTaggedResources(result, subnetGroupArn(g.getClusterSubnetGroupName()), "subnetgroup", g.getTags(), tagKeysFilter); } } if (resourceType == null || "snapshotcopygrant".equalsIgnoreCase(resourceType)) { - for (SnapshotCopyGrant g : snapshotCopyGrants.scan(k -> true)) { + for (SnapshotCopyGrant g : snapshotCopyGrants.scan(inRequestRegion())) { addTaggedResources(result, snapshotCopyGrantArn(g.getSnapshotCopyGrantName()), "snapshotcopygrant", g.getTags(), tagKeysFilter); } } if (resourceType == null || "snapshotschedule".equalsIgnoreCase(resourceType)) { - for (SnapshotSchedule s : snapshotSchedules.scan(k -> true)) { + for (SnapshotSchedule s : snapshotSchedules.scan(inRequestRegion())) { addTaggedResources(result, snapshotScheduleArn(s.getScheduleIdentifier()), "snapshotschedule", s.getTags(), tagKeysFilter); } @@ -4083,7 +4247,7 @@ public class RedshiftService implements ManagedSecretRotator { } case "snapshot" -> { String snapshotId = id.contains("/") ? id.substring(id.lastIndexOf('/') + 1) : id; - String copyKey = copyKey(arn.region(), snapshotId); + String copyKey = regionalKey(arn.region(), snapshotId); Snapshot copy = snapshotCopies.get(copyKey).orElse(null); if (copy != null) { yield new TagHandle(copy.getTags(), updated -> { @@ -4101,20 +4265,20 @@ public class RedshiftService implements ManagedSecretRotator { }); } case "parametergroup" -> { - ClusterParameterGroup group = parameterGroups.get(id) + ClusterParameterGroup group = parameterGroups.get(regionalKey(id)) .orElseThrow(() -> new AwsException("ClusterParameterGroupNotFound", "Cluster parameter group " + id + " not found", 404)); yield new TagHandle(group.getTags(), updated -> { group.setTags(updated); - parameterGroups.put(id, group); + parameterGroups.put(regionalKey(id), group); parameterGroups.flush(); }); } case "subnetgroup" -> { - ClusterSubnetGroup group = subnetGroups.get(id) + ClusterSubnetGroup group = subnetGroups.get(regionalKey(id)) .orElseThrow(() -> new AwsException("ClusterSubnetGroupNotFoundFault", "Cluster subnet group " + id + " not found", 400)); yield new TagHandle(group.getTags(), updated -> { group.setTags(updated); - subnetGroups.put(id, group); + subnetGroups.put(regionalKey(id), group); subnetGroups.flush(); }); } @@ -4127,21 +4291,21 @@ public class RedshiftService implements ManagedSecretRotator { // ClusterParameterGroupNotFound are each modelled at 404. The grant fault is // modelled at 400, so emitting it here would pair a code with a status the // model never gives it. - SnapshotCopyGrant grant = snapshotCopyGrants.get(id) + SnapshotCopyGrant grant = snapshotCopyGrants.get(regionalKey(id)) .orElseThrow(() -> new AwsException("ResourceNotFoundFault", "Snapshot copy grant " + id + " not found", 404)); yield new TagHandle(grant.getTags(), updated -> { grant.setTags(updated); - snapshotCopyGrants.put(id, grant); + snapshotCopyGrants.put(regionalKey(id), grant); snapshotCopyGrants.flush(); }); } case "snapshotschedule" -> { // ResourceNotFoundFault for the same reason as snapshotcopygrant above. - SnapshotSchedule schedule = snapshotSchedules.get(id) + SnapshotSchedule schedule = snapshotSchedules.get(regionalKey(id)) .orElseThrow(() -> new AwsException("ResourceNotFoundFault", "Snapshot schedule " + id + " not found", 404)); yield new TagHandle(schedule.getTags(), updated -> { schedule.setTags(updated); - snapshotSchedules.put(id, schedule); + snapshotSchedules.put(regionalKey(id), schedule); snapshotSchedules.flush(); }); } diff --git a/src/test/java/io/floci/aws/core/common/AvailabilityZoneIdsTest.java b/src/test/java/io/floci/aws/core/common/AvailabilityZoneIdsTest.java index 6359456821..0408646ba2 100644 --- a/src/test/java/io/floci/aws/core/common/AvailabilityZoneIdsTest.java +++ b/src/test/java/io/floci/aws/core/common/AvailabilityZoneIdsTest.java @@ -5,6 +5,7 @@ import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; class AvailabilityZoneIdsTest { @@ -54,4 +55,14 @@ class AvailabilityZoneIdsTest { assertEquals(-1, AvailabilityZoneIds.indexOf("us-east-1", "use1-azx")); assertEquals(-1, AvailabilityZoneIds.indexOf("us-east-1", null)); } + + @Test + void aZonesRegionIsItsNameWithoutTheZoneLetter() { + assertEquals("us-east-1", AvailabilityZoneIds.regionOf("us-east-1a")); + assertEquals("cn-northwest-1", AvailabilityZoneIds.regionOf("cn-northwest-1c")); + assertNull(AvailabilityZoneIds.regionOf("use1-az1")); + assertNull(AvailabilityZoneIds.regionOf("a")); + assertNull(AvailabilityZoneIds.regionOf("")); + assertNull(AvailabilityZoneIds.regionOf(null)); + } } diff --git a/src/test/java/io/floci/aws/core/storage/StorageJsonTest.java b/src/test/java/io/floci/aws/core/storage/StorageJsonTest.java new file mode 100644 index 0000000000..b95895d541 --- /dev/null +++ b/src/test/java/io/floci/aws/core/storage/StorageJsonTest.java @@ -0,0 +1,43 @@ +package io.floci.aws.core.storage; + +import org.junit.jupiter.api.Test; + +import java.time.Instant; +import java.util.LinkedHashMap; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotSame; + +class StorageJsonTest { + + /** A record as the stores keep them: a plain Jackson bean, with a Java time field. */ + public static class Item { + private Instant updatedAt; + private Map tags = new LinkedHashMap<>(); + + public Instant getUpdatedAt() { return updatedAt; } + public void setUpdatedAt(Instant updatedAt) { this.updatedAt = updatedAt; } + public Map getTags() { return tags; } + public void setTags(Map tags) { this.tags = tags; } + } + + @Test + void aCopyHoldsTheSameValuesInARecordOfItsOwn() { + Item item = new Item(); + item.setUpdatedAt(Instant.parse("2026-11-01T00:00:00.123456789Z")); + item.getTags().put("team", "data"); + + Item copy = StorageJson.copy(item); + copy.getTags().put("team", "web"); + + assertNotSame(item, copy); + assertEquals(item.getUpdatedAt(), copy.getUpdatedAt()); + assertEquals(Map.of("team", "data"), item.getTags()); + } + + @Test + void theMapperWritesTimesAsTextAsTheFileStoragesDo() throws Exception { + assertEquals("\"2026-11-01T00:00:00Z\"", StorageJson.mapper().writeValueAsString(Instant.parse("2026-11-01T00:00:00Z"))); + } +} diff --git a/src/test/java/io/floci/aws/services/redshift/RedshiftAutomatedSnapshotServiceTest.java b/src/test/java/io/floci/aws/services/redshift/RedshiftAutomatedSnapshotServiceTest.java index d7f68f120f..43c56e98ed 100644 --- a/src/test/java/io/floci/aws/services/redshift/RedshiftAutomatedSnapshotServiceTest.java +++ b/src/test/java/io/floci/aws/services/redshift/RedshiftAutomatedSnapshotServiceTest.java @@ -304,7 +304,7 @@ class RedshiftAutomatedSnapshotServiceTest { assertNotNull(changed.getUpdatedAt()); Instant activation = ANCHOR.plusSeconds(7200); changed.setUpdatedAt(activation); - fixture.schedules().putForAccount(ACCOUNT, changed.getScheduleIdentifier(), changed); + fixture.schedules().putForAccount(ACCOUNT, RedshiftService.regionalKey("us-east-1", changed.getScheduleIdentifier()), changed); fixture.service().runSnapshotSchedules(activation.plusSeconds(7199)); assertEquals(1, fixture.snapshots().scanForAccount(ACCOUNT, key -> true).size()); @@ -334,9 +334,9 @@ class RedshiftAutomatedSnapshotServiceTest { Instant activation = Instant.now().minusSeconds(7200); Cluster cluster = seed(fixture, ACCOUNT, "warehouse", "us-east-1", "rate(24 hours)"); cluster.setAutomatedSnapshotAnchor(activation); - SnapshotSchedule schedule = spy(fixture.schedules().getForAccount(ACCOUNT, "schedule-warehouse").orElseThrow()); + SnapshotSchedule schedule = spy(fixture.schedules().getForAccount(ACCOUNT, RedshiftService.regionalKey("us-east-1", "schedule-warehouse")).orElseThrow()); schedule.setUpdatedAt(activation); - fixture.schedules().putForAccount(ACCOUNT, "schedule-warehouse", schedule); + fixture.schedules().putForAccount(ACCOUNT, RedshiftService.regionalKey("us-east-1", "schedule-warehouse"), schedule); CountDownLatch betweenSetters = new CountDownLatch(1); CountDownLatch release = new CountDownLatch(1); doAnswer(invocation -> { @@ -452,7 +452,7 @@ class RedshiftAutomatedSnapshotServiceTest { if (definition != null) { SnapshotSchedule schedule = new SnapshotSchedule("schedule-" + id, null, List.of(definition)); schedule.setUpdatedAt(ANCHOR); - fixture.schedules().putForAccount(account, schedule.getScheduleIdentifier(), schedule); + fixture.schedules().putForAccount(account, RedshiftService.regionalKey(region, schedule.getScheduleIdentifier()), schedule); cluster.setSnapshotScheduleIdentifier(schedule.getScheduleIdentifier()); } fixture.clusters().putForAccount(account, id, cluster); diff --git a/src/test/java/io/floci/aws/services/redshift/RedshiftOperationsTest.java b/src/test/java/io/floci/aws/services/redshift/RedshiftOperationsTest.java index 209c3ba50b..97d7a39aa7 100644 --- a/src/test/java/io/floci/aws/services/redshift/RedshiftOperationsTest.java +++ b/src/test/java/io/floci/aws/services/redshift/RedshiftOperationsTest.java @@ -7,6 +7,7 @@ import io.floci.aws.services.redshift.container.RedshiftContainerHandle; import io.floci.aws.services.redshift.container.RedshiftContainerManager; import io.floci.aws.services.redshift.model.ClusterParameterGroup; import io.floci.aws.services.redshift.model.Parameter; +import io.floci.aws.testing.QueryRequests; import io.quarkus.test.InjectMock; import io.quarkus.test.junit.QuarkusTest; import io.restassured.path.xml.XmlPath; @@ -1144,15 +1145,14 @@ public class RedshiftOperationsTest { } + /** {@link #redshift} signed for {@code region}. */ + private static Response redshiftIn(String region, String action, String... keyValues) { + return QueryRequests.request("test", region, "redshift", action, keyValues) + .contentType("application/x-www-form-urlencoded").when().post("/"); + } + private static Response redshift(String action, String... keyValues) { - RequestSpecification request = given() - .contentType("application/x-www-form-urlencoded") - .header("Authorization", AUTH_HEADER) - .formParam("Action", action); - for (int i = 0; i < keyValues.length; i += 2) { - request.formParam(keyValues[i], keyValues[i + 1]); - } - return request.when().post("/"); + return redshiftIn("us-east-1", action, keyValues); } private static void assertFault(Response response, int status, String code) { @@ -1233,8 +1233,10 @@ public class RedshiftOperationsTest { assertFalse(redshift("DescribeClusters", "ClusterIdentifier", "cluster-copy").asString() .contains("ClusterSnapshotCopyStatus")); - // A grant named on enable is reported back. - assertEquals(200, redshift("CreateSnapshotCopyGrant", "SnapshotCopyGrantName", "copy-lifecycle-grant").statusCode()); + // A grant named on enable is reported back. It is made in the destination Region, as on AWS: the source + // Region has no grant of that name. + assertEquals(200, redshiftIn("us-west-2", "CreateSnapshotCopyGrant", + "SnapshotCopyGrantName", "copy-lifecycle-grant").statusCode()); assertEquals(200, redshift("EnableSnapshotCopy", "ClusterIdentifier", "cluster-copy", "DestinationRegion", "us-west-2", "RetentionPeriod", "3", "ManualSnapshotRetentionPeriod", "5", "SnapshotCopyGrantName", "copy-lifecycle-grant").statusCode()); @@ -1244,13 +1246,16 @@ public class RedshiftOperationsTest { assertEquals(5, copy.getInt("ClusterSnapshotCopyStatus.ManualSnapshotRetentionPeriod")); // A grant a cluster's enabled copy still names cannot be deleted (InvalidSnapshotCopyGrantStateFault). - assertFault(redshift("DeleteSnapshotCopyGrant", "SnapshotCopyGrantName", "copy-lifecycle-grant"), + assertFault(redshiftIn("us-west-2", "DeleteSnapshotCopyGrant", "SnapshotCopyGrantName", "copy-lifecycle-grant"), 400, "InvalidSnapshotCopyGrantStateFault"); + assertFault(redshift("DeleteSnapshotCopyGrant", "SnapshotCopyGrantName", "copy-lifecycle-grant"), + 400, "SnapshotCopyGrantNotFoundFault"); assertEquals(200, redshift("DisableSnapshotCopy", "ClusterIdentifier", "cluster-copy").statusCode()); assertEquals(200, redshift("DeleteCluster", "ClusterIdentifier", "cluster-copy", "SkipFinalClusterSnapshot", "true").statusCode()); - assertEquals(200, redshift("DeleteSnapshotCopyGrant", "SnapshotCopyGrantName", "copy-lifecycle-grant").statusCode()); + assertEquals(200, redshiftIn("us-west-2", "DeleteSnapshotCopyGrant", + "SnapshotCopyGrantName", "copy-lifecycle-grant").statusCode()); } /** @@ -1404,10 +1409,12 @@ public class RedshiftOperationsTest { AccountAwareStorageBackend backend = storageFactory.create( "redshift", "redshift-parameter-groups.json", new TypeReference>() {}); - assertTrue(backend.get(name).isEmpty()); + // Parameter groups are Regional: stored under their Region, us-east-1 here. + String key = RedshiftService.regionalKey("us-east-1", name); + assertTrue(backend.get(key).isEmpty()); ClusterParameterGroup legacy = new ClusterParameterGroup(name, "redshift-1.0", "legacy custom group"); legacy.setParameters(List.of(new Parameter("max_cursor_result_set_size", "1000"))); - backend.put(name, legacy); + backend.put(key, legacy); backend.flush(); try { redshift("DescribeClusterParameterGroups", "ParameterGroupName", name).then().statusCode(200) @@ -1426,7 +1433,7 @@ public class RedshiftOperationsTest { .body(containsString("engine-default")); redshift("DeleteClusterParameterGroup", "ParameterGroupName", name).then().statusCode(200); } finally { - backend.delete(name); + backend.delete(key); backend.flush(); } redshift("DescribeClusterParameterGroups", "ParameterGroupName", name).then().statusCode(200) diff --git a/src/test/java/io/floci/aws/services/redshift/RedshiftRegionScopingIntegrationTest.java b/src/test/java/io/floci/aws/services/redshift/RedshiftRegionScopingIntegrationTest.java new file mode 100644 index 0000000000..9efa7b953b --- /dev/null +++ b/src/test/java/io/floci/aws/services/redshift/RedshiftRegionScopingIntegrationTest.java @@ -0,0 +1,131 @@ +package io.floci.aws.services.redshift; + +import io.floci.aws.testing.QueryRequests; +import io.floci.aws.testing.TestAccounts; +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.path.xml.XmlPath; +import io.restassured.response.Response; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Cluster parameter groups, subnet groups, snapshot schedules and snapshot copy grants are Regional on AWS: one + * created in a Region of an account is listed, found by its name and tagged only in that Region, and the same name + * can be used in another Region. Each case creates the resource in {@link #HOME}, checks it from there and from + * {@link #OTHER_REGION}, creates the same name in {@link #OTHER_REGION} and deletes it there, leaving + * {@link #HOME}'s. + */ +@QuarkusTest +class RedshiftRegionScopingIntegrationTest { + + private static final String ACCOUNT = TestAccounts.randomId(); + private static final String HOME = "eu-west-1"; + private static final String OTHER_REGION = "eu-central-1"; + + @Test + void aClusterParameterGroupIsRegional() { + assertRegional(new Kind("ClusterParameterGroup", "ParameterGroupName", "parametergroup", + "ClusterParameterGroupNotFound", "ParameterGroupFamily", "redshift-1.0", "Description", "Region scoping"), + "region-scoped-parameters"); + } + + @Test + void aClusterSubnetGroupIsRegional() { + assertRegional(new Kind("ClusterSubnetGroup", "ClusterSubnetGroupName", "subnetgroup", + "ClusterSubnetGroupNotFoundFault", "Description", "Region scoping", + "SubnetIds.SubnetIdentifier.1", "subnet-0a1b2c3d"), "region-scoped-subnets"); + } + + @Test + void aSnapshotScheduleIsRegional() { + // DescribeSnapshotSchedules lists no error: an unknown schedule is an empty list. + assertRegional(new Kind("SnapshotSchedule", "ScheduleIdentifier", "snapshotschedule", + null, "ScheduleDefinitions.ScheduleDefinition.1", "rate(12 hours)"), "region-scoped-schedule"); + } + + @Test + void aSnapshotCopyGrantIsRegional() { + assertRegional(new Kind("SnapshotCopyGrant", "SnapshotCopyGrantName", "snapshotcopygrant", + "SnapshotCopyGrantNotFoundFault"), "region-scoped-grant"); + } + + /** + * A {@code Create}, {@code Describes}, {@code Delete} family of calls naming the resource by + * {@code nameParam}, which the describe answer lists it under too, and tagged as {@code tagType}. + * {@code notFound} is the error a describe by name answers for a missing one, or null when it answers an empty + * list. + */ + private record Kind(String name, String nameParam, String tagType, String notFound, String... createParams) { + } + + private static void assertRegional(Kind kind, String name) { + create(kind, HOME, name).then().statusCode(200); + try { + describedIn(HOME, kind, name); + notDescribedIn(OTHER_REGION, kind, name); + + create(kind, OTHER_REGION, name).then().statusCode(200); + describedIn(OTHER_REGION, kind, name); + send(OTHER_REGION, "Delete" + kind.name(), kind.nameParam(), name).then().statusCode(200); + notDescribedIn(OTHER_REGION, kind, name); + describedIn(HOME, kind, name); + } finally { + send(HOME, "Delete" + kind.name(), kind.nameParam(), name); + send(OTHER_REGION, "Delete" + kind.name(), kind.nameParam(), name); + } + } + + /** Created with the tag {@code scope=}, so each Region's DescribeTags can be told apart. */ + private static Response create(Kind kind, String region, String name) { + List params = new ArrayList<>(List.of(kind.nameParam(), name, + "Tags.Tag.1.Key", "scope", "Tags.Tag.1.Value", region)); + params.addAll(List.of(kind.createParams())); + return send(region, "Create" + kind.name(), params.toArray(String[]::new)); + } + + private static void describedIn(String region, Kind kind, String name) { + assertTrue(names(send(region, "Describe" + kind.name() + "s"), kind).contains(name)); + assertEquals(List.of(name), names(send(region, "Describe" + kind.name() + "s", kind.nameParam(), name), kind)); + assertEquals(List.of(region), elements(send(region, "DescribeTags", "ResourceName", arn(region, kind, name)), + "Value")); + } + + private static void notDescribedIn(String region, Kind kind, String name) { + assertFalse(names(send(region, "Describe" + kind.name() + "s"), kind).contains(name)); + Response byName = send(region, "Describe" + kind.name() + "s", kind.nameParam(), name); + if (kind.notFound() == null) { + assertEquals(List.of(), names(byName, kind)); + } else { + assertEquals(kind.notFound(), XmlPath.from(byName.asString()).getString("ErrorResponse.Error.Code")); + } + // The account is this class's own, so no other resource of the type is tagged in the Region. + assertEquals(List.of(), elements(send(region, "DescribeTags", "ResourceType", kind.tagType()), "ResourceName")); + } + + /** The names a describe answer lists. */ + private static List names(Response response, Kind kind) { + return elements(response, kind.nameParam()); + } + + /** The text of every {@code element} in a successful answer. */ + private static List elements(Response response, String element) { + response.then().statusCode(200); + return XmlPath.from(response.asString()) + .getList("**.findAll { it.name() == '" + element + "' }", String.class); + } + + private static String arn(String region, Kind kind, String name) { + return "arn:aws:redshift:" + region + ":" + ACCOUNT + ":" + kind.tagType() + ":" + name; + } + + /** A Redshift Query request from {@code region} of {@link #ACCOUNT}, with {@code params} as name/value pairs. */ + private static Response send(String region, String action, String... params) { + return QueryRequests.request(ACCOUNT, region, "redshift", action, params).when().post("/"); + } +} diff --git a/src/test/java/io/floci/aws/services/redshift/RedshiftRegionalRecordsMigrationTest.java b/src/test/java/io/floci/aws/services/redshift/RedshiftRegionalRecordsMigrationTest.java new file mode 100644 index 0000000000..42d5203464 --- /dev/null +++ b/src/test/java/io/floci/aws/services/redshift/RedshiftRegionalRecordsMigrationTest.java @@ -0,0 +1,270 @@ +package io.floci.aws.services.redshift; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +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.common.docker.DockerHostResolver; +import io.floci.aws.core.storage.AccountAwareStorageBackend; +import io.floci.aws.core.storage.StorageFactory; +import io.floci.aws.services.redshift.container.RedshiftContainerManager; +import io.floci.aws.services.redshift.model.Cluster; +import io.floci.aws.services.redshift.model.ClusterParameterGroup; +import io.floci.aws.services.redshift.model.ClusterSubnetGroup; +import io.floci.aws.services.redshift.model.Parameter; +import io.floci.aws.services.redshift.model.SnapshotCopyGrant; +import io.floci.aws.services.redshift.model.SnapshotSchedule; +import io.floci.aws.services.redshift.proxy.RedshiftProxyManager; +import io.floci.aws.testing.StorageFactories; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import java.nio.file.Path; +import java.time.Instant; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import static io.floci.aws.services.redshift.RedshiftService.regionalKey; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.Mockito.mock; + +/** + * Cluster parameter groups, subnet groups, snapshot schedules and snapshot copy grants were stored under their name + * alone and seen from every Region. At startup each moves to the Region it shows it was made in (a subnet group's + * subnets' Region, a copy grant's KMS key's), or else to the default Region, and is copied to every other Region + * where one of its account's clusters uses it: a cluster's parameter group, subnet group and schedule in the + * cluster's Region, its copy grant in the copy's destination Region. + */ +class RedshiftRegionalRecordsMigrationTest { + + private static final String ACCOUNT = "111111111111"; + + @TempDir + Path directory; + + private EmulatorConfig config; + private StorageFactory factory; + private AccountAwareStorageBackend groups; + private AccountAwareStorageBackend subnets; + private AccountAwareStorageBackend schedules; + private AccountAwareStorageBackend grants; + private AccountAwareStorageBackend clusters; + + /** Opens the service's stores in the test's directory; each test fills them as an older Floci stored them. */ + @BeforeEach + void openStores() { + config = StorageFactories.config(directory, ACCOUNT); + factory = StorageFactories.open(config, "persistent"); + groups = factory.create("redshift", "redshift-parameter-groups.json", + new TypeReference>() { }); + subnets = factory.create("redshift", "redshift-subnet-groups.json", + new TypeReference>() { }); + schedules = factory.create("redshift", "redshift-snapshot-schedules.json", + new TypeReference>() { }); + grants = factory.create("redshift", "redshift-snapshot-copy-grants.json", + new TypeReference>() { }); + clusters = factory.create("redshift", "redshift-clusters.json", + new TypeReference>() { }); + } + + @AfterEach + void closeStores() { + factory.shutdownAll(); + } + + @Test + void recordsStoredWithoutARegionMoveToTheDefaultRegionAndToEachRegionWhoseClustersUseThem() { + groups.putForAccount(ACCOUNT, "analytics", new ClusterParameterGroup("analytics", "redshift-1.0", "d")); + subnets.putForAccount(ACCOUNT, "private", new ClusterSubnetGroup("private", "d", null, List.of())); + schedules.putForAccount(ACCOUNT, "nightly", new SnapshotSchedule("nightly", "d", List.of("rate(12 hours)"))); + grants.putForAccount(ACCOUNT, "copies", new SnapshotCopyGrant("copies", "key")); + Cluster west = pausedCluster("west", "eu-west-1"); + west.setClusterParameterGroupName("analytics"); + west.setSnapshotScheduleIdentifier("nightly"); + clusters.putForAccount(ACCOUNT, "west", west); + Cluster east = pausedCluster("east", null); + east.setSnapshotCopyDestinationRegion("us-west-2"); + east.setSnapshotCopyGrantName("copies"); + clusters.putForAccount(ACCOUNT, "east", east); + + service("us-east-1").migrateRegionalRecords(); + + assertEquals(Set.of(regionalKey("us-east-1", "analytics"), regionalKey("eu-west-1", "analytics")), + groups.keysForAccount(ACCOUNT)); + assertEquals(Set.of(regionalKey("us-east-1", "private")), subnets.keysForAccount(ACCOUNT)); + assertEquals(Set.of(regionalKey("us-east-1", "nightly"), regionalKey("eu-west-1", "nightly")), + schedules.keysForAccount(ACCOUNT)); + assertEquals(Set.of(regionalKey("us-east-1", "copies"), regionalKey("us-west-2", "copies")), + grants.keysForAccount(ACCOUNT)); + assertEquals("analytics", service("eu-west-1").describeClusterParameterGroups("analytics") + .get(0).getParameterGroupName()); + assertEquals("ClusterSubnetGroupNotFoundFault", assertThrows(AwsException.class, + () -> service("eu-west-1").describeClusterSubnetGroups("private")).getErrorCode()); + } + + /** + * Each Region a record is copied to gets one of its own: changing or tagging one Region's record leaves the + * other Region's as it was. + */ + @Test + void eachRegionGetsARecordOfItsOwn() { + groups.putForAccount(ACCOUNT, "analytics", new ClusterParameterGroup("analytics", "redshift-1.0", "d")); + grants.putForAccount(ACCOUNT, "copies", new SnapshotCopyGrant("copies", "key")); + Cluster west = pausedCluster("west", "eu-west-1"); + west.setClusterParameterGroupName("analytics"); + west.setSnapshotCopyDestinationRegion("us-west-2"); + west.setSnapshotCopyGrantName("copies"); + clusters.putForAccount(ACCOUNT, "west", west); + service("us-east-1").migrateRegionalRecords(); + + RedshiftService westService = service("eu-west-1"); + westService.modifyClusterParameterGroup("analytics", + List.of(new Parameter(CURSOR_SIZE, "1000"))); + westService.createTags("arn:aws:redshift:eu-west-1:" + ACCOUNT + ":parametergroup:analytics", + Map.of("team", "west")); + service("us-west-2").createTags( + "arn:aws:redshift:us-west-2:" + ACCOUNT + ":snapshotcopygrant:copies", Map.of("team", "west")); + + ClusterParameterGroup eastGroup = groups.getForAccount(ACCOUNT, regionalKey("us-east-1", "analytics")) + .orElseThrow(); + ClusterParameterGroup westGroup = groups.getForAccount(ACCOUNT, regionalKey("eu-west-1", "analytics")) + .orElseThrow(); + assertEquals("1000", parameterValue(westGroup, CURSOR_SIZE)); + assertEquals(parameterValue(new ClusterParameterGroup("analytics", "redshift-1.0", "d"), CURSOR_SIZE), + parameterValue(eastGroup, CURSOR_SIZE)); + assertEquals(Map.of("team", "west"), westGroup.getTags()); + assertEquals(Map.of(), eastGroup.getTags()); + assertEquals(Map.of("team", "west"), + grants.getForAccount(ACCOUNT, regionalKey("us-west-2", "copies")).orElseThrow().getTags()); + assertEquals(Map.of(), + grants.getForAccount(ACCOUNT, regionalKey("us-east-1", "copies")).orElseThrow().getTags()); + } + + /** + * A grant copied to another Region that held its first Region's default key, as a grant created without + * {@code KmsKeyId} does, holds the other Region's default key; a key the grant named stays as it was. + */ + @Test + void aGrantCopiedToAnotherRegionTakesThatRegionsDefaultKey() { + String eastDefault = "arn:aws:kms:us-east-1:" + ACCOUNT + ":alias/aws/redshift"; + String named = "arn:aws:kms:us-east-1:" + ACCOUNT + ":key/1234abcd-12ab-34cd-56ef-1234567890ab"; + grants.putForAccount(ACCOUNT, "defaulted", new SnapshotCopyGrant("defaulted", eastDefault)); + grants.putForAccount(ACCOUNT, "named", new SnapshotCopyGrant("named", named)); + Cluster first = pausedCluster("first", null); + first.setSnapshotCopyDestinationRegion("us-west-2"); + first.setSnapshotCopyGrantName("defaulted"); + clusters.putForAccount(ACCOUNT, "first", first); + Cluster second = pausedCluster("second", null); + second.setSnapshotCopyDestinationRegion("us-west-2"); + second.setSnapshotCopyGrantName("named"); + clusters.putForAccount(ACCOUNT, "second", second); + + service("us-east-1").migrateRegionalRecords(); + + assertEquals("arn:aws:kms:us-west-2:" + ACCOUNT + ":alias/aws/redshift", + grants.getForAccount(ACCOUNT, regionalKey("us-west-2", "defaulted")).orElseThrow().getKmsKeyId()); + assertEquals(eastDefault, + grants.getForAccount(ACCOUNT, regionalKey("us-east-1", "defaulted")).orElseThrow().getKmsKeyId()); + assertEquals(named, + grants.getForAccount(ACCOUNT, regionalKey("us-west-2", "named")).orElseThrow().getKmsKeyId()); + } + + /** + * A grant created in another Region holds that Region's key, so it moves there with its key, and not to the + * default Region. A grant whose key is no ARN moves to the default Region. + */ + @Test + void aGrantMovesToTheRegionOfItsKey() { + String westDefault = "arn:aws:kms:us-west-2:" + ACCOUNT + ":alias/aws/redshift"; + grants.putForAccount(ACCOUNT, "copies", new SnapshotCopyGrant("copies", westDefault)); + grants.putForAccount(ACCOUNT, "keyless", new SnapshotCopyGrant("keyless", "1234abcd")); + Cluster east = pausedCluster("east", null); + east.setSnapshotCopyDestinationRegion("us-west-2"); + east.setSnapshotCopyGrantName("copies"); + clusters.putForAccount(ACCOUNT, "east", east); + + service("us-east-1").migrateRegionalRecords(); + + assertEquals(Set.of(regionalKey("us-west-2", "copies"), regionalKey("us-east-1", "keyless")), + grants.keysForAccount(ACCOUNT)); + assertEquals(westDefault, + grants.getForAccount(ACCOUNT, regionalKey("us-west-2", "copies")).orElseThrow().getKmsKeyId()); + } + + /** + * A subnet group whose subnets EC2 placed in one Region moves to that Region, and not to the default Region, + * unless a cluster there uses it: then the default Region gets a copy. One whose subnets span Regions, or that EC2 + * never placed, moves to the default Region. + */ + @Test + void aSubnetGroupMovesToTheRegionOfItsSubnets() { + ClusterSubnetGroup west = new ClusterSubnetGroup("west", "d", "vpc-1", List.of("subnet-a", "subnet-b")); + west.setSubnetZones(Map.of("subnet-a", "eu-west-1a", "subnet-b", "eu-west-1b")); + subnets.putForAccount(ACCOUNT, "west", west); + ClusterSubnetGroup spread = new ClusterSubnetGroup("spread", "d", "vpc-2", List.of("subnet-c", "subnet-d")); + spread.setSubnetZones(Map.of("subnet-c", "eu-west-1a", "subnet-d", "us-west-2a")); + subnets.putForAccount(ACCOUNT, "spread", spread); + subnets.putForAccount(ACCOUNT, "unplaced", new ClusterSubnetGroup("unplaced", "d", null, List.of("subnet-e"))); + ClusterSubnetGroup shared = new ClusterSubnetGroup("shared", "d", "vpc-3", List.of("subnet-f")); + shared.setSubnetZones(Map.of("subnet-f", "eu-west-1c")); + subnets.putForAccount(ACCOUNT, "shared", shared); + Cluster east = pausedCluster("east", null); + east.setClusterSubnetGroupName("shared"); + clusters.putForAccount(ACCOUNT, "east", east); + + service("us-east-1").migrateRegionalRecords(); + + assertEquals(Set.of(regionalKey("eu-west-1", "west"), regionalKey("us-east-1", "spread"), + regionalKey("us-east-1", "unplaced"), regionalKey("eu-west-1", "shared"), + regionalKey("us-east-1", "shared")), subnets.keysForAccount(ACCOUNT)); + } + + /** + * A service given a plain ObjectMapper, without the Java time module, still copies a record carrying an + * {@code Instant}: a snapshot schedule's {@code updatedAt}. + */ + @Test + void aRecordWithAnInstantIsCopiedWhateverMapperTheServiceWasGiven() { + SnapshotSchedule nightly = new SnapshotSchedule("nightly", "d", List.of("rate(12 hours)")); + nightly.setUpdatedAt(Instant.parse("2026-11-01T00:00:00Z")); + schedules.putForAccount(ACCOUNT, "nightly", nightly); + Cluster west = pausedCluster("west", "eu-west-1"); + west.setSnapshotScheduleIdentifier("nightly"); + clusters.putForAccount(ACCOUNT, "west", west); + + new RedshiftService(factory, mock(RedshiftContainerManager.class), config, + new RegionResolver("us-east-1", ACCOUNT), mock(RedshiftProxyManager.class), + mock(DockerHostResolver.class), new RedshiftCredentialBroker(), null, new ObjectMapper(), null) + .migrateRegionalRecords(); + + assertEquals(Instant.parse("2026-11-01T00:00:00Z"), + schedules.getForAccount(ACCOUNT, regionalKey("eu-west-1", "nightly")).orElseThrow().getUpdatedAt()); + } + + private static final String CURSOR_SIZE = "max_cursor_result_set_size"; + + private static String parameterValue(ClusterParameterGroup group, String name) { + return group.getParameters().stream().filter(parameter -> name.equals(parameter.getParameterName())) + .findFirst().orElseThrow().getParameterValue(); + } + + private static Cluster pausedCluster(String identifier, String region) { + Cluster cluster = new Cluster(); + cluster.setClusterIdentifier(identifier); + cluster.setClusterStatus("paused"); + cluster.setSnapshotRegion(region); + return cluster; + } + + /** A service whose calls run in {@code region}, its default Region too, over the test's stores. */ + private RedshiftService service(String region) { + return new RedshiftService(factory, mock(RedshiftContainerManager.class), config, + new RegionResolver(region, ACCOUNT), mock(RedshiftProxyManager.class), mock(DockerHostResolver.class), + new RedshiftCredentialBroker()); + } +} diff --git a/src/test/java/io/floci/aws/services/redshift/RedshiftServiceTest.java b/src/test/java/io/floci/aws/services/redshift/RedshiftServiceTest.java index 50345c0a70..bd4bc95354 100644 --- a/src/test/java/io/floci/aws/services/redshift/RedshiftServiceTest.java +++ b/src/test/java/io/floci/aws/services/redshift/RedshiftServiceTest.java @@ -527,9 +527,9 @@ class RedshiftServiceTest { @ParameterizedTest @ValueSource(booleans = {false, true}) - void activityParameterUpdatesStayWithinTheCallingAccount(boolean reset) { + void activityParameterUpdatesStayWithinTheCallingAccountAndRegion(boolean reset) { ClusterParameterGroup group = new ClusterParameterGroup("shared", "redshift-1.0", "audit"); - when(parameterGroupBackend.get("shared")).thenReturn(Optional.of(group)); + when(parameterGroupBackend.get(regionalKey("shared"))).thenReturn(Optional.of(group)); Cluster owned = new Cluster(); owned.setClusterIdentifier("owned"); owned.setClusterParameterGroupName("shared"); @@ -538,10 +538,17 @@ class RedshiftServiceTest { foreign.setClusterIdentifier("foreign"); foreign.setClusterParameterGroupName("shared"); foreign.setUserActivityLoggingEnabled(reset); + // A cluster of another Region uses that Region's group of the same name. + Cluster otherRegion = new Cluster(); + otherRegion.setClusterIdentifier("west"); + otherRegion.setClusterParameterGroupName("shared"); + otherRegion.setSnapshotRegion("eu-west-1"); + otherRegion.setUserActivityLoggingEnabled(reset); when(clusterBackend.scanAllAccountEntries(any())).thenReturn(List.of( new AccountAwareStorageBackend.AccountEntry<>("111111111111", "owned", owned), - new AccountAwareStorageBackend.AccountEntry<>("222222222222", "foreign", foreign))); - when(clusterBackend.scan(any())).thenReturn(List.of(owned)); + new AccountAwareStorageBackend.AccountEntry<>("222222222222", "foreign", foreign), + new AccountAwareStorageBackend.AccountEntry<>("111111111111", "west", otherRegion))); + when(clusterBackend.scan(any())).thenReturn(List.of(owned, otherRegion)); if (reset) { service.resetClusterParameterGroup("shared", true, List.of()); @@ -551,7 +558,33 @@ class RedshiftServiceTest { assertEquals(!reset, owned.isUserActivityLoggingEnabled()); assertEquals(reset, foreign.isUserActivityLoggingEnabled()); + assertEquals(reset, otherRegion.isUserActivityLoggingEnabled()); verify(clusterBackend, never()).putForAccount(eq("222222222222"), anyString(), any()); + verify(clusterBackend, never()).putForAccount(anyString(), eq("west"), any()); + } + + /** + * A snapshot schedule is in use only by the clusters of its Region: a cluster of another Region using a + * schedule of the same name is not one of its clusters and does not keep it from being deleted. + */ + @Test + void aSnapshotScheduleIsInUseOnlyByTheClustersOfItsRegion() { + Cluster west = storedCluster("west", "eu-west-1"); + west.setSnapshotScheduleIdentifier("nightly"); + when(clusterBackend.scan(any())).thenReturn(List.of(west)); + SnapshotSchedule schedule = new SnapshotSchedule("nightly", null, List.of("rate(12 hours)")); + when(snapshotScheduleBackend.get(regionalKey("nightly"))).thenReturn(Optional.of(schedule)); + when(snapshotScheduleBackend.get(RedshiftService.regionalKey("eu-west-1", "nightly"))) + .thenReturn(Optional.of(schedule)); + RedshiftService westService = serviceIn("eu-west-1"); + + assertEquals(List.of("west"), westService.clustersUsingSnapshotSchedule("nightly")); + assertEquals(List.of(), service.clustersUsingSnapshotSchedule("nightly")); + assertEquals("InvalidClusterSnapshotScheduleState", assertThrows(AwsException.class, + () -> westService.deleteSnapshotSchedule("nightly")).getErrorCode()); + service.deleteSnapshotSchedule("nightly"); + verify(snapshotScheduleBackend).delete(regionalKey("nightly")); + verify(snapshotScheduleBackend, never()).delete(RedshiftService.regionalKey("eu-west-1", "nightly")); } @Test @@ -992,6 +1025,11 @@ class RedshiftServiceTest { verify(cm).start("111111111111", "c-ra3", "admin", "pw", "dev", "ra3.xlplus"); } + /** The key the four Regional stores keep {@code name} under in us-east-1, the fixture's Region. */ + private static String regionalKey(String name) { + return RedshiftService.regionalKey("us-east-1", name); + } + private StorageFactory sf; private AccountAwareStorageBackend clusterBackend; private AccountAwareStorageBackend snapshotBackend; @@ -1329,6 +1367,34 @@ class RedshiftServiceTest { return service.createIntegration(name, sourceArn, NAMESPACE_ARN, null, null, Map.of(), Map.of(), "us-east-1"); } + /** + * An integration is in the Region its ARN names: another Region of the account neither lists, describes nor + * deletes it, and may give its name to an integration of its own. + */ + @Test + void anIntegrationIsListedDescribedAndDeletedOnlyInItsRegion() { + Integration stored = new Integration(); + stored.setIntegrationArn("arn:aws:redshift:eu-west-1:111111111111:integration:one"); + stored.setIntegrationName("lake-to-warehouse"); + when(integrationBackend.scan(any())).thenReturn(List.of(stored)); + when(integrationBackend.keys()).thenReturn(Set.of("one")); + when(integrationBackend.get("one")).thenReturn(Optional.of(stored)); + RedshiftService west = serviceIn("eu-west-1"); + + assertEquals(List.of(stored), west.describeIntegrations(null, null, null, null).integrations()); + assertEquals(List.of(), service.describeIntegrations(null, null, null, null).integrations()); + for (Executable call : List.of( + () -> service.describeIntegrations(stored.getIntegrationArn(), null, null, null), + () -> service.deleteIntegration(stored.getIntegrationArn()))) { + assertEquals("IntegrationNotFoundFault", assertThrows(AwsException.class, call).getErrorCode()); + } + verify(integrationBackend, never()).delete(any()); + + when(zeroEtlS3.getBucketRegion("lake-bucket")).thenReturn("us-east-1"); + Integration created = createS3Integration("lake-to-warehouse", BUCKET_ARN); + assertEquals("lake-to-warehouse", created.getIntegrationName()); + } + @Test void createsAnS3EventIntegrationThatReplicatesNothing() { when(zeroEtlS3.getBucketRegion("lake-bucket")).thenReturn("us-east-1"); @@ -1713,7 +1779,7 @@ class RedshiftServiceTest { @Test void parameterGroupModifyAndResetRecordUpdatesAfterPersistence() { ClusterParameterGroup group = new ClusterParameterGroup("event-pg", "redshift-1.0", "events"); - when(parameterGroupBackend.get("event-pg")).thenReturn(Optional.of(group)); + when(parameterGroupBackend.get(regionalKey("event-pg"))).thenReturn(Optional.of(group)); service.modifyClusterParameterGroup("event-pg", List.of(new Parameter("max_cursor_result_set_size", "1000"))); service.resetClusterParameterGroup("event-pg", true, List.of()); @@ -1729,7 +1795,7 @@ class RedshiftServiceTest { @Test void invalidParameterGroupResetDoesNotRecordAnUpdate() { ClusterParameterGroup group = new ClusterParameterGroup("event-pg", "redshift-1.0", "events"); - when(parameterGroupBackend.get("event-pg")).thenReturn(Optional.of(group)); + when(parameterGroupBackend.get(regionalKey("event-pg"))).thenReturn(Optional.of(group)); assertThrows(AwsException.class, () -> service.resetClusterParameterGroup("event-pg", false, List.of("unknown-parameter"))); @@ -3359,7 +3425,7 @@ class RedshiftServiceTest { @Test void describeDefaultParameterGroupIsSynthesized() { - when(parameterGroupBackend.get("default.redshift-1.0")).thenReturn(Optional.empty()); + when(parameterGroupBackend.get(regionalKey("default.redshift-1.0"))).thenReturn(Optional.empty()); List groups = service.describeClusterParameterGroups("default.redshift-1.0"); assertEquals(1, groups.size()); @@ -3666,20 +3732,20 @@ class RedshiftServiceTest { @Test void createClusterParameterGroup() { - when(parameterGroupBackend.get("my-pg")).thenReturn(Optional.empty()); + when(parameterGroupBackend.get(regionalKey("my-pg"))).thenReturn(Optional.empty()); ClusterParameterGroup pg = service.createClusterParameterGroup("my-pg", "redshift-1.0", "custom pg"); assertNotNull(pg); assertEquals("my-pg", pg.getParameterGroupName()); assertEquals("redshift-1.0", pg.getParameterGroupFamily()); assertEquals("custom pg", pg.getDescription()); - verify(parameterGroupBackend).put(eq("my-pg"), any(ClusterParameterGroup.class)); + verify(parameterGroupBackend).put(eq(regionalKey("my-pg")), any(ClusterParameterGroup.class)); verify(parameterGroupBackend).flush(); } @Test void createClusterParameterGroupAlreadyExists() { - when(parameterGroupBackend.get("my-pg")).thenReturn(Optional.of(new ClusterParameterGroup())); + when(parameterGroupBackend.get(regionalKey("my-pg"))).thenReturn(Optional.of(new ClusterParameterGroup())); assertThrows(AwsException.class, () -> service.createClusterParameterGroup("my-pg", "redshift-1.0", "custom pg")); @@ -3688,7 +3754,7 @@ class RedshiftServiceTest { @Test void describeClusterParameterGroups() { ClusterParameterGroup pg = new ClusterParameterGroup("my-pg", "redshift-1.0", "custom pg"); - when(parameterGroupBackend.get("my-pg")).thenReturn(Optional.of(pg)); + when(parameterGroupBackend.get(regionalKey("my-pg"))).thenReturn(Optional.of(pg)); List list = service.describeClusterParameterGroups("my-pg"); assertEquals(1, list.size()); @@ -3697,7 +3763,7 @@ class RedshiftServiceTest { @Test void describeClusterParameterGroupsNotFound() { - when(parameterGroupBackend.get("missing-pg")).thenReturn(Optional.empty()); + when(parameterGroupBackend.get(regionalKey("missing-pg"))).thenReturn(Optional.empty()); assertThrows(AwsException.class, () -> service.describeClusterParameterGroups("missing-pg")); @@ -3706,18 +3772,18 @@ class RedshiftServiceTest { @Test void deleteClusterParameterGroup() { ClusterParameterGroup pg = new ClusterParameterGroup("my-pg", "redshift-1.0", "custom pg"); - when(parameterGroupBackend.get("my-pg")).thenReturn(Optional.of(pg)); + when(parameterGroupBackend.get(regionalKey("my-pg"))).thenReturn(Optional.of(pg)); ClusterParameterGroup deleted = service.deleteClusterParameterGroup("my-pg"); assertNotNull(deleted); assertEquals("my-pg", deleted.getParameterGroupName()); - verify(parameterGroupBackend).delete("my-pg"); + verify(parameterGroupBackend).delete(regionalKey("my-pg")); verify(parameterGroupBackend).flush(); } @Test void deleteClusterParameterGroupNotFound() { - when(parameterGroupBackend.get("missing-pg")).thenReturn(Optional.empty()); + when(parameterGroupBackend.get(regionalKey("missing-pg"))).thenReturn(Optional.empty()); assertThrows(AwsException.class, () -> service.deleteClusterParameterGroup("missing-pg")); @@ -3726,7 +3792,7 @@ class RedshiftServiceTest { @Test void modifyClusterParameterGroup() { ClusterParameterGroup group = new ClusterParameterGroup("my-pg", "redshift-1.0", "custom pg"); - when(parameterGroupBackend.get("my-pg")).thenReturn(Optional.of(group)); + when(parameterGroupBackend.get(regionalKey("my-pg"))).thenReturn(Optional.of(group)); ClusterParameterGroup updated = service.modifyClusterParameterGroup("my-pg", List.of(new Parameter("max_cursor_result_set_size", "1000"))); @@ -3734,14 +3800,14 @@ class RedshiftServiceTest { assertEquals("1000", updated.getParameters().stream() .filter(p -> "max_cursor_result_set_size".equals(p.getParameterName())) .findFirst().orElseThrow().getParameterValue()); - verify(parameterGroupBackend).put(eq("my-pg"), any(ClusterParameterGroup.class)); + verify(parameterGroupBackend).put(eq(regionalKey("my-pg")), any(ClusterParameterGroup.class)); verify(parameterGroupBackend).flush(); } @Test void modifyClusterParameterGroupAppendsUnknownParameter() { ClusterParameterGroup group = new ClusterParameterGroup("my-pg", "redshift-1.0", "custom pg"); - when(parameterGroupBackend.get("my-pg")).thenReturn(Optional.of(group)); + when(parameterGroupBackend.get(regionalKey("my-pg"))).thenReturn(Optional.of(group)); ClusterParameterGroup updated = service.modifyClusterParameterGroup("my-pg", List.of(new Parameter("statement_timeout", "5000"))); @@ -3752,7 +3818,7 @@ class RedshiftServiceTest { @Test void modifyClusterParameterGroupNotFound() { - when(parameterGroupBackend.get("missing")).thenReturn(Optional.empty()); + when(parameterGroupBackend.get(regionalKey("missing"))).thenReturn(Optional.empty()); assertThrows(AwsException.class, () -> service.modifyClusterParameterGroup("missing", List.of(new Parameter("x", "y")))); @@ -3762,7 +3828,7 @@ class RedshiftServiceTest { void describeClusterParametersReturnsStoredValues() { ClusterParameterGroup group = new ClusterParameterGroup("my-pg", "redshift-1.0", "custom pg"); group.setParameters(new ArrayList<>(List.of(new Parameter("statement_timeout", "5000")))); - when(parameterGroupBackend.get("my-pg")).thenReturn(Optional.of(group)); + when(parameterGroupBackend.get(regionalKey("my-pg"))).thenReturn(Optional.of(group)); List params = service.describeClusterParameters("my-pg"); @@ -3774,7 +3840,7 @@ class RedshiftServiceTest { @Test void modifyClusterParameterGroupPreservesMetadata() { ClusterParameterGroup group = new ClusterParameterGroup("my-pg", "redshift-1.0", "custom pg"); - when(parameterGroupBackend.get("my-pg")).thenReturn(Optional.of(group)); + when(parameterGroupBackend.get(regionalKey("my-pg"))).thenReturn(Optional.of(group)); // Modify using 2-arg constructor (only name and value) - should preserve description and dataType ClusterParameterGroup updated = service.modifyClusterParameterGroup("my-pg", @@ -3791,7 +3857,7 @@ class RedshiftServiceTest { @Test void resetClusterParameterGroupRestoresOnlySelectedDefaults() { ClusterParameterGroup group = new ClusterParameterGroup("reset-pg", "redshift-1.0", "description"); - when(parameterGroupBackend.get("reset-pg")).thenReturn(Optional.of(group)); + when(parameterGroupBackend.get(regionalKey("reset-pg"))).thenReturn(Optional.of(group)); service.modifyClusterParameterGroup("reset-pg", List.of( new Parameter("max_cursor_result_set_size", "1000"), new Parameter("wlm_json_configuration", "custom"))); @@ -3812,7 +3878,7 @@ class RedshiftServiceTest { void resetAllClusterParametersDropsOverridesOutsideDefaultCatalog() { ClusterParameterGroup group = new ClusterParameterGroup("reset-pg", "redshift-1.0", "description"); group.getTags().put("owner", "analytics"); - when(parameterGroupBackend.get("reset-pg")).thenReturn(Optional.of(group)); + when(parameterGroupBackend.get(regionalKey("reset-pg"))).thenReturn(Optional.of(group)); service.modifyClusterParameterGroup("reset-pg", List.of( new Parameter("max_cursor_result_set_size", "1000"), new Parameter("custom_parameter", "value"))); @@ -3832,7 +3898,7 @@ class RedshiftServiceTest { void resetClusterParametersValidatesEveryNameBeforeMutating() { ClusterParameterGroup group = new ClusterParameterGroup("reset-pg", "redshift-1.0", "description"); group.getParameters().get(0).setParameterValue("1000"); - when(parameterGroupBackend.get("reset-pg")).thenReturn(Optional.of(group)); + when(parameterGroupBackend.get(regionalKey("reset-pg"))).thenReturn(Optional.of(group)); AwsException failure = assertThrows(AwsException.class, () -> service.resetClusterParameterGroup( "reset-pg", false, List.of("max_cursor_result_set_size", "missing"))); @@ -3876,7 +3942,7 @@ class RedshiftServiceTest { String name = RedshiftService.DEFAULT_PARAMETER_GROUP_NAME; ClusterParameterGroup stored = new ClusterParameterGroup(name, "redshift-1.0", "legacy custom group"); stored.setParameters(List.of(new Parameter("max_cursor_result_set_size", "1000"))); - when(parameterGroupBackend.get(name)).thenReturn(Optional.of(stored)); + when(parameterGroupBackend.get(regionalKey(name))).thenReturn(Optional.of(stored)); assertEquals("legacy custom group", service.describeClusterParameterGroups(name).getFirst().getDescription()); List parameters = service.describeClusterParameters(name); @@ -3893,7 +3959,7 @@ class RedshiftServiceTest { String name = RedshiftService.DEFAULT_PARAMETER_GROUP_NAME; ClusterParameterGroup stored = new ClusterParameterGroup(name, "redshift-1.0", "legacy custom group"); stored.setParameters(List.of(new Parameter("max_cursor_result_set_size", "1000"))); - when(parameterGroupBackend.get(name)).thenReturn(Optional.of(stored)); + when(parameterGroupBackend.get(regionalKey(name))).thenReturn(Optional.of(stored)); service.modifyClusterParameterGroup(name, List.of(new Parameter("max_cursor_result_set_size", "2000"))); assertEquals("2000", service.describeClusterParameters(name).getFirst().getParameterValue()); @@ -3902,7 +3968,7 @@ class RedshiftServiceTest { assertEquals("0", service.describeClusterParameters(name).getFirst().getParameterValue()); assertEquals("engine-default", service.describeClusterParameters(name).getFirst().getSource()); assertEquals("legacy custom group", service.describeClusterParameterGroups(name).getFirst().getDescription()); - verify(parameterGroupBackend, times(2)).put(eq(name), any()); + verify(parameterGroupBackend, times(2)).put(eq(regionalKey(name)), any()); verify(parameterGroupBackend, times(2)).flush(); } @@ -3956,7 +4022,7 @@ class RedshiftServiceTest { {"parameterName":"wlm_json_configuration","parameterValue":"custom"} ]} """, ClusterParameterGroup.class); - when(parameterGroupBackend.get("legacy")).thenReturn(Optional.of(group)); + when(parameterGroupBackend.get(regionalKey("legacy"))).thenReturn(Optional.of(group)); List parameters = service.describeClusterParameters("legacy"); @@ -3968,7 +4034,7 @@ class RedshiftServiceTest { @Test void resetSourceSurvivesSerialization() throws Exception { ClusterParameterGroup group = new ClusterParameterGroup("reset-pg", "redshift-1.0", "description"); - when(parameterGroupBackend.get("reset-pg")).thenReturn(Optional.of(group)); + when(parameterGroupBackend.get(regionalKey("reset-pg"))).thenReturn(Optional.of(group)); service.modifyClusterParameterGroup("reset-pg", List.of(new Parameter("max_cursor_result_set_size", "0"))); assertEquals("user", service.describeClusterParameters("reset-pg").getFirst().getSource()); service.resetClusterParameterGroup("reset-pg", true, List.of()); @@ -4095,20 +4161,20 @@ class RedshiftServiceTest { @Test void createClusterSubnetGroup() { - when(subnetGroupBackend.get("my-subnet-group")).thenReturn(Optional.empty()); + when(subnetGroupBackend.get(regionalKey("my-subnet-group"))).thenReturn(Optional.empty()); ClusterSubnetGroup group = service.createClusterSubnetGroup( "my-subnet-group", "test group", "vpc-123", List.of("subnet-1", "subnet-2")); assertEquals("my-subnet-group", group.getClusterSubnetGroupName()); assertEquals(List.of("subnet-1", "subnet-2"), group.getSubnetIds()); - verify(subnetGroupBackend).put(eq("my-subnet-group"), any(ClusterSubnetGroup.class)); + verify(subnetGroupBackend).put(eq(regionalKey("my-subnet-group")), any(ClusterSubnetGroup.class)); verify(subnetGroupBackend).flush(); } @Test void createClusterSubnetGroupAlreadyExists() { - when(subnetGroupBackend.get("existing")).thenReturn(Optional.of(new ClusterSubnetGroup())); + when(subnetGroupBackend.get(regionalKey("existing"))).thenReturn(Optional.of(new ClusterSubnetGroup())); assertThrows(AwsException.class, () -> service.createClusterSubnetGroup("existing", "d", "vpc-1", List.of("subnet-1"))); @@ -4117,7 +4183,7 @@ class RedshiftServiceTest { @Test void describeClusterSubnetGroups() { ClusterSubnetGroup group = new ClusterSubnetGroup("my-group", "d", "vpc-1", List.of("subnet-1")); - when(subnetGroupBackend.get("my-group")).thenReturn(Optional.of(group)); + when(subnetGroupBackend.get(regionalKey("my-group"))).thenReturn(Optional.of(group)); List list = service.describeClusterSubnetGroups("my-group"); @@ -4128,7 +4194,7 @@ class RedshiftServiceTest { @Test void modifyClusterSubnetGroup() { ClusterSubnetGroup group = new ClusterSubnetGroup("my-group", "old", "vpc-1", List.of("subnet-1")); - when(subnetGroupBackend.get("my-group")).thenReturn(Optional.of(group)); + when(subnetGroupBackend.get(regionalKey("my-group"))).thenReturn(Optional.of(group)); ClusterSubnetGroup updated = service.modifyClusterSubnetGroup("my-group", "new", List.of("subnet-2", "subnet-3")); @@ -4139,18 +4205,18 @@ class RedshiftServiceTest { @Test void deleteClusterSubnetGroup() { ClusterSubnetGroup group = new ClusterSubnetGroup("my-group", "d", "vpc-1", List.of("subnet-1")); - when(subnetGroupBackend.get("my-group")).thenReturn(Optional.of(group)); + when(subnetGroupBackend.get(regionalKey("my-group"))).thenReturn(Optional.of(group)); ClusterSubnetGroup deleted = service.deleteClusterSubnetGroup("my-group"); assertEquals("my-group", deleted.getClusterSubnetGroupName()); - verify(subnetGroupBackend).delete("my-group"); + verify(subnetGroupBackend).delete(regionalKey("my-group")); verify(subnetGroupBackend).flush(); } @Test void deleteClusterSubnetGroupNotFound() { - when(subnetGroupBackend.get("missing")).thenReturn(Optional.empty()); + when(subnetGroupBackend.get(regionalKey("missing"))).thenReturn(Optional.empty()); assertThrows(AwsException.class, () -> service.deleteClusterSubnetGroup("missing")); } @@ -4203,19 +4269,19 @@ class RedshiftServiceTest { @Test void createsSnapshotCopyGrant() { - when(snapshotCopyGrantBackend.get("my-grant")).thenReturn(Optional.empty()); + when(snapshotCopyGrantBackend.get(regionalKey("my-grant"))).thenReturn(Optional.empty()); SnapshotCopyGrant grant = service.createSnapshotCopyGrant("my-grant", "key-abc", Map.of()); assertEquals("my-grant", grant.getSnapshotCopyGrantName()); assertEquals("key-abc", grant.getKmsKeyId()); - verify(snapshotCopyGrantBackend).put(eq("my-grant"), any(SnapshotCopyGrant.class)); + verify(snapshotCopyGrantBackend).put(eq(regionalKey("my-grant")), any(SnapshotCopyGrant.class)); verify(snapshotCopyGrantBackend).flush(); } @Test void createSnapshotCopyGrantDefaultsKmsKeyId() { - when(snapshotCopyGrantBackend.get("my-grant")).thenReturn(Optional.empty()); + when(snapshotCopyGrantBackend.get(regionalKey("my-grant"))).thenReturn(Optional.empty()); SnapshotCopyGrant grant = service.createSnapshotCopyGrant("my-grant", null, Map.of()); @@ -4224,7 +4290,7 @@ class RedshiftServiceTest { @Test void createSnapshotCopyGrantStoresTags() { - when(snapshotCopyGrantBackend.get("my-grant")).thenReturn(Optional.empty()); + when(snapshotCopyGrantBackend.get(regionalKey("my-grant"))).thenReturn(Optional.empty()); SnapshotCopyGrant grant = service.createSnapshotCopyGrant("my-grant", "key-abc", Map.of("env", "prod")); @@ -4233,7 +4299,7 @@ class RedshiftServiceTest { @Test void createSnapshotCopyGrantRejectsDuplicateName() { - when(snapshotCopyGrantBackend.get("existing")).thenReturn(Optional.of(new SnapshotCopyGrant())); + when(snapshotCopyGrantBackend.get(regionalKey("existing"))).thenReturn(Optional.of(new SnapshotCopyGrant())); AwsException ex = assertThrows(AwsException.class, () -> service.createSnapshotCopyGrant("existing", "key-abc", Map.of())); @@ -4250,7 +4316,7 @@ class RedshiftServiceTest { "g123456789012345678901234567890123456789012345678901234567890123" // 64 characters }) void createSnapshotCopyGrantRejectsNamesRedshiftRejects(String name) { - when(snapshotCopyGrantBackend.get(name)).thenReturn(Optional.empty()); + when(snapshotCopyGrantBackend.get(regionalKey(name))).thenReturn(Optional.empty()); AwsException ex = assertThrows(AwsException.class, () -> service.createSnapshotCopyGrant(name, "key-abc", Map.of())); @@ -4265,19 +4331,19 @@ class RedshiftServiceTest { void createSnapshotCopyGrantAcceptsMaximumLengthName() { String name = "g12345678901234567890123456789012345678901234567890123456789012"; assertEquals(63, name.length()); - when(snapshotCopyGrantBackend.get(name)).thenReturn(Optional.empty()); + when(snapshotCopyGrantBackend.get(regionalKey(name))).thenReturn(Optional.empty()); SnapshotCopyGrant grant = service.createSnapshotCopyGrant(name, "key-abc", Map.of()); assertEquals(name, grant.getSnapshotCopyGrantName()); - verify(snapshotCopyGrantBackend).put(eq(name), any(SnapshotCopyGrant.class)); + verify(snapshotCopyGrantBackend).put(eq(regionalKey(name)), any(SnapshotCopyGrant.class)); verify(snapshotCopyGrantBackend).flush(); } @Test void describeSnapshotCopyGrantsByName() { SnapshotCopyGrant grant = new SnapshotCopyGrant("my-grant", "key-abc"); - when(snapshotCopyGrantBackend.get("my-grant")).thenReturn(Optional.of(grant)); + when(snapshotCopyGrantBackend.get(regionalKey("my-grant"))).thenReturn(Optional.of(grant)); List list = service.describeSnapshotCopyGrants("my-grant", null, null).items(); @@ -4300,7 +4366,7 @@ class RedshiftServiceTest { @Test void describeSnapshotCopyGrantsRejectsMissingGrant() { - when(snapshotCopyGrantBackend.get("missing")).thenReturn(Optional.empty()); + when(snapshotCopyGrantBackend.get(regionalKey("missing"))).thenReturn(Optional.empty()); AwsException ex = assertThrows(AwsException.class, () -> service.describeSnapshotCopyGrants("missing", null, null)); @@ -4378,7 +4444,7 @@ class RedshiftServiceTest { // AWS documents the two as mutually exclusive but models no error, so Floci filters // by name and then paginates rather than rejecting the pair. SnapshotCopyGrant grant = new SnapshotCopyGrant("my-grant", "key-abc"); - when(snapshotCopyGrantBackend.get("my-grant")).thenReturn(Optional.of(grant)); + when(snapshotCopyGrantBackend.get(regionalKey("my-grant"))).thenReturn(Optional.of(grant)); PaginatedResult page = service.describeSnapshotCopyGrants("my-grant", null, null); @@ -4390,18 +4456,18 @@ class RedshiftServiceTest { @Test void deletesSnapshotCopyGrant() { SnapshotCopyGrant grant = new SnapshotCopyGrant("my-grant", "key-abc"); - when(snapshotCopyGrantBackend.get("my-grant")).thenReturn(Optional.of(grant)); + when(snapshotCopyGrantBackend.get(regionalKey("my-grant"))).thenReturn(Optional.of(grant)); SnapshotCopyGrant deleted = service.deleteSnapshotCopyGrant("my-grant"); assertEquals("my-grant", deleted.getSnapshotCopyGrantName()); - verify(snapshotCopyGrantBackend).delete("my-grant"); + verify(snapshotCopyGrantBackend).delete(regionalKey("my-grant")); verify(snapshotCopyGrantBackend).flush(); } @Test void deleteSnapshotCopyGrantRejectsMissingGrant() { - when(snapshotCopyGrantBackend.get("missing")).thenReturn(Optional.empty()); + when(snapshotCopyGrantBackend.get(regionalKey("missing"))).thenReturn(Optional.empty()); AwsException ex = assertThrows(AwsException.class, () -> service.deleteSnapshotCopyGrant("missing")); assertEquals("SnapshotCopyGrantNotFoundFault", ex.getErrorCode()); @@ -4413,7 +4479,7 @@ class RedshiftServiceTest { @Test void createTagsOnSnapshotCopyGrant() { SnapshotCopyGrant grant = new SnapshotCopyGrant("my-grant", "key-abc"); - when(snapshotCopyGrantBackend.get("my-grant")).thenReturn(Optional.of(grant)); + when(snapshotCopyGrantBackend.get(regionalKey("my-grant"))).thenReturn(Optional.of(grant)); service.createTags("arn:aws:redshift:us-east-1:111111111111:snapshotcopygrant:my-grant", Map.of("env", "prod")); @@ -4424,7 +4490,7 @@ class RedshiftServiceTest { @Test void createTagsOnMissingSnapshotCopyGrantIsNotFound() { - when(snapshotCopyGrantBackend.get("missing")).thenReturn(Optional.empty()); + when(snapshotCopyGrantBackend.get(regionalKey("missing"))).thenReturn(Optional.empty()); AwsException ex = assertThrows(AwsException.class, () -> service.createTags("arn:aws:redshift:us-east-1:111111111111:snapshotcopygrant:missing", @@ -4482,15 +4548,15 @@ class RedshiftServiceTest { schedule.setTags(current); when(clusterBackend.get("res")).thenReturn(Optional.of(cluster)); when(snapshotBackend.get("res")).thenReturn(Optional.of(snapshot)); - when(parameterGroupBackend.get("res")).thenReturn(Optional.of(parameterGroup)); - when(subnetGroupBackend.get("res")).thenReturn(Optional.of(subnetGroup)); - when(snapshotCopyGrantBackend.get("res")).thenReturn(Optional.of(grant)); - when(snapshotScheduleBackend.get("res")).thenReturn(Optional.of(schedule)); + when(parameterGroupBackend.get(regionalKey("res"))).thenReturn(Optional.of(parameterGroup)); + when(subnetGroupBackend.get(regionalKey("res"))).thenReturn(Optional.of(subnetGroup)); + when(snapshotCopyGrantBackend.get(regionalKey("res"))).thenReturn(Optional.of(grant)); + when(snapshotScheduleBackend.get(regionalKey("res"))).thenReturn(Optional.of(schedule)); } @Test void snapshotScheduleRejectsOutOfRangeCronFields() { - when(snapshotScheduleBackend.get("invalid-cron")).thenReturn(Optional.empty()); + when(snapshotScheduleBackend.get(regionalKey("invalid-cron"))).thenReturn(Optional.empty()); AwsException failure = assertThrows(AwsException.class, () -> service.createSnapshotSchedule( "invalid-cron", null, List.of("cron(60 12 *)"), Map.of())); diff --git a/src/test/java/io/floci/aws/services/redshift/RedshiftSnapshotCopyServiceTest.java b/src/test/java/io/floci/aws/services/redshift/RedshiftSnapshotCopyServiceTest.java index e298d14925..3f39c19559 100644 --- a/src/test/java/io/floci/aws/services/redshift/RedshiftSnapshotCopyServiceTest.java +++ b/src/test/java/io/floci/aws/services/redshift/RedshiftSnapshotCopyServiceTest.java @@ -33,6 +33,8 @@ class RedshiftSnapshotCopyServiceTest { private static final String ACCOUNT = "111111111111"; private static final String SOURCE = "us-east-1"; private static final String DESTINATION = "us-west-2"; + /** The key the copy of snapshot {@code nightly} is stored under in {@link #DESTINATION}. */ + private static final String NIGHTLY_COPY = RedshiftService.regionalKey(DESTINATION, "nightly"); @TempDir Path directory; @@ -48,7 +50,7 @@ class RedshiftSnapshotCopyServiceTest { Snapshot source = fixture.snapshots().getForAccount(ACCOUNT, "nightly").orElseThrow(); assertTrue(source.getCopiedToRegions().contains(DESTINATION)); - Snapshot copy = fixture.copies().getForAccount(ACCOUNT, DESTINATION + "::nightly").orElseThrow(); + Snapshot copy = fixture.copies().getForAccount(ACCOUNT, NIGHTLY_COPY).orElseThrow(); assertEquals("arn:aws:redshift:" + DESTINATION + ":" + ACCOUNT + ":snapshot:warehouse/nightly", copy.getSnapshotArn()); assertEquals(SOURCE, copy.getSourceRegion()); @@ -92,7 +94,7 @@ class RedshiftSnapshotCopyServiceTest { seedCluster(fixture, "warehouse", Instant.now().minusSeconds(60)); fixture.service(SOURCE).createSnapshot("nightly", "warehouse"); fixture.service(SOURCE).runSnapshotCopies(Instant.now()); - Path copiedDump = Path.of(fixture.copies().getForAccount(ACCOUNT, DESTINATION + "::nightly") + Path copiedDump = Path.of(fixture.copies().getForAccount(ACCOUNT, NIGHTLY_COPY) .orElseThrow().getSqlDump()); fixture.service(DESTINATION).deleteSnapshot("nightly"); @@ -112,7 +114,7 @@ class RedshiftSnapshotCopyServiceTest { fixture.service(SOURCE).deleteSnapshot("nightly"); - assertTrue(fixture.copies().getForAccount(ACCOUNT, DESTINATION + "::nightly").isPresent()); + assertTrue(fixture.copies().getForAccount(ACCOUNT, NIGHTLY_COPY).isPresent()); assertEquals("nightly", fixture.service(DESTINATION).describeSnapshots("nightly", null) .getFirst().getSnapshotIdentifier()); assertThrows(AwsException.class, () -> fixture.service(SOURCE).describeSnapshots("nightly", null)); @@ -126,14 +128,14 @@ class RedshiftSnapshotCopyServiceTest { fixture.clusters().putForAccount(ACCOUNT, "warehouse", cluster); fixture.service(SOURCE).createSnapshot("nightly", "warehouse"); fixture.service(SOURCE).runSnapshotCopies(Instant.now()); - Path copiedDump = Path.of(fixture.copies().getForAccount(ACCOUNT, DESTINATION + "::nightly") + Path copiedDump = Path.of(fixture.copies().getForAccount(ACCOUNT, NIGHTLY_COPY) .orElseThrow().getSqlDump()); fixture.service(SOURCE).runSnapshotCopies(Instant.now().plus(Duration.ofHours(12))); - assertTrue(fixture.copies().getForAccount(ACCOUNT, DESTINATION + "::nightly").isPresent()); + assertTrue(fixture.copies().getForAccount(ACCOUNT, NIGHTLY_COPY).isPresent()); fixture.service(SOURCE).runSnapshotCopies(Instant.now().plus(Duration.ofDays(2))); - assertTrue(fixture.copies().getForAccount(ACCOUNT, DESTINATION + "::nightly").isEmpty()); + assertTrue(fixture.copies().getForAccount(ACCOUNT, NIGHTLY_COPY).isEmpty()); assertFalse(Files.exists(copiedDump)); assertTrue(fixture.snapshots().getForAccount(ACCOUNT, "nightly").isPresent()); assertTrue(Files.exists(Path.of(fixture.snapshots().getForAccount(ACCOUNT, "nightly") @@ -164,12 +166,12 @@ class RedshiftSnapshotCopyServiceTest { Snapshot unmarked = new Snapshot(source); unmarked.getCopiedToRegions().clear(); fixture.snapshots().putForAccount(ACCOUNT, "nightly", unmarked); - String committedDump = fixture.copies().getForAccount(ACCOUNT, DESTINATION + "::nightly") + String committedDump = fixture.copies().getForAccount(ACCOUNT, NIGHTLY_COPY) .orElseThrow().getSqlDump(); fixture.service(SOURCE).runSnapshotCopies(Instant.now()); - assertEquals(committedDump, fixture.copies().getForAccount(ACCOUNT, DESTINATION + "::nightly") + assertEquals(committedDump, fixture.copies().getForAccount(ACCOUNT, NIGHTLY_COPY) .orElseThrow().getSqlDump()); assertTrue(fixture.snapshots().getForAccount(ACCOUNT, "nightly").orElseThrow() .getCopiedToRegions().contains(DESTINATION)); @@ -185,16 +187,14 @@ class RedshiftSnapshotCopyServiceTest { fixture.service(SOURCE).runSnapshotCopies(Instant.now()); assertTrue(fixture.copies().scanForAccount("222222222222", key -> true).isEmpty()); - assertTrue(Path.of(fixture.copies().getForAccount(ACCOUNT, DESTINATION + "::nightly").orElseThrow() + assertTrue(Path.of(fixture.copies().getForAccount(ACCOUNT, NIGHTLY_COPY).orElseThrow() .getSqlDump()).startsWith(directory.resolve("redshift-dumps").resolve(ACCOUNT))); } @Test void enablingCopyIntoTheClustersOwnRegionIsRefused() { Fixture fixture = fixture(); - Cluster cluster = seedCluster(fixture, "warehouse", null); - cluster.setSnapshotCopyDestinationRegion(null); - fixture.clusters().putForAccount(ACCOUNT, "warehouse", cluster); + seedCluster(fixture, "warehouse", SOURCE, null, null); AwsException refused = assertThrows(AwsException.class, () -> fixture.service(SOURCE).enableSnapshotCopy("warehouse", SOURCE, null, null, null)); @@ -204,6 +204,37 @@ class RedshiftSnapshotCopyServiceTest { assertNotNull(enabled.getSnapshotCopyEnabledAt()); } + /** + * A snapshot copy grant is made in the destination Region, as on AWS: enabling copy names one there, the copy + * takes its key, and it can't be deleted there while the cluster copies with it. A grant of the same name in + * the source Region is another grant. + */ + @Test + void theSnapshotCopyGrantIsTheDestinationRegions() { + Fixture fixture = fixture(); + seedCluster(fixture, "warehouse", SOURCE, null, null); + fixture.service(SOURCE).createSnapshotCopyGrant("copies", "source-key", null); + + AwsException missing = assertThrows(AwsException.class, + () -> fixture.service(SOURCE).enableSnapshotCopy("warehouse", DESTINATION, null, null, "copies")); + assertEquals("SnapshotCopyGrantNotFoundFault", missing.getErrorCode()); + + fixture.service(DESTINATION).createSnapshotCopyGrant("copies", "destination-key", null); + fixture.service(SOURCE).enableSnapshotCopy("warehouse", DESTINATION, null, null, "copies"); + Cluster enabled = fixture.clusters().getForAccount(ACCOUNT, "warehouse").orElseThrow(); + enabled.setSnapshotCopyEnabledAt(Instant.now().minusSeconds(60)); + fixture.clusters().putForAccount(ACCOUNT, "warehouse", enabled); + fixture.service(SOURCE).createSnapshot("nightly", "warehouse"); + fixture.service(SOURCE).runSnapshotCopies(Instant.now()); + + assertEquals("destination-key", fixture.copies().getForAccount(ACCOUNT, NIGHTLY_COPY) + .orElseThrow().getKmsKeyId()); + AwsException inUse = assertThrows(AwsException.class, + () -> fixture.service(DESTINATION).deleteSnapshotCopyGrant("copies")); + assertEquals("InvalidSnapshotCopyGrantStateFault", inUse.getErrorCode()); + assertEquals("source-key", fixture.service(SOURCE).deleteSnapshotCopyGrant("copies").getKmsKeyId()); + } + @Test void aNewSnapshotCannotTakeTheIdentifierOfACopyInThatRegion() { Fixture fixture = fixture(); @@ -224,7 +255,7 @@ class RedshiftSnapshotCopyServiceTest { seedCluster(fixture, "warehouse", Instant.now().minusSeconds(60)); fixture.service(SOURCE).createSnapshot("nightly", "warehouse"); fixture.service(SOURCE).runSnapshotCopies(Instant.now()); - String key = DESTINATION + "::nightly"; + String key = NIGHTLY_COPY; Snapshot retained = new Snapshot(fixture.copies().getForAccount(ACCOUNT, key).orElseThrow()); retained.setSourceSnapshotCreateTime(retained.getSourceSnapshotCreateTime().minusSeconds(30)); retained.setTags(new LinkedHashMap<>(Map.of("env", "prod"))); @@ -251,7 +282,7 @@ class RedshiftSnapshotCopyServiceTest { fixture.clusters().putForAccount(ACCOUNT, "warehouse", cluster); fixture.service(SOURCE).createSnapshot("nightly", "warehouse"); fixture.service(SOURCE).runSnapshotCopies(Instant.now()); - String key = DESTINATION + "::nightly"; + String key = NIGHTLY_COPY; Snapshot copy = new Snapshot(fixture.copies().getForAccount(ACCOUNT, key).orElseThrow()); copy.setSnapshotType("automated"); copy.setSnapshotCreateTime(Instant.now().minus(Duration.ofDays(3))); @@ -296,7 +327,7 @@ class RedshiftSnapshotCopyServiceTest { fixture.service(SOURCE).runSnapshotCopies(Instant.now()); - Snapshot copy = fixture.copies().getForAccount(ACCOUNT, DESTINATION + "::nightly").orElseThrow(); + Snapshot copy = fixture.copies().getForAccount(ACCOUNT, NIGHTLY_COPY).orElseThrow(); assertTrue(copy.getAccountsWithRestoreAccess().isEmpty()); }