mirror of
https://github.com/floci-io/floci.git
synced 2026-11-26 23:29:28 -05:00
feat(redshift): support Redshift UNLOAD to Parquet (#7548)
* feat(redshift): support UNLOAD to Parquet * refactor(redshift): share internal S3 scratch plumbing * fix(redshift): warn when UNLOAD staging cleanup fails
This commit is contained in:
1 parent
189521e5cc
commit
f7cf6fef6e
27 files changed
+1252
-167
No files matched your search
@@ -23,6 +23,7 @@ import io.github.hectorvent.floci.services.iam.ScpProvider;
|
||||
import io.github.hectorvent.floci.services.iam.model.CallerContext;
|
||||
import io.github.hectorvent.floci.services.iam.model.IamRole;
|
||||
import io.github.hectorvent.floci.services.s3.S3ObjectActions;
|
||||
import io.github.hectorvent.floci.services.s3.S3ScratchSpace;
|
||||
import io.github.hectorvent.floci.services.s3.S3Service;
|
||||
import io.quarkus.vertx.http.runtime.CurrentVertxRequest;
|
||||
import io.vertx.core.http.HttpServerRequest;
|
||||
@@ -562,12 +563,8 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
|
||||
conditionContext = conditionContext == null ? new HashMap<>() : new HashMap<>(conditionContext);
|
||||
callerArns.get().putPrincipalKeys(conditionContext);
|
||||
}
|
||||
// Floci Spectrum transfer writes internal materialization to its own scratch bucket under the minted
|
||||
// role session key. Since AWS Spectrum has no S3 write, this transfer is internal and must not be
|
||||
// evaluated against the role's policies, permissions boundary, or SCPs (which often enforce read-only
|
||||
// on data lake buckets). Tying authorization ahead of role policies directly to the minted transfer key
|
||||
// and scratch key ensures boundary/SCP checks apply only to the actual S3 source reads.
|
||||
if (isSpectrumScratchTransfer(credentialScope, action, resources, akid, callerArns.orElse(null))) {
|
||||
// Internal transfers bypass customer policies only for a registered session scope in a tagged bucket.
|
||||
if (isScratchTransfer(ctx, credentialScope, action, resources, akid, callerArns.orElse(null))) {
|
||||
return;
|
||||
}
|
||||
// A create that carries tags is checked with them where its own action takes them, as the tagging
|
||||
@@ -722,14 +719,6 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
|
||||
// presigned URLs add, is a DeleteObject.
|
||||
private static final Set<String> NON_DELETE_OBJECT_SUBRESOURCES = Set.of("uploadId", "tagging", "annotation");
|
||||
|
||||
private static final Set<String> SPECTRUM_SCRATCH_ACTIONS =
|
||||
Set.of("s3:PutObject", "s3:DeleteObject", "s3:AbortMultipartUpload");
|
||||
|
||||
private static final Pattern SPECTRUM_SCRATCH_OBJECT = Pattern.compile(
|
||||
"arn:" + AwsArnUtils.PARTITION_REGEX + ":s3:::"
|
||||
+ Pattern.quote(S3Service.REDSHIFT_SPECTRUM_SCRATCH_BUCKET)
|
||||
+ "/spectrum-[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}\\.csv");
|
||||
|
||||
private static final Set<String> GOVERNANCE_BYPASS_ACTIONS =
|
||||
Set.of("s3:PutObjectRetention", "s3:DeleteObject", "s3:DeleteObjectVersion");
|
||||
|
||||
@@ -770,33 +759,25 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
|
||||
return "POST".equalsIgnoreCase(ctx.getMethod()) && namesUpload && !params.containsKey("uploads");
|
||||
}
|
||||
|
||||
/**
|
||||
* A write or delete of the scratch object in the Spectrum scratch bucket by the exact assumed-role
|
||||
* session running that transfer. The transfer is Floci's own, so it is authorized ahead of the
|
||||
* role's policies and permissions boundaries; any other action, bucket, key or session stays
|
||||
* under normal policy evaluation.
|
||||
*/
|
||||
private boolean isSpectrumScratchTransfer(String credentialScope, String action,
|
||||
List<String> resources, String akid,
|
||||
CallerArns callerArns) {
|
||||
private boolean isScratchTransfer(ContainerRequestContext ctx, String credentialScope, String action,
|
||||
List<String> resources, String akid, CallerArns callerArns) {
|
||||
if (!"s3".equals(credentialScope) || akid == null || callerArns == null
|
||||
|| !CallerArns.TYPE_ASSUMED_ROLE.equals(callerArns.principalType())
|
||||
|| !SPECTRUM_SCRATCH_ACTIONS.contains(action) || resources.isEmpty()) {
|
||||
|| resources.isEmpty() || s3ServiceProvider == null || !s3ServiceProvider.isResolvable()) {
|
||||
return false;
|
||||
}
|
||||
if (s3ServiceProvider != null && s3ServiceProvider.isResolvable()
|
||||
&& !s3ServiceProvider.get().isSpectrumScratchBucket(S3Service.REDSHIFT_SPECTRUM_SCRATCH_BUCKET)) {
|
||||
Optional<String> allowed = iamService.scratchResourceArn(akid);
|
||||
if (allowed.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
Optional<String> allowedScratchArn = iamService.spectrumScratchResourceArn(akid);
|
||||
if (allowedScratchArn.isEmpty()) {
|
||||
return false;
|
||||
String prefix = "s3:ListBucket".equals(action) ? ctx.getUriInfo().getQueryParameters().getFirst("prefix") : null;
|
||||
for (S3ScratchSpace space : S3ScratchSpace.values()) {
|
||||
if (space.permits(action, allowed.get(), resources, prefix)
|
||||
&& s3ServiceProvider.get().isScratchBucket(space.bucketName())) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
String expectedArn = allowedScratchArn.get();
|
||||
if (!SPECTRUM_SCRATCH_OBJECT.matcher(expectedArn).matches()) {
|
||||
return false;
|
||||
}
|
||||
return resources.stream().allMatch(expectedArn::equals);
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -4835,28 +4835,21 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
|
||||
session.getPresignedAction(), session.getPresignedResourceArn()));
|
||||
}
|
||||
|
||||
/** Binds a Redshift Spectrum scratch object ARN to an active transfer role session. */
|
||||
public void registerSpectrumScratchResource(String accessKeyId, String resourceArn) {
|
||||
/** Binds, or clears with null, an internal S3 scratch scope for this transfer session. */
|
||||
public void registerScratchResource(String accessKeyId, String resourceArn) {
|
||||
currentSession(accessKeyId).ifPresent(session -> {
|
||||
session.setSpectrumScratchResourceArn(resourceArn);
|
||||
session.setScratchResourceArn(resourceArn);
|
||||
String accountId = session.getOriginAccountId() != null ? session.getOriginAccountId() : "000000000000";
|
||||
putSessionForAccount(accountId, accessKeyId, session);
|
||||
});
|
||||
}
|
||||
|
||||
/** Clears the Spectrum scratch object permission from the session when the transfer completes. */
|
||||
public void clearSpectrumScratchResource(String accessKeyId) {
|
||||
currentSession(accessKeyId).ifPresent(session -> {
|
||||
session.setSpectrumScratchResourceArn(null);
|
||||
String accountId = session.getOriginAccountId() != null ? session.getOriginAccountId() : "000000000000";
|
||||
putSessionForAccount(accountId, accessKeyId, session);
|
||||
});
|
||||
public void clearScratchResource(String accessKeyId) {
|
||||
registerScratchResource(accessKeyId, null);
|
||||
}
|
||||
|
||||
/** The exact scratch object ARN permitted for this session, if it is a Spectrum transfer session. */
|
||||
public Optional<String> spectrumScratchResourceArn(String accessKeyId) {
|
||||
return currentSession(accessKeyId)
|
||||
.map(SessionCredential::getSpectrumScratchResourceArn)
|
||||
public Optional<String> scratchResourceArn(String accessKeyId) {
|
||||
return currentSession(accessKeyId).map(SessionCredential::getScratchResourceArn)
|
||||
.filter(arn -> arn != null && !arn.isBlank());
|
||||
}
|
||||
|
||||
|
||||
@@ -34,8 +34,8 @@ public class SessionCredential {
|
||||
/** Exact object action and ARN for an internally generated S3 presigned URL. */
|
||||
private String presignedAction;
|
||||
private String presignedResourceArn;
|
||||
/** Exact scratch object ARN permitted for an internal Redshift Spectrum transfer session. */
|
||||
private String spectrumScratchResourceArn;
|
||||
/** Exact object ARN or UUID-scoped prefix permitted for an internal S3 transfer. */
|
||||
private String scratchResourceArn;
|
||||
/**
|
||||
* The long-term identity whose key minted this session through GetSessionToken or
|
||||
* GetFederationToken: an IAM user's ARN, or the account root's. Null for every other session.
|
||||
@@ -141,9 +141,9 @@ public class SessionCredential {
|
||||
public String getPresignedResourceArn() { return presignedResourceArn; }
|
||||
public void setPresignedResourceArn(String presignedResourceArn) { this.presignedResourceArn = presignedResourceArn; }
|
||||
|
||||
public String getSpectrumScratchResourceArn() { return spectrumScratchResourceArn; }
|
||||
public void setSpectrumScratchResourceArn(String spectrumScratchResourceArn) {
|
||||
this.spectrumScratchResourceArn = spectrumScratchResourceArn;
|
||||
public String getScratchResourceArn() { return scratchResourceArn; }
|
||||
public void setScratchResourceArn(String scratchResourceArn) {
|
||||
this.scratchResourceArn = scratchResourceArn;
|
||||
}
|
||||
|
||||
public boolean isLambdaExecutionRole() { return lambdaExecutionRole; }
|
||||
|
||||
+9
@@ -270,6 +270,15 @@ final class BackendResponseCoordinator {
|
||||
}
|
||||
}
|
||||
|
||||
boolean isFirstPending(Ticket ticket) {
|
||||
lock.lock();
|
||||
try {
|
||||
return !pending.isEmpty() && pending.getFirst().ticket().equals(ticket);
|
||||
} finally {
|
||||
lock.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
private boolean canOwnExtendedExecute(Ticket ticket) {
|
||||
for (PendingOperation operation : pending) {
|
||||
if (operation.ticket().equals(ticket)) {
|
||||
|
||||
+20
-5
@@ -228,7 +228,8 @@ public final class CopyStatementParser {
|
||||
boolean cleanPath,
|
||||
boolean encrypted,
|
||||
String sseKmsKeyId,
|
||||
boolean defaultIamRoleRequested) implements S3Statement {
|
||||
boolean defaultIamRoleRequested,
|
||||
boolean parquet) implements S3Statement {
|
||||
|
||||
public S3Unload(
|
||||
String selectQuery,
|
||||
@@ -252,7 +253,7 @@ public final class CopyStatementParser {
|
||||
String sseKmsKeyId) {
|
||||
this(selectQuery, bucket, prefix, delimiter, header, gzip, csv, addQuotes, nullAs, manifest,
|
||||
allowOverwrite, parallel, maxFileSizeBytes, iamRoleArn, extension,
|
||||
escape, cleanPath, encrypted, sseKmsKeyId, false);
|
||||
escape, cleanPath, encrypted, sseKmsKeyId, false, false);
|
||||
}
|
||||
|
||||
public S3Unload(
|
||||
@@ -304,6 +305,9 @@ public final class CopyStatementParser {
|
||||
"(?is)^\\s*UNLOAD\\s*\\(\\s*'(.*)'\\s*\\)\\s*TO\\s*"
|
||||
+ "['\"]s3://([^/'\"\\s]+)(?:/([^'\"\\s]*))?['\"]\\s*(.*)$");
|
||||
|
||||
private static final Pattern PARQUET_PATTERN = Pattern.compile(
|
||||
"(?i)(?:FORMAT\\s+(?:AS\\s+)?)?PARQUET\\b");
|
||||
|
||||
private static final Pattern PARALLEL_PATTERN = Pattern.compile(
|
||||
"(?i)\\bPARALLEL\\b(?:\\s+(ON|OFF|TRUE|FALSE))?");
|
||||
private static final Pattern MAXFILESIZE_PATTERN = Pattern.compile(
|
||||
@@ -325,7 +329,7 @@ public final class CopyStatementParser {
|
||||
* UNLOAD-supported here, while PARTITION is UNLOAD-only and unsupported.
|
||||
*/
|
||||
private static final Pattern UNLOAD_UNSUPPORTED_CLAUSE = Pattern.compile(
|
||||
"(?i)\\b(FIXEDWIDTH|PARQUET|AVRO|ORC|JSON|SHAPEFILE|BZIP2|LZOP|ZSTD"
|
||||
"(?i)\\b(FIXEDWIDTH|AVRO|ORC|JSON|SHAPEFILE|BZIP2|LZOP|ZSTD"
|
||||
+ "|ENCODING|MASTER_SYMMETRIC_KEY"
|
||||
+ "|PARTITION|MAXFILESIZE\\s+\\d+\\s*(?:TB|PB))\\b");
|
||||
|
||||
@@ -437,6 +441,7 @@ public final class CopyStatementParser {
|
||||
options = options.substring(0, semi);
|
||||
}
|
||||
|
||||
boolean parquet = false;
|
||||
boolean csv = false;
|
||||
boolean gzip = false;
|
||||
boolean header = false;
|
||||
@@ -470,6 +475,7 @@ public final class CopyStatementParser {
|
||||
boolean seenDelimiter = false;
|
||||
boolean seenMaxFileSize = false;
|
||||
|
||||
Matcher parquetM = PARQUET_PATTERN.matcher(options);
|
||||
Matcher csvM = CSV_PATTERN.matcher(options);
|
||||
Matcher gzipM = GZIP_PATTERN.matcher(options);
|
||||
Matcher headerM = HEADER_PATTERN.matcher(options);
|
||||
@@ -497,7 +503,13 @@ public final class CopyStatementParser {
|
||||
if (offset >= len) {
|
||||
break;
|
||||
}
|
||||
if (matchClause(extensionM, offset, len)) {
|
||||
if (matchClause(parquetM, offset, len)) {
|
||||
if (parquet) {
|
||||
return null;
|
||||
}
|
||||
parquet = true;
|
||||
offset = parquetM.end();
|
||||
} else if (matchClause(extensionM, offset, len)) {
|
||||
if (seenExtension) {
|
||||
return null;
|
||||
}
|
||||
@@ -626,6 +638,9 @@ public final class CopyStatementParser {
|
||||
return null;
|
||||
}
|
||||
String iamRoleArn = auth.iamRoleArn();
|
||||
if (parquet && (csv || gzip || header || addQuotes || escape || seenDelimiter || seenNull)) {
|
||||
return null;
|
||||
}
|
||||
if (delimiter == null) {
|
||||
delimiter = csv ? "," : "|";
|
||||
}
|
||||
@@ -646,7 +661,7 @@ public final class CopyStatementParser {
|
||||
}
|
||||
return new S3Unload(select, bucket, prefix, delimiter, header, gzip, csv,
|
||||
addQuotes, nullAs, manifest, allowOverwrite, parallel, maxFileSizeBytes, iamRoleArn, extension,
|
||||
escape, cleanPath, encrypted, kmsKeyId, auth.defaultIamRoleRequested);
|
||||
escape, cleanPath, encrypted, kmsKeyId, auth.defaultIamRoleRequested, parquet);
|
||||
}
|
||||
|
||||
private static S3CopyFrom parseCopy(String cleaned, String defaultIamRoleArn) {
|
||||
|
||||
+33
-5
@@ -20,14 +20,14 @@ final class ExtendedS3Exchange {
|
||||
PostgresWireDecoder.FrontendMessage executeFrame,
|
||||
CopyStatementParser.S3Statement statement, S3Service s3Service, IamService iamService,
|
||||
BackendResponseCoordinator coordinator, BackendResponseCoordinator.Ticket ticket) throws IOException {
|
||||
execute(client, backend, executeFrame, statement, s3Service, iamService, null, List.of(), coordinator, ticket);
|
||||
execute(client, backend, executeFrame, statement, s3Service, iamService, null, List.of(), coordinator, ticket, null);
|
||||
}
|
||||
|
||||
static void execute(Socket client, Socket backend,
|
||||
PostgresWireDecoder.FrontendMessage executeFrame,
|
||||
CopyStatementParser.S3Statement statement, S3Service s3Service, IamService iamService,
|
||||
String clusterAccountId, List<String> iamRoleArns, BackendResponseCoordinator coordinator,
|
||||
BackendResponseCoordinator.Ticket ticket) throws IOException {
|
||||
BackendResponseCoordinator.Ticket ticket, RedshiftParquetWriter parquetWriter) throws IOException {
|
||||
BackendResponseCoordinator.GateResult gate;
|
||||
try {
|
||||
gate = coordinator.awaitExtendedExecuteTurn(ticket);
|
||||
@@ -51,7 +51,7 @@ final class ExtendedS3Exchange {
|
||||
}
|
||||
case CopyStatementParser.S3Unload unload -> {
|
||||
CopyResult result = runUnload(client, backend, executeFrame, unload, s3Service, iamService,
|
||||
clusterAccountId, iamRoleArns, coordinator);
|
||||
clusterAccountId, iamRoleArns, coordinator, ticket, parquetWriter);
|
||||
failed = !result.succeeded();
|
||||
deferredReadyForQuery = result.deferredReadyForQuery();
|
||||
}
|
||||
@@ -122,8 +122,35 @@ final class ExtendedS3Exchange {
|
||||
private static CopyResult runUnload(Socket client, Socket backend,
|
||||
PostgresWireDecoder.FrontendMessage executeFrame,
|
||||
CopyStatementParser.S3Unload spec, S3Service s3Service, IamService iamService,
|
||||
String clusterAccountId, List<String> iamRoleArns, BackendResponseCoordinator coordinator) throws IOException {
|
||||
String clusterAccountId, List<String> iamRoleArns, BackendResponseCoordinator coordinator,
|
||||
BackendResponseCoordinator.Ticket ticket, RedshiftParquetWriter parquetWriter) throws IOException {
|
||||
OutputStream backendOut = backend.getOutputStream();
|
||||
List<RedshiftParquetWriter.Column> columns = List.of();
|
||||
if (spec.parquet()) {
|
||||
backendOut.write(new byte[]{'H', 0, 0, 0, 4});
|
||||
backendOut.flush();
|
||||
PostgresWireDecoder preamble = new PostgresWireDecoder(backend.getInputStream());
|
||||
while (!coordinator.isFirstPending(ticket)) {
|
||||
PostgresWireDecoder.FrontendMessage message = preamble.nextMessage();
|
||||
if (message == null) {
|
||||
throw new IOException("Backend closed before Parquet UNLOAD description");
|
||||
}
|
||||
coordinator.onBackendFrame(message.type(), message.body());
|
||||
forward(client, message);
|
||||
if (message.type() == 'E') {
|
||||
forwardClientSyncToBackend(client, backendOut, coordinator);
|
||||
return new CopyResult(false, drainReadyForQuery(client, preamble, coordinator));
|
||||
}
|
||||
}
|
||||
RedshiftParquetWriter.Description description = RedshiftParquetWriter.describe(client, backend, spec.selectQuery());
|
||||
if (description.error() != null) {
|
||||
forward(client, description.error());
|
||||
forwardClientSyncToBackend(client, backendOut, coordinator);
|
||||
return new CopyResult(false, drainReadyForQuery(client,
|
||||
new PostgresWireDecoder(backend.getInputStream()), coordinator));
|
||||
}
|
||||
columns = description.columns();
|
||||
}
|
||||
backendOut.write(executeFrame.toPacketBytes());
|
||||
backendOut.flush();
|
||||
forwardClientSyncToBackend(client, backendOut, coordinator);
|
||||
@@ -140,7 +167,8 @@ final class ExtendedS3Exchange {
|
||||
|
||||
S3CopySimulator.UnloadCollector collector;
|
||||
try {
|
||||
collector = S3CopySimulator.prepareUnload(spec, s3Service, iamService, clusterAccountId, iamRoleArns);
|
||||
collector = S3CopySimulator.prepareUnload(spec, s3Service, iamService, clusterAccountId, iamRoleArns, parquetWriter);
|
||||
collector.columns(columns);
|
||||
} catch (S3CopySimulator.S3TransferException e) {
|
||||
S3CopySimulator.writeCopyFail(backendOut, e.getMessage());
|
||||
drainExecute(client, decoder, coordinator, false);
|
||||
|
||||
+5
-3
@@ -40,6 +40,7 @@ public class RedshiftAuthProxy {
|
||||
private final RdsProxyTlsCertificates tlsCertificates;
|
||||
private final PasswordValidator passwordValidator;
|
||||
private final S3Service s3Service;
|
||||
private final RedshiftParquetWriter parquetWriter;
|
||||
private final IamService iamService;
|
||||
private final SpectrumInterceptor spectrumInterceptor;
|
||||
private final RedshiftAuditLogPublisher auditLogPublisher;
|
||||
@@ -97,7 +98,7 @@ public class RedshiftAuthProxy {
|
||||
int maxConnections, SpectrumInterceptor spectrumInterceptor) {
|
||||
this(clusterKey, backendHost, backendPort, masterUsername, masterPassword, dbName, sigV4,
|
||||
tlsCertificates, passwordValidator, s3Service, iamService, clusterAccountId, iamRoleArns,
|
||||
handshakeTimeoutMillis, backendConnectTimeoutMillis, maxConnections, spectrumInterceptor, null);
|
||||
handshakeTimeoutMillis, backendConnectTimeoutMillis, maxConnections, spectrumInterceptor, null, null);
|
||||
}
|
||||
|
||||
public RedshiftAuthProxy(String clusterKey, String backendHost, int backendPort,
|
||||
@@ -109,7 +110,7 @@ public class RedshiftAuthProxy {
|
||||
List<String> iamRoleArns,
|
||||
int handshakeTimeoutMillis, int backendConnectTimeoutMillis,
|
||||
int maxConnections, SpectrumInterceptor spectrumInterceptor,
|
||||
RedshiftAuditLogPublisher auditLogPublisher) {
|
||||
RedshiftAuditLogPublisher auditLogPublisher, RedshiftParquetWriter parquetWriter) {
|
||||
this.clusterKey = clusterKey;
|
||||
this.backendHost = backendHost;
|
||||
this.backendPort = backendPort;
|
||||
@@ -120,6 +121,7 @@ public class RedshiftAuthProxy {
|
||||
this.tlsCertificates = tlsCertificates;
|
||||
this.passwordValidator = passwordValidator;
|
||||
this.s3Service = s3Service;
|
||||
this.parquetWriter = parquetWriter;
|
||||
this.iamService = iamService;
|
||||
this.spectrumInterceptor = spectrumInterceptor;
|
||||
this.auditLogPublisher = auditLogPublisher;
|
||||
@@ -276,7 +278,7 @@ public class RedshiftAuthProxy {
|
||||
RoleConfiguration roles = roleConfiguration;
|
||||
new RedshiftInterceptingBridge(session.client(), session.backend(), s3Service, iamService,
|
||||
clusterAccountId, roles.iamRoleArns(), spectrumInterceptor, clusterKey, login.database,
|
||||
roles.defaultIamRoleArn(), auditLogPublisher, login.username).run();
|
||||
roles.defaultIamRoleArn(), auditLogPublisher, login.username, parquetWriter).run();
|
||||
publishConnection(client, login, "disconnection");
|
||||
} else {
|
||||
publishConnection(client, login, login.backendUnavailable ? "connection_error" : "authentication failure");
|
||||
|
||||
+10
-8
@@ -64,6 +64,7 @@ public class RedshiftInterceptingBridge {
|
||||
private final Socket client;
|
||||
private final Socket backend;
|
||||
private final S3Service s3Service;
|
||||
private final RedshiftParquetWriter parquetWriter;
|
||||
private final IamService iamService;
|
||||
private final String clusterAccountId;
|
||||
private final List<String> iamRoleArns;
|
||||
@@ -118,7 +119,7 @@ public class RedshiftInterceptingBridge {
|
||||
SpectrumInterceptor spectrumInterceptor, String clusterKey, String databaseName,
|
||||
String defaultIamRoleArn) {
|
||||
this(client, backend, s3Service, iamService, clusterAccountId, iamRoleArns, spectrumInterceptor,
|
||||
clusterKey, databaseName, defaultIamRoleArn, null, null);
|
||||
clusterKey, databaseName, defaultIamRoleArn, null, null, null);
|
||||
}
|
||||
|
||||
public RedshiftInterceptingBridge(Socket client, Socket backend, S3Service s3Service, IamService iamService,
|
||||
@@ -126,17 +127,17 @@ public class RedshiftInterceptingBridge {
|
||||
SpectrumInterceptor spectrumInterceptor, String clusterKey, String databaseName,
|
||||
String defaultIamRoleArn, RedshiftAuditLogPublisher auditLogPublisher) {
|
||||
this(client, backend, s3Service, iamService, clusterAccountId, iamRoleArns, spectrumInterceptor,
|
||||
clusterKey, databaseName, defaultIamRoleArn, auditLogPublisher, null);
|
||||
clusterKey, databaseName, defaultIamRoleArn, auditLogPublisher, null, null);
|
||||
}
|
||||
|
||||
public RedshiftInterceptingBridge(Socket client, Socket backend, S3Service s3Service, IamService iamService,
|
||||
String clusterAccountId, List<String> iamRoleArns,
|
||||
SpectrumInterceptor spectrumInterceptor, String clusterKey, String databaseName,
|
||||
String defaultIamRoleArn, RedshiftAuditLogPublisher auditLogPublisher,
|
||||
String databaseUser) {
|
||||
String databaseUser, RedshiftParquetWriter parquetWriter) {
|
||||
this(client, backend, s3Service, iamService, clusterAccountId, iamRoleArns, spectrumInterceptor,
|
||||
clusterKey, databaseName, defaultIamRoleArn, auditLogPublisher, databaseUser, new ReentrantLock(true),
|
||||
PUMP_PARK_WAIT_MS);
|
||||
PUMP_PARK_WAIT_MS, parquetWriter);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -145,7 +146,7 @@ public class RedshiftInterceptingBridge {
|
||||
*/
|
||||
RedshiftInterceptingBridge(Socket client, Socket backend, ReentrantLock backendLock, long ownershipWaitMillis) {
|
||||
this(client, backend, null, null, null, List.of(), null, null, null, null, null, null, backendLock,
|
||||
ownershipWaitMillis);
|
||||
ownershipWaitMillis, null);
|
||||
}
|
||||
|
||||
private RedshiftInterceptingBridge(Socket client, Socket backend, S3Service s3Service, IamService iamService,
|
||||
@@ -153,8 +154,9 @@ public class RedshiftInterceptingBridge {
|
||||
SpectrumInterceptor spectrumInterceptor, String clusterKey, String databaseName,
|
||||
String defaultIamRoleArn, RedshiftAuditLogPublisher auditLogPublisher,
|
||||
String databaseUser, ReentrantLock backendLock,
|
||||
long ownershipWaitMillis) {
|
||||
long ownershipWaitMillis, RedshiftParquetWriter parquetWriter) {
|
||||
this.client = client;
|
||||
this.parquetWriter = parquetWriter;
|
||||
this.backend = backend;
|
||||
this.s3Service = s3Service;
|
||||
this.iamService = iamService;
|
||||
@@ -306,7 +308,7 @@ public class RedshiftInterceptingBridge {
|
||||
status -> coordinator.onBackendFrame('Z', new byte[]{(byte) status}));
|
||||
case CopyStatementParser.S3Unload unload -> S3CopySimulator.runUnload(
|
||||
client, backend, unload, s3Service, iamService, clusterAccountId, iamRoleArns, coordinator.lastReadyStatus(),
|
||||
status -> coordinator.onBackendFrame('Z', new byte[]{(byte) status}));
|
||||
status -> coordinator.onBackendFrame('Z', new byte[]{(byte) status}), parquetWriter);
|
||||
});
|
||||
if (intercepted) {
|
||||
return;
|
||||
@@ -686,7 +688,7 @@ public class RedshiftInterceptingBridge {
|
||||
try {
|
||||
backend.setSoTimeout(EXCHANGE_READ_TIMEOUT_MS);
|
||||
ExtendedS3Exchange.execute(client, backend, executeFrame, statement, s3Service, iamService,
|
||||
clusterAccountId, iamRoleArns, coordinator, ticket);
|
||||
clusterAccountId, iamRoleArns, coordinator, ticket, parquetWriter);
|
||||
} finally {
|
||||
try {
|
||||
backend.setSoTimeout(PUMP_READ_TIMEOUT_MS);
|
||||
|
||||
+255
@@ -0,0 +1,255 @@
|
||||
package io.github.hectorvent.floci.services.redshift.proxy;
|
||||
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
import io.github.hectorvent.floci.core.common.AwsRegions;
|
||||
import io.github.hectorvent.floci.core.common.PostgresWire;
|
||||
import io.github.hectorvent.floci.core.common.RequestScopes;
|
||||
import io.github.hectorvent.floci.services.floci.duck.FlociDuckClient;
|
||||
import io.github.hectorvent.floci.services.iam.IamService;
|
||||
import io.github.hectorvent.floci.services.s3.S3ScratchSpace;
|
||||
import io.github.hectorvent.floci.services.s3.S3Service;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.DataInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.net.Socket;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
/** Converts PostgreSQL CSV slices using the query's declared types, never data inference. */
|
||||
@ApplicationScoped
|
||||
public class RedshiftParquetWriter {
|
||||
private static final Logger LOG = Logger.getLogger(RedshiftParquetWriter.class);
|
||||
static final String STAGING_BUCKET = S3Service.REDSHIFT_UNLOAD_STAGING_BUCKET;
|
||||
private final FlociDuckClient duck;
|
||||
private final S3Service s3;
|
||||
private final IamService iam;
|
||||
private final String region;
|
||||
|
||||
public RedshiftParquetWriter(FlociDuckClient duck, S3Service s3, IamService iam, EmulatorConfig config) {
|
||||
this.duck = duck;
|
||||
this.s3 = s3;
|
||||
this.iam = iam;
|
||||
region = config.defaultRegion();
|
||||
}
|
||||
|
||||
record Column(String name, String type) { }
|
||||
|
||||
record Description(List<Column> columns, PostgresWireDecoder.FrontendMessage error) { }
|
||||
|
||||
/** Named Parse/Describe/Close leaves the client's portals and transaction intact. */
|
||||
static Description describe(Socket client, Socket backend, String query) throws IOException {
|
||||
String name = "floci_unload_" + UUID.randomUUID().toString().replace("-", "");
|
||||
backend.getOutputStream().write(PostgresWireDecoder.encodeParse(
|
||||
new PostgresWireDecoder.ParseMessage(name, query, List.of()), query));
|
||||
backend.getOutputStream().write(PostgresWire.frame('D', PostgresWire.cStringBytes("S" + name)));
|
||||
backend.getOutputStream().write(PostgresWire.frame('C', PostgresWire.cStringBytes("S" + name)));
|
||||
backend.getOutputStream().write(PostgresWire.frame('H', new byte[0]));
|
||||
backend.getOutputStream().flush();
|
||||
PostgresWireDecoder decoder = new PostgresWireDecoder(backend.getInputStream());
|
||||
byte[] rowDescription = null;
|
||||
S3CopySimulator.S3TransferException rejectedType = null;
|
||||
PostgresWireDecoder.FrontendMessage message;
|
||||
while ((message = decoder.nextMessage()) != null) {
|
||||
if (message.type() == 'N' || message.type() == 'A' || message.type() == 'S') {
|
||||
client.getOutputStream().write(message.toPacketBytes());
|
||||
client.getOutputStream().flush();
|
||||
} else if (message.type() == 'T') {
|
||||
rowDescription = message.body();
|
||||
} else if (message.type() == 'E') {
|
||||
return new Description(List.of(), rejectedType == null ? message
|
||||
: new PostgresWireDecoder.FrontendMessage('E',
|
||||
S3CopySimulator.errorBody(rejectedType.sqlState(), rejectedType.getMessage())));
|
||||
} else if (message.type() == '3') {
|
||||
try {
|
||||
return new Description(rowDescription == null ? List.of() : columns(rowDescription), null);
|
||||
} catch (S3CopySimulator.S3TransferException exception) {
|
||||
rejectedType = exception;
|
||||
// Fail the backend cycle so normal Sync recovery also handles local type errors.
|
||||
String abortSql = "(FLOCI_ABORT_TX)";
|
||||
backend.getOutputStream().write(PostgresWireDecoder.encodeParse(
|
||||
new PostgresWireDecoder.ParseMessage(name, abortSql, List.of()), abortSql));
|
||||
backend.getOutputStream().write(PostgresWire.frame('H', new byte[0]));
|
||||
backend.getOutputStream().flush();
|
||||
}
|
||||
}
|
||||
}
|
||||
throw new IOException("Backend closed while describing UNLOAD query");
|
||||
}
|
||||
|
||||
static List<Column> columns(byte[] description) throws IOException {
|
||||
DataInputStream input = new DataInputStream(new ByteArrayInputStream(description));
|
||||
int count = input.readUnsignedShort();
|
||||
List<Column> columns = new ArrayList<>(count);
|
||||
for (int i = 0; i < count; i++) {
|
||||
ByteArrayOutputStream name = new ByteArrayOutputStream();
|
||||
int character;
|
||||
while ((character = input.readUnsignedByte()) != 0) {
|
||||
name.write(character);
|
||||
}
|
||||
input.readInt(); // table OID
|
||||
input.readShort(); // attribute number
|
||||
int oid = input.readInt();
|
||||
input.readShort(); // type size
|
||||
int modifier = input.readInt();
|
||||
input.readShort(); // format code
|
||||
String columnName = name.toString(StandardCharsets.UTF_8);
|
||||
columns.add(new Column(columnName, type(columnName, oid, modifier)));
|
||||
}
|
||||
return columns;
|
||||
}
|
||||
|
||||
static String type(String column, int oid, int modifier) {
|
||||
return switch (oid) {
|
||||
case 16 -> "BOOLEAN";
|
||||
case 21 -> "SMALLINT";
|
||||
case 23 -> "INTEGER";
|
||||
case 20 -> "BIGINT";
|
||||
case 700 -> "FLOAT";
|
||||
case 701 -> "DOUBLE";
|
||||
case 1082 -> "DATE";
|
||||
case 1114 -> "TIMESTAMP";
|
||||
case 1184 -> "TIMESTAMPTZ";
|
||||
case 1700 -> {
|
||||
if (modifier < 4) {
|
||||
throw unsupported(column, "NUMERIC without declared precision and scale",
|
||||
"Cast it to DECIMAL(p,s), with 1 <= p <= 38 and 0 <= s <= p.");
|
||||
}
|
||||
int precision = (modifier - 4) >> 16;
|
||||
int scale = ((modifier - 4) & 0x7ff) ^ 0x400;
|
||||
scale -= 0x400;
|
||||
if (precision < 1 || precision > 38 || scale < 0 || scale > precision) {
|
||||
throw unsupported(column, "NUMERIC(" + precision + "," + scale + ")",
|
||||
"Cast it to DECIMAL(p,s), with 1 <= p <= 38 and 0 <= s <= p.");
|
||||
}
|
||||
yield "DECIMAL(" + precision + "," + scale + ")";
|
||||
}
|
||||
case 25, 1042, 1043 -> "VARCHAR";
|
||||
default -> {
|
||||
String typeName = switch (oid) {
|
||||
case 17 -> "BYTEA";
|
||||
case 114 -> "JSON";
|
||||
case 1083 -> "TIME";
|
||||
case 1186 -> "INTERVAL";
|
||||
case 1266 -> "TIMETZ";
|
||||
case 2950 -> "UUID";
|
||||
case 3802 -> "JSONB";
|
||||
default -> "PostgreSQL type";
|
||||
};
|
||||
throw unsupported(column, typeName + " (OID " + oid + ")",
|
||||
"Cast it explicitly to a supported scalar type, such as VARCHAR.");
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private static S3CopySimulator.S3TransferException unsupported(String column, String type, String hint) {
|
||||
return new S3CopySimulator.S3TransferException("0A000",
|
||||
"UNLOAD PARQUET does not support column \"" + column.replace("\"", "\"\"")
|
||||
+ "\" of type " + type + ". " + hint, null);
|
||||
}
|
||||
|
||||
List<byte[]> convert(byte[] csv, List<Column> columns, String accountId,
|
||||
RedshiftRoleAccess.RoleSession session, long maxFileSizeBytes) throws IOException {
|
||||
try {
|
||||
return RequestScopes.callAsChecked(accountId,
|
||||
() -> convertScoped(csv, columns, accountId, session, maxFileSizeBytes));
|
||||
} catch (RuntimeException | IOException exception) {
|
||||
throw exception;
|
||||
} catch (Exception exception) {
|
||||
throw new IOException("Unable to convert UNLOAD slice", exception);
|
||||
}
|
||||
}
|
||||
|
||||
private List<byte[]> convertScoped(byte[] csv, List<Column> columns, String accountId,
|
||||
RedshiftRoleAccess.RoleSession session, long maxFileSizeBytes) throws IOException {
|
||||
if (columns.isEmpty()) {
|
||||
throw new IOException("UNLOAD query has no Parquet columns");
|
||||
}
|
||||
S3ScratchSpace.UNLOAD.ensureBucket(s3, region);
|
||||
String root = "unload/" + UUID.randomUUID() + "/";
|
||||
String inputKey = root + "input.csv";
|
||||
String outputKey = root + "output.parquet";
|
||||
try {
|
||||
if (session != null) {
|
||||
iam.registerScratchResource(session.accessKeyId(), AwsArnUtils.Arn.global(
|
||||
AwsRegions.partitionFor(region), "s3", "", STAGING_BUCKET + "/" + root).toString());
|
||||
}
|
||||
s3.putObject(STAGING_BUCKET, inputKey, csv, "text/csv", null);
|
||||
StringBuilder schema = new StringBuilder();
|
||||
StringBuilder projection = new StringBuilder();
|
||||
for (int i = 0; i < columns.size(); i++) {
|
||||
if (i > 0) {
|
||||
schema.append(", ");
|
||||
projection.append(", ");
|
||||
}
|
||||
Column column = columns.get(i);
|
||||
schema.append("'c").append(i).append("': '").append(column.type()).append("'");
|
||||
String expression = "c" + i;
|
||||
if ("TIMESTAMPTZ".equals(column.type())) {
|
||||
expression = "CAST(" + expression + " AS TIMESTAMP)";
|
||||
}
|
||||
projection.append(expression).append(" AS \"")
|
||||
.append(column.name().replace("\"", "\"\"")).append("\"");
|
||||
}
|
||||
String source = csv.length == 0
|
||||
? emptyQuery(columns)
|
||||
: "SELECT " + projection + " FROM read_csv('" + literal("s3://" + STAGING_BUCKET + "/" + inputKey)
|
||||
+ "', header = false, delim = ',', quote = '\"', escape = '\"', nullstr = '', "
|
||||
+ "allow_quoted_nulls = false, auto_detect = false, columns = {"
|
||||
+ schema + "})";
|
||||
String sql = "COPY (" + source + ") TO '"
|
||||
+ literal("s3://" + STAGING_BUCKET + "/" + outputKey)
|
||||
+ "' (FORMAT PARQUET, COMPRESSION SNAPPY, PARQUET_VERSION V1, FILE_SIZE_BYTES "
|
||||
+ maxFileSizeBytes + ", RETURN_STATS true)";
|
||||
String setup = "SET TimeZone = 'UTC'; SET threads = 1;";
|
||||
List<Map<String, Object>> files = session == null
|
||||
? duck.query(sql, setup, accountId)
|
||||
: duck.query(sql, setup, session.accessKeyId(), session.secretAccessKey(), session.sessionToken());
|
||||
if (files.isEmpty()) {
|
||||
throw new IOException("DuckDB returned no Parquet output files");
|
||||
}
|
||||
List<byte[]> result = new ArrayList<>();
|
||||
for (Map<String, Object> file : files) {
|
||||
String key = file.get("filename").toString().substring(("s3://" + STAGING_BUCKET + "/").length());
|
||||
try (InputStream input = s3.openObjectStream(STAGING_BUCKET, key, null)) {
|
||||
result.add(input.readAllBytes());
|
||||
}
|
||||
}
|
||||
return result;
|
||||
} finally {
|
||||
if (session != null) {
|
||||
iam.clearScratchResource(session.accessKeyId());
|
||||
}
|
||||
try {
|
||||
s3.deleteObjectsWithPrefix(STAGING_BUCKET, root, ignored -> {
|
||||
// Internal staging cleanup does not use the external role.
|
||||
});
|
||||
} catch (RuntimeException exception) {
|
||||
LOG.warnv(exception, "Could not remove UNLOAD staging prefix {0}", root);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static String emptyQuery(List<Column> columns) {
|
||||
List<String> expressions = new ArrayList<>();
|
||||
for (Column column : columns) {
|
||||
String type = "TIMESTAMPTZ".equals(column.type()) ? "TIMESTAMP" : column.type();
|
||||
expressions.add("CAST(NULL AS " + type + ") AS \""
|
||||
+ column.name().replace("\"", "\"\"") + "\"");
|
||||
}
|
||||
return "SELECT " + String.join(", ", expressions) + " WHERE false";
|
||||
}
|
||||
|
||||
private static String literal(String value) {
|
||||
return value.replace("'", "''");
|
||||
}
|
||||
|
||||
}
|
||||
+5
-3
@@ -35,6 +35,7 @@ public class RedshiftProxyManager {
|
||||
private final IamService iamService;
|
||||
private final SpectrumInterceptor spectrumInterceptor;
|
||||
private final EmulatorConfig config;
|
||||
private final RedshiftParquetWriter parquetWriter;
|
||||
private final RedshiftAuditLogPublisher auditLogPublisher;
|
||||
private final ConcurrentHashMap<String, RedshiftAuthProxy> proxies = new ConcurrentHashMap<>();
|
||||
/**
|
||||
@@ -53,20 +54,21 @@ public class RedshiftProxyManager {
|
||||
public RedshiftProxyManager(RdsSigV4Validator sigV4Validator, RdsProxyTlsCertificates tlsCertificates,
|
||||
S3Service s3Service, IamService iamService, EmulatorConfig config,
|
||||
SpectrumInterceptor spectrumInterceptor) {
|
||||
this(sigV4Validator, tlsCertificates, s3Service, iamService, config, spectrumInterceptor, null);
|
||||
this(sigV4Validator, tlsCertificates, s3Service, iamService, config, spectrumInterceptor, null, null);
|
||||
}
|
||||
|
||||
@Inject
|
||||
public RedshiftProxyManager(RdsSigV4Validator sigV4Validator, RdsProxyTlsCertificates tlsCertificates,
|
||||
S3Service s3Service, IamService iamService, EmulatorConfig config,
|
||||
SpectrumInterceptor spectrumInterceptor,
|
||||
RedshiftAuditLogPublisher auditLogPublisher) {
|
||||
RedshiftAuditLogPublisher auditLogPublisher, RedshiftParquetWriter parquetWriter) {
|
||||
this.sigV4Validator = sigV4Validator;
|
||||
this.tlsCertificates = tlsCertificates;
|
||||
this.s3Service = s3Service;
|
||||
this.iamService = iamService;
|
||||
this.spectrumInterceptor = spectrumInterceptor;
|
||||
this.config = config;
|
||||
this.parquetWriter = parquetWriter;
|
||||
this.auditLogPublisher = auditLogPublisher;
|
||||
}
|
||||
|
||||
@@ -105,7 +107,7 @@ public class RedshiftProxyManager {
|
||||
clusterAccountId,
|
||||
iamRoleArns,
|
||||
redshiftConfig.proxyHandshakeTimeoutMillis(), redshiftConfig.proxyBackendConnectTimeoutMillis(),
|
||||
redshiftConfig.proxyMaxConnections(), spectrumInterceptor, auditLogPublisher);
|
||||
redshiftConfig.proxyMaxConnections(), spectrumInterceptor, auditLogPublisher, parquetWriter);
|
||||
proxy.updateIamRoles(iamRoleArns, defaultIamRoleArn);
|
||||
try {
|
||||
proxy.start(proxyPort);
|
||||
|
||||
+70
-13
@@ -86,6 +86,8 @@ public final class S3CopySimulator {
|
||||
interface UnloadCollector extends AutoCloseable {
|
||||
void accept(byte[] body) throws IOException;
|
||||
|
||||
void columns(List<RedshiftParquetWriter.Column> columns);
|
||||
|
||||
void complete() throws IOException;
|
||||
|
||||
void abort();
|
||||
@@ -284,11 +286,12 @@ public final class S3CopySimulator {
|
||||
|
||||
static UnloadCollector prepareUnload(CopyStatementParser.S3Unload spec, S3Service s3, IamService iamService,
|
||||
String clusterAccountId) {
|
||||
return prepareUnload(spec, s3, iamService, clusterAccountId, null);
|
||||
return prepareUnload(spec, s3, iamService, clusterAccountId, null, null);
|
||||
}
|
||||
|
||||
static UnloadCollector prepareUnload(CopyStatementParser.S3Unload spec, S3Service s3, IamService iamService,
|
||||
String clusterAccountId, List<String> associatedRoleArns) {
|
||||
String clusterAccountId, List<String> associatedRoleArns,
|
||||
RedshiftParquetWriter parquetWriter) {
|
||||
requireDefaultIamRole(spec);
|
||||
RedshiftRoleAccess.RoleSession roleSession = spec.iamRoleArn() != null
|
||||
? RedshiftRoleAccess.resolveRoleSession(spec.iamRoleArn(), iamService, clusterAccountId, associatedRoleArns)
|
||||
@@ -348,7 +351,7 @@ public final class S3CopySimulator {
|
||||
"UNLOAD memory budget exhausted; retry shortly", null);
|
||||
}
|
||||
try {
|
||||
return new S3UnloadCollector(spec, s3, iamService, roleSession, cleanPath);
|
||||
return new S3UnloadCollector(spec, s3, iamService, roleSession, cleanPath, parquetWriter, clusterAccountId);
|
||||
} catch (IOException e) {
|
||||
UNLOAD_HEAP_MIB.release(UNLOAD_INITIAL_MIB);
|
||||
RedshiftRoleAccess.releaseRoleSession(roleSession, spec.iamRoleArn(), iamService);
|
||||
@@ -1037,15 +1040,16 @@ public final class S3CopySimulator {
|
||||
public static boolean runUnload(Socket client, Socket backend,
|
||||
CopyStatementParser.S3Unload spec, S3Service s3, IamService iamService, String clusterAccountId,
|
||||
char txStatus, IntConsumer onStatusChange) throws IOException {
|
||||
return runUnload(client, backend, spec, s3, iamService, clusterAccountId, null, txStatus, onStatusChange);
|
||||
return runUnload(client, backend, spec, s3, iamService, clusterAccountId, null, txStatus, onStatusChange, null);
|
||||
}
|
||||
|
||||
public static boolean runUnload(Socket client, Socket backend,
|
||||
CopyStatementParser.S3Unload spec, S3Service s3, IamService iamService, String clusterAccountId,
|
||||
List<String> associatedRoleArns, char txStatus, IntConsumer onStatusChange) throws IOException {
|
||||
List<String> associatedRoleArns, char txStatus, IntConsumer onStatusChange,
|
||||
RedshiftParquetWriter parquetWriter) throws IOException {
|
||||
UnloadCollector collector;
|
||||
try {
|
||||
collector = prepareUnload(spec, s3, iamService, clusterAccountId, associatedRoleArns);
|
||||
collector = prepareUnload(spec, s3, iamService, clusterAccountId, associatedRoleArns, parquetWriter);
|
||||
} catch (S3TransferException e) {
|
||||
LOG.debugv(e, "UNLOAD preparation failed for s3://{0}/{1}", spec.bucket(), spec.prefix());
|
||||
sendError(client, backend, e.sqlState(), e.getMessage(), txStatus, onStatusChange);
|
||||
@@ -1053,6 +1057,17 @@ public final class S3CopySimulator {
|
||||
}
|
||||
|
||||
try (collector) {
|
||||
if (spec.parquet()) {
|
||||
RedshiftParquetWriter.Description description = RedshiftParquetWriter.describe(client, backend, spec.selectQuery());
|
||||
if (description.error() != null) {
|
||||
forward(client, description.error());
|
||||
backend.getOutputStream().write(new byte[]{'S', 0, 0, 0, 4});
|
||||
backend.getOutputStream().flush();
|
||||
drainToReadyForQuery(new PostgresWireDecoder(backend.getInputStream()), client, onStatusChange);
|
||||
return true;
|
||||
}
|
||||
collector.columns(description.columns());
|
||||
}
|
||||
return runUnloadStreaming(client, backend, spec, collector, txStatus, onStatusChange);
|
||||
}
|
||||
}
|
||||
@@ -1242,6 +1257,9 @@ public final class S3CopySimulator {
|
||||
}
|
||||
|
||||
private static String fabricateUnloadCopy(CopyStatementParser.S3Unload spec) {
|
||||
if (spec.parquet()) {
|
||||
return "COPY (" + spec.selectQuery() + ") TO STDOUT WITH (FORMAT csv, DELIMITER ',')";
|
||||
}
|
||||
boolean csvFraming = spec.csv() || spec.addQuotes() || spec.header();
|
||||
StringBuilder sql = new StringBuilder("COPY (").append(spec.selectQuery())
|
||||
.append(") TO STDOUT WITH (FORMAT ").append(csvFraming ? "csv" : "text");
|
||||
@@ -1262,6 +1280,10 @@ public final class S3CopySimulator {
|
||||
|
||||
private static final class S3UnloadCollector implements UnloadCollector {
|
||||
private final CopyStatementParser.S3Unload spec;
|
||||
private final RedshiftParquetWriter parquetWriter;
|
||||
private final String accountId;
|
||||
private List<RedshiftParquetWriter.Column> columns = List.of();
|
||||
private boolean quotedCsv;
|
||||
private final S3Service s3;
|
||||
private final IamService iamService;
|
||||
private final RedshiftRoleAccess.RoleSession roleSession;
|
||||
@@ -1290,22 +1312,38 @@ public final class S3CopySimulator {
|
||||
|
||||
private S3UnloadCollector(CopyStatementParser.S3Unload spec, S3Service s3,
|
||||
IamService iamService, RedshiftRoleAccess.RoleSession roleSession,
|
||||
boolean cleanPath) throws IOException {
|
||||
boolean cleanPath, RedshiftParquetWriter parquetWriter,
|
||||
String accountId) throws IOException {
|
||||
this.spec = spec;
|
||||
this.parquetWriter = parquetWriter;
|
||||
this.accountId = accountId;
|
||||
this.cleanPathPending = cleanPath;
|
||||
this.s3 = s3;
|
||||
this.iamService = iamService;
|
||||
this.roleSession = roleSession;
|
||||
threshold = spec.maxFileSizeBytes() > 0 ? spec.maxFileSizeBytes() : UNLOAD_TARGET_FILE_BYTES;
|
||||
contentType = spec.gzip() ? "application/gzip" : "text/plain";
|
||||
contentType = spec.parquet() ? "application/octet-stream"
|
||||
: spec.gzip() ? "application/gzip" : "text/plain";
|
||||
acc = newAccumulator();
|
||||
headerBuf = spec.header() ? new ByteArrayOutputStream() : null;
|
||||
capturingHeader = spec.header();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void columns(List<RedshiftParquetWriter.Column> columns) {
|
||||
this.columns = columns;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void accept(byte[] body) throws IOException {
|
||||
ensureOpen();
|
||||
if (spec.parquet()) {
|
||||
for (byte value : body) {
|
||||
if (value == '"') {
|
||||
quotedCsv = !quotedCsv;
|
||||
}
|
||||
}
|
||||
}
|
||||
runCleanPath();
|
||||
int dataStart = 0;
|
||||
if (capturingHeader) {
|
||||
@@ -1346,7 +1384,8 @@ public final class S3CopySimulator {
|
||||
fail(SQLSTATE_PROGRAM_LIMIT_EXCEEDED,
|
||||
"UNLOAD result exceeds the " + UNLOAD_MAX_TOTAL_BYTES + "-byte limit", null);
|
||||
}
|
||||
if (slicePayload >= threshold && lastByteNewline) {
|
||||
long bufferThreshold = spec.parquet() ? UNLOAD_TARGET_FILE_BYTES : threshold;
|
||||
if (slicePayload >= bufferThreshold && lastByteNewline && !quotedCsv) {
|
||||
writeCurrentSlice();
|
||||
resetSlice();
|
||||
}
|
||||
@@ -1358,7 +1397,7 @@ public final class S3CopySimulator {
|
||||
runCleanPath();
|
||||
byte[] payload = finishSlice(acc, sink);
|
||||
if (slicePayload > 0 || writtenKeys.isEmpty()) {
|
||||
writePayload(payload, sliceIndex);
|
||||
writeSlice(payload);
|
||||
}
|
||||
if (spec.manifest()) {
|
||||
try {
|
||||
@@ -1439,8 +1478,26 @@ public final class S3CopySimulator {
|
||||
|
||||
private void writeCurrentSlice() throws IOException {
|
||||
byte[] payload = finishSlice(acc, sink);
|
||||
writePayload(payload, sliceIndex);
|
||||
sliceIndex++;
|
||||
writeSlice(payload);
|
||||
}
|
||||
|
||||
private void writeSlice(byte[] payload) throws IOException {
|
||||
if (spec.parquet()) {
|
||||
try {
|
||||
for (byte[] file : parquetWriter.convert(payload, columns, accountId, roleSession, threshold)) {
|
||||
writePayload(file, sliceIndex++);
|
||||
}
|
||||
} catch (IOException | RuntimeException exception) {
|
||||
abort();
|
||||
if (exception instanceof S3TransferException transfer) {
|
||||
throw transfer;
|
||||
}
|
||||
throw new S3TransferException(SQLSTATE_INTERNAL,
|
||||
"UNLOAD Parquet conversion failed: " + exception.getMessage(), exception);
|
||||
}
|
||||
} else {
|
||||
writePayload(payload, sliceIndex++);
|
||||
}
|
||||
}
|
||||
|
||||
private void writePayload(byte[] payload, int index) {
|
||||
@@ -1513,7 +1570,7 @@ public final class S3CopySimulator {
|
||||
// EXTENSION 'txt.gz' GZIP), so the caller's extension is the whole suffix.
|
||||
return spec.extension().startsWith(".") ? base + spec.extension() : base + "." + spec.extension();
|
||||
}
|
||||
return spec.gzip() ? base + ".gz" : base;
|
||||
return spec.parquet() ? base + ".parquet" : spec.gzip() ? base + ".gz" : base;
|
||||
}
|
||||
|
||||
private static byte[] finishSlice(OutputStream acc, ByteArrayOutputStream sink) throws IOException {
|
||||
|
||||
+8
-27
@@ -18,6 +18,7 @@ import io.github.hectorvent.floci.services.glue.model.Table;
|
||||
import io.github.hectorvent.floci.services.iam.IamService;
|
||||
import io.github.hectorvent.floci.services.redshift.proxy.RedshiftRoleAccess;
|
||||
import io.github.hectorvent.floci.services.redshift.proxy.S3CopySimulator;
|
||||
import io.github.hectorvent.floci.services.s3.S3ScratchSpace;
|
||||
import io.github.hectorvent.floci.services.s3.S3Service;
|
||||
import io.github.hectorvent.floci.services.s3.model.S3Object;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
@@ -787,7 +788,7 @@ public class ExternalTableMaterializer {
|
||||
String partition = AwsRegions.partitionFor(config.defaultRegion());
|
||||
String scratchArn = AwsArnUtils.Arn.global(partition, "s3", "",
|
||||
SCRATCH_BUCKET + "/" + scratchKey).toString();
|
||||
iamService.registerSpectrumScratchResource(roleSession.accessKeyId(), scratchArn);
|
||||
iamService.registerScratchResource(roleSession.accessKeyId(), scratchArn);
|
||||
}
|
||||
readWithDuckDb(session.accountId(), roleSession, table, sources,
|
||||
config.services().redshift().spectrumMaxRows(), scratchKey);
|
||||
@@ -831,7 +832,7 @@ public class ExternalTableMaterializer {
|
||||
throw exception;
|
||||
} finally {
|
||||
if (roleSession != null && roleSession.accessKeyId() != null) {
|
||||
iamService.clearSpectrumScratchResource(roleSession.accessKeyId());
|
||||
iamService.clearScratchResource(roleSession.accessKeyId());
|
||||
}
|
||||
if (scratchKey != null) {
|
||||
String cleanupKey = scratchKey;
|
||||
@@ -963,7 +964,11 @@ public class ExternalTableMaterializer {
|
||||
|
||||
private void prepareScratchBucket(String accountId) {
|
||||
RequestScopes.runAs(accountId, () -> {
|
||||
ensureScratchBucket();
|
||||
try {
|
||||
S3ScratchSpace.SPECTRUM.ensureBucket(s3Service, config.defaultRegion());
|
||||
} catch (IOException exception) {
|
||||
throw new SpectrumReadException(SQLSTATE_LOAD_FAILED, exception.getMessage(), exception);
|
||||
}
|
||||
if (sweptAccounts.add(accountId)) {
|
||||
sweepStaleScratchObjects();
|
||||
}
|
||||
@@ -1058,30 +1063,6 @@ public class ExternalTableMaterializer {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates the scratch bucket and tags it as ours. A bucket of that name that carries no tag belongs to
|
||||
* the user: it is neither written to nor swept, and the load fails instead of mixing with it.
|
||||
*/
|
||||
private void ensureScratchBucket() {
|
||||
boolean created = true;
|
||||
try {
|
||||
s3Service.createInternalBucket(SCRATCH_BUCKET, config.defaultRegion());
|
||||
} catch (AwsException exception) {
|
||||
if (!"BucketAlreadyOwnedByYou".equals(exception.getErrorCode())) {
|
||||
throw exception;
|
||||
}
|
||||
created = false;
|
||||
}
|
||||
if (created) {
|
||||
s3Service.putBucketTagging(SCRATCH_BUCKET,
|
||||
Map.of(S3Service.INTERNAL_BUCKET_TAG_KEY, S3Service.REDSHIFT_SPECTRUM_SCRATCH_TAG_VALUE));
|
||||
} else if (!S3Service.REDSHIFT_SPECTRUM_SCRATCH_TAG_VALUE.equals(
|
||||
s3Service.getBucketTagging(SCRATCH_BUCKET).get(S3Service.INTERNAL_BUCKET_TAG_KEY))) {
|
||||
throw new SpectrumReadException(SQLSTATE_LOAD_FAILED, "Bucket \"" + SCRATCH_BUCKET
|
||||
+ "\" already exists and is not the Spectrum scratch bucket");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A JVM that dies mid-load leaves its scratch object behind. The first load of an account removes the
|
||||
* old ones; a recent object may belong to a load still running, so only stale ones go.
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
package io.github.hectorvent.floci.services.s3;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.services.s3.model.Bucket;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/** Internal S3 transfers retain separate object and prefix permissions. */
|
||||
public enum S3ScratchSpace {
|
||||
SPECTRUM(S3Service.REDSHIFT_SPECTRUM_SCRATCH_BUCKET, S3Service.REDSHIFT_SPECTRUM_SCRATCH_TAG_VALUE,
|
||||
"spectrum-%s\\.csv", Set.of("s3:PutObject", "s3:DeleteObject", "s3:AbortMultipartUpload")),
|
||||
UNLOAD(S3Service.REDSHIFT_UNLOAD_STAGING_BUCKET, S3Service.REDSHIFT_UNLOAD_STAGING_TAG_VALUE,
|
||||
"unload/%s/", Set.of("s3:GetObject", "s3:PutObject", "s3:DeleteObject", "s3:AbortMultipartUpload", "s3:ListBucket"));
|
||||
|
||||
private final String bucketName;
|
||||
private final String tagValue;
|
||||
private final Pattern resourcePattern;
|
||||
private final Set<String> actions;
|
||||
|
||||
S3ScratchSpace(String bucketName, String tagValue, String keyPattern, Set<String> actions) {
|
||||
this.bucketName = bucketName;
|
||||
this.tagValue = tagValue;
|
||||
this.actions = actions;
|
||||
resourcePattern = Pattern.compile("arn:" + AwsArnUtils.PARTITION_REGEX + ":s3:::" + Pattern.quote(bucketName)
|
||||
+ "/" + keyPattern.formatted("[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}"));
|
||||
}
|
||||
|
||||
public String bucketName() {
|
||||
return bucketName;
|
||||
}
|
||||
|
||||
boolean matchesBucket(Bucket bucket) {
|
||||
return bucketName.equals(bucket.getName()) && bucket.getTags() != null
|
||||
&& tagValue.equals(bucket.getTags().get(S3Service.INTERNAL_BUCKET_TAG_KEY));
|
||||
}
|
||||
|
||||
/** Creation and tagging must finish before another transfer checks ownership. */
|
||||
public synchronized void ensureBucket(S3Service s3, String region) throws IOException {
|
||||
try {
|
||||
s3.createInternalBucket(bucketName, region);
|
||||
} catch (AwsException exception) {
|
||||
if (!"BucketAlreadyOwnedByYou".equals(exception.getErrorCode())) {
|
||||
throw exception;
|
||||
}
|
||||
if (!tagValue.equals(s3.getBucketTagging(bucketName).get(S3Service.INTERNAL_BUCKET_TAG_KEY))) {
|
||||
throw new IOException("Bucket \"" + bucketName + "\" already exists and is not Floci scratch space");
|
||||
}
|
||||
return;
|
||||
}
|
||||
s3.putBucketTagging(bucketName, Map.of(S3Service.INTERNAL_BUCKET_TAG_KEY, tagValue));
|
||||
}
|
||||
|
||||
public boolean permits(String action, String registeredArn, List<String> resources, String listPrefix) {
|
||||
if (!actions.contains(action) || resources.isEmpty() || !resourcePattern.matcher(registeredArn).matches()) {
|
||||
return false;
|
||||
}
|
||||
if ("s3:ListBucket".equals(action)) {
|
||||
AwsArnUtils.Arn arn = AwsArnUtils.parse(registeredArn);
|
||||
String bucketArn = AwsArnUtils.Arn.global(arn.partition(), "s3", "", bucketName).toString();
|
||||
String allowedPrefix = arn.resource().substring(bucketName.length() + 1);
|
||||
return listPrefix != null && listPrefix.startsWith(allowedPrefix)
|
||||
&& resources.stream().allMatch(bucketArn::equals);
|
||||
}
|
||||
return resources.stream().allMatch(resource -> this == UNLOAD
|
||||
? resource.startsWith(registeredArn) : resource.equals(registeredArn));
|
||||
}
|
||||
}
|
||||
@@ -117,6 +117,8 @@ public class S3Service implements Resettable, ResourceProvider {
|
||||
public static final String INTERNAL_BUCKET_PREFIX = "floci-internal-";
|
||||
public static final String REDSHIFT_SPECTRUM_SCRATCH_BUCKET =
|
||||
INTERNAL_BUCKET_PREFIX + "redshift-spectrum-scratch";
|
||||
public static final String REDSHIFT_UNLOAD_STAGING_BUCKET = INTERNAL_BUCKET_PREFIX + "redshift-unload-staging";
|
||||
public static final String REDSHIFT_UNLOAD_STAGING_TAG_VALUE = "redshift-unload-staging";
|
||||
public static final String INTERNAL_BUCKET_TAG_KEY = "floci:internal";
|
||||
public static final String REDSHIFT_SPECTRUM_SCRATCH_TAG_VALUE = "redshift-spectrum-scratch";
|
||||
private static final String AUTHENTICATED_USERS_GROUP_URI = "http://acs.amazonaws.com/groups/global/AuthenticatedUsers";
|
||||
@@ -614,26 +616,16 @@ public class S3Service implements Resettable, ResourceProvider {
|
||||
|
||||
public List<Bucket> listBuckets() {
|
||||
return bucketStore.scan(key -> true).stream()
|
||||
.filter(bucket -> !isSpectrumScratchBucket(bucket))
|
||||
.filter(bucket -> !isScratchBucket(bucket))
|
||||
.toList();
|
||||
}
|
||||
|
||||
/**
|
||||
* The Spectrum scratch bucket is told apart from a user bucket of the same name by the tag the
|
||||
* materializer puts on it, so a user's own bucket is never hidden or treated as scratch space.
|
||||
*/
|
||||
private static boolean isSpectrumScratchBucket(Bucket bucket) {
|
||||
return REDSHIFT_SPECTRUM_SCRATCH_BUCKET.equals(bucket.getName())
|
||||
&& bucket.getTags() != null
|
||||
&& REDSHIFT_SPECTRUM_SCRATCH_TAG_VALUE.equals(bucket.getTags().get(INTERNAL_BUCKET_TAG_KEY));
|
||||
private static boolean isScratchBucket(Bucket bucket) {
|
||||
return Arrays.stream(S3ScratchSpace.values()).anyMatch(space -> space.matchesBucket(bucket));
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if the named bucket is Floci's internal Redshift Spectrum scratch bucket,
|
||||
* verified by its name and internal tag.
|
||||
*/
|
||||
public boolean isSpectrumScratchBucket(String bucketName) {
|
||||
return resolveBucket(bucketName).filter(S3Service::isSpectrumScratchBucket).isPresent();
|
||||
public boolean isScratchBucket(String bucketName) {
|
||||
return resolveBucket(bucketName).filter(S3Service::isScratchBucket).isPresent();
|
||||
}
|
||||
|
||||
public String getBucketOwnerAccountId(String bucketName) {
|
||||
|
||||
Reference in new issue
Block a user