diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/RedshiftEventsTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/RedshiftEventsTest.java new file mode 100644 index 0000000000..9f98fa17b1 --- /dev/null +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/RedshiftEventsTest.java @@ -0,0 +1,60 @@ +package com.floci.test; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +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 java.time.Instant; +import java.util.List; +import java.util.UUID; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assumptions.assumeFalse; + +@DisplayName("Redshift event history") +class RedshiftEventsTest { + + @Test + @DisplayName("SDK reads parameter-group events and their category metadata") + void parameterGroupEventsAndCategories() { + assumeFalse(TestFixtures.isRealAws(), "Checks immediate local event recording"); + String name = "compat-rsevent-" + UUID.randomUUID().toString().substring(0, 12); + String sourceType = "cluster-parameter-group"; + Instant start = Instant.now().minusSeconds(1); + try (RedshiftClient redshift = TestFixtures.redshiftClient()) { + redshift.createClusterParameterGroup(request -> request.parameterGroupName(name) + .parameterGroupFamily("redshift-1.0").description("SDK event compatibility")); + try { + redshift.modifyClusterParameterGroup(request -> request.parameterGroupName(name) + .parameters(Parameter.builder().parameterName("statement_timeout") + .parameterValue("5000").build())); + DescribeEventsResponse history = redshift.describeEvents(request -> request + .sourceIdentifier(name).sourceType(sourceType).startTime(start)); + assertThat(history.events()).extracting(Event::eventId) + .contains("REDSHIFT-EVENT-1003", "REDSHIFT-EVENT-1005"); + assertThat(history.events()).allSatisfy(event -> { + assertThat(event.sourceIdentifier()).isEqualTo(name); + assertThat(event.sourceTypeAsString()).isEqualTo(sourceType); + assertThat(event.date()).isAfterOrEqualTo(start); + assertThat(event.message()).isNotBlank(); + }); + + List categories = redshift.describeEventCategories(request -> request + .sourceType(sourceType)).eventCategoriesMapList(); + assertThat(categories).hasSize(1); + assertThat(categories.get(0).sourceType()).isEqualTo(sourceType); + assertThat(categories.get(0).events()).anySatisfy(info -> { + assertThat(info.eventId()).isEqualTo("REDSHIFT-EVENT-1003"); + assertThat(info.eventCategories()).containsExactly("configuration"); + assertThat(info.severity()).isEqualTo("INFO"); + }); + } finally { + redshift.deleteClusterParameterGroup(request -> request.parameterGroupName(name)); + } + } + } +} diff --git a/docs/services/index.md b/docs/services/index.md index a5e918bb30..ecaed49288 100644 --- a/docs/services/index.md +++ b/docs/services/index.md @@ -76,7 +76,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac | [Neptune](neptune.md) | `POST /` with `Action=` param + Gremlin TCP proxy | Query + WebSocket | 14 | | [DocumentDB](docdb.md) | `POST /` with `Action=` param + MongoDB container | Query + MongoDB wire | 13 | | [DMS](dms.md) | `POST /` + `X-Amz-Target: AmazonDMSv20160101.*` | JSON 1.1 | 20 | -| [Redshift](redshift.md) | `POST /` with `Action=` param + PostgreSQL container | Query + PostgreSQL wire (+ CFN) | 44 | +| [Redshift](redshift.md) | `POST /` with `Action=` param + PostgreSQL container | Query + PostgreSQL wire (+ CFN) | 46 | | [Redshift Data API](redshift-data.md) | `POST /` + `X-Amz-Target: RedshiftData.*` | JSON 1.1 | 11 | | [Redshift Serverless](redshift-serverless.md) | `POST /` + `X-Amz-Target: RedshiftServerless.*` | JSON 1.1 | 55 | | [EMR](emr.md) | `POST /` + `X-Amz-Target: ElasticMapReduce.*` | JSON 1.1 | 40 | diff --git a/docs/services/redshift.md b/docs/services/redshift.md index 923cfea112..41cdfe2108 100644 --- a/docs/services/redshift.md +++ b/docs/services/redshift.md @@ -14,6 +14,35 @@ Snapshot-dump and catalog-seed uploads retry transient Docker I/O failures for u For running SQL without a PostgreSQL wire connection (the way Lambda and Step Functions do), see the [Redshift Data API](redshift-data.md). +## Events + +`DescribeEvents` returns the last hour by default, accepts `StartTime`, `EndTime`, +`Duration`, and a paired `SourceType`/`SourceIdentifier` filter, and retains the last +14 days. `MaxRecords` accepts 20 through 100; continue with the returned `Marker`. +These bounds follow the [AWS DescribeEvents API](https://docs.aws.amazon.com/redshift/latest/APIReference/API_DescribeEvents.html). +History is isolated by account and region and uses the configured Redshift storage +mode, including persistent, hybrid and WAL storage. + +Floci records cluster creation, deletion, reboot, restore, password changes, +parameter-group association and security-group changes. Snapshot operations record +start, completion and failure, including final snapshots. Parameter-group creation, +update, reset and deletion also produce events. The IDs, categories and severities +come from the [AWS event catalog](https://docs.aws.amazon.com/redshift/latest/mgmt/working-with-event-notifications.html). +`DescribeEventCategories` lists the event IDs implemented by Floci, grouped by source +type. It does not advertise hardware failures, maintenance or other conditions Floci +does not simulate. Security-group and scheduled-action source types are accepted as +filters, but Floci does not model resources or generate events for those source types. + +For example, parameter-group events work without a database container: + +```bash +aws --endpoint-url http://localhost:4566 redshift create-cluster-parameter-group \ + --parameter-group-name event-demo --parameter-group-family redshift-1.0 \ + --description 'Event example' +aws --endpoint-url http://localhost:4566 redshift describe-events \ + --source-type cluster-parameter-group --source-identifier event-demo +``` + ## Supported Actions @@ -45,6 +74,8 @@ For running SQL without a PostgreSQL wire connection (the way Lambda and Step Fu | `CreateSnapshotCopyGrant` | Register a snapshot copy grant, defaulting `KmsKeyId` to the AWS-managed Redshift key. `SnapshotCopyGrantName` must be 1-63 characters, start with a lowercase letter, and contain only lowercase letters, digits and non-consecutive hyphens | | `DescribeSnapshotCopyGrants` | List snapshot copy grants, optionally filtered by name, paged with `MaxRecords` and `Marker` | | `DeleteSnapshotCopyGrant` | Remove a snapshot copy grant | +| `DescribeEvents` | - | +| `DescribeEventCategories` | - | | `EnableSnapshotCopy` | Record cross-region snapshot copy on a cluster (`RetentionPeriod` defaults to 7, `ManualSnapshotRetentionPeriod` to -1); `DescribeClusters` then reports `ClusterSnapshotCopyStatus`. A `DestinationRegion` that is not an AWS region is refused with `UnknownSnapshotCopyRegionFault`. No snapshot is copied | | `DisableSnapshotCopy` | Clear a cluster's snapshot copy configuration | | `ModifySnapshotCopyRetentionPeriod` | Change the automated (or, with `Manual`, the manual) snapshot copy retention period | diff --git a/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java b/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java index f63fc90c4a..9a97044fbc 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java @@ -485,6 +485,7 @@ public class AwsQueryController { Map.entry("RemoveTagsFromResource", "rds"), Map.entry("DescribeEngineDefaultParameters", "rds"), Map.entry("DescribeEvents", "rds"), + Map.entry("DescribeEventCategories", "redshift"), Map.entry("DescribeAccountAttributes", "ec2"), Map.entry("DescribeSnapshots", "ec2"), Map.entry("DescribeAccountLimits", "elasticloadbalancing"), diff --git a/src/main/java/io/github/hectorvent/floci/services/redshift/RedshiftEventCatalog.java b/src/main/java/io/github/hectorvent/floci/services/redshift/RedshiftEventCatalog.java new file mode 100644 index 0000000000..e14f21f8f5 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/redshift/RedshiftEventCatalog.java @@ -0,0 +1,77 @@ +package io.github.hectorvent.floci.services.redshift; + +import java.util.List; +import java.util.Set; + +/** + * The event IDs Floci emits, with the source type, category and severity AWS documents for each + * (Amazon Redshift provisioned cluster event notifications). Events AWS raises for conditions the + * emulator has no equivalent of, such as hardware failure or maintenance windows, are not listed. + */ +final class RedshiftEventCatalog { + + static final String CLUSTER = "cluster"; + static final String PARAMETER_GROUP = "cluster-parameter-group"; + static final String SECURITY_GROUP = "cluster-security-group"; + static final String SNAPSHOT = "cluster-snapshot"; + static final String SCHEDULED_ACTION = "scheduled-action"; + + static final Set SOURCE_TYPES = + Set.of(CLUSTER, PARAMETER_GROUP, SECURITY_GROUP, SNAPSHOT, SCHEDULED_ACTION); + static final Set CATEGORIES = Set.of("configuration", "management", "monitoring", "security", "pending"); + static final Set SEVERITIES = Set.of("INFO", "ERROR"); + + record EventInfo(String id, String sourceType, String category, String severity, String description) { } + + static final EventInfo CLUSTER_PARAMETER_GROUP_CHANGED = new EventInfo("REDSHIFT-EVENT-1001", CLUSTER, + "configuration", "INFO", + "Your Amazon Redshift cluster [cluster name] was modified to use parameter group [parameter group name] at [time]."); + static final EventInfo PARAMETER_GROUP_CREATED = new EventInfo("REDSHIFT-EVENT-1003", PARAMETER_GROUP, + "configuration", "INFO", "Cluster parameter group [group name] was created."); + static final EventInfo PARAMETER_GROUP_DELETED = new EventInfo("REDSHIFT-EVENT-1004", PARAMETER_GROUP, + "configuration", "INFO", "Cluster parameter group [group name] was deleted."); + static final EventInfo PARAMETER_GROUP_UPDATED = new EventInfo("REDSHIFT-EVENT-1005", PARAMETER_GROUP, + "configuration", "INFO", "Cluster parameter group [name] was updated at [time]."); + static final EventInfo CLUSTER_CREATED = new EventInfo("REDSHIFT-EVENT-2000", CLUSTER, "management", "INFO", + "Your Amazon Redshift cluster: [cluster name] has been created and is ready for use."); + static final EventInfo CLUSTER_DELETED = new EventInfo("REDSHIFT-EVENT-2001", CLUSTER, "management", "INFO", + "Your Amazon Redshift cluster [cluster name] was deleted at [time]. A final snapshot [was / was not] saved."); + static final EventInfo CLUSTER_SECURITY_GROUPS_UPDATED = new EventInfo("REDSHIFT-EVENT-2002", CLUSTER, + "management", "INFO", "VPC security groups for cluster [cluster name] updated at [time in UTC]."); + static final EventInfo CLUSTER_RESTORE_STARTED = new EventInfo("REDSHIFT-EVENT-2008", CLUSTER, "management", + "INFO", "Your restore operation to create a new Amazon Redshift cluster [cluster name] snapshot " + + "[snapshot name] was started at [time]."); + static final EventInfo SNAPSHOT_STARTED = new EventInfo("REDSHIFT-EVENT-2009", SNAPSHOT, "management", "INFO", + "A user snapshot [snapshot name] for Amazon Redshift Cluster [cluster name] started at [time]."); + static final EventInfo SNAPSHOT_DELETED = new EventInfo("REDSHIFT-EVENT-2011", SNAPSHOT, "management", "INFO", + "The user snapshot [snapshot name] for Amazon Redshift cluster [cluster name] was deleted at [time]."); + static final EventInfo FINAL_SNAPSHOT_STARTED = new EventInfo("REDSHIFT-EVENT-2012", SNAPSHOT, "management", + "INFO", "The final snapshot [snapshot name] for Amazon Redshift cluster [cluster name] was started at [time]."); + static final EventInfo CLUSTER_REBOOTED = new EventInfo("REDSHIFT-EVENT-3000", CLUSTER, "monitoring", "INFO", + "Your Amazon Redshift cluster [cluster name] was rebooted at [time]."); + static final EventInfo CLUSTER_RESTORED = new EventInfo("REDSHIFT-EVENT-3003", CLUSTER, "monitoring", "INFO", + "Amazon Redshift cluster [cluster name] was successfully created from snapshot [snapshot name] " + + "and is available for use."); + static final EventInfo SNAPSHOT_COMPLETED = new EventInfo("REDSHIFT-EVENT-3004", SNAPSHOT, "monitoring", "INFO", + "The user snapshot [snapshot name] for your Amazon Redshift cluster [cluster name] completed " + + "successfully at [time]."); + static final EventInfo FINAL_SNAPSHOT_COMPLETED = new EventInfo("REDSHIFT-EVENT-3005", SNAPSHOT, "monitoring", + "INFO", "The final snapshot [name] for Amazon Redshift cluster [name] completed successfully at [time]."); + static final EventInfo FINAL_SNAPSHOT_FAILED = new EventInfo("REDSHIFT-EVENT-3502", SNAPSHOT, "monitoring", + "ERROR", "The final snapshot [snapshot name] for Amazon Redshift cluster [cluster name] failed at [time]."); + static final EventInfo CLUSTER_RESTORE_FAILED = new EventInfo("REDSHIFT-EVENT-3501", CLUSTER, "monitoring", + "ERROR", "The restore operation to create Amazon Redshift cluster [cluster name] failed at [time]."); + static final EventInfo SNAPSHOT_FAILED = new EventInfo("REDSHIFT-EVENT-3503", SNAPSHOT, "monitoring", "ERROR", + "The user snapshot [snapshot name] for your Amazon Redshift cluster [cluster name] failed at [time]."); + static final EventInfo ADMIN_CREDENTIALS_UPDATED = new EventInfo("REDSHIFT-EVENT-4000", CLUSTER, "security", + "INFO", "Your admin credentials for your Amazon Redshift cluster: [cluster name] were updated at [time]."); + + static final List ALL = List.of(CLUSTER_PARAMETER_GROUP_CHANGED, PARAMETER_GROUP_CREATED, + PARAMETER_GROUP_DELETED, PARAMETER_GROUP_UPDATED, CLUSTER_CREATED, CLUSTER_DELETED, + CLUSTER_SECURITY_GROUPS_UPDATED, CLUSTER_RESTORE_STARTED, SNAPSHOT_STARTED, SNAPSHOT_DELETED, + FINAL_SNAPSHOT_STARTED, CLUSTER_REBOOTED, CLUSTER_RESTORED, SNAPSHOT_COMPLETED, + FINAL_SNAPSHOT_COMPLETED, CLUSTER_RESTORE_FAILED, FINAL_SNAPSHOT_FAILED, SNAPSHOT_FAILED, + ADMIN_CREDENTIALS_UPDATED); + + private RedshiftEventCatalog() { } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/redshift/RedshiftEventService.java b/src/main/java/io/github/hectorvent/floci/services/redshift/RedshiftEventService.java new file mode 100644 index 0000000000..f54114cf22 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/redshift/RedshiftEventService.java @@ -0,0 +1,181 @@ +package io.github.hectorvent.floci.services.redshift; + +import com.fasterxml.jackson.core.type.TypeReference; +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.common.PaginatedResult; +import io.github.hectorvent.floci.core.common.Pagination; +import io.github.hectorvent.floci.core.common.RegionResolver; +import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend; +import io.github.hectorvent.floci.core.storage.StorageFactory; +import io.github.hectorvent.floci.services.redshift.RedshiftEventCatalog.EventInfo; +import io.github.hectorvent.floci.services.redshift.model.RedshiftEvent; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import org.jboss.logging.Logger; + +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicLong; + +/** + * Records the events Floci raises for Redshift resources and serves DescribeEvents and + * DescribeEventCategories from that history. + */ +@ApplicationScoped +public class RedshiftEventService { + + private static final Logger LOG = Logger.getLogger(RedshiftEventService.class); + + /** DescribeEvents reports the past 14 days at most. */ + static final Duration RETENTION = Duration.ofDays(14); + private static final long DEFAULT_WINDOW_MINUTES = 60; + private static final int PAGE_MIN = 20; + private static final int PAGE_MAX = 100; + private static final int PRUNE_EVERY = 200; + + private final AccountAwareStorageBackend events; + private final RegionResolver regionResolver; + private final Clock clock; + private final AtomicLong sequence = new AtomicLong(); + + @Inject + public RedshiftEventService(StorageFactory storageFactory, RegionResolver regionResolver) { + this(storageFactory, regionResolver, Clock.systemUTC()); + } + + RedshiftEventService(StorageFactory storageFactory, RegionResolver regionResolver, Clock clock) { + this.events = storageFactory.create("redshift", "redshift-events.json", + new TypeReference>() { }); + this.regionResolver = regionResolver; + this.clock = clock; + } + + // ── Recording ────────────────────────────────────────────────────────────────────────────────────────────────────────── + + /** Never fails the operation that raised the event: a lost event is logged, not surfaced. */ + public void record(EventInfo info, String sourceIdentifier, String message) { + recordForAccount(events.accountId(), regionResolver.getRegion(), info, sourceIdentifier, message); + } + + public void recordForAccount(String accountId, String region, EventInfo info, String sourceIdentifier, String message) { + try { + Instant now = clock.instant(); + long eventSequence = sequence.incrementAndGet(); + RedshiftEvent event = new RedshiftEvent(); + event.setKey(String.format(Locale.ROOT, "%019d-%010d-%s", now.toEpochMilli(), + eventSequence, UUID.randomUUID().toString().substring(0, 8))); + event.setDate(now); + event.setSeverity(info.severity()); + event.setEventId(info.id()); + event.setSourceIdentifier(sourceIdentifier); + event.setSourceType(info.sourceType()); + event.setEventCategories(new ArrayList<>(List.of(info.category()))); + event.setMessage(message); + events.putForAccount(accountId, key(region, event.getKey()), event); + if (eventSequence % PRUNE_EVERY == 0) { + prune(now); + } + } catch (RuntimeException e) { + LOG.warnv(e, "Could not record Redshift event {0} for {1}", info.id(), sourceIdentifier); + } + } + + private void prune(Instant now) { + Instant floor = now.minus(RETENTION); + for (Map.Entry entry : events.scanAllAccountsWithRawKeys().entrySet()) { + if (entry.getValue().getDate().isBefore(floor)) { + events.deleteRaw(entry.getKey()); + } + } + } + + // ── DescribeEvents / DescribeEventCategories ───────────────────────────── + + public PaginatedResult describeEvents(String sourceIdentifier, String sourceType, Instant startTime, + Instant endTime, Integer duration, Integer maxRecords, + String marker) { + validatePageSize(maxRecords); + boolean hasType = sourceType != null && !sourceType.isBlank(); + boolean hasId = sourceIdentifier != null && !sourceIdentifier.isBlank(); + if (hasType) { + requireSourceType(sourceType); + } + if (hasType != hasId) { + throw new AwsException("InvalidParameterCombination", + "SourceType and SourceIdentifier must be provided together.", 400); + } + if (duration != null && duration < 1) { + throw new AwsException("InvalidParameterValue", "Duration must be at least 1 minute.", 400); + } + Instant now = clock.instant(); + Instant from; + Instant to; + if (startTime != null || endTime != null) { + from = startTime != null ? startTime : now.minus(RETENTION); + to = endTime != null ? endTime : now; + } else { + from = now.minus(Duration.ofMinutes(duration != null ? duration : DEFAULT_WINDOW_MINUTES)); + to = now; + } + if (from.isAfter(to)) { + throw new AwsException("InvalidParameterValue", "StartTime must not be after EndTime.", 400); + } + Instant floor = now.minus(RETENTION); + Instant start = from.isBefore(floor) ? floor : from; + List matching = events.scan(this::inRegion).stream() + .filter(event -> !event.getDate().isBefore(start) && !event.getDate().isAfter(to)) + .filter(event -> !hasType || sourceType.equals(event.getSourceType()) + && sourceIdentifier.equals(event.getSourceIdentifier())) + .sorted(Comparator.comparing(RedshiftEvent::getKey)) + .toList(); + return Pagination.paginate(matching, RedshiftEvent::getKey, maxRecords, marker, PAGE_MAX, PAGE_MAX, + "InvalidParameterValue", "Marker"); + } + + /** The emitted events grouped by source type; a source type that raises none still appears, empty. */ + public Map> describeEventCategories(String sourceType) { + if (sourceType != null && !sourceType.isBlank()) { + requireSourceType(sourceType); + } + Map> byType = new LinkedHashMap<>(); + for (String type : List.of(RedshiftEventCatalog.CLUSTER, RedshiftEventCatalog.PARAMETER_GROUP, + RedshiftEventCatalog.SECURITY_GROUP, RedshiftEventCatalog.SNAPSHOT, + RedshiftEventCatalog.SCHEDULED_ACTION)) { + if (sourceType == null || sourceType.isBlank() || sourceType.equals(type)) { + byType.put(type, RedshiftEventCatalog.ALL.stream() + .filter(info -> info.sourceType().equals(type)).toList()); + } + } + return byType; + } + + private static void requireSourceType(String sourceType) { + if (!RedshiftEventCatalog.SOURCE_TYPES.contains(sourceType)) { + throw new AwsException("InvalidParameterValue", "SourceType must be one of " + + RedshiftEventCatalog.SOURCE_TYPES.stream().sorted().toList() + ".", 400); + } + } + + private static void validatePageSize(Integer maxRecords) { + if (maxRecords != null && (maxRecords < PAGE_MIN || maxRecords > PAGE_MAX)) { + throw new AwsException("InvalidParameterValue", + "MaxRecords must be between " + PAGE_MIN + " and " + PAGE_MAX + ".", 400); + } + } + + private static String key(String region, String name) { + return region + "/" + name; + } + + private boolean inRegion(String storedKey) { + return storedKey.startsWith(regionResolver.getRegion() + "/"); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/redshift/RedshiftQueryHandler.java b/src/main/java/io/github/hectorvent/floci/services/redshift/RedshiftQueryHandler.java index e51ff3b44d..c9bd51d5c6 100644 --- a/src/main/java/io/github/hectorvent/floci/services/redshift/RedshiftQueryHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/redshift/RedshiftQueryHandler.java @@ -9,11 +9,13 @@ import io.github.hectorvent.floci.core.common.IamEnforcementFilter; import io.github.hectorvent.floci.core.common.PaginatedResult; import io.github.hectorvent.floci.core.common.RegionResolver; import io.github.hectorvent.floci.core.common.XmlBuilder; +import io.github.hectorvent.floci.services.redshift.RedshiftEventCatalog.EventInfo; import io.github.hectorvent.floci.services.redshift.model.Cluster; import io.github.hectorvent.floci.services.redshift.model.ClusterParameterGroup; import io.github.hectorvent.floci.services.redshift.model.ClusterSubnetGroup; import io.github.hectorvent.floci.services.redshift.model.Integration; import io.github.hectorvent.floci.services.redshift.model.Parameter; +import io.github.hectorvent.floci.services.redshift.model.RedshiftEvent; import io.github.hectorvent.floci.services.redshift.model.Snapshot; import io.github.hectorvent.floci.services.redshift.model.SnapshotCopyGrant; import io.github.hectorvent.floci.services.redshift.model.SnapshotSchedule; @@ -24,7 +26,12 @@ import jakarta.ws.rs.core.MultivaluedMap; import jakarta.ws.rs.core.Response; import org.jboss.logging.Logger; +import java.math.BigDecimal; +import java.time.Instant; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; +import java.time.format.DateTimeParseException; import java.util.ArrayList; import java.util.Comparator; import java.util.LinkedHashMap; @@ -41,6 +48,9 @@ public class RedshiftQueryHandler { private static final Pattern FILTER_NAME = Pattern.compile("Filters\\.DescribeIntegrationsFilter\\.(\\d+)\\.Name"); + private static final DateTimeFormatter EVENT_TIMESTAMP = + DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").withZone(ZoneOffset.UTC); + // GetClusterCredentials DurationSeconds bounds, inclusive (AWS: 900 to 3600). private static final int MIN_CREDENTIAL_DURATION_SECONDS = 900; private static final int MAX_CREDENTIAL_DURATION_SECONDS = 3600; @@ -621,6 +631,63 @@ public class RedshiftQueryHandler { .build(); return Response.ok(xml).type(MediaType.APPLICATION_XML).build(); } + case "DescribeEvents" -> { + PaginatedResult page = service.describeEvents(params.getFirst("SourceIdentifier"), + params.getFirst("SourceType"), timestampParam(params, "StartTime"), + timestampParam(params, "EndTime"), intParam(params, "Duration"), + intParam(params, "MaxRecords"), params.getFirst("Marker")); + XmlBuilder xmlBuilder = new XmlBuilder() + .start("DescribeEventsResponse", AwsNamespaces.REDSHIFT) + .start("DescribeEventsResult"); + if (page.nextToken() != null) { + xmlBuilder.elem("Marker", page.nextToken()); + } + xmlBuilder.start("Events"); + for (RedshiftEvent event : page.items()) { + xmlBuilder.raw(buildEventXml(event)); + } + String xml = xmlBuilder + .end("Events") + .end("DescribeEventsResult") + .start("ResponseMetadata") + .elem("RequestId", "test-req-id") + .end("ResponseMetadata") + .end("DescribeEventsResponse") + .build(); + return Response.ok(xml).type(MediaType.APPLICATION_XML).build(); + } + case "DescribeEventCategories" -> { + Map> bySourceType = service.describeEventCategories(params.getFirst("SourceType")); + XmlBuilder xmlBuilder = new XmlBuilder() + .start("DescribeEventCategoriesResponse", AwsNamespaces.REDSHIFT) + .start("DescribeEventCategoriesResult") + .start("EventCategoriesMapList"); + for (Map.Entry> entry : bySourceType.entrySet()) { + xmlBuilder.start("EventCategoriesMap") + .elem("SourceType", entry.getKey()) + .start("Events"); + for (EventInfo info : entry.getValue()) { + xmlBuilder.start("EventInfoMap") + .elem("Severity", info.severity()) + .elem("EventDescription", info.description()) + .elem("EventId", info.id()) + .start("EventCategories") + .elem("EventCategory", info.category()) + .end("EventCategories") + .end("EventInfoMap"); + } + xmlBuilder.end("Events").end("EventCategoriesMap"); + } + String xml = xmlBuilder + .end("EventCategoriesMapList") + .end("DescribeEventCategoriesResult") + .start("ResponseMetadata") + .elem("RequestId", "test-req-id") + .end("ResponseMetadata") + .end("DescribeEventCategoriesResponse") + .build(); + return Response.ok(xml).type(MediaType.APPLICATION_XML).build(); + } case "EnableSnapshotCopy" -> { Cluster cluster = service.enableSnapshotCopy(requireParam(params, "ClusterIdentifier"), requireParam(params, "DestinationRegion"), @@ -1235,6 +1302,41 @@ public class RedshiftQueryHandler { return builder.end("Subnets").end("ClusterSubnetGroup").build(); } + private String buildEventXml(RedshiftEvent event) { + XmlBuilder builder = new XmlBuilder() + .start("Event") + .elem("Date", EVENT_TIMESTAMP.format(event.getDate())) + .elem("Severity", event.getSeverity()) + .elem("EventId", event.getEventId()) + .elem("SourceIdentifier", event.getSourceIdentifier()) + .elem("SourceType", event.getSourceType()) + .start("EventCategories"); + for (String category : event.getEventCategories()) { + builder.elem("EventCategory", category); + } + return builder.end("EventCategories") + .elem("Message", event.getMessage()) + .end("Event").build(); + } + + /** ISO 8601 as the SDKs send it, with or without seconds, or epoch seconds. */ + private static Instant timestampParam(MultivaluedMap params, String name) { + String raw = params.getFirst(name); + if (raw == null || raw.isBlank()) { + return null; + } + try { + return OffsetDateTime.parse(raw).toInstant(); + } catch (DateTimeParseException e) { + try { + return Instant.ofEpochMilli(new BigDecimal(raw).movePointRight(3).longValueExact()); + } catch (NumberFormatException | ArithmeticException ignored) { + // Neither form: the ISO 8601 failure below names the parameter. + throw new AwsException("InvalidParameterValue", name + " must be an ISO 8601 timestamp.", 400); + } + } + } + private String buildSnapshotCopyGrantXml(SnapshotCopyGrant grant) { XmlBuilder builder = new XmlBuilder() .start("SnapshotCopyGrant") diff --git a/src/main/java/io/github/hectorvent/floci/services/redshift/RedshiftService.java b/src/main/java/io/github/hectorvent/floci/services/redshift/RedshiftService.java index 2d132d28d9..2ec3857058 100644 --- a/src/main/java/io/github/hectorvent/floci/services/redshift/RedshiftService.java +++ b/src/main/java/io/github/hectorvent/floci/services/redshift/RedshiftService.java @@ -14,6 +14,7 @@ import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend; import io.github.hectorvent.floci.core.storage.StorageFactory; import io.github.hectorvent.floci.services.dynamodb.backend.DynamoDbStreamReader; import io.github.hectorvent.floci.services.rds.proxy.PasswordValidator; +import io.github.hectorvent.floci.services.redshift.RedshiftEventCatalog.EventInfo; import io.github.hectorvent.floci.services.redshift.container.RedshiftContainerHandle; import io.github.hectorvent.floci.services.redshift.container.RedshiftContainerManager; import io.github.hectorvent.floci.services.redshift.model.AutomatedSnapshotState; @@ -23,6 +24,7 @@ import io.github.hectorvent.floci.services.redshift.model.ClusterSubnetGroup; import io.github.hectorvent.floci.services.redshift.model.Endpoint; import io.github.hectorvent.floci.services.redshift.model.Integration; import io.github.hectorvent.floci.services.redshift.model.Parameter; +import io.github.hectorvent.floci.services.redshift.model.RedshiftEvent; import io.github.hectorvent.floci.services.redshift.model.Snapshot; import io.github.hectorvent.floci.services.redshift.model.SnapshotCopyGrant; import io.github.hectorvent.floci.services.redshift.model.SnapshotSchedule; @@ -44,6 +46,7 @@ import java.nio.file.Path; import java.nio.file.Paths; import java.time.Duration; import java.time.Instant; +import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.Collection; @@ -97,6 +100,7 @@ public class RedshiftService implements ManagedSecretRotator { private final ObjectMapper objectMapper; private final DynamoDbStreamReader streamReader; private final RedshiftAuditLogPublisher auditLogPublisher; + private final RedshiftEventService events; // Proxy ports currently handed out, so allocateProxyPort never double-assigns within this JVM. private final Set usedPorts = ConcurrentHashMap.newKeySet(); private final ConcurrentHashMap resourceLocks = new ConcurrentHashMap<>(); @@ -149,13 +153,33 @@ public class RedshiftService implements ManagedSecretRotator { return mutation.get(); } + private static final DateTimeFormatter EVENT_MESSAGE_TIME = + DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm").withZone(ZoneOffset.UTC); + + private static String eventTime() { + return EVENT_MESSAGE_TIME.format(Instant.now()) + " UTC"; + } + + private void emitEvent(EventInfo info, String sourceIdentifier, String message) { + if (events != null) { + events.record(info, sourceIdentifier, message); + } + } + + private void emitSnapshotEvent(String accountId, String region, EventInfo info, String sourceIdentifier, String message) { + if (events != null) { + events.recordForAccount(accountId, region, info, sourceIdentifier, message); + } + } + @Inject public RedshiftService(StorageFactory storageFactory, RedshiftContainerManager containerManager, EmulatorConfig config, RegionResolver regionResolver, RedshiftProxyManager proxyManager, DockerHostResolver dockerHostResolver, RedshiftCredentialBroker credentialBroker, SecretsManagerService secretsManagerService, ObjectMapper objectMapper, - DynamoDbStreamReader streamReader, RedshiftAuditLogPublisher auditLogPublisher) { + DynamoDbStreamReader streamReader, RedshiftAuditLogPublisher auditLogPublisher, + RedshiftEventService events) { this.clusters = storageFactory.create("redshift", "redshift-clusters.json", new TypeReference>() {}); this.snapshots = storageFactory.create("redshift", "redshift-snapshots.json", new TypeReference>() {}); this.parameterGroups = storageFactory.create("redshift", "redshift-parameter-groups.json", new TypeReference>() {}); @@ -175,6 +199,16 @@ public class RedshiftService implements ManagedSecretRotator { this.objectMapper = objectMapper; this.streamReader = streamReader; this.auditLogPublisher = auditLogPublisher; + this.events = events; + } + + RedshiftService(StorageFactory storageFactory, RedshiftContainerManager containerManager, + EmulatorConfig config, RegionResolver regionResolver, RedshiftProxyManager proxyManager, + DockerHostResolver dockerHostResolver, RedshiftCredentialBroker credentialBroker, + SecretsManagerService secretsManagerService, ObjectMapper objectMapper, + DynamoDbStreamReader streamReader, RedshiftAuditLogPublisher auditLogPublisher) { + this(storageFactory, containerManager, config, regionResolver, proxyManager, dockerHostResolver, + credentialBroker, secretsManagerService, objectMapper, streamReader, auditLogPublisher, null); } RedshiftService(StorageFactory storageFactory, RedshiftContainerManager containerManager, @@ -279,8 +313,18 @@ public class RedshiftService implements ManagedSecretRotator { String clusterSubnetGroupName, List vpcSecurityGroupIds, List iamRoleArns, String defaultIamRoleArn, Integer automatedRetention) { validateAutomatedRetention(nodeType, automatedRetention == null ? 1 : automatedRetention); - return mutateCluster(identifier, () -> createClusterLocked(identifier, nodeType, username, password, - clusterSubnetGroupName, vpcSecurityGroupIds, iamRoleArns, defaultIamRoleArn, automatedRetention)); + // The event is recorded under the cluster lock so a queued delete or reboot cannot log first. + return mutateCluster(identifier, () -> { + Cluster cluster = createClusterLocked(identifier, nodeType, username, password, + clusterSubnetGroupName, vpcSecurityGroupIds, iamRoleArns, defaultIamRoleArn, automatedRetention); + emitClusterCreated(identifier); + return cluster; + }); + } + + private void emitClusterCreated(String identifier) { + emitEvent(RedshiftEventCatalog.CLUSTER_CREATED, identifier, "Amazon Redshift cluster '" + identifier + + "' has been created at " + eventTime() + " and is ready for use."); } private Cluster createClusterLocked(String identifier, String nodeType, String username, String password, @@ -398,13 +442,16 @@ public class RedshiftService implements ManagedSecretRotator { String kmsKeyId, String region, String defaultIamRoleArn, Integer automatedRetention) { requireSecretsManager(); String password = RandomPasswordGenerator.generate(objectMapper.createObjectNode()); - Cluster cluster = createCluster(identifier, nodeType, username, password, + // Runs under the cluster lock taken by the caller, which also covers the event recorded below. + Cluster cluster = createClusterLocked(identifier, nodeType, username, password, clusterSubnetGroupName, vpcSecurityGroupIds, iamRoleArns, defaultIamRoleArn, automatedRetention); if (region != null) { cluster.setSnapshotRegion(region); } try { - return createManagedMasterSecret(cluster, kmsKeyId, region); + Cluster created = createManagedMasterSecret(cluster, kmsKeyId, region); + emitClusterCreated(identifier); + return created; } catch (RuntimeException e) { rollbackManagedMasterPasswordCluster(cluster); throw e; @@ -785,7 +832,11 @@ public class RedshiftService implements ManagedSecretRotator { createSnapshot(finalSnapshotIdentifier, identifier, retentionPeriod); } - return mutate(() -> removeCluster(identifier, cluster)); + Cluster removed = mutate(() -> removeCluster(identifier, cluster)); + emitEvent(RedshiftEventCatalog.CLUSTER_DELETED, identifier, "Amazon Redshift cluster '" + identifier + + "' has been deleted at " + eventTime() + ". A final snapshot was " + + (skipSnapshot ? "not " : "") + "saved."); + return removed; } private Cluster removeCluster(String identifier, Cluster cluster) { @@ -856,9 +907,13 @@ public class RedshiftService implements ManagedSecretRotator { .orElseThrow(() -> new AwsException("ClusterNotFound", "Cluster " + clusterIdentifier + " not found", 404)); validateAutomatedRetention(nodeType == null ? cluster.getNodeType() : nodeType, automatedRetention == null ? cluster.getAutomatedSnapshotRetentionPeriod() : automatedRetention); + + boolean passwordChanged = masterUserPassword != null && !masterUserPassword.isBlank(); + boolean parameterGroupChanged = clusterParameterGroupName != null && !clusterParameterGroupName.isBlank(); + boolean securityGroupsChanged = vpcSecurityGroupIds != null && !vpcSecurityGroupIds.isEmpty(); // alterUserPassword runs before any mutation of the cluster object (a live reference // from HybridStorage, not a copy); if it throws, no metadata has been changed yet. - if (masterUserPassword != null && !masterUserPassword.isBlank()) { + if (passwordChanged) { containerManager.alterUserPassword(clusters.accountId(), clusterIdentifier, cluster.getMasterUsername(), masterUserPassword); cluster.setMasterPassword(masterUserPassword); @@ -894,6 +949,20 @@ public class RedshiftService implements ManagedSecretRotator { clusters.put(clusterIdentifier, cluster); clusters.flush(); registerAuditLogging(clusters.accountId(), cluster); + if (passwordChanged) { + emitEvent(RedshiftEventCatalog.ADMIN_CREDENTIALS_UPDATED, clusterIdentifier, + "Your admin credentials for your Amazon Redshift cluster: " + clusterIdentifier + + " were updated at " + eventTime() + "."); + } + if (parameterGroupChanged) { + emitEvent(RedshiftEventCatalog.CLUSTER_PARAMETER_GROUP_CHANGED, clusterIdentifier, + "Your Amazon Redshift cluster " + clusterIdentifier + " was modified to use parameter group " + + clusterParameterGroupName + " at " + eventTime() + "."); + } + if (securityGroupsChanged) { + emitEvent(RedshiftEventCatalog.CLUSTER_SECURITY_GROUPS_UPDATED, clusterIdentifier, + "VPC security groups for cluster " + clusterIdentifier + " updated at " + eventTime() + "."); + } return cluster; } @@ -1242,6 +1311,8 @@ public class RedshiftService implements ManagedSecretRotator { clusters.put(clusterIdentifier, cluster); clusters.flush(); + emitEvent(RedshiftEventCatalog.CLUSTER_REBOOTED, clusterIdentifier, "Your Amazon Redshift cluster " + + clusterIdentifier + " was rebooted at " + eventTime() + "."); return cluster; } @@ -1340,6 +1411,12 @@ public class RedshiftService implements ManagedSecretRotator { if (!dumpFile.startsWith(dumpDir)) { throw new AwsException("InvalidParameterValue", "Invalid snapshot identifier", 400); } + boolean finalSnapshot = retentionPeriod != null; + String eventRegion = scheduledTime == null ? regionResolver.getRegion() : snapshotRegion(cluster); + emitSnapshotEvent(accountId, eventRegion, + finalSnapshot ? RedshiftEventCatalog.FINAL_SNAPSHOT_STARTED : RedshiftEventCatalog.SNAPSHOT_STARTED, + snapshotIdentifier, (finalSnapshot ? "The final snapshot '" : "A user snapshot '") + snapshotIdentifier + + "' for Amazon Redshift cluster '" + clusterIdentifier + "' started at " + eventTime() + "."); boolean committed = false; try { Files.createDirectories(dumpDir); @@ -1360,6 +1437,11 @@ public class RedshiftService implements ManagedSecretRotator { e.addSuppressed(cleanupFailure); } } + emitSnapshotEvent(accountId, eventRegion, + finalSnapshot ? RedshiftEventCatalog.FINAL_SNAPSHOT_FAILED : RedshiftEventCatalog.SNAPSHOT_FAILED, + snapshotIdentifier, (finalSnapshot ? "The final snapshot '" : "The user snapshot '") + + snapshotIdentifier + "' for your Amazon Redshift cluster '" + clusterIdentifier + + "' failed at " + eventTime() + "."); if (e instanceof AwsException awsFailure) { throw awsFailure; } @@ -1369,6 +1451,11 @@ public class RedshiftService implements ManagedSecretRotator { throw failure; } + emitSnapshotEvent(accountId, eventRegion, + finalSnapshot ? RedshiftEventCatalog.FINAL_SNAPSHOT_COMPLETED : RedshiftEventCatalog.SNAPSHOT_COMPLETED, + snapshotIdentifier, (finalSnapshot ? "The final snapshot '" : "The user snapshot '") + + snapshotIdentifier + "' for your Amazon Redshift cluster '" + clusterIdentifier + + "' completed successfully at " + eventTime() + "."); return snapshot; } @@ -1419,6 +1506,9 @@ public class RedshiftService implements ManagedSecretRotator { } } snapshot.setStatus("deleted"); + emitEvent(RedshiftEventCatalog.SNAPSHOT_DELETED, snapshotIdentifier, "The cluster snapshot '" + + snapshotIdentifier + "' for Amazon Redshift cluster '" + snapshot.getClusterIdentifier() + + "' was deleted at " + eventTime() + "."); return snapshot; } @@ -1529,6 +1619,9 @@ public class RedshiftService implements ManagedSecretRotator { cluster.setUserActivityLoggingEnabled(userActivityLoggingEnabled(DEFAULT_PARAMETER_GROUP_NAME)); cluster.setClusterStatus("creating"); storeCluster(cluster); + emitEvent(RedshiftEventCatalog.CLUSTER_RESTORE_STARTED, clusterIdentifier, + "Your restore operation to create a new Amazon Redshift cluster '" + clusterIdentifier + + "' snapshot '" + snapshotIdentifier + "' was started at " + eventTime() + "."); // Hoisted out of the try so a failure after allocateProxyPort() still returns the port. int proxyPort = -1; @@ -1554,13 +1647,18 @@ public class RedshiftService implements ManagedSecretRotator { cluster.setClusterStatus("available"); } catch (AwsException e) { rollbackSnapshotRestore(cluster, proxyPort); + emitClusterRestoreFailure(clusterIdentifier, snapshotIdentifier); throw e; } catch (Exception e) { rollbackSnapshotRestore(cluster, proxyPort); + emitClusterRestoreFailure(clusterIdentifier, snapshotIdentifier); throw new AwsException("InternalFailure", "Failed to restore cluster from snapshot: " + e.getMessage(), 500); } storeCluster(cluster); + emitEvent(RedshiftEventCatalog.CLUSTER_RESTORED, clusterIdentifier, "Amazon Redshift cluster '" + + clusterIdentifier + "' was successfully created from snapshot '" + snapshotIdentifier + + "' and is available for use."); return cluster; } @@ -1577,6 +1675,8 @@ public class RedshiftService implements ManagedSecretRotator { ClusterParameterGroup group = new ClusterParameterGroup(parameterGroupName, parameterGroupFamily, description); parameterGroups.put(parameterGroupName, group); parameterGroups.flush(); + emitEvent(RedshiftEventCatalog.PARAMETER_GROUP_CREATED, parameterGroupName, + "Cluster parameter group '" + parameterGroupName + "' was created."); return group; } @@ -1654,9 +1754,15 @@ public class RedshiftService implements ManagedSecretRotator { parameterGroups.put(parameterGroupName, group); parameterGroups.flush(); refreshClustersForActivityParameter(parameterGroupName, group); + emitParameterGroupUpdated(parameterGroupName); return group; } + private void emitParameterGroupUpdated(String parameterGroupName) { + emitEvent(RedshiftEventCatalog.PARAMETER_GROUP_UPDATED, parameterGroupName, "Cluster parameter group '" + + parameterGroupName + "' was updated at " + eventTime() + "."); + } + private boolean userActivityLoggingEnabled(String parameterGroupName) { ClusterParameterGroup group = parameterGroups.get(parameterGroupName) .or(() -> DEFAULT_PARAMETER_GROUP_NAME.equals(parameterGroupName) @@ -1714,6 +1820,7 @@ public class RedshiftService implements ManagedSecretRotator { parameterGroups.put(parameterGroupName, group); parameterGroups.flush(); refreshClustersForActivityParameter(parameterGroupName, group); + emitParameterGroupUpdated(parameterGroupName); } private void refreshClustersForActivityParameter(String parameterGroupName, ClusterParameterGroup group) { @@ -1768,9 +1875,37 @@ public class RedshiftService implements ManagedSecretRotator { ClusterParameterGroup group = groupOpt.get(); parameterGroups.delete(parameterGroupName); parameterGroups.flush(); + emitEvent(RedshiftEventCatalog.PARAMETER_GROUP_DELETED, parameterGroupName, + "Cluster parameter group '" + parameterGroupName + "' was deleted at " + eventTime() + "."); return group; } + // ── Event Operations ───────────────────────────────────────────────────── + + private RedshiftEventService eventService() { + if (events == null) { + throw new IllegalStateException("Redshift events are not available in this service instance"); + } + return events; + } + + private void emitClusterRestoreFailure(String clusterIdentifier, String snapshotIdentifier) { + emitEvent(RedshiftEventCatalog.CLUSTER_RESTORE_FAILED, clusterIdentifier, + "The restore operation to create Amazon Redshift cluster '" + clusterIdentifier + + "' from snapshot '" + snapshotIdentifier + "' failed at " + eventTime() + "."); + } + + public PaginatedResult describeEvents(String sourceIdentifier, String sourceType, + Instant startTime, Instant endTime, Integer duration, + Integer maxRecords, String marker) { + return eventService().describeEvents(sourceIdentifier, sourceType, startTime, endTime, duration, + maxRecords, marker); + } + + public Map> describeEventCategories(String sourceType) { + return eventService().describeEventCategories(sourceType); + } + // ── Cluster Subnet Group Operations ────────────────────────────────────── public ClusterSubnetGroup createClusterSubnetGroup(String name, String description, String vpcId, List subnetIds) { diff --git a/src/main/java/io/github/hectorvent/floci/services/redshift/model/RedshiftEvent.java b/src/main/java/io/github/hectorvent/floci/services/redshift/model/RedshiftEvent.java new file mode 100644 index 0000000000..beb52efa56 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/redshift/model/RedshiftEvent.java @@ -0,0 +1,38 @@ +package io.github.hectorvent.floci.services.redshift.model; + +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.time.Instant; +import java.util.ArrayList; +import java.util.List; + +/** An event as DescribeEvents reports it. */ +@RegisterForReflection +public class RedshiftEvent { + + private String key; + private Instant date; + private String severity; + private String eventId; + private String sourceIdentifier; + private String sourceType; + private List eventCategories = new ArrayList<>(); + private String message; + + public String getKey() { return key; } + public void setKey(String key) { this.key = key; } + public Instant getDate() { return date; } + public void setDate(Instant date) { this.date = date; } + public String getSeverity() { return severity; } + public void setSeverity(String severity) { this.severity = severity; } + public String getEventId() { return eventId; } + public void setEventId(String eventId) { this.eventId = eventId; } + public String getSourceIdentifier() { return sourceIdentifier; } + public void setSourceIdentifier(String sourceIdentifier) { this.sourceIdentifier = sourceIdentifier; } + public String getSourceType() { return sourceType; } + public void setSourceType(String sourceType) { this.sourceType = sourceType; } + public List getEventCategories() { return eventCategories; } + public void setEventCategories(List eventCategories) { this.eventCategories = eventCategories; } + public String getMessage() { return message; } + public void setMessage(String message) { this.message = message; } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftEventServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftEventServiceTest.java new file mode 100644 index 0000000000..3922086aa0 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftEventServiceTest.java @@ -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 history = factory.create("redshift", "redshift-events.json", + new TypeReference>() { }); + 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 backend = factory.create("redshift", "redshift-events.json", + new TypeReference>() { }); + 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 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 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 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 first = service.describeEvents(null, null, null, null, null, 20, null); + PaginatedResult 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> 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 ids(PaginatedResult 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; + } + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftEventStorageTest.java b/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftEventStorageTest.java new file mode 100644 index 0000000000..e574b50a27 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftEventStorageTest.java @@ -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 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 history(RedshiftEventService service) { + return service.describeEvents(null, null, null, null, null, null, null).items(); + } + + private static List 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(); + } + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftEventsIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftEventsIntegrationTest.java new file mode 100644 index 0000000000..f47d1f7726 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftEventsIntegrationTest.java @@ -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 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")); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftQueryHandlerTest.java b/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftQueryHandlerTest.java index 311482f885..71d9ac7314 100644 --- a/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftQueryHandlerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftQueryHandlerTest.java @@ -33,6 +33,17 @@ import static org.mockito.Mockito.*; class RedshiftQueryHandlerTest { + @Test + void nonFiniteEventTimestampsReturnAnAwsValidationError() { + for (String invalid : List.of("NaN", "Infinity", "-Infinity", "1e300")) { + MultivaluedMap 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"; diff --git a/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftServiceTest.java index 26a77be54f..f6081b93ce 100644 --- a/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftServiceTest.java @@ -575,6 +575,7 @@ class RedshiftServiceTest { private DockerHostResolver dockerHostResolver; private RedshiftCredentialBroker credentialBroker; private SecretsManagerService secretsManagerService; + private RedshiftEventService events; private final Set 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 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> 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