mirror of
https://github.com/floci-io/floci.git
synced 2026-11-27 07:39:24 -05:00
feat(firehose): deliver staged Redshift batches with single-attempt COPY (#6006)
* feat(firehose): deliver staged Redshift batches with single-attempt COPY A flush stages the batch in the intermediate S3 location, then runs COPY against the cluster proxy over JDBC simple-query mode without an IAM role. The load runs on its own thread so that slow COPY queries do not hold the shared flush executor or PutRecord callers, and failures are logged with the staged batch kept in S3. * fix(firehose): address review comments on Redshift single-attempt COPY delivery - Drain buffers before shutting down the Redshift delivery executor on Firehose shutdown and log dropped queued tasks. - Catch RejectedExecutionException in deliverRedshiftBatch to prevent staged records from returning to the buffer. - Extract DatabaseSecretCredentials helper in core.common to deduplicate Secrets Manager credentials parsing across RDS Data, Redshift Data, and Firehose. - Extract RedshiftConnections test helper for waitForConnection and use DockerAvailability.isAvailable() in FirehoseRedshiftDeliveryIntegrationTest. - Update docs and Javadocs to remove outdated references to retries and shared flush threads. * fix(firehose): wait for queued Redshift COPY delivery before shutdown and log secret parse errors * refactor(firehose): deduplicate dropAndLogQueuedTasks helper on shutdown
This commit is contained in:
1 parent
ff813c6f34
commit
fd37e109f8
16 files changed
+1373
-59
No files matched your search
@@ -0,0 +1,70 @@
|
||||
package io.github.hectorvent.floci.core.common;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* Username and password credentials stored in an AWS Secrets Manager secret for a database (RDS,
|
||||
* Redshift, Redshift Data API, or Firehose Redshift destination).
|
||||
*/
|
||||
public record DatabaseSecretCredentials(String username, String password) {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(DatabaseSecretCredentials.class);
|
||||
private static final ObjectMapper DEFAULT_MAPPER = new ObjectMapper();
|
||||
|
||||
public DatabaseSecretCredentials {
|
||||
Objects.requireNonNull(username, "username must not be null");
|
||||
Objects.requireNonNull(password, "password must not be null");
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses credentials from a Secrets Manager secret string JSON payload using the default mapper.
|
||||
*/
|
||||
public static Optional<DatabaseSecretCredentials> parse(String secretString) {
|
||||
return parse(DEFAULT_MAPPER, secretString);
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses credentials from a Secrets Manager secret string using the given ObjectMapper.
|
||||
*/
|
||||
public static Optional<DatabaseSecretCredentials> parse(ObjectMapper mapper, String secretString) {
|
||||
if (secretString == null || secretString.isBlank() || mapper == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
try {
|
||||
return parse(mapper.readTree(secretString));
|
||||
} catch (Exception ignored) {
|
||||
// An unparseable secret string is treated as missing credentials; callers handle Optional.empty()
|
||||
LOG.debugv("Failed to parse database credentials from secret string: {0}", ignored.getMessage());
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses credentials from a Secrets Manager secret JSON node.
|
||||
* Looks for non-null "username" (or fallback "user") and "password" text fields.
|
||||
*/
|
||||
public static Optional<DatabaseSecretCredentials> parse(JsonNode node) {
|
||||
if (node == null || !node.isObject()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
String username = textOrNull(node, "username");
|
||||
if (username == null) {
|
||||
username = textOrNull(node, "user");
|
||||
}
|
||||
String password = textOrNull(node, "password");
|
||||
if (username != null && password != null) {
|
||||
return Optional.of(new DatabaseSecretCredentials(username, password));
|
||||
}
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
private static String textOrNull(JsonNode node, String field) {
|
||||
JsonNode child = node.get(field);
|
||||
return (child != null && !child.isNull()) ? child.asText() : null;
|
||||
}
|
||||
}
|
||||
+150
@@ -0,0 +1,150 @@
|
||||
package io.github.hectorvent.floci.services.firehose;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.core.common.DatabaseSecretCredentials;
|
||||
import io.github.hectorvent.floci.services.firehose.model.RedshiftDestination;
|
||||
import io.github.hectorvent.floci.services.redshift.RedshiftService;
|
||||
import io.github.hectorvent.floci.services.redshift.model.Cluster;
|
||||
import io.github.hectorvent.floci.services.secretsmanager.SecretsManagerService;
|
||||
import io.github.hectorvent.floci.services.secretsmanager.model.SecretVersion;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.DriverManager;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Statement;
|
||||
import java.util.Properties;
|
||||
|
||||
/**
|
||||
* Loads a delivered S3 object into a Floci Redshift cluster. The {@code COPY} runs over a JDBC
|
||||
* connection to the cluster's wire proxy in simple query mode, so the proxy's S3 COPY emulation
|
||||
* does the work exactly as it does for any other client.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class FirehoseRedshiftDelivery {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(FirehoseRedshiftDelivery.class);
|
||||
private static final int CONNECT_TIMEOUT_SECONDS = 10;
|
||||
private static final int SOCKET_TIMEOUT_SECONDS = 150;
|
||||
|
||||
/** Seam for tests; production opens a real JDBC connection. */
|
||||
interface SqlRunner {
|
||||
void execute(String jdbcUrl, String user, String password, String sql) throws SQLException;
|
||||
}
|
||||
|
||||
private final RedshiftService redshiftService;
|
||||
private final SecretsManagerService secretsManagerService;
|
||||
private final ObjectMapper mapper;
|
||||
private final SqlRunner runner;
|
||||
|
||||
@Inject
|
||||
public FirehoseRedshiftDelivery(RedshiftService redshiftService, SecretsManagerService secretsManagerService,
|
||||
ObjectMapper mapper) {
|
||||
this(redshiftService, secretsManagerService, mapper, FirehoseRedshiftDelivery::runJdbc);
|
||||
}
|
||||
|
||||
FirehoseRedshiftDelivery(RedshiftService redshiftService, SecretsManagerService secretsManagerService,
|
||||
ObjectMapper mapper, SqlRunner runner) {
|
||||
this.redshiftService = redshiftService;
|
||||
this.secretsManagerService = secretsManagerService;
|
||||
this.mapper = mapper;
|
||||
this.runner = runner;
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs the destination's COPY for the object at {@code s3://bucket/key}.
|
||||
*
|
||||
* Throws {@code AwsException} when the cluster or the secret cannot be resolved.
|
||||
*
|
||||
* @throws IllegalStateException when the statement itself fails; the message carries the table and SQL state
|
||||
*/
|
||||
public void copy(String accountId, String region, RedshiftDestination destination, String bucket, String key) {
|
||||
RedshiftJdbcUrl target = RedshiftJdbcUrl.parse(destination.getClusterJdbcUrl());
|
||||
Cluster cluster = redshiftService.describeClustersForAccount(accountId, target.clusterIdentifier()).get(0);
|
||||
String[] credentials = credentials(destination, cluster, region);
|
||||
RedshiftDestination.CopyCommand command = destination.getCopyCommand();
|
||||
String sql = RedshiftCopySql.build(command.getDataTableName(), command.getDataTableColumns(), bucket, key,
|
||||
command.getCopyOptions());
|
||||
// The database name in the URL is ignored: the emulated container database is always "dev".
|
||||
String jdbcUrl = "jdbc:postgresql://127.0.0.1:" + cluster.getEndpoint().getPort()
|
||||
+ "/dev?preferQueryMode=simple";
|
||||
try {
|
||||
runner.execute(jdbcUrl, credentials[0], credentials[1], sql);
|
||||
} catch (SQLException e) {
|
||||
throw new IllegalStateException("COPY into " + command.getDataTableName() + " on cluster "
|
||||
+ target.clusterIdentifier() + " failed (SQLSTATE " + e.getSQLState() + "): " + e.getMessage(), e);
|
||||
}
|
||||
LOG.debugv("Firehose copied s3://{0}/{1} into {2} on cluster {3}", bucket, key,
|
||||
command.getDataTableName(), target.clusterIdentifier());
|
||||
}
|
||||
|
||||
private String[] credentials(RedshiftDestination destination, Cluster cluster, String region) {
|
||||
RedshiftDestination.SecretsManagerConfiguration secrets = destination.getSecretsManagerConfiguration();
|
||||
if (secrets != null && Boolean.TRUE.equals(secrets.getEnabled())) {
|
||||
SecretVersion secret = secretsManagerService.getSecretValue(secrets.getSecretArn(), null, null, region);
|
||||
DatabaseSecretCredentials credentials = DatabaseSecretCredentials.parse(mapper, secret.getSecretString())
|
||||
.orElseThrow(() -> new IllegalStateException("Secret " + secrets.getSecretArn()
|
||||
+ " does not contain username and password fields."));
|
||||
return new String[] {credentials.username(), credentials.password()};
|
||||
}
|
||||
if (destination.getPassword() == null) {
|
||||
throw new IllegalStateException("The Redshift destination for cluster " + cluster.getClusterIdentifier()
|
||||
+ " has no Password and no enabled SecretsManagerConfiguration, so Firehose cannot sign in.");
|
||||
}
|
||||
String user = destination.getUsername() != null ? destination.getUsername() : cluster.getMasterUsername();
|
||||
return new String[] {user, destination.getPassword()};
|
||||
}
|
||||
|
||||
/**
|
||||
* Timeouts matter here: a connection that never answers would stall the Redshift delivery thread
|
||||
* and delay emulator shutdown.
|
||||
*/
|
||||
static Properties connectionProperties(String user, String password) {
|
||||
Properties properties = new Properties();
|
||||
properties.setProperty("user", user);
|
||||
properties.setProperty("password", password);
|
||||
properties.setProperty("connectTimeout", String.valueOf(CONNECT_TIMEOUT_SECONDS));
|
||||
properties.setProperty("socketTimeout", String.valueOf(SOCKET_TIMEOUT_SECONDS));
|
||||
return properties;
|
||||
}
|
||||
|
||||
private static void runJdbc(String jdbcUrl, String user, String password, String sql) throws SQLException {
|
||||
Connection connection = DriverManager.getConnection(jdbcUrl, connectionProperties(user, password));
|
||||
executeAndClose(connection, sql);
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs the statement and closes the connection. Once the statement has returned the load is committed
|
||||
* (autocommit), so a failure while closing must not surface as a failed delivery.
|
||||
*/
|
||||
static void executeAndClose(Connection connection, String sql) throws SQLException {
|
||||
try {
|
||||
// Closing the connection closes its statement, so the statement is not closed on its own: a failure there
|
||||
// would be reported as a failed COPY too.
|
||||
Statement statement = connection.createStatement();
|
||||
statement.execute(sql);
|
||||
} catch (SQLException e) {
|
||||
closeAfterFailure(connection, e);
|
||||
throw e;
|
||||
}
|
||||
closeAfterSuccess(connection);
|
||||
}
|
||||
|
||||
private static void closeAfterFailure(Connection connection, SQLException failure) {
|
||||
try {
|
||||
connection.close();
|
||||
} catch (SQLException e) {
|
||||
failure.addSuppressed(e);
|
||||
}
|
||||
}
|
||||
|
||||
private static void closeAfterSuccess(Connection connection) {
|
||||
try {
|
||||
connection.close();
|
||||
} catch (SQLException e) {
|
||||
LOG.warnv(e, "Closing the Redshift connection after a committed COPY failed: {0}", e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -30,16 +30,21 @@ import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
import java.util.*;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.RejectedExecutionException;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
@@ -112,6 +117,8 @@ public class FirehoseService implements ResourceProvider {
|
||||
private final Map<String, Map<String, String>> pendingSourceIterators = new ConcurrentHashMap<>();
|
||||
private final FirehoseParquetConverter parquetConverter;
|
||||
private final FirehoseLambdaTransformer lambdaTransformer;
|
||||
private final FirehoseRedshiftDelivery redshiftDelivery;
|
||||
private final Executor redshiftDeliveryExecutor;
|
||||
// Serialises the read, version check, merge and write of a Redshift UpdateDestination per stream.
|
||||
private final Map<String, Object> redshiftUpdateLocks = new ConcurrentHashMap<>();
|
||||
private final Clock clock;
|
||||
@@ -196,11 +203,39 @@ public class FirehoseService implements ResourceProvider {
|
||||
sourceIteratorStore.deleteForAccount(accountFromScopedKey(key), logicalKeyFromScopedKey(key));
|
||||
}
|
||||
|
||||
@Inject
|
||||
/** Kept so callers that never deliver to Redshift need no delivery collaborator; null means unavailable. */
|
||||
public FirehoseService(StorageFactory storageFactory, S3Service s3Service, KinesisService kinesisService,
|
||||
RegionResolver regionResolver, Clock clock, EmulatorConfig config,
|
||||
FirehoseParquetConverter parquetConverter,
|
||||
FirehoseLambdaTransformer lambdaTransformer) {
|
||||
this(storageFactory, s3Service, kinesisService, regionResolver, clock, config, parquetConverter,
|
||||
lambdaTransformer, null);
|
||||
}
|
||||
|
||||
@Inject
|
||||
public FirehoseService(StorageFactory storageFactory, S3Service s3Service, KinesisService kinesisService,
|
||||
RegionResolver regionResolver, Clock clock, EmulatorConfig config,
|
||||
FirehoseParquetConverter parquetConverter,
|
||||
FirehoseLambdaTransformer lambdaTransformer,
|
||||
FirehoseRedshiftDelivery redshiftDelivery) {
|
||||
this(storageFactory, s3Service, kinesisService, regionResolver, clock, config, parquetConverter,
|
||||
lambdaTransformer, redshiftDelivery, null);
|
||||
}
|
||||
|
||||
public FirehoseService(StorageFactory storageFactory, S3Service s3Service, KinesisService kinesisService,
|
||||
RegionResolver regionResolver, Clock clock, EmulatorConfig config,
|
||||
FirehoseParquetConverter parquetConverter,
|
||||
FirehoseLambdaTransformer lambdaTransformer,
|
||||
FirehoseRedshiftDelivery redshiftDelivery,
|
||||
Executor redshiftDeliveryExecutor) {
|
||||
this.redshiftDelivery = redshiftDelivery;
|
||||
this.redshiftDeliveryExecutor = redshiftDeliveryExecutor != null
|
||||
? redshiftDeliveryExecutor
|
||||
: Executors.newSingleThreadExecutor(r -> {
|
||||
Thread t = new Thread(r, "firehose-redshift-delivery");
|
||||
t.setDaemon(true);
|
||||
return t;
|
||||
});
|
||||
this.streamStore = storageFactory.create("firehose", "streams.json",
|
||||
new TypeReference<Map<String, DeliveryStreamDescription>>() {});
|
||||
this.sourceIteratorStore = storageFactory.create("firehose", "source-iterators.json",
|
||||
@@ -235,10 +270,29 @@ public class FirehoseService implements ResourceProvider {
|
||||
// persist them to disk via storageFactory.flushAll(). Each flush also commits the
|
||||
// source checkpoint it just made durable, so a graceful shutdown neither loses
|
||||
// records nor re-delivers them; storageFactory.flushAll() then writes that
|
||||
// checkpoint out with everything else.
|
||||
// checkpoint out with everything else. Redshift COPY tasks are allowed a brief
|
||||
// window to complete before the delivery executor is forced down.
|
||||
void onPreShutdown(@Observes ShutdownDelayInitiatedEvent ignored) {
|
||||
flushExecutor.shutdownNow();
|
||||
buffers.keySet().forEach(this::flushByKey);
|
||||
if (redshiftDeliveryExecutor instanceof ExecutorService es) {
|
||||
es.shutdown();
|
||||
try {
|
||||
if (!es.awaitTermination(5, TimeUnit.SECONDS)) {
|
||||
dropAndLogQueuedTasks(es);
|
||||
}
|
||||
} catch (InterruptedException e) {
|
||||
dropAndLogQueuedTasks(es);
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void dropAndLogQueuedTasks(ExecutorService es) {
|
||||
List<Runnable> dropped = es.shutdownNow();
|
||||
if (!dropped.isEmpty()) {
|
||||
LOG.warnv("Dropping {0} queued Redshift COPY task(s) on Firehose shutdown", dropped.size());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1070,11 +1124,16 @@ public class FirehoseService implements ResourceProvider {
|
||||
}
|
||||
}
|
||||
|
||||
byte[] body = compression.compress(payload.toByteArray());
|
||||
byte[] rawPayload = payload.toByteArray();
|
||||
byte[] body = compression.compress(rawPayload);
|
||||
s3Service.putObject(bucket, key, body, "application/octet-stream", Map.of(),
|
||||
new PutObjectOptions().withContentEncoding(compression.contentEncoding()));
|
||||
LOG.infov("Flushed {0} records from stream {1} to s3://{2}/{3} ({4})",
|
||||
records.size(), streamName, bucket, key, compression.wireValue());
|
||||
if (isRedshiftStream(stream)) {
|
||||
deliverRedshiftBatch(streamName, stream, bucket, key, rawPayload, checkpoint);
|
||||
return;
|
||||
}
|
||||
// Only now: the records these iterators were read past are durable.
|
||||
commitSourceIterators(streamName, checkpoint);
|
||||
} catch (Exception e) {
|
||||
@@ -1084,6 +1143,79 @@ public class FirehoseService implements ResourceProvider {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Everything after a Redshift batch is staged in S3. The batch is durable in S3, so no failure here may hand its
|
||||
* records back to the buffer: that would stage and load them a second time. Backups and source checkpoints are
|
||||
* completed first, then COPY is submitted to run on its own thread so that a slow or hanging query never holds
|
||||
* the buffer flusher thread or PutRecord.
|
||||
*/
|
||||
private void deliverRedshiftBatch(String streamName, DeliveryStreamDescription stream,
|
||||
String bucket, String key, byte[] rawPayload,
|
||||
Map<String, String> checkpoint) {
|
||||
RedshiftDestination redshift = stream.getDestinations().get(0).getRedshiftDestinationDescription();
|
||||
try {
|
||||
writeRedshiftBackup(stream, redshift, rawPayload);
|
||||
} catch (IOException | RuntimeException e) {
|
||||
LOG.errorv(e, "Backup write for stream {0} failed; the batch is staged in S3 and loads normally but "
|
||||
+ "has no backup copy: {1}", streamName, describe(e));
|
||||
}
|
||||
try {
|
||||
commitSourceIterators(streamName, checkpoint);
|
||||
} catch (RuntimeException e) {
|
||||
LOG.errorv(e, "Could not persist the source checkpoint of stream {0} after its batch was staged; the "
|
||||
+ "source records may be read again: {1}", streamName, describe(e));
|
||||
}
|
||||
if (redshiftDelivery == null) {
|
||||
LOG.warnv("Stream {0} has a Redshift destination but Redshift delivery is unavailable; "
|
||||
+ "the batch stays in s3://{1}/{2}", streamName, bucket, key);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
redshiftDeliveryExecutor.execute(() -> {
|
||||
RequestScopes.runAs(stream.getAccountId(), () -> {
|
||||
try {
|
||||
String region = AwsArnUtils.regionOrDefault(stream.getDeliveryStreamARN(),
|
||||
regionResolver.getDefaultRegion());
|
||||
redshiftDelivery.copy(stream.getAccountId(), region, redshift, bucket, key);
|
||||
} catch (Exception e) {
|
||||
LOG.errorv("Redshift delivery of s3://{0}/{1} into table {2} failed for stream {3}; "
|
||||
+ "the batch stays in s3://{0}/{1}: {4}", bucket, key,
|
||||
redshift.getCopyCommand().getDataTableName(), streamName, describe(e));
|
||||
}
|
||||
});
|
||||
});
|
||||
} catch (RejectedExecutionException e) {
|
||||
LOG.errorv("Redshift delivery executor rejected task for s3://{0}/{1} into table {2} on stream {3}; "
|
||||
+ "the batch stays in s3://{0}/{1}: {4}", bucket, key,
|
||||
redshift.getCopyCommand().getDataTableName(), streamName, describe(e));
|
||||
}
|
||||
}
|
||||
|
||||
private static String describe(Exception e) {
|
||||
return e.getMessage() != null ? e.getMessage() : e.toString();
|
||||
}
|
||||
|
||||
/** Writes the raw batch to the backup location under that location's own prefix, compression and bucket. */
|
||||
private void writeRedshiftBackup(DeliveryStreamDescription stream, RedshiftDestination redshift,
|
||||
byte[] rawPayload) throws IOException {
|
||||
S3Destination backup = redshift.getS3Backup();
|
||||
if (!"Enabled".equals(redshift.getS3BackupMode()) || backup == null || backup.bucketName() == null) {
|
||||
return;
|
||||
}
|
||||
FirehoseCompression compression = FirehoseCompression.forDelivery(backup.getCompressionFormat());
|
||||
String backupKey = S3ObjectKeyResolver.resolveKey(backup, stream.getDeliveryStreamName(),
|
||||
stream.getVersionId(), clock.instant(), compression);
|
||||
ensureBucket(backup.bucketName(), stream);
|
||||
s3Service.putObject(backup.bucketName(), backupKey, compression.compress(rawPayload),
|
||||
"application/octet-stream", Map.of(),
|
||||
new PutObjectOptions().withContentEncoding(compression.contentEncoding()));
|
||||
}
|
||||
|
||||
private static boolean isRedshiftStream(DeliveryStreamDescription stream) {
|
||||
return stream.getDestinations() != null && !stream.getDestinations().isEmpty()
|
||||
&& stream.getDestinations().get(0).getRedshiftDestinationDescription() != null;
|
||||
}
|
||||
|
||||
private void restoreFailedFlush(String streamName, List<byte[]> toFlush, Instant since,
|
||||
Map<String, String> checkpoint) {
|
||||
List<byte[]> buffer = buffers.get(streamName);
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
package io.github.hectorvent.floci.services.firehose;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
@@ -10,15 +12,52 @@ import java.util.regex.Pattern;
|
||||
* outside a quoted literal, which is what keeps the text from carrying a second statement. The separator scan follows PostgreSQL's own
|
||||
* quoting rules rather than a simplified one, because the statement is later run in simple query mode, where
|
||||
* PostgreSQL executes every {@code ;}-separated statement it receives.
|
||||
*
|
||||
* <p>{@link #build} adds no {@code IAM_ROLE} or credentials. AWS hands the cluster temporary credentials of the
|
||||
* stream's role; the wire proxy reads a staged object straight from Floci's S3 when the statement names no role,
|
||||
* whereas an {@code IAM_ROLE} would have to exist in IAM and be associated with the cluster.
|
||||
*/
|
||||
final class RedshiftCopySql {
|
||||
|
||||
private static final String NAME = "(?:[A-Za-z_][A-Za-z0-9_$]*|\"[^\"]+\")";
|
||||
private static final Pattern QUALIFIED_NAME = Pattern.compile(NAME + "(?:\\." + NAME + ")?");
|
||||
private static final Pattern SIMPLE_NAME = Pattern.compile(NAME);
|
||||
private static final Pattern BUCKET = Pattern.compile("[^/'\"\\s]+");
|
||||
private static final Pattern OBJECT_KEY = Pattern.compile("[^'\"\\s]*");
|
||||
|
||||
private RedshiftCopySql() {}
|
||||
|
||||
static String build(String table, String columns, String bucket, String key, String copyOptions) {
|
||||
if (!isValidTableName(table)) {
|
||||
throw new IllegalArgumentException("DataTableName is not a table identifier: " + table);
|
||||
}
|
||||
if (!isValidColumnList(columns)) {
|
||||
throw new IllegalArgumentException("DataTableColumns is not a list of column identifiers: " + columns);
|
||||
}
|
||||
if (!BUCKET.matcher(bucket).matches() || !OBJECT_KEY.matcher(key).matches()) {
|
||||
throw new IllegalArgumentException("The staged object s3://" + bucket + "/" + key
|
||||
+ " has a name the COPY emulation cannot read: keys must not contain whitespace or quotes.");
|
||||
}
|
||||
if (copyOptions != null && hasStatementSeparator(copyOptions)) {
|
||||
throw new IllegalArgumentException("CopyOptions must not contain a statement separator.");
|
||||
}
|
||||
StringBuilder sql = new StringBuilder("COPY ").append(table);
|
||||
if (columns != null && !columns.isBlank()) {
|
||||
List<String> trimmed = new ArrayList<>();
|
||||
for (String column : columns.split(",")) {
|
||||
trimmed.add(column.trim());
|
||||
}
|
||||
sql.append(" (").append(String.join(", ", trimmed)).append(')');
|
||||
}
|
||||
sql.append(" FROM 's3://").append(bucket).append('/').append(key).append('\'');
|
||||
// The closing terminator is dropped: the statement is sent on its own, and a second one cannot follow it.
|
||||
String options = copyOptions == null ? "" : withoutTrailingTerminator(copyOptions).trim();
|
||||
if (!options.isEmpty()) {
|
||||
sql.append(' ').append(options);
|
||||
}
|
||||
return sql.toString();
|
||||
}
|
||||
|
||||
static boolean isValidTableName(String table) {
|
||||
return table != null && QUALIFIED_NAME.matcher(table).matches();
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.DatabaseSecretCredentials;
|
||||
import io.github.hectorvent.floci.core.common.Resettable;
|
||||
import io.github.hectorvent.floci.core.common.SqlParameterParser.ParsedSql;
|
||||
import io.github.hectorvent.floci.services.rds.container.RdsBackendGate;
|
||||
@@ -196,7 +197,7 @@ public class RdsDataService implements Resettable {
|
||||
requiredText(request, "secretArn");
|
||||
RdsDataResourceResolver.DatabaseTarget target =
|
||||
resourceResolver.resolve(resourceArn, region);
|
||||
Credentials credentials = credentials(request, target, region);
|
||||
DatabaseSecretCredentials credentials = credentials(request, target, region);
|
||||
String database = databaseName(request, target);
|
||||
|
||||
// The transaction's connection keeps the cluster awake until it commits, rolls back or expires.
|
||||
@@ -302,7 +303,7 @@ public class RdsDataService implements Resettable {
|
||||
|
||||
RdsDataResourceResolver.DatabaseTarget target =
|
||||
resourceResolver.resolve(resourceArn, region);
|
||||
Credentials credentials = credentials(request, target, region);
|
||||
DatabaseSecretCredentials credentials = credentials(request, target, region);
|
||||
String database = databaseName(request, target);
|
||||
try (RdsBackendGate.Lease _ = enterBackend(target);
|
||||
Connection connection = connectionFactory.open(target, credentials.username(), credentials.password(), database)) {
|
||||
@@ -619,7 +620,7 @@ public class RdsDataService implements Resettable {
|
||||
};
|
||||
}
|
||||
|
||||
private Credentials credentials(JsonNode request, RdsDataResourceResolver.DatabaseTarget target, String region) {
|
||||
private DatabaseSecretCredentials credentials(JsonNode request, RdsDataResourceResolver.DatabaseTarget target, String region) {
|
||||
String secretArn = textOrNull(request, "secretArn");
|
||||
if (secretArn != null && !secretArn.isBlank()) {
|
||||
SecretVersion secret;
|
||||
@@ -628,7 +629,7 @@ public class RdsDataService implements Resettable {
|
||||
} catch (AwsException e) {
|
||||
throw new AwsException("SecretsErrorException", e.getMessage(), 400);
|
||||
}
|
||||
Credentials fromSecret = parseSecretCredentials(secret.getSecretString());
|
||||
DatabaseSecretCredentials fromSecret = parseSecretCredentials(secret.getSecretString());
|
||||
if (fromSecret != null) {
|
||||
return fromSecret;
|
||||
}
|
||||
@@ -636,29 +637,23 @@ public class RdsDataService implements Resettable {
|
||||
"The secret must contain username and password fields.", 400);
|
||||
}
|
||||
String username = target.username() != null && !target.username().isBlank() ? target.username() : "root";
|
||||
return new Credentials(username, target.password());
|
||||
return new DatabaseSecretCredentials(username, target.password());
|
||||
}
|
||||
|
||||
private Credentials parseSecretCredentials(String secretString) {
|
||||
private DatabaseSecretCredentials parseSecretCredentials(String secretString) {
|
||||
if (secretString == null || secretString.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
JsonNode secret;
|
||||
try {
|
||||
JsonNode secret = objectMapper.readTree(secretString);
|
||||
String username = textOrNull(secret, "username");
|
||||
if (username == null) {
|
||||
username = textOrNull(secret, "user");
|
||||
}
|
||||
String password = textOrNull(secret, "password");
|
||||
if (username != null && password != null) {
|
||||
return new Credentials(username, password);
|
||||
}
|
||||
secret = objectMapper.readTree(secretString);
|
||||
} catch (Exception e) {
|
||||
throw new AwsException("InvalidSecretException",
|
||||
"The secret must contain valid JSON credentials.", 400);
|
||||
}
|
||||
throw new AwsException("InvalidSecretException",
|
||||
"The secret must contain username and password fields.", 400);
|
||||
return DatabaseSecretCredentials.parse(secret).orElseThrow(() ->
|
||||
new AwsException("InvalidSecretException",
|
||||
"The secret must contain username and password fields.", 400));
|
||||
}
|
||||
|
||||
private String databaseName(JsonNode request, RdsDataResourceResolver.DatabaseTarget target) {
|
||||
@@ -892,9 +887,6 @@ public class RdsDataService implements Resettable {
|
||||
}
|
||||
}
|
||||
|
||||
private record Credentials(String username, String password) {
|
||||
}
|
||||
|
||||
@FunctionalInterface
|
||||
private interface ConnectionWork {
|
||||
ObjectNode execute(Connection connection, DatabaseEngine engine) throws SQLException;
|
||||
|
||||
+6
-30
@@ -4,6 +4,7 @@ import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.DatabaseSecretCredentials;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.services.redshift.RedshiftCredentialBroker;
|
||||
import io.github.hectorvent.floci.services.redshift.RedshiftService;
|
||||
@@ -79,12 +80,12 @@ class RedshiftDataResourceResolver {
|
||||
return new DatabaseTarget(workgroup.arn(), workgroup.host(), workgroup.port(), database,
|
||||
workgroup.masterUsername(), workgroup.masterPassword(), spectrum);
|
||||
}
|
||||
Credentials creds = secretCredentials(request.get("SecretArn").asText(), region);
|
||||
DatabaseSecretCredentials creds = secretCredentials(request.get("SecretArn").asText(), region);
|
||||
return new DatabaseTarget(workgroup.arn(), workgroup.host(), workgroup.port(), database,
|
||||
creds.username(), creds.password(), spectrum);
|
||||
}
|
||||
|
||||
private Credentials secretCredentials(String secretArn, String region) {
|
||||
private DatabaseSecretCredentials secretCredentials(String secretArn, String region) {
|
||||
validateSecretRegion(secretArn, region);
|
||||
SecretVersion secret;
|
||||
try {
|
||||
@@ -92,11 +93,8 @@ class RedshiftDataResourceResolver {
|
||||
} catch (AwsException e) {
|
||||
throw validation("SecretArn does not resolve to a local secret: " + secretArn);
|
||||
}
|
||||
Credentials creds = parseCredentials(secret.getSecretString());
|
||||
if (creds == null) {
|
||||
throw validation("Secret " + secretArn + " does not contain username and password fields.");
|
||||
}
|
||||
return creds;
|
||||
return DatabaseSecretCredentials.parse(objectMapper, secret.getSecretString())
|
||||
.orElseThrow(() -> validation("Secret " + secretArn + " does not contain username and password fields."));
|
||||
}
|
||||
|
||||
private static void validateSecretRegion(String secretArn, String region) {
|
||||
@@ -115,7 +113,7 @@ class RedshiftDataResourceResolver {
|
||||
validateSecretRegion(secretArn, region);
|
||||
String clusterId = requiredText(request, "ClusterIdentifier");
|
||||
Cluster cluster = cluster(clusterId);
|
||||
Credentials creds = secretCredentials(secretArn, region);
|
||||
DatabaseSecretCredentials creds = secretCredentials(secretArn, region);
|
||||
return target(clusterArn(clusterId, region), cluster, database, creds.username(), creds.password());
|
||||
}
|
||||
|
||||
@@ -158,26 +156,6 @@ class RedshiftDataResourceResolver {
|
||||
return new DatabaseTarget(arn, host, port, database, user, password, spectrum);
|
||||
}
|
||||
|
||||
private Credentials parseCredentials(String secretString) {
|
||||
if (secretString == null || secretString.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
JsonNode node = objectMapper.readTree(secretString);
|
||||
String username = text(node, "username");
|
||||
if (username == null) {
|
||||
username = text(node, "user");
|
||||
}
|
||||
String password = text(node, "password");
|
||||
if (username != null && password != null) {
|
||||
return new Credentials(username, password);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
LOG.debugv("Could not parse Redshift Data API secret: {0}", e.getMessage());
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private String clusterArn(String clusterId, String region) {
|
||||
String r = (region == null || region.isBlank()) ? regionResolver.getDefaultRegion() : region;
|
||||
return AwsArnUtils.Arn.of("redshift", r, regionResolver.getAccountId(), "cluster:" + clusterId).toString();
|
||||
@@ -212,6 +190,4 @@ class RedshiftDataResourceResolver {
|
||||
}
|
||||
}
|
||||
|
||||
private record Credentials(String username, String password) {
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user