mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(glue): serve AWS Glue's Iceberg REST endpoint (#8472)
AWS Glue serves the Apache Iceberg REST catalog at glue.<region>.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.
This commit is contained in:
1 parent
7872b07c43
commit
5059a3cd40
14 files changed
+2026
-1
No files matched your search
@@ -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),
|
||||
|
||||
@@ -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.
|
||||
*
|
||||
* <p>The operations are the twelve AWS lists for the endpoint. The catalog in the path is the caller's default
|
||||
* catalog, named {@code :} or by the caller's account id; Glue supports single-level namespaces only.
|
||||
*/
|
||||
@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<String> 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<String, String> parameters = new LinkedHashMap<>();
|
||||
Iterator<Map.Entry<String, JsonNode>> properties = request.path("properties").fields();
|
||||
while (properties.hasNext()) {
|
||||
Map.Entry<String, JsonNode> property = properties.next();
|
||||
switch (property.getKey()) {
|
||||
case "location" -> database.setLocationUri(property.getValue().asText());
|
||||
case "comment" -> database.setDescription(property.getValue().asText());
|
||||
default -> parameters.put(property.getKey(), property.getValue().asText());
|
||||
}
|
||||
}
|
||||
database.setParameters(parameters);
|
||||
try {
|
||||
glue.createDatabase(database);
|
||||
} catch (AwsException e) {
|
||||
throw translated(e, database.getName(), null);
|
||||
}
|
||||
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<String, String> 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<Map.Entry<String, JsonNode>> updates = request.path("updates").fields();
|
||||
while (updates.hasNext()) {
|
||||
Map.Entry<String, JsonNode> update = updates.next();
|
||||
switch (update.getKey()) {
|
||||
case "location" -> updated.setLocationUri(update.getValue().asText());
|
||||
case "comment" -> updated.setDescription(update.getValue().asText());
|
||||
default -> parameters.put(update.getKey(), update.getValue().asText());
|
||||
}
|
||||
updatedKeys.add(update.getKey());
|
||||
}
|
||||
updated.setParameters(parameters);
|
||||
glue.updateDatabase(database.getName(), updated);
|
||||
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<String, String> 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<Column> 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-<uuid>.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<Long> 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) {
|
||||
}
|
||||
}
|
||||
@@ -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.<region>.amazonaws.com/iceberg}): the twelve operations of the
|
||||
* Apache Iceberg REST catalog specification AWS lists for it, under the {@code /v1/catalogs/{catalog}} prefix.
|
||||
* {@link GlueIcebergRouteFilter} moves requests signed for Glue onto {@link GlueIcebergRouteFilter#INTERNAL_PREFIX}.
|
||||
*/
|
||||
@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();
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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<IcebergRestException> {
|
||||
|
||||
@Override
|
||||
public Response toResponse(IcebergRestException exception) {
|
||||
Map<String, Object> 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();
|
||||
}
|
||||
}
|
||||
@@ -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<Map.Entry<String, JsonNode>> fields = update.path("updates").fields();
|
||||
while (fields.hasNext()) {
|
||||
Map.Entry<String, JsonNode> 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<Long> 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<Map.Entry<String, JsonNode>> refs = metadata.withObject("refs").fields();
|
||||
List<String> dangling = new ArrayList<>();
|
||||
while (refs.hasNext()) {
|
||||
Map.Entry<String, JsonNode> 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);
|
||||
}
|
||||
}
|
||||
@@ -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<a:int>},
|
||||
* {@code array<string>}, {@code map<string,bigint>}).
|
||||
*/
|
||||
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";
|
||||
};
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user