From 5059a3cd40d95151089c8c3bba00871ca01d60b6 Mon Sep 17 00:00:00 2001 From: Priamo Germosen <6233424+pgermosen@users.noreply.github.com> Date: Sun, 15 Nov 2026 13:48:35 -0400 Subject: [PATCH] feat(glue): serve AWS Glue's Iceberg REST endpoint (#8472) AWS Glue serves the Apache Iceberg REST catalog at glue..amazonaws.com/iceberg, the catalog Spark, PyIceberg, Trino and DuckDB attach to read and write Glue's Iceberg tables. Floci had no such endpoint, so none of them could write an Iceberg table through it, and DuckDB, which writes Iceberg only through an attached catalog, could not write one at all. Floci now serves it at /iceberg, routed by the request's signing service as other contested REST paths are, with the twelve operations AWS lists for it. A namespace is a Glue database and a table a Glue table with table_type ICEBERG. The writer writes data files and manifests; a commit checks the request's requirements, applies its updates to the table's metadata JSON, writes the next metadata file next to the last one and moves the Glue table's metadata_location to it, refused with CommitFailedException when the Glue table changed since. A staged create is committed with assert-create, as DuckDB and Spark create tables. No Iceberg library is involved. --- docs/services/glue.md | 19 + .../core/common/ResolvedServiceCatalog.java | 3 +- .../glue/iceberg/GlueIcebergCatalog.java | 594 ++++++++++++++++++ .../glue/iceberg/GlueIcebergController.java | 118 ++++ .../glue/iceberg/GlueIcebergRouteFilter.java | 36 ++ .../glue/iceberg/IcebergRestException.java | 43 ++ .../iceberg/IcebergRestExceptionMapper.java | 26 + .../glue/iceberg/IcebergTableMetadata.java | 430 +++++++++++++ .../services/glue/iceberg/IcebergTypes.java | 54 ++ .../glue/iceberg/GlueIcebergCatalogTest.java | 167 +++++ .../GlueIcebergIamIntegrationTest.java | 48 ++ .../GlueIcebergRestIntegrationTest.java | 221 +++++++ .../services/glue/iceberg/IcebergCommits.java | 24 + .../iceberg/IcebergTableMetadataTest.java | 244 +++++++ 14 files changed, 2026 insertions(+), 1 deletion(-) create mode 100644 src/main/java/io/floci/aws/services/glue/iceberg/GlueIcebergCatalog.java create mode 100644 src/main/java/io/floci/aws/services/glue/iceberg/GlueIcebergController.java create mode 100644 src/main/java/io/floci/aws/services/glue/iceberg/GlueIcebergRouteFilter.java create mode 100644 src/main/java/io/floci/aws/services/glue/iceberg/IcebergRestException.java create mode 100644 src/main/java/io/floci/aws/services/glue/iceberg/IcebergRestExceptionMapper.java create mode 100644 src/main/java/io/floci/aws/services/glue/iceberg/IcebergTableMetadata.java create mode 100644 src/main/java/io/floci/aws/services/glue/iceberg/IcebergTypes.java create mode 100644 src/test/java/io/floci/aws/services/glue/iceberg/GlueIcebergCatalogTest.java create mode 100644 src/test/java/io/floci/aws/services/glue/iceberg/GlueIcebergIamIntegrationTest.java create mode 100644 src/test/java/io/floci/aws/services/glue/iceberg/GlueIcebergRestIntegrationTest.java create mode 100644 src/test/java/io/floci/aws/services/glue/iceberg/IcebergCommits.java create mode 100644 src/test/java/io/floci/aws/services/glue/iceberg/IcebergTableMetadataTest.java diff --git a/docs/services/glue.md b/docs/services/glue.md index aa1689b7a8..f72a294cec 100644 --- a/docs/services/glue.md +++ b/docs/services/glue.md @@ -332,6 +332,25 @@ ARN `arn:aws:glue:::dataQualityRuleset/`. Supported schema formats are `AVRO`, `JSON`, and `PROTOBUF`. Compatibility modes are `NONE`, `DISABLED`, `BACKWARD`, `BACKWARD_ALL`, `FORWARD`, `FORWARD_ALL`, `FULL`, and `FULL_ALL`. +## Iceberg REST endpoint + +Floci serves AWS Glue's [Iceberg REST endpoint](https://docs.aws.amazon.com/glue/latest/dg/connect-glu-iceberg-rest.html) at `/iceberg` on the Floci endpoint (`https://glue..amazonaws.com/iceberg` on AWS), signed for the `glue` service. An Iceberg REST catalog client (Spark's `SparkCatalog` with `type=rest`, PyIceberg, Trino) uses it as it uses AWS's: the warehouse is the account id, and the path prefix is `/v1/catalogs/{catalog}`, where `{catalog}` is `:` (the caller's default catalog) or the caller's account id. + +```python +spark = (SparkSession.builder + .config("spark.sql.catalog.glue", "org.apache.iceberg.spark.SparkCatalog") + .config("spark.sql.catalog.glue.type", "rest") + .config("spark.sql.catalog.glue.uri", "http://localhost:4566/iceberg") + .config("spark.sql.catalog.glue.warehouse", "000000000000") + .config("spark.sql.catalog.glue.rest.sigv4-enabled", "true") + .config("spark.sql.catalog.glue.rest.signing-name", "glue") + .getOrCreate()) +``` + +The operations are the twelve AWS lists: `GetConfig`, `ListNamespaces`, `CreateNamespace`, `LoadNamespaceMetadata`, `UpdateNamespaceProperties`, `DeleteNamespace`, `ListTables`, `CreateTable`, `LoadTable`, `TableExists`, `UpdateTable` and `DeleteTable`. A namespace is a Glue database (single-level, as on AWS); its `location` and `comment` properties are the database's `LocationUri` and `Description`. A table is a Glue table whose `Parameters.table_type` is `ICEBERG` and whose `Parameters.metadata_location` names its current metadata file in S3. The writer writes data files and manifests itself. Each commit checks the request's requirements, applies its updates, writes the next metadata file beside the last one (`/metadata/00001-.metadata.json`), and moves `metadata_location` to it, with `previous_metadata_location` set to the old one. If the Glue table changed since the commit's base, the commit is refused with `CommitFailedException` (409). A commit that fails after writing its metadata file (Glue refuses it, or it was not the last commit) removes that file again. Because every commit lands on the Glue table, Spark's `GlueCatalog` and Athena read each committed snapshot. A staged create (`stage-create`) creates nothing until its commit (`assert-create`), the way Spark and DuckDB create tables. A table with no location takes its namespace's location plus its name. `DeleteTable` drops the Glue table and leaves its files in S3. + +Not yet: IAM policies are not checked on this endpoint, so under IAM enforcement it answers only the account's root credentials and refuses IAM principals (`ForbiddenException`, 403) rather than let them through unchecked. Other accounts' catalogs and nested catalogs (`s3tablescatalog/`) are not served. DuckDB signs SigV4 catalog requests only over HTTPS, so DuckDB attaches this endpoint with SigV4 only when Floci serves TLS (`floci.tls.enabled`). + ## Configuration | Variable | Default | Description | diff --git a/src/main/java/io/floci/aws/core/common/ResolvedServiceCatalog.java b/src/main/java/io/floci/aws/core/common/ResolvedServiceCatalog.java index f52f489d70..b490f936fa 100644 --- a/src/main/java/io/floci/aws/core/common/ResolvedServiceCatalog.java +++ b/src/main/java/io/floci/aws/core/common/ResolvedServiceCatalog.java @@ -46,6 +46,7 @@ import io.floci.aws.services.efs.EfsController; import io.floci.aws.services.eks.EksController; import io.floci.aws.services.emrserverless.EmrServerlessController; import io.floci.aws.services.fis.FisController; +import io.floci.aws.services.glue.iceberg.GlueIcebergController; import io.floci.aws.services.guardduty.GuardDutyController; import io.floci.aws.services.inspector2.Inspector2Controller; import io.floci.aws.services.iot.IotAuthorizerController; @@ -385,7 +386,7 @@ public class ResolvedServiceCatalog { descriptor("glue", "glue", config.services().glue().enabled(), true, "glue", config.storage().mode(), 5000L, null, ServiceProtocol.JSON, protocols(ServiceProtocol.JSON), - Set.of("AWSGlue."), Set.of("glue"), Set.of(), Set.of()), + Set.of("AWSGlue."), Set.of("glue"), Set.of(), Set.of(GlueIcebergController.class)), descriptor("firehose", "firehose", config.services().firehose().enabled(), true, "firehose", config.storage().mode(), 5000L, null, ServiceProtocol.JSON, protocols(ServiceProtocol.JSON), diff --git a/src/main/java/io/floci/aws/services/glue/iceberg/GlueIcebergCatalog.java b/src/main/java/io/floci/aws/services/glue/iceberg/GlueIcebergCatalog.java new file mode 100644 index 0000000000..69923b001d --- /dev/null +++ b/src/main/java/io/floci/aws/services/glue/iceberg/GlueIcebergCatalog.java @@ -0,0 +1,594 @@ +package io.floci.aws.services.glue.iceberg; + +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; +import io.floci.aws.services.glue.model.Database; +import io.floci.aws.services.glue.model.StorageDescriptor; +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 org.jboss.logging.Logger; + +import java.io.IOException; +import java.io.InputStream; +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.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 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. + */ +@ApplicationScoped +public class GlueIcebergCatalog { + + private static final Logger LOG = Logger.getLogger(GlueIcebergCatalog.class); + + static final String DEFAULT_CATALOG = ":"; + private static final String PARAM_TABLE_TYPE = "table_type"; + private static final String PARAM_METADATA_LOCATION = "metadata_location"; + private static final String PARAM_PREVIOUS_METADATA_LOCATION = "previous_metadata_location"; + private static final String ICEBERG = "ICEBERG"; + private static final Pattern S3_LOCATION = Pattern.compile("^s3[an]?://([^/]+)/?(.*)$"); + private static final Pattern METADATA_VERSION = Pattern.compile("^(\\d+)-.*\\.metadata\\.json$"); + /** The REST routes the endpoint answers, as {@code GetConfig}'s {@code endpoints} names them. */ + private static final List ENDPOINTS = List.of( + "GET /v1/{prefix}/namespaces", + "POST /v1/{prefix}/namespaces", + "GET /v1/{prefix}/namespaces/{namespace}", + "POST /v1/{prefix}/namespaces/{namespace}/properties", + "DELETE /v1/{prefix}/namespaces/{namespace}", + "GET /v1/{prefix}/namespaces/{namespace}/tables", + "POST /v1/{prefix}/namespaces/{namespace}/tables", + "GET /v1/{prefix}/namespaces/{namespace}/tables/{table}", + "HEAD /v1/{prefix}/namespaces/{namespace}/tables/{table}", + "POST /v1/{prefix}/namespaces/{namespace}/tables/{table}", + "DELETE /v1/{prefix}/namespaces/{namespace}/tables/{table}"); + + private final GlueService glue; + 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()); + } + + GlueIcebergCatalog(GlueService glue, S3Service s3, RegionResolver regionResolver, ObjectMapper mapper, + EmulatorConfig config, RequestContext requestContext, Clock clock) { + this.glue = glue; + this.s3 = s3; + this.regionResolver = regionResolver; + this.mapper = mapper; + this.config = config; + this.requestContext = requestContext; + this.clock = clock; + } + + // ─── GetConfig ──────────────────────────────────────────────────────────────── + + /** The catalog's configuration: the path prefix of the catalog {@code warehouse} names, and the routes served. */ + ObjectNode config(String warehouse) { + String catalog = warehouse == null || warehouse.isBlank() ? DEFAULT_CATALOG : warehouse; + requireDefaultCatalog(catalog); + ObjectNode config = mapper.createObjectNode(); + config.putObject("defaults"); + config.putObject("overrides").put("prefix", "catalogs/" + catalog); + ArrayNode endpoints = config.putArray("endpoints"); + ENDPOINTS.forEach(endpoints::add); + return config; + } + + // ─── Namespaces ─────────────────────────────────────────────────────────────── + + ObjectNode listNamespaces(String catalog, String parent) { + requireDefaultCatalog(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)); + return result; + } + for (Database database : glue.getDatabases()) { + namespaces.addArray().add(database.getName()); + } + return result; + } + + ObjectNode createNamespace(String catalog, JsonNode request) { + requireDefaultCatalog(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 parameters = new LinkedHashMap<>(); + Iterator> properties = request.path("properties").fields(); + while (properties.hasNext()) { + Map.Entry 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); + } + ObjectNode result = mapper.createObjectNode(); + result.putArray("namespace").add(database.getName()); + result.set("properties", properties(requireNamespace(database.getName()))); + return result; + } + + ObjectNode loadNamespace(String catalog, String namespace) { + requireDefaultCatalog(catalog); + Database database = requireNamespace(namespace(namespace)); + ObjectNode result = mapper.createObjectNode(); + result.putArray("namespace").add(database.getName()); + result.set("properties", properties(database)); + 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 parameters = new LinkedHashMap<>(database.getParameters() == null ? Map.of() + : database.getParameters()); + 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> updates = request.path("updates").fields(); + while (updates.hasNext()) { + Map.Entry 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); + 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()); + } + + // ─── Tables ─────────────────────────────────────────────────────────────────── + + ObjectNode listTables(String catalog, String namespace) { + requireDefaultCatalog(catalog); + Database database = requireNamespace(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()); + } + } + 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. + */ + ObjectNode createTable(String catalog, String namespace, JsonNode request) { + requireDefaultCatalog(catalog); + Database database = requireNamespace(namespace(namespace)); + 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 location = request.hasNonNull("location") ? stripTrailingSlash(request.get("location").asText()) + : defaultLocation(database, name); + ObjectNode metadata = IcebergTableMetadata.forCreate(request, location, clock.millis()); + 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); + try { + createGlueTable(database.getName(), name, metadata, metadataLocation); + } catch (RuntimeException e) { + deleteMetadata(metadataLocation); + throw e; + } + result.put("metadata-location", metadataLocation); + result.set("metadata", metadata); + result.putObject("config"); + return result; + } + + 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); + ObjectNode metadata = readMetadata(metadataLocation); + if ("refs".equals(snapshots)) { + metadata.set("snapshots", referencedSnapshots(metadata)); + } + ObjectNode result = mapper.createObjectNode(); + result.put("metadata-location", metadataLocation); + result.set("metadata", metadata); + result.putObject("config"); + return result; + } + + void tableExists(String catalog, String namespace, String name) { + requireDefaultCatalog(catalog); + Database database = requireNamespace(namespace(namespace)); + requireIcebergTable(database.getName(), 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. + */ + ObjectNode commitTable(String catalog, String namespace, String name, JsonNode request) { + requireDefaultCatalog(catalog); + Database database = requireNamespace(namespace(namespace)); + Table existing = findTable(database.getName(), 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 != null && !GlueTableResolver.isIcebergTable(existing)) { + throw IcebergRestException.badRequest("Table " + database.getName() + "." + name + + " is not an Iceberg table"); + } + String baseLocation = existing == null ? null : GlueTableResolver.icebergMetadataLocation(existing); + ObjectNode base = existing == null ? null : readMetadata(baseLocation); + 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)); + } + if (base != null) { + metadata.withArray("metadata-log").addObject() + .put("timestamp-ms", base.path("last-updated-ms").asLong()) + .put("metadata-file", baseLocation); + } + String metadataLocation = writeMetadata(metadata, base == null ? 0 : metadataVersion(baseLocation) + 1); + try { + if (existing == null) { + glue.createTable(database.getName(), icebergTable(name, metadata, metadataLocation, null)); + } 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); + } + } 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); + throw e; + } + LOG.debugv("Committed Iceberg table {0}.{1} at {2}", database.getName(), name, metadataLocation); + ObjectNode result = mapper.createObjectNode(); + result.put("metadata-location", metadataLocation); + result.set("metadata", metadata); + return result; + } + + /** + * 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. + */ + void dropTable(String catalog, String namespace, String name) { + requireDefaultCatalog(catalog); + Database database = requireNamespace(namespace(namespace)); + requireIcebergTable(database.getName(), name); + glue.deleteTable(database.getName(), name); + } + + // ─── 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) { + throw IcebergRestException.badRequest("AWS Glue supports single-level namespaces only: " + segment); + } + 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 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 = new Table(); + table.setName(name); + table.setTableType("EXTERNAL_TABLE"); + Map parameters = new HashMap<>(); + if (existing != null) { + table.setDescription(existing.getDescription()); + table.setOwner(existing.getOwner()); + if (existing.getParameters() != null) { + parameters.putAll(existing.getParameters()); + } + } + parameters.put(PARAM_TABLE_TYPE, ICEBERG); + parameters.put(PARAM_METADATA_LOCATION, metadataLocation); + table.setParameters(parameters); + StorageDescriptor descriptor = new StorageDescriptor(); + descriptor.setLocation(metadata.path("location").asText()); + List columns = new ArrayList<>(); + for (JsonNode field : IcebergTableMetadata.currentSchema(metadata).path("fields")) { + Column column = new Column(field.path("name").asText(), IcebergTypes.hiveType(field.path("type"))); + if (field.hasNonNull("doc")) { + column.setComment(field.get("doc").asText()); + } + column.setParameters(Map.of( + "iceberg.field.id", field.path("id").asText(), + "iceberg.field.optional", String.valueOf(!field.path("required").asBoolean(false)), + "iceberg.field.current", "true")); + columns.add(column); + } + descriptor.setColumns(columns); + table.setStorageDescriptor(descriptor); + return table; + } + + private ObjectNode readMetadata(String metadataLocation) { + S3Location location = s3Location(metadataLocation); + try (InputStream stream = s3.openObjectStream(location.bucket(), location.key(), null)) { + return (ObjectNode) mapper.readTree(stream); + } catch (AwsException e) { + throw IcebergRestException.badRequest("Cannot read table metadata " + metadataLocation + ": " + + e.getMessage()); + } catch (IOException | ClassCastException e) { + throw IcebergRestException.badRequest("Cannot read table metadata " + metadataLocation + ": " + + e.getMessage()); + } + } + + /** Writes the metadata as the table's {@code version}-th metadata file and answers its location. */ + private String writeMetadata(ObjectNode metadata, int version) { + String fileName = String.format("%05d-%s.metadata.json", version, UUID.randomUUID()); + String metadataLocation = metadata.path("location").asText() + "/metadata/" + fileName; + S3Location location = s3Location(metadataLocation); + try { + s3.putObject(location.bucket(), location.key(), + mapper.writeValueAsString(metadata).getBytes(StandardCharsets.UTF_8), "application/json", null); + } catch (AwsException e) { + throw IcebergRestException.badRequest("Cannot write table metadata " + metadataLocation + ": " + + e.getMessage()); + } catch (IOException e) { + throw new IcebergRestException(500, "ServiceFailureException", "Cannot serialize table metadata: " + + e.getMessage()); + } + return metadataLocation; + } + + /** Removes a metadata file a failed commit wrote; a failure to is logged, since the commit's error matters more. */ + private void deleteMetadata(String metadataLocation) { + S3Location location = s3Location(metadataLocation); + try { + s3.deleteObject(location.bucket(), location.key()); + } catch (RuntimeException e) { + LOG.warnv("Could not remove metadata file {0} of a failed commit: {1}", metadataLocation, e.getMessage()); + } + } + + /** The version a metadata file's name starts with ({@code 00003-.metadata.json}); -1 for another name. */ + static int metadataVersion(String metadataLocation) { + String fileName = metadataLocation.substring(metadataLocation.lastIndexOf('/') + 1); + Matcher matcher = METADATA_VERSION.matcher(fileName); + return matcher.matches() ? Integer.parseInt(matcher.group(1)) : -1; + } + + private ArrayNode referencedSnapshots(ObjectNode metadata) { + List referenced = new ArrayList<>(); + metadata.path("refs").forEach(ref -> referenced.add(ref.path("snapshot-id").asLong())); + ArrayNode kept = mapper.createArrayNode(); + for (JsonNode snapshot : metadata.path("snapshots")) { + if (referenced.contains(snapshot.path("snapshot-id").asLong())) { + kept.add(snapshot); + } + } + return kept; + } + + private static S3Location s3Location(String location) { + Matcher matcher = S3_LOCATION.matcher(location == null ? "" : location); + if (!matcher.matches() || matcher.group(2).isEmpty()) { + throw IcebergRestException.badRequest("Not an S3 object location: " + location); + } + return new S3Location(matcher.group(1), matcher.group(2)); + } + + 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()); + }; + } + + private record S3Location(String bucket, String key) { + } +} diff --git a/src/main/java/io/floci/aws/services/glue/iceberg/GlueIcebergController.java b/src/main/java/io/floci/aws/services/glue/iceberg/GlueIcebergController.java new file mode 100644 index 0000000000..e81b6e1eca --- /dev/null +++ b/src/main/java/io/floci/aws/services/glue/iceberg/GlueIcebergController.java @@ -0,0 +1,118 @@ +package io.floci.aws.services.glue.iceberg; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import jakarta.ws.rs.Consumes; +import jakarta.ws.rs.DELETE; +import jakarta.ws.rs.GET; +import jakarta.ws.rs.HEAD; +import jakarta.ws.rs.POST; +import jakarta.ws.rs.Path; +import jakarta.ws.rs.PathParam; +import jakarta.ws.rs.Produces; +import jakarta.ws.rs.QueryParam; +import jakarta.ws.rs.core.MediaType; +import jakarta.ws.rs.core.Response; + +/** + * AWS Glue's Iceberg REST endpoint ({@code https://glue..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}. + */ +@Path(GlueIcebergRouteFilter.INTERNAL_PREFIX + GlueIcebergRouteFilter.ICEBERG_PATH + "/v1") +@ApplicationScoped +@Produces(MediaType.APPLICATION_JSON) +@Consumes(MediaType.APPLICATION_JSON) +public class GlueIcebergController { + + private final GlueIcebergCatalog catalog; + + @Inject + public GlueIcebergController(GlueIcebergCatalog catalog) { + this.catalog = catalog; + } + + @GET + @Path("/config") + public ObjectNode getConfig(@QueryParam("warehouse") String 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); + } + + @POST + @Path("/catalogs/{catalog}/namespaces") + public ObjectNode createNamespace(@PathParam("catalog") String catalogId, JsonNode 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); + } + + @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); + } + + @DELETE + @Path("/catalogs/{catalog}/namespaces/{namespace}") + public Response dropNamespace(@PathParam("catalog") String catalogId, @PathParam("namespace") String 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); + } + + @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); + } + + @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); + } + + @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); + return Response.noContent().build(); + } + + @POST + @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); + } + + @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); + return Response.noContent().build(); + } +} diff --git a/src/main/java/io/floci/aws/services/glue/iceberg/GlueIcebergRouteFilter.java b/src/main/java/io/floci/aws/services/glue/iceberg/GlueIcebergRouteFilter.java new file mode 100644 index 0000000000..e7200a6986 --- /dev/null +++ b/src/main/java/io/floci/aws/services/glue/iceberg/GlueIcebergRouteFilter.java @@ -0,0 +1,36 @@ +package io.floci.aws.services.glue.iceberg; + +import io.floci.aws.core.common.ResolvedServiceCatalog; +import io.floci.aws.core.common.SignedServiceRoute; +import jakarta.annotation.Priority; +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; + +/** + * 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. + */ +@Provider +@PreMatching +@Priority(5000) +public class GlueIcebergRouteFilter implements ContainerRequestFilter { + + static final String INTERNAL_PREFIX = "/_glueiceberg"; + static final String ICEBERG_PATH = "/iceberg"; + + private final SignedServiceRoute route; + + @Inject + public GlueIcebergRouteFilter(ResolvedServiceCatalog catalog) { + this.route = new SignedServiceRoute(catalog, "glue", INTERNAL_PREFIX, SignedServiceRoute.under(ICEBERG_PATH)); + } + + @Override + public void filter(ContainerRequestContext ctx) { + route.apply(ctx); + } +} diff --git a/src/main/java/io/floci/aws/services/glue/iceberg/IcebergRestException.java b/src/main/java/io/floci/aws/services/glue/iceberg/IcebergRestException.java new file mode 100644 index 0000000000..219ed24223 --- /dev/null +++ b/src/main/java/io/floci/aws/services/glue/iceberg/IcebergRestException.java @@ -0,0 +1,43 @@ +package io.floci.aws.services.glue.iceberg; + +/** + * An error the Iceberg REST catalog answers with its {@code ErrorModel} ({@code {"error": {"message", "type", + * "code"}}}), whose {@code type} an Iceberg client maps to its own exception: {@code NoSuchTableException}, + * {@code CommitFailedException} and so on. + */ +final class IcebergRestException extends RuntimeException { + + private final int code; + private final String type; + + IcebergRestException(int code, String type, String message) { + super(message); + this.code = code; + this.type = type; + } + + int code() { + return code; + } + + String type() { + return type; + } + + static IcebergRestException badRequest(String message) { + return new IcebergRestException(400, "BadRequestException", message); + } + + static IcebergRestException noSuchNamespace(String namespace) { + return new IcebergRestException(404, "NoSuchNamespaceException", "Namespace does not exist: " + namespace); + } + + static IcebergRestException noSuchTable(String namespace, String table) { + return new IcebergRestException(404, "NoSuchTableException", + "Table does not exist: " + namespace + "." + table); + } + + static IcebergRestException alreadyExists(String message) { + return new IcebergRestException(409, "AlreadyExistsException", message); + } +} diff --git a/src/main/java/io/floci/aws/services/glue/iceberg/IcebergRestExceptionMapper.java b/src/main/java/io/floci/aws/services/glue/iceberg/IcebergRestExceptionMapper.java new file mode 100644 index 0000000000..44f434939f --- /dev/null +++ b/src/main/java/io/floci/aws/services/glue/iceberg/IcebergRestExceptionMapper.java @@ -0,0 +1,26 @@ +package io.floci.aws.services.glue.iceberg; + +import jakarta.ws.rs.core.MediaType; +import jakarta.ws.rs.core.Response; +import jakarta.ws.rs.ext.ExceptionMapper; +import jakarta.ws.rs.ext.Provider; + +import java.util.LinkedHashMap; +import java.util.Map; + +/** Answers an Iceberg REST catalog error with the specification's {@code ErrorModel}, not the AWS JSON envelope. */ +@Provider +public final class IcebergRestExceptionMapper implements ExceptionMapper { + + @Override + public Response toResponse(IcebergRestException exception) { + Map error = new LinkedHashMap<>(); + error.put("message", exception.getMessage()); + error.put("type", exception.type()); + error.put("code", exception.code()); + return Response.status(exception.code()) + .type(MediaType.APPLICATION_JSON) + .entity(Map.of("error", error)) + .build(); + } +} diff --git a/src/main/java/io/floci/aws/services/glue/iceberg/IcebergTableMetadata.java b/src/main/java/io/floci/aws/services/glue/iceberg/IcebergTableMetadata.java new file mode 100644 index 0000000000..64bda2e224 --- /dev/null +++ b/src/main/java/io/floci/aws/services/glue/iceberg/IcebergTableMetadata.java @@ -0,0 +1,430 @@ +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 java.util.ArrayList; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; + +/** + * An Iceberg table's metadata as the REST catalog keeps it: the JSON of the table metadata file, changed only by the + * requirements and updates a {@code CommitTableRequest} carries, as the Apache Iceberg REST catalog specification + * defines them. The writer (DuckDB, Spark) writes the data files, manifests and manifest lists itself; the catalog + * checks what the commit assumes and records what it adds, so no Iceberg library is needed. + */ +final class IcebergTableMetadata { + + static final int DEFAULT_FORMAT_VERSION = 2; + /** The last partition field id of a table with no partition fields yet, as Iceberg starts it. */ + private static final int NO_PARTITION_FIELDS = 999; + + private static final JsonNodeFactory JSON = JsonNodeFactory.instance; + + private IcebergTableMetadata() { + } + + /** + * The metadata a table starts with before a staged create's updates apply: nothing but the format version and + * the empty lists and maps every later update fills. + */ + static ObjectNode empty(long nowMillis) { + ObjectNode metadata = JSON.objectNode(); + metadata.put("format-version", DEFAULT_FORMAT_VERSION); + metadata.put("table-uuid", UUID.randomUUID().toString()); + metadata.put("last-sequence-number", 0); + metadata.put("last-updated-ms", nowMillis); + metadata.put("last-column-id", 0); + metadata.put("current-schema-id", -1); + metadata.set("schemas", JSON.arrayNode()); + metadata.put("default-spec-id", -1); + metadata.set("partition-specs", JSON.arrayNode()); + metadata.put("last-partition-id", NO_PARTITION_FIELDS); + metadata.put("default-sort-order-id", -1); + metadata.set("sort-orders", JSON.arrayNode()); + metadata.set("properties", JSON.objectNode()); + metadata.set("refs", JSON.objectNode()); + metadata.set("snapshots", JSON.arrayNode()); + metadata.set("snapshot-log", JSON.arrayNode()); + metadata.set("metadata-log", JSON.arrayNode()); + return metadata; + } + + /** + * The metadata a {@code CreateTableRequest} describes, as the updates a client would send for it: its schema, + * partition spec, sort order, location and properties, ids assigned as given. + */ + static ObjectNode forCreate(JsonNode request, String location, long nowMillis) { + ObjectNode metadata = empty(nowMillis); + JsonNode properties = request.path("properties"); + int formatVersion = properties.path("format-version").asInt(DEFAULT_FORMAT_VERSION); + ArrayNode updates = JSON.arrayNode(); + updates.addObject().put("action", "upgrade-format-version").put("format-version", formatVersion); + ObjectNode addSchema = updates.addObject().put("action", "add-schema"); + addSchema.set("schema", request.path("schema")); + updates.addObject().put("action", "set-current-schema").put("schema-id", -1); + ObjectNode spec = request.hasNonNull("partition-spec") ? ((ObjectNode) request.get("partition-spec")).deepCopy() + : JSON.objectNode().put("spec-id", 0).set("fields", JSON.arrayNode()); + spec.remove("type"); + updates.addObject().put("action", "add-spec").set("spec", spec); + updates.addObject().put("action", "set-default-spec").put("spec-id", -1); + JsonNode order = request.hasNonNull("write-order") ? request.get("write-order") + : JSON.objectNode().put("order-id", 0).set("fields", JSON.arrayNode()); + updates.addObject().put("action", "add-sort-order").set("sort-order", order); + updates.addObject().put("action", "set-default-sort-order").put("sort-order-id", -1); + updates.addObject().put("action", "set-location").put("location", location); + if (properties.isObject() && !properties.isEmpty()) { + updates.addObject().put("action", "set-properties").set("updates", properties); + } + apply(metadata, updates, nowMillis); + return metadata; + } + + /** + * Checks a commit's requirements against the table's current metadata, {@code null} for a table that does not + * exist yet. + * + * @throws IcebergRestException a {@code CommitFailedException} naming the first requirement that does not hold + */ + static void check(JsonNode metadata, JsonNode requirements) { + for (JsonNode requirement : requirements) { + String type = requirement.path("type").asText(); + if ("assert-create".equals(type)) { + if (metadata != null) { + throw commitFailed("Requirement failed: table already exists"); + } + continue; + } + if (metadata == null) { + throw commitFailed("Requirement failed: table does not exist (" + type + ")"); + } + switch (type) { + case "assert-table-uuid" -> requireEqual(type, metadata.path("table-uuid").asText(), + requirement.path("uuid").asText()); + case "assert-ref-snapshot-id" -> { + JsonNode ref = metadata.path("refs").path(requirement.path("ref").asText()); + JsonNode expected = requirement.path("snapshot-id"); + if (expected.isNull() || expected.isMissingNode()) { + if (!ref.isMissingNode()) { + throw commitFailed("Requirement failed: ref " + requirement.path("ref").asText() + + " was created concurrently"); + } + } else if (ref.isMissingNode() || ref.path("snapshot-id").asLong() != expected.asLong()) { + throw commitFailed("Requirement failed: ref " + requirement.path("ref").asText() + + " has changed: expected id " + expected.asLong() + " != " + + (ref.isMissingNode() ? "null" : ref.path("snapshot-id").asLong())); + } + } + case "assert-last-assigned-field-id" -> requireEqual(type, metadata.path("last-column-id").asLong(), + requirement.path("last-assigned-field-id").asLong()); + case "assert-current-schema-id" -> requireEqual(type, metadata.path("current-schema-id").asLong(), + requirement.path("current-schema-id").asLong()); + case "assert-last-assigned-partition-id" -> requireEqual(type, + metadata.path("last-partition-id").asLong(), + requirement.path("last-assigned-partition-id").asLong()); + case "assert-default-spec-id" -> requireEqual(type, metadata.path("default-spec-id").asLong(), + requirement.path("default-spec-id").asLong()); + case "assert-default-sort-order-id" -> requireEqual(type, + metadata.path("default-sort-order-id").asLong(), + requirement.path("default-sort-order-id").asLong()); + default -> throw IcebergRestException.badRequest("Unsupported requirement: " + type); + } + } + } + + /** + * Applies a commit's updates to {@code metadata} in order, as the specification defines each action, and stamps + * {@code last-updated-ms}. + * + * @throws IcebergRestException a {@code BadRequestException} for an action this catalog does not apply + */ + static void apply(ObjectNode metadata, JsonNode updates, long nowMillis) { + // An id of -1 in set-current-schema, set-default-spec and set-default-sort-order names the last one added. + int lastAddedSchema = -1; + int lastAddedSpec = -1; + int lastAddedOrder = -1; + for (JsonNode update : updates) { + String action = update.path("action").asText(); + switch (action) { + case "assign-uuid" -> metadata.put("table-uuid", update.path("uuid").asText()); + case "upgrade-format-version" -> { + int version = update.path("format-version").asInt(); + if (version < metadata.path("format-version").asInt(DEFAULT_FORMAT_VERSION) + && !metadata.path("schemas").isEmpty()) { + throw IcebergRestException.badRequest("Cannot downgrade format version to " + version); + } + metadata.put("format-version", version); + if (version >= 3 && !metadata.has("next-row-id")) { + metadata.put("next-row-id", 0); + } + } + case "add-schema" -> { + ObjectNode schema = ((ObjectNode) update.path("schema")).deepCopy(); + lastAddedSchema = reuseOrAdd(metadata.withArray("schemas"), "schema-id", schema); + long lastColumnId = update.has("last-column-id") ? update.path("last-column-id").asLong() + : Math.max(metadata.path("last-column-id").asLong(), maxFieldId(schema)); + metadata.put("last-column-id", Math.max(metadata.path("last-column-id").asLong(), lastColumnId)); + } + case "set-current-schema" -> metadata.put("current-schema-id", + existing(metadata.path("schemas"), "schema-id", update.path("schema-id").asInt(), + lastAddedSchema, "schema")); + case "add-spec" -> { + ObjectNode spec = ((ObjectNode) update.path("spec")).deepCopy(); + spec.remove("type"); + lastAddedSpec = reuseOrAdd(metadata.withArray("partition-specs"), "spec-id", spec); + long maxField = NO_PARTITION_FIELDS; + for (JsonNode field : spec.path("fields")) { + maxField = Math.max(maxField, field.path("field-id").asLong()); + } + metadata.put("last-partition-id", Math.max(metadata.path("last-partition-id").asLong(), maxField)); + } + case "set-default-spec" -> metadata.put("default-spec-id", + existing(metadata.path("partition-specs"), "spec-id", update.path("spec-id").asInt(), + lastAddedSpec, "partition spec")); + case "add-sort-order" -> { + ObjectNode order = ((ObjectNode) update.path("sort-order")).deepCopy(); + lastAddedOrder = reuseOrAdd(metadata.withArray("sort-orders"), "order-id", order); + } + case "set-default-sort-order" -> metadata.put("default-sort-order-id", + existing(metadata.path("sort-orders"), "order-id", update.path("sort-order-id").asInt(), + lastAddedOrder, "sort order")); + case "add-snapshot" -> addSnapshot(metadata, (ObjectNode) update.path("snapshot")); + case "set-snapshot-ref" -> setRef(metadata, update, nowMillis); + case "remove-snapshot-ref" -> removeRef(metadata, update.path("ref-name").asText()); + case "remove-snapshots" -> removeSnapshots(metadata, update.path("snapshot-ids")); + case "set-location" -> metadata.put("location", update.path("location").asText()); + case "set-properties" -> { + ObjectNode properties = metadata.withObject("properties"); + Iterator> fields = update.path("updates").fields(); + while (fields.hasNext()) { + Map.Entry entry = fields.next(); + properties.put(entry.getKey(), entry.getValue().asText()); + } + } + case "remove-properties" -> { + ObjectNode properties = metadata.withObject("properties"); + for (JsonNode key : update.path("removals")) { + properties.remove(key.asText()); + } + } + case "set-statistics" -> replaceById(metadata.withArray("statistics"), "snapshot-id", + update.path("statistics").deepCopy()); + case "remove-statistics" -> removeById(metadata.withArray("statistics"), "snapshot-id", + update.path("snapshot-id").asLong()); + case "set-partition-statistics" -> replaceById(metadata.withArray("partition-statistics"), + "snapshot-id", update.path("partition-statistics").deepCopy()); + case "remove-partition-statistics" -> removeById(metadata.withArray("partition-statistics"), + "snapshot-id", update.path("snapshot-id").asLong()); + default -> throw IcebergRestException.badRequest("Unsupported update action: " + action); + } + } + metadata.put("last-updated-ms", nowMillis); + } + + /** The schema {@code current-schema-id} names, or an empty one for a table with none. */ + static JsonNode currentSchema(JsonNode metadata) { + int current = metadata.path("current-schema-id").asInt(); + for (JsonNode schema : metadata.path("schemas")) { + if (schema.path("schema-id").asInt() == current) { + return schema; + } + } + return JSON.objectNode().put("type", "struct").set("fields", JSON.arrayNode()); + } + + private static void addSnapshot(ObjectNode metadata, ObjectNode snapshot) { + long id = snapshot.path("snapshot-id").asLong(); + for (JsonNode existing : metadata.withArray("snapshots")) { + if (existing.path("snapshot-id").asLong() == id) { + throw IcebergRestException.badRequest("Snapshot already exists: " + id); + } + } + ObjectNode added = snapshot.deepCopy(); + int formatVersion = metadata.path("format-version").asInt(DEFAULT_FORMAT_VERSION); + if (formatVersion >= 2) { + long sequence = added.path("sequence-number").asLong(); + // As Iceberg checks it: a snapshot with a parent must come after every sequence number the table used, + // whether or not the snapshots that used them were expired since. + if (sequence <= metadata.path("last-sequence-number").asLong() && added.hasNonNull("parent-snapshot-id")) { + throw IcebergRestException.badRequest("Cannot add snapshot with sequence number " + sequence + + " older than last sequence number " + metadata.path("last-sequence-number").asLong()); + } + metadata.put("last-sequence-number", Math.max(sequence, metadata.path("last-sequence-number").asLong())); + } + if (formatVersion >= 3 && added.has("added-rows")) { + long next = metadata.path("next-row-id").asLong(); + if (!added.has("first-row-id")) { + added.put("first-row-id", next); + } + metadata.put("next-row-id", added.path("first-row-id").asLong() + added.path("added-rows").asLong()); + } + metadata.withArray("snapshots").add(added); + } + + private static void setRef(ObjectNode metadata, JsonNode update, long nowMillis) { + String name = update.path("ref-name").asText(); + long snapshotId = update.path("snapshot-id").asLong(); + JsonNode snapshot = null; + for (JsonNode existing : metadata.path("snapshots")) { + if (existing.path("snapshot-id").asLong() == snapshotId) { + snapshot = existing; + } + } + if (snapshot == null) { + throw IcebergRestException.badRequest("Cannot set " + name + " to unknown snapshot: " + snapshotId); + } + ObjectNode ref = JSON.objectNode(); + ref.put("snapshot-id", snapshotId); + ref.put("type", update.path("type").asText("branch")); + for (String retention : new String[] {"max-ref-age-ms", "max-snapshot-age-ms", "min-snapshots-to-keep"}) { + if (update.hasNonNull(retention)) { + ref.set(retention, update.get(retention)); + } + } + metadata.withObject("refs").set(name, ref); + if ("main".equals(name)) { + metadata.put("current-snapshot-id", snapshotId); + metadata.withArray("snapshot-log").addObject() + .put("timestamp-ms", snapshot.path("timestamp-ms").asLong(nowMillis)) + .put("snapshot-id", snapshotId); + } + } + + private static void removeSnapshots(ObjectNode metadata, JsonNode ids) { + Set removed = new HashSet<>(); + for (JsonNode id : ids) { + removed.add(id.asLong()); + } + ArrayNode kept = JSON.arrayNode(); + for (JsonNode snapshot : metadata.withArray("snapshots")) { + if (!removed.contains(snapshot.path("snapshot-id").asLong())) { + kept.add(snapshot); + } + } + metadata.set("snapshots", kept); + // A ref to a removed snapshot goes with it, as Iceberg removes it, and main's takes the current snapshot. + Iterator> refs = metadata.withObject("refs").fields(); + List dangling = new ArrayList<>(); + while (refs.hasNext()) { + Map.Entry ref = refs.next(); + if (removed.contains(ref.getValue().path("snapshot-id").asLong())) { + dangling.add(ref.getKey()); + } + } + dangling.forEach(name -> removeRef(metadata, name)); + ArrayNode log = JSON.arrayNode(); + for (JsonNode entry : metadata.withArray("snapshot-log")) { + if (!removed.contains(entry.path("snapshot-id").asLong())) { + log.add(entry); + } + } + metadata.set("snapshot-log", log); + } + + /** + * Adds a schema, partition spec or sort order as Iceberg's catalog does: an identical one already there is + * reused, anything else takes the next free id, so an id already in the table never comes to mean something + * else. Answers the id it has. + */ + private static int reuseOrAdd(ArrayNode array, String idField, ObjectNode element) { + for (JsonNode existing : array) { + ObjectNode withoutId = ((ObjectNode) existing).deepCopy(); + withoutId.remove(idField); + ObjectNode candidate = element.deepCopy(); + candidate.remove(idField); + if (withoutId.equals(candidate)) { + return existing.path(idField).asInt(); + } + } + int id = nextId(array, idField); + element.put(idField, id); + array.add(element); + return id; + } + + /** The id an update names, -1 being the one this commit last added, refused when the table has none such. */ + private static int existing(JsonNode array, String idField, int id, int lastAdded, String what) { + int resolved = id == -1 ? lastAdded : id; + if (resolved == -1) { + throw IcebergRestException.badRequest("Cannot set the last added " + what + ": none was added"); + } + for (JsonNode element : array) { + if (element.path(idField).asInt() == resolved) { + return resolved; + } + } + throw IcebergRestException.badRequest("Cannot set an unknown " + what + ": " + resolved); + } + + /** Removes a ref; removing main leaves the table with no current snapshot. */ + private static void removeRef(ObjectNode metadata, String name) { + metadata.withObject("refs").remove(name); + if ("main".equals(name)) { + metadata.put("current-snapshot-id", -1); + } + } + + private static void replaceById(ArrayNode array, String idField, JsonNode element) { + for (int i = 0; i < array.size(); i++) { + if (array.get(i).path(idField).asLong() == element.path(idField).asLong()) { + array.set(i, element); + return; + } + } + array.add(element); + } + + private static void removeById(ArrayNode array, String idField, long id) { + for (int i = array.size() - 1; i >= 0; i--) { + if (array.get(i).path(idField).asLong() == id) { + array.remove(i); + } + } + } + + private static int nextId(ArrayNode array, String idField) { + int next = 0; + for (JsonNode element : array) { + next = Math.max(next, element.path(idField).asInt() + 1); + } + return next; + } + + private static long maxFieldId(JsonNode type) { + long max = 0; + if (type.isObject()) { + if (type.has("id")) { + max = Math.max(max, type.path("id").asLong()); + } + for (String key : new String[] {"element-id", "key-id", "value-id"}) { + if (type.has(key)) { + max = Math.max(max, type.path(key).asLong()); + } + } + for (JsonNode child : type) { + max = Math.max(max, maxFieldId(child)); + } + } else if (type.isArray()) { + for (JsonNode child : type) { + max = Math.max(max, maxFieldId(child)); + } + } + return max; + } + + private static void requireEqual(String type, Object actual, Object expected) { + if (!actual.equals(expected)) { + throw commitFailed("Requirement failed: " + type + " has changed: expected " + expected + " != " + actual); + } + } + + private static IcebergRestException commitFailed(String message) { + return new IcebergRestException(409, "CommitFailedException", message); + } +} diff --git a/src/main/java/io/floci/aws/services/glue/iceberg/IcebergTypes.java b/src/main/java/io/floci/aws/services/glue/iceberg/IcebergTypes.java new file mode 100644 index 0000000000..83a59d6c01 --- /dev/null +++ b/src/main/java/io/floci/aws/services/glue/iceberg/IcebergTypes.java @@ -0,0 +1,54 @@ +package io.floci.aws.services.glue.iceberg; + +import com.fasterxml.jackson.databind.JsonNode; + +import java.util.StringJoiner; + +/** + * The Hive type a Glue column holds for an Iceberg field, as AWS Glue writes an Iceberg table's columns: a primitive + * as its Hive name ({@code long} is {@code bigint}), a nested type spelled out ({@code struct}, + * {@code array}, {@code map}). + */ +final class IcebergTypes { + + private IcebergTypes() { + } + + static String hiveType(JsonNode type) { + if (type.isTextual()) { + return primitive(type.asText()); + } + return switch (type.path("type").asText()) { + case "struct" -> { + StringJoiner fields = new StringJoiner(",", "struct<", ">"); + for (JsonNode field : type.path("fields")) { + fields.add(field.path("name").asText() + ":" + hiveType(field.path("type"))); + } + yield fields.toString(); + } + case "list" -> "array<" + hiveType(type.path("element")) + ">"; + case "map" -> "map<" + hiveType(type.path("key")) + "," + hiveType(type.path("value")) + ">"; + default -> "string"; + }; + } + + private static String primitive(String type) { + if (type.startsWith("decimal")) { + return type.replace(" ", ""); + } + if (type.startsWith("fixed")) { + return "binary"; + } + return switch (type) { + case "boolean" -> "boolean"; + case "int" -> "int"; + case "long" -> "bigint"; + case "float" -> "float"; + case "double" -> "double"; + case "date" -> "date"; + case "timestamp", "timestamptz", "timestamp_ns", "timestamptz_ns" -> "timestamp"; + case "binary" -> "binary"; + default -> "string"; + }; + } +} diff --git a/src/test/java/io/floci/aws/services/glue/iceberg/GlueIcebergCatalogTest.java b/src/test/java/io/floci/aws/services/glue/iceberg/GlueIcebergCatalogTest.java new file mode 100644 index 0000000000..3ac50a57f6 --- /dev/null +++ b/src/test/java/io/floci/aws/services/glue/iceberg/GlueIcebergCatalogTest.java @@ -0,0 +1,167 @@ +package io.floci.aws.services.glue.iceberg; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import io.floci.aws.config.EmulatorConfig; +import io.floci.aws.core.common.AwsException; +import io.floci.aws.core.common.RegionResolver; +import io.floci.aws.core.common.RequestContext; +import io.floci.aws.services.glue.GlueService; +import io.floci.aws.services.glue.model.Database; +import io.floci.aws.services.glue.model.Table; +import io.floci.aws.services.s3.S3Service; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Answers; +import org.mockito.ArgumentCaptor; +import org.mockito.Mockito; + +import java.io.ByteArrayInputStream; +import java.nio.charset.StandardCharsets; +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.HashMap; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.isNull; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +/** The catalog's commit paths when Glue refuses the write, and who it answers under IAM enforcement. */ +class GlueIcebergCatalogTest { + + private static final String CREATE_COMMIT = """ + {"requirements":[{"type":"assert-create"}],"updates":[ + {"action":"add-schema","schema":{"type":"struct","schema-id":0,"fields":[ + {"id":1,"name":"id","required":false,"type":"long"}]}}, + {"action":"set-current-schema","schema-id":-1}, + {"action":"add-spec","spec":{"spec-id":0,"fields":[]}},{"action":"set-default-spec","spec-id":-1}, + {"action":"add-sort-order","sort-order":{"order-id":0,"fields":[]}}, + {"action":"set-default-sort-order","sort-order-id":-1}, + {"action":"set-location","location":"s3://lake-bucket/lake/events"}]} + """; + + private final ObjectMapper mapper = new ObjectMapper(); + private GlueService glue; + private S3Service s3; + private EmulatorConfig config; + private RequestContext requestContext; + private GlueIcebergCatalog catalog; + + @BeforeEach + void setUp() { + glue = Mockito.mock(GlueService.class); + s3 = Mockito.mock(S3Service.class); + config = Mockito.mock(EmulatorConfig.class, Answers.RETURNS_DEEP_STUBS); + requestContext = Mockito.mock(RequestContext.class); + catalog = new GlueIcebergCatalog(glue, s3, new RegionResolver("us-east-1", "000000000000"), mapper, config, + requestContext, Clock.fixed(Instant.ofEpochMilli(10_000L), ZoneOffset.UTC)); + Database database = new Database("lake"); + database.setLocationUri("s3://lake-bucket/lake"); + when(glue.getDatabase("lake")).thenReturn(database); + } + + private void tableMissing() { + when(glue.getTable("lake", "events")).thenThrow(new AwsException("EntityNotFoundException", + "Table not found: lake.events", 400)); + } + + private void tableExists() { + ObjectNode metadata = IcebergTableMetadata.empty(1_000L); + try { + IcebergTableMetadata.apply(metadata, mapper.readTree(CREATE_COMMIT).path("updates"), 2_000L); + } catch (Exception e) { + throw new IllegalStateException(e); + } + String location = "s3://lake-bucket/lake/events/metadata/00000-a.metadata.json"; + Table table = new Table(); + table.setName("events"); + table.setVersionId("1"); + Map parameters = new HashMap<>(); + parameters.put("table_type", "ICEBERG"); + parameters.put("metadata_location", location); + table.setParameters(parameters); + when(glue.getTable("lake", "events")).thenReturn(table); + when(s3.openObjectStream("lake-bucket", "lake/events/metadata/00000-a.metadata.json", null)) + .thenAnswer(invocation -> new ByteArrayInputStream( + mapper.writeValueAsString(metadata).getBytes(StandardCharsets.UTF_8))); + } + + private String writtenMetadataKey() { + ArgumentCaptor key = ArgumentCaptor.forClass(String.class); + verify(s3).putObject(eq("lake-bucket"), key.capture(), any(), eq("application/json"), isNull()); + return key.getValue(); + } + + @Test + void aCommitGlueRefusesAsConcurrentIsACommitFailureAndItsMetadataFileIsRemoved() throws Exception { + tableExists(); + doThrow(new AwsException("ConcurrentModificationException", "concurrent", 400)) + .when(glue).updateTable(eq("lake"), any(), eq("1"), eq(false)); + + IcebergRestException e = assertThrows(IcebergRestException.class, () -> catalog.commitTable(":", "lake", + "events", mapper.readTree(IcebergCommits.snapshotCommit(7, null, 1)))); + + assertEquals("CommitFailedException", e.type()); + String written = writtenMetadataKey(); + verify(s3).deleteObject("lake-bucket", written); + } + + @Test + void aStagedCreateIsAConflictOnlyWhenTheTableAppearedMeanwhile() throws Exception { + tableMissing(); + doThrow(new AwsException("AlreadyExistsException", "Table already exists", 400)) + .when(glue).createTable(eq("lake"), any()); + + IcebergRestException raced = assertThrows(IcebergRestException.class, + () -> catalog.commitTable(":", "lake", "events", mapper.readTree(CREATE_COMMIT))); + + assertEquals("CommitFailedException", raced.type()); + String written = writtenMetadataKey(); + verify(s3).deleteObject("lake-bucket", written); + } + + @Test + void aStagedCreateIntoANamespaceThatWentAwayAnswersThatInsteadOfAConflict() throws Exception { + tableMissing(); + doThrow(new AwsException("EntityNotFoundException", "Database not found: lake", 400)) + .when(glue).createTable(eq("lake"), any()); + + IcebergRestException gone = assertThrows(IcebergRestException.class, + () -> catalog.commitTable(":", "lake", "events", mapper.readTree(CREATE_COMMIT))); + + assertEquals("NoSuchNamespaceException", gone.type()); + String written = writtenMetadataKey(); + verify(s3).deleteObject("lake-bucket", written); + } + + @Test + void underIamEnforcementOnlyRootCredentialsAndFlocisOwnCallersReachTheCatalog() { + when(config.services().iam().enforcementEnabled()).thenReturn(true); + when(requestContext.getAccountId()).thenReturn("000000000000"); + + when(requestContext.getAccessKeyId()).thenReturn("AKIAEXAMPLEUSER0001"); + IcebergRestException refused = assertThrows(IcebergRestException.class, () -> catalog.config(null)); + assertEquals(403, refused.code()); + assertEquals("ForbiddenException", refused.type()); + + for (String rootOrInternal : new String[] {"test", "000000000000", null}) { + when(requestContext.getAccessKeyId()).thenReturn(rootOrInternal); + assertEquals("catalogs/:", catalog.config(null).path("overrides").path("prefix").asText()); + } + } + + @Test + void withoutEnforcementAnyCallerReachesTheCatalog() { + when(config.services().iam().enforcementEnabled()).thenReturn(false); + when(requestContext.getAccessKeyId()).thenReturn("AKIAEXAMPLEUSER0001"); + + assertEquals("catalogs/:", catalog.config(null).path("overrides").path("prefix").asText()); + } +} diff --git a/src/test/java/io/floci/aws/services/glue/iceberg/GlueIcebergIamIntegrationTest.java b/src/test/java/io/floci/aws/services/glue/iceberg/GlueIcebergIamIntegrationTest.java new file mode 100644 index 0000000000..d276a62ef4 --- /dev/null +++ b/src/test/java/io/floci/aws/services/glue/iceberg/GlueIcebergIamIntegrationTest.java @@ -0,0 +1,48 @@ +package io.floci.aws.services.glue.iceberg; + +import io.floci.aws.testing.SignedIamEnforcementProfile; +import io.floci.aws.testing.SignedIamUsers; +import io.floci.aws.testutil.AwsRequestSigner; +import io.quarkus.test.common.http.TestHTTPResource; +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.TestProfile; +import io.restassured.response.Response; +import org.junit.jupiter.api.Test; + +import java.net.URI; +import java.util.Map; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; + +/** + * Under IAM enforcement, no rule maps the Glue Iceberg REST endpoint's routes to the Glue actions AWS checks for them + * yet, so the endpoint refuses an IAM principal, even one allowed every Glue action, rather than let it through + * unchecked; the account's root credentials still reach it. + */ +@QuarkusTest +@TestProfile(SignedIamEnforcementProfile.class) +class GlueIcebergIamIntegrationTest { + + @TestHTTPResource("/") + URI endpoint; + + @Test + void anIamPrincipalIsRefusedAndRootCredentialsAreAnswered() throws Exception { + String allowEverything = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\"," + + "\"Action\":\"glue:*\",\"Resource\":\"*\"}]}"; + try (SignedIamUsers.User user = SignedIamUsers.createUser(endpoint, "glue-iceberg-", "glue", allowEverything)) { + get(user.signer("glue"), "/iceberg/v1/config").then().statusCode(403) + .body("error.type", equalTo("ForbiddenException")); + get(user.signer("glue"), "/iceberg/v1/catalogs/:/namespaces").then().statusCode(403); + } + get(AwsRequestSigner.signedAs("test", "test", "glue"), "/iceberg/v1/config").then().statusCode(200) + .body("overrides.prefix", equalTo("catalogs/:")); + } + + private Response get(AwsRequestSigner signer, String path) throws Exception { + URI uri = endpoint.resolve(path); + return given().urlEncodingEnabled(false).headers(signer.headersFor("GET", uri, Map.of(), new byte[0])) + .request("GET", uri); + } +} diff --git a/src/test/java/io/floci/aws/services/glue/iceberg/GlueIcebergRestIntegrationTest.java b/src/test/java/io/floci/aws/services/glue/iceberg/GlueIcebergRestIntegrationTest.java new file mode 100644 index 0000000000..e5d5a2b804 --- /dev/null +++ b/src/test/java/io/floci/aws/services/glue/iceberg/GlueIcebergRestIntegrationTest.java @@ -0,0 +1,221 @@ +package io.floci.aws.services.glue.iceberg; + +import io.floci.aws.services.glue.GlueService; +import io.floci.aws.services.glue.model.Table; +import io.floci.aws.services.s3.S3Service; +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; +import org.junit.jupiter.api.Test; + +import java.net.URI; +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; +import static org.hamcrest.Matchers.hasItem; +import static org.hamcrest.Matchers.not; +import static org.hamcrest.Matchers.nullValue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * AWS Glue's Iceberg REST endpoint as a REST catalog client (Spark, PyIceberg) uses it, signed for {@code glue}: a + * staged create committed with {@code assert-create}, as DuckDB and Spark create tables, then snapshot commits that + * move the Glue table's {@code metadata_location}, one based on a stale snapshot refused. + */ +@QuarkusTest +class GlueIcebergRestIntegrationTest { + + private static final String PREFIX = "/iceberg/v1/catalogs/000000000000"; + 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 + S3Service s3Service; + + @Inject + GlueService glueService; + + private String bucket; + private String namespace; + + @BeforeEach + void createBucket() { + long suffix = System.nanoTime(); + bucket = "iceberg-rest-" + suffix; + namespace = "lake_" + suffix; + s3Service.createBucket(bucket, "us-east-1"); + } + + @AfterEach + void dropNamespace() { + send(glue, "DELETE", PREFIX + "/namespaces/" + namespace + "/tables/events", null); + send(glue, "DELETE", PREFIX + "/namespaces/" + namespace, null); + } + + private String tablePath() { + return PREFIX + "/namespaces/" + namespace + "/tables/events"; + } + + private void createNamespace() { + send(glue, "POST", PREFIX + "/namespaces", "{\"namespace\":[\"" + namespace + "\"],\"properties\":" + + "{\"location\":\"s3://" + bucket + "/lake\",\"owner\":\"data\"}}").then().statusCode(200) + .body("namespace[0]", equalTo(namespace)); + } + + private String createTable() { + send(glue, "POST", PREFIX + "/namespaces/" + namespace + "/tables", "{\"stage-create\":true,\"name\":\"events\"," + + "\"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) + .body("metadata-location", endsWith(".metadata.json")) + .extract().path("metadata-location"); + } + + private static String snapshotCommit(long snapshotId, Long parent) { + return IcebergCommits.snapshotCommit(snapshotId, parent, snapshotId); + } + + @Test + void configNamesTheCatalogsPrefixAndTheRoutesItServes() { + send(glue, "GET", "/iceberg/v1/config?warehouse=000000000000", null).then().statusCode(200) + .body("overrides.prefix", equalTo("catalogs/000000000000")) + .body("endpoints", hasItem("POST /v1/{prefix}/namespaces/{namespace}/tables/{table}")); + send(glue, "GET", "/iceberg/v1/config", null).then().statusCode(200) + .body("overrides.prefix", equalTo("catalogs/:")); + send(glue, "GET", "/iceberg/v1/config?warehouse=111122223333", null).then().statusCode(400) + .body("error.type", equalTo("BadRequestException")); + } + + @Test + void aStagedCreateIsCommittedAsAGlueIcebergTableWhoseMetadataLocationEachCommitMoves() throws Exception { + createNamespace(); + send(glue, "GET", PREFIX + "/namespaces/" + namespace, null).then().statusCode(200) + .body("properties.location", equalTo("s3://" + bucket + "/lake")) + .body("properties.owner", equalTo("data")); + + String created = createTable(); + Table table = glueService.getTable(namespace, "events"); + assertEquals("ICEBERG", table.getParameters().get("table_type")); + assertEquals(created, table.getParameters().get("metadata_location")); + assertEquals(List.of("id:bigint", "name:string"), table.getStorageDescriptor().getColumns().stream() + .map(column -> column.getName() + ":" + column.getType()).toList()); + assertTrue(created.contains("/lake/events/metadata/00000-"), created); + String stored = new String(s3Service.openObjectStream(bucket, + created.substring(("s3://" + bucket + "/").length()), null).readAllBytes(), StandardCharsets.UTF_8); + assertTrue(stored.contains("11111111-2222-3333-4444-555555555555"), stored); + + String committed = send(glue, "POST", tablePath(), snapshotCommit(7, null)).then().statusCode(200) + .body("metadata.current-snapshot-id", equalTo(7)) + .body("metadata.metadata-log[0].metadata-file", equalTo(created)) + .extract().path("metadata-location"); + + assertTrue(committed.contains("/metadata/00001-"), committed); + Table updated = glueService.getTable(namespace, "events"); + assertEquals(committed, updated.getParameters().get("metadata_location")); + assertEquals(created, updated.getParameters().get("previous_metadata_location")); + send(glue, "GET", tablePath(), null).then().statusCode(200) + .body("metadata-location", equalTo(committed)) + .body("metadata.refs.main.snapshot-id", equalTo(7)); + send(glue, "HEAD", tablePath(), null).then().statusCode(204); + send(glue, "GET", PREFIX + "/namespaces/" + namespace + "/tables", null).then().statusCode(200) + .body("identifiers.name", hasItem("events")); + } + + @Test + void aCommitBasedOnAStaleSnapshotIsRefusedAndLeavesTheTableAsItWas() { + createNamespace(); + createTable(); + String first = send(glue, "POST", tablePath(), snapshotCommit(7, null)).then().statusCode(200) + .extract().path("metadata-location"); + + send(glue, "POST", tablePath(), snapshotCommit(8, null)).then().statusCode(409) + .body("error.type", equalTo("CommitFailedException")); + + assertEquals(first, glueService.getTable(namespace, "events").getParameters().get("metadata_location")); + send(glue, "POST", tablePath(), snapshotCommit(8, 7L)).then().statusCode(200) + .body("metadata.current-snapshot-id", equalTo(8)); + } + + @Test + void missingTablesAndNamespacesAnswerTheIcebergErrors() { + send(glue, "GET", PREFIX + "/namespaces/" + namespace + "/tables/events", null).then().statusCode(404) + .body("error.type", equalTo("NoSuchNamespaceException")); + createNamespace(); + send(glue, "GET", tablePath(), null).then().statusCode(404) + .body("error.type", equalTo("NoSuchTableException")); + send(glue, "POST", tablePath(), snapshotCommit(7, null)).then().statusCode(404) + .body("error.type", equalTo("NoSuchTableException")); + createTable(); + send(glue, "DELETE", PREFIX + "/namespaces/" + namespace, null).then().statusCode(409) + .body("error.type", equalTo("NamespaceNotEmptyException")); + send(glue, "DELETE", tablePath(), null).then().statusCode(204); + send(glue, "GET", tablePath(), null).then().statusCode(404); + } + + @Test + void namespacePropertiesAreUpdatedAndRemovedAsGlueDatabaseFields() { + createNamespace(); + + send(glue, "POST", PREFIX + "/namespaces/" + namespace + "/properties", + "{\"removals\":[\"owner\",\"missing-key\"],\"updates\":{\"comment\":\"raw events\",\"team\":\"x\"}}") + .then().statusCode(200) + .body("removed", equalTo(List.of("owner"))) + .body("missing", equalTo(List.of("missing-key"))) + .body("updated", hasItem("comment")); + + assertEquals("raw events", glueService.getDatabase(namespace).getDescription()); + assertEquals(Map.of("team", "x"), glueService.getDatabase(namespace).getParameters()); + } + + @Test + void onlyARequestSignedForGlueReachesTheEndpoint() { + AwsRequestSigner s3 = AwsRequestSigner.signedAs("test", "test", "s3"); + + send(s3, "GET", "/iceberg/v1/config", null).then().statusCode(not(equalTo(200))) + .body(not(containsString("overrides"))); + } + + 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); + } + } +} diff --git a/src/test/java/io/floci/aws/services/glue/iceberg/IcebergCommits.java b/src/test/java/io/floci/aws/services/glue/iceberg/IcebergCommits.java new file mode 100644 index 0000000000..5967511084 --- /dev/null +++ b/src/test/java/io/floci/aws/services/glue/iceberg/IcebergCommits.java @@ -0,0 +1,24 @@ +package io.floci.aws.services.glue.iceberg; + +/** The commit bodies the Iceberg catalog tests send, as an Iceberg writer builds them. */ +final class IcebergCommits { + + private IcebergCommits() { + } + + /** + * An append committing snapshot {@code snapshotId} to {@code main}, required to find {@code main} at + * {@code parentSnapshotId} (absent when null), which is also the new snapshot's parent. + */ + static String snapshotCommit(long snapshotId, Long parentSnapshotId, long sequenceNumber) { + String parent = parentSnapshotId == null ? "" : "\"parent-snapshot-id\":" + parentSnapshotId + ","; + return """ + {"requirements":[{"type":"assert-ref-snapshot-id","ref":"main","snapshot-id":%s}],"updates":[ + {"action":"add-snapshot","snapshot":{"snapshot-id":%d,%s"sequence-number":%d,"timestamp-ms":5000, + "manifest-list":"s3://lake-bucket/lake/events/metadata/snap-%d.avro", + "summary":{"operation":"append"},"schema-id":0}}, + {"action":"set-snapshot-ref","ref-name":"main","type":"branch","snapshot-id":%d}]} + """.formatted(parentSnapshotId == null ? "null" : parentSnapshotId, snapshotId, parent, sequenceNumber, + snapshotId, snapshotId); + } +} diff --git a/src/test/java/io/floci/aws/services/glue/iceberg/IcebergTableMetadataTest.java b/src/test/java/io/floci/aws/services/glue/iceberg/IcebergTableMetadataTest.java new file mode 100644 index 0000000000..a7303c5e65 --- /dev/null +++ b/src/test/java/io/floci/aws/services/glue/iceberg/IcebergTableMetadataTest.java @@ -0,0 +1,244 @@ +package io.floci.aws.services.glue.iceberg; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class IcebergTableMetadataTest { + + private static final ObjectMapper MAPPER = new ObjectMapper(); + + /** The commit DuckDB 1.5.4 sends after a staged create of {@code (id BIGINT, name VARCHAR)}. */ + private static final String DUCKDB_CREATE_COMMIT = """ + {"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":{"type":"struct","schema-id":0,"fields":[ + {"id":1,"name":"id","required":false,"type":"long"}, + {"id":2,"name":"name","required":false,"type":"string"}],"identifier-field-ids":[]}}, + {"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://lake-bucket/lake/events"}, + {"action":"set-properties","updates":{"format-version":"2"}}, + {"action":"set-current-schema","schema-id":0}], + "identifier":{"name":"events","namespace":["lake"]}} + """; + + private static JsonNode json(String text) throws Exception { + return MAPPER.readTree(text); + } + + private static ObjectNode created() throws Exception { + JsonNode commit = json(DUCKDB_CREATE_COMMIT); + IcebergTableMetadata.check(null, commit.path("requirements")); + ObjectNode metadata = IcebergTableMetadata.empty(1_000L); + IcebergTableMetadata.apply(metadata, commit.path("updates"), 2_000L); + return metadata; + } + + private static JsonNode snapshotCommit(long snapshotId, Long parentRefId, long sequence) throws Exception { + return json(IcebergCommits.snapshotCommit(snapshotId, parentRefId, sequence)); + } + + @Test + void duckdbsStagedCreateCommitBuildsTheTablesMetadata() throws Exception { + ObjectNode metadata = created(); + + assertEquals("11111111-2222-3333-4444-555555555555", metadata.path("table-uuid").asText()); + assertEquals(2, metadata.path("format-version").asInt()); + assertEquals(0, metadata.path("current-schema-id").asInt()); + assertEquals(2, metadata.path("last-column-id").asInt()); + assertEquals("long", IcebergTableMetadata.currentSchema(metadata).path("fields").get(0).path("type").asText()); + assertEquals(0, metadata.path("default-spec-id").asInt()); + assertEquals(999, metadata.path("last-partition-id").asInt()); + assertEquals(0, metadata.path("default-sort-order-id").asInt()); + assertEquals("s3://lake-bucket/lake/events", metadata.path("location").asText()); + assertEquals("2", metadata.path("properties").path("format-version").asText()); + assertEquals(2_000L, metadata.path("last-updated-ms").asLong()); + } + + @Test + void aSnapshotOnMainBecomesTheCurrentSnapshotAndIsLogged() throws Exception { + ObjectNode metadata = created(); + JsonNode commit = snapshotCommit(7L, null, 1); + + IcebergTableMetadata.check(metadata, commit.path("requirements")); + IcebergTableMetadata.apply(metadata, commit.path("updates"), 6_000L); + + assertEquals(7L, metadata.path("current-snapshot-id").asLong()); + assertEquals(1L, metadata.path("last-sequence-number").asLong()); + assertEquals(7L, metadata.path("refs").path("main").path("snapshot-id").asLong()); + assertEquals("branch", metadata.path("refs").path("main").path("type").asText()); + assertEquals(1, metadata.path("snapshots").size()); + assertEquals(5_000L, metadata.path("snapshot-log").get(0).path("timestamp-ms").asLong()); + } + + @Test + void aCommitBasedOnAStaleSnapshotOrAnExistingTableFails() throws Exception { + ObjectNode metadata = created(); + JsonNode first = snapshotCommit(7L, null, 1); + IcebergTableMetadata.apply(metadata, first.path("updates"), 6_000L); + + IcebergRestException concurrentAppend = assertThrows(IcebergRestException.class, + () -> IcebergTableMetadata.check(metadata, snapshotCommit(8L, null, 2).path("requirements"))); + IcebergRestException staleParent = assertThrows(IcebergRestException.class, + () -> IcebergTableMetadata.check(metadata, snapshotCommit(9L, 6L, 2).path("requirements"))); + IcebergRestException existing = assertThrows(IcebergRestException.class, + () -> IcebergTableMetadata.check(metadata, json(DUCKDB_CREATE_COMMIT).path("requirements"))); + + assertEquals("CommitFailedException", concurrentAppend.type()); + assertEquals(409, staleParent.code()); + assertEquals("CommitFailedException", existing.type()); + IcebergTableMetadata.check(metadata, snapshotCommit(8L, 7L, 2).path("requirements")); + } + + @Test + void propertiesSnapshotsAndRefsCanBeRemoved() throws Exception { + ObjectNode metadata = created(); + IcebergTableMetadata.apply(metadata, snapshotCommit(7L, null, 1).path("updates"), 6_000L); + + IcebergTableMetadata.apply(metadata, json(""" + [{"action":"set-properties","updates":{"write.format.default":"parquet"}}, + {"action":"remove-properties","removals":["format-version"]}, + {"action":"remove-snapshot-ref","ref-name":"main"}, + {"action":"remove-snapshots","snapshot-ids":[7]}] + """), 7_000L); + + assertEquals("parquet", metadata.path("properties").path("write.format.default").asText()); + assertTrue(metadata.path("properties").path("format-version").isMissingNode()); + assertTrue(metadata.path("refs").path("main").isMissingNode()); + assertEquals(0, metadata.path("snapshots").size()); + assertEquals(0, metadata.path("snapshot-log").size()); + } + + @Test + void removingMainOrItsSnapshotLeavesNoCurrentSnapshotAndNoDanglingRef() throws Exception { + ObjectNode metadata = created(); + IcebergTableMetadata.apply(metadata, snapshotCommit(7L, null, 1).path("updates"), 6_000L); + IcebergTableMetadata.apply(metadata, + json("[{\"action\":\"set-snapshot-ref\",\"ref-name\":\"audit\",\"type\":\"tag\",\"snapshot-id\":7}]"), + 6_500L); + + IcebergTableMetadata.apply(metadata, json("[{\"action\":\"remove-snapshots\",\"snapshot-ids\":[7]}]"), 7_000L); + + assertEquals(-1L, metadata.path("current-snapshot-id").asLong()); + assertTrue(metadata.path("refs").isEmpty(), metadata.path("refs").toString()); + ObjectNode other = created(); + IcebergTableMetadata.apply(other, snapshotCommit(7L, null, 1).path("updates"), 6_000L); + IcebergTableMetadata.apply(other, json("[{\"action\":\"remove-snapshot-ref\",\"ref-name\":\"main\"}]"), 7_000L); + assertEquals(-1L, other.path("current-snapshot-id").asLong()); + } + + @Test + void aSchemaSpecOrSortOrderIdTheTableDoesNotHaveIsRefused() throws Exception { + ObjectNode metadata = created(); + + for (String update : new String[] {"{\"action\":\"set-current-schema\",\"schema-id\":999}", + "{\"action\":\"set-current-schema\",\"schema-id\":-1}", + "{\"action\":\"set-default-spec\",\"spec-id\":5}", + "{\"action\":\"set-default-sort-order\",\"sort-order-id\":-1}"}) { + IcebergRestException e = assertThrows(IcebergRestException.class, + () -> IcebergTableMetadata.apply(metadata, json("[" + update + "]"), 8_000L), update); + assertEquals("BadRequestException", e.type(), update); + } + assertEquals(0, metadata.path("current-schema-id").asInt()); + } + + @Test + void anAddedSchemaReusesAnIdenticalOneAndNeverRewritesAnExistingId() throws Exception { + ObjectNode metadata = created(); + String changed = "[{\"action\":\"add-schema\",\"schema\":{\"type\":\"struct\",\"schema-id\":0,\"fields\":[" + + "{\"id\":1,\"name\":\"id\",\"required\":false,\"type\":\"long\"}," + + "{\"id\":2,\"name\":\"name\",\"required\":false,\"type\":\"string\"}," + + "{\"id\":3,\"name\":\"tag\",\"required\":false,\"type\":\"string\"}],\"identifier-field-ids\":[]}}," + + "{\"action\":\"set-current-schema\",\"schema-id\":-1}]"; + + IcebergTableMetadata.apply(metadata, json(changed), 8_000L); + IcebergTableMetadata.apply(metadata, json(changed), 9_000L); + + assertEquals(2, metadata.path("schemas").size()); + assertEquals(2, metadata.path("schemas").get(0).path("fields").size(), "schema 0 is left as it was"); + assertEquals(1, metadata.path("current-schema-id").asInt()); + assertEquals(3, metadata.path("last-column-id").asInt()); + } + + @Test + void aSnapshotAfterExpiryStillComesAfterEverySequenceNumberUsed() throws Exception { + ObjectNode metadata = created(); + IcebergTableMetadata.apply(metadata, snapshotCommit(7L, null, 1).path("updates"), 6_000L); + IcebergTableMetadata.apply(metadata, snapshotCommit(8L, 7L, 2).path("updates"), 6_100L); + IcebergTableMetadata.apply(metadata, json("[{\"action\":\"remove-snapshots\",\"snapshot-ids\":[7]}]"), 6_200L); + + IcebergRestException e = assertThrows(IcebergRestException.class, () -> IcebergTableMetadata.apply(metadata, + snapshotCommit(9L, 8L, 2).path("updates"), 6_300L)); + + assertEquals("BadRequestException", e.type()); + IcebergTableMetadata.apply(metadata, snapshotCommit(9L, 8L, 3).path("updates"), 6_400L); + assertEquals(3L, metadata.path("last-sequence-number").asLong()); + } + + @Test + void aVersionThreeSnapshotTakesTheNextRowIdsAndAdvancesThem() throws Exception { + ObjectNode metadata = created(); + IcebergTableMetadata.apply(metadata, json("[{\"action\":\"upgrade-format-version\",\"format-version\":3}]"), + 6_000L); + + IcebergTableMetadata.apply(metadata, json(""" + [{"action":"add-snapshot","snapshot":{"snapshot-id":7,"sequence-number":1,"timestamp-ms":5000, + "manifest-list":"s3://b/m.avro","summary":{"operation":"append"},"added-rows":10}}] + """), 7_000L); + + assertEquals(0L, metadata.path("snapshots").get(0).path("first-row-id").asLong()); + assertEquals(10L, metadata.path("next-row-id").asLong()); + } + + @Test + void aCreateRequestBecomesTheSameMetadataItsUpdatesWould() throws Exception { + ObjectNode metadata = IcebergTableMetadata.forCreate(json(""" + {"name":"events","schema":{"type":"struct","schema-id":0,"fields":[ + {"id":1,"name":"id","required":true,"type":"long"}, + {"id":2,"name":"tags","required":false,"type":{"type":"list","element-id":3,"element":"string", + "element-required":false}}]}, + "partition-spec":{"spec-id":0,"type":"struct","fields":[ + {"name":"id_bucket","transform":"bucket[4]","source-id":1,"field-id":1000}]}, + "properties":{"format-version":"2","owner":"lake"}} + """), "s3://lake-bucket/lake/events", 3_000L); + + assertEquals(3, metadata.path("last-column-id").asInt()); + assertEquals(1000, metadata.path("last-partition-id").asInt()); + assertTrue(metadata.path("partition-specs").get(0).path("type").isMissingNode()); + assertEquals("lake", metadata.path("properties").path("owner").asText()); + assertEquals("s3://lake-bucket/lake/events", metadata.path("location").asText()); + } + + @Test + void anUpdateTheCatalogDoesNotApplyIsRefused() throws Exception { + ObjectNode metadata = created(); + + IcebergRestException e = assertThrows(IcebergRestException.class, () -> IcebergTableMetadata.apply(metadata, + json("[{\"action\":\"add-encryption-key\",\"encryption-key\":{}}]"), 1L)); + + assertEquals("BadRequestException", e.type()); + assertEquals(400, e.code()); + } + + @Test + void hiveTypesSpellOutNestedIcebergTypes() throws Exception { + assertEquals("bigint", IcebergTypes.hiveType(json("\"long\""))); + assertEquals("decimal(10,2)", IcebergTypes.hiveType(json("\"decimal(10, 2)\""))); + assertEquals("struct>", IcebergTypes.hiveType(json(""" + {"type":"struct","fields":[{"id":1,"name":"a","type":"int"}, + {"id":2,"name":"b","type":{"type":"list","element-id":3,"element":"string"}}]} + """))); + assertEquals("map", IcebergTypes.hiveType(json(""" + {"type":"map","key-id":1,"key":"string","value-id":2,"value":"timestamptz"} + """))); + } +}