feat(rds): add the snapshot export task API (#5787)

* feat(rds): add StartExportTask, DescribeExportTasks and CancelExportTask with the export task lifecycle

* docs(rds): document the snapshot export task API

* fix(rds): route the export task actions to RDS when a request has no signing scope

* fix(rds): refuse an export to a bucket outside the snapshot's region

* fix(rds): answer export task calls with a copy of the task taken under the lock

* fix(rds): refuse an unknown DescribeExportTasks filter name before matching any task

* fix(rds): fail an export to a bucket in another region as a task, as RDS does, rather than refuse it

* docs(rds): say that a bucket in another region fails an export in mock mode too
This commit is contained in:
Simon Claessens authored and GitHub committed 2026-10-16 12:03:50 -04:00
1 parent dfeb05a400
commit 772ec8d0c9
15 files changed
+1724 -5

No files matched your search

@@ -578,7 +578,8 @@ public class AwsQueryController {
"ModifyDBClusterParameterGroup", "DeleteDBClusterParameterGroup",
"DescribeDBClusterParameters",
"CreateOptionGroup", "DescribeOptionGroups", "ModifyOptionGroup", "DeleteOptionGroup",
"DescribeDBSnapshots", "DescribeDBClusterSnapshots"
"DescribeDBSnapshots", "DescribeDBClusterSnapshots",
"StartExportTask", "DescribeExportTasks", "CancelExportTask"
);
private static final Set<String> CLOUDFORMATION_ACTIONS = Set.of(
@@ -8,6 +8,7 @@ import io.github.hectorvent.floci.core.common.AwsQueryResponse;
import io.github.hectorvent.floci.core.common.XmlBuilder;
import io.github.hectorvent.floci.services.docdb.DocDbQueryHandler;
import io.github.hectorvent.floci.services.neptune.NeptuneQueryHandler;
import io.github.hectorvent.floci.services.rds.export.RdsExportTaskService;
import io.github.hectorvent.floci.services.rds.model.DatabaseEngine;
import io.github.hectorvent.floci.services.rds.model.DbCluster;
import io.github.hectorvent.floci.services.rds.model.DbClusterEndpoint;
@@ -27,6 +28,7 @@ import io.github.hectorvent.floci.services.rds.model.DbRoleAssociation;
import io.github.hectorvent.floci.services.rds.model.DbSnapshot;
import io.github.hectorvent.floci.services.rds.model.DbSubnetGroup;
import io.github.hectorvent.floci.services.rds.model.EventSubscription;
import io.github.hectorvent.floci.services.rds.model.ExportTask;
import io.github.hectorvent.floci.services.rds.model.GlobalCluster;
import io.github.hectorvent.floci.services.rds.model.GlobalClusterMember;
import io.github.hectorvent.floci.services.rds.model.LogExportChanges;
@@ -62,13 +64,15 @@ public class RdsQueryHandler {
private static final Logger LOG = Logger.getLogger(RdsQueryHandler.class);
private final RdsService service;
private final RdsExportTaskService exportTaskService;
private final DocDbQueryHandler docDbQueryHandler;
private final NeptuneQueryHandler neptuneQueryHandler;
private final EmulatorConfig config;
@Inject
public RdsQueryHandler(RdsService service, EmulatorConfig config, DocDbQueryHandler docDbQueryHandler,
NeptuneQueryHandler neptuneQueryHandler) {
public RdsQueryHandler(RdsService service, RdsExportTaskService exportTaskService, EmulatorConfig config,
DocDbQueryHandler docDbQueryHandler, NeptuneQueryHandler neptuneQueryHandler) {
this.exportTaskService = exportTaskService;
this.docDbQueryHandler = docDbQueryHandler;
this.neptuneQueryHandler = neptuneQueryHandler;
this.service = service;
@@ -178,6 +182,9 @@ public class RdsQueryHandler {
case "RestoreDBClusterToPointInTime" -> handleRestoreDbClusterToPointInTime(params, region);
case "DescribeDBClusterSnapshotAttributes" -> handleDescribeDbClusterSnapshotAttributes(params, region);
case "ModifyDBClusterSnapshotAttribute" -> handleModifyDbClusterSnapshotAttribute(params, region);
case "StartExportTask" -> handleStartExportTask(params, region);
case "DescribeExportTasks" -> handleDescribeExportTasks(params, region);
case "CancelExportTask" -> handleCancelExportTask(params, region);
case "DescribeGlobalClusters" -> handleDescribeGlobalClusters(params);
case "CreateGlobalCluster" -> handleCreateGlobalCluster(params, region);
case "ModifyGlobalCluster" -> handleModifyGlobalCluster(params);
@@ -1983,6 +1990,94 @@ public class RdsQueryHandler {
}
}
private Response handleStartExportTask(MultivaluedMap<String, String> params, String region) {
String exportTaskIdentifier = params.getFirst("ExportTaskIdentifier");
String sourceArn = params.getFirst("SourceArn");
String s3BucketName = params.getFirst("S3BucketName");
String iamRoleArn = params.getFirst("IamRoleArn");
String kmsKeyId = params.getFirst("KmsKeyId");
Response missing = firstMissingParam(
"ExportTaskIdentifier", exportTaskIdentifier,
"SourceArn", sourceArn,
"S3BucketName", s3BucketName,
"IamRoleArn", iamRoleArn,
"KmsKeyId", kmsKeyId);
if (missing != null) {
return missing;
}
ExportTask task = exportTaskService.startExportTask(exportTaskIdentifier, sourceArn, s3BucketName,
params.getFirst("S3Prefix"), iamRoleArn, kmsKeyId, memberList(params, "ExportOnly"), region);
return Response.ok(AwsQueryResponse.envelope("StartExportTask", AwsNamespaces.RDS, exportTaskXml(task)))
.build();
}
private Response handleDescribeExportTasks(MultivaluedMap<String, String> params, String region) {
String sourceType = params.getFirst("SourceType");
if (sourceType != null && !List.of("SNAPSHOT", "CLUSTER").contains(sourceType)) {
throw new AwsException("InvalidParameterValue", "SourceType must be SNAPSHOT or CLUSTER.", 400);
}
Integer maxRecords = parseOptionalInt(params.getFirst("MaxRecords"));
if (maxRecords != null && (maxRecords < 20 || maxRecords > 100)) {
throw new AwsException("InvalidParameterValue", "MaxRecords must be between 20 and 100.", 400);
}
Map<String, List<String>> filters = new LinkedHashMap<>();
for (int i = 1; params.getFirst("Filters.Filter." + i + ".Name") != null; i++) {
String name = params.getFirst("Filters.Filter." + i + ".Name");
filters.put(name, extractRdsFilterValues(params, name));
}
List<ExportTask> all = exportTaskService.describeExportTasks(params.getFirst("ExportTaskIdentifier"),
params.getFirst("SourceArn"), sourceType, filters, region);
int from = Math.min(parseMarker(params.getFirst("Marker")), all.size());
int to = Math.min(from + (maxRecords != null ? maxRecords : 100), all.size());
XmlBuilder xml = new XmlBuilder().start("ExportTasks");
for (ExportTask task : all.subList(from, to)) {
xml.start("ExportTask").raw(exportTaskXml(task)).end("ExportTask");
}
xml.end("ExportTasks");
if (to < all.size()) {
xml.elem("Marker", String.valueOf(to));
}
return Response.ok(AwsQueryResponse.envelope("DescribeExportTasks", AwsNamespaces.RDS, xml.build())).build();
}
private Response handleCancelExportTask(MultivaluedMap<String, String> params, String region) {
String exportTaskIdentifier = params.getFirst("ExportTaskIdentifier");
Response missing = firstMissingParam("ExportTaskIdentifier", exportTaskIdentifier);
if (missing != null) {
return missing;
}
ExportTask task = exportTaskService.cancelExportTask(exportTaskIdentifier, region);
return Response.ok(AwsQueryResponse.envelope("CancelExportTask", AwsNamespaces.RDS, exportTaskXml(task)))
.build();
}
static String exportTaskXml(ExportTask task) {
XmlBuilder xml = new XmlBuilder()
.elem("ExportTaskIdentifier", task.getExportTaskIdentifier())
.elem("SourceArn", task.getSourceArn())
.elem("SourceType", task.getSourceType());
if (!task.getExportOnly().isEmpty()) {
xml.start("ExportOnly");
for (String entry : task.getExportOnly()) {
xml.elem("member", entry);
}
xml.end("ExportOnly");
}
xml.elem("SnapshotTime", task.getSnapshotTime() != null ? task.getSnapshotTime().toString() : null)
.elem("TaskStartTime", task.getTaskStartTime() != null ? task.getTaskStartTime().toString() : null)
.elem("TaskEndTime", task.getTaskEndTime() != null ? task.getTaskEndTime().toString() : null)
.elem("S3Bucket", task.getS3Bucket())
.elem("S3Prefix", task.getS3Prefix())
.elem("IamRoleArn", task.getIamRoleArn())
.elem("KmsKeyId", task.getKmsKeyId())
.elem("Status", task.getStatus())
.elem("PercentProgress", task.getPercentProgress())
.elem("TotalExtractedDataInGB", task.getTotalExtractedDataInGb())
.elem("FailureCause", task.getFailureCause())
.elem("WarningMessage", task.getWarningMessage());
return xml.build();
}
private Response handleDescribeDbSnapshots(MultivaluedMap<String, String> params, String region) {
String snapshotId = params.getFirst("DBSnapshotIdentifier");
String instanceId = params.getFirst("DBInstanceIdentifier");
@@ -34,6 +34,7 @@ import io.github.hectorvent.floci.services.kms.model.KmsKey;
import io.github.hectorvent.floci.services.rds.container.AutoPauseListener;
import io.github.hectorvent.floci.services.rds.container.RdsContainerHandle;
import io.github.hectorvent.floci.services.rds.container.RdsContainerManager;
import io.github.hectorvent.floci.services.rds.export.SnapshotExportSource;
import io.github.hectorvent.floci.services.rds.model.DatabaseEngine;
import io.github.hectorvent.floci.services.rds.model.DbCluster;
import io.github.hectorvent.floci.services.rds.model.DbClusterEndpoint;
@@ -2265,6 +2266,69 @@ public class RdsService implements Resettable, ResourceProvider {
return resource.substring("cluster-snapshot:".length());
}
/**
* The DB snapshot or DB cluster snapshot {@code sourceArn} names, as an export task reads it.
* Floci keeps PostgreSQL data in its snapshots, so a snapshot of any other engine cannot be
* exported, and an ARN naming a live cluster rather than a snapshot is refused.
*/
public SnapshotExportSource snapshotExportSource(String sourceArn, String region) {
String effectiveRegion = effectiveRegion(region);
String accountId = currentAccountId();
AwsArnUtils.Arn arn;
try {
arn = AwsArnUtils.parse(sourceArn);
} catch (IllegalArgumentException malformed) {
throw new AwsException("InvalidParameterValue", "Invalid SourceArn: " + sourceArn, 400);
}
String resource = arn.resource();
boolean clusterSnapshot = resource.startsWith("cluster-snapshot:");
if (!"rds".equals(arn.service()) || !(clusterSnapshot || resource.startsWith("snapshot:"))) {
throw new AwsException("InvalidParameterValue",
"SourceArn must name a DB snapshot or a DB cluster snapshot: " + sourceArn, 400);
}
boolean ours = AwsRegions.partitionFor(effectiveRegion).equals(arn.partition())
&& effectiveRegion.equals(arn.region()) && accountId.equals(arn.accountId());
String snapshotId = resource.substring(resource.indexOf(':') + 1);
if (clusterSnapshot) {
if (!ours) {
throw new AwsException("DBClusterSnapshotNotFoundFault",
"DBClusterSnapshot " + snapshotId + " not found.", 404);
}
DbClusterSnapshot snapshot = requireClusterSnapshot(accountId, effectiveRegion, snapshotId);
requireExportable(snapshot.getStatus(), snapshot.getEngine(), sourceArn);
String sqlDump = snapshotData.get(clusterSnapshotDataKey(effectiveRegion, snapshotId))
.orElseThrow(() -> new AwsException("DBClusterSnapshotNotFoundFault",
"DB cluster snapshot data for " + snapshotId + " not found.", 404));
return new SnapshotExportSource(snapshot.getDbClusterSnapshotArn(),
imageForEngine(snapshot.getEngine(), snapshot.getEngineVersion()),
snapshot.getMasterUsername(), snapshot.getMasterPassword(),
snapshot.getSnapshotCreateTime(), sqlDump);
}
DbSnapshot snapshot = ours ? findSnapshotForScope(accountId, effectiveRegion, snapshotId) : null;
if (snapshot == null) {
throw new AwsException("DBSnapshotNotFound", "DBSnapshot " + snapshotId + " not found.", 404);
}
requireExportable(snapshot.getStatus(), snapshot.getEngine(), sourceArn);
String sqlDump = getSnapshotDataForScope(accountId, effectiveRegion, snapshotId)
.orElseThrow(() -> new AwsException("DBSnapshotNotFound",
"DBSnapshot data for " + snapshotId + " not found.", 404));
return new SnapshotExportSource(snapshot.getDbSnapshotArn(),
imageForEngine(snapshot.getEngine(), snapshot.getEngineVersion()),
snapshot.getMasterUsername(), snapshot.getMasterPassword(),
snapshot.getSnapshotCreateTime(), sqlDump);
}
private static void requireExportable(String status, DatabaseEngine engine, String sourceArn) {
if (!"available".equals(status)) {
throw new AwsException("InvalidExportSourceState",
"The snapshot " + sourceArn + " is not available for export.", 400);
}
if (engine != DatabaseEngine.POSTGRES) {
throw new AwsException("InvalidExportSourceState",
"Floci exports PostgreSQL snapshots only: " + sourceArn, 400);
}
}
/** Cluster snapshot dumps share the snapshot data store with instance snapshots under their own prefix. */
private String clusterSnapshotDataKey(String region, String snapshotId) {
return dbResourceKey(region, "cluster-snapshot:" + snapshotId);
@@ -0,0 +1,71 @@
package io.github.hectorvent.floci.services.rds.export;
import io.github.hectorvent.floci.core.common.AwsException;
import java.util.List;
import java.util.regex.Pattern;
/**
* The {@code ExportOnly} list of a PostgreSQL export: each entry names a {@code database}, a
* {@code database.schema} or a {@code database.schema.table}, and an empty list exports
* everything. RDS supports a partial export only for names made of letters, digits, {@code $} and
* {@code _}, so any other entry is refused.
*/
final class ExportOnlySelection {
private static final Pattern IDENTIFIER = Pattern.compile("[A-Za-z0-9$_]+");
private final List<String[]> entries;
private ExportOnlySelection(List<String[]> entries) {
this.entries = entries;
}
static ExportOnlySelection of(List<String> exportOnly) {
if (exportOnly == null || exportOnly.isEmpty()) {
return new ExportOnlySelection(List.of());
}
List<String[]> parsed = exportOnly.stream().map(ExportOnlySelection::parse).toList();
return new ExportOnlySelection(parsed);
}
private static String[] parse(String entry) {
String[] parts = entry.split("\\.", -1);
if (parts.length > 3) {
throw invalid(entry);
}
for (String part : parts) {
if (!IDENTIFIER.matcher(part).matches()) {
throw invalid(entry);
}
}
return parts;
}
private static AwsException invalid(String entry) {
return new AwsException("InvalidExportOnly",
"The ExportOnly value " + entry + " isn't valid for a PostgreSQL export: use database, "
+ "database.schema or database.schema.table.", 400);
}
boolean includesDatabase(String database) {
return entries.isEmpty() || entries.stream().anyMatch(entry -> entry[0].equals(database));
}
boolean includes(String database, String schema, String table) {
if (entries.isEmpty()) {
return true;
}
for (String[] entry : entries) {
if (!entry[0].equals(database)) {
continue;
}
if (entry.length == 1
|| (entry.length == 2 && entry[1].equals(schema))
|| (entry.length == 3 && entry[1].equals(schema) && entry[2].equals(table))) {
return true;
}
}
return false;
}
}
@@ -0,0 +1,460 @@
package io.github.hectorvent.floci.services.rds.export;
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.RequestScopes;
import io.github.hectorvent.floci.core.common.Resettable;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.rds.RdsService;
import io.github.hectorvent.floci.services.rds.model.ExportTask;
import io.github.hectorvent.floci.services.s3.S3Service;
import io.quarkus.runtime.StartupEvent;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.enterprise.event.Observes;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.time.Clock;
import java.time.Instant;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.Executor;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Pattern;
/**
* RDS snapshot exports to Amazon S3: {@code StartExportTask}, {@code DescribeExportTasks} and
* {@code CancelExportTask}. A task is {@code STARTING} while its snapshot is restored,
* {@code IN_PROGRESS} while its tables are written, and then {@code COMPLETE} or {@code FAILED}.
* A cancel moves it to {@code CANCELING} until the worker stops before its next table, then to
* {@code CANCELED}, and leaves what was already written in the bucket, as RDS does.
*
* <p>Deviations, documented in {@code docs/services/rds.md}: the IAM role is not assumed and the
* KMS key does not encrypt anything, both are recorded as given; only PostgreSQL snapshots can be
* exported, since Floci's snapshots hold PostgreSQL data only; and a live cluster cannot be the
* source.
*/
@ApplicationScoped
public class RdsExportTaskService implements Resettable {
private static final Logger LOG = Logger.getLogger(RdsExportTaskService.class);
static final String RESTART_FAILURE_CAUSE = "The emulator restarted before the export finished";
static final long RESET_DRAIN_TIMEOUT_MILLIS = 5_000L;
private static final long RESET_ADMISSION_WAIT_MILLIS = 30_000L;
static final long GIB = 1_073_741_824L;
private static final String KEY_PREFIX = "export-task::";
// Letters, digits and single hyphens, starting with a letter and not ending with a hyphen.
private static final Pattern IDENTIFIER = Pattern.compile("[A-Za-z](?:-?[A-Za-z0-9])*");
private static final int IDENTIFIER_MAX_LENGTH = 60;
private static final Set<String> FILTER_NAMES =
Set.of("export-task-identifier", "s3-bucket", "source-arn", "status");
private final StorageBackend<String, ExportTask> tasks;
private final RdsService rdsService;
private final S3Service s3Service;
private final SnapshotExporter exporter;
private final RegionResolver regionResolver;
private final boolean mock;
private final Clock clock;
private final Executor workers;
private final Object lock = new Object();
// Reset support, following SesExportJobService: beforeReset bumps the generation so a running
// worker stops writing, then waits for the workers already running, for a bounded time. A
// StartExportTask arriving meanwhile waits for afterReset rather than being wiped by it.
private final AtomicInteger generation = new AtomicInteger();
private boolean resetting;
private final Object workerMonitor = new Object();
private int activeWorkers;
@Inject
public RdsExportTaskService(StorageFactory storageFactory, RdsService rdsService, S3Service s3Service,
UnsupportedSnapshotExporter exporter, RegionResolver regionResolver,
EmulatorConfig config, Clock clock) {
this(storageFactory.create("rds", "rds-export-tasks.json",
new TypeReference<Map<String, ExportTask>>() {}),
rdsService, s3Service, exporter, regionResolver, config.services().rds().mock(), clock,
task -> Thread.ofVirtual().name("rds-export").start(task));
}
RdsExportTaskService(StorageBackend<String, ExportTask> tasks, RdsService rdsService, S3Service s3Service,
SnapshotExporter exporter, RegionResolver regionResolver, boolean mock, Clock clock,
Executor workers) {
this.tasks = tasks;
this.rdsService = rdsService;
this.s3Service = s3Service;
this.exporter = exporter;
this.regionResolver = regionResolver;
this.mock = mock;
this.clock = clock;
this.workers = workers;
recoverInterruptedTasks();
}
public ExportTask startExportTask(String exportTaskIdentifier, String sourceArn, String s3BucketName,
String s3Prefix, String iamRoleArn, String kmsKeyId,
List<String> exportOnly, String region) {
String effectiveRegion = effectiveRegion(region);
String accountId = regionResolver.getAccountId();
if (exportTaskIdentifier.length() > IDENTIFIER_MAX_LENGTH
|| !IDENTIFIER.matcher(exportTaskIdentifier).matches()) {
throw new AwsException("InvalidParameterValue", "The export task identifier " + exportTaskIdentifier
+ " is not valid: use 1 to 60 letters, digits or single hyphens, starting with a letter"
+ " and not ending with a hyphen.", 400);
}
ExportOnlySelection.of(exportOnly);
SnapshotExportSource source = rdsService.snapshotExportSource(sourceArn, effectiveRegion);
if (!s3Service.bucketExists(s3BucketName)) {
throw new AwsException("InvalidS3BucketFault",
"The S3 bucket " + s3BucketName + " doesn't exist.", 400);
}
String bucketRegion = s3Service.getBucketRegion(s3BucketName);
if (bucketRegion == null || bucketRegion.isBlank()) {
bucketRegion = regionResolver.getDefaultRegion();
}
boolean bucketInAnotherRegion = !bucketRegion.equalsIgnoreCase(effectiveRegion);
ExportTask task = new ExportTask();
task.setExportTaskIdentifier(exportTaskIdentifier);
task.setSourceArn(source.sourceArn());
task.setSourceType(ExportTask.SOURCE_TYPE_SNAPSHOT);
task.setExportOnly(exportOnly);
task.setSnapshotTime(source.snapshotTime());
task.setTaskStartTime(Instant.now(clock));
task.setS3Bucket(s3BucketName);
task.setS3Prefix(s3Prefix);
task.setIamRoleArn(iamRoleArn);
task.setKmsKeyId(kmsKeyId);
task.setStatus(ExportTask.STATUS_STARTING);
task.setRegion(effectiveRegion);
task.setAccountId(accountId);
task.setRuntimeArn(regionResolver.buildArn("rds", effectiveRegion, accountId,
"export-task:" + exportTaskIdentifier));
task.setRuntimeVolumeId("export-" + UUID.randomUUID().toString().replace("-", "").substring(0, 16));
synchronized (lock) {
awaitResetFinished();
if (tasks.get(key(effectiveRegion, exportTaskIdentifier)).isPresent()) {
throw new AwsException("ExportTaskAlreadyExists",
"The export task with the ID " + exportTaskIdentifier + " already exists.", 400);
}
tasks.put(key(effectiveRegion, exportTaskIdentifier), task);
ExportTask started = new ExportTask(task);
int startedIn = generation.get();
// The worker runs on a fresh thread, where account-aware storage would otherwise fall
// back to the default account and never find this task again.
workers.execute(() -> RequestScopes.runAs(accountId, effectiveRegion,
() -> run(effectiveRegion, exportTaskIdentifier, source, bucketInAnotherRegion, startedIn)));
return started;
}
}
public List<ExportTask> describeExportTasks(String exportTaskIdentifier, String sourceArn, String sourceType,
Map<String, List<String>> filters, String region) {
String effectiveRegion = effectiveRegion(region);
for (String name : filters.keySet()) {
if (!FILTER_NAMES.contains(name)) {
throw new AwsException("InvalidParameterValue", "Unrecognized filter name: " + name, 400);
}
}
if (exportTaskIdentifier != null && !exportTaskIdentifier.isBlank()) {
requireTask(effectiveRegion, exportTaskIdentifier);
}
List<ExportTask> found;
synchronized (lock) {
found = tasks.scan(key -> key.startsWith(KEY_PREFIX + effectiveRegion + "::")).stream()
.map(ExportTask::new)
.toList();
}
return found.stream()
.filter(task -> matches(exportTaskIdentifier, task.getExportTaskIdentifier()))
.filter(task -> matches(sourceArn, task.getSourceArn()))
.filter(task -> matches(sourceType, task.getSourceType()))
.filter(task -> matchesFilters(task, filters))
.sorted(Comparator.comparing(ExportTask::getTaskStartTime))
.toList();
}
public ExportTask cancelExportTask(String exportTaskIdentifier, String region) {
String effectiveRegion = effectiveRegion(region);
synchronized (lock) {
ExportTask task = requireTask(effectiveRegion, exportTaskIdentifier);
if (task.isTerminal() || ExportTask.STATUS_CANCELING.equals(task.getStatus())) {
throw new AwsException("InvalidExportTaskStateFault",
"The export task with the ID " + exportTaskIdentifier + " can't be canceled because its "
+ "status is " + task.getStatus() + ".", 400);
}
task.setStatus(ExportTask.STATUS_CANCELING);
tasks.put(key(effectiveRegion, exportTaskIdentifier), task);
return new ExportTask(task);
}
}
// Holds lock. A start arriving while a reset drains would capture the already-bumped generation,
// so its task would be wiped by clear() after it was admitted. It waits for afterReset.
private void awaitResetFinished() {
long deadline = System.currentTimeMillis() + RESET_ADMISSION_WAIT_MILLIS;
while (resetting) {
long remaining = deadline - System.currentTimeMillis();
if (remaining <= 0) {
throw resettingNow();
}
try {
lock.wait(remaining);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw resettingNow();
}
}
}
private static AwsException resettingNow() {
return new AwsException("Throttling", "Export tasks are not accepted while the emulator is resetting.", 429);
}
private void run(String region, String taskId, SnapshotExportSource source, boolean bucketInAnotherRegion,
int startedIn) {
synchronized (workerMonitor) {
activeWorkers++;
}
try {
runTask(region, taskId, source, bucketInAnotherRegion, startedIn);
} finally {
synchronized (workerMonitor) {
activeWorkers--;
workerMonitor.notifyAll();
}
}
}
private void runTask(String region, String taskId, SnapshotExportSource source, boolean bucketInAnotherRegion,
int startedIn) {
Optional<ExportTask> current = tasks.get(key(region, taskId));
if (current.isEmpty() || current.get().isTerminal() || generation.get() != startedIn) {
return;
}
if (ExportTask.STATUS_CANCELING.equals(current.get().getStatus())) {
// Canceled before its worker started: nothing to restore, nothing to stop.
finish(region, taskId, startedIn, ExportTask.STATUS_CANCELED, null, null);
return;
}
if (bucketInAnotherRegion) {
finish(region, taskId, startedIn, ExportTask.STATUS_FAILED, "The S3 bucket "
+ current.get().getS3Bucket() + " isn't located in the current AWS Region. Review your S3 bucket"
+ " name and retry the export.", null);
return;
}
if (mock) {
finish(region, taskId, startedIn, ExportTask.STATUS_COMPLETE, null,
new SnapshotExporter.Outcome(0, List.of(), Instant.now(clock)));
return;
}
SnapshotExporter.Progress progress = new SnapshotExporter.Progress() {
@Override
public void extracting(int percent) {
synchronized (lock) {
if (abandonedByReset()) {
return;
}
tasks.get(key(region, taskId))
.filter(task -> !task.isTerminal() && !ExportTask.STATUS_CANCELING.equals(task.getStatus()))
.ifPresent(task -> {
task.setStatus(ExportTask.STATUS_IN_PROGRESS);
task.setPercentProgress(percent);
tasks.put(key(region, taskId), task);
});
}
}
@Override
public boolean canceled() {
return abandonedByReset() || tasks.get(key(region, taskId))
.map(task -> ExportTask.STATUS_CANCELING.equals(task.getStatus()) || task.isTerminal())
.orElse(true);
}
@Override
public boolean abandonedByReset() {
return generation.get() != startedIn;
}
};
try {
SnapshotExporter.Outcome outcome = exporter.export(current.get(), source, progress);
finish(region, taskId, startedIn, ExportTask.STATUS_COMPLETE, null, outcome);
} catch (RuntimeException e) {
LOG.warnv(e, "RDS export task {0} failed", taskId);
finish(region, taskId, startedIn, ExportTask.STATUS_FAILED,
e.getMessage() != null ? e.getMessage() : e.toString(), null);
}
}
/** A task canceled while it ran ends {@code CANCELED} whatever its worker reached. */
private void finish(String region, String taskId, int startedIn, String status, String failureCause,
SnapshotExporter.Outcome outcome) {
synchronized (lock) {
if (generation.get() != startedIn) {
LOG.infov("RDS export task {0} abandoned by an emulator reset", taskId);
return;
}
Optional<ExportTask> current = tasks.get(key(region, taskId));
if (current.isEmpty() || current.get().isTerminal()) {
return;
}
ExportTask task = current.get();
if (ExportTask.STATUS_CANCELING.equals(task.getStatus())) {
task.setStatus(ExportTask.STATUS_CANCELED);
} else {
task.setStatus(status);
task.setFailureCause(failureCause);
if (ExportTask.STATUS_COMPLETE.equals(status)) {
task.setPercentProgress(100);
}
}
if (outcome != null) {
task.setTotalExtractedDataInGb((int) (outcome.bytesExtracted() / GIB));
if (!outcome.warnings().isEmpty()) {
task.setWarningMessage(String.join(" ", outcome.warnings()));
}
}
task.setTaskEndTime(outcome != null && outcome.finishedAt() != null
? outcome.finishedAt() : Instant.now(clock));
tasks.put(key(region, taskId), task);
}
}
private ExportTask requireTask(String region, String taskId) {
return tasks.get(key(region, taskId))
.orElseThrow(() -> new AwsException("ExportTaskNotFound",
"The export task with the ID " + taskId + " doesn't exist.", 404));
}
private static boolean matches(String wanted, String actual) {
return wanted == null || wanted.isBlank() || wanted.equals(actual);
}
private static boolean matchesFilters(ExportTask task, Map<String, List<String>> filters) {
for (Map.Entry<String, List<String>> filter : filters.entrySet()) {
List<String> values = filter.getValue();
if (values.isEmpty()) {
continue;
}
boolean matched = switch (filter.getKey()) {
case "export-task-identifier" -> values.contains(task.getExportTaskIdentifier());
case "s3-bucket" -> values.contains(task.getS3Bucket());
case "source-arn" -> values.contains(task.getSourceArn());
case "status" -> values.stream()
.anyMatch(value -> value.toUpperCase(Locale.ROOT).equals(task.getStatus()));
default -> throw new IllegalStateException("Unvalidated filter name: " + filter.getKey());
};
if (!matched) {
return false;
}
}
return true;
}
private String effectiveRegion(String region) {
return region != null && !region.isBlank() ? region : regionResolver.getDefaultRegion();
}
private static String key(String region, String taskId) {
return KEY_PREFIX + region + "::" + taskId;
}
/**
* Runs from the constructor, where no request scope is active, so the store has to be read
* across accounts: a plain scan would only ever sweep the default account's tasks.
*/
private void recoverInterruptedTasks() {
if (!(tasks instanceof AccountAwareStorageBackend<ExportTask> accountTasks)) {
return;
}
for (AccountAwareStorageBackend.AccountEntry<ExportTask> entry
: accountTasks.scanAllAccountEntries(k -> k.startsWith(KEY_PREFIX))) {
ExportTask task = entry.value();
if (task.isTerminal()) {
continue;
}
if (ExportTask.STATUS_CANCELING.equals(task.getStatus())) {
task.setStatus(ExportTask.STATUS_CANCELED);
} else {
task.setStatus(ExportTask.STATUS_FAILED);
task.setFailureCause(RESTART_FAILURE_CAUSE);
}
task.setTaskEndTime(Instant.now(clock));
accountTasks.putForAccount(entry.accountId(), entry.key(), task);
LOG.warnv("RDS export task {0} was interrupted by a restart and is now {1}",
task.getExportTaskIdentifier(), task.getStatus());
if (!mock) {
try {
exporter.discard(task);
} catch (RuntimeException e) {
LOG.warnv(e, "Could not remove what RDS export task {0} left behind",
task.getExportTaskIdentifier());
}
}
}
}
/**
* Forces the bean, which is otherwise created on first use, at startup, so a task a restart
* interrupted is failed and its restore container and volume removed straight away rather than
* when a client first calls an export action.
*/
void onStart(@Observes StartupEvent ignored) {
LOG.debugv("RDS export task service ready");
}
@Override
public void beforeReset() {
synchronized (lock) {
resetting = true;
generation.incrementAndGet();
}
boolean interrupted = false;
long deadline = System.currentTimeMillis() + RESET_DRAIN_TIMEOUT_MILLIS;
synchronized (workerMonitor) {
while (activeWorkers > 0) {
long remaining = deadline - System.currentTimeMillis();
if (remaining <= 0) {
LOG.warnv("{0} RDS export worker(s) still running after {1}ms",
activeWorkers, RESET_DRAIN_TIMEOUT_MILLIS);
break;
}
try {
workerMonitor.wait(remaining);
} catch (InterruptedException e) {
// Keep draining to the deadline; the interrupt is re-asserted on the way out.
interrupted = true;
}
}
}
if (interrupted) {
Thread.currentThread().interrupt();
}
}
@Override
public void afterReset() {
synchronized (lock) {
resetting = false;
lock.notifyAll();
}
}
@Override
public void clear() {
tasks.clear();
LOG.info("Cleared all RDS export tasks");
}
}
@@ -0,0 +1,10 @@
package io.github.hectorvent.floci.services.rds.export;
import java.time.Instant;
/**
* What an export task reads from a DB snapshot or DB cluster snapshot: the image its data
* restores into, the master login, the time it was taken and its dump.
*/
public record SnapshotExportSource(String sourceArn, String image, String masterUsername,
String masterPassword, Instant snapshotTime, String sqlDump) {}
@@ -0,0 +1,33 @@
package io.github.hectorvent.floci.services.rds.export;
import io.github.hectorvent.floci.services.rds.model.ExportTask;
import java.time.Instant;
import java.util.List;
/** Writes one export task's data to its bucket. */
public interface SnapshotExporter {
/** How the exporter reports back to the task it runs for. */
interface Progress {
/** The snapshot is restored and tables are being written; {@code percent} of them are done. */
void extracting(int percent);
/** True once the task was canceled, which stops the export before its next table. */
boolean canceled();
boolean abandonedByReset();
}
/**
* What an export wrote: its size, a warning for each table it had to leave out, and when it
* finished, which is also the end time its {@code export_info} file records.
*/
record Outcome(long bytesExtracted, List<String> warnings, Instant finishedAt) {}
Outcome export(ExportTask task, SnapshotExportSource source, Progress progress);
/** Removes whatever an export that never finished left behind, after a restart. */
default void discard(ExportTask task) {}
}
@@ -0,0 +1,16 @@
package io.github.hectorvent.floci.services.rds.export;
import io.github.hectorvent.floci.services.rds.model.ExportTask;
import jakarta.enterprise.context.ApplicationScoped;
@ApplicationScoped
public class UnsupportedSnapshotExporter implements SnapshotExporter {
static final String FAILURE_CAUSE = "Floci does not write snapshot data to S3 yet: "
+ "export tasks complete only in mock mode (FLOCI_SERVICES_RDS_MOCK=true)";
@Override
public Outcome export(ExportTask task, SnapshotExportSource source, Progress progress) {
throw new UnsupportedOperationException(FAILURE_CAUSE);
}
}
@@ -0,0 +1,187 @@
package io.github.hectorvent.floci.services.rds.model;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
/**
* A snapshot export to Amazon S3, as {@code StartExportTask} and {@code DescribeExportTasks}
* describe it. {@code IamRoleArn} and {@code KmsKeyId} are kept as given: Floci writes to its own
* S3 without assuming the role or encrypting with the key.
*/
@RegisterForReflection
public class ExportTask {
public static final String STATUS_STARTING = "STARTING";
public static final String STATUS_IN_PROGRESS = "IN_PROGRESS";
public static final String STATUS_COMPLETE = "COMPLETE";
public static final String STATUS_FAILED = "FAILED";
public static final String STATUS_CANCELING = "CANCELING";
public static final String STATUS_CANCELED = "CANCELED";
public static final String SOURCE_TYPE_SNAPSHOT = "SNAPSHOT";
@JsonProperty("ExportTaskIdentifier")
private String exportTaskIdentifier;
@JsonProperty("SourceArn")
private String sourceArn;
@JsonProperty("SourceType")
private String sourceType;
@JsonProperty("ExportOnly")
private List<String> exportOnly = new ArrayList<>();
@JsonProperty("SnapshotTime")
private Instant snapshotTime;
@JsonProperty("TaskStartTime")
private Instant taskStartTime;
@JsonProperty("TaskEndTime")
private Instant taskEndTime;
@JsonProperty("S3Bucket")
private String s3Bucket;
@JsonProperty("S3Prefix")
private String s3Prefix;
@JsonProperty("IamRoleArn")
private String iamRoleArn;
@JsonProperty("KmsKeyId")
private String kmsKeyId;
@JsonProperty("Status")
private String status;
@JsonProperty("PercentProgress")
private int percentProgress;
@JsonProperty("TotalExtractedDataInGB")
private int totalExtractedDataInGb;
@JsonProperty("FailureCause")
private String failureCause;
@JsonProperty("WarningMessage")
private String warningMessage;
@JsonProperty("Region")
private String region;
/** The account that started the task, which its worker runs as. */
@JsonProperty("AccountId")
private String accountId;
/**
* The task's ARN as Floci names its restore container's runtime, so the container carries the
* task's account and region. RDS gives export tasks no ARN, so this is never reported.
*/
@JsonProperty("RuntimeArn")
private String runtimeArn;
/** The name the restore container and its volume are created under, unique to this task. */
@JsonProperty("RuntimeVolumeId")
private String runtimeVolumeId;
public ExportTask() {}
public ExportTask(ExportTask other) {
this.exportTaskIdentifier = other.exportTaskIdentifier;
this.sourceArn = other.sourceArn;
this.sourceType = other.sourceType;
this.exportOnly = new ArrayList<>(other.exportOnly);
this.snapshotTime = other.snapshotTime;
this.taskStartTime = other.taskStartTime;
this.taskEndTime = other.taskEndTime;
this.s3Bucket = other.s3Bucket;
this.s3Prefix = other.s3Prefix;
this.iamRoleArn = other.iamRoleArn;
this.kmsKeyId = other.kmsKeyId;
this.status = other.status;
this.percentProgress = other.percentProgress;
this.totalExtractedDataInGb = other.totalExtractedDataInGb;
this.failureCause = other.failureCause;
this.warningMessage = other.warningMessage;
this.region = other.region;
this.accountId = other.accountId;
this.runtimeArn = other.runtimeArn;
this.runtimeVolumeId = other.runtimeVolumeId;
}
@JsonIgnore
public boolean isTerminal() {
return STATUS_COMPLETE.equals(status)
|| STATUS_FAILED.equals(status)
|| STATUS_CANCELED.equals(status);
}
public String getExportTaskIdentifier() { return exportTaskIdentifier; }
public void setExportTaskIdentifier(String exportTaskIdentifier) { this.exportTaskIdentifier = exportTaskIdentifier; }
public String getSourceArn() { return sourceArn; }
public void setSourceArn(String sourceArn) { this.sourceArn = sourceArn; }
public String getSourceType() { return sourceType; }
public void setSourceType(String sourceType) { this.sourceType = sourceType; }
public List<String> getExportOnly() { return exportOnly; }
public void setExportOnly(List<String> exportOnly) {
this.exportOnly = exportOnly != null ? new ArrayList<>(exportOnly) : new ArrayList<>();
}
public Instant getSnapshotTime() { return snapshotTime; }
public void setSnapshotTime(Instant snapshotTime) { this.snapshotTime = snapshotTime; }
public Instant getTaskStartTime() { return taskStartTime; }
public void setTaskStartTime(Instant taskStartTime) { this.taskStartTime = taskStartTime; }
public Instant getTaskEndTime() { return taskEndTime; }
public void setTaskEndTime(Instant taskEndTime) { this.taskEndTime = taskEndTime; }
public String getS3Bucket() { return s3Bucket; }
public void setS3Bucket(String s3Bucket) { this.s3Bucket = s3Bucket; }
public String getS3Prefix() { return s3Prefix; }
public void setS3Prefix(String s3Prefix) { this.s3Prefix = s3Prefix; }
public String getIamRoleArn() { return iamRoleArn; }
public void setIamRoleArn(String iamRoleArn) { this.iamRoleArn = iamRoleArn; }
public String getKmsKeyId() { return kmsKeyId; }
public void setKmsKeyId(String kmsKeyId) { this.kmsKeyId = kmsKeyId; }
public String getStatus() { return status; }
public void setStatus(String status) { this.status = status; }
public int getPercentProgress() { return percentProgress; }
public void setPercentProgress(int percentProgress) { this.percentProgress = percentProgress; }
public int getTotalExtractedDataInGb() { return totalExtractedDataInGb; }
public void setTotalExtractedDataInGb(int totalExtractedDataInGb) { this.totalExtractedDataInGb = totalExtractedDataInGb; }
public String getFailureCause() { return failureCause; }
public void setFailureCause(String failureCause) { this.failureCause = failureCause; }
public String getWarningMessage() { return warningMessage; }
public void setWarningMessage(String warningMessage) { this.warningMessage = warningMessage; }
public String getRegion() { return region; }
public void setRegion(String region) { this.region = region; }
public String getAccountId() { return accountId; }
public void setAccountId(String accountId) { this.accountId = accountId; }
public String getRuntimeArn() { return runtimeArn; }
public void setRuntimeArn(String runtimeArn) { this.runtimeArn = runtimeArn; }
public String getRuntimeVolumeId() { return runtimeVolumeId; }
public void setRuntimeVolumeId(String runtimeVolumeId) { this.runtimeVolumeId = runtimeVolumeId; }
}