fix(redshift): scope parameter groups, subnet groups, schedules, copy grants and integrations to their Region (#8565)

Redshift cluster parameter groups, subnet groups, snapshot schedules and snapshot copy grants are now stored under <region>::<name>, and zero-ETL integrations are listed, described and deleted only in the Region their ARN names, with names unique per Region.

The snapshot scheduler reads a cluster's schedule in the cluster's Region. EnableSnapshotCopy and snapshot copies look up the grant in the destination Region. The in-use checks for deleting a grant or schedule are scoped to the Region.

Records stored before this change move at startup. A subnet group goes to its subnets' Region and a copy grant to its KMS key's Region; anything else goes to the default Region. Every other Region where a cluster uses a record gets its own copy.

StorageJson in core.storage builds the mapper used by the persistent, hybrid and WAL storages, and copies a record through that form; AppConfigService.copy uses it too. AvailabilityZoneIds.regionOf gives a zone's Region for EFS, EKS and Redshift.

Part of #8218
This commit is contained in:
mrfelek authored and GitHub committed 2026-11-16 10:55:19 -04:00
1 parent ad6ca74685
commit 4a7953bb0b
17 files changed
+948 -194

No files matched your search

@@ -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));
}
}
@@ -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<String, String> tags = new LinkedHashMap<>();
public Instant getUpdatedAt() { return updatedAt; }
public void setUpdatedAt(Instant updatedAt) { this.updatedAt = updatedAt; }
public Map<String, String> getTags() { return tags; }
public void setTags(Map<String, String> 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")));
}
}
@@ -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);
@@ -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<ClusterParameterGroup> backend = storageFactory.create(
"redshift", "redshift-parameter-groups.json", new TypeReference<Map<String, ClusterParameterGroup>>() {});
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("<Source>engine-default</Source>"));
redshift("DeleteClusterParameterGroup", "ParameterGroupName", name).then().statusCode(200);
} finally {
backend.delete(name);
backend.delete(key);
backend.flush();
}
redshift("DescribeClusterParameterGroups", "ParameterGroupName", name).then().statusCode(200)
@@ -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<name>}, {@code Describe<name>s}, {@code Delete<name>} 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=<region>}, so each Region's DescribeTags can be told apart. */
private static Response create(Kind kind, String region, String name) {
List<String> 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<String> names(Response response, Kind kind) {
return elements(response, kind.nameParam());
}
/** The text of every {@code element} in a successful answer. */
private static List<String> 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("/");
}
}
@@ -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<ClusterParameterGroup> groups;
private AccountAwareStorageBackend<ClusterSubnetGroup> subnets;
private AccountAwareStorageBackend<SnapshotSchedule> schedules;
private AccountAwareStorageBackend<SnapshotCopyGrant> grants;
private AccountAwareStorageBackend<Cluster> 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<Map<String, ClusterParameterGroup>>() { });
subnets = factory.create("redshift", "redshift-subnet-groups.json",
new TypeReference<Map<String, ClusterSubnetGroup>>() { });
schedules = factory.create("redshift", "redshift-snapshot-schedules.json",
new TypeReference<Map<String, SnapshotSchedule>>() { });
grants = factory.create("redshift", "redshift-snapshot-copy-grants.json",
new TypeReference<Map<String, SnapshotCopyGrant>>() { });
clusters = factory.create("redshift", "redshift-clusters.json",
new TypeReference<Map<String, Cluster>>() { });
}
@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());
}
}
@@ -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<Cluster> clusterBackend;
private AccountAwareStorageBackend<Snapshot> 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.<Executable>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<ClusterParameterGroup> 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<ClusterParameterGroup> 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<Parameter> 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<Parameter> 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<Parameter> 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<ClusterSubnetGroup> 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<SnapshotCopyGrant> 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<SnapshotCopyGrant> 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()));
@@ -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());
}