mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(redshift): execute S3 auto-copy and COPY JOB RUN (#7898)
A job failure (SQLState 42xx or 0A000) cannot clear on its own, so re-marking the bucket made every sweep reconnect and log a WARN. The job now waits for the next upload. The predicate is shared with CopyJobRunner via S3TransferException.isJobFailure.
This commit is contained in:
1 parent
b954b4fb87
commit
4d4f20b812
25 files changed
+1572
-60
No files matched your search
@@ -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();
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -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<String> 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<String> 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> T scoped(Integration integration, Supplier<T> action) {
|
||||
return RequestScopes.callAs(integration.getAccountId(),
|
||||
AwsArnUtils.parse(integration.getIntegrationArn()).region(), action);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clear() {
|
||||
work.pendingBuckets.clear();
|
||||
work.reconcileAll.set(true);
|
||||
}
|
||||
}
|
||||
@@ -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<Integer> usedPorts = ConcurrentHashMap.newKeySet();
|
||||
private final ConcurrentHashMap<ResourceKey, ResourceLock> 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<Map<String, Cluster>>() {});
|
||||
this.snapshots = storageFactory.create("redshift", "redshift-snapshots.json", new TypeReference<Map<String, Snapshot>>() {});
|
||||
this.snapshotCopies = storageFactory.create("redshift", "redshift-snapshot-copies.json", new TypeReference<Map<String, Snapshot>>() {});
|
||||
@@ -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<String, String> 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<Integration> 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<String, String> 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");
|
||||
|
||||
@@ -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<String> 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<String> 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<String> 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<String> roles) throws IOException {
|
||||
String expectedETag, String versionId,
|
||||
S3Service s3, IamService iam, String account, List<String> roles,
|
||||
boolean exactObject) throws IOException {
|
||||
List<ColumnInfo> catalog = columns(backend, spec);
|
||||
List<String> discovered = spec.jsonAuto() && (spec.columns() == null || spec.columns().isEmpty())
|
||||
? catalog.stream().map(ColumnInfo::name).toList() : null;
|
||||
List<Integer> widths = spec.transforms().truncateColumns() ? S3CopySimulator.alignMaxBytes(spec, catalog) : null;
|
||||
List<CopyRecordTransformer.ColumnKind> 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())) {
|
||||
|
||||
@@ -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<String> roles) throws IOException {
|
||||
List<List<String>> 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<String> 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<String> job, CopyStatementParser.S3CopyFrom copy,
|
||||
S3Service s3, IamService iam, String account, List<String> 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<String> checkpointed = new HashSet<>();
|
||||
Map<String, FileRevision> failedFiles = new HashMap<>();
|
||||
for (List<String> 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("\"", "\"\"") + "\"";
|
||||
}
|
||||
}
|
||||
@@ -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<Token> 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");
|
||||
};
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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<String> roles,
|
||||
BackendResponseCoordinator coordinator, CopyBackendSession copyBackend) throws IOException {
|
||||
OutputStream output = backend.getOutputStream();
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -80,7 +80,18 @@ public final class S3CopySimulator {
|
||||
}
|
||||
|
||||
record CopyInput(CopyStatementParser.S3CopyFrom spec, List<String> 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<String> 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<String> associatedRoleArns) {
|
||||
return prepareObjectCopy(spec, s3, iamService, clusterAccountId, associatedRoleArns, null, null);
|
||||
}
|
||||
|
||||
static CopyInput prepareObjectCopy(CopyStatementParser.S3CopyFrom spec, S3Service s3, IamService iamService,
|
||||
String clusterAccountId, List<String> 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<String> associatedRoleArns) {
|
||||
List<String> 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<String> 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<String> discoveredColumns,
|
||||
private static void streamObjects(CopyInput input, List<String> discoveredColumns,
|
||||
List<Integer> columnMaxBytes, List<CopyRecordTransformer.ColumnKind> columnKinds,
|
||||
S3Service s3, IamService iamService, RedshiftRoleAccess.RoleSession roleSession,
|
||||
List<String> 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<String> 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())) {
|
||||
|
||||
@@ -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<String> 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<String> 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<Cluster> 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);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user