mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(athena): run Iceberg CREATE TABLE, DML and VACUUM through Glue's Iceberg REST catalog (#8488)
This commit is contained in:
1 parent
dbfe6e0769
commit
8206115dc8
27 files changed
+2063
-177
No files matched your search
+13
-2
@@ -159,7 +159,7 @@ Not yet supported:
|
||||
|
||||
Hive DDL runs against the Glue Data Catalog rather than the query engine, as it does on Athena, and its query reports `StatementType` `DDL`:
|
||||
|
||||
- `CREATE EXTERNAL TABLE [IF NOT EXISTS]` creates the Glue table: its columns and `PARTITIONED BY` keys, `COMMENT`, `CLUSTERED BY ... INTO n BUCKETS`, `ROW FORMAT DELIMITED` (stored as the `LazySimpleSerDe` parameters Hive uses, `field.delim` and the rest) or `ROW FORMAT SERDE ... WITH SERDEPROPERTIES`, `STORED AS` (`TEXTFILE`, the default, `PARQUET`, `ORC`, `AVRO`, `SEQUENCEFILE`, `RCFILE`, `ION`, or `INPUTFORMAT ... OUTPUTFORMAT ...`), `LOCATION` and `TBLPROPERTIES`. Names are lower-cased and string literals take Hive's backslash escapes, so `FIELDS TERMINATED BY '\t'` stores a tab. `SORTED BY` is kept as the table's sort columns. Every format is registered, but Floci's query engine reads only Parquet, JSON and delimited text (see [Format inference](#format-inference)): an `ORC`, `AVRO`, `ION`, `RCFILE` or `SEQUENCEFILE` table serves other Glue clients, such as Spark on EMR, and Athena queries on it fail. A `CREATE TABLE` without `EXTERNAL` fails unless it creates an Iceberg table or is a `CREATE TABLE AS`, which go to the query engine.
|
||||
- `CREATE EXTERNAL TABLE [IF NOT EXISTS]` creates the Glue table: its columns and `PARTITIONED BY` keys, `COMMENT`, `CLUSTERED BY ... INTO n BUCKETS`, `ROW FORMAT DELIMITED` (stored as the `LazySimpleSerDe` parameters Hive uses, `field.delim` and the rest) or `ROW FORMAT SERDE ... WITH SERDEPROPERTIES`, `STORED AS` (`TEXTFILE`, the default, `PARQUET`, `ORC`, `AVRO`, `SEQUENCEFILE`, `RCFILE`, `ION`, or `INPUTFORMAT ... OUTPUTFORMAT ...`), `LOCATION` and `TBLPROPERTIES`. Names are lower-cased and string literals take Hive's backslash escapes, so `FIELDS TERMINATED BY '\t'` stores a tab. `SORTED BY` is kept as the table's sort columns. Every format is registered, but Floci's query engine reads only Parquet, JSON and delimited text (see [Format inference](#format-inference)): an `ORC`, `AVRO`, `ION`, `RCFILE` or `SEQUENCEFILE` table serves other Glue clients, such as Spark on EMR, and Athena queries on it fail. A `CREATE TABLE` without `EXTERNAL` fails unless it creates an Iceberg table (see [Iceberg tables](#iceberg-tables)) or is a `CREATE TABLE AS`, which goes to the query engine.
|
||||
- `DROP TABLE [IF EXISTS]` removes a Hive table's metadata and leaves its data in S3. An Iceberg table is a managed table, so dropping it deletes the objects under its location too, as Athena does.
|
||||
- `ALTER TABLE ... ADD [IF NOT EXISTS] PARTITION (...) [LOCATION '...'] [PARTITION ...]` creates the partitions; one without a `LOCATION` is placed at `<table location>/key=value/...`. `ALTER TABLE ... DROP [IF EXISTS] PARTITION (...)[, PARTITION ...]` deletes them. A partition specification has to name every partition key.
|
||||
- `MSCK REPAIR TABLE` lists the table's location and adds a partition for every Hive-style `key=value/...` folder path that holds an object and has none yet, with that folder, spelled as it is in S3, as the partition's location. A folder name with an invalid escape is skipped. Like Athena it only adds partitions, never removes them.
|
||||
@@ -167,6 +167,17 @@ Hive DDL runs against the Glue Data Catalog rather than the query engine, as it
|
||||
|
||||
Without `IF [NOT] EXISTS`, a table or partition that already exists, or does not, fails the query. Other `ALTER TABLE` statements are not supported.
|
||||
|
||||
## Iceberg tables
|
||||
|
||||
Athena manages Iceberg tables through AWS Glue's Iceberg REST catalog, which Floci serves (see [Glue's Iceberg REST endpoint](glue.md#iceberg-rest-endpoint)):
|
||||
|
||||
- `CREATE TABLE [IF NOT EXISTS] [db.]table (col type [COMMENT '...'], ...) [PARTITIONED BY (col | transform, ...)] LOCATION 's3://...' TBLPROPERTIES ('table_type'='ICEBERG' [, ...])` creates an empty Iceberg v2 table: a Glue table whose `table_type` is `ICEBERG` and whose `metadata_location` names its first metadata file. The partition transforms are `year(ts)`, `month(ts)`, `day(ts)`, `hour(ts)`, `bucket(N, col)` and `truncate(L, col)`, each on the column types Athena lists for it (`year`, `month` and `day` on a date or timestamp, `hour` on a timestamp, `bucket` on an int, bigint, decimal, date, timestamp, string or binary, `truncate` on an int, bigint, decimal or string); `bucket` and `truncate` need a positive width. As on Athena, only Athena's Iceberg table properties are accepted (`format`, `write_compression`, `optimize_rewrite_data_file_threshold`, `optimize_rewrite_delete_file_threshold`, `vacuum_min_snapshots_to_keep`, `vacuum_max_snapshot_age_seconds`, `vacuum_max_metadata_files_to_keep` and `write_data_path_enabled`), and `tinyint`, `smallint` and `char` columns are refused. Floci writes data files as Parquet, so a `format` other than `parquet` is refused. The query reports `StatementType` `DDL`.
|
||||
- `INSERT INTO`, `UPDATE`, `DELETE FROM` and `MERGE INTO` on an Iceberg table run in the query engine, which attaches Glue's Iceberg REST catalog for the statement, with a token for the calling account and Region that is revoked when the statement ends, and writes the table through it. DuckDB writes the data, delete and manifest files, and each commit moves the Glue table's `metadata_location`, so Spark's `GlueCatalog` and later Athena queries read it.
|
||||
- `VACUUM [db.]table` expires the snapshots older than `vacuum_max_snapshot_age_seconds` (default 432000, 5 days), except the newest `vacuum_min_snapshots_to_keep` (default 1) of each branch and every tagged snapshot. It then deletes the table's metadata files beyond the newest `vacuum_max_metadata_files_to_keep` (default 100), and every file under the table's location that no remaining snapshot references and that is older than the maximum snapshot age, orphan files included. Files are deleted only from a bucket the calling account owns. While one of Floci's own writes to the table is running, `VACUUM` expires snapshots but leaves the files for its next run; another engine's write still in flight is protected only by the age, as on Athena. A table at a bucket's root has its snapshots expired but no files deleted.
|
||||
- `DROP TABLE` deletes an Iceberg table's files too (see [Hive DDL](#hive-ddl)).
|
||||
|
||||
`CREATE TABLE AS` with `table_type = 'ICEBERG'` and `OPTIMIZE` are not supported yet.
|
||||
|
||||
## Configuration
|
||||
|
||||
| Property | Default | Description |
|
||||
@@ -257,6 +268,6 @@ See [S3 Select](s3.md#s3-select) for details on execution modes and supported SQ
|
||||
|
||||
Set `FLOCI_SERVICES_ATHENA_MOCK=true` to skip DuckDB entirely for Athena. In this mode queries transition to `SUCCEEDED` immediately with an empty result set, useful for unit tests that only exercise the Athena state machine, not the query results.
|
||||
|
||||
`CREATE DATABASE` and the [Hive DDL](#hive-ddl) statements still change the Glue catalog in mock mode, and `SHOW PARTITIONS` still returns its rows, since none of them needs the sidecar.
|
||||
`CREATE DATABASE`, the [Hive DDL](#hive-ddl) statements and an Iceberg `CREATE TABLE` still change the Glue catalog in mock mode, and `SHOW PARTITIONS` still returns its rows, since none of them needs the sidecar. Writes to an Iceberg table and `VACUUM` need it, so they succeed without effect.
|
||||
|
||||
When mock mode is enabled the sidecar does **not** start. S3 Select will use the Java evaluator for CSV and JSON. Parquet queries will fail unless `FLOCI_SERVICES_DUCK_URL` points to an already-running floci-duck instance.
|
||||
@@ -349,7 +349,9 @@ spark = (SparkSession.builder
|
||||
|
||||
The operations are the twelve AWS lists: `GetConfig`, `ListNamespaces`, `CreateNamespace`, `LoadNamespaceMetadata`, `UpdateNamespaceProperties`, `DeleteNamespace`, `ListTables`, `CreateTable`, `LoadTable`, `TableExists`, `UpdateTable` and `DeleteTable`. A namespace is a Glue database (single-level, as on AWS); its `location` and `comment` properties are the database's `LocationUri` and `Description`. A table is a Glue table whose `Parameters.table_type` is `ICEBERG` and whose `Parameters.metadata_location` names its current metadata file in S3. The writer writes data files and manifests itself. Each commit checks the request's requirements, applies its updates, writes the next metadata file beside the last one (`<location>/metadata/00001-<uuid>.metadata.json`), and moves `metadata_location` to it, with `previous_metadata_location` set to the old one. If the Glue table changed since the commit's base, the commit is refused with `CommitFailedException` (409). A commit that fails after writing its metadata file (Glue refuses it, or it was not the last commit) removes that file again. Because every commit lands on the Glue table, Spark's `GlueCatalog` and Athena read each committed snapshot. A staged create (`stage-create`) creates nothing until its commit (`assert-create`), the way Spark and DuckDB create tables. A table with no location takes its namespace's location plus its name. `DeleteTable` drops the Glue table and leaves its files in S3.
|
||||
|
||||
Not yet: IAM policies are not checked on this endpoint, so under IAM enforcement it answers only the account's root credentials and refuses IAM principals (`ForbiddenException`, 403) rather than let them through unchecked. Other accounts' catalogs and nested catalogs (`s3tablescatalog/<bucket>`) are not served. DuckDB signs SigV4 catalog requests only over HTTPS, so DuckDB attaches this endpoint with SigV4 only when Floci serves TLS (`floci.tls.enabled`).
|
||||
[Athena](athena.md#iceberg-tables) creates and writes Iceberg tables through this endpoint: its query engine attaches it with a bearer token Floci issues for one statement, acting as the calling account in its Region.
|
||||
|
||||
Not yet: IAM policies are not checked on this endpoint, so under IAM enforcement it answers only the account's root credentials and Floci's own query engine, and refuses IAM principals (`ForbiddenException`, 403) rather than let them through unchecked. Other accounts' catalogs and nested catalogs (`s3tablescatalog/<bucket>`) are not served. DuckDB signs SigV4 catalog requests only over HTTPS, so DuckDB attaches this endpoint with SigV4 only when Floci serves TLS (`floci.tls.enabled`).
|
||||
|
||||
## Configuration
|
||||
|
||||
|
||||
@@ -42,6 +42,12 @@ public class AccountContextFilter implements ContainerRequestFilter {
|
||||
*/
|
||||
public static final String PINNED_ACCOUNT_PROPERTY = AccountContextFilter.class.getName() + ".accountId";
|
||||
|
||||
/**
|
||||
* Set beside {@link #PINNED_ACCOUNT_PROPERTY} by a filter that resolved the request to a Region as well (a token
|
||||
* that acts in one), which the request then runs in instead of the default Region.
|
||||
*/
|
||||
public static final String PINNED_REGION_PROPERTY = AccountContextFilter.class.getName() + ".region";
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(AccountContextFilter.class);
|
||||
|
||||
/** The signing names S3 answers to; an S3 client expects S3's XML error document. */
|
||||
@@ -90,7 +96,8 @@ public class AccountContextFilter implements ContainerRequestFilter {
|
||||
requestContext.setAccountId(pinnedAccount.toString());
|
||||
requestContext.setAccessKeyId(null);
|
||||
requestContext.setSessionToken(null);
|
||||
applyRegion(regionResolver.resolveRegionFromAuth(null));
|
||||
Object pinnedRegion = ctx.getProperty(PINNED_REGION_PROPERTY);
|
||||
applyRegion(pinnedRegion != null ? pinnedRegion.toString() : regionResolver.resolveRegionFromAuth(null));
|
||||
return;
|
||||
}
|
||||
MultivaluedMap<String, String> query = ResteasyRequests.queryParameters(ctx);
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package io.floci.aws.services.athena;
|
||||
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.services.glue.iceberg.IcebergSchemas;
|
||||
import io.floci.aws.services.glue.model.Column;
|
||||
import io.floci.aws.services.glue.model.StorageDescriptor;
|
||||
import io.floci.aws.services.glue.model.Table;
|
||||
@@ -15,9 +16,10 @@ import java.util.Set;
|
||||
/**
|
||||
* Parses the Hive DDL statements Athena runs against the Glue Data Catalog rather than against
|
||||
* data: {@code CREATE EXTERNAL TABLE}, {@code DROP TABLE}, {@code ALTER TABLE ... ADD|DROP
|
||||
* PARTITION}, {@code MSCK REPAIR TABLE} and {@code SHOW PARTITIONS}. {@link #parse} answers null
|
||||
* for every other statement, an Iceberg {@code CREATE TABLE} and {@code CREATE TABLE AS} included,
|
||||
* so those keep going to the query engine.
|
||||
* PARTITION}, {@code MSCK REPAIR TABLE} and {@code SHOW PARTITIONS}, and the Iceberg {@code CREATE TABLE ...
|
||||
* TBLPROPERTIES ('table_type'='ICEBERG')} and {@code VACUUM}, which Floci runs against Glue's Iceberg catalog.
|
||||
* {@link #parse} answers null for every other statement, {@code CREATE TABLE AS} included, so those keep going to
|
||||
* the query engine.
|
||||
*
|
||||
* <p>Names are lower-cased, as Athena stores them in Glue. String literals take Hive's backslash
|
||||
* escapes, so {@code FIELDS TERMINATED BY '\t'} stores a tab.
|
||||
@@ -25,7 +27,7 @@ import java.util.Set;
|
||||
final class AthenaHiveDdl {
|
||||
|
||||
sealed interface Statement permits CreateTable, DropTable, AddPartitions, DropPartitions, RepairTable,
|
||||
ShowPartitions {
|
||||
ShowPartitions, CreateIcebergTable, Vacuum {
|
||||
TableRef ref();
|
||||
}
|
||||
|
||||
@@ -55,6 +57,16 @@ final class AthenaHiveDdl {
|
||||
record ShowPartitions(TableRef ref) implements Statement {
|
||||
}
|
||||
|
||||
/** An Iceberg {@code CREATE TABLE}: its columns, partition transforms, location and other table properties. */
|
||||
record CreateIcebergTable(TableRef ref, boolean ifNotExists, List<Column> columns,
|
||||
List<IcebergSchemas.PartitionField> partitioning, String location,
|
||||
Map<String, String> properties) implements Statement {
|
||||
}
|
||||
|
||||
/** {@code VACUUM}: expires an Iceberg table's old snapshots. */
|
||||
record Vacuum(TableRef ref) implements Statement {
|
||||
}
|
||||
|
||||
private record Format(String inputFormat, String outputFormat, String serde) {
|
||||
}
|
||||
|
||||
@@ -102,9 +114,12 @@ final class AthenaHiveDdl {
|
||||
return finish(createTable());
|
||||
}
|
||||
if (peekWords("CREATE", "TABLE")) {
|
||||
if (isIcebergOrCtas()) {
|
||||
if (isCtas()) {
|
||||
return null;
|
||||
}
|
||||
if (isIceberg()) {
|
||||
return finish(createIcebergTable());
|
||||
}
|
||||
throw invalid("Athena creates a table without EXTERNAL only as an Iceberg table "
|
||||
+ "(TBLPROPERTIES ('table_type'='ICEBERG')); use CREATE EXTERNAL TABLE for a Hive table");
|
||||
}
|
||||
@@ -112,6 +127,9 @@ final class AthenaHiveDdl {
|
||||
boolean ifExists = acceptWords("IF", "EXISTS");
|
||||
return finish(new DropTable(tableRef(), ifExists));
|
||||
}
|
||||
if (acceptWords("VACUUM")) {
|
||||
return finish(new Vacuum(tableRef()));
|
||||
}
|
||||
if (acceptWords("MSCK", "REPAIR", "TABLE")) {
|
||||
return finish(new RepairTable(tableRef()));
|
||||
}
|
||||
@@ -145,7 +163,8 @@ final class AthenaHiveDdl {
|
||||
return statement;
|
||||
}
|
||||
|
||||
private boolean isIcebergOrCtas() {
|
||||
/** A {@code CREATE TABLE AS} (with a {@code WITH (...)} property list or not), which the query engine runs. */
|
||||
private boolean isCtas() {
|
||||
for (int i = position; i < tokens.size(); i++) {
|
||||
Token token = tokens.get(i);
|
||||
Token following = i + 1 < tokens.size() ? tokens.get(i + 1) : null;
|
||||
@@ -154,15 +173,76 @@ final class AthenaHiveDdl {
|
||||
if (token.isWord("AS") && query || token.isWord("WITH") && following != null && following.is("(")) {
|
||||
return true;
|
||||
}
|
||||
if (token.kind() == Kind.STRING && "table_type".equalsIgnoreCase(token.text())
|
||||
&& i + 2 < tokens.size() && tokens.get(i + 1).is("=")
|
||||
&& "ICEBERG".equalsIgnoreCase(tokens.get(i + 2).text())) {
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/** A {@code CREATE TABLE} whose table properties make it an Iceberg table. */
|
||||
private boolean isIceberg() {
|
||||
for (int i = position; i + 2 < tokens.size(); i++) {
|
||||
if (tokens.get(i).kind() == Kind.STRING && "table_type".equalsIgnoreCase(tokens.get(i).text())
|
||||
&& tokens.get(i + 1).is("=") && "ICEBERG".equalsIgnoreCase(tokens.get(i + 2).text())) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private CreateIcebergTable createIcebergTable() {
|
||||
expectWords("CREATE", "TABLE");
|
||||
boolean ifNotExists = acceptWords("IF", "NOT", "EXISTS");
|
||||
TableRef ref = tableRef();
|
||||
expect("(");
|
||||
List<Column> columns = columns();
|
||||
String location = null;
|
||||
List<IcebergSchemas.PartitionField> partitioning = new ArrayList<>();
|
||||
Map<String, String> properties = new LinkedHashMap<>();
|
||||
while (position < tokens.size() && !tokens.get(position).is(";")) {
|
||||
if (acceptWords("PARTITIONED", "BY")) {
|
||||
expect("(");
|
||||
partitioning = partitionTransforms();
|
||||
} else if (acceptWords("LOCATION")) {
|
||||
location = string();
|
||||
} else if (acceptWords("TBLPROPERTIES")) {
|
||||
properties.putAll(properties());
|
||||
} else {
|
||||
throw invalid("Unexpected '" + tokens.get(position).text() + "' in CREATE TABLE");
|
||||
}
|
||||
}
|
||||
properties.keySet().removeIf(key -> key.equalsIgnoreCase("table_type"));
|
||||
return new CreateIcebergTable(ref, ifNotExists, columns, partitioning, location, properties);
|
||||
}
|
||||
|
||||
/**
|
||||
* An Iceberg table's {@code PARTITIONED BY} entries, after the opening parenthesis: a column, or a transform of
|
||||
* one ({@code day(ts)}, {@code bucket(16, id)}, {@code truncate(4, name)}).
|
||||
*/
|
||||
private List<IcebergSchemas.PartitionField> partitionTransforms() {
|
||||
List<IcebergSchemas.PartitionField> fields = new ArrayList<>();
|
||||
do {
|
||||
String name = identifier();
|
||||
if (accept("(")) {
|
||||
Integer width = null;
|
||||
if (position < tokens.size() && tokens.get(position).kind() == Kind.NUMBER) {
|
||||
String argument = next().text();
|
||||
try {
|
||||
width = Integer.parseInt(argument);
|
||||
} catch (NumberFormatException e) {
|
||||
throw invalid("The width of partition transform " + name + " must be a whole number: "
|
||||
+ argument);
|
||||
}
|
||||
expect(",");
|
||||
}
|
||||
fields.add(new IcebergSchemas.PartitionField(name, width, identifier()));
|
||||
expect(")");
|
||||
} else {
|
||||
fields.add(new IcebergSchemas.PartitionField("identity", null, name));
|
||||
}
|
||||
} while (accept(","));
|
||||
expect(")");
|
||||
return fields;
|
||||
}
|
||||
|
||||
private CreateTable createTable() {
|
||||
boolean ifNotExists = acceptWords("IF", "NOT", "EXISTS");
|
||||
TableRef ref = tableRef();
|
||||
|
||||
@@ -8,7 +8,6 @@ import io.floci.aws.services.glue.model.Partition;
|
||||
import io.floci.aws.services.glue.model.StorageDescriptor;
|
||||
import io.floci.aws.services.glue.model.Table;
|
||||
import io.floci.aws.services.s3.S3Service;
|
||||
import io.floci.aws.services.s3.model.S3Object;
|
||||
|
||||
import java.net.URLDecoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
@@ -28,19 +27,20 @@ import java.util.stream.Collectors;
|
||||
* Athena treats Iceberg tables as managed; {@code MSCK REPAIR TABLE}
|
||||
* adds the Hive-style {@code key=value} partitions it finds under the table's location and never
|
||||
* removes any; {@code IF [NOT] EXISTS} turns a duplicate or missing table or partition from an
|
||||
* error into a no-op.
|
||||
* error into a no-op. An Iceberg {@code CREATE TABLE} goes to {@link AthenaIcebergStatements}.
|
||||
*/
|
||||
final class AthenaHiveDdlExecutor {
|
||||
|
||||
private static final int LIST_PAGE_SIZE = 1000;
|
||||
private static final String HIVE_ESCAPED_CHARACTERS = "\"#%'*/:=?\\{[]^";
|
||||
|
||||
private final GlueService glueService;
|
||||
private final S3Service s3Service;
|
||||
private final AthenaIcebergStatements icebergStatements;
|
||||
|
||||
AthenaHiveDdlExecutor(GlueService glueService, S3Service s3Service) {
|
||||
AthenaHiveDdlExecutor(GlueService glueService, S3Service s3Service, AthenaIcebergStatements icebergStatements) {
|
||||
this.glueService = glueService;
|
||||
this.s3Service = s3Service;
|
||||
this.icebergStatements = icebergStatements;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -73,6 +73,12 @@ final class AthenaHiveDdlExecutor {
|
||||
yield List.of();
|
||||
}
|
||||
case AthenaHiveDdl.ShowPartitions show -> partitionNames(database, existingTable(database, table));
|
||||
case AthenaHiveDdl.CreateIcebergTable create -> {
|
||||
icebergStatements.createTable(database, create);
|
||||
yield List.of();
|
||||
}
|
||||
case AthenaHiveDdl.Vacuum vacuum ->
|
||||
throw new IllegalStateException("VACUUM runs on the query engine, not against the catalog alone");
|
||||
};
|
||||
}
|
||||
|
||||
@@ -106,37 +112,7 @@ final class AthenaHiveDdlExecutor {
|
||||
}
|
||||
if (GlueTableResolver.isIcebergTable(found)) {
|
||||
// Athena treats an Iceberg table as managed: dropping it removes its data too.
|
||||
deleteObjectsUnder(found.getStorageDescriptor() != null ? found.getStorageDescriptor().getLocation() : null);
|
||||
}
|
||||
}
|
||||
|
||||
private void deleteObjectsUnder(String location) {
|
||||
S3Prefix prefix = S3Prefix.of(location);
|
||||
if (prefix == null) {
|
||||
return;
|
||||
}
|
||||
String continuation = null;
|
||||
do {
|
||||
S3Service.ListObjectsResult page = s3Service.listObjectsWithPrefixes(prefix.bucket(), prefix.prefix(), null,
|
||||
LIST_PAGE_SIZE, continuation, null);
|
||||
for (S3Object object : page.objects()) {
|
||||
s3Service.deleteObject(prefix.bucket(), object.getKey());
|
||||
}
|
||||
continuation = page.isTruncated() ? page.nextContinuationToken() : null;
|
||||
} while (continuation != null);
|
||||
}
|
||||
|
||||
/** An {@code s3://bucket/prefix/} location split into its bucket and its key prefix, ending in a slash. */
|
||||
private record S3Prefix(String bucket, String prefix) {
|
||||
static S3Prefix of(String location) {
|
||||
if (location == null || !location.startsWith("s3://")) {
|
||||
return null;
|
||||
}
|
||||
String withoutScheme = location.substring("s3://".length());
|
||||
int slash = withoutScheme.indexOf('/');
|
||||
String bucket = slash < 0 ? withoutScheme : withoutScheme.substring(0, slash);
|
||||
String prefix = slash < 0 ? "" : withoutScheme.substring(slash + 1);
|
||||
return new S3Prefix(bucket, prefix.isEmpty() || prefix.endsWith("/") ? prefix : prefix + "/");
|
||||
icebergStatements.purge(found);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -164,7 +140,8 @@ final class AthenaHiveDdlExecutor {
|
||||
/** Adds every complete {@code key=value/...} folder path under the table's location that has no partition yet. */
|
||||
private void repair(String database, Table table) {
|
||||
List<Column> keys = partitionKeys(table);
|
||||
S3Prefix root = S3Prefix.of(table.getStorageDescriptor() != null ? table.getStorageDescriptor().getLocation() : null);
|
||||
TableLocation root = TableLocation.of(table.getStorageDescriptor() != null
|
||||
? table.getStorageDescriptor().getLocation() : null);
|
||||
if (keys.isEmpty() || root == null) {
|
||||
return;
|
||||
}
|
||||
@@ -173,20 +150,14 @@ final class AthenaHiveDdlExecutor {
|
||||
.collect(Collectors.toCollection(HashSet::new));
|
||||
// Each new partition's values and the folder they were found in, kept as spelled in S3.
|
||||
Map<List<String>, String> found = new LinkedHashMap<>();
|
||||
String continuation = null;
|
||||
do {
|
||||
S3Service.ListObjectsResult page = s3Service.listObjectsWithPrefixes(root.bucket(), root.prefix(), null,
|
||||
LIST_PAGE_SIZE, continuation, null);
|
||||
for (S3Object object : page.objects()) {
|
||||
String relative = object.getKey().substring(root.prefix().length());
|
||||
List<String> values = hivePartitionValues(relative, keys);
|
||||
if (values != null && !existing.contains(values)) {
|
||||
found.putIfAbsent(values, "s3://" + root.bucket() + "/" + root.prefix()
|
||||
+ String.join("/", Arrays.asList(relative.split("/", -1)).subList(0, keys.size())) + "/");
|
||||
}
|
||||
root.forEachObject(s3Service, object -> {
|
||||
String relative = object.getKey().substring(root.prefix().length());
|
||||
List<String> values = hivePartitionValues(relative, keys);
|
||||
if (values != null && !existing.contains(values)) {
|
||||
found.putIfAbsent(values, "s3://" + root.bucket() + "/" + root.prefix()
|
||||
+ String.join("/", Arrays.asList(relative.split("/", -1)).subList(0, keys.size())) + "/");
|
||||
}
|
||||
continuation = page.isTruncated() ? page.nextContinuationToken() : null;
|
||||
} while (continuation != null);
|
||||
});
|
||||
found.forEach((values, location) -> createPartition(database, table, values, location, true));
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,546 @@
|
||||
package io.floci.aws.services.athena;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
import io.floci.aws.core.common.docker.ContainerReachableEndpoint;
|
||||
import io.floci.aws.services.floci.duck.FlociDuckClient;
|
||||
import io.floci.aws.services.glue.GlueService;
|
||||
import io.floci.aws.services.glue.GlueTableResolver;
|
||||
import io.floci.aws.services.glue.iceberg.GlueIcebergCatalog;
|
||||
import io.floci.aws.services.glue.iceberg.GlueIcebergTokens;
|
||||
import io.floci.aws.services.glue.iceberg.IcebergRestException;
|
||||
import io.floci.aws.services.glue.iceberg.IcebergSchemas;
|
||||
import io.floci.aws.services.glue.model.Table;
|
||||
import io.floci.aws.services.s3.S3Service;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.locks.Lock;
|
||||
import java.util.concurrent.locks.ReentrantReadWriteLock;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* Athena's statements on Iceberg tables, run against AWS Glue's Iceberg REST catalog the way Athena manages Iceberg
|
||||
* tables: {@code CREATE TABLE ... TBLPROPERTIES ('table_type'='ICEBERG')} creates one, {@code INSERT INTO},
|
||||
* {@code UPDATE}, {@code DELETE FROM} and {@code MERGE INTO} write one through the query engine attached to that
|
||||
* catalog, and {@code VACUUM} expires its old snapshots and removes the files nothing references any more.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class AthenaIcebergStatements {
|
||||
|
||||
/** The name the query engine attaches Glue's Iceberg REST catalog under. */
|
||||
static final String CATALOG_ALIAS = "glue_iceberg";
|
||||
|
||||
/** The table properties Athena allows on an Iceberg table, {@code table_type} aside. */
|
||||
private static final Set<String> TABLE_PROPERTIES = Set.of("format", "write_compression",
|
||||
"optimize_rewrite_data_file_threshold", "optimize_rewrite_delete_file_threshold",
|
||||
"vacuum_min_snapshots_to_keep", "vacuum_max_snapshot_age_seconds", "vacuum_max_metadata_files_to_keep",
|
||||
"write_data_path_enabled");
|
||||
private static final String MIN_SNAPSHOTS_TO_KEEP = "vacuum_min_snapshots_to_keep";
|
||||
private static final String MAX_SNAPSHOT_AGE_SECONDS = "vacuum_max_snapshot_age_seconds";
|
||||
private static final String MAX_METADATA_FILES_TO_KEEP = "vacuum_max_metadata_files_to_keep";
|
||||
private static final long DEFAULT_MIN_SNAPSHOTS_TO_KEEP = 1;
|
||||
private static final long DEFAULT_MAX_SNAPSHOT_AGE_SECONDS = 432_000;
|
||||
private static final long DEFAULT_MAX_METADATA_FILES_TO_KEEP = 100;
|
||||
/** Athena creates Iceberg v2 tables. */
|
||||
private static final String FORMAT_VERSION = "2";
|
||||
private static final String DEFAULT_CATALOG = ":";
|
||||
private static final String DEFAULT_DATA_CATALOG = "awsdatacatalog";
|
||||
/** How long the query engine's catalog token lives at most; it is revoked as soon as the statement ends. */
|
||||
private static final Duration TOKEN_LIFETIME = Duration.ofHours(1);
|
||||
private static final Pattern DML = Pattern.compile("^(?:INSERT\\s+INTO|MERGE\\s+INTO|DELETE\\s+FROM|UPDATE)\\s+",
|
||||
Pattern.CASE_INSENSITIVE);
|
||||
private static final Pattern S3_URI = Pattern.compile("^s3[an]?://([^/]+)/(.*)$");
|
||||
|
||||
private final GlueIcebergCatalog catalog;
|
||||
private final GlueService glue;
|
||||
private final S3Service s3;
|
||||
private final GlueIcebergTokens tokens;
|
||||
private final ContainerReachableEndpoint containerEndpoint;
|
||||
private final FlociDuckClient duck;
|
||||
private final RegionResolver regionResolver;
|
||||
private final ObjectMapper mapper;
|
||||
private final Clock clock;
|
||||
private final Map<String, ReentrantReadWriteLock> tableLocks = new ConcurrentHashMap<>();
|
||||
|
||||
@Inject
|
||||
public AthenaIcebergStatements(GlueIcebergCatalog catalog, GlueService glue, S3Service s3,
|
||||
GlueIcebergTokens tokens, ContainerReachableEndpoint containerEndpoint,
|
||||
FlociDuckClient duck, RegionResolver regionResolver, ObjectMapper mapper) {
|
||||
this(catalog, glue, s3, tokens, containerEndpoint, duck, regionResolver, mapper, Clock.systemUTC());
|
||||
}
|
||||
|
||||
AthenaIcebergStatements(GlueIcebergCatalog catalog, GlueService glue, S3Service s3, GlueIcebergTokens tokens,
|
||||
ContainerReachableEndpoint containerEndpoint, FlociDuckClient duck,
|
||||
RegionResolver regionResolver, ObjectMapper mapper, Clock clock) {
|
||||
this.catalog = catalog;
|
||||
this.glue = glue;
|
||||
this.s3 = s3;
|
||||
this.tokens = tokens;
|
||||
this.containerEndpoint = containerEndpoint;
|
||||
this.duck = duck;
|
||||
this.regionResolver = regionResolver;
|
||||
this.mapper = mapper;
|
||||
this.clock = clock;
|
||||
}
|
||||
|
||||
// ─── CREATE TABLE ─────────────────────────────────────────────────────────────
|
||||
|
||||
/** Creates the Iceberg table {@code create} describes in {@code database}, with no data. */
|
||||
void createTable(String database, AthenaHiveDdl.CreateIcebergTable create) {
|
||||
String table = create.ref().table();
|
||||
if (create.ifNotExists() && findTable(database, table) != null) {
|
||||
return;
|
||||
}
|
||||
Map<String, String> properties = new HashMap<>();
|
||||
create.properties().forEach((key, value) -> {
|
||||
String name = key.toLowerCase(Locale.ROOT);
|
||||
if (!TABLE_PROPERTIES.contains(name)) {
|
||||
throw invalid("Unsupported table property key: " + key + ". Athena allows only a predefined list "
|
||||
+ "of table properties on an Iceberg table");
|
||||
}
|
||||
properties.put(name, value);
|
||||
});
|
||||
String format = properties.get("format");
|
||||
if (format != null && !format.equalsIgnoreCase("parquet")) {
|
||||
throw invalid("Floci writes Iceberg data files as Parquet only, not " + format);
|
||||
}
|
||||
properties.put("format-version", FORMAT_VERSION);
|
||||
ObjectNode request;
|
||||
try {
|
||||
request = IcebergSchemas.createTableRequest(table, create.columns(), create.partitioning(),
|
||||
create.location(), properties);
|
||||
} catch (IllegalArgumentException e) {
|
||||
throw invalid(e.getMessage());
|
||||
}
|
||||
try {
|
||||
catalog.createTable(DEFAULT_CATALOG, database, request);
|
||||
} catch (IcebergRestException e) {
|
||||
if (create.ifNotExists() && "AlreadyExistsException".equals(e.type())) {
|
||||
return;
|
||||
}
|
||||
throw invalid(e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
// ─── DROP TABLE ───────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Deletes a dropped Iceberg table's files, everything under its location, as Athena does for a table it treats
|
||||
* as managed; only from a bucket of the calling account.
|
||||
*/
|
||||
void purge(Table table) {
|
||||
TableLocation location = TableLocation.of(table.getStorageDescriptor() != null
|
||||
? table.getStorageDescriptor().getLocation() : null);
|
||||
if (location != null && location.ownedBy(s3, regionResolver.getAccountId())) {
|
||||
location.forEachObject(s3, object -> s3.deleteObject(location.bucket(), object.getKey()));
|
||||
}
|
||||
}
|
||||
|
||||
// ─── INSERT / UPDATE / DELETE / MERGE ─────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* A data-changing statement whose target is an Iceberg table, rewritten to write that table through the query
|
||||
* engine's attachment of Glue's Iceberg REST catalog: the setup SQL that attaches it with a catalog token for the
|
||||
* calling account and Region, and the table's write lock it holds, both given up once the statement ends.
|
||||
*/
|
||||
record IcebergWrite(String query, String setupSql, String token, Lock lock) {
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code query} rewritten to write its Iceberg target through the attached catalog, or null when it is not an
|
||||
* {@code INSERT INTO}, {@code UPDATE}, {@code DELETE FROM} or {@code MERGE INTO} of an Iceberg table; a target
|
||||
* named without a database is in {@code contextDatabase}.
|
||||
*/
|
||||
IcebergWrite write(String query, String contextDatabase) {
|
||||
Target target = target(query);
|
||||
if (target == null) {
|
||||
return null;
|
||||
}
|
||||
String database = target.database() != null ? target.database() : contextDatabase;
|
||||
Table table = findTable(database, target.table());
|
||||
if (!GlueTableResolver.isIcebergTable(table)) {
|
||||
return null;
|
||||
}
|
||||
String accountId = regionResolver.getAccountId();
|
||||
// Held, shared with other writes, until the statement ends, so VACUUM leaves the files it stages alone.
|
||||
Lock lock = tableLock(database, target.table()).readLock();
|
||||
lock.lock();
|
||||
String token = tokens.mint(accountId, regionResolver.getRegion(), TOKEN_LIFETIME);
|
||||
String setup = "INSTALL iceberg; LOAD iceberg;\nATTACH " + literal(accountId) + " AS " + CATALOG_ALIAS
|
||||
+ " (TYPE iceberg, ENDPOINT " + literal(containerEndpoint.baseUrl() + "/iceberg")
|
||||
+ ", AUTHORIZATION_TYPE 'oauth2', TOKEN " + literal(token) + ", ACCESS_DELEGATION_MODE 'none');\n";
|
||||
String rewritten = query.substring(0, target.start()) + CATALOG_ALIAS + "."
|
||||
+ GlueViewDdlBuilder.quote(database) + "." + GlueViewDdlBuilder.quote(target.table())
|
||||
+ query.substring(target.end());
|
||||
return new IcebergWrite(rewritten, setup, token, lock);
|
||||
}
|
||||
|
||||
/** Gives up the catalog token and the table lock of a write once its statement has ended, on its thread. */
|
||||
void finished(IcebergWrite write) {
|
||||
try {
|
||||
tokens.revoke(write.token());
|
||||
} finally {
|
||||
write.lock().unlock();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The lock between Floci's own writes to a table, which share it, and {@code VACUUM}'s file sweep, which takes
|
||||
* it alone: a file a running write staged is not yet referenced by any snapshot, and a short
|
||||
* {@code vacuum_max_snapshot_age_seconds} would otherwise let the sweep delete it.
|
||||
*/
|
||||
private ReentrantReadWriteLock tableLock(String database, String table) {
|
||||
return tableLocks.computeIfAbsent(regionResolver.getAccountId() + "/" + regionResolver.getRegion() + "/"
|
||||
+ database + "/" + table, key -> new ReentrantReadWriteLock());
|
||||
}
|
||||
|
||||
/** The table a statement writes, and where its name sits in the statement. */
|
||||
record Target(String database, String table, int start, int end) {
|
||||
}
|
||||
|
||||
/**
|
||||
* The table an {@code INSERT INTO}, {@code UPDATE}, {@code DELETE FROM} or {@code MERGE INTO} writes:
|
||||
* {@code t}, {@code db.t} or {@code awsdatacatalog.db.t}, each part bare or double-quoted. Null for any other
|
||||
* statement, or one writing another catalog's table.
|
||||
*/
|
||||
static Target target(String query) {
|
||||
int start = statementStart(query);
|
||||
Matcher dml = DML.matcher(query).region(start, query.length());
|
||||
if (!dml.lookingAt()) {
|
||||
return null;
|
||||
}
|
||||
List<String> parts = new ArrayList<>();
|
||||
int i = dml.end();
|
||||
int nameStart = i;
|
||||
int nameEnd;
|
||||
while (true) {
|
||||
int partEnd = identifierEnd(query, i);
|
||||
if (partEnd == i) {
|
||||
return null;
|
||||
}
|
||||
String part = query.charAt(i) == '"'
|
||||
? query.substring(i + 1, partEnd - 1).replace("\"\"", "\"")
|
||||
: query.substring(i, partEnd);
|
||||
parts.add(part.toLowerCase(Locale.ROOT));
|
||||
nameEnd = partEnd;
|
||||
int next = skipSpaces(query, partEnd);
|
||||
if (next < query.length() && query.charAt(next) == '.') {
|
||||
i = skipSpaces(query, next + 1);
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
return switch (parts.size()) {
|
||||
case 1 -> new Target(null, parts.get(0), nameStart, nameEnd);
|
||||
case 2 -> new Target(parts.get(0), parts.get(1), nameStart, nameEnd);
|
||||
case 3 -> DEFAULT_DATA_CATALOG.equals(parts.get(0))
|
||||
? new Target(parts.get(1), parts.get(2), nameStart, nameEnd) : null;
|
||||
default -> null;
|
||||
};
|
||||
}
|
||||
|
||||
/** Where the statement starts, past leading whitespace and comments. */
|
||||
private static int statementStart(String query) {
|
||||
int i = 0;
|
||||
while (true) {
|
||||
i = skipSpaces(query, i);
|
||||
if (query.startsWith("--", i)) {
|
||||
int lineEnd = query.indexOf('\n', i);
|
||||
i = lineEnd < 0 ? query.length() : lineEnd + 1;
|
||||
} else if (query.startsWith("/*", i)) {
|
||||
int commentEnd = query.indexOf("*/", i + 2);
|
||||
i = commentEnd < 0 ? query.length() : commentEnd + 2;
|
||||
} else {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static int skipSpaces(String query, int i) {
|
||||
while (i < query.length() && Character.isWhitespace(query.charAt(i))) {
|
||||
i++;
|
||||
}
|
||||
return i;
|
||||
}
|
||||
|
||||
/** The index just past the identifier at {@code i}, or {@code i} when none starts there. */
|
||||
private static int identifierEnd(String query, int i) {
|
||||
if (i >= query.length()) {
|
||||
return i;
|
||||
}
|
||||
if (query.charAt(i) == '"') {
|
||||
int j = i + 1;
|
||||
while (j < query.length()) {
|
||||
if (query.charAt(j) == '"') {
|
||||
if (j + 1 < query.length() && query.charAt(j + 1) == '"') {
|
||||
j += 2;
|
||||
continue;
|
||||
}
|
||||
return j + 1;
|
||||
}
|
||||
j++;
|
||||
}
|
||||
return i;
|
||||
}
|
||||
int j = i;
|
||||
while (j < query.length() && (Character.isLetterOrDigit(query.charAt(j)) || query.charAt(j) == '_')) {
|
||||
j++;
|
||||
}
|
||||
return j;
|
||||
}
|
||||
|
||||
// ─── VACUUM ───────────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Runs {@code VACUUM} on the Iceberg table {@code ref} names, a table without a database being in
|
||||
* {@code contextDatabase}: expires the snapshots older than {@code vacuum_max_snapshot_age_seconds} beyond the
|
||||
* newest {@code vacuum_min_snapshots_to_keep} of each branch, then removes the table's metadata files beyond the
|
||||
* newest {@code vacuum_max_metadata_files_to_keep}, and every file under its location that no snapshot left
|
||||
* references and that is older than that age, orphans included. Files are deleted only from a bucket of the
|
||||
* calling account; elsewhere they stay, as Athena's VACUUM succeeds without deleting files it may not delete.
|
||||
* While one of Floci's own writes to the table runs, the files stay for the next {@code VACUUM}.
|
||||
*/
|
||||
void vacuum(AthenaHiveDdl.TableRef ref, String contextDatabase) {
|
||||
String database = ref.database() != null ? ref.database() : contextDatabase;
|
||||
Table table = findTable(database, ref.table());
|
||||
if (table == null) {
|
||||
throw new AwsException("InvalidRequestException", "Table " + database + "." + ref.table()
|
||||
+ " does not exist", 400);
|
||||
}
|
||||
if (!GlueTableResolver.isIcebergTable(table)) {
|
||||
throw invalid("VACUUM is supported only for Apache Iceberg tables");
|
||||
}
|
||||
ObjectNode loaded = loadTable(database, ref.table());
|
||||
JsonNode metadata = loaded.path("metadata");
|
||||
JsonNode properties = metadata.path("properties");
|
||||
long now = clock.millis();
|
||||
long cutoff = now - Duration.ofSeconds(longProperty(properties, MAX_SNAPSHOT_AGE_SECONDS,
|
||||
DEFAULT_MAX_SNAPSHOT_AGE_SECONDS)).toMillis();
|
||||
long minSnapshots = longProperty(properties, MIN_SNAPSHOTS_TO_KEEP, DEFAULT_MIN_SNAPSHOTS_TO_KEEP);
|
||||
long metadataFilesToKeep = longProperty(properties, MAX_METADATA_FILES_TO_KEEP,
|
||||
DEFAULT_MAX_METADATA_FILES_TO_KEEP);
|
||||
|
||||
Set<Long> retained = retainedSnapshots(metadata, cutoff, minSnapshots);
|
||||
List<Long> expired = new ArrayList<>();
|
||||
for (JsonNode snapshot : metadata.path("snapshots")) {
|
||||
long id = snapshot.path("snapshot-id").asLong();
|
||||
if (!retained.contains(id)) {
|
||||
expired.add(id);
|
||||
}
|
||||
}
|
||||
if (!expired.isEmpty()) {
|
||||
loaded = commitExpiry(database, ref.table(), metadata, expired);
|
||||
metadata = loaded.path("metadata");
|
||||
}
|
||||
Lock sweep = tableLock(database, ref.table()).writeLock();
|
||||
if (!sweep.tryLock()) {
|
||||
// A write to the table is running; its staged files stay, and the next VACUUM sweeps.
|
||||
return;
|
||||
}
|
||||
try {
|
||||
removeUnreferencedFiles(loaded.path("metadata-location").asText(), metadata, cutoff, metadataFilesToKeep);
|
||||
} finally {
|
||||
sweep.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The snapshots {@code VACUUM} keeps, as Iceberg's snapshot expiration keeps them: each tag's snapshot; on each
|
||||
* branch, the ancestors of its head while they are among its newest {@code minSnapshots} or newer than
|
||||
* {@code cutoff}; and any other snapshot newer than {@code cutoff}.
|
||||
*/
|
||||
static Set<Long> retainedSnapshots(JsonNode metadata, long cutoff, long minSnapshots) {
|
||||
Map<Long, JsonNode> snapshots = new HashMap<>();
|
||||
for (JsonNode snapshot : metadata.path("snapshots")) {
|
||||
snapshots.put(snapshot.path("snapshot-id").asLong(), snapshot);
|
||||
}
|
||||
Map<String, JsonNode> refs = new HashMap<>();
|
||||
metadata.path("refs").properties().forEach(entry -> refs.put(entry.getKey(), entry.getValue()));
|
||||
if (refs.isEmpty() && metadata.hasNonNull("current-snapshot-id")
|
||||
&& metadata.path("current-snapshot-id").asLong() != -1) {
|
||||
refs.put("main", JsonNodeFactory.instance.objectNode()
|
||||
.put("snapshot-id", metadata.path("current-snapshot-id").asLong()).put("type", "branch"));
|
||||
}
|
||||
Set<Long> retained = new HashSet<>();
|
||||
for (JsonNode ref : refs.values()) {
|
||||
long head = ref.path("snapshot-id").asLong();
|
||||
if ("tag".equals(ref.path("type").asText())) {
|
||||
retained.add(head);
|
||||
continue;
|
||||
}
|
||||
JsonNode snapshot = snapshots.get(head);
|
||||
for (long kept = 0; snapshot != null; kept++) {
|
||||
if (kept >= minSnapshots && snapshot.path("timestamp-ms").asLong() < cutoff) {
|
||||
break;
|
||||
}
|
||||
retained.add(snapshot.path("snapshot-id").asLong());
|
||||
snapshot = snapshot.hasNonNull("parent-snapshot-id")
|
||||
? snapshots.get(snapshot.path("parent-snapshot-id").asLong()) : null;
|
||||
}
|
||||
}
|
||||
snapshots.forEach((id, snapshot) -> {
|
||||
if (snapshot.path("timestamp-ms").asLong() >= cutoff) {
|
||||
retained.add(id);
|
||||
}
|
||||
});
|
||||
return retained;
|
||||
}
|
||||
|
||||
private ObjectNode commitExpiry(String database, String table, JsonNode metadata, List<Long> expired) {
|
||||
ObjectNode commit = mapper.createObjectNode();
|
||||
ArrayNode requirements = commit.putArray("requirements");
|
||||
requirements.addObject().put("type", "assert-table-uuid").put("uuid", metadata.path("table-uuid").asText());
|
||||
ObjectNode main = requirements.addObject().put("type", "assert-ref-snapshot-id").put("ref", "main");
|
||||
JsonNode mainRef = metadata.path("refs").path("main");
|
||||
if (mainRef.hasNonNull("snapshot-id")) {
|
||||
main.put("snapshot-id", mainRef.path("snapshot-id").asLong());
|
||||
} else {
|
||||
main.putNull("snapshot-id");
|
||||
}
|
||||
ArrayNode ids = commit.putArray("updates").addObject().put("action", "remove-snapshots")
|
||||
.putArray("snapshot-ids");
|
||||
expired.forEach(ids::add);
|
||||
try {
|
||||
return catalog.commitTable(DEFAULT_CATALOG, database, table, commit);
|
||||
} catch (IcebergRestException e) {
|
||||
throw invalid(e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes the files under the table's location nothing references any more: metadata files beyond the newest
|
||||
* {@code metadataFilesToKeep} before the current one, and any other file neither the metadata (its manifest
|
||||
* lists and statistics files) nor a retained snapshot reaches, once it is older than {@code cutoff}, which spares
|
||||
* the files of another engine's write still in flight, as on Athena; Floci's own writes hold the table's lock.
|
||||
*/
|
||||
private void removeUnreferencedFiles(String metadataLocation, JsonNode metadata, long cutoff,
|
||||
long metadataFilesToKeep) {
|
||||
TableLocation location = TableLocation.of(metadata.path("location").asText());
|
||||
if (location == null || location.prefix().isEmpty() || !location.ownedBy(s3, regionResolver.getAccountId())) {
|
||||
// Athena's VACUUM expects a table in a folder, not at a bucket's root, and deletes as the caller.
|
||||
return;
|
||||
}
|
||||
Set<String> referenced = new HashSet<>();
|
||||
addS3Uri(referenced, metadataLocation);
|
||||
List<String> previousMetadata = new ArrayList<>();
|
||||
metadata.path("metadata-log").forEach(entry -> previousMetadata.add(entry.path("metadata-file").asText()));
|
||||
Set<String> expiredMetadata = new HashSet<>();
|
||||
for (int i = 0; i < previousMetadata.size(); i++) {
|
||||
addS3Uri(i >= previousMetadata.size() - metadataFilesToKeep ? referenced : expiredMetadata,
|
||||
previousMetadata.get(i));
|
||||
}
|
||||
List<Long> snapshotIds = new ArrayList<>();
|
||||
for (JsonNode snapshot : metadata.path("snapshots")) {
|
||||
snapshotIds.add(snapshot.path("snapshot-id").asLong());
|
||||
addS3Uri(referenced, snapshot.path("manifest-list").asText(null));
|
||||
}
|
||||
// Table and partition statistics files (Puffin and the like) the metadata still lists.
|
||||
for (String statistics : List.of("statistics", "partition-statistics")) {
|
||||
metadata.path(statistics).forEach(file -> addS3Uri(referenced, file.path("statistics-path").asText(null)));
|
||||
}
|
||||
referenced.addAll(filesOf(metadataLocation, snapshotIds));
|
||||
Instant before = Instant.ofEpochMilli(cutoff);
|
||||
location.forEachObject(s3, object -> {
|
||||
String uri = "s3://" + location.bucket() + "/" + object.getKey();
|
||||
boolean expiredVersion = expiredMetadata.contains(uri);
|
||||
boolean old = object.getLastModified() != null && object.getLastModified().isBefore(before);
|
||||
if (!referenced.contains(uri) && (expiredVersion || old)) {
|
||||
s3.deleteObject(location.bucket(), object.getKey());
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/** The manifests and data and delete files each snapshot reaches, read by the query engine. */
|
||||
private Set<String> filesOf(String metadataLocation, List<Long> snapshotIds) {
|
||||
Set<String> files = new HashSet<>();
|
||||
if (snapshotIds.isEmpty()) {
|
||||
return files;
|
||||
}
|
||||
StringBuilder sql = new StringBuilder();
|
||||
for (Long id : snapshotIds) {
|
||||
if (!sql.isEmpty()) {
|
||||
sql.append("\nUNION\n");
|
||||
}
|
||||
sql.append("SELECT manifest_path, file_path FROM iceberg_metadata(").append(literal(metadataLocation))
|
||||
.append(", snapshot_from_id => ").append(id).append(")");
|
||||
}
|
||||
for (Map<String, Object> row : duck.query(sql.toString(), "INSTALL iceberg; LOAD iceberg;\n",
|
||||
regionResolver.getAccountId())) {
|
||||
addS3Uri(files, row.get("manifest_path"));
|
||||
addS3Uri(files, row.get("file_path"));
|
||||
}
|
||||
return files;
|
||||
}
|
||||
|
||||
private static void addS3Uri(Set<String> files, Object path) {
|
||||
if (path == null) {
|
||||
return;
|
||||
}
|
||||
Matcher uri = S3_URI.matcher(path.toString());
|
||||
// s3a:// and s3n:// name the same object as s3://.
|
||||
files.add(uri.matches() ? "s3://" + uri.group(1) + "/" + uri.group(2) : path.toString());
|
||||
}
|
||||
|
||||
// ─── Helpers ──────────────────────────────────────────────────────────────────
|
||||
|
||||
private ObjectNode loadTable(String database, String table) {
|
||||
try {
|
||||
return catalog.loadTable(DEFAULT_CATALOG, database, table, null);
|
||||
} catch (IcebergRestException e) {
|
||||
throw invalid(e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private Table findTable(String database, String table) {
|
||||
try {
|
||||
return glue.getTable(database, table);
|
||||
} catch (AwsException e) {
|
||||
if ("EntityNotFoundException".equals(e.getErrorCode())) {
|
||||
return null;
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
private static long longProperty(JsonNode properties, String name, long fallback) {
|
||||
JsonNode value = properties.get(name);
|
||||
if (value == null || value.asText().isBlank()) {
|
||||
return fallback;
|
||||
}
|
||||
try {
|
||||
long parsed = Long.parseLong(value.asText().trim());
|
||||
if (parsed <= 0) {
|
||||
throw invalid("Table property " + name + " must be a positive number: " + value.asText());
|
||||
}
|
||||
return parsed;
|
||||
} catch (NumberFormatException e) {
|
||||
throw invalid("Table property " + name + " must be a positive number: " + value.asText());
|
||||
}
|
||||
}
|
||||
|
||||
private static String literal(String value) {
|
||||
return "'" + value.replace("'", "''") + "'";
|
||||
}
|
||||
|
||||
private static AwsException invalid(String message) {
|
||||
return new AwsException("InvalidRequestException", message, 400);
|
||||
}
|
||||
}
|
||||
@@ -110,6 +110,7 @@ public class AthenaService {
|
||||
private final GlueViewDdlBuilder ddlBuilder;
|
||||
private final RegionResolver regionResolver;
|
||||
private final AthenaHiveDdlExecutor hiveDdlExecutor;
|
||||
private final AthenaIcebergStatements icebergStatements;
|
||||
|
||||
@Inject
|
||||
public AthenaService(StorageFactory storageFactory,
|
||||
@@ -119,7 +120,8 @@ public class AthenaService {
|
||||
EmulatorConfig config,
|
||||
Vertx vertx,
|
||||
GlueViewDdlBuilder ddlBuilder,
|
||||
RegionResolver regionResolver) {
|
||||
RegionResolver regionResolver,
|
||||
AthenaIcebergStatements icebergStatements) {
|
||||
this.queryStore = storageFactory.create("athena", "queries.json",
|
||||
new TypeReference<>() {});
|
||||
this.workGroupStore = storageFactory.create("athena", "workgroups.json",
|
||||
@@ -135,7 +137,8 @@ public class AthenaService {
|
||||
this.vertx = vertx;
|
||||
this.ddlBuilder = ddlBuilder;
|
||||
this.regionResolver = regionResolver;
|
||||
this.hiveDdlExecutor = new AthenaHiveDdlExecutor(glueService, s3Service);
|
||||
this.icebergStatements = icebergStatements;
|
||||
this.hiveDdlExecutor = new AthenaHiveDdlExecutor(glueService, s3Service, icebergStatements);
|
||||
}
|
||||
|
||||
public String startQueryExecution(String query,
|
||||
@@ -160,7 +163,9 @@ public class AthenaService {
|
||||
} catch (AwsException e) {
|
||||
invalidHiveDdl = e;
|
||||
}
|
||||
boolean hiveDdlStatement = hiveDdl != null || invalidHiveDdl != null;
|
||||
// VACUUM reads the table's manifests, so it runs on the query engine like a query.
|
||||
AthenaHiveDdl.Vacuum vacuum = hiveDdl instanceof AthenaHiveDdl.Vacuum statement ? statement : null;
|
||||
boolean hiveDdlStatement = (hiveDdl != null && vacuum == null) || invalidHiveDdl != null;
|
||||
// AWS reports the result CSV object itself as the OutputLocation, not a
|
||||
// directory prefix — the same key is written and returned to the client.
|
||||
// Statements that do not return rows must not be wrapped in a result COPY.
|
||||
@@ -225,17 +230,31 @@ public class AthenaService {
|
||||
// Athena fails a query that reads a table with an incomplete location template, or that
|
||||
// leaves an injected partition column unconstrained. It fails the query rather than the
|
||||
// submission, which is what throwing here produces.
|
||||
if (vacuum != null) {
|
||||
icebergStatements.vacuum(vacuum.ref(), database);
|
||||
return null;
|
||||
}
|
||||
List<Table> projectionTables = tablesForProjectionCheck(database);
|
||||
PartitionProjection.assertLocationTemplatesComplete(query, projectionTables);
|
||||
PartitionProjection.assertInjectedColumnsFiltered(query, projectionTables);
|
||||
String setupDdl = TrinoSqlCompatibility.FUNCTION_MACROS + ddlBuilder.build(database, query);
|
||||
String duckQuery = TrinoSqlCompatibility.translate(query);
|
||||
if (outputLocation != null) {
|
||||
ensureOutputBucket(outputLocation);
|
||||
}
|
||||
duckClient.execute(duckQuery, setupDdl, outputLocation, accountId);
|
||||
if (outputLocation != null) {
|
||||
resultColumnTypeStore.put(id, describeColumnTypes(duckQuery, setupDdl, accountId));
|
||||
// A write to an Iceberg table goes through the engine's attachment of Glue's Iceberg catalog.
|
||||
AthenaIcebergStatements.IcebergWrite icebergWrite = icebergStatements.write(query, database);
|
||||
try {
|
||||
String setupDdl = (icebergWrite != null ? icebergWrite.setupSql() : "")
|
||||
+ TrinoSqlCompatibility.FUNCTION_MACROS + ddlBuilder.build(database, query);
|
||||
String duckQuery = TrinoSqlCompatibility.translate(
|
||||
icebergWrite != null ? icebergWrite.query() : query);
|
||||
if (outputLocation != null) {
|
||||
ensureOutputBucket(outputLocation);
|
||||
}
|
||||
duckClient.execute(duckQuery, setupDdl, outputLocation, accountId);
|
||||
if (outputLocation != null) {
|
||||
resultColumnTypeStore.put(id, describeColumnTypes(duckQuery, setupDdl, accountId));
|
||||
}
|
||||
} finally {
|
||||
if (icebergWrite != null) {
|
||||
icebergStatements.finished(icebergWrite);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
})
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
package io.floci.aws.services.athena;
|
||||
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.services.s3.S3Service;
|
||||
import io.floci.aws.services.s3.model.S3Object;
|
||||
|
||||
import java.util.function.Consumer;
|
||||
|
||||
/** A table's {@code s3://bucket/prefix/} location split into its bucket and its key prefix, ending in a slash. */
|
||||
record TableLocation(String bucket, String prefix) {
|
||||
|
||||
private static final int LIST_PAGE_SIZE = 1000;
|
||||
|
||||
/** The location {@code location} names, or null when it is not an {@code s3://} location. */
|
||||
static TableLocation of(String location) {
|
||||
if (location == null || !location.startsWith("s3://")) {
|
||||
return null;
|
||||
}
|
||||
String withoutScheme = location.substring("s3://".length());
|
||||
int slash = withoutScheme.indexOf('/');
|
||||
String bucket = slash < 0 ? withoutScheme : withoutScheme.substring(0, slash);
|
||||
String prefix = slash < 0 ? "" : withoutScheme.substring(slash + 1);
|
||||
return new TableLocation(bucket, prefix.isEmpty() || prefix.endsWith("/") ? prefix : prefix + "/");
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether {@code accountId} owns the location's bucket, and so may delete what lies under it: Floci deletes a
|
||||
* table's files itself, where Athena deletes them as the caller, so a table placed in another account's bucket
|
||||
* keeps them. False when the bucket does not exist.
|
||||
*/
|
||||
boolean ownedBy(S3Service s3, String accountId) {
|
||||
try {
|
||||
return accountId.equals(s3.getBucketOwnerAccountId(bucket));
|
||||
} catch (AwsException e) {
|
||||
if ("NoSuchBucket".equals(e.getErrorCode())) {
|
||||
return false;
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
/** Hands each object under the location to {@code action}, a page at a time; the action may delete it. */
|
||||
void forEachObject(S3Service s3, Consumer<S3Object> action) {
|
||||
String continuation = null;
|
||||
do {
|
||||
S3Service.ListObjectsResult page = s3.listObjectsWithPrefixes(bucket, prefix, null, LIST_PAGE_SIZE,
|
||||
continuation, null);
|
||||
page.objects().forEach(action);
|
||||
continuation = page.isTruncated() ? page.nextContinuationToken() : null;
|
||||
} while (continuation != null);
|
||||
}
|
||||
}
|
||||
@@ -4,10 +4,8 @@ import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
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.RequestContext;
|
||||
import io.floci.aws.services.glue.GlueService;
|
||||
import io.floci.aws.services.glue.GlueTableResolver;
|
||||
import io.floci.aws.services.glue.model.Column;
|
||||
@@ -73,24 +71,19 @@ public class GlueIcebergCatalog {
|
||||
private final S3Service s3;
|
||||
private final RegionResolver regionResolver;
|
||||
private final ObjectMapper mapper;
|
||||
private final EmulatorConfig config;
|
||||
private final RequestContext requestContext;
|
||||
private final Clock clock;
|
||||
|
||||
@Inject
|
||||
public GlueIcebergCatalog(GlueService glue, S3Service s3, RegionResolver regionResolver, ObjectMapper mapper,
|
||||
EmulatorConfig config, RequestContext requestContext) {
|
||||
this(glue, s3, regionResolver, mapper, config, requestContext, Clock.systemUTC());
|
||||
public GlueIcebergCatalog(GlueService glue, S3Service s3, RegionResolver regionResolver, ObjectMapper mapper) {
|
||||
this(glue, s3, regionResolver, mapper, Clock.systemUTC());
|
||||
}
|
||||
|
||||
GlueIcebergCatalog(GlueService glue, S3Service s3, RegionResolver regionResolver, ObjectMapper mapper,
|
||||
EmulatorConfig config, RequestContext requestContext, Clock clock) {
|
||||
Clock clock) {
|
||||
this.glue = glue;
|
||||
this.s3 = s3;
|
||||
this.regionResolver = regionResolver;
|
||||
this.mapper = mapper;
|
||||
this.config = config;
|
||||
this.requestContext = requestContext;
|
||||
this.clock = clock;
|
||||
}
|
||||
|
||||
@@ -239,7 +232,7 @@ public class GlueIcebergCatalog {
|
||||
* Creates a table from a {@code CreateTableRequest}, or, with {@code stage-create}, answers the metadata it would
|
||||
* have without creating it: the commit that follows, required to find no table ({@code assert-create}), does.
|
||||
*/
|
||||
ObjectNode createTable(String catalog, String namespace, JsonNode request) {
|
||||
public ObjectNode createTable(String catalog, String namespace, JsonNode request) {
|
||||
requireDefaultCatalog(catalog);
|
||||
Database database = requireNamespace(namespace(namespace));
|
||||
String name = request.path("name").asText();
|
||||
@@ -271,7 +264,7 @@ public class GlueIcebergCatalog {
|
||||
return result;
|
||||
}
|
||||
|
||||
ObjectNode loadTable(String catalog, String namespace, String name, String snapshots) {
|
||||
public ObjectNode loadTable(String catalog, String namespace, String name, String snapshots) {
|
||||
requireDefaultCatalog(catalog);
|
||||
Database database = requireNamespace(namespace(namespace));
|
||||
Table table = requireIcebergTable(database.getName(), name);
|
||||
@@ -299,7 +292,7 @@ public class GlueIcebergCatalog {
|
||||
* ({@code CommitFailedException}) when the Glue table changed since. A commit requiring {@code assert-create}
|
||||
* creates the table.
|
||||
*/
|
||||
ObjectNode commitTable(String catalog, String namespace, String name, JsonNode request) {
|
||||
public ObjectNode commitTable(String catalog, String namespace, String name, JsonNode request) {
|
||||
requireDefaultCatalog(catalog);
|
||||
Database database = requireNamespace(namespace(namespace));
|
||||
Table existing = findTable(database.getName(), name);
|
||||
@@ -375,31 +368,12 @@ public class GlueIcebergCatalog {
|
||||
// ─── Helpers ──────────────────────────────────────────────────────────────────
|
||||
|
||||
private void requireDefaultCatalog(String catalog) {
|
||||
requireCheckableCaller();
|
||||
if (!DEFAULT_CATALOG.equals(catalog) && !regionResolver.getAccountId().equals(catalog)) {
|
||||
throw IcebergRestException.badRequest("Catalog " + catalog
|
||||
+ " is not supported: use the caller's default catalog (':' or its account id)");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Under IAM enforcement, no rule maps this endpoint's routes to the Glue actions AWS checks for them yet, and an
|
||||
* unmapped REST route is allowed, so an IAM principal is refused here rather than let through unchecked: only the
|
||||
* account's root credentials, and Floci's own callers, which carry no access key, reach the catalog then.
|
||||
*/
|
||||
private void requireCheckableCaller() {
|
||||
if (!config.services().iam().enforcementEnabled()) {
|
||||
return;
|
||||
}
|
||||
String accessKeyId = requestContext.getAccessKeyId();
|
||||
if (accessKeyId != null && !"test".equals(accessKeyId)
|
||||
&& !accessKeyId.equals(requestContext.getAccountId())) {
|
||||
throw new IcebergRestException(403, "ForbiddenException",
|
||||
"AWS Glue's Iceberg REST endpoint does not check IAM policies in Floci yet, so under IAM "
|
||||
+ "enforcement it answers only the account's root credentials");
|
||||
}
|
||||
}
|
||||
|
||||
/** The namespace a path segment names, refused when it has more than one level (a {@code 0x1F} separator). */
|
||||
private static String namespace(String segment) {
|
||||
if (segment.indexOf('\u001f') >= 0) {
|
||||
|
||||
@@ -2,6 +2,8 @@ package io.floci.aws.services.glue.iceberg;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.floci.aws.config.EmulatorConfig;
|
||||
import io.floci.aws.core.common.RequestContext;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import jakarta.ws.rs.Consumes;
|
||||
@@ -20,6 +22,12 @@ import jakarta.ws.rs.core.Response;
|
||||
* AWS Glue's Iceberg REST endpoint ({@code https://glue.<region>.amazonaws.com/iceberg}): the twelve operations of the
|
||||
* Apache Iceberg REST catalog specification AWS lists for it, under the {@code /v1/catalogs/{catalog}} prefix.
|
||||
* {@link GlueIcebergRouteFilter} moves requests signed for Glue onto {@link GlueIcebergRouteFilter#INTERNAL_PREFIX}.
|
||||
*
|
||||
* <p>Under IAM enforcement, no rule maps these routes to the Glue actions AWS checks for them yet, and an unmapped REST
|
||||
* route is allowed, so an IAM principal is refused here rather than let through unchecked: only the account's root
|
||||
* credentials, and a bearer token Floci minted for its own query engine, reach the catalog then. The check sits at
|
||||
* this entry point, not in {@link GlueIcebergCatalog}, because Floci's Athena calls the catalog directly for a caller
|
||||
* IAM already checked.
|
||||
*/
|
||||
@Path(GlueIcebergRouteFilter.INTERNAL_PREFIX + GlueIcebergRouteFilter.ICEBERG_PATH + "/v1")
|
||||
@ApplicationScoped
|
||||
@@ -28,76 +36,80 @@ import jakarta.ws.rs.core.Response;
|
||||
public class GlueIcebergController {
|
||||
|
||||
private final GlueIcebergCatalog catalog;
|
||||
private final EmulatorConfig config;
|
||||
private final RequestContext requestContext;
|
||||
|
||||
@Inject
|
||||
public GlueIcebergController(GlueIcebergCatalog catalog) {
|
||||
public GlueIcebergController(GlueIcebergCatalog catalog, EmulatorConfig config, RequestContext requestContext) {
|
||||
this.catalog = catalog;
|
||||
this.config = config;
|
||||
this.requestContext = requestContext;
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/config")
|
||||
public ObjectNode getConfig(@QueryParam("warehouse") String warehouse) {
|
||||
return catalog.config(warehouse);
|
||||
return catalog().config(warehouse);
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/catalogs/{catalog}/namespaces")
|
||||
public ObjectNode listNamespaces(@PathParam("catalog") String catalogId, @QueryParam("parent") String parent) {
|
||||
return catalog.listNamespaces(catalogId, parent);
|
||||
return catalog().listNamespaces(catalogId, parent);
|
||||
}
|
||||
|
||||
@POST
|
||||
@Path("/catalogs/{catalog}/namespaces")
|
||||
public ObjectNode createNamespace(@PathParam("catalog") String catalogId, JsonNode request) {
|
||||
return catalog.createNamespace(catalogId, request);
|
||||
return catalog().createNamespace(catalogId, request);
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/catalogs/{catalog}/namespaces/{namespace}")
|
||||
public ObjectNode loadNamespaceMetadata(@PathParam("catalog") String catalogId,
|
||||
@PathParam("namespace") String namespace) {
|
||||
return catalog.loadNamespace(catalogId, namespace);
|
||||
return catalog().loadNamespace(catalogId, namespace);
|
||||
}
|
||||
|
||||
@POST
|
||||
@Path("/catalogs/{catalog}/namespaces/{namespace}/properties")
|
||||
public ObjectNode updateNamespaceProperties(@PathParam("catalog") String catalogId,
|
||||
@PathParam("namespace") String namespace, JsonNode request) {
|
||||
return catalog.updateNamespaceProperties(catalogId, namespace, request);
|
||||
return catalog().updateNamespaceProperties(catalogId, namespace, request);
|
||||
}
|
||||
|
||||
@DELETE
|
||||
@Path("/catalogs/{catalog}/namespaces/{namespace}")
|
||||
public Response dropNamespace(@PathParam("catalog") String catalogId, @PathParam("namespace") String namespace) {
|
||||
catalog.dropNamespace(catalogId, namespace);
|
||||
catalog().dropNamespace(catalogId, namespace);
|
||||
return Response.noContent().build();
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/catalogs/{catalog}/namespaces/{namespace}/tables")
|
||||
public ObjectNode listTables(@PathParam("catalog") String catalogId, @PathParam("namespace") String namespace) {
|
||||
return catalog.listTables(catalogId, namespace);
|
||||
return catalog().listTables(catalogId, namespace);
|
||||
}
|
||||
|
||||
@POST
|
||||
@Path("/catalogs/{catalog}/namespaces/{namespace}/tables")
|
||||
public ObjectNode createTable(@PathParam("catalog") String catalogId, @PathParam("namespace") String namespace,
|
||||
JsonNode request) {
|
||||
return catalog.createTable(catalogId, namespace, request);
|
||||
return catalog().createTable(catalogId, namespace, request);
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/catalogs/{catalog}/namespaces/{namespace}/tables/{table}")
|
||||
public ObjectNode loadTable(@PathParam("catalog") String catalogId, @PathParam("namespace") String namespace,
|
||||
@PathParam("table") String table, @QueryParam("snapshots") String snapshots) {
|
||||
return catalog.loadTable(catalogId, namespace, table, snapshots);
|
||||
return catalog().loadTable(catalogId, namespace, table, snapshots);
|
||||
}
|
||||
|
||||
@HEAD
|
||||
@Path("/catalogs/{catalog}/namespaces/{namespace}/tables/{table}")
|
||||
public Response tableExists(@PathParam("catalog") String catalogId, @PathParam("namespace") String namespace,
|
||||
@PathParam("table") String table) {
|
||||
catalog.tableExists(catalogId, namespace, table);
|
||||
catalog().tableExists(catalogId, namespace, table);
|
||||
return Response.noContent().build();
|
||||
}
|
||||
|
||||
@@ -105,14 +117,28 @@ public class GlueIcebergController {
|
||||
@Path("/catalogs/{catalog}/namespaces/{namespace}/tables/{table}")
|
||||
public ObjectNode updateTable(@PathParam("catalog") String catalogId, @PathParam("namespace") String namespace,
|
||||
@PathParam("table") String table, JsonNode request) {
|
||||
return catalog.commitTable(catalogId, namespace, table, request);
|
||||
return catalog().commitTable(catalogId, namespace, table, request);
|
||||
}
|
||||
|
||||
@DELETE
|
||||
@Path("/catalogs/{catalog}/namespaces/{namespace}/tables/{table}")
|
||||
public Response dropTable(@PathParam("catalog") String catalogId, @PathParam("namespace") String namespace,
|
||||
@PathParam("table") String table) {
|
||||
catalog.dropTable(catalogId, namespace, table);
|
||||
catalog().dropTable(catalogId, namespace, table);
|
||||
return Response.noContent().build();
|
||||
}
|
||||
|
||||
/** The catalog, once the caller is one this endpoint can answer under IAM enforcement. */
|
||||
private GlueIcebergCatalog catalog() {
|
||||
if (config.services().iam().enforcementEnabled()) {
|
||||
String accessKeyId = requestContext.getAccessKeyId();
|
||||
if (accessKeyId != null && !"test".equals(accessKeyId)
|
||||
&& !accessKeyId.equals(requestContext.getAccountId())) {
|
||||
throw new IcebergRestException(403, "ForbiddenException",
|
||||
"AWS Glue's Iceberg REST endpoint does not check IAM policies in Floci yet, so under IAM "
|
||||
+ "enforcement it answers only the account's root credentials");
|
||||
}
|
||||
}
|
||||
return catalog;
|
||||
}
|
||||
}
|
||||
@@ -1,18 +1,24 @@
|
||||
package io.floci.aws.services.glue.iceberg;
|
||||
|
||||
import io.floci.aws.core.common.AccountContextFilter;
|
||||
import io.floci.aws.core.common.ResolvedServiceCatalog;
|
||||
import io.floci.aws.core.common.SignedServiceRoute;
|
||||
import jakarta.annotation.Priority;
|
||||
import jakarta.enterprise.inject.Instance;
|
||||
import jakarta.inject.Inject;
|
||||
import jakarta.ws.rs.container.ContainerRequestContext;
|
||||
import jakarta.ws.rs.container.ContainerRequestFilter;
|
||||
import jakarta.ws.rs.container.PreMatching;
|
||||
import jakarta.ws.rs.ext.Provider;
|
||||
|
||||
import java.util.Optional;
|
||||
import java.util.function.Predicate;
|
||||
|
||||
/**
|
||||
* Routes AWS Glue's Iceberg REST endpoint, {@code /iceberg}, which S3's path-style routes would otherwise take for a
|
||||
* bucket named {@code iceberg}: a request signed for {@code glue} is moved onto {@link #INTERNAL_PREFIX}, where
|
||||
* {@link GlueIcebergController} serves it.
|
||||
* {@link GlueIcebergController} serves it. So is one bearing a token {@link GlueIcebergTokens} issued, as the account
|
||||
* and in the Region the token acts as; a bearer token it did not issue is no Glue request.
|
||||
*/
|
||||
@Provider
|
||||
@PreMatching
|
||||
@@ -22,15 +28,38 @@ public class GlueIcebergRouteFilter implements ContainerRequestFilter {
|
||||
static final String INTERNAL_PREFIX = "/_glueiceberg";
|
||||
static final String ICEBERG_PATH = "/iceberg";
|
||||
|
||||
private static final String BEARER = "Bearer ";
|
||||
|
||||
private final SignedServiceRoute route;
|
||||
private final Predicate<String> icebergPaths = SignedServiceRoute.under(ICEBERG_PATH);
|
||||
// A @PreMatching filter is wired into the request pipeline at build time, so holding the tokens bean directly would
|
||||
// place it, and the SecureRandom it holds, in the native-image build heap. Resolve it per bearer request instead.
|
||||
private final Instance<GlueIcebergTokens> tokens;
|
||||
|
||||
@Inject
|
||||
public GlueIcebergRouteFilter(ResolvedServiceCatalog catalog) {
|
||||
this.route = new SignedServiceRoute(catalog, "glue", INTERNAL_PREFIX, SignedServiceRoute.under(ICEBERG_PATH));
|
||||
public GlueIcebergRouteFilter(ResolvedServiceCatalog catalog, Instance<GlueIcebergTokens> tokens) {
|
||||
this.route = new SignedServiceRoute(catalog, "glue", INTERNAL_PREFIX, icebergPaths);
|
||||
this.tokens = tokens;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void filter(ContainerRequestContext ctx) {
|
||||
String authorization = ctx.getHeaderString("Authorization");
|
||||
if (authorization != null && authorization.startsWith(BEARER)) {
|
||||
String path = ctx.getUriInfo().getPath();
|
||||
String normalizedPath = path.startsWith("/") ? path : "/" + path;
|
||||
Optional<GlueIcebergTokens.Grant> grant = tokens.get()
|
||||
.resolve(authorization.substring(BEARER.length()).trim());
|
||||
if (grant.isPresent() && icebergPaths.test(normalizedPath)) {
|
||||
ctx.setRequestUri(ctx.getUriInfo().getRequestUriBuilder()
|
||||
.replacePath(INTERNAL_PREFIX + normalizedPath)
|
||||
.build());
|
||||
ctx.setProperty(SignedServiceRoute.INTERNAL_PREFIX_PROPERTY, INTERNAL_PREFIX);
|
||||
ctx.setProperty(AccountContextFilter.PINNED_ACCOUNT_PROPERTY, grant.get().accountId());
|
||||
ctx.setProperty(AccountContextFilter.PINNED_REGION_PROPERTY, grant.get().region());
|
||||
return;
|
||||
}
|
||||
}
|
||||
route.apply(ctx);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package io.floci.aws.services.glue.iceberg;
|
||||
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
|
||||
import java.security.SecureRandom;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.Base64;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
/**
|
||||
* Bearer tokens for Floci's own callers of the Glue Iceberg REST endpoint: the DuckDB sidecar that runs Athena's
|
||||
* Iceberg statements attaches the endpoint with one (DuckDB signs catalog requests with SigV4 only over HTTPS, and
|
||||
* the endpoint accepts OAuth bearer tokens on AWS too). Each token acts as one account in one Region and expires.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class GlueIcebergTokens {
|
||||
|
||||
private static final int TOKEN_BYTES = 32;
|
||||
|
||||
private final SecureRandom random = new SecureRandom();
|
||||
private final Map<String, Grant> grants = new ConcurrentHashMap<>();
|
||||
private final Clock clock;
|
||||
|
||||
public GlueIcebergTokens() {
|
||||
this(Clock.systemUTC());
|
||||
}
|
||||
|
||||
GlueIcebergTokens(Clock clock) {
|
||||
this.clock = clock;
|
||||
}
|
||||
|
||||
/** A token that acts as {@code accountId} in {@code region} until {@code lifetime} has passed. */
|
||||
public String mint(String accountId, String region, Duration lifetime) {
|
||||
Instant now = clock.instant();
|
||||
grants.values().removeIf(grant -> !now.isBefore(grant.expiresAt()));
|
||||
byte[] bytes = new byte[TOKEN_BYTES];
|
||||
random.nextBytes(bytes);
|
||||
String token = Base64.getUrlEncoder().withoutPadding().encodeToString(bytes);
|
||||
grants.put(token, new Grant(accountId, region, now.plus(lifetime)));
|
||||
return token;
|
||||
}
|
||||
|
||||
/** Gives a token up before it expires, once its caller is done. */
|
||||
public void revoke(String token) {
|
||||
grants.remove(token);
|
||||
}
|
||||
|
||||
/** The account and Region a live token acts as. */
|
||||
Optional<Grant> resolve(String token) {
|
||||
Grant grant = token == null ? null : grants.get(token);
|
||||
return grant != null && clock.instant().isBefore(grant.expiresAt()) ? Optional.of(grant) : Optional.empty();
|
||||
}
|
||||
|
||||
record Grant(String accountId, String region, Instant expiresAt) {
|
||||
}
|
||||
}
|
||||
@@ -5,7 +5,7 @@ package io.floci.aws.services.glue.iceberg;
|
||||
* "code"}}}), whose {@code type} an Iceberg client maps to its own exception: {@code NoSuchTableException},
|
||||
* {@code CommitFailedException} and so on.
|
||||
*/
|
||||
final class IcebergRestException extends RuntimeException {
|
||||
public final class IcebergRestException extends RuntimeException {
|
||||
|
||||
private final int code;
|
||||
private final String type;
|
||||
@@ -16,11 +16,11 @@ final class IcebergRestException extends RuntimeException {
|
||||
this.type = type;
|
||||
}
|
||||
|
||||
int code() {
|
||||
public int code() {
|
||||
return code;
|
||||
}
|
||||
|
||||
String type() {
|
||||
public String type() {
|
||||
return type;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,307 @@
|
||||
package io.floci.aws.services.glue.iceberg;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.floci.aws.services.glue.model.Column;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* The Iceberg {@code CreateTableRequest} an Athena {@code CREATE TABLE ... TBLPROPERTIES ('table_type'='ICEBERG')}
|
||||
* describes: its columns' Hive types as an Iceberg schema, field ids assigned top-level first and then nested in
|
||||
* order, and its {@code PARTITIONED BY} entries as a partition spec of identity, {@code bucket}, {@code truncate},
|
||||
* {@code year}, {@code month}, {@code day} and {@code hour} transforms. As in Athena, {@code tinyint},
|
||||
* {@code smallint} and {@code char} columns are refused.
|
||||
*/
|
||||
public final class IcebergSchemas {
|
||||
|
||||
/** The first partition field id Iceberg assigns. */
|
||||
private static final int FIRST_PARTITION_FIELD_ID = 1000;
|
||||
|
||||
private static final JsonNodeFactory JSON = JsonNodeFactory.instance;
|
||||
|
||||
/** One {@code PARTITIONED BY} entry: a transform ({@code identity}, {@code bucket}, ...), its argument, a column. */
|
||||
public record PartitionField(String transform, Integer argument, String sourceColumn) {
|
||||
}
|
||||
|
||||
private IcebergSchemas() {
|
||||
}
|
||||
|
||||
public static ObjectNode createTableRequest(String name, List<Column> columns, List<PartitionField> partitioning,
|
||||
String location, Map<String, String> properties) {
|
||||
ObjectNode request = JSON.objectNode();
|
||||
request.put("name", name);
|
||||
if (location != null) {
|
||||
request.put("location", location);
|
||||
}
|
||||
ObjectNode schema = request.putObject("schema");
|
||||
schema.put("type", "struct");
|
||||
schema.put("schema-id", 0);
|
||||
ArrayNode fields = schema.putArray("fields");
|
||||
int[] nextId = {columns.size() + 1};
|
||||
for (int i = 0; i < columns.size(); i++) {
|
||||
Column column = columns.get(i);
|
||||
ObjectNode field = fields.addObject();
|
||||
field.put("id", i + 1);
|
||||
field.put("name", column.getName());
|
||||
field.put("required", false);
|
||||
field.set("type", icebergType(new TypeReader(column.getType()), nextId));
|
||||
if (column.getComment() != null) {
|
||||
field.put("doc", column.getComment());
|
||||
}
|
||||
}
|
||||
ObjectNode spec = request.putObject("partition-spec");
|
||||
spec.put("spec-id", 0);
|
||||
ArrayNode specFields = spec.putArray("fields");
|
||||
int partitionId = FIRST_PARTITION_FIELD_ID;
|
||||
for (PartitionField partition : partitioning) {
|
||||
JsonNode source = null;
|
||||
for (JsonNode field : fields) {
|
||||
if (field.path("name").asText().equalsIgnoreCase(partition.sourceColumn())) {
|
||||
source = field;
|
||||
}
|
||||
}
|
||||
if (source == null) {
|
||||
throw new IllegalArgumentException("PARTITIONED BY names no column: " + partition.sourceColumn());
|
||||
}
|
||||
String transform = partition.transform().toLowerCase(Locale.ROOT);
|
||||
String sourceName = source.path("name").asText();
|
||||
ObjectNode specField = specFields.addObject();
|
||||
specField.put("name", switch (transform) {
|
||||
case "identity" -> sourceName;
|
||||
case "truncate" -> sourceName + "_trunc";
|
||||
default -> sourceName + "_" + transform;
|
||||
});
|
||||
specField.put("transform", partitionTransform(transform, partition.argument(), sourceName,
|
||||
source.path("type")));
|
||||
specField.put("source-id", source.path("id").asInt());
|
||||
specField.put("field-id", partitionId++);
|
||||
}
|
||||
ObjectNode requestProperties = request.putObject("properties");
|
||||
requestProperties.put("format-version", String.valueOf(IcebergTableMetadata.DEFAULT_FORMAT_VERSION));
|
||||
properties.forEach(requestProperties::put);
|
||||
return request;
|
||||
}
|
||||
|
||||
/**
|
||||
* The Iceberg transform a {@code PARTITIONED BY} entry names, refused when its width or its column's type is not
|
||||
* one Athena takes: {@code bucket(N, col)} and {@code truncate(L, col)} need a positive width, the others none;
|
||||
* {@code year}, {@code month} and {@code day} take a date or timestamp, {@code hour} a timestamp, {@code bucket}
|
||||
* an int, long, decimal, date, timestamp, string or binary, and {@code truncate} an int, long, decimal or string.
|
||||
*/
|
||||
private static String partitionTransform(String transform, Integer width, String column, JsonNode type) {
|
||||
boolean widthed = transform.equals("bucket") || transform.equals("truncate");
|
||||
if (!Set.of("identity", "bucket", "truncate", "year", "month", "day", "hour").contains(transform)) {
|
||||
throw new IllegalArgumentException("Unsupported partition transform: " + transform);
|
||||
}
|
||||
if (widthed && (width == null || width <= 0)) {
|
||||
throw new IllegalArgumentException("Partition transform " + transform + " needs a positive width: "
|
||||
+ transform + "(N, " + column + ")");
|
||||
}
|
||||
if (!widthed && width != null) {
|
||||
throw new IllegalArgumentException("Partition transform " + transform + " takes no width: " + transform
|
||||
+ "(" + column + ")");
|
||||
}
|
||||
String typeName = type.isTextual() ? type.asText().replaceFirst("\\(.*", "") : type.path("type").asText();
|
||||
Set<String> accepted = switch (transform) {
|
||||
case "year", "month", "day" -> Set.of("date", "timestamp");
|
||||
case "hour" -> Set.of("timestamp");
|
||||
case "bucket" -> Set.of("int", "long", "decimal", "date", "timestamp", "string", "binary");
|
||||
case "truncate" -> Set.of("int", "long", "decimal", "string");
|
||||
default -> Set.of("boolean", "int", "long", "float", "double", "decimal", "date", "timestamp", "string",
|
||||
"binary");
|
||||
};
|
||||
if (!accepted.contains(typeName)) {
|
||||
throw new IllegalArgumentException("Partition transform " + transform + " does not take column " + column
|
||||
+ " of type " + typeName);
|
||||
}
|
||||
return widthed ? transform + "[" + width + "]" : transform;
|
||||
}
|
||||
|
||||
private static JsonNode icebergType(TypeReader reader, int[] nextId) {
|
||||
String word = reader.word().toLowerCase(Locale.ROOT);
|
||||
switch (word) {
|
||||
case "array" -> {
|
||||
reader.expect('<');
|
||||
ObjectNode list = JSON.objectNode();
|
||||
list.put("type", "list");
|
||||
list.put("element-id", nextId[0]++);
|
||||
list.set("element", icebergType(reader, nextId));
|
||||
list.put("element-required", false);
|
||||
reader.expect('>');
|
||||
return list;
|
||||
}
|
||||
case "map" -> {
|
||||
reader.expect('<');
|
||||
ObjectNode map = JSON.objectNode();
|
||||
map.put("type", "map");
|
||||
map.put("key-id", nextId[0]++);
|
||||
map.put("value-id", nextId[0]++);
|
||||
map.set("key", icebergType(reader, nextId));
|
||||
reader.expect(',');
|
||||
map.set("value", icebergType(reader, nextId));
|
||||
map.put("value-required", false);
|
||||
reader.expect('>');
|
||||
return map;
|
||||
}
|
||||
case "struct" -> {
|
||||
reader.expect('<');
|
||||
ObjectNode struct = JSON.objectNode();
|
||||
struct.put("type", "struct");
|
||||
ArrayNode fields = struct.putArray("fields");
|
||||
List<String> names = new ArrayList<>();
|
||||
List<TypeReader.Mark> types = new ArrayList<>();
|
||||
do {
|
||||
names.add(reader.word());
|
||||
reader.expect(':');
|
||||
types.add(reader.mark());
|
||||
reader.skipType();
|
||||
} while (reader.accept(','));
|
||||
reader.expect('>');
|
||||
// Fields of one struct take their ids before any type nested in them, as Iceberg assigns them.
|
||||
int first = nextId[0];
|
||||
nextId[0] += names.size();
|
||||
for (int i = 0; i < names.size(); i++) {
|
||||
ObjectNode field = fields.addObject();
|
||||
field.put("id", first + i);
|
||||
field.put("name", names.get(i));
|
||||
field.put("required", false);
|
||||
field.set("type", icebergType(reader.at(types.get(i)), nextId));
|
||||
}
|
||||
return struct;
|
||||
}
|
||||
case "decimal" -> {
|
||||
reader.expect('(');
|
||||
String precision = reader.word();
|
||||
reader.expect(',');
|
||||
String scale = reader.word();
|
||||
reader.expect(')');
|
||||
return JSON.textNode("decimal(" + precision + ", " + scale + ")");
|
||||
}
|
||||
case "tinyint", "smallint", "char" ->
|
||||
throw new IllegalArgumentException(word + " is not supported for Iceberg tables in Athena");
|
||||
case "varchar" -> {
|
||||
if (reader.accept('(')) {
|
||||
reader.word();
|
||||
reader.expect(')');
|
||||
}
|
||||
return JSON.textNode("string");
|
||||
}
|
||||
case "string" -> {
|
||||
return JSON.textNode("string");
|
||||
}
|
||||
case "int", "integer" -> {
|
||||
return JSON.textNode("int");
|
||||
}
|
||||
case "bigint" -> {
|
||||
return JSON.textNode("long");
|
||||
}
|
||||
case "float", "real" -> {
|
||||
return JSON.textNode("float");
|
||||
}
|
||||
case "double" -> {
|
||||
return JSON.textNode("double");
|
||||
}
|
||||
case "boolean" -> {
|
||||
return JSON.textNode("boolean");
|
||||
}
|
||||
case "date" -> {
|
||||
return JSON.textNode("date");
|
||||
}
|
||||
case "timestamp" -> {
|
||||
if (reader.accept('(')) {
|
||||
reader.word();
|
||||
reader.expect(')');
|
||||
}
|
||||
return JSON.textNode("timestamp");
|
||||
}
|
||||
case "binary", "varbinary" -> {
|
||||
return JSON.textNode("binary");
|
||||
}
|
||||
default -> throw new IllegalArgumentException("Unsupported Iceberg column type: " + word);
|
||||
}
|
||||
}
|
||||
|
||||
/** Reads a Hive type string a token at a time. */
|
||||
private static final class TypeReader {
|
||||
|
||||
private final String text;
|
||||
private int position;
|
||||
|
||||
TypeReader(String text) {
|
||||
this.text = text;
|
||||
}
|
||||
|
||||
record Mark(int position) {
|
||||
}
|
||||
|
||||
Mark mark() {
|
||||
skipSpaces();
|
||||
return new Mark(position);
|
||||
}
|
||||
|
||||
TypeReader at(Mark mark) {
|
||||
TypeReader reader = new TypeReader(text);
|
||||
reader.position = mark.position();
|
||||
return reader;
|
||||
}
|
||||
|
||||
String word() {
|
||||
skipSpaces();
|
||||
int start = position;
|
||||
while (position < text.length()
|
||||
&& (Character.isLetterOrDigit(text.charAt(position)) || text.charAt(position) == '_')) {
|
||||
position++;
|
||||
}
|
||||
if (start == position) {
|
||||
throw new IllegalArgumentException("Cannot read type " + text + " at " + position);
|
||||
}
|
||||
return text.substring(start, position);
|
||||
}
|
||||
|
||||
boolean accept(char c) {
|
||||
skipSpaces();
|
||||
if (position < text.length() && text.charAt(position) == c) {
|
||||
position++;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
void expect(char c) {
|
||||
if (!accept(c)) {
|
||||
throw new IllegalArgumentException("Cannot read type " + text + ": expected '" + c + "' at "
|
||||
+ position);
|
||||
}
|
||||
}
|
||||
|
||||
/** Moves past one type, nested brackets included. */
|
||||
void skipType() {
|
||||
word();
|
||||
skipSpaces();
|
||||
if (position < text.length() && (text.charAt(position) == '<' || text.charAt(position) == '(')) {
|
||||
int depth = 0;
|
||||
do {
|
||||
char c = text.charAt(position++);
|
||||
if (c == '<' || c == '(') {
|
||||
depth++;
|
||||
} else if (c == '>' || c == ')') {
|
||||
depth--;
|
||||
}
|
||||
} while (depth > 0 && position < text.length());
|
||||
}
|
||||
}
|
||||
|
||||
private void skipSpaces() {
|
||||
while (position < text.length() && Character.isWhitespace(text.charAt(position))) {
|
||||
position++;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -325,6 +325,18 @@ final class IcebergTableMetadata {
|
||||
}
|
||||
}
|
||||
metadata.set("snapshot-log", log);
|
||||
// So do the removed snapshots' statistics files, as Iceberg's metadata builder drops them.
|
||||
for (String statistics : List.of("statistics", "partition-statistics")) {
|
||||
if (metadata.has(statistics)) {
|
||||
ArrayNode keptStatistics = JSON.arrayNode();
|
||||
for (JsonNode file : metadata.withArray(statistics)) {
|
||||
if (!removed.contains(file.path("snapshot-id").asLong())) {
|
||||
keptStatistics.add(file);
|
||||
}
|
||||
}
|
||||
metadata.set(statistics, keptStatistics);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -26,7 +26,8 @@ class AthenaHiveDdlExecutorTest {
|
||||
table.setName("events");
|
||||
when(glue.getTable("lake", "events")).thenReturn(table);
|
||||
doThrow(new AwsException("EntityNotFoundException", "Table not found", 400)).when(glue).deleteTable("lake", "events");
|
||||
AthenaHiveDdlExecutor executor = new AthenaHiveDdlExecutor(glue, Mockito.mock(S3Service.class));
|
||||
AthenaHiveDdlExecutor executor = new AthenaHiveDdlExecutor(glue, Mockito.mock(S3Service.class),
|
||||
Mockito.mock(AthenaIcebergStatements.class));
|
||||
|
||||
assertDoesNotThrow(() -> executor.execute(AthenaHiveDdl.parse("DROP TABLE IF EXISTS events"), "lake"));
|
||||
AwsException e = assertThrows(AwsException.class,
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package io.floci.aws.services.athena;
|
||||
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.services.glue.iceberg.IcebergSchemas;
|
||||
import io.floci.aws.services.glue.model.Column;
|
||||
import io.floci.aws.services.glue.model.StorageDescriptor;
|
||||
import io.floci.aws.services.glue.model.Table;
|
||||
@@ -109,15 +110,60 @@ class AthenaHiveDdlTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void createTableWithoutExternalIsLeftToIcebergAndCtasOrRefused() {
|
||||
assertNull(AthenaHiveDdl.parse("CREATE TABLE t (a int) LOCATION 's3://b/t/' TBLPROPERTIES ('table_type'='ICEBERG')"));
|
||||
void createTableWithoutExternalIsIcebergOrLeftToCtasOrRefused() {
|
||||
assertInstanceOf(AthenaHiveDdl.CreateIcebergTable.class, AthenaHiveDdl.parse(
|
||||
"CREATE TABLE t (a int) LOCATION 's3://b/t/' TBLPROPERTIES ('table_type'='ICEBERG')"));
|
||||
assertNull(AthenaHiveDdl.parse("CREATE TABLE t WITH (format = 'PARQUET') AS SELECT 1 AS a"));
|
||||
assertNull(AthenaHiveDdl.parse("CREATE TABLE t WITH (table_type = 'ICEBERG') AS SELECT 1 AS a"));
|
||||
assertNull(AthenaHiveDdl.parse("CREATE TABLE t AS SELECT 1 AS a"));
|
||||
AwsException hive = assertThrows(AwsException.class,
|
||||
() -> AthenaHiveDdl.parse("CREATE TABLE t (a int) STORED AS PARQUET LOCATION 's3://b/t/'"));
|
||||
assertTrue(hive.getMessage().contains("EXTERNAL"), hive.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anIcebergCreateTableKeepsItsColumnsPartitionTransformsLocationAndProperties() {
|
||||
AthenaHiveDdl.CreateIcebergTable create = assertInstanceOf(AthenaHiveDdl.CreateIcebergTable.class,
|
||||
AthenaHiveDdl.parse("""
|
||||
CREATE TABLE IF NOT EXISTS Lake.events (
|
||||
id bigint COMMENT 'the id',
|
||||
category string,
|
||||
ts timestamp,
|
||||
name string)
|
||||
PARTITIONED BY (category, bucket(16, id), day(ts), truncate(4, name))
|
||||
LOCATION 's3://lake/events/'
|
||||
TBLPROPERTIES ('table_type'='ICEBERG', 'format'='parquet', 'vacuum_min_snapshots_to_keep'='3');
|
||||
"""));
|
||||
|
||||
assertTrue(create.ifNotExists());
|
||||
assertEquals(new AthenaHiveDdl.TableRef("lake", "events"), create.ref());
|
||||
assertEquals(List.of("id:bigint", "category:string", "ts:timestamp", "name:string"), create.columns().stream()
|
||||
.map(column -> column.getName() + ":" + column.getType()).toList());
|
||||
assertEquals("the id", create.columns().getFirst().getComment());
|
||||
assertEquals(List.of(new IcebergSchemas.PartitionField("identity", null, "category"),
|
||||
new IcebergSchemas.PartitionField("bucket", 16, "id"),
|
||||
new IcebergSchemas.PartitionField("day", null, "ts"),
|
||||
new IcebergSchemas.PartitionField("truncate", 4, "name")), create.partitioning());
|
||||
assertEquals("s3://lake/events/", create.location());
|
||||
assertEquals(Map.of("format", "parquet", "vacuum_min_snapshots_to_keep", "3"), create.properties());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aMalformedIcebergPartitionTransformSaysWhatIsWrong() {
|
||||
AwsException e = assertThrows(AwsException.class, () -> AthenaHiveDdl.parse(
|
||||
"CREATE TABLE t (id int) PARTITIONED BY (bucket(id, 16)) TBLPROPERTIES ('table_type'='ICEBERG')"));
|
||||
|
||||
assertEquals("InvalidRequestException", e.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void vacuumNamesItsTable() {
|
||||
assertEquals(new AthenaHiveDdl.TableRef("lake", "events"), assertInstanceOf(AthenaHiveDdl.Vacuum.class,
|
||||
AthenaHiveDdl.parse("VACUUM lake.events;")).ref());
|
||||
assertEquals(new AthenaHiveDdl.TableRef(null, "_events"), assertInstanceOf(AthenaHiveDdl.Vacuum.class,
|
||||
AthenaHiveDdl.parse("vacuum `_events`")).ref());
|
||||
}
|
||||
|
||||
@Test
|
||||
void dropRepairAndShowNameTheirTable() {
|
||||
AthenaHiveDdl.DropTable drop = assertInstanceOf(AthenaHiveDdl.DropTable.class,
|
||||
|
||||
@@ -0,0 +1,217 @@
|
||||
package io.floci.aws.services.athena;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
import io.floci.aws.core.common.RequestScopes;
|
||||
import io.floci.aws.core.storage.StorageFactory;
|
||||
import io.floci.aws.services.athena.model.QueryExecution;
|
||||
import io.floci.aws.services.athena.model.QueryExecutionContext;
|
||||
import io.floci.aws.services.athena.model.QueryExecutionState;
|
||||
import io.floci.aws.services.athena.model.ResultConfiguration;
|
||||
import io.floci.aws.services.floci.duck.FlociDuckClient;
|
||||
import io.floci.aws.services.glue.GlueService;
|
||||
import io.floci.aws.services.glue.iceberg.GlueIcebergCatalog;
|
||||
import io.floci.aws.services.glue.model.Database;
|
||||
import io.floci.aws.services.glue.model.Table;
|
||||
import io.floci.aws.services.s3.S3Service;
|
||||
import io.floci.aws.testing.SidecarContainersProfile;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import io.vertx.core.Vertx;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.TreeMap;
|
||||
|
||||
import static org.awaitility.Awaitility.await;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.junit.jupiter.api.Assertions.fail;
|
||||
|
||||
/**
|
||||
* Athena's Iceberg statements run end to end through the real floci-duck sidecar: {@code CREATE TABLE} makes a Glue
|
||||
* Iceberg table, {@code INSERT}, {@code UPDATE}, {@code DELETE} and {@code MERGE} write it through the sidecar's
|
||||
* attachment of Glue's Iceberg REST endpoint, each commit moving the Glue table's {@code metadata_location}, and
|
||||
* {@code VACUUM} expires old snapshots and removes files nothing references.
|
||||
*/
|
||||
@QuarkusTest
|
||||
@TestProfile(SidecarContainersProfile.class)
|
||||
class AthenaIcebergSidecarIntegrationTest {
|
||||
|
||||
private static final String ACCOUNT = "000000000000";
|
||||
private static final String REGION = "us-east-1";
|
||||
|
||||
@Inject
|
||||
StorageFactory storageFactory;
|
||||
|
||||
@Inject
|
||||
FlociDuckClient duck;
|
||||
|
||||
@Inject
|
||||
GlueService glue;
|
||||
|
||||
@Inject
|
||||
S3Service s3;
|
||||
|
||||
@Inject
|
||||
Vertx vertx;
|
||||
|
||||
@Inject
|
||||
GlueViewDdlBuilder ddlBuilder;
|
||||
|
||||
@Inject
|
||||
RegionResolver regionResolver;
|
||||
|
||||
@Inject
|
||||
AthenaIcebergStatements icebergStatements;
|
||||
|
||||
@Inject
|
||||
GlueIcebergCatalog catalog;
|
||||
|
||||
private AthenaService athena;
|
||||
private String bucket;
|
||||
private String database;
|
||||
|
||||
@BeforeAll
|
||||
static void requireDocker() {
|
||||
SidecarContainersProfile.requireDocker();
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void createDatabase() {
|
||||
athena = new AthenaService(storageFactory, duck, glue, s3, AthenaTestConfigs.realQueries(), vertx, ddlBuilder, regionResolver,
|
||||
icebergStatements);
|
||||
long suffix = System.nanoTime();
|
||||
bucket = "athena-iceberg-" + suffix;
|
||||
database = "lake_" + suffix;
|
||||
s3.createBucket(bucket, REGION);
|
||||
Database lake = new Database(database);
|
||||
lake.setLocationUri("s3://" + bucket + "/lake");
|
||||
RequestScopes.runAs(ACCOUNT, REGION, () -> glue.createDatabase(lake));
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void dropDatabase() {
|
||||
RequestScopes.runAs(ACCOUNT, REGION, () -> {
|
||||
for (Table table : glue.getTables(database)) {
|
||||
glue.deleteTable(database, table.getName());
|
||||
}
|
||||
glue.deleteDatabase(database);
|
||||
});
|
||||
TableLocation.of("s3://" + bucket + "/").forEachObject(s3, object -> s3.deleteObject(bucket, object.getKey()));
|
||||
s3.deleteBucket(bucket);
|
||||
}
|
||||
|
||||
@Test
|
||||
void anIcebergTableIsCreatedThenWrittenByEachDmlStatementAndReadBack() {
|
||||
run("CREATE TABLE events (id bigint, name string, category string) LOCATION 's3://" + bucket
|
||||
+ "/lake/events/' TBLPROPERTIES ('table_type'='ICEBERG')");
|
||||
|
||||
committed("INSERT INTO events VALUES (1, 'a', 'x'), (2, 'b', 'y')");
|
||||
committed("UPDATE " + database + ".events SET name = 'bb' WHERE id = 2");
|
||||
committed("DELETE FROM awsdatacatalog." + database + ".events WHERE id = 1");
|
||||
committed("""
|
||||
MERGE INTO events t
|
||||
USING (SELECT 3 AS id, 'c' AS name, 'x' AS category UNION ALL SELECT 2, 'b2', 'y') s
|
||||
ON t.id = s.id
|
||||
WHEN MATCHED THEN UPDATE SET name = s.name
|
||||
WHEN NOT MATCHED THEN INSERT VALUES (s.id, s.name, s.category)""");
|
||||
|
||||
assertEquals(List.of(row("id", "2", "name", "b2", "category", "y"), row("id", "3", "name", "c", "category", "x")),
|
||||
rows("SELECT id, name, category FROM events ORDER BY id"));
|
||||
assertEquals("2", loadTable("events").path("metadata").path("properties").path("format-version").asText());
|
||||
}
|
||||
|
||||
/** Runs a write and checks its commit landed on the Glue table, moving its {@code metadata_location}. */
|
||||
private void committed(String sql) {
|
||||
String before = metadataLocation("events");
|
||||
run(sql);
|
||||
assertNotEquals(before, metadataLocation("events"), sql);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aPartitionedIcebergTableIsWrittenByItsSpec() {
|
||||
run("CREATE TABLE events (id bigint, category string) PARTITIONED BY (category, bucket(4, id)) LOCATION 's3://"
|
||||
+ bucket + "/lake/events/' TBLPROPERTIES ('table_type'='ICEBERG')");
|
||||
JsonNode spec = loadTable("events").path("metadata").path("partition-specs").get(0).path("fields");
|
||||
assertEquals("category", spec.get(0).path("name").asText());
|
||||
assertEquals("bucket[4]", spec.get(1).path("transform").asText());
|
||||
|
||||
run("INSERT INTO events VALUES (1, 'x'), (2, 'y'), (3, 'x')");
|
||||
|
||||
assertEquals(List.of(row("category", "x", "n", "2"), row("category", "y", "n", "1")),
|
||||
rows("SELECT category, count(*) AS n FROM events GROUP BY category ORDER BY category"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void vacuumExpiresSnapshotsOlderThanTheTablesMaximumAgeAndRemovesOrphans() {
|
||||
run("CREATE TABLE events (id bigint) LOCATION 's3://" + bucket + "/lake/events/' "
|
||||
+ "TBLPROPERTIES ('table_type'='ICEBERG', 'vacuum_max_snapshot_age_seconds'='1')");
|
||||
run("INSERT INTO events VALUES (1)");
|
||||
run("INSERT INTO events VALUES (2)");
|
||||
run("INSERT INTO events VALUES (3)");
|
||||
assertEquals(3, loadTable("events").path("metadata").path("snapshots").size());
|
||||
String orphan = "lake/events/data/orphan.parquet";
|
||||
s3.putObject(bucket, orphan, "not table data".getBytes(StandardCharsets.UTF_8), "application/octet-stream",
|
||||
null);
|
||||
|
||||
// The snapshots and the orphan become older than the table's one-second maximum age.
|
||||
await().atMost(Duration.ofSeconds(30)).pollInterval(Duration.ofSeconds(1)).untilAsserted(() -> {
|
||||
run("VACUUM events");
|
||||
assertEquals(1, loadTable("events").path("metadata").path("snapshots").size());
|
||||
assertTrue(s3.listObjects(bucket, orphan, null, 10).isEmpty(), "the orphan file is removed");
|
||||
});
|
||||
|
||||
assertEquals(List.of(row("id", "1"), row("id", "2"), row("id", "3")),
|
||||
rows("SELECT id FROM events ORDER BY id"));
|
||||
}
|
||||
|
||||
private void run(String sql) {
|
||||
QueryExecutionContext context = new QueryExecutionContext();
|
||||
context.setDatabase(database);
|
||||
String id = RequestScopes.callAs(ACCOUNT, REGION, () -> athena.startQueryExecution(sql, "primary", context,
|
||||
new ResultConfiguration("s3://" + bucket + "/results/")));
|
||||
QueryExecution execution = await().atMost(Duration.ofSeconds(60)).pollInterval(Duration.ofMillis(100))
|
||||
.until(() -> RequestScopes.callAs(ACCOUNT, REGION, () -> athena.getQueryExecution(id)),
|
||||
found -> found.getStatus().getState() != QueryExecutionState.RUNNING
|
||||
&& found.getStatus().getState() != QueryExecutionState.QUEUED);
|
||||
if (execution.getStatus().getState() != QueryExecutionState.SUCCEEDED) {
|
||||
fail(sql + " -> " + execution.getStatus().getState() + ": " + execution.getStatus().getStateChangeReason());
|
||||
}
|
||||
}
|
||||
|
||||
private List<Map<String, String>> rows(String sql) {
|
||||
return RequestScopes.callAs(ACCOUNT, REGION, () -> duck.query(TrinoSqlCompatibility.translate(sql),
|
||||
TrinoSqlCompatibility.FUNCTION_MACROS + ddlBuilder.build(database, sql), ACCOUNT)).stream()
|
||||
.map(found -> {
|
||||
Map<String, String> row = new TreeMap<>();
|
||||
found.forEach((column, value) -> row.put(column, String.valueOf(value)));
|
||||
return row;
|
||||
}).toList();
|
||||
}
|
||||
|
||||
private static Map<String, String> row(String... columnsAndValues) {
|
||||
Map<String, String> row = new TreeMap<>();
|
||||
for (int i = 0; i < columnsAndValues.length; i += 2) {
|
||||
row.put(columnsAndValues[i], columnsAndValues[i + 1]);
|
||||
}
|
||||
return row;
|
||||
}
|
||||
|
||||
private String metadataLocation(String table) {
|
||||
return RequestScopes.callAs(ACCOUNT, REGION,
|
||||
() -> glue.getTable(database, table).getParameters().get("metadata_location"));
|
||||
}
|
||||
|
||||
private JsonNode loadTable(String table) {
|
||||
return RequestScopes.callAs(ACCOUNT, REGION, () -> catalog.loadTable(":", database, table, null));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,324 @@
|
||||
package io.floci.aws.services.athena;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
import io.floci.aws.core.common.docker.ContainerReachableEndpoint;
|
||||
import io.floci.aws.services.floci.duck.FlociDuckClient;
|
||||
import io.floci.aws.services.glue.GlueService;
|
||||
import io.floci.aws.services.glue.iceberg.GlueIcebergCatalog;
|
||||
import io.floci.aws.services.glue.iceberg.GlueIcebergTokens;
|
||||
import io.floci.aws.services.glue.model.Column;
|
||||
import io.floci.aws.services.glue.model.StorageDescriptor;
|
||||
import io.floci.aws.services.glue.model.Table;
|
||||
import io.floci.aws.services.s3.S3Service;
|
||||
import io.floci.aws.services.s3.model.S3Object;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.Mockito;
|
||||
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneOffset;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
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.anyInt;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.ArgumentMatchers.isNull;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* Which statements write an Iceberg table and how they are pointed at the attached catalog, which Iceberg tables
|
||||
* {@code CREATE TABLE} accepts, and which snapshots and files {@code VACUUM} keeps.
|
||||
*/
|
||||
class AthenaIcebergStatementsTest {
|
||||
|
||||
private static final long NOW = 1_000_000_000L;
|
||||
private static final long DAY = Duration.ofDays(1).toMillis();
|
||||
|
||||
private final ObjectMapper mapper = new ObjectMapper();
|
||||
private GlueIcebergCatalog catalog;
|
||||
private GlueService glue;
|
||||
private S3Service s3;
|
||||
private GlueIcebergTokens tokens;
|
||||
private FlociDuckClient duck;
|
||||
private AthenaIcebergStatements statements;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
catalog = Mockito.mock(GlueIcebergCatalog.class);
|
||||
glue = Mockito.mock(GlueService.class);
|
||||
s3 = Mockito.mock(S3Service.class);
|
||||
tokens = Mockito.mock(GlueIcebergTokens.class);
|
||||
duck = Mockito.mock(FlociDuckClient.class);
|
||||
ContainerReachableEndpoint endpoint = Mockito.mock(ContainerReachableEndpoint.class);
|
||||
when(endpoint.baseUrl()).thenReturn("http://floci:4566");
|
||||
statements = new AthenaIcebergStatements(catalog, glue, s3, tokens, endpoint, duck,
|
||||
new RegionResolver("eu-west-1", "111122223333"), mapper,
|
||||
Clock.fixed(Instant.ofEpochMilli(NOW), ZoneOffset.UTC));
|
||||
}
|
||||
|
||||
private void glueTable(String database, String name, boolean iceberg) {
|
||||
Table table = new Table();
|
||||
table.setName(name);
|
||||
Map<String, String> parameters = new HashMap<>();
|
||||
if (iceberg) {
|
||||
parameters.put("table_type", "ICEBERG");
|
||||
parameters.put("metadata_location", "s3://lake/" + name + "/metadata/00000-a.metadata.json");
|
||||
}
|
||||
table.setParameters(parameters);
|
||||
when(glue.getTable(database, name)).thenReturn(table);
|
||||
}
|
||||
|
||||
// ─── Writes ──────────────────────────────────────────────────────────────────
|
||||
|
||||
@Test
|
||||
void theTargetOfEachWritingStatementIsFoundPastCommentsAndQuoting() {
|
||||
String insert = "-- load\n/* batch */ insert into Lake . \"Ev\"\"ents\" (a) SELECT 1";
|
||||
AthenaIcebergStatements.Target target = AthenaIcebergStatements.target(insert);
|
||||
assertEquals("lake", target.database());
|
||||
assertEquals("ev\"ents", target.table());
|
||||
assertEquals("Lake . \"Ev\"\"ents\"", insert.substring(target.start(), target.end()));
|
||||
|
||||
assertEquals(new AthenaIcebergStatements.Target(null, "events", 12, 18),
|
||||
AthenaIcebergStatements.target("DELETE FROM events WHERE id = 1"));
|
||||
AthenaIcebergStatements.Target merge = AthenaIcebergStatements.target(
|
||||
"MERGE INTO awsdatacatalog.lake.events AS t USING src s ON t.id = s.id WHEN MATCHED THEN DELETE");
|
||||
assertEquals("lake", merge.database());
|
||||
assertEquals("events", merge.table());
|
||||
assertEquals("events", AthenaIcebergStatements.target("UPDATE events SET a = 1").table());
|
||||
|
||||
assertNull(AthenaIcebergStatements.target("UPDATE other_catalog.lake.events SET a = 1"));
|
||||
assertNull(AthenaIcebergStatements.target("SELECT * FROM events"));
|
||||
assertNull(AthenaIcebergStatements.target("INSERT INTO"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aWriteToAnIcebergTableGoesThroughTheAttachedCatalogWithATokenForTheCallingAccount() {
|
||||
glueTable("lake", "events", true);
|
||||
when(tokens.mint(eq("111122223333"), eq("eu-west-1"), any())).thenReturn("tok'en");
|
||||
|
||||
AthenaIcebergStatements.IcebergWrite write = statements.write(
|
||||
"INSERT INTO events SELECT * FROM staging", "lake");
|
||||
|
||||
assertEquals("INSERT INTO glue_iceberg.\"lake\".\"events\" SELECT * FROM staging", write.query());
|
||||
assertEquals("""
|
||||
INSTALL iceberg; LOAD iceberg;
|
||||
ATTACH '111122223333' AS glue_iceberg (TYPE iceberg, ENDPOINT 'http://floci:4566/iceberg', \
|
||||
AUTHORIZATION_TYPE 'oauth2', TOKEN 'tok''en', ACCESS_DELEGATION_MODE 'none');
|
||||
""", write.setupSql());
|
||||
statements.finished(write);
|
||||
verify(tokens).revoke("tok'en");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aWriteToAHiveTableOrAMissingOneIsLeftAlone() {
|
||||
glueTable("lake", "hive_events", false);
|
||||
when(glue.getTable("lake", "missing")).thenThrow(new AwsException("EntityNotFoundException", "missing", 400));
|
||||
|
||||
assertNull(statements.write("INSERT INTO lake.hive_events VALUES (1)", "default"));
|
||||
assertNull(statements.write("INSERT INTO missing VALUES (1)", "lake"));
|
||||
assertNull(statements.write("SELECT 1", "lake"));
|
||||
verify(tokens, never()).mint(anyString(), anyString(), any());
|
||||
}
|
||||
|
||||
// ─── CREATE TABLE ─────────────────────────────────────────────────────────────
|
||||
|
||||
private static AthenaHiveDdl.CreateIcebergTable create(boolean ifNotExists, Map<String, String> properties) {
|
||||
return new AthenaHiveDdl.CreateIcebergTable(new AthenaHiveDdl.TableRef(null, "events"), ifNotExists,
|
||||
List.of(new Column("id", "bigint")), List.of(), "s3://lake/events/", properties);
|
||||
}
|
||||
|
||||
@Test
|
||||
void createTableAsksTheCatalogForAVersion2TableWithItsProperties() {
|
||||
when(glue.getTable("lake", "events")).thenThrow(new AwsException("EntityNotFoundException", "missing", 400));
|
||||
|
||||
statements.createTable("lake", create(false, Map.of("Format", "parquet",
|
||||
"vacuum_max_snapshot_age_seconds", "60")));
|
||||
|
||||
ArgumentCaptor<JsonNode> request = ArgumentCaptor.forClass(JsonNode.class);
|
||||
verify(catalog).createTable(eq(":"), eq("lake"), request.capture());
|
||||
assertEquals("events", request.getValue().path("name").asText());
|
||||
assertEquals("s3://lake/events/", request.getValue().path("location").asText());
|
||||
assertEquals(Map.of("format", "parquet", "vacuum_max_snapshot_age_seconds", "60", "format-version", "2"),
|
||||
mapper.convertValue(request.getValue().path("properties"), Map.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createTableRefusesPropertiesAthenaDoesNotAllowAndFormatsFlociCannotWrite() {
|
||||
AwsException unknown = assertThrows(AwsException.class,
|
||||
() -> statements.createTable("lake", create(false, Map.of("write.format.default", "parquet"))));
|
||||
assertTrue(unknown.getMessage().contains("write.format.default"), unknown.getMessage());
|
||||
|
||||
AwsException orc = assertThrows(AwsException.class,
|
||||
() -> statements.createTable("lake", create(false, Map.of("format", "orc"))));
|
||||
assertEquals("InvalidRequestException", orc.getErrorCode());
|
||||
verify(catalog, never()).createTable(anyString(), anyString(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void createTableIfNotExistsLeavesAnExistingTableAlone() {
|
||||
glueTable("lake", "events", true);
|
||||
|
||||
statements.createTable("lake", create(true, Map.of()));
|
||||
|
||||
verify(catalog, never()).createTable(anyString(), anyString(), any());
|
||||
}
|
||||
|
||||
// ─── VACUUM ───────────────────────────────────────────────────────────────────
|
||||
|
||||
private static String snapshot(long id, Long parent, long timestamp) {
|
||||
return "{\"snapshot-id\":" + id + (parent == null ? "" : ",\"parent-snapshot-id\":" + parent)
|
||||
+ ",\"timestamp-ms\":" + timestamp + ",\"manifest-list\":\"s3://lake/events/metadata/snap-" + id
|
||||
+ ".avro\"}";
|
||||
}
|
||||
|
||||
@Test
|
||||
void vacuumKeepsTagsTheNewestSnapshotsOfEachBranchAndAnythingNewerThanTheCutoff() throws Exception {
|
||||
JsonNode metadata = mapper.readTree("{\"snapshots\":[" + String.join(",",
|
||||
snapshot(1, null, 100), snapshot(2, 1L, 200), snapshot(3, 2L, 300), snapshot(4, null, 50),
|
||||
snapshot(5, null, 400)) + "],\"refs\":{\"main\":{\"snapshot-id\":3,\"type\":\"branch\"},"
|
||||
+ "\"v1\":{\"snapshot-id\":1,\"type\":\"tag\"}}}");
|
||||
|
||||
assertEquals(Set.of(3L, 1L, 5L), AthenaIcebergStatements.retainedSnapshots(metadata, 250, 1));
|
||||
assertEquals(Set.of(3L, 2L, 1L, 5L), AthenaIcebergStatements.retainedSnapshots(metadata, 250, 2));
|
||||
assertEquals(Set.of(1L, 2L, 3L, 4L, 5L), AthenaIcebergStatements.retainedSnapshots(metadata, 0, 1));
|
||||
}
|
||||
|
||||
@Test
|
||||
void vacuumExpiresOldSnapshotsAndDeletesOnlyFilesNothingRetainedReferences() throws Exception {
|
||||
glueTable("lake", "events", true);
|
||||
long old = NOW - 10 * DAY;
|
||||
String base = "s3://lake/events/metadata/";
|
||||
ObjectNode before = (ObjectNode) mapper.readTree("{\"table-uuid\":\"u\",\"location\":\"s3://lake/events\","
|
||||
+ "\"properties\":{},\"snapshots\":[" + snapshot(1, null, old) + "," + snapshot(2, 1L, old + 1)
|
||||
+ "],\"refs\":{\"main\":{\"snapshot-id\":2,\"type\":\"branch\"}},\"metadata-log\":[]}");
|
||||
ObjectNode after = before.deepCopy();
|
||||
after.withArray("snapshots").remove(0);
|
||||
// A retained manifest list and a statistics file named with the other S3 schemes are still referenced.
|
||||
((ObjectNode) after.withArray("snapshots").get(0)).put("manifest-list",
|
||||
"s3a://lake/events/metadata/snap-2.avro");
|
||||
after.withArray("statistics").addObject().put("snapshot-id", 2)
|
||||
.put("statistics-path", "s3n://lake/events/metadata/stats-2.puffin");
|
||||
after.withArray("metadata-log").addObject().put("metadata-file", base + "00001-b.metadata.json");
|
||||
when(catalog.loadTable(":", "lake", "events", null)).thenReturn(loaded(base + "00001-b.metadata.json",
|
||||
before));
|
||||
when(catalog.commitTable(eq(":"), eq("lake"), eq("events"), any()))
|
||||
.thenReturn(loaded(base + "00002-c.metadata.json", after));
|
||||
when(s3.getBucketOwnerAccountId("lake")).thenReturn("111122223333");
|
||||
when(duck.query(anyString(), anyString(), eq("111122223333"))).thenReturn(List.of(Map.of(
|
||||
"manifest_path", "s3a://lake/events/metadata/m2.avro",
|
||||
"file_path", "s3://lake/events/data/kept.parquet")));
|
||||
when(s3.listObjectsWithPrefixes(eq("lake"), eq("events/"), isNull(), anyInt(), isNull(), isNull()))
|
||||
.thenReturn(new S3Service.ListObjectsResult(List.of(
|
||||
object("events/metadata/00000-a.metadata.json", old),
|
||||
object("events/metadata/00001-b.metadata.json", old),
|
||||
object("events/metadata/00002-c.metadata.json", NOW),
|
||||
object("events/metadata/snap-1.avro", old),
|
||||
object("events/metadata/snap-2.avro", old),
|
||||
object("events/metadata/stats-2.puffin", old),
|
||||
object("events/metadata/m1.avro", old),
|
||||
object("events/metadata/m2.avro", old),
|
||||
object("events/data/expired.parquet", old),
|
||||
object("events/data/kept.parquet", old),
|
||||
object("events/data/in-flight.parquet", NOW - 1000)), List.of(), false, null));
|
||||
|
||||
statements.vacuum(new AthenaHiveDdl.TableRef("lake", "events"), "default");
|
||||
|
||||
ArgumentCaptor<JsonNode> commit = ArgumentCaptor.forClass(JsonNode.class);
|
||||
verify(catalog).commitTable(eq(":"), eq("lake"), eq("events"), commit.capture());
|
||||
assertEquals(mapper.readTree("""
|
||||
{"requirements":[{"type":"assert-table-uuid","uuid":"u"},
|
||||
{"type":"assert-ref-snapshot-id","ref":"main","snapshot-id":2}],
|
||||
"updates":[{"action":"remove-snapshots","snapshot-ids":[1]}]}
|
||||
"""), mapper.readTree(commit.getValue().toString()));
|
||||
ArgumentCaptor<String> deleted = ArgumentCaptor.forClass(String.class);
|
||||
verify(s3, Mockito.atLeastOnce()).deleteObject(eq("lake"), deleted.capture());
|
||||
assertEquals(Set.of("events/metadata/00000-a.metadata.json", "events/metadata/snap-1.avro",
|
||||
"events/metadata/m1.avro", "events/data/expired.parquet"), Set.copyOf(deleted.getAllValues()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDroppedIcebergTablesFilesAreDeletedOnlyFromTheCallingAccountsBucket() {
|
||||
when(s3.getBucketOwnerAccountId("ours")).thenReturn("111122223333");
|
||||
when(s3.getBucketOwnerAccountId("theirs")).thenReturn("999988887777");
|
||||
when(s3.listObjectsWithPrefixes(eq("ours"), eq("events/"), isNull(), anyInt(), isNull(), isNull()))
|
||||
.thenReturn(new S3Service.ListObjectsResult(List.of(object("events/data/a.parquet", NOW)), List.of(),
|
||||
false, null));
|
||||
|
||||
statements.purge(tableAt("s3://ours/events"));
|
||||
statements.purge(tableAt("s3://theirs/events/"));
|
||||
|
||||
verify(s3).deleteObject("ours", "events/data/a.parquet");
|
||||
verify(s3, never()).listObjectsWithPrefixes(eq("theirs"), any(), any(), anyInt(), any(), any());
|
||||
}
|
||||
|
||||
private static Table tableAt(String location) {
|
||||
Table table = new Table();
|
||||
StorageDescriptor descriptor = new StorageDescriptor();
|
||||
descriptor.setLocation(location);
|
||||
table.setStorageDescriptor(descriptor);
|
||||
return table;
|
||||
}
|
||||
|
||||
@Test
|
||||
void whileFlocisOwnWriteToTheTableRunsVacuumLeavesItsFilesForTheNextRun() throws Exception {
|
||||
glueTable("lake", "events", true);
|
||||
when(tokens.mint(anyString(), anyString(), any())).thenReturn("t");
|
||||
ObjectNode metadata = (ObjectNode) mapper.readTree("{\"table-uuid\":\"u\",\"location\":\"s3://lake/events\","
|
||||
+ "\"properties\":{},\"snapshots\":[],\"refs\":{},\"metadata-log\":[]}");
|
||||
when(catalog.loadTable(":", "lake", "events", null)).thenReturn(loaded(
|
||||
"s3://lake/events/metadata/00000-a.metadata.json", metadata));
|
||||
when(s3.getBucketOwnerAccountId("lake")).thenReturn("111122223333");
|
||||
when(s3.listObjectsWithPrefixes(eq("lake"), eq("events/"), isNull(), anyInt(), isNull(), isNull()))
|
||||
.thenReturn(new S3Service.ListObjectsResult(List.of(
|
||||
object("events/data/staged.parquet", NOW - 10 * DAY)), List.of(), false, null));
|
||||
|
||||
AthenaIcebergStatements.IcebergWrite write = statements.write("INSERT INTO events VALUES (1)", "lake");
|
||||
statements.vacuum(new AthenaHiveDdl.TableRef("lake", "events"), "default");
|
||||
verify(s3, never()).deleteObject(anyString(), anyString());
|
||||
|
||||
statements.finished(write);
|
||||
statements.vacuum(new AthenaHiveDdl.TableRef("lake", "events"), "default");
|
||||
verify(s3).deleteObject("lake", "events/data/staged.parquet");
|
||||
}
|
||||
|
||||
@Test
|
||||
void vacuumOfAHiveTableIsRefused() {
|
||||
glueTable("lake", "hive_events", false);
|
||||
|
||||
AwsException e = assertThrows(AwsException.class,
|
||||
() -> statements.vacuum(new AthenaHiveDdl.TableRef(null, "hive_events"), "lake"));
|
||||
|
||||
assertTrue(e.getMessage().contains("only for Apache Iceberg tables"), e.getMessage());
|
||||
}
|
||||
|
||||
private ObjectNode loaded(String metadataLocation, JsonNode metadata) {
|
||||
ObjectNode result = mapper.createObjectNode();
|
||||
result.put("metadata-location", metadataLocation);
|
||||
result.set("metadata", metadata);
|
||||
return result;
|
||||
}
|
||||
|
||||
private static S3Object object(String key, long lastModified) {
|
||||
S3Object object = new S3Object();
|
||||
object.setKey(key);
|
||||
object.setLastModified(Instant.ofEpochMilli(lastModified));
|
||||
return object;
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,5 @@
|
||||
package io.floci.aws.services.athena;
|
||||
|
||||
import io.floci.aws.config.EmulatorConfig;
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
import io.floci.aws.core.common.RequestScopes;
|
||||
import io.floci.aws.core.storage.StorageFactory;
|
||||
@@ -28,7 +27,6 @@ import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.Mockito.doAnswer;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* A query runs on a worker after the call that started it has returned, with no request scope of its own;
|
||||
@@ -68,7 +66,7 @@ class AthenaQueryScopeTest {
|
||||
return null;
|
||||
}).when(duckClient).execute(anyString(), any(), any(), any());
|
||||
AthenaService athena = new AthenaService(storageFactory, duckClient, glueService, mock(S3Service.class),
|
||||
realQueries(), vertx, ddlBuilder, regionResolver);
|
||||
AthenaTestConfigs.realQueries(), vertx, ddlBuilder, regionResolver, mock(AthenaIcebergStatements.class));
|
||||
try {
|
||||
String expected = RequestScopes.callAs(account, REGION, () -> {
|
||||
glueService.createDatabase(new Database(database));
|
||||
@@ -90,15 +88,4 @@ class AthenaQueryScopeTest {
|
||||
RequestScopes.runAs(account, REGION, () -> glueService.deleteDatabase(database));
|
||||
}
|
||||
}
|
||||
|
||||
/** A configuration under which a query is handed to the duck client rather than answered at once. */
|
||||
private static EmulatorConfig realQueries() {
|
||||
EmulatorConfig config = mock(EmulatorConfig.class);
|
||||
EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);
|
||||
EmulatorConfig.AthenaServiceConfig athena = mock(EmulatorConfig.AthenaServiceConfig.class);
|
||||
when(config.services()).thenReturn(services);
|
||||
when(services.athena()).thenReturn(athena);
|
||||
when(athena.mock()).thenReturn(false);
|
||||
return config;
|
||||
}
|
||||
}
|
||||
@@ -66,7 +66,7 @@ class AthenaServiceTest {
|
||||
when(athena.mock()).thenReturn(false);
|
||||
|
||||
service = new AthenaService(storageFactory, duckClient, glueService, s3Service,
|
||||
config, vertx, ddlBuilder, mock(RegionResolver.class));
|
||||
config, vertx, ddlBuilder, mock(RegionResolver.class), mock(AthenaIcebergStatements.class));
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
package io.floci.aws.services.athena;
|
||||
|
||||
import io.floci.aws.config.EmulatorConfig;
|
||||
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/** Configurations Athena tests construct {@link AthenaService} with. */
|
||||
final class AthenaTestConfigs {
|
||||
|
||||
private AthenaTestConfigs() {
|
||||
}
|
||||
|
||||
/** A configuration under which a query is handed to the query engine rather than answered at once. */
|
||||
static EmulatorConfig realQueries() {
|
||||
EmulatorConfig config = mock(EmulatorConfig.class);
|
||||
EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);
|
||||
EmulatorConfig.AthenaServiceConfig athena = mock(EmulatorConfig.AthenaServiceConfig.class);
|
||||
when(config.services()).thenReturn(services);
|
||||
when(services.athena()).thenReturn(athena);
|
||||
when(athena.mock()).thenReturn(false);
|
||||
return config;
|
||||
}
|
||||
}
|
||||
@@ -2,17 +2,14 @@ package io.floci.aws.services.glue.iceberg;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
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.RequestContext;
|
||||
import io.floci.aws.services.glue.GlueService;
|
||||
import io.floci.aws.services.glue.model.Database;
|
||||
import io.floci.aws.services.glue.model.Table;
|
||||
import io.floci.aws.services.s3.S3Service;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.Answers;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.Mockito;
|
||||
|
||||
@@ -33,7 +30,7 @@ import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/** The catalog's commit paths when Glue refuses the write, and who it answers under IAM enforcement. */
|
||||
/** The catalog's commit paths when Glue refuses the write. */
|
||||
class GlueIcebergCatalogTest {
|
||||
|
||||
private static final String CREATE_COMMIT = """
|
||||
@@ -50,18 +47,14 @@ class GlueIcebergCatalogTest {
|
||||
private final ObjectMapper mapper = new ObjectMapper();
|
||||
private GlueService glue;
|
||||
private S3Service s3;
|
||||
private EmulatorConfig config;
|
||||
private RequestContext requestContext;
|
||||
private GlueIcebergCatalog catalog;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
glue = Mockito.mock(GlueService.class);
|
||||
s3 = Mockito.mock(S3Service.class);
|
||||
config = Mockito.mock(EmulatorConfig.class, Answers.RETURNS_DEEP_STUBS);
|
||||
requestContext = Mockito.mock(RequestContext.class);
|
||||
catalog = new GlueIcebergCatalog(glue, s3, new RegionResolver("us-east-1", "000000000000"), mapper, config,
|
||||
requestContext, Clock.fixed(Instant.ofEpochMilli(10_000L), ZoneOffset.UTC));
|
||||
catalog = new GlueIcebergCatalog(glue, s3, new RegionResolver("us-east-1", "000000000000"), mapper,
|
||||
Clock.fixed(Instant.ofEpochMilli(10_000L), ZoneOffset.UTC));
|
||||
Database database = new Database("lake");
|
||||
database.setLocationUri("s3://lake-bucket/lake");
|
||||
when(glue.getDatabase("lake")).thenReturn(database);
|
||||
@@ -140,28 +133,4 @@ class GlueIcebergCatalogTest {
|
||||
String written = writtenMetadataKey();
|
||||
verify(s3).deleteObject("lake-bucket", written);
|
||||
}
|
||||
|
||||
@Test
|
||||
void underIamEnforcementOnlyRootCredentialsAndFlocisOwnCallersReachTheCatalog() {
|
||||
when(config.services().iam().enforcementEnabled()).thenReturn(true);
|
||||
when(requestContext.getAccountId()).thenReturn("000000000000");
|
||||
|
||||
when(requestContext.getAccessKeyId()).thenReturn("AKIAEXAMPLEUSER0001");
|
||||
IcebergRestException refused = assertThrows(IcebergRestException.class, () -> catalog.config(null));
|
||||
assertEquals(403, refused.code());
|
||||
assertEquals("ForbiddenException", refused.type());
|
||||
|
||||
for (String rootOrInternal : new String[] {"test", "000000000000", null}) {
|
||||
when(requestContext.getAccessKeyId()).thenReturn(rootOrInternal);
|
||||
assertEquals("catalogs/:", catalog.config(null).path("overrides").path("prefix").asText());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void withoutEnforcementAnyCallerReachesTheCatalog() {
|
||||
when(config.services().iam().enforcementEnabled()).thenReturn(false);
|
||||
when(requestContext.getAccessKeyId()).thenReturn("AKIAEXAMPLEUSER0001");
|
||||
|
||||
assertEquals("catalogs/:", catalog.config(null).path("overrides").path("prefix").asText());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package io.floci.aws.services.glue.iceberg;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.floci.aws.config.EmulatorConfig;
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
import io.floci.aws.core.common.RequestContext;
|
||||
import io.floci.aws.services.glue.GlueService;
|
||||
import io.floci.aws.services.s3.S3Service;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.Answers;
|
||||
import org.mockito.Mockito;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/** Who the endpoint answers under IAM enforcement. */
|
||||
class GlueIcebergControllerTest {
|
||||
|
||||
private EmulatorConfig config;
|
||||
private RequestContext requestContext;
|
||||
private GlueIcebergController controller;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
config = Mockito.mock(EmulatorConfig.class, Answers.RETURNS_DEEP_STUBS);
|
||||
requestContext = Mockito.mock(RequestContext.class);
|
||||
GlueIcebergCatalog catalog = new GlueIcebergCatalog(Mockito.mock(GlueService.class),
|
||||
Mockito.mock(S3Service.class), new RegionResolver("us-east-1", "000000000000"), new ObjectMapper());
|
||||
controller = new GlueIcebergController(catalog, config, requestContext);
|
||||
}
|
||||
|
||||
@Test
|
||||
void underIamEnforcementOnlyRootCredentialsAndFlocisOwnCallersReachTheCatalog() {
|
||||
when(config.services().iam().enforcementEnabled()).thenReturn(true);
|
||||
when(requestContext.getAccountId()).thenReturn("000000000000");
|
||||
|
||||
when(requestContext.getAccessKeyId()).thenReturn("AKIAEXAMPLEUSER0001");
|
||||
IcebergRestException refused = assertThrows(IcebergRestException.class, () -> controller.getConfig(null));
|
||||
assertEquals(403, refused.code());
|
||||
assertEquals("ForbiddenException", refused.type());
|
||||
|
||||
for (String rootOrInternal : new String[] {"test", "000000000000", null}) {
|
||||
when(requestContext.getAccessKeyId()).thenReturn(rootOrInternal);
|
||||
assertEquals("catalogs/:", controller.getConfig(null).path("overrides").path("prefix").asText());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void withoutEnforcementAnyCallerReachesTheCatalog() {
|
||||
when(config.services().iam().enforcementEnabled()).thenReturn(false);
|
||||
when(requestContext.getAccessKeyId()).thenReturn("AKIAEXAMPLEUSER0001");
|
||||
|
||||
assertEquals("catalogs/:", controller.getConfig(null).path("overrides").path("prefix").asText());
|
||||
}
|
||||
}
|
||||
+28
-1
@@ -7,18 +7,22 @@ import io.quarkus.test.common.http.TestHTTPResource;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import io.restassured.response.Response;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.net.URI;
|
||||
import java.time.Duration;
|
||||
import java.util.Map;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.not;
|
||||
|
||||
/**
|
||||
* Under IAM enforcement, no rule maps the Glue Iceberg REST endpoint's routes to the Glue actions AWS checks for them
|
||||
* yet, so the endpoint refuses an IAM principal, even one allowed every Glue action, rather than let it through
|
||||
* unchecked; the account's root credentials still reach it.
|
||||
* unchecked; the account's root credentials still reach it, and so does a token Floci minted for its query engine,
|
||||
* as the account and Region it was minted for.
|
||||
*/
|
||||
@QuarkusTest
|
||||
@TestProfile(SignedIamEnforcementProfile.class)
|
||||
@@ -27,6 +31,9 @@ class GlueIcebergIamIntegrationTest {
|
||||
@TestHTTPResource("/")
|
||||
URI endpoint;
|
||||
|
||||
@Inject
|
||||
GlueIcebergTokens tokens;
|
||||
|
||||
@Test
|
||||
void anIamPrincipalIsRefusedAndRootCredentialsAreAnswered() throws Exception {
|
||||
String allowEverything = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\","
|
||||
@@ -40,6 +47,26 @@ class GlueIcebergIamIntegrationTest {
|
||||
.body("overrides.prefix", equalTo("catalogs/:"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aMintedTokenActsAsItsAccountUntilRevokedAndAnUnknownOneReachesNothing() {
|
||||
String token = tokens.mint("111122223333", "eu-west-1", Duration.ofMinutes(5));
|
||||
try {
|
||||
bearer(token, "/iceberg/v1/config?warehouse=111122223333").then().statusCode(200)
|
||||
.body("overrides.prefix", equalTo("catalogs/111122223333"));
|
||||
bearer(token, "/iceberg/v1/config?warehouse=000000000000").then().statusCode(400)
|
||||
.body("error.type", equalTo("BadRequestException"));
|
||||
} finally {
|
||||
tokens.revoke(token);
|
||||
}
|
||||
bearer(token, "/iceberg/v1/config?warehouse=111122223333").then().statusCode(not(equalTo(200)));
|
||||
bearer("not-a-minted-token", "/iceberg/v1/config").then().statusCode(not(equalTo(200)));
|
||||
}
|
||||
|
||||
private Response bearer(String token, String path) {
|
||||
return given().urlEncodingEnabled(false).header("Authorization", "Bearer " + token)
|
||||
.get(endpoint.resolve(path));
|
||||
}
|
||||
|
||||
private Response get(AwsRequestSigner signer, String path) throws Exception {
|
||||
URI uri = endpoint.resolve(path);
|
||||
return given().urlEncodingEnabled(false).headers(signer.headersFor("GET", uri, Map.of(), new byte[0]))
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
package io.floci.aws.services.glue.iceberg;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.floci.aws.services.glue.model.Column;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/** The Iceberg {@code CreateTableRequest} an Athena Iceberg {@code CREATE TABLE} describes. */
|
||||
class IcebergSchemasTest {
|
||||
|
||||
private final ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
private static Column column(String name, String type) {
|
||||
return new Column(name, type);
|
||||
}
|
||||
|
||||
@Test
|
||||
void hiveTypesBecomeIcebergTypesWithTopLevelIdsFirstThenNestedOnesInOrder() throws Exception {
|
||||
Column id = column("id", "bigint");
|
||||
id.setComment("the id");
|
||||
JsonNode request = IcebergSchemas.createTableRequest("events", List.of(id,
|
||||
column("tags", "array<string>"),
|
||||
column("attrs", "map<string,int>"),
|
||||
column("info", "struct<a:int,b:struct<c:varchar(10)>>"),
|
||||
column("price", "decimal(10,2)"),
|
||||
column("ts", "timestamp"),
|
||||
column("flag", "boolean")), List.of(), "s3://lake/events", Map.of("format-version", "2"));
|
||||
|
||||
assertEquals(mapper.readTree("""
|
||||
{"type":"struct","schema-id":0,"fields":[
|
||||
{"id":1,"name":"id","required":false,"type":"long","doc":"the id"},
|
||||
{"id":2,"name":"tags","required":false,"type":{"type":"list","element-id":8,"element":"string",
|
||||
"element-required":false}},
|
||||
{"id":3,"name":"attrs","required":false,"type":{"type":"map","key-id":9,"value-id":10,
|
||||
"key":"string","value":"int","value-required":false}},
|
||||
{"id":4,"name":"info","required":false,"type":{"type":"struct","fields":[
|
||||
{"id":11,"name":"a","required":false,"type":"int"},
|
||||
{"id":12,"name":"b","required":false,"type":{"type":"struct","fields":[
|
||||
{"id":13,"name":"c","required":false,"type":"string"}]}}]}},
|
||||
{"id":5,"name":"price","required":false,"type":"decimal(10, 2)"},
|
||||
{"id":6,"name":"ts","required":false,"type":"timestamp"},
|
||||
{"id":7,"name":"flag","required":false,"type":"boolean"}]}
|
||||
"""), request.path("schema"));
|
||||
assertEquals("events", request.path("name").asText());
|
||||
assertEquals("s3://lake/events", request.path("location").asText());
|
||||
assertEquals("2", request.path("properties").path("format-version").asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
void partitionedByEntriesBecomeASpecOfTransformsNamedAsIcebergNamesThem() throws Exception {
|
||||
JsonNode request = IcebergSchemas.createTableRequest("events", List.of(column("id", "bigint"),
|
||||
column("category", "string"), column("ts", "timestamp"), column("name", "string")), List.of(
|
||||
new IcebergSchemas.PartitionField("identity", null, "category"),
|
||||
new IcebergSchemas.PartitionField("bucket", 16, "id"),
|
||||
new IcebergSchemas.PartitionField("day", null, "ts"),
|
||||
new IcebergSchemas.PartitionField("truncate", 4, "NAME")), null, Map.of());
|
||||
|
||||
assertEquals(mapper.readTree("""
|
||||
{"spec-id":0,"fields":[
|
||||
{"name":"category","transform":"identity","source-id":2,"field-id":1000},
|
||||
{"name":"id_bucket","transform":"bucket[16]","source-id":1,"field-id":1001},
|
||||
{"name":"ts_day","transform":"day","source-id":3,"field-id":1002},
|
||||
{"name":"name_trunc","transform":"truncate[4]","source-id":4,"field-id":1003}]}
|
||||
"""), request.path("partition-spec"));
|
||||
assertTrue(request.path("location").isMissingNode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void typesAthenaDoesNotSupportOnIcebergTablesAreRefused() {
|
||||
for (String type : List.of("tinyint", "smallint", "char(3)")) {
|
||||
IllegalArgumentException e = assertThrows(IllegalArgumentException.class,
|
||||
() -> IcebergSchemas.createTableRequest("t", List.of(column("c", type)), List.of(), null,
|
||||
Map.of()));
|
||||
assertTrue(e.getMessage().contains("not supported for Iceberg tables"), e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void aPartitionTransformWithoutItsWidthOrOnAColumnTypeItDoesNotTakeIsRefused() {
|
||||
List<Column> columns = List.of(column("id", "bigint"), column("name", "string"), column("ts", "timestamp"),
|
||||
column("dt", "date"));
|
||||
for (IcebergSchemas.PartitionField partition : List.of(
|
||||
new IcebergSchemas.PartitionField("bucket", null, "id"),
|
||||
new IcebergSchemas.PartitionField("bucket", 0, "id"),
|
||||
new IcebergSchemas.PartitionField("truncate", -1, "name"),
|
||||
new IcebergSchemas.PartitionField("day", 4, "ts"),
|
||||
new IcebergSchemas.PartitionField("identity", 2, "id"),
|
||||
new IcebergSchemas.PartitionField("day", null, "name"),
|
||||
new IcebergSchemas.PartitionField("hour", null, "dt"),
|
||||
new IcebergSchemas.PartitionField("truncate", 4, "ts"))) {
|
||||
assertThrows(IllegalArgumentException.class, () -> IcebergSchemas.createTableRequest("t", columns,
|
||||
List.of(partition), null, Map.of()), partition.toString());
|
||||
}
|
||||
JsonNode spec = IcebergSchemas.createTableRequest("t", columns, List.of(
|
||||
new IcebergSchemas.PartitionField("month", null, "dt"),
|
||||
new IcebergSchemas.PartitionField("bucket", 8, "name")), null, Map.of()).path("partition-spec");
|
||||
assertEquals("month", spec.path("fields").get(0).path("transform").asText());
|
||||
assertEquals("bucket[8]", spec.path("fields").get(1).path("transform").asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aPartitionOfAnUnknownColumnOrTransformIsRefused() {
|
||||
List<Column> columns = List.of(column("id", "bigint"));
|
||||
|
||||
assertThrows(IllegalArgumentException.class, () -> IcebergSchemas.createTableRequest("t", columns,
|
||||
List.of(new IcebergSchemas.PartitionField("identity", null, "missing")), null, Map.of()));
|
||||
assertThrows(IllegalArgumentException.class, () -> IcebergSchemas.createTableRequest("t", columns,
|
||||
List.of(new IcebergSchemas.PartitionField("week", null, "id")), null, Map.of()));
|
||||
}
|
||||
}
|
||||
@@ -136,6 +136,27 @@ class IcebergTableMetadataTest {
|
||||
assertEquals(-1L, other.path("current-snapshot-id").asLong());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRemovedSnapshotsStatisticsFilesGoWithIt() throws Exception {
|
||||
ObjectNode metadata = created();
|
||||
IcebergTableMetadata.apply(metadata, snapshotCommit(7L, null, 1).path("updates"), 6_000L);
|
||||
IcebergTableMetadata.apply(metadata, snapshotCommit(8L, 7L, 2).path("updates"), 6_100L);
|
||||
IcebergTableMetadata.apply(metadata, json("""
|
||||
[{"action":"set-statistics","statistics":{"snapshot-id":7,"statistics-path":"s3://b/t/7.stats",
|
||||
"file-size-in-bytes":1,"file-footer-size-in-bytes":1,"blob-metadata":[]}},
|
||||
{"action":"set-statistics","statistics":{"snapshot-id":8,"statistics-path":"s3://b/t/8.stats",
|
||||
"file-size-in-bytes":1,"file-footer-size-in-bytes":1,"blob-metadata":[]}},
|
||||
{"action":"set-partition-statistics","partition-statistics":{"snapshot-id":7,
|
||||
"statistics-path":"s3://b/t/7.pstats","file-size-in-bytes":1}}]
|
||||
"""), 6_200L);
|
||||
|
||||
IcebergTableMetadata.apply(metadata, json("[{\"action\":\"remove-snapshots\",\"snapshot-ids\":[7]}]"), 7_000L);
|
||||
|
||||
assertEquals(1, metadata.path("statistics").size());
|
||||
assertEquals(8L, metadata.path("statistics").get(0).path("snapshot-id").asLong());
|
||||
assertTrue(metadata.path("partition-statistics").isEmpty(), metadata.path("partition-statistics").toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSchemaSpecOrSortOrderIdTheTableDoesNotHaveIsRefused() throws Exception {
|
||||
ObjectNode metadata = created();
|
||||
|
||||
Reference in new issue
Block a user