mirror of
https://github.com/floci-io/floci.git
synced 2026-11-24 06:20:24 -05:00
feat(redshift): emulate Redshift COPY FROM s3 over Simple Query protocol (#3100)
* feat(redshift): parse COPY FROM s3 statements
* feat(redshift): simulate Redshift COPY FROM s3 via CopyIn
* feat(redshift): mediate the intercepting bridge pump with a backend lock
* feat(redshift): dispatch COPY FROM s3 via intercepting bridge
* test(redshift): cover COPY from S3 end to end
* docs(redshift): document COPY from S3 support
* fix(redshift): harden the S3 COPY simulator error and protocol handling
Address code review findings on the Part 4 COPY simulator:
- Guarantee exactly one client response on a mid-copy failure. The abort
path sent CopyFail, relayed the backend's ErrorResponse/ReadyForQuery,
then also synthesized its own, desynchronizing the client. It now emits
one response: the backend's, or a synthesized one only when the backend
is unreachable.
- Catch RuntimeException (AwsException) while streaming objects. A key that
vanished between listing and reading previously propagated out of the
bridge and closed the connection with the backend stuck in CopyIn.
- Reply to the client when the backend closes before CopyInResponse
instead of returning silently and leaving the client blocked.
- Stop doubling backslashes when quoting DELIMITER / NULL values. Under
standard_conforming_strings a backslash is literal, so NULL AS '\N' was
reaching the backend as '\N' and nulls loaded as text.
- Reject COPY statements carrying an option the simulator cannot honour
(PARQUET, JSON, MAXERROR, credentials, ...) or a trailing statement,
so they fail open to PostgreSQL rather than loading with wrong framing.
- Scan option keywords with string literals blanked, so NULL AS 'csv' no
longer flips the format and DELIMITER ';' no longer trips the trailing
check.
- Report the failed-transaction status ('E') in a synthesized error when
the client is in a transaction block; track it from the backend's
ReadyForQuery in the bridge.
- Bound the backend read timeout during an owned exchange (60s) instead of
blocking forever; back off between idle-wait retries.
- Relay asynchronous backend messages (NoticeResponse, ParameterStatus)
to the client instead of dropping them; log every tolerated AwsException.
- Honour the BackendExchange return value so a future interceptor can
decline before touching the backend.
Tests: cover the mid-copy abort (one E + one Z), backend EOF, literal
NULL AS '\N', the unsupported-clause and trailing-statement rejections,
failed-transaction status, plus a GZIP end-to-end case; the missing-object
integration test now seeds its own bucket.
* fix(redshift): address review feedback on COPY option parsing, prefix pagination, and tx state
* fix(redshift): handle backend tx abort sync failure and log socket close
* fix(redshift): verify backend transaction status 'E' after abort query
This commit is contained in:
1 parent
ee5c87d6d6
commit
85180a4d88
13 files changed
+1868
-64
No files matched your search
+275
@@ -0,0 +1,275 @@
|
||||
package io.github.hectorvent.floci.services.redshift.proxy;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* Recognises a Simple Query statement that is an S3 {@code COPY <table> FROM 's3://...'}.
|
||||
* Any other statement, or a COPY that uses an option this simulator cannot honour, returns
|
||||
* {@code null} so the bridge falls back to DDL rewriting and PostgreSQL reports its own error.
|
||||
*/
|
||||
public final class CopyStatementParser {
|
||||
|
||||
public record S3CopyFrom(
|
||||
String targetTable,
|
||||
List<String> columns,
|
||||
String bucket,
|
||||
String keyOrPrefix,
|
||||
String delimiter,
|
||||
int headerLines,
|
||||
boolean gzip,
|
||||
boolean csv,
|
||||
String nullAs) {
|
||||
}
|
||||
|
||||
private static final Pattern COPY_PATTERN = Pattern.compile(
|
||||
"(?is)^\\s*COPY\\s+((?:\"[^\"]*\"|[^\\s(])+)\\s*(?:\\(([^)]*)\\))?\\s+FROM\\s*"
|
||||
+ "['\"]s3://([^/'\"\\s]+)(?:/([^'\"\\s]*))?['\"]\\s*(.*)$");
|
||||
|
||||
private static final Pattern QUALIFIED_NAME = Pattern.compile(
|
||||
"(?:[A-Za-z_][A-Za-z0-9_$]*|\"[^\"]+\")(?:\\.(?:[A-Za-z_][A-Za-z0-9_$]*|\"[^\"]+\"))?");
|
||||
private static final Pattern SIMPLE_NAME = Pattern.compile("[A-Za-z_][A-Za-z0-9_$]*|\"[^\"]+\"");
|
||||
|
||||
private static final Pattern DELIMITER_PATTERN = Pattern.compile(
|
||||
"(?i)\\bDELIMITER\\s+(?:AS\\s+)?(?:'((?:[^']|'')*)'|\"([^\"]*)\"|([^\\s;]+))");
|
||||
private static final Pattern NULL_AS_PATTERN = Pattern.compile(
|
||||
"(?i)\\bNULL\\s+(?:AS\\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");
|
||||
private static final Pattern GZIP_PATTERN = Pattern.compile("(?i)\\bGZIP\\b");
|
||||
private static final Pattern CSV_PATTERN = Pattern.compile("(?i)\\b(?:FORMAT\\s+(?:AS\\s+)?)?CSV\\b");
|
||||
|
||||
/**
|
||||
* Options this simulator does not implement. A COPY carrying any of these is not intercepted:
|
||||
* the original statement is forwarded so PostgreSQL rejects it, rather than the simulator
|
||||
* silently loading the data with the wrong framing.
|
||||
*/
|
||||
private static final Pattern UNSUPPORTED_CLAUSE = Pattern.compile(
|
||||
"(?i)\\b(FIXEDWIDTH|PARQUET|AVRO|ORC|JSON|SHAPEFILE|BZIP2|LZOP|ZSTD|MANIFEST|MAXERROR"
|
||||
+ "|DATEFORMAT|TIMEFORMAT|ENCRYPTED|ENCODING|REGION|CREDENTIALS|IAM_ROLE"
|
||||
+ "|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"
|
||||
+ "|STATUPDATE|NOLOAD|ROUNDEC|QUOTE|SSH|READRATIO|COMPROWS|DIMENSION)\\b");
|
||||
|
||||
/** A {@code ;} followed by another statement: only a lone trailing {@code ;} is tolerated. */
|
||||
private static final Pattern TRAILING_STATEMENT = Pattern.compile(";\\s*\\S");
|
||||
|
||||
private CopyStatementParser() {
|
||||
}
|
||||
|
||||
public static S3CopyFrom parse(String sql) {
|
||||
if (sql == null || sql.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
String cleaned = stripLeadingComments(sql.trim());
|
||||
Matcher matcher = COPY_PATTERN.matcher(cleaned);
|
||||
if (!matcher.matches()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
String table = matcher.group(1).trim();
|
||||
if (!QUALIFIED_NAME.matcher(table).matches()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
List<String> columns = List.of();
|
||||
String columnsGroup = matcher.group(2);
|
||||
if (columnsGroup != null && !columnsGroup.isBlank()) {
|
||||
columns = Arrays.stream(columnsGroup.split(","))
|
||||
.map(String::trim)
|
||||
.filter(s -> !s.isEmpty())
|
||||
.toList();
|
||||
if (columns.stream().anyMatch(c -> !SIMPLE_NAME.matcher(c).matches())) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
String bucket = matcher.group(3);
|
||||
String keyOrPrefix = matcher.group(4) != null ? matcher.group(4) : "";
|
||||
String options = matcher.group(5) != null ? matcher.group(5) : "";
|
||||
|
||||
// Scan for keywords and separators on a copy with string literals blanked out, so a
|
||||
// value like NULL AS 'json' or DELIMITER ';' cannot trip a keyword or the trailing check.
|
||||
String flagScan = blankQuoted(options);
|
||||
if (UNSUPPORTED_CLAUSE.matcher(flagScan).find() || TRAILING_STATEMENT.matcher(flagScan).find()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
int semiIdx = flagScan.indexOf(';');
|
||||
if (semiIdx >= 0) {
|
||||
if (!flagScan.substring(semiIdx + 1).isBlank()) {
|
||||
return null;
|
||||
}
|
||||
options = options.substring(0, semiIdx);
|
||||
}
|
||||
|
||||
boolean csv = false;
|
||||
boolean gzip = false;
|
||||
String nullAs = null;
|
||||
String delimiter = null;
|
||||
int headerLines = 0;
|
||||
|
||||
boolean seenCsv = false;
|
||||
boolean seenGzip = false;
|
||||
boolean seenNull = false;
|
||||
boolean seenDelimiter = false;
|
||||
boolean seenHeader = false;
|
||||
|
||||
Matcher csvMatcher = CSV_PATTERN.matcher(options);
|
||||
Matcher gzipMatcher = GZIP_PATTERN.matcher(options);
|
||||
Matcher ignoreHeaderMatcher = IGNOREHEADER_PATTERN.matcher(options);
|
||||
Matcher headerMatcher = HEADER_PATTERN.matcher(options);
|
||||
Matcher delimiterMatcher = DELIMITER_PATTERN.matcher(options);
|
||||
Matcher nullMatcher = NULL_AS_PATTERN.matcher(options);
|
||||
|
||||
int offset = 0;
|
||||
int len = options.length();
|
||||
while (offset < len) {
|
||||
while (offset < len && Character.isWhitespace(options.charAt(offset))) {
|
||||
offset++;
|
||||
}
|
||||
if (offset >= len) {
|
||||
break;
|
||||
}
|
||||
|
||||
if (matchClause(csvMatcher, offset, len)) {
|
||||
if (seenCsv) {
|
||||
return null;
|
||||
}
|
||||
seenCsv = true;
|
||||
csv = true;
|
||||
offset = csvMatcher.end();
|
||||
} else if (matchClause(gzipMatcher, offset, len)) {
|
||||
if (seenGzip) {
|
||||
return null;
|
||||
}
|
||||
seenGzip = true;
|
||||
gzip = true;
|
||||
offset = gzipMatcher.end();
|
||||
} else if (matchClause(ignoreHeaderMatcher, offset, len)) {
|
||||
if (seenHeader) {
|
||||
return null;
|
||||
}
|
||||
seenHeader = true;
|
||||
headerLines = Math.max(0, Integer.parseInt(ignoreHeaderMatcher.group(1)));
|
||||
offset = ignoreHeaderMatcher.end();
|
||||
} else if (matchClause(headerMatcher, offset, len)) {
|
||||
if (seenHeader) {
|
||||
return null;
|
||||
}
|
||||
seenHeader = true;
|
||||
headerLines = 1;
|
||||
offset = headerMatcher.end();
|
||||
} else if (matchClause(delimiterMatcher, offset, len)) {
|
||||
if (seenDelimiter) {
|
||||
return null;
|
||||
}
|
||||
seenDelimiter = true;
|
||||
delimiter = extractDelimiterValue(delimiterMatcher);
|
||||
offset = delimiterMatcher.end();
|
||||
} else if (matchClause(nullMatcher, offset, len)) {
|
||||
if (seenNull) {
|
||||
return null;
|
||||
}
|
||||
seenNull = true;
|
||||
nullAs = extractNullValue(nullMatcher);
|
||||
offset = nullMatcher.end();
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
if (delimiter == null) {
|
||||
delimiter = csv ? "," : "|";
|
||||
}
|
||||
|
||||
return new S3CopyFrom(table, columns, bucket, keyOrPrefix, delimiter, headerLines, gzip, csv, nullAs);
|
||||
}
|
||||
|
||||
private static boolean matchClause(Matcher m, int start, int end) {
|
||||
m.region(start, end);
|
||||
return m.lookingAt();
|
||||
}
|
||||
|
||||
private static String extractDelimiterValue(Matcher matcher) {
|
||||
String value = matcher.group(1) != null ? matcher.group(1)
|
||||
: matcher.group(2) != null ? matcher.group(2)
|
||||
: matcher.group(3);
|
||||
if (value != null) {
|
||||
value = unescape(value);
|
||||
}
|
||||
return "\\t".equals(value) || "\t".equals(value) ? "\t" : value;
|
||||
}
|
||||
|
||||
private static String extractNullValue(Matcher matcher) {
|
||||
String value = matcher.group(1) != null ? matcher.group(1) : matcher.group(2);
|
||||
return unescape(value);
|
||||
}
|
||||
|
||||
private static String unescape(String s) {
|
||||
if (s == null) {
|
||||
return null;
|
||||
}
|
||||
return s.replace("''", "'").replace("\\\\", "\\");
|
||||
}
|
||||
|
||||
/** Replace every character inside a single- or double-quoted run with a space. */
|
||||
private static String blankQuoted(String s) {
|
||||
StringBuilder out = new StringBuilder(s.length());
|
||||
boolean inSingle = false;
|
||||
boolean inDouble = false;
|
||||
for (int i = 0; i < s.length(); i++) {
|
||||
char c = s.charAt(i);
|
||||
if (inSingle) {
|
||||
if (c == '\'') {
|
||||
if (i + 1 < s.length() && s.charAt(i + 1) == '\'') {
|
||||
out.append(" ");
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
inSingle = false;
|
||||
}
|
||||
out.append(' ');
|
||||
} else if (inDouble) {
|
||||
if (c == '"') {
|
||||
inDouble = false;
|
||||
}
|
||||
out.append(' ');
|
||||
} else if (c == '\'') {
|
||||
inSingle = true;
|
||||
out.append(' ');
|
||||
} else if (c == '"') {
|
||||
inDouble = true;
|
||||
out.append(' ');
|
||||
} else {
|
||||
out.append(c);
|
||||
}
|
||||
}
|
||||
return out.toString();
|
||||
}
|
||||
|
||||
private static String stripLeadingComments(String sql) {
|
||||
String current = sql;
|
||||
while (true) {
|
||||
if (current.startsWith("--")) {
|
||||
int newline = current.indexOf('\n');
|
||||
if (newline < 0) {
|
||||
return "";
|
||||
}
|
||||
current = current.substring(newline + 1).stripLeading();
|
||||
} else if (current.startsWith("/*")) {
|
||||
int close = current.indexOf("*/");
|
||||
if (close < 0) {
|
||||
return "";
|
||||
}
|
||||
current = current.substring(close + 2).stripLeading();
|
||||
} else {
|
||||
return current;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+6
-2
@@ -4,6 +4,7 @@ import io.github.hectorvent.floci.services.rds.proxy.PostgresProtocolHandler;
|
||||
import io.github.hectorvent.floci.services.rds.proxy.RdsAuthProxy;
|
||||
import io.github.hectorvent.floci.services.rds.proxy.RdsProxyTlsCertificates;
|
||||
import io.github.hectorvent.floci.services.rds.proxy.RdsSigV4Validator;
|
||||
import io.github.hectorvent.floci.services.s3.S3Service;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.io.IOException;
|
||||
@@ -32,6 +33,7 @@ public class RedshiftAuthProxy {
|
||||
private final RdsSigV4Validator sigV4;
|
||||
private final RdsProxyTlsCertificates tlsCertificates;
|
||||
private final RdsAuthProxy.PasswordValidator passwordValidator;
|
||||
private final S3Service s3Service;
|
||||
|
||||
private volatile boolean running;
|
||||
private ServerSocket serverSocket;
|
||||
@@ -39,7 +41,8 @@ public class RedshiftAuthProxy {
|
||||
public RedshiftAuthProxy(String clusterKey, String backendHost, int backendPort,
|
||||
String masterUsername, String masterPassword, String dbName,
|
||||
RdsSigV4Validator sigV4, RdsProxyTlsCertificates tlsCertificates,
|
||||
RdsAuthProxy.PasswordValidator passwordValidator) {
|
||||
RdsAuthProxy.PasswordValidator passwordValidator,
|
||||
S3Service s3Service) {
|
||||
this.clusterKey = clusterKey;
|
||||
this.backendHost = backendHost;
|
||||
this.backendPort = backendPort;
|
||||
@@ -49,6 +52,7 @@ public class RedshiftAuthProxy {
|
||||
this.sigV4 = sigV4;
|
||||
this.tlsCertificates = tlsCertificates;
|
||||
this.passwordValidator = passwordValidator;
|
||||
this.s3Service = s3Service;
|
||||
}
|
||||
|
||||
public void start(int proxyPort) throws IOException {
|
||||
@@ -145,7 +149,7 @@ public class RedshiftAuthProxy {
|
||||
if (session != null) {
|
||||
// Redshift-only DDL (DISTKEY/SORTKEY/ENCODE/...) is rewritten for the plain
|
||||
// PostgreSQL backend on the way through; every other message is relayed verbatim.
|
||||
new RedshiftInterceptingBridge(session.client(), backend).run();
|
||||
new RedshiftInterceptingBridge(session.client(), backend, s3Service).run();
|
||||
}
|
||||
} catch (Exception e) {
|
||||
LOG.debugv("Redshift connection error for cluster {0}: {1}", clusterKey, e.getMessage());
|
||||
|
||||
+223
-48
@@ -1,117 +1,292 @@
|
||||
package io.github.hectorvent.floci.services.redshift.proxy;
|
||||
|
||||
import io.github.hectorvent.floci.services.s3.S3Service;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.net.Socket;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.net.SocketTimeoutException;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.concurrent.locks.LockSupport;
|
||||
import java.util.concurrent.locks.ReentrantLock;
|
||||
import java.util.function.IntConsumer;
|
||||
|
||||
/**
|
||||
* Replaces the transparent {@code PostgresProtocolHandler.bridge} for Redshift connections so
|
||||
* Simple Query ({@code 'Q'}) DDL can be rewritten for a plain PostgreSQL backend before it is
|
||||
* forwarded.
|
||||
* Replaces the transparent {@code bridge()} for Redshift connections so Simple Query ({@code 'Q'})
|
||||
* traffic can be inspected before it reaches the backing PostgreSQL container.
|
||||
*
|
||||
* <p><b>Model.</b> Backend→client is a verbatim byte pump on a virtual thread, exactly as a
|
||||
* plain proxy: extended-protocol pipelines, {@code COPY … FROM STDIN}, asynchronous
|
||||
* {@code NotificationResponse} and backend EOF all flow through untouched. Client→backend is
|
||||
* a framed loop: every frontend message is forwarded opaque <em>except</em> a {@code 'Q'}, whose
|
||||
* SQL is run through {@link RedshiftSqlInterceptor#rewrite} and re-encoded only if it changed.
|
||||
* <p><b>Model.</b> Backend→client is a byte pump on a virtual thread. Client→backend is a
|
||||
* framed loop: every frontend message is forwarded opaque except a {@code 'Q'}, whose SQL is run
|
||||
* through {@link RedshiftSqlInterceptor#rewrite} and re-encoded only if it changed.
|
||||
*
|
||||
* <p><b>Fail-open.</b> A {@code rewrite} failure, or any statement the interceptor leaves
|
||||
* untouched, forwards the original bytes; PostgreSQL then returns its own error. The bridge never
|
||||
* closes the connection because of a rewrite failure.
|
||||
* <p><b>Backend ownership.</b> A future interceptor that injects its own query and reads the reply
|
||||
* (the S3 COPY simulator) must own the backend exclusively and only start when no earlier request
|
||||
* is still being answered. {@link #backendLock} serialises pump reads against such an exchange, and
|
||||
* {@link #outstandingResponses} plus {@link #pumpBetweenMessages} gate it to a safe boundary. If the
|
||||
* backend cannot be caught idle within {@link #PUMP_PARK_WAIT_MS}, the exchange is skipped and the
|
||||
* original {@code 'Q'} is forwarded (fail-open).
|
||||
*/
|
||||
public class RedshiftInterceptingBridge {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(RedshiftInterceptingBridge.class);
|
||||
|
||||
private static final int PUMP_READ_TIMEOUT_MS = 200;
|
||||
private static final int CLIENT_READ_TIMEOUT_MS = 10_000;
|
||||
private static final long PUMP_PARK_WAIT_MS = 2_000L;
|
||||
/** Bounded read timeout while an exchange owns the backend, so a stalled backend cannot hang the session. */
|
||||
private static final int EXCHANGE_READ_TIMEOUT_MS = 60_000;
|
||||
private static final long BUSY_BACKOFF_NANOS = 2_000_000L;
|
||||
|
||||
private final Socket client;
|
||||
private final Socket backend;
|
||||
private final AtomicBoolean closed = new AtomicBoolean();
|
||||
private final S3Service s3Service;
|
||||
|
||||
public RedshiftInterceptingBridge(Socket client, Socket backend) {
|
||||
private final ReentrantLock backendLock = new ReentrantLock(true);
|
||||
private volatile boolean pumpBetweenMessages = true;
|
||||
private final AtomicInteger outstandingResponses = new AtomicInteger(0);
|
||||
private volatile boolean pumpFinished = false;
|
||||
/** Transaction-status byte from the backend's most recent {@code ReadyForQuery}; {@code 'I'} until one is seen. */
|
||||
private volatile char lastBackendStatus = 'I';
|
||||
|
||||
public RedshiftInterceptingBridge(Socket client, Socket backend, S3Service s3Service) {
|
||||
this.client = client;
|
||||
this.backend = backend;
|
||||
this.s3Service = s3Service;
|
||||
}
|
||||
|
||||
@FunctionalInterface
|
||||
interface BackendExchange {
|
||||
/** @return {@code true} if the exchange handled the query; {@code false} to forward the original. */
|
||||
boolean run() throws IOException;
|
||||
}
|
||||
|
||||
public void run() {
|
||||
try {
|
||||
InputStream clientIn = client.getInputStream();
|
||||
OutputStream backendOut = backend.getOutputStream();
|
||||
|
||||
backend.setSoTimeout(PUMP_READ_TIMEOUT_MS);
|
||||
client.setSoTimeout(CLIENT_READ_TIMEOUT_MS);
|
||||
Thread.ofVirtual().name("redshift-pump-backend-to-client").start(this::pumpBackendToClient);
|
||||
|
||||
InputStream clientIn = client.getInputStream();
|
||||
OutputStream backendOut = backend.getOutputStream();
|
||||
PostgresWireDecoder decoder = new PostgresWireDecoder(clientIn);
|
||||
|
||||
while (true) {
|
||||
PostgresWireDecoder.FrontendMessage msg = decoder.nextMessage(backendOut);
|
||||
PostgresWireDecoder.FrontendMessage msg;
|
||||
try {
|
||||
msg = decoder.nextMessage();
|
||||
} catch (SocketTimeoutException e) {
|
||||
if (decoder.isBetweenMessages()) {
|
||||
continue;
|
||||
}
|
||||
LOG.warnv("Client socket timed out mid-message: {0}", e.getMessage());
|
||||
break;
|
||||
}
|
||||
if (msg == null) {
|
||||
break; // client EOF
|
||||
break;
|
||||
}
|
||||
|
||||
if (!msg.isQuery()) {
|
||||
if (msg.type() == 'X') { // Terminate
|
||||
if (msg.type() == 'S') {
|
||||
outstandingResponses.incrementAndGet();
|
||||
}
|
||||
backendOut.write(msg.toPacketBytes());
|
||||
backendOut.flush();
|
||||
if (msg.type() == 'X') {
|
||||
break;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
String sql = msg.getSql();
|
||||
|
||||
CopyStatementParser.S3CopyFrom copyFrom = null;
|
||||
try {
|
||||
copyFrom = CopyStatementParser.parse(sql);
|
||||
} catch (RuntimeException e) {
|
||||
LOG.warnv("CopyStatementParser failed, forwarding original query: {0}", e.getMessage());
|
||||
}
|
||||
|
||||
if (copyFrom != null) {
|
||||
CopyStatementParser.S3CopyFrom spec = copyFrom;
|
||||
boolean intercepted = runWithBackendOwned(
|
||||
() -> S3CopySimulator.runCopyFrom(client, backend, spec, s3Service, lastBackendStatus,
|
||||
status -> lastBackendStatus = (char) status));
|
||||
if (intercepted) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
byte[] toBackend = msg.toPacketBytes();
|
||||
try {
|
||||
String rewritten = RedshiftSqlInterceptor.rewrite(sql);
|
||||
if (rewritten != sql) { // identity: rewrite returns the same instance when nothing matched
|
||||
if (rewritten != sql) {
|
||||
toBackend = PostgresWireDecoder.encodeQuery(rewritten);
|
||||
}
|
||||
} catch (RuntimeException e) {
|
||||
LOG.warnv("RedshiftSqlInterceptor failed, forwarding original query: {0}", e.getMessage());
|
||||
toBackend = msg.toPacketBytes();
|
||||
}
|
||||
outstandingResponses.incrementAndGet();
|
||||
backendOut.write(toBackend);
|
||||
backendOut.flush();
|
||||
// The response returns over the untouched pump.
|
||||
}
|
||||
} catch (IOException e) {
|
||||
LOG.debugv(e, "RedshiftInterceptingBridge client loop ended");
|
||||
} catch (Exception e) {
|
||||
LOG.warnv(e, "Unexpected error in RedshiftInterceptingBridge");
|
||||
} finally {
|
||||
closeBoth();
|
||||
}
|
||||
}
|
||||
|
||||
private void pumpBackendToClient() {
|
||||
try {
|
||||
InputStream backendIn = backend.getInputStream();
|
||||
OutputStream clientOut = client.getOutputStream();
|
||||
byte[] buf = new byte[8192];
|
||||
int n;
|
||||
while ((n = backendIn.read(buf)) != -1) {
|
||||
clientOut.write(buf, 0, n);
|
||||
clientOut.flush();
|
||||
}
|
||||
} catch (IOException e) {
|
||||
LOG.debugv(e, "backend->client pump ended");
|
||||
} finally {
|
||||
closeBoth();
|
||||
}
|
||||
}
|
||||
|
||||
private void closeBoth() {
|
||||
if (closed.compareAndSet(false, true)) {
|
||||
closeQuietly(client, "client");
|
||||
closeQuietly(backend, "backend");
|
||||
}
|
||||
}
|
||||
|
||||
private void closeQuietly(Socket s, String which) {
|
||||
/**
|
||||
* Take exclusive ownership of an idle backend at a wire-message boundary, run {@code exchange},
|
||||
* then release it. Returns {@code false} if the backend could not be caught idle within
|
||||
* {@link #PUMP_PARK_WAIT_MS}; the caller must then forward the original {@code 'Q'} unmodified.
|
||||
*/
|
||||
boolean runWithBackendOwned(BackendExchange exchange) throws IOException {
|
||||
long deadlineNanos = System.nanoTime() + PUMP_PARK_WAIT_MS * 1_000_000L;
|
||||
while (true) {
|
||||
if (pumpFinished) {
|
||||
return false;
|
||||
}
|
||||
boolean locked;
|
||||
try {
|
||||
locked = backendLock.tryLock(PUMP_READ_TIMEOUT_MS, TimeUnit.MILLISECONDS);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new IOException("interrupted while acquiring the backend lock", e);
|
||||
}
|
||||
if (!locked) {
|
||||
if (System.nanoTime() >= deadlineNanos) {
|
||||
LOG.warn("could not take the backend stream in time; forwarding the COPY unintercepted");
|
||||
return false;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
boolean backendBusy;
|
||||
try {
|
||||
backendBusy = !pumpBetweenMessages || outstandingResponses.get() > 0;
|
||||
if (!backendBusy || pumpFinished) {
|
||||
backend.setSoTimeout(EXCHANGE_READ_TIMEOUT_MS);
|
||||
try {
|
||||
return exchange.run();
|
||||
} finally {
|
||||
try {
|
||||
backend.setSoTimeout(PUMP_READ_TIMEOUT_MS);
|
||||
} catch (IOException e) {
|
||||
LOG.debugv(e, "could not restore backend read timeout (socket closing)");
|
||||
}
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
backendLock.unlock();
|
||||
}
|
||||
if (System.nanoTime() >= deadlineNanos) {
|
||||
LOG.warn("backend did not go idle in time; forwarding the COPY unintercepted");
|
||||
return false;
|
||||
}
|
||||
LockSupport.parkNanos(BUSY_BACKOFF_NANOS);
|
||||
}
|
||||
}
|
||||
|
||||
private void pumpBackendToClient() {
|
||||
WireFrameTracker tracker = new WireFrameTracker(status -> {
|
||||
lastBackendStatus = (char) status;
|
||||
outstandingResponses.updateAndGet(v -> Math.max(0, v - 1));
|
||||
});
|
||||
try {
|
||||
if (s != null && !s.isClosed()) {
|
||||
s.close();
|
||||
InputStream backendIn = backend.getInputStream();
|
||||
OutputStream clientOut = client.getOutputStream();
|
||||
byte[] buffer = new byte[8192];
|
||||
while (true) {
|
||||
backendLock.lockInterruptibly();
|
||||
try {
|
||||
int read;
|
||||
try {
|
||||
read = backendIn.read(buffer);
|
||||
} catch (SocketTimeoutException e) {
|
||||
continue;
|
||||
}
|
||||
if (read == -1) {
|
||||
break;
|
||||
}
|
||||
clientOut.write(buffer, 0, read);
|
||||
clientOut.flush();
|
||||
tracker.consume(buffer, 0, read);
|
||||
pumpBetweenMessages = tracker.betweenMessages();
|
||||
} finally {
|
||||
backendLock.unlock();
|
||||
}
|
||||
}
|
||||
} catch (IOException e) {
|
||||
LOG.debugv(e, "backend->client pump ended");
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
} finally {
|
||||
pumpFinished = true;
|
||||
closeQuietly(client, "client");
|
||||
closeQuietly(backend, "backend");
|
||||
}
|
||||
}
|
||||
|
||||
private void closeQuietly(Socket socket, String which) {
|
||||
try {
|
||||
if (socket != null && !socket.isClosed()) {
|
||||
socket.close();
|
||||
}
|
||||
} catch (IOException e) {
|
||||
LOG.debugv(e, "error closing {0} socket", which);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Tracks PostgreSQL wire-message boundaries in a byte stream without buffering it. Each backend
|
||||
* message is {@code type(1) . length(int32, includes itself) . body}. {@link #betweenMessages()}
|
||||
* is true exactly when the next byte would begin a new message; {@code onReadyForQuery} fires
|
||||
* once per completed {@code 'Z'} with its one-byte transaction-status payload.
|
||||
*/
|
||||
static final class WireFrameTracker {
|
||||
private final IntConsumer onReadyForQuery;
|
||||
private int headerBytesSeen = 0;
|
||||
private final byte[] header = new byte[5];
|
||||
private long bodyRemaining = 0;
|
||||
private char pendingType = 0;
|
||||
|
||||
WireFrameTracker(IntConsumer onReadyForQuery) {
|
||||
this.onReadyForQuery = onReadyForQuery;
|
||||
}
|
||||
|
||||
boolean betweenMessages() {
|
||||
return headerBytesSeen == 0 && bodyRemaining == 0;
|
||||
}
|
||||
|
||||
void consume(byte[] buf, int off, int len) {
|
||||
for (int i = off; i < off + len; i++) {
|
||||
if (bodyRemaining > 0) {
|
||||
int current = buf[i] & 0xFF;
|
||||
bodyRemaining--;
|
||||
if (bodyRemaining == 0 && pendingType == 'Z') {
|
||||
onReadyForQuery.accept(current);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
header[headerBytesSeen++] = buf[i];
|
||||
if (headerBytesSeen == 5) {
|
||||
long msgLen = ((header[1] & 0xFFL) << 24) | ((header[2] & 0xFFL) << 16)
|
||||
| ((header[3] & 0xFFL) << 8) | (header[4] & 0xFFL);
|
||||
pendingType = (char) (header[0] & 0xFF);
|
||||
bodyRemaining = Math.max(0, msgLen - 4);
|
||||
headerBytesSeen = 0;
|
||||
if (bodyRemaining == 0 && pendingType == 'Z') {
|
||||
onReadyForQuery.accept('I');
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+6
-2
@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.redshift.proxy;
|
||||
import io.github.hectorvent.floci.services.rds.proxy.RdsAuthProxy;
|
||||
import io.github.hectorvent.floci.services.rds.proxy.RdsProxyTlsCertificates;
|
||||
import io.github.hectorvent.floci.services.rds.proxy.RdsSigV4Validator;
|
||||
import io.github.hectorvent.floci.services.s3.S3Service;
|
||||
import io.quarkus.runtime.ShutdownEvent;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.enterprise.event.Observes;
|
||||
@@ -24,6 +25,7 @@ public class RedshiftProxyManager {
|
||||
|
||||
private final RdsSigV4Validator sigV4Validator;
|
||||
private final RdsProxyTlsCertificates tlsCertificates;
|
||||
private final S3Service s3Service;
|
||||
private final ConcurrentHashMap<String, RedshiftAuthProxy> proxies = new ConcurrentHashMap<>();
|
||||
/**
|
||||
* Proxies whose listener could not be closed during a failed start or replace. The
|
||||
@@ -34,9 +36,11 @@ public class RedshiftProxyManager {
|
||||
private final ConcurrentHashMap<String, RedshiftAuthProxy> unclosableProxies = new ConcurrentHashMap<>();
|
||||
|
||||
@Inject
|
||||
public RedshiftProxyManager(RdsSigV4Validator sigV4Validator, RdsProxyTlsCertificates tlsCertificates) {
|
||||
public RedshiftProxyManager(RdsSigV4Validator sigV4Validator, RdsProxyTlsCertificates tlsCertificates,
|
||||
S3Service s3Service) {
|
||||
this.sigV4Validator = sigV4Validator;
|
||||
this.tlsCertificates = tlsCertificates;
|
||||
this.s3Service = s3Service;
|
||||
}
|
||||
|
||||
public synchronized void startProxy(String relayKey, int proxyPort,
|
||||
@@ -50,7 +54,7 @@ public class RedshiftProxyManager {
|
||||
tlsCertificates.ensureHost(advertisedHost);
|
||||
RedshiftAuthProxy proxy = new RedshiftAuthProxy(
|
||||
relayKey, backendHost, backendPort, masterUsername, masterPassword, dbName,
|
||||
sigV4Validator, tlsCertificates, passwordValidator);
|
||||
sigV4Validator, tlsCertificates, passwordValidator, s3Service);
|
||||
try {
|
||||
proxy.start(proxyPort);
|
||||
} catch (IOException | RuntimeException e) {
|
||||
|
||||
+404
@@ -0,0 +1,404 @@
|
||||
package io.github.hectorvent.floci.services.redshift.proxy;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.services.s3.S3Service;
|
||||
import io.github.hectorvent.floci.services.s3.model.S3Object;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.net.Socket;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.zip.GZIPInputStream;
|
||||
|
||||
/**
|
||||
* Emulates {@code COPY <table> FROM 's3://bucket/keyOrPrefix'} by reading the S3 object (or every
|
||||
* object under the prefix, in key order) through {@link S3Service} and streaming it into the
|
||||
* backing PostgreSQL container over a fabricated {@code COPY <table> FROM STDIN} exchange.
|
||||
*
|
||||
* <p>The caller must own the backend socket exclusively for the whole call: this class writes a
|
||||
* query and reads its response frames directly. Every exit path leaves the client with exactly one
|
||||
* response for its original {@code 'Q'} (a {@code CommandComplete}/{@code ReadyForQuery} on success,
|
||||
* a single {@code ErrorResponse}/{@code ReadyForQuery} on failure) and never closes the connection.
|
||||
*/
|
||||
public final class S3CopySimulator {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(S3CopySimulator.class);
|
||||
|
||||
private static final int LIST_PAGE_SIZE = 1000;
|
||||
private static final int CHUNK = 8192;
|
||||
|
||||
private static final String SQLSTATE_INSUFFICIENT_PRIVILEGE = "42501";
|
||||
private static final String SQLSTATE_INTERNAL = "XX000";
|
||||
|
||||
private S3CopySimulator() {
|
||||
}
|
||||
|
||||
/**
|
||||
* @param txStatus the transaction-status byte from the client's last {@code ReadyForQuery}
|
||||
* ({@code 'I'} idle, {@code 'T'} in a block, {@code 'E'} failed block); a
|
||||
* synthesized error reports {@code 'I'} outside a block and {@code 'E'} inside.
|
||||
* @return {@code true} when the exchange was handled (success or a clean error sent to the
|
||||
* client). Part 4 always handles; the value exists so a later interceptor can decline.
|
||||
*/
|
||||
public static boolean runCopyFrom(Socket client, Socket backend,
|
||||
CopyStatementParser.S3CopyFrom spec, S3Service s3,
|
||||
char txStatus) throws IOException {
|
||||
return runCopyFrom(client, backend, spec, s3, txStatus, null);
|
||||
}
|
||||
|
||||
public static boolean runCopyFrom(Socket client, Socket backend,
|
||||
CopyStatementParser.S3CopyFrom spec, S3Service s3,
|
||||
char txStatus, java.util.function.IntConsumer onStatusChange) throws IOException {
|
||||
try {
|
||||
s3.authorizeAnonymousListBucket(spec.bucket());
|
||||
} catch (AwsException e) {
|
||||
LOG.debugv(e, "ListBucket denied for COPY from s3://{0}/{1}", spec.bucket(), spec.keyOrPrefix());
|
||||
sendAccessDenied(client, backend, spec, txStatus, onStatusChange);
|
||||
return true;
|
||||
}
|
||||
|
||||
List<String> keys;
|
||||
try {
|
||||
keys = resolveKeys(spec, s3);
|
||||
} catch (AwsException e) {
|
||||
LOG.warnv(e, "failed to list s3://{0}/{1} for COPY", spec.bucket(), spec.keyOrPrefix());
|
||||
sendError(client, backend, SQLSTATE_INTERNAL,
|
||||
"S3 COPY could not list s3://" + spec.bucket() + "/" + spec.keyOrPrefix(), txStatus, onStatusChange);
|
||||
return true;
|
||||
}
|
||||
|
||||
try {
|
||||
for (String key : keys) {
|
||||
s3.authorizeAnonymousGetObject(spec.bucket(), key);
|
||||
}
|
||||
} catch (AwsException e) {
|
||||
LOG.debugv(e, "GetObject denied for COPY from s3://{0}/{1}", spec.bucket(), spec.keyOrPrefix());
|
||||
sendAccessDenied(client, backend, spec, txStatus, onStatusChange);
|
||||
return true;
|
||||
}
|
||||
|
||||
if (keys.isEmpty()) {
|
||||
sendError(client, backend, SQLSTATE_INTERNAL,
|
||||
"S3 object s3://" + spec.bucket() + "/" + spec.keyOrPrefix() + " not found", txStatus, onStatusChange);
|
||||
return true;
|
||||
}
|
||||
|
||||
OutputStream backendOut = backend.getOutputStream();
|
||||
backendOut.write(PostgresWireDecoder.encodeQuery(fabricateCopy(spec)));
|
||||
backendOut.flush();
|
||||
|
||||
PostgresWireDecoder backendDecoder = new PostgresWireDecoder(backend.getInputStream());
|
||||
PostgresWireDecoder.FrontendMessage first;
|
||||
try {
|
||||
first = nextNonAsync(backendDecoder, client);
|
||||
} catch (IOException e) {
|
||||
LOG.warnv(e, "backend read failed while awaiting CopyInResponse");
|
||||
closeQuietly(backend);
|
||||
sendError(client, null, SQLSTATE_INTERNAL, "S3 COPY failed: backend closed or timed out", txStatus, onStatusChange);
|
||||
closeQuietly(client);
|
||||
return true;
|
||||
}
|
||||
if (first == null) {
|
||||
LOG.warn("backend closed before answering the fabricated COPY");
|
||||
closeQuietly(backend);
|
||||
sendError(client, null, SQLSTATE_INTERNAL, "S3 COPY failed: backend closed before COPY started", txStatus, onStatusChange);
|
||||
closeQuietly(client);
|
||||
return true;
|
||||
}
|
||||
if (first.type() != 'G') {
|
||||
// Backend rejected the COPY itself (e.g. no such table). Its ErrorResponse and the
|
||||
// ReadyForQuery that follows are the client's one response.
|
||||
forward(client, first);
|
||||
drainToReadyForQuery(backendDecoder, client, onStatusChange);
|
||||
return true;
|
||||
}
|
||||
|
||||
// The CopyIn stream is open. Any failure from here is resolved with exactly one response:
|
||||
// a CopyFail to the backend, whose ErrorResponse/ReadyForQuery is relayed to the client;
|
||||
// or, if the backend is unreachable, one synthesized ErrorResponse/ReadyForQuery.
|
||||
try {
|
||||
streamObjects(spec, s3, keys, backendOut);
|
||||
writeCopyDone(backendOut);
|
||||
drainToReadyForQuery(backendDecoder, client, onStatusChange);
|
||||
} catch (RuntimeException | IOException e) {
|
||||
LOG.warnv(e, "S3 COPY streaming failed; aborting the open CopyIn");
|
||||
abortOpenCopyIn(client, backend, backendOut, backendDecoder, e, txStatus, onStatusChange);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private static void abortOpenCopyIn(Socket client, Socket backend, OutputStream backendOut,
|
||||
PostgresWireDecoder backendDecoder, Exception cause,
|
||||
char txStatus, java.util.function.IntConsumer onStatusChange) throws IOException {
|
||||
try {
|
||||
writeCopyFail(backendOut, cause.getMessage());
|
||||
drainToReadyForQuery(backendDecoder, client, onStatusChange);
|
||||
} catch (IOException backendGone) {
|
||||
LOG.debugv(backendGone, "backend unreachable while aborting CopyIn; synthesizing client error");
|
||||
closeQuietly(backend);
|
||||
String detail = cause.getMessage() != null ? cause.getMessage() : cause.toString();
|
||||
sendError(client, null, SQLSTATE_INTERNAL, "S3 COPY failed: " + detail, txStatus, onStatusChange);
|
||||
closeQuietly(client);
|
||||
}
|
||||
}
|
||||
|
||||
private static List<String> resolveKeys(CopyStatementParser.S3CopyFrom spec, S3Service s3) {
|
||||
List<String> keys = new ArrayList<>();
|
||||
if (s3.objectExists(spec.bucket(), spec.keyOrPrefix())) {
|
||||
keys.add(spec.keyOrPrefix());
|
||||
return keys;
|
||||
}
|
||||
String continuationToken = null;
|
||||
do {
|
||||
S3Service.ListObjectsResult result = s3.listObjectsWithPrefixes(
|
||||
spec.bucket(), spec.keyOrPrefix(), 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);
|
||||
|
||||
keys.sort(String::compareTo);
|
||||
return keys;
|
||||
}
|
||||
|
||||
private static String fabricateCopy(CopyStatementParser.S3CopyFrom spec) {
|
||||
StringBuilder sql = new StringBuilder("COPY ").append(spec.targetTable());
|
||||
if (spec.columns() != null && !spec.columns().isEmpty()) {
|
||||
sql.append(" (").append(String.join(", ", spec.columns())).append(")");
|
||||
}
|
||||
sql.append(" FROM STDIN WITH (FORMAT ").append(spec.csv() ? "csv" : "text");
|
||||
String delimiter = spec.delimiter() != null ? spec.delimiter() : (spec.csv() ? "," : "|");
|
||||
sql.append(", DELIMITER '").append(quoteLiteral(delimiter)).append("'");
|
||||
if (spec.nullAs() != null) {
|
||||
sql.append(", NULL '").append(quoteLiteral(spec.nullAs())).append("'");
|
||||
}
|
||||
sql.append(")");
|
||||
return sql.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Quote a value for a single-quoted SQL string literal. PostgreSQL defaults to
|
||||
* {@code standard_conforming_strings = on}, where a backslash is an ordinary character, so only
|
||||
* the quote itself is doubled: {@code NULL AS '\N'} must reach the backend as {@code '\N'}.
|
||||
*/
|
||||
private static String quoteLiteral(String value) {
|
||||
return value.replace("'", "''");
|
||||
}
|
||||
|
||||
private static void streamObjects(CopyStatementParser.S3CopyFrom spec, S3Service s3,
|
||||
List<String> keys, OutputStream backendOut) throws IOException {
|
||||
byte[] buffer = new byte[CHUNK];
|
||||
for (int i = 0; i < keys.size(); i++) {
|
||||
S3Object object = s3.getObject(spec.bucket(), keys.get(i));
|
||||
byte[] data = object != null && object.getData() != null ? object.getData() : new byte[0];
|
||||
InputStream in = new ByteArrayInputStream(data);
|
||||
if (spec.gzip()) {
|
||||
in = new GZIPInputStream(in);
|
||||
}
|
||||
if (i == 0 && spec.headerLines() > 0) {
|
||||
skipLines(in, spec.headerLines());
|
||||
}
|
||||
int read;
|
||||
boolean endsWithNewline = false;
|
||||
boolean hasData = false;
|
||||
while ((read = in.read(buffer)) != -1) {
|
||||
if (read > 0) {
|
||||
hasData = true;
|
||||
endsWithNewline = (buffer[read - 1] == '\n');
|
||||
writeCopyData(backendOut, buffer, read);
|
||||
}
|
||||
}
|
||||
in.close();
|
||||
if (hasData && !endsWithNewline) {
|
||||
writeCopyData(backendOut, new byte[]{'\n'}, 1);
|
||||
}
|
||||
}
|
||||
backendOut.flush();
|
||||
}
|
||||
|
||||
private static void skipLines(InputStream in, int lines) throws IOException {
|
||||
int seen = 0;
|
||||
int b;
|
||||
while (seen < lines && (b = in.read()) != -1) {
|
||||
if (b == '\n') {
|
||||
seen++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void writeCopyData(OutputStream out, byte[] buf, int len) throws IOException {
|
||||
out.write('d');
|
||||
out.write(intBytes(4 + len));
|
||||
out.write(buf, 0, len);
|
||||
}
|
||||
|
||||
private static void writeCopyDone(OutputStream out) throws IOException {
|
||||
out.write('c');
|
||||
out.write(intBytes(4));
|
||||
out.flush();
|
||||
}
|
||||
|
||||
private static void writeCopyFail(OutputStream out, String reason) throws IOException {
|
||||
byte[] message = (reason == null ? "S3 COPY aborted" : reason).getBytes(StandardCharsets.UTF_8);
|
||||
out.write('f');
|
||||
out.write(intBytes(4 + message.length + 1));
|
||||
out.write(message);
|
||||
out.write(0);
|
||||
out.flush();
|
||||
}
|
||||
|
||||
/** Read the next backend message, relaying asynchronous messages to the client as it goes. */
|
||||
private static PostgresWireDecoder.FrontendMessage nextNonAsync(PostgresWireDecoder decoder, Socket client)
|
||||
throws IOException {
|
||||
OutputStream clientOut = client.getOutputStream();
|
||||
while (true) {
|
||||
PostgresWireDecoder.FrontendMessage message = decoder.nextMessage();
|
||||
if (message == null) {
|
||||
return null;
|
||||
}
|
||||
char type = message.type();
|
||||
if (type == 'N' || type == 'A' || type == 'S') {
|
||||
clientOut.write(message.toPacketBytes());
|
||||
clientOut.flush();
|
||||
continue;
|
||||
}
|
||||
return message;
|
||||
}
|
||||
}
|
||||
|
||||
private static void drainToReadyForQuery(PostgresWireDecoder decoder, Socket client,
|
||||
java.util.function.IntConsumer onStatusChange) throws IOException {
|
||||
OutputStream clientOut = client.getOutputStream();
|
||||
while (true) {
|
||||
PostgresWireDecoder.FrontendMessage message = decoder.nextMessage();
|
||||
if (message == null) {
|
||||
return;
|
||||
}
|
||||
clientOut.write(message.toPacketBytes());
|
||||
clientOut.flush();
|
||||
if (message.type() == 'Z') {
|
||||
if (onStatusChange != null && message.body().length > 0) {
|
||||
onStatusChange.accept(message.body()[0]);
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void forward(Socket client, PostgresWireDecoder.FrontendMessage message) throws IOException {
|
||||
client.getOutputStream().write(message.toPacketBytes());
|
||||
client.getOutputStream().flush();
|
||||
}
|
||||
|
||||
private static void sendAccessDenied(Socket client, Socket backend, CopyStatementParser.S3CopyFrom spec,
|
||||
char txStatus, java.util.function.IntConsumer onStatusChange) throws IOException {
|
||||
sendError(client, backend, SQLSTATE_INSUFFICIENT_PRIVILEGE,
|
||||
"S3 access denied for s3://" + spec.bucket() + "/" + spec.keyOrPrefix(), txStatus, onStatusChange);
|
||||
}
|
||||
|
||||
private static void sendError(Socket client, Socket backend, String sqlState, String message,
|
||||
char txStatus, java.util.function.IntConsumer onStatusChange) throws IOException {
|
||||
if (txStatus == 'T' && backend != null && !backend.isClosed()) {
|
||||
if (!failBackendTransaction(backend, onStatusChange)) {
|
||||
closeQuietly(backend);
|
||||
// Backend transaction state could not be confirmed; do not report an unconfirmed
|
||||
// failed transaction ('E') or leave a desynchronized backend in the pump.
|
||||
try {
|
||||
OutputStream out = client.getOutputStream();
|
||||
byte[] body = errorBody(sqlState, message);
|
||||
out.write('E');
|
||||
out.write(intBytes(4 + body.length));
|
||||
out.write(body);
|
||||
out.flush();
|
||||
} catch (IOException e) {
|
||||
LOG.debugv(e, "failed to send ErrorResponse to client before closing socket");
|
||||
} finally {
|
||||
closeQuietly(client);
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
OutputStream out = client.getOutputStream();
|
||||
byte[] body = errorBody(sqlState, message);
|
||||
out.write('E');
|
||||
out.write(intBytes(4 + body.length));
|
||||
out.write(body);
|
||||
byte status = (txStatus == 'I' || txStatus == 0) ? (byte) 'I' : (byte) 'E';
|
||||
out.write(new byte[]{'Z', 0, 0, 0, 5, status});
|
||||
out.flush();
|
||||
if (onStatusChange != null) {
|
||||
onStatusChange.accept(status);
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean failBackendTransaction(Socket backend, java.util.function.IntConsumer onStatusChange) {
|
||||
try {
|
||||
OutputStream out = backend.getOutputStream();
|
||||
out.write(PostgresWireDecoder.encodeQuery("(FLOCI_ABORT_TX)"));
|
||||
out.flush();
|
||||
PostgresWireDecoder decoder = new PostgresWireDecoder(backend.getInputStream());
|
||||
while (true) {
|
||||
PostgresWireDecoder.FrontendMessage msg = decoder.nextMessage();
|
||||
if (msg == null) {
|
||||
LOG.warn("backend closed before transaction abort could be synchronized");
|
||||
return false;
|
||||
}
|
||||
if (msg.type() == 'Z') {
|
||||
char status = (msg.body().length > 0) ? (char) msg.body()[0] : 0;
|
||||
if (onStatusChange != null && status != 0) {
|
||||
onStatusChange.accept(status);
|
||||
}
|
||||
if (status != 'E') {
|
||||
LOG.warnv("backend returned unexpected transaction status {0} instead of 'E' after abort query", status);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
} catch (IOException e) {
|
||||
LOG.warnv(e, "failed to synchronize backend transaction abort state");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static void closeQuietly(Socket s) {
|
||||
try {
|
||||
if (s != null && !s.isClosed()) {
|
||||
s.close();
|
||||
}
|
||||
} catch (IOException e) {
|
||||
LOG.debugv(e, "failed to close socket: {0}", s);
|
||||
}
|
||||
}
|
||||
|
||||
private static byte[] errorBody(String sqlState, String message) {
|
||||
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
|
||||
writeField(bytes, 'S', "ERROR");
|
||||
writeField(bytes, 'C', sqlState);
|
||||
writeField(bytes, 'M', message);
|
||||
bytes.write(0);
|
||||
return bytes.toByteArray();
|
||||
}
|
||||
|
||||
private static void writeField(ByteArrayOutputStream bytes, char tag, String value) {
|
||||
bytes.write(tag);
|
||||
byte[] raw = value.getBytes(StandardCharsets.UTF_8);
|
||||
bytes.write(raw, 0, raw.length);
|
||||
bytes.write(0);
|
||||
}
|
||||
|
||||
private static byte[] intBytes(int value) {
|
||||
return new byte[]{
|
||||
(byte) (value >>> 24), (byte) (value >>> 16), (byte) (value >>> 8), (byte) value
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -612,6 +612,11 @@ public class S3Service implements Resettable, ResourceProvider {
|
||||
authorizeGetObject(bucketName, key, null, RequestAuthorization.unsigned());
|
||||
}
|
||||
|
||||
/** Authorize an unsigned {@code s3:ListBucket}; see {@link #authorizeAnonymousGetObject}. */
|
||||
public void authorizeAnonymousListBucket(String bucketName) {
|
||||
authorizeListBucket(bucketName, RequestAuthorization.unsigned());
|
||||
}
|
||||
|
||||
public void authorizeCloudFrontOacGetObject(
|
||||
String bucketName, String key, String distributionArn) {
|
||||
authorizeCloudFrontGetObject(
|
||||
|
||||
Reference in new issue
Block a user