refactor(glue): share Redshift JDBC target resolution and record the outcome of a crawl (#9195)

This commit is contained in:
Vũ Thế Huy authored and GitHub committed 2026-11-22 08:10:30 -04:00
1 parent 351973d3f8
commit 2250972578
13 files changed
+440 -88

No files matched your search

@@ -1,19 +1,15 @@
package io.floci.aws.services.firehose;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.floci.aws.core.common.DatabaseSecretCredentials;
import io.floci.aws.core.common.RequestScopes;
import io.floci.aws.core.common.ServicePrincipals;
import io.floci.aws.services.firehose.model.RedshiftDestination;
import io.floci.aws.services.iam.IamService;
import io.floci.aws.services.iam.ServiceRoleAuthorizer;
import io.floci.aws.services.iam.ServiceRoleAuthorizer.Permission;
import io.floci.aws.services.redshift.RedshiftService;
import io.floci.aws.services.redshift.model.Cluster;
import io.floci.aws.services.redshift.RedshiftJdbcTargets;
import io.floci.aws.services.redshift.RedshiftJdbcTargets.Backend;
import io.floci.aws.services.redshift.RedshiftJdbcUrl;
import io.floci.aws.services.redshift.proxy.RedshiftRoleAccess;
import io.floci.aws.services.redshiftserverless.RedshiftServerlessService;
import io.floci.aws.services.secretsmanager.SecretsManagerService;
import io.floci.aws.services.secretsmanager.model.SecretVersion;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
@@ -47,38 +43,22 @@ public class FirehoseRedshiftDelivery {
void execute(String jdbcUrl, String user, String password, String sql) throws SQLException;
}
/**
* Where a delivery connects. {@code defaultUser} signs in when the destination names none.
*/
private record Backend(String description, String host, int port, String database, String defaultUser) {
}
private final RedshiftService redshiftService;
private final RedshiftServerlessService serverlessService;
private final SecretsManagerService secretsManagerService;
private final RedshiftJdbcTargets jdbcTargets;
private final ServiceRoleAuthorizer roleAuthorizer;
private final IamService iamService;
private final ObjectMapper mapper;
private final SqlRunner runner;
@Inject
public FirehoseRedshiftDelivery(RedshiftService redshiftService, RedshiftServerlessService serverlessService,
SecretsManagerService secretsManagerService,
ServiceRoleAuthorizer roleAuthorizer, IamService iamService,
ObjectMapper mapper) {
this(redshiftService, serverlessService, secretsManagerService, roleAuthorizer, iamService, mapper,
FirehoseRedshiftDelivery::runJdbc);
public FirehoseRedshiftDelivery(RedshiftJdbcTargets jdbcTargets, ServiceRoleAuthorizer roleAuthorizer,
IamService iamService) {
this(jdbcTargets, roleAuthorizer, iamService, FirehoseRedshiftDelivery::runJdbc);
}
FirehoseRedshiftDelivery(RedshiftService redshiftService, RedshiftServerlessService serverlessService,
SecretsManagerService secretsManagerService, ServiceRoleAuthorizer roleAuthorizer,
IamService iamService, ObjectMapper mapper, SqlRunner runner) {
this.redshiftService = redshiftService;
this.serverlessService = serverlessService;
this.secretsManagerService = secretsManagerService;
FirehoseRedshiftDelivery(RedshiftJdbcTargets jdbcTargets, ServiceRoleAuthorizer roleAuthorizer,
IamService iamService, SqlRunner runner) {
this.jdbcTargets = jdbcTargets;
this.roleAuthorizer = roleAuthorizer;
this.iamService = iamService;
this.mapper = mapper;
this.runner = runner;
}
@@ -128,9 +108,7 @@ public class FirehoseRedshiftDelivery {
*/
public void copy(String accountId, String region, RedshiftDestination destination, String bucket, String key) {
RedshiftJdbcUrl target = RedshiftJdbcUrl.parse(destination.getClusterJdbcUrl());
Backend backend = target.serverless()
? workgroupBackend(accountId, region, target)
: clusterBackend(accountId, target);
Backend backend = jdbcTargets.resolve(accountId, region, target);
String[] credentials = credentials(destination, backend, region);
RedshiftDestination.CopyCommand command = destination.getCopyCommand();
String jdbcUrl = "jdbc:postgresql://" + backend.host() + ":" + backend.port() + "/" + backend.database()
@@ -163,38 +141,10 @@ public class FirehoseRedshiftDelivery {
: null;
}
private Backend clusterBackend(String accountId, RedshiftJdbcUrl target) {
Cluster cluster = redshiftService.describeClustersForAccount(accountId, target.clusterIdentifier()).get(0);
// The database name in the URL is ignored: the emulated container database is always "dev".
return new Backend("cluster " + target.clusterIdentifier(), "127.0.0.1", cluster.getEndpoint().getPort(),
"dev", cluster.getMasterUsername());
}
/**
* A workgroup has one database, so a URL that names another one cannot load anything: the same
* refusal the Data API gives, here a failed delivery that goes through the retry path.
*/
private Backend workgroupBackend(String accountId, String region, RedshiftJdbcUrl target) {
RedshiftServerlessService.WorkgroupTarget workgroup = RequestScopes.callAs(accountId, region,
() -> serverlessService.getWorkgroupTarget(target.clusterIdentifier(), region));
if (!target.database().equals(workgroup.database())) {
throw new IllegalStateException("Database " + target.database() + " does not exist in workgroup "
+ workgroup.workgroupName() + "; the only database is " + workgroup.database() + ".");
}
int port = workgroup.endpoint() != null && workgroup.endpoint().getPort() > 0
? workgroup.endpoint().getPort()
: workgroup.port();
return new Backend("workgroup " + workgroup.workgroupName(), "127.0.0.1", port,
workgroup.database(), workgroup.adminUsername());
}
private String[] credentials(RedshiftDestination destination, Backend backend, 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."));
DatabaseSecretCredentials credentials = jdbcTargets.credentialsFromSecret(secrets.getSecretArn(), region);
return new String[] {credentials.username(), credentials.password()};
}
if (destination.getPassword() == null) {
@@ -0,0 +1,25 @@
package io.floci.aws.services.glue;
/**
* How a crawl ended: its {@code LastCrawl} status, the table changes it made to the Data Catalog, and the
* message {@code LastCrawl.ErrorMessage} carries when it failed.
*/
record CrawlOutcome(String status, int tablesCreated, int tablesUpdated, int tablesDeleted, String errorMessage) {
static CrawlOutcome succeeded() {
return succeeded(0, 0, 0);
}
static CrawlOutcome succeeded(int tablesCreated, int tablesUpdated, int tablesDeleted) {
return new CrawlOutcome(GlueCrawlerRunService.STATUS_SUCCEEDED, tablesCreated, tablesUpdated,
tablesDeleted, null);
}
static CrawlOutcome failed(String errorMessage) {
return new CrawlOutcome(GlueCrawlerRunService.STATUS_FAILED, 0, 0, 0, errorMessage);
}
static CrawlOutcome cancelled() {
return new CrawlOutcome(GlueCrawlerRunService.STATUS_CANCELLED, 0, 0, 0, null);
}
}
@@ -0,0 +1,14 @@
package io.floci.aws.services.glue;
/**
* Runs a crawl of the named crawler's targets and reports how it ended. The run service calls it when a
* crawl settles; a crawl that reads no data store ends as {@link CrawlOutcome#succeeded()} with no table changes.
*/
@FunctionalInterface
interface CrawlRunner {
CrawlOutcome run(String crawlerName);
/** Crawls nothing: every crawl succeeds without touching the Data Catalog. */
CrawlRunner NO_DATA_STORE = crawlerName -> CrawlOutcome.succeeded();
}
@@ -26,10 +26,11 @@ import java.util.Map;
import java.util.UUID;
/**
* Glue crawler runs. No data store is crawled and no table is written: a crawl follows the crawler
* state machine (READY, RUNNING, back to READY with a LastCrawl status) and settles lazily when
* read. With the default {@code crawler-run-duration-seconds} of 0 a crawl finishes as soon as it
* starts; a positive duration keeps the crawler RUNNING for that long.
* Glue crawler runs. A crawl follows the crawler state machine (READY, RUNNING, back to READY with a
* LastCrawl status) and settles lazily when read, asking the {@link CrawlRunner} how it ended. With the
* default {@code crawler-run-duration-seconds} of 0 a crawl finishes as soon as it starts; a positive
* duration keeps the crawler RUNNING for that long. The default runner crawls no data store and
* writes no table.
*
* <p>Every public method is synchronized. Starting and stopping a crawl, and the crawler mutations
* AWS refuses while a crawl runs (UpdateCrawler, DeleteCrawler), check the crawl state and act on
@@ -44,6 +45,7 @@ public class GlueCrawlerRunService {
static final String STATE_RUNNING = "RUNNING";
static final String STATUS_SUCCEEDED = "SUCCEEDED";
static final String STATUS_CANCELLED = "CANCELLED";
static final String STATUS_FAILED = "FAILED";
private static final String LOG_GROUP = "/aws-glue/crawlers";
static final String CRAWL_ID_PREFIX = "crawl:";
@@ -57,6 +59,7 @@ public class GlueCrawlerRunService {
private final GlueService glueService;
private final int runDurationSeconds;
private final Clock clock;
private final CrawlRunner crawlRunner;
@Inject
public GlueCrawlerRunService(StorageFactory storageFactory, GlueService glueService, EmulatorConfig config,
@@ -64,12 +67,19 @@ public class GlueCrawlerRunService {
this(new RegionScopedStorage<>(storageFactory, regionResolver, "glue", "crawler_runs.json", new TypeReference<>() {}),
new RegionScopedStorage<>(storageFactory, regionResolver,
"glue", "workflow_run_crawls.json", new TypeReference<>() {}),
glueService, config.services().glue().crawlerRunDurationSeconds(), Clock.systemUTC());
glueService, config.services().glue().crawlerRunDurationSeconds(), Clock.systemUTC(),
CrawlRunner.NO_DATA_STORE);
}
GlueCrawlerRunService(StorageBackend<String, CrawlerRunRecord> recordStore,
StorageBackend<String, List<FinishedCrawl>> workflowCrawlStore, GlueService glueService,
int runDurationSeconds, Clock clock) {
this(recordStore, workflowCrawlStore, glueService, runDurationSeconds, clock, CrawlRunner.NO_DATA_STORE);
}
GlueCrawlerRunService(StorageBackend<String, CrawlerRunRecord> recordStore,
StorageBackend<String, List<FinishedCrawl>> workflowCrawlStore, GlueService glueService,
int runDurationSeconds, Clock clock, CrawlRunner crawlRunner) {
if (runDurationSeconds < 0) {
throw new IllegalArgumentException(
"floci.services.glue.crawler-run-duration-seconds must not be negative: " + runDurationSeconds);
@@ -79,6 +89,7 @@ public class GlueCrawlerRunService {
this.glueService = glueService;
this.runDurationSeconds = runDurationSeconds;
this.clock = clock;
this.crawlRunner = crawlRunner;
}
public synchronized String startCrawler(String name) {
@@ -114,7 +125,7 @@ public class GlueCrawlerRunService {
if (record.getCurrentStart() == null) {
throw new AwsException("CrawlerNotRunningException", "Crawler with name " + name + " isn't running", 400);
}
finish(record, clock.instant(), STATUS_CANCELLED);
finish(record, clock.instant(), CrawlOutcome.cancelled());
LOG.infov("Stopped Glue crawler {0}", name);
}
@@ -132,6 +143,7 @@ public class GlueCrawlerRunService {
if (record.getLastStatus() != null) {
LastCrawlInfo lastCrawl = new LastCrawlInfo();
lastCrawl.setStatus(record.getLastStatus());
lastCrawl.setErrorMessage(record.getLastErrorMessage());
lastCrawl.setStartTime(record.getLastStart());
lastCrawl.setLogGroup(LOG_GROUP);
lastCrawl.setLogStream(crawler.getName());
@@ -303,9 +315,9 @@ public class GlueCrawlerRunService {
List<Double> runtimes = record.getRuntimeSeconds();
metrics.put("LastRuntimeSeconds", runtimes.isEmpty() ? 0.0 : runtimes.getLast());
metrics.put("MedianRuntimeSeconds", median(runtimes));
metrics.put("TablesCreated", 0);
metrics.put("TablesUpdated", 0);
metrics.put("TablesDeleted", 0);
metrics.put("TablesCreated", record.getLastTablesCreated());
metrics.put("TablesUpdated", record.getLastTablesUpdated());
metrics.put("TablesDeleted", record.getLastTablesDeleted());
return metrics;
}
@@ -335,11 +347,24 @@ public class GlueCrawlerRunService {
}
Instant finishesAt = record.getCurrentStart().plusSeconds(runDurationSeconds);
if (!clock.instant().isBefore(finishesAt)) {
finish(record, finishesAt, STATUS_SUCCEEDED);
finish(record, finishesAt, runCrawl(record.getCrawlerName()));
}
}
private void finish(CrawlerRunRecord record, Instant finishedAt, String status) {
/**
* A runner that throws must still end the crawl: otherwise the crawl stays active, every later read
* invokes the runner again, and a workflow's crawl never reaches its completion history.
*/
private CrawlOutcome runCrawl(String crawlerName) {
try {
return crawlRunner.run(crawlerName);
} catch (RuntimeException e) {
LOG.warnv(e, "Glue crawler {0} failed: {1}", crawlerName, e.getMessage());
return CrawlOutcome.failed(e.getMessage() != null ? e.getMessage() : e.getClass().getSimpleName());
}
}
private void finish(CrawlerRunRecord record, Instant finishedAt, CrawlOutcome outcome) {
List<Double> runtimes = new ArrayList<>(record.getRuntimeSeconds());
runtimes.add(Duration.between(record.getCurrentStart(), finishedAt).toMillis() / 1000.0);
if (runtimes.size() > MAX_RUNTIME_HISTORY) {
@@ -350,7 +375,11 @@ public class GlueCrawlerRunService {
finished.setSequence(record.getFinishedCount() + 1);
finished.setStartedAt(record.getCurrentStart());
finished.setFinishedAt(finishedAt);
finished.setStatus(status);
finished.setStatus(outcome.status());
finished.setErrorMessage(outcome.errorMessage());
finished.setTablesCreated(outcome.tablesCreated());
finished.setTablesUpdated(outcome.tablesUpdated());
finished.setTablesDeleted(outcome.tablesDeleted());
finished.setCrawlId(record.getCurrentCrawlId());
finished.setOriginRunId(record.getCurrentOriginRunId());
finished.setWorkflowRunId(record.getCurrentWorkflowRunId());
@@ -369,7 +398,11 @@ public class GlueCrawlerRunService {
record.setRecentCrawls(recent);
record.setFinishedCount(finished.getSequence());
record.setLastStart(record.getCurrentStart());
record.setLastStatus(status);
record.setLastStatus(outcome.status());
record.setLastErrorMessage(outcome.errorMessage());
record.setLastTablesCreated(outcome.tablesCreated());
record.setLastTablesUpdated(outcome.tablesUpdated());
record.setLastTablesDeleted(outcome.tablesDeleted());
record.setLastMessagePrefix(record.getCurrentMessagePrefix());
record.setCurrentStart(null);
record.setCurrentMessagePrefix(null);
@@ -21,6 +21,10 @@ public class CrawlerRunRecord {
private Instant lastStart;
private String lastStatus;
private String lastMessagePrefix;
private String lastErrorMessage;
private int lastTablesCreated;
private int lastTablesUpdated;
private int lastTablesDeleted;
private List<Double> runtimeSeconds = new ArrayList<>();
private long finishedCount;
private List<FinishedCrawl> recentCrawls = new ArrayList<>();
@@ -54,6 +58,18 @@ public class CrawlerRunRecord {
public String getLastMessagePrefix() { return lastMessagePrefix; }
public void setLastMessagePrefix(String lastMessagePrefix) { this.lastMessagePrefix = lastMessagePrefix; }
public String getLastErrorMessage() { return lastErrorMessage; }
public void setLastErrorMessage(String lastErrorMessage) { this.lastErrorMessage = lastErrorMessage; }
public int getLastTablesCreated() { return lastTablesCreated; }
public void setLastTablesCreated(int lastTablesCreated) { this.lastTablesCreated = lastTablesCreated; }
public int getLastTablesUpdated() { return lastTablesUpdated; }
public void setLastTablesUpdated(int lastTablesUpdated) { this.lastTablesUpdated = lastTablesUpdated; }
public int getLastTablesDeleted() { return lastTablesDeleted; }
public void setLastTablesDeleted(int lastTablesDeleted) { this.lastTablesDeleted = lastTablesDeleted; }
public List<Double> getRuntimeSeconds() { return runtimeSeconds; }
public void setRuntimeSeconds(List<Double> runtimeSeconds) { this.runtimeSeconds = runtimeSeconds; }
@@ -17,6 +17,10 @@ public class FinishedCrawl {
private Instant startedAt;
private Instant finishedAt;
private String status;
private String errorMessage;
private int tablesCreated;
private int tablesUpdated;
private int tablesDeleted;
private String crawlId;
private String originRunId;
private String workflowRunId;
@@ -44,6 +48,18 @@ public class FinishedCrawl {
public String getStatus() { return status; }
public void setStatus(String status) { this.status = status; }
public String getErrorMessage() { return errorMessage; }
public void setErrorMessage(String errorMessage) { this.errorMessage = errorMessage; }
public int getTablesCreated() { return tablesCreated; }
public void setTablesCreated(int tablesCreated) { this.tablesCreated = tablesCreated; }
public int getTablesUpdated() { return tablesUpdated; }
public void setTablesUpdated(int tablesUpdated) { this.tablesUpdated = tablesUpdated; }
public int getTablesDeleted() { return tablesDeleted; }
public void setTablesDeleted(int tablesDeleted) { this.tablesDeleted = tablesDeleted; }
public String getCrawlId() { return crawlId; }
public void setCrawlId(String crawlId) { this.crawlId = crawlId; }
@@ -0,0 +1,89 @@
package io.floci.aws.services.redshift;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.floci.aws.core.common.DatabaseSecretCredentials;
import io.floci.aws.core.common.RequestScopes;
import io.floci.aws.services.redshift.model.Cluster;
import io.floci.aws.services.redshiftserverless.RedshiftServerlessService;
import io.floci.aws.services.secretsmanager.SecretsManagerService;
import io.floci.aws.services.secretsmanager.model.SecretVersion;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
/**
* Resolves the address a Redshift JDBC URL names to the Floci backend that serves it, and reads the
* database credentials a Secrets Manager secret holds. Shared by the callers that open their own JDBC
* session to a cluster or workgroup (Firehose delivery, Glue crawlers).
*/
@ApplicationScoped
public class RedshiftJdbcTargets {
/**
* Where a JDBC session connects. {@code defaultUser} is the account that signs in when the caller
* names none.
*/
public record Backend(String description, String host, int port, String database, String defaultUser) {
}
private final RedshiftService redshiftService;
private final RedshiftServerlessService serverlessService;
private final SecretsManagerService secretsManagerService;
private final ObjectMapper mapper;
@Inject
public RedshiftJdbcTargets(RedshiftService redshiftService, RedshiftServerlessService serverlessService,
SecretsManagerService secretsManagerService, ObjectMapper mapper) {
this.redshiftService = redshiftService;
this.serverlessService = serverlessService;
this.secretsManagerService = secretsManagerService;
this.mapper = mapper;
}
/**
* The backend a URL addresses.
*
* @throws io.floci.aws.core.common.AwsException when the cluster or the workgroup does not exist
* @throws IllegalStateException when a serverless URL names a database the workgroup does not have
*/
public Backend resolve(String accountId, String region, RedshiftJdbcUrl url) {
return url.serverless() ? workgroupBackend(accountId, region, url) : clusterBackend(accountId, url);
}
/**
* The username and password stored in a secret.
*
* @throws io.floci.aws.core.common.AwsException when the secret does not exist
* @throws IllegalStateException when the secret holds no username and password
*/
public DatabaseSecretCredentials credentialsFromSecret(String secretId, String region) {
SecretVersion secret = secretsManagerService.getSecretValue(secretId, null, null, region);
return DatabaseSecretCredentials.parse(mapper, secret.getSecretString())
.orElseThrow(() -> new IllegalStateException("Secret " + secretId
+ " does not contain username and password fields."));
}
private Backend clusterBackend(String accountId, RedshiftJdbcUrl target) {
Cluster cluster = redshiftService.describeClustersForAccount(accountId, target.clusterIdentifier()).get(0);
// The database name in the URL is ignored: the emulated container database is always "dev".
return new Backend("cluster " + target.clusterIdentifier(), "127.0.0.1", cluster.getEndpoint().getPort(),
"dev", cluster.getMasterUsername());
}
/**
* A workgroup has one database, so a URL that names another one cannot connect: the same refusal the
* Data API gives.
*/
private Backend workgroupBackend(String accountId, String region, RedshiftJdbcUrl target) {
RedshiftServerlessService.WorkgroupTarget workgroup = RequestScopes.callAs(accountId, region,
() -> serverlessService.getWorkgroupTarget(target.clusterIdentifier(), region));
if (!target.database().equals(workgroup.database())) {
throw new IllegalStateException("Database " + target.database() + " does not exist in workgroup "
+ workgroup.workgroupName() + "; the only database is " + workgroup.database() + ".");
}
int port = workgroup.endpoint() != null && workgroup.endpoint().getPort() > 0
? workgroup.endpoint().getPort()
: workgroup.port();
return new Backend("workgroup " + workgroup.workgroupName(), "127.0.0.1", port,
workgroup.database(), workgroup.adminUsername());
}
}
@@ -1,21 +1,22 @@
package io.floci.aws.services.firehose;
package io.floci.aws.services.redshift;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* The logical address in a Firehose {@code ClusterJDBCURL}. Floci routes by the first host label
* The logical address in a Redshift JDBC URL, as a Firehose {@code ClusterJDBCURL} or a Glue
* connection's {@code JDBC_CONNECTION_URL} carries it. Floci routes by the first host label
* (the cluster identifier or workgroup name) and ignores the host suffix and port, because a
* Floci cluster is reachable on a Docker host and a dynamic port, not on the AWS-shaped name the
* API requires.
*/
record RedshiftJdbcUrl(String clusterIdentifier, boolean serverless, String database) {
public record RedshiftJdbcUrl(String clusterIdentifier, boolean serverless, String database) {
private static final Pattern URL = Pattern.compile(
"jdbc:(?:redshift|postgresql)://([A-Za-z0-9-]{1,63})\\.([A-Za-z0-9.\\-]+):\\d{1,5}/([a-zA-Z0-9_$-]+)");
private static final Pattern SERVICE_LABEL = Pattern.compile("(?:^|\\.)redshift(-serverless)?\\.");
static RedshiftJdbcUrl parse(String url) {
public static RedshiftJdbcUrl parse(String url) {
Matcher matcher = URL.matcher(url == null ? "" : url);
if (!matcher.matches()) {
throw new IllegalArgumentException("Unsupported ClusterJDBCURL: " + url);