mirror of
https://github.com/floci-io/floci.git
synced 2026-11-27 07:39:24 -05:00
feat(redshift): support more COPY and UNLOAD options (#5204)
* feat(redshift): support more COPY and UNLOAD options COPY now accepts REGION, CREDENTIALS, key-based credentials, EMPTYASNULL, BLANKSASNULL, REMOVEQUOTES, ACCEPTINVCHARS and TRUNCATECOLUMNS. UNLOAD now accepts REGION, CREDENTIALS, key-based credentials and EXTENSION. Field content options run in a new CopyRecordTransformer; TRUNCATECOLUMNS reads column lengths from the catalog and so needs the Simple Query protocol. Clauses that cannot be honoured still fail open to PostgreSQL. * feat(redshift): support UNLOAD ESCAPE, CLEANPATH and server-side encryption options UNLOAD now accepts ESCAPE (text framing only), CLEANPATH, ENCRYPTED AUTO and ENCRYPTED with KMS_KEY_ID, which is stored as aws:kms server-side encryption on the data and manifest objects. CLEANPATH lists and authorizes every delete up front but removes the objects only when the first output arrives, so a query that PostgreSQL rejects keeps the previous export. An empty prefix, ALLOWOVERWRITE and client-side encryption still fail open to PostgreSQL. * fix(redshift): address review findings on COPY and UNLOAD options - Reject blank access key, secret, session token and IAM role so an empty pair cannot enable unsigned S3 access. - CLEANPATH lists and authorizes the prefix again when the first output arrives, so an object uploaded since preparation does not survive. - REMOVEQUOTES no longer closes a text-mode field on an escaped quote. - TRUNCATECOLUMNS counts characters, as PostgreSQL does for varchar(n), and cuts decoded text so escape sequences are never split. - Bound the heap used by field-level COPY options with a per-object size limit and a budget shared across connections. * fix(redshift): delete the CLEANPATH prefix under one bucket lock S3Service.deleteObjectsWithPrefix lists the prefix, authorizes every key and deletes them while holding the bucket monitor that PutObject and DeleteObject already use, so an upload cannot land between the listing and the deletes and survive next to the new export. * fix(redshift): measure TRUNCATECOLUMNS in bytes and tighten review follow-ups Redshift counts CHAR(n) and VARCHAR(n) in bytes, so TRUNCATECOLUMNS now measures decoded bytes and cuts on a character boundary instead of counting characters. The UNLOAD docs described bare ENCRYPTED as client-side; client-side is the MASTER_SYMMETRIC_KEY form. The concurrent-put lock test now waits for the put thread to be BLOCKED instead of a fixed 300 ms timeout. * style(redshift): fix import order in S3CopySimulatorTest
This commit is contained in:
1 parent
52985a2f19
commit
38ce99ba54
10 files changed
+1889
-66
No files matched your search
+352
@@ -0,0 +1,352 @@
|
||||
package io.github.hectorvent.floci.services.redshift.proxy;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Applies the COPY options that change field content to the bytes of one S3 object before they
|
||||
* reach PostgreSQL's {@code COPY ... FROM STDIN}. The object is already fully in memory, so the
|
||||
* transform works on a byte array: there are no chunk boundaries to straddle.
|
||||
*/
|
||||
final class CopyRecordTransformer {
|
||||
|
||||
private static final String SQLSTATE_INTERNAL = "XX000";
|
||||
private static final byte NEWLINE = '\n';
|
||||
private static final byte CARRIAGE_RETURN = '\r';
|
||||
private static final byte BACKSLASH = '\\';
|
||||
private static final byte DOUBLE_QUOTE = '"';
|
||||
private static final byte SINGLE_QUOTE = '\'';
|
||||
|
||||
private record Field(int tokenEnd, byte[] value, boolean quoted) {
|
||||
}
|
||||
|
||||
private final CopyStatementParser.CopyTransforms transforms;
|
||||
private final boolean csv;
|
||||
private final byte delimiter;
|
||||
private final byte[] nullMarker;
|
||||
private final List<Integer> columnMaxBytes;
|
||||
|
||||
CopyRecordTransformer(CopyStatementParser.S3CopyFrom spec, List<Integer> columnMaxBytes) {
|
||||
this.transforms = spec.transforms();
|
||||
this.csv = spec.csv();
|
||||
String delimiterText = spec.delimiter() != null ? spec.delimiter() : (spec.csv() ? "," : "|");
|
||||
this.delimiter = delimiterText.getBytes(StandardCharsets.UTF_8)[0];
|
||||
String marker = spec.nullAs() != null ? spec.nullAs() : (spec.csv() ? "" : "\\N");
|
||||
this.nullMarker = marker.getBytes(StandardCharsets.UTF_8);
|
||||
this.columnMaxBytes = columnMaxBytes;
|
||||
}
|
||||
|
||||
byte[] apply(byte[] input) {
|
||||
byte[] data = transforms.invalidCharReplacement() != null
|
||||
? sanitizeUtf8(input, (byte) transforms.invalidCharReplacement().charValue())
|
||||
: input;
|
||||
if (!transforms.fieldLevel()) {
|
||||
return data;
|
||||
}
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream(data.length + 16);
|
||||
int position = 0;
|
||||
while (position < data.length) {
|
||||
position = transformRecord(data, position, out);
|
||||
}
|
||||
return out.toByteArray();
|
||||
}
|
||||
|
||||
static byte[] sanitizeUtf8(byte[] input, byte replacement) {
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream(input.length);
|
||||
int i = 0;
|
||||
while (i < input.length) {
|
||||
int length = validSequenceLength(input, i);
|
||||
if (length == 0) {
|
||||
out.write(replacement);
|
||||
i++;
|
||||
} else {
|
||||
out.write(input, i, length);
|
||||
i += length;
|
||||
}
|
||||
}
|
||||
return out.toByteArray();
|
||||
}
|
||||
|
||||
private static int validSequenceLength(byte[] bytes, int index) {
|
||||
int lead = bytes[index] & 0xFF;
|
||||
if (lead < 0x80) {
|
||||
return 1;
|
||||
}
|
||||
int length;
|
||||
if (lead >= 0xC2 && lead <= 0xDF) {
|
||||
length = 2;
|
||||
} else if (lead >= 0xE0 && lead <= 0xEF) {
|
||||
length = 3;
|
||||
} else if (lead >= 0xF0 && lead <= 0xF4) {
|
||||
length = 4;
|
||||
} else {
|
||||
return 0;
|
||||
}
|
||||
if (index + length > bytes.length) {
|
||||
return 0;
|
||||
}
|
||||
for (int k = 1; k < length; k++) {
|
||||
if ((bytes[index + k] & 0xC0) != 0x80) {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
int second = bytes[index + 1] & 0xFF;
|
||||
boolean overlongOrOutOfRange = (lead == 0xE0 && second < 0xA0)
|
||||
|| (lead == 0xED && second > 0x9F)
|
||||
|| (lead == 0xF0 && second < 0x90)
|
||||
|| (lead == 0xF4 && second > 0x8F);
|
||||
return overlongOrOutOfRange ? 0 : length;
|
||||
}
|
||||
|
||||
private int transformRecord(byte[] data, int start, ByteArrayOutputStream out) {
|
||||
int position = start;
|
||||
int column = 0;
|
||||
while (true) {
|
||||
Field field = scanField(data, position);
|
||||
writeField(field, column, out);
|
||||
position = field.tokenEnd();
|
||||
if (position >= data.length) {
|
||||
out.write(NEWLINE);
|
||||
return data.length;
|
||||
}
|
||||
if (data[position] == NEWLINE) {
|
||||
out.write(NEWLINE);
|
||||
return position + 1;
|
||||
}
|
||||
if (isCrlfAt(data, position)) {
|
||||
out.write(NEWLINE);
|
||||
return Math.min(position + 2, data.length);
|
||||
}
|
||||
if (data[position] != delimiter) {
|
||||
throw malformed("unexpected character after closing quote");
|
||||
}
|
||||
out.write(delimiter);
|
||||
position++;
|
||||
column++;
|
||||
}
|
||||
}
|
||||
|
||||
private Field scanField(byte[] data, int start) {
|
||||
int length = data.length;
|
||||
if (start < length && transforms.removeQuotes()
|
||||
&& (data[start] == DOUBLE_QUOTE || data[start] == SINGLE_QUOTE)) {
|
||||
byte quote = data[start];
|
||||
for (int j = start + 1; j < length; j++) {
|
||||
if (!csv && data[j] == BACKSLASH) {
|
||||
// Text mode: a backslash escapes the next byte, so an escaped quote never closes the field.
|
||||
j++;
|
||||
continue;
|
||||
}
|
||||
boolean closes = data[j] == quote
|
||||
&& (j + 1 == length || data[j + 1] == delimiter || data[j + 1] == NEWLINE
|
||||
|| isCrlfAt(data, j + 1));
|
||||
if (closes) {
|
||||
return new Field(j + 1, Arrays.copyOfRange(data, start + 1, j), true);
|
||||
}
|
||||
}
|
||||
throw malformed("quoted field has no closing quote");
|
||||
}
|
||||
if (start < length && csv && data[start] == DOUBLE_QUOTE) {
|
||||
ByteArrayOutputStream value = new ByteArrayOutputStream();
|
||||
int j = start + 1;
|
||||
while (j < length) {
|
||||
if (data[j] == DOUBLE_QUOTE) {
|
||||
if (j + 1 < length && data[j + 1] == DOUBLE_QUOTE) {
|
||||
value.write(DOUBLE_QUOTE);
|
||||
j += 2;
|
||||
continue;
|
||||
}
|
||||
return new Field(j + 1, value.toByteArray(), true);
|
||||
}
|
||||
value.write(data[j]);
|
||||
j++;
|
||||
}
|
||||
throw malformed("quoted field has no closing quote");
|
||||
}
|
||||
int j = start;
|
||||
while (j < length && data[j] != delimiter && data[j] != NEWLINE) {
|
||||
if (!csv && data[j] == BACKSLASH && j + 1 < length) {
|
||||
j++;
|
||||
}
|
||||
j++;
|
||||
}
|
||||
int valueEnd = j;
|
||||
if (j < length && data[j] == NEWLINE && j > start && data[j - 1] == CARRIAGE_RETURN) {
|
||||
valueEnd = j - 1;
|
||||
}
|
||||
return new Field(j, Arrays.copyOfRange(data, start, valueEnd), false);
|
||||
}
|
||||
|
||||
/** A carriage return that ends the record: followed by a newline or by the end of the data. */
|
||||
private static boolean isCrlfAt(byte[] data, int index) {
|
||||
return index < data.length && data[index] == CARRIAGE_RETURN
|
||||
&& (index + 1 == data.length || data[index + 1] == NEWLINE);
|
||||
}
|
||||
|
||||
private void writeField(Field field, int column, ByteArrayOutputStream out) {
|
||||
byte[] value = field.value();
|
||||
boolean nulled = (transforms.blanksAsNull() && isBlank(value))
|
||||
|| (transforms.emptyAsNull() && value.length == 0);
|
||||
if (nulled) {
|
||||
out.writeBytes(nullMarker);
|
||||
return;
|
||||
}
|
||||
// A field that already is the NULL marker must not be cut: that would turn NULL into data.
|
||||
byte[] limited = !field.quoted() && Arrays.equals(value, nullMarker) ? value : truncate(value, column);
|
||||
if (!field.quoted()) {
|
||||
out.writeBytes(limited);
|
||||
} else if (csv) {
|
||||
writeCsvQuoted(limited, out);
|
||||
} else {
|
||||
out.writeBytes(escapeTextField(limited));
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean isBlank(byte[] value) {
|
||||
if (value.length == 0) {
|
||||
return false;
|
||||
}
|
||||
for (byte b : value) {
|
||||
if (b != ' ' && b != '\t') {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private byte[] truncate(byte[] value, int column) {
|
||||
if (!transforms.truncateColumns() || columnMaxBytes == null || column >= columnMaxBytes.size()) {
|
||||
return value;
|
||||
}
|
||||
Integer max = columnMaxBytes.get(column);
|
||||
if (max == null) {
|
||||
return value;
|
||||
}
|
||||
// Redshift counts CHAR(n) and VARCHAR(n) in bytes, so measure the decoded bytes and cut at a
|
||||
// character boundary. Text mode decodes its escapes first so one is never split.
|
||||
byte[] decoded = csv ? value : decodeTextEscapes(value);
|
||||
int end = byteLimitBoundary(decoded, max);
|
||||
if (end == decoded.length) {
|
||||
return value;
|
||||
}
|
||||
byte[] kept = Arrays.copyOf(decoded, end);
|
||||
return csv ? kept : encodeTextEscapes(kept);
|
||||
}
|
||||
|
||||
/** Largest offset not above {@code maxBytes} that does not fall inside a multi-byte character. */
|
||||
private static int byteLimitBoundary(byte[] bytes, int maxBytes) {
|
||||
if (bytes.length <= maxBytes) {
|
||||
return bytes.length;
|
||||
}
|
||||
int end = maxBytes;
|
||||
while (end > 0 && (bytes[end] & 0xC0) == 0x80) {
|
||||
end--;
|
||||
}
|
||||
return end;
|
||||
}
|
||||
|
||||
/** Decodes COPY text escapes: backslash b f n r t v, octal NNN, hex xHH, and backslash c for any other c. */
|
||||
private static byte[] decodeTextEscapes(byte[] value) {
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream(value.length);
|
||||
int i = 0;
|
||||
while (i < value.length) {
|
||||
byte b = value[i];
|
||||
if (b != BACKSLASH || i + 1 >= value.length) {
|
||||
out.write(b);
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
byte next = value[i + 1];
|
||||
if (next >= '0' && next <= '7') {
|
||||
int octal = 0;
|
||||
int digits = 0;
|
||||
i++;
|
||||
while (i < value.length && digits < 3 && value[i] >= '0' && value[i] <= '7') {
|
||||
octal = octal * 8 + (value[i] - '0');
|
||||
i++;
|
||||
digits++;
|
||||
}
|
||||
out.write(octal);
|
||||
} else if (next == 'x' && i + 2 < value.length && Character.digit(value[i + 2], 16) >= 0) {
|
||||
int hex = Character.digit(value[i + 2], 16);
|
||||
i += 3;
|
||||
if (i < value.length && Character.digit(value[i], 16) >= 0) {
|
||||
hex = hex * 16 + Character.digit(value[i], 16);
|
||||
i++;
|
||||
}
|
||||
out.write(hex);
|
||||
} else {
|
||||
out.write(switch (next) {
|
||||
case 'b' -> '\b';
|
||||
case 'f' -> '\f';
|
||||
case 'n' -> '\n';
|
||||
case 'r' -> '\r';
|
||||
case 't' -> '\t';
|
||||
case 'v' -> 0x0B;
|
||||
default -> next;
|
||||
});
|
||||
i += 2;
|
||||
}
|
||||
}
|
||||
return out.toByteArray();
|
||||
}
|
||||
|
||||
private byte[] encodeTextEscapes(byte[] value) {
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream(value.length + 4);
|
||||
for (byte b : value) {
|
||||
if (b == BACKSLASH || b == delimiter) {
|
||||
out.write(BACKSLASH);
|
||||
out.write(b);
|
||||
} else if (b == NEWLINE) {
|
||||
out.write(BACKSLASH);
|
||||
out.write('n');
|
||||
} else if (b == CARRIAGE_RETURN) {
|
||||
out.write(BACKSLASH);
|
||||
out.write('r');
|
||||
} else {
|
||||
out.write(b);
|
||||
}
|
||||
}
|
||||
return out.toByteArray();
|
||||
}
|
||||
|
||||
private byte[] escapeTextField(byte[] value) {
|
||||
ByteArrayOutputStream escaped = new ByteArrayOutputStream(value.length + 4);
|
||||
for (int i = 0; i < value.length; i++) {
|
||||
byte b = value[i];
|
||||
if (b == BACKSLASH && i + 1 < value.length) {
|
||||
escaped.write(b);
|
||||
escaped.write(value[++i]);
|
||||
} else if (b == delimiter) {
|
||||
escaped.write(BACKSLASH);
|
||||
escaped.write(b);
|
||||
} else if (b == NEWLINE) {
|
||||
escaped.write(BACKSLASH);
|
||||
escaped.write('n');
|
||||
} else if (b == CARRIAGE_RETURN) {
|
||||
escaped.write(BACKSLASH);
|
||||
escaped.write('r');
|
||||
} else {
|
||||
escaped.write(b);
|
||||
}
|
||||
}
|
||||
return escaped.toByteArray();
|
||||
}
|
||||
|
||||
private static void writeCsvQuoted(byte[] value, ByteArrayOutputStream out) {
|
||||
out.write(DOUBLE_QUOTE);
|
||||
for (byte b : value) {
|
||||
if (b == DOUBLE_QUOTE) {
|
||||
out.write(DOUBLE_QUOTE);
|
||||
}
|
||||
out.write(b);
|
||||
}
|
||||
out.write(DOUBLE_QUOTE);
|
||||
}
|
||||
|
||||
private static S3CopySimulator.S3TransferException malformed(String detail) {
|
||||
return new S3CopySimulator.S3TransferException(SQLSTATE_INTERNAL, "COPY failed: " + detail, null);
|
||||
}
|
||||
}
|
||||
+417
-30
@@ -1,5 +1,6 @@
|
||||
package io.github.hectorvent.floci.services.redshift.proxy;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.regex.Matcher;
|
||||
@@ -16,6 +17,25 @@ public final class CopyStatementParser {
|
||||
public sealed interface S3Statement permits S3CopyFrom, S3Unload {
|
||||
}
|
||||
|
||||
/** COPY options that change field content; {@link #NONE} keeps the plain byte-copy path. */
|
||||
public record CopyTransforms(
|
||||
boolean blanksAsNull,
|
||||
boolean emptyAsNull,
|
||||
boolean removeQuotes,
|
||||
boolean truncateColumns,
|
||||
Character invalidCharReplacement) {
|
||||
|
||||
public static final CopyTransforms NONE = new CopyTransforms(false, false, false, false, null);
|
||||
|
||||
public boolean fieldLevel() {
|
||||
return blanksAsNull || emptyAsNull || removeQuotes || truncateColumns;
|
||||
}
|
||||
|
||||
public boolean any() {
|
||||
return fieldLevel() || invalidCharReplacement != null;
|
||||
}
|
||||
}
|
||||
|
||||
public record S3CopyFrom(
|
||||
String targetTable,
|
||||
List<String> columns,
|
||||
@@ -29,7 +49,32 @@ public final class CopyStatementParser {
|
||||
String iamRoleArn,
|
||||
boolean jsonAuto,
|
||||
boolean jsonAutoIgnoreCase,
|
||||
boolean manifest) implements S3Statement {
|
||||
boolean manifest,
|
||||
CopyTransforms transforms) implements S3Statement {
|
||||
|
||||
public S3CopyFrom {
|
||||
if (transforms == null) {
|
||||
transforms = CopyTransforms.NONE;
|
||||
}
|
||||
}
|
||||
|
||||
public S3CopyFrom(
|
||||
String targetTable,
|
||||
List<String> columns,
|
||||
String bucket,
|
||||
String keyOrPrefix,
|
||||
String delimiter,
|
||||
int headerLines,
|
||||
boolean gzip,
|
||||
boolean csv,
|
||||
String nullAs,
|
||||
String iamRoleArn,
|
||||
boolean jsonAuto,
|
||||
boolean jsonAutoIgnoreCase,
|
||||
boolean manifest) {
|
||||
this(targetTable, columns, bucket, keyOrPrefix, delimiter, headerLines, gzip, csv,
|
||||
nullAs, iamRoleArn, jsonAuto, jsonAutoIgnoreCase, manifest, CopyTransforms.NONE);
|
||||
}
|
||||
|
||||
public S3CopyFrom(
|
||||
String targetTable,
|
||||
@@ -78,7 +123,52 @@ public final class CopyStatementParser {
|
||||
boolean allowOverwrite,
|
||||
boolean parallel,
|
||||
long maxFileSizeBytes,
|
||||
String iamRoleArn) implements S3Statement {
|
||||
String iamRoleArn,
|
||||
String extension,
|
||||
boolean escape,
|
||||
boolean cleanPath,
|
||||
boolean encrypted,
|
||||
String sseKmsKeyId) implements S3Statement {
|
||||
|
||||
public S3Unload(
|
||||
String selectQuery,
|
||||
String bucket,
|
||||
String prefix,
|
||||
String delimiter,
|
||||
boolean header,
|
||||
boolean gzip,
|
||||
boolean csv,
|
||||
boolean addQuotes,
|
||||
String nullAs,
|
||||
boolean manifest,
|
||||
boolean allowOverwrite,
|
||||
boolean parallel,
|
||||
long maxFileSizeBytes,
|
||||
String iamRoleArn,
|
||||
String extension) {
|
||||
this(selectQuery, bucket, prefix, delimiter, header, gzip, csv, addQuotes, nullAs, manifest,
|
||||
allowOverwrite, parallel, maxFileSizeBytes, iamRoleArn, extension,
|
||||
false, false, false, null);
|
||||
}
|
||||
|
||||
public S3Unload(
|
||||
String selectQuery,
|
||||
String bucket,
|
||||
String prefix,
|
||||
String delimiter,
|
||||
boolean header,
|
||||
boolean gzip,
|
||||
boolean csv,
|
||||
boolean addQuotes,
|
||||
String nullAs,
|
||||
boolean manifest,
|
||||
boolean allowOverwrite,
|
||||
boolean parallel,
|
||||
long maxFileSizeBytes,
|
||||
String iamRoleArn) {
|
||||
this(selectQuery, bucket, prefix, delimiter, header, gzip, csv, addQuotes, nullAs, manifest,
|
||||
allowOverwrite, parallel, maxFileSizeBytes, iamRoleArn, null);
|
||||
}
|
||||
}
|
||||
|
||||
private static final Pattern COPY_PATTERN = Pattern.compile(
|
||||
@@ -96,17 +186,23 @@ public final class CopyStatementParser {
|
||||
private static final Pattern ADDQUOTES_PATTERN = Pattern.compile("(?i)\\bADDQUOTES\\b");
|
||||
private static final Pattern MANIFEST_PATTERN = Pattern.compile("(?i)\\bMANIFEST\\b");
|
||||
private static final Pattern ALLOWOVERWRITE_PATTERN = Pattern.compile("(?i)\\bALLOWOVERWRITE\\b");
|
||||
private static final Pattern ESCAPE_PATTERN = Pattern.compile("(?i)\\bESCAPE\\b");
|
||||
private static final Pattern CLEANPATH_PATTERN = Pattern.compile("(?i)\\bCLEANPATH\\b");
|
||||
private static final Pattern ENCRYPTED_PATTERN = Pattern.compile("(?i)\\bENCRYPTED(?:\\s+(AUTO)\\b)?");
|
||||
private static final Pattern KMS_KEY_ID_PATTERN = Pattern.compile(
|
||||
"(?i)\\bKMS_KEY_ID\\s+(?:'((?:[^']|'')*)'|\"([^\"]*)\")");
|
||||
private static final Pattern EXTENSION_PATTERN = Pattern.compile(
|
||||
"(?i)\\bEXTENSION\\s+(?:'((?:[^']|'')*)'|\"([^\"]*)\")");
|
||||
|
||||
/**
|
||||
* UNLOAD options this simulator cannot honour. Distinct from the COPY set:
|
||||
* MANIFEST / ALLOWOVERWRITE / PARALLEL / MAXFILESIZE are UNLOAD-supported here,
|
||||
* while EXTENSION / CLEANPATH / PARTITION are UNLOAD-only and unsupported.
|
||||
* MANIFEST / ALLOWOVERWRITE / PARALLEL / MAXFILESIZE / EXTENSION / CLEANPATH are
|
||||
* 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"
|
||||
+ "|ENCRYPTED|ENCODING|REGION|CREDENTIALS|ACCESS_KEY_ID"
|
||||
+ "|SECRET_ACCESS_KEY|SESSION_TOKEN|MASTER_SYMMETRIC_KEY|KMS_KEY_ID"
|
||||
+ "|EXTENSION|CLEANPATH|PARTITION|MAXFILESIZE\\s+\\d+\\s*(?:TB|PB))\\b");
|
||||
+ "|ENCODING|MASTER_SYMMETRIC_KEY"
|
||||
+ "|PARTITION|MAXFILESIZE\\s+\\d+\\s*(?:TB|PB))\\b");
|
||||
|
||||
private static final Pattern QUALIFIED_NAME = Pattern.compile(
|
||||
"(?:[A-Za-z_][A-Za-z0-9_$]*|\"[^\"]+\")(?:\\.(?:[A-Za-z_][A-Za-z0-9_$]*|\"[^\"]+\"))?");
|
||||
@@ -118,6 +214,28 @@ public final class CopyStatementParser {
|
||||
"(?i)\\bNULL\\s+(?:AS\\s+)?(?:'((?:[^']|'')*)'|\"([^\"]*)\")");
|
||||
private static final Pattern IAM_ROLE_PATTERN = Pattern.compile(
|
||||
"(?i)\\bIAM_ROLE\\s+(?:'((?:[^']|'')*)'|\"([^\"]*)\")");
|
||||
private static final Pattern BLANKSASNULL_PATTERN = Pattern.compile("(?i)\\bBLANKSASNULL\\b");
|
||||
private static final Pattern EMPTYASNULL_PATTERN = Pattern.compile("(?i)\\bEMPTYASNULL\\b");
|
||||
private static final Pattern REMOVEQUOTES_PATTERN = Pattern.compile("(?i)\\bREMOVEQUOTES\\b");
|
||||
private static final Pattern TRUNCATECOLUMNS_PATTERN = Pattern.compile("(?i)\\bTRUNCATECOLUMNS\\b");
|
||||
private static final Pattern ACCEPTINVCHARS_PATTERN = Pattern.compile(
|
||||
"(?i)\\bACCEPTINVCHARS(?:\\s+(?:AS\\s+)?'([ -&(-~])')?");
|
||||
private static final Pattern CREDENTIALS_PATTERN = Pattern.compile(
|
||||
"(?i)\\bCREDENTIALS\\s+(?:AS\\s+)?(?:'((?:[^']|'')*)'|\"([^\"]*)\")");
|
||||
private static final Pattern ACCESS_KEY_ID_PATTERN = Pattern.compile(
|
||||
"(?i)\\bACCESS_KEY_ID\\s+(?:AS\\s+)?(?:'((?:[^']|'')*)'|\"([^\"]*)\")");
|
||||
private static final Pattern SECRET_ACCESS_KEY_PATTERN = Pattern.compile(
|
||||
"(?i)\\bSECRET_ACCESS_KEY\\s+(?:AS\\s+)?(?:'((?:[^']|'')*)'|\"([^\"]*)\")");
|
||||
private static final Pattern SESSION_TOKEN_PATTERN = Pattern.compile(
|
||||
"(?i)\\bSESSION_TOKEN\\s+(?:AS\\s+)?(?:'((?:[^']|'')*)'|\"([^\"]*)\")");
|
||||
private static final Pattern REGION_PATTERN = Pattern.compile(
|
||||
"(?i)\\bREGION\\s+(?:AS\\s+)?(?:'((?:[^']|'')*)'|\"([^\"]*)\")");
|
||||
private static final Pattern CREDENTIALS_ROLE = Pattern.compile(
|
||||
"(?i)(?:^|;)\\s*aws_iam_role\\s*=\\s*([^;\\s]+)");
|
||||
private static final Pattern CREDENTIALS_KEY_ID = Pattern.compile(
|
||||
"(?i)(?:^|;)\\s*aws_access_key_id\\s*=\\s*[^;\\s]+");
|
||||
private static final Pattern CREDENTIALS_SECRET = Pattern.compile(
|
||||
"(?i)(?:^|;)\\s*aws_secret_access_key\\s*=\\s*[^;\\s]+");
|
||||
private static final Pattern IGNOREHEADER_PATTERN = Pattern.compile(
|
||||
"(?i)\\bIGNOREHEADER\\s+(?:AS\\s+)?(\\d+)\\b");
|
||||
private static final Pattern HEADER_PATTERN = Pattern.compile("(?i)\\bHEADER\\b");
|
||||
@@ -133,10 +251,10 @@ public final class CopyStatementParser {
|
||||
*/
|
||||
private static final Pattern UNSUPPORTED_CLAUSE = Pattern.compile(
|
||||
"(?i)\\b(FIXEDWIDTH|PARQUET|AVRO|ORC|SHAPEFILE|BZIP2|LZOP|ZSTD|MAXERROR"
|
||||
+ "|DATEFORMAT|TIMEFORMAT|ENCRYPTED|ENCODING|REGION|CREDENTIALS"
|
||||
+ "|ACCESS_KEY_ID|SECRET_ACCESS_KEY|SESSION_TOKEN|MASTER_SYMMETRIC_KEY|KMS_KEY_ID"
|
||||
+ "|ACCEPTINVCHARS|ACCEPTANYDATE|BLANKSASNULL|EMPTYASNULL|FILLRECORD|TRIMBLANKS"
|
||||
+ "|TRUNCATECOLUMNS|IGNOREBLANKLINES|ESCAPE|REMOVEQUOTES|EXPLICIT_IDS|COMPUPDATE"
|
||||
+ "|DATEFORMAT|TIMEFORMAT|ENCRYPTED|ENCODING"
|
||||
+ "|MASTER_SYMMETRIC_KEY|KMS_KEY_ID"
|
||||
+ "|ACCEPTANYDATE|FILLRECORD|TRIMBLANKS"
|
||||
+ "|IGNOREBLANKLINES|ESCAPE|EXPLICIT_IDS|COMPUPDATE"
|
||||
+ "|STATUPDATE|NOLOAD|ROUNDEC|QUOTE|SSH|READRATIO|COMPROWS|DIMENSION)\\b");
|
||||
|
||||
/** A {@code ;} followed by another statement: only a lone trailing {@code ;} is tolerated. */
|
||||
@@ -192,8 +310,18 @@ public final class CopyStatementParser {
|
||||
String nullAs = null;
|
||||
String delimiter = null;
|
||||
long maxFileSizeBytes = 0L;
|
||||
String iamRoleArn = null;
|
||||
String extension = null;
|
||||
boolean escape = false;
|
||||
boolean cleanPath = false;
|
||||
boolean encrypted = false;
|
||||
boolean encryptedAuto = false;
|
||||
String kmsKeyId = null;
|
||||
|
||||
boolean seenEscape = false;
|
||||
boolean seenCleanPath = false;
|
||||
boolean seenEncrypted = false;
|
||||
boolean seenKmsKeyId = false;
|
||||
boolean seenExtension = false;
|
||||
boolean seenCsv = false;
|
||||
boolean seenGzip = false;
|
||||
boolean seenHeader = false;
|
||||
@@ -204,7 +332,6 @@ public final class CopyStatementParser {
|
||||
boolean seenNull = false;
|
||||
boolean seenDelimiter = false;
|
||||
boolean seenMaxFileSize = false;
|
||||
boolean seenIamRole = false;
|
||||
|
||||
Matcher csvM = CSV_PATTERN.matcher(options);
|
||||
Matcher gzipM = GZIP_PATTERN.matcher(options);
|
||||
@@ -216,8 +343,14 @@ public final class CopyStatementParser {
|
||||
Matcher delimiterM = DELIMITER_PATTERN.matcher(options);
|
||||
Matcher nullM = NULL_AS_PATTERN.matcher(options);
|
||||
Matcher maxFileSizeM = MAXFILESIZE_PATTERN.matcher(options);
|
||||
Matcher iamRoleM = IAM_ROLE_PATTERN.matcher(options);
|
||||
Matcher extensionM = EXTENSION_PATTERN.matcher(options);
|
||||
Matcher escapeM = ESCAPE_PATTERN.matcher(options);
|
||||
Matcher cleanPathM = CLEANPATH_PATTERN.matcher(options);
|
||||
Matcher encryptedM = ENCRYPTED_PATTERN.matcher(options);
|
||||
Matcher kmsKeyIdM = KMS_KEY_ID_PATTERN.matcher(options);
|
||||
AuthClauses auth = new AuthClauses(options);
|
||||
|
||||
int next;
|
||||
int offset = 0;
|
||||
int len = options.length();
|
||||
while (offset < len) {
|
||||
@@ -227,7 +360,46 @@ public final class CopyStatementParser {
|
||||
if (offset >= len) {
|
||||
break;
|
||||
}
|
||||
if (matchClause(maxFileSizeM, offset, len)) {
|
||||
if (matchClause(extensionM, offset, len)) {
|
||||
if (seenExtension) {
|
||||
return null;
|
||||
}
|
||||
seenExtension = true;
|
||||
extension = extractNullValue(extensionM);
|
||||
if (extension.isEmpty() || extension.indexOf('/') >= 0) {
|
||||
return null;
|
||||
}
|
||||
offset = extensionM.end();
|
||||
} else if (matchClause(escapeM, offset, len)) {
|
||||
if (seenEscape) {
|
||||
return null;
|
||||
}
|
||||
seenEscape = true;
|
||||
escape = true;
|
||||
offset = escapeM.end();
|
||||
} else if (matchClause(cleanPathM, offset, len)) {
|
||||
if (seenCleanPath) {
|
||||
return null;
|
||||
}
|
||||
seenCleanPath = true;
|
||||
cleanPath = true;
|
||||
offset = cleanPathM.end();
|
||||
} else if (matchClause(encryptedM, offset, len)) {
|
||||
if (seenEncrypted) {
|
||||
return null;
|
||||
}
|
||||
seenEncrypted = true;
|
||||
encrypted = true;
|
||||
encryptedAuto = encryptedM.group(1) != null;
|
||||
offset = encryptedM.end();
|
||||
} else if (matchClause(kmsKeyIdM, offset, len)) {
|
||||
if (seenKmsKeyId) {
|
||||
return null;
|
||||
}
|
||||
seenKmsKeyId = true;
|
||||
kmsKeyId = extractNullValue(kmsKeyIdM);
|
||||
offset = kmsKeyIdM.end();
|
||||
} else if (matchClause(maxFileSizeM, offset, len)) {
|
||||
if (seenMaxFileSize) {
|
||||
return null;
|
||||
}
|
||||
@@ -303,23 +475,41 @@ public final class CopyStatementParser {
|
||||
seenNull = true;
|
||||
nullAs = extractNullValue(nullM);
|
||||
offset = nullM.end();
|
||||
} else if (matchClause(iamRoleM, offset, len)) {
|
||||
if (seenIamRole) {
|
||||
} else if ((next = auth.consume(offset, len)) != AuthClauses.NO_MATCH) {
|
||||
if (next == AuthClauses.REJECT) {
|
||||
return null;
|
||||
}
|
||||
seenIamRole = true;
|
||||
iamRoleArn = extractNullValue(iamRoleM);
|
||||
offset = iamRoleM.end();
|
||||
offset = next;
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
if (!auth.consistent()) {
|
||||
return null;
|
||||
}
|
||||
String iamRoleArn = auth.iamRoleArn();
|
||||
if (delimiter == null) {
|
||||
delimiter = csv ? "," : "|";
|
||||
}
|
||||
// ESCAPE relies on PostgreSQL text framing, which CSV, ADDQUOTES and HEADER all replace here.
|
||||
if (escape && (csv || addQuotes || header)) {
|
||||
return null;
|
||||
}
|
||||
// An empty prefix would make CLEANPATH delete the whole bucket.
|
||||
if (cleanPath && (allowOverwrite || prefix.isEmpty())) {
|
||||
return null;
|
||||
}
|
||||
// Only ENCRYPTED AUTO and ENCRYPTED KMS_KEY_ID are emulated. Bare ENCRYPTED and MASTER_SYMMETRIC_KEY are not.
|
||||
if (kmsKeyId != null && (kmsKeyId.isBlank() || !encrypted || encryptedAuto)) {
|
||||
return null;
|
||||
}
|
||||
if (encrypted && !encryptedAuto && kmsKeyId == null) {
|
||||
return null;
|
||||
}
|
||||
return new S3Unload(select, bucket, prefix, delimiter, header, gzip, csv,
|
||||
addQuotes, nullAs, manifest, allowOverwrite, parallel, maxFileSizeBytes, iamRoleArn);
|
||||
addQuotes, nullAs, manifest, allowOverwrite, parallel, maxFileSizeBytes, iamRoleArn, extension,
|
||||
escape, cleanPath, encrypted, kmsKeyId);
|
||||
}
|
||||
|
||||
private static S3CopyFrom parseCopy(String cleaned) {
|
||||
@@ -372,8 +562,17 @@ public final class CopyStatementParser {
|
||||
String nullAs = null;
|
||||
String delimiter = null;
|
||||
int headerLines = 0;
|
||||
String iamRoleArn = null;
|
||||
boolean blanksAsNull = false;
|
||||
boolean emptyAsNull = false;
|
||||
boolean removeQuotes = false;
|
||||
boolean truncateColumns = false;
|
||||
Character invalidChar = null;
|
||||
|
||||
boolean seenTruncateColumns = false;
|
||||
boolean seenBlanksAsNull = false;
|
||||
boolean seenEmptyAsNull = false;
|
||||
boolean seenRemoveQuotes = false;
|
||||
boolean seenAcceptInvChars = false;
|
||||
boolean seenCsv = false;
|
||||
boolean seenGzip = false;
|
||||
boolean seenJson = false;
|
||||
@@ -381,7 +580,6 @@ public final class CopyStatementParser {
|
||||
boolean seenNull = false;
|
||||
boolean seenDelimiter = false;
|
||||
boolean seenHeader = false;
|
||||
boolean seenIamRole = false;
|
||||
|
||||
Matcher csvMatcher = CSV_PATTERN.matcher(options);
|
||||
Matcher gzipMatcher = GZIP_PATTERN.matcher(options);
|
||||
@@ -391,8 +589,14 @@ public final class CopyStatementParser {
|
||||
Matcher headerMatcher = HEADER_PATTERN.matcher(options);
|
||||
Matcher delimiterMatcher = DELIMITER_PATTERN.matcher(options);
|
||||
Matcher nullMatcher = NULL_AS_PATTERN.matcher(options);
|
||||
Matcher iamRoleMatcher = IAM_ROLE_PATTERN.matcher(options);
|
||||
Matcher blanksAsNullMatcher = BLANKSASNULL_PATTERN.matcher(options);
|
||||
Matcher emptyAsNullMatcher = EMPTYASNULL_PATTERN.matcher(options);
|
||||
Matcher removeQuotesMatcher = REMOVEQUOTES_PATTERN.matcher(options);
|
||||
Matcher truncateColumnsMatcher = TRUNCATECOLUMNS_PATTERN.matcher(options);
|
||||
Matcher acceptInvCharsMatcher = ACCEPTINVCHARS_PATTERN.matcher(options);
|
||||
AuthClauses auth = new AuthClauses(options);
|
||||
|
||||
int next;
|
||||
int offset = 0;
|
||||
int len = options.length();
|
||||
while (offset < len) {
|
||||
@@ -460,24 +664,203 @@ public final class CopyStatementParser {
|
||||
seenNull = true;
|
||||
nullAs = extractNullValue(nullMatcher);
|
||||
offset = nullMatcher.end();
|
||||
} else if (matchClause(iamRoleMatcher, offset, len)) {
|
||||
if (seenIamRole) {
|
||||
} else if (matchClause(blanksAsNullMatcher, offset, len)) {
|
||||
if (seenBlanksAsNull) {
|
||||
return null;
|
||||
}
|
||||
seenIamRole = true;
|
||||
iamRoleArn = extractNullValue(iamRoleMatcher);
|
||||
offset = iamRoleMatcher.end();
|
||||
seenBlanksAsNull = true;
|
||||
blanksAsNull = true;
|
||||
offset = blanksAsNullMatcher.end();
|
||||
} else if (matchClause(emptyAsNullMatcher, offset, len)) {
|
||||
if (seenEmptyAsNull) {
|
||||
return null;
|
||||
}
|
||||
seenEmptyAsNull = true;
|
||||
emptyAsNull = true;
|
||||
offset = emptyAsNullMatcher.end();
|
||||
} else if (matchClause(removeQuotesMatcher, offset, len)) {
|
||||
if (seenRemoveQuotes) {
|
||||
return null;
|
||||
}
|
||||
seenRemoveQuotes = true;
|
||||
removeQuotes = true;
|
||||
offset = removeQuotesMatcher.end();
|
||||
} else if (matchClause(truncateColumnsMatcher, offset, len)) {
|
||||
if (seenTruncateColumns) {
|
||||
return null;
|
||||
}
|
||||
seenTruncateColumns = true;
|
||||
truncateColumns = true;
|
||||
offset = truncateColumnsMatcher.end();
|
||||
} else if (matchClause(acceptInvCharsMatcher, offset, len)) {
|
||||
if (seenAcceptInvChars) {
|
||||
return null;
|
||||
}
|
||||
seenAcceptInvChars = true;
|
||||
invalidChar = acceptInvCharsMatcher.group(1) != null
|
||||
? Character.valueOf(acceptInvCharsMatcher.group(1).charAt(0))
|
||||
: Character.valueOf('?');
|
||||
offset = acceptInvCharsMatcher.end();
|
||||
} else if ((next = auth.consume(offset, len)) != AuthClauses.NO_MATCH) {
|
||||
if (next == AuthClauses.REJECT) {
|
||||
return null;
|
||||
}
|
||||
offset = next;
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
if (!auth.consistent()) {
|
||||
return null;
|
||||
}
|
||||
String iamRoleArn = auth.iamRoleArn();
|
||||
if (delimiter == null) {
|
||||
delimiter = csv ? "," : "|";
|
||||
}
|
||||
|
||||
CopyTransforms transforms = new CopyTransforms(
|
||||
blanksAsNull, emptyAsNull, removeQuotes, truncateColumns, invalidChar);
|
||||
if (transforms.any() && jsonAuto) {
|
||||
return null;
|
||||
}
|
||||
if (transforms.removeQuotes() && csv) {
|
||||
return null;
|
||||
}
|
||||
if (transforms.fieldLevel() && delimiter.getBytes(StandardCharsets.UTF_8).length != 1) {
|
||||
return null;
|
||||
}
|
||||
if (invalidChar != null && replacementIsFramingSyntax(invalidChar, delimiter, csv)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return new S3CopyFrom(table, columns, bucket, keyOrPrefix, delimiter, headerLines, gzip, csv,
|
||||
nullAs, iamRoleArn, jsonAuto, jsonAutoIgnoreCase, manifest);
|
||||
nullAs, iamRoleArn, jsonAuto, jsonAutoIgnoreCase, manifest, transforms);
|
||||
}
|
||||
|
||||
/**
|
||||
* Collects the S3 authorization and region clauses shared by COPY and UNLOAD. Key material is
|
||||
* checked for shape only and never stored: the simulator reads S3 as the cluster role or as an
|
||||
* unsigned request.
|
||||
*/
|
||||
private static final class AuthClauses {
|
||||
static final int NO_MATCH = -1;
|
||||
static final int REJECT = -2;
|
||||
|
||||
private final Matcher iamRole;
|
||||
private final Matcher credentials;
|
||||
private final Matcher accessKeyId;
|
||||
private final Matcher secretAccessKey;
|
||||
private final Matcher sessionToken;
|
||||
private final Matcher region;
|
||||
|
||||
private String iamRoleArn;
|
||||
private String credentialsRoleArn;
|
||||
private boolean seenIamRole;
|
||||
private boolean seenCredentials;
|
||||
private boolean seenAccessKeyId;
|
||||
private boolean seenSecretAccessKey;
|
||||
private boolean seenSessionToken;
|
||||
private boolean seenRegion;
|
||||
private boolean credentialsHaveKeys;
|
||||
private boolean credentialsMalformed;
|
||||
|
||||
AuthClauses(String options) {
|
||||
iamRole = IAM_ROLE_PATTERN.matcher(options);
|
||||
credentials = CREDENTIALS_PATTERN.matcher(options);
|
||||
accessKeyId = ACCESS_KEY_ID_PATTERN.matcher(options);
|
||||
secretAccessKey = SECRET_ACCESS_KEY_PATTERN.matcher(options);
|
||||
sessionToken = SESSION_TOKEN_PATTERN.matcher(options);
|
||||
region = REGION_PATTERN.matcher(options);
|
||||
}
|
||||
|
||||
int consume(int offset, int end) {
|
||||
if (matchClause(iamRole, offset, end)) {
|
||||
if (seenIamRole) {
|
||||
return REJECT;
|
||||
}
|
||||
seenIamRole = true;
|
||||
iamRoleArn = extractNullValue(iamRole);
|
||||
return isBlank(iamRoleArn) ? REJECT : iamRole.end();
|
||||
}
|
||||
if (matchClause(credentials, offset, end)) {
|
||||
if (seenCredentials) {
|
||||
return REJECT;
|
||||
}
|
||||
seenCredentials = true;
|
||||
readCredentials(extractNullValue(credentials));
|
||||
return credentials.end();
|
||||
}
|
||||
if (matchClause(accessKeyId, offset, end)) {
|
||||
if (seenAccessKeyId) {
|
||||
return REJECT;
|
||||
}
|
||||
seenAccessKeyId = true;
|
||||
return isBlank(extractNullValue(accessKeyId)) ? REJECT : accessKeyId.end();
|
||||
}
|
||||
if (matchClause(secretAccessKey, offset, end)) {
|
||||
if (seenSecretAccessKey) {
|
||||
return REJECT;
|
||||
}
|
||||
seenSecretAccessKey = true;
|
||||
return isBlank(extractNullValue(secretAccessKey)) ? REJECT : secretAccessKey.end();
|
||||
}
|
||||
if (matchClause(sessionToken, offset, end)) {
|
||||
if (seenSessionToken) {
|
||||
return REJECT;
|
||||
}
|
||||
seenSessionToken = true;
|
||||
return isBlank(extractNullValue(sessionToken)) ? REJECT : sessionToken.end();
|
||||
}
|
||||
if (matchClause(region, offset, end)) {
|
||||
if (seenRegion) {
|
||||
return REJECT;
|
||||
}
|
||||
seenRegion = true;
|
||||
return region.end();
|
||||
}
|
||||
return NO_MATCH;
|
||||
}
|
||||
|
||||
private void readCredentials(String value) {
|
||||
Matcher role = CREDENTIALS_ROLE.matcher(value);
|
||||
if (role.find()) {
|
||||
credentialsRoleArn = role.group(1);
|
||||
}
|
||||
boolean hasId = CREDENTIALS_KEY_ID.matcher(value).find();
|
||||
boolean hasSecret = CREDENTIALS_SECRET.matcher(value).find();
|
||||
credentialsHaveKeys = hasId && hasSecret;
|
||||
credentialsMalformed = hasId != hasSecret;
|
||||
}
|
||||
|
||||
boolean consistent() {
|
||||
if (credentialsMalformed || seenAccessKeyId != seenSecretAccessKey) {
|
||||
return false;
|
||||
}
|
||||
if (seenSessionToken && !seenAccessKeyId) {
|
||||
return false;
|
||||
}
|
||||
if (seenCredentials && seenAccessKeyId) {
|
||||
return false;
|
||||
}
|
||||
if (seenCredentials && credentialsRoleArn == null && !credentialsHaveKeys) {
|
||||
return false;
|
||||
}
|
||||
int roles = (seenIamRole ? 1 : 0) + (credentialsRoleArn != null ? 1 : 0);
|
||||
boolean keys = seenAccessKeyId || credentialsHaveKeys;
|
||||
return roles <= 1 && !(roles == 1 && keys);
|
||||
}
|
||||
|
||||
String iamRoleArn() {
|
||||
return iamRoleArn != null ? iamRoleArn : credentialsRoleArn;
|
||||
}
|
||||
}
|
||||
|
||||
/** The replacement is applied before records are scanned, so it must not change the framing. */
|
||||
private static boolean replacementIsFramingSyntax(char replacement, String delimiter, boolean csv) {
|
||||
return String.valueOf(replacement).equals(delimiter)
|
||||
|| (!csv && replacement == '\\')
|
||||
|| (csv && replacement == '"');
|
||||
}
|
||||
|
||||
private static boolean matchClause(Matcher m, int start, int end) {
|
||||
@@ -495,6 +878,10 @@ public final class CopyStatementParser {
|
||||
return "\\t".equals(value) || "\t".equals(value) ? "\t" : value;
|
||||
}
|
||||
|
||||
private static boolean isBlank(String value) {
|
||||
return value == null || value.isBlank();
|
||||
}
|
||||
|
||||
private static String extractNullValue(Matcher matcher) {
|
||||
String value = matcher.group(1) != null ? matcher.group(1) : matcher.group(2);
|
||||
return unescape(value);
|
||||
|
||||
+246
-29
@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.redshift.proxy;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.services.iam.IamService;
|
||||
import io.github.hectorvent.floci.services.s3.S3Service;
|
||||
import io.github.hectorvent.floci.services.s3.model.PutObjectOptions;
|
||||
import io.github.hectorvent.floci.services.s3.model.S3Object;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
@@ -14,7 +15,9 @@ import java.io.OutputStream;
|
||||
import java.net.Socket;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.Semaphore;
|
||||
import java.util.function.IntConsumer;
|
||||
@@ -47,6 +50,11 @@ public final class S3CopySimulator {
|
||||
static long UNLOAD_TARGET_FILE_BYTES = 6L * 1024 * 1024;
|
||||
/** Whole-result ceiling; a larger UNLOAD is aborted rather than filling the in-memory S3 store. */
|
||||
static long UNLOAD_MAX_TOTAL_BYTES = 256L * 1024 * 1024;
|
||||
/** Decompressed size ceiling for one object when a COPY field-content option forces it into heap. */
|
||||
static long COPY_TRANSFORM_MAX_OBJECT_BYTES = 64L * 1024 * 1024;
|
||||
/** Shared across every connection: a transform holds the input plus about two further copies of it. */
|
||||
static final Semaphore COPY_TRANSFORM_HEAP_MIB = new Semaphore(192);
|
||||
private static final int COPY_TRANSFORM_HEAP_FACTOR = 3;
|
||||
private static final long UNLOAD_WARN_BYTES = 32L * 1024 * 1024;
|
||||
/** Shared across every connection so concurrent UNLOADs cannot multiply the per-slice heap cost without bound. */
|
||||
static final Semaphore UNLOAD_HEAP_MIB = new Semaphore(192);
|
||||
@@ -172,7 +180,13 @@ public final class S3CopySimulator {
|
||||
}
|
||||
|
||||
static void streamCopyInput(CopyInput input, List<String> discoveredColumns, OutputStream backendOut) throws IOException {
|
||||
streamObjects(input.spec(), discoveredColumns, input.s3(), input.iamService(), input.roleSession(), input.keys(), backendOut);
|
||||
streamCopyInput(input, discoveredColumns, null, backendOut);
|
||||
}
|
||||
|
||||
static void streamCopyInput(CopyInput input, List<String> discoveredColumns,
|
||||
List<Integer> columnMaxBytes, OutputStream backendOut) throws IOException {
|
||||
streamObjects(input.spec(), discoveredColumns, columnMaxBytes, input.s3(), input.iamService(),
|
||||
input.roleSession(), input.keys(), backendOut);
|
||||
}
|
||||
|
||||
static void releaseCopySession(CopyInput input) {
|
||||
@@ -194,6 +208,7 @@ public final class S3CopySimulator {
|
||||
? RedshiftRoleAccess.resolveRoleSession(spec.iamRoleArn(), iamService, clusterAccountId, associatedRoleArns)
|
||||
: null;
|
||||
String probeKey = unloadDataKey(spec, 0);
|
||||
boolean cleanPath = false;
|
||||
try {
|
||||
if (roleSession != null) {
|
||||
RedshiftRoleAccess.authorizeRoleAction(s3, iamService, spec.iamRoleArn(), "s3:PutObject",
|
||||
@@ -205,7 +220,7 @@ public final class S3CopySimulator {
|
||||
RedshiftRoleAccess.objectArn(spec.iamRoleArn(), spec.bucket(), manifestKey));
|
||||
s3.authorizeSignedPutObject(roleSession.accessKeyId(), roleSession.sessionToken(), spec.bucket(), manifestKey);
|
||||
}
|
||||
if (!spec.allowOverwrite()) {
|
||||
if (!spec.allowOverwrite() && !spec.cleanPath()) {
|
||||
RedshiftRoleAccess.authorizeRoleAction(s3, iamService, spec.iamRoleArn(), "s3:ListBucket",
|
||||
RedshiftRoleAccess.bucketArn(spec.iamRoleArn(), spec.bucket()));
|
||||
s3.authorizeSignedListBucket(roleSession.accessKeyId(), roleSession.sessionToken(), spec.bucket());
|
||||
@@ -220,7 +235,7 @@ public final class S3CopySimulator {
|
||||
if (spec.manifest()) {
|
||||
s3.authorizeAnonymousPutObject(spec.bucket(), spec.prefix() + "manifest");
|
||||
}
|
||||
if (!spec.allowOverwrite()) {
|
||||
if (!spec.allowOverwrite() && !spec.cleanPath()) {
|
||||
s3.authorizeAnonymousListBucket(spec.bucket());
|
||||
if (targetPrefixHasObjects(spec, s3)) {
|
||||
throw new S3TransferException(SQLSTATE_INTERNAL,
|
||||
@@ -229,6 +244,10 @@ public final class S3CopySimulator {
|
||||
}
|
||||
}
|
||||
}
|
||||
if (spec.cleanPath()) {
|
||||
collectCleanPathKeys(spec, s3, iamService, roleSession);
|
||||
cleanPath = true;
|
||||
}
|
||||
} catch (AwsException e) {
|
||||
RedshiftRoleAccess.releaseRoleSession(roleSession, spec.iamRoleArn(), iamService);
|
||||
throw new S3TransferException(unloadWriteSqlState(e), unloadWriteMessage(e, spec), e);
|
||||
@@ -243,7 +262,7 @@ public final class S3CopySimulator {
|
||||
"UNLOAD memory budget exhausted; retry shortly", null);
|
||||
}
|
||||
try {
|
||||
return new S3UnloadCollector(spec, s3, iamService, roleSession);
|
||||
return new S3UnloadCollector(spec, s3, iamService, roleSession, cleanPath);
|
||||
} catch (IOException e) {
|
||||
UNLOAD_HEAP_MIB.release(UNLOAD_INITIAL_MIB);
|
||||
RedshiftRoleAccess.releaseRoleSession(roleSession, spec.iamRoleArn(), iamService);
|
||||
@@ -294,12 +313,22 @@ public final class S3CopySimulator {
|
||||
}
|
||||
|
||||
try {
|
||||
boolean noColumnList = spec.columns() == null || spec.columns().isEmpty();
|
||||
boolean discoverForJson = spec.jsonAuto() && noColumnList;
|
||||
boolean truncate = spec.transforms().truncateColumns();
|
||||
List<String> discoveredColumns = null;
|
||||
if (spec.jsonAuto() && (spec.columns() == null || spec.columns().isEmpty())) {
|
||||
discoveredColumns = discoverTableColumns(client, backend, spec, txStatus, onStatusChange);
|
||||
if (discoveredColumns == null) {
|
||||
List<Integer> columnMaxBytes = null;
|
||||
if (discoverForJson || truncate) {
|
||||
List<ColumnInfo> catalog = discoverColumnInfo(client, backend, spec, txStatus, onStatusChange);
|
||||
if (catalog == null) {
|
||||
return true;
|
||||
}
|
||||
if (discoverForJson) {
|
||||
discoveredColumns = catalog.stream().map(ColumnInfo::name).toList();
|
||||
}
|
||||
if (truncate) {
|
||||
columnMaxBytes = alignMaxBytes(spec, catalog);
|
||||
}
|
||||
}
|
||||
|
||||
OutputStream backendOut = backend.getOutputStream();
|
||||
@@ -336,7 +365,7 @@ public final class S3CopySimulator {
|
||||
// a CopyFail to the backend, whose ErrorResponse/ReadyForQuery is relayed to the client;
|
||||
// or, if the backend is unreachable, one synthesized ErrorResponse/ReadyForQuery.
|
||||
try {
|
||||
streamCopyInput(input, discoveredColumns, backendOut);
|
||||
streamCopyInput(input, discoveredColumns, columnMaxBytes, backendOut);
|
||||
writeCopyDone(backendOut);
|
||||
drainToReadyForQuery(backendDecoder, client, onStatusChange);
|
||||
} catch (RuntimeException | IOException e) {
|
||||
@@ -431,8 +460,15 @@ public final class S3CopySimulator {
|
||||
}
|
||||
|
||||
private static void streamObjects(CopyStatementParser.S3CopyFrom spec, List<String> discoveredColumns,
|
||||
S3Service s3, IamService iamService, RedshiftRoleAccess.RoleSession roleSession,
|
||||
List<Integer> columnMaxBytes, S3Service s3, IamService iamService, RedshiftRoleAccess.RoleSession roleSession,
|
||||
List<String> keys, OutputStream backendOut) throws IOException {
|
||||
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'.
|
||||
throw new S3TransferException(SQLSTATE_INTERNAL,
|
||||
"COPY ... TRUNCATECOLUMNS needs catalog column lengths, which are only available over "
|
||||
+ "the Simple Query protocol; connect with preferQueryMode=simple", null);
|
||||
}
|
||||
byte[] buffer = new byte[CHUNK];
|
||||
for (int i = 0; i < keys.size(); i++) {
|
||||
if (roleSession != null) {
|
||||
@@ -459,10 +495,14 @@ public final class S3CopySimulator {
|
||||
if (i == 0 && spec.headerLines() > 0) {
|
||||
skipLines(in, spec.headerLines());
|
||||
}
|
||||
InputStream source = in;
|
||||
if (spec.transforms().any()) {
|
||||
source = new ByteArrayInputStream(transformObject(spec, columnMaxBytes, in));
|
||||
}
|
||||
int read;
|
||||
boolean endsWithNewline = false;
|
||||
boolean hasData = false;
|
||||
while ((read = in.read(buffer)) != -1) {
|
||||
while ((read = source.read(buffer)) != -1) {
|
||||
if (read > 0) {
|
||||
hasData = true;
|
||||
endsWithNewline = (buffer[read - 1] == '\n');
|
||||
@@ -478,10 +518,87 @@ public final class S3CopySimulator {
|
||||
backendOut.flush();
|
||||
}
|
||||
|
||||
private static List<String> discoverTableColumns(Socket client, Socket backend,
|
||||
CopyStatementParser.S3CopyFrom spec,
|
||||
char txStatus, IntConsumer onStatusChange) throws IOException {
|
||||
String query = "SELECT a.attname FROM pg_catalog.pg_attribute a "
|
||||
/**
|
||||
* Reads one decompressed object into heap and transforms it. The read is bounded by a per-object
|
||||
* ceiling and by a budget shared across connections, so a large or highly compressed object fails
|
||||
* its own statement instead of exhausting the emulator heap.
|
||||
*/
|
||||
private static byte[] transformObject(CopyStatementParser.S3CopyFrom spec, List<Integer> columnMaxBytes,
|
||||
InputStream in) throws IOException {
|
||||
int heldMib = 0;
|
||||
try {
|
||||
ByteArrayOutputStream buffered = new ByteArrayOutputStream();
|
||||
byte[] chunk = new byte[CHUNK];
|
||||
long total = 0;
|
||||
int read;
|
||||
while ((read = in.read(chunk)) != -1) {
|
||||
total += read;
|
||||
if (total > COPY_TRANSFORM_MAX_OBJECT_BYTES) {
|
||||
throw new S3TransferException(SQLSTATE_PROGRAM_LIMIT_EXCEEDED,
|
||||
"COPY object exceeds the " + COPY_TRANSFORM_MAX_OBJECT_BYTES
|
||||
+ "-byte limit for the field-level options "
|
||||
+ "(EMPTYASNULL, BLANKSASNULL, REMOVEQUOTES, ACCEPTINVCHARS, TRUNCATECOLUMNS)", null);
|
||||
}
|
||||
int wantedMib = (int) ((total * COPY_TRANSFORM_HEAP_FACTOR) / (1024 * 1024)) + 1;
|
||||
while (heldMib < wantedMib) {
|
||||
if (!COPY_TRANSFORM_HEAP_MIB.tryAcquire(1)) {
|
||||
throw new S3TransferException(SQLSTATE_CONFIGURATION_LIMIT_EXCEEDED,
|
||||
"COPY memory budget exhausted; retry shortly", null);
|
||||
}
|
||||
heldMib++;
|
||||
}
|
||||
buffered.write(chunk, 0, read);
|
||||
}
|
||||
return new CopyRecordTransformer(spec, columnMaxBytes).apply(buffered.toByteArray());
|
||||
} finally {
|
||||
COPY_TRANSFORM_HEAP_MIB.release(heldMib);
|
||||
}
|
||||
}
|
||||
|
||||
record ColumnInfo(String name, Integer maxBytes) {
|
||||
}
|
||||
|
||||
/** Positional max character length per COPY column; null entries mean no limit. */
|
||||
static List<Integer> alignMaxBytes(CopyStatementParser.S3CopyFrom spec, List<ColumnInfo> catalog) {
|
||||
if (spec.columns() == null || spec.columns().isEmpty()) {
|
||||
return catalog.stream().map(ColumnInfo::maxBytes).toList();
|
||||
}
|
||||
Map<String, Integer> byName = new HashMap<>();
|
||||
for (ColumnInfo info : catalog) {
|
||||
byName.put(info.name(), info.maxBytes());
|
||||
}
|
||||
List<Integer> aligned = new ArrayList<>();
|
||||
for (String column : spec.columns()) {
|
||||
String key = column.startsWith("\"") ? unquoteIdentifier(column) : column.toLowerCase(Locale.ROOT);
|
||||
aligned.add(byName.get(key));
|
||||
}
|
||||
return aligned;
|
||||
}
|
||||
|
||||
private static List<String> parseDataRow(byte[] body) {
|
||||
int count = ((body[0] & 0xFF) << 8) | (body[1] & 0xFF);
|
||||
List<String> values = new ArrayList<>(count);
|
||||
int offset = 2;
|
||||
for (int i = 0; i < count; i++) {
|
||||
int length = ((body[offset] & 0xFF) << 24) | ((body[offset + 1] & 0xFF) << 16)
|
||||
| ((body[offset + 2] & 0xFF) << 8) | (body[offset + 3] & 0xFF);
|
||||
offset += 4;
|
||||
if (length < 0) {
|
||||
values.add(null);
|
||||
continue;
|
||||
}
|
||||
values.add(new String(body, offset, length, StandardCharsets.UTF_8));
|
||||
offset += length;
|
||||
}
|
||||
return values;
|
||||
}
|
||||
|
||||
private static List<ColumnInfo> discoverColumnInfo(Socket client, Socket backend,
|
||||
CopyStatementParser.S3CopyFrom spec,
|
||||
char txStatus, IntConsumer onStatusChange) throws IOException {
|
||||
// 1042 = bpchar, 1043 = varchar; atttypmod carries the declared length plus a 4-byte header.
|
||||
String query = "SELECT a.attname, CASE WHEN a.atttypid IN (1042, 1043) AND a.atttypmod > 4 "
|
||||
+ "THEN a.atttypmod - 4 END FROM pg_catalog.pg_attribute a "
|
||||
+ "WHERE a.attrelid = to_regclass('" + quoteLiteral(spec.targetTable()) + "') "
|
||||
+ "AND a.attnum > 0 AND NOT a.attisdropped "
|
||||
+ "ORDER BY a.attnum";
|
||||
@@ -491,21 +608,17 @@ public final class S3CopySimulator {
|
||||
backendOut.flush();
|
||||
|
||||
PostgresWireDecoder backendDecoder = new PostgresWireDecoder(backend.getInputStream());
|
||||
List<String> cols = new ArrayList<>();
|
||||
List<ColumnInfo> cols = new ArrayList<>();
|
||||
PostgresWireDecoder.FrontendMessage msg;
|
||||
while ((msg = backendDecoder.nextMessage()) != null) {
|
||||
char type = msg.type();
|
||||
if (type == 'D') {
|
||||
byte[] body = msg.body();
|
||||
if (body.length >= 6) {
|
||||
int colCount = ((body[0] & 0xFF) << 8) | (body[1] & 0xFF);
|
||||
if (colCount >= 1) {
|
||||
int colLen = ((body[2] & 0xFF) << 24) | ((body[3] & 0xFF) << 16)
|
||||
| ((body[4] & 0xFF) << 8) | (body[5] & 0xFF);
|
||||
if (colLen > 0 && 6 + colLen <= body.length) {
|
||||
cols.add(new String(body, 6, colLen, StandardCharsets.UTF_8));
|
||||
}
|
||||
}
|
||||
List<String> values = parseDataRow(msg.body());
|
||||
if (!values.isEmpty() && values.get(0) != null) {
|
||||
Integer maxBytes = values.size() >= 2 && values.get(1) != null
|
||||
? Integer.valueOf(values.get(1))
|
||||
: null;
|
||||
cols.add(new ColumnInfo(values.get(0), maxBytes));
|
||||
}
|
||||
} else if (type == 'E') {
|
||||
forward(client, msg);
|
||||
@@ -886,6 +999,80 @@ public final class S3CopySimulator {
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Lists every object under the target prefix and authorizes the delete of each, so a denial fails
|
||||
* the UNLOAD before anything is removed or written. It runs at preparation, to fail early, and
|
||||
* again when the first output arrives, to delete what is there then. Nothing is deleted here, so
|
||||
* a query the backend rejects, or a failed memory reservation, leaves the previous export in place.
|
||||
*/
|
||||
private static List<String> collectCleanPathKeys(CopyStatementParser.S3Unload spec, S3Service s3,
|
||||
IamService iamService,
|
||||
RedshiftRoleAccess.RoleSession roleSession) {
|
||||
authorizeCleanPathList(spec, s3, iamService, roleSession);
|
||||
List<String> keys = new ArrayList<>();
|
||||
String continuationToken = null;
|
||||
do {
|
||||
S3Service.ListObjectsResult result = s3.listObjectsWithPrefixes(
|
||||
spec.bucket(), spec.prefix(), null, LIST_PAGE_SIZE, continuationToken, null);
|
||||
if (result != null && result.objects() != null) {
|
||||
for (S3Object object : result.objects()) {
|
||||
keys.add(object.getKey());
|
||||
}
|
||||
}
|
||||
continuationToken = (result != null && result.isTruncated()) ? result.nextContinuationToken() : null;
|
||||
} while (continuationToken != null);
|
||||
|
||||
for (String key : keys) {
|
||||
authorizeCleanPathDelete(spec, s3, iamService, roleSession, key);
|
||||
}
|
||||
return keys;
|
||||
}
|
||||
|
||||
private static void authorizeCleanPathList(CopyStatementParser.S3Unload spec, S3Service s3,
|
||||
IamService iamService,
|
||||
RedshiftRoleAccess.RoleSession roleSession) {
|
||||
if (roleSession != null) {
|
||||
RedshiftRoleAccess.authorizeRoleAction(s3, iamService, spec.iamRoleArn(), "s3:ListBucket",
|
||||
RedshiftRoleAccess.bucketArn(spec.iamRoleArn(), spec.bucket()));
|
||||
s3.authorizeSignedListBucket(roleSession.accessKeyId(), roleSession.sessionToken(), spec.bucket());
|
||||
} else {
|
||||
s3.authorizeAnonymousListBucket(spec.bucket());
|
||||
}
|
||||
}
|
||||
|
||||
private static void authorizeCleanPathDelete(CopyStatementParser.S3Unload spec, S3Service s3,
|
||||
IamService iamService,
|
||||
RedshiftRoleAccess.RoleSession roleSession, String key) {
|
||||
if (roleSession != null) {
|
||||
RedshiftRoleAccess.authorizeRoleAction(s3, iamService, spec.iamRoleArn(), "s3:DeleteObject",
|
||||
RedshiftRoleAccess.objectArn(spec.iamRoleArn(), spec.bucket(), key));
|
||||
s3.authorizeSignedDeleteObject(roleSession.accessKeyId(), roleSession.sessionToken(),
|
||||
spec.bucket(), key);
|
||||
} else {
|
||||
s3.authorizeAnonymousDeleteObject(spec.bucket(), key);
|
||||
}
|
||||
}
|
||||
|
||||
/** Server-side encryption headers requested by ENCRYPTED KMS_KEY_ID, or null when none apply. */
|
||||
private static PutObjectOptions unloadObjectOptions(CopyStatementParser.S3Unload spec) {
|
||||
if (spec.sseKmsKeyId() == null) {
|
||||
return null;
|
||||
}
|
||||
return new PutObjectOptions()
|
||||
.withServerSideEncryption("aws:kms")
|
||||
.withSseKmsKeyId(spec.sseKmsKeyId());
|
||||
}
|
||||
|
||||
private static void putUnloadObject(S3Service s3, CopyStatementParser.S3Unload spec, String key,
|
||||
byte[] payload, String contentType) {
|
||||
PutObjectOptions options = unloadObjectOptions(spec);
|
||||
if (options == null) {
|
||||
s3.putObject(spec.bucket(), key, payload, contentType, Map.of());
|
||||
} else {
|
||||
s3.putObject(spec.bucket(), key, payload, contentType, Map.of(), options);
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean targetPrefixHasObjects(CopyStatementParser.S3Unload spec, S3Service s3) {
|
||||
S3Service.ListObjectsResult r = s3.listObjectsWithPrefixes(
|
||||
spec.bucket(), spec.prefix(), null, 1, null, null);
|
||||
@@ -920,6 +1107,8 @@ public final class S3CopySimulator {
|
||||
private final String contentType;
|
||||
private final List<String> writtenKeys = new ArrayList<>();
|
||||
private final List<Integer> writtenLengths = new ArrayList<>();
|
||||
private final boolean cleanPathPending;
|
||||
private boolean cleanPathDone;
|
||||
|
||||
private ByteArrayOutputStream sink = new ByteArrayOutputStream();
|
||||
private OutputStream acc;
|
||||
@@ -938,8 +1127,10 @@ public final class S3CopySimulator {
|
||||
private int heldMib = UNLOAD_INITIAL_MIB;
|
||||
|
||||
private S3UnloadCollector(CopyStatementParser.S3Unload spec, S3Service s3,
|
||||
IamService iamService, RedshiftRoleAccess.RoleSession roleSession) throws IOException {
|
||||
IamService iamService, RedshiftRoleAccess.RoleSession roleSession,
|
||||
boolean cleanPath) throws IOException {
|
||||
this.spec = spec;
|
||||
this.cleanPathPending = cleanPath;
|
||||
this.s3 = s3;
|
||||
this.iamService = iamService;
|
||||
this.roleSession = roleSession;
|
||||
@@ -953,6 +1144,7 @@ public final class S3CopySimulator {
|
||||
@Override
|
||||
public void accept(byte[] body) throws IOException {
|
||||
ensureOpen();
|
||||
runCleanPath();
|
||||
int dataStart = 0;
|
||||
if (capturingHeader) {
|
||||
int newline = -1;
|
||||
@@ -1001,6 +1193,7 @@ public final class S3CopySimulator {
|
||||
@Override
|
||||
public void complete() throws IOException {
|
||||
ensureOpen();
|
||||
runCleanPath();
|
||||
byte[] payload = finishSlice(acc, sink);
|
||||
if (slicePayload > 0 || writtenKeys.isEmpty()) {
|
||||
writePayload(payload, sliceIndex);
|
||||
@@ -1015,10 +1208,10 @@ public final class S3CopySimulator {
|
||||
} else {
|
||||
s3.authorizeAnonymousPutObject(spec.bucket(), key);
|
||||
}
|
||||
s3.putObject(spec.bucket(), key,
|
||||
putUnloadObject(s3, spec, key,
|
||||
manifestJson(spec.bucket(), writtenKeys, writtenLengths)
|
||||
.getBytes(StandardCharsets.UTF_8),
|
||||
"application/json", Map.of());
|
||||
"application/json");
|
||||
} catch (RuntimeException e) {
|
||||
fail(SQLSTATE_INTERNAL, "UNLOAD manifest write failed", e);
|
||||
}
|
||||
@@ -1052,6 +1245,25 @@ public final class S3CopySimulator {
|
||||
closed = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* CLEANPATH, second half: once, before the first write, removes what is under the prefix then.
|
||||
* S3 lists, authorizes every delete and deletes under one bucket lock, so an object uploaded
|
||||
* since preparation, or while this runs, does not survive next to the new export.
|
||||
*/
|
||||
private void runCleanPath() {
|
||||
if (cleanPathDone || !cleanPathPending) {
|
||||
return;
|
||||
}
|
||||
cleanPathDone = true;
|
||||
try {
|
||||
authorizeCleanPathList(spec, s3, iamService, roleSession);
|
||||
s3.deleteObjectsWithPrefix(spec.bucket(), spec.prefix(),
|
||||
key -> authorizeCleanPathDelete(spec, s3, iamService, roleSession, key));
|
||||
} catch (RuntimeException e) {
|
||||
fail(SQLSTATE_INTERNAL, "UNLOAD CLEANPATH failed", e);
|
||||
}
|
||||
}
|
||||
|
||||
private void acquireForCurrentSlice() {
|
||||
int wantedMib = (int) ((rawSlice * 3) / (1024 * 1024)) + 1;
|
||||
while (heldMib < wantedMib) {
|
||||
@@ -1079,7 +1291,7 @@ public final class S3CopySimulator {
|
||||
} else {
|
||||
s3.authorizeAnonymousPutObject(spec.bucket(), key);
|
||||
}
|
||||
s3.putObject(spec.bucket(), key, payload, contentType, Map.of());
|
||||
putUnloadObject(s3, spec, key, payload, contentType);
|
||||
} catch (AwsException e) {
|
||||
fail(unloadWriteSqlState(e), unloadWriteMessage(e, spec), e);
|
||||
} catch (RuntimeException e) {
|
||||
@@ -1134,6 +1346,11 @@ public final class S3CopySimulator {
|
||||
String base = spec.parallel()
|
||||
? spec.prefix() + String.format("%04d_part_00", index)
|
||||
: spec.prefix() + String.format("%03d", index);
|
||||
if (spec.extension() != null) {
|
||||
// AWS adds the compression suffix only when no extension is given (its example is
|
||||
// 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;
|
||||
}
|
||||
|
||||
|
||||
@@ -113,6 +113,7 @@ public class S3Service implements Resettable, ResourceProvider {
|
||||
private static final Set<String> SUPPORTED_SERVER_SIDE_ENCRYPTION_VALUES = Set.of("AES256", "aws:kms", "aws:kms:dsse", "aws:fsx");
|
||||
private static final String SSE_C_ALGORITHM = "AES256";
|
||||
private static final int SSE_C_KEY_BYTES = 32;
|
||||
private static final int DELETE_PREFIX_PAGE_SIZE = 1000;
|
||||
|
||||
@FunctionalInterface
|
||||
interface LambdaInvoker {
|
||||
@@ -1915,6 +1916,37 @@ public class S3Service implements Resettable, ResourceProvider {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes every object whose key starts with {@code prefix}. The bucket monitor is held across the
|
||||
* listing, the authorization of each key and the deletes, so a concurrent PutObject cannot land
|
||||
* between them and survive. {@code authorizeDelete} runs for every key before the first delete, so
|
||||
* a denial removes nothing.
|
||||
*/
|
||||
public int deleteObjectsWithPrefix(String bucketName, String prefix, Consumer<String> authorizeDelete) {
|
||||
Bucket bucket = bucketStore.get(bucketName)
|
||||
.orElseThrow(() -> new AwsException("NoSuchBucket",
|
||||
"The specified bucket does not exist.", 404));
|
||||
synchronized (bucket) {
|
||||
List<String> keys = new ArrayList<>();
|
||||
String continuationToken = null;
|
||||
do {
|
||||
ListObjectsResult page = listObjectsWithPrefixes(
|
||||
bucketName, prefix, null, DELETE_PREFIX_PAGE_SIZE, continuationToken, null);
|
||||
for (S3Object object : page.objects()) {
|
||||
keys.add(object.getKey());
|
||||
}
|
||||
continuationToken = page.isTruncated() ? page.nextContinuationToken() : null;
|
||||
} while (continuationToken != null);
|
||||
for (String key : keys) {
|
||||
authorizeDelete.accept(key);
|
||||
}
|
||||
for (String key : keys) {
|
||||
deleteObject(bucketName, key);
|
||||
}
|
||||
return keys.size();
|
||||
}
|
||||
}
|
||||
|
||||
// A current delete marker answers 404 NoSuchKey, the same as a missing key. That is deliberate:
|
||||
// the S3 conditional-deletes guide says "If the latest version of the object is a delete marker,
|
||||
// the object doesn't exist and the DeleteObject API will fail and return a 412 Precondition
|
||||
|
||||
Reference in new issue
Block a user