feat(athena): run Iceberg CREATE TABLE, DML and VACUUM through Glue's Iceberg REST catalog (#8488)

This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-11-15 14:52:36 -04:00
1 parent dbfe6e0769
commit 8206115dc8
27 files changed
+2063 -177

No files matched your search

@@ -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);
}
}
}
/**