feat(redshift): add event history and DescribeEvents (#6663)

This commit is contained in:
Vũ Thế Huy authored and GitHub committed 2026-10-26 21:25:14 -04:00
1 parent 15e2c98957
commit e9e2b38da6
14 files changed
+1301 -9

No files matched your search

@@ -0,0 +1,217 @@
package io.github.hectorvent.floci.services.redshift;
import com.fasterxml.jackson.core.type.TypeReference;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.PaginatedResult;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.ServiceConfigAccess;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.redshift.model.RedshiftEvent;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
class RedshiftEventServiceTest {
private MutableClock clock;
private RedshiftEventService service;
private StorageFactory factory;
@Test
void explicitRecordingUsesTheOwnersHistory() {
String owner = "565656565656";
String region = "us-west-2";
service.recordForAccount(owner, region, RedshiftEventCatalog.SNAPSHOT_COMPLETED, "owner-snapshot", "completed");
AccountAwareStorageBackend<RedshiftEvent> history = factory.create("redshift", "redshift-events.json",
new TypeReference<Map<String, RedshiftEvent>>() { });
assertEquals(1, history.scanForAccount(owner, key -> key.startsWith(region + "/")).size());
assertTrue(service.describeEvents(null, null, null, null, null, null, null).items().isEmpty());
}
@Test
void pruningRemovesExpiredHistoryAcrossAccountsAndRegionsDuringAlternatingTraffic() {
AccountAwareStorageBackend<RedshiftEvent> backend = factory.create("redshift", "redshift-events.json",
new TypeReference<Map<String, RedshiftEvent>>() { });
Instant expired = clock.instant().minus(RedshiftEventService.RETENTION).minusSeconds(1);
for (String scope : List.of("000000000000/us-east-1", "000000000000/us-west-2", "111111111111/us-east-1")) {
RedshiftEvent event = new RedshiftEvent();
event.setKey("expired");
event.setDate(expired);
int separator = scope.indexOf('/');
backend.putForAccount(scope.substring(0, separator), scope.substring(separator + 1) + "/expired", event);
}
RedshiftEvent recent = new RedshiftEvent();
recent.setKey("recent");
recent.setDate(clock.instant());
backend.putForAccount("111111111111", "us-west-2/recent", recent);
AtomicReference<String> region = new AtomicReference<>("us-east-1");
RegionResolver resolver = mock(RegionResolver.class);
when(resolver.getRegion()).thenAnswer(invocation -> region.get());
RedshiftEventService alternating = new RedshiftEventService(factory, resolver, clock);
for (int index = 0; index < 200; index++) {
region.set(index % 2 == 0 ? "us-east-1" : "us-west-2");
alternating.record(RedshiftEventCatalog.CLUSTER_CREATED, "warehouse", "created");
}
Map<String, RedshiftEvent> stored = backend.scanAllAccountsWithRawKeys();
assertEquals(201, stored.size());
assertTrue(stored.values().stream().noneMatch(event -> event.getDate().equals(expired)));
assertTrue(stored.containsKey("111111111111/us-west-2/recent"));
}
@BeforeEach
void setUp() {
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
ServiceConfigAccess access = mock(ServiceConfigAccess.class);
when(access.storageMode("redshift")).thenReturn("memory");
when(config.storage().persistentPath()).thenReturn("target/test-data");
when(config.defaultAccountId()).thenReturn("000000000000");
factory = new StorageFactory(config, access);
clock = new MutableClock(Instant.parse("2026-10-26T12:00:00Z"));
service = new RedshiftEventService(factory, new RegionResolver("us-east-1", "000000000000"), clock);
}
@Test
void describeEventsDefaultsToTheLastHour() {
service.record(RedshiftEventCatalog.CLUSTER_CREATED, "warehouse", "created");
clock.advance(Duration.ofMinutes(30));
service.record(RedshiftEventCatalog.CLUSTER_REBOOTED, "warehouse", "rebooted");
clock.advance(Duration.ofMinutes(45));
assertEquals(List.of("REDSHIFT-EVENT-3000"), ids(service.describeEvents(null, null, null, null, null, null, null)));
assertEquals(List.of("REDSHIFT-EVENT-2000", "REDSHIFT-EVENT-3000"),
ids(service.describeEvents(null, null, null, null, 120, null, null)));
}
@Test
void describeEventsFiltersBySourceAndTimeWindow() {
service.record(RedshiftEventCatalog.CLUSTER_CREATED, "warehouse", "created");
service.record(RedshiftEventCatalog.CLUSTER_CREATED, "analytics", "created");
service.record(RedshiftEventCatalog.PARAMETER_GROUP_CREATED, "warehouse", "group created");
Instant start = clock.instant().minusSeconds(60);
Instant end = clock.instant().plusSeconds(60);
List<RedshiftEvent> events = service.describeEvents("warehouse", "cluster", start, end, null, null, null).items();
assertEquals(1, events.size());
assertEquals("warehouse", events.getFirst().getSourceIdentifier());
assertTrue(service.describeEvents(null, null, end.plusSeconds(1), end.plusSeconds(2), null, null, null)
.items().isEmpty());
}
@Test
void describeEventsRejectsAnUnpairedSourceAndOutOfRangePages() {
assertEquals("InvalidParameterCombination", assertThrows(AwsException.class,
() -> service.describeEvents("warehouse", null, null, null, null, null, null)).getErrorCode());
assertEquals("InvalidParameterCombination", assertThrows(AwsException.class,
() -> service.describeEvents(null, "cluster", null, null, null, null, null)).getErrorCode());
assertEquals("InvalidParameterValue", assertThrows(AwsException.class,
() -> service.describeEvents(null, "database", null, null, null, null, null)).getErrorCode());
assertEquals("InvalidParameterValue", assertThrows(AwsException.class,
() -> service.describeEvents(null, null, null, null, null, 19, null)).getErrorCode());
assertEquals("InvalidParameterValue", assertThrows(AwsException.class,
() -> service.describeEvents(null, null, null, null, null, 101, null)).getErrorCode());
}
@Test
void describeEventsPagesWithoutRepeatingOrSkipping() {
for (int i = 0; i < 25; i++) {
service.record(RedshiftEventCatalog.CLUSTER_CREATED, "cluster-" + i, "created " + i);
}
PaginatedResult<RedshiftEvent> first = service.describeEvents(null, null, null, null, null, 20, null);
PaginatedResult<RedshiftEvent> second = service.describeEvents(null, null, null, null, null, 20,
first.nextToken());
assertEquals(20, first.items().size());
assertEquals(5, second.items().size());
assertNull(second.nextToken());
assertEquals("cluster-0", first.items().getFirst().getSourceIdentifier());
assertEquals("cluster-20", second.items().getFirst().getSourceIdentifier());
}
@Test
void describeEventsReportsAtMostFourteenDays() {
service.record(RedshiftEventCatalog.CLUSTER_CREATED, "warehouse", "created");
clock.advance(Duration.ofDays(13));
assertEquals(1, service.describeEvents(null, null, null, null, 60 * 24 * 30, null, null).items().size());
clock.advance(Duration.ofDays(2));
assertTrue(service.describeEvents(null, null, null, null, 60 * 24 * 30, null, null).items().isEmpty());
}
@Test
void describeEventCategoriesGroupsEventsBySourceType() {
Map<String, List<RedshiftEventCatalog.EventInfo>> all = service.describeEventCategories(null);
assertEquals(List.of("cluster", "cluster-parameter-group", "cluster-security-group", "cluster-snapshot",
"scheduled-action"), List.copyOf(all.keySet()));
assertTrue(all.get("cluster").stream().anyMatch(info -> "REDSHIFT-EVENT-2000".equals(info.id())));
assertEquals(List.of("cluster-snapshot"), List.copyOf(service.describeEventCategories("cluster-snapshot").keySet()));
assertTrue(service.describeEventCategories("scheduled-action").get("scheduled-action").isEmpty());
assertEquals("InvalidParameterValue", assertThrows(AwsException.class,
() -> service.describeEventCategories("database")).getErrorCode());
}
@Test
void eventHistoryIsRegional() {
service.record(RedshiftEventCatalog.CLUSTER_CREATED, "warehouse", "created");
RedshiftEventService west = new RedshiftEventService(factory,
new RegionResolver("us-west-2", "000000000000"), clock);
assertTrue(west.describeEvents(null, null, null, null, null, null, null).items().isEmpty());
assertEquals(1, service.describeEvents(null, null, null, null, null, null, null).items().size());
}
private static List<String> ids(PaginatedResult<RedshiftEvent> page) {
return page.items().stream().map(RedshiftEvent::getEventId).toList();
}
private static final class MutableClock extends Clock {
private Instant now;
private MutableClock(Instant now) {
this.now = now;
}
private void advance(Duration duration) {
now = now.plus(duration);
}
@Override
public ZoneId getZone() {
return ZoneOffset.UTC;
}
@Override
public Clock withZone(ZoneId zone) {
return this;
}
@Override
public Instant instant() {
return now;
}
}
}
@@ -0,0 +1,126 @@
package io.github.hectorvent.floci.services.redshift;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.ServiceConfigAccess;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.redshift.model.RedshiftEvent;
import org.junit.jupiter.api.io.TempDir;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import java.nio.file.Path;
import java.time.Clock;
import java.time.Instant;
import java.time.ZoneOffset;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
class RedshiftEventStorageTest {
private static final String ACCOUNT = "111111111111";
private static final String OTHER_ACCOUNT = "222222222222";
private static final String EAST = "us-east-1";
private static final String WEST = "us-west-2";
private static final Instant NOW = Instant.parse("2026-10-26T12:00:00Z");
@TempDir
Path directory;
@ParameterizedTest
@ValueSource(strings = {"persistent", "hybrid", "wal"})
void historySurvivesRestart(String mode) {
String originalKey;
try (Fixture first = fixture(mode, ACCOUNT)) {
first.east().record(RedshiftEventCatalog.CLUSTER_CREATED, "warehouse", "created before restart");
originalKey = history(first.east()).getFirst().getKey();
}
try (Fixture restarted = fixture(mode, ACCOUNT)) {
restarted.factory().loadAll();
restarted.factory().loadAll();
List<RedshiftEvent> history = history(restarted.east());
assertEquals(1, history.size());
assertEquals(originalKey, history.getFirst().getKey());
assertEquals(NOW, history.getFirst().getDate());
assertEquals("REDSHIFT-EVENT-2000", history.getFirst().getEventId());
assertEquals("created before restart", history.getFirst().getMessage());
restarted.east().record(RedshiftEventCatalog.CLUSTER_REBOOTED, "warehouse", "rebooted after restart");
assertEquals(2, history(restarted.east()).size());
}
try (Fixture third = fixture(mode, ACCOUNT)) {
assertEquals(2, history(third.east()).size());
assertEquals(2, history(third.east()).stream().map(RedshiftEvent::getKey).distinct().count());
assertEquals(List.of("REDSHIFT-EVENT-2000", "REDSHIFT-EVENT-3000"), history(third.east()).stream()
.map(RedshiftEvent::getEventId).sorted().toList());
}
}
@ParameterizedTest
@ValueSource(strings = {"persistent", "hybrid", "wal"})
void persistedHistoryStaysWithinItsAccountAndRegion(String mode) {
try (Fixture owner = fixture(mode, ACCOUNT)) {
owner.east().record(RedshiftEventCatalog.CLUSTER_CREATED, "east-cluster", "east owner");
owner.west().record(RedshiftEventCatalog.CLUSTER_CREATED, "west-cluster", "west owner");
assertEquals(List.of("east-cluster"), sourceIds(owner.east()));
assertEquals(List.of("west-cluster"), sourceIds(owner.west()));
}
try (Fixture other = fixture(mode, OTHER_ACCOUNT)) {
assertTrue(history(other.east()).isEmpty());
assertTrue(history(other.west()).isEmpty());
other.east().record(RedshiftEventCatalog.CLUSTER_CREATED, "other-cluster", "other owner");
}
try (Fixture restored = fixture(mode, ACCOUNT)) {
assertEquals(List.of("east-cluster"), sourceIds(restored.east()));
assertEquals(List.of("west-cluster"), sourceIds(restored.west()));
restored.east().record(RedshiftEventCatalog.CLUSTER_REBOOTED, "east-cluster", "owner reboot");
assertEquals(2, history(restored.east()).size());
assertEquals(1, history(restored.west()).size());
}
try (Fixture otherRestored = fixture(mode, OTHER_ACCOUNT)) {
assertEquals(List.of("other-cluster"), sourceIds(otherRestored.east()));
assertTrue(history(otherRestored.west()).isEmpty());
}
}
private Fixture fixture(String mode, String account) {
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
when(config.defaultAccountId()).thenReturn(account);
when(config.storage().persistentPath()).thenReturn(directory.toString());
when(config.storage().wal().compactionIntervalMs()).thenReturn(60_000L);
ServiceConfigAccess access = mock(ServiceConfigAccess.class);
when(access.storageMode("redshift")).thenReturn(mode);
when(access.storageFlushInterval("redshift")).thenReturn(60_000L);
StorageFactory factory = new StorageFactory(config, access);
Clock clock = Clock.fixed(NOW, ZoneOffset.UTC);
RedshiftEventService east = new RedshiftEventService(factory, new RegionResolver(EAST, account), clock);
RedshiftEventService west = new RedshiftEventService(factory, new RegionResolver(WEST, account), clock);
return new Fixture(factory, east, west);
}
private static List<RedshiftEvent> history(RedshiftEventService service) {
return service.describeEvents(null, null, null, null, null, null, null).items();
}
private static List<String> sourceIds(RedshiftEventService service) {
return history(service).stream().map(RedshiftEvent::getSourceIdentifier).toList();
}
private record Fixture(StorageFactory factory, RedshiftEventService east,
RedshiftEventService west) implements AutoCloseable {
@Override
public void close() {
factory.shutdownAll();
}
}
}
@@ -0,0 +1,147 @@
package io.github.hectorvent.floci.services.redshift;
import io.quarkus.test.common.http.TestHTTPResource;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.redshift.RedshiftClient;
import software.amazon.awssdk.services.redshift.model.DescribeEventsResponse;
import software.amazon.awssdk.services.redshift.model.Event;
import software.amazon.awssdk.services.redshift.model.EventCategoriesMap;
import software.amazon.awssdk.services.redshift.model.Parameter;
import software.amazon.awssdk.services.redshift.model.RedshiftException;
import java.net.URI;
import java.time.Instant;
import java.util.List;
import java.util.UUID;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
@QuarkusTest
class RedshiftEventsIntegrationTest {
private static final String ACCOUNT = "313131313131";
private static final String SOURCE_TYPE = "cluster-parameter-group";
@TestHTTPResource
URI endpoint;
@Test
void sdkDescribesRealParameterGroupEventsAndCategoryMetadata() {
String name = name();
Instant before = Instant.now().minusSeconds(1);
try (RedshiftClient redshift = redshift(Region.US_EAST_1)) {
createGroup(redshift, name);
try {
redshift.modifyClusterParameterGroup(request -> request.parameterGroupName(name)
.parameters(Parameter.builder().parameterName("statement_timeout").parameterValue("5000").build()));
DescribeEventsResponse response = redshift.describeEvents(request -> request.sourceIdentifier(name)
.sourceType(SOURCE_TYPE).startTime(before).endTime(Instant.now().plusSeconds(1)));
assertTrue(response.events().size() >= 2);
Event created = response.events().stream().filter(event -> "REDSHIFT-EVENT-1003".equals(event.eventId()))
.findFirst().orElseThrow();
assertEquals(name, created.sourceIdentifier());
assertEquals(SOURCE_TYPE, created.sourceTypeAsString());
assertEquals("INFO", created.severity());
assertEquals(List.of("configuration"), created.eventCategories());
assertFalse(created.date().isBefore(before));
assertTrue(created.message().contains(name));
assertTrue(response.events().stream().anyMatch(event -> "REDSHIFT-EVENT-1005".equals(event.eventId())));
List<EventCategoriesMap> categories = redshift.describeEventCategories(request -> request
.sourceType(SOURCE_TYPE)).eventCategoriesMapList();
assertEquals(1, categories.size());
assertEquals(SOURCE_TYPE, categories.getFirst().sourceType());
assertTrue(categories.getFirst().events().stream().anyMatch(info ->
"REDSHIFT-EVENT-1003".equals(info.eventId())
&& info.eventCategories().equals(List.of("configuration"))
&& "INFO".equals(info.severity()) && !info.eventDescription().isBlank()));
} finally {
redshift.deleteClusterParameterGroup(request -> request.parameterGroupName(name));
}
assertTrue(redshift.describeEvents(request -> request.sourceIdentifier(name).sourceType(SOURCE_TYPE))
.events().stream().anyMatch(event -> "REDSHIFT-EVENT-1004".equals(event.eventId())));
}
}
@Test
void sdkReceivesAwsErrorsForAnUnpairedSourceAndOutOfRangePages() {
String name = name();
try (RedshiftClient redshift = redshift(Region.US_EAST_1)) {
RedshiftException unpaired = assertThrows(RedshiftException.class, () -> redshift.describeEvents(request ->
request.sourceIdentifier(name)));
assertEquals("InvalidParameterCombination", unpaired.awsErrorDetails().errorCode());
RedshiftException pageSize = assertThrows(RedshiftException.class, () -> redshift.describeEvents(request ->
request.maxRecords(19)));
assertEquals("InvalidParameterValue", pageSize.awsErrorDetails().errorCode());
}
}
@Test
void historyIsIsolatedByRegion() {
String name = name();
try (RedshiftClient east = redshift(Region.US_EAST_1); RedshiftClient west = redshift(Region.US_WEST_2)) {
createGroup(east, name);
try {
assertEquals(1, east.describeEvents(request -> request.sourceIdentifier(name).sourceType(SOURCE_TYPE))
.events().size());
assertTrue(west.describeEvents(request -> request.sourceIdentifier(name).sourceType(SOURCE_TYPE))
.events().isEmpty());
} finally {
east.deleteClusterParameterGroup(request -> request.parameterGroupName(name));
}
}
}
@Test
void historyIsIsolatedByAccount() {
String name = name();
String otherAccount = "414141414141";
try (RedshiftClient owner = redshift(Region.US_EAST_1, ACCOUNT);
RedshiftClient other = redshift(Region.US_EAST_1, otherAccount)) {
createGroup(owner, name);
try {
assertEquals(1, owner.describeEvents(request -> request.sourceIdentifier(name).sourceType(SOURCE_TYPE))
.events().size());
assertTrue(other.describeEvents(request -> request.sourceIdentifier(name).sourceType(SOURCE_TYPE))
.events().isEmpty());
createGroup(other, name);
try {
assertEquals(1, other.describeEvents(request -> request.sourceIdentifier(name).sourceType(SOURCE_TYPE))
.events().size());
assertEquals(1, owner.describeEvents(request -> request.sourceIdentifier(name).sourceType(SOURCE_TYPE))
.events().size());
} finally {
other.deleteClusterParameterGroup(request -> request.parameterGroupName(name));
}
} finally {
owner.deleteClusterParameterGroup(request -> request.parameterGroupName(name));
}
}
}
private RedshiftClient redshift(Region region) {
return redshift(region, ACCOUNT);
}
private RedshiftClient redshift(Region region, String account) {
return RedshiftClient.builder().endpointOverride(endpoint).region(region)
.credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create(account, "test")))
.build();
}
private static String name() {
return "sdk-rsevent-" + UUID.randomUUID().toString().substring(0, 12);
}
private static void createGroup(RedshiftClient client, String name) {
client.createClusterParameterGroup(request -> request.parameterGroupName(name)
.parameterGroupFamily("redshift-1.0").description("SDK event integration"));
}
}
@@ -33,6 +33,17 @@ import static org.mockito.Mockito.*;
class RedshiftQueryHandlerTest {
@Test
void nonFiniteEventTimestampsReturnAnAwsValidationError() {
for (String invalid : List.of("NaN", "Infinity", "-Infinity", "1e300")) {
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
params.putSingle("StartTime", invalid);
AwsException error = assertThrows(AwsException.class, () -> handler.handle("DescribeEvents", params));
assertEquals("InvalidParameterValue", error.getErrorCode());
}
verifyNoInteractions(service);
}
@Test
void modifyClusterIamRolesParsesAndReturnsDefaultRole() {
String role = "arn:aws:iam::111111111111:role/default";
@@ -575,6 +575,7 @@ class RedshiftServiceTest {
private DockerHostResolver dockerHostResolver;
private RedshiftCredentialBroker credentialBroker;
private SecretsManagerService secretsManagerService;
private RedshiftEventService events;
private final Set<String> existingStreams = new HashSet<>();
private RedshiftService service;
@@ -627,6 +628,7 @@ class RedshiftServiceTest {
credentialBroker = new RedshiftCredentialBroker();
secretsManagerService = mock(SecretsManagerService.class);
events = mock(RedshiftEventService.class);
ObjectMapper mapper = new ObjectMapper();
// Answers DescribeStream the way the native handler does: it throws for an unknown stream.
DynamoDbOperations streams = call -> {
@@ -640,7 +642,167 @@ class RedshiftServiceTest {
service = new RedshiftService(sf, cm, config, regionResolver, proxyManager, dockerHostResolver,
credentialBroker, secretsManagerService, mapper,
new DynamoDbApiStreamReader(streams, CheckpointLifetime.PROCESS));
new DynamoDbApiStreamReader(streams, CheckpointLifetime.PROCESS), null, events);
}
@Test
void successfulClusterOperationsRecordTheirLifecycleEvents() {
when(cm.start(any(), any(), any(), any()))
.thenReturn(new RedshiftContainerHandle("container", "event-cluster", "localhost", 5432));
Cluster cluster = service.createCluster("event-cluster", "dc2.large", "admin", "password123");
when(clusterBackend.get("event-cluster")).thenReturn(Optional.of(cluster));
service.modifyCluster("event-cluster", null, null, "changedPassword123", "custom-pg", List.of("sg-new"));
service.rebootCluster("event-cluster");
service.deleteCluster("event-cluster");
InOrder recorded = inOrder(events);
recorded.verify(events).record(eq(RedshiftEventCatalog.CLUSTER_CREATED), eq("event-cluster"), anyString());
recorded.verify(events).record(eq(RedshiftEventCatalog.ADMIN_CREDENTIALS_UPDATED), eq("event-cluster"), anyString());
recorded.verify(events).record(eq(RedshiftEventCatalog.CLUSTER_PARAMETER_GROUP_CHANGED), eq("event-cluster"), anyString());
recorded.verify(events).record(eq(RedshiftEventCatalog.CLUSTER_SECURITY_GROUPS_UPDATED), eq("event-cluster"), anyString());
recorded.verify(events).record(eq(RedshiftEventCatalog.CLUSTER_REBOOTED), eq("event-cluster"), anyString());
recorded.verify(events).record(eq(RedshiftEventCatalog.CLUSTER_DELETED), eq("event-cluster"), anyString());
recorded.verifyNoMoreInteractions();
}
@Test
void creationEventIsRecordedBeforeAQueuedClusterOperationCanRun() throws Exception {
when(cm.start(any(), any(), any(), any()))
.thenReturn(new RedshiftContainerHandle("container", "event-cluster", "localhost", 5432));
AtomicReference<Cluster> stored = new AtomicReference<>();
when(clusterBackend.get("event-cluster")).thenAnswer(invocation -> Optional.ofNullable(stored.get()));
doAnswer(invocation -> {
stored.set(invocation.getArgument(1));
return null;
}).when(clusterBackend).put(eq("event-cluster"), any(Cluster.class));
AtomicReference<Future<?>> queued = new AtomicReference<>();
try (ExecutorService executor = Executors.newSingleThreadExecutor()) {
doAnswer(invocation -> {
queued.set(executor.submit(() -> service.rebootCluster("event-cluster")));
assertThrows(TimeoutException.class, () -> queued.get().get(300, TimeUnit.MILLISECONDS),
"A queued reboot ran before the creation event was recorded");
return null;
}).when(events).record(eq(RedshiftEventCatalog.CLUSTER_CREATED), eq("event-cluster"), anyString());
service.createCluster("event-cluster", "dc2.large", "admin", "password123");
queued.get().get(5, TimeUnit.SECONDS);
}
InOrder recorded = inOrder(events);
recorded.verify(events).record(eq(RedshiftEventCatalog.CLUSTER_CREATED), eq("event-cluster"), anyString());
recorded.verify(events).record(eq(RedshiftEventCatalog.CLUSTER_REBOOTED), eq("event-cluster"), anyString());
}
@Test
void failedClusterOperationsNeverRecordSuccessEvents() {
when(cm.start(any(), any(), any(), any())).thenThrow(new RuntimeException("startup failed"));
assertThrows(AwsException.class,
() -> service.createCluster("event-cluster", "dc2.large", "admin", "password123"));
Cluster cluster = new Cluster();
cluster.setClusterIdentifier("event-cluster");
cluster.setMasterUsername("admin");
cluster.setMasterPassword("password123");
cluster.setClusterStatus("available");
when(clusterBackend.get("event-cluster")).thenReturn(Optional.of(cluster));
doThrow(new AwsException("InternalFailure", "password change failed", 500))
.when(cm).alterUserPassword(anyString(), anyString(), anyString(), anyString());
assertThrows(AwsException.class,
() -> service.modifyCluster("event-cluster", null, null, "changedPassword123", null, null));
doThrow(new RuntimeException("dump failed")).when(cm).takeSnapshot(anyString(), anyString(), anyString(), any(Path.class));
assertThrows(AwsException.class, () -> service.rebootCluster("event-cluster"));
doThrow(new RuntimeException("proxy stop failed")).when(proxyManager).stopProxy("111111111111:event-cluster");
assertThrows(AwsException.class, () -> service.deleteCluster("event-cluster"));
verifyNoInteractions(events);
}
@Test
void managedPasswordClusterRecordsCreationOnlyAfterTheSecretExists() {
when(cm.start(eq("111111111111"), eq("event-managed"), eq("admin"), anyString()))
.thenReturn(new RedshiftContainerHandle("container", "event-managed", "localhost", 5432));
Secret secret = new Secret();
secret.setArn("arn:aws:secretsmanager:us-east-1:111111111111:secret:event-managed");
secret.setCurrentVersionId("version-1");
when(secretsManagerService.createSecret(eq("redshift/event-managed"), anyString(), isNull(),
anyString(), isNull(), anyList(), eq("redshift"), eq("us-east-1"))).thenReturn(secret);
service.createClusterWithManagedMasterPassword("event-managed", "dc2.large", "admin", null,
List.of(), List.of(), null, "us-east-1");
InOrder recorded = inOrder(secretsManagerService, events);
recorded.verify(secretsManagerService).createSecret(eq("redshift/event-managed"), anyString(), isNull(),
anyString(), isNull(), anyList(), eq("redshift"), eq("us-east-1"));
recorded.verify(events).record(eq(RedshiftEventCatalog.CLUSTER_CREATED), eq("event-managed"), anyString());
recorded.verifyNoMoreInteractions();
}
@Test
void managedPasswordClusterRolledBackAfterSecretFailureRecordsNoEvents() {
when(cm.start(eq("111111111111"), eq("event-failed"), eq("admin"), anyString()))
.thenReturn(new RedshiftContainerHandle("container", "event-failed", "localhost", 5432));
when(secretsManagerService.createSecret(eq("redshift/event-failed"), anyString(), isNull(),
anyString(), isNull(), anyList(), eq("redshift"), eq("us-east-1")))
.thenThrow(new AwsException("InternalFailure", "secret store unavailable", 500));
assertThrows(AwsException.class, () -> service.createClusterWithManagedMasterPassword(
"event-failed", "dc2.large", "admin", null, List.of(), List.of(), null, "us-east-1"));
verify(clusterBackend).delete("event-failed");
verifyNoInteractions(events);
}
@ParameterizedTest
@ValueSource(booleans = {false, true})
void snapshotEventsReportStartAndTheActualOutcome(boolean fails) {
Cluster cluster = new Cluster();
cluster.setClusterIdentifier("event-cluster");
cluster.setMasterUsername("admin");
when(clusterBackend.get("event-cluster")).thenReturn(Optional.of(cluster));
if (fails) {
doThrow(new RuntimeException("snapshot failed"))
.when(cm).takeSnapshot(anyString(), anyString(), anyString(), any(Path.class));
assertThrows(AwsException.class, () -> service.createSnapshot("event-snapshot", "event-cluster"));
} else {
service.createSnapshot("event-snapshot", "event-cluster");
}
InOrder recorded = inOrder(events);
recorded.verify(events).recordForAccount(eq("111111111111"), eq("us-east-1"),
eq(RedshiftEventCatalog.SNAPSHOT_STARTED), eq("event-snapshot"), anyString());
recorded.verify(events).recordForAccount(eq("111111111111"), eq("us-east-1"),
eq(fails ? RedshiftEventCatalog.SNAPSHOT_FAILED : RedshiftEventCatalog.SNAPSHOT_COMPLETED),
eq("event-snapshot"), anyString());
recorded.verifyNoMoreInteractions();
}
@Test
void parameterGroupModifyAndResetRecordUpdatesAfterPersistence() {
ClusterParameterGroup group = new ClusterParameterGroup("event-pg", "redshift-1.0", "events");
when(parameterGroupBackend.get("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());
InOrder recorded = inOrder(parameterGroupBackend, events);
recorded.verify(parameterGroupBackend).flush();
recorded.verify(events).record(eq(RedshiftEventCatalog.PARAMETER_GROUP_UPDATED), eq("event-pg"), anyString());
recorded.verify(parameterGroupBackend).flush();
recorded.verify(events).record(eq(RedshiftEventCatalog.PARAMETER_GROUP_UPDATED), eq("event-pg"), anyString());
verify(events, times(2)).record(any(), anyString(), anyString());
}
@Test
void invalidParameterGroupResetDoesNotRecordAnUpdate() {
ClusterParameterGroup group = new ClusterParameterGroup("event-pg", "redshift-1.0", "events");
when(parameterGroupBackend.get("event-pg")).thenReturn(Optional.of(group));
assertThrows(AwsException.class,
() -> service.resetClusterParameterGroup("event-pg", false, List.of("unknown-parameter")));
verifyNoInteractions(events);
verify(parameterGroupBackend, never()).flush();
}
@Test
@@ -1081,6 +1243,10 @@ class RedshiftServiceTest {
verify(clusterBackend, never()).delete("c1");
verify(clusterBackend, atLeast(1)).put(eq("c1"), argThat(c -> "failed".equals(c.getClusterStatus())));
verify(clusterBackend, atLeastOnce()).flush();
InOrder recorded = inOrder(events);
recorded.verify(events).record(eq(RedshiftEventCatalog.CLUSTER_RESTORE_STARTED), eq("c1"), anyString());
recorded.verify(events).record(eq(RedshiftEventCatalog.CLUSTER_RESTORE_FAILED), eq("c1"), anyString());
recorded.verifyNoMoreInteractions();
}
@Test