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

@@ -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"),
@@ -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<String> SOURCE_TYPES =
Set.of(CLUSTER, PARAMETER_GROUP, SECURITY_GROUP, SNAPSHOT, SCHEDULED_ACTION);
static final Set<String> CATEGORIES = Set.of("configuration", "management", "monitoring", "security", "pending");
static final Set<String> 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<EventInfo> 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() { }
}
@@ -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<RedshiftEvent> 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<Map<String, RedshiftEvent>>() { });
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<String, RedshiftEvent> entry : events.scanAllAccountsWithRawKeys().entrySet()) {
if (entry.getValue().getDate().isBefore(floor)) {
events.deleteRaw(entry.getKey());
}
}
}
// ── DescribeEvents / DescribeEventCategories ─────────────────────────────
public PaginatedResult<RedshiftEvent> 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<RedshiftEvent> 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<String, List<EventInfo>> describeEventCategories(String sourceType) {
if (sourceType != null && !sourceType.isBlank()) {
requireSourceType(sourceType);
}
Map<String, List<EventInfo>> 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() + "/");
}
}
@@ -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<RedshiftEvent> 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<String, List<EventInfo>> bySourceType = service.describeEventCategories(params.getFirst("SourceType"));
XmlBuilder xmlBuilder = new XmlBuilder()
.start("DescribeEventCategoriesResponse", AwsNamespaces.REDSHIFT)
.start("DescribeEventCategoriesResult")
.start("EventCategoriesMapList");
for (Map.Entry<String, List<EventInfo>> 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<String, String> 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")
@@ -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<Integer> usedPorts = ConcurrentHashMap.newKeySet();
private final ConcurrentHashMap<ResourceKey, ResourceLock> 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<Map<String, Cluster>>() {});
this.snapshots = storageFactory.create("redshift", "redshift-snapshots.json", new TypeReference<Map<String, Snapshot>>() {});
this.parameterGroups = storageFactory.create("redshift", "redshift-parameter-groups.json", new TypeReference<Map<String, ClusterParameterGroup>>() {});
@@ -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<String> vpcSecurityGroupIds,
List<String> 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<RedshiftEvent> 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<String, List<EventInfo>> describeEventCategories(String sourceType) {
return eventService().describeEventCategories(sourceType);
}
// ── Cluster Subnet Group Operations ──────────────────────────────────────
public ClusterSubnetGroup createClusterSubnetGroup(String name, String description, String vpcId, List<String> subnetIds) {
@@ -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<String> 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<String> getEventCategories() { return eventCategories; }
public void setEventCategories(List<String> eventCategories) { this.eventCategories = eventCategories; }
public String getMessage() { return message; }
public void setMessage(String message) { this.message = message; }
}