mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
refactor(glue): share Redshift JDBC target resolution and record the outcome of a crawl (#9195)
This commit is contained in:
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());
|
||||
}
|
||||
}
|
||||
+5
-4
@@ -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);
|
||||
@@ -7,6 +7,7 @@ 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.model.IamRole;
|
||||
import io.floci.aws.services.redshift.RedshiftJdbcTargets;
|
||||
import io.floci.aws.services.redshift.RedshiftService;
|
||||
import io.floci.aws.services.redshift.model.Cluster;
|
||||
import io.floci.aws.services.redshift.model.Endpoint;
|
||||
@@ -53,6 +54,7 @@ class FirehoseRedshiftDeliveryTest {
|
||||
private IamService iamService;
|
||||
private final List<String[]> executed = new ArrayList<>();
|
||||
private FirehoseRedshiftDelivery delivery;
|
||||
private RedshiftJdbcTargets jdbcTargets;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
@@ -65,7 +67,8 @@ class FirehoseRedshiftDeliveryTest {
|
||||
serverless = mock(RedshiftServerlessService.class);
|
||||
roleAuthorizer = mock(ServiceRoleAuthorizer.class);
|
||||
iamService = mock(IamService.class);
|
||||
delivery = new FirehoseRedshiftDelivery(redshift, serverless, secrets, roleAuthorizer, iamService, mapper,
|
||||
jdbcTargets = new RedshiftJdbcTargets(redshift, serverless, secrets, mapper);
|
||||
delivery = new FirehoseRedshiftDelivery(jdbcTargets, roleAuthorizer, iamService,
|
||||
(url, user, password, sql) -> executed.add(new String[] {url, user, password, sql}));
|
||||
}
|
||||
|
||||
@@ -282,8 +285,8 @@ class FirehoseRedshiftDeliveryTest {
|
||||
void aFailedCopyNeitherLeaksCredentialsIntoTheErrorNorKeepsTheSession() throws Exception {
|
||||
knownLoadRole();
|
||||
List<String> sent = new ArrayList<>();
|
||||
FirehoseRedshiftDelivery failing = new FirehoseRedshiftDelivery(redshift, serverless, secrets,
|
||||
roleAuthorizer, iamService, mapper, (url, user, password, sql) -> {
|
||||
FirehoseRedshiftDelivery failing = new FirehoseRedshiftDelivery(jdbcTargets,
|
||||
roleAuthorizer, iamService, (url, user, password, sql) -> {
|
||||
sent.add(sql);
|
||||
throw new SQLException("rejected: " + sql, "XX000");
|
||||
});
|
||||
@@ -348,8 +351,8 @@ class FirehoseRedshiftDeliveryTest {
|
||||
|
||||
@Test
|
||||
void jdbcFailureIsWrappedWithTableClusterAndSqlState() {
|
||||
FirehoseRedshiftDelivery failing = new FirehoseRedshiftDelivery(redshift, serverless, secrets,
|
||||
roleAuthorizer, iamService, mapper,
|
||||
FirehoseRedshiftDelivery failing = new FirehoseRedshiftDelivery(jdbcTargets,
|
||||
roleAuthorizer, iamService,
|
||||
(url, user, password, sql) -> {
|
||||
throw new SQLException("relation \"events\" does not exist", "42P01");
|
||||
});
|
||||
|
||||
@@ -11,6 +11,7 @@ import io.floci.aws.services.iam.ScpProvider;
|
||||
import io.floci.aws.services.iam.ServiceRoleAuthorizer;
|
||||
import io.floci.aws.services.iam.model.CallerContext;
|
||||
import io.floci.aws.services.iam.model.IamRole;
|
||||
import io.floci.aws.services.redshift.RedshiftJdbcTargets;
|
||||
import io.floci.aws.services.redshift.RedshiftService;
|
||||
import io.floci.aws.services.redshiftserverless.RedshiftServerlessService;
|
||||
import io.floci.aws.services.secretsmanager.SecretsManagerService;
|
||||
@@ -68,9 +69,9 @@ class FirehoseRedshiftRoleAccessTest {
|
||||
when(scpProvider.isResolvable()).thenReturn(false);
|
||||
ServiceRoleAuthorizer authorizer = new ServiceRoleAuthorizer(config, iamService, evaluator,
|
||||
new AssumeRolePolicyEvaluator(new ObjectMapper(), evaluator), scpProvider);
|
||||
delivery = new FirehoseRedshiftDelivery(mock(RedshiftService.class), mock(RedshiftServerlessService.class),
|
||||
mock(SecretsManagerService.class), authorizer, iamService, new ObjectMapper(),
|
||||
(url, user, password, sql) -> { });
|
||||
delivery = new FirehoseRedshiftDelivery(new RedshiftJdbcTargets(mock(RedshiftService.class),
|
||||
mock(RedshiftServerlessService.class), mock(SecretsManagerService.class), new ObjectMapper()),
|
||||
authorizer, iamService, (url, user, password, sql) -> { });
|
||||
}
|
||||
|
||||
private void role(String name, String arn, String trust, String policy) {
|
||||
|
||||
@@ -7,6 +7,7 @@ import io.floci.aws.core.storage.StorageFactory;
|
||||
import io.floci.aws.services.glue.model.Crawler;
|
||||
import io.floci.aws.services.glue.model.CrawlerRunRecord;
|
||||
import io.floci.aws.services.glue.model.CrawlerTargets;
|
||||
import io.floci.aws.services.glue.model.LastCrawlInfo;
|
||||
import io.floci.aws.services.glue.model.S3Target;
|
||||
import io.floci.aws.services.glue.model.Schedule;
|
||||
import io.floci.aws.services.glue.schemaregistry.GlueSchemaRegistryService;
|
||||
@@ -29,6 +30,7 @@ import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
@@ -68,6 +70,79 @@ class GlueCrawlerRunServiceTest {
|
||||
return new GlueCrawlerRunService(recordStore, new InMemoryStorage<>(), glueService, runDurationSeconds, clock);
|
||||
}
|
||||
|
||||
private GlueCrawlerRunService service(CrawlRunner runner) {
|
||||
return new GlueCrawlerRunService(recordStore, new InMemoryStorage<>(), glueService, 0, clock, runner);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aCrawlThatFailsReportsFailedWithItsErrorMessageAndNoTableChanges() {
|
||||
createCrawler("raw", null);
|
||||
GlueCrawlerRunService service = service(name -> CrawlOutcome.failed("Connection missing not found."));
|
||||
|
||||
service.startCrawler("raw");
|
||||
|
||||
Crawler crawler = service.withRunState(glueService.getCrawler("raw"));
|
||||
assertEquals("READY", crawler.getState());
|
||||
assertEquals("FAILED", crawler.getLastCrawl().getStatus());
|
||||
assertEquals("Connection missing not found.", crawler.getLastCrawl().getErrorMessage());
|
||||
Map<String, Object> metrics = metrics(service, "raw");
|
||||
assertEquals(0, metrics.get("TablesCreated"));
|
||||
assertEquals(0, metrics.get("TablesUpdated"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRunnerThatThrowsEndsTheCrawlAsFailedInsteadOfLeavingItActive() {
|
||||
createCrawler("raw", null);
|
||||
AtomicInteger calls = new AtomicInteger();
|
||||
GlueCrawlerRunService service = service(name -> {
|
||||
calls.incrementAndGet();
|
||||
throw new IllegalStateException("backend exploded");
|
||||
});
|
||||
|
||||
service.startCrawler("raw", null, "wfr_1");
|
||||
|
||||
assertFalse(service.isRunning("raw"));
|
||||
assertEquals(1, calls.get());
|
||||
LastCrawlInfo lastCrawl = service.withRunState(glueService.getCrawler("raw")).getLastCrawl();
|
||||
assertEquals("FAILED", lastCrawl.getStatus());
|
||||
assertEquals("backend exploded", lastCrawl.getErrorMessage());
|
||||
assertEquals("FAILED", service.crawlsInWorkflowRun("wfr_1").get(0).state());
|
||||
service.startCrawler("raw");
|
||||
assertEquals(2, calls.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
void metricsReportTheTableChangesOfTheLastCrawl() {
|
||||
createCrawler("raw", null);
|
||||
List<CrawlOutcome> outcomes = List.of(CrawlOutcome.succeeded(3, 0, 0), CrawlOutcome.succeeded(1, 2, 0));
|
||||
int[] next = {0};
|
||||
GlueCrawlerRunService service = service(name -> outcomes.get(next[0]++));
|
||||
|
||||
service.startCrawler("raw");
|
||||
service.startCrawler("raw");
|
||||
|
||||
Map<String, Object> metrics = metrics(service, "raw");
|
||||
assertEquals(1, metrics.get("TablesCreated"));
|
||||
assertEquals(2, metrics.get("TablesUpdated"));
|
||||
assertEquals(0, metrics.get("TablesDeleted"));
|
||||
assertEquals("SUCCEEDED", service.withRunState(glueService.getCrawler("raw")).getLastCrawl().getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aLaterSuccessfulCrawlClearsTheErrorMessageOfAFailedOne() {
|
||||
createCrawler("raw", null);
|
||||
List<CrawlOutcome> outcomes = List.of(CrawlOutcome.failed("boom"), CrawlOutcome.succeeded());
|
||||
int[] next = {0};
|
||||
GlueCrawlerRunService service = service(name -> outcomes.get(next[0]++));
|
||||
|
||||
service.startCrawler("raw");
|
||||
service.startCrawler("raw");
|
||||
|
||||
LastCrawlInfo lastCrawl = service.withRunState(glueService.getCrawler("raw")).getLastCrawl();
|
||||
assertEquals("SUCCEEDED", lastCrawl.getStatus());
|
||||
assertNull(lastCrawl.getErrorMessage());
|
||||
}
|
||||
|
||||
private void createCrawler(String name, String scheduleExpression) {
|
||||
S3Target target = new S3Target();
|
||||
target.setPath("s3://raw/" + name);
|
||||
|
||||
@@ -0,0 +1,129 @@
|
||||
package io.floci.aws.services.redshift;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.core.common.DatabaseSecretCredentials;
|
||||
import io.floci.aws.services.redshift.RedshiftJdbcTargets.Backend;
|
||||
import io.floci.aws.services.redshift.model.Cluster;
|
||||
import io.floci.aws.services.redshift.model.Endpoint;
|
||||
import io.floci.aws.services.redshiftserverless.RedshiftServerlessService;
|
||||
import io.floci.aws.services.redshiftserverless.RedshiftServerlessService.WorkgroupTarget;
|
||||
import io.floci.aws.services.secretsmanager.SecretsManagerService;
|
||||
import io.floci.aws.services.secretsmanager.model.SecretVersion;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class RedshiftJdbcTargetsTest {
|
||||
|
||||
private static final String ACCOUNT_ID = "000000000000";
|
||||
private static final String REGION = "us-east-1";
|
||||
private static final String SECRET_ARN = "arn:aws:secretsmanager:us-east-1:000000000000:secret:admin-AbCdEf";
|
||||
|
||||
private RedshiftService redshift;
|
||||
private RedshiftServerlessService serverless;
|
||||
private SecretsManagerService secrets;
|
||||
private RedshiftJdbcTargets targets;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
redshift = mock(RedshiftService.class);
|
||||
serverless = mock(RedshiftServerlessService.class);
|
||||
secrets = mock(SecretsManagerService.class);
|
||||
targets = new RedshiftJdbcTargets(redshift, serverless, secrets, new ObjectMapper());
|
||||
}
|
||||
|
||||
private static RedshiftJdbcUrl clusterUrl() {
|
||||
return RedshiftJdbcUrl.parse("jdbc:redshift://c1.abc.us-east-1.redshift.amazonaws.com:5439/analytics");
|
||||
}
|
||||
|
||||
private static RedshiftJdbcUrl workgroupUrl(String database) {
|
||||
return RedshiftJdbcUrl.parse("jdbc:redshift://wg1.000000000000.us-east-1.redshift-serverless.amazonaws.com:5439/"
|
||||
+ database);
|
||||
}
|
||||
|
||||
private void workgroup(String database, Endpoint endpoint, int runtimePort) {
|
||||
when(serverless.getWorkgroupTarget("wg1", REGION)).thenReturn(new WorkgroupTarget(
|
||||
"arn:aws:redshift-serverless:us-east-1:000000000000:workgroup/id1", "wg1", "host.docker.internal",
|
||||
runtimePort, database, "workgroupadmin", "ignored", "workgroupadmin", List.of(), null, endpoint));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aClusterUrlResolvesToTheClusterPortAndTheEmulatedDevDatabase() {
|
||||
Cluster cluster = mock(Cluster.class);
|
||||
when(cluster.getEndpoint()).thenReturn(new Endpoint("host.docker.internal", 41234));
|
||||
when(cluster.getMasterUsername()).thenReturn("admin");
|
||||
when(redshift.describeClustersForAccount(ACCOUNT_ID, "c1")).thenReturn(List.of(cluster));
|
||||
|
||||
Backend backend = targets.resolve(ACCOUNT_ID, REGION, clusterUrl());
|
||||
|
||||
assertEquals(new Backend("cluster c1", "127.0.0.1", 41234, "dev", "admin"), backend);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aClusterThatDoesNotExistIsRefusedByTheRedshiftService() {
|
||||
when(redshift.describeClustersForAccount(ACCOUNT_ID, "c1"))
|
||||
.thenThrow(new AwsException("ClusterNotFound", "Cluster c1 not found.", 404));
|
||||
|
||||
assertThrows(AwsException.class, () -> targets.resolve(ACCOUNT_ID, REGION, clusterUrl()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aServerlessUrlResolvesToTheWorkgroupEndpointItsDatabaseAndItsAdminUser() {
|
||||
workgroup("analytics", new Endpoint("localhost", 41300), 5432);
|
||||
|
||||
Backend backend = targets.resolve(ACCOUNT_ID, REGION, workgroupUrl("analytics"));
|
||||
|
||||
assertEquals(new Backend("workgroup wg1", "127.0.0.1", 41300, "analytics", "workgroupadmin"), backend);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aWorkgroupWithoutAnEndpointFallsBackToItsRuntimePort() {
|
||||
workgroup("analytics", null, 5432);
|
||||
|
||||
assertEquals(5432, targets.resolve(ACCOUNT_ID, REGION, workgroupUrl("analytics")).port());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aServerlessUrlNamingAnotherDatabaseIsRefused() {
|
||||
workgroup("analytics", new Endpoint("localhost", 41300), 5432);
|
||||
|
||||
IllegalStateException refused = assertThrows(IllegalStateException.class,
|
||||
() -> targets.resolve(ACCOUNT_ID, REGION, workgroupUrl("other")));
|
||||
|
||||
assertTrue(refused.getMessage().contains("Database other does not exist in workgroup wg1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void credentialsComeFromTheUsernameAndPasswordInTheSecret() {
|
||||
SecretVersion version = mock(SecretVersion.class);
|
||||
when(version.getSecretString()).thenReturn("{\"username\":\"admin\",\"password\":\"pw-managed\"}");
|
||||
when(secrets.getSecretValue(eq(SECRET_ARN), any(), any(), eq(REGION))).thenReturn(version);
|
||||
|
||||
DatabaseSecretCredentials credentials = targets.credentialsFromSecret(SECRET_ARN, REGION);
|
||||
|
||||
assertEquals(new DatabaseSecretCredentials("admin", "pw-managed"), credentials);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSecretWithoutUsernameAndPasswordIsRefused() {
|
||||
SecretVersion version = mock(SecretVersion.class);
|
||||
when(version.getSecretString()).thenReturn("{\"token\":\"x\"}");
|
||||
when(secrets.getSecretValue(eq(SECRET_ARN), any(), any(), eq(REGION))).thenReturn(version);
|
||||
|
||||
IllegalStateException refused = assertThrows(IllegalStateException.class,
|
||||
() -> targets.credentialsFromSecret(SECRET_ARN, REGION));
|
||||
|
||||
assertEquals("Secret " + SECRET_ARN + " does not contain username and password fields.",
|
||||
refused.getMessage());
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package io.floci.aws.services.firehose;
|
||||
package io.floci.aws.services.redshift;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
Reference in new issue
Block a user