diff --git a/docs/services/redshift.md b/docs/services/redshift.md index 0e212359ba..7b95b32b56 100644 --- a/docs/services/redshift.md +++ b/docs/services/redshift.md @@ -312,6 +312,7 @@ JOB CREATE my_copy_job AUTO ON; COPY JOB LIST; COPY JOB SHOW my_copy_job; COPY JOB ALTER my_copy_job AUTO OFF; +COPY JOB RUN my_copy_job; COPY JOB DROP my_copy_job; ``` @@ -326,8 +327,24 @@ and see their own rows in `sys_copy_job`; superusers can see all rows. COPY options are stored for execution time, including formats the ordinary COPY simulator does not yet implement. The COPY JOB restrictions above are checked at creation time. -Jobs only record the COPY for now: nothing loads files automatically, and `COPY JOB RUN` is refused. The -SQLSTATEs and messages of the refusals are Floci's own, not captured from AWS. +`COPY JOB RUN` scans the job's S3 prefix and loads files not yet committed by that job, including with +`AUTO OFF`. An active S3 event integration runs matching `AUTO ON` jobs in provisioned clusters and +Serverless workgroups. Each object uses the stored COPY options and IAM role, with the same role association, +trust and S3 authorization checks as an ordinary COPY. + +Files older than the job are skipped. Successfully ingested filenames (`status = 'I'`) are loaded once per job, +even after an overwrite or notification redelivery. A file whose load fails is rolled back to its own savepoint +and recorded with `status = 'E'` so later files in the same run continue; overwriting a failed file with a new +ETag or version ID lets a subsequent run retry it. Checkpoints record bucket, key, ETag, version ID, file size, +modification time, enqueue time and status in `floci_internal.copy_job_detail` and expose them through +`sys_copy_job_detail`, in the same PostgreSQL transaction as the target rows. They survive Floci restarts with +the target database. Dropping a job removes its checkpoints. + +The background sweep scheduler reconciles on startup and when S3 uploads mark a bucket. If a target is +temporarily unavailable or a job run fails, the scheduler marks the bucket again for the next sweep. Deleting an +integration switches its bucket's jobs to `AUTO OFF`, retaining their definitions and checkpoints. Resume a +paused cluster before deleting its integration. +The SQLSTATEs and messages of job validation errors are Floci's own, not captured from AWS. See AWS's [COPY JOB](https://docs.aws.amazon.com/redshift/latest/dg/r_COPY-JOB.html) and [auto-copy](https://docs.aws.amazon.com/redshift/latest/dg/loading-data-copy-job.html) references. @@ -478,9 +495,10 @@ A bucket joins a target once (`IntegrationConflictOperationFault`), and a target takes at most 50 S3 event integrations (`IntegrationQuotaExceededFault`). Those two fault names are Floci's reading of the AWS API's fault list; their messages are not captured from AWS. -The integration is `active` as soon as it is created, where AWS reports `creating` first. It does not load -anything yet, and the bucket policy, the namespace resource policy and the existing notifications of the bucket -are not checked. [COPY JOB](#copy-job) statements work independently of the integration. +The integration is `active` as soon as it is created, where AWS reports `creating` first. It enables +automatic ingestion for matching [COPY JOB](#copy-job) definitions. Integration creation does not check +the bucket notification policy, namespace resource policy or existing bucket notifications. Loading still +checks the job's IAM role and S3 access. Manual `COPY JOB RUN` works independently of the integration. ### Resource policies diff --git a/src/main/java/io/floci/aws/services/redshift/RedshiftQueryHandler.java b/src/main/java/io/floci/aws/services/redshift/RedshiftQueryHandler.java index ba4ca4adc2..9e6e22d950 100644 --- a/src/main/java/io/floci/aws/services/redshift/RedshiftQueryHandler.java +++ b/src/main/java/io/floci/aws/services/redshift/RedshiftQueryHandler.java @@ -531,7 +531,9 @@ public class RedshiftQueryHandler { .start("DescribeIntegrationsResult") .start("Integrations"); for (Integration integration : found.integrations()) { - xmlBuilder.raw(buildIntegrationXml(integration, true)); + xmlBuilder.start("Integration") + .raw(buildIntegrationXml(integration, true)) + .end("Integration"); } xmlBuilder.end("Integrations"); // Marker only when a further page exists: real Redshift omits it on the terminal page, @@ -1624,13 +1626,12 @@ public class RedshiftQueryHandler { */ private String buildIntegrationXml(Integration integration, boolean includeErrors) { XmlBuilder builder = new XmlBuilder() - .start("Integration") - .elem("IntegrationArn", integration.getIntegrationArn()) - .elem("IntegrationName", integration.getIntegrationName()) - .elem("SourceArn", integration.getSourceArn()) - .elem("TargetArn", integration.getTargetArn()) - .elem("Status", integration.getStatus()) - .elem("CreateTime", integration.getCreateTime()); + .elem("IntegrationArn", integration.getIntegrationArn()) + .elem("IntegrationName", integration.getIntegrationName()) + .elem("SourceArn", integration.getSourceArn()) + .elem("TargetArn", integration.getTargetArn()) + .elem("Status", integration.getStatus()) + .elem("CreateTime", integration.getCreateTime()); if (integration.getSourceType() != null) { builder.elem("SourceType", integration.getSourceType()); } @@ -1664,7 +1665,7 @@ public class RedshiftQueryHandler { } builder.end("Tags"); } - return builder.end("Integration").build(); + return builder.build(); } /** diff --git a/src/main/java/io/floci/aws/services/redshift/RedshiftS3AutoCopyConsumer.java b/src/main/java/io/floci/aws/services/redshift/RedshiftS3AutoCopyConsumer.java new file mode 100644 index 0000000000..dba69d94ac --- /dev/null +++ b/src/main/java/io/floci/aws/services/redshift/RedshiftS3AutoCopyConsumer.java @@ -0,0 +1,119 @@ +package io.floci.aws.services.redshift; + +import io.floci.aws.config.EmulatorConfig; +import io.floci.aws.core.common.AwsArnUtils; +import io.floci.aws.core.common.RequestScopes; +import io.floci.aws.core.common.SweepScheduler; +import io.floci.aws.core.common.SweepWorker; +import io.floci.aws.services.redshift.model.Integration; +import io.floci.aws.services.redshiftdata.RedshiftCopyJobExecutor; +import io.floci.aws.services.s3.model.S3ObjectUpdatedEvent; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.enterprise.event.Observes; +import jakarta.inject.Inject; +import org.jboss.logging.Logger; + +import java.time.Instant; +import java.util.HashSet; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.function.Supplier; + +@ApplicationScoped +public class RedshiftS3AutoCopyConsumer extends SweepScheduler { + private static final Logger LOG = Logger.getLogger(RedshiftS3AutoCopyConsumer.class); + + private static final class WorkQueue { + private final Set pendingBuckets = ConcurrentHashMap.newKeySet(); + private final AtomicBoolean reconcileAll = new AtomicBoolean(true); + } + + private final RedshiftService service; + private final RedshiftCopyJobExecutor writer; + private final WorkQueue work; + + @Inject + public RedshiftS3AutoCopyConsumer(RedshiftService service, RedshiftCopyJobExecutor writer, EmulatorConfig config) { + this(service, writer, config.services().redshift().enabled(), + Math.max(1L, TimeUnit.MILLISECONDS.toSeconds(config.services().redshift().pollIntervalMs()))); + } + + RedshiftS3AutoCopyConsumer(RedshiftService service, RedshiftCopyJobExecutor writer, + boolean enabled, long intervalSeconds) { + this(service, writer, new WorkQueue(), enabled, intervalSeconds); + } + + private RedshiftS3AutoCopyConsumer(RedshiftService service, RedshiftCopyJobExecutor writer, + WorkQueue work, boolean enabled, long intervalSeconds) { + super(new SweepWorker("redshift-s3-auto-copy", enabled, intervalSeconds, true, + ignored -> sweep(work, service, writer))); + this.service = service; + this.writer = writer; + this.work = work; + } + + RedshiftS3AutoCopyConsumer() { + this.service = null; + this.writer = null; + this.work = null; + } + + void updated(@Observes S3ObjectUpdatedEvent event) { + work.pendingBuckets.add(event.bucketName()); + } + + void markReconcile() { + work.reconcileAll.set(true); + } + + void pollOnce() { + tick(Instant.now()); + } + + private static void sweep(WorkQueue work, RedshiftService service, RedshiftCopyJobExecutor writer) { + boolean fullReconcile = work.reconcileAll.getAndSet(false); + Set buckets = new HashSet<>(work.pendingBuckets); + work.pendingBuckets.removeAll(buckets); + if (!fullReconcile && buckets.isEmpty()) { + return; + } + for (Integration integration : service.listS3AutoCopyIntegrations()) { + if (!"active".equals(integration.getStatus())) { + continue; + } + String sourceBucket = AwsArnUtils.parse(integration.getSourceArn()).resource(); + if (!fullReconcile && !buckets.contains(sourceBucket)) { + continue; + } + try { + if (scoped(integration, () -> writer.runAutomatic(integration))) { + work.pendingBuckets.add(sourceBucket); + } + } catch (RuntimeException exception) { + work.pendingBuckets.add(sourceBucket); + LOG.warnv(exception, "S3 auto-copy failed for integration {0}; will retry", + integration.getIntegrationArn()); + } + } + } + + public void disable(Integration integration) { + scoped(integration, () -> { + writer.disable(integration); + return null; + }); + } + + private static T scoped(Integration integration, Supplier action) { + return RequestScopes.callAs(integration.getAccountId(), + AwsArnUtils.parse(integration.getIntegrationArn()).region(), action); + } + + @Override + public void clear() { + work.pendingBuckets.clear(); + work.reconcileAll.set(true); + } +} diff --git a/src/main/java/io/floci/aws/services/redshift/RedshiftService.java b/src/main/java/io/floci/aws/services/redshift/RedshiftService.java index 736e7f2357..133d8b4afd 100644 --- a/src/main/java/io/floci/aws/services/redshift/RedshiftService.java +++ b/src/main/java/io/floci/aws/services/redshift/RedshiftService.java @@ -121,6 +121,7 @@ public class RedshiftService implements ManagedSecretRotator { private final RedshiftZeroEtlEndpoints zeroEtlEndpoints; private final S3Service s3Service; private final ServiceCallAuthorizer serviceCallAuthorizer; + private final RedshiftS3AutoCopyConsumer autoCopyConsumer; // Proxy ports currently handed out, so allocateProxyPort never double-assigns within this JVM. private final Set usedPorts = ConcurrentHashMap.newKeySet(); private final ConcurrentHashMap resourceLocks = new ConcurrentHashMap<>(); @@ -205,7 +206,8 @@ public class RedshiftService implements ManagedSecretRotator { DynamoDbStreamReader streamReader, RedshiftAuditLogPublisher auditLogPublisher, RedshiftEventService events, RedshiftIntegrationEventPublisher integrationEvents, Ec2Service ec2Service, RedshiftZeroEtlEndpoints zeroEtlEndpoints, - S3Service s3Service, ServiceCallAuthorizer serviceCallAuthorizer) { + S3Service s3Service, ServiceCallAuthorizer serviceCallAuthorizer, + RedshiftS3AutoCopyConsumer autoCopyConsumer) { 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>() {}); @@ -232,11 +234,26 @@ public class RedshiftService implements ManagedSecretRotator { this.zeroEtlEndpoints = zeroEtlEndpoints; this.s3Service = s3Service; this.serviceCallAuthorizer = serviceCallAuthorizer; + this.autoCopyConsumer = autoCopyConsumer; if (this.auditLogPublisher != null) { this.auditLogPublisher.setDeliveryStatusListener(this::recordAuditDeliveryOutcome); } } + public RedshiftService(StorageFactory storageFactory, RedshiftContainerManager containerManager, + EmulatorConfig config, RegionResolver regionResolver, + RedshiftProxyManager proxyManager, DockerHostResolver dockerHostResolver, + RedshiftCredentialBroker credentialBroker, + SecretsManagerService secretsManagerService, ObjectMapper objectMapper, + DynamoDbStreamReader streamReader, RedshiftAuditLogPublisher auditLogPublisher, + RedshiftEventService events, RedshiftIntegrationEventPublisher integrationEvents, + Ec2Service ec2Service, RedshiftZeroEtlEndpoints zeroEtlEndpoints, + S3Service s3Service, ServiceCallAuthorizer serviceCallAuthorizer) { + this(storageFactory, containerManager, config, regionResolver, proxyManager, dockerHostResolver, + credentialBroker, secretsManagerService, objectMapper, streamReader, auditLogPublisher, events, + integrationEvents, ec2Service, zeroEtlEndpoints, s3Service, serviceCallAuthorizer, null); + } + RedshiftService(StorageFactory storageFactory, RedshiftContainerManager containerManager, EmulatorConfig config, RegionResolver regionResolver, RedshiftProxyManager proxyManager, DockerHostResolver dockerHostResolver, @@ -247,7 +264,7 @@ public class RedshiftService implements ManagedSecretRotator { Ec2Service ec2Service, RedshiftZeroEtlEndpoints zeroEtlEndpoints) { this(storageFactory, containerManager, config, regionResolver, proxyManager, dockerHostResolver, credentialBroker, secretsManagerService, objectMapper, streamReader, auditLogPublisher, events, - integrationEvents, ec2Service, zeroEtlEndpoints, null, null); + integrationEvents, ec2Service, zeroEtlEndpoints, null, null, null); } // Hand-built test constructions need not supply EC2; a null ec2Service skips subnet resolution. @@ -259,7 +276,7 @@ public class RedshiftService implements ManagedSecretRotator { RedshiftEventService events, RedshiftIntegrationEventPublisher integrationEvents) { this(storageFactory, containerManager, config, regionResolver, proxyManager, dockerHostResolver, credentialBroker, secretsManagerService, objectMapper, streamReader, auditLogPublisher, events, - integrationEvents, null, null); + integrationEvents, null, null, null, null, null); } // Hand-built test constructions that create integrations in the AWS form need the endpoints. @@ -275,6 +292,18 @@ public class RedshiftService implements ManagedSecretRotator { integrationEvents, null, zeroEtlEndpoints); } + RedshiftService(StorageFactory storageFactory, RedshiftContainerManager containerManager, + EmulatorConfig config, RegionResolver regionResolver, RedshiftProxyManager proxyManager, + DockerHostResolver dockerHostResolver, RedshiftCredentialBroker credentialBroker, + SecretsManagerService secretsManagerService, ObjectMapper objectMapper, + DynamoDbStreamReader streamReader, RedshiftAuditLogPublisher auditLogPublisher, + RedshiftEventService events, RedshiftIntegrationEventPublisher integrationEvents, + RedshiftZeroEtlEndpoints zeroEtlEndpoints, RedshiftS3AutoCopyConsumer autoCopyConsumer) { + this(storageFactory, containerManager, config, regionResolver, proxyManager, dockerHostResolver, + credentialBroker, secretsManagerService, objectMapper, streamReader, auditLogPublisher, events, + integrationEvents, null, zeroEtlEndpoints, null, null, autoCopyConsumer); + } + RedshiftService(StorageFactory storageFactory, RedshiftContainerManager containerManager, EmulatorConfig config, RegionResolver regionResolver, RedshiftProxyManager proxyManager, DockerHostResolver dockerHostResolver, RedshiftCredentialBroker credentialBroker, @@ -605,6 +634,9 @@ public class RedshiftService implements ManagedSecretRotator { Map tags, String region) { Integration integration = createIntegrationLocked(integrationName, sourceArn, targetArn, kmsKeyId, description, additionalEncryptionContext, tags, region); + if (autoCopyConsumer != null && S3_EVENT_SOURCE_TYPE.equals(integration.getSourceType())) { + autoCopyConsumer.markReconcile(); + } publishIntegrationEvents(); return integration; } @@ -850,6 +882,16 @@ public class RedshiftService implements ManagedSecretRotator { .toList(); } + public List listS3AutoCopyIntegrations() { + return integrations.scanAllAccountEntries(key -> true).stream() + .filter(entry -> S3_EVENT_SOURCE_TYPE.equals(entry.value().getSourceType())) + .map(entry -> { + Integration integration = entry.value(); + integration.setAccountId(entry.accountId()); + return integration; + }).toList(); + } + public void updateIntegrationRuntime(String accountId, String integrationArn, Map shardSequenceNumbers, boolean successful, String error) { @@ -991,6 +1033,15 @@ public class RedshiftService implements ManagedSecretRotator { } public Integration deleteIntegration(String integrationArn) { + if (integrationArn == null || integrationArn.isBlank()) { + throw new AwsException("InvalidParameterValue", "IntegrationArn is required.", 400); + } + if (autoCopyConsumer != null) { + integrations.keys().stream().map(integrations::get).flatMap(Optional::stream) + .filter(integration -> integrationArn.equals(integration.getIntegrationArn()) + && S3_EVENT_SOURCE_TYPE.equals(integration.getSourceType())) + .findFirst().ifPresent(autoCopyConsumer::disable); + } Integration deleted = deleteIntegrationLocked(integrationArn); publishIntegrationEvents(); return deleted; @@ -1686,6 +1737,9 @@ public class RedshiftService implements ManagedSecretRotator { clusters.put(clusterIdentifier, cluster); clusters.flush(); registerAuditLogging(accountId, cluster); + if (autoCopyConsumer != null) { + autoCopyConsumer.markReconcile(); + } return cluster; } catch (RuntimeException failure) { cluster.setClusterStatus("paused"); diff --git a/src/main/java/io/floci/aws/services/redshift/proxy/CopyEtlLoader.java b/src/main/java/io/floci/aws/services/redshift/proxy/CopyEtlLoader.java index 4e658d8de3..d11b573501 100644 --- a/src/main/java/io/floci/aws/services/redshift/proxy/CopyEtlLoader.java +++ b/src/main/java/io/floci/aws/services/redshift/proxy/CopyEtlLoader.java @@ -30,7 +30,7 @@ final class CopyEtlLoader { private CopyEtlLoader() { } - static boolean runSimple(Socket client, Socket socket, CopyStatementParser.S3CopyFrom spec, + static boolean runSimple(Socket client, Socket socket, CopyStatementParser.S3Statement spec, S3Service s3, IamService iam, String account, List roles, char status, IntConsumer onStatusChange) throws IOException { CopyBackendSession backend = new CopyBackendSession(socket, response -> { @@ -73,14 +73,18 @@ final class CopyEtlLoader { return true; } - static long execute(CopyBackendSession backend, CopyStatementParser.S3CopyFrom spec, + static long execute(CopyBackendSession backend, CopyStatementParser.S3Statement spec, S3Service s3, IamService iam, String account, List roles, boolean callerTransaction) throws IOException { backend.begin(callerTransaction); String savepoint = "floci_load_" + UUID.randomUUID().toString().replace("-", ""); backend.execute("SAVEPOINT " + savepoint); try { - long rows = load(backend, spec, s3, iam, account, roles); + long rows = switch (spec) { + case CopyStatementParser.S3CopyFrom copy -> load(backend, copy, null, null, s3, iam, account, roles, false); + case CopyStatementParser.S3CopyJobRun run -> CopyJobRunner.load(backend, run.name(), s3, iam, account, roles); + default -> throw new IllegalArgumentException("Expected COPY statement"); + }; backend.execute("RELEASE SAVEPOINT " + savepoint); return rows; } catch (IOException | RuntimeException exception) { @@ -98,15 +102,25 @@ final class CopyEtlLoader { } } + static long executeObject(CopyBackendSession backend, CopyStatementParser.S3CopyFrom spec, + String expectedETag, String versionId, + S3Service s3, IamService iam, String account, List roles) throws IOException { + return load(backend, spec, expectedETag, versionId, s3, iam, account, roles, true); + } + private static long load(CopyBackendSession backend, CopyStatementParser.S3CopyFrom spec, - S3Service s3, IamService iam, String account, List roles) throws IOException { + String expectedETag, String versionId, + S3Service s3, IamService iam, String account, List roles, + boolean exactObject) throws IOException { List catalog = columns(backend, spec); List discovered = spec.jsonAuto() && (spec.columns() == null || spec.columns().isEmpty()) ? catalog.stream().map(ColumnInfo::name).toList() : null; List widths = spec.transforms().truncateColumns() ? S3CopySimulator.alignMaxBytes(spec, catalog) : null; List kinds = spec.transforms().needsColumnTypes() ? S3CopySimulator.alignKinds(spec, catalog) : null; - CopyInput input = S3CopySimulator.prepareCopy(spec, s3, iam, account, roles); + CopyInput input = exactObject + ? S3CopySimulator.prepareObjectCopy(spec, s3, iam, account, roles, expectedETag, versionId) + : S3CopySimulator.prepareCopy(spec, s3, iam, account, roles); try { if (!spec.transforms().toleratesErrors()) { return backend.copy(S3CopySimulator.copyBackendSql(spec, discovered), @@ -157,7 +171,7 @@ final class CopyEtlLoader { int rejected = 0; for (String key : input.keys()) { S3CopySimulator.authorizeCopyObject(spec, input.s3(), input.iamService(), input.roleSession(), key); - S3Object object = input.s3().getObject(spec.bucket(), key); + S3Object object = input.readObject(key); byte[] data = object != null && object.getData() != null ? object.getData() : new byte[0]; try (InputStream raw = new ByteArrayInputStream(data); InputStream source = CopySourceInputStream.open(raw, spec.gzip())) { diff --git a/src/main/java/io/floci/aws/services/redshift/proxy/CopyJobRunner.java b/src/main/java/io/floci/aws/services/redshift/proxy/CopyJobRunner.java new file mode 100644 index 0000000000..762bc58f04 --- /dev/null +++ b/src/main/java/io/floci/aws/services/redshift/proxy/CopyJobRunner.java @@ -0,0 +1,159 @@ +package io.floci.aws.services.redshift.proxy; + +import io.floci.aws.core.common.PostgresWire; +import io.floci.aws.services.iam.IamService; +import io.floci.aws.services.redshift.proxy.S3CopySimulator.S3TransferException; +import io.floci.aws.services.s3.S3Service; +import io.floci.aws.services.s3.model.S3Object; + +import java.io.IOException; +import java.math.BigDecimal; +import java.time.Instant; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; + +/** Checkpoints and target rows are written on the same backend transaction. */ +final class CopyJobRunner { + private record FileRevision(String etag, String versionId) { + boolean matches(S3Object object) { + return Objects.equals(etag, object.getETag()) && Objects.equals(versionId, object.getVersionId()); + } + } + + private CopyJobRunner() { + } + + static long load(CopyBackendSession backend, String name, S3Service s3, IamService iam, + String account, List roles) throws IOException { + List> jobs = backend.query("SELECT job_id, job_text, bucket, prefix, " + + "extract(epoch FROM created_at), owner FROM floci_internal.copy_job_for_run(" + + PostgresWire.quoteLiteral(name) + ")"); + if (jobs.isEmpty()) { + throw new S3TransferException("42704", "Copy job does not exist: " + name, null); + } + List job = jobs.getFirst(); + CopyStatementParser.S3Statement parsed = CopyStatementParser.parse(job.get(1)); + if (!(parsed instanceof CopyStatementParser.S3CopyFrom copy)) { + throw new S3TransferException("0A000", "Unsupported COPY options in job " + name, null); + } + RedshiftRoleAccess.RoleSession session = RedshiftRoleAccess.resolveRoleSession(copy.iamRoleArn(), iam, account, roles); + try { + RedshiftRoleAccess.authorizeRoleList(s3, iam, session, copy.iamRoleArn(), copy.bucket(), copy.keyOrPrefix()); + String caller = backend.query("SELECT current_user").getFirst().getFirst(); + backend.execute("SET LOCAL ROLE " + identifier(job.get(5))); + long count = loadFiles(backend, job, copy, s3, iam, account, roles); + backend.execute("SET LOCAL ROLE " + identifier(caller)); + return count; + } finally { + RedshiftRoleAccess.releaseRoleSession(session, copy.iamRoleArn(), iam); + } + } + + private static long loadFiles(CopyBackendSession backend, List job, CopyStatementParser.S3CopyFrom copy, + S3Service s3, IamService iam, String account, List roles) throws IOException { + long id = Long.parseLong(job.get(0)); + // S3 stores lastModified at millisecond precision. + Instant created = Instant.ofEpochMilli(new BigDecimal(job.get(4)).movePointRight(3).longValue()); + Set checkpointed = new HashSet<>(); + Map failedFiles = new HashMap<>(); + for (List row : backend.query( + "SELECT key, status, etag, version_id FROM floci_internal.copy_job_loaded_keys(" + id + ")")) { + if (row.isEmpty() || row.getFirst() == null) { + continue; + } + String status = row.size() > 1 && row.get(1) != null ? row.get(1) : "I"; + if ("E".equals(status)) { + failedFiles.put(row.getFirst(), new FileRevision( + row.size() > 2 ? row.get(2) : null, + row.size() > 3 ? row.get(3) : null)); + } else { + checkpointed.add(row.getFirst()); + } + } + long count = 0; + String token = null; + do { + S3Service.ListObjectsResult page = s3.listObjectsWithPrefixes(job.get(2), job.get(3), null, 1000, token, null); + for (S3Object object : page.objects()) { + if (object.getLastModified() != null && object.getLastModified().isBefore(created)) { + continue; + } + if (checkpointed.contains(object.getKey())) { + continue; + } + FileRevision previousFailure = failedFiles.get(object.getKey()); + if (previousFailure != null && previousFailure.matches(object)) { + continue; + } + String fileSavepoint = "floci_job_file_" + UUID.randomUUID().toString().replace("-", ""); + backend.execute("SAVEPOINT " + fileSavepoint); + try { + String checkpoint = "SELECT floci_internal.reserve_copy_job_file(" + + fileMetadataArgs(id, object) + ")"; + if (!"t".equals(backend.query(checkpoint).getFirst().getFirst())) { + backend.execute("RELEASE SAVEPOINT " + fileSavepoint); + checkpointed.add(object.getKey()); + continue; + } + count += CopyEtlLoader.executeObject(backend, forObject(copy, object.getKey()), + object.getETag(), object.getVersionId(), s3, iam, account, roles); + backend.execute("RELEASE SAVEPOINT " + fileSavepoint); + checkpointed.add(object.getKey()); + failedFiles.remove(object.getKey()); + } catch (IOException | RuntimeException exception) { + rollbackFileSavepoint(backend, fileSavepoint, exception); + if (exception instanceof S3TransferException transfer && S3TransferException.isJobFailure(transfer.sqlState())) { + throw transfer; + } + backend.query("SELECT floci_internal.record_copy_job_file_error(" + + fileMetadataArgs(id, object) + ")"); + failedFiles.put(object.getKey(), new FileRevision(object.getETag(), object.getVersionId())); + } + } + token = page.isTruncated() ? page.nextContinuationToken() : null; + } while (token != null); + return count; + } + + private static String fileMetadataArgs(long id, S3Object object) { + String modified = object.getLastModified() == null + ? "NULL" + : PostgresWire.quoteLiteral(object.getLastModified().toString()) + "::timestamptz"; + return id + ", " + PostgresWire.quoteLiteral(object.getKey()) + ", " + + literal(object.getETag()) + ", " + literal(object.getVersionId()) + ", " + + object.getSize() + ", " + modified; + } + + private static void rollbackFileSavepoint(CopyBackendSession backend, String savepoint, + Exception cause) throws IOException { + try { + backend.recover(); + backend.execute("ROLLBACK TO SAVEPOINT " + savepoint); + backend.execute("RELEASE SAVEPOINT " + savepoint); + } catch (IOException | RuntimeException recoveryFailure) { + IOException failure = new IOException("Unable to recover failed COPY job file", recoveryFailure); + failure.addSuppressed(cause); + throw failure; + } + } + + static CopyStatementParser.S3CopyFrom forObject(CopyStatementParser.S3CopyFrom copy, String key) { + return new CopyStatementParser.S3CopyFrom(copy.targetTable(), copy.columns(), copy.bucket(), key, + copy.delimiter(), copy.headerLines(), copy.gzip(), copy.csv(), copy.nullAs(), copy.iamRoleArn(), + copy.jsonAuto(), copy.jsonAutoIgnoreCase(), copy.manifest(), copy.transforms(), + copy.defaultIamRoleRequested(), copy.accessKeys()); + } + + private static String literal(String value) { + return value == null ? "NULL" : PostgresWire.quoteLiteral(value); + } + + private static String identifier(String value) { + return "\"" + value.replace("\"", "\"\"") + "\""; + } +} diff --git a/src/main/java/io/floci/aws/services/redshift/proxy/CopyJobSql.java b/src/main/java/io/floci/aws/services/redshift/proxy/CopyJobSql.java index 4bac6b8cc5..075597a816 100644 --- a/src/main/java/io/floci/aws/services/redshift/proxy/CopyJobSql.java +++ b/src/main/java/io/floci/aws/services/redshift/proxy/CopyJobSql.java @@ -17,6 +17,15 @@ public final class CopyJobSql { private CopyJobSql() { } + public static String runName(String sql) { + if (sql == null || RedshiftAuditSql.statements(sql).size() != 1) { + return null; + } + List tokens = RedshiftAuditSql.tokens(RedshiftAuditSql.statements(sql).getFirst()); + return tokens.size() == 4 && tokens.get(0).keyword("COPY") && tokens.get(1).keyword("JOB") + && tokens.get(2).keyword("RUN") && isName(tokens.get(3)) ? tokens.get(3).identifier() : null; + } + /** Identifies job clauses outside strings, quoted identifiers and comments. */ public static boolean matches(String sql) { return sql != null && RedshiftAuditSql.statements(sql).stream() @@ -103,7 +112,8 @@ public final class CopyJobSql { ? "CALL floci_internal.alter_copy_job(" + PostgresWire.quoteLiteral(arguments.getFirst().identifier()) + ", " + arguments.get(2).keyword("ON") + ")" : reject("42601", "COPY JOB ALTER needs a job name and AUTO ON or AUTO OFF"); - case "RUN" -> reject("0A000", "COPY JOB RUN is not supported"); + case "RUN" -> hasName && arguments.size() == 1 ? sql + : reject("42601", "COPY JOB RUN needs a job name"); default -> reject("42601", "Unknown COPY JOB command"); }; } diff --git a/src/main/java/io/floci/aws/services/redshift/proxy/CopyStatementParser.java b/src/main/java/io/floci/aws/services/redshift/proxy/CopyStatementParser.java index 9b67f69927..ad147055ea 100644 --- a/src/main/java/io/floci/aws/services/redshift/proxy/CopyStatementParser.java +++ b/src/main/java/io/floci/aws/services/redshift/proxy/CopyStatementParser.java @@ -14,12 +14,24 @@ import java.util.regex.Pattern; */ public final class CopyStatementParser { - public sealed interface S3Statement permits S3CopyFrom, S3Unload { + public sealed interface S3Statement permits S3CopyFrom, S3Unload, S3CopyJobRun { String iamRoleArn(); boolean defaultIamRoleRequested(); } + public record S3CopyJobRun(String name) implements S3Statement { + @Override + public String iamRoleArn() { + return null; + } + + @Override + public boolean defaultIamRoleRequested() { + return false; + } + } + /** Access keys a COPY names, as {@code CREDENTIALS 'aws_access_key_id=...'} or {@code ACCESS_KEY_ID}. */ public record AccessKeys(String accessKeyId, String secretAccessKey, String sessionToken) { // Keeps the secret and token out of logs and error messages that print the statement @@ -419,6 +431,10 @@ public final class CopyStatementParser { } public static S3Statement parse(String sql, String defaultIamRoleArn) { + String job = CopyJobSql.runName(sql); + if (job != null) { + return new S3CopyJobRun(job); + } if (sql == null || sql.isBlank()) { return null; } diff --git a/src/main/java/io/floci/aws/services/redshift/proxy/ExtendedS3Exchange.java b/src/main/java/io/floci/aws/services/redshift/proxy/ExtendedS3Exchange.java index 62e3ff0858..0861d250b1 100644 --- a/src/main/java/io/floci/aws/services/redshift/proxy/ExtendedS3Exchange.java +++ b/src/main/java/io/floci/aws/services/redshift/proxy/ExtendedS3Exchange.java @@ -44,6 +44,8 @@ final class ExtendedS3Exchange { boolean failed = true; try { failed = !switch (statement) { + case CopyStatementParser.S3CopyJobRun run -> runEtlCopy(client, backend, executeFrame, run, + s3Service, iamService, clusterAccountId, iamRoleArns, coordinator, copyBackend); case CopyStatementParser.S3CopyFrom copy -> runEtlCopy(client, backend, executeFrame, copy, s3Service, iamService, clusterAccountId, iamRoleArns, coordinator, copyBackend); case CopyStatementParser.S3Unload unload -> runOwnedUnload(client, backend, executeFrame, unload, @@ -153,7 +155,7 @@ final class ExtendedS3Exchange { } private static boolean runEtlCopy(Socket client, Socket backend, - PostgresWireDecoder.FrontendMessage executeFrame, CopyStatementParser.S3CopyFrom spec, + PostgresWireDecoder.FrontendMessage executeFrame, CopyStatementParser.S3Statement spec, S3Service s3, IamService iam, String account, List roles, BackendResponseCoordinator coordinator, CopyBackendSession copyBackend) throws IOException { OutputStream output = backend.getOutputStream(); diff --git a/src/main/java/io/floci/aws/services/redshift/proxy/RedshiftInterceptingBridge.java b/src/main/java/io/floci/aws/services/redshift/proxy/RedshiftInterceptingBridge.java index 4bc7843bce..e580f0d910 100644 --- a/src/main/java/io/floci/aws/services/redshift/proxy/RedshiftInterceptingBridge.java +++ b/src/main/java/io/floci/aws/services/redshift/proxy/RedshiftInterceptingBridge.java @@ -316,6 +316,9 @@ public class RedshiftInterceptingBridge { if (parsed != null) { CopyStatementParser.S3Statement statement = parsed; boolean intercepted = runWithBackendOwned(() -> switch (statement) { + case CopyStatementParser.S3CopyJobRun run -> CopyEtlLoader.runSimple( + client, backend, run, s3Service, iamService, clusterAccountId, iamRoleArns, + coordinator.lastReadyStatus(), status -> coordinator.onBackendFrame('Z', new byte[]{(byte) status})); case CopyStatementParser.S3CopyFrom copy -> S3CopySimulator.runCopyFrom( client, backend, copy, s3Service, iamService, clusterAccountId, iamRoleArns, coordinator.lastReadyStatus(), status -> coordinator.onBackendFrame('Z', new byte[]{(byte) status})); @@ -394,7 +397,7 @@ public class RedshiftInterceptingBridge { coordinator.register(BackendResponseCoordinator.Operation.PARSE, mutation); String rewritten = parse.sql(); - if (statement instanceof CopyStatementParser.S3CopyFrom copy) { + if (statement instanceof CopyStatementParser.S3CopyFrom || statement instanceof CopyStatementParser.S3CopyJobRun) { rewritten = "DO $$BEGIN NULL; END$$"; } else if (statement instanceof CopyStatementParser.S3Unload unload) { rewritten = S3CopySimulator.unloadBackendSql(unload); @@ -660,7 +663,7 @@ public class RedshiftInterceptingBridge { } private CopyStatementParser.S3Statement parseS3Statement(String sql) { - if (CopyJobSql.matches(sql)) { + if (CopyJobSql.matches(sql) && CopyJobSql.runName(sql) == null) { return null; } try { diff --git a/src/main/java/io/floci/aws/services/redshift/proxy/S3CopySimulator.java b/src/main/java/io/floci/aws/services/redshift/proxy/S3CopySimulator.java index d1c9a218a7..2b27ddeca0 100644 --- a/src/main/java/io/floci/aws/services/redshift/proxy/S3CopySimulator.java +++ b/src/main/java/io/floci/aws/services/redshift/proxy/S3CopySimulator.java @@ -80,7 +80,18 @@ public final class S3CopySimulator { } record CopyInput(CopyStatementParser.S3CopyFrom spec, List keys, S3Service s3, - IamService iamService, RedshiftRoleAccess.RoleSession roleSession) { + IamService iamService, RedshiftRoleAccess.RoleSession roleSession, + String expectedETag, String versionId) { + S3Object readObject(String key) { + S3Object object = versionId != null + ? s3.getObject(spec.bucket(), key, versionId) + : s3.getObject(spec.bucket(), key); + if (expectedETag != null && (object == null || !expectedETag.equals(object.getETag()))) { + throw new S3TransferException(SQLSTATE_INTERNAL, + "S3 object s3://" + spec.bucket() + "/" + key + " changed during COPY", null); + } + return object; + } } interface UnloadCollector extends AutoCloseable { @@ -107,6 +118,11 @@ public final class S3CopySimulator { public String sqlState() { return sqlState; } + + /** Syntax or unsupported-feature states: retrying the same job cannot succeed until the job is fixed. */ + public static boolean isJobFailure(String sqlState) { + return sqlState != null && (sqlState.startsWith("42") || "0A000".equals(sqlState)); + } } static CopyInput prepareCopy(CopyStatementParser.S3CopyFrom spec, S3Service s3, IamService iamService) { @@ -121,12 +137,26 @@ public final class S3CopySimulator { static CopyInput prepareCopy(CopyStatementParser.S3CopyFrom spec, S3Service s3, IamService iamService, String clusterAccountId, List associatedRoleArns) { return asKeyAccount(spec, s3, iamService, - () -> prepareCopyScoped(spec, s3, iamService, clusterAccountId, associatedRoleArns)); + () -> prepareCopyScoped(spec, s3, iamService, clusterAccountId, associatedRoleArns, false, null, null)); + } + + static CopyInput prepareObjectCopy(CopyStatementParser.S3CopyFrom spec, S3Service s3, IamService iamService, + String clusterAccountId, List associatedRoleArns) { + return prepareObjectCopy(spec, s3, iamService, clusterAccountId, associatedRoleArns, null, null); + } + + static CopyInput prepareObjectCopy(CopyStatementParser.S3CopyFrom spec, S3Service s3, IamService iamService, + String clusterAccountId, List associatedRoleArns, + String expectedETag, String versionId) { + return asKeyAccount(spec, s3, iamService, + () -> prepareCopyScoped(spec, s3, iamService, clusterAccountId, associatedRoleArns, true, + expectedETag, versionId)); } private static CopyInput prepareCopyScoped(CopyStatementParser.S3CopyFrom spec, S3Service s3, IamService iamService, String clusterAccountId, - List associatedRoleArns) { + List associatedRoleArns, boolean exactObject, + String expectedETag, String versionId) { requireDefaultIamRole(spec); RedshiftRoleAccess.RoleSession roleSession = resolveCopySession(spec, s3, iamService, clusterAccountId, associatedRoleArns); @@ -134,7 +164,7 @@ public final class S3CopySimulator { try { if (spec.manifest()) { authorizeCopyObject(spec, s3, iamService, roleSession, spec.keyOrPrefix()); - } else { + } else if (!exactObject) { if (roleSession != null) { RedshiftRoleAccess.authorizeSessionAction(s3, iamService, roleSession, spec.iamRoleArn(), "s3:ListBucket", copyBucketArn(spec, s3), Map.of("s3:prefix", List.of(spec.keyOrPrefix()))); @@ -151,7 +181,7 @@ public final class S3CopySimulator { List keys; try { - keys = resolveKeys(spec, s3); + keys = exactObject ? List.of(spec.keyOrPrefix()) : resolveKeys(spec, s3); } catch (AwsException e) { throw new S3TransferException(SQLSTATE_INTERNAL, "S3 COPY could not list s3://" + spec.bucket() + "/" + spec.keyOrPrefix(), e); @@ -169,7 +199,7 @@ public final class S3CopySimulator { throw new S3TransferException(SQLSTATE_INSUFFICIENT_PRIVILEGE, "S3 access denied for s3://" + spec.bucket() + "/" + spec.keyOrPrefix(), e); } - return new CopyInput(spec, List.copyOf(keys), s3, iamService, roleSession); + return new CopyInput(spec, List.copyOf(keys), s3, iamService, roleSession, expectedETag, versionId); } catch (RuntimeException e) { RedshiftRoleAccess.releaseRoleSession(roleSession, spec.iamRoleArn(), iamService); throw e; @@ -252,8 +282,7 @@ public final class S3CopySimulator { String account = keyAccount(input.spec(), input.s3(), input.iamService()); try { RequestScopes.callAsChecked(account, () -> { - streamObjects(input.spec(), discoveredColumns, columnMaxBytes, columnKinds, input.s3(), - input.iamService(), input.roleSession(), input.keys(), backendOut); + streamObjects(input, discoveredColumns, columnMaxBytes, columnKinds, backendOut); return null; }); } catch (IOException | RuntimeException e) { @@ -564,10 +593,10 @@ public final class S3CopySimulator { return value.replace("'", "''"); } - private static void streamObjects(CopyStatementParser.S3CopyFrom spec, List discoveredColumns, + private static void streamObjects(CopyInput input, List discoveredColumns, List columnMaxBytes, List columnKinds, - S3Service s3, IamService iamService, RedshiftRoleAccess.RoleSession roleSession, - List keys, OutputStream backendOut) throws IOException { + OutputStream backendOut) throws IOException { + CopyStatementParser.S3CopyFrom spec = input.spec(); if (spec.transforms().truncateColumns() && columnMaxBytes == null) { // Extended Query fixes the statement at Parse time, so there is no catalog round trip to // learn column lengths; same limitation and remedy as FORMAT AS JSON 'auto'. @@ -581,9 +610,10 @@ public final class S3CopySimulator { + "available over the Simple Query protocol; connect with preferQueryMode=simple", null); } byte[] buffer = new byte[CHUNK]; + List keys = input.keys(); for (int i = 0; i < keys.size(); i++) { - authorizeCopyObject(spec, s3, iamService, roleSession, keys.get(i)); - S3Object object = s3.getObject(spec.bucket(), keys.get(i)); + authorizeCopyObject(spec, input.s3(), input.iamService(), input.roleSession(), keys.get(i)); + S3Object object = input.readObject(keys.get(i)); byte[] data = object != null && object.getData() != null ? object.getData() : new byte[0]; InputStream rawIn = new ByteArrayInputStream(data); try (InputStream in = CopySourceInputStream.open(rawIn, spec.gzip())) { diff --git a/src/main/java/io/floci/aws/services/redshiftdata/RedshiftCopyJobExecutor.java b/src/main/java/io/floci/aws/services/redshiftdata/RedshiftCopyJobExecutor.java new file mode 100644 index 0000000000..49a308195b --- /dev/null +++ b/src/main/java/io/floci/aws/services/redshiftdata/RedshiftCopyJobExecutor.java @@ -0,0 +1,198 @@ +package io.floci.aws.services.redshiftdata; + +import io.floci.aws.core.common.AwsArnUtils; +import io.floci.aws.core.common.AwsException; +import io.floci.aws.services.redshift.RedshiftService; +import io.floci.aws.services.redshift.RedshiftZeroEtlEndpoints; +import io.floci.aws.services.redshift.model.Cluster; +import io.floci.aws.services.redshift.model.Integration; +import io.floci.aws.services.redshift.proxy.S3CopySimulator.S3TransferException; +import io.floci.aws.services.redshiftserverless.RedshiftServerlessService.WorkgroupTarget; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import org.jboss.logging.Logger; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.List; + +@ApplicationScoped +public class RedshiftCopyJobExecutor { + private static final Logger LOG = Logger.getLogger(RedshiftCopyJobExecutor.class); + + private final RedshiftService service; + private final RedshiftZeroEtlEndpoints endpoints; + private final RedshiftDataConnectionFactory connections; + + private record TargetResolution(RedshiftDataResourceResolver.DatabaseTarget database, boolean unavailable) { + private static final TargetResolution MISSING = new TargetResolution(null, false); + private static final TargetResolution UNAVAILABLE = new TargetResolution(null, true); + } + + @Inject + RedshiftCopyJobExecutor(RedshiftService service, RedshiftZeroEtlEndpoints endpoints, + RedshiftDataConnectionFactory connections) { + this.service = service; + this.endpoints = endpoints; + this.connections = connections; + } + + /** Returns whether the bucket needs another sweep. */ + public boolean runAutomatic(Integration integration) { + return apply(integration, false); + } + + public void disable(Integration integration) { + apply(integration, true); + } + + private boolean apply(Integration integration, boolean disable) { + TargetResolution resolution = target(integration, disable); + RedshiftDataResourceResolver.DatabaseTarget target = resolution.database(); + if (target == null) { + return !disable && resolution.unavailable(); + } + boolean retry = false; + try (Connection connection = connections.open(target)) { + List databases = new ArrayList<>(); + try (Statement statement = connection.createStatement(); ResultSet rows = statement.executeQuery( + "SELECT datname FROM pg_database WHERE datallowconn AND NOT datistemplate AND datname <> 'postgres'")) { + while (rows.next()) { + databases.add(rows.getString(1)); + } + } + for (String database : databases) { + RedshiftDataResourceResolver.DatabaseTarget databaseTarget = new RedshiftDataResourceResolver.DatabaseTarget( + target.arn(), target.host(), target.port(), database, target.user(), target.password()); + try (Connection databaseConnection = connections.open(databaseTarget)) { + retry |= applyToDatabase(databaseConnection, integration, disable); + } catch (SQLException exception) { + if (!"42P01".equals(exception.getSQLState()) && !"3F000".equals(exception.getSQLState())) { + if (disable) { + throw exception; + } + retry = true; + LOG.warnv(exception, "S3 auto-copy failed in database {0} for integration {1}; will retry", + database, integration.getIntegrationArn()); + } + } + } + } catch (SQLException exception) { + throw new AwsException("InternalFailure", "Could not process Redshift S3 copy jobs: " + + exception.getMessage(), 500); + } + return retry; + } + + private static boolean applyToDatabase(Connection connection, Integration integration, boolean disable) + throws SQLException { + String bucket = AwsArnUtils.parse(integration.getSourceArn()).resource(); + if (disable) { + try (PreparedStatement statement = connection.prepareStatement( + "UPDATE floci_internal.copy_job SET is_auto = false WHERE bucket = ?")) { + statement.setString(1, bucket); + statement.executeUpdate(); + } + return false; + } + List jobs = new ArrayList<>(); + try (PreparedStatement statement = connection.prepareStatement( + "SELECT job_name FROM floci_internal.copy_job WHERE is_auto AND bucket = ?")) { + statement.setString(1, bucket); + try (ResultSet rows = statement.executeQuery()) { + while (rows.next()) { + jobs.add(rows.getString(1)); + } + } + } + boolean retry = false; + for (String job : jobs) { + retry |= runAutomaticJob(connection, job); + } + return retry; + } + + private static boolean runAutomaticJob(Connection connection, String job) throws SQLException { + connection.setAutoCommit(false); + boolean retry = false; + try { + try (PreparedStatement lock = connection.prepareStatement( + "SELECT 1 FROM floci_internal.copy_job WHERE job_name = ? AND is_auto FOR UPDATE")) { + lock.setQueryTimeout(5); + lock.setString(1, job); + try (ResultSet row = lock.executeQuery()) { + if (row.next()) { + try (Statement statement = connection.createStatement()) { + statement.execute("COPY JOB RUN \"" + job.replace("\"", "\"\"") + "\""); + } + } + } + } + connection.commit(); + } catch (SQLException exception) { + connection.rollback(); + if (S3TransferException.isJobFailure(exception.getSQLState())) { + LOG.warnv(exception, "Automatic COPY job {0} failed and will run again on the next upload", job); + } else { + LOG.warnv(exception, "Automatic COPY job {0} failed; its files will be retried", job); + retry = true; + } + } + connection.setAutoCommit(true); + return retry; + } + + private TargetResolution target(Integration integration, boolean disable) { + if (RedshiftZeroEtlEndpoints.isNamespaceArn(integration.getTargetArn())) { + WorkgroupTarget workgroup; + try { + workgroup = endpoints.targetWorkgroup(integration.getAccountId(), integration.getTargetArn()); + } catch (AwsException exception) { + if ("ResourceNotFoundException".equals(exception.getErrorCode())) { + LOG.debugv("Target namespace not found for S3 integration {0}", integration.getIntegrationArn()); + return TargetResolution.MISSING; + } + if ("ValidationException".equals(exception.getErrorCode())) { + LOG.debugv("Workgroup target unavailable for S3 integration {0}: {1}", + integration.getIntegrationArn(), exception.getMessage()); + return TargetResolution.UNAVAILABLE; + } + throw exception; + } + if (workgroup == null || workgroup.host() == null || workgroup.port() <= 0 + || workgroup.endpoint() == null || workgroup.endpoint().getPort() <= 0) { + return TargetResolution.UNAVAILABLE; + } + return new TargetResolution(new RedshiftDataResourceResolver.DatabaseTarget(workgroup.arn(), "127.0.0.1", + workgroup.endpoint().getPort(), workgroup.database(), workgroup.masterUsername(), workgroup.masterPassword()), + false); + } + List clusters; + try { + clusters = service.describeClustersForAccount(integration.getAccountId(), + integration.getTargetClusterIdentifier()); + } catch (AwsException exception) { + if ("ClusterNotFound".equals(exception.getErrorCode())) { + LOG.debugv("Target cluster not found for S3 integration {0}", integration.getIntegrationArn()); + return TargetResolution.MISSING; + } + throw exception; + } + if (clusters.isEmpty()) { + return TargetResolution.MISSING; + } + Cluster cluster = clusters.getFirst(); + if (!"available".equals(cluster.getClusterStatus()) || cluster.getProxyPort() <= 0) { + if (disable) { + throw new AwsException("InvalidClusterState", "Resume the cluster before deleting its S3 integration.", 400); + } + return TargetResolution.UNAVAILABLE; + } + return new TargetResolution(new RedshiftDataResourceResolver.DatabaseTarget(integration.getTargetArn(), + "127.0.0.1", cluster.getProxyPort(), "dev", cluster.getMasterUsername(), cluster.getMasterPassword()), false); + } +} diff --git a/src/main/resources/redshift/bootstrap-catalog.sql b/src/main/resources/redshift/bootstrap-catalog.sql index 85041161aa..0d08007e97 100644 --- a/src/main/resources/redshift/bootstrap-catalog.sql +++ b/src/main/resources/redshift/bootstrap-catalog.sql @@ -435,6 +435,94 @@ BEGIN END; $$; +CREATE TABLE IF NOT EXISTS floci_internal.copy_job_detail ( + job_id bigint NOT NULL REFERENCES floci_internal.copy_job(job_id) ON DELETE CASCADE, + bucket text NOT NULL, + key text NOT NULL, + etag text, + version_id text, + file_size bigint NOT NULL DEFAULT 0, + modification_time timestamptz NOT NULL DEFAULT clock_timestamp(), + status character(1) NOT NULL DEFAULT 'I', + loaded_at timestamptz NOT NULL DEFAULT clock_timestamp(), + PRIMARY KEY (job_id, bucket, key) +); + +CREATE OR REPLACE FUNCTION floci_internal.copy_job_for_run(name text) +RETURNS SETOF floci_internal.copy_job +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$ +BEGIN + RETURN QUERY SELECT j.* FROM floci_internal.copy_job j + WHERE j.job_name = $1 AND (j.owner = session_user OR (SELECT rolsuper FROM pg_roles WHERE rolname = session_user)) + FOR UPDATE; +END; +$$; + +CREATE OR REPLACE FUNCTION floci_internal.copy_job_loaded_keys(id bigint) +RETURNS TABLE(key text, status character(1), etag text, version_id text) +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$ +BEGIN + RETURN QUERY SELECT d.key, d.status, d.etag, d.version_id FROM floci_internal.copy_job_detail d + JOIN floci_internal.copy_job j ON j.job_id = d.job_id + WHERE d.job_id = $1 AND (j.owner = session_user OR (SELECT rolsuper FROM pg_roles WHERE rolname = session_user)); +END; +$$; + +CREATE OR REPLACE FUNCTION floci_internal.reserve_copy_job_file( + id bigint, key text, etag text, version_id text, file_size bigint DEFAULT 0, modification_time timestamptz DEFAULT NULL) +RETURNS boolean +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$ +DECLARE + source_bucket text; +BEGIN + SELECT j.bucket INTO source_bucket FROM floci_internal.copy_job j + WHERE j.job_id = $1 AND (j.owner = session_user OR (SELECT rolsuper FROM pg_roles WHERE rolname = session_user)) + FOR UPDATE; + IF NOT FOUND THEN + RAISE EXCEPTION 'Copy job does not exist' USING ERRCODE = '42704'; + END IF; + INSERT INTO floci_internal.copy_job_detail (job_id, bucket, key, etag, version_id, file_size, modification_time, status, loaded_at) + VALUES ($1, source_bucket, $2, $3, $4, COALESCE($5, 0), COALESCE($6, clock_timestamp()), 'I', clock_timestamp()) + ON CONFLICT ON CONSTRAINT copy_job_detail_pkey DO UPDATE + SET etag = EXCLUDED.etag, + version_id = EXCLUDED.version_id, + file_size = EXCLUDED.file_size, + modification_time = EXCLUDED.modification_time, + status = 'I', + loaded_at = clock_timestamp() + WHERE floci_internal.copy_job_detail.status = 'E' + AND (floci_internal.copy_job_detail.etag IS DISTINCT FROM EXCLUDED.etag + OR floci_internal.copy_job_detail.version_id IS DISTINCT FROM EXCLUDED.version_id); + RETURN FOUND; +END; +$$; + +CREATE OR REPLACE FUNCTION floci_internal.record_copy_job_file_error( + id bigint, key text, etag text, version_id text, file_size bigint DEFAULT 0, modification_time timestamptz DEFAULT NULL) +RETURNS void +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$ +DECLARE + source_bucket text; +BEGIN + SELECT j.bucket INTO source_bucket FROM floci_internal.copy_job j + WHERE j.job_id = $1 AND (j.owner = session_user OR (SELECT rolsuper FROM pg_roles WHERE rolname = session_user)) + FOR UPDATE; + IF NOT FOUND THEN + RAISE EXCEPTION 'Copy job does not exist' USING ERRCODE = '42704'; + END IF; + INSERT INTO floci_internal.copy_job_detail (job_id, bucket, key, etag, version_id, file_size, modification_time, status, loaded_at) + VALUES ($1, source_bucket, $2, $3, $4, COALESCE($5, 0), COALESCE($6, clock_timestamp()), 'E', clock_timestamp()) + ON CONFLICT ON CONSTRAINT copy_job_detail_pkey DO UPDATE + SET etag = EXCLUDED.etag, + version_id = EXCLUDED.version_id, + file_size = EXCLUDED.file_size, + modification_time = EXCLUDED.modification_time, + status = 'E', + loaded_at = clock_timestamp() + WHERE floci_internal.copy_job_detail.status <> 'I'; +END; +$$; + CREATE OR REPLACE PROCEDURE floci_internal.create_copy_job( name text, iam_role text, job_text text, is_auto boolean, target_table text, bucket text, prefix text) LANGUAGE plpgsql SECURITY INVOKER AS $$ @@ -503,6 +591,23 @@ SELECT j.job_id::bigint AS job_id, FROM floci_internal.copy_job j WHERE j.owner = session_user OR (SELECT rolsuper FROM pg_roles WHERE rolname = session_user); +CREATE OR REPLACE VIEW pg_catalog.sys_copy_job_detail AS +SELECT COALESCE((SELECT u.usesysid::integer FROM pg_catalog.pg_user u WHERE u.usename = j.owner), 0) AS user_id, + current_database()::text AS database_name, + j.job_id::bigint AS job_id, + j.job_name::text AS job_name, + ('s3://' || j.bucket || '/' || j.prefix)::text AS file_location, + d.key::text AS file_name, + d.file_size::bigint AS file_size, + COALESCE(d.etag, '')::text AS file_etag, + left(j.job_text, 256)::character(256) AS job_text, + (d.modification_time AT TIME ZONE 'UTC')::timestamp without time zone AS modification_time, + (d.loaded_at AT TIME ZONE 'UTC')::timestamp without time zone AS enqueue_time, + d.status::character(1) AS status +FROM floci_internal.copy_job_detail d +JOIN floci_internal.copy_job j ON j.job_id = d.job_id +WHERE j.owner = session_user OR (SELECT rolsuper FROM pg_roles WHERE rolname = session_user); + GRANT USAGE ON SCHEMA pg_catalog TO PUBLIC; GRANT USAGE ON SCHEMA floci_internal TO PUBLIC; -- Schema access for COPY JOB must not expose the unrelated privileged catalog writers. diff --git a/src/test/java/io/floci/aws/services/redshift/RedshiftS3AutoCopyConsumerTest.java b/src/test/java/io/floci/aws/services/redshift/RedshiftS3AutoCopyConsumerTest.java new file mode 100644 index 0000000000..82c4153d82 --- /dev/null +++ b/src/test/java/io/floci/aws/services/redshift/RedshiftS3AutoCopyConsumerTest.java @@ -0,0 +1,128 @@ +package io.floci.aws.services.redshift; + +import io.floci.aws.core.common.AwsArnUtils; +import io.floci.aws.services.redshift.model.Integration; +import io.floci.aws.services.redshiftdata.RedshiftCopyJobExecutor; +import io.floci.aws.services.s3.model.S3ObjectUpdatedEvent; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; + +import java.util.List; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; + +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.*; + +class RedshiftS3AutoCopyConsumerTest { + @Test + @Timeout(10) + void observingAnUploadDoesNotWaitForAnActiveCopy() throws Exception { + RedshiftService service = mock(RedshiftService.class); + RedshiftCopyJobExecutor writer = mock(RedshiftCopyJobExecutor.class); + Integration integration = integration("active", "active"); + when(service.listS3AutoCopyIntegrations()).thenReturn(List.of(integration)); + CountDownLatch copying = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + doAnswer(invocation -> { + copying.countDown(); + assertTrue(release.await(5, TimeUnit.SECONDS)); + return null; + }).when(writer).runAutomatic(integration); + RedshiftS3AutoCopyConsumer consumer = new RedshiftS3AutoCopyConsumer(service, writer, false, 1); + CompletableFuture poll = CompletableFuture.runAsync(consumer::pollOnce); + try { + assertTrue(copying.await(5, TimeUnit.SECONDS)); + consumer.updated(new S3ObjectUpdatedEvent("bucket", "key")); + } finally { + release.countDown(); + poll.get(5, TimeUnit.SECONDS); + } + } + + @Test + void processesActiveIntegrationsAndContinuesAfterAFailedTarget() { + RedshiftService service = mock(RedshiftService.class); + RedshiftCopyJobExecutor writer = mock(RedshiftCopyJobExecutor.class); + Integration failed = integration("failed", "active"); + Integration healthy = integration("healthy", "active"); + Integration inactive = integration("inactive", "creating"); + when(service.listS3AutoCopyIntegrations()).thenReturn(List.of(failed, inactive, healthy)); + doThrow(new IllegalStateException("Target unavailable")).when(writer).runAutomatic(failed); + RedshiftS3AutoCopyConsumer consumer = new RedshiftS3AutoCopyConsumer(service, writer, false, 1); + consumer.pollOnce(); + verify(writer).runAutomatic(failed); + verify(writer).runAutomatic(healthy); + verify(writer, never()).runAutomatic(inactive); + consumer.beforeReset(); + consumer.pollOnce(); + verify(writer, times(1)).runAutomatic(healthy); + consumer.clear(); + consumer.afterReset(); + consumer.pollOnce(); + verify(writer, times(2)).runAutomatic(healthy); + } + + @Test + void deletionDisablesJobsWithoutDroppingTheirMetadata() { + RedshiftService service = mock(RedshiftService.class); + RedshiftCopyJobExecutor writer = mock(RedshiftCopyJobExecutor.class); + RedshiftS3AutoCopyConsumer consumer = new RedshiftS3AutoCopyConsumer(service, writer, false, 1); + Integration integration = integration("deleted", "active"); + consumer.disable(integration); + verify(writer).disable(integration); + verifyNoMoreInteractions(writer); + } + + @Test + void timerSkipsIdleTicksAfterInitialReconciliationAndEventsTargetMatchingBucket() { + RedshiftService service = mock(RedshiftService.class); + RedshiftCopyJobExecutor writer = mock(RedshiftCopyJobExecutor.class); + Integration first = integration("first", "active"); + first.setSourceArn("arn:aws:s3:::bucket-a"); + Integration second = integration("second", "active"); + second.setSourceArn("arn:aws:s3:::bucket-b"); + when(service.listS3AutoCopyIntegrations()).thenReturn(List.of(first, second)); + RedshiftS3AutoCopyConsumer consumer = new RedshiftS3AutoCopyConsumer(service, writer, false, 1); + consumer.pollOnce(); + verify(writer, times(1)).runAutomatic(first); + verify(writer, times(1)).runAutomatic(second); + consumer.pollOnce(); + verifyNoMoreInteractions(writer); + + consumer.updated(new S3ObjectUpdatedEvent("bucket-a", "key")); + consumer.pollOnce(); + verify(writer, times(2)).runAutomatic(first); + verify(writer, times(1)).runAutomatic(second); + } + + @Test + void retriesMarkedBucketWithoutAnotherUploadAndStopsAfterSuccess() { + RedshiftService service = mock(RedshiftService.class); + RedshiftCopyJobExecutor writer = mock(RedshiftCopyJobExecutor.class); + Integration retry = integration("retry", "active"); + Integration healthy = integration("healthy", "active"); + healthy.setSourceArn("arn:aws:s3:::other-bucket"); + when(service.listS3AutoCopyIntegrations()).thenReturn(List.of(retry, healthy)); + when(writer.runAutomatic(retry)).thenReturn(true, false); + RedshiftS3AutoCopyConsumer consumer = new RedshiftS3AutoCopyConsumer(service, writer, false, 1); + + consumer.pollOnce(); + consumer.pollOnce(); + consumer.pollOnce(); + + verify(writer, times(2)).runAutomatic(retry); + verify(writer).runAutomatic(healthy); + } + + private static Integration integration(String name, String status) { + Integration integration = new Integration(); + integration.setAccountId("123456789012"); + integration.setIntegrationArn(AwsArnUtils.Arn.of("redshift", "us-east-1", "123456789012", + "integration:" + name).toString()); + integration.setStatus(status); + integration.setSourceArn("arn:aws:s3:::bucket"); + return integration; + } +} diff --git a/src/test/java/io/floci/aws/services/redshift/RedshiftS3AutoCopyIntegrationTest.java b/src/test/java/io/floci/aws/services/redshift/RedshiftS3AutoCopyIntegrationTest.java new file mode 100644 index 0000000000..ebe22ce8c2 --- /dev/null +++ b/src/test/java/io/floci/aws/services/redshift/RedshiftS3AutoCopyIntegrationTest.java @@ -0,0 +1,151 @@ +package io.floci.aws.services.redshift; + +import io.floci.aws.services.iam.IamService; +import io.floci.aws.services.redshift.model.Cluster; +import io.floci.aws.testing.DockerAvailability; +import io.quarkus.test.common.http.TestHTTPResource; +import io.quarkus.test.junit.QuarkusTest; +import jakarta.inject.Inject; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; +import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; +import software.amazon.awssdk.core.sync.RequestBody; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.redshift.RedshiftClient; +import software.amazon.awssdk.services.s3.S3Client; + +import java.net.URI; +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.List; +import java.util.UUID; + +import static org.junit.jupiter.api.Assertions.*; + +@QuarkusTest +class RedshiftS3AutoCopyIntegrationTest { + @Inject + RedshiftService service; + @Inject + IamService iam; + @Inject + RedshiftS3AutoCopyConsumer consumer; + @TestHTTPResource + URI endpoint; + + @BeforeAll + static void requireDocker() throws InterruptedException { + Assumptions.assumeTrue(DockerAvailability.isAvailable(), "Docker is required for Redshift auto-copy"); + } + + @ParameterizedTest + @ValueSource(strings = {"simple", "extended"}) + void sdkUploadsAreLoadedOnceAndDeletionPreservesManualExecution(String mode) throws Exception { + String id = "auto-copy-" + UUID.randomUUID().toString().substring(0, 8); + String roleName = "AutoCopy" + UUID.randomUUID().toString().replace("-", ""); + String role = iam.createRole(roleName, "/", """ + {"Version":"2012-10-17","Statement":[{"Effect":"Allow", + "Principal":{"Service":"redshift.amazonaws.com"},"Action":"sts:AssumeRole"}]} + """, null, 0, null).getArn(); + iam.putRolePolicy(roleName, "S3", """ + {"Version":"2012-10-17","Statement":[{"Effect":"Allow", + "Action":["s3:GetObject","s3:ListBucket"],"Resource":"*"}]} + """); + Cluster cluster = service.createCluster(id, "dc2.large", "admin", "Secret123", null, List.of(), List.of(role)); + StaticCredentialsProvider credentials = StaticCredentialsProvider.create(AwsBasicCredentials.create("test", "test")); + try (S3Client s3 = S3Client.builder().endpointOverride(endpoint).region(Region.US_EAST_1) + .credentialsProvider(credentials).forcePathStyle(true).build(); + RedshiftClient redshift = RedshiftClient.builder().endpointOverride(endpoint).region(Region.US_EAST_1) + .credentialsProvider(credentials).build(); + Connection connection = RedshiftConnections.waitForConnection(RedshiftConnections.jdbcUrl(cluster) + + "?preferQueryMode=" + mode, "admin", "Secret123"); + Statement statement = connection.createStatement()) { + s3.createBucket(request -> request.bucket(id)); + put(s3, id, "prefix/old", "99\n"); + statement.execute("CREATE TABLE events (id integer)"); + statement.execute("COPY events FROM 's3://" + id + "/prefix/' IAM_ROLE '" + role + "' JOB CREATE ingest"); + String integration = redshift.createIntegration(request -> request.integrationName(id) + .sourceArn("arn:aws:s3:::" + id).targetArn("arn:aws:redshift:us-east-1:000000000000:cluster:" + id)) + .integrationArn(); + try { + put(s3, id, "elsewhere/ignored", "98\n"); + put(s3, id, "prefix/first", "1\n"); + consumer.pollOnce(); + assertEquals(1, count(statement, "events")); + put(s3, id, "prefix/first", "2\n"); + consumer.pollOnce(); + consumer.clear(); + consumer.pollOnce(); + assertEquals(1, count(statement, "events")); + assertEquals(1, count(statement, "floci_internal.copy_job_detail")); + } finally { + redshift.deleteIntegration(request -> request.integrationArn(integration)); + } + try (ResultSet job = statement.executeQuery("COPY JOB SHOW ingest")) { + assertTrue(job.next()); + assertEquals(0, job.getInt("is_auto")); + } + put(s3, id, "prefix/second", "3\n"); + consumer.pollOnce(); + assertEquals(1, count(statement, "events")); + connection.setAutoCommit(false); + statement.execute("COPY JOB RUN ingest"); + assertEquals(2, count(statement, "events")); + connection.rollback(); + connection.setAutoCommit(true); + assertEquals(1, count(statement, "events")); + statement.execute("COPY JOB RUN ingest"); + assertEquals(2, count(statement, "events")); + put(s3, id, "prefix/bad", "invalid\n"); + put(s3, id, "prefix/good", "4\n"); + statement.execute("COPY JOB RUN ingest"); + assertEquals(3, count(statement, "events")); + assertEquals(4, count(statement, "floci_internal.copy_job_detail")); + assertEquals("E", fileStatus(statement, "prefix/bad")); + assertEquals("I", fileStatus(statement, "prefix/good")); + put(s3, id, "prefix/bad", "5\n"); + statement.execute("COPY JOB RUN ingest"); + assertEquals(4, count(statement, "events")); + assertEquals("I", fileStatus(statement, "prefix/bad")); + statement.execute("COPY JOB DROP ingest"); + assertEquals(0, count(statement, "floci_internal.copy_job_detail")); + + statement.execute("CREATE USER blocked_owner PASSWORD 'Secret123'"); + statement.execute("SET SESSION AUTHORIZATION blocked_owner"); + statement.execute("COPY public.events FROM 's3://" + id + "/protected/' IAM_ROLE '" + + role + "' JOB CREATE blocked_job AUTO OFF"); + statement.execute("RESET SESSION AUTHORIZATION"); + put(s3, id, "protected/file", "6\n"); + SQLException denied = assertThrows(SQLException.class, () -> statement.execute("COPY JOB RUN blocked_job")); + assertEquals("42501", denied.getSQLState()); + assertEquals(4, count(statement, "events")); + assertEquals(0, count(statement, "floci_internal.copy_job_detail")); + } finally { + service.deleteCluster(id); + } + } + + private static void put(S3Client client, String bucket, String key, String body) { + client.putObject(request -> request.bucket(bucket).key(key), RequestBody.fromString(body)); + } + + private static long count(Statement statement, String table) throws SQLException { + try (ResultSet rows = statement.executeQuery("SELECT count(*) FROM " + table)) { + assertTrue(rows.next()); + return rows.getLong(1); + } + } + + private static String fileStatus(Statement statement, String fileName) throws SQLException { + try (ResultSet rows = statement.executeQuery( + "SELECT status FROM sys_copy_job_detail WHERE file_name = '" + fileName + "'")) { + assertTrue(rows.next()); + return rows.getString(1).trim(); + } + } +} diff --git a/src/test/java/io/floci/aws/services/redshift/RedshiftS3EventIntegrationTest.java b/src/test/java/io/floci/aws/services/redshift/RedshiftS3EventIntegrationTest.java index ac62e05b2c..456d55194d 100644 --- a/src/test/java/io/floci/aws/services/redshift/RedshiftS3EventIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/redshift/RedshiftS3EventIntegrationTest.java @@ -14,6 +14,9 @@ import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.redshift.RedshiftClient; +import software.amazon.awssdk.services.redshift.model.CreateIntegrationResponse; +import software.amazon.awssdk.services.redshift.model.DeleteIntegrationResponse; +import software.amazon.awssdk.services.redshift.model.DescribeIntegrationsResponse; import software.amazon.awssdk.services.redshift.model.RedshiftException; import java.net.URI; @@ -22,6 +25,7 @@ import java.util.List; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.not; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertThrows; @QuarkusTest @@ -126,6 +130,22 @@ class RedshiftS3EventIntegrationTest { assertEquals(400, error.statusCode()); assertEquals("InvalidParameterValue", error.awsErrorDetails().errorCode()); } + CreateIntegrationResponse createdIntegration = client.createIntegration( + request -> request.integrationName("s3-sdk-roundtrip") + .sourceArn("arn:aws:s3:::" + BUCKET).targetArn(namespaceArn)); + assertNotNull(createdIntegration.integrationArn()); + assertEquals("s3-sdk-roundtrip", createdIntegration.integrationName()); + assertEquals("arn:aws:s3:::" + BUCKET, createdIntegration.sourceArn()); + assertEquals(namespaceArn, createdIntegration.targetArn()); + assertEquals("active", createdIntegration.statusAsString()); + DescribeIntegrationsResponse described = client.describeIntegrations( + request -> request.integrationArn(createdIntegration.integrationArn())); + assertEquals(1, described.integrations().size()); + assertEquals(createdIntegration.integrationArn(), described.integrations().getFirst().integrationArn()); + DeleteIntegrationResponse deletedIntegration = client.deleteIntegration( + request -> request.integrationArn(createdIntegration.integrationArn())); + assertEquals(createdIntegration.integrationArn(), deletedIntegration.integrationArn()); + assertEquals("s3-sdk-roundtrip", deletedIntegration.integrationName()); } } diff --git a/src/test/java/io/floci/aws/services/redshift/RedshiftServiceTest.java b/src/test/java/io/floci/aws/services/redshift/RedshiftServiceTest.java index 57d7180952..9522039725 100644 --- a/src/test/java/io/floci/aws/services/redshift/RedshiftServiceTest.java +++ b/src/test/java/io/floci/aws/services/redshift/RedshiftServiceTest.java @@ -898,6 +898,7 @@ class RedshiftServiceTest { private RedshiftServerlessService zeroEtlServerless; private EmulatorConfig config; private S3Service zeroEtlS3; + private RedshiftS3AutoCopyConsumer autoCopyConsumer; private RedshiftService service; @BeforeEach @@ -971,10 +972,12 @@ class RedshiftServiceTest { zeroEtlServerless = mock(RedshiftServerlessService.class); zeroEtlS3 = mock(S3Service.class); when(zeroEtlS3.ownsBucket(any())).thenReturn(true); + autoCopyConsumer = mock(RedshiftS3AutoCopyConsumer.class); service = new RedshiftService(sf, cm, config, regionResolver, proxyManager, dockerHostResolver, credentialBroker, secretsManagerService, mapper, new DynamoDbApiStreamReader(streams, CheckpointLifetime.PROCESS), null, events, integrationEvents, - new RedshiftZeroEtlEndpoints(zeroEtlDynamoDb, zeroEtlServerless, zeroEtlS3, regionResolver)); + new RedshiftZeroEtlEndpoints(zeroEtlDynamoDb, zeroEtlServerless, zeroEtlS3, regionResolver), + autoCopyConsumer); } private static final String ORDERS_TABLE_ARN = "arn:aws:dynamodb:us-east-1:111111111111:table/orders"; @@ -1322,6 +1325,25 @@ class RedshiftServiceTest { verify(integrationEvents, never()).queue(any(), any(), any(), any()); } + @Test + void deletingAnS3IntegrationDisablesJobsBeforeRemovingItsMetadata() { + Integration stored = new Integration(); + stored.setIntegrationArn("arn:aws:redshift:us-east-1:111111111111:integration:s3-one"); + stored.setSourceType("s3-event-notifications"); + when(integrationBackend.keys()).thenReturn(Set.of("s3-one")); + when(integrationBackend.get("s3-one")).thenReturn(Optional.of(stored)); + doThrow(new AwsException("InvalidClusterState", "Paused", 400)).when(autoCopyConsumer).disable(stored); + + assertThrows(AwsException.class, () -> service.deleteIntegration(stored.getIntegrationArn())); + verify(integrationBackend, never()).delete(any()); + clearInvocations(autoCopyConsumer, integrationBackend); + doNothing().when(autoCopyConsumer).disable(stored); + service.deleteIntegration(stored.getIntegrationArn()); + InOrder order = inOrder(autoCopyConsumer, integrationBackend); + order.verify(autoCopyConsumer).disable(stored); + order.verify(integrationBackend).delete("s3-one"); + } + @Test void sourceTypesFilterMatchesTheSourceTypeOfAnS3EventIntegration() { Integration stored = new Integration(); diff --git a/src/test/java/io/floci/aws/services/redshift/proxy/CopyJobCatalogTest.java b/src/test/java/io/floci/aws/services/redshift/proxy/CopyJobCatalogTest.java index fc2e19964e..ba146096d6 100644 --- a/src/test/java/io/floci/aws/services/redshift/proxy/CopyJobCatalogTest.java +++ b/src/test/java/io/floci/aws/services/redshift/proxy/CopyJobCatalogTest.java @@ -79,7 +79,7 @@ class CopyJobCatalogTest { void truncateJobs() throws SQLException { if (cluster != null) { try (Connection connection = open(); Statement statement = connection.createStatement()) { - statement.execute("TRUNCATE floci_internal.copy_job"); + statement.execute("TRUNCATE floci_internal.copy_job CASCADE"); } } } @@ -145,6 +145,64 @@ class CopyJobCatalogTest { } } + @Test + void fileCheckpointsDeduplicateAndRetryOnlyChangedFailedFiles() throws SQLException { + try (Connection connection = open(); Statement statement = connection.createStatement()) { + statement.execute(CopyJobSql.rewrite(COPY + " JOB CREATE checkpoint_job", false)); + long jobId; + try (ResultSet job = statement.executeQuery("SELECT job_id FROM floci_internal.copy_job WHERE job_name = 'checkpoint_job'")) { + assertTrue(job.next()); + jobId = job.getLong(1); + } + try (PreparedStatement reserve = connection.prepareStatement( + "SELECT floci_internal.reserve_copy_job_file(?, ?, ?, NULL, 2, CURRENT_TIMESTAMP)"); + PreparedStatement failure = connection.prepareStatement( + "SELECT floci_internal.record_copy_job_file_error(?, ?, ?, NULL, 2, CURRENT_TIMESTAMP)")) { + reserve.setLong(1, jobId); + reserve.setString(2, "loaded.csv"); + reserve.setString(3, "v1"); + assertReservation(reserve, true); + assertReservation(reserve, false); + + failure.setLong(1, jobId); + failure.setString(2, "retry.csv"); + failure.setString(3, "v1"); + failure.execute(); + failure.setString(3, "v2"); + failure.execute(); + assertCheckpoint(statement, "retry.csv", "E", "v2"); + + reserve.setString(2, "retry.csv"); + reserve.setString(3, "v2"); + assertReservation(reserve, false); + reserve.setString(3, "v3"); + assertReservation(reserve, true); + assertReservation(reserve, false); + failure.setString(3, "v4"); + failure.execute(); + assertCheckpoint(statement, "retry.csv", "I", "v3"); + assertCheckpoint(statement, "loaded.csv", "I", "v1"); + } + } + } + + private static void assertReservation(PreparedStatement statement, boolean expected) throws SQLException { + try (ResultSet result = statement.executeQuery()) { + assertTrue(result.next()); + assertEquals(expected, result.getBoolean(1)); + } + } + + private static void assertCheckpoint(Statement statement, String key, String status, String etag) throws SQLException { + try (ResultSet checkpoint = statement.executeQuery( + "SELECT status, etag FROM floci_internal.copy_job_detail WHERE key = '" + key + "'")) { + assertTrue(checkpoint.next()); + assertEquals(status, checkpoint.getString(1).trim()); + assertEquals(etag, checkpoint.getString(2)); + assertFalse(checkpoint.next()); + } + } + @Test void concurrentCreatesCannotExceedTheJobLimit() throws Exception { try (Connection connection = open(); Statement statement = connection.createStatement()) { diff --git a/src/test/java/io/floci/aws/services/redshift/proxy/CopyJobRunTest.java b/src/test/java/io/floci/aws/services/redshift/proxy/CopyJobRunTest.java new file mode 100644 index 0000000000..0b9bde4156 --- /dev/null +++ b/src/test/java/io/floci/aws/services/redshift/proxy/CopyJobRunTest.java @@ -0,0 +1,47 @@ +package io.floci.aws.services.redshift.proxy; + +import io.floci.aws.services.s3.S3Service; +import io.floci.aws.services.s3.model.S3Object; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; + +class CopyJobRunTest { + @Test + void recognizesOnlyAStandaloneRunWithAValidName() { + assertEquals("Mixed", CopyJobSql.runName("/* comment */ COPY JOB RUN \"Mixed\";")); + assertEquals("my_job", CopyJobSql.runName("copy job run MY_JOB")); + assertNull(CopyJobSql.runName("COPY JOB RUN j; SELECT 1")); + assertNull(CopyJobSql.runName("COPY JOB RUN")); + assertNull(CopyJobSql.runName("COPY JOB RUN j extra")); + assertNotNull(CopyStatementParser.parse("COPY JOB RUN j")); + } + + @Test + void preservesOptionsAndUsesTheExactObjectKey() { + String copy = "COPY t FROM 's3://bucket/prefix/' IAM_ROLE 'role' CSV"; + CopyStatementParser.S3CopyFrom spec = (CopyStatementParser.S3CopyFrom) CopyStatementParser.parse(copy); + CopyStatementParser.S3CopyFrom object = CopyJobRunner.forObject(spec, "prefix/a'b.csv"); + assertEquals("prefix/a'b.csv", object.keyOrPrefix()); + assertEquals("role", object.iamRoleArn()); + assertTrue(object.csv()); + assertEquals("bucket", object.bucket()); + } + + @Test + void deletedObjectNeverFallsBackToALongerKeyWithTheSamePrefix() { + S3Service s3 = mock(S3Service.class); + S3Object longer = new S3Object("bucket", "prefix/abc", new byte[0], "text/plain"); + when(s3.objectExists("bucket", "prefix/a")).thenReturn(false); + when(s3.listObjectsWithPrefixes("bucket", "prefix/a", null, 1000, null, null)) + .thenReturn(new S3Service.ListObjectsResult(List.of(longer), List.of(), false, null)); + CopyStatementParser.S3CopyFrom spec = (CopyStatementParser.S3CopyFrom) CopyStatementParser.parse( + "COPY t FROM 's3://bucket/prefix/a' CSV"); + S3CopySimulator.CopyInput input = S3CopySimulator.prepareObjectCopy(spec, s3, null, null, List.of()); + assertEquals(List.of("prefix/a"), input.keys()); + verify(s3, never()).listObjectsWithPrefixes("bucket", "prefix/a", null, 1000, null, null); + } +} diff --git a/src/test/java/io/floci/aws/services/redshift/proxy/CopyJobRunnerTest.java b/src/test/java/io/floci/aws/services/redshift/proxy/CopyJobRunnerTest.java new file mode 100644 index 0000000000..066e5141b7 --- /dev/null +++ b/src/test/java/io/floci/aws/services/redshift/proxy/CopyJobRunnerTest.java @@ -0,0 +1,179 @@ +package io.floci.aws.services.redshift.proxy; + +import io.floci.aws.services.iam.IamService; +import io.floci.aws.services.iam.model.IamRole; +import io.floci.aws.services.s3.S3Service; +import io.floci.aws.services.s3.model.S3Object; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; + +import java.io.ByteArrayOutputStream; +import java.net.ServerSocket; +import java.net.Socket; +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.TimeUnit; +import java.util.function.Function; +import java.util.stream.IntStream; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; + +@Timeout(10) +class CopyJobRunnerTest { + private static final String ACCOUNT = "000000000000"; + private static final String ROLE = "arn:aws:iam::000000000000:role/Load"; + private static final String COPY = "COPY t FROM 's3://bucket/prefix/' IAM_ROLE '" + ROLE + "' CSV"; + + @Test + void missingOrHiddenJobFailsBeforeReadingS3() throws Exception { + S3Service s3 = mock(S3Service.class); + withBackend(new ByteArrayOutputStream(), new ArrayList<>(), sql -> List.of(), backend -> { + S3CopySimulator.S3TransferException error = assertThrows(S3CopySimulator.S3TransferException.class, + () -> CopyJobRunner.load(backend, "missing", s3, null, ACCOUNT, List.of())); + assertEquals("42704", error.sqlState()); + }); + verifyNoInteractions(s3); + } + + @Test + void skipsOldAndCheckpointedFilesAndLoadsOnlyTheUnseenObjectAcrossPagesAsItsOwner() throws Exception { + S3Service s3 = mock(S3Service.class); + IamService iam = jobIam(); + S3Object old = object("prefix/old", 10); + S3Object seen = object("prefix/seen", 30); + S3Object fresh = object("prefix/a'b", 40); + when(s3.listObjectsWithPrefixes("bucket", "prefix/", null, 1000, null, null)) + .thenReturn(new S3Service.ListObjectsResult(List.of(old, seen), List.of(), true, "page2")); + when(s3.listObjectsWithPrefixes("bucket", "prefix/", null, 1000, "page2", null)) + .thenReturn(new S3Service.ListObjectsResult(List.of(fresh), List.of(), false, null)); + when(s3.objectExists("bucket", "prefix/a'b")).thenReturn(true); + when(s3.getObject("bucket", "prefix/a'b")).thenReturn(fresh); + ByteArrayOutputStream copied = new ByteArrayOutputStream(); + List statements = new ArrayList<>(); + withBackend(copied, statements, sql -> jobRows(sql, List.of(List.of("prefix/seen"))), + backend -> assertEquals(1, runJob(backend, s3, iam))); + assertEquals("1\n", copied.toString(StandardCharsets.UTF_8)); + assertEquals(1, statements.stream().filter(sql -> sql.contains("reserve_copy_job_file")).count()); + assertTrue(statements.contains("SET LOCAL ROLE \"job_owner\"")); + assertTrue(statements.contains("SET LOCAL ROLE \"admin\"")); + } + + @Test + void loadsMoreThanOneHundredFilesInOneRun() throws Exception { + S3Service s3 = mock(S3Service.class); + IamService iam = jobIam(); + List files = IntStream.range(0, 101).mapToObj(index -> object("prefix/" + index, 30)).toList(); + when(s3.listObjectsWithPrefixes("bucket", "prefix/", null, 1000, null, null)) + .thenReturn(new S3Service.ListObjectsResult(files.subList(0, 100), List.of(), true, "page2")); + when(s3.listObjectsWithPrefixes("bucket", "prefix/", null, 1000, "page2", null)) + .thenReturn(new S3Service.ListObjectsResult(files.subList(100, 101), List.of(), false, null)); + for (S3Object file : files) { + when(s3.getObject("bucket", file.getKey())).thenReturn(file); + } + ByteArrayOutputStream copied = new ByteArrayOutputStream(); + withBackend(copied, new ArrayList<>(), sql -> jobRows(sql, List.of()), + backend -> assertEquals(101, runJob(backend, s3, iam))); + assertEquals("1\n".repeat(101), copied.toString(StandardCharsets.UTF_8)); + } + + @Test + void isolatesFailedOrOverwrittenObjectAndContinuesWithValidFiles() throws Exception { + S3Service s3 = mock(S3Service.class); + IamService iam = jobIam(); + S3Object overwritten = object("prefix/a", 30); + overwritten.setETag("\"etag-listed\""); + S3Object replaced = object("prefix/a", 31); + replaced.setETag("\"etag-new\""); + S3Object versioned = object("prefix/b", 35); + versioned.setETag("\"etag-v1\""); + versioned.setVersionId("v1"); + when(s3.listObjectsWithPrefixes("bucket", "prefix/", null, 1000, null, null)) + .thenReturn(new S3Service.ListObjectsResult(List.of(overwritten, versioned), List.of(), false, null)); + when(s3.getObject("bucket", "prefix/a")).thenReturn(replaced); + when(s3.getObject("bucket", "prefix/b", "v1")).thenReturn(versioned); + ByteArrayOutputStream copied = new ByteArrayOutputStream(); + List statements = new ArrayList<>(); + withBackend(copied, statements, sql -> jobRows(sql, List.of()), + backend -> assertEquals(1, runJob(backend, s3, iam))); + assertEquals("1\n", copied.toString(StandardCharsets.UTF_8)); + assertTrue(statements.stream().anyMatch(sql -> sql.startsWith("ROLLBACK TO SAVEPOINT floci_job_file_"))); + assertTrue(statements.stream().anyMatch(sql -> sql.contains("record_copy_job_file_error") + && sql.contains("'prefix/a'"))); + verify(s3).getObject("bucket", "prefix/b", "v1"); + } + + private static long runJob(CopyBackendSession backend, S3Service s3, IamService iam) throws Exception { + backend.begin(false); + long count = CopyJobRunner.load(backend, "job", s3, iam, ACCOUNT, List.of(ROLE)); + backend.finish(false); + return count; + } + + private static IamService jobIam() { + IamService iam = mock(IamService.class); + IamRole role = new IamRole(); + role.setArn(ROLE); + role.setAssumeRolePolicyDocument(""" + {"Statement":[{"Effect":"Allow","Principal":{"Service":"redshift.amazonaws.com"},"Action":"sts:AssumeRole"}]} + """); + when(iam.findRole(ACCOUNT, "Load")).thenReturn(Optional.of(role)); + return iam; + } + + private static List> jobRows(String sql, List> checkpoints) { + if (sql.contains("copy_job_for_run")) { + return List.of(List.of("1", COPY, "bucket", "prefix/", "20", "job_owner")); + } + if (sql.equals("SELECT current_user")) { + return List.of(List.of("admin")); + } + if (sql.contains("copy_job_loaded_keys")) { + return checkpoints; + } + if (sql.contains("reserve_copy_job_file")) { + return List.of(List.of("t")); + } + if (sql.contains("record_copy_job_file_error")) { + return List.of(List.of("")); + } + return List.of(); + } + + @FunctionalInterface + private interface BackendAction { + void run(CopyBackendSession backend) throws Exception; + } + + private static void withBackend(ByteArrayOutputStream copied, List statements, + Function>> rows, BackendAction action) throws Exception { + try (ServerSocket listener = new ServerSocket(0); + Socket socket = new Socket("localhost", listener.getLocalPort()); + Socket server = listener.accept()) { + socket.setSoTimeout(3000); + socket.setTcpNoDelay(true); + server.setTcpNoDelay(true); + CompletableFuture response = CompletableFuture.runAsync(() -> { + try { + new FakeCopyBackend(server).serveUntilSync(copied, statements::add, rows); + } catch (Exception exception) { + throw new AssertionError(exception); + } + }); + CopyBackendSession backend = new CopyBackendSession(socket, frame -> { }); + action.run(backend); + backend.synchronize(); + response.get(5, TimeUnit.SECONDS); + } + } + + private static S3Object object(String key, long modified) { + S3Object object = new S3Object("bucket", key, "1\n".getBytes(StandardCharsets.UTF_8), "text/plain"); + object.setLastModified(Instant.ofEpochSecond(modified)); + return object; + } +} diff --git a/src/test/java/io/floci/aws/services/redshift/proxy/CopyJobSqlTest.java b/src/test/java/io/floci/aws/services/redshift/proxy/CopyJobSqlTest.java index 3397db9d0c..ccd5ed7fdc 100644 --- a/src/test/java/io/floci/aws/services/redshift/proxy/CopyJobSqlTest.java +++ b/src/test/java/io/floci/aws/services/redshift/proxy/CopyJobSqlTest.java @@ -97,8 +97,8 @@ class CopyJobSqlTest { } @Test - void runIsRefusedUntilItIsSupported() { - assertThat(CopyJobSql.rewrite("COPY JOB RUN j", false), containsString("COPY JOB RUN is not supported")); + void runIsExecutedByTheS3Interceptor() { + assertThat(CopyJobSql.rewrite("COPY JOB RUN j", false), equalTo("COPY JOB RUN j")); } @Test diff --git a/src/test/java/io/floci/aws/services/redshift/proxy/FakeCopyBackend.java b/src/test/java/io/floci/aws/services/redshift/proxy/FakeCopyBackend.java index f05f139ff0..d0fc5120a5 100644 --- a/src/test/java/io/floci/aws/services/redshift/proxy/FakeCopyBackend.java +++ b/src/test/java/io/floci/aws/services/redshift/proxy/FakeCopyBackend.java @@ -2,14 +2,19 @@ package io.floci.aws.services.redshift.proxy; import io.floci.aws.core.common.PostgresWire; +import java.io.ByteArrayOutputStream; import java.io.OutputStream; import java.net.Socket; +import java.nio.charset.StandardCharsets; import java.util.HashMap; +import java.util.List; import java.util.Map; +import java.util.function.Function; /** Extended-query backend for COPY tests, including catalog discovery and transaction recovery. */ final class FakeCopyBackend { private final Socket socket; + private Function>> rows = sql -> List.of(); FakeCopyBackend(Socket socket) { this.socket = socket; @@ -23,6 +28,12 @@ final class FakeCopyBackend { serve(OutputStream.nullOutputStream(), false, failCommit, observer); } + void serveUntilSync(OutputStream copied, StatementObserver observer, + Function>> rows) throws Exception { + this.rows = rows; + serve(copied, false, false, observer); + } + private void serve(OutputStream copied, boolean stopAfterLoad, boolean failCommit, StatementObserver observer) throws Exception { PostgresWireDecoder decoder = new PostgresWireDecoder(socket.getInputStream()); @@ -69,6 +80,9 @@ final class FakeCopyBackend { } else if (sql.startsWith("COPY ")) { PostgresWire.write(out, 'G', new byte[]{0, 0, 0}); } else { + for (List row : rows.apply(sql)) { + PostgresWire.write(out, 'D', dataRow(row)); + } if (sql.startsWith("SELECT a.attname")) { PostgresWire.write(out, 'D', new byte[]{0, 3}, PostgresWire.int32(2), new byte[]{'i', 'd'}, PostgresWire.int32(-1), PostgresWire.int32(2), new byte[]{'2', '3'}); @@ -117,4 +131,15 @@ final class FakeCopyBackend { interface StatementObserver { void executed(String sql) throws Exception; } + + private static byte[] dataRow(List row) throws Exception { + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + bytes.write(new byte[]{(byte) (row.size() >> 8), (byte) row.size()}); + for (String value : row) { + byte[] field = value.getBytes(StandardCharsets.UTF_8); + bytes.write(PostgresWire.int32(field.length)); + bytes.write(field); + } + return bytes.toByteArray(); + } } diff --git a/src/test/java/io/floci/aws/services/redshift/proxy/S3CopySimulatorTest.java b/src/test/java/io/floci/aws/services/redshift/proxy/S3CopySimulatorTest.java index 71048dc792..d299875f7c 100644 --- a/src/test/java/io/floci/aws/services/redshift/proxy/S3CopySimulatorTest.java +++ b/src/test/java/io/floci/aws/services/redshift/proxy/S3CopySimulatorTest.java @@ -1796,7 +1796,7 @@ class S3CopySimulatorTest { S3Object dataObj = new S3Object("wh", "users.json", ndjson.getBytes(StandardCharsets.UTF_8), "application/json"); when(s3.getObject("wh", "users.json")).thenReturn(dataObj); - S3CopySimulator.CopyInput input = new S3CopySimulator.CopyInput(spec, List.of("users.json"), s3, null, null); + S3CopySimulator.CopyInput input = new S3CopySimulator.CopyInput(spec, List.of("users.json"), s3, null, null, null, null); ByteArrayOutputStream out = new ByteArrayOutputStream(); S3CopySimulator.streamCopyInput(input, out); @@ -1829,7 +1829,7 @@ class S3CopySimulatorTest { "1| \n2||x\n".getBytes(StandardCharsets.UTF_8), "text/plain"); when(s3.getObject("wh", "p.txt")).thenReturn(dataObj); - S3CopySimulator.CopyInput input = new S3CopySimulator.CopyInput(spec, List.of("p.txt"), s3, null, null); + S3CopySimulator.CopyInput input = new S3CopySimulator.CopyInput(spec, List.of("p.txt"), s3, null, null, null, null); ByteArrayOutputStream out = new ByteArrayOutputStream(); S3CopySimulator.streamCopyInput(input, out); @@ -1845,7 +1845,7 @@ class S3CopySimulatorTest { when(s3.getObject("wh", "p/b.txt")).thenReturn(new S3Object("wh", "p/b.txt", "id|name\n2|b\n".getBytes(StandardCharsets.UTF_8), "text/plain")); S3CopySimulator.CopyInput input = - new S3CopySimulator.CopyInput(spec, List.of("p/a.txt", "p/b.txt"), s3, null, null); + new S3CopySimulator.CopyInput(spec, List.of("p/a.txt", "p/b.txt"), s3, null, null, null, null); ByteArrayOutputStream out = new ByteArrayOutputStream(); S3CopySimulator.streamCopyInput(input, out); @@ -1866,7 +1866,7 @@ class S3CopySimulatorTest { } when(s3.getObject("wh", "p.gz")).thenReturn(new S3Object("wh", "p.gz", gz.toByteArray(), "application/gzip")); - S3CopySimulator.CopyInput input = new S3CopySimulator.CopyInput(spec, List.of("p.gz"), s3, null, null); + S3CopySimulator.CopyInput input = new S3CopySimulator.CopyInput(spec, List.of("p.gz"), s3, null, null, null, null); ByteArrayOutputStream out = new ByteArrayOutputStream(); S3CopySimulator.streamCopyInput(input, out); @@ -1978,7 +1978,7 @@ class S3CopySimulatorTest { false, false, false, transforms); when(s3.getObject("wh", "p.txt")).thenReturn(new S3Object("wh", "p.txt", "1|03/31/2003\n".getBytes(StandardCharsets.UTF_8), "text/plain")); - S3CopySimulator.CopyInput input = new S3CopySimulator.CopyInput(spec, List.of("p.txt"), s3, null, null); + S3CopySimulator.CopyInput input = new S3CopySimulator.CopyInput(spec, List.of("p.txt"), s3, null, null, null, null); ByteArrayOutputStream out = new ByteArrayOutputStream(); S3CopySimulator.streamCopyInput(input, null, null, @@ -1996,7 +1996,7 @@ class S3CopySimulatorTest { false, false, false, transforms); when(s3.getObject("wh", "p.txt")).thenReturn(new S3Object("wh", "p.txt", "1|\n|03/31/2003\n".getBytes(StandardCharsets.UTF_8), "text/plain")); - S3CopySimulator.CopyInput input = new S3CopySimulator.CopyInput(spec, List.of("p.txt"), s3, null, null); + S3CopySimulator.CopyInput input = new S3CopySimulator.CopyInput(spec, List.of("p.txt"), s3, null, null, null, null); ByteArrayOutputStream out = new ByteArrayOutputStream(); S3CopySimulator.streamCopyInput(input, null, null, @@ -2014,7 +2014,7 @@ class S3CopySimulatorTest { false, false, false, transforms); when(s3.getObject("wh", "p.txt")).thenReturn(new S3Object("wh", "p.txt", "1\n2|b|7\n".getBytes(StandardCharsets.UTF_8), "text/plain")); - S3CopySimulator.CopyInput input = new S3CopySimulator.CopyInput(spec, List.of("p.txt"), s3, null, null); + S3CopySimulator.CopyInput input = new S3CopySimulator.CopyInput(spec, List.of("p.txt"), s3, null, null, null, null); ByteArrayOutputStream out = new ByteArrayOutputStream(); S3CopySimulator.streamCopyInput(input, null, null, List.of(CopyRecordTransformer.ColumnKind.OTHER, @@ -2029,7 +2029,7 @@ class S3CopySimulatorTest { false, false, false, false, null, null, null, false, true); CopyStatementParser.S3CopyFrom spec = new CopyStatementParser.S3CopyFrom( "t", List.of(), "wh", "k", "|", 0, false, false, null, null, false, false, false, transforms); - S3CopySimulator.CopyInput input = new S3CopySimulator.CopyInput(spec, List.of("k"), s3, null, null); + S3CopySimulator.CopyInput input = new S3CopySimulator.CopyInput(spec, List.of("k"), s3, null, null, null, null); S3CopySimulator.S3TransferException failure = assertThrows(S3CopySimulator.S3TransferException.class, () -> S3CopySimulator.streamCopyInput(input, new ByteArrayOutputStream())); @@ -2042,7 +2042,7 @@ class S3CopySimulatorTest { false, false, false, false, null, CopyTemporalFormat.parse("MM/DD/YYYY", false), null, false); CopyStatementParser.S3CopyFrom spec = new CopyStatementParser.S3CopyFrom( "t", List.of(), "wh", "k", "|", 0, false, false, null, null, false, false, false, transforms); - S3CopySimulator.CopyInput input = new S3CopySimulator.CopyInput(spec, List.of("k"), s3, null, null); + S3CopySimulator.CopyInput input = new S3CopySimulator.CopyInput(spec, List.of("k"), s3, null, null, null, null); S3CopySimulator.S3TransferException failure = assertThrows(S3CopySimulator.S3TransferException.class, () -> S3CopySimulator.streamCopyInput(input, new ByteArrayOutputStream())); @@ -2055,7 +2055,7 @@ class S3CopySimulatorTest { new CopyStatementParser.CopyTransforms(false, false, false, true, null); CopyStatementParser.S3CopyFrom spec = new CopyStatementParser.S3CopyFrom( "t", List.of(), "wh", "k", "|", 0, false, false, null, null, false, false, false, transforms); - S3CopySimulator.CopyInput input = new S3CopySimulator.CopyInput(spec, List.of("k"), s3, null, null); + S3CopySimulator.CopyInput input = new S3CopySimulator.CopyInput(spec, List.of("k"), s3, null, null, null, null); S3CopySimulator.S3TransferException failure = assertThrows(S3CopySimulator.S3TransferException.class, () -> S3CopySimulator.streamCopyInput(input, new ByteArrayOutputStream())); @@ -2070,7 +2070,7 @@ class S3CopySimulatorTest { "t", List.of(), "wh", "k", "|", 0, false, false, null, null, false, false, false, transforms); when(s3.getObject("wh", "k")).thenReturn( new S3Object("wh", "k", "1||x\n1||x\n".getBytes(StandardCharsets.UTF_8), "text/plain")); - S3CopySimulator.CopyInput input = new S3CopySimulator.CopyInput(spec, List.of("k"), s3, null, null); + S3CopySimulator.CopyInput input = new S3CopySimulator.CopyInput(spec, List.of("k"), s3, null, null, null, null); long saved = S3CopySimulator.COPY_TRANSFORM_MAX_OBJECT_BYTES; int availableBefore = S3CopySimulator.COPY_TRANSFORM_HEAP_MIB.availablePermits(); @@ -2093,7 +2093,7 @@ class S3CopySimulatorTest { "t", List.of(), "wh", "k", "|", 0, false, false, null, null, false, false, false, transforms); when(s3.getObject("wh", "k")).thenReturn( new S3Object("wh", "k", "1\n2\n".getBytes(StandardCharsets.UTF_8), "text/plain")); - S3CopySimulator.CopyInput input = new S3CopySimulator.CopyInput(spec, List.of("k"), s3, null, null); + S3CopySimulator.CopyInput input = new S3CopySimulator.CopyInput(spec, List.of("k"), s3, null, null, null, null); long saved = S3CopySimulator.COPY_TRANSFORM_MAX_OBJECT_BYTES; int availableBefore = S3CopySimulator.COPY_TRANSFORM_HEAP_MIB.availablePermits(); @@ -2124,7 +2124,7 @@ class S3CopySimulatorTest { String inputData = "1\n".repeat(2000); when(s3.getObject("wh", "k")).thenReturn( new S3Object("wh", "k", inputData.getBytes(StandardCharsets.UTF_8), "text/plain")); - S3CopySimulator.CopyInput input = new S3CopySimulator.CopyInput(spec, List.of("k"), s3, null, null); + S3CopySimulator.CopyInput input = new S3CopySimulator.CopyInput(spec, List.of("k"), s3, null, null, null, null); List kinds = new ArrayList<>(); for (int i = 0; i < 300; i++) { @@ -2178,7 +2178,7 @@ class S3CopySimulatorTest { S3Object dataObj = new S3Object("wh", "users.json", ndjson.getBytes(StandardCharsets.UTF_8), "application/json"); when(s3.getObject("wh", "users.json")).thenReturn(dataObj); - S3CopySimulator.CopyInput input = new S3CopySimulator.CopyInput(spec, List.of("users.json"), s3, null, null); + S3CopySimulator.CopyInput input = new S3CopySimulator.CopyInput(spec, List.of("users.json"), s3, null, null, null, null); ByteArrayOutputStream out = new ByteArrayOutputStream(); S3CopySimulator.streamCopyInput(input, out); @@ -2203,7 +2203,7 @@ class S3CopySimulatorTest { S3Object dataObj = new S3Object("wh", "users.json.gz", gzippedOut.toByteArray(), "application/gzip"); when(s3.getObject("wh", "users.json.gz")).thenReturn(dataObj); - S3CopySimulator.CopyInput input = new S3CopySimulator.CopyInput(spec, List.of("users.json.gz"), s3, null, null); + S3CopySimulator.CopyInput input = new S3CopySimulator.CopyInput(spec, List.of("users.json.gz"), s3, null, null, null, null); ByteArrayOutputStream out = new ByteArrayOutputStream(); S3CopySimulator.streamCopyInput(input, out); diff --git a/src/test/java/io/floci/aws/services/redshiftdata/RedshiftCopyJobExecutorTest.java b/src/test/java/io/floci/aws/services/redshiftdata/RedshiftCopyJobExecutorTest.java new file mode 100644 index 0000000000..4d77062263 --- /dev/null +++ b/src/test/java/io/floci/aws/services/redshiftdata/RedshiftCopyJobExecutorTest.java @@ -0,0 +1,138 @@ +package io.floci.aws.services.redshiftdata; + +import io.floci.aws.core.common.AwsException; +import io.floci.aws.services.redshift.RedshiftService; +import io.floci.aws.services.redshift.RedshiftZeroEtlEndpoints; +import io.floci.aws.services.redshift.model.Cluster; +import io.floci.aws.services.redshift.model.Endpoint; +import io.floci.aws.services.redshift.model.Integration; +import io.floci.aws.services.redshiftserverless.RedshiftServerlessService.WorkgroupTarget; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.*; + +class RedshiftCopyJobExecutorTest { + private final RedshiftService service = mock(RedshiftService.class); + private final RedshiftZeroEtlEndpoints endpoints = mock(RedshiftZeroEtlEndpoints.class); + private final RedshiftDataConnectionFactory connections = mock(RedshiftDataConnectionFactory.class); + private final RedshiftCopyJobExecutor executor = new RedshiftCopyJobExecutor(service, endpoints, connections); + + @Test + void missingClusterOrNamespaceDoesNotPreventIntegrationDeletion() { + Integration cluster = integration("arn:aws:redshift:us-east-1:123456789012:cluster:target"); + when(service.describeClustersForAccount("123456789012", "target")) + .thenThrow(new AwsException("ClusterNotFound", "Gone", 404)); + assertFalse(executor.runAutomatic(cluster)); + assertDoesNotThrow(() -> executor.disable(cluster)); + Integration namespace = integration("arn:aws:redshift-serverless:us-east-1:123456789012:namespace/target"); + doThrow(new AwsException("ResourceNotFoundException", "Gone", 404)) + .when(endpoints).targetWorkgroup("123456789012", namespace.getTargetArn()); + assertFalse(executor.runAutomatic(namespace)); + assertDoesNotThrow(() -> executor.disable(namespace)); + doThrow(new AwsException("ValidationException", + "Workgroup runtime is not available for Data API execution.", 400)) + .when(endpoints).targetWorkgroup("123456789012", namespace.getTargetArn()); + assertTrue(executor.runAutomatic(namespace)); + assertDoesNotThrow(() -> executor.disable(namespace)); + verifyNoInteractions(connections); + } + + @Test + void pausedClusterSkipsLoadsAndRefusesDeletionWithoutLosingIntegrationState() { + Integration integration = integration("arn:aws:redshift:us-east-1:123456789012:cluster:target"); + Cluster cluster = new Cluster(); + cluster.setClusterStatus("paused"); + when(service.describeClustersForAccount("123456789012", "target")).thenReturn(List.of(cluster)); + assertTrue(executor.runAutomatic(integration)); + AwsException error = assertThrows(AwsException.class, () -> executor.disable(integration)); + assertEquals("InvalidClusterState", error.getErrorCode()); + verifyNoInteractions(connections); + } + + @Test + void serverlessCleanupUsesTheWorkgroupProxyAndMatchesOnlyTheSourceBucket() throws Exception { + Integration integration = integration("arn:aws:redshift-serverless:us-east-1:123456789012:namespace/target"); + Endpoint endpoint = new Endpoint(); + endpoint.setPort(15439); + WorkgroupTarget target = new WorkgroupTarget("workgroup-arn", "workgroup", "backend", 5432, "analytics", + "master", "password", "admin", List.of(), null, endpoint); + when(endpoints.targetWorkgroup("123456789012", integration.getTargetArn())).thenReturn(target); + Connection database = mock(Connection.class); + PreparedStatement update = mock(PreparedStatement.class); + openDatabase(database); + when(database.prepareStatement(anyString())).thenReturn(update); + executor.disable(integration); + verify(connections, times(2)).open(argThat(value -> value.host().equals("127.0.0.1") + && value.port() == 15439 && value.database().equals("analytics"))); + verify(update).setString(1, "source-bucket"); + verify(update).executeUpdate(); + verify(database).close(); + } + + @ParameterizedTest + @CsvSource({ + "Connection lost, 08006, true", + "Target table is missing, 42P01, false" + }) + void failedJobRollsBackAndRetryIsRequestedOnlyForTransientFailures(String message, String sqlState, + boolean retryExpected) throws Exception { + Integration integration = integration("arn:aws:redshift:us-east-1:123456789012:cluster:target"); + Cluster cluster = new Cluster(); + cluster.setClusterStatus("available"); + cluster.setProxyPort(15439); + when(service.describeClustersForAccount("123456789012", "target")).thenReturn(List.of(cluster)); + Connection database = mock(Connection.class); + openDatabase(database); + PreparedStatement findJobs = mock(PreparedStatement.class); + PreparedStatement lock = mock(PreparedStatement.class); + Statement run = mock(Statement.class); + ResultSet jobs = mock(ResultSet.class); + ResultSet locked = mock(ResultSet.class); + when(database.prepareStatement(startsWith("SELECT job_name"))).thenReturn(findJobs); + when(database.prepareStatement(contains("FOR UPDATE"))).thenReturn(lock); + when(database.createStatement()).thenReturn(run); + when(findJobs.executeQuery()).thenReturn(jobs); + when(jobs.next()).thenReturn(true, true, false); + when(jobs.getString(1)).thenReturn("failed", "healthy"); + when(lock.executeQuery()).thenReturn(locked); + when(locked.next()).thenReturn(true); + when(run.execute("COPY JOB RUN \"failed\"")).thenThrow(new SQLException(message, sqlState)); + + assertEquals(retryExpected, executor.runAutomatic(integration)); + + verify(database).rollback(); + verify(run).execute("COPY JOB RUN \"healthy\""); + verify(database).commit(); + } + + private void openDatabase(Connection database) throws SQLException { + Connection connection = mock(Connection.class); + Statement statement = mock(Statement.class); + ResultSet databases = mock(ResultSet.class); + when(connections.open(any())).thenReturn(connection, database); + when(connection.createStatement()).thenReturn(statement); + when(statement.executeQuery(anyString())).thenReturn(databases); + when(databases.next()).thenReturn(true, false); + when(databases.getString(1)).thenReturn("analytics"); + } + + private static Integration integration(String target) { + Integration integration = new Integration(); + integration.setAccountId("123456789012"); + integration.setTargetArn(target); + integration.setTargetClusterIdentifier("target"); + integration.setSourceArn("arn:aws:s3:::source-bucket"); + return integration; + } +} diff --git a/src/test/java/io/floci/aws/services/redshiftdata/RedshiftDataResourceResolverTest.java b/src/test/java/io/floci/aws/services/redshiftdata/RedshiftDataResourceResolverTest.java index d51d10dece..19a8164f42 100644 --- a/src/test/java/io/floci/aws/services/redshiftdata/RedshiftDataResourceResolverTest.java +++ b/src/test/java/io/floci/aws/services/redshiftdata/RedshiftDataResourceResolverTest.java @@ -48,6 +48,21 @@ class RedshiftDataResourceResolverTest { return new RedshiftDataResourceResolver(redshift, secrets, mapper, broker, regionResolver, serverless); } + @Test + void copyJobRunUsesTheProxyForSingleStatementsAndBatches() { + Cluster target = cluster(); + target.setProxyPort(5439); + RedshiftService redshift = mock(RedshiftService.class); + when(redshift.describeClusters("wh")).thenReturn(List.of(target)); + ObjectNode request = mapper.createObjectNode().put("ClusterIdentifier", "wh") + .put("DbUser", "admin").put("Database", "dev").put("Sql", "COPY JOB RUN ingest"); + RedshiftDataResourceResolver resolver = resolver(redshift, mock(SecretsManagerService.class)); + assertEquals(5439, resolver.resolve(request, REGION).port()); + request.remove("Sql"); + request.putArray("Sqls").add("SELECT 1").add("COPY JOB RUN ingest"); + assertEquals(5439, resolver.resolve(request, REGION).port()); + } + @Test void resolvesClusterIdentifierAndMasterDbUser() { RedshiftService redshift = mock(RedshiftService.class);