diff --git a/docs/services/redshift.md b/docs/services/redshift.md index c7bcd6ce10..5e75366076 100644 --- a/docs/services/redshift.md +++ b/docs/services/redshift.md @@ -155,7 +155,7 @@ The attributes follow the [CloudFormation resource schema](https://docs.aws.amaz | `ModifyEventSubscription` | Update the specified subscription filters, topic or enabled state | | `DeleteEventSubscription` | Delete an event notification subscription | | `DescribeEventSubscriptions` | List event subscriptions filtered by name or tags | -| `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 | +| `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`. A background sweep then copies the cluster's snapshots to that Region, see [Cross-region snapshot copy](#cross-region-snapshot-copy) | | `DisableSnapshotCopy` | Clear a cluster's snapshot copy configuration | | `ModifySnapshotCopyRetentionPeriod` | Change the automated (or, with `Manual`, the manual) snapshot copy retention period | | `CreateSnapshotSchedule` | Create a UTC rate or cron schedule that takes automated snapshots on associated clusters, with optional tags | @@ -306,6 +306,18 @@ and [COPY authorization parameters](https://docs.aws.amazon.com/redshift/latest/ `CreateTags`/`DeleteTags`/`DescribeTags` do not list that fault at all and return `ResourceNotFoundFault` (HTTP 404) for any missing resource, grants included. +## Cross-region snapshot copy + +`EnableSnapshotCopy` makes a background sweep (`FLOCI_SERVICES_REDSHIFT_SNAPSHOT_COPY_SWEEP_INTERVAL_SECONDS`, 60 by default) copy the cluster's snapshots to the destination Region. + +- **Only newer snapshots are copied.** A snapshot taken before copy was enabled stays where it is, as does a snapshot of a cluster whose copy was later disabled. +- **A copy is a separate snapshot in the destination Region.** It keeps the source's identifier, cluster identifier and type, gets an ARN in the destination Region, reports `SourceRegion`, and carries the copy grant's `KmsKeyId` when the cluster has one. `DescribeClusterSnapshots`, `DeleteClusterSnapshot`, `RestoreFromClusterSnapshot` and the tagging actions use the copy when the request's Region has one, and the snapshot itself otherwise. +- **The dump is copied to its own file.** Copies live under `/redshift-dumps//copies//`. +- **Copies are independent of the source.** Deleting the source snapshot leaves the copy, and deleting a copy does not bring it back: the source remembers the Regions it was carried to. A copy interrupted by a restart is finished by the next sweep without a second dump. +- **Hybrid storage can lose a copy after a crash.** The copy is written before the source is marked, but hybrid storage flushes in the background and does not report a failed write. If the copy's write fails and the source's succeeds, a crash before the next flush leaves the source marked as copied without a copy, and later sweeps skip it. Persistent and WAL storage report the failed write before the source is marked, so a crash there leaves the snapshot to be copied again. +- **Retention.** Copied automated snapshots follow the cluster's current `RetentionPeriod`, so `ModifySnapshotCopyRetentionPeriod` changes existing ones. Copied manual snapshots keep the `ManualSnapshotRetentionPeriod` they were copied with; `-1` keeps them until deleted. Retention counts from the source snapshot's creation time. +- **The cluster store has no Region.** A cluster restored from a copy is created in the same store as every other cluster, as before. + ## Automated snapshots Clusters take automated SQL-dump snapshots using their associated snapshot schedule. Use @@ -481,6 +493,8 @@ For `AWS::Redshift::ClusterParameterGroup`, `Parameters` is applied via `ModifyC | `FLOCI_SERVICES_REDSHIFT_AUTOMATED_SNAPSHOTS_ENABLED` | `true` | Run background automated snapshot and retention sweeps | | `FLOCI_SERVICES_REDSHIFT_CLOUDWATCH_METRICS_ENABLED` | `true` | Publish the `AWS/Redshift` metrics of available clusters to CloudWatch once a minute, see [CloudWatch metrics](#cloudwatch-metrics) | | `FLOCI_SERVICES_REDSHIFT_SNAPSHOT_SWEEP_INTERVAL_SECONDS` | `60` | Delay between background snapshot sweeps | +| `FLOCI_SERVICES_REDSHIFT_SNAPSHOT_COPY_ENABLED` | `true` | Run the background sweep that copies snapshots of copy-enabled clusters to their destination Region | +| `FLOCI_SERVICES_REDSHIFT_SNAPSHOT_COPY_SWEEP_INTERVAL_SECONDS` | `60` | Delay between snapshot copy sweeps | | `FLOCI_SERVICES_REDSHIFT_IMAGE_VERSION` | `postgres:15-alpine` | PostgreSQL Docker image backing each cluster | | `FLOCI_SERVICES_REDSHIFT_DEFAULT_PORT` | `5439` | Reported Redshift port hint (the real host port is dynamic and comes from `DescribeClusters`) | | `FLOCI_SERVICES_REDSHIFT_PROXY_BASE_PORT` | `7100` | Lowest host port the per-cluster auth proxies bind | @@ -892,7 +906,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, and IAM authentication. Cross-region snapshot copy is stored and reported, but no snapshot is copied to another region. +- Resize, pause/resume, and IAM authentication. - 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/config/EmulatorConfig.java b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java index 7d620a4c0e..ac99fa2376 100644 --- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java +++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java @@ -1736,6 +1736,16 @@ public interface EmulatorConfig { boolean cloudwatchMetricsEnabled(); @WithDefault("60") long snapshotSweepIntervalSeconds(); + + /** + * Copy snapshots of clusters with snapshot copy enabled into the destination Region. + * Env: FLOCI_SERVICES_REDSHIFT_SNAPSHOT_COPY_ENABLED + */ + @WithDefault("true") + boolean snapshotCopyEnabled(); + + @WithDefault("60") + long snapshotCopySweepIntervalSeconds(); @WithDefault("true") boolean enabled(); @WithDefault("5439") diff --git a/src/main/java/io/github/hectorvent/floci/core/common/SweepScheduler.java b/src/main/java/io/github/hectorvent/floci/core/common/SweepScheduler.java new file mode 100644 index 0000000000..d6ab925a47 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/core/common/SweepScheduler.java @@ -0,0 +1,60 @@ +package io.github.hectorvent.floci.core.common; + +import io.quarkus.runtime.ShutdownEvent; +import io.quarkus.runtime.StartupEvent; +import jakarta.annotation.Priority; +import jakarta.enterprise.event.Observes; + +import java.time.Instant; + +/** + * Forwards a bean's startup, shutdown and reset events to a {@link SweepWorker}. A subclass supplies the + * worker; the state it sweeps lives in the owning service's storage, which reset wipes, so there is nothing + * to clear here. + */ +public abstract class SweepScheduler implements Resettable { + private final SweepWorker worker; + + protected SweepScheduler(SweepWorker worker) { + this.worker = worker; + } + + // Quarkus builds the client proxy of an @ApplicationScoped subclass through this; the proxy never uses it. + protected SweepScheduler() { + this.worker = null; + } + + public void onStart(@Observes StartupEvent ignored) { + worker.start(); + } + + // Priority below APPLICATION (2000) so the worker drains before EmulatorLifecycle.onStop flushes storage. + public void onStop(@Observes @Priority(1000) ShutdownEvent ignored) { + worker.stop(); + } + + /** Whether a background worker exists, which the owner's configuration switches decide. */ + public boolean active() { + return worker.active(); + } + + public void tick(Instant now) { + worker.tick(now); + } + + /** Drains a running sweep so it cannot write into storage that reset is about to clear. */ + @Override + public void beforeReset() { + worker.pause(); + } + + @Override + public void clear() { + // The swept state lives in the owning service's storage, which reset wipes. + } + + @Override + public void afterReset() { + worker.resume(); + } +} 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 a5925b7c4d..85d2203f29 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 @@ -1226,7 +1226,11 @@ public class RedshiftQueryHandler { .elem("ManualSnapshotRetentionPeriod", snapshot.getManualSnapshotRetentionPeriod().toString()) .elem("Status", snapshot.getStatus()) .elem("Port", String.valueOf(snapshot.getPort())) - .elem("MasterUsername", snapshot.getMasterUsername()); + .elem("MasterUsername", snapshot.getMasterUsername()) + .elem("SourceRegion", snapshot.getSourceRegion()); + if (snapshot.getKmsKeyId() != null) { + builder.elem("Encrypted", "true").elem("KmsKeyId", snapshot.getKmsKeyId()); + } return builder.end("Snapshot").build(); } 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 b0b76d9202..65ba7410a3 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 @@ -42,6 +42,7 @@ import jakarta.inject.Inject; import org.jboss.logging.Logger; import java.io.IOException; +import java.io.UncheckedIOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; @@ -50,6 +51,7 @@ import java.time.Duration; import java.time.Instant; import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; +import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.Collection; import java.util.Comparator; @@ -77,6 +79,8 @@ public class RedshiftService implements ManagedSecretRotator { private final AccountAwareStorageBackend clusters; private final AccountAwareStorageBackend snapshots; + // Snapshots copied into another Region, keyed region::identifier because the store above has no Region. + private final AccountAwareStorageBackend snapshotCopies; private final AccountAwareStorageBackend parameterGroups; private final AccountAwareStorageBackend subnetGroups; private static final int MIN_INTEGRATION_RECORDS = 20; @@ -189,6 +193,7 @@ public class RedshiftService implements ManagedSecretRotator { RedshiftEventService events, RedshiftIntegrationEventPublisher integrationEvents) { this.clusters = storageFactory.create("redshift", "redshift-clusters.json", new TypeReference>() {}); this.snapshots = storageFactory.create("redshift", "redshift-snapshots.json", new TypeReference>() {}); + this.snapshotCopies = storageFactory.create("redshift", "redshift-snapshot-copies.json", new TypeReference>() {}); this.parameterGroups = storageFactory.create("redshift", "redshift-parameter-groups.json", new TypeReference>() {}); this.subnetGroups = storageFactory.create("redshift", "redshift-subnet-groups.json", new TypeReference>() {}); this.integrations = storageFactory.create("redshift", "redshift-integrations.json", new TypeReference>() {}); @@ -1645,7 +1650,9 @@ public class RedshiftService implements ManagedSecretRotator { rejectPausedCluster(cluster); validateSnapshotIdentifier(snapshotIdentifier); String clusterIdentifier = cluster.getClusterIdentifier(); - if ((scheduledTime == null ? snapshots.get(snapshotIdentifier) + boolean shadowedByCopy = scheduledTime == null + && snapshotCopies.get(copyKey(regionResolver.getRegion(), snapshotIdentifier)).isPresent(); + if (shadowedByCopy || (scheduledTime == null ? snapshots.get(snapshotIdentifier) : snapshots.getForAccount(accountId, snapshotIdentifier)).isPresent()) { throw new AwsException("ClusterSnapshotAlreadyExists", "Snapshot " + snapshotIdentifier + " already exists", 400); } @@ -1730,18 +1737,37 @@ public class RedshiftService implements ManagedSecretRotator { public List describeSnapshots(String snapshotIdentifier, String clusterIdentifier) { if (snapshotIdentifier != null && !snapshotIdentifier.isBlank()) { - Optional snapshot = snapshots.get(snapshotIdentifier); + Optional snapshot = findSnapshot(snapshotIdentifier); if (snapshot.isEmpty()) { throw new AwsException("ClusterSnapshotNotFound", "Snapshot " + snapshotIdentifier + " not found", 404); } return List.of(snapshot.get()); } + List visible = new ArrayList<>(snapshots.scan(k -> true)); + // A copy in this Region stands in for the snapshot of the same name it was copied from. + List copies = copiesInRegion(regionResolver.getRegion()); + Set copied = new LinkedHashSet<>(); + copies.forEach(copy -> copied.add(copy.getSnapshotIdentifier())); + visible.removeIf(snapshot -> copied.contains(snapshot.getSnapshotIdentifier())); + visible.addAll(copies); if (clusterIdentifier != null && !clusterIdentifier.isBlank()) { - return snapshots.scan(k -> true).stream() - .filter(s -> clusterIdentifier.equals(s.getClusterIdentifier())) - .toList(); + return visible.stream().filter(s -> clusterIdentifier.equals(s.getClusterIdentifier())).toList(); } - return snapshots.scan(k -> true); + return visible; + } + + private static String copyKey(String region, String snapshotIdentifier) { + return region + "::" + snapshotIdentifier; + } + + private List copiesInRegion(String region) { + return snapshotCopies.scan(key -> key.startsWith(region + "::")); + } + + /** The copy in this request's Region if there is one, otherwise the snapshot itself. */ + private Optional findSnapshot(String snapshotIdentifier) { + return snapshotCopies.get(copyKey(regionResolver.getRegion(), snapshotIdentifier)) + .or(() -> snapshots.get(snapshotIdentifier)); } public List describeSnapshots(String snapshotIdentifier) { @@ -1749,7 +1775,7 @@ public class RedshiftService implements ManagedSecretRotator { } public Optional getSnapshot(String snapshotIdentifier) { - return snapshots.get(snapshotIdentifier); + return findSnapshot(snapshotIdentifier); } public Snapshot deleteSnapshot(String snapshotIdentifier) { @@ -1757,7 +1783,9 @@ public class RedshiftService implements ManagedSecretRotator { } private Snapshot removeSnapshot(String snapshotIdentifier) { - Optional snapshotOpt = snapshots.get(snapshotIdentifier); + String copyKey = copyKey(regionResolver.getRegion(), snapshotIdentifier); + Optional copyOpt = snapshotCopies.get(copyKey); + Optional snapshotOpt = copyOpt.or(() -> snapshots.get(snapshotIdentifier)); if (snapshotOpt.isEmpty()) { throw new AwsException("ClusterSnapshotNotFound", "Snapshot " + snapshotIdentifier + " not found", 404); } @@ -1765,8 +1793,13 @@ public class RedshiftService implements ManagedSecretRotator { if ("automated".equals(snapshot.getSnapshotType())) { throw new AwsException("InvalidClusterSnapshotState", "Automated snapshots cannot be deleted manually", 400); } - snapshots.delete(snapshotIdentifier); - snapshots.flush(); + if (copyOpt.isPresent()) { + snapshotCopies.delete(copyKey); + snapshotCopies.flush(); + } else { + snapshots.delete(snapshotIdentifier); + snapshots.flush(); + } if (isTrustedDumpPath(snapshot.getSqlDump())) { try { Files.deleteIfExists(Paths.get(snapshot.getSqlDump())); @@ -1849,7 +1882,7 @@ public class RedshiftService implements ManagedSecretRotator { throw new AwsException("ClusterAlreadyExists", "Cluster " + clusterIdentifier + " already exists", 400); } - Optional snapshotOpt = snapshots.get(snapshotIdentifier); + Optional snapshotOpt = findSnapshot(snapshotIdentifier); if (snapshotOpt.isEmpty()) { throw new AwsException("ClusterSnapshotNotFound", "Snapshot " + snapshotIdentifier + " not found", 404); } @@ -2170,7 +2203,7 @@ public class RedshiftService implements ManagedSecretRotator { case RedshiftEventCatalog.CLUSTER -> clusters.get(sourceIdentifier).isPresent(); case RedshiftEventCatalog.PARAMETER_GROUP -> DEFAULT_PARAMETER_GROUP_NAME.equals(sourceIdentifier) || parameterGroups.get(sourceIdentifier).isPresent(); - case RedshiftEventCatalog.SNAPSHOT -> snapshots.get(sourceIdentifier).isPresent(); + case RedshiftEventCatalog.SNAPSHOT -> findSnapshot(sourceIdentifier).isPresent(); default -> false; }; } @@ -2391,7 +2424,7 @@ public class RedshiftService implements ManagedSecretRotator { } } - /** Copy is recorded on the cluster only; no snapshot is actually copied to another region. */ + /** Records the copy on the cluster; {@link #runSnapshotCopies} carries the snapshots to the destination. */ public Cluster enableSnapshotCopy(String clusterIdentifier, String destinationRegion, Integer retentionPeriod, Integer manualRetentionPeriod, String snapshotCopyGrantName) { @@ -2411,6 +2444,11 @@ public class RedshiftService implements ManagedSecretRotator { throw new AwsException("UnknownSnapshotCopyRegionFault", "Unknown destination region: " + destinationRegion, 404); } + if (destinationRegion.equals(snapshotRegion(cluster))) { + // A copy in the cluster's own Region would shadow the snapshots it was copied from. + throw new AwsException("UnknownSnapshotCopyRegionFault", + "The destination region must differ from the cluster's region: " + destinationRegion, 404); + } int retention = retentionPeriod == null ? DEFAULT_SNAPSHOT_COPY_RETENTION_DAYS : retentionPeriod; int manualRetention = manualRetentionPeriod == null ? RETAIN_MANUAL_SNAPSHOTS_INDEFINITELY : manualRetentionPeriod; @@ -2425,6 +2463,7 @@ public class RedshiftService implements ManagedSecretRotator { cluster.setSnapshotCopyRetentionPeriod(retention); cluster.setSnapshotCopyManualRetentionPeriod(manualRetention); cluster.setSnapshotCopyGrantName(hasGrant ? snapshotCopyGrantName : null); + cluster.setSnapshotCopyEnabledAt(Instant.now()); clusters.put(clusterIdentifier, cluster); clusters.flush(); return cluster; @@ -2444,6 +2483,7 @@ public class RedshiftService implements ManagedSecretRotator { cluster.setSnapshotCopyRetentionPeriod(null); cluster.setSnapshotCopyManualRetentionPeriod(null); cluster.setSnapshotCopyGrantName(null); + cluster.setSnapshotCopyEnabledAt(null); clusters.put(clusterIdentifier, cluster); clusters.flush(); return cluster; @@ -2625,6 +2665,257 @@ public class RedshiftService implements ManagedSecretRotator { } } + /** + * One copy sweep: carries the snapshots of every copy-enabled cluster to its destination Region, + * then removes the copies whose retention has run out. One snapshot failing is logged and retried + * by the next sweep without stopping the rest. + */ + void runSnapshotCopies(Instant now) { + for (AccountAwareStorageBackend.AccountEntry entry : clusters.scanAllAccountEntries(key -> true)) { + if (Thread.currentThread().isInterrupted()) { + return; + } + if (entry.value().getSnapshotCopyDestinationRegion() != null) { + copySnapshotsOf(entry.accountId(), entry.key(), now); + } + } + expireSnapshotCopies(now); + } + + private void copySnapshotsOf(String accountId, String clusterId, Instant now) { + Cluster cluster = clusters.getForAccount(accountId, clusterId).orElse(null); + if (cluster == null || cluster.getSnapshotCopyDestinationRegion() == null) { + return; + } + if (cluster.getSnapshotCopyEnabledAt() == null) { + // Enabled before the enable time was recorded: copy from now on rather than the whole history. + cluster = backfillSnapshotCopyEnabledAt(accountId, clusterId, now); + if (cluster == null) { + return; + } + } + String destination = cluster.getSnapshotCopyDestinationRegion(); + Instant enabledAt = cluster.getSnapshotCopyEnabledAt(); + List candidates = snapshots.scanForAccount(accountId, key -> true).stream() + .filter(snapshot -> clusterId.equals(snapshot.getClusterIdentifier())) + .filter(snapshot -> "available".equals(snapshot.getStatus())) + .filter(snapshot -> !snapshot.getCopiedToRegions().contains(destination)) + .filter(snapshot -> snapshot.getSnapshotCreateTime() != null + && !snapshot.getSnapshotCreateTime().isBefore(enabledAt)) + .map(Snapshot::getSnapshotIdentifier) + .toList(); + for (String snapshotId : candidates) { + try { + copySnapshotToRegion(accountId, snapshotId, cluster); + } catch (RuntimeException e) { + // Without the stack: a snapshot that cannot be copied fails again every sweep. + LOG.warnv("Could not copy Redshift snapshot {0} of account {1} to {2}; will retry: {3}", + snapshotId, accountId, destination, e.getMessage()); + LOG.debugv(e, "Copy failure of snapshot {0}", snapshotId); + } + } + } + + private Cluster backfillSnapshotCopyEnabledAt(String accountId, String clusterId, Instant now) { + return withResourceLock(accountId, "cluster", clusterId, () -> mutate(() -> { + Cluster current = clusters.getForAccount(accountId, clusterId).orElse(null); + if (current == null || current.getSnapshotCopyDestinationRegion() == null) { + return null; + } + if (current.getSnapshotCopyEnabledAt() == null) { + current.setSnapshotCopyEnabledAt(now); + clusters.putForAccount(accountId, clusterId, current); + clusters.flush(); + } + return current; + })); + } + + private void copySnapshotToRegion(String accountId, String snapshotId, Cluster cluster) { + String destination = cluster.getSnapshotCopyDestinationRegion(); + withResourceLock(accountId, "snapshot", snapshotId, () -> { + Snapshot source = snapshots.getForAccount(accountId, snapshotId).orElse(null); + if (source == null || !"available".equals(source.getStatus()) + || source.getCopiedToRegions().contains(destination)) { + return null; + } + // The candidates were chosen before the locks: copying may since have been disabled, re-enabled + // (which moves the enable time past this snapshot) or the cluster recreated. + Cluster current = clusters.getForAccount(accountId, cluster.getClusterIdentifier()).orElse(null); + if (current == null || !destination.equals(current.getSnapshotCopyDestinationRegion()) + || current.getSnapshotCopyEnabledAt() == null || source.getSnapshotCreateTime() == null + || source.getSnapshotCreateTime().isBefore(current.getSnapshotCopyEnabledAt())) { + return null; + } + String key = copyKey(destination, snapshotId); + Snapshot existing = snapshotCopies.getForAccount(accountId, key).orElse(null); + if (existing != null) { + if (Objects.equals(source.getSnapshotCreateTime(), existing.getSourceSnapshotCreateTime())) { + // A previous sweep committed this very copy and died before marking the source. + mutate(() -> markCopied(accountId, snapshotId, destination)); + } else { + // The source was deleted and recreated under the same name: the retained copy is an + // independent backup and must not be replaced. + LOG.warnv("Not copying Redshift snapshot {0} of account {1} to {2}: the destination already " + + "holds a retained copy of an earlier snapshot with this identifier", + snapshotId, accountId, destination); + } + return null; + } + Path dump; + try { + dump = copyDump(accountId, source, destination); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + Snapshot copy = buildSnapshotCopy(accountId, source, current, dump); + try { + mutate(() -> { + snapshotCopies.putAllAtomicallyForAccount(accountId, Map.of(key, copy)); + // Hybrid flushes log instead of throwing: write the copy before the source marker that + // makes later sweeps skip it, so the marker never reaches disk ahead of the copy. + snapshotCopies.flush(); + markCopied(accountId, snapshotId, destination); + snapshots.flush(); + return null; + }); + } catch (RuntimeException e) { + // The records change in memory before they are flushed, so undo them before the dump goes. + rollbackSnapshotCopy(accountId, key, source); + deleteCopyDump(accountId, dump == null ? null : dump.toString()); + throw e; + } + return null; + }); + } + + private void rollbackSnapshotCopy(String accountId, String key, Snapshot source) { + try { + mutate(() -> { + snapshotCopies.deleteAllAtomicallyForAccounts(Map.of(accountId, Set.of(key))); + snapshots.putAllAtomicallyForAccount(accountId, Map.of(source.getSnapshotIdentifier(), source)); + // The copy may already have been flushed before the failure. + snapshotCopies.flush(); + snapshots.flush(); + return null; + }); + } catch (RuntimeException rollbackFailure) { + LOG.warnv(rollbackFailure, "Could not undo the failed copy of snapshot {0} to {1}", source.getSnapshotIdentifier(), key); + } + } + + private Snapshot buildSnapshotCopy(String accountId, Snapshot source, Cluster cluster, Path dump) { + String destination = cluster.getSnapshotCopyDestinationRegion(); + Snapshot copy = new Snapshot(source); + copy.setSnapshotArn(AwsArnUtils.Arn.of("redshift", destination, accountId, + "snapshot:" + source.getClusterIdentifier() + "/" + source.getSnapshotIdentifier()).toString()); + copy.setSourceRegion(snapshotRegion(cluster)); + copy.setSourceSnapshotArn(source.getSnapshotArn()); + copy.setSourceSnapshotCreateTime(source.getSnapshotCreateTime()); + copy.setSqlDump(dump == null ? null : dump.toString()); + copy.setCopiedToRegions(new LinkedHashSet<>()); + copy.setTags(new LinkedHashMap<>()); + copy.setKmsKeyId(Optional.ofNullable(cluster.getSnapshotCopyGrantName()) + .flatMap(name -> snapshotCopyGrants.getForAccount(accountId, name)) + .map(SnapshotCopyGrant::getKmsKeyId).orElse(null)); + if ("automated".equals(source.getSnapshotType())) { + copy.setAutomatedSnapshotRetentionPeriod(cluster.getSnapshotCopyRetentionPeriod()); + } else { + copy.setManualSnapshotRetentionPeriod(cluster.getSnapshotCopyManualRetentionPeriod()); + } + return copy; + } + + /** Copies the source dump into the destination Region's directory, or returns {@code null} for a metadata-only snapshot. */ + private Path copyDump(String accountId, Snapshot source, String destination) throws IOException { + String stored = source.getSqlDump(); + if (stored == null || stored.isBlank()) { + return null; + } + Path accountDir = accountDumpDir(accountId); + Path destinationDir = accountDir.resolve("copies").resolve(destination).normalize(); + if (!destinationDir.startsWith(accountDir)) { + throw new IOException("Invalid destination Region: " + destination); + } + return SnapshotDumpCopier.copy(Paths.get(stored), accountDir, destinationDir); + } + + /** Records that the snapshot has been carried to the Region, so a deleted or expired copy stays gone. */ + private Void markCopied(String accountId, String snapshotId, String destination) { + Snapshot current = snapshots.getForAccount(accountId, snapshotId).orElse(null); + if (current != null) { + Snapshot marked = new Snapshot(current); + marked.getCopiedToRegions().add(destination); + snapshots.putAllAtomicallyForAccount(accountId, Map.of(snapshotId, marked)); + } + return null; + } + + private void expireSnapshotCopies(Instant now) { + for (AccountAwareStorageBackend.AccountEntry entry : snapshotCopies.scanAllAccountEntries(key -> true)) { + if (Thread.currentThread().isInterrupted()) { + return; + } + try { + withResourceLock(entry.accountId(), "snapshot", entry.value().getSnapshotIdentifier(), () -> mutate(() -> { + // Read again under the lock: the scanned copy may have been replaced by a newer one meanwhile. + Snapshot current = snapshotCopies.getForAccount(entry.accountId(), entry.key()).orElse(null); + if (current == null || !isSnapshotCopyExpired(entry.accountId(), entry.key(), current, now)) { + return null; + } + snapshotCopies.deleteAllAtomicallyForAccounts(Map.of(entry.accountId(), Set.of(entry.key()))); + snapshotCopies.flush(); + deleteCopyDump(entry.accountId(), current.getSqlDump()); + return null; + })); + } catch (RuntimeException e) { + LOG.warnv(e, "Could not expire Redshift snapshot copy {0} of account {1}; will retry", + entry.key(), entry.accountId()); + } + } + } + + /** + * Copied automated snapshots follow the source cluster's current copy retention, as + * ModifySnapshotCopyRetentionPeriod changes existing ones; copied manual snapshots keep the + * retention they were copied with. + */ + private boolean isSnapshotCopyExpired(String accountId, String key, Snapshot copy, Instant now) { + if (copy.getSnapshotCreateTime() == null) { + return false; + } + int retention; + if ("automated".equals(copy.getSnapshotType())) { + String region = key.substring(0, key.indexOf("::")); + // A cluster recreated under the same name has a new generation and no say over the old copies. + Integer current = clusters.getForAccount(accountId, copy.getClusterIdentifier()) + .filter(cluster -> region.equals(cluster.getSnapshotCopyDestinationRegion())) + .filter(cluster -> Objects.equals(cluster.getSnapshotGeneration(), copy.getClusterGeneration())) + .map(Cluster::getSnapshotCopyRetentionPeriod).orElse(null); + Integer stored = copy.getAutomatedSnapshotRetentionPeriod(); + retention = current != null ? current : stored != null ? stored : DEFAULT_SNAPSHOT_COPY_RETENTION_DAYS; + } else { + retention = copy.getManualSnapshotRetentionPeriod(); + } + return retention > 0 && !now.isBefore(copy.getSnapshotCreateTime().plus(retention, ChronoUnit.DAYS)); + } + + /** Deletes a copy's dump if it still lies in the account's directory; a failure is logged and the file left. */ + private void deleteCopyDump(String accountId, String stored) { + if (stored == null || stored.isBlank()) { + return; + } + Path file = Paths.get(stored).toAbsolutePath().normalize(); + if (!file.startsWith(accountDumpDir(accountId))) { + return; + } + try { + Files.deleteIfExists(file); + } catch (IOException e) { + LOG.warnv(e, "Could not delete the dump file {0} of a Redshift snapshot copy", file); + } + } + private void removeAutomatedSnapshot(String accountId, String snapshotId) { withResourceLock(accountId, "snapshot", snapshotId, () -> mutate(() -> { Snapshot current = snapshots.getForAccount(accountId, snapshotId).orElse(null); @@ -2818,9 +3109,15 @@ public class RedshiftService implements ManagedSecretRotator { } if (resourceType == null || "snapshot".equalsIgnoreCase(resourceType)) { for (Snapshot s : snapshots.scan(k -> true)) { + if (snapshotCopies.get(copyKey(regionResolver.getRegion(), s.getSnapshotIdentifier())).isPresent()) { + continue; + } addTaggedResources(result, snapshotArn(s.getClusterIdentifier(), s.getSnapshotIdentifier()), "snapshot", s.getTags(), tagKeysFilter); } + for (Snapshot s : copiesInRegion(regionResolver.getRegion())) { + addTaggedResources(result, s.getSnapshotArn(), "snapshot", s.getTags(), tagKeysFilter); + } } if (resourceType == null || "parametergroup".equalsIgnoreCase(resourceType)) { for (ClusterParameterGroup g : parameterGroups.scan(k -> true)) { @@ -2973,6 +3270,15 @@ public class RedshiftService implements ManagedSecretRotator { } case "snapshot" -> { String snapshotId = id.contains("/") ? id.substring(id.lastIndexOf('/') + 1) : id; + String copyKey = copyKey(arn.region(), snapshotId); + Snapshot copy = snapshotCopies.get(copyKey).orElse(null); + if (copy != null) { + yield new TagHandle(copy.getTags(), updated -> { + copy.setTags(updated); + snapshotCopies.put(copyKey, copy); + snapshotCopies.flush(); + }); + } Snapshot snapshot = snapshots.get(snapshotId) .orElseThrow(() -> new AwsException("ClusterSnapshotNotFound", "Snapshot " + snapshotId + " not found", 404)); yield new TagHandle(snapshot.getTags(), updated -> { diff --git a/src/main/java/io/github/hectorvent/floci/services/redshift/RedshiftSnapshotCopyScheduler.java b/src/main/java/io/github/hectorvent/floci/services/redshift/RedshiftSnapshotCopyScheduler.java new file mode 100644 index 0000000000..b7ee7721ce --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/redshift/RedshiftSnapshotCopyScheduler.java @@ -0,0 +1,22 @@ +package io.github.hectorvent.floci.services.redshift; + +import io.github.hectorvent.floci.config.EmulatorConfig; +import io.github.hectorvent.floci.core.common.SweepScheduler; +import io.github.hectorvent.floci.core.common.SweepWorker; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; + +/** Drives cross-Region snapshot copies outside AWS request threads, one sweep at a time. */ +@ApplicationScoped +public class RedshiftSnapshotCopyScheduler extends SweepScheduler { + @Inject + public RedshiftSnapshotCopyScheduler(RedshiftService service, EmulatorConfig config) { + super(worker(service, config.services().redshift())); + } + + private static SweepWorker worker(RedshiftService service, EmulatorConfig.RedshiftServiceConfig redshift) { + return new SweepWorker("redshift-snapshot-copy", + redshift.enabled() && redshift.snapshotCopyEnabled(), + redshift.snapshotCopySweepIntervalSeconds(), true, service::runSnapshotCopies); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/redshift/RedshiftSnapshotScheduler.java b/src/main/java/io/github/hectorvent/floci/services/redshift/RedshiftSnapshotScheduler.java index 852081b04c..454697e48c 100644 --- a/src/main/java/io/github/hectorvent/floci/services/redshift/RedshiftSnapshotScheduler.java +++ b/src/main/java/io/github/hectorvent/floci/services/redshift/RedshiftSnapshotScheduler.java @@ -1,56 +1,22 @@ package io.github.hectorvent.floci.services.redshift; import io.github.hectorvent.floci.config.EmulatorConfig; -import io.github.hectorvent.floci.core.common.Resettable; +import io.github.hectorvent.floci.core.common.SweepScheduler; import io.github.hectorvent.floci.core.common.SweepWorker; -import io.quarkus.runtime.ShutdownEvent; -import io.quarkus.runtime.StartupEvent; -import jakarta.annotation.Priority; import jakarta.enterprise.context.ApplicationScoped; -import jakarta.enterprise.event.Observes; import jakarta.inject.Inject; -import java.time.Instant; - /** Drives automated snapshots outside AWS request threads. */ @ApplicationScoped -public class RedshiftSnapshotScheduler implements Resettable { - private final SweepWorker worker; - +public class RedshiftSnapshotScheduler extends SweepScheduler { @Inject public RedshiftSnapshotScheduler(RedshiftService service, EmulatorConfig config) { - EmulatorConfig.RedshiftServiceConfig redshift = config.services().redshift(); - this.worker = new SweepWorker("redshift-snapshot-scheduler", + super(worker(service, config.services().redshift())); + } + + private static SweepWorker worker(RedshiftService service, EmulatorConfig.RedshiftServiceConfig redshift) { + return new SweepWorker("redshift-snapshot-scheduler", redshift.enabled() && redshift.automatedSnapshotsEnabled(), redshift.snapshotSweepIntervalSeconds(), false, service::runSnapshotSchedules); } - - void onStart(@Observes StartupEvent ignored) { - worker.start(); - } - - // Priority below APPLICATION (2000) so the worker drains before EmulatorLifecycle.onStop flushes storage. - void onStop(@Observes @Priority(1000) ShutdownEvent ignored) { - worker.stop(); - } - - public void tick(Instant now) { - worker.tick(now); - } - - /** Drains a running sweep so it cannot write old snapshots back into storage that reset is about to clear. */ - @Override - public void beforeReset() { - worker.pause(); - } - - @Override - public void clear() { - // Snapshot state lives in RedshiftService storage, which reset wipes. - } - - @Override - public void afterReset() { - worker.resume(); - } } diff --git a/src/main/java/io/github/hectorvent/floci/services/redshift/SnapshotDumpCopier.java b/src/main/java/io/github/hectorvent/floci/services/redshift/SnapshotDumpCopier.java new file mode 100644 index 0000000000..10bf9a8811 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/redshift/SnapshotDumpCopier.java @@ -0,0 +1,42 @@ +package io.github.hectorvent.floci.services.redshift; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; +import java.util.UUID; + +/** Copies a snapshot dump into another directory without ever exposing a half-written file. */ +public final class SnapshotDumpCopier { + private SnapshotDumpCopier() { + } + + /** + * Copies {@code stored}, which must be a regular file inside {@code sourceDirectory}, into + * {@code destinationDirectory} under a fresh name. Each copy gets its own file, so replacing an earlier + * copy never touches the dump it still points to; the snapshot name is left out because a 255-character + * name plus a suffix would exceed filesystem filename limits. + */ + public static Path copy(Path stored, Path sourceDirectory, Path destinationDirectory) throws IOException { + Path from = stored.toAbsolutePath().normalize(); + if (!from.startsWith(sourceDirectory) || from.equals(sourceDirectory) || !Files.isRegularFile(from)) { + throw new IOException("Snapshot dump is missing or outside its directory: " + from); + } + String fileName = UUID.randomUUID().toString(); + Path to = destinationDirectory.resolve(fileName + ".sql"); + Path staging = destinationDirectory.resolve(fileName + ".sql.copying"); + Files.createDirectories(destinationDirectory); + try { + Files.copy(from, staging, StandardCopyOption.REPLACE_EXISTING); + Files.move(staging, to, StandardCopyOption.ATOMIC_MOVE); + } catch (IOException e) { + try { + Files.deleteIfExists(staging); + } catch (IOException cleanupFailure) { + e.addSuppressed(cleanupFailure); + } + throw e; + } + return to; + } +} 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 cdca5ea596..c0b18f60cc 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 @@ -90,6 +90,8 @@ public class Cluster { private Integer snapshotCopyRetentionPeriod; private Integer snapshotCopyManualRetentionPeriod; private String snapshotCopyGrantName; + // Only snapshots taken after this instant are copied, as AWS copies from the moment copy is enabled. + private Instant snapshotCopyEnabledAt; private String snapshotScheduleIdentifier; private Instant automatedSnapshotAnchor; private String snapshotRegion; @@ -114,6 +116,8 @@ public class Cluster { public void setSnapshotCopyRetentionPeriod(Integer snapshotCopyRetentionPeriod) { this.snapshotCopyRetentionPeriod = snapshotCopyRetentionPeriod; } public Integer getSnapshotCopyManualRetentionPeriod() { return snapshotCopyManualRetentionPeriod; } public void setSnapshotCopyManualRetentionPeriod(Integer snapshotCopyManualRetentionPeriod) { this.snapshotCopyManualRetentionPeriod = snapshotCopyManualRetentionPeriod; } + public Instant getSnapshotCopyEnabledAt() { return snapshotCopyEnabledAt; } + public void setSnapshotCopyEnabledAt(Instant snapshotCopyEnabledAt) { this.snapshotCopyEnabledAt = snapshotCopyEnabledAt; } public String getSnapshotCopyGrantName() { return snapshotCopyGrantName; } public void setSnapshotCopyGrantName(String snapshotCopyGrantName) { this.snapshotCopyGrantName = snapshotCopyGrantName; } public String getSnapshotScheduleIdentifier() { return snapshotScheduleIdentifier; } diff --git a/src/main/java/io/github/hectorvent/floci/services/redshift/model/Snapshot.java b/src/main/java/io/github/hectorvent/floci/services/redshift/model/Snapshot.java index 43eca6efe0..271cc0ec16 100644 --- a/src/main/java/io/github/hectorvent/floci/services/redshift/model/Snapshot.java +++ b/src/main/java/io/github/hectorvent/floci/services/redshift/model/Snapshot.java @@ -4,7 +4,9 @@ import io.quarkus.runtime.annotations.RegisterForReflection; import java.time.Instant; import java.util.LinkedHashMap; +import java.util.LinkedHashSet; import java.util.Map; +import java.util.Set; @RegisterForReflection public class Snapshot { @@ -22,6 +24,25 @@ public class Snapshot { private Integer automatedSnapshotRetentionPeriod; private Instant scheduledTime; private String clusterGeneration; + private String sourceRegion; + private String sourceSnapshotArn; + private Instant sourceSnapshotCreateTime; + private String kmsKeyId; + private Set copiedToRegions = new LinkedHashSet<>(); + + public String getSourceRegion() { return sourceRegion; } + public void setSourceRegion(String value) { sourceRegion = value; } + public String getSourceSnapshotArn() { return sourceSnapshotArn; } + public void setSourceSnapshotArn(String value) { sourceSnapshotArn = value; } + public Instant getSourceSnapshotCreateTime() { return sourceSnapshotCreateTime; } + public void setSourceSnapshotCreateTime(Instant value) { sourceSnapshotCreateTime = value; } + public String getKmsKeyId() { return kmsKeyId; } + public void setKmsKeyId(String value) { kmsKeyId = value; } + /** Regions this snapshot has been carried to, kept so a copy that was deleted there stays gone. */ + public Set getCopiedToRegions() { return copiedToRegions; } + public void setCopiedToRegions(Set value) { + copiedToRegions = value == null ? new LinkedHashSet<>() : value; + } public String getClusterGeneration() { return clusterGeneration; } public void setClusterGeneration(String value) { clusterGeneration = value; } @@ -35,6 +56,29 @@ public class Snapshot { public Snapshot() {} + public Snapshot(Snapshot other) { + this.snapshotIdentifier = other.snapshotIdentifier; + this.clusterIdentifier = other.clusterIdentifier; + this.status = other.status; + this.port = other.port; + this.masterUsername = other.masterUsername; + this.masterPassword = other.masterPassword; + this.sqlDump = other.sqlDump; + this.snapshotArn = other.snapshotArn; + this.snapshotCreateTime = other.snapshotCreateTime; + this.manualSnapshotRetentionPeriod = other.manualSnapshotRetentionPeriod; + this.snapshotType = other.snapshotType; + this.automatedSnapshotRetentionPeriod = other.automatedSnapshotRetentionPeriod; + this.scheduledTime = other.scheduledTime; + this.clusterGeneration = other.clusterGeneration; + this.sourceRegion = other.sourceRegion; + this.sourceSnapshotArn = other.sourceSnapshotArn; + this.sourceSnapshotCreateTime = other.sourceSnapshotCreateTime; + this.kmsKeyId = other.kmsKeyId; + this.copiedToRegions = new LinkedHashSet<>(other.copiedToRegions); + this.tags = new LinkedHashMap<>(other.tags); + } + public Snapshot(String snapshotIdentifier, String clusterIdentifier, String status, int port, String masterUsername) { this.snapshotIdentifier = snapshotIdentifier; this.clusterIdentifier = clusterIdentifier; diff --git a/src/main/java/io/github/hectorvent/floci/services/redshiftserverless/RedshiftServerlessScheduledActionScheduler.java b/src/main/java/io/github/hectorvent/floci/services/redshiftserverless/RedshiftServerlessScheduledActionScheduler.java index 367d83061d..57c5d2f8d7 100644 --- a/src/main/java/io/github/hectorvent/floci/services/redshiftserverless/RedshiftServerlessScheduledActionScheduler.java +++ b/src/main/java/io/github/hectorvent/floci/services/redshiftserverless/RedshiftServerlessScheduledActionScheduler.java @@ -1,62 +1,24 @@ package io.github.hectorvent.floci.services.redshiftserverless; import io.github.hectorvent.floci.config.EmulatorConfig; -import io.github.hectorvent.floci.core.common.Resettable; +import io.github.hectorvent.floci.core.common.SweepScheduler; import io.github.hectorvent.floci.core.common.SweepWorker; -import io.quarkus.runtime.ShutdownEvent; -import io.quarkus.runtime.StartupEvent; -import jakarta.annotation.Priority; import jakarta.enterprise.context.ApplicationScoped; -import jakarta.enterprise.event.Observes; import jakarta.inject.Inject; -import java.time.Instant; - /** Drives Serverless scheduled actions outside AWS request threads, one sweep at a time. */ @ApplicationScoped -public class RedshiftServerlessScheduledActionScheduler implements Resettable { - private final SweepWorker worker; - +public class RedshiftServerlessScheduledActionScheduler extends SweepScheduler { @Inject public RedshiftServerlessScheduledActionScheduler(RedshiftServerlessScheduledActionService service, EmulatorConfig config) { - EmulatorConfig.RedshiftServerlessServiceConfig serverless = config.services().redshiftServerless(); - this.worker = new SweepWorker("redshift-serverless-scheduled-actions", + super(worker(service, config.services().redshiftServerless())); + } + + private static SweepWorker worker(RedshiftServerlessScheduledActionService service, + EmulatorConfig.RedshiftServerlessServiceConfig serverless) { + return new SweepWorker("redshift-serverless-scheduled-actions", serverless.enabled() && serverless.scheduledActionsEnabled(), serverless.scheduledActionSweepIntervalSeconds(), false, service::runScheduledActions); } - - void onStart(@Observes StartupEvent ignored) { - worker.start(); - } - - // Priority below APPLICATION (2000) so the worker drains before EmulatorLifecycle.onStop flushes storage. - void onStop(@Observes @Priority(1000) ShutdownEvent ignored) { - worker.stop(); - } - - /** Whether a background worker exists, which the two configuration switches decide. */ - boolean active() { - return worker.active(); - } - - public void tick(Instant now) { - worker.tick(now); - } - - /** Drains a running sweep so it cannot write a claim back into storage that reset is about to clear. */ - @Override - public void beforeReset() { - worker.pause(); - } - - @Override - public void clear() { - // Claims live with the actions in RedshiftServerlessScheduledActionService storage, which reset wipes. - } - - @Override - public void afterReset() { - worker.resume(); - } } diff --git a/src/main/java/io/github/hectorvent/floci/services/redshiftserverless/RedshiftServerlessService.java b/src/main/java/io/github/hectorvent/floci/services/redshiftserverless/RedshiftServerlessService.java index cd979b0af5..6e79e4a235 100644 --- a/src/main/java/io/github/hectorvent/floci/services/redshiftserverless/RedshiftServerlessService.java +++ b/src/main/java/io/github/hectorvent/floci/services/redshiftserverless/RedshiftServerlessService.java @@ -10,6 +10,7 @@ import io.github.hectorvent.floci.core.common.RegionResolver; import io.github.hectorvent.floci.core.common.Resettable; import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend; import io.github.hectorvent.floci.core.storage.StorageFactory; +import io.github.hectorvent.floci.services.redshift.SnapshotDumpCopier; import io.github.hectorvent.floci.services.redshift.TempCredential; import io.github.hectorvent.floci.services.redshiftserverless.RedshiftServerlessSnapshotCopyService.CopyRule; import io.github.hectorvent.floci.services.redshiftserverless.model.ConfigParameter; @@ -31,7 +32,6 @@ import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; -import java.nio.file.StandardCopyOption; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.ArrayList; @@ -816,29 +816,8 @@ public class RedshiftServerlessService implements Resettable { if (stored == null || stored.isBlank()) { return null; } - Path sourceDirectory = dumpDir(rule.accountId(), rule.sourceRegion()); - Path from = Paths.get(stored).toAbsolutePath().normalize(); - if (!from.startsWith(sourceDirectory) || from.equals(sourceDirectory) || !Files.isRegularFile(from)) { - throw new IOException("Snapshot dump is missing or outside its account and Region directory: " + from); - } - Path destinationDirectory = dumpDir(rule.accountId(), rule.destinationRegion()); - // Each copy gets its own file, so replacing an earlier copy never touches the dump it still points to. - // The name is left out: a 255-character snapshot name plus a suffix would exceed filesystem filename limits. - String copyFileName = UUID.randomUUID().toString(); - Path to = destinationDirectory.resolve(copyFileName + ".sql").normalize(); - Path staging = destinationDirectory.resolve(copyFileName + ".sql.copying").normalize(); - if (!to.startsWith(destinationDirectory) || !staging.startsWith(destinationDirectory)) { - throw new IOException("Invalid snapshot name: " + source.getSnapshotName()); - } - Files.createDirectories(destinationDirectory); - try { - Files.copy(from, staging, StandardCopyOption.REPLACE_EXISTING); - Files.move(staging, to, StandardCopyOption.ATOMIC_MOVE); - } catch (IOException e) { - deleteDumpQuietly(staging); - throw e; - } - return to; + return SnapshotDumpCopier.copy(Paths.get(stored), dumpDir(rule.accountId(), rule.sourceRegion()), + dumpDir(rule.accountId(), rule.destinationRegion())); } /** Records that the snapshot has been carried to the rule's Region, so a deleted or expired copy stays gone. */ diff --git a/src/main/java/io/github/hectorvent/floci/services/redshiftserverless/RedshiftServerlessSnapshotCopyScheduler.java b/src/main/java/io/github/hectorvent/floci/services/redshiftserverless/RedshiftServerlessSnapshotCopyScheduler.java index e1ac918d33..54016cead4 100644 --- a/src/main/java/io/github/hectorvent/floci/services/redshiftserverless/RedshiftServerlessSnapshotCopyScheduler.java +++ b/src/main/java/io/github/hectorvent/floci/services/redshiftserverless/RedshiftServerlessSnapshotCopyScheduler.java @@ -1,63 +1,25 @@ package io.github.hectorvent.floci.services.redshiftserverless; import io.github.hectorvent.floci.config.EmulatorConfig; -import io.github.hectorvent.floci.core.common.Resettable; +import io.github.hectorvent.floci.core.common.SweepScheduler; import io.github.hectorvent.floci.core.common.SweepWorker; -import io.quarkus.runtime.ShutdownEvent; -import io.quarkus.runtime.StartupEvent; -import jakarta.annotation.Priority; import jakarta.enterprise.context.ApplicationScoped; -import jakarta.enterprise.event.Observes; import jakarta.inject.Inject; -import java.time.Instant; - /** Drives Serverless snapshot copies outside AWS request threads, one sweep at a time. */ @ApplicationScoped -public class RedshiftServerlessSnapshotCopyScheduler implements Resettable { - private final SweepWorker worker; - +public class RedshiftServerlessSnapshotCopyScheduler extends SweepScheduler { @Inject public RedshiftServerlessSnapshotCopyScheduler(RedshiftServerlessSnapshotCopyService copies, EmulatorConfig config) { - EmulatorConfig.RedshiftServerlessServiceConfig serverless = config.services().redshiftServerless(); - this.worker = new SweepWorker("redshift-serverless-snapshot-copy", + super(worker(copies, config.services().redshiftServerless())); + } + + private static SweepWorker worker(RedshiftServerlessSnapshotCopyService copies, + EmulatorConfig.RedshiftServerlessServiceConfig serverless) { + return new SweepWorker("redshift-serverless-snapshot-copy", serverless.enabled() && serverless.snapshotCopyEnabled(), serverless.snapshotCopySweepIntervalSeconds(), true, copies::runCopySweep); } - - void onStart(@Observes StartupEvent ignored) { - worker.start(); - } - - // Priority below APPLICATION (2000) so the worker drains before EmulatorLifecycle.onStop flushes storage. - void onStop(@Observes @Priority(1000) ShutdownEvent ignored) { - worker.stop(); - } - - /** Whether a background worker exists, which the two configuration switches decide. */ - boolean active() { - return worker.active(); - } - - public void tick(Instant now) { - worker.tick(now); - } - - /** Drains a running sweep so it cannot write a copy back into storage that reset is about to clear. */ - @Override - public void beforeReset() { - worker.pause(); - } - - @Override - public void clear() { - // Copies live in RedshiftServerlessService storage, which reset wipes. - } - - @Override - public void afterReset() { - worker.resume(); - } } diff --git a/src/main/java/io/github/hectorvent/floci/services/redshiftserverless/RedshiftServerlessSnapshotExpirationScheduler.java b/src/main/java/io/github/hectorvent/floci/services/redshiftserverless/RedshiftServerlessSnapshotExpirationScheduler.java index 0f90b10202..79fdf94e90 100644 --- a/src/main/java/io/github/hectorvent/floci/services/redshiftserverless/RedshiftServerlessSnapshotExpirationScheduler.java +++ b/src/main/java/io/github/hectorvent/floci/services/redshiftserverless/RedshiftServerlessSnapshotExpirationScheduler.java @@ -1,64 +1,27 @@ package io.github.hectorvent.floci.services.redshiftserverless; import io.github.hectorvent.floci.config.EmulatorConfig; -import io.github.hectorvent.floci.core.common.Resettable; +import io.github.hectorvent.floci.core.common.SweepScheduler; import io.github.hectorvent.floci.core.common.SweepWorker; -import io.quarkus.runtime.ShutdownEvent; -import io.quarkus.runtime.StartupEvent; -import jakarta.annotation.Priority; import jakarta.enterprise.context.ApplicationScoped; -import jakarta.enterprise.event.Observes; import jakarta.inject.Inject; -import java.time.Instant; - /** Drives Serverless snapshot expirations outside AWS request threads, one sweep at a time. */ @ApplicationScoped -public class RedshiftServerlessSnapshotExpirationScheduler implements Resettable { - private final SweepWorker worker; - +public class RedshiftServerlessSnapshotExpirationScheduler extends SweepScheduler { @Inject public RedshiftServerlessSnapshotExpirationScheduler(RedshiftServerlessService service, RedshiftServerlessResourcePolicyService policies, EmulatorConfig config) { - EmulatorConfig.RedshiftServerlessServiceConfig serverless = config.services().redshiftServerless(); - this.worker = new SweepWorker("redshift-serverless-snapshot-expiration", + super(worker(service, policies, config.services().redshiftServerless())); + } + + private static SweepWorker worker(RedshiftServerlessService service, + RedshiftServerlessResourcePolicyService policies, + EmulatorConfig.RedshiftServerlessServiceConfig serverless) { + return new SweepWorker("redshift-serverless-snapshot-expiration", serverless.enabled() && serverless.snapshotExpirationEnabled(), serverless.snapshotExpirationSweepIntervalSeconds(), true, now -> service.expireSnapshots(now, policies::deleteExpiredSnapshotPolicy)); } - - void onStart(@Observes StartupEvent ignored) { - worker.start(); - } - - // Priority below APPLICATION (2000) so the worker drains before EmulatorLifecycle.onStop flushes storage. - void onStop(@Observes @Priority(1000) ShutdownEvent ignored) { - worker.stop(); - } - - /** Whether a background worker exists, which the two configuration switches decide. */ - boolean active() { - return worker.active(); - } - - public void tick(Instant now) { - worker.tick(now); - } - - /** Drains a running sweep so it cannot write a snapshot back into storage that reset is about to clear. */ - @Override - public void beforeReset() { - worker.pause(); - } - - @Override - public void clear() { - // Snapshot state lives in RedshiftServerlessService storage, which reset wipes. - } - - @Override - public void afterReset() { - worker.resume(); - } } diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index 34ca868b9c..1e816665b2 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -536,6 +536,8 @@ floci: automated-snapshots-enabled: true cloudwatch-metrics-enabled: true snapshot-sweep-interval-seconds: 60 + snapshot-copy-enabled: true + snapshot-copy-sweep-interval-seconds: 60 default-port: 5439 image-version: postgres:15-alpine poll-interval-ms: 1000 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 7a6db3e2d1..84c859ae89 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 @@ -851,6 +851,7 @@ class RedshiftServiceTest { private AccountAwareStorageBackend parameterGroupBackend; private AccountAwareStorageBackend subnetGroupBackend; private AccountAwareStorageBackend snapshotCopyGrantBackend; + private AccountAwareStorageBackend snapshotCopyBackend; private AccountAwareStorageBackend snapshotScheduleBackend; private AccountAwareStorageBackend integrationBackend; private RedshiftContainerManager cm; @@ -874,6 +875,7 @@ class RedshiftServiceTest { parameterGroupBackend = mock(AccountAwareStorageBackend.class); subnetGroupBackend = mock(AccountAwareStorageBackend.class); snapshotCopyGrantBackend = mock(AccountAwareStorageBackend.class); + snapshotCopyBackend = mock(AccountAwareStorageBackend.class); snapshotScheduleBackend = mock(AccountAwareStorageBackend.class); integrationBackend = mock(AccountAwareStorageBackend.class); cm = mock(RedshiftContainerManager.class); @@ -905,6 +907,7 @@ class RedshiftServiceTest { when(sf.create(eq("redshift"), eq("redshift-parameter-groups.json"), any())).thenReturn(parameterGroupBackend); when(sf.create(eq("redshift"), eq("redshift-subnet-groups.json"), any())).thenReturn(subnetGroupBackend); when(sf.create(eq("redshift"), eq("redshift-snapshot-copy-grants.json"), any())).thenReturn(snapshotCopyGrantBackend); + when(sf.create(eq("redshift"), eq("redshift-snapshot-copies.json"), any())).thenReturn(snapshotCopyBackend); when(sf.create(eq("redshift"), eq("redshift-integrations.json"), any())).thenReturn(integrationBackend); when(sf.create(eq("redshift"), eq("redshift-snapshot-schedules.json"), any())).thenReturn(snapshotScheduleBackend); when(clusterBackend.accountId()).thenReturn("111111111111"); diff --git a/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftSnapshotCopyServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftSnapshotCopyServiceTest.java new file mode 100644 index 0000000000..5b1a314aa3 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftSnapshotCopyServiceTest.java @@ -0,0 +1,350 @@ +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.RegionResolver; +import io.github.hectorvent.floci.core.common.ServiceConfigAccess; +import io.github.hectorvent.floci.core.common.docker.DockerHostResolver; +import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend; +import io.github.hectorvent.floci.core.storage.StorageFactory; +import io.github.hectorvent.floci.services.redshift.container.RedshiftContainerManager; +import io.github.hectorvent.floci.services.redshift.model.Cluster; +import io.github.hectorvent.floci.services.redshift.model.Snapshot; +import io.github.hectorvent.floci.services.redshift.proxy.RedshiftProxyManager; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.Duration; +import java.time.Instant; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Stream; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.*; + +class RedshiftSnapshotCopyServiceTest { + private static final String ACCOUNT = "111111111111"; + private static final String SOURCE = "us-east-1"; + private static final String DESTINATION = "us-west-2"; + + @TempDir + Path directory; + + @Test + void copiesAnAvailableSnapshotIntoTheDestinationRegionOnce() throws Exception { + Fixture fixture = fixture(); + seedCluster(fixture, "warehouse", Instant.now().minusSeconds(60)); + fixture.service(SOURCE).createSnapshot("nightly", "warehouse"); + + fixture.service(SOURCE).runSnapshotCopies(Instant.now()); + fixture.service(SOURCE).runSnapshotCopies(Instant.now()); + + Snapshot source = fixture.snapshots().getForAccount(ACCOUNT, "nightly").orElseThrow(); + assertTrue(source.getCopiedToRegions().contains(DESTINATION)); + Snapshot copy = fixture.copies().getForAccount(ACCOUNT, DESTINATION + "::nightly").orElseThrow(); + assertEquals("arn:aws:redshift:" + DESTINATION + ":" + ACCOUNT + ":snapshot:warehouse/nightly", + copy.getSnapshotArn()); + assertEquals(SOURCE, copy.getSourceRegion()); + assertEquals(source.getSnapshotArn(), copy.getSourceSnapshotArn()); + assertEquals("backup contents", Files.readString(Path.of(copy.getSqlDump()))); + assertNotEquals(source.getSqlDump(), copy.getSqlDump()); + assertEquals(1, dumpFilesUnderCopies()); + } + + @Test + void copyIsVisibleAndRestorableOnlyThroughTheDestinationRegion() { + Fixture fixture = fixture(); + seedCluster(fixture, "warehouse", Instant.now().minusSeconds(60)); + fixture.service(SOURCE).createSnapshot("nightly", "warehouse"); + fixture.service(SOURCE).runSnapshotCopies(Instant.now()); + + Snapshot atDestination = fixture.service(DESTINATION).describeSnapshots("nightly", null).getFirst(); + Snapshot atSource = fixture.service(SOURCE).describeSnapshots("nightly", null).getFirst(); + + assertTrue(atDestination.getSnapshotArn().contains(":" + DESTINATION + ":")); + assertTrue(atSource.getSnapshotArn().contains(":" + SOURCE + ":")); + assertEquals(1, fixture.service(DESTINATION).describeSnapshots(null, "warehouse").size()); + assertEquals(atDestination.getSqlDump(), fixture.service(DESTINATION).getSnapshot("nightly") + .orElseThrow().getSqlDump()); + } + + @Test + void snapshotsTakenBeforeCopyWasEnabledStayWhereTheyAre() { + Fixture fixture = fixture(); + seedCluster(fixture, "warehouse", Instant.now().plusSeconds(3600)); + fixture.service(SOURCE).createSnapshot("old", "warehouse"); + + fixture.service(SOURCE).runSnapshotCopies(Instant.now()); + + assertTrue(fixture.copies().scanForAccount(ACCOUNT, key -> true).isEmpty()); + } + + @Test + void aCopyDeletedAtTheDestinationIsNotCopiedAgain() { + Fixture fixture = fixture(); + seedCluster(fixture, "warehouse", Instant.now().minusSeconds(60)); + fixture.service(SOURCE).createSnapshot("nightly", "warehouse"); + fixture.service(SOURCE).runSnapshotCopies(Instant.now()); + Path copiedDump = Path.of(fixture.copies().getForAccount(ACCOUNT, DESTINATION + "::nightly") + .orElseThrow().getSqlDump()); + + fixture.service(DESTINATION).deleteSnapshot("nightly"); + fixture.service(SOURCE).runSnapshotCopies(Instant.now()); + + assertTrue(fixture.copies().scanForAccount(ACCOUNT, key -> true).isEmpty()); + assertFalse(Files.exists(copiedDump)); + assertTrue(fixture.snapshots().getForAccount(ACCOUNT, "nightly").isPresent()); + } + + @Test + void deletingTheSourceLeavesTheCopyInPlace() { + Fixture fixture = fixture(); + seedCluster(fixture, "warehouse", Instant.now().minusSeconds(60)); + fixture.service(SOURCE).createSnapshot("nightly", "warehouse"); + fixture.service(SOURCE).runSnapshotCopies(Instant.now()); + + fixture.service(SOURCE).deleteSnapshot("nightly"); + + assertTrue(fixture.copies().getForAccount(ACCOUNT, DESTINATION + "::nightly").isPresent()); + assertEquals("nightly", fixture.service(DESTINATION).describeSnapshots("nightly", null) + .getFirst().getSnapshotIdentifier()); + assertThrows(AwsException.class, () -> fixture.service(SOURCE).describeSnapshots("nightly", null)); + } + + @Test + void copiedManualSnapshotsExpireAfterTheCopyRetentionAndLeaveTheSourceAlone() { + Fixture fixture = fixture(); + Cluster cluster = seedCluster(fixture, "warehouse", Instant.now().minusSeconds(60)); + cluster.setSnapshotCopyManualRetentionPeriod(1); + fixture.clusters().putForAccount(ACCOUNT, "warehouse", cluster); + fixture.service(SOURCE).createSnapshot("nightly", "warehouse"); + fixture.service(SOURCE).runSnapshotCopies(Instant.now()); + Path copiedDump = Path.of(fixture.copies().getForAccount(ACCOUNT, DESTINATION + "::nightly") + .orElseThrow().getSqlDump()); + + fixture.service(SOURCE).runSnapshotCopies(Instant.now().plus(Duration.ofHours(12))); + assertTrue(fixture.copies().getForAccount(ACCOUNT, DESTINATION + "::nightly").isPresent()); + + fixture.service(SOURCE).runSnapshotCopies(Instant.now().plus(Duration.ofDays(2))); + assertTrue(fixture.copies().getForAccount(ACCOUNT, DESTINATION + "::nightly").isEmpty()); + assertFalse(Files.exists(copiedDump)); + assertTrue(fixture.snapshots().getForAccount(ACCOUNT, "nightly").isPresent()); + assertTrue(Files.exists(Path.of(fixture.snapshots().getForAccount(ACCOUNT, "nightly") + .orElseThrow().getSqlDump()))); + } + + @Test + void aSnapshotWhoseDumpIsMissingIsLeftUncopiedAndRetried() throws IOException { + Fixture fixture = fixture(); + seedCluster(fixture, "warehouse", Instant.now().minusSeconds(60)); + Snapshot snapshot = fixture.service(SOURCE).createSnapshot("nightly", "warehouse"); + Files.delete(Path.of(snapshot.getSqlDump())); + + fixture.service(SOURCE).runSnapshotCopies(Instant.now()); + + assertTrue(fixture.copies().scanForAccount(ACCOUNT, key -> true).isEmpty()); + assertTrue(fixture.snapshots().getForAccount(ACCOUNT, "nightly").orElseThrow() + .getCopiedToRegions().isEmpty()); + } + + @Test + void aCopyCommittedBeforeTheSourceWasMarkedIsNotCopiedTwice() { + Fixture fixture = fixture(); + seedCluster(fixture, "warehouse", Instant.now().minusSeconds(60)); + fixture.service(SOURCE).createSnapshot("nightly", "warehouse"); + fixture.service(SOURCE).runSnapshotCopies(Instant.now()); + Snapshot source = fixture.snapshots().getForAccount(ACCOUNT, "nightly").orElseThrow(); + Snapshot unmarked = new Snapshot(source); + unmarked.getCopiedToRegions().clear(); + fixture.snapshots().putForAccount(ACCOUNT, "nightly", unmarked); + String committedDump = fixture.copies().getForAccount(ACCOUNT, DESTINATION + "::nightly") + .orElseThrow().getSqlDump(); + + fixture.service(SOURCE).runSnapshotCopies(Instant.now()); + + assertEquals(committedDump, fixture.copies().getForAccount(ACCOUNT, DESTINATION + "::nightly") + .orElseThrow().getSqlDump()); + assertTrue(fixture.snapshots().getForAccount(ACCOUNT, "nightly").orElseThrow() + .getCopiedToRegions().contains(DESTINATION)); + assertEquals(1, dumpFilesUnderCopies()); + } + + @Test + void copiesKeepAccountsSeparate() { + Fixture fixture = fixture(); + seedCluster(fixture, "warehouse", Instant.now().minusSeconds(60)); + fixture.service(SOURCE).createSnapshot("nightly", "warehouse"); + + fixture.service(SOURCE).runSnapshotCopies(Instant.now()); + + assertTrue(fixture.copies().scanForAccount("222222222222", key -> true).isEmpty()); + assertTrue(Path.of(fixture.copies().getForAccount(ACCOUNT, DESTINATION + "::nightly").orElseThrow() + .getSqlDump()).startsWith(directory.resolve("redshift-dumps").resolve(ACCOUNT))); + } + + @Test + void enablingCopyIntoTheClustersOwnRegionIsRefused() { + Fixture fixture = fixture(); + Cluster cluster = seedCluster(fixture, "warehouse", null); + cluster.setSnapshotCopyDestinationRegion(null); + fixture.clusters().putForAccount(ACCOUNT, "warehouse", cluster); + + AwsException refused = assertThrows(AwsException.class, + () -> fixture.service(SOURCE).enableSnapshotCopy("warehouse", SOURCE, null, null, null)); + assertEquals("UnknownSnapshotCopyRegionFault", refused.getErrorCode()); + + Cluster enabled = fixture.service(SOURCE).enableSnapshotCopy("warehouse", DESTINATION, null, null, null); + assertNotNull(enabled.getSnapshotCopyEnabledAt()); + } + + @Test + void aNewSnapshotCannotTakeTheIdentifierOfACopyInThatRegion() { + Fixture fixture = fixture(); + seedCluster(fixture, "warehouse", Instant.now().minusSeconds(60)); + fixture.service(SOURCE).createSnapshot("nightly", "warehouse"); + fixture.service(SOURCE).runSnapshotCopies(Instant.now()); + fixture.service(SOURCE).deleteSnapshot("nightly"); + + AwsException refused = assertThrows(AwsException.class, + () -> fixture.service(DESTINATION).createSnapshot("nightly", "warehouse")); + assertEquals("ClusterSnapshotAlreadyExists", refused.getErrorCode()); + } + + @Test + void aRecreatedSourceDoesNotReplaceTheRetainedCopyOfAnEarlierSnapshot() throws Exception { + Fixture fixture = fixture(); + seedCluster(fixture, "warehouse", Instant.now().minusSeconds(60)); + fixture.service(SOURCE).createSnapshot("nightly", "warehouse"); + fixture.service(SOURCE).runSnapshotCopies(Instant.now()); + String key = DESTINATION + "::nightly"; + Snapshot retained = new Snapshot(fixture.copies().getForAccount(ACCOUNT, key).orElseThrow()); + retained.setSourceSnapshotCreateTime(retained.getSourceSnapshotCreateTime().minusSeconds(30)); + retained.setTags(new LinkedHashMap<>(Map.of("env", "prod"))); + fixture.copies().putForAccount(ACCOUNT, key, retained); + fixture.service(SOURCE).deleteSnapshot("nightly"); + fixture.service(SOURCE).createSnapshot("nightly", "warehouse"); + + fixture.service(SOURCE).runSnapshotCopies(Instant.now()); + + Snapshot kept = fixture.copies().getForAccount(ACCOUNT, key).orElseThrow(); + assertEquals(retained.getSqlDump(), kept.getSqlDump()); + assertEquals(Map.of("env", "prod"), kept.getTags()); + assertTrue(Files.exists(Path.of(kept.getSqlDump()))); + assertEquals(1, dumpFilesUnderCopies()); + assertTrue(fixture.snapshots().getForAccount(ACCOUNT, "nightly").orElseThrow() + .getCopiedToRegions().isEmpty()); + } + + @Test + void aCopyOfARemovedClusterKeepsItsOwnRetentionWhenTheNameIsReused() { + Fixture fixture = fixture(); + Cluster cluster = seedCluster(fixture, "warehouse", Instant.now().minusSeconds(60)); + cluster.setSnapshotGeneration("gen-1"); + fixture.clusters().putForAccount(ACCOUNT, "warehouse", cluster); + fixture.service(SOURCE).createSnapshot("nightly", "warehouse"); + fixture.service(SOURCE).runSnapshotCopies(Instant.now()); + String key = DESTINATION + "::nightly"; + Snapshot copy = new Snapshot(fixture.copies().getForAccount(ACCOUNT, key).orElseThrow()); + copy.setSnapshotType("automated"); + copy.setSnapshotCreateTime(Instant.now().minus(Duration.ofDays(3))); + copy.setAutomatedSnapshotRetentionPeriod(7); + fixture.copies().putForAccount(ACCOUNT, key, copy); + cluster.setSnapshotGeneration("gen-2"); + cluster.setSnapshotCopyRetentionPeriod(1); + fixture.clusters().putForAccount(ACCOUNT, "warehouse", cluster); + + fixture.service(SOURCE).runSnapshotCopies(Instant.now()); + assertTrue(fixture.copies().getForAccount(ACCOUNT, key).isPresent()); + + cluster.setSnapshotGeneration("gen-1"); + fixture.clusters().putForAccount(ACCOUNT, "warehouse", cluster); + fixture.service(SOURCE).runSnapshotCopies(Instant.now()); + assertTrue(fixture.copies().getForAccount(ACCOUNT, key).isEmpty()); + } + + @Test + void describeTagsListsOnlyTheCopyTagsForASnapshotItShadows() { + Fixture fixture = fixture(); + seedCluster(fixture, "warehouse", Instant.now().minusSeconds(60)); + fixture.service(SOURCE).createSnapshot("nightly", "warehouse"); + String sourceArn = "arn:aws:redshift:" + SOURCE + ":" + ACCOUNT + ":snapshot:warehouse/nightly"; + String copyArn = "arn:aws:redshift:" + DESTINATION + ":" + ACCOUNT + ":snapshot:warehouse/nightly"; + fixture.service(SOURCE).createTags(sourceArn, Map.of("env", "prod")); + fixture.service(SOURCE).runSnapshotCopies(Instant.now()); + fixture.service(DESTINATION).createTags(copyArn, Map.of("env", "test")); + + List tags = fixture.service(DESTINATION) + .describeTags(null, "snapshot", null); + + assertEquals(List.of(new RedshiftService.TaggedResource(copyArn, "snapshot", "env", "test")), tags); + } + + private long dumpFilesUnderCopies() { + Path root = directory.resolve("redshift-dumps").resolve(ACCOUNT).resolve("copies"); + if (!Files.isDirectory(root)) { + return 0; + } + try (Stream files = Files.walk(root)) { + return files.filter(Files::isRegularFile).count(); + } catch (IOException e) { + throw new AssertionError(e); + } + } + + private Fixture fixture() { + EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS); + when(config.storage().persistentPath()).thenReturn(directory.toString()); + when(config.defaultAccountId()).thenReturn(ACCOUNT); + ServiceConfigAccess access = mock(ServiceConfigAccess.class); + when(access.storageMode("redshift")).thenReturn("persistent"); + StorageFactory factory = new StorageFactory(config, access); + RedshiftContainerManager manager = mock(RedshiftContainerManager.class); + try { + doAnswer(invocation -> { + Files.createDirectories(invocation.getArgument(3, Path.class).getParent()); + Files.writeString(invocation.getArgument(3, Path.class), "backup contents"); + return null; + }).when(manager).takeSnapshot(anyString(), anyString(), anyString(), any(Path.class)); + } catch (Exception e) { + throw new AssertionError(e); + } + return new Fixture(factory, config, manager, + factory.create("redshift", "redshift-clusters.json", new TypeReference>() { }), + factory.create("redshift", "redshift-snapshots.json", new TypeReference>() { }), + factory.create("redshift", "redshift-snapshot-copies.json", new TypeReference>() { })); + } + + private static Cluster seedCluster(Fixture fixture, String id, Instant copyEnabledAt) { + Cluster cluster = new Cluster(); + cluster.setClusterIdentifier(id); + cluster.setNodeType("dc2.large"); + cluster.setMasterUsername("admin"); + cluster.setMasterPassword("Secret123!"); + cluster.setClusterStatus("available"); + cluster.setSnapshotRegion(SOURCE); + cluster.setSnapshotCopyDestinationRegion(DESTINATION); + cluster.setSnapshotCopyRetentionPeriod(7); + cluster.setSnapshotCopyManualRetentionPeriod(-1); + cluster.setSnapshotCopyEnabledAt(copyEnabledAt); + fixture.clusters().putForAccount(ACCOUNT, id, cluster); + return cluster; + } + + private record Fixture(StorageFactory factory, EmulatorConfig config, RedshiftContainerManager manager, + AccountAwareStorageBackend clusters, + AccountAwareStorageBackend snapshots, + AccountAwareStorageBackend copies) { + /** A service resolving every request to the given Region, over the same storage. */ + RedshiftService service(String region) { + return new RedshiftService(factory, manager, config, new RegionResolver(region, ACCOUNT), + mock(RedshiftProxyManager.class), mock(DockerHostResolver.class), new RedshiftCredentialBroker()); + } + } +} diff --git a/src/test/java/io/github/hectorvent/floci/testutil/ShutdownOrdering.java b/src/test/java/io/github/hectorvent/floci/testutil/ShutdownOrdering.java index f05b0de061..bfaf399bac 100644 --- a/src/test/java/io/github/hectorvent/floci/testutil/ShutdownOrdering.java +++ b/src/test/java/io/github/hectorvent/floci/testutil/ShutdownOrdering.java @@ -15,9 +15,9 @@ public final class ShutdownOrdering { private ShutdownOrdering() { } - /** The class's {@code onStop(ShutdownEvent)} observer must carry a priority below APPLICATION. */ + /** The class's {@code onStop(ShutdownEvent)} observer, declared or inherited, must carry a priority below APPLICATION. */ public static void assertStopsBeforeStorageCloses(Class owner) throws NoSuchMethodException { - Method onStop = owner.getDeclaredMethod("onStop", ShutdownEvent.class); + Method onStop = findOnStop(owner); Annotation priority = Arrays.stream(onStop.getParameterAnnotations()[0]) .filter(Priority.class::isInstance) .findFirst() @@ -25,4 +25,15 @@ public final class ShutdownOrdering { assertTrue(((Priority) priority).value() < Interceptor.Priority.APPLICATION, owner.getSimpleName() + ".onStop must run before EmulatorLifecycle.onStop"); } + + private static Method findOnStop(Class owner) throws NoSuchMethodException { + for (Class type = owner; type != null; type = type.getSuperclass()) { + try { + return type.getDeclaredMethod("onStop", ShutdownEvent.class); + } catch (NoSuchMethodException ignored) { + // Not declared here: an observer shared through a base class sits further up. + } + } + throw new NoSuchMethodException(owner.getName() + ".onStop(ShutdownEvent)"); + } } diff --git a/src/test/resources/application.yml b/src/test/resources/application.yml index 5558e6e00e..79fd9ba177 100644 --- a/src/test/resources/application.yml +++ b/src/test/resources/application.yml @@ -214,6 +214,8 @@ floci: automated-snapshots-enabled: false cloudwatch-metrics-enabled: true snapshot-sweep-interval-seconds: 60 + snapshot-copy-enabled: false + snapshot-copy-sweep-interval-seconds: 60 default-port: 5439 image-version: postgres:15-alpine poll-interval-ms: 1000