feat(glue): serve federated S3 Tables catalogs on Glue's Iceberg REST endpoint (#8516)

This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-11-15 19:33:21 -04:00
1 parent 722472e76b
commit 0999528349
12 files changed
+1010 -291

No files matched your search

+4 -2
View File
@@ -351,7 +351,9 @@ The operations are the twelve AWS lists: `GetConfig`, `ListNamespaces`, `CreateN
[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`).
A table bucket federated from Amazon S3 Tables (see [Catalogs and Amazon S3 Tables](#catalogs-and-amazon-s3-tables)) is a catalog of this endpoint too: the warehouse `<account>:s3tablescatalog/<bucket>` configures the prefix `catalogs/<account>:s3tablescatalog:<bucket>` (levels joined by `:`, as AWS's route table writes nested catalogs; `s3tablescatalog:<bucket>` names the caller's own). Its namespaces and tables are the bucket's: S3 Tables decides where a table lives, so a create names no location (a staged create already creates the table, empty, at its warehouse location), namespaces take no properties (Spark's `owner` is let go), no commit moves a table out of its warehouse, each commit moves the table's metadata location with S3 Tables' version token (a stale one answering `CommitFailedException`), a table a staged create holds is listed only once committed, and dropping a table deletes its warehouse, data and all, as S3 Tables' `DeleteTable` does.
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 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`).
## Catalogs and Amazon S3 Tables
@@ -361,7 +363,7 @@ Not yet: IAM policies are not checked on this endpoint, so under IAM enforcement
aws glue create-catalog --cli-input-json '{"Name":"s3tablescatalog","CatalogInput":{"FederatedCatalog":{"Identifier":"arn:aws:s3tables:us-east-1:000000000000:bucket/*","ConnectionName":"aws:s3tables"},"AllowFullTableExternalDataAccess":"True"}}'
```
Each table bucket of the account is then a child catalog, `s3tablescatalog/<bucket>` (or `<account>:s3tablescatalog/<bucket>`), listed by `GetCatalogs` with `ParentCatalogId` `s3tablescatalog`, whose `FederatedCatalog.Identifier` is the bucket's ARN. With that `CatalogId`, `GetDatabases` and `GetDatabase` answer the bucket's namespaces, and `GetTables` and `GetTable` its tables, read from S3 Tables: Iceberg tables whose `metadata_location` and columns come from the table's current metadata file. A table without metadata yet has neither. Catalog ids answer as `<account>:<catalog>[/<child>]`. Writing through a federated catalog (`CreateDatabase`, `CreateTable` with its `CatalogId`), a federated catalog's IAM resources, and the Iceberg REST endpoint's federated catalogs are not served yet.
Each table bucket of the account is then a child catalog, `s3tablescatalog/<bucket>` (or `<account>:s3tablescatalog/<bucket>`), listed by `GetCatalogs` with `ParentCatalogId` `s3tablescatalog`, whose `FederatedCatalog.Identifier` is the bucket's ARN. With that `CatalogId`, `GetDatabases` and `GetDatabase` answer the bucket's namespaces, and `GetTables` and `GetTable` its tables, read from S3 Tables: Iceberg tables whose `metadata_location` and columns come from the table's current metadata file. A table without metadata yet has neither. Catalog ids answer as `<account>:<catalog>[/<child>]`. Writing through a federated catalog with Glue's own API (`CreateDatabase`, `CreateTable` with its `CatalogId`) and a federated catalog's IAM resources are not served yet; the [Iceberg REST endpoint](#iceberg-rest-endpoint) writes to its tables.
## Configuration
@@ -189,6 +189,19 @@ public class GlueCatalogService {
return path(catalogId).isDefault();
}
/**
* The ARN of the table bucket a federated S3 Tables catalog id names ({@code [<account>:]s3tablescatalog/<bucket>}),
* and the catalog's id as catalogs answer it; empty for any other catalog id.
*/
public Optional<FederatedBucket> federatedTableBucket(String catalogId, String region) {
return federated(catalogId, region).map(found -> new FederatedBucket(found.bucket().getArn(),
found.bucket().getName(), found.catalogId()));
}
/** A table bucket a federated catalog names, and the catalog's qualified id. */
public record FederatedBucket(String bucketArn, String bucketName, String catalogId) {
}
public GlueService.Page<Database> getDatabases(String catalogId, Integer maxResults, String nextToken,
String region) {
Optional<Federated> federated = federated(catalogId, region);
@@ -6,11 +6,11 @@ import com.fasterxml.jackson.databind.node.ArrayNode;
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.services.glue.GlueCatalogService;
import io.floci.aws.services.glue.GlueService;
import io.floci.aws.services.glue.GlueTableResolver;
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.services.s3tables.S3TablesService;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
@@ -19,24 +19,25 @@ import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.time.Clock;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* The Iceberg REST catalog AWS Glue serves at {@code /iceberg}, over Floci's Glue Data Catalog: a namespace is a Glue
* database, a table a Glue table whose {@code table_type} is {@code ICEBERG} and whose {@code metadata_location}
* names its current metadata file in S3. A commit writes the next metadata file beside the last one and moves
* {@code metadata_location} to it, refused when the Glue table changed since the commit's base was read, so Spark's
* {@code GlueCatalog}, Athena and any other reader of the Glue table see each commit.
* The Iceberg REST catalog AWS Glue serves at {@code /iceberg}. The catalog a request names decides where its
* namespaces and tables live ({@link IcebergCatalogStore}): the caller's default catalog ({@code :} or its account id)
* is Floci's Glue Data Catalog, whose tables are Glue tables with {@code table_type} {@code ICEBERG}; a table bucket
* federated from Amazon S3 Tables ({@code s3tablescatalog:<bucket>}, or {@code <account>:s3tablescatalog:<bucket>}, the
* colons standing for the slashes of its Glue catalog id) keeps them in S3 Tables. A commit checks its requirements,
* applies its updates, writes the next metadata file beside the last one, and has the store move the table's current
* metadata file to it, refused when the table changed since the commit's base was read; so Spark's {@code GlueCatalog},
* Athena and S3 Tables readers see each commit.
*
* <p>The operations are the twelve AWS lists for the endpoint. The catalog in the path is the caller's default
* catalog, named {@code :} or by the caller's account id; Glue supports single-level namespaces only.
* <p>The operations are the twelve AWS lists for the endpoint; Glue supports single-level namespaces only.
*/
@ApplicationScoped
public class GlueIcebergCatalog {
@@ -44,11 +45,8 @@ public class GlueIcebergCatalog {
private static final Logger LOG = Logger.getLogger(GlueIcebergCatalog.class);
static final String DEFAULT_CATALOG = ":";
private static final String PARAM_TABLE_TYPE = IcebergGlueTables.PARAM_TABLE_TYPE;
private static final String PARAM_METADATA_LOCATION = IcebergGlueTables.PARAM_METADATA_LOCATION;
private static final String PARAM_PREVIOUS_METADATA_LOCATION = "previous_metadata_location";
private static final String ICEBERG = IcebergGlueTables.ICEBERG;
private static final Pattern METADATA_VERSION = Pattern.compile("^(\\d+)-.*\\.metadata\\.json$");
private static final Pattern ACCOUNT_QUALIFIER = Pattern.compile("^(\\d{12}):(.+)$");
/** The REST routes the endpoint answers, as {@code GetConfig}'s {@code endpoints} names them. */
private static final List<String> ENDPOINTS = List.of(
"GET /v1/{prefix}/namespaces",
@@ -63,20 +61,25 @@ public class GlueIcebergCatalog {
"POST /v1/{prefix}/namespaces/{namespace}/tables/{table}",
"DELETE /v1/{prefix}/namespaces/{namespace}/tables/{table}");
private final GlueService glue;
private final GlueIcebergStore glueStore;
private final GlueCatalogService catalogs;
private final S3TablesService s3Tables;
private final S3Service s3;
private final RegionResolver regionResolver;
private final ObjectMapper mapper;
private final Clock clock;
@Inject
public GlueIcebergCatalog(GlueService glue, S3Service s3, RegionResolver regionResolver, ObjectMapper mapper) {
this(glue, s3, regionResolver, mapper, Clock.systemUTC());
public GlueIcebergCatalog(GlueService glue, S3Service s3, RegionResolver regionResolver, ObjectMapper mapper,
GlueCatalogService catalogs, S3TablesService s3Tables) {
this(glue, s3, regionResolver, mapper, catalogs, s3Tables, Clock.systemUTC());
}
GlueIcebergCatalog(GlueService glue, S3Service s3, RegionResolver regionResolver, ObjectMapper mapper,
Clock clock) {
this.glue = glue;
GlueCatalogService catalogs, S3TablesService s3Tables, Clock clock) {
this.glueStore = new GlueIcebergStore(glue);
this.catalogs = catalogs;
this.s3Tables = s3Tables;
this.s3 = s3;
this.regionResolver = regionResolver;
this.mapper = mapper;
@@ -85,13 +88,23 @@ public class GlueIcebergCatalog {
// ─── GetConfig ────────────────────────────────────────────────────────────────
/** The catalog's configuration: the path prefix of the catalog {@code warehouse} names, and the routes served. */
/**
* The catalog's configuration: the path prefix of the catalog {@code warehouse} names (the default catalog when it
* names none, or a federated S3 Tables catalog such as {@code <account>:s3tablescatalog/<bucket>}), and the routes
* served.
*/
ObjectNode config(String warehouse) {
String catalog = warehouse == null || warehouse.isBlank() ? DEFAULT_CATALOG : warehouse;
requireDefaultCatalog(catalog);
String prefix;
if (isDefault(catalog)) {
prefix = catalog;
} else {
prefix = federatedBucket(catalog).map(bucket -> bucket.catalogId().replace('/', ':'))
.orElseThrow(() -> unsupported(catalog));
}
ObjectNode config = mapper.createObjectNode();
config.putObject("defaults");
config.putObject("overrides").put("prefix", "catalogs/" + catalog);
config.putObject("overrides").put("prefix", "catalogs/" + prefix);
ArrayNode endpoints = config.putArray("endpoints");
ENDPOINTS.forEach(endpoints::add);
return config;
@@ -100,158 +113,122 @@ public class GlueIcebergCatalog {
// ─── Namespaces ───────────────────────────────────────────────────────────────
ObjectNode listNamespaces(String catalog, String parent) {
requireDefaultCatalog(catalog);
IcebergCatalogStore store = store(catalog);
ObjectNode result = mapper.createObjectNode();
ArrayNode namespaces = result.putArray("namespaces");
if (parent != null && !parent.isBlank()) {
// Glue namespaces have one level, so nothing sits beneath one.
requireNamespace(namespace(parent));
store.namespaceProperties(namespace(parent));
return result;
}
for (Database database : glue.getDatabases()) {
namespaces.addArray().add(database.getName());
for (String namespace : store.namespaces()) {
namespaces.addArray().add(namespace);
}
return result;
}
ObjectNode createNamespace(String catalog, JsonNode request) {
requireDefaultCatalog(catalog);
IcebergCatalogStore store = store(catalog);
JsonNode levels = request.path("namespace");
if (!levels.isArray() || levels.size() != 1) {
throw IcebergRestException.badRequest("AWS Glue supports single-level namespaces only");
}
Database database = new Database(levels.get(0).asText());
Map<String, String> parameters = new LinkedHashMap<>();
Iterator<Map.Entry<String, JsonNode>> properties = request.path("properties").fields();
while (properties.hasNext()) {
Map.Entry<String, JsonNode> property = properties.next();
switch (property.getKey()) {
case "location" -> database.setLocationUri(property.getValue().asText());
case "comment" -> database.setDescription(property.getValue().asText());
default -> parameters.put(property.getKey(), property.getValue().asText());
}
}
database.setParameters(parameters);
try {
glue.createDatabase(database);
} catch (AwsException e) {
throw translated(e, database.getName(), null);
}
String namespace = levels.get(0).asText();
store.createNamespace(namespace, strings(request.path("properties")));
ObjectNode result = mapper.createObjectNode();
result.putArray("namespace").add(database.getName());
result.set("properties", properties(requireNamespace(database.getName())));
result.putArray("namespace").add(namespace);
result.set("properties", mapper.valueToTree(store.namespaceProperties(namespace)));
return result;
}
ObjectNode loadNamespace(String catalog, String namespace) {
requireDefaultCatalog(catalog);
Database database = requireNamespace(namespace(namespace));
IcebergCatalogStore store = store(catalog);
String name = namespace(namespace);
Map<String, String> properties = store.namespaceProperties(name);
ObjectNode result = mapper.createObjectNode();
result.putArray("namespace").add(database.getName());
result.set("properties", properties(database));
result.putArray("namespace").add(name);
result.set("properties", mapper.valueToTree(properties));
return result;
}
ObjectNode updateNamespaceProperties(String catalog, String namespace, JsonNode request) {
requireDefaultCatalog(catalog);
Database database = requireNamespace(namespace(namespace));
Database updated = new Database(database.getName());
updated.setDescription(database.getDescription());
updated.setLocationUri(database.getLocationUri());
Map<String, String> parameters = new LinkedHashMap<>(database.getParameters() == null ? Map.of()
: database.getParameters());
IcebergCatalogStore store = store(catalog);
List<String> removals = new ArrayList<>();
request.path("removals").forEach(key -> removals.add(key.asText()));
IcebergCatalogStore.PropertyChanges changes = store.updateNamespaceProperties(namespace(namespace), removals,
strings(request.path("updates")));
ObjectNode result = mapper.createObjectNode();
ArrayNode removed = result.putArray("removed");
ArrayNode missing = result.putArray("missing");
for (JsonNode key : request.path("removals")) {
String name = key.asText();
boolean present = switch (name) {
case "location" -> updated.getLocationUri() != null;
case "comment" -> updated.getDescription() != null;
default -> parameters.containsKey(name);
};
if (!present) {
missing.add(name);
continue;
}
switch (name) {
case "location" -> updated.setLocationUri(null);
case "comment" -> updated.setDescription(null);
default -> parameters.remove(name);
}
removed.add(name);
}
ArrayNode updatedKeys = result.putArray("updated");
Iterator<Map.Entry<String, JsonNode>> updates = request.path("updates").fields();
while (updates.hasNext()) {
Map.Entry<String, JsonNode> update = updates.next();
switch (update.getKey()) {
case "location" -> updated.setLocationUri(update.getValue().asText());
case "comment" -> updated.setDescription(update.getValue().asText());
default -> parameters.put(update.getKey(), update.getValue().asText());
}
updatedKeys.add(update.getKey());
}
updated.setParameters(parameters);
glue.updateDatabase(database.getName(), updated);
result.set("removed", mapper.valueToTree(changes.removed()));
result.set("missing", mapper.valueToTree(changes.missing()));
result.set("updated", mapper.valueToTree(changes.updated()));
return result;
}
void dropNamespace(String catalog, String namespace) {
requireDefaultCatalog(catalog);
Database database = requireNamespace(namespace(namespace));
if (!glue.getTables(database.getName()).isEmpty()) {
throw new IcebergRestException(409, "NamespaceNotEmptyException",
"Namespace " + database.getName() + " is not empty");
}
glue.deleteDatabase(database.getName());
store(catalog).dropNamespace(namespace(namespace));
}
// ─── Tables ───────────────────────────────────────────────────────────────────
ObjectNode listTables(String catalog, String namespace) {
requireDefaultCatalog(catalog);
Database database = requireNamespace(namespace(namespace));
IcebergCatalogStore store = store(catalog);
String name = namespace(namespace);
ObjectNode result = mapper.createObjectNode();
ArrayNode identifiers = result.putArray("identifiers");
for (Table table : glue.getTables(database.getName())) {
if (GlueTableResolver.isIcebergTable(table)) {
ObjectNode identifier = identifiers.addObject();
identifier.putArray("namespace").add(database.getName());
identifier.put("name", table.getName());
}
for (String table : store.tables(name)) {
ObjectNode identifier = identifiers.addObject();
identifier.putArray("namespace").add(name);
identifier.put("name", table);
}
return result;
}
/**
* 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.
* have without committing it: the commit that follows, required to find no table ({@code assert-create}), does. A
* store that decides where tables live (S3 Tables) holds the table, empty, from here on.
*/
public ObjectNode createTable(String catalog, String namespace, JsonNode request) {
requireDefaultCatalog(catalog);
Database database = requireNamespace(namespace(namespace));
IcebergCatalogStore store = store(catalog);
String ns = namespace(namespace);
store.namespaceProperties(ns);
String name = request.path("name").asText();
if (name.isBlank()) {
throw IcebergRestException.badRequest("Table name is required");
}
if (findTable(database.getName(), name) != null) {
throw IcebergRestException.alreadyExists("Table already exists: " + database.getName() + "." + name);
String requested = request.hasNonNull("location") ? request.get("location").asText() : null;
Optional<IcebergCatalogStore.StoredTable> existing = store.table(ns, name);
boolean reserved = existing.isPresent() && store.managesLocations()
&& existing.get().metadataLocation() == null;
if (existing.isPresent() && !reserved) {
throw IcebergRestException.alreadyExists("Table already exists: " + ns + "." + name);
}
String location = request.hasNonNull("location") ? stripTrailingSlash(request.get("location").asText())
: defaultLocation(database, name);
ObjectNode metadata = IcebergTableMetadata.forCreate(request, location, clock.millis());
if (reserved && requested != null) {
throw IcebergRestException.badRequest("S3 Tables decides where a table lives: a create names no location");
}
// Checked before a store that decides locations creates the table, so a bad request leaves nothing behind.
ObjectNode metadata = IcebergTableMetadata.forCreate(request, requested == null ? "s3://placeholder" : requested,
clock.millis());
boolean reservedHere = !reserved && store.managesLocations();
String location = reserved ? existing.get().location() : store.locationForNewTable(ns, name, requested);
metadata.put("location", location);
ObjectNode result = mapper.createObjectNode();
if (request.path("stage-create").asBoolean(false)) {
result.set("metadata", metadata);
result.putObject("config");
return result;
}
String metadataLocation = writeMetadata(metadata, 0);
String metadataLocation = null;
try {
createGlueTable(database.getName(), name, metadata, metadataLocation);
metadataLocation = writeMetadata(metadata, 0);
store.create(ns, name, metadata, metadataLocation, reserved ? existing.get() : null);
} catch (RuntimeException e) {
deleteMetadata(metadataLocation);
if (metadataLocation != null) {
deleteMetadata(metadataLocation);
}
if (reservedHere) {
dropEmptyReservation(store, ns, name);
}
throw e;
}
result.put("metadata-location", metadataLocation);
@@ -261,10 +238,9 @@ public class GlueIcebergCatalog {
}
public ObjectNode loadTable(String catalog, String namespace, String name, String snapshots) {
requireDefaultCatalog(catalog);
Database database = requireNamespace(namespace(namespace));
Table table = requireIcebergTable(database.getName(), name);
String metadataLocation = GlueTableResolver.icebergMetadataLocation(table);
IcebergCatalogStore store = store(catalog);
String ns = namespace(namespace);
String metadataLocation = requireIcebergTable(store, ns, name).metadataLocation();
ObjectNode metadata = readMetadata(metadataLocation);
if ("refs".equals(snapshots)) {
metadata.set("snapshots", referencedSnapshots(metadata));
@@ -277,73 +253,75 @@ public class GlueIcebergCatalog {
}
void tableExists(String catalog, String namespace, String name) {
requireDefaultCatalog(catalog);
Database database = requireNamespace(namespace(namespace));
requireIcebergTable(database.getName(), name);
IcebergCatalogStore store = store(catalog);
requireIcebergTable(store, namespace(namespace), name);
}
/**
* Applies a {@code CommitTableRequest}: checks its requirements against the table's current metadata, applies its
* updates, writes the next metadata file and moves the Glue table's {@code metadata_location} to it, refused
* ({@code CommitFailedException}) when the Glue table changed since. A commit requiring {@code assert-create}
* creates the table.
* updates, writes the next metadata file and has the store make it current, refused
* ({@code CommitFailedException}) when the table changed since. A commit requiring {@code assert-create} creates
* the table.
*/
public ObjectNode commitTable(String catalog, String namespace, String name, JsonNode request) {
requireDefaultCatalog(catalog);
Database database = requireNamespace(namespace(namespace));
Table existing = findTable(database.getName(), name);
IcebergCatalogStore store = store(catalog);
String ns = namespace(namespace);
store.namespaceProperties(ns);
Optional<IcebergCatalogStore.StoredTable> existing = store.table(ns, name);
boolean creating = false;
for (JsonNode requirement : request.path("requirements")) {
creating |= "assert-create".equals(requirement.path("type").asText());
}
if (existing == null && !creating) {
throw IcebergRestException.noSuchTable(database.getName(), name);
if (existing.isPresent() && !existing.get().iceberg()) {
throw IcebergRestException.badRequest("Table " + ns + "." + name + " is not an Iceberg table");
}
if (existing != null && !GlueTableResolver.isIcebergTable(existing)) {
throw IcebergRestException.badRequest("Table " + database.getName() + "." + name
+ " is not an Iceberg table");
IcebergCatalogStore.StoredTable current = existing.filter(table -> table.metadataLocation() != null)
.orElse(null);
if (current == null && !creating) {
throw IcebergRestException.noSuchTable(ns, name);
}
String baseLocation = existing == null ? null : GlueTableResolver.icebergMetadataLocation(existing);
ObjectNode base = existing == null ? null : readMetadata(baseLocation);
ObjectNode base = current == null ? null : readMetadata(current.metadataLocation());
IcebergTableMetadata.check(base, request.path("requirements"));
long now = clock.millis();
ObjectNode metadata = base == null ? IcebergTableMetadata.empty(now) : base.deepCopy();
IcebergTableMetadata.apply(metadata, request.path("updates"), now);
if (!metadata.hasNonNull("location")) {
metadata.put("location", defaultLocation(database, name));
IcebergCatalogStore.StoredTable reserved = current == null ? existing.orElse(null) : null;
boolean reservedHere = base == null && reserved == null && store.managesLocations();
if (base == null) {
reserved = placeNewTable(store, ns, name, metadata, reserved);
} else if (store.managesLocations()) {
// S3 Tables decided where the table lives; no commit moves it.
requireManagedLocation(metadata, current.location(), ns, name);
}
if (base != null) {
metadata.withArray("metadata-log").addObject()
.put("timestamp-ms", base.path("last-updated-ms").asLong())
.put("metadata-file", baseLocation);
.put("metadata-file", current.metadataLocation());
}
String metadataLocation = writeMetadata(metadata, base == null ? 0 : metadataVersion(baseLocation) + 1);
String metadataLocation = null;
try {
if (existing == null) {
glue.createTable(database.getName(), icebergTable(name, metadata, metadataLocation, null));
metadataLocation = writeMetadata(metadata,
base == null ? 0 : metadataVersion(current.metadataLocation()) + 1);
if (base == null) {
store.create(ns, name, metadata, metadataLocation, reserved);
} else {
Table updated = icebergTable(existing.getName(), metadata, metadataLocation, existing);
updated.getParameters().put(PARAM_PREVIOUS_METADATA_LOCATION, baseLocation);
glue.updateTable(database.getName(), updated, existing.getVersionId(), false);
store.commit(ns, name, current, metadata, metadataLocation);
}
} catch (AwsException e) {
// The metadata file names a commit that did not happen.
deleteMetadata(metadataLocation);
if ("AlreadyExistsException".equals(e.getErrorCode())) {
throw new IcebergRestException(409, "CommitFailedException",
"Table " + database.getName() + "." + name + " was created concurrently");
}
if ("ConcurrentModificationException".equals(e.getErrorCode())) {
throw new IcebergRestException(409, "CommitFailedException",
"Table " + database.getName() + "." + name + " was changed concurrently");
}
// A create can only miss its namespace, dropped since it was looked up.
throw translated(e, database.getName(), existing == null ? null : name);
} catch (RuntimeException e) {
deleteMetadata(metadataLocation);
// The metadata file names a commit that did not happen.
if (metadataLocation != null) {
deleteMetadata(metadataLocation);
}
if (reservedHere) {
dropEmptyReservation(store, ns, name);
}
if (e instanceof IcebergRestException rest && "AlreadyExistsException".equals(rest.type())) {
throw new IcebergRestException(409, "CommitFailedException",
"Table " + ns + "." + name + " was created concurrently");
}
throw e;
}
LOG.debugv("Committed Iceberg table {0}.{1} at {2}", database.getName(), name, metadataLocation);
LOG.debugv("Committed Iceberg table {0}.{1} at {2}", ns, name, metadataLocation);
ObjectNode result = mapper.createObjectNode();
result.put("metadata-location", metadataLocation);
result.set("metadata", metadata);
@@ -351,22 +329,114 @@ public class GlueIcebergCatalog {
}
/**
* Drops the Glue table. Its metadata and data files stay where they are, as Glue's DeleteTable leaves a table's
* storage alone, whether or not the client asked for a purge.
* Drops the table. A Glue table's metadata and data files stay where they are, as Glue's DeleteTable leaves a
* table's storage alone whether or not the client asked for a purge; an S3 Tables table's warehouse, its data and
* metadata, goes with it, as S3 Tables' DeleteTable deletes it.
*/
void dropTable(String catalog, String namespace, String name) {
requireDefaultCatalog(catalog);
Database database = requireNamespace(namespace(namespace));
requireIcebergTable(database.getName(), name);
glue.deleteTable(database.getName(), name);
IcebergCatalogStore store = store(catalog);
String ns = namespace(namespace);
store.namespaceProperties(ns);
IcebergCatalogStore.StoredTable table = store.table(ns, name)
.orElseThrow(() -> IcebergRestException.noSuchTable(ns, name));
if (!table.iceberg()) {
throw IcebergRestException.noSuchTable(ns, name);
}
store.drop(ns, name);
}
// ─── Helpers ──────────────────────────────────────────────────────────────────
private void requireDefaultCatalog(String catalog) {
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)");
/** The store of the catalog a request's path names. */
private IcebergCatalogStore store(String catalog) {
if (isDefault(catalog)) {
return glueStore;
}
return federatedBucket(catalog)
.<IcebergCatalogStore>map(bucket -> new S3TablesIcebergStore(s3Tables, bucket.bucketArn(),
regionResolver.getRegion()))
.orElseThrow(() -> unsupported(catalog));
}
private boolean isDefault(String catalog) {
return DEFAULT_CATALOG.equals(catalog) || regionResolver.getAccountId().equals(catalog);
}
/**
* The table bucket a catalog names, as a request's path does ({@code [<account>:]s3tablescatalog:<bucket>}) or a
* warehouse does ({@code [<account>:]s3tablescatalog/<bucket>}); empty for any other catalog.
*/
private Optional<GlueCatalogService.FederatedBucket> federatedBucket(String catalog) {
if (catalogs == null || catalog == null) {
return Optional.empty();
}
Matcher qualified = ACCOUNT_QUALIFIER.matcher(catalog);
String account = qualified.matches() ? qualified.group(1) + ":" : "";
String path = (qualified.matches() ? qualified.group(2) : catalog).replace(':', '/');
try {
return catalogs.federatedTableBucket(account + path, regionResolver.getRegion());
} catch (AwsException e) {
// Another account's catalog is not found here; any other failure is the caller's to see.
if ("EntityNotFoundException".equals(e.getErrorCode())) {
return Optional.empty();
}
throw e;
}
}
private static IcebergRestException unsupported(String catalog) {
return IcebergRestException.badRequest("Catalog " + catalog + " is not supported: use the caller's default "
+ "catalog (':' or its account id) or a table bucket of its federated S3 Tables catalog "
+ "(s3tablescatalog:<bucket>)");
}
/**
* Gives a table a commit creates its location: S3 Tables decides it, holding the table from here on if a staged
* create has not already, and refuses another; elsewhere the commit's own location stands, or the namespace's
* default. Answers the empty table S3 Tables holds, if any.
*/
private IcebergCatalogStore.StoredTable placeNewTable(IcebergCatalogStore store, String ns, String name,
ObjectNode metadata, IcebergCatalogStore.StoredTable reserved) {
if (!store.managesLocations()) {
if (!metadata.hasNonNull("location")) {
metadata.put("location", store.locationForNewTable(ns, name, null));
}
return reserved;
}
if (reserved != null) {
requireManagedLocation(metadata, reserved.location(), ns, name);
metadata.put("location", reserved.location());
return reserved;
}
if (metadata.hasNonNull("location")) {
// Checked before S3 Tables creates the table, so a refused commit leaves nothing behind.
throw IcebergRestException.badRequest("S3 Tables decides where a table lives: a commit that creates "
+ ns + "." + name + " names no location of its own; stage the create first");
}
metadata.put("location", store.locationForNewTable(ns, name, null));
return store.table(ns, name).orElse(null);
}
/** Refuses metadata whose location is not the one S3 Tables gave the table. */
private static void requireManagedLocation(ObjectNode metadata, String location, String ns, String name) {
if (metadata.hasNonNull("location")
&& !IcebergGlueTables.stripTrailingSlash(metadata.get("location").asText()).equals(location)) {
throw IcebergRestException.badRequest("S3 Tables decides where a table lives: " + ns + "." + name
+ " lives at " + location);
}
}
/**
* Drops a table this request had S3 Tables create, once the request failed before anything was committed to it,
* so it does not stay behind empty; a failure to is logged, since the request's error matters more.
*/
private void dropEmptyReservation(IcebergCatalogStore store, String ns, String name) {
try {
if (store.table(ns, name).filter(table -> table.metadataLocation() == null).isPresent()) {
store.drop(ns, name);
}
} catch (RuntimeException e) {
LOG.warnv("Could not drop the empty table {0}.{1} a failed create left: {2}", ns, name, e.getMessage());
}
}
@@ -378,88 +448,18 @@ public class GlueIcebergCatalog {
return segment;
}
private Database requireNamespace(String name) {
try {
return glue.getDatabase(name);
} catch (AwsException e) {
if ("EntityNotFoundException".equals(e.getErrorCode())) {
throw IcebergRestException.noSuchNamespace(name);
}
throw e;
}
private static IcebergCatalogStore.StoredTable requireIcebergTable(IcebergCatalogStore store, String namespace,
String name) {
store.namespaceProperties(namespace);
return store.table(namespace, name)
.filter(table -> table.iceberg() && table.metadataLocation() != null)
.orElseThrow(() -> IcebergRestException.noSuchTable(namespace, name));
}
private Table findTable(String database, String name) {
try {
return glue.getTable(database, name);
} catch (AwsException e) {
if ("EntityNotFoundException".equals(e.getErrorCode())) {
return null;
}
throw e;
}
}
private Table requireIcebergTable(String database, String name) {
Table table = findTable(database, name);
if (table == null || !GlueTableResolver.isIcebergTable(table)) {
throw IcebergRestException.noSuchTable(database, name);
}
return table;
}
private ObjectNode properties(Database database) {
ObjectNode properties = mapper.createObjectNode();
if (database.getParameters() != null) {
database.getParameters().forEach(properties::put);
}
if (database.getLocationUri() != null) {
properties.put("location", database.getLocationUri());
}
if (database.getDescription() != null) {
properties.put("comment", database.getDescription());
}
return properties;
}
private static String defaultLocation(Database database, String table) {
if (database.getLocationUri() == null || database.getLocationUri().isBlank()) {
throw IcebergRestException.badRequest("Table " + database.getName() + "." + table
+ " needs a location: the request names none and namespace " + database.getName()
+ " has no location property");
}
return stripTrailingSlash(database.getLocationUri()) + "/" + table;
}
private static String stripTrailingSlash(String location) {
return location.endsWith("/") ? location.substring(0, location.length() - 1) : location;
}
private void createGlueTable(String database, String name, ObjectNode metadata, String metadataLocation) {
try {
glue.createTable(database, icebergTable(name, metadata, metadataLocation, null));
} catch (AwsException e) {
throw translated(e, database, name);
}
}
/**
* The Glue table holding an Iceberg table: {@code table_type} and {@code metadata_location} in its parameters,
* its location and its current schema's columns in its storage descriptor, as AWS Glue keeps one. What
* {@code existing} holds beyond those (a description, other parameters) carries over.
*/
private Table icebergTable(String name, ObjectNode metadata, String metadataLocation, Table existing) {
Table table = IcebergGlueTables.glueTable(name, metadata, metadataLocation);
if (existing != null) {
table.setDescription(existing.getDescription());
table.setOwner(existing.getOwner());
if (existing.getParameters() != null) {
Map<String, String> parameters = new HashMap<>(existing.getParameters());
parameters.putAll(table.getParameters());
table.setParameters(parameters);
}
}
return table;
private static Map<String, String> strings(JsonNode object) {
Map<String, String> values = new LinkedHashMap<>();
object.fields().forEachRemaining(entry -> values.put(entry.getKey(), entry.getValue().asText()));
return values;
}
private ObjectNode readMetadata(String metadataLocation) {
@@ -530,13 +530,4 @@ public class GlueIcebergCatalog {
throw IcebergRestException.badRequest(e.getMessage());
}
}
private static IcebergRestException translated(AwsException e, String database, String table) {
return switch (e.getErrorCode()) {
case "AlreadyExistsException" -> IcebergRestException.alreadyExists(e.getMessage());
case "EntityNotFoundException" -> table == null ? IcebergRestException.noSuchNamespace(database)
: IcebergRestException.noSuchTable(database, table);
default -> IcebergRestException.badRequest(e.getMessage());
};
}
}
@@ -0,0 +1,243 @@
package io.floci.aws.services.glue.iceberg;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.services.glue.GlueService;
import io.floci.aws.services.glue.GlueTableResolver;
import io.floci.aws.services.glue.model.Database;
import io.floci.aws.services.glue.model.Table;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
/**
* The account's default Glue Data Catalog as an Iceberg catalog: a namespace is a Glue database, whose {@code location}
* and {@code comment} properties are its {@code LocationUri} and {@code Description}; a table is a Glue table whose
* {@code table_type} is {@code ICEBERG} and whose {@code metadata_location} names its current metadata file. A commit
* moves {@code metadata_location}, refused when the Glue table's version changed since its base.
*/
final class GlueIcebergStore implements IcebergCatalogStore {
private static final String PARAM_PREVIOUS_METADATA_LOCATION = "previous_metadata_location";
private final GlueService glue;
GlueIcebergStore(GlueService glue) {
this.glue = glue;
}
@Override
public boolean managesLocations() {
return false;
}
@Override
public List<String> namespaces() {
return glue.getDatabases().stream().map(Database::getName).toList();
}
@Override
public Map<String, String> namespaceProperties(String namespace) {
return properties(requireDatabase(namespace));
}
@Override
public void createNamespace(String namespace, Map<String, String> properties) {
Database database = new Database(namespace);
Map<String, String> parameters = new LinkedHashMap<>();
properties.forEach((key, value) -> {
switch (key) {
case "location" -> database.setLocationUri(value);
case "comment" -> database.setDescription(value);
default -> parameters.put(key, value);
}
});
database.setParameters(parameters);
try {
glue.createDatabase(database);
} catch (AwsException e) {
throw translated(e, namespace, null);
}
}
@Override
public PropertyChanges updateNamespaceProperties(String namespace, List<String> removals,
Map<String, String> updates) {
Database database = requireDatabase(namespace);
Database updated = new Database(database.getName());
updated.setDescription(database.getDescription());
updated.setLocationUri(database.getLocationUri());
Map<String, String> parameters = new LinkedHashMap<>(database.getParameters() == null ? Map.of()
: database.getParameters());
List<String> removed = new ArrayList<>();
List<String> missing = new ArrayList<>();
for (String name : removals) {
boolean present = switch (name) {
case "location" -> updated.getLocationUri() != null;
case "comment" -> updated.getDescription() != null;
default -> parameters.containsKey(name);
};
if (!present) {
missing.add(name);
continue;
}
switch (name) {
case "location" -> updated.setLocationUri(null);
case "comment" -> updated.setDescription(null);
default -> parameters.remove(name);
}
removed.add(name);
}
updates.forEach((key, value) -> {
switch (key) {
case "location" -> updated.setLocationUri(value);
case "comment" -> updated.setDescription(value);
default -> parameters.put(key, value);
}
});
updated.setParameters(parameters);
glue.updateDatabase(database.getName(), updated);
return new PropertyChanges(removed, missing, List.copyOf(updates.keySet()));
}
@Override
public void dropNamespace(String namespace) {
Database database = requireDatabase(namespace);
if (!glue.getTables(database.getName()).isEmpty()) {
throw new IcebergRestException(409, "NamespaceNotEmptyException",
"Namespace " + database.getName() + " is not empty");
}
glue.deleteDatabase(database.getName());
}
@Override
public List<String> tables(String namespace) {
Database database = requireDatabase(namespace);
return glue.getTables(database.getName()).stream()
.filter(GlueTableResolver::isIcebergTable)
.map(Table::getName)
.toList();
}
@Override
public Optional<StoredTable> table(String namespace, String name) {
Table table;
try {
table = glue.getTable(namespace, name);
} catch (AwsException e) {
if ("EntityNotFoundException".equals(e.getErrorCode())) {
return Optional.empty();
}
throw e;
}
boolean iceberg = GlueTableResolver.isIcebergTable(table);
return Optional.of(new StoredTable(iceberg ? GlueTableResolver.icebergMetadataLocation(table) : null,
table.getVersionId(), null, iceberg));
}
@Override
public String locationForNewTable(String namespace, String name, String requestedLocation) {
if (requestedLocation != null) {
return IcebergGlueTables.stripTrailingSlash(requestedLocation);
}
Database database = requireDatabase(namespace);
if (database.getLocationUri() == null || database.getLocationUri().isBlank()) {
throw IcebergRestException.badRequest("Table " + database.getName() + "." + name
+ " needs a location: the request names none and namespace " + database.getName()
+ " has no location property");
}
return IcebergGlueTables.stripTrailingSlash(database.getLocationUri()) + "/" + name;
}
@Override
public void create(String namespace, String name, ObjectNode metadata, String metadataLocation,
StoredTable reserved) {
try {
glue.createTable(namespace, icebergTable(name, metadata, metadataLocation, null));
} catch (AwsException e) {
throw translated(e, namespace, null);
}
}
@Override
public void commit(String namespace, String name, StoredTable base, ObjectNode metadata, String metadataLocation) {
Table existing;
try {
existing = glue.getTable(namespace, name);
} catch (AwsException e) {
throw translated(e, namespace, name);
}
Table updated = icebergTable(existing.getName(), metadata, metadataLocation, existing);
updated.getParameters().put(PARAM_PREVIOUS_METADATA_LOCATION, base.metadataLocation());
try {
glue.updateTable(namespace, updated, base.token(), false);
} catch (AwsException e) {
if ("ConcurrentModificationException".equals(e.getErrorCode())) {
throw new IcebergRestException(409, "CommitFailedException",
"Table " + namespace + "." + name + " was changed concurrently");
}
throw translated(e, namespace, name);
}
}
@Override
public void drop(String namespace, String name) {
glue.deleteTable(namespace, name);
}
private Database requireDatabase(String name) {
try {
return glue.getDatabase(name);
} catch (AwsException e) {
if ("EntityNotFoundException".equals(e.getErrorCode())) {
throw IcebergRestException.noSuchNamespace(name);
}
throw e;
}
}
private static Map<String, String> properties(Database database) {
Map<String, String> properties = new LinkedHashMap<>();
if (database.getParameters() != null) {
properties.putAll(database.getParameters());
}
if (database.getLocationUri() != null) {
properties.put("location", database.getLocationUri());
}
if (database.getDescription() != null) {
properties.put("comment", database.getDescription());
}
return properties;
}
/**
* The Glue table holding an Iceberg table, as {@link IcebergGlueTables#glueTable} builds it; what {@code existing}
* holds beyond that (a description, an owner, other parameters) carries over.
*/
private static Table icebergTable(String name, ObjectNode metadata, String metadataLocation, Table existing) {
Table table = IcebergGlueTables.glueTable(name, metadata, metadataLocation);
if (existing != null) {
table.setDescription(existing.getDescription());
table.setOwner(existing.getOwner());
if (existing.getParameters() != null) {
Map<String, String> parameters = new HashMap<>(existing.getParameters());
parameters.putAll(table.getParameters());
table.setParameters(parameters);
}
}
return table;
}
private static IcebergRestException translated(AwsException e, String database, String table) {
return switch (e.getErrorCode()) {
case "AlreadyExistsException" -> IcebergRestException.alreadyExists(e.getMessage());
case "EntityNotFoundException" -> table == null ? IcebergRestException.noSuchNamespace(database)
: IcebergRestException.noSuchTable(database, table);
default -> IcebergRestException.badRequest(e.getMessage());
};
}
}
@@ -0,0 +1,70 @@
package io.floci.aws.services.glue.iceberg;
import com.fasterxml.jackson.databind.node.ObjectNode;
import java.util.List;
import java.util.Map;
import java.util.Optional;
/**
* Where a catalog of AWS Glue's Iceberg REST endpoint keeps its namespaces and tables: the account's default Glue Data
* Catalog ({@link GlueIcebergStore}), or a table bucket federated from Amazon S3 Tables ({@link S3TablesIcebergStore}).
* The endpoint itself checks a commit's requirements, applies its updates and writes metadata files; a store only
* records which metadata file is current, refusing a commit whose base is no longer current. Errors are the endpoint's
* own ({@link IcebergRestException}).
*/
interface IcebergCatalogStore {
/**
* A table the store holds: its current metadata file (null while S3 Tables holds a table nothing has committed to
* yet), the token a commit has to name as its base, its location when the store manages it, and whether it is an
* Iceberg table at all.
*/
record StoredTable(String metadataLocation, String token, String location, boolean iceberg) {
}
/** What a namespace properties update removed, could not find, and updated. */
record PropertyChanges(List<String> removed, List<String> missing, List<String> updated) {
}
/** Whether the store decides where a table lives, so a table's location is never the client's to name. */
boolean managesLocations();
List<String> namespaces();
/** The namespace's properties; {@code NoSuchNamespaceException} when there is no such namespace. */
Map<String, String> namespaceProperties(String namespace);
void createNamespace(String namespace, Map<String, String> properties);
PropertyChanges updateNamespaceProperties(String namespace, List<String> removals, Map<String, String> updates);
/** Drops an empty namespace; {@code NamespaceNotEmptyException} when it holds tables. */
void dropNamespace(String namespace);
/** The namespace's Iceberg tables. */
List<String> tables(String namespace);
Optional<StoredTable> table(String namespace, String name);
/**
* The location a new table takes: the one the request names, or the store's own. A store that manages locations
* (S3 Tables) creates the table here, empty, and refuses a location the request names.
*/
String locationForNewTable(String namespace, String name, String requestedLocation);
/**
* Records a new table whose first metadata file is {@code metadataLocation}; {@code reserved} is the empty table
* {@link #locationForNewTable} left, if the store made one. {@code AlreadyExistsException} when the table appeared
* meanwhile.
*/
void create(String namespace, String name, ObjectNode metadata, String metadataLocation, StoredTable reserved);
/**
* Moves the table's current metadata file from {@code base}'s to {@code metadataLocation};
* {@code CommitFailedException} when the table changed since {@code base} was read.
*/
void commit(String namespace, String name, StoredTable base, ObjectNode metadata, String metadataLocation);
void drop(String namespace, String name);
}
@@ -71,6 +71,11 @@ public final class IcebergGlueTables {
}
}
/** {@code location} without a trailing slash. */
static String stripTrailingSlash(String location) {
return location != null && location.endsWith("/") ? location.substring(0, location.length() - 1) : location;
}
/** The bucket and key an {@code s3://} (or {@code s3a://}, {@code s3n://}) object location names. */
static S3Location s3Location(String location) {
Matcher matcher = S3_LOCATION.matcher(location == null ? "" : location);
@@ -0,0 +1,191 @@
package io.floci.aws.services.glue.iceberg;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.services.s3tables.S3TablesService;
import io.floci.aws.services.s3tables.model.Namespace;
import io.floci.aws.services.s3tables.model.S3Table;
import java.util.List;
import java.util.Map;
import java.util.Optional;
/**
* A table bucket federated from Amazon S3 Tables ({@code s3tablescatalog/<bucket>}) as an Iceberg catalog: a namespace
* is one of the bucket's namespaces, which take no properties, and a table one of its tables. S3 Tables decides where
* a table lives (its warehouse location) when the table is created, and moves the table's metadata location with
* {@code UpdateTableMetadataLocation}, refused when the version token is no longer the table's. A table S3 Tables holds
* but nothing has committed to yet, as a staged create leaves it, has no metadata location.
*/
final class S3TablesIcebergStore implements IcebergCatalogStore {
private static final String ICEBERG = "ICEBERG";
private static final String SPARK_OWNER_PROPERTY = "owner";
private final S3TablesService s3Tables;
private final String bucketArn;
private final String region;
S3TablesIcebergStore(S3TablesService s3Tables, String bucketArn, String region) {
this.s3Tables = s3Tables;
this.bucketArn = bucketArn;
this.region = region;
}
@Override
public boolean managesLocations() {
return true;
}
@Override
public List<String> namespaces() {
return s3Tables.listNamespaces(bucketArn, null, region).stream().map(Namespace::getName).toList();
}
@Override
public Map<String, String> namespaceProperties(String namespace) {
requireNamespace(namespace);
return Map.of();
}
/**
* Creates a namespace. S3 Tables namespaces store no properties: the {@code owner} Spark adds to every
* {@code CREATE NAMESPACE} is let go, any other property refused rather than silently lost.
*/
@Override
public void createNamespace(String namespace, Map<String, String> properties) {
if (!properties.keySet().stream().allMatch(SPARK_OWNER_PROPERTY::equals)) {
throw IcebergRestException.badRequest("S3 Tables namespaces take no properties");
}
try {
s3Tables.createNamespace(bucketArn, List.of(namespace), region);
} catch (AwsException e) {
if ("ConflictException".equals(e.getErrorCode())) {
throw IcebergRestException.alreadyExists("Namespace already exists: " + namespace);
}
throw IcebergRestException.badRequest(e.getMessage());
}
}
@Override
public PropertyChanges updateNamespaceProperties(String namespace, List<String> removals,
Map<String, String> updates) {
requireNamespace(namespace);
if (!updates.isEmpty()) {
throw IcebergRestException.badRequest("S3 Tables namespaces take no properties");
}
return new PropertyChanges(List.of(), List.copyOf(removals), List.of());
}
@Override
public void dropNamespace(String namespace) {
requireNamespace(namespace);
try {
s3Tables.deleteNamespace(bucketArn, namespace, region);
} catch (AwsException e) {
if ("ConflictException".equals(e.getErrorCode())) {
throw new IcebergRestException(409, "NamespaceNotEmptyException",
"Namespace " + namespace + " is not empty");
}
throw IcebergRestException.badRequest(e.getMessage());
}
}
/** The namespace's tables that hold Iceberg metadata; one a staged create holds, empty, is not loadable yet. */
@Override
public List<String> tables(String namespace) {
requireNamespace(namespace);
return s3Tables.listTables(bucketArn, namespace, null, region).stream()
.filter(table -> table.getMetadataLocation() != null && !table.getMetadataLocation().isBlank())
.map(S3Table::getName)
.toList();
}
@Override
public Optional<StoredTable> table(String namespace, String name) {
requireNamespace(namespace);
try {
S3Table table = s3Tables.getTable(bucketArn, namespace, name, region);
return Optional.of(stored(table));
} catch (AwsException e) {
if ("NotFoundException".equals(e.getErrorCode())) {
return Optional.empty();
}
throw e;
}
}
@Override
public String locationForNewTable(String namespace, String name, String requestedLocation) {
if (requestedLocation != null) {
throw IcebergRestException.badRequest("S3 Tables decides where a table lives: a create names no location");
}
requireNamespace(namespace);
try {
return stored(s3Tables.createTable(bucketArn, namespace, name, ICEBERG, null, null, null, Map.of(),
region)).location();
} catch (AwsException e) {
if ("ConflictException".equals(e.getErrorCode())) {
throw IcebergRestException.alreadyExists("Table already exists: " + namespace + "." + name);
}
throw IcebergRestException.badRequest(e.getMessage());
}
}
@Override
public void create(String namespace, String name, ObjectNode metadata, String metadataLocation,
StoredTable reserved) {
StoredTable table = reserved != null ? reserved : table(namespace, name)
.orElseThrow(() -> IcebergRestException.noSuchTable(namespace, name));
if (table.metadataLocation() != null) {
throw IcebergRestException.alreadyExists("Table already exists: " + namespace + "." + name);
}
commit(namespace, name, table, metadata, metadataLocation);
}
@Override
public void commit(String namespace, String name, StoredTable base, ObjectNode metadata, String metadataLocation) {
try {
s3Tables.updateTableMetadataLocation(bucketArn, namespace, name, metadataLocation, base.token(), region);
} catch (AwsException e) {
if ("ConflictException".equals(e.getErrorCode())) {
throw new IcebergRestException(409, "CommitFailedException",
"Table " + namespace + "." + name + " was changed concurrently");
}
if ("NotFoundException".equals(e.getErrorCode())) {
throw IcebergRestException.noSuchTable(namespace, name);
}
throw IcebergRestException.badRequest(e.getMessage());
}
}
@Override
public void drop(String namespace, String name) {
try {
s3Tables.deleteTable(bucketArn, namespace, name, region);
} catch (AwsException e) {
if ("NotFoundException".equals(e.getErrorCode())) {
throw IcebergRestException.noSuchTable(namespace, name);
}
throw IcebergRestException.badRequest(e.getMessage());
}
}
private void requireNamespace(String namespace) {
try {
s3Tables.getNamespace(bucketArn, namespace, region);
} catch (AwsException e) {
if ("NotFoundException".equals(e.getErrorCode())) {
throw IcebergRestException.noSuchNamespace(namespace);
}
throw e;
}
}
private static StoredTable stored(S3Table table) {
String location = IcebergGlueTables.stripTrailingSlash(table.getWarehouseLocation());
String metadataLocation = table.getMetadataLocation() == null || table.getMetadataLocation().isBlank()
? null : table.getMetadataLocation();
return new StoredTable(metadataLocation, table.getVersionToken(), location, true);
}
}
@@ -54,7 +54,7 @@ class GlueIcebergCatalogTest {
glue = Mockito.mock(GlueService.class);
s3 = Mockito.mock(S3Service.class);
catalog = new GlueIcebergCatalog(glue, s3, new RegionResolver("us-east-1", "000000000000"), mapper,
Clock.fixed(Instant.ofEpochMilli(10_000L), ZoneOffset.UTC));
null, null, 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);
@@ -27,7 +27,8 @@ class GlueIcebergControllerTest {
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());
Mockito.mock(S3Service.class), new RegionResolver("us-east-1", "000000000000"), new ObjectMapper(),
null, null);
controller = new GlueIcebergController(catalog, config, requestContext);
}
@@ -7,7 +7,6 @@ import io.floci.aws.testutil.AwsRequestSigner;
import io.quarkus.test.common.http.TestHTTPResource;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.Response;
import io.restassured.specification.RequestSpecification;
import jakarta.inject.Inject;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
@@ -18,7 +17,6 @@ import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.endsWith;
import static org.hamcrest.Matchers.equalTo;
@@ -84,18 +82,7 @@ class GlueIcebergRestIntegrationTest {
+ "\"schema\":" + SCHEMA + ",\"properties\":{\"format-version\":\"2\"}}").then().statusCode(200)
.body("metadata.location", equalTo("s3://" + bucket + "/lake/events"))
.body("metadata-location", nullValue());
return send(glue, "POST", tablePath(), """
{"requirements":[{"type":"assert-create"}],"updates":[
{"action":"assign-uuid","uuid":"11111111-2222-3333-4444-555555555555"},
{"action":"upgrade-format-version","format-version":2},
{"action":"add-schema","last-column-id":2,"schema":%s},
{"action":"add-spec","spec":{"spec-id":0,"fields":[]}},{"action":"set-default-spec","spec-id":0},
{"action":"add-sort-order","sort-order":{"order-id":0,"fields":[]}},
{"action":"set-default-sort-order","sort-order-id":0},
{"action":"set-location","location":"s3://%s/lake/events"},
{"action":"set-properties","updates":{"format-version":"2"}},
{"action":"set-current-schema","schema-id":0}]}
""".formatted(SCHEMA, bucket)).then().statusCode(200)
return send(glue, "POST", tablePath(), IcebergCommits.createCommit(SCHEMA, "s3://" + bucket + "/lake/events")).then().statusCode(200)
.body("metadata-location", endsWith(".metadata.json"))
.extract().path("metadata-location");
}
@@ -205,17 +192,6 @@ class GlueIcebergRestIntegrationTest {
}
private Response send(AwsRequestSigner signer, String method, String path, String body) {
URI uri = endpoint.resolve(path);
byte[] bytes = body == null ? new byte[0] : body.getBytes(StandardCharsets.UTF_8);
try {
RequestSpecification request = given().urlEncodingEnabled(false)
.headers(signer.headersFor(method, uri, Map.of(), bytes));
if (body != null) {
request = request.contentType("application/json").body(bytes);
}
return request.request(method, uri);
} catch (Exception e) {
throw new IllegalStateException(e);
}
return IcebergCommits.send(endpoint, signer, method, path, body);
}
}
@@ -0,0 +1,182 @@
package io.floci.aws.services.glue.iceberg;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.floci.aws.core.common.RequestScopes;
import io.floci.aws.services.glue.GlueCatalogService;
import io.floci.aws.services.s3tables.S3TablesService;
import io.floci.aws.services.s3tables.model.Namespace;
import io.floci.aws.services.s3tables.model.S3Table;
import io.floci.aws.services.s3tables.model.TableBucket;
import io.floci.aws.testutil.AwsRequestSigner;
import io.quarkus.test.common.http.TestHTTPResource;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.Response;
import jakarta.inject.Inject;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.net.URI;
import java.util.List;
import java.util.Map;
import static org.hamcrest.Matchers.endsWith;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasSize;
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;
/**
* AWS Glue's Iceberg REST endpoint serving a table bucket federated from Amazon S3 Tables: the warehouse
* {@code <account>:s3tablescatalog/<bucket>} configures the prefix {@code catalogs/<account>:s3tablescatalog:<bucket>},
* under which namespaces and tables are the bucket's own, S3 Tables placing each table and each commit moving its
* metadata location.
*/
@QuarkusTest
class GlueIcebergS3TablesRestIntegrationTest {
private static final String ACCOUNT = "000000000000";
private static final String REGION = "us-east-1";
private static final String SCHEMA = """
{"type":"struct","schema-id":0,"fields":[{"id":1,"name":"id","required":false,"type":"long"},
{"id":2,"name":"name","required":false,"type":"string"}]}""";
private final AwsRequestSigner glue = AwsRequestSigner.signedAs("test", "test", "glue");
@TestHTTPResource("/")
URI endpoint;
@Inject
S3TablesService s3Tables;
@Inject
GlueCatalogService catalogs;
private TableBucket bucket;
private String prefix;
@BeforeEach
void federateATableBucket() throws Exception {
String name = "rest-" + System.nanoTime();
ObjectNode input = (ObjectNode) new ObjectMapper().readTree("""
{"FederatedCatalog":{"Identifier":"arn:aws:s3tables:us-east-1:000000000000:bucket/%s",
"ConnectionName":"aws:s3tables"}}""".formatted(name));
RequestScopes.runAs(ACCOUNT, REGION, () -> {
bucket = s3Tables.createTableBucket(name, null, null, Map.of(), REGION);
catalogs.createCatalog("s3tablescatalog", input, Map.of(), REGION);
});
prefix = "/iceberg/v1/catalogs/" + ACCOUNT + ":s3tablescatalog:" + bucket.getName();
}
@AfterEach
void removeTheBucket() {
RequestScopes.runAs(ACCOUNT, REGION, () -> {
catalogs.deleteCatalog("s3tablescatalog", REGION);
for (Namespace namespace : s3Tables.listNamespaces(bucket.getArn(), null, REGION)) {
for (S3Table table : s3Tables.listTables(bucket.getArn(), namespace.getName(), null, REGION)) {
s3Tables.deleteTable(bucket.getArn(), namespace.getName(), table.getName(), REGION);
}
s3Tables.deleteNamespace(bucket.getArn(), namespace.getName(), REGION);
}
s3Tables.deleteTableBucket(bucket.getArn(), REGION);
});
}
private Response send(String method, String path, String body) {
return IcebergCommits.send(endpoint, glue, method, path, body);
}
private S3Table s3Table(String name) {
return RequestScopes.callAs(ACCOUNT, REGION, () -> s3Tables.getTable(bucket.getArn(), "sales", name, REGION));
}
@Test
void theWarehouseOfATableBucketConfiguresItsCatalogsPrefix() {
send("GET", "/iceberg/v1/config?warehouse=" + ACCOUNT + "%3As3tablescatalog%2F" + bucket.getName(), null)
.then().statusCode(200)
.body("overrides.prefix", equalTo("catalogs/" + ACCOUNT + ":s3tablescatalog:" + bucket.getName()));
send("GET", "/iceberg/v1/config?warehouse=" + ACCOUNT + "%3As3tablescatalog%2Fno-such-bucket", null)
.then().statusCode(400).body("error.type", equalTo("BadRequestException"));
}
@Test
void aStagedCreateAndItsCommitMakeAnS3TableWhoseMetadataLocationEachCommitMoves() {
send("POST", prefix + "/namespaces", "{\"namespace\":[\"sales\"]}").then().statusCode(200);
send("GET", "/iceberg/v1/catalogs/s3tablescatalog:" + bucket.getName() + "/namespaces", null)
.then().statusCode(200).body("namespaces[0][0]", equalTo("sales"));
String location = send("POST", prefix + "/namespaces/sales/tables",
"{\"stage-create\":true,\"name\":\"orders\",\"schema\":" + SCHEMA + "}")
.then().statusCode(200).extract().path("metadata.location");
S3Table reserved = s3Table("orders");
assertEquals(reserved.getWarehouseLocation().replaceAll("/$", ""), location);
assertNull(reserved.getMetadataLocation(), "a staged create commits nothing yet");
send("GET", prefix + "/namespaces/sales/tables", null).then().statusCode(200)
.body("identifiers", hasSize(0));
String created = send("POST", prefix + "/namespaces/sales/tables/orders",
IcebergCommits.createCommit(SCHEMA, location)).then().statusCode(200)
.body("metadata-location", endsWith(".metadata.json"))
.extract().path("metadata-location");
assertEquals(created, s3Table("orders").getMetadataLocation());
assertTrue(created.startsWith(location + "/metadata/00000-"), created);
String committed = send("POST", prefix + "/namespaces/sales/tables/orders",
IcebergCommits.snapshotCommit(7, null, 1)).then().statusCode(200)
.body("metadata.current-snapshot-id", equalTo(7))
.extract().path("metadata-location");
assertEquals(committed, s3Table("orders").getMetadataLocation());
send("POST", prefix + "/namespaces/sales/tables/orders", IcebergCommits.snapshotCommit(8, null, 2))
.then().statusCode(409).body("error.type", equalTo("CommitFailedException"));
send("POST", prefix + "/namespaces/sales/tables/orders", "{\"requirements\":[],\"updates\":["
+ "{\"action\":\"set-location\",\"location\":\"s3://elsewhere/orders\"}]}")
.then().statusCode(400).body("error.type", equalTo("BadRequestException"));
assertEquals(committed, s3Table("orders").getMetadataLocation(), "a refused move leaves the table where it was");
send("GET", prefix + "/namespaces/sales/tables/orders", null).then().statusCode(200)
.body("metadata-location", equalTo(committed));
send("GET", prefix + "/namespaces/sales/tables", null).then().statusCode(200)
.body("identifiers[0].name", equalTo("orders"));
send("DELETE", prefix + "/namespaces/sales/tables/orders", null).then().statusCode(204);
assertTrue(RequestScopes.callAs(ACCOUNT, REGION,
() -> s3Tables.listTables(bucket.getArn(), "sales", null, REGION)).isEmpty());
}
@Test
void aCreateNamingALocationOrAPropertyIsRefusedSinceS3TablesDecidesThem() {
send("POST", prefix + "/namespaces", "{\"namespace\":[\"sales\"],\"properties\":{\"comment\":\"x\"}}")
.then().statusCode(400).body("error.type", equalTo("BadRequestException"));
// Spark adds its user as owner to every CREATE NAMESPACE; S3 Tables cannot keep it, so it is let go.
send("POST", prefix + "/namespaces", "{\"namespace\":[\"sales\"],\"properties\":{\"owner\":\"spark\"}}")
.then().statusCode(200);
send("POST", prefix + "/namespaces/sales/tables/direct", IcebergCommits.createCommit(SCHEMA,
"s3://elsewhere/direct")).then().statusCode(400).body("error.type", equalTo("BadRequestException"));
assertTrue(RequestScopes.callAs(ACCOUNT, REGION,
() -> s3Tables.listTables(bucket.getArn(), "sales", null, REGION)).isEmpty(),
"a refused create leaves no table behind");
send("POST", prefix + "/namespaces/sales/tables", "{\"name\":\"orders\",\"schema\":" + SCHEMA
+ ",\"location\":\"s3://elsewhere/orders\"}")
.then().statusCode(400).body("error.type", equalTo("BadRequestException"));
}
@Test
void aCommitOnAStaleVersionTokenIsACommitFailure() throws Exception {
send("POST", prefix + "/namespaces", "{\"namespace\":[\"sales\"]}").then().statusCode(200);
send("POST", prefix + "/namespaces/sales/tables", "{\"name\":\"orders\",\"schema\":" + SCHEMA + "}")
.then().statusCode(200);
S3TablesIcebergStore store = new S3TablesIcebergStore(s3Tables, bucket.getArn(), REGION);
IcebergCatalogStore.StoredTable base = RequestScopes.callAs(ACCOUNT, REGION,
() -> store.table("sales", "orders").orElseThrow());
RequestScopes.runAs(ACCOUNT, REGION, () -> s3Tables.updateTableMetadataLocation(bucket.getArn(), "sales",
"orders", base.metadataLocation(), base.token(), REGION));
IcebergRestException stale = assertThrows(IcebergRestException.class, () -> RequestScopes.runAs(ACCOUNT,
REGION, () -> store.commit("sales", "orders", base, null, base.metadataLocation() + ".next")));
assertEquals("CommitFailedException", stale.type());
assertEquals(List.of("orders"), RequestScopes.callAs(ACCOUNT, REGION, () -> store.tables("sales")));
}
}
@@ -1,6 +1,16 @@
package io.floci.aws.services.glue.iceberg;
/** The commit bodies the Iceberg catalog tests send, as an Iceberg writer builds them. */
import io.floci.aws.testutil.AwsRequestSigner;
import io.restassured.response.Response;
import io.restassured.specification.RequestSpecification;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import static io.restassured.RestAssured.given;
/** The commit bodies the Iceberg catalog tests send, as an Iceberg writer builds them, and how they send them. */
final class IcebergCommits {
private IcebergCommits() {
@@ -21,4 +31,39 @@ final class IcebergCommits {
""".formatted(parentSnapshotId == null ? "null" : parentSnapshotId, snapshotId, parent, sequenceNumber,
snapshotId, snapshotId);
}
/**
* The commit that creates a table a staged create described, as DuckDB and Spark send it: required to find no
* table, with a two-column {@code schema} and its {@code location}.
*/
static String createCommit(String schema, String location) {
return """
{"requirements":[{"type":"assert-create"}],"updates":[
{"action":"assign-uuid","uuid":"11111111-2222-3333-4444-555555555555"},
{"action":"upgrade-format-version","format-version":2},
{"action":"add-schema","last-column-id":2,"schema":%s},
{"action":"add-spec","spec":{"spec-id":0,"fields":[]}},{"action":"set-default-spec","spec-id":0},
{"action":"add-sort-order","sort-order":{"order-id":0,"fields":[]}},
{"action":"set-default-sort-order","sort-order-id":0},
{"action":"set-location","location":"%s"},
{"action":"set-properties","updates":{"format-version":"2"}},
{"action":"set-current-schema","schema-id":0}]}
""".formatted(schema, location);
}
/** Sends a request to the Iceberg REST endpoint at {@code path}, signed by {@code signer}. */
static Response send(URI endpoint, AwsRequestSigner signer, String method, String path, String body) {
URI uri = endpoint.resolve(path);
byte[] bytes = body == null ? new byte[0] : body.getBytes(StandardCharsets.UTF_8);
try {
RequestSpecification request = given().urlEncodingEnabled(false)
.headers(signer.headersFor(method, uri, Map.of(), bytes));
if (body != null) {
request = request.contentType("application/json").body(bytes);
}
return request.request(method, uri);
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
}