feat(glue): crawl a Redshift database through a crawler's JDBC target (#9484)

A crawler with a JdbcTarget now crawls a Redshift cluster or workgroup through its Glue connection: it signs in with the connection's secret, username and password, or KMS-encrypted password, selects tables and views by the include path and exclusions, and writes one Data Catalog table per relation, updating only changed schemas and keeping user-added metadata. The read runs off the run service's lock and the write only while the crawl is still current. UTF-8 byte truncation moves to core.common.Utf8 for Glue, RDS log files and S3.

Closes #7818
This commit is contained in:
Vũ Thế Huy authored and GitHub committed 2026-11-26 08:20:16 -04:00
1 parent 6a3874a3e2
commit 1f86733b1c
17 files changed
+1976 -48

No files matched your search

@@ -6,13 +6,23 @@ import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.services.glue.GlueClient;
import software.amazon.awssdk.services.glue.model.BatchGetCrawlersResponse;
import software.amazon.awssdk.services.glue.model.ConnectionPropertyKey;
import software.amazon.awssdk.services.glue.model.ConnectionType;
import software.amazon.awssdk.services.glue.model.Crawler;
import software.amazon.awssdk.services.glue.model.CrawlerMetrics;
import software.amazon.awssdk.services.glue.model.CrawlerNotRunningException;
import software.amazon.awssdk.services.glue.model.CrawlerState;
import software.amazon.awssdk.services.glue.model.LastCrawlStatus;
import software.amazon.awssdk.services.glue.model.ScheduleState;
import software.amazon.awssdk.services.glue.model.Table;
import software.amazon.awssdk.services.redshift.RedshiftClient;
import software.amazon.awssdk.services.redshift.model.ClusterNotFoundException;
import software.amazon.awssdk.services.redshiftdata.RedshiftDataClient;
import software.amazon.awssdk.services.redshiftdata.model.DescribeStatementResponse;
import software.amazon.awssdk.services.redshiftdata.model.StatusString;
import java.time.Duration;
import java.time.Instant;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
@@ -94,4 +104,113 @@ class GlueCrawlerRunTest {
assertThat(crawler.schedule().state()).isEqualTo(ScheduleState.SCHEDULED);
assertThat(crawler.schedule().scheduleExpression()).isEqualTo("cron(30 3 * * ? *)");
}
@Test
@DisplayName("A JDBC crawl naming a missing connection ends FAILED with an error message")
void jdbcCrawlWithAMissingConnectionFails() throws InterruptedException {
String name = TestFixtures.uniqueName("jdbc_missing_conn");
glue.createCrawler(r -> r
.name(name)
.role(ROLE)
.databaseName("default")
.targets(t -> t.jdbcTargets(j -> j.connectionName("absent-connection").path("dev/public/%"))));
try {
glue.startCrawler(r -> r.name(name));
Crawler crawler = awaitReady(name);
assertThat(crawler.lastCrawl().status()).isEqualTo(LastCrawlStatus.FAILED);
assertThat(crawler.lastCrawl().errorMessage()).contains("absent-connection");
assertThat(glue.getCrawlerMetrics(r -> r.crawlerNameList(name)).crawlerMetricsList().get(0)
.tablesCreated()).isZero();
} finally {
glue.deleteCrawler(r -> r.name(name));
}
}
@Test
@DisplayName("A JDBC crawl of a Redshift cluster writes its tables to the Data Catalog")
void jdbcCrawlOfARedshiftCluster() throws InterruptedException {
String clusterId = TestFixtures.uniqueName("glue-crawl-rs");
String database = TestFixtures.uniqueName("rs_lake").replace('-', '_');
String connection = TestFixtures.uniqueName("rs-conn");
String crawlerName = TestFixtures.uniqueName("rs_crawler");
RedshiftClient redshift = TestFixtures.redshiftClient();
RedshiftDataClient data = TestFixtures.redshiftDataClient();
try {
redshift.createCluster(r -> r
.clusterIdentifier(clusterId)
.nodeType("dc2.large")
.masterUsername("admin")
.masterUserPassword("password123"));
execute(data, clusterId, "CREATE TABLE crawl_orders (id int, amount numeric(10,2), note varchar(20))");
glue.createDatabase(r -> r.databaseInput(d -> d.name(database)));
glue.createConnection(r -> r.connectionInput(c -> c
.name(connection)
.connectionType(ConnectionType.JDBC)
.connectionProperties(Map.of(
ConnectionPropertyKey.JDBC_CONNECTION_URL,
"jdbc:redshift://" + clusterId + ".abc123.us-east-1.redshift.amazonaws.com:5439/dev",
ConnectionPropertyKey.USERNAME, "admin",
ConnectionPropertyKey.PASSWORD, "password123"))));
glue.createCrawler(r -> r
.name(crawlerName)
.role(ROLE)
.databaseName(database)
.targets(t -> t.jdbcTargets(j -> j.connectionName(connection).path("dev/public/crawl%"))));
glue.startCrawler(r -> r.name(crawlerName));
Crawler crawler = awaitReady(crawlerName);
assertThat(crawler.lastCrawl().status()).isEqualTo(LastCrawlStatus.SUCCEEDED);
Table table = glue.getTable(r -> r.databaseName(database).name("dev_public_crawl_orders")).table();
assertThat(table.storageDescriptor().columns())
.extracting(c -> c.name() + ":" + c.type())
.containsExactly("id:int", "amount:decimal(10,2)", "note:string");
assertThat(table.storageDescriptor().location()).isEqualTo("dev.public.crawl_orders");
assertThat(table.parameters()).containsEntry("classification", "redshift")
.containsEntry("connectionName", connection);
assertThat(glue.getCrawlerMetrics(r -> r.crawlerNameList(crawlerName)).crawlerMetricsList().get(0)
.tablesCreated()).isEqualTo(1);
} finally {
cleanUp(() -> glue.deleteCrawler(r -> r.name(crawlerName)));
cleanUp(() -> glue.deleteConnection(r -> r.connectionName(connection)));
cleanUp(() -> glue.deleteDatabase(r -> r.name(database)));
try {
redshift.deleteCluster(r -> r.clusterIdentifier(clusterId).skipFinalClusterSnapshot(true));
} catch (ClusterNotFoundException ignored) {
// The cluster does not exist when creation failed.
}
data.close();
redshift.close();
}
}
private static Crawler awaitReady(String name) throws InterruptedException {
Instant deadline = Instant.now().plus(Duration.ofSeconds(90));
while (Instant.now().isBefore(deadline)) {
Crawler crawler = glue.getCrawler(r -> r.name(name)).crawler();
if (crawler.state() == CrawlerState.READY && crawler.lastCrawl() != null) {
return crawler;
}
Thread.sleep(TestFixtures.isRealAws() ? 5_000L : 250L);
}
throw new IllegalStateException("Crawler " + name + " did not finish in time");
}
private static void execute(RedshiftDataClient data, String clusterId, String sql) {
String id = data.executeStatement(r -> r.clusterIdentifier(clusterId).dbUser("admin").database("dev")
.sql(sql).waitTimeSeconds(30)).id();
DescribeStatementResponse describe = data.describeStatement(r -> r.id(id));
assertThat(describe.status())
.as("statement %s error: %s", id, describe.error())
.isEqualTo(StatusString.FINISHED);
}
private static void cleanUp(Runnable step) {
try {
step.run();
} catch (Exception ignored) {
// Cleanup is best effort: every name is unique to this run and the emulator is disposable.
}
}
}
+34 -7
View File
@@ -110,7 +110,7 @@ reference does not say whether the flag covers them, so Floci does not guess. Th
catalog's `ConnectionPasswordEncryption` setting produces (see Encryption settings below).
`TestConnection` is asynchronous on AWS and returns nothing; Floci checks the request's shape and accepts it
without opening a socket to the data store, since no job or crawler runs against a connection yet.
without opening a socket to the data store. A crawler's JDBC target does use the connection (see Crawlers).
#### Resource policy
@@ -212,12 +212,39 @@ the run is `FAILED`.
| StartCrawlerSchedule | Sets a crawler's schedule to `SCHEDULED`. |
| StopCrawlerSchedule | Sets a crawler's schedule to `NOT_SCHEDULED`. |
Crawls do not read the data store or write tables. A crawl follows the crawler's state machine:
`GetCrawler` reports `RUNNING` with `CrawlElapsedTime` while it runs, then `READY` with a `LastCrawl`
of `SUCCEEDED` (or `CANCELLED` after `StopCrawler`). With the default `crawler-run-duration-seconds` of
0 a crawl finishes as soon as it starts; a positive value keeps the crawler `RUNNING` that long.
`GetCrawlerMetrics` reports zero tables created, updated and deleted. Schedules are stored and their
state can be switched, but a schedule never starts a crawl on its own.
A crawl follows the crawler's state machine: `GetCrawler` reports `RUNNING` with `CrawlElapsedTime` while
it runs, then `READY` with a `LastCrawl` of `SUCCEEDED`, `FAILED` with an `ErrorMessage`, or `CANCELLED`
after `StopCrawler`. With the default `crawler-run-duration-seconds` of 0 a crawl finishes as soon as it
starts; a positive value keeps the crawler `RUNNING` that long. Schedules are stored and their state can be
switched, but a schedule never starts a crawl on its own.
S3 and the other non-JDBC targets are not read: their crawls succeed with zero tables created, updated and
deleted. A `JdbcTarget` whose connection's `JDBC_CONNECTION_URL` names a Redshift cluster or workgroup
(`jdbc:redshift://<cluster-or-workgroup>.<...>.redshift[-serverless].<...>:<port>/<database>`) is crawled:
- The crawl signs in with the secret in the connection's `AuthenticationConfiguration.SecretArn` or
`SECRET_ID` property, otherwise with its `USERNAME` and `PASSWORD` (or `ENCRYPTED_PASSWORD`).
- `Path` is `database/schema/table` or `database/schema`. `%` stands for any run of characters in the
schema or the table, never in the database, and the path is case-sensitive. The database must be the one
the connection reaches (`dev` for a cluster, the workgroup's database for a workgroup); another name fails
the crawl. `Exclusions` are globs
matched against the object path relative to the include path: the table name for `dev/public/%`,
`schema/table` for `dev/%`.
- Each table or view the signed-in user can select from becomes a Data Catalog table named
`<TablePrefix><database>_<schema>_<table>` (lowercased, other characters replaced by `_`) in the
crawler's `DatabaseName`, with `Location` `database.schema.table`, columns mapped to Hive types, and the
`classification` (`redshift`), `connectionName` and `typeOfData` (`table` or `view`) parameters.
`EnableAdditionalMetadata` adds `aws:RawType` (`RAWTYPES`) and the comment parameters (`COMMENTS`).
- A table already in the catalog is updated when its schema changed, unless
`SchemaChangePolicy.UpdateBehavior` is `LOG`. Only what the crawler writes is compared and replaced:
other table parameters, and the comments and parameters of columns that still exist, are kept. Tables
are never deleted, so `TablesDeleted` stays 0.
- The data store is read in the background, and the crawler stays `RUNNING` until the read finishes. A
missing connection or database, an unreachable endpoint, or refused credentials ends the crawl `FAILED`
with nothing written. A crawl stopped while it reads writes nothing.
`GetCrawlerMetrics` reports the tables the last crawl created and updated. Other JDBC engines, partitions,
custom classifiers and `RecrawlPolicy` are not implemented.
#### Triggers
@@ -0,0 +1,24 @@
package io.floci.aws.core.common;
/** Helpers for UTF-8 byte-budgeted strings. */
public final class Utf8 {
private Utf8() {
}
/** The longest prefix of {@code text} that is at most {@code maxBytes} in UTF-8, cut on a code point boundary. */
public static String truncate(String text, int maxBytes) {
int bytes = 0;
int i = 0;
while (i < text.length()) {
int codePoint = text.codePointAt(i);
int size = codePoint < 0x80 ? 1 : codePoint < 0x800 ? 2 : codePoint < 0x10000 ? 3 : 4;
if (bytes + size > maxBytes) {
break;
}
bytes += size;
i += Character.charCount(codePoint);
}
return text.substring(0, i);
}
}
@@ -3,12 +3,33 @@ 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.
*
* <p>A crawl that reads a data store over the network splits in two: {@link #read} reads the store and may
* block, so the run service calls it in the background, outside its lock; the {@link CatalogWrite} it returns
* writes the Data Catalog and runs under the lock, only while the crawl is still the crawler's current one, so a
* stopped crawl writes nothing.
*/
@FunctionalInterface
interface CrawlRunner {
CrawlOutcome run(String crawlerName);
/** Whether a crawl of the crawler reads a data store, so the run service reads it in the background. */
default boolean readsDataStore(String crawlerName) {
return false;
}
/** Reads the crawler's data stores and returns the step that writes what was found. */
default CatalogWrite read(String crawlerName) {
return () -> run(crawlerName);
}
/** Writes what a crawl found to the Data Catalog and reports how the crawl ended. */
@FunctionalInterface
interface CatalogWrite {
CrawlOutcome apply();
}
/** Crawls nothing: every crawl succeeds without touching the Data Catalog. */
CrawlRunner NO_DATA_STORE = crawlerName -> CrawlOutcome.succeeded();
}
@@ -4,6 +4,7 @@ import com.fasterxml.jackson.core.type.TypeReference;
import io.floci.aws.config.EmulatorConfig;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.common.RequestScopes;
import io.floci.aws.core.storage.RegionScopedStorage;
import io.floci.aws.core.storage.StorageBackend;
import io.floci.aws.core.storage.StorageFactory;
@@ -24,13 +25,18 @@ import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executor;
import java.util.concurrent.RejectedExecutionException;
/**
* 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.
* duration keeps the crawler RUNNING for that long. A crawl that reads a data store (a JDBC target)
* reads it in the background and stays RUNNING until the read has finished as well; what it found is
* written when the crawl settles, and discarded when the crawl was stopped first.
*
* <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
@@ -60,15 +66,31 @@ public class GlueCrawlerRunService {
private final int runDurationSeconds;
private final Clock clock;
private final CrawlRunner crawlRunner;
private final Executor readExecutor;
// Crawl id to the background read of its data stores. In memory: a crawl still reading when Floci
// stopped has none after a restart, and its next settle reads again.
private final Map<String, CompletableFuture<CrawlRunner.CatalogWrite>> reads = new ConcurrentHashMap<>();
@Inject
public GlueCrawlerRunService(StorageFactory storageFactory, GlueService glueService, EmulatorConfig config,
RegionResolver regionResolver) {
RegionResolver regionResolver, JdbcCrawlRunner jdbcCrawlRunner) {
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(),
CrawlRunner.NO_DATA_STORE);
jdbcCrawlRunner, readerThreads(regionResolver));
}
/**
* A read runs on its own thread, in the account and Region of the request that started it, since the
* stores it reads are scoped to them.
*/
private static Executor readerThreads(RegionResolver regionResolver) {
return task -> {
String accountId = regionResolver.getAccountId();
String region = regionResolver.getRegion();
Thread.ofVirtual().name("glue-crawl-read").start(() -> RequestScopes.runAs(accountId, region, task));
};
}
GlueCrawlerRunService(StorageBackend<String, CrawlerRunRecord> recordStore,
@@ -80,6 +102,14 @@ public class GlueCrawlerRunService {
GlueCrawlerRunService(StorageBackend<String, CrawlerRunRecord> recordStore,
StorageBackend<String, List<FinishedCrawl>> workflowCrawlStore, GlueService glueService,
int runDurationSeconds, Clock clock, CrawlRunner crawlRunner) {
// Only for a runner that reads no data store, which never hands a read to the executor.
this(recordStore, workflowCrawlStore, glueService, runDurationSeconds, clock, crawlRunner, Runnable::run);
}
/** {@code readExecutor} must run each task after the call that hands it over has returned. */
GlueCrawlerRunService(StorageBackend<String, CrawlerRunRecord> recordStore,
StorageBackend<String, List<FinishedCrawl>> workflowCrawlStore, GlueService glueService,
int runDurationSeconds, Clock clock, CrawlRunner crawlRunner, Executor readExecutor) {
if (runDurationSeconds < 0) {
throw new IllegalArgumentException(
"floci.services.glue.crawler-run-duration-seconds must not be negative: " + runDurationSeconds);
@@ -90,6 +120,7 @@ public class GlueCrawlerRunService {
this.runDurationSeconds = runDurationSeconds;
this.clock = clock;
this.crawlRunner = crawlRunner;
this.readExecutor = readExecutor;
}
public synchronized String startCrawler(String name) {
@@ -115,6 +146,9 @@ public class GlueCrawlerRunService {
record.setCurrentWorkflowRunId(workflowRunId);
recordStore.put(name, record);
LOG.infov("Started Glue crawler {0}", name);
if (crawlRunner.readsDataStore(name)) {
startRead(name, crawlId);
}
settle(record);
return crawlId;
}
@@ -125,6 +159,7 @@ public class GlueCrawlerRunService {
if (record.getCurrentStart() == null) {
throw new AwsException("CrawlerNotRunningException", "Crawler with name " + name + " isn't running", 400);
}
reads.remove(record.getCurrentCrawlId());
finish(record, clock.instant(), CrawlOutcome.cancelled());
LOG.infov("Stopped Glue crawler {0}", name);
}
@@ -348,8 +383,69 @@ public class GlueCrawlerRunService {
return;
}
Instant finishesAt = record.getCurrentStart().plusSeconds(runDurationSeconds);
if (!clock.instant().isBefore(finishesAt)) {
finish(record, finishesAt, runCrawl(record.getCrawlerName()));
if (clock.instant().isBefore(finishesAt)) {
return;
}
String name = record.getCrawlerName();
if (!crawlRunner.readsDataStore(name)) {
finish(record, finishesAt, runCrawl(name));
return;
}
String crawlId = record.getCurrentCrawlId();
CompletableFuture<CrawlRunner.CatalogWrite> read = reads.get(crawlId);
if (read == null) {
startRead(name, crawlId);
return;
}
if (!read.isDone()) {
return;
}
reads.remove(crawlId);
// A read that outlasts the run duration ends the crawl when it finishes, not when the duration ran out.
Instant now = clock.instant();
finish(record, finishesAt.isAfter(now) ? finishesAt : now, write(name, read.join()));
}
private void startRead(String name, String crawlId) {
CompletableFuture<CrawlRunner.CatalogWrite> read = new CompletableFuture<>();
reads.put(crawlId, read);
try {
readExecutor.execute(() -> {
read.complete(readDataStores(name));
readFinished(name, crawlId);
});
} catch (RejectedExecutionException e) {
LOG.warnv(e, "Glue crawler {0} could not start reading its data stores", name);
read.complete(() -> CrawlOutcome.failed("Floci is shutting down"));
}
}
private CrawlRunner.CatalogWrite readDataStores(String name) {
try {
return crawlRunner.read(name);
} catch (RuntimeException e) {
LOG.warnv(e, "Glue crawler {0} could not read its data stores: {1}", name, e.getMessage());
String message = e.getMessage() != null ? e.getMessage() : e.getClass().getSimpleName();
return () -> CrawlOutcome.failed(message);
}
}
/** Settles the crawl a background read belonged to, so what it found is written without waiting for a read. */
private synchronized void readFinished(String name, String crawlId) {
CrawlerRunRecord record = recordStore.get(name).orElse(null);
if (record == null || !crawlId.equals(record.getCurrentCrawlId())) {
reads.remove(crawlId);
return;
}
settle(record);
}
private CrawlOutcome write(String name, CrawlRunner.CatalogWrite write) {
try {
return write.apply();
} catch (RuntimeException e) {
LOG.warnv(e, "Glue crawler {0} could not write what it found: {1}", name, e.getMessage());
return CrawlOutcome.failed(e.getMessage() != null ? e.getMessage() : e.getClass().getSimpleName());
}
}
@@ -0,0 +1,23 @@
package io.floci.aws.services.glue;
import java.sql.SQLException;
import java.util.List;
/** Reads the tables and views, with their columns, that a JDBC session to a data store can select from. */
@FunctionalInterface
interface JdbcCatalogReader {
/**
* @throws SQLException when the session cannot open, as for an unreachable endpoint or a refused sign-in,
* or when the catalog query fails
*/
List<JdbcTableSchema> read(String jdbcUrl, String user, String password) throws SQLException;
/** A table or view; {@code comment} is its database comment, or null. */
record JdbcTableSchema(String schema, String name, boolean view, String comment, List<JdbcColumn> columns) {
}
/** A column as the database declares it: {@code rawType} is the native type, such as {@code numeric(10,2)}. */
record JdbcColumn(String name, String rawType, String comment) {
}
}
@@ -0,0 +1,402 @@
package io.floci.aws.services.glue;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.DatabaseSecretCredentials;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.common.Utf8;
import io.floci.aws.services.glue.JdbcCatalogReader.JdbcColumn;
import io.floci.aws.services.glue.JdbcCatalogReader.JdbcTableSchema;
import io.floci.aws.services.glue.model.AuthenticationConfiguration;
import io.floci.aws.services.glue.model.Column;
import io.floci.aws.services.glue.model.Connection;
import io.floci.aws.services.glue.model.Crawler;
import io.floci.aws.services.glue.model.JdbcTarget;
import io.floci.aws.services.glue.model.StorageDescriptor;
import io.floci.aws.services.glue.model.Table;
import io.floci.aws.services.kms.KmsService;
import io.floci.aws.services.redshift.RedshiftJdbcTargets;
import io.floci.aws.services.redshift.RedshiftJdbcUrl;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.nio.charset.StandardCharsets;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Base64;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Crawls the JDBC targets of a crawler whose Glue connection points at a Redshift cluster or workgroup:
* opens a session with the connection's credentials, reads the tables and views the include path selects,
* and writes one Data Catalog table for each into the crawler's database. Other JDBC engines and the
* crawler's other targets are not read.
*
* <p>A table is named {@code <TablePrefix><database>_<schema>_<table>}, lowercased, with every character
* other than a letter, digit or underscore replaced by an underscore, and its location is
* {@code database.schema.table}.
*/
@ApplicationScoped
public class JdbcCrawlRunner implements CrawlRunner {
private static final Logger LOG = Logger.getLogger(JdbcCrawlRunner.class);
private static final int MAX_TABLE_NAME_LENGTH = 128;
private static final int MAX_COMMENT_BYTES = 255;
private static final Pattern NUMERIC = Pattern.compile("(?:numeric|decimal)\\((\\d+),(\\d+)\\)");
private static final Pattern NOT_A_NAME_CHARACTER = Pattern.compile("[^a-z0-9_]");
// The table and column parameters a crawl writes; every other parameter belongs to whoever set it.
private static final Set<String> CRAWLER_TABLE_PARAMETERS = Set.of("classification", "compressionType",
"connectionName", "typeOfData", "CrawlerSchemaDeserializerVersion", "CrawlerSchemaSerializerVersion",
"UPDATED_BY_CRAWLER", "aws:RawTableComment");
private static final Set<String> CRAWLER_COLUMN_PARAMETERS = Set.of("aws:RawType", "aws:RawColumnComment");
private final GlueService glueService;
private final RedshiftJdbcTargets jdbcTargets;
private final KmsService kmsService;
private final RegionResolver regionResolver;
private final JdbcCatalogReader reader;
@Inject
public JdbcCrawlRunner(GlueService glueService, RedshiftJdbcTargets jdbcTargets, KmsService kmsService,
RegionResolver regionResolver) {
this(glueService, jdbcTargets, kmsService, regionResolver, new PostgresCatalogReader());
}
JdbcCrawlRunner(GlueService glueService, RedshiftJdbcTargets jdbcTargets, KmsService kmsService,
RegionResolver regionResolver, JdbcCatalogReader reader) {
this.glueService = glueService;
this.jdbcTargets = jdbcTargets;
this.kmsService = kmsService;
this.regionResolver = regionResolver;
this.reader = reader;
}
/** The run service calls this for a crawler with no JDBC target, which crawls nothing. */
@Override
public CrawlOutcome run(String crawlerName) {
return readsDataStore(crawlerName) ? read(crawlerName).apply() : CrawlOutcome.succeeded();
}
@Override
public boolean readsDataStore(String crawlerName) {
try {
return !jdbcTargetsOf(glueService.getCrawler(crawlerName)).isEmpty();
} catch (AwsException e) {
LOG.debugv("Glue crawler {0} is gone, so it reads no data store: {1}", crawlerName, e.getMessage());
return false;
}
}
/**
* Reads every JDBC target. Any target that cannot be read fails the whole crawl before anything is written.
*
* @throws AwsException when a connection does not exist, or the cluster, workgroup or secret it names
* @throws IllegalStateException when a connection cannot be used or the data store cannot be read
*/
@Override
public CatalogWrite read(String crawlerName) {
Crawler crawler = glueService.getCrawler(crawlerName);
Map<String, Table> found = new LinkedHashMap<>();
for (JdbcTarget target : jdbcTargetsOf(crawler)) {
for (Table table : readTarget(crawler, target)) {
found.putIfAbsent(table.getName(), table);
}
}
return () -> write(crawler, List.copyOf(found.values()));
}
private static List<JdbcTarget> jdbcTargetsOf(Crawler crawler) {
if (crawler.getTargets() == null || crawler.getTargets().getJdbcTargets() == null) {
return List.of();
}
return crawler.getTargets().getJdbcTargets();
}
private List<Table> readTarget(Crawler crawler, JdbcTarget target) {
String connectionName = target.getConnectionName();
if (connectionName == null || connectionName.isBlank()) {
throw new IllegalStateException("A JDBC target of crawler " + crawler.getName() + " names no connection.");
}
Connection connection = glueService.getConnection(connectionName, false);
Map<String, String> properties = connection.getConnectionProperties() == null
? Map.of() : connection.getConnectionProperties();
RedshiftJdbcUrl url = redshiftUrl(connectionName, properties.get("JDBC_CONNECTION_URL"));
JdbcIncludePath includePath;
try {
includePath = JdbcIncludePath.parse(target.getPath(), target.getExclusions());
} catch (IllegalArgumentException e) {
throw new IllegalStateException(e.getMessage(), e);
}
String region = regionResolver.getRegion();
RedshiftJdbcTargets.Backend backend = jdbcTargets.resolve(regionResolver.getAccountId(), region, url);
if (!includePath.database().equals(backend.database())) {
throw new IllegalStateException("Include path " + target.getPath() + " names database "
+ includePath.database() + ", but connection " + connectionName + " reaches "
+ backend.description() + ", whose only database is " + backend.database() + ".");
}
DatabaseSecretCredentials credentials = credentials(connection, properties, region);
String jdbcUrl = "jdbc:postgresql://" + backend.host() + ":" + backend.port() + "/" + backend.database()
+ "?preferQueryMode=simple";
List<JdbcTableSchema> schemas;
try {
schemas = reader.read(jdbcUrl, credentials.username(), credentials.password());
} catch (SQLException e) {
throw new IllegalStateException("Could not read " + target.getPath() + " through connection "
+ connectionName + " (" + backend.description() + "): " + e.getMessage(), e);
}
List<String> metadata = target.getEnableAdditionalMetadata() == null
? List.of() : target.getEnableAdditionalMetadata();
List<Table> tables = new ArrayList<>();
for (JdbcTableSchema schema : schemas) {
if (includePath.selects(schema.schema(), schema.name())) {
tables.add(catalogTable(crawler, connectionName, includePath.database(), schema,
metadata.contains("RAWTYPES"), metadata.contains("COMMENTS")));
}
}
return tables;
}
private static RedshiftJdbcUrl redshiftUrl(String connectionName, String jdbcUrl) {
if (jdbcUrl == null || jdbcUrl.isBlank()) {
throw new IllegalStateException("Connection " + connectionName + " has no JDBC_CONNECTION_URL.");
}
try {
return RedshiftJdbcUrl.parse(jdbcUrl);
} catch (IllegalArgumentException e) {
throw new IllegalStateException("Connection " + connectionName + " does not point at a Redshift cluster"
+ " or workgroup; Floci crawls only Redshift JDBC targets: " + jdbcUrl, e);
}
}
/** The secret the connection names wins over a username and password stored on it. */
private DatabaseSecretCredentials credentials(Connection connection, Map<String, String> properties,
String region) {
AuthenticationConfiguration authentication = connection.getAuthenticationConfiguration();
String secretId = authentication != null && authentication.getSecretArn() != null
? authentication.getSecretArn()
: properties.get("SECRET_ID");
if (secretId != null && !secretId.isBlank()) {
return jdbcTargets.credentialsFromSecret(secretId, region);
}
String user = properties.get("USERNAME");
String password = properties.get("PASSWORD");
if (password == null && properties.get("ENCRYPTED_PASSWORD") != null) {
password = new String(kmsService.decrypt(Base64.getDecoder().decode(properties.get("ENCRYPTED_PASSWORD")),
region), StandardCharsets.UTF_8);
}
if (user == null || password == null) {
throw new IllegalStateException("Connection " + connection.getName()
+ " has no credentials: set SECRET_ID, or USERNAME and PASSWORD.");
}
return new DatabaseSecretCredentials(user, password);
}
private static Table catalogTable(Crawler crawler, String connectionName, String database,
JdbcTableSchema schema, boolean rawTypes, boolean comments) {
List<Column> columns = new ArrayList<>();
for (JdbcColumn source : schema.columns()) {
Column column = new Column(source.name(), catalogType(source.rawType()));
Map<String, String> parameters = new LinkedHashMap<>();
if (rawTypes) {
parameters.put("aws:RawType", source.rawType());
}
if (comments && source.comment() != null) {
parameters.put("aws:RawColumnComment", Utf8.truncate(source.comment(), MAX_COMMENT_BYTES));
}
if (!parameters.isEmpty()) {
column.setParameters(parameters);
}
columns.add(column);
}
Map<String, String> parameters = new LinkedHashMap<>();
parameters.put("classification", "redshift");
parameters.put("compressionType", "none");
parameters.put("connectionName", connectionName);
parameters.put("typeOfData", schema.view() ? "view" : "table");
parameters.put("CrawlerSchemaDeserializerVersion", "1.0");
parameters.put("CrawlerSchemaSerializerVersion", "1.0");
parameters.put("UPDATED_BY_CRAWLER", crawler.getName());
if (comments && schema.comment() != null) {
parameters.put("aws:RawTableComment", Utf8.truncate(schema.comment(), MAX_COMMENT_BYTES));
}
StorageDescriptor descriptor = new StorageDescriptor();
descriptor.setColumns(columns);
descriptor.setLocation(database + "." + schema.schema() + "." + schema.name());
descriptor.setCompressed(false);
descriptor.setNumberOfBuckets(-1);
StorageDescriptor.SerDeInfo serde = new StorageDescriptor.SerDeInfo();
serde.setParameters(new LinkedHashMap<>());
descriptor.setSerdeInfo(serde);
descriptor.setParameters(new LinkedHashMap<>(parameters));
descriptor.setStoredAsSubDirectories(false);
Table table = new Table();
table.setName(tableName(crawler.getTablePrefix(), database, schema));
table.setTableType("EXTERNAL_TABLE");
table.setParameters(parameters);
table.setStorageDescriptor(descriptor);
return table;
}
private static String tableName(String prefix, String database, JdbcTableSchema schema) {
String raw = (prefix == null ? "" : prefix) + database + "_" + schema.schema() + "_" + schema.name();
String name = NOT_A_NAME_CHARACTER.matcher(raw.toLowerCase(Locale.ROOT)).replaceAll("_");
return name.length() > MAX_TABLE_NAME_LENGTH ? name.substring(0, MAX_TABLE_NAME_LENGTH) : name;
}
/** The Hive type a crawler records for a Redshift column; types with no Hive counterpart become strings. */
static String catalogType(String rawType) {
String type = rawType.toLowerCase(Locale.ROOT).replace(" ", "");
Matcher numeric = NUMERIC.matcher(type);
if (numeric.matches()) {
return "decimal(" + numeric.group(1) + "," + numeric.group(2) + ")";
}
return switch (type) {
case "smallint", "int2" -> "smallint";
case "integer", "int", "int4" -> "int";
case "bigint", "int8" -> "bigint";
case "numeric", "decimal" -> "decimal(18,0)";
case "real", "float4" -> "float";
case "doubleprecision", "float8", "float" -> "double";
case "boolean", "bool" -> "boolean";
case "date" -> "date";
case "timestampwithouttimezone", "timestampwithtimezone", "timestamp", "timestamptz" -> "timestamp";
default -> "string";
};
}
/**
* Creates the tables the catalog does not have and updates the ones whose schema changed, unless the
* crawler's {@code SchemaChangePolicy.UpdateBehavior} is {@code LOG}.
*
* @throws AwsException when the crawler's database does not exist
*/
private CrawlOutcome write(Crawler crawler, List<Table> tables) {
String database = crawler.getDatabaseName();
if (database == null || database.isBlank()) {
throw new IllegalStateException("Crawler " + crawler.getName() + " has no DatabaseName to write to.");
}
glueService.getDatabase(database);
Map<String, Table> existing = new HashMap<>();
for (Table table : glueService.getTables(database)) {
existing.put(table.getName(), table);
}
boolean logOnly = crawler.getSchemaChangePolicy() != null
&& "LOG".equals(crawler.getSchemaChangePolicy().getUpdateBehavior());
int created = 0;
int updated = 0;
for (Table table : tables) {
Table current = existing.get(table.getName());
if (current == null) {
glueService.createTable(database, table);
created++;
} else if (!sameSchema(current, table)) {
if (logOnly) {
LOG.infov("Glue crawler {0} found a changed schema for {1}.{2} and only logs it",
crawler.getName(), database, table.getName());
continue;
}
glueService.updateTable(database, merged(current, table), null, false);
updated++;
}
}
LOG.infov("Glue crawler {0} created {1} and updated {2} tables in {3}", crawler.getName(), created,
updated, database);
return CrawlOutcome.succeeded(created, updated, 0);
}
/**
* Whether the catalog table already holds what the crawl found. Only what the crawler writes is compared:
* metadata a user added (other parameters, column comments) never makes a table look changed.
*/
private static boolean sameSchema(Table current, Table crawled) {
StorageDescriptor currentDescriptor = current.getStorageDescriptor();
if (currentDescriptor == null) {
return false;
}
return Objects.equals(currentDescriptor.getLocation(), crawled.getStorageDescriptor().getLocation())
&& crawlerOwned(current.getParameters(), CRAWLER_TABLE_PARAMETERS).equals(crawled.getParameters())
&& columnsOf(currentDescriptor).equals(columnsOf(crawled.getStorageDescriptor()));
}
private static List<List<Object>> columnsOf(StorageDescriptor descriptor) {
List<List<Object>> columns = new ArrayList<>();
if (descriptor.getColumns() != null) {
for (Column column : descriptor.getColumns()) {
// A stored column may have no Type, and List.of refuses nulls.
columns.add(Arrays.asList(column.getName(), column.getType(),
crawlerOwned(column.getParameters(), CRAWLER_COLUMN_PARAMETERS)));
}
}
return columns;
}
private static Map<String, String> crawlerOwned(Map<String, String> parameters, Set<String> keys) {
return filterParameters(parameters, keys, true);
}
/** The parameters the crawler did not write, which a user or another tool owns. */
private static Map<String, String> userOwned(Map<String, String> parameters, Set<String> crawlerKeys) {
return filterParameters(parameters, crawlerKeys, false);
}
private static Map<String, String> filterParameters(Map<String, String> parameters, Set<String> keys,
boolean include) {
Map<String, String> filtered = new LinkedHashMap<>();
if (parameters != null) {
for (Map.Entry<String, String> parameter : parameters.entrySet()) {
if (keys.contains(parameter.getKey()) == include) {
filtered.put(parameter.getKey(), parameter.getValue());
}
}
}
return filtered;
}
/**
* The crawled schema laid over the stored table: the crawler's columns, location and parameters replace
* its own earlier ones, and the metadata a user added to the table and to columns that still exist stays.
*/
private static Table merged(Table current, Table crawled) {
Map<String, String> tableParameters = userOwned(current.getParameters(), CRAWLER_TABLE_PARAMETERS);
tableParameters.putAll(crawled.getParameters());
crawled.setParameters(tableParameters);
StorageDescriptor descriptor = crawled.getStorageDescriptor();
StorageDescriptor currentDescriptor = current.getStorageDescriptor();
Map<String, String> descriptorParameters = userOwned(
currentDescriptor == null ? null : currentDescriptor.getParameters(), CRAWLER_TABLE_PARAMETERS);
descriptorParameters.putAll(descriptor.getParameters());
descriptor.setParameters(descriptorParameters);
Map<String, Column> currentColumns = new HashMap<>();
if (currentDescriptor != null && currentDescriptor.getColumns() != null) {
for (Column column : currentDescriptor.getColumns()) {
currentColumns.put(column.getName(), column);
}
}
for (Column column : descriptor.getColumns()) {
Column stored = currentColumns.get(column.getName());
if (stored == null) {
continue;
}
column.setComment(stored.getComment());
Map<String, String> columnParameters = userOwned(stored.getParameters(), CRAWLER_COLUMN_PARAMETERS);
if (column.getParameters() != null) {
columnParameters.putAll(column.getParameters());
}
column.setParameters(columnParameters.isEmpty() ? null : columnParameters);
}
crawled.setDescription(current.getDescription());
crawled.setOwner(current.getOwner());
crawled.setRetention(current.getRetention());
return crawled;
}
}
@@ -0,0 +1,152 @@
package io.floci.aws.services.glue;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
/**
* The include path of a crawler's JDBC target for a database that has schemas: {@code database/schema/table}
* or {@code database/schema}, where {@code %} stands for any run of characters in the schema or the table
* but never in the database. A two-segment path takes every table of the schemas it names. The path is
* case-sensitive. Exclusions are Unix-style globs matched against the object path relative to the include
* path, from its first segment that holds a {@code %}: {@code dev/public/%} matches exclusions against the
* table name, {@code dev/%} against {@code schema/table}.
*/
final class JdbcIncludePath {
private final String database;
private final Pattern schema;
private final Pattern table;
private final int literalSegments;
private final List<Pattern> exclusions;
private JdbcIncludePath(String database, Pattern schema, Pattern table, int literalSegments,
List<Pattern> exclusions) {
this.database = database;
this.schema = schema;
this.table = table;
this.literalSegments = literalSegments;
this.exclusions = exclusions;
}
/** @throws IllegalArgumentException when the path is not {@code database/schema[/table]} */
static JdbcIncludePath parse(String path, List<String> exclusions) {
String[] segments = path == null ? new String[0] : path.split("/", -1);
if (segments.length < 2 || segments.length > 3) {
throw new IllegalArgumentException("Include path " + path
+ " must be database/schema/table or database/schema.");
}
for (String segment : segments) {
if (segment.isEmpty()) {
throw new IllegalArgumentException("Include path " + path + " has an empty segment.");
}
}
if (segments[0].contains("%")) {
throw new IllegalArgumentException("Include path " + path + " cannot use % for the database.");
}
String tableSegment = segments.length == 3 ? segments[2] : "%";
int literalSegments = 1;
if (!segments[1].contains("%")) {
literalSegments = tableSegment.contains("%") ? 2 : 3;
}
List<Pattern> compiled = new ArrayList<>();
if (exclusions != null) {
for (String exclusion : exclusions) {
compiled.add(glob(exclusion));
}
}
return new JdbcIncludePath(segments[0], like(segments[1]), like(tableSegment), literalSegments,
List.copyOf(compiled));
}
String database() {
return database;
}
/** Whether the crawl takes {@code schema.table}: the include path names it and no exclusion removes it. */
boolean selects(String schemaName, String tableName) {
if (!schema.matcher(schemaName).matches() || !table.matcher(tableName).matches()) {
return false;
}
String relative = literalSegments <= 1 ? schemaName + "/" + tableName : tableName;
for (Pattern exclusion : exclusions) {
if (exclusion.matcher(relative).matches()) {
return false;
}
}
return true;
}
private static Pattern like(String segment) {
StringBuilder regex = new StringBuilder();
int start = 0;
int percent;
while ((percent = segment.indexOf('%', start)) >= 0) {
regex.append(Pattern.quote(segment.substring(start, percent))).append(".*");
start = percent + 1;
}
regex.append(Pattern.quote(segment.substring(start)));
return Pattern.compile(regex.toString(), Pattern.DOTALL);
}
/**
* {@code *} matches within one path segment, {@code **} across segments, {@code ?} one character,
* {@code [...]} a class ({@code !} negates), {@code {a,b}} a group, and a backslash escapes.
*/
static Pattern glob(String glob) {
StringBuilder regex = new StringBuilder();
boolean inGroup = false;
for (int i = 0; i < glob.length(); i++) {
char c = glob.charAt(i);
switch (c) {
case '\\' -> {
if (i + 1 < glob.length()) {
regex.append(Pattern.quote(String.valueOf(glob.charAt(++i))));
} else {
regex.append(Pattern.quote("\\"));
}
}
case '*' -> {
if (i + 1 < glob.length() && glob.charAt(i + 1) == '*') {
regex.append(".*");
i++;
} else {
regex.append("[^/]*");
}
}
case '?' -> regex.append("[^/]");
case '[' -> {
int close = glob.indexOf(']', i + 1);
if (close < 0) {
regex.append(Pattern.quote("["));
} else {
String body = glob.substring(i + 1, close);
if (body.startsWith("!")) {
body = "^" + body.substring(1);
}
regex.append('[').append(body.replace("\\", "\\\\").replace("[", "\\[")).append(']');
i = close;
}
}
case '{' -> {
regex.append("(?:");
inGroup = true;
}
case '}' -> {
if (inGroup) {
regex.append(')');
inGroup = false;
} else {
regex.append(Pattern.quote("}"));
}
}
case ',' -> regex.append(inGroup ? "|" : ",");
default -> regex.append(Pattern.quote(String.valueOf(c)));
}
}
if (inGroup) {
throw new IllegalArgumentException("Exclusion " + glob + " has an unclosed group.");
}
return Pattern.compile(regex.toString(), Pattern.DOTALL);
}
}
@@ -0,0 +1,87 @@
package io.floci.aws.services.glue;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
/**
* Reads the tables and views of a PostgreSQL wire database, the protocol a Floci Redshift cluster or
* workgroup speaks. Only relations the signed-in user can select from are returned, and system and Floci
* schemas are left out.
*/
final class PostgresCatalogReader implements JdbcCatalogReader {
// An endpoint that never answers must not hold a crawl forever.
private static final int CONNECT_TIMEOUT_SECONDS = 10;
private static final int SOCKET_TIMEOUT_SECONDS = 60;
static final String CATALOG_SQL = """
SELECT n.nspname, c.relname, c.relkind IN ('v', 'm') AS is_view,
obj_description(c.oid, 'pg_class') AS table_comment,
a.attname, format_type(a.atttypid, a.atttypmod) AS column_type,
col_description(c.oid, a.attnum) AS column_comment
FROM pg_catalog.pg_class c
JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
JOIN pg_catalog.pg_attribute a ON a.attrelid = c.oid AND a.attnum > 0 AND NOT a.attisdropped
WHERE c.relkind IN ('r', 'p', 'v', 'm')
AND NOT c.relispartition
AND n.nspname NOT IN ('pg_catalog', 'information_schema', 'pg_toast', 'floci_internal', 'sys')
AND n.nspname NOT LIKE 'pg\\_%'
AND has_table_privilege(c.oid, 'SELECT')
ORDER BY n.nspname, c.relname, a.attnum
""";
@Override
public List<JdbcTableSchema> read(String jdbcUrl, String user, String password) throws SQLException {
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));
try (Connection connection = DriverManager.getConnection(jdbcUrl, properties);
Statement statement = connection.createStatement();
ResultSet rows = statement.executeQuery(CATALOG_SQL)) {
List<CatalogRow> catalog = new ArrayList<>();
while (rows.next()) {
catalog.add(new CatalogRow(rows.getString(1), rows.getString(2), rows.getBoolean(3),
rows.getString(4), rows.getString(5), rows.getString(6), rows.getString(7)));
}
return group(catalog);
}
}
/** One column of one relation, as a row of {@link #CATALOG_SQL}. */
record CatalogRow(String schema, String table, boolean view, String tableComment, String column,
String columnType, String columnComment) {
}
/** A relation's identity. Schema and name stay apart: quoted names may hold dots. */
private record RelationKey(String schema, String table) {
}
/** Gathers the columns of each relation, keeping the order of the rows. */
static List<JdbcTableSchema> group(List<CatalogRow> rows) {
Map<RelationKey, List<CatalogRow>> byRelation = new LinkedHashMap<>();
for (CatalogRow row : rows) {
byRelation.computeIfAbsent(new RelationKey(row.schema(), row.table()), key -> new ArrayList<>()).add(row);
}
List<JdbcTableSchema> tables = new ArrayList<>();
for (List<CatalogRow> relation : byRelation.values()) {
CatalogRow first = relation.getFirst();
List<JdbcColumn> columns = new ArrayList<>();
for (CatalogRow row : relation) {
columns.add(new JdbcColumn(row.column(), row.columnType(), row.columnComment()));
}
tables.add(new JdbcTableSchema(first.schema(), first.table(), first.view(), first.tableComment(),
List.copyOf(columns)));
}
return tables;
}
}
@@ -1,6 +1,7 @@
package io.floci.aws.services.rds;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.Utf8;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
@@ -169,7 +170,7 @@ final class RdsLogFiles {
}
if (lineBytes > MAX_BYTES) {
// A single line over 1 MB is cut there, as the API reference says the block is.
line = truncateUtf8(lines.get(end), MAX_BYTES - 1) + "\n";
line = Utf8.truncate(lines.get(end), MAX_BYTES - 1) + "\n";
lineBytes = line.getBytes(StandardCharsets.UTF_8).length;
}
data.append(line);
@@ -178,20 +179,4 @@ final class RdsLogFiles {
}
return new Portion(data.toString(), Integer.toString(end), end < lines.size());
}
/** The longest prefix of {@code text} that is at most {@code maxBytes} in UTF-8, cut between characters. */
static String truncateUtf8(String text, int maxBytes) {
int bytes = 0;
int i = 0;
while (i < text.length()) {
int codePoint = text.codePointAt(i);
int size = codePoint < 0x80 ? 1 : codePoint < 0x800 ? 2 : codePoint < 0x10000 ? 3 : 4;
if (bytes + size > maxBytes) {
break;
}
bytes += size;
i += Character.charCount(codePoint);
}
return text.substring(0, i);
}
}
@@ -23,6 +23,7 @@ import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.common.RequestScopes;
import io.floci.aws.core.common.Resettable;
import io.floci.aws.core.common.ServicePrincipals;
import io.floci.aws.core.common.Utf8;
import io.floci.aws.core.common.XmlBuilder;
import io.floci.aws.core.common.XmlParser;
import io.floci.aws.core.resource.ExplorerResource;
@@ -8194,7 +8195,7 @@ public class S3Service implements Resettable, ResourceProvider {
if (representable && utf8Length(segment) <= budget && !hasEncodedShape(segment, budget)) {
return segment;
}
String prefix = truncateUtf8(segment, budget - 1 - SHA256_HEX_CHARS);
String prefix = Utf8.truncate(segment, budget - 1 - SHA256_HEX_CHARS);
if (WINDOWS_FILE_NAMES) {
prefix = windowsSafePrefix(prefix);
}
@@ -8267,23 +8268,6 @@ public class S3Service implements Resettable, ResourceProvider {
return true;
}
private static String truncateUtf8(String segment, int maxBytes) {
int end = 0;
int used = 0;
int i = 0;
while (i < segment.length()) {
int codePoint = segment.codePointAt(i);
int byteCount = codePoint < 0x80 ? 1 : codePoint < 0x800 ? 2 : codePoint < 0x10000 ? 3 : 4;
if (used + byteCount > maxBytes) {
break;
}
used += byteCount;
i += Character.charCount(codePoint);
end = i;
}
return segment.substring(0, end);
}
private static int utf8Length(String segment) {
return segment.getBytes(StandardCharsets.UTF_8).length;
}
@@ -0,0 +1,40 @@
package io.floci.aws.core.common;
import org.junit.jupiter.api.Test;
import java.nio.charset.StandardCharsets;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
class Utf8Test {
@Test
void returnsInputUnchangedWhenWithinByteBudget() {
assertEquals("", Utf8.truncate("", 10));
assertEquals("hello", Utf8.truncate("hello", 5));
assertEquals("café😀", Utf8.truncate("café😀", 9));
}
@Test
void cutsOnCodePointBoundariesWithoutSplittingMultiByteOrSurrogatePairs() {
assertEquals("abc", Utf8.truncate("abcdef", 3));
assertEquals("caf", Utf8.truncate("café", 4));
assertEquals("café", Utf8.truncate("café", 5));
assertEquals("a", Utf8.truncate("a中b", 3));
assertEquals("a中", Utf8.truncate("a中b", 4));
// A 4-byte emoji is a surrogate pair; budgets of 1..3 bytes into it must drop the whole emoji.
String withEmoji = "ab😀cd";
assertEquals("ab", Utf8.truncate(withEmoji, 3));
assertEquals("ab", Utf8.truncate(withEmoji, 4));
assertEquals("ab", Utf8.truncate(withEmoji, 5));
assertEquals("ab😀", Utf8.truncate(withEmoji, 6));
assertTrue(Utf8.truncate(withEmoji, 5).getBytes(StandardCharsets.UTF_8).length <= 5);
}
@Test
void returnsEmptyWhenBudgetIsZeroOrNegative() {
assertEquals("", Utf8.truncate("abc", 0));
assertEquals("", Utf8.truncate("abc", -5));
}
}
@@ -144,6 +144,155 @@ class GlueCrawlerRunServiceTest {
assertNull(lastCrawl.getErrorMessage());
}
/** A runner that reads a data store: each read and each write is counted, and the write reports {@code outcome}. */
private static class DataStoreRunner implements CrawlRunner {
private final AtomicInteger reads = new AtomicInteger();
private final AtomicInteger writes = new AtomicInteger();
private RuntimeException readFailure;
private CrawlOutcome outcome = CrawlOutcome.succeeded(2, 0, 0);
@Override
public CrawlOutcome run(String crawlerName) {
throw new AssertionError("a crawl that reads a data store must not run inline");
}
@Override
public boolean readsDataStore(String crawlerName) {
return true;
}
@Override
public CatalogWrite read(String crawlerName) {
reads.incrementAndGet();
if (readFailure != null) {
throw readFailure;
}
return () -> {
writes.incrementAndGet();
return outcome;
};
}
}
private final List<Runnable> backgroundTasks = new ArrayList<>();
private GlueCrawlerRunService backgroundService(int runDurationSeconds, CrawlRunner runner) {
return new GlueCrawlerRunService(recordStore, new InMemoryStorage<>(), glueService, runDurationSeconds, clock,
runner, backgroundTasks::add);
}
private void runBackgroundTasks() {
List<Runnable> tasks = new ArrayList<>(backgroundTasks);
backgroundTasks.clear();
for (Runnable task : tasks) {
task.run();
}
}
@Test
void aCrawlThatReadsADataStoreRunsUntilTheReadFinishesThenWritesWhatItFound() {
createCrawler("jdbc", null);
DataStoreRunner runner = new DataStoreRunner();
GlueCrawlerRunService service = backgroundService(0, runner);
service.startCrawler("jdbc");
assertTrue(service.isRunning("jdbc"));
assertEquals(0, runner.reads.get());
runBackgroundTasks();
assertFalse(service.isRunning("jdbc"));
assertEquals(1, runner.writes.get());
assertEquals("SUCCEEDED", read(service, "jdbc").getLastCrawl().getStatus());
assertEquals(2, metrics(service, "jdbc").get("TablesCreated"));
}
@Test
void stoppingACrawlWhileItReadsDiscardsWhatTheReadFound() {
createCrawler("jdbc", null);
DataStoreRunner runner = new DataStoreRunner();
GlueCrawlerRunService service = backgroundService(0, runner);
service.startCrawler("jdbc");
service.stopCrawler("jdbc");
runBackgroundTasks();
assertEquals(0, runner.writes.get());
assertFalse(service.isRunning("jdbc"));
assertEquals("CANCELLED", read(service, "jdbc").getLastCrawl().getStatus());
assertEquals(0, metrics(service, "jdbc").get("TablesCreated"));
}
@Test
void aReadThatThrowsEndsTheCrawlAsFailedWithoutWriting() {
createCrawler("jdbc", null);
DataStoreRunner runner = new DataStoreRunner();
runner.readFailure = new IllegalStateException("password authentication failed");
GlueCrawlerRunService service = backgroundService(0, runner);
service.startCrawler("jdbc", null, "wfr_1");
runBackgroundTasks();
LastCrawlInfo lastCrawl = read(service, "jdbc").getLastCrawl();
assertEquals("FAILED", lastCrawl.getStatus());
assertEquals("password authentication failed", lastCrawl.getErrorMessage());
assertEquals("password authentication failed", service.crawlsInWorkflowRun("wfr_1").get(0).errorMessage());
assertEquals(0, runner.writes.get());
}
@Test
void aWriteThatThrowsEndsTheCrawlAsFailed() {
createCrawler("jdbc", null);
CrawlRunner runner = new DataStoreRunner() {
@Override
public CatalogWrite read(String crawlerName) {
return () -> {
throw new AwsException("EntityNotFoundException", "Database lake not found.", 400);
};
}
};
GlueCrawlerRunService service = backgroundService(0, runner);
service.startCrawler("jdbc");
runBackgroundTasks();
LastCrawlInfo lastCrawl = read(service, "jdbc").getLastCrawl();
assertEquals("FAILED", lastCrawl.getStatus());
assertEquals("Database lake not found.", lastCrawl.getErrorMessage());
}
@Test
void aReadThatFinishesEarlyWaitsForTheRunDurationBeforeWriting() {
createCrawler("jdbc", null);
DataStoreRunner runner = new DataStoreRunner();
GlueCrawlerRunService service = backgroundService(30, runner);
service.startCrawler("jdbc");
runBackgroundTasks();
assertTrue(service.isRunning("jdbc"));
assertEquals(0, runner.writes.get());
clock.advance(Duration.ofSeconds(30));
assertFalse(service.isRunning("jdbc"));
assertEquals(1, runner.writes.get());
}
@Test
void aCrawlStillReadingWhenFlociStoppedReadsAgain() {
createCrawler("jdbc", null);
DataStoreRunner runner = new DataStoreRunner();
backgroundService(0, runner).startCrawler("jdbc");
backgroundTasks.clear();
GlueCrawlerRunService restarted = backgroundService(0, runner);
assertTrue(restarted.isRunning("jdbc"));
runBackgroundTasks();
assertFalse(restarted.isRunning("jdbc"));
assertEquals(1, runner.reads.get());
assertEquals(1, runner.writes.get());
assertEquals("SUCCEEDED", read(restarted, "jdbc").getLastCrawl().getStatus());
}
private void createCrawler(String name, String scheduleExpression) {
S3Target target = new S3Target();
target.setPath("s3://raw/" + name);
@@ -0,0 +1,135 @@
package io.floci.aws.services.glue;
import io.floci.aws.services.redshift.RedshiftConnections;
import io.floci.aws.services.redshift.RedshiftService;
import io.floci.aws.services.redshift.model.Cluster;
import io.floci.aws.testing.DockerAvailability;
import io.floci.aws.testing.GlueRequests;
import io.floci.aws.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.ValidatableResponse;
import jakarta.inject.Inject;
import org.awaitility.Awaitility;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import org.junit.jupiter.api.condition.EnabledIfSystemProperty;
import java.sql.Connection;
import java.sql.Statement;
import java.time.Duration;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
/**
* End to end: a Glue crawler with a JDBC target reads a Floci Redshift cluster through a Glue connection
* and writes the tables it finds to the Data Catalog. Needs a Docker daemon, like every Redshift
* integration test.
*/
@QuarkusTest
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
@EnabledIfSystemProperty(named = "nightly.checks.enabled", matches = "true")
class GlueRedshiftCrawlerDockerNightlyIntegrationTest {
private static final String ACCOUNT_ID = "000000000000";
private static final String REGION = "us-east-1";
private static final String CLUSTER_ID = "glue-crawl-rs";
private static final String URL = "jdbc:redshift://" + CLUSTER_ID
+ ".abc123.us-east-1.redshift.amazonaws.com:5439/dev";
@Inject
RedshiftService redshiftService;
@BeforeAll
void createClusterWithTables() throws Exception {
Assumptions.assumeTrue(DockerAvailability.isAvailable(),
"Docker daemon must be available for Glue Redshift crawler integration tests");
RestAssuredJsonUtils.configureAwsContentTypes();
Cluster cluster = redshiftService.createCluster(CLUSTER_ID, "dc2.large", "admin", "Secret123");
try (Connection connection = RedshiftConnections.waitForConnection(cluster);
Statement statement = connection.createStatement()) {
statement.execute("CREATE SCHEMA sales");
statement.execute("CREATE TABLE public.orders (id integer, amount numeric(10,2), note varchar(64))");
statement.execute("CREATE TABLE public.orders_tmp (id integer)");
statement.execute("CREATE TABLE sales.invoices (id bigint, issued_on date)");
statement.execute("CREATE VIEW public.recent_orders AS SELECT id FROM public.orders");
}
}
@AfterAll
void deleteCluster() throws InterruptedException {
if (DockerAvailability.isAvailable()) {
redshiftService.deleteCluster(CLUSTER_ID);
}
}
private static ValidatableResponse call(String action, String body) {
return GlueRequests.call(action, ACCOUNT_ID, REGION, body);
}
private static void createConnection(String name, String password) {
call("CreateConnection", """
{"ConnectionInput": {"Name": "%s", "ConnectionType": "JDBC",
"ConnectionProperties": {"JDBC_CONNECTION_URL": "%s", "USERNAME": "admin", "PASSWORD": "%s"}}}
""".formatted(name, URL, password)).statusCode(200);
}
/**
* Creates the crawler's Data Catalog database here rather than in {@code @BeforeAll}: RestAssured has no
* port for the Quarkus application until a test runs.
*/
private static void crawl(String crawler, String database, String connection, String path,
String exclusions) {
call("CreateDatabase", "{\"DatabaseInput\": {\"Name\": \"" + database + "\"}}").statusCode(200);
call("CreateCrawler", """
{"Name": "%s", "Role": "arn:aws:iam::000000000000:role/glue", "DatabaseName": "%s",
"Targets": {"JdbcTargets": [{"ConnectionName": "%s", "Path": "%s", "Exclusions": [%s]}]}}
""".formatted(crawler, database, connection, path, exclusions)).statusCode(200);
call("StartCrawler", "{\"Name\": \"" + crawler + "\"}").statusCode(200);
Awaitility.await()
.atMost(Duration.ofSeconds(60))
.pollInterval(Duration.ofMillis(500))
.untilAsserted(() -> call("GetCrawler", "{\"Name\": \"" + crawler + "\"}")
.body("Crawler.State", equalTo("READY")));
}
@Test
void crawlsTheTablesAndViewsOfTheIncludePathIntoTheCatalog() {
createConnection("rs-good", "Secret123");
crawl("rs-crawler", "rs_lake", "rs-good", "dev/%", "\"**_tmp\"");
call("GetCrawler", "{\"Name\": \"rs-crawler\"}")
.body("Crawler.LastCrawl.Status", equalTo("SUCCEEDED"));
call("GetTables", "{\"DatabaseName\": \"rs_lake\"}")
.statusCode(200)
.body("TableList.Name", containsInAnyOrder("dev_public_orders", "dev_public_recent_orders",
"dev_sales_invoices"));
call("GetTable", "{\"DatabaseName\": \"rs_lake\", \"Name\": \"dev_public_orders\"}")
.statusCode(200)
.body("Table.StorageDescriptor.Columns.Type", contains("int",
"decimal(10,2)", "string"))
.body("Table.StorageDescriptor.Location", equalTo("dev.public.orders"))
.body("Table.Parameters.classification", equalTo("redshift"));
call("GetTable", "{\"DatabaseName\": \"rs_lake\", \"Name\": \"dev_public_recent_orders\"}")
.body("Table.Parameters.typeOfData", equalTo("view"));
call("GetCrawlerMetrics", "{\"CrawlerNameList\": [\"rs-crawler\"]}")
.body("CrawlerMetricsList[0].TablesCreated", equalTo(3));
}
@Test
void aWrongPasswordFailsTheCrawlWithTheSignInError() {
createConnection("rs-bad", "not-the-password");
crawl("rs-bad-crawler", "rs_lake_bad", "rs-bad", "dev/public/%", "");
call("GetCrawler", "{\"Name\": \"rs-bad-crawler\"}")
.body("Crawler.LastCrawl.Status", equalTo("FAILED"))
.body("Crawler.LastCrawl.ErrorMessage", containsString("rs-bad"));
}
}
@@ -0,0 +1,512 @@
package io.floci.aws.services.glue;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.DatabaseSecretCredentials;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.storage.StorageFactory;
import io.floci.aws.services.glue.JdbcCatalogReader.JdbcColumn;
import io.floci.aws.services.glue.JdbcCatalogReader.JdbcTableSchema;
import io.floci.aws.services.glue.model.AuthenticationConfiguration;
import io.floci.aws.services.glue.model.Column;
import io.floci.aws.services.glue.model.ConnectionInput;
import io.floci.aws.services.glue.model.Crawler;
import io.floci.aws.services.glue.model.CrawlerTargets;
import io.floci.aws.services.glue.model.Database;
import io.floci.aws.services.glue.model.JdbcTarget;
import io.floci.aws.services.glue.model.S3Target;
import io.floci.aws.services.glue.model.SchemaChangePolicy;
import io.floci.aws.services.glue.model.StorageDescriptor;
import io.floci.aws.services.glue.model.Table;
import io.floci.aws.services.glue.schemaregistry.GlueSchemaRegistryService;
import io.floci.aws.services.kms.KmsService;
import io.floci.aws.services.redshift.RedshiftJdbcTargets;
import io.floci.aws.services.redshift.RedshiftJdbcUrl;
import io.floci.aws.services.resourcegroupstagging.ResourceGroupsTaggingService;
import io.floci.aws.testing.InMemoryStorageFactory;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.hasEntry;
import static org.hamcrest.Matchers.hasKey;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.not;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
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 JdbcCrawlRunnerTest {
private static final String REGION = "us-east-1";
private static final String ACCOUNT_ID = "000000000000";
private static final String URL = "jdbc:redshift://analytics.abc123.us-east-1.redshift.amazonaws.com:5439/dev";
private static final String SESSION_URL = "jdbc:postgresql://rs-backend:15439/dev?preferQueryMode=simple";
private GlueService glueService;
private RedshiftJdbcTargets jdbcTargets;
private List<String> sessions;
private List<JdbcTableSchema> tables;
private SQLException readFailure;
private JdbcCrawlRunner runner;
@BeforeEach
void setUp() {
RegionResolver regionResolver = new RegionResolver(REGION, ACCOUNT_ID);
StorageFactory storageFactory = new InMemoryStorageFactory(ACCOUNT_ID);
KmsService kmsService = new KmsService(storageFactory, regionResolver);
glueService = new GlueService(storageFactory, new GlueSchemaRegistryService(storageFactory, regionResolver),
regionResolver, new ResourceGroupsTaggingService(storageFactory), kmsService);
jdbcTargets = mock(RedshiftJdbcTargets.class);
when(jdbcTargets.resolve(eq(ACCOUNT_ID), eq(REGION), any(RedshiftJdbcUrl.class)))
.thenReturn(new RedshiftJdbcTargets.Backend("cluster analytics", "rs-backend", 15439, "dev", "admin"));
sessions = new ArrayList<>();
tables = new ArrayList<>();
JdbcCatalogReader reader = (jdbcUrl, user, password) -> {
sessions.add(jdbcUrl + " " + user + " " + password);
if (readFailure != null) {
throw readFailure;
}
return tables;
};
runner = new JdbcCrawlRunner(glueService, jdbcTargets, kmsService, regionResolver, reader);
glueService.createDatabase(new Database("lake"));
}
private void connection(String name, Map<String, String> properties) {
ConnectionInput input = new ConnectionInput();
input.setName(name);
input.setConnectionType("JDBC");
input.setConnectionProperties(new LinkedHashMap<>(properties));
glueService.createConnection(input, null, REGION);
}
private void passwordConnection(String name) {
connection(name, Map.of("JDBC_CONNECTION_URL", URL, "USERNAME", "crawler", "PASSWORD", "Secret123"));
}
private static JdbcTarget target(String connectionName, String path, String... exclusions) {
JdbcTarget target = new JdbcTarget();
target.setConnectionName(connectionName);
target.setPath(path);
if (exclusions.length > 0) {
target.setExclusions(List.of(exclusions));
}
return target;
}
private Crawler crawler(String name, JdbcTarget... targets) {
CrawlerTargets crawlerTargets = new CrawlerTargets();
crawlerTargets.setJdbcTargets(List.of(targets));
Crawler crawler = new Crawler();
crawler.setName(name);
crawler.setRole("arn:aws:iam::000000000000:role/glue");
crawler.setDatabaseName("lake");
crawler.setTargets(crawlerTargets);
return crawler;
}
private void create(Crawler crawler) {
glueService.createCrawler(crawler, null, REGION);
}
private static JdbcTableSchema table(String schema, String name, JdbcColumn... columns) {
return new JdbcTableSchema(schema, name, false, null, List.of(columns));
}
private static JdbcColumn column(String name, String rawType) {
return new JdbcColumn(name, rawType, null);
}
private CrawlOutcome crawl(String crawlerName) {
return runner.read(crawlerName).apply();
}
private static List<String> columnsOf(Table table) {
List<String> columns = new ArrayList<>();
for (Column column : table.getStorageDescriptor().getColumns()) {
columns.add(column.getName() + ":" + column.getType());
}
return columns;
}
@Test
void readsADataStoreOnlyForACrawlerWithJdbcTargets() {
passwordConnection("analytics");
create(crawler("jdbc", target("analytics", "dev/public/%")));
S3Target s3 = new S3Target();
s3.setPath("s3://raw/data");
CrawlerTargets s3Targets = new CrawlerTargets();
s3Targets.setS3Targets(List.of(s3));
Crawler s3Crawler = crawler("s3");
s3Crawler.setTargets(s3Targets);
create(s3Crawler);
assertTrue(runner.readsDataStore("jdbc"));
assertFalse(runner.readsDataStore("s3"));
assertFalse(runner.readsDataStore("missing"));
}
@Test
void aCrawlerWithoutJdbcTargetsSucceedsWithoutTouchingTheCatalog() {
S3Target s3 = new S3Target();
s3.setPath("s3://raw/data");
CrawlerTargets s3Targets = new CrawlerTargets();
s3Targets.setS3Targets(List.of(s3));
Crawler crawler = crawler("s3");
crawler.setDatabaseName(null);
crawler.setTargets(s3Targets);
create(crawler);
assertEquals(CrawlOutcome.succeeded(), runner.run("s3"));
assertThat(sessions, empty());
}
@Test
void createsACatalogTableForEachSelectedTable() {
passwordConnection("analytics");
create(crawler("orders", target("analytics", "dev/public/%")));
tables.add(table("public", "orders", column("id", "integer"), column("amount", "numeric(10,2)"),
column("note", "character varying(256)"), column("placed_at", "timestamp without time zone"),
column("paid", "boolean")));
tables.add(table("sales", "invoices", column("id", "bigint")));
CrawlOutcome outcome = crawl("orders");
assertEquals(CrawlOutcome.succeeded(1, 0, 0), outcome);
assertEquals(List.of(SESSION_URL + " crawler Secret123"), sessions);
Table created = glueService.getTable("lake", "dev_public_orders");
assertThat(columnsOf(created), contains("id:int", "amount:decimal(10,2)", "note:string",
"placed_at:timestamp", "paid:boolean"));
assertEquals("dev.public.orders", created.getStorageDescriptor().getLocation());
assertEquals("EXTERNAL_TABLE", created.getTableType());
assertThat(created.getParameters(), hasEntry("classification", "redshift"));
assertThat(created.getParameters(), hasEntry("connectionName", "analytics"));
assertThat(created.getParameters(), hasEntry("typeOfData", "table"));
assertThat(created.getParameters(), hasEntry("UPDATED_BY_CRAWLER", "orders"));
assertThat(created.getStorageDescriptor().getParameters(), hasEntry("classification", "redshift"));
assertThat(glueService.getTables("lake"), hasSize(1));
}
@Test
void mapsRedshiftTypesToCatalogTypes() {
passwordConnection("analytics");
create(crawler("types", target("analytics", "dev/public/types")));
tables.add(table("public", "types", column("a", "smallint"), column("b", "bigint"), column("c", "real"),
column("d", "double precision"), column("e", "numeric"), column("f", "character(1)"),
column("g", "text"), column("h", "date"), column("i", "timestamp with time zone"),
column("j", "super"), column("k", "time without time zone")));
crawl("types");
assertThat(columnsOf(glueService.getTable("lake", "dev_public_types")), contains("a:smallint", "b:bigint",
"c:float", "d:double", "e:decimal(18,0)", "f:string", "g:string", "h:date", "i:timestamp",
"j:string", "k:string"));
}
@Test
void appliesTheTablePrefixAndTheExclusions() {
passwordConnection("analytics");
Crawler crawler = crawler("prefixed", target("analytics", "dev/%", "audit/*", "**_tmp"));
crawler.setTablePrefix("rs_");
create(crawler);
tables.add(table("public", "orders", column("id", "integer")));
tables.add(table("public", "orders_tmp", column("id", "integer")));
tables.add(table("audit", "events", column("id", "integer")));
tables.add(table("Sales", "Big-Deals", column("id", "integer")));
CrawlOutcome outcome = crawl("prefixed");
assertEquals(CrawlOutcome.succeeded(2, 0, 0), outcome);
List<String> names = new ArrayList<>();
for (Table table : glueService.getTables("lake")) {
names.add(table.getName());
}
names.sort(null);
assertEquals(List.of("rs_dev_public_orders", "rs_dev_sales_big_deals"), names);
}
@Test
void marksAViewAsAView() {
passwordConnection("analytics");
create(crawler("views", target("analytics", "dev/public/%")));
tables.add(new JdbcTableSchema("public", "recent_orders", true, null, List.of(column("id", "integer"))));
crawl("views");
assertThat(glueService.getTable("lake", "dev_public_recent_orders").getParameters(),
hasEntry("typeOfData", "view"));
}
@Test
void addsRawTypesAndCommentsOnlyWhenTheTargetAsksForThem() {
passwordConnection("analytics");
JdbcTarget withMetadata = target("analytics", "dev/public/orders");
withMetadata.setEnableAdditionalMetadata(List.of("RAWTYPES", "COMMENTS"));
create(crawler("metadata", withMetadata));
create(crawler("plain", target("analytics", "dev/public/orders")));
tables.add(new JdbcTableSchema("public", "orders", false, "Orders placed online",
List.of(new JdbcColumn("id", "integer", "order key"))));
crawl("metadata");
Table rich = glueService.getTable("lake", "dev_public_orders");
Column id = rich.getStorageDescriptor().getColumns().getFirst();
assertThat(id.getParameters(), hasEntry("aws:RawType", "integer"));
assertThat(id.getParameters(), hasEntry("aws:RawColumnComment", "order key"));
assertThat(rich.getParameters(), hasEntry("aws:RawTableComment", "Orders placed online"));
glueService.deleteTable("lake", "dev_public_orders");
crawl("plain");
Table plain = glueService.getTable("lake", "dev_public_orders");
assertNull(plain.getStorageDescriptor().getColumns().getFirst().getParameters());
assertThat(plain.getParameters(), not(hasKey("aws:RawTableComment")));
}
@Test
void aSecondCrawlUpdatesOnlyTheTablesWhoseSchemaChanged() {
passwordConnection("analytics");
create(crawler("orders", target("analytics", "dev/public/%")));
tables.add(table("public", "orders", column("id", "integer")));
tables.add(table("public", "customers", column("id", "integer")));
crawl("orders");
tables.set(0, table("public", "orders", column("id", "integer"), column("total", "bigint")));
CrawlOutcome second = crawl("orders");
assertEquals(CrawlOutcome.succeeded(0, 1, 0), second);
assertThat(columnsOf(glueService.getTable("lake", "dev_public_orders")), contains("id:int", "total:bigint"));
assertEquals(CrawlOutcome.succeeded(0, 0, 0), crawl("orders"));
}
@Test
void anUpdateBehaviorOfLogLeavesExistingTablesAlone() {
passwordConnection("analytics");
Crawler crawler = crawler("orders", target("analytics", "dev/public/%"));
SchemaChangePolicy policy = new SchemaChangePolicy();
policy.setUpdateBehavior("LOG");
crawler.setSchemaChangePolicy(policy);
create(crawler);
tables.add(table("public", "orders", column("id", "integer")));
crawl("orders");
tables.set(0, table("public", "orders", column("id", "integer"), column("total", "bigint")));
CrawlOutcome second = crawl("orders");
assertEquals(CrawlOutcome.succeeded(0, 0, 0), second);
assertThat(columnsOf(glueService.getTable("lake", "dev_public_orders")), contains("id:int"));
}
@Test
void readsTheCredentialsFromTheSecretTheConnectionNames() {
connection("by-secret", Map.of("JDBC_CONNECTION_URL", URL, "SECRET_ID", "rs-secret"));
when(jdbcTargets.credentialsFromSecret("rs-secret", REGION))
.thenReturn(new DatabaseSecretCredentials("secret-user", "secret-pass"));
create(crawler("secret", target("by-secret", "dev/public/%")));
crawl("secret");
assertEquals(List.of(SESSION_URL + " secret-user secret-pass"), sessions);
}
@Test
void readsTheCredentialsFromTheAuthenticationConfigurationSecret() {
ConnectionInput input = new ConnectionInput();
input.setName("by-auth");
input.setConnectionType("JDBC");
input.setConnectionProperties(new LinkedHashMap<>(Map.of("JDBC_CONNECTION_URL", URL)));
AuthenticationConfiguration authentication = new AuthenticationConfiguration();
authentication.setAuthenticationType("BASIC");
authentication.setSecretArn("arn:aws:secretsmanager:us-east-1:000000000000:secret:rs-AbCdEf");
input.setAuthenticationConfiguration(authentication);
glueService.createConnection(input, null, REGION);
when(jdbcTargets.credentialsFromSecret("arn:aws:secretsmanager:us-east-1:000000000000:secret:rs-AbCdEf",
REGION)).thenReturn(new DatabaseSecretCredentials("auth-user", "auth-pass"));
create(crawler("auth", target("by-auth", "dev/public/%")));
crawl("auth");
assertEquals(List.of(SESSION_URL + " auth-user auth-pass"), sessions);
}
@Test
void aMissingConnectionFailsBeforeReadingAnything() {
create(crawler("orphan", target("missing", "dev/public/%")));
AwsException e = assertThrows(AwsException.class, () -> runner.read("orphan"));
assertThat(e.getMessage(), containsString("missing"));
assertThat(sessions, empty());
}
@Test
void aConnectionWithoutCredentialsFails() {
connection("anonymous", Map.of("JDBC_CONNECTION_URL", URL));
create(crawler("anonymous", target("anonymous", "dev/public/%")));
IllegalStateException e = assertThrows(IllegalStateException.class, () -> runner.read("anonymous"));
assertThat(e.getMessage(), containsString("anonymous"));
assertThat(sessions, empty());
}
@Test
void aConnectionToAnotherEngineFails() {
connection("mysql", Map.of("JDBC_CONNECTION_URL", "jdbc:mysql://db.example.com:3306/shop",
"USERNAME", "u", "PASSWORD", "p"));
create(crawler("mysql", target("mysql", "shop/%")));
IllegalStateException e = assertThrows(IllegalStateException.class, () -> runner.read("mysql"));
assertThat(e.getMessage(), containsString("Redshift"));
}
@Test
void badCredentialsOrAnUnreachableEndpointFailWithTheDriverMessageAndWriteNothing() {
passwordConnection("analytics");
create(crawler("orders", target("analytics", "dev/public/%")));
readFailure = new SQLException("password authentication failed for user \"crawler\"", "28P01");
IllegalStateException e = assertThrows(IllegalStateException.class, () -> runner.read("orders"));
assertThat(e.getMessage(), containsString("password authentication failed"));
assertThat(e.getMessage(), containsString("analytics"));
assertThat(glueService.getTables("lake"), empty());
}
@Test
void aFailingTargetWritesNothingFromTheTargetsThatSucceeded() {
passwordConnection("analytics");
create(crawler("two", target("analytics", "dev/public/%"), target("missing", "dev/sales/%")));
tables.add(table("public", "orders", column("id", "integer")));
assertThrows(AwsException.class, () -> runner.read("two"));
assertThat(glueService.getTables("lake"), empty());
}
@Test
void aMissingCatalogDatabaseFailsTheWrite() {
passwordConnection("analytics");
Crawler crawler = crawler("nowhere", target("analytics", "dev/public/%"));
crawler.setDatabaseName("absent");
create(crawler);
tables.add(table("public", "orders", column("id", "integer")));
CrawlRunner.CatalogWrite write = runner.read("nowhere");
AwsException e = assertThrows(AwsException.class, write::apply);
assertThat(e.getMessage(), containsString("absent"));
}
@Test
void anIncludePathNamingAnotherDatabaseFailsBeforeReading() {
passwordConnection("analytics");
create(crawler("elsewhere", target("analytics", "missing/public/%")));
tables.add(table("public", "orders", column("id", "integer")));
IllegalStateException e = assertThrows(IllegalStateException.class, () -> runner.read("elsewhere"));
assertThat(e.getMessage(), containsString("missing"));
assertThat(e.getMessage(), containsString("dev"));
assertThat(sessions, empty());
}
/** Adds a table parameter and a comment and parameter on the first column, as a user editing the table would. */
private void annotate(String tableName) {
Table table = glueService.getTable("lake", tableName);
Map<String, String> parameters = new LinkedHashMap<>(table.getParameters());
parameters.put("owner_team", "data");
table.setParameters(parameters);
Column first = table.getStorageDescriptor().getColumns().getFirst();
first.setComment("primary key");
first.setParameters(Map.of("pii", "false"));
glueService.updateTable("lake", table, null, false);
}
@Test
void anUnchangedSourceKeepsTheMetadataAUserAdded() {
passwordConnection("analytics");
create(crawler("orders", target("analytics", "dev/public/%")));
tables.add(table("public", "orders", column("id", "integer")));
crawl("orders");
annotate("dev_public_orders");
CrawlOutcome second = crawl("orders");
assertEquals(CrawlOutcome.succeeded(0, 0, 0), second);
Table table = glueService.getTable("lake", "dev_public_orders");
assertThat(table.getParameters(), hasEntry("owner_team", "data"));
assertEquals("primary key", table.getStorageDescriptor().getColumns().getFirst().getComment());
}
@Test
void aSchemaChangeKeepsTheMetadataAUserAdded() {
passwordConnection("analytics");
create(crawler("orders", target("analytics", "dev/public/%")));
tables.add(table("public", "orders", column("id", "integer")));
crawl("orders");
annotate("dev_public_orders");
tables.set(0, table("public", "orders", column("id", "integer"), column("total", "bigint")));
CrawlOutcome second = crawl("orders");
assertEquals(CrawlOutcome.succeeded(0, 1, 0), second);
Table table = glueService.getTable("lake", "dev_public_orders");
assertThat(columnsOf(table), contains("id:int", "total:bigint"));
assertThat(table.getParameters(), hasEntry("owner_team", "data"));
assertThat(table.getParameters(), hasEntry("classification", "redshift"));
Column id = table.getStorageDescriptor().getColumns().getFirst();
assertEquals("primary key", id.getComment());
assertThat(id.getParameters(), hasEntry("pii", "false"));
}
@Test
void aStoredColumnWithoutATypeIsReplacedByTheCrawledSchema() {
passwordConnection("analytics");
create(crawler("orders", target("analytics", "dev/public/%")));
tables.add(table("public", "orders", column("id", "integer")));
crawl("orders");
Table untyped = glueService.getTable("lake", "dev_public_orders");
StorageDescriptor descriptor = untyped.getStorageDescriptor();
descriptor.setColumns(List.of(new Column("id", null)));
glueService.updateTable("lake", untyped, null, false);
CrawlOutcome outcome = crawl("orders");
assertEquals(CrawlOutcome.succeeded(0, 1, 0), outcome);
assertThat(columnsOf(glueService.getTable("lake", "dev_public_orders")), contains("id:int"));
}
@Test
void truncatesLongCommentsOnCodePointBoundaries() {
passwordConnection("analytics");
JdbcTarget withComments = target("analytics", "dev/public/orders");
withComments.setEnableAdditionalMetadata(List.of("COMMENTS"));
create(crawler("emoji", withComments));
String comment = "a".repeat(253) + "😀";
tables.add(new JdbcTableSchema("public", "orders", false, comment,
List.of(new JdbcColumn("id", "integer", comment))));
crawl("emoji");
Table table = glueService.getTable("lake", "dev_public_orders");
String expected = "a".repeat(253);
assertEquals(expected, table.getParameters().get("aws:RawTableComment"));
assertEquals(expected, table.getStorageDescriptor().getColumns().getFirst().getParameters()
.get("aws:RawColumnComment"));
}
}
@@ -0,0 +1,133 @@
package io.floci.aws.services.glue;
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.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
class JdbcIncludePathTest {
private static JdbcIncludePath path(String path, String... exclusions) {
return JdbcIncludePath.parse(path, List.of(exclusions));
}
@Test
void namesTheDatabase() {
assertEquals("dev", path("dev/public/%").database());
}
@Test
void percentAsTheTableSelectsEveryTableOfTheSchema() {
JdbcIncludePath path = path("dev/public/%");
assertTrue(path.selects("public", "orders"));
assertFalse(path.selects("sales", "orders"));
}
@Test
void percentAsTheSchemaSelectsEveryTableOfEverySchema() {
JdbcIncludePath path = path("dev/%");
assertTrue(path.selects("public", "orders"));
assertTrue(path.selects("sales", "invoices"));
}
@Test
void aSchemaWithoutATableSelectsEveryTableOfThatSchema() {
JdbcIncludePath path = path("dev/public");
assertTrue(path.selects("public", "orders"));
assertFalse(path.selects("sales", "orders"));
}
@Test
void aFullPathSelectsOneTableAndIsCaseSensitive() {
JdbcIncludePath path = path("dev/public/orders");
assertTrue(path.selects("public", "orders"));
assertFalse(path.selects("public", "Orders"));
assertFalse(path.selects("public", "orders_archive"));
}
@Test
void percentInsideASegmentMatchesAnyRunOfCharacters() {
JdbcIncludePath path = path("dev/public/order%");
assertTrue(path.selects("public", "orders"));
assertTrue(path.selects("public", "order_items"));
assertFalse(path.selects("public", "customers"));
}
@Test
void underscoreInAPathIsALiteralCharacter() {
JdbcIncludePath path = path("dev/public/order_items");
assertFalse(path.selects("public", "orderXitems"));
}
@Test
void refusesAPercentDatabase() {
IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> path("%/public/%"));
assertTrue(e.getMessage().contains("%/public/%"), e.getMessage());
}
@Test
void refusesAPathWithoutASchemaOrWithTooManySegments() {
assertThrows(IllegalArgumentException.class, () -> path("dev"));
assertThrows(IllegalArgumentException.class, () -> path("dev/public/orders/extra"));
assertThrows(IllegalArgumentException.class, () -> path(""));
assertThrows(IllegalArgumentException.class, () -> JdbcIncludePath.parse(null, List.of()));
}
@Test
void exclusionsMatchTableNamesRelativeToASchemaPath() {
JdbcIncludePath path = path("dev/public/%", "HR*", "Market_*", "**_Table");
assertFalse(path.selects("public", "HR_staff"));
assertFalse(path.selects("public", "Market_share"));
assertFalse(path.selects("public", "Sales_Table"));
assertTrue(path.selects("public", "orders"));
}
@Test
void exclusionsMatchSchemaAndTableRelativeToADatabasePath() {
JdbcIncludePath path = path("dev/%", "audit/*");
assertFalse(path.selects("audit", "events"));
assertTrue(path.selects("public", "events"));
}
@Test
void singleStarDoesNotCrossASchemaBoundaryButDoubleStarDoes() {
assertTrue(path("dev/%", "*").selects("public", "orders"));
assertFalse(path("dev/%", "**").selects("public", "orders"));
assertFalse(path("dev/%", "**orders").selects("public", "orders"));
}
@Test
void exclusionsSupportQuestionMarkBracketsAndGroups() {
JdbcIncludePath path = path("dev/public/%", "tmp?", "log[0-9]", "stage[!x]", "{a,b}_copy");
assertFalse(path.selects("public", "tmp1"));
assertTrue(path.selects("public", "tmp12"));
assertFalse(path.selects("public", "log7"));
assertFalse(path.selects("public", "stagey"));
assertTrue(path.selects("public", "stagex"));
assertFalse(path.selects("public", "a_copy"));
assertFalse(path.selects("public", "b_copy"));
assertTrue(path.selects("public", "c_copy"));
}
@Test
void anEscapedCharacterInAnExclusionIsLiteral() {
JdbcIncludePath path = path("dev/public/%", "tmp\\*");
assertFalse(path.selects("public", "tmp*"));
assertTrue(path.selects("public", "tmp1"));
}
}
@@ -0,0 +1,39 @@
package io.floci.aws.services.glue;
import io.floci.aws.services.glue.JdbcCatalogReader.JdbcColumn;
import io.floci.aws.services.glue.JdbcCatalogReader.JdbcTableSchema;
import io.floci.aws.services.glue.PostgresCatalogReader.CatalogRow;
import org.junit.jupiter.api.Test;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
class PostgresCatalogReaderTest {
@Test
void groupsColumnsByTableInQueryOrder() {
List<JdbcTableSchema> tables = PostgresCatalogReader.group(List.of(
new CatalogRow("public", "orders", false, "placed orders", "id", "integer", "key"),
new CatalogRow("public", "orders", false, "placed orders", "total", "bigint", null),
new CatalogRow("public", "recent", true, null, "id", "integer", null)));
assertEquals(List.of(
new JdbcTableSchema("public", "orders", false, "placed orders", List.of(
new JdbcColumn("id", "integer", "key"), new JdbcColumn("total", "bigint", null))),
new JdbcTableSchema("public", "recent", true, null, List.of(new JdbcColumn("id", "integer", null)))),
tables);
}
@Test
void keepsApartTablesWhoseQuotedNamesJoinToTheSameDottedName() {
List<JdbcTableSchema> tables = PostgresCatalogReader.group(List.of(
new CatalogRow("a", "b.c", false, null, "left_id", "integer", null),
new CatalogRow("a.b", "c", false, null, "right_id", "bigint", null)));
assertEquals(List.of(
new JdbcTableSchema("a", "b.c", false, null, List.of(new JdbcColumn("left_id", "integer", null))),
new JdbcTableSchema("a.b", "c", false, null, List.of(new JdbcColumn("right_id", "bigint", null)))),
tables);
}
}