diff --git a/docs/services/index.md b/docs/services/index.md index 32562840da..0ffc778d68 100644 --- a/docs/services/index.md +++ b/docs/services/index.md @@ -74,7 +74,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) | 35 | +| [Redshift](redshift.md) | `POST /` with `Action=` param + PostgreSQL container | Query + PostgreSQL wire (+ CFN) | 43 | | [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 | 24 | | [EMR](emr.md) | `POST /` + `X-Amz-Target: ElasticMapReduce.*` | JSON 1.1 | 37 | diff --git a/docs/services/redshift.md b/docs/services/redshift.md index 5fdddb5526..4c94c434cf 100644 --- a/docs/services/redshift.md +++ b/docs/services/redshift.md @@ -29,7 +29,7 @@ For running SQL without a PostgreSQL wire connection (the way Lambda and Step Fu | `DescribeClusterParameters` | Return the parameters of a group, with any values set by `ModifyClusterParameterGroup` | | `ModifyClusterParameterGroup` | Update parameter values on a group | | `DeleteClusterParameterGroup` | Remove a parameter group | -| `CreateTags` | Add or overwrite tags on a cluster, snapshot, subnet group, parameter group or snapshot copy grant | +| `CreateTags` | Add or overwrite tags on a cluster, snapshot, subnet group, parameter group, snapshot copy grant or snapshot schedule | | `DeleteTags` | Remove tags by key from a resource | | `DescribeTags` | List tagged resources and their tags | | `CreateClusterSubnetGroup` | Register a cluster subnet group (metadata only) | @@ -42,6 +42,14 @@ 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 | +| `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 | +| `CreateSnapshotSchedule` | Store a snapshot schedule of `rate(...)` / `cron(...)` definitions with optional tags; a `ScheduleIdentifier` other than letters, digits and hyphens is refused with `InvalidParameterValue`. No snapshots are taken on it | +| `ModifySnapshotSchedule` | Replace a schedule's definitions | +| `DescribeSnapshotSchedules` | List schedules filtered by `ScheduleIdentifier`, `ClusterIdentifier`, `TagKeys` and `TagValues`, paged with `MaxRecords` and `Marker`, with their associated clusters | +| `DeleteSnapshotSchedule` | Remove a schedule; refused with `InvalidClusterSnapshotScheduleState` while a cluster uses it | +| `ModifyClusterSnapshotSchedule` | Associate a cluster with a schedule, or disassociate it with `DisassociateSchedule` | | `ModifyCluster` | Update node type, parameter group, security groups, Multi-AZ flag, or the master password | | `DescribeClusterVersions` | Return the single emulated engine version and its parameter group family | | `DescribeOrderableClusterOptions` | Return the static node types and cluster types, optionally filtered by `NodeType` or `ClusterVersion` | @@ -499,7 +507,7 @@ These views expose the documented Redshift column names, types, and ordering map - Multi-node clusters: `NodeType` and `NumberOfNodes` are stored as metadata; every cluster is a single PostgreSQL container. - Parameter groups apply no real engine settings; values are stored and echoed back only. - Subnet groups, VPC routing, and security groups are metadata only. -- Resize, pause/resume, IAM authentication, snapshot schedules, and cross-region snapshot copy. +- Resize, pause/resume, and IAM authentication. Snapshot schedules and cross-region snapshot copy are stored and reported, but no snapshot is taken on a schedule or copied to another region. - `IAM_ROLE default` and cross-account role ARNs are not supported for COPY or UNLOAD. - The auth proxy validates the master user's password and any live `GetClusterCredentials` credential. Other non-master users pass straight through to PostgreSQL, which remains the authority for their credentials. - A cluster using `ManageMasterPassword` keeps its generated password in sync with the 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 14ff0cb5a6..ab539de565 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 @@ -644,6 +644,9 @@ public class AwsQueryController { "ModifyClusterParameterGroup", "CreateClusterSubnetGroup", "DescribeClusterSubnetGroups", "ModifyClusterSubnetGroup", "DeleteClusterSubnetGroup", "CreateSnapshotCopyGrant", "DescribeSnapshotCopyGrants", "DeleteSnapshotCopyGrant", + "EnableSnapshotCopy", "DisableSnapshotCopy", "ModifySnapshotCopyRetentionPeriod", + "CreateSnapshotSchedule", "DescribeSnapshotSchedules", "ModifySnapshotSchedule", + "DeleteSnapshotSchedule", "ModifyClusterSnapshotSchedule", "CreateTags", "DeleteTags", "DescribeTags", "GetClusterCredentials", "GetClusterCredentialsWithIAM" ); 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 3c9969186e..cd6c0d7725 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 @@ -13,6 +13,7 @@ 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.Snapshot; import io.github.hectorvent.floci.services.redshift.model.SnapshotCopyGrant; +import io.github.hectorvent.floci.services.redshift.model.SnapshotSchedule; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import jakarta.ws.rs.core.MediaType; @@ -564,6 +565,72 @@ public class RedshiftQueryHandler { .build(); return Response.ok(xml).type(MediaType.APPLICATION_XML).build(); } + case "EnableSnapshotCopy" -> { + Cluster cluster = service.enableSnapshotCopy(requireParam(params, "ClusterIdentifier"), + requireParam(params, "DestinationRegion"), + intParam(params, "RetentionPeriod"), + intParam(params, "ManualSnapshotRetentionPeriod"), + params.getFirst("SnapshotCopyGrantName")); + return clusterResponse(action, cluster); + } + case "DisableSnapshotCopy" -> { + return clusterResponse(action, service.disableSnapshotCopy(requireParam(params, "ClusterIdentifier"))); + } + case "ModifySnapshotCopyRetentionPeriod" -> { + String clusterIdentifier = requireParam(params, "ClusterIdentifier"); + requireParam(params, "RetentionPeriod"); + Cluster cluster = service.modifySnapshotCopyRetentionPeriod(clusterIdentifier, + intParam(params, "RetentionPeriod"), Boolean.parseBoolean(params.getFirst("Manual"))); + return clusterResponse(action, cluster); + } + case "CreateSnapshotSchedule" -> { + SnapshotSchedule schedule = service.createSnapshotSchedule(params.getFirst("ScheduleIdentifier"), + params.getFirst("ScheduleDescription"), memberList(params, "ScheduleDefinitions"), + parseTags(params)); + return snapshotScheduleResponse(action, schedule); + } + case "ModifySnapshotSchedule" -> { + SnapshotSchedule schedule = service.modifySnapshotSchedule(requireParam(params, "ScheduleIdentifier"), + memberList(params, "ScheduleDefinitions")); + return snapshotScheduleResponse(action, schedule); + } + case "DescribeSnapshotSchedules" -> { + PaginatedResult page = service.describeSnapshotSchedules( + params.getFirst("ScheduleIdentifier"), params.getFirst("ClusterIdentifier"), + memberList(params, "TagKeys"), memberList(params, "TagValues"), + intParam(params, "MaxRecords"), params.getFirst("Marker")); + XmlBuilder xmlBuilder = new XmlBuilder() + .start("DescribeSnapshotSchedulesResponse") + .start("DescribeSnapshotSchedulesResult") + .start("SnapshotSchedules"); + for (SnapshotSchedule schedule : page.items()) { + xmlBuilder.start("SnapshotSchedule") + .raw(buildSnapshotScheduleFields(schedule)) + .end("SnapshotSchedule"); + } + xmlBuilder.end("SnapshotSchedules"); + if (page.nextToken() != null) { + xmlBuilder.elem("Marker", page.nextToken()); + } + String xml = xmlBuilder + .end("DescribeSnapshotSchedulesResult") + .start("ResponseMetadata") + .elem("RequestId", "test-req-id") + .end("ResponseMetadata") + .end("DescribeSnapshotSchedulesResponse") + .build(); + return Response.ok(xml).type(MediaType.APPLICATION_XML).build(); + } + case "DeleteSnapshotSchedule" -> { + service.deleteSnapshotSchedule(requireParam(params, "ScheduleIdentifier")); + return emptyResponse(action); + } + case "ModifyClusterSnapshotSchedule" -> { + service.modifyClusterSnapshotSchedule(requireParam(params, "ClusterIdentifier"), + params.getFirst("ScheduleIdentifier"), + Boolean.parseBoolean(params.getFirst("DisassociateSchedule"))); + return emptyResponse(action); + } case "ModifyCluster" -> { String clusterIdentifier = params.getFirst("ClusterIdentifier"); if (clusterIdentifier == null || clusterIdentifier.isBlank()) { @@ -846,6 +913,20 @@ public class RedshiftQueryHandler { builder.end("Tags"); } + if (cluster.getSnapshotCopyDestinationRegion() != null) { + builder.start("ClusterSnapshotCopyStatus") + .elem("DestinationRegion", cluster.getSnapshotCopyDestinationRegion()) + .elem("RetentionPeriod", String.valueOf(cluster.getSnapshotCopyRetentionPeriod())) + .elem("ManualSnapshotRetentionPeriod", String.valueOf(cluster.getSnapshotCopyManualRetentionPeriod())) + .elem("SnapshotCopyGrantName", cluster.getSnapshotCopyGrantName()) + .end("ClusterSnapshotCopyStatus"); + } + + if (cluster.getSnapshotScheduleIdentifier() != null) { + builder.elem("SnapshotScheduleIdentifier", cluster.getSnapshotScheduleIdentifier()) + .elem("SnapshotScheduleState", "ACTIVE"); + } + if (cluster.getEndpoint() != null) { builder.start("Endpoint") .elem("Address", cluster.getEndpoint().getAddress()) @@ -924,6 +1005,75 @@ public class RedshiftQueryHandler { return builder.end("Snapshot").build(); } + private Response clusterResponse(String operation, Cluster cluster) { + String xml = new XmlBuilder() + .start(operation + "Response") + .start(operation + "Result") + .raw(buildClusterXml(cluster)) + .end(operation + "Result") + .start("ResponseMetadata") + .elem("RequestId", "test-req-id") + .end("ResponseMetadata") + .end(operation + "Response") + .build(); + return Response.ok(xml).type(MediaType.APPLICATION_XML).build(); + } + + // Create/ModifySnapshotSchedule return the SnapshotSchedule members directly inside the Result. + private Response snapshotScheduleResponse(String operation, SnapshotSchedule schedule) { + String xml = new XmlBuilder() + .start(operation + "Response") + .start(operation + "Result") + .raw(buildSnapshotScheduleFields(schedule)) + .end(operation + "Result") + .start("ResponseMetadata") + .elem("RequestId", "test-req-id") + .end("ResponseMetadata") + .end(operation + "Response") + .build(); + return Response.ok(xml).type(MediaType.APPLICATION_XML).build(); + } + + private static Response emptyResponse(String operation) { + String xml = new XmlBuilder() + .start(operation + "Response") + .start("ResponseMetadata") + .elem("RequestId", "test-req-id") + .end("ResponseMetadata") + .end(operation + "Response") + .build(); + return Response.ok(xml).type(MediaType.APPLICATION_XML).build(); + } + + // No snapshots are taken on a schedule, so NextInvocations is omitted. An association + // takes effect immediately, hence ACTIVE. + private String buildSnapshotScheduleFields(SnapshotSchedule schedule) { + XmlBuilder builder = new XmlBuilder().start("ScheduleDefinitions"); + for (String definition : schedule.getScheduleDefinitions()) { + builder.elem("ScheduleDefinition", definition); + } + builder.end("ScheduleDefinitions") + .elem("ScheduleIdentifier", schedule.getScheduleIdentifier()) + .elem("ScheduleDescription", schedule.getScheduleDescription()); + builder.start("Tags"); + for (Map.Entry tag : schedule.getTags().entrySet()) { + builder.start("Tag") + .elem("Key", tag.getKey()) + .elem("Value", tag.getValue()) + .end("Tag"); + } + builder.end("Tags"); + List associated = service.clustersUsingSnapshotSchedule(schedule.getScheduleIdentifier()); + builder.elem("AssociatedClusterCount", associated.size()).start("AssociatedClusters"); + for (String clusterIdentifier : associated) { + builder.start("ClusterAssociatedToSchedule") + .elem("ClusterIdentifier", clusterIdentifier) + .elem("ScheduleAssociationState", "ACTIVE") + .end("ClusterAssociatedToSchedule"); + } + return builder.end("AssociatedClusters").build(); + } + private Response loggingStatusResponse(String operation, Cluster cluster) { String xml = new XmlBuilder() .start(operation + "Response") @@ -1162,6 +1312,8 @@ public class RedshiftQueryHandler { case "VpcSecurityGroupIds" -> quoted + "(\\.member|\\.VpcSecurityGroupId)?\\.\\d+"; case "IamRoles", "AddIamRoles", "RemoveIamRoles" -> quoted + "(\\.member|\\.IamRoleArn)?\\.\\d+"; case "TagKeys" -> quoted + "(\\.member|\\.TagKey)?\\.\\d+"; + case "TagValues" -> quoted + "(\\.member|\\.TagValue)?\\.\\d+"; + case "ScheduleDefinitions" -> quoted + "(\\.member|\\.ScheduleDefinition)?\\.\\d+"; case "DbGroups" -> quoted + "(\\.member|\\.DbGroup)?\\.\\d+"; default -> quoted + "(\\.member)?\\.\\d+"; }; 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 869200abd1..aa74953c25 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 @@ -5,6 +5,7 @@ import com.fasterxml.jackson.databind.ObjectMapper; import io.github.hectorvent.floci.config.EmulatorConfig; import io.github.hectorvent.floci.core.common.AwsArnUtils; import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.common.AwsRegions; import io.github.hectorvent.floci.core.common.PaginatedResult; import io.github.hectorvent.floci.core.common.Pagination; import io.github.hectorvent.floci.core.common.RegionResolver; @@ -23,6 +24,7 @@ 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.Snapshot; import io.github.hectorvent.floci.services.redshift.model.SnapshotCopyGrant; +import io.github.hectorvent.floci.services.redshift.model.SnapshotSchedule; import io.github.hectorvent.floci.services.redshift.proxy.RedshiftProxyManager; import io.github.hectorvent.floci.services.secretsmanager.RandomPasswordGenerator; import io.github.hectorvent.floci.services.secretsmanager.SecretsManagerService; @@ -51,6 +53,7 @@ import java.util.Set; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Consumer; +import java.util.regex.Matcher; import java.util.regex.Pattern; @ApplicationScoped @@ -75,6 +78,7 @@ public class RedshiftService { private final AccountAwareStorageBackend integrations; private final AccountAwareStorageBackend snapshotCopyGrants; + private final AccountAwareStorageBackend snapshotSchedules; private final RedshiftContainerManager containerManager; private final EmulatorConfig config; private final RegionResolver regionResolver; @@ -100,6 +104,7 @@ public class RedshiftService { this.subnetGroups = storageFactory.create("redshift", "redshift-subnet-groups.json", new TypeReference>() {}); this.integrations = storageFactory.create("redshift", "redshift-integrations.json", new TypeReference>() {}); this.snapshotCopyGrants = storageFactory.create("redshift", "redshift-snapshot-copy-grants.json", new TypeReference>() {}); + this.snapshotSchedules = storageFactory.create("redshift", "redshift-snapshot-schedules.json", new TypeReference>() {}); this.containerManager = containerManager; this.config = config; this.regionResolver = regionResolver; @@ -1317,11 +1322,253 @@ public class RedshiftService { SnapshotCopyGrant grant = snapshotCopyGrants.get(name) .orElseThrow(() -> new AwsException("SnapshotCopyGrantNotFoundFault", "Snapshot copy grant " + name + " not found", 400)); + boolean inUse = clusters.scan(k -> true).stream() + .anyMatch(c -> name.equals(c.getSnapshotCopyGrantName())); + if (inUse) { + throw new AwsException("InvalidSnapshotCopyGrantStateFault", + "Snapshot copy grant " + name + " is used by one or more clusters", 400); + } snapshotCopyGrants.delete(name); snapshotCopyGrants.flush(); return grant; } + // ── Snapshot Copy Operations ───────────────────────────────────────────── + + private static final int DEFAULT_SNAPSHOT_COPY_RETENTION_DAYS = 7; + // AWS reports -1 ("retain indefinitely") when ManualSnapshotRetentionPeriod is not given. + private static final int RETAIN_MANUAL_SNAPSHOTS_INDEFINITELY = -1; + + private Cluster requireCluster(String clusterIdentifier) { + return clusters.get(clusterIdentifier) + .orElseThrow(() -> new AwsException("ClusterNotFound", "Cluster " + clusterIdentifier + " not found", 404)); + } + + // Automated snapshots: 1 to 35 days. + private static void validateAutomatedRetention(int days) { + if (days < 1 || days > 35) { + throw new AwsException("InvalidRetentionPeriodFault", + "RetentionPeriod must be between 1 and 35 days.", 400); + } + } + + // Manual snapshots: -1 (indefinitely) or 1 to 3653 days. + private static void validateManualRetention(int days) { + if (days != RETAIN_MANUAL_SNAPSHOTS_INDEFINITELY && (days < 1 || days > 3653)) { + throw new AwsException("InvalidRetentionPeriodFault", + "ManualSnapshotRetentionPeriod must be -1 or between 1 and 3653 days.", 400); + } + } + + /** Copy is recorded on the cluster only; no snapshot is actually copied to another region. */ + public synchronized Cluster enableSnapshotCopy(String clusterIdentifier, String destinationRegion, + Integer retentionPeriod, Integer manualRetentionPeriod, + String snapshotCopyGrantName) { + Cluster cluster = requireCluster(clusterIdentifier); + if (cluster.getSnapshotCopyDestinationRegion() != null) { + throw new AwsException("SnapshotCopyAlreadyEnabledFault", + "Snapshot copy is already enabled on cluster " + clusterIdentifier + ".", 400); + } + if (!AwsRegions.isRegionId(destinationRegion)) { + throw new AwsException("UnknownSnapshotCopyRegionFault", + "Unknown destination region: " + destinationRegion, 404); + } + int retention = retentionPeriod == null ? DEFAULT_SNAPSHOT_COPY_RETENTION_DAYS : retentionPeriod; + int manualRetention = manualRetentionPeriod == null + ? RETAIN_MANUAL_SNAPSHOTS_INDEFINITELY : manualRetentionPeriod; + validateAutomatedRetention(retention); + validateManualRetention(manualRetention); + boolean hasGrant = snapshotCopyGrantName != null && !snapshotCopyGrantName.isBlank(); + if (hasGrant && snapshotCopyGrants.get(snapshotCopyGrantName).isEmpty()) { + throw new AwsException("SnapshotCopyGrantNotFoundFault", + "Snapshot copy grant " + snapshotCopyGrantName + " not found", 400); + } + cluster.setSnapshotCopyDestinationRegion(destinationRegion); + cluster.setSnapshotCopyRetentionPeriod(retention); + cluster.setSnapshotCopyManualRetentionPeriod(manualRetention); + cluster.setSnapshotCopyGrantName(hasGrant ? snapshotCopyGrantName : null); + clusters.put(clusterIdentifier, cluster); + clusters.flush(); + return cluster; + } + + public synchronized Cluster disableSnapshotCopy(String clusterIdentifier) { + Cluster cluster = requireCluster(clusterIdentifier); + if (cluster.getSnapshotCopyDestinationRegion() == null) { + throw new AwsException("SnapshotCopyAlreadyDisabledFault", + "Snapshot copy is not enabled on cluster " + clusterIdentifier + ".", 400); + } + cluster.setSnapshotCopyDestinationRegion(null); + cluster.setSnapshotCopyRetentionPeriod(null); + cluster.setSnapshotCopyManualRetentionPeriod(null); + cluster.setSnapshotCopyGrantName(null); + clusters.put(clusterIdentifier, cluster); + clusters.flush(); + return cluster; + } + + public synchronized Cluster modifySnapshotCopyRetentionPeriod(String clusterIdentifier, int retentionPeriod, + boolean manual) { + Cluster cluster = requireCluster(clusterIdentifier); + // SnapshotCopyDisabledFault, not ...AlreadyDisabledFault: the model lists only this one here. + if (cluster.getSnapshotCopyDestinationRegion() == null) { + throw new AwsException("SnapshotCopyDisabledFault", + "Snapshot copy is not enabled on cluster " + clusterIdentifier + ".", 400); + } + if (manual) { + validateManualRetention(retentionPeriod); + cluster.setSnapshotCopyManualRetentionPeriod(retentionPeriod); + } else { + validateAutomatedRetention(retentionPeriod); + cluster.setSnapshotCopyRetentionPeriod(retentionPeriod); + } + clusters.put(clusterIdentifier, cluster); + clusters.flush(); + return cluster; + } + + // ── Snapshot Schedule Operations ───────────────────────────────────────── + + private static final int SNAPSHOT_SCHEDULE_PAGE_MAX = 100; + + private static final Pattern RATE_DEFINITION = + Pattern.compile("rate\\(\\s*(\\d+)\\s+(hours?|days?)\\s*\\)"); + private static final Pattern CRON_DEFINITION = + Pattern.compile("cron\\(\\s*([A-Za-z0-9,\\-*/?#]+(?:\\s+[A-Za-z0-9,\\-*/?#]+){2,5})\\s*\\)"); + // The API reference allows only alphanumerics; the management guide's own example uses a hyphen. + private static final Pattern SCHEDULE_IDENTIFIER = Pattern.compile("[A-Za-z0-9-]+"); + + /** + * Shape check against the Redshift snapshot-schedule documentation: {@code rate( hours|days)} + * with a frequency between once an hour and once a day, or {@code cron(...)} with three to six + * whitespace-separated fields drawn from the documented cron alphabet. Per-field value ranges + * are not checked. + */ + private static boolean isValidScheduleDefinition(String definition) { + if (definition == null) { + return false; + } + Matcher rate = RATE_DEFINITION.matcher(definition); + if (rate.matches()) { + long n = Long.parseLong(rate.group(1).length() > 9 ? "0" : rate.group(1)); + return rate.group(2).startsWith("hour") ? n >= 1 && n <= 24 : n == 1; + } + return CRON_DEFINITION.matcher(definition).matches(); + } + private static void validateScheduleDefinitions(List definitions) { + if (definitions == null || definitions.isEmpty()) { + throw new AwsException("InvalidSchedule", "ScheduleDefinitions must contain at least one definition.", 400); + } + for (String definition : definitions) { + if (!isValidScheduleDefinition(definition)) { + throw new AwsException("InvalidSchedule", "Invalid schedule definition: " + definition, 400); + } + } + } + + private SnapshotSchedule requireSnapshotSchedule(String scheduleIdentifier) { + return snapshotSchedules.get(scheduleIdentifier) + .orElseThrow(() -> new AwsException("SnapshotScheduleNotFound", + "Snapshot schedule " + scheduleIdentifier + " not found", 400)); + } + + public synchronized SnapshotSchedule createSnapshotSchedule(String scheduleIdentifier, String description, + List definitions, Map tags) { + String id = (scheduleIdentifier == null || scheduleIdentifier.isBlank()) + ? UUID.randomUUID().toString().replace("-", "") + : scheduleIdentifier; + if (!SCHEDULE_IDENTIFIER.matcher(id).matches()) { + throw new AwsException("InvalidParameterValue", + "ScheduleIdentifier may contain only letters, digits and hyphens: " + id, 400); + } + if (snapshotSchedules.get(id).isPresent()) { + throw new AwsException("SnapshotScheduleAlreadyExists", "Snapshot schedule " + id + " already exists", 400); + } + validateScheduleDefinitions(definitions); + SnapshotSchedule schedule = new SnapshotSchedule(id, description, definitions); + if (tags != null && !tags.isEmpty()) { + schedule.setTags(new LinkedHashMap<>(tags)); + } + snapshotSchedules.put(id, schedule); + snapshotSchedules.flush(); + return schedule; + } + + /** + * Every filter given must match. An unknown schedule or cluster yields an empty list rather + * than a fault: the model lists no errors for this operation. + */ + public PaginatedResult describeSnapshotSchedules(String scheduleIdentifier, + String clusterIdentifier, + List tagKeys, List tagValues, + Integer maxRecords, String marker) { + String clusterSchedule = null; + if (clusterIdentifier != null && !clusterIdentifier.isBlank()) { + clusterSchedule = clusters.get(clusterIdentifier).map(Cluster::getSnapshotScheduleIdentifier).orElse(null); + if (clusterSchedule == null) { + return new PaginatedResult<>(List.of(), null); + } + } + String byCluster = clusterSchedule; + List matching = snapshotSchedules.scan(k -> true).stream() + .filter(s -> scheduleIdentifier == null || scheduleIdentifier.isBlank() + || scheduleIdentifier.equals(s.getScheduleIdentifier())) + .filter(s -> byCluster == null || byCluster.equals(s.getScheduleIdentifier())) + .filter(s -> tagKeys == null || tagKeys.isEmpty() + || tagKeys.stream().anyMatch(s.getTags()::containsKey)) + .filter(s -> tagValues == null || tagValues.isEmpty() + || tagValues.stream().anyMatch(s.getTags()::containsValue)) + .toList(); + return Pagination.paginate(matching, SnapshotSchedule::getScheduleIdentifier, maxRecords, marker, + SNAPSHOT_SCHEDULE_PAGE_MAX, "InvalidParameterValue"); + } + + /** Identifiers of the clusters currently using the schedule, sorted for a stable response. */ + public List clustersUsingSnapshotSchedule(String scheduleIdentifier) { + return clusters.scan(k -> true).stream() + .filter(c -> scheduleIdentifier.equals(c.getSnapshotScheduleIdentifier())) + .map(Cluster::getClusterIdentifier) + .sorted() + .toList(); + } + + public synchronized SnapshotSchedule modifySnapshotSchedule(String scheduleIdentifier, List definitions) { + SnapshotSchedule schedule = requireSnapshotSchedule(scheduleIdentifier); + validateScheduleDefinitions(definitions); + schedule.setScheduleDefinitions(new ArrayList<>(definitions)); + snapshotSchedules.put(scheduleIdentifier, schedule); + snapshotSchedules.flush(); + return schedule; + } + + public synchronized void deleteSnapshotSchedule(String scheduleIdentifier) { + requireSnapshotSchedule(scheduleIdentifier); + if (!clustersUsingSnapshotSchedule(scheduleIdentifier).isEmpty()) { + throw new AwsException("InvalidClusterSnapshotScheduleState", + "Snapshot schedule " + scheduleIdentifier + " is associated with one or more clusters.", 400); + } + snapshotSchedules.delete(scheduleIdentifier); + snapshotSchedules.flush(); + } + + public synchronized Cluster modifyClusterSnapshotSchedule(String clusterIdentifier, String scheduleIdentifier, + boolean disassociate) { + Cluster cluster = requireCluster(clusterIdentifier); + if (disassociate) { + cluster.setSnapshotScheduleIdentifier(null); + } else { + if (scheduleIdentifier == null || scheduleIdentifier.isBlank()) { + throw new AwsException("InvalidParameterValue", + "ScheduleIdentifier is required unless DisassociateSchedule is true", 400); + } + requireSnapshotSchedule(scheduleIdentifier); + cluster.setSnapshotScheduleIdentifier(scheduleIdentifier); + } + clusters.put(clusterIdentifier, cluster); + clusters.flush(); + return cluster; + } + // ── Tagging Operations ─────────────────────────────────────────────────── /** A resolved tag target: its current tags plus a sink that persists an updated map. */ @@ -1384,6 +1631,12 @@ public class RedshiftService { "snapshotcopygrant", g.getTags(), tagKeysFilter); } } + if (resourceType == null || "snapshotschedule".equalsIgnoreCase(resourceType)) { + for (SnapshotSchedule s : snapshotSchedules.scan(k -> true)) { + addTaggedResources(result, snapshotScheduleArn(s.getScheduleIdentifier()), + "snapshotschedule", s.getTags(), tagKeysFilter); + } + } return result; } @@ -1425,13 +1678,17 @@ public class RedshiftService { return regionResolver.buildArn("redshift", regionResolver.getRegion(), "snapshotcopygrant:" + name); } + private String snapshotScheduleArn(String scheduleIdentifier) { + return regionResolver.buildArn("redshift", regionResolver.getRegion(), "snapshotschedule:" + scheduleIdentifier); + } + /** * Resolves a tagging ResourceName to its backing resource. * * Redshift ARNs have the shape {@code arn:aws:redshift::::}, * where {@code } is one of {@code cluster}, {@code snapshot} (id shape * {@code /}), {@code parametergroup}, {@code subnetgroup} or - * {@code snapshotcopygrant}. Unlike RDS's tag + * {@code snapshotcopygrant} or {@code snapshotschedule}. Unlike RDS's tag * resolution, there is no bare-name fallback: Redshift tagging is new, so there is no * existing caller to stay backward compatible with. */ @@ -1514,6 +1771,16 @@ public class RedshiftService { snapshotCopyGrants.flush(); }); } + case "snapshotschedule" -> { + // ResourceNotFoundFault for the same reason as snapshotcopygrant above. + SnapshotSchedule schedule = snapshotSchedules.get(id) + .orElseThrow(() -> new AwsException("ResourceNotFoundFault", "Snapshot schedule " + id + " not found", 404)); + yield new TagHandle(schedule.getTags(), updated -> { + schedule.setTags(updated); + snapshotSchedules.put(id, schedule); + snapshotSchedules.flush(); + }); + } default -> throw new AwsException("InvalidParameterValue", "Tagging for resource type '" + type + "' is not supported: " + resourceName, 400); }; diff --git a/src/main/java/io/github/hectorvent/floci/services/redshift/model/Cluster.java b/src/main/java/io/github/hectorvent/floci/services/redshift/model/Cluster.java index 75b157d3d0..6629606339 100644 --- a/src/main/java/io/github/hectorvent/floci/services/redshift/model/Cluster.java +++ b/src/main/java/io/github/hectorvent/floci/services/redshift/model/Cluster.java @@ -73,6 +73,24 @@ public class Cluster { public String getLoggingS3TableGranularity() { return loggingS3TableGranularity; } public void setLoggingS3TableGranularity(String loggingS3TableGranularity) { this.loggingS3TableGranularity = loggingS3TableGranularity; } + // Cross-region snapshot copy (EnableSnapshotCopy). Enabled exactly when the destination is set. + private String snapshotCopyDestinationRegion; + private Integer snapshotCopyRetentionPeriod; + private Integer snapshotCopyManualRetentionPeriod; + private String snapshotCopyGrantName; + private String snapshotScheduleIdentifier; + + public String getSnapshotCopyDestinationRegion() { return snapshotCopyDestinationRegion; } + public void setSnapshotCopyDestinationRegion(String snapshotCopyDestinationRegion) { this.snapshotCopyDestinationRegion = snapshotCopyDestinationRegion; } + public Integer getSnapshotCopyRetentionPeriod() { return snapshotCopyRetentionPeriod; } + public void setSnapshotCopyRetentionPeriod(Integer snapshotCopyRetentionPeriod) { this.snapshotCopyRetentionPeriod = snapshotCopyRetentionPeriod; } + public Integer getSnapshotCopyManualRetentionPeriod() { return snapshotCopyManualRetentionPeriod; } + public void setSnapshotCopyManualRetentionPeriod(Integer snapshotCopyManualRetentionPeriod) { this.snapshotCopyManualRetentionPeriod = snapshotCopyManualRetentionPeriod; } + public String getSnapshotCopyGrantName() { return snapshotCopyGrantName; } + public void setSnapshotCopyGrantName(String snapshotCopyGrantName) { this.snapshotCopyGrantName = snapshotCopyGrantName; } + public String getSnapshotScheduleIdentifier() { return snapshotScheduleIdentifier; } + public void setSnapshotScheduleIdentifier(String snapshotScheduleIdentifier) { this.snapshotScheduleIdentifier = snapshotScheduleIdentifier; } + private boolean multiAZ = false; public boolean isMultiAZ() { return multiAZ; } diff --git a/src/main/java/io/github/hectorvent/floci/services/redshift/model/SnapshotSchedule.java b/src/main/java/io/github/hectorvent/floci/services/redshift/model/SnapshotSchedule.java new file mode 100644 index 0000000000..d746013c17 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/redshift/model/SnapshotSchedule.java @@ -0,0 +1,37 @@ +package io.github.hectorvent.floci.services.redshift.model; + +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** + * A snapshot schedule. Associated clusters are not stored here: each cluster records the + * schedule it uses, so deleting a cluster cannot leave a stale association behind. + */ +@RegisterForReflection +public class SnapshotSchedule { + private String scheduleIdentifier; + private String scheduleDescription; + private List scheduleDefinitions = new ArrayList<>(); + private Map tags = new LinkedHashMap<>(); + + public SnapshotSchedule() {} + + public SnapshotSchedule(String scheduleIdentifier, String scheduleDescription, List scheduleDefinitions) { + this.scheduleIdentifier = scheduleIdentifier; + this.scheduleDescription = scheduleDescription; + this.scheduleDefinitions = new ArrayList<>(scheduleDefinitions); + } + + public String getScheduleIdentifier() { return scheduleIdentifier; } + public void setScheduleIdentifier(String scheduleIdentifier) { this.scheduleIdentifier = scheduleIdentifier; } + public String getScheduleDescription() { return scheduleDescription; } + public void setScheduleDescription(String scheduleDescription) { this.scheduleDescription = scheduleDescription; } + public List getScheduleDefinitions() { return scheduleDefinitions; } + public void setScheduleDefinitions(List scheduleDefinitions) { this.scheduleDefinitions = scheduleDefinitions; } + public Map getTags() { return tags; } + public void setTags(Map tags) { this.tags = tags; } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftOperationsTest.java b/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftOperationsTest.java index 59b201d253..eff00a4e92 100644 --- a/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftOperationsTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftOperationsTest.java @@ -5,6 +5,8 @@ import io.github.hectorvent.floci.services.redshift.container.RedshiftContainerM import io.quarkus.test.InjectMock; import io.quarkus.test.junit.QuarkusTest; import io.restassured.path.xml.XmlPath; +import io.restassured.response.Response; +import io.restassured.specification.RequestSpecification; import jakarta.inject.Inject; import org.junit.jupiter.api.MethodOrderer; import org.junit.jupiter.api.Order; @@ -940,4 +942,215 @@ public class RedshiftOperationsTest { .then() .statusCode(200); } + + + private static Response redshift(String action, String... keyValues) { + RequestSpecification request = given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", AUTH_HEADER) + .formParam("Action", action); + for (int i = 0; i < keyValues.length; i += 2) { + request.formParam(keyValues[i], keyValues[i + 1]); + } + return request.when().post("/"); + } + + private static void assertFault(Response response, int status, String code) { + assertEquals(status, response.statusCode(), response.asString()); + assertEquals(code, XmlPath.from(response.asString()).getString("ErrorResponse.Error.Code")); + } + + private static XmlPath describeCluster(String clusterIdentifier) { + Response response = redshift("DescribeClusters", "ClusterIdentifier", clusterIdentifier); + assertEquals(200, response.statusCode(), response.asString()); + return XmlPath.from(response.asString()) + .setRootPath("DescribeClustersResponse.DescribeClustersResult.Clusters.Cluster"); + } + + private static XmlPath describeSchedules(String... filters) { + Response response = redshift("DescribeSnapshotSchedules", filters); + assertEquals(200, response.statusCode(), response.asString()); + return XmlPath.from(response.asString()) + .setRootPath("DescribeSnapshotSchedulesResponse.DescribeSnapshotSchedulesResult.SnapshotSchedules"); + } + + /** + * aws_redshift_snapshot_copy reads ClusterSnapshotCopyStatus back through DescribeClusters, + * so every assertion here reads the state through that separate call. + */ + @Test + @Order(9) + void snapshotCopyLifecycle() { + when(containerManager.start(any(), eq("cluster-copy"), any(), any())) + .thenReturn(new RedshiftContainerHandle("c9", "cluster-copy", "localhost", 5449)); + assertEquals(200, redshift("CreateCluster", "ClusterIdentifier", "cluster-copy", "NodeType", "dc2.large", + "MasterUsername", "admin", "MasterUserPassword", "password123").statusCode()); + + assertFalse(redshift("DescribeClusters", "ClusterIdentifier", "cluster-copy").asString() + .contains("ClusterSnapshotCopyStatus")); + assertFault(redshift("DisableSnapshotCopy", "ClusterIdentifier", "cluster-copy"), + 400, "SnapshotCopyAlreadyDisabledFault"); + assertFault(redshift("ModifySnapshotCopyRetentionPeriod", "ClusterIdentifier", "cluster-copy", + "RetentionPeriod", "10"), 400, "SnapshotCopyDisabledFault"); + assertFault(redshift("EnableSnapshotCopy", "ClusterIdentifier", "no-such-cluster", + "DestinationRegion", "us-west-2"), 404, "ClusterNotFound"); + assertFault(redshift("EnableSnapshotCopy", "ClusterIdentifier", "cluster-copy", + "DestinationRegion", "us-west-2", "RetentionPeriod", "0"), 400, "InvalidRetentionPeriodFault"); + assertFault(redshift("EnableSnapshotCopy", "ClusterIdentifier", "cluster-copy", + "DestinationRegion", "us-west-2", "SnapshotCopyGrantName", "no-such-grant"), + 400, "SnapshotCopyGrantNotFoundFault"); + for (String bad : List.of("us-nowhere-1", "not a region")) { + assertFault(redshift("EnableSnapshotCopy", "ClusterIdentifier", "cluster-copy", + "DestinationRegion", bad), 404, "UnknownSnapshotCopyRegionFault"); + } + assertFalse(redshift("DescribeClusters", "ClusterIdentifier", "cluster-copy").asString() + .contains("ClusterSnapshotCopyStatus")); + + Response enabled = redshift("EnableSnapshotCopy", + "ClusterIdentifier", "cluster-copy", "DestinationRegion", "us-west-2"); + assertEquals(200, enabled.statusCode(), enabled.asString()); + assertEquals("us-west-2", XmlPath.from(enabled.asString()).getString( + "EnableSnapshotCopyResponse.EnableSnapshotCopyResult.Cluster.ClusterSnapshotCopyStatus.DestinationRegion")); + + XmlPath copy = describeCluster("cluster-copy"); + assertEquals("us-west-2", copy.getString("ClusterSnapshotCopyStatus.DestinationRegion")); + assertEquals(7, copy.getInt("ClusterSnapshotCopyStatus.RetentionPeriod")); + assertEquals(-1, copy.getInt("ClusterSnapshotCopyStatus.ManualSnapshotRetentionPeriod")); + + assertFault(redshift("EnableSnapshotCopy", "ClusterIdentifier", "cluster-copy", + "DestinationRegion", "eu-west-1"), 400, "SnapshotCopyAlreadyEnabledFault"); + + assertEquals(200, redshift("ModifySnapshotCopyRetentionPeriod", "ClusterIdentifier", "cluster-copy", + "RetentionPeriod", "14").statusCode()); + assertEquals(200, redshift("ModifySnapshotCopyRetentionPeriod", "ClusterIdentifier", "cluster-copy", + "RetentionPeriod", "30", "Manual", "true").statusCode()); + copy = describeCluster("cluster-copy"); + assertEquals(14, copy.getInt("ClusterSnapshotCopyStatus.RetentionPeriod")); + assertEquals(30, copy.getInt("ClusterSnapshotCopyStatus.ManualSnapshotRetentionPeriod")); + assertEquals("us-west-2", copy.getString("ClusterSnapshotCopyStatus.DestinationRegion")); + + assertEquals(200, redshift("DisableSnapshotCopy", "ClusterIdentifier", "cluster-copy").statusCode()); + assertFalse(redshift("DescribeClusters", "ClusterIdentifier", "cluster-copy").asString() + .contains("ClusterSnapshotCopyStatus")); + + // A grant named on enable is reported back. + assertEquals(200, redshift("CreateSnapshotCopyGrant", "SnapshotCopyGrantName", "copy-lifecycle-grant").statusCode()); + assertEquals(200, redshift("EnableSnapshotCopy", "ClusterIdentifier", "cluster-copy", + "DestinationRegion", "us-west-2", "RetentionPeriod", "3", + "ManualSnapshotRetentionPeriod", "5", "SnapshotCopyGrantName", "copy-lifecycle-grant").statusCode()); + copy = describeCluster("cluster-copy"); + assertEquals("copy-lifecycle-grant", copy.getString("ClusterSnapshotCopyStatus.SnapshotCopyGrantName")); + assertEquals(3, copy.getInt("ClusterSnapshotCopyStatus.RetentionPeriod")); + assertEquals(5, copy.getInt("ClusterSnapshotCopyStatus.ManualSnapshotRetentionPeriod")); + + // A grant a cluster's enabled copy still names cannot be deleted (InvalidSnapshotCopyGrantStateFault). + assertFault(redshift("DeleteSnapshotCopyGrant", "SnapshotCopyGrantName", "copy-lifecycle-grant"), + 400, "InvalidSnapshotCopyGrantStateFault"); + assertEquals(200, redshift("DisableSnapshotCopy", "ClusterIdentifier", "cluster-copy").statusCode()); + + assertEquals(200, redshift("DeleteCluster", "ClusterIdentifier", "cluster-copy").statusCode()); + assertEquals(200, redshift("DeleteSnapshotCopyGrant", "SnapshotCopyGrantName", "copy-lifecycle-grant").statusCode()); + } + + /** + * aws_redshift_snapshot_schedule_association reads DescribeSnapshotSchedules by ClusterIdentifier + * and ScheduleIdentifier and looks for the cluster in AssociatedClusters with state ACTIVE. + */ + @Test + @Order(10) + void snapshotScheduleLifecycle() { + when(containerManager.start(any(), eq("cluster-sched"), any(), any())) + .thenReturn(new RedshiftContainerHandle("c10", "cluster-sched", "localhost", 5450)); + assertEquals(200, redshift("CreateCluster", "ClusterIdentifier", "cluster-sched", "NodeType", "dc2.large", + "MasterUsername", "admin", "MasterUserPassword", "password123").statusCode()); + + Response created = redshift("CreateSnapshotSchedule", + "ScheduleIdentifier", "sched-1", + "ScheduleDescription", "twice a day", + "ScheduleDefinitions.ScheduleDefinition.1", "rate(12 hours)", + "Tags.Tag.1.Key", "env", "Tags.Tag.1.Value", "test"); + assertEquals(200, created.statusCode(), created.asString()); + assertEquals("sched-1", XmlPath.from(created.asString()) + .getString("CreateSnapshotScheduleResponse.CreateSnapshotScheduleResult.ScheduleIdentifier")); + + assertFault(redshift("CreateSnapshotSchedule", "ScheduleIdentifier", "sched-1", + "ScheduleDefinitions.ScheduleDefinition.1", "rate(1 day)"), 400, "SnapshotScheduleAlreadyExists"); + assertFault(redshift("CreateSnapshotSchedule", "ScheduleIdentifier", "sched-bad", + "ScheduleDefinitions.ScheduleDefinition.1", "every noon"), 400, "InvalidSchedule"); + for (String bad : List.of("rate(foo)", "rate(0 hours)", "rate(25 hours)", "rate(2 days)", + "cron(not-a-cron-expression)", "cron(0 12)")) { + assertFault(redshift("CreateSnapshotSchedule", "ScheduleIdentifier", "sched-bad", + "ScheduleDefinitions.ScheduleDefinition.1", bad), 400, "InvalidSchedule"); + } + for (String badId : List.of("sched bad", "sched_bad", "sched!")) { + assertFault(redshift("CreateSnapshotSchedule", "ScheduleIdentifier", badId, + "ScheduleDefinitions.ScheduleDefinition.1", "rate(1 day)"), 400, "InvalidParameterValue"); + assertEquals(0, describeSchedules("ScheduleIdentifier", badId).getList("SnapshotSchedule").size()); + } + for (String goodId : List.of("tf-redshift-snapshot-schedule", "Sched2")) { + assertEquals(200, redshift("CreateSnapshotSchedule", "ScheduleIdentifier", goodId, + "ScheduleDefinitions.ScheduleDefinition.1", "rate(1 day)").statusCode()); + assertEquals(List.of(goodId), describeSchedules("ScheduleIdentifier", goodId) + .getList("SnapshotSchedule.ScheduleIdentifier")); + assertEquals(200, redshift("DeleteSnapshotSchedule", "ScheduleIdentifier", goodId).statusCode()); + } + + XmlPath schedules = describeSchedules("ScheduleIdentifier", "sched-1"); + assertEquals(1, schedules.getList("SnapshotSchedule.ScheduleIdentifier").size()); + assertEquals("rate(12 hours)", schedules.getString("SnapshotSchedule.ScheduleDefinitions.ScheduleDefinition")); + assertEquals("twice a day", schedules.getString("SnapshotSchedule.ScheduleDescription")); + assertEquals("env", schedules.getString("SnapshotSchedule.Tags.Tag.Key")); + assertEquals(0, schedules.getInt("SnapshotSchedule.AssociatedClusterCount")); + assertEquals(0, describeSchedules("ScheduleIdentifier", "no-such-schedule") + .getList("SnapshotSchedule").size()); + + assertFault(redshift("ModifyClusterSnapshotSchedule", "ClusterIdentifier", "cluster-sched", + "ScheduleIdentifier", "no-such-schedule"), 400, "SnapshotScheduleNotFound"); + assertFault(redshift("ModifyClusterSnapshotSchedule", "ClusterIdentifier", "no-such-cluster", + "ScheduleIdentifier", "sched-1"), 404, "ClusterNotFound"); + assertEquals(200, redshift("ModifyClusterSnapshotSchedule", "ClusterIdentifier", "cluster-sched", + "ScheduleIdentifier", "sched-1").statusCode()); + + for (XmlPath associated : List.of(describeSchedules("ClusterIdentifier", "cluster-sched"), + describeSchedules("ScheduleIdentifier", "sched-1"))) { + assertEquals("sched-1", associated.getString("SnapshotSchedule.ScheduleIdentifier")); + assertEquals(1, associated.getInt("SnapshotSchedule.AssociatedClusterCount")); + assertEquals("cluster-sched", associated.getString( + "SnapshotSchedule.AssociatedClusters.ClusterAssociatedToSchedule.ClusterIdentifier")); + assertEquals("ACTIVE", associated.getString( + "SnapshotSchedule.AssociatedClusters.ClusterAssociatedToSchedule.ScheduleAssociationState")); + } + assertEquals("sched-1", describeCluster("cluster-sched").getString("SnapshotScheduleIdentifier")); + + assertFault(redshift("DeleteSnapshotSchedule", "ScheduleIdentifier", "sched-1"), + 400, "InvalidClusterSnapshotScheduleState"); + + assertFault(redshift("ModifySnapshotSchedule", "ScheduleIdentifier", "sched-1", + "ScheduleDefinitions.ScheduleDefinition.1", "rate(foo)"), 400, "InvalidSchedule"); + assertEquals(200, redshift("ModifySnapshotSchedule", "ScheduleIdentifier", "sched-1", + "ScheduleDefinitions.ScheduleDefinition.1", "cron(0 12 * * ? *)").statusCode()); + assertEquals("cron(0 12 * * ? *)", describeSchedules("ScheduleIdentifier", "sched-1") + .getString("SnapshotSchedule.ScheduleDefinitions.ScheduleDefinition")); + + String scheduleArn = "arn:aws:redshift:us-east-1:000000000000:snapshotschedule:sched-1"; + assertEquals(200, redshift("CreateTags", "ResourceName", scheduleArn, + "Tags.Tag.1.Key", "team", "Tags.Tag.1.Value", "data").statusCode()); + XmlPath tags = XmlPath.from(redshift("DescribeTags", "ResourceName", scheduleArn).asString()) + .setRootPath("DescribeTagsResponse.DescribeTagsResult.TaggedResources"); + assertEquals(List.of("env", "team"), tags.getList("TaggedResource.Tag.Key")); + assertEquals("snapshotschedule", tags.getString("TaggedResource[0].ResourceType")); + assertEquals(List.of("sched-1"), describeSchedules("TagValues.TagValue.1", "data") + .getList("SnapshotSchedule.ScheduleIdentifier")); + + assertEquals(200, redshift("ModifyClusterSnapshotSchedule", "ClusterIdentifier", "cluster-sched", + "DisassociateSchedule", "true").statusCode()); + assertEquals(0, describeSchedules("ClusterIdentifier", "cluster-sched").getList("SnapshotSchedule").size()); + assertEquals(0, describeSchedules("ScheduleIdentifier", "sched-1").getInt("SnapshotSchedule.AssociatedClusterCount")); + + assertEquals(200, redshift("DeleteSnapshotSchedule", "ScheduleIdentifier", "sched-1").statusCode()); + assertEquals(0, describeSchedules("ScheduleIdentifier", "sched-1").getList("SnapshotSchedule").size()); + assertFault(redshift("DeleteSnapshotSchedule", "ScheduleIdentifier", "sched-1"), 400, "SnapshotScheduleNotFound"); + + assertEquals(200, redshift("DeleteCluster", "ClusterIdentifier", "cluster-sched").statusCode()); + } } 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 fa6d401c53..5624f7d5c4 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 @@ -11,6 +11,7 @@ import io.github.hectorvent.floci.services.redshift.model.Endpoint; import io.github.hectorvent.floci.services.redshift.model.Parameter; 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; import jakarta.ws.rs.core.MultivaluedHashMap; import jakarta.ws.rs.core.MultivaluedMap; import jakarta.ws.rs.core.Response; @@ -513,6 +514,26 @@ class RedshiftQueryHandlerTest { assertEquals("InvalidParameterValue", ex.getErrorCode()); } + @Test + void createSnapshotScheduleReadsScheduleDefinitionLocationNameInNumericOrder() { + // The SDK serialises ScheduleDefinitions as "ScheduleDefinitions.ScheduleDefinition.N". + MultivaluedMap params = new MultivaluedHashMap<>(); + params.putSingle("ScheduleIdentifier", "sched"); + params.putSingle("ScheduleDefinitions.ScheduleDefinition.10", "cron(0 1 * * ? *)"); + params.putSingle("ScheduleDefinitions.ScheduleDefinition.2", "rate(12 hours)"); + when(service.createSnapshotSchedule(any(), any(), any(), any())) + .thenAnswer(inv -> new SnapshotSchedule(inv.getArgument(0), null, inv.getArgument(2))); + + Response response = handler.handle("CreateSnapshotSchedule", params); + + assertEquals(200, response.getStatus()); + verify(service).createSnapshotSchedule(eq("sched"), isNull(), + eq(List.of("rate(12 hours)", "cron(0 1 * * ? *)")), eq(Map.of())); + String xml = (String) response.getEntity(); + assertTrue(xml.contains("" + + "rate(12 hours)"), xml); + } + @Test void createsSnapshotCopyGrant() { MultivaluedMap params = new MultivaluedHashMap<>(); diff --git a/tools/docs/services.yaml b/tools/docs/services.yaml index 376f1aef7a..cc1eadae87 100644 --- a/tools/docs/services.yaml +++ b/tools/docs/services.yaml @@ -304,10 +304,10 @@ services: doc: docs/services/redshift.md sources: - { path: src/main/java/io/github/hectorvent/floci/services/redshift/RedshiftQueryHandler.java, mode: switch } - # SubnetIds / VpcSecurityGroupIds / IamRoles / AddIamRoles / RemoveIamRoles / TagKeys / DbGroups - # are labels of an inner member-name switch (memberKeyRegex), not actions, same shape as the - # rds exclusions above. - exclude_actions: [SubnetIds, VpcSecurityGroupIds, IamRoles, AddIamRoles, RemoveIamRoles, TagKeys, DbGroups] + # SubnetIds / VpcSecurityGroupIds / IamRoles / AddIamRoles / RemoveIamRoles / TagKeys / TagValues / + # DbGroups / ScheduleDefinitions are labels of an inner member-name switch (memberKeyRegex), not + # actions, same shape as the rds exclusions above. + exclude_actions: [SubnetIds, VpcSecurityGroupIds, IamRoles, AddIamRoles, RemoveIamRoles, TagKeys, TagValues, DbGroups, ScheduleDefinitions] - service: redshiftdata doc: docs/services/redshift-data.md sources: